Compare commits

...

60 Commits

Author SHA1 Message Date
catlog22
f6c7c14042 ccw: fix view JSON errors and WSL MCP install 2026-03-05 14:29:06 +08:00
catlog22
dc1dc87023 codex-lens: add Swift (.swift) indexing support 2026-03-05 14:28:13 +08:00
catlog22
ed02874a99 codex-lens: respect embedding config during warmup 2026-03-05 14:27:54 +08:00
catlog22
60218f6bf3 codex-lens: harden CLI embedding errors and flags 2026-03-05 14:27:36 +08:00
catlog22
6341ed43e1 codex-lens: ship default LSP config and fix entrypoint 2026-03-05 14:27:16 +08:00
catlog22
1fb49c0e39 refactor: remove subagent references and update CLI tool usage across documentation 2026-03-05 11:15:13 +08:00
catlog22
99a45e3136 refactor: update skill invocation methods and enhance CLI usage examples 2026-03-05 10:59:07 +08:00
catlog22
bf057a927b Add quality gates, role library, and templates for team lifecycle v3
- Introduced quality gates documentation outlining scoring dimensions and per-phase criteria.
- Created a dynamic role library with definitions for core and specialist roles, including data engineer, devops engineer, ml engineer, orchestrator, performance optimizer, and security expert.
- Added templates for architecture documents, epics and stories, product briefs, and requirements PRD to standardize outputs across phases.
2026-03-05 10:20:42 +08:00
catlog22
bbdd1840de Add document standards, quality gates, and templates for team lifecycle phases
- Introduced `document-standards.md` to define YAML frontmatter schema, naming conventions, and content structure for spec-generator outputs.
- Created `quality-gates.md` outlining per-phase quality gate criteria and scoring dimensions for spec-generator outputs.
- Added templates for architecture documents, epics and stories, product briefs, and requirements PRD to streamline documentation in respective phases.
2026-03-04 23:54:20 +08:00
catlog22
fd0c9efa4d fix: update Agent tool call instructions and clarify TaskOutput usage 2026-03-04 23:46:58 +08:00
catlog22
fd847070d5 Refactor architecture optimization and issue resolution workflows
- Enhanced multi-perspective discussion capabilities in discuss-subagent for architecture optimization, integrating CLI tools for structured analysis and recommendations.
- Updated explore-subagent to utilize CLI tools directly for architecture-critical structure exploration, improving efficiency.
- Streamlined discuss-subagent in team-coordinate to leverage CLI for multi-perspective critiques, enhancing artifact evaluation.
- Modified explore-subagent in team-coordinate to adopt CLI tools for codebase exploration, ensuring consistency across roles.
- Expanded team-issue skill to include additional tools for issue resolution, refining role-specific execution and restrictions.
- Improved explorer role specifications to utilize CLI for exploration tasks, enhancing context gathering for architecture-critical structures.
- Adjusted implementer role specifications to route execution through CLI tools, optimizing backend selection for task execution.
- Enhanced integrator role specifications to utilize CLI for queue formation, improving issue resolution efficiency.
- Updated planner role specifications to leverage CLI for solution generation, ensuring structured implementation planning.
- Refined analyst role specifications to utilize CLI for codebase exploration, enhancing context generation for research.
- Adjusted executor role specifications to utilize CLI tools for task execution, improving backend selection and error handling.
- Enhanced writer role specifications to generate documents using CLI tools, streamlining document generation processes.
- Updated team-planex skill to reflect changes in execution methods, focusing on CLI tools for task execution.
- Refined team-testing role specifications to utilize CLI for test generation and failure resolution, improving testing workflows.
- Enhanced ultra-analyze role specifications to leverage CLI tools for discussion and exploration tasks, improving analysis depth and clarity.
2026-03-04 23:19:36 +08:00
catlog22
16bbfcd12a refactor: replace Task tool with Agent tool and fix schema compliance
## Task -> Agent Replacement
- Replace all Task({}) calls with Agent({}) across .claude/ directory
- Update allowed-tools declarations from Task to Agent
- Update documentation references from "Task tool" to "Agent tool"

## Schema Compliance Fixes

### Agent Schema
- Add missing required `description` parameter in 6 files
- Add missing `run_in_background: false` for subagent calls
- Add missing `subagent_type` parameter

### AskUserQuestion Schema
- Fix issue-manage/SKILL.md: reduce options from 5 to 4 (max allowed)

### SendMessage Schema
- Fix team-worker.md: use correct params (type, content, summary)
- Remove invalid `team_name` parameter

### TaskCreate/TaskUpdate Schema
- Remove invalid `blockedBy`, `owner`, `status` from TaskCreate calls
- Use separate TaskUpdate calls for dependencies and ownership
- Fix TaskUpdate syntax to use object parameter

### TeamDelete Schema
- Remove parameters from TeamDelete() calls (should be no params)

### TaskOutput Schema
- Fix Python-style syntax to JavaScript object syntax

## Files Changed
- 146 files updated across commands/, skills/, skills_lib/, agents/
2026-03-04 22:40:39 +08:00
catlog22
64e772f9b8 feat: add message bus (.msg/) to codex team-lifecycle skill
Align codex version with Claude version's team_msg message bus for
frontend pipeline UI integration:

- Phase 2: create .msg/ dir, write meta.json with pipeline_stages/roles,
  init messages.jsonl with session event
- Phase 4: log task completion events, update role_state in meta.json
- Phase 5: update meta.json status to completed, log shutdown event
- SKILL.md: document .msg/ in session directory and add schema reference
2026-03-04 16:35:07 +08:00
catlog22
e9f8a72343 Add subagents for discussion, document generation, and code exploration
- Introduced Discuss Subagent for lightweight multi-perspective critique, reducing overhead from ~60-90s to ~5s.
- Added Doc Generation Subagent for generating documents with CLI analysis and template filling.
- Implemented Explore Subagent for centralized codebase exploration with caching, replacing the standalone explorer role.
- Created templates for architecture documents, epics, product briefs, and requirements PRD to standardize outputs.
- Added a review file for tracking changes and discussions.
2026-03-04 16:23:58 +08:00
catlog22
a82e45fcf1 Add comprehensive documentation templates and schemas for project documentation workflow
- Introduced agent instruction template for generating documentation tasks.
- Created CSV schema for tasks including definitions and example entries.
- Defined documentation dimensions across five waves with specific focus areas.
- Established quality standards for documentation, including completeness, accuracy, clarity, and context integration.
2026-03-04 15:43:24 +08:00
catlog22
ab9b8ecbc0 Add comprehensive documentation for Numerical Analysis Workflow
- Introduced agent instruction template for task assignments in numerical analysis.
- Defined CSV schema for tasks, including input, computed, and output columns.
- Specified analysis dimensions across six phases of the workflow.
- Established phase topology for the diamond deep tree structure of the workflow.
- Outlined quality standards for assessing analysis reports, including criteria and quality gates.
2026-03-04 15:08:17 +08:00
catlog22
f389e3e6dd feat: add dynamic pipeline detection for team sessions v5 architecture
Backend:
- Fix readLegacyFiles to handle { name, prefix }[] role format
- Add roles backfill in getEffectiveTeamMeta when meta.json exists
- Ensure pipeline_stages and roles flow correctly to API response

Team Skills:
- Add pipeline metadata initialization to all 16 team skill coordinator roles
- Each skill now reports pipeline_stages and roles to meta.json at session init

Documentation:
- Update command references and component documentation
- Add numerical-analysis-workflow skill spec
- Sync zh/en translations for commands and components
2026-03-04 14:52:07 +08:00
catlog22
b203ada9c5 fix: update command references and improve documentation for workflow commands 2026-03-04 14:11:15 +08:00
catlog22
fb0f56bfc0 fix: improve error handling for workspace switch and support --host 0.0.0.0
- Add safeParseJson() helper with content-type validation and proxy error detection
- Allow token acquisition from any interface when server binds to 0.0.0.0 or ::
- Provide clear error messages when proxy intercepts localhost requests
2026-03-04 13:59:56 +08:00
catlog22
91fa594578 feat: Improve DynamicPipeline component with enhanced fallback UI and add localization for no stages message 2026-03-04 11:51:30 +08:00
catlog22
ffd5282932 Refactor team collaboration skills and update documentation
- Renamed `team-lifecycle-v5` to `team-lifecycle` across various documentation files for consistency.
- Updated references in code examples and usage sections to reflect the new skill name.
- Added a new command file for the `monitor` functionality in the `team-iterdev` skill, detailing the coordinator's monitoring events and task management.
- Introduced new components for dynamic pipeline visualization and session coordinates display in the frontend.
- Implemented utility functions for pipeline stage detection and status derivation based on message history.
- Enhanced the team role panel to map members to their respective pipeline roles with status indicators.
- Updated Chinese documentation to reflect the changes in skill names and descriptions.
2026-03-04 11:07:48 +08:00
catlog22
5e96722c09 fix: wait for zustand hydration before workspace initialization
Fix blank page on first load via `ccw view` by waiting for zustand persist
hydration to complete before initializing workspace.

- Add _hasHydrated state tracking in workflowStore
- Add setHasHydrated action to mark hydration complete
- Update AppShell to wait for hydration before calling switchWorkspace
- Ensures projectPath is properly restored from localStorage before queries execute
2026-03-04 10:56:07 +08:00
catlog22
26bda9c634 feat: Add coordinator commands and role specifications for UI design team
- Implemented the 'monitor' command for coordinator role to handle monitoring events, task completion, and pipeline management.
- Created role specifications for the coordinator, detailing responsibilities, command execution protocols, and session management.
- Added role specifications for the analyst, discussant, explorer, and synthesizer in the ultra-analyze skill, defining their context loading, analysis, and synthesis processes.
2026-03-03 23:35:41 +08:00
catlog22
a7ed0365f7 feat: Enhance team messaging system with new operations and data handling
- Added support for new message type 'state_update' in TeamMessageType.
- Updated TeamMessageFeed component to handle both legacy and new reference formats.
- Modified CLI options to clarify usage and added new commands for broadcasting messages and retrieving role states.
- Implemented new command 'get_state' to read role state from meta.json.
- Enhanced team message logging to auto-generate summaries and handle structured data.
- Improved backward compatibility by enriching team metadata from legacy files.
- Refactored message handling functions to streamline operations and improve clarity.
2026-03-03 16:11:57 +08:00
catlog22
628578b2bb Merge branch 'main' of https://github.com/catlog22/Claude-Code-Workflow 2026-03-03 11:33:23 +08:00
catlog22
08564d487a feat: enhance hook templates management by adding protection category and improving command safety 2026-03-03 11:33:00 +08:00
Copilot
747b509ec2 fix: sync docs/package-lock.json with package.json dependencies (#127)
* Initial plan

* fix: update docs/package-lock.json to include missing dependencies

Co-authored-by: catlog22 <28037070+catlog22@users.noreply.github.com>

---------

Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com>
Co-authored-by: catlog22 <28037070+catlog22@users.noreply.github.com>
2026-03-03 10:47:22 +08:00
catlog22
9cfd5c05fc feat: implement backend API for installing hook templates in HookManager and HookWizard components 2026-03-03 10:26:32 +08:00
catlog22
25f766ef26 docs: remove non-existent lite-lite-lite command references
Remove /workflow:lite-lite-lite from documentation as it does not exist
as an actual command or skill. Users should use workflow-lite-planex instead.

Updated files:
- docs/commands/claude/workflow.md
- docs/commands/claude/index.md
- docs/zh/commands/claude/workflow.md
- docs/zh/commands/claude/index.md
- docs-site/commands/claude/index.md
2026-03-03 10:12:56 +08:00
catlog22
9613644fc4 feat(hooks): introduce hook templates management and execution
- Added a new command `ccw hook template` with subcommands for listing, installing, and executing templates.
- Implemented backend support for managing hook templates, including API routes for fetching and installing templates.
- Created a new file `hook-templates.ts` to define and manage hook templates, including their execution logic.
- Added a migration script to convert old-style hooks to the new template-based approach.
- Updated documentation to reflect new template commands and usage examples.
- Enhanced error handling and output formatting for better user experience.
2026-03-03 10:07:34 +08:00
catlog22
59787dc9be feat: enhance responsive design for documentation layout; adjust margins and paddings for better content scaling 2026-03-03 09:30:42 +08:00
catlog22
d7169029ee feat: implement CSRF token helper and update fetch headers; adjust layout styles for responsiveness 2026-03-02 23:27:42 +08:00
catlog22
1bf9006d65 Refactor Chinese documentation for team skills and commands
- Removed outdated table of contents from commands-skills.md
- Updated skills overview in claude-collaboration.md with new skill names and descriptions
- Enhanced clarity and structure of skills details, including roles and pipelines
- Added new team skills: team-arch-opt, team-perf-opt, team-brainstorm, team-frontend, team-uidesign, team-issue, team-iterdev, team-quality-assurance, team-roadmap-dev, team-tech-debt, team-ultra-analyze
- Improved user command section for better usability
- Streamlined best practices for team skills usage
2026-03-02 22:49:52 +08:00
catlog22
99d6438303 feat: add documentation for Checkbox, Input, and Select components; enhance Queue and Terminal features
- Introduced Checkbox component documentation in Chinese, covering usage, properties, and examples.
- Added Input component documentation in Chinese, detailing its attributes and various states.
- Created Select component documentation in Chinese, including subcomponents and usage examples.
- Developed Queue management documentation, outlining its core functionalities and component structure.
- Added Terminal dashboard documentation, describing its layout, core features, and usage examples.
- Documented team workflows, detailing various team skills and their applications in project management.
2026-03-02 19:38:30 +08:00
catlog22
a58aa26a30 fix(uninstall): add manifest tracking for skill hub installations
Fixes #126: ccw uninstall was not cleaning up skills and commands
installed via Skill Hub because cpSync() bypassed manifest tracking.

Changes:
- Add copyDirectoryWithManifest() helper to install.ts and skill-hub-routes.ts
- Track all skill files in manifest during Skill Hub installation (CLI and API)
- Add orphan cleanup logic to uninstall.ts for defense in depth
- Fix installSkillFromRemote() and installSkillFromRemotePath() to track files

Root cause: Skill Hub installation methods used cpSync() which did not
track files in manifest, causing skills/commands to remain after uninstall.
2026-03-02 19:30:34 +08:00
catlog22
2dce4b3e8f fix(docs): resolve hydration mismatch and favicon 404 issues
- Add minimal theme preload script to prevent FOUC
- Fix favicon path to use base variable for GitHub Pages
- Theme script only sets data-theme attribute (no color mode)
- Maintains SSR/client consistency while eliminating flash

Fixes:
- Hydration mismatch error from localStorage access before Vue mount
- Favicon 404 on GitHub Pages deployment
- FOUC when theme applies after hydration

The new script is minimal and safe:
- Runs synchronously in head (before render)
- Only reads localStorage and sets attribute
- Matches what ThemeSwitcher.vue will do after mount
- No DOM manipulation that could cause mismatch
2026-03-02 17:47:27 +08:00
catlog22
b780734649 Add comprehensive command and skill reference documentation in Chinese
- Created a new document for command and skill references, detailing orchestrator commands, workflow session commands, issue workflow commands, IDAW commands, with-file workflows, cycle workflows, CLI commands, memory commands, team skills, workflow skills, utility skills, and Codex capabilities.
- Added a comparison table for workflows, outlining their best uses, levels, self-containment, and automatic chaining behavior.
2026-03-02 17:41:40 +08:00
catlog22
3bb4a821de feat(skill): add team-arch-opt architecture optimization skill
New team skill focused on structural architecture improvements
(dependency cycles, coupling/cohesion, layering violations, God Classes,
dead code). Isomorphic to team-perf-opt with pipeline:
ANALYZE → DESIGN → REFACTOR → VALIDATE + REVIEW.

Roles: coordinator, analyzer, designer, refactorer, validator, reviewer.
Supports single/fan-out/independent/auto parallel modes.
2026-03-02 16:46:44 +08:00
catlog22
d346d48ba2 fix(analyze-with-file): add session termination boundary and optimize Phase 4 UX
- Add explicit session termination output before lite-planex handoff to
  prevent phase collision between analyze-with-file and lite-plan
- Restructure Phase 4: display conclusions summary before asking next step
- Simplify post-completion options to 3 (执行任务/产出Issue/完成),
  remove redundant 导出报告 since report is always shown
- Update 01-lite-plan.md context isolation label to match new option name
2026-03-02 16:46:33 +08:00
catlog22
57636040d2 Refactor workflow-lite-planex documentation to standardize phase naming and improve clarity
- Updated phase references in SKILL.md and 01-lite-plan.md to use "LP-Phase" prefix for consistency.
- Added critical context isolation note in 01-lite-plan.md to clarify phase invocation rules.
- Enhanced execution process descriptions to reflect updated phase naming conventions.

Improve error handling in frontend routing

- Introduced ChunkErrorBoundary component to handle lazy-loaded chunk load failures.
- Wrapped lazy-loaded routes with error boundary and suspense for better user experience.
- Created PageSkeleton component for loading states in lazy-loaded routes.

Sanitize header values in notification routes

- Added regex validation for header values to prevent XSS attacks by allowing only printable ASCII characters.

Enhance mobile responsiveness in documentation styles

- Updated CSS breakpoints to use custom properties for better maintainability.
- Improved layout styles across various components to ensure consistent behavior on mobile devices.
2026-03-02 16:36:40 +08:00
catlog22
980be3d87d fix(planning-agent): clarify CLI output as markdown text, relax constraint wording
Change CLI CONSTRAINTS from schema-driven JSON output to structured
markdown text output, matching the architecture where CLI produces text
plans and Claude agent parses them into JSON.
2026-03-02 16:31:04 +08:00
catlog22
a4cb1e7eb2 fix(planning-agent): relax task parser regex and inject Prior Analysis into CLI context
1. extractStructuredTasks regex: /### (TASK-\d+|T\d+):/ was too strict,
   failing when Gemini outputs fewer #'s or omits colon. Relaxed to
   /#{1,3}\s*(TASK-\d+|T\d+):?\s*/ to tolerate format variations.

2. CLI Command Template CONTEXT field: added explicit instruction to use
   Prior Analysis from task description as primary planning context when
   exploration files are absent.
2026-03-02 16:28:10 +08:00
catlog22
4f3ef5cba8 fix(planning-agent): remove skip-CLI logic, keep Prior Analysis as context
Revert the Phase 2 skip when no explorations. CLI execution should always
run but use Prior Analysis block from task description as primary context
when exploration files are absent.
2026-03-02 16:22:04 +08:00
catlog22
e54d76f7be fix(planning-agent): enforce blocking CLI calls overriding global default
Global CLAUDE.md sets `run_in_background: true` as default for CLI calls,
which conflicts with the agent's need for synchronous results. The agent
may have followed the global default, firing CLI in background and getting
no output to parse. Strengthen the instruction to explicitly override the
global default with `run_in_background: false`.
2026-03-02 16:19:19 +08:00
catlog22
c12acd41ee fix(planning-agent): add Prior Analysis fast path to skip CLI execution
When cli-lite-planning-agent receives empty exploration context (from
analyze-with-file → lite-plan flow), it previously spent all tool budget
on CLI execution (Phase 2) leaving no budget for file writing (Phase 4).

Add explicit "Prior Analysis Fast Path" in Execution Flow: when prompt
contains "No exploration files", skip Phase 2 and generate plan directly
from task description's Prior Analysis block, preserving tool budget for
mandatory file output (plan.json + .task/*.json).
2026-03-02 16:17:37 +08:00
catlog22
73cc2ef3fa Refactor and optimize templates and code structure
- Deleted outdated templates for epics, product brief, and requirements PRD.
- Introduced lazy loading for locale messages in i18n module to enhance performance.
- Updated main application bootstrap to parallelize CSRF token fetching and locale loading.
- Implemented code splitting for router configuration to optimize bundle size and loading times.
- Added WebSocket connection limits and rate limiting to improve server performance and prevent abuse.
- Enhanced input validation with compiled regex patterns for better performance and maintainability.
2026-03-02 15:57:55 +08:00
catlog22
ce2927b28d refactor(workflow-lite-planex): update skill name and improve documentation consistency 2026-03-02 15:31:17 +08:00
catlog22
121e834459 feat: add multi-mode workflow planning skill with session management and task generation 2026-03-02 15:25:56 +08:00
catlog22
2c2b9d6e29 Refactor code structure for improved readability and maintainability 2026-03-02 14:26:04 +08:00
catlog22
0d5cc4a74f refactor(workflow): rename workflow-lite-plan to workflow-lite-planex and remove standalone lite-execute
- Rename skill directory from workflow-lite-plan to workflow-lite-planex (planex = plan + execute)
- Remove standalone lite-execute command entry from command.json and analyze_commands.py
- Update all 60+ files referencing workflow-lite-plan to use workflow-lite-planex
- Update descriptions to clarify Phase 1: plan → Phase 2: execute architecture
- Remove lite-execute as standalone command from orchestrator routing tables
- Update docs (EN/ZH) to reflect unified planex naming and phase descriptions
2026-03-02 14:03:17 +08:00
catlog22
71485b89e6 fix(workflow): resolve analyze-with-file and lite-plan phase conflict
Add workflow boundary markers to analyze-with-file Post-Completion Options
so that when "生成任务" triggers lite-plan via Skill(), the model follows
lite-plan's Phase 1-5 exclusively instead of returning to analyze Phase 4
synthesis. Root cause: Skill() expands inline (shared context), causing
phase number collision between the two workflows.
2026-03-02 13:08:59 +08:00
catlog22
2fc792a3b7 7.2.0 2026-03-02 12:28:39 +08:00
catlog22
0af4ca040f fix(mcp): improve CCW config update logic and add debug logging
- Fix McpManagerPage to read config after optimistic update and pass only expected fields
- Add debug logging for enabledTools config building and ccw-tools server saving
2026-03-02 12:27:42 +08:00
catlog22
7af258f43d feat(routing): add greenfield task type and narrow roadmap detection
- Add dedicated greenfield (0→1) task type with complexity-adaptive routing
  (low→brainstorm-to-plan, medium→greenfield-plan, high→greenfield-phased)
- Narrow roadmap regex to only /roadmap|路线.*图/ to prevent false matches
- Change brainstorm-to-plan chain from lite-plan to workflow-plan→execute
- Sync all changes between ccw.md and ccw-coordinator.md
2026-03-02 12:27:31 +08:00
catlog22
8ad283086b fix(tests): add test for disabling all tools in CcwToolsMcpCard component
fix(api): handle empty enabledTools array and improve default tool logic
fix(queueScheduler): ignore network errors in loadInitialState
fix(auth): ensure token generation handles max session capacity
chore(dependencies): update package requirements to use compatible version specifiers
chore(tests): add new test cases for incremental indexer and migrations
2026-03-02 11:26:15 +08:00
catlog22
b36a46d59d fix(ui): prevent dropdown truncation in Collapsible content
Apply overflow-hidden only when collapsible is closed, allowing
dropdown menus to overflow properly when expanded.
2026-03-02 11:19:28 +08:00
catlog22
899a92f2eb fix(skill): constrain roadmap interactive feedback to plan-only modifications
Add explicit constraints preventing Phase 3 interactive rounds from
modifying source code. Feedback handlers now clearly scope updates to
roadmap.md and issues.jsonl only, with code changes deferred to handoff.
2026-03-02 11:17:42 +08:00
catlog22
d0ac3a5cd2 fix(csrf): prevent undefined token when session at max capacity
Root cause: generateToken() returned undefined when session already
had maxTokensPerSession (5) tokens, causing ERR_HTTP_INVALID_HEADER_VALUE.

Fix: Force generate token even when at capacity, ensuring we always
return a valid token string.

Related: v7.1.1 CLI process hang fix
2026-03-02 09:58:54 +08:00
catlog22
0939510e0d fix(lite-plan): handle empty exploration context when prior analysis exists
When analyze-with-file artifacts are passed to lite-plan, exploration is
skipped (hasPriorAnalysis=true) leaving manifest.explorations empty. The
agent prompt's exploration section rendered as blank, causing the planning
agent to lack context and fail to produce task JSON. Add conditional to
output a fallback hint directing the agent to use the Prior Analysis block
in the task description as primary planning context.
2026-03-02 00:04:32 +08:00
catlog22
deea92581b fix(cli): resolve process hang after CLI execution
Root cause: HTTP Keep-Alive connections kept event loop alive,
preventing process.exit() from executing even after CLI_EXECUTION_COMPLETED
event was sent.

Fix: Add `agent: false` and `Connection: close` header to HTTP requests
in notifyDashboard() and broadcastStreamEvent() functions.

- agent: false - Creates new Agent per request instead of global Keep-Alive Agent
- Connection: close - Tells server to close connection after response

Fixes issue where `ccw cli --tool gemini` would complete execution but
Bash command would hang indefinitely.
2026-03-01 23:34:31 +08:00
607 changed files with 45171 additions and 38501 deletions

View File

@@ -155,7 +155,7 @@
}, },
"development_index": { "development_index": {
"type": "object", "type": "object",
"description": "Categorized development history (lite-plan/lite-execute)", "description": "Categorized development history (lite-planex sessions)",
"properties": { "properties": {
"feature": { "type": "array", "items": { "$ref": "#/$defs/devIndexEntry" } }, "feature": { "type": "array", "items": { "$ref": "#/$defs/devIndexEntry" } },
"enhancement": { "type": "array", "items": { "$ref": "#/$defs/devIndexEntry" } }, "enhancement": { "type": "array", "items": { "$ref": "#/$defs/devIndexEntry" } },

View File

@@ -85,13 +85,14 @@ Tools are selected based on **tags** defined in the configuration. Use tags to m
```bash ```bash
# Explicit tool selection # Explicit tool selection
ccw cli -p "<PROMPT>" --tool <tool-id> --mode <analysis|write|review> ccw cli -p "<PROMPT>" --tool <tool-id> --mode <analysis|write>
# Model override # Model override
ccw cli -p "<PROMPT>" --tool <tool-id> --model <model-id> --mode <analysis|write> ccw cli -p "<PROMPT>" --tool <tool-id> --model <model-id> --mode <analysis|write>
# Code review (codex only) # Code review (codex only - review mode and target flags are invalid for other tools)
ccw cli -p "<PROMPT>" --tool codex --mode review ccw cli -p "<PROMPT>" --tool codex --mode review
ccw cli --tool codex --mode review --commit <hash>
# Tag-based auto-selection (future) # Tag-based auto-selection (future)
ccw cli -p "<PROMPT>" --tags <tag1,tag2> --mode <analysis|write> ccw cli -p "<PROMPT>" --tags <tag1,tag2> --mode <analysis|write>
@@ -292,11 +293,8 @@ ccw cli -p "..." --tool gemini --mode analysis --rule analysis-review-architectu
- **`review`** - **`review`**
- Permission: Read-only (code review output) - Permission: Read-only (code review output)
- Use For: Git-aware code review of uncommitted changes, branch diffs, specific commits - Use For: Git-aware code review of uncommitted changes, branch diffs, specific commits
- Specification: **codex only** - uses `codex review` subcommand - Specification: **codex only** - uses `codex review` subcommand. Other tools MUST NOT use this mode
- Tool Behavior: - **Constraint**: Target flags (`--uncommitted`, `--base`, `--commit`) are **codex-only** and mutually exclusive with prompt
- `codex`: Executes `codex review` for structured code review
- Other tools (gemini/qwen/claude): Accept mode but no operation change (treated as analysis)
- **Constraint**: Target flags (`--uncommitted`, `--base`, `--commit`) and prompt are mutually exclusive
- With prompt only: `ccw cli -p "Focus on security" --tool codex --mode review` (reviews uncommitted by default) - With prompt only: `ccw cli -p "Focus on security" --tool codex --mode review` (reviews uncommitted by default)
- With target flag only: `ccw cli --tool codex --mode review --commit abc123` (no prompt allowed) - With target flag only: `ccw cli --tool codex --mode review --commit abc123` (no prompt allowed)
@@ -309,7 +307,7 @@ ccw cli -p "..." --tool gemini --mode analysis --rule analysis-review-architectu
- **`--mode <mode>`** - **`--mode <mode>`**
- Description: **REQUIRED**: analysis, write, review - Description: **REQUIRED**: analysis, write, review
- Default: **NONE** (must specify) - Default: **NONE** (must specify)
- Note: `review` mode triggers `codex review` subcommand for codex tool only - Note: `review` mode is **codex-only**. Using `--mode review` with other tools (gemini/qwen/claude) is invalid and should be rejected
- **`--model <model>`** - **`--model <model>`**
- Description: Model override - Description: Model override
@@ -446,7 +444,7 @@ ccw cli --tool codex --mode review --base main
ccw cli --tool codex --mode review --commit abc123 ccw cli --tool codex --mode review --commit abc123
``` ```
> **Note**: `--mode review` only triggers special behavior for `codex` tool. Target flags (`--uncommitted`, `--base`, `--commit`) and prompt are **mutually exclusive** - use one or the other, not both. > **Note**: `--mode review` and target flags (`--uncommitted`, `--base`, `--commit`) are **codex-only**. Using them with other tools is invalid. When using codex, target flags and prompt are **mutually exclusive** - use one or the other, not both.
--- ---
@@ -455,9 +453,9 @@ ccw cli --tool codex --mode review --commit abc123
**Single-Use Authorization**: Each execution requires explicit user instruction. Previous authorization does NOT carry over. **Single-Use Authorization**: Each execution requires explicit user instruction. Previous authorization does NOT carry over.
**Mode Hierarchy**: **Mode Hierarchy**:
- `analysis`: Read-only, safe for auto-execution - `analysis`: Read-only, safe for auto-execution. Available for all tools
- `write`: Create/Modify/Delete files, full operations - requires explicit `--mode write` - `write`: Create/Modify/Delete files, full operations - requires explicit `--mode write`. Available for all tools
- `review`: Git-aware code review (codex only), read-only output - requires explicit `--mode review` - `review`: **codex-only**. Git-aware code review, read-only output. Invalid for other tools (gemini/qwen/claude)
- **Exception**: User provides clear instructions like "modify", "create", "implement" - **Exception**: User provides clear instructions like "modify", "create", "implement"
--- ---

View File

@@ -783,7 +783,7 @@ All workflows use the same file structure definition regardless of complexity. *
**Examples**: **Examples**:
*Workflow Commands (lightweight):* *Workflow Commands (lightweight):*
- `/workflow-lite-plan "feature idea"` (exploratory) → `.scratchpad/lite-plan-feature-idea-20250105-143110.md` - `/workflow-lite-planex "feature idea"` (exploratory) → `.scratchpad/lite-plan-feature-idea-20250105-143110.md`
- `/workflow:lite-fix "bug description"` (bug fixing) → `.scratchpad/lite-fix-bug-20250105-143130.md` - `/workflow:lite-fix "bug description"` (bug fixing) → `.scratchpad/lite-fix-bug-20250105-143130.md`
> **Note**: Direct CLI commands (`/cli:analyze`, `/cli:execute`, etc.) have been replaced by semantic invocation and workflow commands. > **Note**: Direct CLI commands (`/cli:analyze`, `/cli:execute`, etc.) have been replaced by semantic invocation and workflow commands.

View File

@@ -16,18 +16,19 @@ Available CLI endpoints are dynamically defined by the config file
- **File Modification**: @~/.ccw/workflows/file-modification.md - **File Modification**: @~/.ccw/workflows/file-modification.md
### Agent Calls ### Agent Calls
- **Always use `run_in_background: false`** for Task tool agent calls: `Task({ subagent_type: "xxx", prompt: "...", run_in_background: false })` to ensure synchronous execution and immediate result visibility - **Always use `run_in_background: false`** for Agent tool calls: `Agent({ subagent_type: "xxx", prompt: "...", run_in_background: false })` to ensure synchronous execution and immediate result visibility
- **TaskOutput usage**: Only use `TaskOutput({ task_id: "xxx", block: false })` + sleep loop to poll completion status. NEVER read intermediate output during agent/CLI execution - wait for final result only
### CLI Tool Calls (ccw cli) ### CLI Tool Calls (ccw cli)
- **Default: Use Bash `run_in_background: true`** - Unless otherwise specified, always execute CLI calls in background using Bash tool's background mode: - **Default**: CLI calls (`ccw cli`) default to background execution (`run_in_background: true`):
``` ```
Bash({ Bash({
command: "ccw cli -p '...' --tool gemini", command: "ccw cli -p '...' --tool gemini",
run_in_background: true // Bash tool parameter, not ccw cli parameter run_in_background: true // Bash tool parameter, not ccw cli parameter
}) })
``` ```
- **After CLI call**: Stop output immediately - let CLI execute in background. **DO NOT use TaskOutput polling** - wait for hook callback to receive results - **CRITICAL — Agent-specific instructions ALWAYS override this default.** If an agent's definition file (`.claude/agents/*.md`) specifies `run_in_background: false`, that instruction takes highest priority. Subagents (Agent tool agents) CANNOT receive hook callbacks, so they MUST use `run_in_background: false` for CLI calls that produce required results.
- **After CLI call (main conversation only)**: Stop output immediately - let CLI execute in background. **DO NOT use TaskOutput polling** - wait for hook callback to receive results
### CLI Analysis Calls ### CLI Analysis Calls
- **Wait for results**: MUST wait for CLI analysis to complete before taking any write action. Do NOT proceed with fixes while analysis is running - **Wait for results**: MUST wait for CLI analysis to complete before taking any write action. Do NOT proceed with fixes while analysis is running

View File

@@ -126,10 +126,11 @@ const planObject = generatePlanFromSchema(schema, context)
Phase 1: Schema & Context Loading Phase 1: Schema & Context Loading
├─ Read schema reference (plan-overview-base-schema or plan-overview-fix-schema) ├─ Read schema reference (plan-overview-base-schema or plan-overview-fix-schema)
├─ Aggregate multi-angle context (explorations or diagnoses) ├─ Aggregate multi-angle context (explorations or diagnoses)
├─ If no explorations: use "## Prior Analysis" block from task description as primary context
└─ Determine output structure from schema └─ Determine output structure from schema
Phase 2: CLI Execution Phase 2: CLI Execution
├─ Construct CLI command with planning template ├─ Construct CLI command with planning template (include Prior Analysis context when no explorations)
├─ Execute Gemini (fallback: Qwen → degraded mode) ├─ Execute Gemini (fallback: Qwen → degraded mode)
└─ Timeout: 60 minutes └─ Timeout: 60 minutes
@@ -173,7 +174,7 @@ TASK:
• Identify dependencies and execution phases • Identify dependencies and execution phases
• Generate complexity-appropriate fields (rationale, verification, risks, code_skeleton, data_flow) • Generate complexity-appropriate fields (rationale, verification, risks, code_skeleton, data_flow)
MODE: analysis MODE: analysis
CONTEXT: @**/* | Memory: {context_summary} CONTEXT: @**/* | Memory: {context_summary}. If task description contains '## Prior Analysis', treat it as primary planning context with pre-analyzed files, findings, and recommendations.
EXPECTED: EXPECTED:
## Summary ## Summary
[overview] [overview]
@@ -229,9 +230,9 @@ EXPECTED:
**Total**: [time] **Total**: [time]
CONSTRAINTS: CONSTRAINTS:
- Follow schema structure from {schema_path} - Output as structured markdown text following the EXPECTED format above
- Task IDs use format TASK-001, TASK-002, etc. (FIX-001 for fix-plan) - Task IDs use format TASK-001, TASK-002, etc. (FIX-001 for fix-plan)
- Complexity determines required fields: - Complexity determines required sections:
* Low: base fields only * Low: base fields only
* Medium: + rationale + verification + design_decisions * Medium: + rationale + verification + design_decisions
* High: + risks + code_skeleton + data_flow * High: + risks + code_skeleton + data_flow
@@ -256,8 +257,8 @@ function extractSection(cliOutput, header) {
// Parse structured tasks from CLI output // Parse structured tasks from CLI output
function extractStructuredTasks(cliOutput, complexity) { function extractStructuredTasks(cliOutput, complexity) {
const tasks = [] const tasks = []
// Split by task headers (supports both TASK-NNN and T\d+ formats) // Split by task headers (flexible: 1-3 #, optional colon, supports TASK-NNN and T\d+)
const taskBlocks = cliOutput.split(/### (TASK-\d+|T\d+):/).slice(1) const taskBlocks = cliOutput.split(/#{1,3}\s*(TASK-\d+|T\d+):?\s*/).slice(1)
for (let i = 0; i < taskBlocks.length; i += 2) { for (let i = 0; i < taskBlocks.length; i += 2) {
const rawId = taskBlocks[i].trim() const rawId = taskBlocks[i].trim()
@@ -820,8 +821,8 @@ function validateTask(task) {
- **Write BOTH plan.json AND .task/*.json files** (two-layer output) - **Write BOTH plan.json AND .task/*.json files** (two-layer output)
- Handle CLI errors with fallback chain - Handle CLI errors with fallback chain
**Bash Tool**: **Bash Tool (OVERRIDE global CLAUDE.md default)**:
- Use `run_in_background=false` for all Bash/CLI calls to ensure foreground execution - **MUST use `run_in_background: false`** for ALL Bash/CLI calls — results are required before proceeding. This overrides any global `run_in_background: true` default.
**NEVER**: **NEVER**:
- Execute implementation (return plan only) - Execute implementation (return plan only)

View File

@@ -1,25 +1,25 @@
--- ---
name: team-worker name: team-worker
description: | description: |
Unified worker agent for team-lifecycle-v5. Contains all shared team behavior Unified worker agent for team-lifecycle. Contains all shared team behavior
(Phase 1 Task Discovery, Phase 5 Report + Fast-Advance, Message Bus, Consensus (Phase 1 Task Discovery, Phase 5 Report + Fast-Advance, Message Bus, Consensus
Handling, Inner Loop lifecycle). Loads role-specific Phase 2-4 logic from a Handling, Inner Loop lifecycle). Loads role-specific Phase 2-4 logic from a
role_spec markdown file passed in the prompt. role_spec markdown file passed in the prompt.
Examples: Examples:
- Context: Coordinator spawns analyst worker - Context: Coordinator spawns analyst worker
user: "role: analyst\nrole_spec: .claude/skills/team-lifecycle-v5/role-specs/analyst.md\nsession: .workflow/.team/TLS-xxx" user: "role: analyst\nrole_spec: .claude/skills/team-lifecycle/role-specs/analyst.md\nsession: .workflow/.team/TLS-xxx"
assistant: "Loading role spec, discovering RESEARCH-* tasks, executing Phase 2-4 domain logic" assistant: "Loading role spec, discovering RESEARCH-* tasks, executing Phase 2-4 domain logic"
commentary: Agent parses prompt, loads role spec, runs built-in Phase 1 then role-specific Phase 2-4 then built-in Phase 5 commentary: Agent parses prompt, loads role spec, runs built-in Phase 1 then role-specific Phase 2-4 then built-in Phase 5
- Context: Coordinator spawns writer worker with inner loop - Context: Coordinator spawns writer worker with inner loop
user: "role: writer\nrole_spec: .claude/skills/team-lifecycle-v5/role-specs/writer.md\ninner_loop: true" user: "role: writer\nrole_spec: .claude/skills/team-lifecycle/role-specs/writer.md\ninner_loop: true"
assistant: "Loading role spec, processing all DRAFT-* tasks in inner loop" assistant: "Loading role spec, processing all DRAFT-* tasks in inner loop"
commentary: Agent detects inner_loop=true, loops Phase 1-5 for each same-prefix task commentary: Agent detects inner_loop=true, loops Phase 1-5 for each same-prefix task
color: green color: green
--- ---
You are a **team-lifecycle-v5 worker agent**. You execute a specific role within a team pipeline. Your behavior is split into: You are a **team-lifecycle worker agent**. You execute a specific role within a team pipeline. Your behavior is split into:
- **Built-in phases** (Phase 1, Phase 5): Task discovery, reporting, fast-advance, inner loop — defined below. - **Built-in phases** (Phase 1, Phase 5): Task discovery, reporting, fast-advance, inner loop — defined below.
- **Role-specific phases** (Phase 2-4): Loaded from a role_spec markdown file. - **Role-specific phases** (Phase 2-4): Loaded from a role_spec markdown file.
@@ -35,7 +35,7 @@ Parse the following fields from your prompt:
| `role` | Yes | Role name (analyst, writer, planner, executor, tester, reviewer, architect, fe-developer, fe-qa) | | `role` | Yes | Role name (analyst, writer, planner, executor, tester, reviewer, architect, fe-developer, fe-qa) |
| `role_spec` | Yes | Path to role-spec .md file containing Phase 2-4 instructions | | `role_spec` | Yes | Path to role-spec .md file containing Phase 2-4 instructions |
| `session` | Yes | Session folder path (e.g., `.workflow/.team/TLS-xxx-2026-02-27`) | | `session` | Yes | Session folder path (e.g., `.workflow/.team/TLS-xxx-2026-02-27`) |
| `session_id` | Yes | Session ID (folder name, e.g., `TLS-xxx-2026-02-27`) | | `session_id` | Yes | Session ID (folder name, e.g., `TLS-xxx-2026-02-27`). Used directly as `session_id` param for all message bus operations |
| `team_name` | Yes | Team name for SendMessage | | `team_name` | Yes | Team name for SendMessage |
| `requirement` | Yes | Original task/requirement description | | `requirement` | Yes | Original task/requirement description |
| `inner_loop` | Yes | `true` or `false` — whether to loop through same-prefix tasks | | `inner_loop` | Yes | `true` or `false` — whether to loop through same-prefix tasks |
@@ -49,30 +49,45 @@ Parse the following fields from your prompt:
- `prefix`: Task prefix to filter (e.g., `RESEARCH`, `DRAFT`, `IMPL`) - `prefix`: Task prefix to filter (e.g., `RESEARCH`, `DRAFT`, `IMPL`)
- `inner_loop`: Override from frontmatter if present - `inner_loop`: Override from frontmatter if present
- `discuss_rounds`: Array of discuss round IDs this role handles - `discuss_rounds`: Array of discuss round IDs this role handles
- `subagents`: Array of subagent types this role may call - `delegates_to`: (DEPRECATED - team workers cannot delegate to other agents) Array for documentation only
- `message_types`: Success/error/fix message type mappings - `message_types`: Success/error/fix message type mappings
3. Parse **body** (content after frontmatter) to get Phase 2-4 execution instructions 3. Parse **body** (content after frontmatter) to get Phase 2-4 execution instructions
4. Store parsed metadata and instructions for use in execution phases 4. Store parsed metadata and instructions for use in execution phases
--- ---
## Main Execution Loop ## Execution Flow
``` ```
Entry: Entry:
Parse prompt → extract role, role_spec, session, session_id, team_name, inner_loop Parse prompt → extract role, role_spec, session, session_id, team_name, inner_loop
Read role_spec → parse frontmatter (prefix, discuss_rounds, etc.) Read role_spec → parse frontmatter + body (Phase 2-4 instructions)
Read role_spec body → store Phase 2-4 instructions
Load wisdom files from <session>/wisdom/ (if exist) Load wisdom files from <session>/wisdom/ (if exist)
context_accumulator = [] ← inner_loop only, in-memory across iterations
Main Loop: Main Loop:
Phase 1: Task Discovery [built-in] Phase 1: Task Discovery [built-in]
Phase 2-4: Execute Role Spec [from .md] Phase 2-4: Execute Role Spec [from .md]
Phase 5: Report [built-in] Phase 5: Report [built-in]
inner_loop AND more same-prefix tasks? → Phase 5-L → back to Phase 1 inner_loop=true AND more same-prefix tasks? → Phase 5-L → back to Phase 1
no more tasks? → Phase 5-F → STOP inner_loop=false OR no more tasks? → Phase 5-F → STOP
``` ```
**Inner loop** (`inner_loop=true`): Processes ALL same-prefix tasks sequentially in a single agent instance. `context_accumulator` maintains context across task iterations for knowledge continuity.
| Step | Phase 5-L (loop) | Phase 5-F (final) |
|------|-----------------|------------------|
| TaskUpdate completed | YES | YES |
| team_msg state_update | YES | YES |
| Accumulate summary | YES | - |
| SendMessage to coordinator | NO | YES (all tasks) |
| Fast-Advance check | - | YES |
**Interrupt conditions** (break inner loop immediately):
- consensus_blocked HIGH → SendMessage → STOP
- Cumulative errors >= 3 → SendMessage → STOP
--- ---
## Phase 1: Task Discovery (Built-in) ## Phase 1: Task Discovery (Built-in)
@@ -90,7 +105,7 @@ Execute on every loop iteration:
- If inner loop continuation → proceed to Phase 5-F (all done) - If inner loop continuation → proceed to Phase 5-F (all done)
4. **Has matching tasks** → pick first by ID order 4. **Has matching tasks** → pick first by ID order
5. `TaskGet(taskId)` → read full task details 5. `TaskGet(taskId)` → read full task details
6. `TaskUpdate(taskId, status="in_progress")` → claim the task 6. `TaskUpdate({ taskId: taskId, status: "in_progress" })` → claim the task
### Resume Artifact Check ### Resume Artifact Check
@@ -108,107 +123,42 @@ After claiming a task, check if output artifacts already exist (indicates resume
The role_spec contains Phase 2, Phase 3, and Phase 4 sections with domain-specific logic. Follow those instructions exactly. Key integration points with built-in infrastructure: The role_spec contains Phase 2, Phase 3, and Phase 4 sections with domain-specific logic. Follow those instructions exactly. Key integration points with built-in infrastructure:
### Subagent Delegation ## CRITICAL LIMITATION: No Agent Delegation
When role_spec instructs to call a subagent, use these templates: **Team workers CANNOT call the Agent() tool to spawn other agents.**
**Discuss subagent** (for inline discuss rounds): Test evidence shows that team members spawned via Agent tool do not have access to the Agent tool themselves. Only the coordinator (main conversation context) can spawn agents.
### Alternatives for Team Workers
When role-spec instructions require analysis or exploration:
**Option A: CLI Tools** (Recommended)
```javascript
Bash(`ccw cli -p "..." --tool gemini --mode analysis`, { run_in_background: false })
``` ```
Task({
subagent_type: "cli-discuss-agent",
run_in_background: false,
description: "Discuss <round-id>",
prompt: `## Multi-Perspective Critique: <round-id>
### Input **Option B: Direct Tools**
- Artifact: <artifact-path> Use Read, Grep, Glob, mcp__ace-tool__search_context directly.
- Round: <round-id>
- Perspectives: <perspective-list-from-role-spec>
- Session: <session-folder>
- Discovery Context: <session-folder>/spec/discovery-context.json
### Perspective Routing **Option C: Request Coordinator Help**
Send message to coordinator requesting agent delegation:
| Perspective | CLI Tool | Role | Focus Areas | ```javascript
|-------------|----------|------|-------------| mcp__ccw-tools__team_msg({
| Product | gemini | Product Manager | Market fit, user value, business viability | operation: "log",
| Technical | codex | Tech Lead | Feasibility, tech debt, performance, security | session_id: sessionId,
| Quality | claude | QA Lead | Completeness, testability, consistency | from: role,
| Risk | gemini | Risk Analyst | Risk identification, dependencies, failure modes | to: "coordinator",
| Coverage | gemini | Requirements Analyst | Requirement completeness vs discovery-context | type: "agent_request",
summary: "Request exploration agent for X",
### Execution Steps data: { reason: "...", scope: "..." }
1. Read artifact from <artifact-path>
2. For each perspective, launch CLI analysis in background
3. Wait for all CLI results
4. Divergence detection + consensus determination
5. Synthesize convergent/divergent themes + action items
6. Write discussion record to: <session-folder>/discussions/<round-id>-discussion.md
### Return Value
JSON with: verdict (consensus_reached|consensus_blocked), severity (HIGH|MEDIUM|LOW), average_rating, divergences, action_items, recommendation, discussion_path`
})
```
**Explore subagent** (for codebase exploration):
```
Task({
subagent_type: "cli-explore-agent",
run_in_background: false,
description: "Explore <angle>",
prompt: `Explore codebase for: <query>
Focus angle: <angle>
Keywords: <keyword-list>
Session folder: <session-folder>
## Cache Check
1. Read <session-folder>/explorations/cache-index.json (if exists)
2. Look for entry with matching angle
3. If found AND file exists -> read cached result, return summary
4. If not found -> proceed to exploration
## Output
Write JSON to: <session-folder>/explorations/explore-<angle>.json
Update cache-index.json with new entry
Return summary: file count, pattern count, top 5 files, output path`
})
```
**Doc-generation subagent** (for writer document generation):
```
Task({
subagent_type: "universal-executor",
run_in_background: false,
description: "Generate <doc-type>",
prompt: `## Document Generation: <doc-type>
### Session
- Folder: <session-folder>
- Spec config: <spec-config-path>
### Document Config
- Type: <doc-type>
- Template: <template-path>
- Output: <output-path>
- Prior discussion: <discussion-file or "none">
### Writer Accumulator (prior decisions)
<JSON array of prior task summaries from context_accumulator>
### Output Requirements
1. Write document to <output-path>
2. Return JSON: { artifact_path, summary, key_decisions[], sections_generated[], warnings[] }`
}) })
SendMessage({ recipient: "coordinator", content: "..." })
``` ```
### Consensus Handling ### Consensus Handling
After a discuss subagent returns, handle the verdict: When role-spec instructions require consensus/discussion, handle the verdict:
| Verdict | Severity | Action | | Verdict | Severity | Action |
|---------|----------|--------| |---------|----------|--------|
@@ -232,25 +182,32 @@ Discussion: <session-folder>/discussions/<round-id>-discussion.md
## Phase 5: Report + Fast-Advance (Built-in) ## Phase 5: Report + Fast-Advance (Built-in)
After Phase 4 completes, determine Phase 5 variant: After Phase 4 completes, determine Phase 5 variant (see Execution Flow for decision table).
### Phase 5-L: Loop Completion (when inner_loop=true AND more same-prefix tasks pending) ### Phase 5-L: Loop Completion (inner_loop=true AND more same-prefix tasks pending)
1. **TaskUpdate**: Mark current task `completed` 1. **TaskUpdate**: Mark current task `completed`
2. **Message Bus**: Log completion with verification evidence 2. **Message Bus**: Log state_update (combines state publish + audit log)
``` ```
mcp__ccw-tools__team_msg( mcp__ccw-tools__team_msg(
operation="log", operation="log",
team=<session_id>, session_id=<session_id>,
from=<role>, from=<role>,
to="coordinator", type="state_update",
type=<message_types.success>, data={
summary="[<role>] <task-id> complete. <brief-summary>. Verified: <verification_method>", status: "task_complete",
ref=<artifact-path> task_id: "<task-id>",
ref: "<artifact-path>",
key_findings: <from Phase 4>,
decisions: <from Phase 4>,
files_modified: <from Phase 4>,
artifact_path: "<artifact-path>",
verification: "<verification_method>"
}
) )
``` ```
**CLI fallback**: `ccw team log --team <session_id> --from <role> --to coordinator --type <type> --summary "[<role>] ..." --json` > `to` defaults to "coordinator", `summary` auto-generated. `type="state_update"` auto-syncs data to `meta.json.role_state[<role>]`.
3. **Accumulate summary** to context_accumulator (in-memory): 3. **Accumulate** to `context_accumulator` (in-memory):
``` ```
context_accumulator.append({ context_accumulator.append({
task: "<task-id>", task: "<task-id>",
@@ -258,43 +215,46 @@ After Phase 4 completes, determine Phase 5 variant:
key_decisions: <from Phase 4>, key_decisions: <from Phase 4>,
discuss_verdict: <from Phase 4 or "none">, discuss_verdict: <from Phase 4 or "none">,
discuss_rating: <from Phase 4 or null>, discuss_rating: <from Phase 4 or null>,
summary: "<brief summary>" summary: "<brief summary>",
files_modified: <from Phase 4>
}) })
``` ```
4. **Interrupt check**: 4. **Interrupt check**: consensus_blocked HIGH or errors >= 3 → SendMessage → STOP
- consensus_blocked HIGH → SendMessage to coordinator → STOP 5. **Loop**: Return to Phase 1
- Cumulative errors >= 3 → SendMessage to coordinator → STOP
5. **Loop**: Return to Phase 1 to find next same-prefix task
**Phase 5-L does NOT**: SendMessage to coordinator, Fast-Advance, spawn successors. **Phase 5-L does NOT**: SendMessage to coordinator, Fast-Advance, spawn successors.
### Phase 5-F: Final Report (when no more same-prefix tasks OR inner_loop=false) ### Phase 5-F: Final Report (no more same-prefix tasks OR inner_loop=false)
1. **TaskUpdate**: Mark current task `completed` 1. **TaskUpdate**: Mark current task `completed`
2. **Message Bus**: Log completion (same as Phase 5-L step 2) 2. **Message Bus**: Log state_update (same call as Phase 5-L step 2)
3. **Compile final report**: All task summaries + discuss results + artifact paths 3. **Compile final report** and **SendMessage** to coordinator:
4. **Fast-Advance Check**: ```javascript
- Call `TaskList()`, find pending tasks whose blockedBy are ALL completed SendMessage({
- Apply fast-advance rules (see table below) type: "message",
5. **SendMessage** to coordinator OR **spawn successor** directly recipient: "coordinator",
content: "[<role>] <final-report>",
### Fast-Advance Rules summary: "[<role>] Final report delivered"
})
```
Report contents: tasks completed (count + list), artifacts produced (paths), files modified (with evidence), discuss results (verdicts + ratings), key decisions (from context_accumulator), verification summary, warnings/issues.
4. **Fast-Advance Check**: Call `TaskList()`, find pending tasks whose blockedBy are ALL completed, apply rules:
| Condition | Action | | Condition | Action |
|-----------|--------| |-----------|--------|
| Same-prefix successor (inner loop role) | Do NOT spawn — main agent handles via inner loop | | Same-prefix successor (inner loop role) | Do NOT spawn — main agent handles via inner loop |
| 1 ready task, simple linear successor, different prefix | Spawn directly via `Task(run_in_background: true)` + log `fast_advance` to message bus | | 1 ready task, simple linear successor, different prefix | Spawn directly via `Agent(run_in_background: true)` + log `fast_advance` |
| Multiple ready tasks (parallel window) | SendMessage to coordinator (needs orchestration) | | Multiple ready tasks (parallel window) | SendMessage to coordinator (needs orchestration) |
| No ready tasks + others running | SendMessage to coordinator (status update) | | No ready tasks + others running | SendMessage to coordinator (status update) |
| No ready tasks + nothing running | SendMessage to coordinator (pipeline may be complete) | | No ready tasks + nothing running | SendMessage to coordinator (pipeline may be complete) |
| Checkpoint task (e.g., spec->impl transition) | SendMessage to coordinator (needs user confirmation) | | Checkpoint task (e.g., spec->impl transition) | SendMessage to coordinator (needs user confirmation) |
### Fast-Advance Spawn Template ### Fast-Advance Spawn
When fast-advancing to a different-prefix successor: When fast-advancing to a different-prefix successor:
``` ```
Task({ Agent({
subagent_type: "team-worker", subagent_type: "team-worker",
description: "Spawn <successor-role> worker", description: "Spawn <successor-role> worker",
team_name: <team_name>, team_name: <team_name>,
@@ -311,160 +271,104 @@ inner_loop: <true|false based on successor role>`
}) })
``` ```
### Fast-Advance Notification After spawning, MUST log to message bus (passive log, NOT a SendMessage):
After spawning a successor via fast-advance, MUST log to message bus:
``` ```
mcp__ccw-tools__team_msg( mcp__ccw-tools__team_msg(
operation="log", operation="log",
team=<session_id>, session_id=<session_id>,
from=<role>, from=<role>,
to="coordinator",
type="fast_advance", type="fast_advance",
summary="[<role>] fast-advanced <completed-task-id> → spawned <successor-role> for <successor-task-id>" summary="[<role>] fast-advanced <completed-task-id> → spawned <successor-role> for <successor-task-id>"
) )
``` ```
This is a passive log entry (NOT a SendMessage). Coordinator reads it on next callback to reconcile `active_workers`. Coordinator reads this on next callback to reconcile `active_workers`.
### SendMessage Format
```
SendMessage(team_name=<team_name>, recipient="coordinator", message="[<role>] <final-report>")
```
**Final report contents**:
- Tasks completed (count + list)
- Artifacts produced (paths)
- Files modified (paths + before/after evidence from Phase 4 verification)
- Discuss results (verdicts + ratings)
- Key decisions (from context_accumulator)
- Verification summary (methods used, pass/fail status)
- Any warnings or issues
--- ---
## Inner Loop Framework ## Knowledge Transfer & Wisdom
When `inner_loop=true`, the agent processes ALL same-prefix tasks sequentially in a single agent instance:
```
context_accumulator = []
Phase 1: Find first <prefix>-* task
Phase 2-4: Execute role spec
Phase 5-L: Mark done, log, accumulate, check interrupts
More <prefix>-* tasks? → Phase 1 (loop)
No more? → Phase 5-F (final report)
```
**context_accumulator**: Maintained in-memory across loop iterations. Each entry contains task summary + key decisions + discuss results. Passed to subagents as context for knowledge continuity.
**Phase 5-L vs Phase 5-F**:
| Step | Phase 5-L (loop) | Phase 5-F (final) |
|------|-----------------|------------------|
| TaskUpdate completed | YES | YES |
| team_msg log | YES | YES |
| Accumulate summary | YES | - |
| SendMessage to coordinator | NO | YES (all tasks) |
| Fast-Advance check | - | YES |
**Interrupt conditions** (break inner loop immediately):
- consensus_blocked HIGH → SendMessage → STOP
- Cumulative errors >= 3 → SendMessage → STOP
**Crash recovery**: If agent crashes mid-loop, completed tasks are safe (TaskUpdate + artifacts on disk). Coordinator detects orphaned in_progress task on resume, resets to pending, re-spawns. New agent resumes from the interrupted task via Resume Artifact Check.
---
## Wisdom Accumulation
### Load (Phase 2)
Extract session folder from prompt. Read wisdom files if they exist:
```
<session>/wisdom/learnings.md
<session>/wisdom/decisions.md
<session>/wisdom/conventions.md
<session>/wisdom/issues.md
```
Use wisdom context to inform Phase 2-4 execution.
### Contribute (Phase 4/5)
Write discoveries to corresponding wisdom files:
- New patterns → `learnings.md`
- Architecture/design decisions → `decisions.md`
- Codebase conventions → `conventions.md`
- Risks and known issues → `issues.md`
---
## Knowledge Transfer
### Upstream Context Loading (Phase 2) ### Upstream Context Loading (Phase 2)
When executing Phase 2 of a role-spec, the worker MUST load available cross-role context: The worker MUST load available cross-role context before executing role-spec Phase 2:
| Source | Path | Load Method | | Source | Method | Priority |
|--------|------|-------------| |--------|--------|----------|
| Upstream artifacts | `<session>/artifacts/*.md` | Read files listed in task description or dependency chain | | Upstream role state | `team_msg(operation="get_state", role=<upstream_role>)` | **Primary** — O(1) from meta.json |
| Shared memory | `<session>/shared-memory.json` | Read and parse JSON | | Upstream artifacts | Read files referenced in the state's artifact paths | Secondary — for large content |
| Wisdom | `<session>/wisdom/*.md` | Read all wisdom files | | Wisdom files | Read `<session>/wisdom/*.md` | Always load if exists |
| Exploration cache | `<session>/explorations/cache-index.json` | Check before new explorations | | Exploration cache | Check `<session>/explorations/cache-index.json` | Before new explorations |
> **Legacy fallback**: If `get_state` returns null (older sessions), fall back to reading `<session>/shared-memory.json`.
### Downstream Context Publishing (Phase 4) ### Downstream Context Publishing (Phase 4)
After Phase 4 verification, the worker MUST publish its contributions: After Phase 4 verification, the worker MUST publish its contributions:
1. **Artifact**: Write deliverable to `<session>/artifacts/<prefix>-<task-id>-<name>.md` 1. **Artifact**: Write deliverable to `<session>/artifacts/<prefix>-<task-id>-<name>.md`
2. **shared-memory.json**: Read-merge-write under role namespace 2. **State data**: Prepare payload for Phase 5 `state_update` message (see Phase 5-L step 2 for schema)
```json
{ "<role>": { "key_findings": [...], "decisions": [...], "files_modified": [...] } }
```
3. **Wisdom**: Append new patterns to `learnings.md`, decisions to `decisions.md`, issues to `issues.md` 3. **Wisdom**: Append new patterns to `learnings.md`, decisions to `decisions.md`, issues to `issues.md`
4. **Context accumulator** (inner_loop only): Append summary (see Phase 5-L step 3 for schema). Maintain full accumulator for context continuity across iterations.
### Inner Loop Context Accumulator ### Wisdom Files
For `inner_loop: true` roles, `context_accumulator` is maintained in-memory:
``` ```
context_accumulator.append({ <session>/wisdom/learnings.md ← New patterns discovered
task: "<task-id>", <session>/wisdom/decisions.md ← Architecture/design decisions
artifact: "<output-path>", <session>/wisdom/conventions.md ← Codebase conventions
key_decisions: [...], <session>/wisdom/issues.md ← Risks and known issues
summary: "<brief>",
files_modified: [...]
})
``` ```
Pass the full accumulator to each subsequent task's Phase 3 subagent as `## Prior Context`. Load in Phase 2 to inform execution. Contribute in Phase 4/5 with discoveries.
--- ---
## Message Bus Protocol ## Message Bus Protocol
Always use `mcp__ccw-tools__team_msg` for logging. Parameters: Always use `mcp__ccw-tools__team_msg` for team communication.
### log (with state_update) — Primary for Phase 5
| Param | Value | | Param | Value |
|-------|-------| |-------|-------|
| operation | "log" | | operation | "log" |
| team | `<session_id>` (NOT team_name) | | session_id | `<session_id>` (NOT team_name) |
| from | `<role>` | | from | `<role>` |
| to | "coordinator" | | type | "state_update" for completion; or role_spec message_types for non-state messages |
| type | From role_spec message_types | | data | structured state payload (auto-synced to meta.json when type="state_update"). Use `data.ref` for artifact paths |
| summary | `[<role>] <message>` |
| ref | artifact path (optional) |
**Critical**: `team` param must be session ID (e.g., `TLS-my-project-2026-02-27`), not team name. > **Defaults**: `to` defaults to "coordinator", `summary` auto-generated as `[<from>] <type> → <to>`.
> When `type="state_update"`: data is auto-synced to `meta.json.role_state[<role>]`. Top-level keys (`pipeline_mode`, `pipeline_stages`, `team_name`, `task_description`) are promoted to meta root.
### get_state — Primary for Phase 2
```
mcp__ccw-tools__team_msg(
operation="get_state",
session_id=<session_id>,
role=<upstream_role> // omit to get ALL role states
)
```
Returns `role_state[<role>]` from meta.json.
### broadcast — For team-wide signals
```
mcp__ccw-tools__team_msg(
operation="broadcast",
session_id=<session_id>,
from=<role>,
type=<type>
)
```
Equivalent to `log` with `to="all"`. Summary auto-generated.
**CLI fallback** (if MCP tool unavailable): **CLI fallback** (if MCP tool unavailable):
``` ```
ccw team log --team <session_id> --from <role> --to coordinator --type <type> --summary "[<role>] ..." --json ccw team log --session-id <session_id> --from <role> --type <type> --json
``` ```
--- ---
@@ -475,7 +379,7 @@ ccw team log --team <session_id> --from <role> --to coordinator --type <type> --
|---------|-----------| |---------|-----------|
| Process own prefix tasks | Process other role's prefix tasks | | Process own prefix tasks | Process other role's prefix tasks |
| SendMessage to coordinator | Directly communicate with other workers | | SendMessage to coordinator | Directly communicate with other workers |
| Use declared subagents (discuss, explore, doc-gen) | Create tasks for other roles | | Use CLI tools for analysis/exploration | Create tasks for other roles |
| Fast-advance simple successors | Spawn parallel worker batches | | Fast-advance simple successors | Spawn parallel worker batches |
| Write to own artifacts + wisdom | Modify resources outside own scope | | Write to own artifacts + wisdom | Modify resources outside own scope |
@@ -486,13 +390,11 @@ ccw team log --team <session_id> --from <role> --to coordinator --type <type> --
| Scenario | Resolution | | Scenario | Resolution |
|----------|------------| |----------|------------|
| Role spec file not found | Report error via SendMessage, STOP | | Role spec file not found | Report error via SendMessage, STOP |
| Subagent failure | Retry once with alternative subagent_type. Still fails → log warning, continue if possible | | CLI tool failure | Retry once. Still fails → log warning, continue with available data |
| Discuss subagent failure | Skip discuss, log warning in report. Proceed without discuss verdict |
| Explore subagent failure | Continue without codebase context |
| Cumulative errors >= 3 | SendMessage to coordinator with error summary, STOP | | Cumulative errors >= 3 | SendMessage to coordinator with error summary, STOP |
| No tasks found | SendMessage idle status, STOP | | No tasks found | SendMessage idle status, STOP |
| Context missing (prior doc, template) | Request from coordinator via SendMessage | | Context missing (prior doc, template) | Request from coordinator via SendMessage |
| Agent crash mid-loop | Self-healing: coordinator resets orphaned task, re-spawns | | Agent crash mid-loop | Self-healing: completed tasks are safe (TaskUpdate + artifacts on disk). Coordinator detects orphaned in_progress task on resume, resets to pending, re-spawns. New agent resumes via Resume Artifact Check. |
--- ---

View File

@@ -2,7 +2,7 @@
name: ccw-coordinator name: ccw-coordinator
description: Command orchestration tool - analyze requirements, recommend chain, execute sequentially with state persistence description: Command orchestration tool - analyze requirements, recommend chain, execute sequentially with state persistence
argument-hint: "[task description]" argument-hint: "[task description]"
allowed-tools: Task(*), AskUserQuestion(*), Read(*), Write(*), Bash(*), Glob(*), Grep(*) allowed-tools: Agent(*), AskUserQuestion(*), Read(*), Write(*), Bash(*), Glob(*), Grep(*)
--- ---
# CCW Coordinator Command # CCW Coordinator Command
@@ -17,10 +17,10 @@ Interactive orchestration tool: analyze task → discover commands → recommend
| Skill | 包含操作 | | Skill | 包含操作 |
|-------|---------| |-------|---------|
| `workflow-lite-plan` | lite-plan, lite-execute | | `workflow-lite-planex` | lite-plan (includes execution phase internally) |
| `workflow-plan` | plan, plan-verify, replan | | `workflow-plan` | plan, plan-verify, replan |
| `workflow-execute` | execute | | `workflow-execute` | execute |
| `workflow-multi-cli-plan` | multi-cli-plan | | `workflow-multi-cli-plan` | multi-cli-plan (includes execution phase internally) |
| `workflow-test-fix` | test-fix-gen, test-cycle-execute | | `workflow-test-fix` | test-fix-gen, test-cycle-execute |
| `workflow-tdd-plan` | tdd-plan, tdd-verify | | `workflow-tdd-plan` | tdd-plan, tdd-verify |
| `review-cycle` | review-session-cycle, review-module-cycle, review-cycle-fix | | `review-cycle` | review-session-cycle, review-module-cycle, review-cycle-fix |
@@ -30,7 +30,7 @@ Interactive orchestration tool: analyze task → discover commands → recommend
| `workflow:roadmap-with-file` | strategic requirement roadmap → issue creation → execution-plan.json | | `workflow:roadmap-with-file` | strategic requirement roadmap → issue creation → execution-plan.json |
| `workflow:integration-test-cycle` | explore → test dev → test-fix cycle → reflection | | `workflow:integration-test-cycle` | explore → test dev → test-fix cycle → reflection |
| `workflow:refactor-cycle` | tech debt discovery → prioritize → execute → validate | | `workflow:refactor-cycle` | tech debt discovery → prioritize → execute → validate |
| `team-planex` | planner + executor wave pipeline适合大量零散 issue 或 roadmap 产出的清晰 issue,实现 0→1 开发| | `team-planex` | planner + executor wave pipeline适合大量零散 issue 或 roadmap 产出的清晰 issue|
## Core Concept: Minimum Execution Units (最小执行单元) ## Core Concept: Minimum Execution Units (最小执行单元)
@@ -49,9 +49,9 @@ Interactive orchestration tool: analyze task → discover commands → recommend
| Unit Name | Commands | Purpose | Output | | Unit Name | Commands | Purpose | Output |
|-----------|----------|---------|--------| |-----------|----------|---------|--------|
| **Quick Implementation** | lite-plan → lite-execute | Lightweight plan and immediate execution | Working code | | **Quick Implementation** | lite-plan (Phase 1: plan → Phase 2: execute) | Lightweight plan and immediate execution | Working code |
| **Multi-CLI Planning** | multi-cli-plan → lite-execute | Multi-perspective analysis and execution | Working code | | **Multi-CLI Planning** | multi-cli-plan (Phase 1: plan → Phase 2: execute) | Multi-perspective analysis and execution | Working code |
| **Bug Fix** | lite-plan (--bugfix) → lite-execute | Quick bug diagnosis and fix execution | Fixed code | | **Bug Fix** | lite-plan --bugfix (Phase 1: plan → Phase 2: execute) | Quick bug diagnosis and fix execution | Fixed code |
| **Full Planning + Execution** | plan → execute | Detailed planning and execution | Working code | | **Full Planning + Execution** | plan → execute | Detailed planning and execution | Working code |
| **Verified Planning + Execution** | plan → plan-verify → execute | Planning with verification and execution | Working code | | **Verified Planning + Execution** | plan → plan-verify → execute | Planning with verification and execution | Working code |
| **Replanning + Execution** | replan → execute | Update plan and execute changes | Working code | | **Replanning + Execution** | replan → execute | Update plan and execute changes | Working code |
@@ -85,7 +85,7 @@ Interactive orchestration tool: analyze task → discover commands → recommend
| Unit Name | Commands | Purpose | Output | | Unit Name | Commands | Purpose | Output |
|-----------|----------|---------|--------| |-----------|----------|---------|--------|
| **Analyze to Plan** | analyze-with-file → lite-plan | Collaborative analysis → auto chain to lite-plan | discussion.md + code | | **Analyze to Plan** | analyze-with-file → lite-plan | Collaborative analysis → auto chain to lite-plan | discussion.md + code |
| **Brainstorm to Plan** | brainstorm-with-file → lite-plan | Multi-perspective ideation → auto chain to lite-plan | brainstorm.md + code | | **Brainstorm to Plan** | brainstorm-with-file → plan → execute | Multi-perspective ideation → formal planning | brainstorm.md + code |
| **Debug With File** | debug-with-file | Hypothesis-driven debugging with documentation | understanding.md | | **Debug With File** | debug-with-file | Hypothesis-driven debugging with documentation | understanding.md |
| **Collaborative Plan** | collaborative-plan-with-file → unified-execute-with-file | Multi-agent collaborative planning and execution | plan-note.md + code | | **Collaborative Plan** | collaborative-plan-with-file → unified-execute-with-file | Multi-agent collaborative planning and execution | plan-note.md + code |
| **Roadmap Plan** | roadmap-with-file → team-planex | Requirement decomposition and wave execution | execution-plan.json + code | | **Roadmap Plan** | roadmap-with-file → team-planex | Requirement decomposition and wave execution | execution-plan.json + code |
@@ -101,8 +101,8 @@ Interactive orchestration tool: analyze task → discover commands → recommend
| Command | Can Precede | Atomic Units | | Command | Can Precede | Atomic Units |
|---------|-----------|--------------| |---------|-----------|--------------|
| lite-plan | lite-execute, convert-to-plan | Quick Implementation, Rapid-to-Issue, Bug Fix | | lite-plan | convert-to-plan | Quick Implementation, Rapid-to-Issue, Bug Fix |
| multi-cli-plan | lite-execute | Multi-CLI Planning | | multi-cli-plan | (execution is internal) | Multi-CLI Planning |
| plan | plan-verify, execute | Full Planning + Execution, Verified Planning + Execution | | plan | plan-verify, execute | Full Planning + Execution, Verified Planning + Execution |
| plan-verify | execute | Verified Planning + Execution | | plan-verify | execute | Verified Planning + Execution |
| replan | execute | Replanning + Execution | | replan | execute | Replanning + Execution |
@@ -118,7 +118,7 @@ Interactive orchestration tool: analyze task → discover commands → recommend
| issue:queue | issue:execute | Issue Workflow, Rapid-to-Issue, Brainstorm-to-Issue | | issue:queue | issue:execute | Issue Workflow, Rapid-to-Issue, Brainstorm-to-Issue |
| issue:from-brainstorm | issue:queue | Brainstorm-to-Issue | | issue:from-brainstorm | issue:queue | Brainstorm-to-Issue |
| analyze-with-file | lite-plan (auto) | Analyze to Plan | | analyze-with-file | lite-plan (auto) | Analyze to Plan |
| brainstorm-with-file | lite-plan (auto), issue:from-brainstorm | Brainstorm to Plan, Brainstorm-to-Issue | | brainstorm-with-file | plan (auto), issue:from-brainstorm | Brainstorm to Plan, Brainstorm-to-Issue |
| collaborative-plan-with-file | unified-execute-with-file | Collaborative Plan | | collaborative-plan-with-file | unified-execute-with-file | Collaborative Plan |
| roadmap-with-file | team-planex | Roadmap Plan | | roadmap-with-file | team-planex | Roadmap Plan |
| unified-execute-with-file | (terminal) | Collaborative Plan | | unified-execute-with-file | (terminal) | Collaborative Plan |
@@ -137,8 +137,8 @@ Interactive orchestration tool: analyze task → discover commands → recommend
**Example Pipeline with Units**: **Example Pipeline with Units**:
``` ```
需求 → 【lite-plan → lite-execute】→ 代码 → 【test-fix-gen → test-cycle-execute】→ 测试通过 需求 → 【lite-plan】→ 代码 → 【test-fix-gen → test-cycle-execute】→ 测试通过
└──── Quick Implementation ────┘ └────── Test Validation ──────┘ └── Quick Implementation ── └────── Test Validation ──────┘
``` ```
## 3-Phase Workflow ## 3-Phase Workflow
@@ -165,11 +165,13 @@ function detectTaskType(text) {
if (/urgent|production|critical/.test(text) && /fix|bug/.test(text)) return 'bugfix-hotfix'; if (/urgent|production|critical/.test(text) && /fix|bug/.test(text)) return 'bugfix-hotfix';
// With-File workflow patterns (specific keywords - must come before generic bugfix) // With-File workflow patterns (specific keywords - must come before generic bugfix)
if (/brainstorm.*issue|头脑风暴.*issue|idea.*issue|想法.*issue|从.*头脑风暴|convert.*brainstorm/.test(text)) return 'brainstorm-to-issue'; if (/brainstorm.*issue|头脑风暴.*issue|idea.*issue|想法.*issue|从.*头脑风暴|convert.*brainstorm/.test(text)) return 'brainstorm-to-issue';
// 0→1 Greenfield detection (priority over brainstorm/roadmap)
if (/从零开始|from scratch|0.*to.*1|greenfield|全新.*开发|新项目|new project|build.*from.*ground/.test(text)) return 'greenfield';
if (/brainstorm|ideation|头脑风暴|创意|发散思维|creative thinking/.test(text)) return 'brainstorm-file'; if (/brainstorm|ideation|头脑风暴|创意|发散思维|creative thinking/.test(text)) return 'brainstorm-file';
if (/debug.*document|hypothesis.*debug|深度调试|假设.*验证|systematic debug/.test(text)) return 'debug-file'; if (/debug.*document|hypothesis.*debug|深度调试|假设.*验证|systematic debug/.test(text)) return 'debug-file';
if (/analyze.*document|collaborative analysis|协作分析|深度.*理解/.test(text)) return 'analyze-file'; if (/analyze.*document|collaborative analysis|协作分析|深度.*理解/.test(text)) return 'analyze-file';
if (/collaborative.*plan|协作.*规划|多人.*规划|multi.*agent.*plan|Plan Note|分工.*规划/.test(text)) return 'collaborative-plan'; if (/collaborative.*plan|协作.*规划|多人.*规划|multi.*agent.*plan|Plan Note|分工.*规划/.test(text)) return 'collaborative-plan';
if (/roadmap|需求.*规划|需求.*拆解|requirement.*plan|progressive.*plan|路线.*图/.test(text)) return 'roadmap'; if (/roadmap|路线.*图/.test(text)) return 'roadmap'; // Narrowed: only explicit roadmap keywords
if (/spec.*gen|specification|PRD|产品需求|产品文档|产品规格/.test(text)) return 'spec-driven'; if (/spec.*gen|specification|PRD|产品需求|产品文档|产品规格/.test(text)) return 'spec-driven';
// Cycle workflow patterns // Cycle workflow patterns
if (/integration.*test|集成测试|端到端.*测试|e2e.*test|integration.*cycle/.test(text)) return 'integration-test'; if (/integration.*test|集成测试|端到端.*测试|e2e.*test|integration.*cycle/.test(text)) return 'integration-test';
@@ -232,13 +234,7 @@ const commandPorts = {
tags: ['planning'], tags: ['planning'],
atomic_group: 'quick-implementation' atomic_group: 'quick-implementation'
}, },
'lite-execute': { // lite-execute is now an internal phase of lite-plan and multi-cli-plan (not a standalone command)
name: 'lite-execute',
input: ['plan', 'multi-cli-plan'],
output: ['code'],
tags: ['execution'],
atomic_groups: ['quick-implementation', 'multi-cli-planning', 'bug-fix']
},
'plan': { 'plan': {
name: 'plan', name: 'plan',
input: ['requirement', 'specification'], input: ['requirement', 'specification'],
@@ -407,7 +403,7 @@ const commandPorts = {
output: ['brainstorm-document'], output: ['brainstorm-document'],
tags: ['brainstorm', 'with-file'], tags: ['brainstorm', 'with-file'],
atomic_group: 'brainstorm-to-plan', atomic_group: 'brainstorm-to-plan',
note: 'Auto chains to lite-plan with brainstorm artifacts' note: 'Auto chains to workflow-plan with brainstorm artifacts'
}, },
'issue:from-brainstorm': { 'issue:from-brainstorm': {
name: 'issue:from-brainstorm', name: 'issue:from-brainstorm',
@@ -515,8 +511,10 @@ function determinePortFlow(taskType, constraints) {
// Issue workflow types // Issue workflow types
'issue-batch': { inputPort: 'codebase', outputPort: 'completed-issues' }, 'issue-batch': { inputPort: 'codebase', outputPort: 'completed-issues' },
'issue-transition': { inputPort: 'requirement', outputPort: 'completed-issues' }, 'issue-transition': { inputPort: 'requirement', outputPort: 'completed-issues' },
// With-File workflow types (auto chain to lite-plan) // 0→1 Greenfield (exploration → formal planning → execution)
'brainstorm-file': { inputPort: 'exploration-topic', outputPort: 'code' }, 'greenfield': { inputPort: 'exploration-topic', outputPort: 'test-passed' },
// With-File workflow types (auto chain to plan)
'brainstorm-file': { inputPort: 'exploration-topic', outputPort: 'test-passed' },
'brainstorm-to-issue': { inputPort: 'brainstorm-document', outputPort: 'completed-issues' }, 'brainstorm-to-issue': { inputPort: 'brainstorm-document', outputPort: 'completed-issues' },
'debug-file': { inputPort: 'bug-report', outputPort: 'understanding-document' }, 'debug-file': { inputPort: 'bug-report', outputPort: 'understanding-document' },
'analyze-file': { inputPort: 'analysis-topic', outputPort: 'code' }, 'analyze-file': { inputPort: 'analysis-topic', outputPort: 'code' },
@@ -546,12 +544,11 @@ function determinePortFlow(taskType, constraints) {
Recommended Command Chain: Recommended Command Chain:
Pipeline (管道视图): Pipeline (管道视图):
需求 → lite-plan → 计划 → lite-execute → 代码 → test-cycle-execute → 测试通过 需求 → lite-plan → 代码 → test-cycle-execute → 测试通过
Commands (命令列表): Commands (命令列表):
1. /workflow-lite-plan 1. /workflow-lite-planex
2. /workflow:lite-execute 2. /workflow-test-fix
3. /workflow-test-fix
Proceed? [Confirm / Show Details / Adjust / Cancel] Proceed? [Confirm / Show Details / Adjust / Cancel]
``` ```
@@ -686,9 +683,7 @@ function formatCommand(cmd, previousResults, analysis) {
if (['lite-plan', 'plan', 'tdd-plan', 'multi-cli-plan'].includes(name)) { if (['lite-plan', 'plan', 'tdd-plan', 'multi-cli-plan'].includes(name)) {
prompt += ` "${analysis.goal}"`; prompt += ` "${analysis.goal}"`;
} else if (name === 'lite-execute') { // lite-execute is now an internal phase of lite-plan (not invoked separately)
const hasPlan = previousResults.some(r => r.command.includes('plan'));
prompt += hasPlan ? ' --in-memory' : ` "${analysis.goal}"`;
} else if (name === 'execute') { } else if (name === 'execute') {
const plan = previousResults.find(r => r.command.includes('plan')); const plan = previousResults.find(r => r.command.includes('plan'));
@@ -707,7 +702,7 @@ function formatCommand(cmd, previousResults, analysis) {
prompt = `/spec-generator -y "${analysis.goal}"`; prompt = `/spec-generator -y "${analysis.goal}"`;
} else if (name === 'test-gen') { } else if (name === 'test-gen') {
const impl = previousResults.find(r => r.command.includes('execute') || r.command.includes('lite-execute')); const impl = previousResults.find(r => r.command.includes('execute'));
prompt += impl?.session_id ? ` "${impl.session_id}"` : ` "${analysis.goal}"`; prompt += impl?.session_id ? ` "${impl.session_id}"` : ` "${analysis.goal}"`;
} else if (name === 'test-fix-gen') { } else if (name === 'test-fix-gen') {
@@ -856,7 +851,7 @@ workflow 操作通过 `Skill()` 调用对应的 Skill。
```javascript ```javascript
// Skill 调用方式 // Skill 调用方式
Skill({ skill: 'workflow-lite-plan', args: '"task description"' }); Skill({ skill: 'workflow-lite-planex', args: '"task description"' });
Skill({ skill: 'workflow-execute', args: '--resume-session="WFS-xxx"' }); Skill({ skill: 'workflow-execute', args: '--resume-session="WFS-xxx"' });
Skill({ skill: 'brainstorm', args: '"exploration topic"' }); Skill({ skill: 'brainstorm', args: '"exploration topic"' });
Skill({ skill: 'spec-generator', args: '"product specification"' }); Skill({ skill: 'spec-generator', args: '"product specification"' });
@@ -909,10 +904,10 @@ Task: <description>
| Skill | 包含操作 | | Skill | 包含操作 |
|-------|---------| |-------|---------|
| `workflow-lite-plan` | lite-plan, lite-execute | | `workflow-lite-planex` | lite-plan (includes execution phase internally) |
| `workflow-plan` | plan, plan-verify, replan | | `workflow-plan` | plan, plan-verify, replan |
| `workflow-execute` | execute | | `workflow-execute` | execute |
| `workflow-multi-cli-plan` | multi-cli-plan | | `workflow-multi-cli-plan` | multi-cli-plan (includes execution phase internally) |
| `workflow-test-fix` | test-fix-gen, test-cycle-execute | | `workflow-test-fix` | test-fix-gen, test-cycle-execute |
| `workflow-tdd-plan` | tdd-plan, tdd-verify | | `workflow-tdd-plan` | tdd-plan, tdd-verify |
| `review-cycle` | review-session-cycle, review-module-cycle, review-cycle-fix | | `review-cycle` | review-session-cycle, review-module-cycle, review-cycle-fix |
@@ -944,7 +939,7 @@ Task: <description>
| Task Type | Pipeline | Minimum Units | | Task Type | Pipeline | Minimum Units |
|-----------|----------|---| |-----------|----------|---|
| **feature** (simple) | 需求 →【lite-plan → lite-execute】→ 代码 →【test-fix-gen → test-cycle-execute】→ 测试通过 | Quick Implementation + Test Validation | | **feature** (simple) | 需求 →【lite-plan】→ 代码 →【test-fix-gen → test-cycle-execute】→ 测试通过 | Quick Implementation + Test Validation |
| **feature** (complex) | 需求 →【plan → plan-verify】→ validate → execute → 代码 → review → fix | Full Planning + Code Review + Testing | | **feature** (complex) | 需求 →【plan → plan-verify】→ validate → execute → 代码 → review → fix | Full Planning + Code Review + Testing |
| **bugfix** | Bug报告 → lite-plan (--bugfix) → 修复代码 →【test-fix-gen → test-cycle-execute】→ 测试通过 | Bug Fix + Test Validation | | **bugfix** | Bug报告 → lite-plan (--bugfix) → 修复代码 →【test-fix-gen → test-cycle-execute】→ 测试通过 | Bug Fix + Test Validation |
| **tdd** | 需求 → tdd-plan → TDD任务 → execute → 代码 → tdd-verify | TDD Planning + Execution | | **tdd** | 需求 → tdd-plan → TDD任务 → execute → 代码 → tdd-verify | TDD Planning + Execution |
@@ -952,12 +947,13 @@ Task: <description>
| **test-gen** | 代码/会话 →【test-gen → execute】→ 测试通过 | Test Generation + Execution | | **test-gen** | 代码/会话 →【test-gen → execute】→ 测试通过 | Test Generation + Execution |
| **review** | 代码 →【review-* → review-cycle-fix】→ 修复代码 →【test-fix-gen → test-cycle-execute】→ 测试通过 | Code Review + Testing | | **review** | 代码 →【review-* → review-cycle-fix】→ 修复代码 →【test-fix-gen → test-cycle-execute】→ 测试通过 | Code Review + Testing |
| **brainstorm** | 探索主题 → brainstorm → 分析 →【plan → plan-verify】→ execute → test | Exploration + Planning + Execution | | **brainstorm** | 探索主题 → brainstorm → 分析 →【plan → plan-verify】→ execute → test | Exploration + Planning + Execution |
| **multi-cli** | 需求 → multi-cli-plan → 对比分析 → lite-execute → test | Multi-Perspective + Testing | | **multi-cli** | 需求 → multi-cli-plan → 对比分析 → 代码 → test | Multi-Perspective + Testing |
| **spec-driven** | 需求 →【spec-generator → plan → execute】→ 代码 →【test-fix-gen → test-cycle-execute】→ 测试通过 | Spec-Driven + Testing | | **spec-driven** | 需求 →【spec-generator → plan → execute】→ 代码 →【test-fix-gen → test-cycle-execute】→ 测试通过 | Spec-Driven + Testing |
| **issue-batch** | 代码库 →【discover → plan → queue → execute】→ 完成 issues | Issue Workflow | | **issue-batch** | 代码库 →【discover → plan → queue → execute】→ 完成 issues | Issue Workflow |
| **issue-transition** | 需求 →【lite-plan → convert-to-plan → queue → execute】→ 完成 issues | Rapid-to-Issue | | **issue-transition** | 需求 →【lite-plan → convert-to-plan → queue → execute】→ 完成 issues | Rapid-to-Issue |
| **analyze-file** | 分析主题 →【analyze-with-file → lite-plan → lite-execute】→ 代码 | Analyze to Plan | | **analyze-file** | 分析主题 →【analyze-with-file → lite-plan】→ 代码 | Analyze to Plan |
| **brainstorm-file** | 主题 →【brainstorm-with-file → lite-plan → lite-execute】→ 代码 | Brainstorm to Plan | | **greenfield** | 需求 →【brainstorm-with-file → plan → execute】→ 代码 → test | Greenfield (0→1) |
| **brainstorm-file** | 主题 →【brainstorm-with-file → plan → execute】→ 代码 → test | Brainstorm to Plan |
| **brainstorm-to-issue** | brainstorm.md →【from-brainstorm → queue → execute】→ 完成 issues | Brainstorm to Issue | | **brainstorm-to-issue** | brainstorm.md →【from-brainstorm → queue → execute】→ 完成 issues | Brainstorm to Issue |
| **debug-file** | Bug报告 → debug-with-file → understanding.md (自包含) | Debug With File | | **debug-file** | Bug报告 → debug-with-file → understanding.md (自包含) | Debug With File |
| **collaborative-plan** | 需求 →【collaborative-plan-with-file → unified-execute-with-file】→ 代码 | Collaborative Plan | | **collaborative-plan** | 需求 →【collaborative-plan-with-file → unified-execute-with-file】→ 代码 | Collaborative Plan |
@@ -967,8 +963,8 @@ Task: <description>
| **team-planex** | 需求 → team-planex → 代码 (自包含) | Team Plan+Execute | | **team-planex** | 需求 → team-planex → 代码 (自包含) | Team Plan+Execute |
| **bugfix-hotfix** | Bug报告(紧急) → lite-plan (--hotfix) → 修复代码 | Hotfix (skip tests) | | **bugfix-hotfix** | Bug报告(紧急) → lite-plan (--hotfix) → 修复代码 | Hotfix (skip tests) |
| **exploration** | 探索主题 → brainstorm →【plan → execute】→ 代码 → test | Exploration + Planning | | **exploration** | 探索主题 → brainstorm →【plan → execute】→ 代码 → test | Exploration + Planning |
| **quick-task** | 需求 →【lite-plan → lite-execute】→ 代码 → test | Quick Implementation | | **quick-task** | 需求 →【lite-plan】→ 代码 → test | Quick Implementation |
| **ui-design** | UI需求 → ui-design:explore → plan → execute → 代码 | UI Design | | **ui-design** | UI需求 → ui-design:explore → plan → execute → 代码 | UI Design |
| **documentation** | 文档需求 → lite-plan → lite-execute → 文档 | Documentation | | **documentation** | 文档需求 → lite-plan → 文档 | Documentation |
Refer to the Skill 映射 section above for available Skills and Commands. Refer to the Skill 映射 section above for available Skills and Commands.

View File

@@ -15,7 +15,7 @@ Main process orchestrator: intent analysis → workflow selection → command ch
| Skill | 内部流水线 | | Skill | 内部流水线 |
|-------|-----------| |-------|-----------|
| `workflow-lite-plan` | explore → plan → confirm → execute | | `workflow-lite-planex` | explore → plan → confirm → execute |
| `workflow-plan` | session → context → convention → gen → verify/replan | | `workflow-plan` | session → context → convention → gen → verify/replan |
| `workflow-execute` | session discovery → task processing → commit | | `workflow-execute` | session discovery → task processing → commit |
| `workflow-tdd-plan` | 6-phase TDD plan → verify | | `workflow-tdd-plan` | 6-phase TDD plan → verify |
@@ -28,7 +28,7 @@ Main process orchestrator: intent analysis → workflow selection → command ch
| `workflow:roadmap-with-file` | strategic requirement roadmap → issue creation → execution-plan.json | | `workflow:roadmap-with-file` | strategic requirement roadmap → issue creation → execution-plan.json |
| `workflow:integration-test-cycle` | explore → test dev → test-fix cycle → reflection | | `workflow:integration-test-cycle` | explore → test dev → test-fix cycle → reflection |
| `workflow:refactor-cycle` | tech debt discovery → prioritize → execute → validate | | `workflow:refactor-cycle` | tech debt discovery → prioritize → execute → validate |
| `team-planex` | planner + executor wave pipeline适合大量零散 issue 或 roadmap 产出的清晰 issue,实现 0→1 开发| | `team-planex` | planner + executor wave pipeline适合大量零散 issue 或 roadmap 产出的清晰 issue|
## Core Concept: Self-Contained Skills (自包含 Skill) ## Core Concept: Self-Contained Skills (自包含 Skill)
@@ -43,17 +43,19 @@ Main process orchestrator: intent analysis → workflow selection → command ch
| 单元类型 | Skill | 说明 | | 单元类型 | Skill | 说明 |
|---------|-------|------| |---------|-------|------|
| 轻量 Plan+Execute | `workflow-lite-plan` | 内部完成 plan→execute | | 轻量 Plan+Execute | `workflow-lite-planex` | 内部完成 plan→execute |
| 标准 Planning | `workflow-plan``workflow-execute` | plan 和 execute 是独立 Skill | | 标准 Planning | `workflow-plan``workflow-execute` | plan 和 execute 是独立 Skill |
| TDD Planning | `workflow-tdd-plan``workflow-execute` | tdd-plan 和 execute 是独立 Skill | | TDD Planning | `workflow-tdd-plan``workflow-execute` | tdd-plan 和 execute 是独立 Skill |
| 规格驱动 | `spec-generator``workflow-plan``workflow-execute` | 规格文档驱动完整开发 | | 规格驱动 | `spec-generator``workflow-plan``workflow-execute` | 规格文档驱动完整开发 |
| 测试流水线 | `workflow-test-fix` | 内部完成 gen→cycle | | 测试流水线 | `workflow-test-fix` | 内部完成 gen→cycle |
| 代码审查 | `review-cycle` | 内部完成 review→fix | | 代码审查 | `review-cycle` | 内部完成 review→fix |
| 多CLI协作 | `workflow-multi-cli-plan` | ACE context → CLI discussion → plan → execute | | 多CLI协作 | `workflow-multi-cli-plan` | ACE context → CLI discussion → plan → execute |
| 分析→规划 | `workflow:analyze-with-file``workflow-lite-plan` | 协作分析产物自动传递给 lite-plan | | 分析→规划 | `workflow:analyze-with-file``workflow-lite-planex` | 协作分析产物自动传递给 lite-plan |
| 头脑风暴→规划 | `workflow:brainstorm-with-file``workflow-lite-plan` | 头脑风暴产物自动传递给 lite-plan | | 头脑风暴→规划 | `workflow:brainstorm-with-file``workflow-plan``workflow-execute` | 头脑风暴产物自动传递给正式规划 |
| 0→1 开发(小) | `workflow:brainstorm-with-file``workflow-plan``workflow-execute` | 小规模从零开始,探索+正式规划+实现 |
| 0→1 开发(中/大) | `workflow:brainstorm-with-file``workflow-plan``workflow-execute` | 探索后正式规划+执行 |
| 协作规划 | `workflow:collaborative-plan-with-file``workflow:unified-execute-with-file` | 多 agent 协作规划→通用执行 | | 协作规划 | `workflow:collaborative-plan-with-file``workflow:unified-execute-with-file` | 多 agent 协作规划→通用执行 |
| 需求路线图 | `workflow:roadmap-with-file``team-planex` | 需求拆解→issue 创建→wave pipeline 执行 | | 需求路线图 | `workflow:roadmap-with-file``team-planex` | 需求拆解→issue 创建→wave pipeline 执行(需明确 roadmap 关键词)|
| 集成测试循环 | `workflow:integration-test-cycle` | 自迭代集成测试闭环 | | 集成测试循环 | `workflow:integration-test-cycle` | 自迭代集成测试闭环 |
| 重构循环 | `workflow:refactor-cycle` | 技术债务发现→重构→验证 | | 重构循环 | `workflow:refactor-cycle` | 技术债务发现→重构→验证 |
@@ -124,12 +126,14 @@ function detectTaskType(text) {
const patterns = { const patterns = {
'bugfix-hotfix': /urgent|production|critical/ && /fix|bug/, 'bugfix-hotfix': /urgent|production|critical/ && /fix|bug/,
// With-File workflows (documented exploration → auto chain to lite-plan) // With-File workflows (documented exploration → auto chain to lite-plan)
// 0→1 Greenfield detection (priority over brainstorm/roadmap)
'greenfield': /从零开始|from scratch|0.*to.*1|greenfield|全新.*开发|新项目|new project|build.*from.*ground/,
'brainstorm': /brainstorm|ideation|头脑风暴|创意|发散思维|creative thinking|multi-perspective.*think|compare perspectives|探索.*可能/, 'brainstorm': /brainstorm|ideation|头脑风暴|创意|发散思维|creative thinking|multi-perspective.*think|compare perspectives|探索.*可能/,
'brainstorm-to-issue': /brainstorm.*issue|头脑风暴.*issue|idea.*issue|想法.*issue|从.*头脑风暴|convert.*brainstorm/, 'brainstorm-to-issue': /brainstorm.*issue|头脑风暴.*issue|idea.*issue|想法.*issue|从.*头脑风暴|convert.*brainstorm/,
'debug-file': /debug.*document|hypothesis.*debug|troubleshoot.*track|investigate.*log|调试.*记录|假设.*验证|systematic debug|深度调试/, 'debug-file': /debug.*document|hypothesis.*debug|troubleshoot.*track|investigate.*log|调试.*记录|假设.*验证|systematic debug|深度调试/,
'analyze-file': /analyze.*document|explore.*concept|understand.*architecture|investigate.*discuss|collaborative analysis|分析.*讨论|深度.*理解|协作.*分析/, 'analyze-file': /analyze.*document|explore.*concept|understand.*architecture|investigate.*discuss|collaborative analysis|分析.*讨论|深度.*理解|协作.*分析/,
'collaborative-plan': /collaborative.*plan|协作.*规划|多人.*规划|multi.*agent.*plan|Plan Note|分工.*规划/, 'collaborative-plan': /collaborative.*plan|协作.*规划|多人.*规划|multi.*agent.*plan|Plan Note|分工.*规划/,
'roadmap': /roadmap|需求.*规划|需求.*拆解|requirement.*plan|progressive.*plan|路线.*图/, 'roadmap': /roadmap|路线.*图/, // Narrowed: only explicit roadmap keywords (需求规划/需求拆解 moved to greenfield routing)
'spec-driven': /spec.*gen|specification|PRD|产品需求|产品文档|产品规格/, 'spec-driven': /spec.*gen|specification|PRD|产品需求|产品文档|产品规格/,
// Cycle workflows (self-iterating with reflection) // Cycle workflows (self-iterating with reflection)
'integration-test': /integration.*test|集成测试|端到端.*测试|e2e.*test|integration.*cycle/, 'integration-test': /integration.*test|集成测试|端到端.*测试|e2e.*test|integration.*cycle/,
@@ -184,13 +188,18 @@ async function clarifyRequirements(analysis) {
function selectWorkflow(analysis) { function selectWorkflow(analysis) {
const levelMap = { const levelMap = {
'bugfix-hotfix': { level: 2, flow: 'bugfix.hotfix' }, 'bugfix-hotfix': { level: 2, flow: 'bugfix.hotfix' },
// 0→1 Greenfield (complexity-adaptive routing)
'greenfield': { level: analysis.complexity === 'high' ? 4 : 3,
flow: analysis.complexity === 'high' ? 'greenfield-phased' // large: brainstorm → workflow-plan → execute
: analysis.complexity === 'medium' ? 'greenfield-plan' // medium: brainstorm → workflow-plan → execute
: 'brainstorm-to-plan' }, // small: brainstorm → workflow-plan
// With-File workflows → auto chain to lite-plan // With-File workflows → auto chain to lite-plan
'brainstorm': { level: 4, flow: 'brainstorm-to-plan' }, // brainstorm-with-file → lite-plan 'brainstorm': { level: 4, flow: 'brainstorm-to-plan' }, // brainstorm-with-file → workflow-plan
'brainstorm-to-issue': { level: 4, flow: 'brainstorm-to-issue' }, // Brainstorm → Issue workflow 'brainstorm-to-issue': { level: 4, flow: 'brainstorm-to-issue' }, // Brainstorm → Issue workflow
'debug-file': { level: 3, flow: 'debug-with-file' }, // Hypothesis-driven debugging (standalone) 'debug-file': { level: 3, flow: 'debug-with-file' }, // Hypothesis-driven debugging (standalone)
'analyze-file': { level: 3, flow: 'analyze-to-plan' }, // analyze-with-file → lite-plan 'analyze-file': { level: 3, flow: 'analyze-to-plan' }, // analyze-with-file → lite-plan
'collaborative-plan': { level: 3, flow: 'collaborative-plan' }, // Multi-agent collaborative planning 'collaborative-plan': { level: 3, flow: 'collaborative-plan' }, // Multi-agent collaborative planning
'roadmap': { level: 4, flow: 'roadmap' }, // roadmap → team-planex 'roadmap': { level: 4, flow: 'roadmap' }, // roadmap → team-planex (explicit roadmap only)
'spec-driven': { level: 4, flow: 'spec-driven' }, // spec-generator → plan → execute 'spec-driven': { level: 4, flow: 'spec-driven' }, // spec-generator → plan → execute
// Cycle workflows (self-iterating with reflection) // Cycle workflows (self-iterating with reflection)
'integration-test': { level: 3, flow: 'integration-test-cycle' }, 'integration-test': { level: 3, flow: 'integration-test-cycle' },
@@ -222,7 +231,7 @@ function buildCommandChain(workflow, analysis) {
const chains = { const chains = {
// Level 2 - Lightweight // Level 2 - Lightweight
'rapid': [ 'rapid': [
{ cmd: 'workflow-lite-plan', args: `"${analysis.goal}"` }, { cmd: 'workflow-lite-planex', args: `"${analysis.goal}"` },
...(analysis.constraints?.includes('skip-tests') ? [] : [ ...(analysis.constraints?.includes('skip-tests') ? [] : [
{ cmd: 'workflow-test-fix', args: '' } { cmd: 'workflow-test-fix', args: '' }
]) ])
@@ -230,21 +239,21 @@ function buildCommandChain(workflow, analysis) {
// Level 2 Bridge - Lightweight to Issue Workflow // Level 2 Bridge - Lightweight to Issue Workflow
'rapid-to-issue': [ 'rapid-to-issue': [
{ cmd: 'workflow-lite-plan', args: `"${analysis.goal}" --plan-only` }, { cmd: 'workflow-lite-planex', args: `"${analysis.goal}" --plan-only` },
{ cmd: 'issue:convert-to-plan', args: '--latest-lite-plan -y' }, { cmd: 'issue:convert-to-plan', args: '--latest-lite-plan -y' },
{ cmd: 'issue:queue', args: '' }, { cmd: 'issue:queue', args: '' },
{ cmd: 'issue:execute', args: '--queue auto' } { cmd: 'issue:execute', args: '--queue auto' }
], ],
'bugfix.standard': [ 'bugfix.standard': [
{ cmd: 'workflow-lite-plan', args: `--bugfix "${analysis.goal}"` }, { cmd: 'workflow-lite-planex', args: `--bugfix "${analysis.goal}"` },
...(analysis.constraints?.includes('skip-tests') ? [] : [ ...(analysis.constraints?.includes('skip-tests') ? [] : [
{ cmd: 'workflow-test-fix', args: '' } { cmd: 'workflow-test-fix', args: '' }
]) ])
], ],
'bugfix.hotfix': [ 'bugfix.hotfix': [
{ cmd: 'workflow-lite-plan', args: `--hotfix "${analysis.goal}"` } { cmd: 'workflow-lite-planex', args: `--hotfix "${analysis.goal}"` }
], ],
'multi-cli-plan': [ 'multi-cli-plan': [
@@ -255,18 +264,22 @@ function buildCommandChain(workflow, analysis) {
], ],
'docs': [ 'docs': [
{ cmd: 'workflow-lite-plan', args: `"${analysis.goal}"` } { cmd: 'workflow-lite-planex', args: `"${analysis.goal}"` }
], ],
// With-File → Auto Chain to lite-plan // With-File → Auto Chain to lite-plan
'analyze-to-plan': [ 'analyze-to-plan': [
{ cmd: 'workflow:analyze-with-file', args: `"${analysis.goal}"` }, { cmd: 'workflow:analyze-with-file', args: `"${analysis.goal}"` },
{ cmd: 'workflow-lite-plan', args: '' } // auto receives analysis artifacts (discussion.md) { cmd: 'workflow-lite-planex', args: '' } // auto receives analysis artifacts (discussion.md)
], ],
'brainstorm-to-plan': [ 'brainstorm-to-plan': [
{ cmd: 'workflow:brainstorm-with-file', args: `"${analysis.goal}"` }, { cmd: 'workflow:brainstorm-with-file', args: `"${analysis.goal}"` },
{ cmd: 'workflow-lite-plan', args: '' } // auto receives brainstorm artifacts (brainstorm.md) { cmd: 'workflow-plan', args: '' }, // formal planning with brainstorm artifacts
{ cmd: 'workflow-execute', args: '' },
...(analysis.constraints?.includes('skip-tests') ? [] : [
{ cmd: 'workflow-test-fix', args: '' }
])
], ],
'debug-with-file': [ 'debug-with-file': [
@@ -281,6 +294,26 @@ function buildCommandChain(workflow, analysis) {
{ cmd: 'issue:execute', args: '--queue auto' } { cmd: 'issue:execute', args: '--queue auto' }
], ],
// 0→1 Greenfield (complexity-adaptive)
'greenfield-plan': [
{ cmd: 'workflow:brainstorm-with-file', args: `"${analysis.goal}"` },
{ cmd: 'workflow-plan', args: '' }, // formal planning after exploration
{ cmd: 'workflow-execute', args: '' },
...(analysis.constraints?.includes('skip-tests') ? [] : [
{ cmd: 'workflow-test-fix', args: '' }
])
],
'greenfield-phased': [
{ cmd: 'workflow:brainstorm-with-file', args: `"${analysis.goal}"` },
{ cmd: 'workflow-plan', args: '' }, // formal planning after exploration
{ cmd: 'workflow-execute', args: '' },
{ cmd: 'review-cycle', args: '' },
...(analysis.constraints?.includes('skip-tests') ? [] : [
{ cmd: 'workflow-test-fix', args: '' }
])
],
// Universal Plan+Execute // Universal Plan+Execute
'collaborative-plan': [ 'collaborative-plan': [
{ cmd: 'workflow:collaborative-plan-with-file', args: `"${analysis.goal}"` }, { cmd: 'workflow:collaborative-plan-with-file', args: `"${analysis.goal}"` },
@@ -338,7 +371,7 @@ function buildCommandChain(workflow, analysis) {
{ cmd: 'workflow-execute', args: '' } { cmd: 'workflow-execute', args: '' }
], ],
// Level 4 - Full Exploration // Level 4 - Full Exploration (brainstorm → formal planning → execute)
'full': [ 'full': [
{ cmd: 'brainstorm', args: `"${analysis.goal}"` }, { cmd: 'brainstorm', args: `"${analysis.goal}"` },
{ cmd: 'workflow-plan', args: '' }, { cmd: 'workflow-plan', args: '' },
@@ -443,7 +476,7 @@ function setupTodoTracking(chain, workflow, analysis) {
``` ```
**Output**: **Output**:
- TODO: `-> CCW:rapid: [1/2] workflow-lite-plan | CCW:rapid: [2/2] workflow-test-fix | ...` - TODO: `-> CCW:rapid: [1/2] workflow-lite-planex | CCW:rapid: [2/2] workflow-test-fix | ...`
- Status File: `.workflow/.ccw/{session_id}/status.json` - Status File: `.workflow/.ccw/{session_id}/status.json`
--- ---
@@ -595,15 +628,17 @@ Phase 5: Execute Command Chain
| Input | Type | Level | Pipeline | | Input | Type | Level | Pipeline |
|-------|------|-------|----------| |-------|------|-------|----------|
| "Add API endpoint" | feature (low) | 2 | workflow-lite-plan → workflow-test-fix | | "Add API endpoint" | feature (low) | 2 | workflow-lite-planex → workflow-test-fix |
| "Fix login timeout" | bugfix | 2 | workflow-lite-plan → workflow-test-fix | | "Fix login timeout" | bugfix | 2 | workflow-lite-planex → workflow-test-fix |
| "Use issue workflow" | issue-transition | 2.5 | workflow-lite-plan(plan-only) → convert-to-plan → queue → execute | | "Use issue workflow" | issue-transition | 2.5 | workflow-lite-planex(plan-only) → convert-to-plan → queue → execute |
| "协作分析: 认证架构" | analyze-file | 3 | analyze-with-file → workflow-lite-plan | | "协作分析: 认证架构" | analyze-file | 3 | analyze-with-file → workflow-lite-planex |
| "深度调试 WebSocket" | debug-file | 3 | workflow:debug-with-file | | "深度调试 WebSocket" | debug-file | 3 | workflow:debug-with-file |
| "头脑风暴: 通知系统" | brainstorm | 4 | brainstorm-with-file → workflow-lite-plan | | "从零开始: 用户系统" | greenfield (medium) | 3 | brainstorm-with-file → workflow-plan → workflow-execute → workflow-test-fix |
| "greenfield: 大型平台" | greenfield (high) | 4 | brainstorm-with-file → workflow-plan → workflow-execute → review-cycle → workflow-test-fix |
| "头脑风暴: 通知系统" | brainstorm | 4 | brainstorm-with-file → workflow-plan → workflow-execute → workflow-test-fix |
| "从头脑风暴创建 issue" | brainstorm-to-issue | 4 | issue:from-brainstorm → issue:queue → issue:execute | | "从头脑风暴创建 issue" | brainstorm-to-issue | 4 | issue:from-brainstorm → issue:queue → issue:execute |
| "协作规划: 实时通知系统" | collaborative-plan | 3 | collaborative-plan-with-file → unified-execute-with-file | | "协作规划: 实时通知系统" | collaborative-plan | 3 | collaborative-plan-with-file → unified-execute-with-file |
| "需求路线图: OAuth + 2FA" | roadmap | 4 | roadmap-with-file → team-planex | | "roadmap: OAuth + 2FA" | roadmap | 4 | roadmap-with-file → team-planex |
| "specification: 用户系统" | spec-driven | 4 | spec-generator → workflow-plan → workflow-execute → workflow-test-fix | | "specification: 用户系统" | spec-driven | 4 | spec-generator → workflow-plan → workflow-execute → workflow-test-fix |
| "集成测试: 支付流程" | integration-test | 3 | workflow:integration-test-cycle | | "集成测试: 支付流程" | integration-test | 3 | workflow:integration-test-cycle |
| "重构 auth 模块" | refactor | 3 | workflow:refactor-cycle | | "重构 auth 模块" | refactor | 3 | workflow:refactor-cycle |
@@ -638,13 +673,13 @@ Phase 5: Execute Command Chain
```javascript ```javascript
// Initial state (rapid workflow: 2 steps) // Initial state (rapid workflow: 2 steps)
todos = [ todos = [
{ content: "CCW:rapid: [1/2] workflow-lite-plan", status: "in_progress" }, { content: "CCW:rapid: [1/2] workflow-lite-planex", status: "in_progress" },
{ content: "CCW:rapid: [2/2] workflow-test-fix", status: "pending" } { content: "CCW:rapid: [2/2] workflow-test-fix", status: "pending" }
]; ];
// After step 1 completes // After step 1 completes
todos = [ todos = [
{ content: "CCW:rapid: [1/2] workflow-lite-plan", status: "completed" }, { content: "CCW:rapid: [1/2] workflow-lite-planex", status: "completed" },
{ content: "CCW:rapid: [2/2] workflow-test-fix", status: "in_progress" } { content: "CCW:rapid: [2/2] workflow-test-fix", status: "in_progress" }
]; ];
``` ```
@@ -669,7 +704,7 @@ todos = [
"complexity": "medium" "complexity": "medium"
}, },
"command_chain": [ "command_chain": [
{ "index": 0, "command": "workflow-lite-plan", "status": "completed" }, { "index": 0, "command": "workflow-lite-planex", "status": "completed" },
{ "index": 1, "command": "workflow-test-fix", "status": "running" } { "index": 1, "command": "workflow-test-fix", "status": "running" }
], ],
"current_index": 1 "current_index": 1
@@ -687,13 +722,13 @@ todos = [
| Workflow | Purpose | Auto Chain | Output Folder | | Workflow | Purpose | Auto Chain | Output Folder |
|----------|---------|------------|---------------| |----------|---------|------------|---------------|
| **brainstorm-with-file** | Multi-perspective ideation | → workflow-lite-plan (auto) | `.workflow/.brainstorm/` | | **brainstorm-with-file** | Multi-perspective ideation | → workflow-plan → workflow-execute (auto) | `.workflow/.brainstorm/` |
| **debug-with-file** | Hypothesis-driven debugging | Standalone (self-contained) | `.workflow/.debug/` | | **debug-with-file** | Hypothesis-driven debugging | Standalone (self-contained) | `.workflow/.debug/` |
| **analyze-with-file** | Collaborative analysis | → workflow-lite-plan (auto) | `.workflow/.analysis/` | | **analyze-with-file** | Collaborative analysis | → workflow-lite-planex (auto) | `.workflow/.analysis/` |
| **collaborative-plan-with-file** | Multi-agent collaborative planning | → unified-execute-with-file | `.workflow/.planning/` | | **collaborative-plan-with-file** | Multi-agent collaborative planning | → unified-execute-with-file | `.workflow/.planning/` |
| **roadmap-with-file** | Strategic requirement roadmap | → team-planex | `.workflow/.planning/` | | **roadmap-with-file** | Strategic requirement roadmap | → team-planex | `.workflow/.planning/` |
**Auto Chain Mechanism**: When `analyze-with-file` or `brainstorm-with-file` completes, its artifacts (discussion.md / brainstorm.md) are automatically passed to `workflow-lite-plan` as context input. No user intervention needed. **Auto Chain Mechanism**: When `analyze-with-file` completes, its artifacts (discussion.md) are automatically passed to `workflow-lite-planex`. When `brainstorm-with-file` completes, its artifacts (brainstorm.md) are passed to `workflow-plan` for formal planning. No user intervention needed.
**Detection Keywords**: **Detection Keywords**:
- **brainstorm**: 头脑风暴, 创意, 发散思维, multi-perspective, compare perspectives - **brainstorm**: 头脑风暴, 创意, 发散思维, multi-perspective, compare perspectives
@@ -752,9 +787,14 @@ todos = [
# Multi-CLI collaborative planning # Multi-CLI collaborative planning
/ccw "multi-cli plan: 支付网关API设计" # → workflow-multi-cli-plan → workflow-test-fix /ccw "multi-cli plan: 支付网关API设计" # → workflow-multi-cli-plan → workflow-test-fix
# With-File workflows → auto chain to lite-plan # 0→1 Greenfield development (exploration-first)
/ccw "协作分析: 理解现有认证架构的设计决策" # → analyze-with-file → workflow-lite-plan /ccw "从零开始: 用户认证系统" # → brainstorm-with-file → workflow-plan → workflow-execute → workflow-test-fix
/ccw "头脑风暴: 用户通知系统重新设计" # → brainstorm-with-file → workflow-lite-plan /ccw "new project: 数据导出模块" # → brainstorm-with-file → workflow-plan → workflow-execute → workflow-test-fix
/ccw "全新开发: 实时通知系统" # → brainstorm-with-file → workflow-plan → workflow-execute → review-cycle → workflow-test-fix
# With-File workflows → auto chain
/ccw "协作分析: 理解现有认证架构的设计决策" # → analyze-with-file → workflow-lite-planex
/ccw "头脑风暴: 用户通知系统重新设计" # → brainstorm-with-file → workflow-plan → workflow-execute → workflow-test-fix
/ccw "深度调试: 系统随机崩溃问题" # → debug-with-file (standalone) /ccw "深度调试: 系统随机崩溃问题" # → debug-with-file (standalone)
/ccw "从头脑风暴 BS-通知系统-2025-01-28 创建 issue" # → brainstorm-to-issue (bridge) /ccw "从头脑风暴 BS-通知系统-2025-01-28 创建 issue" # → brainstorm-to-issue (bridge)
@@ -763,8 +803,8 @@ todos = [
# Collaborative planning & requirement workflows # Collaborative planning & requirement workflows
/ccw "协作规划: 实时通知系统架构" # → collaborative-plan-with-file → unified-execute /ccw "协作规划: 实时通知系统架构" # → collaborative-plan-with-file → unified-execute
/ccw "需求路线图: 用户认证 OAuth + 2FA" # → roadmap-with-file → team-planex /ccw "roadmap: 用户认证 OAuth + 2FA 路线图" # → roadmap-with-file → team-planex (explicit roadmap only)
/ccw "roadmap: 数据导出功能路线图" # → roadmap-with-file → team-planex /ccw "roadmap: 数据导出功能路线图" # → roadmap-with-file → team-planex (explicit roadmap only)
# Team workflows (kept: team-planex) # Team workflows (kept: team-planex)
/ccw "team planex: 用户认证系统" # → team-planex (planner + executor wave pipeline) /ccw "team planex: 用户认证系统" # → team-planex (planner + executor wave pipeline)

View File

@@ -378,7 +378,7 @@ docker-compose.override.yml
## Integration Points ## Integration Points
### Workflow Commands ### Workflow Commands
- **After `workflow-lite-plan` skill**: Suggest running cli-init for better analysis - **After `workflow-lite-planex` skill**: Suggest running cli-init for better analysis
- **Before analysis**: Recommend updating ignore patterns for cleaner results - **Before analysis**: Recommend updating ignore patterns for cleaner results
### CLI Tool Integration ### CLI Tool Integration

View File

@@ -86,7 +86,7 @@ async function selectCommandCategory() {
header: "Category", header: "Category",
options: [ options: [
{ label: "Planning", description: "lite-plan, plan, multi-cli-plan, tdd-plan, quick-plan-with-file" }, { label: "Planning", description: "lite-plan, plan, multi-cli-plan, tdd-plan, quick-plan-with-file" },
{ label: "Execution", description: "lite-execute, execute, unified-execute-with-file" }, { label: "Execution", description: "execute, unified-execute-with-file" },
{ label: "Testing", description: "test-fix-gen, test-cycle-execute, test-gen, tdd-verify" }, { label: "Testing", description: "test-fix-gen, test-cycle-execute, test-gen, tdd-verify" },
{ label: "Review", description: "review-session-cycle, review-module-cycle, review-cycle-fix" }, { label: "Review", description: "review-session-cycle, review-module-cycle, review-cycle-fix" },
{ label: "Bug Fix", description: "lite-plan --bugfix, debug-with-file" }, { label: "Bug Fix", description: "lite-plan --bugfix, debug-with-file" },
@@ -107,7 +107,7 @@ async function selectCommandCategory() {
async function selectCommand(category) { async function selectCommand(category) {
const commandOptions = { const commandOptions = {
'Planning': [ 'Planning': [
{ label: "/workflow-lite-plan", description: "Lightweight merged-mode planning" }, { label: "/workflow-lite-planex", description: "Lightweight merged-mode planning" },
{ label: "/workflow-plan", description: "Full planning with architecture design" }, { label: "/workflow-plan", description: "Full planning with architecture design" },
{ label: "/workflow-multi-cli-plan", description: "Multi-CLI collaborative planning (Gemini+Codex+Claude)" }, { label: "/workflow-multi-cli-plan", description: "Multi-CLI collaborative planning (Gemini+Codex+Claude)" },
{ label: "/workflow-tdd-plan", description: "TDD workflow planning with Red-Green-Refactor" }, { label: "/workflow-tdd-plan", description: "TDD workflow planning with Red-Green-Refactor" },
@@ -116,7 +116,6 @@ async function selectCommand(category) {
{ label: "/workflow:replan", description: "Update plan and execute changes" } { label: "/workflow:replan", description: "Update plan and execute changes" }
], ],
'Execution': [ 'Execution': [
{ label: "/workflow:lite-execute", description: "Execute from in-memory plan" },
{ label: "/workflow-execute", description: "Execute from planning session" }, { label: "/workflow-execute", description: "Execute from planning session" },
{ label: "/workflow:unified-execute-with-file", description: "Universal execution engine" } { label: "/workflow:unified-execute-with-file", description: "Universal execution engine" }
], ],
@@ -133,7 +132,7 @@ async function selectCommand(category) {
{ label: "/workflow:review", description: "Post-implementation review" } { label: "/workflow:review", description: "Post-implementation review" }
], ],
'Bug Fix': [ 'Bug Fix': [
{ label: "/workflow-lite-plan", description: "Lightweight bug diagnosis and fix (with --bugfix flag)" }, { label: "/workflow-lite-planex", description: "Lightweight bug diagnosis and fix (with --bugfix flag)" },
{ label: "/workflow:debug-with-file", description: "Hypothesis-driven debugging with documentation" } { label: "/workflow:debug-with-file", description: "Hypothesis-driven debugging with documentation" }
], ],
'Brainstorm': [ 'Brainstorm': [
@@ -181,8 +180,8 @@ async function selectExecutionUnit() {
header: "Unit", header: "Unit",
options: [ options: [
// Planning + Execution Units // Planning + Execution Units
{ label: "quick-implementation", description: "【lite-plan → lite-execute】" }, { label: "quick-implementation", description: "【lite-plan】" },
{ label: "multi-cli-planning", description: "【multi-cli-plan → lite-execute】" }, { label: "multi-cli-planning", description: "【multi-cli-plan】" },
{ label: "full-planning-execution", description: "【plan → execute】" }, { label: "full-planning-execution", description: "【plan → execute】" },
{ label: "verified-planning-execution", description: "【plan → plan-verify → execute】" }, { label: "verified-planning-execution", description: "【plan → plan-verify → execute】" },
{ label: "replanning-execution", description: "【replan → execute】" }, { label: "replanning-execution", description: "【replan → execute】" },
@@ -193,7 +192,7 @@ async function selectExecutionUnit() {
// Review Units // Review Units
{ label: "code-review", description: "【review-*-cycle → review-cycle-fix】" }, { label: "code-review", description: "【review-*-cycle → review-cycle-fix】" },
// Bug Fix Units // Bug Fix Units
{ label: "bug-fix", description: "【lite-plan --bugfix → lite-execute】" }, { label: "bug-fix", description: "【lite-plan --bugfix】" },
// Issue Units // Issue Units
{ label: "issue-workflow", description: "【discover → plan → queue → execute】" }, { label: "issue-workflow", description: "【discover → plan → queue → execute】" },
{ label: "rapid-to-issue", description: "【lite-plan → convert-to-plan → queue → execute】" }, { label: "rapid-to-issue", description: "【lite-plan → convert-to-plan → queue → execute】" },
@@ -303,8 +302,7 @@ async function defineSteps(templateDesign) {
"description": "Quick implementation with testing", "description": "Quick implementation with testing",
"level": 2, "level": 2,
"steps": [ "steps": [
{ "cmd": "/workflow-lite-plan", "args": "\"{{goal}}\"", "unit": "quick-implementation", "execution": { "type": "slash-command", "mode": "mainprocess" }, "contextHint": "Create lightweight implementation plan" }, { "cmd": "/workflow-lite-planex", "args": "\"{{goal}}\"", "unit": "quick-implementation", "execution": { "type": "slash-command", "mode": "mainprocess" }, "contextHint": "Create lightweight implementation plan (includes execution)" },
{ "cmd": "/workflow:lite-execute", "args": "--in-memory", "unit": "quick-implementation", "execution": { "type": "slash-command", "mode": "mainprocess" }, "contextHint": "Execute implementation based on plan" },
{ "cmd": "/workflow-test-fix", "unit": "test-validation", "execution": { "type": "slash-command", "mode": "mainprocess" }, "contextHint": "Generate test tasks" }, { "cmd": "/workflow-test-fix", "unit": "test-validation", "execution": { "type": "slash-command", "mode": "mainprocess" }, "contextHint": "Generate test tasks" },
{ "cmd": "/workflow-test-fix", "unit": "test-validation", "execution": { "type": "slash-command", "mode": "async" }, "contextHint": "Execute test-fix cycle until pass rate >= 95%" } { "cmd": "/workflow-test-fix", "unit": "test-validation", "execution": { "type": "slash-command", "mode": "async" }, "contextHint": "Execute test-fix cycle until pass rate >= 95%" }
] ]
@@ -336,8 +334,7 @@ async function defineSteps(templateDesign) {
"description": "Bug diagnosis and fix with testing", "description": "Bug diagnosis and fix with testing",
"level": 2, "level": 2,
"steps": [ "steps": [
{ "cmd": "/workflow-lite-plan", "args": "--bugfix \"{{goal}}\"", "unit": "bug-fix", "execution": { "type": "slash-command", "mode": "mainprocess" }, "contextHint": "Diagnose and plan bug fix" }, { "cmd": "/workflow-lite-planex", "args": "--bugfix \"{{goal}}\"", "unit": "bug-fix", "execution": { "type": "slash-command", "mode": "mainprocess" }, "contextHint": "Diagnose, plan, and execute bug fix" },
{ "cmd": "/workflow:lite-execute", "args": "--in-memory", "unit": "bug-fix", "execution": { "type": "slash-command", "mode": "mainprocess" }, "contextHint": "Execute bug fix" },
{ "cmd": "/workflow-test-fix", "unit": "test-validation", "execution": { "type": "slash-command", "mode": "mainprocess" }, "contextHint": "Generate regression tests" }, { "cmd": "/workflow-test-fix", "unit": "test-validation", "execution": { "type": "slash-command", "mode": "mainprocess" }, "contextHint": "Generate regression tests" },
{ "cmd": "/workflow-test-fix", "unit": "test-validation", "execution": { "type": "slash-command", "mode": "async" }, "contextHint": "Verify fix with tests" } { "cmd": "/workflow-test-fix", "unit": "test-validation", "execution": { "type": "slash-command", "mode": "async" }, "contextHint": "Verify fix with tests" }
] ]
@@ -351,7 +348,7 @@ async function defineSteps(templateDesign) {
"description": "Urgent production bug fix (no tests)", "description": "Urgent production bug fix (no tests)",
"level": 2, "level": 2,
"steps": [ "steps": [
{ "cmd": "/workflow-lite-plan", "args": "--hotfix \"{{goal}}\"", "unit": "standalone", "execution": { "type": "slash-command", "mode": "mainprocess" }, "contextHint": "Emergency hotfix mode" } { "cmd": "/workflow-lite-planex", "args": "--hotfix \"{{goal}}\"", "unit": "standalone", "execution": { "type": "slash-command", "mode": "mainprocess" }, "contextHint": "Emergency hotfix mode" }
] ]
} }
``` ```
@@ -420,7 +417,7 @@ async function defineSteps(templateDesign) {
"description": "Bridge lightweight planning to issue workflow", "description": "Bridge lightweight planning to issue workflow",
"level": 2, "level": 2,
"steps": [ "steps": [
{ "cmd": "/workflow-lite-plan", "args": "\"{{goal}}\"", "unit": "rapid-to-issue", "execution": { "type": "slash-command", "mode": "mainprocess" }, "contextHint": "Create lightweight plan" }, { "cmd": "/workflow-lite-planex", "args": "\"{{goal}}\"", "unit": "rapid-to-issue", "execution": { "type": "slash-command", "mode": "mainprocess" }, "contextHint": "Create lightweight plan" },
{ "cmd": "/issue:convert-to-plan", "args": "--latest-lite-plan -y", "unit": "rapid-to-issue", "execution": { "type": "slash-command", "mode": "mainprocess" }, "contextHint": "Convert to issue plan" }, { "cmd": "/issue:convert-to-plan", "args": "--latest-lite-plan -y", "unit": "rapid-to-issue", "execution": { "type": "slash-command", "mode": "mainprocess" }, "contextHint": "Convert to issue plan" },
{ "cmd": "/issue:queue", "unit": "rapid-to-issue", "execution": { "type": "slash-command", "mode": "mainprocess" }, "contextHint": "Form execution queue" }, { "cmd": "/issue:queue", "unit": "rapid-to-issue", "execution": { "type": "slash-command", "mode": "mainprocess" }, "contextHint": "Form execution queue" },
{ "cmd": "/issue:execute", "args": "--queue auto", "unit": "rapid-to-issue", "execution": { "type": "slash-command", "mode": "async" }, "contextHint": "Execute issue queue" } { "cmd": "/issue:execute", "args": "--queue auto", "unit": "rapid-to-issue", "execution": { "type": "slash-command", "mode": "async" }, "contextHint": "Execute issue queue" }
@@ -503,7 +500,7 @@ async function defineSteps(templateDesign) {
"level": 3, "level": 3,
"steps": [ "steps": [
{ "cmd": "/workflow-multi-cli-plan", "args": "\"{{goal}}\"", "unit": "multi-cli-planning", "execution": { "type": "slash-command", "mode": "mainprocess" }, "contextHint": "Gemini+Codex+Claude collaborative planning" }, { "cmd": "/workflow-multi-cli-plan", "args": "\"{{goal}}\"", "unit": "multi-cli-planning", "execution": { "type": "slash-command", "mode": "mainprocess" }, "contextHint": "Gemini+Codex+Claude collaborative planning" },
{ "cmd": "/workflow:lite-execute", "args": "--in-memory", "unit": "multi-cli-planning", "execution": { "type": "slash-command", "mode": "mainprocess" }, "contextHint": "Execute converged plan" }, // lite-execute is now an internal phase of multi-cli-plan (not invoked separately)
{ "cmd": "/workflow-test-fix", "unit": "test-validation", "execution": { "type": "slash-command", "mode": "mainprocess" }, "contextHint": "Generate tests" }, { "cmd": "/workflow-test-fix", "unit": "test-validation", "execution": { "type": "slash-command", "mode": "mainprocess" }, "contextHint": "Generate tests" },
{ "cmd": "/workflow-test-fix", "unit": "test-validation", "execution": { "type": "slash-command", "mode": "async" }, "contextHint": "Execute test cycle" } { "cmd": "/workflow-test-fix", "unit": "test-validation", "execution": { "type": "slash-command", "mode": "async" }, "contextHint": "Execute test cycle" }
] ]
@@ -530,7 +527,7 @@ Each command has input/output ports for pipeline composition:
| tdd-plan | requirement | tdd-tasks | tdd-planning-execution | | tdd-plan | requirement | tdd-tasks | tdd-planning-execution |
| replan | session, feedback | replan | replanning-execution | | replan | session, feedback | replan | replanning-execution |
| **Execution** | | **Execution** |
| lite-execute | plan, multi-cli-plan | code | (multiple) | | ~~lite-execute~~ | _(internal phase of lite-plan/multi-cli-plan, not standalone)_ | code | — |
| execute | detailed-plan, verified-plan, replan, tdd-tasks | code | (multiple) | | execute | detailed-plan, verified-plan, replan, tdd-tasks | code | (multiple) |
| **Testing** | | **Testing** |
| test-fix-gen | failing-tests, session | test-tasks | test-validation | | test-fix-gen | failing-tests, session | test-tasks | test-validation |
@@ -563,9 +560,9 @@ Each command has input/output ports for pipeline composition:
| Unit Name | Commands | Purpose | | Unit Name | Commands | Purpose |
|-----------|----------|---------| |-----------|----------|---------|
| **quick-implementation** | lite-plan → lite-execute | Lightweight plan and execution | | **quick-implementation** | lite-plan (Phase 1: plan → Phase 2: execute) | Lightweight plan and execution |
| **multi-cli-planning** | multi-cli-plan → lite-execute | Multi-perspective planning and execution | | **multi-cli-planning** | multi-cli-plan (Phase 1: plan → Phase 2: execute) | Multi-perspective planning and execution |
| **bug-fix** | lite-plan --bugfix → lite-execute | Bug diagnosis and fix | | **bug-fix** | lite-plan --bugfix (Phase 1: plan → Phase 2: execute) | Bug diagnosis and fix |
| **full-planning-execution** | plan → execute | Detailed planning and execution | | **full-planning-execution** | plan → execute | Detailed planning and execution |
| **verified-planning-execution** | plan → plan-verify → execute | Planning with verification | | **verified-planning-execution** | plan → plan-verify → execute | Planning with verification |
| **replanning-execution** | replan → execute | Update plan and execute | | **replanning-execution** | replan → execute | Update plan and execute |

View File

@@ -15,16 +15,16 @@ When `--yes` or `-y`: Auto-skip interrupted task, continue with remaining.
```javascript ```javascript
const SKILL_CHAIN_MAP = { const SKILL_CHAIN_MAP = {
'bugfix': ['workflow-lite-plan', 'workflow-test-fix'], 'bugfix': ['workflow-lite-planex', 'workflow-test-fix'],
'bugfix-hotfix': ['workflow-lite-plan'], 'bugfix-hotfix': ['workflow-lite-planex'],
'feature': ['workflow-lite-plan', 'workflow-test-fix'], 'feature': ['workflow-lite-planex', 'workflow-test-fix'],
'feature-complex': ['workflow-plan', 'workflow-execute', 'workflow-test-fix'], 'feature-complex': ['workflow-plan', 'workflow-execute', 'workflow-test-fix'],
'refactor': ['workflow:refactor-cycle'], 'refactor': ['workflow:refactor-cycle'],
'tdd': ['workflow-tdd-plan', 'workflow-execute'], 'tdd': ['workflow-tdd-plan', 'workflow-execute'],
'test': ['workflow-test-fix'], 'test': ['workflow-test-fix'],
'test-fix': ['workflow-test-fix'], 'test-fix': ['workflow-test-fix'],
'review': ['review-cycle'], 'review': ['review-cycle'],
'docs': ['workflow-lite-plan'] 'docs': ['workflow-lite-planex']
}; };
``` ```

View File

@@ -2,7 +2,7 @@
name: run-coordinate name: run-coordinate
description: IDAW coordinator - execute task skill chains via external CLI with hook callbacks and git checkpoints description: IDAW coordinator - execute task skill chains via external CLI with hook callbacks and git checkpoints
argument-hint: "[-y|--yes] [--task <id>[,<id>,...]] [--dry-run] [--tool <tool>]" argument-hint: "[-y|--yes] [--task <id>[,<id>,...]] [--dry-run] [--tool <tool>]"
allowed-tools: Task(*), AskUserQuestion(*), Read(*), Write(*), Bash(*), Glob(*), Grep(*) allowed-tools: Agent(*), AskUserQuestion(*), Read(*), Write(*), Bash(*), Glob(*), Grep(*)
--- ---
# IDAW Run Coordinate Command (/idaw:run-coordinate) # IDAW Run Coordinate Command (/idaw:run-coordinate)
@@ -26,16 +26,16 @@ Coordinator variant of `/idaw:run`: external CLI execution with background tasks
```javascript ```javascript
const SKILL_CHAIN_MAP = { const SKILL_CHAIN_MAP = {
'bugfix': ['workflow-lite-plan', 'workflow-test-fix'], 'bugfix': ['workflow-lite-planex', 'workflow-test-fix'],
'bugfix-hotfix': ['workflow-lite-plan'], 'bugfix-hotfix': ['workflow-lite-planex'],
'feature': ['workflow-lite-plan', 'workflow-test-fix'], 'feature': ['workflow-lite-planex', 'workflow-test-fix'],
'feature-complex': ['workflow-plan', 'workflow-execute', 'workflow-test-fix'], 'feature-complex': ['workflow-plan', 'workflow-execute', 'workflow-test-fix'],
'refactor': ['workflow:refactor-cycle'], 'refactor': ['workflow:refactor-cycle'],
'tdd': ['workflow-tdd-plan', 'workflow-execute'], 'tdd': ['workflow-tdd-plan', 'workflow-execute'],
'test': ['workflow-test-fix'], 'test': ['workflow-test-fix'],
'test-fix': ['workflow-test-fix'], 'test-fix': ['workflow-test-fix'],
'review': ['review-cycle'], 'review': ['review-cycle'],
'docs': ['workflow-lite-plan'] 'docs': ['workflow-lite-planex']
}; };
``` ```
@@ -216,7 +216,7 @@ const chain = firstTask.skill_chain || SKILL_CHAIN_MAP[resolvedType] || SKILL_CH
firstTask.status = 'in_progress'; firstTask.status = 'in_progress';
firstTask.task_type = resolvedType; firstTask.task_type = resolvedType;
firstTask.execution.started_at = new Date().toISOString(); firstTask.execution.started_at = new Date().toISOString();
Write(`.workflow/.idaw/tasks/${firstTask.id}.json`, JSON.stringify(firstTask, null, 2)); Write(`.workflow/.idaw/tasks/${firstTask.id}.json`, JSON.stringify(firstAgent, null, 2));
// Update session // Update session
session.current_task = firstTask.id; session.current_task = firstTask.id;
@@ -239,7 +239,7 @@ CONSTRAINTS: Keep concise`;
// Assemble prompt for first skill // Assemble prompt for first skill
const skillName = chain[0]; const skillName = chain[0];
const prompt = assembleCliPrompt(skillName, firstTask, null, autoYes); const prompt = assembleCliPrompt(skillName, firstAgent, null, autoYes);
session.prompts_used.push({ session.prompts_used.push({
task_id: firstTask.id, task_id: firstTask.id,
@@ -403,7 +403,7 @@ CONSTRAINTS: Actionable diagnosis`;
nextTask.status = 'in_progress'; nextTask.status = 'in_progress';
nextTask.task_type = nextType; nextTask.task_type = nextType;
nextTask.execution.started_at = new Date().toISOString(); nextTask.execution.started_at = new Date().toISOString();
Write(`.workflow/.idaw/tasks/${nextTaskId}.json`, JSON.stringify(nextTask, null, 2)); Write(`.workflow/.idaw/tasks/${nextTaskId}.json`, JSON.stringify(nextAgent, null, 2));
session.current_task = nextTaskId; session.current_task = nextTaskId;
session.current_skill_index = 0; session.current_skill_index = 0;
@@ -417,7 +417,7 @@ CONSTRAINTS: Actionable diagnosis`;
} }
const nextSkillName = nextChain[0]; const nextSkillName = nextChain[0];
const nextPrompt = assembleCliPrompt(nextSkillName, nextTask, null, true); const nextPrompt = assembleCliPrompt(nextSkillName, nextAgent, null, true);
session.prompts_used.push({ session.prompts_used.push({
task_id: nextTaskId, task_id: nextTaskId,
@@ -472,11 +472,11 @@ function assembleCliPrompt(skillName, task, previousResult, autoYes) {
const yFlag = autoYes ? ' -y' : ''; const yFlag = autoYes ? ' -y' : '';
// Map skill to command invocation // Map skill to command invocation
if (skillName === 'workflow-lite-plan') { if (skillName === 'workflow-lite-planex') {
const goal = sanitize(`${task.title}\n${task.description}`); const goal = sanitize(`${task.title}\n${task.description}`);
prompt = `/workflow-lite-plan${yFlag} "${goal}"`; prompt = `/workflow-lite-planex${yFlag} "${goal}"`;
if (task.task_type === 'bugfix') prompt = `/workflow-lite-plan${yFlag} --bugfix "${goal}"`; if (task.task_type === 'bugfix') prompt = `/workflow-lite-planex${yFlag} --bugfix "${goal}"`;
if (task.task_type === 'bugfix-hotfix') prompt = `/workflow-lite-plan${yFlag} --hotfix "${goal}"`; if (task.task_type === 'bugfix-hotfix') prompt = `/workflow-lite-planex${yFlag} --hotfix "${goal}"`;
} else if (skillName === 'workflow-plan') { } else if (skillName === 'workflow-plan') {
prompt = `/workflow-plan${yFlag} "${sanitize(task.title)}"`; prompt = `/workflow-plan${yFlag} "${sanitize(task.title)}"`;
@@ -608,8 +608,8 @@ Phase 5: handleStepCompletion()
{ {
"task_id": "IDAW-001", "task_id": "IDAW-001",
"skill_index": 0, "skill_index": 0,
"skill": "workflow-lite-plan", "skill": "workflow-lite-planex",
"prompt": "/workflow-lite-plan -y \"Fix login timeout\"", "prompt": "/workflow-lite-planex -y \"Fix login timeout\"",
"timestamp": "ISO" "timestamp": "ISO"
} }
] ]

View File

@@ -15,16 +15,16 @@ When `--yes` or `-y`: Skip all confirmations, auto-skip on failure, proceed with
```javascript ```javascript
const SKILL_CHAIN_MAP = { const SKILL_CHAIN_MAP = {
'bugfix': ['workflow-lite-plan', 'workflow-test-fix'], 'bugfix': ['workflow-lite-planex', 'workflow-test-fix'],
'bugfix-hotfix': ['workflow-lite-plan'], 'bugfix-hotfix': ['workflow-lite-planex'],
'feature': ['workflow-lite-plan', 'workflow-test-fix'], 'feature': ['workflow-lite-planex', 'workflow-test-fix'],
'feature-complex': ['workflow-plan', 'workflow-execute', 'workflow-test-fix'], 'feature-complex': ['workflow-plan', 'workflow-execute', 'workflow-test-fix'],
'refactor': ['workflow:refactor-cycle'], 'refactor': ['workflow:refactor-cycle'],
'tdd': ['workflow-tdd-plan', 'workflow-execute'], 'tdd': ['workflow-tdd-plan', 'workflow-execute'],
'test': ['workflow-test-fix'], 'test': ['workflow-test-fix'],
'test-fix': ['workflow-test-fix'], 'test-fix': ['workflow-test-fix'],
'review': ['review-cycle'], 'review': ['review-cycle'],
'docs': ['workflow-lite-plan'] 'docs': ['workflow-lite-planex']
}; };
``` ```

View File

@@ -2,7 +2,7 @@
name: issue:discover-by-prompt name: issue:discover-by-prompt
description: Discover issues from user prompt with Gemini-planned iterative multi-agent exploration. Uses ACE semantic search for context gathering and supports cross-module comparison (e.g., frontend vs backend API contracts). description: Discover issues from user prompt with Gemini-planned iterative multi-agent exploration. Uses ACE semantic search for context gathering and supports cross-module comparison (e.g., frontend vs backend API contracts).
argument-hint: "[-y|--yes] <prompt> [--scope=src/**] [--depth=standard|deep] [--max-iterations=5]" argument-hint: "[-y|--yes] <prompt> [--scope=src/**] [--depth=standard|deep] [--max-iterations=5]"
allowed-tools: Skill(*), TodoWrite(*), Read(*), Bash(*), Task(*), AskUserQuestion(*), Glob(*), Grep(*), mcp__ace-tool__search_context(*), mcp__exa__search(*) allowed-tools: Skill(*), TodoWrite(*), Read(*), Bash(*), Agent(*), AskUserQuestion(*), Glob(*), Grep(*), mcp__ace-tool__search_context(*), mcp__exa__search(*)
--- ---
## Auto Mode ## Auto Mode
@@ -404,7 +404,7 @@ while (shouldContinue && iteration < maxIterations) {
// Step 3: Launch dimension agents with ACE context // Step 3: Launch dimension agents with ACE context
const agentPromises = iterationPlan.dimensions.map(dimension => const agentPromises = iterationPlan.dimensions.map(dimension =>
Task({ Agent({
subagent_type: "cli-explore-agent", subagent_type: "cli-explore-agent",
run_in_background: false, run_in_background: false,
description: `Explore ${dimension.name} (iteration ${iteration})`, description: `Explore ${dimension.name} (iteration ${iteration})`,

View File

@@ -2,7 +2,7 @@
name: issue:discover name: issue:discover
description: Discover potential issues from multiple perspectives (bug, UX, test, quality, security, performance, maintainability, best-practices) using CLI explore. Supports Exa external research for security and best-practices perspectives. description: Discover potential issues from multiple perspectives (bug, UX, test, quality, security, performance, maintainability, best-practices) using CLI explore. Supports Exa external research for security and best-practices perspectives.
argument-hint: "[-y|--yes] <path-pattern> [--perspectives=bug,ux,...] [--external]" argument-hint: "[-y|--yes] <path-pattern> [--perspectives=bug,ux,...] [--external]"
allowed-tools: Skill(*), TodoWrite(*), Read(*), Bash(*), Task(*), AskUserQuestion(*), Glob(*), Grep(*) allowed-tools: Skill(*), TodoWrite(*), Read(*), Bash(*), Agent(*), AskUserQuestion(*), Glob(*), Grep(*)
--- ---
## Auto Mode ## Auto Mode
@@ -185,7 +185,7 @@ Launch N agents in parallel (one per selected perspective):
```javascript ```javascript
// Launch agents in parallel - agents write JSON and return summary // Launch agents in parallel - agents write JSON and return summary
const agentPromises = selectedPerspectives.map(perspective => const agentPromises = selectedPerspectives.map(perspective =>
Task({ Agent({
subagent_type: "cli-explore-agent", subagent_type: "cli-explore-agent",
run_in_background: false, run_in_background: false,
description: `Discover ${perspective} issues`, description: `Discover ${perspective} issues`,
@@ -322,7 +322,7 @@ if (response === "Export to Issues") {
**Perspective Analysis Agent**: **Perspective Analysis Agent**:
```javascript ```javascript
Task({ Agent({
subagent_type: "cli-explore-agent", subagent_type: "cli-explore-agent",
run_in_background: false, run_in_background: false,
description: `Discover ${perspective} issues`, description: `Discover ${perspective} issues`,
@@ -368,7 +368,7 @@ Task({
**Exa Research Agent** (for security and best-practices): **Exa Research Agent** (for security and best-practices):
```javascript ```javascript
Task({ Agent({
subagent_type: "cli-explore-agent", subagent_type: "cli-explore-agent",
run_in_background: false, run_in_background: false,
description: `External research for ${perspective} via Exa`, description: `External research for ${perspective} via Exa`,

View File

@@ -429,7 +429,7 @@ On failure, run:
{ timeout: 3600000, run_in_background: true } { timeout: 3600000, run_in_background: true }
); );
} else { } else {
return Task({ return Agent({
subagent_type: 'code-developer', subagent_type: 'code-developer',
run_in_background: false, run_in_background: false,
description: `Execute solution ${solutionId}`, description: `Execute solution ${solutionId}`,

View File

@@ -2,7 +2,7 @@
name: plan name: plan
description: Batch plan issue resolution using issue-plan-agent (explore + plan closed-loop) description: Batch plan issue resolution using issue-plan-agent (explore + plan closed-loop)
argument-hint: "[-y|--yes] --all-pending <issue-id>[,<issue-id>,...] [--batch-size 3]" argument-hint: "[-y|--yes] --all-pending <issue-id>[,<issue-id>,...] [--batch-size 3]"
allowed-tools: TodoWrite(*), Task(*), Skill(*), AskUserQuestion(*), Bash(*), Read(*), Write(*) allowed-tools: TodoWrite(*), Agent(*), Skill(*), AskUserQuestion(*), Bash(*), Read(*), Write(*)
--- ---
## Auto Mode ## Auto Mode
@@ -222,7 +222,7 @@ for (let i = 0; i < agentTasks.length; i += MAX_PARALLEL) {
// Collect results from this chunk // Collect results from this chunk
for (const { taskId, batchIndex } of taskIds) { for (const { taskId, batchIndex } of taskIds) {
const result = TaskOutput(task_id=taskId, block=true); const result = TaskOutput({ task_id: taskId, block: true });
// Extract JSON from potential markdown code blocks (agent may wrap in ```json...```) // Extract JSON from potential markdown code blocks (agent may wrap in ```json...```)
const jsonText = extractJsonFromMarkdown(result); const jsonText = extractJsonFromMarkdown(result);

View File

@@ -2,7 +2,7 @@
name: queue name: queue
description: Form execution queue from bound solutions using issue-queue-agent (solution-level) description: Form execution queue from bound solutions using issue-queue-agent (solution-level)
argument-hint: "[-y|--yes] [--queues <n>] [--issue <id>]" argument-hint: "[-y|--yes] [--queues <n>] [--issue <id>]"
allowed-tools: TodoWrite(*), Task(*), Bash(*), Read(*), Write(*) allowed-tools: TodoWrite(*), Agent(*), Bash(*), Read(*), Write(*)
--- ---
## Auto Mode ## Auto Mode
@@ -247,7 +247,7 @@ if (numQueues === 1) {
description=`Queue ${i + 1}/${numQueues}: ${group.length} solutions` description=`Queue ${i + 1}/${numQueues}: ${group.length} solutions`
) )
); );
// All agents launched in parallel via single message with multiple Task tool calls // All agents launched in parallel via single message with multiple Agent tool calls
} }
``` ```

View File

@@ -2,7 +2,7 @@
name: prepare name: prepare
description: Delegate to universal-executor agent to analyze project via Gemini/Qwen CLI and return JSON core content package for task context description: Delegate to universal-executor agent to analyze project via Gemini/Qwen CLI and return JSON core content package for task context
argument-hint: "[--tool gemini|qwen] \"task context description\"" argument-hint: "[--tool gemini|qwen] \"task context description\""
allowed-tools: Task(*), Bash(*) allowed-tools: Agent(*), Bash(*)
examples: examples:
- /memory:prepare "在当前前端基础上开发用户认证功能" - /memory:prepare "在当前前端基础上开发用户认证功能"
- /memory:prepare --tool qwen "重构支付模块API" - /memory:prepare --tool qwen "重构支付模块API"

View File

@@ -2,7 +2,7 @@
name: analyze-with-file name: analyze-with-file
description: Interactive collaborative analysis with documented discussions, CLI-assisted exploration, and evolving understanding description: Interactive collaborative analysis with documented discussions, CLI-assisted exploration, and evolving understanding
argument-hint: "[-y|--yes] [-c|--continue] \"topic or question\"" argument-hint: "[-y|--yes] [-c|--continue] \"topic or question\""
allowed-tools: TodoWrite(*), Task(*), AskUserQuestion(*), Read(*), Grep(*), Glob(*), Bash(*), Edit(*), Write(*) allowed-tools: TodoWrite(*), Agent(*), AskUserQuestion(*), Read(*), Grep(*), Glob(*), Bash(*), Edit(*), Write(*)
--- ---
## Auto Mode ## Auto Mode
@@ -226,7 +226,7 @@ Interactive collaborative analysis workflow with **documented discussion process
**Single Exploration Example**: **Single Exploration Example**:
```javascript ```javascript
Task({ Agent({
subagent_type: "cli-explore-agent", subagent_type: "cli-explore-agent",
run_in_background: false, run_in_background: false,
description: `Explore codebase: ${topicSlug}`, description: `Explore codebase: ${topicSlug}`,
@@ -256,7 +256,7 @@ Schema: {relevant_files, patterns, key_findings, questions_for_user, _metadata}
```javascript ```javascript
// Launch parallel explorations for each selected perspective // Launch parallel explorations for each selected perspective
selectedPerspectives.forEach(perspective => { selectedPerspectives.forEach(perspective => {
Task({ Agent({
subagent_type: "cli-explore-agent", subagent_type: "cli-explore-agent",
run_in_background: false, // Sequential execution, wait for each run_in_background: false, // Sequential execution, wait for each
description: `Explore ${perspective.name}: ${topicSlug}`, description: `Explore ${perspective.name}: ${topicSlug}`,
@@ -399,7 +399,7 @@ CONSTRAINTS: ${perspective.constraints}
- explorations.json contains initial findings - explorations.json contains initial findings
- discussion.md has Round 1 results - discussion.md has Round 1 results
**Guideline**: For complex tasks (code analysis, implementation, refactoring), delegate to agents via Task tool (cli-explore-agent, code-developer, universal-executor) or CLI calls (ccw cli). Avoid direct analysis/execution in main process. **Guideline**: For complex tasks (code analysis, implementation, refactoring), delegate to agents via Agent tool (cli-explore-agent, code-developer, universal-executor) or CLI calls (ccw cli). Avoid direct analysis/execution in main process.
**Workflow Steps**: **Workflow Steps**:
@@ -526,7 +526,7 @@ CONSTRAINTS: ${perspective.constraints}
- **📌 Decision summary**: How key decisions shaped the final conclusions (link conclusions back to decisions) - **📌 Decision summary**: How key decisions shaped the final conclusions (link conclusions back to decisions)
- Write to conclusions.json - Write to conclusions.json
2. **Final discussion.md Update** 3. **Final discussion.md Update**
- Append conclusions section: - Append conclusions section:
- **Summary**: High-level overview - **Summary**: High-level overview
- **Key Conclusions**: Ranked with evidence and confidence - **Key Conclusions**: Ranked with evidence and confidence
@@ -542,29 +542,51 @@ CONSTRAINTS: ${perspective.constraints}
- **Trade-offs Made**: Key trade-offs and why certain paths were chosen over others - **Trade-offs Made**: Key trade-offs and why certain paths were chosen over others
- Add session statistics: rounds, duration, sources, artifacts, **decision count** - Add session statistics: rounds, duration, sources, artifacts, **decision count**
3. **Post-Completion Options** 4. **Display Conclusions Summary**
- Present analysis conclusions to the user before asking for next steps:
```javascript
console.log(`
## Analysis Report
**Summary**: ${conclusions.summary}
**Key Conclusions** (${conclusions.key_conclusions.length}):
${conclusions.key_conclusions.map((c, i) => `${i+1}. [${c.confidence}] ${c.point}`).join('\n')}
**Recommendations** (${conclusions.recommendations.length}):
${conclusions.recommendations.map((r, i) => `${i+1}. [${r.priority}] ${r.action} — ${r.rationale}`).join('\n')}
${conclusions.open_questions.length > 0 ? `\n**Open Questions**:\n${conclusions.open_questions.map(q => '- ' + q).join('\n')}` : ''}
📄 Full report: ${sessionFolder}/discussion.md
`)
```
5. **Post-Completion Options** (⚠️ TERMINAL — analyze-with-file ends after user selection)
> **WORKFLOW BOUNDARY**: After user selects any option below, the analyze-with-file workflow is **COMPLETE**.
> If "执行任务" is selected, workflow-lite-planex takes over exclusively — do NOT return to any analyze-with-file phase.
> The "Phase" numbers in workflow-lite-planex (LP-Phase 1-5) are SEPARATE from analyze-with-file phases.
```javascript ```javascript
const hasActionableRecs = conclusions.recommendations?.some(r => r.priority === 'high' || r.priority === 'medium') const hasActionableRecs = conclusions.recommendations?.some(r => r.priority === 'high' || r.priority === 'medium')
const nextStep = AskUserQuestion({ const nextStep = AskUserQuestion({
questions: [{ questions: [{
question: "Analysis complete. What's next?", question: "Report generated. What would you like to do next?",
header: "Next Step", header: "Next Step",
multiSelect: false, multiSelect: false,
options: [ options: [
{ label: hasActionableRecs ? "生成任务 (Recommended)" : "生成任务", description: "Launch workflow-lite-plan with analysis context" }, { label: hasActionableRecs ? "执行任务 (Recommended)" : "执行任务", description: "Launch workflow-lite-planex to plan & execute" },
{ label: "创建Issue", description: "Launch issue-discover with conclusions" }, { label: "产出Issue", description: "Launch issue-discover with conclusions" },
{ label: "导出报告", description: "Generate standalone analysis report" },
{ label: "完成", description: "No further action" } { label: "完成", description: "No further action" }
] ]
}] }]
}) })
``` ```
**Handle "生成任务"**: **Handle "执行任务"** (⚠️ TERMINAL — analyze-with-file ends here, lite-plan takes over exclusively):
```javascript ```javascript
if (nextStep.includes("生成任务")) { if (nextStep.includes("执行任务")) {
// 1. Build task description from high/medium priority recommendations // 1. Build task description from high/medium priority recommendations
const taskDescription = conclusions.recommendations const taskDescription = conclusions.recommendations
.filter(r => r.priority === 'high' || r.priority === 'medium') .filter(r => r.priority === 'high' || r.priority === 'medium')
@@ -585,8 +607,19 @@ CONSTRAINTS: ${perspective.constraints}
if (findings.length) contextLines.push(`**Key Findings**:\n${findings.map(f => `- ${f}`).join('\n')}`) if (findings.length) contextLines.push(`**Key Findings**:\n${findings.map(f => `- ${f}`).join('\n')}`)
} }
// 3. Call lite-plan with enriched task description (no special flags) // 3. ⛔ SESSION TERMINATION — output explicit boundary
Skill(skill="workflow-lite-plan", args=`"${taskDescription}\n\n${contextLines.join('\n')}"`) console.log(`
---
## ⛔ ANALYZE-WITH-FILE SESSION COMPLETE
All Phase 1-4 of analyze-with-file are FINISHED.
Session: ${sessionId} — concluded at ${new Date().toISOString()}
DO NOT reference any analyze-with-file phase instructions beyond this point.
---
`)
// 4. Hand off to lite-plan — analyze-with-file COMPLETE, do NOT return to any analyze phase
Skill(skill="workflow-lite-planex", args=`"${taskDescription}\n\n${contextLines.join('\n')}"`)
return // ⛔ analyze-with-file terminates here
} }
``` ```
@@ -706,7 +739,7 @@ In round 1 we discussed X, then in round 2 user said Y...
## Best Practices ## Best Practices
1. **Clear Topic Definition**: Detailed topics lead to better dimension identification 1. **Clear Topic Definition**: Detailed topics lead to better dimension identification
2. **Agent-First for Complex Tasks**: For code analysis, implementation, or refactoring tasks during discussion, delegate to agents via Task tool (cli-explore-agent, code-developer, universal-executor) or CLI calls (ccw cli). Avoid direct analysis/execution in main process 2. **Agent-First for Complex Tasks**: For code analysis, implementation, or refactoring tasks during discussion, delegate to agents via Agent tool (cli-explore-agent, code-developer, universal-executor) or CLI calls (ccw cli). Avoid direct analysis/execution in main process
3. **Review discussion.md**: Check understanding evolution before conclusions 3. **Review discussion.md**: Check understanding evolution before conclusions
4. **Embrace Corrections**: Track wrong-to-right transformations as learnings 4. **Embrace Corrections**: Track wrong-to-right transformations as learnings
5. **Document Evolution**: discussion.md captures full thinking process 5. **Document Evolution**: discussion.md captures full thinking process
@@ -764,12 +797,12 @@ User agrees with current direction, wants deeper code analysis
- Quick information gathering without multi-round iteration - Quick information gathering without multi-round iteration
- Follow-up analysis building on existing session - Follow-up analysis building on existing session
**Use `Skill(skill="workflow-lite-plan", args="\"task description\"")` when:** **Use `Skill(skill="workflow-lite-planex", args="\"task description\"")` when:**
- Ready to implement (past analysis phase) - Ready to implement (past analysis phase)
- Need simple task breakdown - Need simple task breakdown
- Focus on quick execution planning - Focus on quick execution planning
> **Note**: Phase 4「生成任务」assembles analysis context as inline `## Prior Analysis` block in task description, allowing lite-plan to skip redundant exploration automatically. > **Note**: Phase 4「执行任务」assembles analysis context as inline `## Prior Analysis` block in task description, allowing lite-plan to skip redundant exploration automatically.
--- ---

View File

@@ -2,7 +2,7 @@
name: brainstorm-with-file name: brainstorm-with-file
description: Interactive brainstorming with multi-CLI collaboration, idea expansion, and documented thought evolution description: Interactive brainstorming with multi-CLI collaboration, idea expansion, and documented thought evolution
argument-hint: "[-y|--yes] [-c|--continue] [-m|--mode creative|structured] \"idea or topic\"" argument-hint: "[-y|--yes] [-c|--continue] [-m|--mode creative|structured] \"idea or topic\""
allowed-tools: TodoWrite(*), Task(*), AskUserQuestion(*), Read(*), Grep(*), Glob(*), Bash(*), Edit(*), Write(*) allowed-tools: TodoWrite(*), Agent(*), AskUserQuestion(*), Read(*), Grep(*), Glob(*), Bash(*), Edit(*), Write(*)
--- ---
## Auto Mode ## Auto Mode
@@ -245,7 +245,7 @@ Output as structured exploration vectors for multi-perspective analysis.
**Agent Call Example**: **Agent Call Example**:
```javascript ```javascript
Task({ Agent({
subagent_type: "cli-explore-agent", subagent_type: "cli-explore-agent",
run_in_background: false, run_in_background: false,
description: `Explore codebase for brainstorm: ${topicSlug}`, description: `Explore codebase for brainstorm: ${topicSlug}`,
@@ -410,7 +410,7 @@ CONSTRAINTS: Consider existing system architecture
- perspectives.json contains initial ideas - perspectives.json contains initial ideas
- brainstorm.md has Round 2 findings - brainstorm.md has Round 2 findings
**Guideline**: For complex tasks (code analysis, implementation, POC creation), delegate to agents via Task tool (cli-explore-agent, code-developer, universal-executor) or CLI calls (ccw cli). Avoid direct analysis/execution in main process. **Guideline**: For complex tasks (code analysis, implementation, POC creation), delegate to agents via Agent tool (cli-explore-agent, code-developer, universal-executor) or CLI calls (ccw cli). Avoid direct analysis/execution in main process.
**Workflow Steps**: **Workflow Steps**:
@@ -725,7 +725,7 @@ Dimensions matched against topic keywords to identify focus areas:
## Best Practices ## Best Practices
1. **Clear Topic Definition**: Detailed topics → better role selection and exploration 1. **Clear Topic Definition**: Detailed topics → better role selection and exploration
2. **Agent-First for Complex Tasks**: For code analysis, POC implementation, or technical validation during refinement, delegate to agents via Task tool (cli-explore-agent, code-developer, universal-executor) or CLI calls (ccw cli). Avoid direct analysis/execution in main process 2. **Agent-First for Complex Tasks**: For code analysis, POC implementation, or technical validation during refinement, delegate to agents via Agent tool (cli-explore-agent, code-developer, universal-executor) or CLI calls (ccw cli). Avoid direct analysis/execution in main process
3. **Review brainstorm.md**: Check thought evolution before final decisions 3. **Review brainstorm.md**: Check thought evolution before final decisions
4. **Embrace Conflicts**: Perspective conflicts often reveal important tradeoffs 4. **Embrace Conflicts**: Perspective conflicts often reveal important tradeoffs
5. **Document Evolution**: brainstorm.md captures full thinking process for team review 5. **Document Evolution**: brainstorm.md captures full thinking process for team review
@@ -769,7 +769,7 @@ See full markdown template in original file (lines 955-1161).
- Want shared collaborative planning document - Want shared collaborative planning document
- Need structured task breakdown with agent coordination - Need structured task breakdown with agent coordination
**Use `Skill(skill="workflow-lite-plan", args="\"task description\"")` when:** **Use `Skill(skill="workflow-lite-planex", args="\"task description\"")` when:**
- Direction is already clear - Direction is already clear
- Ready to move from ideas to execution - Ready to move from ideas to execution
- Need simple implementation breakdown - Need simple implementation breakdown

View File

@@ -2,7 +2,7 @@
name: clean name: clean
description: Intelligent code cleanup with mainline detection, stale artifact discovery, and safe execution description: Intelligent code cleanup with mainline detection, stale artifact discovery, and safe execution
argument-hint: "[-y|--yes] [--dry-run] [\"focus area\"]" argument-hint: "[-y|--yes] [--dry-run] [\"focus area\"]"
allowed-tools: TodoWrite(*), Task(*), AskUserQuestion(*), Read(*), Glob(*), Bash(*), Write(*) allowed-tools: TodoWrite(*), Agent(*), AskUserQuestion(*), Read(*), Glob(*), Bash(*), Write(*)
--- ---
# Clean Command (/workflow:clean) # Clean Command (/workflow:clean)

View File

@@ -2,7 +2,7 @@
name: workflow:collaborative-plan-with-file name: workflow:collaborative-plan-with-file
description: Collaborative planning with Plan Note - Understanding agent creates shared plan-note.md template, parallel agents fill pre-allocated sections, conflict detection without merge. Outputs executable plan-note.md. description: Collaborative planning with Plan Note - Understanding agent creates shared plan-note.md template, parallel agents fill pre-allocated sections, conflict detection without merge. Outputs executable plan-note.md.
argument-hint: "[-y|--yes] <task description> [--max-agents=5]" argument-hint: "[-y|--yes] <task description> [--max-agents=5]"
allowed-tools: TodoWrite(*), Task(*), AskUserQuestion(*), Read(*), Bash(*), Write(*), Glob(*), Grep(*), mcp__ace-tool__search_context(*) allowed-tools: TodoWrite(*), Agent(*), AskUserQuestion(*), Read(*), Bash(*), Write(*), Glob(*), Grep(*), mcp__ace-tool__search_context(*)
--- ---
## Auto Mode ## Auto Mode

View File

@@ -2,7 +2,7 @@
name: debug-with-file name: debug-with-file
description: Interactive hypothesis-driven debugging with documented exploration, understanding evolution, and Gemini-assisted correction description: Interactive hypothesis-driven debugging with documented exploration, understanding evolution, and Gemini-assisted correction
argument-hint: "[-y|--yes] \"bug description or error message\"" argument-hint: "[-y|--yes] \"bug description or error message\""
allowed-tools: TodoWrite(*), Task(*), AskUserQuestion(*), Read(*), Grep(*), Glob(*), Bash(*), Edit(*), Write(*) allowed-tools: TodoWrite(*), Agent(*), AskUserQuestion(*), Read(*), Grep(*), Glob(*), Bash(*), Edit(*), Write(*)
--- ---
## Auto Mode ## Auto Mode
@@ -651,6 +651,6 @@ if (autoYes) {
| Empty debug.log | Verify reproduction triggered the code path | | Empty debug.log | Verify reproduction triggered the code path |
| All hypotheses rejected | Use Gemini to generate new hypotheses based on disproven assumptions | | All hypotheses rejected | Use Gemini to generate new hypotheses based on disproven assumptions |
| Fix doesn't work | Document failed fix attempt, iterate with refined understanding | | Fix doesn't work | Document failed fix attempt, iterate with refined understanding |
| >5 iterations | Review consolidated understanding, escalate to `workflow-lite-plan` skill with full context | | >5 iterations | Review consolidated understanding, escalate to `workflow-lite-planex` skill with full context |
| Gemini unavailable | Fallback to manual hypothesis generation, document without Gemini insights | | Gemini unavailable | Fallback to manual hypothesis generation, document without Gemini insights |
| Understanding too long | Consolidate aggressively, archive old iterations to separate file | | Understanding too long | Consolidate aggressively, archive old iterations to separate file |

View File

@@ -2,7 +2,7 @@
name: integration-test-cycle name: integration-test-cycle
description: Self-iterating integration test workflow with codebase exploration, test development, autonomous test-fix cycles, and reflection-driven strategy adjustment description: Self-iterating integration test workflow with codebase exploration, test development, autonomous test-fix cycles, and reflection-driven strategy adjustment
argument-hint: "[-y|--yes] [-c|--continue] [--max-iterations=N] \"module or feature description\"" argument-hint: "[-y|--yes] [-c|--continue] [--max-iterations=N] \"module or feature description\""
allowed-tools: TodoWrite(*), Task(*), AskUserQuestion(*), Read(*), Grep(*), Glob(*), Bash(*), Edit(*), Write(*), Skill(*) allowed-tools: TodoWrite(*), Agent(*), AskUserQuestion(*), Read(*), Grep(*), Glob(*), Bash(*), Edit(*), Write(*), Skill(*)
--- ---
## Auto Mode ## Auto Mode
@@ -209,7 +209,7 @@ Unified integration test workflow: **Explore → Design → Develop → Test →
1. **Codebase Exploration via cli-explore-agent** 1. **Codebase Exploration via cli-explore-agent**
```javascript ```javascript
Task({ Agent({
subagent_type: "cli-explore-agent", subagent_type: "cli-explore-agent",
run_in_background: false, run_in_background: false,
description: `Explore integration points: ${topicSlug}`, description: `Explore integration points: ${topicSlug}`,
@@ -391,7 +391,7 @@ Also set `state.json.phase` to `"designed"`.
1. **Generate Integration Tests via @code-developer** 1. **Generate Integration Tests via @code-developer**
```javascript ```javascript
Task({ Agent({
subagent_type: "code-developer", subagent_type: "code-developer",
run_in_background: false, run_in_background: false,
description: `Generate integration tests: ${topicSlug}`, description: `Generate integration tests: ${topicSlug}`,
@@ -435,7 +435,7 @@ Also set state.json "phase" to "developed".
2. **Code Validation Gate via @test-fix-agent** 2. **Code Validation Gate via @test-fix-agent**
```javascript ```javascript
Task({ Agent({
subagent_type: "test-fix-agent", subagent_type: "test-fix-agent",
run_in_background: false, run_in_background: false,
description: `Validate generated tests: ${topicSlug}`, description: `Validate generated tests: ${topicSlug}`,
@@ -605,7 +605,7 @@ After each iteration, update the `## Cumulative Learnings` section in reflection
**@test-fix-agent** (test execution): **@test-fix-agent** (test execution):
```javascript ```javascript
Task({ Agent({
subagent_type: "test-fix-agent", subagent_type: "test-fix-agent",
run_in_background: false, run_in_background: false,
description: `Execute integration tests: iteration ${N}`, description: `Execute integration tests: iteration ${N}`,
@@ -637,7 +637,7 @@ For each failure, assign:
**@cli-planning-agent** (failure analysis with reflection): **@cli-planning-agent** (failure analysis with reflection):
```javascript ```javascript
Task({ Agent({
subagent_type: "cli-planning-agent", subagent_type: "cli-planning-agent",
run_in_background: false, run_in_background: false,
description: `Analyze failures: iteration ${N} - ${strategy}`, description: `Analyze failures: iteration ${N} - ${strategy}`,
@@ -676,7 +676,7 @@ Analyze test failures using reflection context and generate fix strategy.
**@test-fix-agent** (apply fixes): **@test-fix-agent** (apply fixes):
```javascript ```javascript
Task({ Agent({
subagent_type: "test-fix-agent", subagent_type: "test-fix-agent",
run_in_background: false, run_in_background: false,
description: `Apply fixes: iteration ${N} - ${strategy}`, description: `Apply fixes: iteration ${N} - ${strategy}`,

View File

@@ -2,7 +2,7 @@
name: refactor-cycle name: refactor-cycle
description: Tech debt discovery and self-iterating refactoring with multi-dimensional analysis, prioritized execution, regression validation, and reflection-driven adjustment description: Tech debt discovery and self-iterating refactoring with multi-dimensional analysis, prioritized execution, regression validation, and reflection-driven adjustment
argument-hint: "[-y|--yes] [-c|--continue] [--scope=module|project] \"module or refactoring goal\"" argument-hint: "[-y|--yes] [-c|--continue] [--scope=module|project] \"module or refactoring goal\""
allowed-tools: TodoWrite(*), Task(*), AskUserQuestion(*), Read(*), Grep(*), Glob(*), Bash(*), Edit(*), Write(*) allowed-tools: TodoWrite(*), Agent(*), AskUserQuestion(*), Read(*), Grep(*), Glob(*), Bash(*), Edit(*), Write(*)
--- ---
## Auto Mode ## Auto Mode
@@ -200,7 +200,7 @@ Closed-loop tech debt lifecycle: **Discover → Assess → Plan → Refactor →
1. **Codebase Exploration via cli-explore-agent** 1. **Codebase Exploration via cli-explore-agent**
```javascript ```javascript
Task({ Agent({
subagent_type: "cli-explore-agent", subagent_type: "cli-explore-agent",
run_in_background: false, run_in_background: false,
description: `Explore codebase for debt: ${topicSlug}`, description: `Explore codebase for debt: ${topicSlug}`,
@@ -465,7 +465,7 @@ Set `state.json.current_item` to item ID.
#### Step 4.2: Execute Refactoring #### Step 4.2: Execute Refactoring
```javascript ```javascript
Task({ Agent({
subagent_type: "code-developer", subagent_type: "code-developer",
run_in_background: false, run_in_background: false,
description: `Refactor ${item.id}: ${item.title}`, description: `Refactor ${item.id}: ${item.title}`,
@@ -499,7 +499,7 @@ ${JSON.stringify(item.refactor_plan, null, 2)}
```javascript ```javascript
// 1. Run tests // 1. Run tests
Task({ Agent({
subagent_type: "test-fix-agent", subagent_type: "test-fix-agent",
run_in_background: false, run_in_background: false,
description: `Validate refactoring: ${item.id}`, description: `Validate refactoring: ${item.id}`,
@@ -827,7 +827,7 @@ AskUserQuestion({
- Need regression-safe iterative refactoring with rollback - Need regression-safe iterative refactoring with rollback
- Want documented reasoning for each refactoring decision - Want documented reasoning for each refactoring decision
**Use `workflow-lite-plan` skill when:** **Use `workflow-lite-planex` skill when:**
- Single specific bug or issue to fix - Single specific bug or issue to fix
- No systematic debt analysis needed - No systematic debt analysis needed

View File

@@ -2,7 +2,7 @@
name: roadmap-with-file name: roadmap-with-file
description: Strategic requirement roadmap with iterative decomposition and issue creation. Outputs roadmap.md (human-readable, single source) + issues.jsonl (machine-executable). Handoff to team-planex. description: Strategic requirement roadmap with iterative decomposition and issue creation. Outputs roadmap.md (human-readable, single source) + issues.jsonl (machine-executable). Handoff to team-planex.
argument-hint: "[-y|--yes] [-c|--continue] [-m progressive|direct|auto] \"requirement description\"" argument-hint: "[-y|--yes] [-c|--continue] [-m progressive|direct|auto] \"requirement description\""
allowed-tools: TodoWrite(*), Task(*), AskUserQuestion(*), Read(*), Grep(*), Glob(*), Bash(*), Edit(*), Write(*) allowed-tools: TodoWrite(*), Agent(*), AskUserQuestion(*), Read(*), Grep(*), Glob(*), Bash(*), Edit(*), Write(*)
--- ---
## Auto Mode ## Auto Mode
@@ -355,12 +355,12 @@ Bash(`mkdir -p ${sessionFolder}`)
**Agent Prompt Template**: **Agent Prompt Template**:
```javascript ```javascript
Task({ Agent({
subagent_type: "cli-roadmap-plan-agent", subagent_type: "cli-roadmap-plan-agent",
run_in_background: false, run_in_background: false,
description: `Roadmap decomposition: ${slug}`, description: `Roadmap decomposition: ${slug}`,
prompt: ` prompt: `
## Roadmap Decomposition Task ## Roadmap Decomposition Agent
### Input Context ### Input Context
- **Requirement**: ${requirement} - **Requirement**: ${requirement}
@@ -534,10 +534,10 @@ ${selectedMode === 'progressive' ? `**Progressive Mode**:
| Scenario | Recommended Command | | Scenario | Recommended Command |
|----------|-------------------| |----------|-------------------|
| Strategic planning, need issue tracking | `/workflow:roadmap-with-file` | | Strategic planning, need issue tracking | `/workflow:roadmap-with-file` |
| Quick task breakdown, immediate execution | `/workflow-lite-plan` | | Quick task breakdown, immediate execution | `/workflow-lite-planex` |
| Collaborative multi-agent planning | `/workflow:collaborative-plan-with-file` | | Collaborative multi-agent planning | `/workflow:collaborative-plan-with-file` |
| Full specification documents | `spec-generator` skill | | Full specification documents | `spec-generator` skill |
| Code implementation from existing plan | `/workflow:lite-execute` | | Code implementation from existing plan | `/workflow-lite-planex` (Phase 1: plan → Phase 2: execute) |
--- ---

View File

@@ -2,7 +2,7 @@
name: animation-extract name: animation-extract
description: Extract animation and transition patterns from prompt inference and image references for design system documentation description: Extract animation and transition patterns from prompt inference and image references for design system documentation
argument-hint: "[-y|--yes] [--design-id <id>] [--session <id>] [--images "<glob>"] [--focus "<types>"] [--interactive] [--refine]" argument-hint: "[-y|--yes] [--design-id <id>] [--session <id>] [--images "<glob>"] [--focus "<types>"] [--interactive] [--refine]"
allowed-tools: TodoWrite(*), Read(*), Write(*), Glob(*), Bash(*), AskUserQuestion(*), Task(ui-design-agent) allowed-tools: TodoWrite(*), Read(*), Write(*), Glob(*), Bash(*), AskUserQuestion(*), Agent(ui-design-agent)
--- ---
## Auto Mode ## Auto Mode
@@ -207,14 +207,14 @@ IF has_images:
### Step 2: Generate Animation Specification Options (Agent Task 1) ### Step 2: Generate Animation Specification Options (Agent Task 1)
**Executor**: `Task(ui-design-agent)` **Executor**: `Agent(ui-design-agent)`
**Conditional Logic**: Branch based on `refine_mode` flag **Conditional Logic**: Branch based on `refine_mode` flag
```javascript ```javascript
IF NOT refine_mode: IF NOT refine_mode:
// EXPLORATION MODE (default) // EXPLORATION MODE (default)
Task(ui-design-agent): ` Agent(ui-design-agent): `
[ANIMATION_SPECIFICATION_GENERATION_TASK] [ANIMATION_SPECIFICATION_GENERATION_TASK]
Generate context-aware animation specification questions Generate context-aware animation specification questions
@@ -308,7 +308,7 @@ IF NOT refine_mode:
ELSE: ELSE:
// REFINEMENT MODE // REFINEMENT MODE
Task(ui-design-agent): ` Agent(ui-design-agent): `
[ANIMATION_REFINEMENT_OPTIONS_TASK] [ANIMATION_REFINEMENT_OPTIONS_TASK]
Generate refinement options for existing animation system Generate refinement options for existing animation system
@@ -656,7 +656,7 @@ ELSE:
## Phase 2: Animation System Generation (Agent Task 2) ## Phase 2: Animation System Generation (Agent Task 2)
**Executor**: `Task(ui-design-agent)` for animation token generation **Executor**: `Agent(ui-design-agent)` for animation token generation
### Step 1: Load User Selection or Use Defaults ### Step 1: Load User Selection or Use Defaults
@@ -706,14 +706,14 @@ IF has_images:
bash(mkdir -p {base_path}/animation-extraction) bash(mkdir -p {base_path}/animation-extraction)
``` ```
### Step 3: Launch Animation Generation Task ### Step 3: Launch Animation Generation Agent
**Conditional Task**: Branch based on `refine_mode` flag **Conditional Task**: Branch based on `refine_mode` flag
```javascript ```javascript
IF NOT refine_mode: IF NOT refine_mode:
// EXPLORATION MODE // EXPLORATION MODE
Task(ui-design-agent): ` Agent(ui-design-agent): `
[ANIMATION_SYSTEM_GENERATION_TASK] [ANIMATION_SYSTEM_GENERATION_TASK]
Generate production-ready animation system based on user preferences and CSS extraction Generate production-ready animation system based on user preferences and CSS extraction
@@ -871,7 +871,7 @@ IF NOT refine_mode:
ELSE: ELSE:
// REFINEMENT MODE // REFINEMENT MODE
Task(ui-design-agent): ` Agent(ui-design-agent): `
[ANIMATION_SYSTEM_REFINEMENT_TASK] [ANIMATION_SYSTEM_REFINEMENT_TASK]
Apply selected refinements to existing animation system Apply selected refinements to existing animation system

View File

@@ -2,7 +2,7 @@
name: explore-auto name: explore-auto
description: Interactive exploratory UI design workflow with style-centric batch generation, creates design variants from prompts/images with parallel execution and user selection description: Interactive exploratory UI design workflow with style-centric batch generation, creates design variants from prompts/images with parallel execution and user selection
argument-hint: "[--input "<value>"] [--targets "<list>"] [--target-type "page|component"] [--session <id>] [--style-variants <count>] [--layout-variants <count>]" argument-hint: "[--input "<value>"] [--targets "<list>"] [--target-type "page|component"] [--session <id>] [--style-variants <count>] [--layout-variants <count>]"
allowed-tools: Skill(*), TodoWrite(*), Read(*), Bash(*), Glob(*), Write(*), Task(conceptual-planning-agent) allowed-tools: Skill(*), TodoWrite(*), Read(*), Bash(*), Glob(*), Write(*), Agent(conceptual-planning-agent)
--- ---
# UI Design Auto Workflow Command # UI Design Auto Workflow Command

View File

@@ -2,7 +2,7 @@
name: generate name: generate
description: Assemble UI prototypes by combining layout templates with design tokens (default animation support), pure assembler without new content generation description: Assemble UI prototypes by combining layout templates with design tokens (default animation support), pure assembler without new content generation
argument-hint: [--design-id <id>] [--session <id>] argument-hint: [--design-id <id>] [--session <id>]
allowed-tools: TodoWrite(*), Read(*), Write(*), Task(ui-design-agent), Bash(*) allowed-tools: TodoWrite(*), Read(*), Write(*), Agent(ui-design-agent), Bash(*)
--- ---
# Generate UI Prototypes (/workflow:ui-design:generate) # Generate UI Prototypes (/workflow:ui-design:generate)
@@ -129,7 +129,7 @@ ELSE:
## Phase 2: Assembly (Agent) ## Phase 2: Assembly (Agent)
**Executor**: `Task(ui-design-agent)` grouped by `target × style` (max 10 layouts per agent, max 6 concurrent agents) **Executor**: `Agent(ui-design-agent)` grouped by `target × style` (max 10 layouts per agent, max 6 concurrent agents)
**⚠️ Core Principle**: **Each agent processes ONLY ONE style** (but can process multiple layouts for that style) **⚠️ Core Principle**: **Each agent processes ONLY ONE style** (but can process multiple layouts for that style)
@@ -204,7 +204,7 @@ TodoWrite({todos: [
For each batch (up to 6 parallel agents per batch): For each batch (up to 6 parallel agents per batch):
For each agent group `{target, style_id, layout_ids[]}` in current batch: For each agent group `{target, style_id, layout_ids[]}` in current batch:
```javascript ```javascript
Task(ui-design-agent): ` Agent(ui-design-agent): `
[LAYOUT_STYLE_ASSEMBLY] [LAYOUT_STYLE_ASSEMBLY]
🎯 {target} × Style-{style_id} × Layouts-{layout_ids} 🎯 {target} × Style-{style_id} × Layouts-{layout_ids}
⚠️ CONSTRAINT: Use ONLY style-{style_id}/design-tokens.json (never mix styles) ⚠️ CONSTRAINT: Use ONLY style-{style_id}/design-tokens.json (never mix styles)

View File

@@ -2,7 +2,7 @@
name: workflow:ui-design:import-from-code name: workflow:ui-design:import-from-code
description: Import design system from code files (CSS/JS/HTML/SCSS) with automatic file discovery and parallel agent analysis description: Import design system from code files (CSS/JS/HTML/SCSS) with automatic file discovery and parallel agent analysis
argument-hint: "[--design-id <id>] [--session <id>] [--source <path>]" argument-hint: "[--design-id <id>] [--session <id>] [--source <path>]"
allowed-tools: Read,Write,Bash,Glob,Grep,Task,TodoWrite allowed-tools: Read,Write,Bash,Glob,Grep,Agent,TodoWrite
auto-continue: true auto-continue: true
--- ---

View File

@@ -2,7 +2,7 @@
name: layout-extract name: layout-extract
description: Extract structural layout information from reference images or text prompts using Claude analysis with variant generation or refinement mode description: Extract structural layout information from reference images or text prompts using Claude analysis with variant generation or refinement mode
argument-hint: "[-y|--yes] [--design-id <id>] [--session <id>] [--images "<glob>"] [--prompt "<desc>"] [--targets "<list>"] [--variants <count>] [--device-type <desktop|mobile|tablet|responsive>] [--interactive] [--refine]" argument-hint: "[-y|--yes] [--design-id <id>] [--session <id>] [--images "<glob>"] [--prompt "<desc>"] [--targets "<list>"] [--variants <count>] [--device-type <desktop|mobile|tablet|responsive>] [--interactive] [--refine]"
allowed-tools: TodoWrite(*), Read(*), Write(*), Glob(*), Bash(*), AskUserQuestion(*), Task(ui-design-agent), mcp__exa__web_search_exa(*) allowed-tools: TodoWrite(*), Read(*), Write(*), Glob(*), Bash(*), AskUserQuestion(*), Agent(ui-design-agent), mcp__exa__web_search_exa(*)
--- ---
## Auto Mode ## Auto Mode
@@ -162,7 +162,7 @@ IF refine_mode:
``` ```
### Step 1: Generate Options (Agent Task 1 - Mode-Specific) ### Step 1: Generate Options (Agent Task 1 - Mode-Specific)
**Executor**: `Task(ui-design-agent)` **Executor**: `Agent(ui-design-agent)`
**Exploration Mode** (default): Generate contrasting layout concepts **Exploration Mode** (default): Generate contrasting layout concepts
**Refinement Mode** (`--refine`): Generate refinement options for existing layouts **Refinement Mode** (`--refine`): Generate refinement options for existing layouts
@@ -171,7 +171,7 @@ IF refine_mode:
// Conditional agent task based on refine_mode // Conditional agent task based on refine_mode
IF NOT refine_mode: IF NOT refine_mode:
// EXPLORATION MODE // EXPLORATION MODE
Task(ui-design-agent): ` Agent(ui-design-agent): `
[LAYOUT_CONCEPT_GENERATION_TASK] [LAYOUT_CONCEPT_GENERATION_TASK]
Generate {variants_count} structurally distinct layout concepts for each target Generate {variants_count} structurally distinct layout concepts for each target
@@ -217,7 +217,7 @@ IF NOT refine_mode:
` `
ELSE: ELSE:
// REFINEMENT MODE // REFINEMENT MODE
Task(ui-design-agent): ` Agent(ui-design-agent): `
[LAYOUT_REFINEMENT_OPTIONS_TASK] [LAYOUT_REFINEMENT_OPTIONS_TASK]
Generate refinement options for existing layout(s) Generate refinement options for existing layout(s)
@@ -461,7 +461,7 @@ Proceeding to generate {total_selections} detailed layout template(s)...
## Phase 2: Layout Template Generation (Agent Task 2) ## Phase 2: Layout Template Generation (Agent Task 2)
**Executor**: `Task(ui-design-agent)` × `Total_Selected_Templates` in **parallel** **Executor**: `Agent(ui-design-agent)` × `Total_Selected_Templates` in **parallel**
### Step 1: Load User Selections or Default to All ### Step 1: Load User Selections or Default to All
```bash ```bash
@@ -512,7 +512,7 @@ REPORT: "Generating {total_tasks} layout templates across {targets.length} targe
Generate layout templates for ALL selected concepts in parallel: Generate layout templates for ALL selected concepts in parallel:
```javascript ```javascript
FOR each task in task_list: FOR each task in task_list:
Task(ui-design-agent): ` Agent(ui-design-agent): `
[LAYOUT_TEMPLATE_GENERATION_TASK #{task.variant_id} for {task.target}] [LAYOUT_TEMPLATE_GENERATION_TASK #{task.variant_id} for {task.target}]
Generate detailed layout template based on user-selected concept. Generate detailed layout template based on user-selected concept.
Focus ONLY on structure and layout. DO NOT concern with visual style (colors, fonts, etc.). Focus ONLY on structure and layout. DO NOT concern with visual style (colors, fonts, etc.).

View File

@@ -2,7 +2,7 @@
name: workflow:ui-design:reference-page-generator name: workflow:ui-design:reference-page-generator
description: Generate multi-component reference pages and documentation from design run extraction description: Generate multi-component reference pages and documentation from design run extraction
argument-hint: "[--design-run <path>] [--package-name <name>] [--output-dir <path>]" argument-hint: "[--design-run <path>] [--package-name <name>] [--output-dir <path>]"
allowed-tools: Read,Write,Bash,Task,TodoWrite allowed-tools: Read,Write,Bash,Agent,TodoWrite
auto-continue: true auto-continue: true
--- ---
@@ -198,7 +198,7 @@ echo "[Phase 1] Component data preparation complete"
**Agent Task**: **Agent Task**:
```javascript ```javascript
Task(ui-design-agent): ` Agent(ui-design-agent): `
[PREVIEW_SHOWCASE_GENERATION] [PREVIEW_SHOWCASE_GENERATION]
Generate interactive multi-component showcase panel for reference package Generate interactive multi-component showcase panel for reference package
@@ -210,7 +210,7 @@ Task(ui-design-agent): `
2. ${package_dir}/design-tokens.json (design tokens - REQUIRED) 2. ${package_dir}/design-tokens.json (design tokens - REQUIRED)
3. ${package_dir}/animation-tokens.json (optional, if exists) 3. ${package_dir}/animation-tokens.json (optional, if exists)
## Generation Task ## Generation Agent
Create interactive showcase with these sections: Create interactive showcase with these sections:

View File

@@ -2,7 +2,7 @@
name: unified-execute-with-file name: unified-execute-with-file
description: Universal execution engine for consuming any planning/brainstorm/analysis output with minimal progress tracking, multi-agent coordination, and incremental execution description: Universal execution engine for consuming any planning/brainstorm/analysis output with minimal progress tracking, multi-agent coordination, and incremental execution
argument-hint: "[-y|--yes] [<path>[,<path2>] | -p|--plan <path>[,<path2>]] [--auto-commit] [--commit-prefix \"prefix\"] [\"execution context or task name\"]" argument-hint: "[-y|--yes] [<path>[,<path2>] | -p|--plan <path>[,<path2>]] [--auto-commit] [--commit-prefix \"prefix\"] [\"execution context or task name\"]"
allowed-tools: TodoWrite(*), Task(*), AskUserQuestion(*), Read(*), Grep(*), Glob(*), Bash(*), Edit(*), Write(*) allowed-tools: TodoWrite(*), Agent(*), AskUserQuestion(*), Read(*), Grep(*), Glob(*), Bash(*), Edit(*), Write(*)
--- ---
## Auto Mode ## Auto Mode
@@ -34,7 +34,7 @@ When `--yes` or `-y`: Auto-confirm execution decisions, follow plan's DAG depend
``` ```
**Execution Methods**: **Execution Methods**:
- **Agent**: Task tool with code-developer (recommended for standard tasks) - **Agent**: Agent tool with code-developer (recommended for standard tasks)
- **CLI-Codex**: `ccw cli --tool codex` (complex tasks, git-aware) - **CLI-Codex**: `ccw cli --tool codex` (complex tasks, git-aware)
- **CLI-Gemini**: `ccw cli --tool gemini` (analysis-heavy tasks) - **CLI-Gemini**: `ccw cli --tool gemini` (analysis-heavy tasks)
- **Auto**: Select based on task complexity (default in `-y` mode) - **Auto**: Select based on task complexity (default in `-y` mode)
@@ -99,7 +99,7 @@ Universal execution engine consuming **any** planning output and executing it wi
│ Phase 5: Per-Task Execution (Agent OR CLI) │ │ Phase 5: Per-Task Execution (Agent OR CLI) │
│ ├─ Extract relevant notes from previous tasks │ │ ├─ Extract relevant notes from previous tasks │
│ ├─ Inject notes into execution context │ │ ├─ Inject notes into execution context │
│ ├─ Route to Agent (Task tool) OR CLI (ccw cli command) │ │ ├─ Route to Agent (Agent tool) OR CLI (ccw cli command) │
│ ├─ Generate structured notes for next task │ │ ├─ Generate structured notes for next task │
│ ├─ Auto-commit if enabled (conventional commit format) │ │ ├─ Auto-commit if enabled (conventional commit format) │
│ └─ Append event to unified log │ │ └─ Append event to unified log │
@@ -507,10 +507,10 @@ ${recommendations.map(r => \`- ${r}\`).join('\\n')}
When: `executionMethod === "Agent"` or `Auto + Low Complexity` When: `executionMethod === "Agent"` or `Auto + Low Complexity`
Execute task via Task tool with code-developer agent: Execute task via Agent tool with code-developer agent:
```javascript ```javascript
Task({ Agent({
subagent_type: "code-developer", // or other agent types subagent_type: "code-developer", // or other agent types
run_in_background: false, run_in_background: false,
description: task.title, description: task.title,

View File

@@ -45,9 +45,9 @@ const COMMAND_TO_SKILL_MAP = {
// workflow commands → skills // workflow commands → skills
'/workflow-plan': 'workflow-plan', '/workflow-plan': 'workflow-plan',
'/workflow-execute': 'workflow-execute', '/workflow-execute': 'workflow-execute',
'/workflow-lite-plan': 'workflow-lite-plan', '/workflow-lite-planex': 'workflow-lite-planex',
'/workflow:lite-execute': 'workflow-lite-plan', // lite-execute is part of lite-plan skill '/workflow:lite-execute': 'workflow-lite-planex', // lite-execute is part of lite-plan skill
'/workflow:lite-fix': 'workflow-lite-plan', // lite-fix is part of lite-plan skill '/workflow:lite-fix': 'workflow-lite-planex', // lite-fix is part of lite-plan skill
'/workflow-multi-cli-plan': 'workflow-multi-cli-plan', '/workflow-multi-cli-plan': 'workflow-multi-cli-plan',
'/workflow-plan-verify': 'workflow-plan', // plan-verify is a phase of workflow-plan '/workflow-plan-verify': 'workflow-plan', // plan-verify is a phase of workflow-plan
'/workflow:replan': 'workflow-plan', // replan is a phase of workflow-plan '/workflow:replan': 'workflow-plan', // replan is a phase of workflow-plan
@@ -87,7 +87,7 @@ const COMMAND_TO_SKILL_MAP = {
// general commands // general commands
'/ccw-debug': null, // deleted, no replacement '/ccw-debug': null, // deleted, no replacement
'/ccw view': null, // deleted, no replacement '/ccw view': null, // deleted, no replacement
'/workflow:lite-lite-lite': 'workflow-lite-plan', '/workflow:lite-lite-lite': 'workflow-lite-planex',
// ui-design (these still exist as commands) // ui-design (these still exist as commands)
'/workflow:ui-design:auto': '/workflow:ui-design:explore-auto', '/workflow:ui-design:auto': '/workflow:ui-design:explore-auto',
'/workflow:ui-design:update': '/workflow:ui-design:generate', '/workflow:ui-design:update': '/workflow:ui-design:generate',
@@ -302,8 +302,8 @@ function fixBrokenReferences() {
"skill='compact'": "skill='memory-capture'", "skill='compact'": "skill='memory-capture'",
'skill="workflow:brainstorm:role-analysis"': 'skill="brainstorm"', 'skill="workflow:brainstorm:role-analysis"': 'skill="brainstorm"',
"skill='workflow:brainstorm:role-analysis'": "skill='brainstorm'", "skill='workflow:brainstorm:role-analysis'": "skill='brainstorm'",
'skill="workflow:lite-execute"': 'skill="workflow-lite-plan"', 'skill="workflow:lite-execute"': 'skill="workflow-lite-planex"',
"skill='workflow:lite-execute'": "skill='workflow-lite-plan'", "skill='workflow:lite-execute'": "skill='workflow-lite-planex'",
}; };
for (const [oldCall, newCall] of Object.entries(skillCallFixes)) { for (const [oldCall, newCall] of Object.entries(skillCallFixes)) {
@@ -321,8 +321,8 @@ function fixBrokenReferences() {
const proseRefFixes = { const proseRefFixes = {
'`/workflow-plan`': '`workflow-plan` skill', '`/workflow-plan`': '`workflow-plan` skill',
'`/workflow-execute`': '`workflow-execute` skill', '`/workflow-execute`': '`workflow-execute` skill',
'`/workflow:lite-execute`': '`workflow-lite-plan` skill', '`/workflow:lite-execute`': '`workflow-lite-planex` skill',
'`/workflow:lite-fix`': '`workflow-lite-plan` skill', '`/workflow:lite-fix`': '`workflow-lite-planex` skill',
'`/workflow-plan-verify`': '`workflow-plan` skill (plan-verify phase)', '`/workflow-plan-verify`': '`workflow-plan` skill (plan-verify phase)',
'`/workflow:replan`': '`workflow-plan` skill (replan phase)', '`/workflow:replan`': '`workflow-plan` skill (replan phase)',
'`/workflow-tdd-plan`': '`workflow-tdd-plan` skill', '`/workflow-tdd-plan`': '`workflow-tdd-plan` skill',
@@ -347,8 +347,8 @@ function fixBrokenReferences() {
'`/workflow:ui-design:auto`': '`/workflow:ui-design:explore-auto`', '`/workflow:ui-design:auto`': '`/workflow:ui-design:explore-auto`',
'`/workflow:ui-design:update`': '`/workflow:ui-design:generate`', '`/workflow:ui-design:update`': '`/workflow:ui-design:generate`',
'`/workflow-multi-cli-plan`': '`workflow-multi-cli-plan` skill', '`/workflow-multi-cli-plan`': '`workflow-multi-cli-plan` skill',
'`/workflow-lite-plan`': '`workflow-lite-plan` skill', '`/workflow-lite-planex`': '`workflow-lite-planex` skill',
'`/cli:plan`': '`workflow-lite-plan` skill', '`/cli:plan`': '`workflow-lite-planex` skill',
'`/test-cycle-execute`': '`workflow-test-fix` skill', '`/test-cycle-execute`': '`workflow-test-fix` skill',
}; };

View File

@@ -83,7 +83,7 @@
| 内容类型 | 保留要求 | 示例 | | 内容类型 | 保留要求 | 示例 |
|---------|---------|------| |---------|---------|------|
| **Bash命令** | 完整命令,包含所有参数、管道、重定向 | `find . -name "*.json" \| head -1` | | **Bash命令** | 完整命令,包含所有参数、管道、重定向 | `find . -name "*.json" \| head -1` |
| **Agent Prompt** | 全文保留包含OBJECTIVE、TASK、EXPECTED等所有节 | 完整的Task({prompt: "..."}) | | **Agent Prompt** | 全文保留包含OBJECTIVE、TASK、EXPECTED等所有节 | 完整的Agent({prompt: "..."}) |
| **代码函数** | 完整函数体所有if/else分支 | `analyzeTaskComplexity()` 全部代码 | | **代码函数** | 完整函数体所有if/else分支 | `analyzeTaskComplexity()` 全部代码 |
| **参数表格** | 所有行列,不省略任何参数 | Session Types表格 | | **参数表格** | 所有行列,不省略任何参数 | Session Types表格 |
| **JSON Schema** | 所有字段、类型、required定义 | context-package.json schema | | **JSON Schema** | 所有字段、类型、required定义 | context-package.json schema |
@@ -95,7 +95,7 @@
1. **将代码替换为描述** 1. **将代码替换为描述**
- ❌ 错误:`Execute context gathering agent` - ❌ 错误:`Execute context gathering agent`
- ✅ 正确:完整的 `Task({ subagent_type: "context-search-agent", prompt: "...[完整200行prompt]..." })` - ✅ 正确:完整的 `Agent({ subagent_type: "context-search-agent", prompt: "...[完整200行prompt]..." })`
2. **省略Prompt内容** 2. **省略Prompt内容**
- ❌ 错误:`Agent prompt for context gathering (see original file)` - ❌ 错误:`Agent prompt for context gathering (see original file)`
@@ -277,7 +277,7 @@ commands/ skills/
--- ---
name: {skill-name} name: {skill-name}
description: {简短描述}. Triggers on "{trigger-phrase}". description: {简短描述}. Triggers on "{trigger-phrase}".
allowed-tools: Task, AskUserQuestion, TodoWrite, Read, Write, Edit, Bash, Glob, Grep allowed-tools: Agent, AskUserQuestion, TodoWrite, Read, Write, Edit, Bash, Glob, Grep
--- ---
``` ```
@@ -440,7 +440,7 @@ Complete: IMPL_PLAN.md + Task JSONs
|--------|---------|---------| |--------|---------|---------|
| **代码块数量** | 计数 ` ```bash `` ```javascript ` | 与原文件相等 | | **代码块数量** | 计数 ` ```bash `` ```javascript ` | 与原文件相等 |
| **表格数量** | 计数 ` \| ` 开头的行 | 与原文件相等 | | **表格数量** | 计数 ` \| ` 开头的行 | 与原文件相等 |
| **Agent Prompt** | 搜索 `Task({` | 完整的prompt参数内容 | | **Agent Prompt** | 搜索 `Agent({` | 完整的prompt参数内容 |
| **步骤编号** | 检查 `### Step` | 编号序列与原文件一致 | | **步骤编号** | 检查 `### Step` | 编号序列与原文件一致 |
| **文件行数** | `wc -l` | ±20%以内 | | **文件行数** | `wc -l` | ±20%以内 |
| **关键函数** | 搜索函数名 | 所有函数完整保留 | | **关键函数** | 搜索函数名 | 所有函数完整保留 |
@@ -492,10 +492,10 @@ Execute the context-search-agent to gather project context.
### Step 2: Run context gathering ### Step 2: Run context gathering
```javascript ```javascript
Task({ Agent({
subagent_type: "context-search-agent", subagent_type: "context-search-agent",
prompt: ` prompt: `
## Context Search Task ## Context Search Agent
### OBJECTIVE ### OBJECTIVE
Gather comprehensive context for planning session ${sessionId} Gather comprehensive context for planning session ${sessionId}
@@ -535,7 +535,7 @@ Gather comprehensive context for planning session ${sessionId}
│ └─→ 数量应相等 │ │ └─→ 数量应相等 │
│ │ │ │
│ Step 3: 关键内容抽查 │ │ Step 3: 关键内容抽查 │
│ - 搜索 Task({ → Agent Prompt 完整性 │ │ - 搜索 Agent({ → Agent Prompt 完整性 │
│ - 搜索函数名 → 函数体完整性 │ │ - 搜索函数名 → 函数体完整性 │
│ - 搜索表格标记 → 表格完整性 │ │ - 搜索表格标记 → 表格完整性 │
│ │ │ │
@@ -562,8 +562,8 @@ grep -c '^|' commands/workflow/tools/context-gather.md
grep -c '^|' skills/workflow-plan/phases/02-context-gathering.md grep -c '^|' skills/workflow-plan/phases/02-context-gathering.md
# 4. Agent Prompt检查 # 4. Agent Prompt检查
grep -c 'Task({' commands/workflow/tools/context-gather.md grep -c 'Agent({' commands/workflow/tools/context-gather.md
grep -c 'Task({' skills/workflow-plan/phases/02-context-gathering.md grep -c 'Agent({' skills/workflow-plan/phases/02-context-gathering.md
# 5. 函数定义检查 # 5. 函数定义检查
grep -E '^(function|const.*=.*=>|async function)' commands/workflow/tools/context-gather.md grep -E '^(function|const.*=.*=>|async function)' commands/workflow/tools/context-gather.md

View File

@@ -140,7 +140,7 @@ graph TD
--- ---
name: {skill-name} name: {skill-name}
description: {一句话描述}. {触发关键词}. Triggers on "{关键词1}", "{关键词2}". description: {一句话描述}. {触发关键词}. Triggers on "{关键词1}", "{关键词2}".
allowed-tools: Task, AskUserQuestion, Read, Bash, Glob, Grep, Write, {其他MCP工具} allowed-tools: Agent, AskUserQuestion, Read, Bash, Glob, Grep, Write, {其他MCP工具}
--- ---
# {Skill 标题} # {Skill 标题}
@@ -192,7 +192,7 @@ description: | # 必需:描述 + 触发词
Generate XXX documents. Generate XXX documents.
Triggers on "keyword1", "keyword2". Triggers on "keyword1", "keyword2".
allowed-tools: | # 必需:允许使用的工具 allowed-tools: | # 必需:允许使用的工具
Task, AskUserQuestion, Read, Bash, Agent, AskUserQuestion, Read, Bash,
Glob, Grep, Write, mcp__chrome__* Glob, Grep, Write, mcp__chrome__*
--- ---
``` ```
@@ -641,7 +641,7 @@ touch my-skill/templates/agent-base.md
--- ---
name: my-skill name: my-skill
description: Generate XXX. Triggers on "keyword1", "keyword2". description: Generate XXX. Triggers on "keyword1", "keyword2".
allowed-tools: Task, AskUserQuestion, Read, Bash, Glob, Grep, Write allowed-tools: Agent, AskUserQuestion, Read, Bash, Glob, Grep, Write
--- ---
# My Skill # My Skill
@@ -680,7 +680,7 @@ Generate XXX through multi-phase analysis.
| 工具 | 用途 | 适用 Skill | | 工具 | 用途 | 适用 Skill |
|------|------|------------| |------|------|------------|
| `Task` | 启动子 Agent | 所有 | | `Agent` | 启动子 Agent | 所有 |
| `AskUserQuestion` | 用户交互 | 所有 | | `AskUserQuestion` | 用户交互 | 所有 |
| `Read/Write/Glob/Grep` | 文件操作 | 所有 | | `Read/Write/Glob/Grep` | 文件操作 | 所有 |
| `Bash` | 脚本执行 | 需要自动化 | | `Bash` | 脚本执行 | 需要自动化 |

View File

@@ -1,7 +1,7 @@
--- ---
name: brainstorm name: brainstorm
description: Unified brainstorming skill with dual-mode operation - auto pipeline and single role analysis. Triggers on "brainstorm", "头脑风暴". description: Unified brainstorming skill with dual-mode operation - auto pipeline and single role analysis. Triggers on "brainstorm", "头脑风暴".
allowed-tools: Skill(*), Task(conceptual-planning-agent, context-search-agent), AskUserQuestion(*), TodoWrite(*), Read(*), Write(*), Edit(*), Glob(*), Bash(*) allowed-tools: Skill(*), Agent(conceptual-planning-agent, context-search-agent), AskUserQuestion(*), TodoWrite(*), Read(*), Write(*), Edit(*), Glob(*), Bash(*)
--- ---
# Brainstorm # Brainstorm

View File

@@ -1,18 +1,18 @@
--- ---
name: ccw-help name: ccw-help
description: CCW command help system. Search, browse, recommend commands. Triggers "ccw-help", "ccw-issue". description: CCW command help system. Search, browse, recommend commands, skills, teams. Triggers "ccw-help", "ccw-issue".
allowed-tools: Read, Grep, Glob, AskUserQuestion allowed-tools: Read, Grep, Glob, AskUserQuestion
version: 7.0.0 version: 8.0.0
--- ---
# CCW-Help Skill # CCW-Help Skill
CCW 命令帮助系统,提供命令搜索、推荐、文档查看功能。 CCW 命令帮助系统,提供命令搜索、推荐、文档查看、Skill/Team 浏览功能。
## Trigger Conditions ## Trigger Conditions
- 关键词: "ccw-help", "ccw-issue", "帮助", "命令", "怎么用", "ccw 怎么用", "工作流" - 关键词: "ccw-help", "ccw-issue", "帮助", "命令", "怎么用", "ccw 怎么用", "工作流", "skill", "team"
- 场景: 询问命令用法、搜索命令、请求下一步建议、询问任务应该用哪个工作流 - 场景: 询问命令用法、搜索命令、请求下一步建议、询问任务应该用哪个工作流、浏览 Skill/Team 目录
## Operation Modes ## Operation Modes
@@ -61,7 +61,7 @@ CCW 命令帮助系统,提供命令搜索、推荐、文档查看功能。
4. Get user confirmation 4. Get user confirmation
5. Execute chain with TODO tracking 5. Execute chain with TODO tracking
**Supported Workflows**: **Supported Workflows** (参考 [ccw.md](../../commands/ccw.md)):
- **Level 1** (Lite-Lite-Lite): Ultra-simple quick tasks - **Level 1** (Lite-Lite-Lite): Ultra-simple quick tasks
- **Level 2** (Rapid/Hotfix): Bug fixes, simple features, documentation - **Level 2** (Rapid/Hotfix): Bug fixes, simple features, documentation
- **Level 2.5** (Rapid-to-Issue): Bridge from quick planning to issue workflow - **Level 2.5** (Rapid-to-Issue): Bridge from quick planning to issue workflow
@@ -71,12 +71,17 @@ CCW 命令帮助系统,提供命令搜索、推荐、文档查看功能。
- Test-fix workflows (debug failing tests) - Test-fix workflows (debug failing tests)
- Review workflows (code review and fixes) - Review workflows (code review and fixes)
- UI design workflows - UI design workflows
- Multi-CLI collaborative workflows
- Cycle workflows (integration-test, refactor)
- **Level 4** (Full): Exploratory tasks with brainstorming - **Level 4** (Full): Exploratory tasks with brainstorming
- **With-File Workflows**: Documented exploration with multi-CLI collaboration - **With-File Workflows**: Documented exploration with multi-CLI collaboration
- `brainstorm-with-file`: Multi-perspective ideation - `brainstorm-with-file`: Multi-perspective ideation → workflow-plan → workflow-execute
- `debug-with-file`: Hypothesis-driven debugging - `debug-with-file`: Hypothesis-driven debugging (standalone)
- `analyze-with-file`: Collaborative analysis - `analyze-with-file`: Collaborative analysis → workflow-lite-planex
- `collaborative-plan-with-file`: Multi-agent planning → unified-execute
- `roadmap-with-file`: Strategic requirement roadmap → team-planex
- **Issue Workflow**: Batch issue discovery, planning, queueing, execution - **Issue Workflow**: Batch issue discovery, planning, queueing, execution
- **Team Workflow**: team-planex wave pipeline for parallel execution
### Mode 6: Issue Reporting ### Mode 6: Issue Reporting
@@ -86,6 +91,16 @@ CCW 命令帮助系统,提供命令搜索、推荐、文档查看功能。
1. Use AskUserQuestion to gather context 1. Use AskUserQuestion to gather context
2. Generate structured issue template 2. Generate structured issue template
### Mode 7: Skill & Team Browsing
**Triggers**: "skill", "team", "技能", "团队", "有哪些 skill", "team 怎么用"
**Process**:
1. Query `command.json` skills array
2. Filter by category: workflow / team / review / meta / utility / standalone
3. Present categorized skill list with descriptions
4. For team skills, explain team architecture and usage patterns
## Data Source ## Data Source
Single source of truth: **[command.json](command.json)** Single source of truth: **[command.json](command.json)**
@@ -94,8 +109,9 @@ Single source of truth: **[command.json](command.json)**
|-------|---------| |-------|---------|
| `commands[]` | Flat command list with metadata | | `commands[]` | Flat command list with metadata |
| `commands[].flow` | Relationships (next_steps, prerequisites) | | `commands[].flow` | Relationships (next_steps, prerequisites) |
| `commands[].essential` | Essential flag for onboarding |
| `agents[]` | Agent directory | | `agents[]` | Agent directory |
| `skills[]` | Skill directory with categories |
| `skills[].is_team` | Whether skill uses team architecture |
| `essential_commands[]` | Core commands list | | `essential_commands[]` | Core commands list |
### Source Path Format ### Source Path Format
@@ -109,6 +125,77 @@ Single source of truth: **[command.json](command.json)**
} }
``` ```
## Skill Catalog
### Workflow Skills (核心工作流)
| Skill | 内部流水线 | 触发词 |
|-------|-----------|--------|
| `workflow-lite-planex` | explore → plan → confirm → execute | "lite-plan", 快速任务 |
| `workflow-plan` | session → context → convention → gen → verify | "workflow-plan", 正式规划 |
| `workflow-execute` | session discovery → task processing → commit | "workflow-execute", 执行 |
| `workflow-tdd-plan` | 6-phase TDD plan → verify | "tdd-plan", TDD 开发 |
| `workflow-test-fix` | session → context → analysis → gen → cycle | "test-fix", 测试修复 |
| `workflow-multi-cli-plan` | ACE context → CLI discussion → plan → execute | "multi-cli", 多CLI协作 |
| `workflow-skill-designer` | Meta-skill for designing workflow skills | "skill-designer" |
### Team Skills (团队协作)
Team Skills 使用 `team-worker` agent 架构Coordinator 编排流水线Workers 是加载了 role-spec 的 `team-worker` agents。
| Skill | 用途 | 架构 |
|-------|------|------|
| `team-planex` | 规划+执行 wave pipeline | planner + executor, 适合清晰 issue/roadmap |
| `team-lifecycle` | 完整生命周期 (spec/impl/test) | team-worker agents with role-specs |
| `team-lifecycle-v4` | 优化版生命周期 | Optimized pipeline |
| `team-lifecycle-v3` | 基础版生命周期 | All roles invoke unified skill |
| `team-coordinate` | 通用动态团队协调 | 运行时动态生成 role-specs |
| `team-coordinate` | 通用团队协调 v1 | Dynamic role generation |
| `team-brainstorm` | 团队头脑风暴 | Multi-perspective analysis |
| `team-frontend` | 前端开发团队 | Frontend specialists |
| `team-issue` | Issue 解决团队 | Issue resolution pipeline |
| `team-iterdev` | 迭代开发团队 | Iterative development |
| `team-review` | 代码扫描/漏洞审查 | Scanning + vulnerability review |
| `team-roadmap-dev` | Roadmap 驱动开发 | Requirement → implementation |
| `team-tech-debt` | 技术债务清理 | Debt identification + cleanup |
| `team-testing` | 测试团队 | Test planning + execution |
| `team-quality-assurance` | QA 团队 | Quality assurance pipeline |
| `team-uidesign` | UI 设计团队 | Design system + prototyping |
| `team-ultra-analyze` | 深度协作分析 | Deep collaborative analysis |
| `team-executor` | 轻量执行 (恢复会话) | Resume existing sessions |
| `team-executor` | 轻量执行 v2 | Improved session resumption |
### Standalone Skills (独立技能)
| Skill | 用途 |
|-------|------|
| `brainstorm` | 双模头脑风暴 (auto pipeline / single role) |
| `review-code` | 多维度代码审查 |
| `review-cycle` | 审查+自动修复编排 |
| `spec-generator` | 6阶段规格文档链 (product-brief → PRD → architecture → epics) |
| `issue-manage` | 交互式 Issue 管理 (CRUD) |
| `memory-capture` | 统一记忆捕获 (session compact / quick tip) |
| `memory-manage` | 统一记忆管理 (CLAUDE.md + documentation) |
| `command-generator` | 命令文件生成器 |
| `skill-generator` | Meta-skill: 创建新 Skill |
| `skill-tuning` | Skill 诊断与优化 |
## Workflow Mapping (CCW Auto-Route)
CCW 根据任务意图自动选择工作流级别(参考 [ccw.md](../../commands/ccw.md)
| 输入示例 | 类型 | 级别 | 流水线 |
|---------|------|------|--------|
| "Add API endpoint" | feature (low) | 2 | workflow-lite-planex → workflow-test-fix |
| "Fix login timeout" | bugfix | 2 | workflow-lite-planex → workflow-test-fix |
| "协作分析: 认证架构" | analyze-file | 3 | analyze-with-file → workflow-lite-planex |
| "重构 auth 模块" | refactor | 3 | workflow:refactor-cycle |
| "multi-cli: API设计" | multi-cli | 3 | workflow-multi-cli-plan → workflow-test-fix |
| "头脑风暴: 通知系统" | brainstorm | 4 | brainstorm-with-file → workflow-plan → workflow-execute |
| "roadmap: OAuth + 2FA" | roadmap | 4 | roadmap-with-file → team-planex |
| "specification: 用户系统" | spec-driven | 4 | spec-generator → workflow-plan → workflow-execute |
| "team planex: 用户系统" | team-planex | Team | team-planex |
## Slash Commands ## Slash Commands
```bash ```bash
@@ -116,6 +203,8 @@ Single source of truth: **[command.json](command.json)**
/ccw-help # General help entry /ccw-help # General help entry
/ccw-help search <keyword> # Search commands /ccw-help search <keyword> # Search commands
/ccw-help next <command> # Get next step suggestions /ccw-help next <command> # Get next step suggestions
/ccw-help skills # Browse skill catalog
/ccw-help teams # Browse team skills
/ccw-issue # Issue reporting /ccw-issue # Issue reporting
``` ```
@@ -128,6 +217,9 @@ Single source of truth: **[command.json](command.json)**
/ccw "头脑风暴: 用户通知系统" # → detect brainstorm, use brainstorm-with-file /ccw "头脑风暴: 用户通知系统" # → detect brainstorm, use brainstorm-with-file
/ccw "深度调试: 系统随机崩溃" # → detect debug-file, use debug-with-file /ccw "深度调试: 系统随机崩溃" # → detect debug-file, use debug-with-file
/ccw "协作分析: 认证架构设计" # → detect analyze-file, use analyze-with-file /ccw "协作分析: 认证架构设计" # → detect analyze-file, use analyze-with-file
/ccw "roadmap: OAuth + 2FA 路线图" # → roadmap-with-file → team-planex
/ccw "集成测试: 支付流程" # → integration-test-cycle
/ccw "重构 auth 模块" # → refactor-cycle
``` ```
## Maintenance ## Maintenance
@@ -135,6 +227,7 @@ Single source of truth: **[command.json](command.json)**
### Update Mechanism ### Update Mechanism
CCW-Help skill supports manual updates through user confirmation dialog. CCW-Help skill supports manual updates through user confirmation dialog.
Script scans `commands/`, `agents/`, and `skills/` directories to regenerate all indexes.
#### How to Update #### How to Update
@@ -153,18 +246,33 @@ cd D:/Claude_dms3/.claude/skills/ccw-help
python scripts/auto-update.py python scripts/auto-update.py
``` ```
This runs `analyze_commands.py` to scan commands/ and agents/ directories and regenerate `command.json`. This runs `analyze_commands.py` to scan commands/, agents/, and skills/ directories and regenerate `command.json` + all index files.
#### Update Scripts #### Update Scripts
- **`auto-update.py`**: Simple wrapper that runs analyze_commands.py - **`auto-update.py`**: Simple wrapper that runs analyze_commands.py
- **`analyze_commands.py`**: Scans directories and generates command index - **`analyze_commands.py`**: Scans directories and generates command/agent/skill indexes
#### Generated Index Files
| File | Content |
|------|---------|
| `command.json` | Master index: commands + agents + skills |
| `index/all-commands.json` | Flat command list |
| `index/all-agents.json` | Agent directory |
| `index/all-skills.json` | Skill directory with metadata |
| `index/skills-by-category.json` | Skills grouped by category |
| `index/by-category.json` | Commands by category |
| `index/by-use-case.json` | Commands by usage scenario |
| `index/essential-commands.json` | Core commands for onboarding |
| `index/command-relationships.json` | Command flow relationships |
## Statistics ## Statistics
- **Commands**: 50+ - **Commands**: 50+
- **Agents**: 16 - **Agents**: 22
- **Workflows**: 6 main levels + 3 with-file variants - **Skills**: 36+ (7 workflow, 19 team, 10+ standalone/utility)
- **Workflows**: 6 main levels + 5 with-file variants + 2 cycle variants
- **Essential**: 10 core commands - **Essential**: 10 core commands
## Core Principle ## Core Principle

File diff suppressed because it is too large Load Diff

View File

@@ -29,6 +29,11 @@
"description": "|", "description": "|",
"source": "../../../agents/cli-planning-agent.md" "source": "../../../agents/cli-planning-agent.md"
}, },
{
"name": "cli-roadmap-plan-agent",
"description": "|",
"source": "../../../agents/cli-roadmap-plan-agent.md"
},
{ {
"name": "code-developer", "name": "code-developer",
"description": "|", "description": "|",
@@ -74,6 +79,16 @@
"description": "|", "description": "|",
"source": "../../../agents/tdd-developer.md" "source": "../../../agents/tdd-developer.md"
}, },
{
"name": "team-worker",
"description": "|",
"source": "../../../agents/team-worker.md"
},
{
"name": "test-action-planning-agent",
"description": "|",
"source": "../../../agents/test-action-planning-agent.md"
},
{ {
"name": "test-context-search-agent", "name": "test-context-search-agent",
"description": "|", "description": "|",

View File

@@ -43,6 +43,72 @@
"difficulty": "Intermediate", "difficulty": "Intermediate",
"source": "../../../commands/cli/codex-review.md" "source": "../../../commands/cli/codex-review.md"
}, },
{
"name": "flow-create",
"command": "/flow-create",
"description": "Flow Template Generator - Generate workflow templates for meta-skill/flow-coordinator with interactive 3-phase workflow",
"arguments": "[template-name] [--output <path>]",
"category": "general",
"subcategory": null,
"usage_scenario": "implementation",
"difficulty": "Intermediate",
"source": "../../../commands/flow-create.md"
},
{
"name": "add",
"command": "/idaw:add",
"description": "Add IDAW tasks - manual creation or import from ccw issue",
"arguments": "[-y|--yes] [--from-issue <id>[,<id>,...]] \\\"description\\\" [--type <task_type>] [--priority <1-5>]",
"category": "idaw",
"subcategory": null,
"usage_scenario": "general",
"difficulty": "Intermediate",
"source": "../../../commands/idaw/add.md"
},
{
"name": "resume",
"command": "/idaw:resume",
"description": "Resume interrupted IDAW session from last checkpoint",
"arguments": "[-y|--yes] [session-id]",
"category": "idaw",
"subcategory": null,
"usage_scenario": "session-management",
"difficulty": "Intermediate",
"source": "../../../commands/idaw/resume.md"
},
{
"name": "run-coordinate",
"command": "/idaw:run-coordinate",
"description": "IDAW coordinator - execute task skill chains via external CLI with hook callbacks and git checkpoints",
"arguments": "[-y|--yes] [--task <id>[,<id>,...]] [--dry-run] [--tool <tool>]",
"category": "idaw",
"subcategory": null,
"usage_scenario": "general",
"difficulty": "Intermediate",
"source": "../../../commands/idaw/run-coordinate.md"
},
{
"name": "run",
"command": "/idaw:run",
"description": "IDAW orchestrator - execute task skill chains serially with git checkpoints",
"arguments": "[-y|--yes] [--task <id>[,<id>,...]] [--dry-run]",
"category": "idaw",
"subcategory": null,
"usage_scenario": "general",
"difficulty": "Intermediate",
"source": "../../../commands/idaw/run.md"
},
{
"name": "status",
"command": "/idaw:status",
"description": "View IDAW task and session progress",
"arguments": "[session-id]",
"category": "idaw",
"subcategory": null,
"usage_scenario": "session-management",
"difficulty": "Beginner",
"source": "../../../commands/idaw/status.md"
},
{ {
"name": "convert-to-plan", "name": "convert-to-plan",
"command": "/issue:convert-to-plan", "command": "/issue:convert-to-plan",
@@ -131,6 +197,17 @@
"difficulty": "Intermediate", "difficulty": "Intermediate",
"source": "../../../commands/issue/queue.md" "source": "../../../commands/issue/queue.md"
}, },
{
"name": "prepare",
"command": "/memory:prepare",
"description": "Delegate to universal-executor agent to analyze project via Gemini/Qwen CLI and return JSON core content package for task context",
"arguments": "[--tool gemini|qwen] \\\"task context description\\",
"category": "memory",
"subcategory": null,
"usage_scenario": "general",
"difficulty": "Intermediate",
"source": "../../../commands/memory/prepare.md"
},
{ {
"name": "style-skill-memory", "name": "style-skill-memory",
"command": "/memory:style-skill-memory", "command": "/memory:style-skill-memory",
@@ -175,6 +252,17 @@
"difficulty": "Intermediate", "difficulty": "Intermediate",
"source": "../../../commands/workflow/clean.md" "source": "../../../commands/workflow/clean.md"
}, },
{
"name": "workflow:collaborative-plan-with-file",
"command": "/workflow:collaborative-plan-with-file",
"description": "Collaborative planning with Plan Note - Understanding agent creates shared plan-note.md template, parallel agents fill pre-allocated sections, conflict detection without merge. Outputs executable plan-note.md.",
"arguments": "[-y|--yes] <task description> [--max-agents=5]",
"category": "workflow",
"subcategory": null,
"usage_scenario": "planning",
"difficulty": "Intermediate",
"source": "../../../commands/workflow/collaborative-plan-with-file.md"
},
{ {
"name": "debug-with-file", "name": "debug-with-file",
"command": "/workflow:debug-with-file", "command": "/workflow:debug-with-file",
@@ -186,17 +274,72 @@
"difficulty": "Intermediate", "difficulty": "Intermediate",
"source": "../../../commands/workflow/debug-with-file.md" "source": "../../../commands/workflow/debug-with-file.md"
}, },
{
"name": "init-guidelines",
"command": "/workflow:init-guidelines",
"description": "Interactive wizard to fill specs/*.md based on project analysis",
"arguments": "[--reset]",
"category": "workflow",
"subcategory": null,
"usage_scenario": "general",
"difficulty": "Intermediate",
"source": "../../../commands/workflow/init-guidelines.md"
},
{
"name": "init-specs",
"command": "/workflow:init-specs",
"description": "Interactive wizard to create individual specs or personal constraints with scope selection",
"arguments": "[--scope <global|project>] [--dimension <specs|personal>] [--category <general|exploration|planning|execution>]",
"category": "workflow",
"subcategory": null,
"usage_scenario": "general",
"difficulty": "Intermediate",
"source": "../../../commands/workflow/init-specs.md"
},
{ {
"name": "init", "name": "init",
"command": "/workflow:init", "command": "/workflow:init",
"description": "Initialize project-level state with intelligent project analysis using cli-explore-agent", "description": "Initialize project-level state with intelligent project analysis using cli-explore-agent",
"arguments": "[--regenerate]", "arguments": "[--regenerate] [--skip-specs]",
"category": "workflow", "category": "workflow",
"subcategory": null, "subcategory": null,
"usage_scenario": "general", "usage_scenario": "general",
"difficulty": "Intermediate", "difficulty": "Intermediate",
"source": "../../../commands/workflow/init.md" "source": "../../../commands/workflow/init.md"
}, },
{
"name": "integration-test-cycle",
"command": "/workflow:integration-test-cycle",
"description": "Self-iterating integration test workflow with codebase exploration, test development, autonomous test-fix cycles, and reflection-driven strategy adjustment",
"arguments": "[-y|--yes] [-c|--continue] [--max-iterations=N] \\\"module or feature description\\",
"category": "workflow",
"subcategory": null,
"usage_scenario": "testing",
"difficulty": "Intermediate",
"source": "../../../commands/workflow/integration-test-cycle.md"
},
{
"name": "refactor-cycle",
"command": "/workflow:refactor-cycle",
"description": "Tech debt discovery and self-iterating refactoring with multi-dimensional analysis, prioritized execution, regression validation, and reflection-driven adjustment",
"arguments": "[-y|--yes] [-c|--continue] [--scope=module|project] \\\"module or refactoring goal\\",
"category": "workflow",
"subcategory": null,
"usage_scenario": "general",
"difficulty": "Intermediate",
"source": "../../../commands/workflow/refactor-cycle.md"
},
{
"name": "roadmap-with-file",
"command": "/workflow:roadmap-with-file",
"description": "Strategic requirement roadmap with iterative decomposition and issue creation. Outputs roadmap.md (human-readable, single source) + issues.jsonl (machine-executable). Handoff to team-planex.",
"arguments": "[-y|--yes] [-c|--continue] [-m progressive|direct|auto] \\\"requirement description\\",
"category": "workflow",
"subcategory": null,
"usage_scenario": "general",
"difficulty": "Intermediate",
"source": "../../../commands/workflow/roadmap-with-file.md"
},
{ {
"name": "complete", "name": "complete",
"command": "/workflow:session:complete", "command": "/workflow:session:complete",
@@ -233,8 +376,8 @@
{ {
"name": "solidify", "name": "solidify",
"command": "/workflow:session:solidify", "command": "/workflow:session:solidify",
"description": "Crystallize session learnings and user-defined constraints into permanent project guidelines", "description": "Crystallize session learnings and user-defined constraints into permanent project guidelines, or compress recent memories",
"arguments": "[-y|--yes] [--type <convention|constraint|learning>] [--category <category>] \\\"rule or insight\\", "arguments": "[-y|--yes] [--type <convention|constraint|learning|compress>] [--category <category>] [--limit <N>] \\\"rule or insight\\",
"category": "workflow", "category": "workflow",
"subcategory": "session", "subcategory": "session",
"usage_scenario": "general", "usage_scenario": "general",
@@ -252,6 +395,17 @@
"difficulty": "Intermediate", "difficulty": "Intermediate",
"source": "../../../commands/workflow/session/start.md" "source": "../../../commands/workflow/session/start.md"
}, },
{
"name": "sync",
"command": "/workflow:session:sync",
"description": "Quick-sync session work to specs/*.md and project-tech",
"arguments": "[-y|--yes] [\\\"what was done\\\"]",
"category": "workflow",
"subcategory": "session",
"usage_scenario": "general",
"difficulty": "Intermediate",
"source": "../../../commands/workflow/session/sync.md"
},
{ {
"name": "animation-extract", "name": "animation-extract",
"command": "/workflow:ui-design:animation-extract", "command": "/workflow:ui-design:animation-extract",
@@ -366,7 +520,7 @@
"name": "unified-execute-with-file", "name": "unified-execute-with-file",
"command": "/workflow:unified-execute-with-file", "command": "/workflow:unified-execute-with-file",
"description": "Universal execution engine for consuming any planning/brainstorm/analysis output with minimal progress tracking, multi-agent coordination, and incremental execution", "description": "Universal execution engine for consuming any planning/brainstorm/analysis output with minimal progress tracking, multi-agent coordination, and incremental execution",
"arguments": "[-y|--yes] [-p|--plan <path>] [-m|--mode sequential|parallel] [\\\"execution context or task name\\\"]", "arguments": "[-y|--yes] [<path>[,<path2>] | -p|--plan <path>[,<path2>]] [--auto-commit] [--commit-prefix \\\"prefix\\\"] [\\\"execution context or task name\\\"]",
"category": "workflow", "category": "workflow",
"subcategory": null, "subcategory": null,
"usage_scenario": "implementation", "usage_scenario": "implementation",

View File

@@ -0,0 +1,352 @@
[
{
"name": "brainstorm",
"description": "Unified brainstorming skill with dual-mode operation - auto pipeline and single role analysis. Triggers on \"brainstorm\", \"头脑风暴\".",
"category": "standalone",
"is_team": false,
"has_phases": true,
"has_role_specs": false,
"version": "",
"source": "../../../skills/brainstorm/SKILL.md"
},
{
"name": "ccw-help",
"description": "CCW command help system. Search, browse, recommend commands, skills, teams. Triggers \"ccw-help\", \"ccw-issue\".",
"category": "utility",
"is_team": false,
"has_phases": false,
"has_role_specs": false,
"version": "8.0.0",
"source": "../../../skills/ccw-help/SKILL.md"
},
{
"name": "command-generator",
"description": "Command file generator - 5 phase workflow for creating Claude Code command files with YAML frontmatter. Generates .md command files for project or user scope. Triggers on \"create command\", \"new command\", \"command generator\".",
"category": "meta",
"is_team": false,
"has_phases": true,
"has_role_specs": false,
"version": "",
"source": "../../../skills/command-generator/SKILL.md"
},
{
"name": "issue-manage",
"description": "Interactive issue management with menu-driven CRUD operations. Use when managing issues, viewing issue status, editing issue fields, performing bulk operations, or viewing issue history. Triggers on \"manage issue\", \"list issues\", \"edit issue\", \"delete issue\", \"bulk update\", \"issue dashboard\", \"issue history\", \"completed issues\".",
"category": "utility",
"is_team": false,
"has_phases": false,
"has_role_specs": false,
"version": "",
"source": "../../../skills/issue-manage/SKILL.md"
},
{
"name": "memory-capture",
"description": "Unified memory capture with routing - session compact or quick tips. Triggers on \"memory capture\", \"compact session\", \"save session\", \"quick tip\", \"memory tips\", \"记录\", \"压缩会话\".",
"category": "utility",
"is_team": false,
"has_phases": true,
"has_role_specs": false,
"version": "",
"source": "../../../skills/memory-capture/SKILL.md"
},
{
"name": "memory-manage",
"description": "Unified memory management - CLAUDE.md updates and documentation generation with interactive routing. Triggers on \"memory manage\", \"update claude\", \"update memory\", \"generate docs\", \"更新记忆\", \"生成文档\".",
"category": "utility",
"is_team": false,
"has_phases": true,
"has_role_specs": false,
"version": "",
"source": "../../../skills/memory-manage/SKILL.md"
},
{
"name": "review-code",
"description": "Multi-dimensional code review with structured reports. Analyzes correctness, readability, performance, security, testing, and architecture. Triggers on \"review code\", \"code review\", \"审查代码\", \"代码审查\".",
"category": "review",
"is_team": false,
"has_phases": true,
"has_role_specs": false,
"version": "",
"source": "../../../skills/review-code/SKILL.md"
},
{
"name": "review-cycle",
"description": "Unified multi-dimensional code review with automated fix orchestration. Routes to session-based (git changes), module-based (path patterns), or fix mode. Triggers on \"workflow:review-cycle\", \"workflow:review-session-cycle\", \"workflow:review-module-cycle\", \"workflow:review-cycle-fix\".",
"category": "review",
"is_team": false,
"has_phases": true,
"has_role_specs": false,
"version": "",
"source": "../../../skills/review-cycle/SKILL.md"
},
{
"name": "skill-generator",
"description": "Meta-skill for creating new Claude Code skills with configurable execution modes. Supports sequential (fixed order) and autonomous (stateless) phase patterns. Use for skill scaffolding, skill creation, or building new workflows. Triggers on \"create skill\", \"new skill\", \"skill generator\".",
"category": "meta",
"is_team": false,
"has_phases": true,
"has_role_specs": false,
"version": "",
"source": "../../../skills/skill-generator/SKILL.md"
},
{
"name": "skill-tuning",
"description": "Universal skill diagnosis and optimization tool. Detect and fix skill execution issues including context explosion, long-tail forgetting, data flow disruption, and agent coordination failures. Supports Gemini CLI for deep analysis. Triggers on \"skill tuning\", \"tune skill\", \"skill diagnosis\", \"optimize skill\", \"skill debug\".",
"category": "meta",
"is_team": false,
"has_phases": true,
"has_role_specs": false,
"version": "",
"source": "../../../skills/skill-tuning/SKILL.md"
},
{
"name": "spec-generator",
"description": "Specification generator - 6 phase document chain producing product brief, PRD, architecture, and epics. Triggers on \"generate spec\", \"create specification\", \"spec generator\", \"workflow:spec\".",
"category": "meta",
"is_team": false,
"has_phases": true,
"has_role_specs": false,
"version": "",
"source": "../../../skills/spec-generator/SKILL.md"
},
{
"name": "team-arch-opt",
"description": "Unified team skill for architecture optimization. Uses team-worker agent architecture with role-spec files for domain logic. Coordinator orchestrates pipeline, workers are team-worker agents. Triggers on \"team arch-opt\".",
"category": "team",
"is_team": true,
"has_phases": false,
"has_role_specs": true,
"version": "",
"source": "../../../skills/team-arch-opt/SKILL.md"
},
{
"name": "team-brainstorm",
"description": "Unified team skill for brainstorming team. All roles invoke this skill with --role arg for role-specific execution. Triggers on \"team brainstorm\".",
"category": "team",
"is_team": true,
"has_phases": false,
"has_role_specs": false,
"version": "",
"source": "../../../skills/team-brainstorm/SKILL.md"
},
{
"name": "team-coordinate",
"description": "Universal team coordination skill with dynamic role generation. Uses team-worker agent architecture with role-spec files. Only coordinator is built-in -- all worker roles are generated at runtime as role-specs and spawned via team-worker agent. Beat/cadence model for orchestration. Triggers on \"Team Coordinate \".",
"category": "team",
"is_team": true,
"has_phases": false,
"has_role_specs": false,
"version": "",
"source": "../../../skills/team-coordinate/SKILL.md"
},
{
"name": "team-executor",
"description": "Lightweight session execution skill. Resumes existing team-coordinate sessions for pure execution via team-worker agents. No analysis, no role generation -- only loads and executes. Session path required. Triggers on \"Team Executor\".",
"category": "team",
"is_team": true,
"has_phases": false,
"has_role_specs": false,
"version": "",
"source": "../../../skills/team-executor/SKILL.md"
},
{
"name": "team-frontend",
"description": "Unified team skill for frontend development team. All roles invoke this skill with --role arg. Built-in ui-ux-pro-max design intelligence. Triggers on \"team frontend\".",
"category": "team",
"is_team": true,
"has_phases": false,
"has_role_specs": false,
"version": "",
"source": "../../../skills/team-frontend/SKILL.md"
},
{
"name": "team-issue",
"description": "Unified team skill for issue resolution. All roles invoke this skill with --role arg for role-specific execution. Triggers on \"team issue\".",
"category": "team",
"is_team": true,
"has_phases": false,
"has_role_specs": false,
"version": "",
"source": "../../../skills/team-issue/SKILL.md"
},
{
"name": "team-iterdev",
"description": "Unified team skill for iterative development team. All roles invoke this skill with --role arg for role-specific execution. Triggers on \"team iterdev\".",
"category": "team",
"is_team": true,
"has_phases": false,
"has_role_specs": false,
"version": "",
"source": "../../../skills/team-iterdev/SKILL.md"
},
{
"name": "team-lifecycle",
"description": "Unified team skill for full lifecycle - spec/impl/test. Uses team-worker agent architecture with role-spec files for domain logic. Coordinator orchestrates pipeline, workers are team-worker agents loaded with role-specific Phase 2-4 specs. Triggers on \"team lifecycle\".",
"category": "team",
"is_team": true,
"has_phases": false,
"has_role_specs": true,
"version": "",
"source": "../../../skills/team-lifecycle/SKILL.md"
},
{
"name": "team-perf-opt",
"description": "Unified team skill for performance optimization. Uses team-worker agent architecture with role-spec files for domain logic. Coordinator orchestrates pipeline, workers are team-worker agents. Triggers on \"team perf-opt\".",
"category": "team",
"is_team": true,
"has_phases": false,
"has_role_specs": true,
"version": "",
"source": "../../../skills/team-perf-opt/SKILL.md"
},
{
"name": "team-planex",
"description": "Unified team skill for plan-and-execute pipeline. Uses team-worker agent architecture with role-spec files for domain logic. Coordinator orchestrates pipeline, workers are team-worker agents. Triggers on \"team planex\".",
"category": "team",
"is_team": true,
"has_phases": false,
"has_role_specs": true,
"version": "",
"source": "../../../skills/team-planex/SKILL.md"
},
{
"name": "team-quality-assurance",
"description": "Unified team skill for quality assurance team. All roles invoke this skill with --role arg for role-specific execution. Triggers on \"team quality-assurance\", \"team qa\".",
"category": "team",
"is_team": true,
"has_phases": false,
"has_role_specs": false,
"version": "",
"source": "../../../skills/team-quality-assurance/SKILL.md"
},
{
"name": "team-review",
"description": "Unified team skill for code scanning, vulnerability review, optimization suggestions, and automated fix. 4-role team: coordinator, scanner, reviewer, fixer. Triggers on team-review.",
"category": "team",
"is_team": false,
"has_phases": false,
"has_role_specs": false,
"version": "",
"source": "../../../skills/team-review/SKILL.md"
},
{
"name": "team-roadmap-dev",
"description": "Unified team skill for roadmap-driven development workflow. Coordinator discusses roadmap with user, then dispatches phased execution pipeline (plan -> execute -> verify). All roles invoke this skill with --role arg. Triggers on \"team roadmap-dev\".",
"category": "team",
"is_team": true,
"has_phases": false,
"has_role_specs": false,
"version": "",
"source": "../../../skills/team-roadmap-dev/SKILL.md"
},
{
"name": "team-tech-debt",
"description": "Unified team skill for tech debt identification and cleanup. All roles invoke this skill with --role arg for role-specific execution. Triggers on \"team tech-debt\", \"tech debt cleanup\", \"技术债务\".",
"category": "team",
"is_team": true,
"has_phases": false,
"has_role_specs": false,
"version": "",
"source": "../../../skills/team-tech-debt/SKILL.md"
},
{
"name": "team-testing",
"description": "Unified team skill for testing team. All roles invoke this skill with --role arg for role-specific execution. Triggers on \"team testing\".",
"category": "team",
"is_team": true,
"has_phases": false,
"has_role_specs": false,
"version": "",
"source": "../../../skills/team-testing/SKILL.md"
},
{
"name": "team-uidesign",
"description": "Unified team skill for UI design team. All roles invoke this skill with --role arg for role-specific execution. CP-9 Dual-Track design+implementation.",
"category": "team",
"is_team": true,
"has_phases": false,
"has_role_specs": false,
"version": "",
"source": "../../../skills/team-uidesign/SKILL.md"
},
{
"name": "team-ultra-analyze",
"description": "Unified team skill for deep collaborative analysis. All roles invoke this skill with --role arg for role-specific execution. Triggers on \"team ultra-analyze\", \"team analyze\".",
"category": "team",
"is_team": true,
"has_phases": false,
"has_role_specs": false,
"version": "",
"source": "../../../skills/team-ultra-analyze/SKILL.md"
},
{
"name": "workflow-execute",
"description": "Coordinate agent execution for workflow tasks with automatic session discovery, parallel task processing, and status tracking. Triggers on \"workflow-execute\".",
"category": "workflow",
"is_team": false,
"has_phases": true,
"has_role_specs": false,
"version": "",
"source": "../../../skills/workflow-execute/SKILL.md"
},
{
"name": "workflow-lite-planex",
"description": "Lightweight planning and execution skill (Phase 1: plan, Phase 2: execute). Triggers on \"workflow-lite-planex\".",
"category": "workflow",
"is_team": false,
"has_phases": true,
"has_role_specs": false,
"version": "",
"source": "../../../skills/workflow-lite-planex/SKILL.md"
},
{
"name": "workflow-multi-cli-plan",
"description": "Multi-CLI collaborative planning and execution skill with integrated execution phase. Triggers on \"workflow-multi-cli-plan\".",
"category": "workflow",
"is_team": false,
"has_phases": true,
"has_role_specs": false,
"version": "",
"source": "../../../skills/workflow-multi-cli-plan/SKILL.md"
},
{
"name": "workflow-plan",
"description": "Unified planning skill - 4-phase planning workflow, plan verification, and interactive replanning. Triggers on \"workflow-plan\", \"workflow-plan-verify\", \"workflow:replan\".",
"category": "workflow",
"is_team": false,
"has_phases": true,
"has_role_specs": false,
"version": "",
"source": "../../../skills/workflow-plan/SKILL.md"
},
{
"name": "workflow-skill-designer",
"description": "Meta-skill for designing orchestrator+phases structured workflow skills. Creates SKILL.md coordinator with progressive phase loading, TodoWrite patterns, and data flow. Triggers on \"design workflow skill\", \"create workflow skill\", \"workflow skill designer\".",
"category": "workflow",
"is_team": false,
"has_phases": true,
"has_role_specs": false,
"version": "",
"source": "../../../skills/workflow-skill-designer/SKILL.md"
},
{
"name": "workflow-tdd-plan",
"description": "Unified TDD workflow skill combining 6-phase TDD planning with Red-Green-Refactor task chain generation, and 4-phase TDD verification with compliance reporting. Triggers on \"workflow-tdd-plan\", \"workflow-tdd-verify\".",
"category": "workflow",
"is_team": false,
"has_phases": true,
"has_role_specs": false,
"version": "",
"source": "../../../skills/workflow-tdd-plan/SKILL.md"
},
{
"name": "workflow-test-fix",
"description": "Unified test-fix pipeline combining test generation (session, context, analysis, task gen) with iterative test-cycle execution (adaptive strategy, progressive testing, CLI fallback). Triggers on \"workflow-test-fix\", \"workflow-test-fix\", \"test fix workflow\".",
"category": "workflow",
"is_team": false,
"has_phases": true,
"has_role_specs": false,
"version": "",
"source": "../../../skills/workflow-test-fix/SKILL.md"
}
]

View File

@@ -22,6 +22,17 @@
"usage_scenario": "general", "usage_scenario": "general",
"difficulty": "Intermediate", "difficulty": "Intermediate",
"source": "../../../commands/ccw.md" "source": "../../../commands/ccw.md"
},
{
"name": "flow-create",
"command": "/flow-create",
"description": "",
"arguments": "",
"category": "general",
"subcategory": null,
"usage_scenario": "implementation",
"difficulty": "Intermediate",
"source": "../../../commands/flow-create.md"
} }
] ]
}, },
@@ -51,6 +62,65 @@
} }
] ]
}, },
"idaw": {
"_root": [
{
"name": "add",
"command": "/idaw:add",
"description": "Add IDAW tasks - manual creation or import from ccw issue",
"arguments": "[-y|--yes] [--from-issue <id>[,<id>,...]] \\\"description\\\" [--type <task_type>] [--priority <1-5>]",
"category": "idaw",
"subcategory": null,
"usage_scenario": "general",
"difficulty": "Intermediate",
"source": "../../../commands/idaw/add.md"
},
{
"name": "resume",
"command": "/idaw:resume",
"description": "Resume interrupted IDAW session from last checkpoint",
"arguments": "[-y|--yes] [session-id]",
"category": "idaw",
"subcategory": null,
"usage_scenario": "session-management",
"difficulty": "Intermediate",
"source": "../../../commands/idaw/resume.md"
},
{
"name": "run-coordinate",
"command": "/idaw:run-coordinate",
"description": "IDAW coordinator - execute task skill chains via external CLI with hook callbacks and git checkpoints",
"arguments": "[-y|--yes] [--task <id>[,<id>,...]] [--dry-run] [--tool <tool>]",
"category": "idaw",
"subcategory": null,
"usage_scenario": "general",
"difficulty": "Intermediate",
"source": "../../../commands/idaw/run-coordinate.md"
},
{
"name": "run",
"command": "/idaw:run",
"description": "IDAW orchestrator - execute task skill chains serially with git checkpoints",
"arguments": "[-y|--yes] [--task <id>[,<id>,...]] [--dry-run]",
"category": "idaw",
"subcategory": null,
"usage_scenario": "general",
"difficulty": "Intermediate",
"source": "../../../commands/idaw/run.md"
},
{
"name": "status",
"command": "/idaw:status",
"description": "View IDAW task and session progress",
"arguments": "[session-id]",
"category": "idaw",
"subcategory": null,
"usage_scenario": "session-management",
"difficulty": "Beginner",
"source": "../../../commands/idaw/status.md"
}
]
},
"issue": { "issue": {
"_root": [ "_root": [
{ {
@@ -145,6 +215,17 @@
}, },
"memory": { "memory": {
"_root": [ "_root": [
{
"name": "prepare",
"command": "/memory:prepare",
"description": "Delegate to universal-executor agent to analyze project via Gemini/Qwen CLI and return JSON core content package for task context",
"arguments": "[--tool gemini|qwen] \\\"task context description\\",
"category": "memory",
"subcategory": null,
"usage_scenario": "general",
"difficulty": "Intermediate",
"source": "../../../commands/memory/prepare.md"
},
{ {
"name": "style-skill-memory", "name": "style-skill-memory",
"command": "/memory:style-skill-memory", "command": "/memory:style-skill-memory",
@@ -193,6 +274,17 @@
"difficulty": "Intermediate", "difficulty": "Intermediate",
"source": "../../../commands/workflow/clean.md" "source": "../../../commands/workflow/clean.md"
}, },
{
"name": "workflow:collaborative-plan-with-file",
"command": "/workflow:collaborative-plan-with-file",
"description": "Collaborative planning with Plan Note - Understanding agent creates shared plan-note.md template, parallel agents fill pre-allocated sections, conflict detection without merge. Outputs executable plan-note.md.",
"arguments": "[-y|--yes] <task description> [--max-agents=5]",
"category": "workflow",
"subcategory": null,
"usage_scenario": "planning",
"difficulty": "Intermediate",
"source": "../../../commands/workflow/collaborative-plan-with-file.md"
},
{ {
"name": "debug-with-file", "name": "debug-with-file",
"command": "/workflow:debug-with-file", "command": "/workflow:debug-with-file",
@@ -204,22 +296,77 @@
"difficulty": "Intermediate", "difficulty": "Intermediate",
"source": "../../../commands/workflow/debug-with-file.md" "source": "../../../commands/workflow/debug-with-file.md"
}, },
{
"name": "init-guidelines",
"command": "/workflow:init-guidelines",
"description": "Interactive wizard to fill specs/*.md based on project analysis",
"arguments": "[--reset]",
"category": "workflow",
"subcategory": null,
"usage_scenario": "general",
"difficulty": "Intermediate",
"source": "../../../commands/workflow/init-guidelines.md"
},
{
"name": "init-specs",
"command": "/workflow:init-specs",
"description": "Interactive wizard to create individual specs or personal constraints with scope selection",
"arguments": "[--scope <global|project>] [--dimension <specs|personal>] [--category <general|exploration|planning|execution>]",
"category": "workflow",
"subcategory": null,
"usage_scenario": "general",
"difficulty": "Intermediate",
"source": "../../../commands/workflow/init-specs.md"
},
{ {
"name": "init", "name": "init",
"command": "/workflow:init", "command": "/workflow:init",
"description": "Initialize project-level state with intelligent project analysis using cli-explore-agent", "description": "Initialize project-level state with intelligent project analysis using cli-explore-agent",
"arguments": "[--regenerate]", "arguments": "[--regenerate] [--skip-specs]",
"category": "workflow", "category": "workflow",
"subcategory": null, "subcategory": null,
"usage_scenario": "general", "usage_scenario": "general",
"difficulty": "Intermediate", "difficulty": "Intermediate",
"source": "../../../commands/workflow/init.md" "source": "../../../commands/workflow/init.md"
}, },
{
"name": "integration-test-cycle",
"command": "/workflow:integration-test-cycle",
"description": "Self-iterating integration test workflow with codebase exploration, test development, autonomous test-fix cycles, and reflection-driven strategy adjustment",
"arguments": "[-y|--yes] [-c|--continue] [--max-iterations=N] \\\"module or feature description\\",
"category": "workflow",
"subcategory": null,
"usage_scenario": "testing",
"difficulty": "Intermediate",
"source": "../../../commands/workflow/integration-test-cycle.md"
},
{
"name": "refactor-cycle",
"command": "/workflow:refactor-cycle",
"description": "Tech debt discovery and self-iterating refactoring with multi-dimensional analysis, prioritized execution, regression validation, and reflection-driven adjustment",
"arguments": "[-y|--yes] [-c|--continue] [--scope=module|project] \\\"module or refactoring goal\\",
"category": "workflow",
"subcategory": null,
"usage_scenario": "general",
"difficulty": "Intermediate",
"source": "../../../commands/workflow/refactor-cycle.md"
},
{
"name": "roadmap-with-file",
"command": "/workflow:roadmap-with-file",
"description": "Strategic requirement roadmap with iterative decomposition and issue creation. Outputs roadmap.md (human-readable, single source) + issues.jsonl (machine-executable). Handoff to team-planex.",
"arguments": "[-y|--yes] [-c|--continue] [-m progressive|direct|auto] \\\"requirement description\\",
"category": "workflow",
"subcategory": null,
"usage_scenario": "general",
"difficulty": "Intermediate",
"source": "../../../commands/workflow/roadmap-with-file.md"
},
{ {
"name": "unified-execute-with-file", "name": "unified-execute-with-file",
"command": "/workflow:unified-execute-with-file", "command": "/workflow:unified-execute-with-file",
"description": "Universal execution engine for consuming any planning/brainstorm/analysis output with minimal progress tracking, multi-agent coordination, and incremental execution", "description": "Universal execution engine for consuming any planning/brainstorm/analysis output with minimal progress tracking, multi-agent coordination, and incremental execution",
"arguments": "[-y|--yes] [-p|--plan <path>] [-m|--mode sequential|parallel] [\\\"execution context or task name\\\"]", "arguments": "[-y|--yes] [<path>[,<path2>] | -p|--plan <path>[,<path2>]] [--auto-commit] [--commit-prefix \\\"prefix\\\"] [\\\"execution context or task name\\\"]",
"category": "workflow", "category": "workflow",
"subcategory": null, "subcategory": null,
"usage_scenario": "implementation", "usage_scenario": "implementation",
@@ -264,8 +411,8 @@
{ {
"name": "solidify", "name": "solidify",
"command": "/workflow:session:solidify", "command": "/workflow:session:solidify",
"description": "Crystallize session learnings and user-defined constraints into permanent project guidelines", "description": "Crystallize session learnings and user-defined constraints into permanent project guidelines, or compress recent memories",
"arguments": "[-y|--yes] [--type <convention|constraint|learning>] [--category <category>] \\\"rule or insight\\", "arguments": "[-y|--yes] [--type <convention|constraint|learning|compress>] [--category <category>] [--limit <N>] \\\"rule or insight\\",
"category": "workflow", "category": "workflow",
"subcategory": "session", "subcategory": "session",
"usage_scenario": "general", "usage_scenario": "general",
@@ -282,6 +429,17 @@
"usage_scenario": "general", "usage_scenario": "general",
"difficulty": "Intermediate", "difficulty": "Intermediate",
"source": "../../../commands/workflow/session/start.md" "source": "../../../commands/workflow/session/start.md"
},
{
"name": "sync",
"command": "/workflow:session:sync",
"description": "Quick-sync session work to specs/*.md and project-tech",
"arguments": "[-y|--yes] [\\\"what was done\\\"]",
"category": "workflow",
"subcategory": "session",
"usage_scenario": "general",
"difficulty": "Intermediate",
"source": "../../../commands/workflow/session/sync.md"
} }
], ],
"ui-design": [ "ui-design": [

View File

@@ -33,6 +33,39 @@
"difficulty": "Intermediate", "difficulty": "Intermediate",
"source": "../../../commands/cli/cli-init.md" "source": "../../../commands/cli/cli-init.md"
}, },
{
"name": "add",
"command": "/idaw:add",
"description": "Add IDAW tasks - manual creation or import from ccw issue",
"arguments": "[-y|--yes] [--from-issue <id>[,<id>,...]] \\\"description\\\" [--type <task_type>] [--priority <1-5>]",
"category": "idaw",
"subcategory": null,
"usage_scenario": "general",
"difficulty": "Intermediate",
"source": "../../../commands/idaw/add.md"
},
{
"name": "run-coordinate",
"command": "/idaw:run-coordinate",
"description": "IDAW coordinator - execute task skill chains via external CLI with hook callbacks and git checkpoints",
"arguments": "[-y|--yes] [--task <id>[,<id>,...]] [--dry-run] [--tool <tool>]",
"category": "idaw",
"subcategory": null,
"usage_scenario": "general",
"difficulty": "Intermediate",
"source": "../../../commands/idaw/run-coordinate.md"
},
{
"name": "run",
"command": "/idaw:run",
"description": "IDAW orchestrator - execute task skill chains serially with git checkpoints",
"arguments": "[-y|--yes] [--task <id>[,<id>,...]] [--dry-run]",
"category": "idaw",
"subcategory": null,
"usage_scenario": "general",
"difficulty": "Intermediate",
"source": "../../../commands/idaw/run.md"
},
{ {
"name": "issue:discover-by-prompt", "name": "issue:discover-by-prompt",
"command": "/issue:discover-by-prompt", "command": "/issue:discover-by-prompt",
@@ -77,6 +110,17 @@
"difficulty": "Intermediate", "difficulty": "Intermediate",
"source": "../../../commands/issue/queue.md" "source": "../../../commands/issue/queue.md"
}, },
{
"name": "prepare",
"command": "/memory:prepare",
"description": "Delegate to universal-executor agent to analyze project via Gemini/Qwen CLI and return JSON core content package for task context",
"arguments": "[--tool gemini|qwen] \\\"task context description\\",
"category": "memory",
"subcategory": null,
"usage_scenario": "general",
"difficulty": "Intermediate",
"source": "../../../commands/memory/prepare.md"
},
{ {
"name": "clean", "name": "clean",
"command": "/workflow:clean", "command": "/workflow:clean",
@@ -99,17 +143,61 @@
"difficulty": "Intermediate", "difficulty": "Intermediate",
"source": "../../../commands/workflow/debug-with-file.md" "source": "../../../commands/workflow/debug-with-file.md"
}, },
{
"name": "init-guidelines",
"command": "/workflow:init-guidelines",
"description": "Interactive wizard to fill specs/*.md based on project analysis",
"arguments": "[--reset]",
"category": "workflow",
"subcategory": null,
"usage_scenario": "general",
"difficulty": "Intermediate",
"source": "../../../commands/workflow/init-guidelines.md"
},
{
"name": "init-specs",
"command": "/workflow:init-specs",
"description": "Interactive wizard to create individual specs or personal constraints with scope selection",
"arguments": "[--scope <global|project>] [--dimension <specs|personal>] [--category <general|exploration|planning|execution>]",
"category": "workflow",
"subcategory": null,
"usage_scenario": "general",
"difficulty": "Intermediate",
"source": "../../../commands/workflow/init-specs.md"
},
{ {
"name": "init", "name": "init",
"command": "/workflow:init", "command": "/workflow:init",
"description": "Initialize project-level state with intelligent project analysis using cli-explore-agent", "description": "Initialize project-level state with intelligent project analysis using cli-explore-agent",
"arguments": "[--regenerate]", "arguments": "[--regenerate] [--skip-specs]",
"category": "workflow", "category": "workflow",
"subcategory": null, "subcategory": null,
"usage_scenario": "general", "usage_scenario": "general",
"difficulty": "Intermediate", "difficulty": "Intermediate",
"source": "../../../commands/workflow/init.md" "source": "../../../commands/workflow/init.md"
}, },
{
"name": "refactor-cycle",
"command": "/workflow:refactor-cycle",
"description": "Tech debt discovery and self-iterating refactoring with multi-dimensional analysis, prioritized execution, regression validation, and reflection-driven adjustment",
"arguments": "[-y|--yes] [-c|--continue] [--scope=module|project] \\\"module or refactoring goal\\",
"category": "workflow",
"subcategory": null,
"usage_scenario": "general",
"difficulty": "Intermediate",
"source": "../../../commands/workflow/refactor-cycle.md"
},
{
"name": "roadmap-with-file",
"command": "/workflow:roadmap-with-file",
"description": "Strategic requirement roadmap with iterative decomposition and issue creation. Outputs roadmap.md (human-readable, single source) + issues.jsonl (machine-executable). Handoff to team-planex.",
"arguments": "[-y|--yes] [-c|--continue] [-m progressive|direct|auto] \\\"requirement description\\",
"category": "workflow",
"subcategory": null,
"usage_scenario": "general",
"difficulty": "Intermediate",
"source": "../../../commands/workflow/roadmap-with-file.md"
},
{ {
"name": "list", "name": "list",
"command": "/workflow:session:list", "command": "/workflow:session:list",
@@ -124,8 +212,8 @@
{ {
"name": "solidify", "name": "solidify",
"command": "/workflow:session:solidify", "command": "/workflow:session:solidify",
"description": "Crystallize session learnings and user-defined constraints into permanent project guidelines", "description": "Crystallize session learnings and user-defined constraints into permanent project guidelines, or compress recent memories",
"arguments": "[-y|--yes] [--type <convention|constraint|learning>] [--category <category>] \\\"rule or insight\\", "arguments": "[-y|--yes] [--type <convention|constraint|learning|compress>] [--category <category>] [--limit <N>] \\\"rule or insight\\",
"category": "workflow", "category": "workflow",
"subcategory": "session", "subcategory": "session",
"usage_scenario": "general", "usage_scenario": "general",
@@ -143,6 +231,17 @@
"difficulty": "Intermediate", "difficulty": "Intermediate",
"source": "../../../commands/workflow/session/start.md" "source": "../../../commands/workflow/session/start.md"
}, },
{
"name": "sync",
"command": "/workflow:session:sync",
"description": "Quick-sync session work to specs/*.md and project-tech",
"arguments": "[-y|--yes] [\\\"what was done\\\"]",
"category": "workflow",
"subcategory": "session",
"usage_scenario": "general",
"difficulty": "Intermediate",
"source": "../../../commands/workflow/session/sync.md"
},
{ {
"name": "animation-extract", "name": "animation-extract",
"command": "/workflow:ui-design:animation-extract", "command": "/workflow:ui-design:animation-extract",
@@ -223,6 +322,98 @@
"source": "../../../commands/workflow/analyze-with-file.md" "source": "../../../commands/workflow/analyze-with-file.md"
} }
], ],
"implementation": [
{
"name": "flow-create",
"command": "/flow-create",
"description": "",
"arguments": "",
"category": "general",
"subcategory": null,
"usage_scenario": "implementation",
"difficulty": "Intermediate",
"source": "../../../commands/flow-create.md"
},
{
"name": "execute",
"command": "/issue:execute",
"description": "Execute queue with DAG-based parallel orchestration (one commit per solution)",
"arguments": "[-y|--yes] --queue <queue-id> [--worktree [<existing-path>]]",
"category": "issue",
"subcategory": null,
"usage_scenario": "implementation",
"difficulty": "Intermediate",
"source": "../../../commands/issue/execute.md"
},
{
"name": "generate",
"command": "/workflow:ui-design:generate",
"description": "Assemble UI prototypes by combining layout templates with design tokens (default animation support), pure assembler without new content generation",
"arguments": "[--design-id <id>] [--session <id>]",
"category": "workflow",
"subcategory": "ui-design",
"usage_scenario": "implementation",
"difficulty": "Intermediate",
"source": "../../../commands/workflow/ui-design/generate.md"
},
{
"name": "unified-execute-with-file",
"command": "/workflow:unified-execute-with-file",
"description": "Universal execution engine for consuming any planning/brainstorm/analysis output with minimal progress tracking, multi-agent coordination, and incremental execution",
"arguments": "[-y|--yes] [<path>[,<path2>] | -p|--plan <path>[,<path2>]] [--auto-commit] [--commit-prefix \\\"prefix\\\"] [\\\"execution context or task name\\\"]",
"category": "workflow",
"subcategory": null,
"usage_scenario": "implementation",
"difficulty": "Intermediate",
"source": "../../../commands/workflow/unified-execute-with-file.md"
}
],
"session-management": [
{
"name": "resume",
"command": "/idaw:resume",
"description": "Resume interrupted IDAW session from last checkpoint",
"arguments": "[-y|--yes] [session-id]",
"category": "idaw",
"subcategory": null,
"usage_scenario": "session-management",
"difficulty": "Intermediate",
"source": "../../../commands/idaw/resume.md"
},
{
"name": "status",
"command": "/idaw:status",
"description": "View IDAW task and session progress",
"arguments": "[session-id]",
"category": "idaw",
"subcategory": null,
"usage_scenario": "session-management",
"difficulty": "Beginner",
"source": "../../../commands/idaw/status.md"
},
{
"name": "complete",
"command": "/workflow:session:complete",
"description": "Mark active workflow session as complete, archive with lessons learned, update manifest, remove active flag",
"arguments": "[-y|--yes] [--detailed]",
"category": "workflow",
"subcategory": "session",
"usage_scenario": "session-management",
"difficulty": "Intermediate",
"source": "../../../commands/workflow/session/complete.md"
},
{
"name": "resume",
"command": "/workflow:session:resume",
"description": "Resume the most recently paused workflow session with automatic session discovery and status update",
"arguments": "",
"category": "workflow",
"subcategory": "session",
"usage_scenario": "session-management",
"difficulty": "Intermediate",
"source": "../../../commands/workflow/session/resume.md"
}
],
"planning": [ "planning": [
{ {
"name": "convert-to-plan", "name": "convert-to-plan",
@@ -268,6 +459,17 @@
"difficulty": "Intermediate", "difficulty": "Intermediate",
"source": "../../../commands/workflow/brainstorm-with-file.md" "source": "../../../commands/workflow/brainstorm-with-file.md"
}, },
{
"name": "workflow:collaborative-plan-with-file",
"command": "/workflow:collaborative-plan-with-file",
"description": "Collaborative planning with Plan Note - Understanding agent creates shared plan-note.md template, parallel agents fill pre-allocated sections, conflict detection without merge. Outputs executable plan-note.md.",
"arguments": "[-y|--yes] <task description> [--max-agents=5]",
"category": "workflow",
"subcategory": null,
"usage_scenario": "planning",
"difficulty": "Intermediate",
"source": "../../../commands/workflow/collaborative-plan-with-file.md"
},
{ {
"name": "workflow:ui-design:codify-style", "name": "workflow:ui-design:codify-style",
"command": "/workflow:ui-design:codify-style", "command": "/workflow:ui-design:codify-style",
@@ -313,41 +515,6 @@
"source": "../../../commands/workflow/ui-design/reference-page-generator.md" "source": "../../../commands/workflow/ui-design/reference-page-generator.md"
} }
], ],
"implementation": [
{
"name": "execute",
"command": "/issue:execute",
"description": "Execute queue with DAG-based parallel orchestration (one commit per solution)",
"arguments": "[-y|--yes] --queue <queue-id> [--worktree [<existing-path>]]",
"category": "issue",
"subcategory": null,
"usage_scenario": "implementation",
"difficulty": "Intermediate",
"source": "../../../commands/issue/execute.md"
},
{
"name": "generate",
"command": "/workflow:ui-design:generate",
"description": "Assemble UI prototypes by combining layout templates with design tokens (default animation support), pure assembler without new content generation",
"arguments": "[--design-id <id>] [--session <id>]",
"category": "workflow",
"subcategory": "ui-design",
"usage_scenario": "implementation",
"difficulty": "Intermediate",
"source": "../../../commands/workflow/ui-design/generate.md"
},
{
"name": "unified-execute-with-file",
"command": "/workflow:unified-execute-with-file",
"description": "Universal execution engine for consuming any planning/brainstorm/analysis output with minimal progress tracking, multi-agent coordination, and incremental execution",
"arguments": "[-y|--yes] [-p|--plan <path>] [-m|--mode sequential|parallel] [\\\"execution context or task name\\\"]",
"category": "workflow",
"subcategory": null,
"usage_scenario": "implementation",
"difficulty": "Intermediate",
"source": "../../../commands/workflow/unified-execute-with-file.md"
}
],
"documentation": [ "documentation": [
{ {
"name": "style-skill-memory", "name": "style-skill-memory",
@@ -361,28 +528,17 @@
"source": "../../../commands/memory/style-skill-memory.md" "source": "../../../commands/memory/style-skill-memory.md"
} }
], ],
"session-management": [ "testing": [
{ {
"name": "complete", "name": "integration-test-cycle",
"command": "/workflow:session:complete", "command": "/workflow:integration-test-cycle",
"description": "Mark active workflow session as complete, archive with lessons learned, update manifest, remove active flag", "description": "Self-iterating integration test workflow with codebase exploration, test development, autonomous test-fix cycles, and reflection-driven strategy adjustment",
"arguments": "[-y|--yes] [--detailed]", "arguments": "[-y|--yes] [-c|--continue] [--max-iterations=N] \\\"module or feature description\\",
"category": "workflow", "category": "workflow",
"subcategory": "session", "subcategory": null,
"usage_scenario": "session-management", "usage_scenario": "testing",
"difficulty": "Intermediate", "difficulty": "Intermediate",
"source": "../../../commands/workflow/session/complete.md" "source": "../../../commands/workflow/integration-test-cycle.md"
},
{
"name": "resume",
"command": "/workflow:session:resume",
"description": "Resume the most recently paused workflow session with automatic session discovery and status update",
"arguments": "",
"category": "workflow",
"subcategory": "session",
"usage_scenario": "session-management",
"difficulty": "Intermediate",
"source": "../../../commands/workflow/session/resume.md"
} }
] ]
} }

View File

@@ -1,6 +1,64 @@
{ {
"workflow-plan": {
"calls_internally": [
"workflow:session:start"
],
"next_steps": [
"workflow-plan-verify",
"workflow:session:list",
"workflow:unified-execute-with-file"
],
"alternatives": [],
"prerequisites": []
},
"workflow-tdd-plan": {
"calls_internally": [
"workflow:session:start"
],
"next_steps": [
"workflow-tdd-verify",
"workflow:session:list",
"workflow:unified-execute-with-file"
],
"alternatives": [],
"prerequisites": []
},
"workflow:unified-execute-with-file": {
"prerequisites": [
"workflow-plan",
"workflow-tdd-plan"
],
"related": [
"workflow:session:list",
"workflow:session:resume"
],
"next_steps": [
"review-cycle",
"workflow-test-fix"
]
},
"workflow-plan-verify": {
"prerequisites": [
"workflow-plan"
],
"next_steps": [
"workflow:unified-execute-with-file"
],
"related": [
"workflow:session:list"
]
},
"workflow-tdd-verify": {
"prerequisites": [
"workflow:unified-execute-with-file"
],
"related": []
},
"workflow:session:start": { "workflow:session:start": {
"next_steps": [], "next_steps": [
"workflow-plan",
"workflow:unified-execute-with-file"
],
"related": [ "related": [
"workflow:session:list", "workflow:session:list",
"workflow:session:resume" "workflow:session:resume"
@@ -11,5 +69,23 @@
"related": [ "related": [
"workflow:session:list" "workflow:session:list"
] ]
},
"workflow-lite-planex": {
"calls_internally": [],
"next_steps": [
"workflow:session:list"
],
"alternatives": [
"workflow-plan"
],
"prerequisites": []
},
"review-cycle": {
"prerequisites": [
"workflow:unified-execute-with-file"
],
"related": [
"workflow-test-fix"
]
} }
} }

View File

@@ -0,0 +1,364 @@
{
"standalone": [
{
"name": "brainstorm",
"description": "Unified brainstorming skill with dual-mode operation - auto pipeline and single role analysis. Triggers on \"brainstorm\", \"头脑风暴\".",
"category": "standalone",
"is_team": false,
"has_phases": true,
"has_role_specs": false,
"version": "",
"source": "../../../skills/brainstorm/SKILL.md"
}
],
"meta": [
{
"name": "command-generator",
"description": "Command file generator - 5 phase workflow for creating Claude Code command files with YAML frontmatter. Generates .md command files for project or user scope. Triggers on \"create command\", \"new command\", \"command generator\".",
"category": "meta",
"is_team": false,
"has_phases": true,
"has_role_specs": false,
"version": "",
"source": "../../../skills/command-generator/SKILL.md"
},
{
"name": "skill-generator",
"description": "Meta-skill for creating new Claude Code skills with configurable execution modes. Supports sequential (fixed order) and autonomous (stateless) phase patterns. Use for skill scaffolding, skill creation, or building new workflows. Triggers on \"create skill\", \"new skill\", \"skill generator\".",
"category": "meta",
"is_team": false,
"has_phases": true,
"has_role_specs": false,
"version": "",
"source": "../../../skills/skill-generator/SKILL.md"
},
{
"name": "skill-tuning",
"description": "Universal skill diagnosis and optimization tool. Detect and fix skill execution issues including context explosion, long-tail forgetting, data flow disruption, and agent coordination failures. Supports Gemini CLI for deep analysis. Triggers on \"skill tuning\", \"tune skill\", \"skill diagnosis\", \"optimize skill\", \"skill debug\".",
"category": "meta",
"is_team": false,
"has_phases": true,
"has_role_specs": false,
"version": "",
"source": "../../../skills/skill-tuning/SKILL.md"
},
{
"name": "spec-generator",
"description": "Specification generator - 6 phase document chain producing product brief, PRD, architecture, and epics. Triggers on \"generate spec\", \"create specification\", \"spec generator\", \"workflow:spec\".",
"category": "meta",
"is_team": false,
"has_phases": true,
"has_role_specs": false,
"version": "",
"source": "../../../skills/spec-generator/SKILL.md"
}
],
"utility": [
{
"name": "ccw-help",
"description": "CCW command help system. Search, browse, recommend commands, skills, teams. Triggers \"ccw-help\", \"ccw-issue\".",
"category": "utility",
"is_team": false,
"has_phases": false,
"has_role_specs": false,
"version": "8.0.0",
"source": "../../../skills/ccw-help/SKILL.md"
},
{
"name": "issue-manage",
"description": "Interactive issue management with menu-driven CRUD operations. Use when managing issues, viewing issue status, editing issue fields, performing bulk operations, or viewing issue history. Triggers on \"manage issue\", \"list issues\", \"edit issue\", \"delete issue\", \"bulk update\", \"issue dashboard\", \"issue history\", \"completed issues\".",
"category": "utility",
"is_team": false,
"has_phases": false,
"has_role_specs": false,
"version": "",
"source": "../../../skills/issue-manage/SKILL.md"
},
{
"name": "memory-capture",
"description": "Unified memory capture with routing - session compact or quick tips. Triggers on \"memory capture\", \"compact session\", \"save session\", \"quick tip\", \"memory tips\", \"记录\", \"压缩会话\".",
"category": "utility",
"is_team": false,
"has_phases": true,
"has_role_specs": false,
"version": "",
"source": "../../../skills/memory-capture/SKILL.md"
},
{
"name": "memory-manage",
"description": "Unified memory management - CLAUDE.md updates and documentation generation with interactive routing. Triggers on \"memory manage\", \"update claude\", \"update memory\", \"generate docs\", \"更新记忆\", \"生成文档\".",
"category": "utility",
"is_team": false,
"has_phases": true,
"has_role_specs": false,
"version": "",
"source": "../../../skills/memory-manage/SKILL.md"
}
],
"review": [
{
"name": "review-code",
"description": "Multi-dimensional code review with structured reports. Analyzes correctness, readability, performance, security, testing, and architecture. Triggers on \"review code\", \"code review\", \"审查代码\", \"代码审查\".",
"category": "review",
"is_team": false,
"has_phases": true,
"has_role_specs": false,
"version": "",
"source": "../../../skills/review-code/SKILL.md"
},
{
"name": "review-cycle",
"description": "Unified multi-dimensional code review with automated fix orchestration. Routes to session-based (git changes), module-based (path patterns), or fix mode. Triggers on \"workflow:review-cycle\", \"workflow:review-session-cycle\", \"workflow:review-module-cycle\", \"workflow:review-cycle-fix\".",
"category": "review",
"is_team": false,
"has_phases": true,
"has_role_specs": false,
"version": "",
"source": "../../../skills/review-cycle/SKILL.md"
}
],
"team": [
{
"name": "team-arch-opt",
"description": "Unified team skill for architecture optimization. Uses team-worker agent architecture with role-spec files for domain logic. Coordinator orchestrates pipeline, workers are team-worker agents. Triggers on \"team arch-opt\".",
"category": "team",
"is_team": true,
"has_phases": false,
"has_role_specs": true,
"version": "",
"source": "../../../skills/team-arch-opt/SKILL.md"
},
{
"name": "team-brainstorm",
"description": "Unified team skill for brainstorming team. All roles invoke this skill with --role arg for role-specific execution. Triggers on \"team brainstorm\".",
"category": "team",
"is_team": true,
"has_phases": false,
"has_role_specs": false,
"version": "",
"source": "../../../skills/team-brainstorm/SKILL.md"
},
{
"name": "team-coordinate",
"description": "Universal team coordination skill with dynamic role generation. Uses team-worker agent architecture with role-spec files. Only coordinator is built-in -- all worker roles are generated at runtime as role-specs and spawned via team-worker agent. Beat/cadence model for orchestration. Triggers on \"Team Coordinate \".",
"category": "team",
"is_team": true,
"has_phases": false,
"has_role_specs": false,
"version": "",
"source": "../../../skills/team-coordinate/SKILL.md"
},
{
"name": "team-executor",
"description": "Lightweight session execution skill. Resumes existing team-coordinate sessions for pure execution via team-worker agents. No analysis, no role generation -- only loads and executes. Session path required. Triggers on \"Team Executor\".",
"category": "team",
"is_team": true,
"has_phases": false,
"has_role_specs": false,
"version": "",
"source": "../../../skills/team-executor/SKILL.md"
},
{
"name": "team-frontend",
"description": "Unified team skill for frontend development team. All roles invoke this skill with --role arg. Built-in ui-ux-pro-max design intelligence. Triggers on \"team frontend\".",
"category": "team",
"is_team": true,
"has_phases": false,
"has_role_specs": false,
"version": "",
"source": "../../../skills/team-frontend/SKILL.md"
},
{
"name": "team-issue",
"description": "Unified team skill for issue resolution. All roles invoke this skill with --role arg for role-specific execution. Triggers on \"team issue\".",
"category": "team",
"is_team": true,
"has_phases": false,
"has_role_specs": false,
"version": "",
"source": "../../../skills/team-issue/SKILL.md"
},
{
"name": "team-iterdev",
"description": "Unified team skill for iterative development team. All roles invoke this skill with --role arg for role-specific execution. Triggers on \"team iterdev\".",
"category": "team",
"is_team": true,
"has_phases": false,
"has_role_specs": false,
"version": "",
"source": "../../../skills/team-iterdev/SKILL.md"
},
{
"name": "team-lifecycle",
"description": "Unified team skill for full lifecycle - spec/impl/test. Uses team-worker agent architecture with role-spec files for domain logic. Coordinator orchestrates pipeline, workers are team-worker agents loaded with role-specific Phase 2-4 specs. Triggers on \"team lifecycle\".",
"category": "team",
"is_team": true,
"has_phases": false,
"has_role_specs": true,
"version": "",
"source": "../../../skills/team-lifecycle/SKILL.md"
},
{
"name": "team-perf-opt",
"description": "Unified team skill for performance optimization. Uses team-worker agent architecture with role-spec files for domain logic. Coordinator orchestrates pipeline, workers are team-worker agents. Triggers on \"team perf-opt\".",
"category": "team",
"is_team": true,
"has_phases": false,
"has_role_specs": true,
"version": "",
"source": "../../../skills/team-perf-opt/SKILL.md"
},
{
"name": "team-planex",
"description": "Unified team skill for plan-and-execute pipeline. Uses team-worker agent architecture with role-spec files for domain logic. Coordinator orchestrates pipeline, workers are team-worker agents. Triggers on \"team planex\".",
"category": "team",
"is_team": true,
"has_phases": false,
"has_role_specs": true,
"version": "",
"source": "../../../skills/team-planex/SKILL.md"
},
{
"name": "team-quality-assurance",
"description": "Unified team skill for quality assurance team. All roles invoke this skill with --role arg for role-specific execution. Triggers on \"team quality-assurance\", \"team qa\".",
"category": "team",
"is_team": true,
"has_phases": false,
"has_role_specs": false,
"version": "",
"source": "../../../skills/team-quality-assurance/SKILL.md"
},
{
"name": "team-review",
"description": "Unified team skill for code scanning, vulnerability review, optimization suggestions, and automated fix. 4-role team: coordinator, scanner, reviewer, fixer. Triggers on team-review.",
"category": "team",
"is_team": false,
"has_phases": false,
"has_role_specs": false,
"version": "",
"source": "../../../skills/team-review/SKILL.md"
},
{
"name": "team-roadmap-dev",
"description": "Unified team skill for roadmap-driven development workflow. Coordinator discusses roadmap with user, then dispatches phased execution pipeline (plan -> execute -> verify). All roles invoke this skill with --role arg. Triggers on \"team roadmap-dev\".",
"category": "team",
"is_team": true,
"has_phases": false,
"has_role_specs": false,
"version": "",
"source": "../../../skills/team-roadmap-dev/SKILL.md"
},
{
"name": "team-tech-debt",
"description": "Unified team skill for tech debt identification and cleanup. All roles invoke this skill with --role arg for role-specific execution. Triggers on \"team tech-debt\", \"tech debt cleanup\", \"技术债务\".",
"category": "team",
"is_team": true,
"has_phases": false,
"has_role_specs": false,
"version": "",
"source": "../../../skills/team-tech-debt/SKILL.md"
},
{
"name": "team-testing",
"description": "Unified team skill for testing team. All roles invoke this skill with --role arg for role-specific execution. Triggers on \"team testing\".",
"category": "team",
"is_team": true,
"has_phases": false,
"has_role_specs": false,
"version": "",
"source": "../../../skills/team-testing/SKILL.md"
},
{
"name": "team-uidesign",
"description": "Unified team skill for UI design team. All roles invoke this skill with --role arg for role-specific execution. CP-9 Dual-Track design+implementation.",
"category": "team",
"is_team": true,
"has_phases": false,
"has_role_specs": false,
"version": "",
"source": "../../../skills/team-uidesign/SKILL.md"
},
{
"name": "team-ultra-analyze",
"description": "Unified team skill for deep collaborative analysis. All roles invoke this skill with --role arg for role-specific execution. Triggers on \"team ultra-analyze\", \"team analyze\".",
"category": "team",
"is_team": true,
"has_phases": false,
"has_role_specs": false,
"version": "",
"source": "../../../skills/team-ultra-analyze/SKILL.md"
}
],
"workflow": [
{
"name": "workflow-execute",
"description": "Coordinate agent execution for workflow tasks with automatic session discovery, parallel task processing, and status tracking. Triggers on \"workflow-execute\".",
"category": "workflow",
"is_team": false,
"has_phases": true,
"has_role_specs": false,
"version": "",
"source": "../../../skills/workflow-execute/SKILL.md"
},
{
"name": "workflow-lite-planex",
"description": "Lightweight planning and execution skill (Phase 1: plan, Phase 2: execute). Triggers on \"workflow-lite-planex\".",
"category": "workflow",
"is_team": false,
"has_phases": true,
"has_role_specs": false,
"version": "",
"source": "../../../skills/workflow-lite-planex/SKILL.md"
},
{
"name": "workflow-multi-cli-plan",
"description": "Multi-CLI collaborative planning and execution skill with integrated execution phase. Triggers on \"workflow-multi-cli-plan\".",
"category": "workflow",
"is_team": false,
"has_phases": true,
"has_role_specs": false,
"version": "",
"source": "../../../skills/workflow-multi-cli-plan/SKILL.md"
},
{
"name": "workflow-plan",
"description": "Unified planning skill - 4-phase planning workflow, plan verification, and interactive replanning. Triggers on \"workflow-plan\", \"workflow-plan-verify\", \"workflow:replan\".",
"category": "workflow",
"is_team": false,
"has_phases": true,
"has_role_specs": false,
"version": "",
"source": "../../../skills/workflow-plan/SKILL.md"
},
{
"name": "workflow-skill-designer",
"description": "Meta-skill for designing orchestrator+phases structured workflow skills. Creates SKILL.md coordinator with progressive phase loading, TodoWrite patterns, and data flow. Triggers on \"design workflow skill\", \"create workflow skill\", \"workflow skill designer\".",
"category": "workflow",
"is_team": false,
"has_phases": true,
"has_role_specs": false,
"version": "",
"source": "../../../skills/workflow-skill-designer/SKILL.md"
},
{
"name": "workflow-tdd-plan",
"description": "Unified TDD workflow skill combining 6-phase TDD planning with Red-Green-Refactor task chain generation, and 4-phase TDD verification with compliance reporting. Triggers on \"workflow-tdd-plan\", \"workflow-tdd-verify\".",
"category": "workflow",
"is_team": false,
"has_phases": true,
"has_role_specs": false,
"version": "",
"source": "../../../skills/workflow-tdd-plan/SKILL.md"
},
{
"name": "workflow-test-fix",
"description": "Unified test-fix pipeline combining test generation (session, context, analysis, task gen) with iterative test-cycle execution (adaptive strategy, progressive testing, CLI fallback). Triggers on \"workflow-test-fix\", \"workflow-test-fix\", \"test fix workflow\".",
"category": "workflow",
"is_team": false,
"has_phases": true,
"has_role_specs": false,
"version": "",
"source": "../../../skills/workflow-test-fix/SKILL.md"
}
]
}

View File

@@ -1,11 +1,10 @@
#!/usr/bin/env python3 #!/usr/bin/env python3
""" """
Analyze all command/agent files and generate index files for ccw-help skill. Analyze all command/agent/skill files and generate index files for ccw-help skill.
Outputs relative paths pointing to source files (no reference folder duplication). Outputs relative paths pointing to source files (no reference folder duplication).
""" """
import os import os
import re
import json import json
from pathlib import Path from pathlib import Path
from collections import defaultdict from collections import defaultdict
@@ -15,9 +14,13 @@ from typing import Dict, List, Any
BASE_DIR = Path("D:/Claude_dms3/.claude") BASE_DIR = Path("D:/Claude_dms3/.claude")
COMMANDS_DIR = BASE_DIR / "commands" COMMANDS_DIR = BASE_DIR / "commands"
AGENTS_DIR = BASE_DIR / "agents" AGENTS_DIR = BASE_DIR / "agents"
SKILLS_DIR = BASE_DIR / "skills"
SKILL_DIR = BASE_DIR / "skills" / "ccw-help" SKILL_DIR = BASE_DIR / "skills" / "ccw-help"
INDEX_DIR = SKILL_DIR / "index" INDEX_DIR = SKILL_DIR / "index"
# Skills to skip (internal/shared, not user-facing)
SKIP_SKILLS = {"_shared", "ccw-help"}
def parse_frontmatter(content: str) -> Dict[str, Any]: def parse_frontmatter(content: str) -> Dict[str, Any]:
"""Extract YAML frontmatter from markdown content.""" """Extract YAML frontmatter from markdown content."""
frontmatter = {} frontmatter = {}
@@ -139,6 +142,66 @@ def analyze_agent_file(file_path: Path) -> Dict[str, Any]:
"source": rel_path # Relative from index/ dir (e.g., "../../../agents/...") "source": rel_path # Relative from index/ dir (e.g., "../../../agents/...")
} }
def categorize_skill(name: str, description: str) -> str:
"""Determine skill category from name and description."""
if name.startswith('team-'):
return "team"
if name.startswith('workflow-'):
return "workflow"
if name.startswith('review-'):
return "review"
if name.startswith('spec-') or name.startswith('command-') or name.startswith('skill-'):
return "meta"
if name.startswith('memory-') or name.startswith('issue-'):
return "utility"
return "standalone"
def analyze_skill_dir(skill_path: Path) -> Dict[str, Any] | None:
"""Analyze a skill directory and extract metadata from SKILL.md."""
skill_md = skill_path / "SKILL.md"
if not skill_md.exists():
return None
with open(skill_md, 'r', encoding='utf-8') as f:
content = f.read()
frontmatter = parse_frontmatter(content)
name = frontmatter.get('name', skill_path.name)
description = frontmatter.get('description', '')
allowed_tools = frontmatter.get('allowed-tools', '')
version = frontmatter.get('version', '')
category = categorize_skill(name, description)
# Detect if it's a team skill (uses TeamCreate + SendMessage together)
is_team = 'TeamCreate' in allowed_tools and 'SendMessage' in allowed_tools
# Detect if it has phases
phases_dir = skill_path / "phases"
has_phases = phases_dir.exists() and any(phases_dir.iterdir()) if phases_dir.exists() else False
# Detect if it has role-specs
role_specs_dir = skill_path / "role-specs"
has_role_specs = role_specs_dir.exists() and any(role_specs_dir.iterdir()) if role_specs_dir.exists() else False
# Build relative path from INDEX_DIR
rel_from_base = skill_path.relative_to(BASE_DIR)
rel_path = "../../../" + str(rel_from_base).replace('\\', '/') + "/SKILL.md"
return {
"name": name,
"description": description,
"category": category,
"is_team": is_team,
"has_phases": has_phases,
"has_role_specs": has_role_specs,
"version": version,
"source": rel_path
}
def build_command_relationships() -> Dict[str, Any]: def build_command_relationships() -> Dict[str, Any]:
"""Build command relationship mappings.""" """Build command relationship mappings."""
return { return {
@@ -176,21 +239,17 @@ def build_command_relationships() -> Dict[str, Any]:
"alternatives": ["workflow:resume"], "alternatives": ["workflow:resume"],
"related": ["workflow:session:list", "workflow:status"] "related": ["workflow:session:list", "workflow:status"]
}, },
"workflow-lite-plan": { "workflow-lite-planex": {
"calls_internally": ["workflow:lite-execute"], "calls_internally": [],
"next_steps": ["workflow:lite-execute", "workflow:status"], "next_steps": ["workflow:status"],
"alternatives": ["workflow-plan"], "alternatives": ["workflow-plan"],
"prerequisites": [] "prerequisites": []
}, },
"workflow:lite-fix": { "workflow:lite-fix": {
"next_steps": ["workflow:lite-execute", "workflow:status"], "next_steps": ["workflow:status"],
"alternatives": ["workflow-lite-plan"], "alternatives": ["workflow-lite-planex"],
"related": ["workflow-test-fix"] "related": ["workflow-test-fix"]
}, },
"workflow:lite-execute": {
"prerequisites": ["workflow-lite-plan", "workflow:lite-fix"],
"related": ["workflow-execute", "workflow:status"]
},
"workflow:review-session-cycle": { "workflow:review-session-cycle": {
"prerequisites": ["workflow-execute"], "prerequisites": ["workflow-execute"],
"next_steps": ["workflow:review-fix"], "next_steps": ["workflow:review-fix"],
@@ -213,7 +272,7 @@ def build_command_relationships() -> Dict[str, Any]:
def identify_essential_commands(all_commands: List[Dict]) -> List[Dict]: def identify_essential_commands(all_commands: List[Dict]) -> List[Dict]:
"""Identify the most essential commands for beginners.""" """Identify the most essential commands for beginners."""
essential_names = [ essential_names = [
"workflow-lite-plan", "workflow:lite-fix", "workflow-plan", "workflow-lite-planex", "workflow:lite-fix", "workflow-plan",
"workflow-execute", "workflow:status", "workflow:session:start", "workflow-execute", "workflow:status", "workflow:session:start",
"workflow:review-session-cycle", "cli:analyze", "cli:chat", "workflow:review-session-cycle", "cli:analyze", "cli:chat",
"memory:docs", "workflow:brainstorm:artifacts", "memory:docs", "workflow:brainstorm:artifacts",
@@ -267,7 +326,24 @@ def main():
except Exception as e: except Exception as e:
print(f" ERROR analyzing {agent_file}: {e}") print(f" ERROR analyzing {agent_file}: {e}")
print(f"\nAnalyzed {len(all_commands)} commands, {len(all_agents)} agents") # Analyze skill directories
print("\n=== Analyzing Skill Files ===")
skill_dirs = [d for d in SKILLS_DIR.iterdir() if d.is_dir() and d.name not in SKIP_SKILLS]
print(f"Found {len(skill_dirs)} skill directories")
all_skills = []
for skill_dir in sorted(skill_dirs):
try:
metadata = analyze_skill_dir(skill_dir)
if metadata:
all_skills.append(metadata)
print(f" OK {metadata['name']} [{metadata['category']}]")
else:
print(f" SKIP {skill_dir.name} (no SKILL.md)")
except Exception as e:
print(f" ERROR analyzing {skill_dir}: {e}")
print(f"\nAnalyzed {len(all_commands)} commands, {len(all_agents)} agents, {len(all_skills)} skills")
# Generate index files # Generate index files
INDEX_DIR.mkdir(parents=True, exist_ok=True) INDEX_DIR.mkdir(parents=True, exist_ok=True)
@@ -320,15 +396,62 @@ def main():
json.dump(relationships, f, indent=2, ensure_ascii=False) json.dump(relationships, f, indent=2, ensure_ascii=False)
print(f"OK Generated {relationships_path.name} ({os.path.getsize(relationships_path)} bytes)") print(f"OK Generated {relationships_path.name} ({os.path.getsize(relationships_path)} bytes)")
# 7. all-skills.json
all_skills_path = INDEX_DIR / "all-skills.json"
with open(all_skills_path, 'w', encoding='utf-8') as f:
json.dump(all_skills, f, indent=2, ensure_ascii=False)
print(f"OK Generated {all_skills_path.name} ({os.path.getsize(all_skills_path)} bytes)")
# 8. skills-by-category.json
skills_by_cat = defaultdict(list)
for skill in all_skills:
skills_by_cat[skill['category']].append(skill)
skills_by_cat_path = INDEX_DIR / "skills-by-category.json"
with open(skills_by_cat_path, 'w', encoding='utf-8') as f:
json.dump(dict(skills_by_cat), f, indent=2, ensure_ascii=False)
print(f"OK Generated {skills_by_cat_path.name} ({os.path.getsize(skills_by_cat_path)} bytes)")
# Generate master command.json (includes commands, agents, skills)
master = {
"_metadata": {
"version": "4.0.0",
"total_commands": len(all_commands),
"total_agents": len(all_agents),
"total_skills": len(all_skills),
"description": "Auto-generated CCW-Help command index from analyze_commands.py",
"generated": "Auto-updated - all commands, agents, skills synced from file system",
"last_sync": "command.json now stays in sync with CLI definitions"
},
"essential_commands": [cmd['name'] for cmd in essential],
"commands": all_commands,
"agents": all_agents,
"skills": all_skills,
"categories": sorted(set(cmd['category'] for cmd in all_commands)),
"skill_categories": sorted(skills_by_cat.keys())
}
master_path = SKILL_DIR / "command.json"
with open(master_path, 'w', encoding='utf-8') as f:
json.dump(master, f, indent=2, ensure_ascii=False)
print(f"\nOK Generated command.json ({os.path.getsize(master_path)} bytes)")
# Print summary # Print summary
print("\n=== Summary ===") print("\n=== Summary ===")
print(f"Commands: {len(all_commands)}") print(f"Commands: {len(all_commands)}")
print(f"Agents: {len(all_agents)}") print(f"Agents: {len(all_agents)}")
print(f"Skills: {len(all_skills)}")
print(f"Essential: {len(essential)}") print(f"Essential: {len(essential)}")
print(f"\nBy category:") print(f"\nCommands by category:")
for cat in sorted(by_category.keys()): for cat in sorted(by_category.keys()):
total = sum(len(cmds) for cmds in by_category[cat].values()) total = sum(len(cmds) for cmds in by_category[cat].values())
print(f" {cat}: {total}") print(f" {cat}: {total}")
print(f"\nSkills by category:")
for cat in sorted(skills_by_cat.keys()):
print(f" {cat}: {len(skills_by_cat[cat])}")
for skill in skills_by_cat[cat]:
team_tag = " [team]" if skill['is_team'] else ""
print(f" - {skill['name']}{team_tag}")
print(f"\nIndex: {INDEX_DIR}") print(f"\nIndex: {INDEX_DIR}")
print("=== Complete ===") print("=== Complete ===")

View File

@@ -1,7 +1,7 @@
--- ---
name: issue-manage name: issue-manage
description: Interactive issue management with menu-driven CRUD operations. Use when managing issues, viewing issue status, editing issue fields, performing bulk operations, or viewing issue history. Triggers on "manage issue", "list issues", "edit issue", "delete issue", "bulk update", "issue dashboard", "issue history", "completed issues". description: Interactive issue management with menu-driven CRUD operations. Use when managing issues, viewing issue status, editing issue fields, performing bulk operations, or viewing issue history. Triggers on "manage issue", "list issues", "edit issue", "delete issue", "bulk update", "issue dashboard", "issue history", "completed issues".
allowed-tools: Bash, Read, Write, AskUserQuestion, Task, Glob allowed-tools: Bash, Read, Write, AskUserQuestion, Agent, Glob
--- ---
# Issue Management Skill # Issue Management Skill
@@ -219,9 +219,8 @@ const action = AskUserQuestion({
header: 'Action', header: 'Action',
options: [ options: [
{ label: 'List Issues', description: 'Browse active issues' }, { label: 'List Issues', description: 'Browse active issues' },
{ label: 'View Issue', description: 'Detail view' }, { label: 'View Issue', description: 'Detail view (includes history)' },
{ label: 'Edit Issue', description: 'Modify fields' }, { label: 'Edit Issue', description: 'Modify fields' },
{ label: 'View History', description: 'Completed issues' },
{ label: 'Bulk Operations', description: 'Batch actions' } { label: 'Bulk Operations', description: 'Batch actions' }
] ]
}] }]

View File

@@ -1,7 +1,7 @@
--- ---
name: memory-manage name: memory-manage
description: Unified memory management - CLAUDE.md updates and documentation generation with interactive routing. Triggers on "memory manage", "update claude", "update memory", "generate docs", "更新记忆", "生成文档". description: Unified memory management - CLAUDE.md updates and documentation generation with interactive routing. Triggers on "memory manage", "update claude", "update memory", "generate docs", "更新记忆", "生成文档".
allowed-tools: Task(*), Bash(*), AskUserQuestion(*), Read(*) allowed-tools: Agent(*), Bash(*), AskUserQuestion(*), Read(*)
--- ---
# Memory Management Skill # Memory Management Skill

View File

@@ -1,7 +1,7 @@
--- ---
name: review-code name: review-code
description: Multi-dimensional code review with structured reports. Analyzes correctness, readability, performance, security, testing, and architecture. Triggers on "review code", "code review", "审查代码", "代码审查". description: Multi-dimensional code review with structured reports. Analyzes correctness, readability, performance, security, testing, and architecture. Triggers on "review code", "code review", "审查代码", "代码审查".
allowed-tools: Task, AskUserQuestion, Read, Write, Glob, Grep, Bash, mcp__ace-tool__search_context, mcp__ide__getDiagnostics allowed-tools: Agent, AskUserQuestion, Read, Write, Glob, Grep, Bash, mcp__ace-tool__search_context, mcp__ide__getDiagnostics
--- ---
# Review Code # Review Code

View File

@@ -132,8 +132,9 @@ async function runOrchestrator() {
// 确定当前需要审查的维度(使用 StateManager // 确定当前需要审查的维度(使用 StateManager
const currentDimension = StateManager.getNextDimension(state); const currentDimension = StateManager.getNextDimension(state);
const result = await Task({ const result = await Agent({
subagent_type: 'universal-executor', subagent_type: 'universal-executor',
description: `Execute code review action: ${actionId}`,
run_in_background: false, run_in_background: false,
prompt: ` prompt: `
[WORK_DIR] [WORK_DIR]

View File

@@ -1,7 +1,7 @@
--- ---
name: review-cycle name: review-cycle
description: Unified multi-dimensional code review with automated fix orchestration. Routes to session-based (git changes), module-based (path patterns), or fix mode. Triggers on "workflow:review-cycle", "workflow:review-session-cycle", "workflow:review-module-cycle", "workflow:review-cycle-fix". description: Unified multi-dimensional code review with automated fix orchestration. Routes to session-based (git changes), module-based (path patterns), or fix mode. Triggers on "workflow:review-cycle", "workflow:review-session-cycle", "workflow:review-module-cycle", "workflow:review-cycle-fix".
allowed-tools: Task, AskUserQuestion, TaskCreate, TaskUpdate, TaskList, Read, Write, Edit, Bash, Glob, Grep, Skill allowed-tools: Agent, AskUserQuestion, TaskCreate, TaskUpdate, TaskList, Read, Write, Edit, Bash, Glob, Grep, Skill
--- ---
# Review Cycle # Review Cycle

View File

@@ -332,7 +332,7 @@ for (let i = 0; i < batches.length; i += MAX_PARALLEL) {
// Launch agents in parallel (run_in_background=true) // Launch agents in parallel (run_in_background=true)
for (const batch of chunk) { for (const batch of chunk) {
const taskId = Task({ const taskId = Agent({
subagent_type: "cli-planning-agent", subagent_type: "cli-planning-agent",
run_in_background: true, run_in_background: true,
description: `Plan batch ${batch.batch_id}: ${batch.findings.length} findings`, description: `Plan batch ${batch.batch_id}: ${batch.findings.length} findings`,
@@ -386,7 +386,7 @@ for (let i = 1; i <= aggregatedPlan.groups.length; i++) {
**Planning Agent (Batch Mode - Partial Plan Only)**: **Planning Agent (Batch Mode - Partial Plan Only)**:
```javascript ```javascript
Task({ Agent({
subagent_type: "cli-planning-agent", subagent_type: "cli-planning-agent",
run_in_background: true, run_in_background: true,
description: `Plan batch ${batch.batch_id}: ${batch.findings.length} findings`, description: `Plan batch ${batch.batch_id}: ${batch.findings.length} findings`,
@@ -488,7 +488,7 @@ Before finalizing outputs:
**Execution Agent** (per group): **Execution Agent** (per group):
```javascript ```javascript
Task({ Agent({
subagent_type: "cli-execute-agent", subagent_type: "cli-execute-agent",
description: `Fix ${group.findings.length} issues: ${group.group_name}`, description: `Fix ${group.findings.length} issues: ${group.group_name}`,
prompt: ` prompt: `

View File

@@ -1,7 +1,7 @@
--- ---
name: skill-generator name: skill-generator
description: Meta-skill for creating new Claude Code skills with configurable execution modes. Supports sequential (fixed order) and autonomous (stateless) phase patterns. Use for skill scaffolding, skill creation, or building new workflows. Triggers on "create skill", "new skill", "skill generator". description: Meta-skill for creating new Claude Code skills with configurable execution modes. Supports sequential (fixed order) and autonomous (stateless) phase patterns. Use for skill scaffolding, skill creation, or building new workflows. Triggers on "create skill", "new skill", "skill generator".
allowed-tools: Task, AskUserQuestion, Read, Bash, Glob, Grep, Write allowed-tools: Agent, AskUserQuestion, Read, Bash, Glob, Grep, Write
--- ---
# Skill Generator # Skill Generator

View File

@@ -240,7 +240,7 @@ async function executePhase(phaseId, phaseConfig, workDir) {
const phasePrompt = Read(\`\${skillDir}/phases/\${phaseId}.md\`); const phasePrompt = Read(\`\${skillDir}/phases/\${phaseId}.md\`);
// Use Task to invoke Agent // Use Task to invoke Agent
const result = await Task({ const result = await Agent({
subagent_type: phaseConfig.agent?.type || 'universal-executor', subagent_type: phaseConfig.agent?.type || 'universal-executor',
run_in_background: phaseConfig.agent?.run_in_background || false, run_in_background: phaseConfig.agent?.run_in_background || false,
prompt: \` prompt: \`
@@ -573,7 +573,7 @@ async function runOrchestrator(workDir) {
try { try {
const actionPrompt = Read(\`\${skillDir}/phases/actions/\${actionId}.md\`); const actionPrompt = Read(\`\${skillDir}/phases/actions/\${actionId}.md\`);
const result = await Task({ const result = await Agent({
subagent_type: 'universal-executor', subagent_type: 'universal-executor',
run_in_background: false, run_in_background: false,
prompt: \` prompt: \`

View File

@@ -12,7 +12,7 @@ Suitable for scenarios that need immediate results.
```javascript ```javascript
// Agent call - synchronous // Agent call - synchronous
const result = Task({ const result = Agent({
subagent_type: 'universal-executor', subagent_type: 'universal-executor',
prompt: 'Execute task...', prompt: 'Execute task...',
run_in_background: false // Key: synchronous execution run_in_background: false // Key: synchronous execution
@@ -77,7 +77,7 @@ ccw cli -p "<PROMPT>" --tool <gemini|qwen|codex> --mode <analysis|write>
General-purpose executor, the most commonly used agent type. General-purpose executor, the most commonly used agent type.
```javascript ```javascript
Task({ Agent({
subagent_type: 'universal-executor', subagent_type: 'universal-executor',
prompt: ` prompt: `
Execute task: Execute task:
@@ -99,7 +99,7 @@ Execute task:
Code exploration agent for quick codebase understanding. Code exploration agent for quick codebase understanding.
```javascript ```javascript
Task({ Agent({
subagent_type: 'Explore', subagent_type: 'Explore',
prompt: ` prompt: `
Explore src/ directory: Explore src/ directory:
@@ -123,7 +123,7 @@ Thoroughness: medium
Deep code analysis agent. Deep code analysis agent.
```javascript ```javascript
Task({ Agent({
subagent_type: 'cli-explore-agent', subagent_type: 'cli-explore-agent',
prompt: ` prompt: `
Deep analysis of src/auth/ module: Deep analysis of src/auth/ module:

View File

@@ -111,7 +111,7 @@ async function runOrchestrator() {
try { try {
const actionPrompt = Read(\`phases/actions/${actionId}.md\`); const actionPrompt = Read(\`phases/actions/${actionId}.md\`);
const result = await Task({ const result = await Agent({
subagent_type: 'universal-executor', subagent_type: 'universal-executor',
run_in_background: false, run_in_background: false,
prompt: \` prompt: \`

View File

@@ -96,7 +96,7 @@ async function execute${toPascalCase(id)}(context) {
\` : '// No MCP tools configured'} \` : '// No MCP tools configured'}
// 3. Launch Agent for in-depth analysis // 3. Launch Agent for in-depth analysis
const agentResult = await Task({ const agentResult = await Agent({
subagent_type: '\${agent.type}', subagent_type: '\${agent.type}',
prompt: \` prompt: \`
\${generateAgentPrompt(analysis_type, scope)} \${generateAgentPrompt(analysis_type, scope)}
@@ -408,7 +408,7 @@ const semanticContext = await mcp__ace_tool__search_context({
}); });
// Use semantic search results as Agent input context // Use semantic search results as Agent input context
const agentResult = await Task({ const agentResult = await Agent({
subagent_type: 'Explore', subagent_type: 'Explore',
prompt: \` prompt: \`
Based on following semantic search results, perform in-depth analysis: Based on following semantic search results, perform in-depth analysis:

View File

@@ -274,7 +274,7 @@ const tasks = [
\`\`\`javascript \`\`\`javascript
const results = await Promise.all( const results = await Promise.all(
tasks.map(task => tasks.map(task =>
Task({ Agent({
subagent_type: 'universal-executor', subagent_type: 'universal-executor',
run_in_background: false, run_in_background: false,
prompt: task.prompt prompt: task.prompt

View File

@@ -223,7 +223,7 @@ function filterDocsByPhase(specs, phase, phaseIndex) {
--- ---
name: api-docs-generator name: api-docs-generator
description: Generate API documentation from source code. Triggers on "generate api docs", "api documentation". description: Generate API documentation from source code. Triggers on "generate api docs", "api documentation".
allowed-tools: Task, Read, Write, Glob, Grep, Bash allowed-tools: Agent, Read, Write, Glob, Grep, Bash
--- ---
# API Docs Generator # API Docs Generator
@@ -265,7 +265,7 @@ Phase 3: Generation → api-docs.md
--- ---
name: task-manager name: task-manager
description: Interactive task management with CRUD operations. Triggers on "manage tasks", "task list". description: Interactive task management with CRUD operations. Triggers on "manage tasks", "task list".
allowed-tools: Task, AskUserQuestion, Read, Write allowed-tools: Agent, AskUserQuestion, Read, Write
--- ---
# Task Manager # Task Manager

View File

@@ -1,7 +1,7 @@
--- ---
name: skill-tuning name: skill-tuning
description: Universal skill diagnosis and optimization tool. Detect and fix skill execution issues including context explosion, long-tail forgetting, data flow disruption, and agent coordination failures. Supports Gemini CLI for deep analysis. Triggers on "skill tuning", "tune skill", "skill diagnosis", "optimize skill", "skill debug". description: Universal skill diagnosis and optimization tool. Detect and fix skill execution issues including context explosion, long-tail forgetting, data flow disruption, and agent coordination failures. Supports Gemini CLI for deep analysis. Triggers on "skill tuning", "tune skill", "skill diagnosis", "optimize skill", "skill debug".
allowed-tools: Task, AskUserQuestion, Read, Write, Bash, Glob, Grep, mcp__ace-tool__search_context allowed-tools: Agent, AskUserQuestion, Read, Write, Bash, Glob, Grep, mcp__ace-tool__search_context
--- ---
# Skill Tuning # Skill Tuning

View File

@@ -193,7 +193,7 @@ async function execute(state, workDir) {
type: 'agent_failure', type: 'agent_failure',
severity: 'medium', severity: 'medium',
location: { file: 'SKILL.md' }, location: { file: 'SKILL.md' },
description: 'Task tool used but not declared in allowed-tools', description: 'Agent tool used but not declared in allowed-tools',
evidence: [`${totalCalls} Task calls found, but Task not in allowed-tools`], evidence: [`${totalCalls} Task calls found, but Task not in allowed-tools`],
root_cause: 'Tool declaration mismatch', root_cause: 'Tool declaration mismatch',
impact: 'May cause runtime permission issues', impact: 'May cause runtime permission issues',

View File

@@ -216,7 +216,7 @@ async function execute(state, workDir) {
file: 'phases/*.md', file: 'phases/*.md',
action: 'modify', action: 'modify',
diff: `+ try { diff: `+ try {
const result = await Task({...}); const result = await Agent({...});
+ if (!result) throw new Error('Empty result'); + if (!result) throw new Error('Empty result');
+ } catch (e) { + } catch (e) {
+ updateState({ errors: [...errors, e.message], error_count: error_count + 1 }); + updateState({ errors: [...errors, e.message], error_count: error_count + 1 });

View File

@@ -99,8 +99,9 @@ async function runOrchestrator(workDir) {
target_skill: { name: state.target_skill.name, path: state.target_skill.path } target_skill: { name: state.target_skill.name, path: state.target_skill.path }
}; };
const result = await Task({ const result = await Agent({
subagent_type: 'universal-executor', subagent_type: 'universal-executor',
description: `Execute skill-tuning action: ${actionId}`,
run_in_background: false, run_in_background: false,
prompt: ` prompt: `
[CONTEXT] [CONTEXT]

View File

@@ -115,7 +115,10 @@ Write(`${workDir}/final-output.json`, finalResult); // 只存最终结果
async function executePhase(context) { async function executePhase(context) {
const { previousResult, constraints, config } = context; const { previousResult, constraints, config } = context;
const result = await Task({ const result = await Agent({
subagent_type: 'universal-executor',
description: 'Execute phase with context passing',
run_in_background: false,
prompt: ` prompt: `
[CONTEXT] [CONTEXT]
Previous: ${JSON.stringify(previousResult)} Previous: ${JSON.stringify(previousResult)}

View File

@@ -140,8 +140,10 @@ function updateHistory(state, newItem) {
```javascript ```javascript
// Add summarization before passing to next phase // Add summarization before passing to next phase
const summary = await Task({ const summary = await Agent({
subagent_type: 'universal-executor', subagent_type: 'universal-executor',
description: 'Summarize content for context compression',
run_in_background: false,
prompt: `Summarize in <100 words: ${fullContent}\nReturn JSON: { summary, key_points[] }` prompt: `Summarize in <100 words: ${fullContent}\nReturn JSON: { summary, key_points[] }`
}); });
nextPhasePrompt = `Previous summary: ${summary.summary}`; nextPhasePrompt = `Previous summary: ${summary.summary}`;
@@ -268,12 +270,17 @@ function validateAgentResult(result, requiredFields) {
### flatten_nesting ### flatten_nesting
```javascript ```javascript
// Before: Agent A's prompt tells it to call Task({subagent_type: 'B'}) // Before: Agent A's prompt tells it to call Agent({subagent_type: 'B'})
// After: Agent A returns signal, orchestrator handles // After: Agent A returns signal, orchestrator handles
// Agent A: return { needs_agent_b: true, context: {...} } // Agent A: return { needs_agent_b: true, context: {...} }
// Orchestrator: // Orchestrator:
if (parsedA.needs_agent_b) { if (parsedA.needs_agent_b) {
resultB = await Task({ subagent_type: 'B', prompt: `Context: ${parsedA.context}` }); resultB = await Agent({
subagent_type: 'B',
description: 'Handle delegated task from Agent A',
run_in_background: false,
prompt: `Context: ${parsedA.context}`
});
} }
``` ```

View File

@@ -67,7 +67,7 @@ spec-generator/
## Handoff ## Handoff
After Phase 6, choose execution path: After Phase 6, choose execution path:
- `workflow-lite-plan` - Execute per Epic - `workflow-lite-planex` - Execute per Epic
- `workflow:req-plan-with-file` - Roadmap decomposition - `workflow:req-plan-with-file` - Roadmap decomposition
- `workflow-plan` - Full planning - `workflow-plan` - Full planning
- `issue:new` - Create issues per Epic - `issue:new` - Create issues per Epic

View File

@@ -1,7 +1,7 @@
--- ---
name: spec-generator name: spec-generator
description: Specification generator - 6 phase document chain producing product brief, PRD, architecture, and epics. Triggers on "generate spec", "create specification", "spec generator", "workflow:spec". description: Specification generator - 6 phase document chain producing product brief, PRD, architecture, and epics. Triggers on "generate spec", "create specification", "spec generator", "workflow:spec".
allowed-tools: Task, AskUserQuestion, TaskCreate, TaskUpdate, TaskList, Read, Write, Edit, Bash, Glob, Grep, Skill allowed-tools: Agent, AskUserQuestion, TaskCreate, TaskUpdate, TaskList, Read, Write, Edit, Bash, Glob, Grep, Skill
--- ---
# Spec Generator # Spec Generator

View File

@@ -117,7 +117,7 @@ const hasCodebase = Glob('**/*.{ts,js,py,java,go,rs}').length > 0
|| Glob('Cargo.toml').length > 0; || Glob('Cargo.toml').length > 0;
if (hasCodebase) { if (hasCodebase) {
Task({ Agent({
subagent_type: "cli-explore-agent", subagent_type: "cli-explore-agent",
run_in_background: false, run_in_background: false,
description: `Explore codebase for spec: ${slug}`, description: `Explore codebase for spec: ${slug}`,

View File

@@ -210,7 +210,7 @@ AskUserQuestion({
options: [ options: [
{ {
label: "Execute via lite-plan", label: "Execute via lite-plan",
description: "Start implementing with /workflow-lite-plan, one Epic at a time" description: "Start implementing with /workflow-lite-planex, one Epic at a time"
}, },
{ {
label: "Create roadmap", label: "Create roadmap",
@@ -242,7 +242,7 @@ if (selection === "Execute via lite-plan") {
const epicContent = Read(firstMvpFile); const epicContent = Read(firstMvpFile);
const title = extractTitle(epicContent); // First # heading const title = extractTitle(epicContent); // First # heading
const description = extractSection(epicContent, "Description"); const description = extractSection(epicContent, "Description");
Skill(skill="workflow-lite-plan", args=`"${title}: ${description}"`) Skill(skill="workflow-lite-planex", args=`"${title}: ${description}"`)
} }
if (selection === "Full planning" || selection === "Create roadmap") { if (selection === "Full planning" || selection === "Create roadmap") {

View File

@@ -0,0 +1,476 @@
---
name: team-arch-opt
description: Unified team skill for architecture optimization. Uses team-worker agent architecture with role-spec files for domain logic. Coordinator orchestrates pipeline, workers are team-worker agents. Triggers on "team arch-opt".
allowed-tools: Agent, TaskCreate, TaskList, TaskGet, TaskUpdate, TeamCreate, TeamDelete, SendMessage, AskUserQuestion, Read, Write, Edit, Bash, Glob, Grep, mcp__ace-tool__search_context
---
# Team Architecture Optimization
Unified team skill: Analyze codebase architecture, identify structural issues (dependency cycles, coupling/cohesion, layering violations, God Classes, dead code), design refactoring strategies, implement changes, validate improvements, and review code quality. Built on **team-worker agent architecture** -- all worker roles share a single agent definition with role-specific Phase 2-4 loaded from markdown specs.
## Architecture
```
+---------------------------------------------------+
| Skill(skill="team-arch-opt") |
| args="<task-description>" |
+-------------------+-------------------------------+
|
Orchestration Mode (auto -> coordinator)
|
Coordinator (inline)
Phase 0-5 orchestration
|
+-------+-------+-------+-------+-------+
v v v v v
[tw] [tw] [tw] [tw] [tw]
analyzer desig- refact- valid- review-
ner orer ator er
CLI Tools (callable by workers inline):
[explore] [discuss]
(tw) = team-worker agent
```
## Role Router
This skill is **coordinator-only**. Workers do NOT invoke this skill -- they are spawned as `team-worker` agents directly.
### Input Parsing
Parse `$ARGUMENTS`. No `--role` needed -- always routes to coordinator.
### Role Registry
| Role | Spec | Task Prefix | Type | Inner Loop |
|------|------|-------------|------|------------|
| coordinator | [roles/coordinator/role.md](roles/coordinator/role.md) | (none) | orchestrator | - |
| analyzer | [role-specs/analyzer.md](role-specs/analyzer.md) | ANALYZE-* | orchestration | false |
| designer | [role-specs/designer.md](role-specs/designer.md) | DESIGN-* | orchestration | false |
| refactorer | [role-specs/refactorer.md](role-specs/refactorer.md) | REFACTOR-* / FIX-* | code_generation | true |
| validator | [role-specs/validator.md](role-specs/validator.md) | VALIDATE-* | validation | false |
| reviewer | [role-specs/reviewer.md](role-specs/reviewer.md) | REVIEW-* / QUALITY-* | read_only_analysis | false |
### CLI Tool Registry
| Tool | Spec | Used By | Purpose |
|------|------|---------|---------|
| explore | [cli-tools/explore.md](cli-tools/explore.md) | analyzer, refactorer | Shared codebase exploration for architecture-critical structures and dependency graphs |
| discuss | [cli-tools/discuss.md](cli-tools/discuss.md) | designer, reviewer | Multi-perspective discussion for refactoring approaches and review findings |
### Dispatch
Always route to coordinator. Coordinator reads `roles/coordinator/role.md` and executes its phases.
### Orchestration Mode
User just provides task description.
**Invocation**:
```bash
Skill(skill="team-arch-opt", args="<task-description>") # auto mode
Skill(skill="team-arch-opt", args="--parallel-mode=fan-out <task-description>") # force fan-out
Skill(skill="team-arch-opt", args='--parallel-mode=independent "target1" "target2"') # independent
Skill(skill="team-arch-opt", args="--max-branches=3 <task-description>") # limit branches
```
**Parallel Modes**:
| Mode | Description | When to Use |
|------|-------------|------------|
| `auto` (default) | count <= 2 -> single, count >= 3 -> fan-out | General refactoring requests |
| `single` | Linear pipeline, no branching | Simple or tightly coupled refactorings |
| `fan-out` | Shared ANALYZE+DESIGN, then N parallel REFACTOR->VALIDATE+REVIEW branches | Multiple independent architecture issues |
| `independent` | M fully independent pipelines from analysis to review | Separate refactoring targets |
**Lifecycle**:
```
User provides task description + optional --parallel-mode / --max-branches
-> coordinator Phase 1-3: Parse flags -> TeamCreate -> Create task chain (mode-aware)
-> coordinator Phase 4: spawn first batch workers (background) -> STOP
-> Worker (team-worker agent) executes -> SendMessage callback -> coordinator advances
-> [auto/fan-out] CP-2.5: Design complete -> create N branch tasks -> spawn all REFACTOR-B* in parallel
-> [independent] All pipelines run in parallel from the start
-> Per-branch/pipeline fix cycles run independently
-> All branches/pipelines complete -> AGGREGATE -> Phase 5 report + completion action
```
**User Commands** (wake paused coordinator):
| Command | Action |
|---------|--------|
| `check` / `status` | Output execution status graph (branch-grouped), no advancement |
| `resume` / `continue` | Check worker states, advance next step |
| `revise <TASK-ID> [feedback]` | Create revision task + cascade downstream (scoped to branch) |
| `feedback <text>` | Analyze feedback impact, create targeted revision chain |
| `recheck` | Re-run quality check |
| `improve [dimension]` | Auto-improve weakest dimension |
---
## Command Execution Protocol
When coordinator needs to execute a command (dispatch, monitor):
1. **Read the command file**: `roles/coordinator/commands/<command-name>.md`
2. **Follow the workflow** defined in the command file (Phase 2-4 structure)
3. **Commands are inline execution guides** -- NOT separate agents or subprocesses
4. **Execute synchronously** -- complete the command workflow before proceeding
Example:
```
Phase 3 needs task dispatch
-> Read roles/coordinator/commands/dispatch.md
-> Execute Phase 2 (Context Loading)
-> Execute Phase 3 (Task Chain Creation)
-> Execute Phase 4 (Validation)
-> Continue to Phase 4
```
---
## Coordinator Spawn Template
### v5 Worker Spawn (all roles)
When coordinator spawns workers, use `team-worker` agent with role-spec path:
```
Agent({
subagent_type: "team-worker",
description: "Spawn <role> worker",
team_name: <team-name>,
name: "<role>",
run_in_background: true,
prompt: `## Role Assignment
role: <role>
role_spec: .claude/skills/team-arch-opt/role-specs/<role>.md
session: <session-folder>
session_id: <session-id>
team_name: <team-name>
requirement: <task-description>
inner_loop: <true|false>
Read role_spec file to load Phase 2-4 domain instructions.
Execute built-in Phase 1 (task discovery) -> role-spec Phase 2-4 -> built-in Phase 5 (report).`
})
```
**Inner Loop roles** (refactorer): Set `inner_loop: true`. The team-worker agent handles the loop internally.
**Single-task roles** (analyzer, designer, validator, reviewer): Set `inner_loop: false`.
---
## Pipeline Definitions
### Pipeline Diagrams
**Single Mode** (linear, backward compatible):
```
Pipeline: Single (Linear with Review-Fix Cycle)
=====================================================================
Stage 1 Stage 2 Stage 3 Stage 4
ANALYZE-001 --> DESIGN-001 --> REFACTOR-001 --> VALIDATE-001
[analyzer] [designer] [refactorer] [validator]
^ |
+<--FIX-001---->+
| REVIEW-001
+<--------> [reviewer]
(max 3 iterations) |
COMPLETE
=====================================================================
```
**Fan-out Mode** (shared stages 1-2, parallel branches 3-4):
```
Pipeline: Fan-out (N parallel refactoring branches)
=====================================================================
Stage 1 Stage 2 CP-2.5 Stage 3+4 (per branch)
(branch creation)
ANALYZE-001 --> DESIGN-001 --+-> REFACTOR-B01 --> VALIDATE-B01 + REVIEW-B01 (fix cycle)
[analyzer] [designer] | [refactorer] [validator] [reviewer]
+-> REFACTOR-B02 --> VALIDATE-B02 + REVIEW-B02 (fix cycle)
| [refactorer] [validator] [reviewer]
+-> REFACTOR-B0N --> VALIDATE-B0N + REVIEW-B0N (fix cycle)
|
AGGREGATE -> Phase 5
=====================================================================
```
**Independent Mode** (M fully independent pipelines):
```
Pipeline: Independent (M complete pipelines)
=====================================================================
Pipeline A: ANALYZE-A01 --> DESIGN-A01 --> REFACTOR-A01 --> VALIDATE-A01 + REVIEW-A01
Pipeline B: ANALYZE-B01 --> DESIGN-B01 --> REFACTOR-B01 --> VALIDATE-B01 + REVIEW-B01
Pipeline C: ANALYZE-C01 --> DESIGN-C01 --> REFACTOR-C01 --> VALIDATE-C01 + REVIEW-C01
|
AGGREGATE -> Phase 5
=====================================================================
```
### Cadence Control
**Beat model**: Event-driven, each beat = coordinator wake -> process -> spawn -> STOP.
```
Beat Cycle (single beat)
======================================================================
Event Coordinator Workers
----------------------------------------------------------------------
callback/resume --> +- handleCallback -+
| mark completed |
| check pipeline |
+- handleSpawnNext -+
| find ready tasks |
| spawn workers ---+--> [team-worker A] Phase 1-5
| (parallel OK) --+--> [team-worker B] Phase 1-5
+- STOP (idle) -----+ |
|
callback <-----------------------------------------+
(next beat) SendMessage + TaskUpdate(completed)
======================================================================
Fast-Advance (skips coordinator for simple linear successors)
======================================================================
[Worker A] Phase 5 complete
+- 1 ready task? simple successor?
| --> spawn team-worker B directly
| --> log fast_advance to message bus (coordinator syncs on next wake)
+- complex case? --> SendMessage to coordinator
======================================================================
```
```
Beat View: Architecture Optimization Pipeline
======================================================================
Event Coordinator Workers
----------------------------------------------------------------------
new task --> +- Phase 1-3: clarify -+
| TeamCreate |
| create ANALYZE-001 |
+- Phase 4: spawn ------+--> [analyzer] Phase 1-5
+- STOP (idle) ---------+ |
|
callback <----------------------------------------------+
(analyzer done) --> +- handleCallback ------+ analyze_complete
| mark ANALYZE done |
| spawn designer ------+--> [designer] Phase 1-5
+- STOP ----------------+ |
|
callback <----------------------------------------------+
(designer done) --> +- handleCallback ------+ design_complete
| mark DESIGN done |
| spawn refactorer ----+--> [refactorer] Phase 1-5
+- STOP ----------------+ |
|
callback <----------------------------------------------+
(refactorer done)--> +- handleCallback ------+ refactor_complete
| mark REFACTOR done |
| spawn valid+reviewer-+--> [validator] Phase 1-5
| (parallel) -------+--> [reviewer] Phase 1-5
+- STOP ----------------+ | |
| |
callback x2 <--------------------------------------+-----------+
--> +- handleCallback ------+
| both done? |
| YES + pass -> Phase 5|
| NO / fail -> FIX task|
| spawn refactorer ----+--> [refactorer] FIX-001
+- STOP or Phase 5 -----+
======================================================================
```
**Checkpoints**:
| Checkpoint | Trigger | Location | Behavior |
|------------|---------|----------|----------|
| CP-1 | ANALYZE-001 complete | After Stage 1 | User reviews architecture report, can refine scope |
| CP-2 | DESIGN-001 complete | After Stage 2 | User reviews refactoring plan, can adjust priorities |
| CP-2.5 | DESIGN-001 complete (auto/fan-out) | After Stage 2 | Auto-create N branch tasks from refactoring plan, spawn all REFACTOR-B* in parallel |
| CP-3 | REVIEW/VALIDATE fail | Stage 4 (per-branch) | Auto-create FIX task for that branch only (max 3x per branch) |
| CP-4 | All tasks/branches complete | Phase 5 | Aggregate results, interactive completion action |
### Task Metadata Registry
**Single mode** (backward compatible):
| Task ID | Role | Phase | Dependencies | Description |
|---------|------|-------|-------------|-------------|
| ANALYZE-001 | analyzer | Stage 1 | (none) | Analyze architecture, identify structural issues |
| DESIGN-001 | designer | Stage 2 | ANALYZE-001 | Design refactoring plan from architecture report |
| REFACTOR-001 | refactorer | Stage 3 | DESIGN-001 | Implement highest-priority refactorings |
| VALIDATE-001 | validator | Stage 4 | REFACTOR-001 | Validate build, tests, metrics, API compatibility |
| REVIEW-001 | reviewer | Stage 4 | REFACTOR-001 | Review refactoring code for correctness |
| FIX-001 | refactorer | Stage 3 (cycle) | REVIEW-001 or VALIDATE-001 | Fix issues found in review/validation |
**Fan-out mode** (branch tasks created at CP-2.5):
| Task ID | Role | Phase | Dependencies | Description |
|---------|------|-------|-------------|-------------|
| ANALYZE-001 | analyzer | Stage 1 (shared) | (none) | Analyze architecture |
| DESIGN-001 | designer | Stage 2 (shared) | ANALYZE-001 | Design plan with discrete REFACTOR-IDs |
| REFACTOR-B{NN} | refactorer | Stage 3 (branch) | DESIGN-001 | Implement REFACTOR-{NNN} only |
| VALIDATE-B{NN} | validator | Stage 4 (branch) | REFACTOR-B{NN} | Validate branch B{NN} |
| REVIEW-B{NN} | reviewer | Stage 4 (branch) | REFACTOR-B{NN} | Review branch B{NN} |
| FIX-B{NN}-{cycle} | refactorer | Fix (branch) | (none) | Fix issues in branch B{NN} |
| VALIDATE-B{NN}-R{cycle} | validator | Retry (branch) | FIX-B{NN}-{cycle} | Re-validate after fix |
| REVIEW-B{NN}-R{cycle} | reviewer | Retry (branch) | FIX-B{NN}-{cycle} | Re-review after fix |
**Independent mode**:
| Task ID | Role | Phase | Dependencies | Description |
|---------|------|-------|-------------|-------------|
| ANALYZE-{P}01 | analyzer | Stage 1 | (none) | Analyze for pipeline {P} target |
| DESIGN-{P}01 | designer | Stage 2 | ANALYZE-{P}01 | Design for pipeline {P} |
| REFACTOR-{P}01 | refactorer | Stage 3 | DESIGN-{P}01 | Implement pipeline {P} refactorings |
| VALIDATE-{P}01 | validator | Stage 4 | REFACTOR-{P}01 | Validate pipeline {P} |
| REVIEW-{P}01 | reviewer | Stage 4 | REFACTOR-{P}01 | Review pipeline {P} |
| FIX-{P}01-{cycle} | refactorer | Fix | (none) | Fix issues in pipeline {P} |
### Task Naming Rules
| Mode | Stage 3 | Stage 4 | Fix | Retry |
|------|---------|---------|-----|-------|
| Single | REFACTOR-001 | VALIDATE-001, REVIEW-001 | FIX-001 | VALIDATE-001-R1, REVIEW-001-R1 |
| Fan-out | REFACTOR-B01 | VALIDATE-B01, REVIEW-B01 | FIX-B01-1 | VALIDATE-B01-R1, REVIEW-B01-R1 |
| Independent | REFACTOR-A01 | VALIDATE-A01, REVIEW-A01 | FIX-A01-1 | VALIDATE-A01-R1, REVIEW-A01-R1 |
---
## Completion Action
When the pipeline completes (all tasks done, coordinator Phase 5):
```
AskUserQuestion({
questions: [{
question: "Team pipeline complete. What would you like to do?",
header: "Completion",
multiSelect: false,
options: [
{ label: "Archive & Clean (Recommended)", description: "Archive session, clean up tasks and team resources" },
{ label: "Keep Active", description: "Keep session active for follow-up work or inspection" },
{ label: "Export Results", description: "Export deliverables to a specified location, then clean" }
]
}]
})
```
| Choice | Action |
|--------|--------|
| Archive & Clean | Update session status="completed" -> TeamDelete() -> output final summary |
| Keep Active | Update session status="paused" -> output resume instructions: `Skill(skill="team-arch-opt", args="resume")` |
| Export Results | AskUserQuestion for target path -> copy deliverables -> Archive & Clean |
---
## Session Directory
**Single mode**:
```
.workflow/<session-id>/
+-- session.json # Session metadata + status + parallel_mode
+-- artifacts/
| +-- architecture-baseline.json # Analyzer: pre-refactoring metrics
| +-- architecture-report.md # Analyzer: ranked structural issue findings
| +-- refactoring-plan.md # Designer: prioritized refactoring plan
| +-- validation-results.json # Validator: post-refactoring validation
| +-- review-report.md # Reviewer: code review findings
+-- explorations/
| +-- cache-index.json # Shared explore cache
| +-- <hash>.md # Cached exploration results
+-- wisdom/
| +-- patterns.md # Discovered patterns and conventions
+-- .msg/
| +-- messages.jsonl # Message bus log
| +-- meta.json # Session state + cross-role state
+-- discussions/
| +-- DISCUSS-REFACTOR.md # Refactoring design discussion record
| +-- DISCUSS-REVIEW.md # Review discussion record
```
**Fan-out mode** (adds branches/ directory):
```
.workflow/<session-id>/
+-- session.json # + parallel_mode, branches, fix_cycles
+-- artifacts/
| +-- architecture-baseline.json # Shared baseline (all branches use this)
| +-- architecture-report.md # Shared architecture report
| +-- refactoring-plan.md # Shared plan with discrete REFACTOR-IDs
| +-- aggregate-results.json # Aggregated results from all branches
| +-- branches/
| +-- B01/
| | +-- refactoring-detail.md # Extracted REFACTOR-001 detail
| | +-- validation-results.json # Branch B01 validation
| | +-- review-report.md # Branch B01 review
| +-- B02/
| | +-- refactoring-detail.md
| | +-- validation-results.json
| | +-- review-report.md
| +-- B0N/
+-- explorations/ wisdom/ discussions/ # Same as single
```
**Independent mode** (adds pipelines/ directory):
```
.workflow/<session-id>/
+-- session.json # + parallel_mode, independent_targets, fix_cycles
+-- artifacts/
| +-- aggregate-results.json # Aggregated results from all pipelines
| +-- pipelines/
| +-- A/
| | +-- architecture-baseline.json
| | +-- architecture-report.md
| | +-- refactoring-plan.md
| | +-- validation-results.json
| | +-- review-report.md
| +-- B/
| +-- architecture-baseline.json
| +-- ...
+-- explorations/ wisdom/ discussions/ # Same as single
```
## Session Resume
Coordinator supports `--resume` / `--continue` for interrupted sessions:
1. Scan session directory for sessions with status "active" or "paused"
2. Multiple matches -> AskUserQuestion for selection
3. Audit TaskList -> reconcile session state <-> task status
4. Reset in_progress -> pending (interrupted tasks)
5. Rebuild team and spawn needed workers only
6. Create missing tasks with correct blockedBy
7. Kick first executable task -> Phase 4 coordination loop
## Shared Resources
| Resource | Path | Usage |
|----------|------|-------|
| Architecture Baseline | [<session>/artifacts/architecture-baseline.json](<session>/artifacts/architecture-baseline.json) | Pre-refactoring metrics for comparison |
| Architecture Report | [<session>/artifacts/architecture-report.md](<session>/artifacts/architecture-report.md) | Analyzer output consumed by designer |
| Refactoring Plan | [<session>/artifacts/refactoring-plan.md](<session>/artifacts/refactoring-plan.md) | Designer output consumed by refactorer |
| Validation Results | [<session>/artifacts/validation-results.json](<session>/artifacts/validation-results.json) | Validator output consumed by reviewer |
## Error Handling
| Scenario | Resolution |
|----------|------------|
| Role spec file not found | Error with expected path (role-specs/<name>.md) |
| Command file not found | Fallback to inline execution in coordinator role.md |
| CLI tool spec not found | Error with expected path (cli-tools/<name>.md) |
| Fast-advance orphan detected | Coordinator resets task to pending on next check |
| consensus_blocked HIGH | Coordinator creates revision task or pauses pipeline |
| team-worker agent unavailable | Error: requires .claude/agents/team-worker.md |
| Completion action timeout | Default to Keep Active |
| Analysis tool not available | Fallback to static analysis methods |
| Validation regression detected | Auto-create FIX task with regression details (scoped to branch/pipeline) |
| Review-fix cycle exceeds 3 iterations | Escalate to user with summary of remaining issues (per-branch/pipeline scope) |
| One branch REFACTOR fails | Mark that branch failed, other branches continue to completion |
| Branch scope overlap detected | Designer constrains non-overlapping target files; REFACTOR logs warning on detection |
| Meta.json concurrent writes | Each worker writes only its own namespace key (e.g., `refactorer.B01`) |
| Branch fix cycle >= 3 | Escalate only that branch to user, other branches continue independently |
| max_branches exceeded | Coordinator truncates to top N refactorings by priority at CP-2.5 |
| Independent pipeline partial failure | Failed pipeline marked, others continue; aggregate reports partial results |

View File

@@ -0,0 +1,80 @@
---
prefix: ANALYZE
inner_loop: false
cli_tools: [explore]
message_types:
success: analyze_complete
error: error
---
# Architecture Analyzer
Analyze codebase architecture to identify structural issues: dependency cycles, coupling/cohesion problems, layering violations, God Classes, code duplication, dead code, and API surface bloat. Produce quantified baseline metrics and a ranked architecture report.
## Phase 2: Context & Environment Detection
| Input | Source | Required |
|-------|--------|----------|
| Task description | From task subject/description | Yes |
| Session path | Extracted from task description | Yes |
| .msg/meta.json | <session>/wisdom/.msg/meta.json | No |
1. Extract session path and target scope from task description
2. Detect project type by scanning for framework markers:
| Signal File | Project Type | Analysis Focus |
|-------------|-------------|----------------|
| package.json + React/Vue/Angular | Frontend | Component tree, prop drilling, state management, barrel exports |
| package.json + Express/Fastify/NestJS | Backend Node | Service layer boundaries, middleware chains, DB access patterns |
| Cargo.toml / go.mod / pom.xml | Native/JVM Backend | Module boundaries, trait/interface usage, dependency injection |
| Mixed framework markers | Full-stack / Monorepo | Cross-package dependencies, shared types, API contracts |
| CLI entry / bin/ directory | CLI Tool | Command structure, plugin architecture, configuration layering |
| No detection | Generic | All architecture dimensions |
3. Use `explore` CLI tool to map module structure, dependency graph, and layer boundaries within target scope
4. Detect available analysis tools (linters, dependency analyzers, build tools)
## Phase 3: Architecture Analysis
Execute analysis based on detected project type:
**Dependency analysis**:
- Build import/require graph across modules
- Detect circular dependencies (direct and transitive cycles)
- Identify layering violations (e.g., UI importing from data layer, utils importing from domain)
- Calculate fan-in/fan-out per module (high fan-out = fragile hub, high fan-in = tightly coupled)
**Structural analysis**:
- Identify God Classes / God Modules (> 500 LOC, > 10 public methods, too many responsibilities)
- Calculate coupling metrics (afferent/efferent coupling per module)
- Calculate cohesion metrics (LCOM -- Lack of Cohesion of Methods)
- Detect code duplication (repeated logic blocks, copy-paste patterns)
- Identify missing abstractions (repeated conditionals, switch-on-type patterns)
**API surface analysis**:
- Count exported symbols per module (export bloat detection)
- Identify dead exports (exported but never imported elsewhere)
- Detect dead code (unreachable functions, unused variables, orphan files)
- Check for pattern inconsistencies (mixed naming conventions, inconsistent error handling)
**All project types**:
- Collect quantified architecture baseline metrics (dependency count, cycle count, coupling scores, LOC distribution)
- Rank top 3-7 architecture issues by severity (Critical / High / Medium)
- Record evidence: file paths, line numbers, measured values
## Phase 4: Report Generation
1. Write architecture baseline to `<session>/artifacts/architecture-baseline.json`:
- Module count, dependency count, cycle count, average coupling, average cohesion
- God Class candidates with LOC and method count
- Dead code file count, dead export count
- Timestamp and project type details
2. Write architecture report to `<session>/artifacts/architecture-report.md`:
- Ranked list of architecture issues with severity, location (file:line or module), measured impact
- Issue categories: CYCLE, COUPLING, COHESION, GOD_CLASS, DUPLICATION, LAYER_VIOLATION, DEAD_CODE, API_BLOAT
- Evidence summary per issue
- Detected project type and analysis methods used
3. Update `<session>/wisdom/.msg/meta.json` under `analyzer` namespace:
- Read existing -> merge `{ "analyzer": { project_type, issue_count, top_issue, scope, categories } }` -> write back

View File

@@ -0,0 +1,118 @@
---
prefix: DESIGN
inner_loop: false
discuss_rounds: [DISCUSS-REFACTOR]
cli_tools: [discuss]
message_types:
success: design_complete
error: error
---
# Refactoring Designer
Analyze architecture reports and baseline metrics to design a prioritized refactoring plan with concrete strategies, expected structural improvements, and risk assessments.
## Phase 2: Analysis Loading
| Input | Source | Required |
|-------|--------|----------|
| Architecture report | <session>/artifacts/architecture-report.md | Yes |
| Architecture baseline | <session>/artifacts/architecture-baseline.json | Yes |
| .msg/meta.json | <session>/wisdom/.msg/meta.json | Yes |
| Wisdom files | <session>/wisdom/patterns.md | No |
1. Extract session path from task description
2. Read architecture report -- extract ranked issue list with severities and categories
3. Read architecture baseline -- extract current structural metrics
4. Load .msg/meta.json for analyzer findings (project_type, scope)
5. Assess overall refactoring complexity:
| Issue Count | Severity Mix | Complexity |
|-------------|-------------|------------|
| 1-2 | All Medium | Low |
| 2-3 | Mix of High/Medium | Medium |
| 3+ or any Critical | Any Critical present | High |
## Phase 3: Strategy Formulation
For each architecture issue, select refactoring approach by type:
| Issue Type | Strategies | Risk Level |
|------------|-----------|------------|
| Circular dependency | Interface extraction, dependency inversion, mediator pattern | High |
| God Class/Module | SRP decomposition, extract class/module, delegate pattern | High |
| Layering violation | Move to correct layer, introduce Facade, add anti-corruption layer | Medium |
| Code duplication | Extract shared utility/base class, template method pattern | Low |
| High coupling | Introduce interface/abstraction, dependency injection, event-driven | Medium |
| API bloat / dead exports | Privatize internals, re-export only public API, barrel file cleanup | Low |
| Dead code | Safe removal with reference verification | Low |
| Missing abstraction | Extract interface/type, introduce strategy/factory pattern | Medium |
Prioritize refactorings by impact/effort ratio:
| Priority | Criteria |
|----------|----------|
| P0 (Critical) | High impact + Low effort -- quick wins (dead code removal, simple moves) |
| P1 (High) | High impact + Medium effort (cycle breaking, layer fixes) |
| P2 (Medium) | Medium impact + Low effort (duplication extraction) |
| P3 (Low) | Low impact or High effort -- defer (large God Class decomposition) |
If complexity is High, invoke `discuss` CLI tool (DISCUSS-REFACTOR round) to evaluate trade-offs between competing strategies before finalizing the plan.
Define measurable success criteria per refactoring (target metric improvement or structural change).
## Phase 4: Plan Output
1. Write refactoring plan to `<session>/artifacts/refactoring-plan.md`:
Each refactoring MUST have a unique REFACTOR-ID and self-contained detail block:
```markdown
### REFACTOR-001: <title>
- Priority: P0
- Target issue: <issue from report>
- Issue type: <CYCLE|COUPLING|GOD_CLASS|DUPLICATION|LAYER_VIOLATION|DEAD_CODE|API_BLOAT>
- Target files: <file-list>
- Strategy: <selected approach>
- Expected improvement: <metric> by <description>
- Risk level: <Low/Medium/High>
- Success criteria: <specific structural change to verify>
- Implementation guidance:
1. <step 1>
2. <step 2>
3. <step 3>
### REFACTOR-002: <title>
...
```
Requirements:
- Each REFACTOR-ID is sequentially numbered (REFACTOR-001, REFACTOR-002, ...)
- Each refactoring must be **non-overlapping** in target files (no two REFACTOR-IDs modify the same file unless explicitly noted with conflict resolution)
- Implementation guidance must be self-contained -- a branch refactorer should be able to work from a single REFACTOR block without reading others
2. Update `<session>/wisdom/.msg/meta.json` under `designer` namespace:
- Read existing -> merge -> write back:
```json
{
"designer": {
"complexity": "<Low|Medium|High>",
"refactoring_count": 4,
"priorities": ["P0", "P0", "P1", "P2"],
"discuss_used": false,
"refactorings": [
{
"id": "REFACTOR-001",
"title": "<title>",
"issue_type": "<CYCLE|COUPLING|...>",
"priority": "P0",
"target_files": ["src/a.ts", "src/b.ts"],
"expected_improvement": "<metric> by <description>",
"success_criteria": "<threshold>"
}
]
}
}
```
3. If DISCUSS-REFACTOR was triggered, record discussion summary in `<session>/discussions/DISCUSS-REFACTOR.md`

View File

@@ -0,0 +1,106 @@
---
prefix: REFACTOR
inner_loop: true
additional_prefixes: [FIX]
cli_tools: [explore]
message_types:
success: refactor_complete
error: error
fix: fix_required
---
# Code Refactorer
Implement architecture refactoring changes following the design plan. For FIX tasks, apply targeted corrections based on review/validation feedback.
## Modes
| Mode | Task Prefix | Trigger | Focus |
|------|-------------|---------|-------|
| Refactor | REFACTOR | Design plan ready | Apply refactorings per plan priority |
| Fix | FIX | Review/validation feedback | Targeted fixes for identified issues |
## Phase 2: Plan & Context Loading
| Input | Source | Required |
|-------|--------|----------|
| Refactoring plan | <session>/artifacts/refactoring-plan.md | Yes (REFACTOR, no branch) |
| Branch refactoring detail | <session>/artifacts/branches/B{NN}/refactoring-detail.md | Yes (REFACTOR with branch) |
| Pipeline refactoring plan | <session>/artifacts/pipelines/{P}/refactoring-plan.md | Yes (REFACTOR with pipeline) |
| Review/validation feedback | From task description | Yes (FIX) |
| .msg/meta.json | <session>/wisdom/.msg/meta.json | Yes |
| Wisdom files | <session>/wisdom/patterns.md | No |
| Context accumulator | From prior REFACTOR/FIX tasks | Yes (inner loop) |
1. Extract session path and task mode (REFACTOR or FIX) from task description
2. **Detect branch/pipeline context** from task description:
| Task Description Field | Value | Context |
|----------------------|-------|---------
| `BranchId: B{NN}` | Present | Fan-out branch -- load single refactoring detail |
| `PipelineId: {P}` | Present | Independent pipeline -- load pipeline-scoped plan |
| Neither present | - | Single mode -- load full refactoring plan |
3. **Load refactoring context by mode**:
- **Single mode (no branch)**: Read `<session>/artifacts/refactoring-plan.md` -- extract ALL priority-ordered changes
- **Fan-out branch**: Read `<session>/artifacts/branches/B{NN}/refactoring-detail.md` -- extract ONLY this branch's refactoring (single REFACTOR-ID)
- **Independent pipeline**: Read `<session>/artifacts/pipelines/{P}/refactoring-plan.md` -- extract this pipeline's plan
4. For FIX: parse review/validation feedback for specific issues to address
5. Use `explore` CLI tool to load implementation context for target files
6. For inner loop (single mode only): load context_accumulator from prior REFACTOR/FIX tasks
**Meta.json namespace**:
- Single: write to `refactorer` namespace
- Fan-out: write to `refactorer.B{NN}` namespace
- Independent: write to `refactorer.{P}` namespace
## Phase 3: Code Implementation
Implementation backend selection:
| Backend | Condition | Method |
|---------|-----------|--------|
| CLI | Multi-file refactoring with clear plan | ccw cli --tool gemini --mode write |
| Direct | Single-file changes or targeted fixes | Inline Edit/Write tools |
For REFACTOR tasks:
- **Single mode**: Apply refactorings in plan priority order (P0 first, then P1, etc.)
- **Fan-out branch**: Apply ONLY this branch's single refactoring (from refactoring-detail.md)
- **Independent pipeline**: Apply this pipeline's refactorings in priority order
- Follow implementation guidance from plan (target files, patterns)
- **Preserve existing behavior -- refactoring must not change functionality**
- **Update ALL import references** when moving/renaming modules
- **Update ALL test files** that reference moved/renamed symbols
For FIX tasks:
- Read specific issues from review/validation feedback
- Apply targeted corrections to flagged code locations
- Verify the fix addresses the exact concern raised
General rules:
- Make minimal, focused changes per refactoring
- Add comments only where refactoring logic is non-obvious
- Preserve existing code style and conventions
- Verify no dangling imports after module moves
## Phase 4: Self-Validation
| Check | Method | Pass Criteria |
|-------|--------|---------------|
| Syntax | IDE diagnostics or build check | No new errors |
| File integrity | Verify all planned files exist and are modified | All present |
| Import integrity | Verify no broken imports after moves | All imports resolve |
| Acceptance | Match refactoring plan success criteria | All structural changes applied |
| No regression | Run existing tests if available | No new failures |
If validation fails, attempt auto-fix (max 2 attempts) before reporting error.
Append to context_accumulator for next REFACTOR/FIX task (single/inner-loop mode only):
- Files modified, refactorings applied, validation results
- Any discovered patterns or caveats for subsequent iterations
**Branch output paths**:
- Single: write artifacts to `<session>/artifacts/`
- Fan-out: write artifacts to `<session>/artifacts/branches/B{NN}/`
- Independent: write artifacts to `<session>/artifacts/pipelines/{P}/`

View File

@@ -0,0 +1,116 @@
---
prefix: REVIEW
inner_loop: false
additional_prefixes: [QUALITY]
discuss_rounds: [DISCUSS-REVIEW]
cli_tools: [discuss]
message_types:
success: review_complete
error: error
fix: fix_required
---
# Architecture Reviewer
Review refactoring code changes for correctness, pattern consistency, completeness, migration safety, and adherence to best practices. Provide structured verdicts with actionable feedback.
## Phase 2: Context Loading
| Input | Source | Required |
|-------|--------|----------|
| Refactoring code changes | From REFACTOR task artifacts / git diff | Yes |
| Refactoring plan / detail | Varies by mode (see below) | Yes |
| Validation results | Varies by mode (see below) | No |
| .msg/meta.json | <session>/wisdom/.msg/meta.json | Yes |
1. Extract session path from task description
2. **Detect branch/pipeline context** from task description:
| Task Description Field | Value | Context |
|----------------------|-------|---------
| `BranchId: B{NN}` | Present | Fan-out branch -- review only this branch's changes |
| `PipelineId: {P}` | Present | Independent pipeline -- review pipeline-scoped changes |
| Neither present | - | Single mode -- review all refactoring changes |
3. **Load refactoring context by mode**:
- Single: Read `<session>/artifacts/refactoring-plan.md`
- Fan-out branch: Read `<session>/artifacts/branches/B{NN}/refactoring-detail.md`
- Independent: Read `<session>/artifacts/pipelines/{P}/refactoring-plan.md`
4. Load .msg/meta.json for scoped refactorer namespace:
- Single: `refactorer` namespace
- Fan-out: `refactorer.B{NN}` namespace
- Independent: `refactorer.{P}` namespace
5. Identify changed files from refactorer context -- read ONLY files modified by this branch/pipeline
6. If validation results available, read from scoped path:
- Single: `<session>/artifacts/validation-results.json`
- Fan-out: `<session>/artifacts/branches/B{NN}/validation-results.json`
- Independent: `<session>/artifacts/pipelines/{P}/validation-results.json`
## Phase 3: Multi-Dimension Review
Analyze refactoring changes across five dimensions:
| Dimension | Focus | Severity |
|-----------|-------|----------|
| Correctness | No behavior changes, all references updated, no dangling imports | Critical |
| Pattern consistency | Follows existing patterns, naming consistent, language-idiomatic | High |
| Completeness | All related code updated (imports, tests, config, documentation) | High |
| Migration safety | No dangling references, backward compatible, public API preserved | Critical |
| Best practices | Clean Architecture / SOLID principles, appropriate abstraction level | Medium |
Per-dimension review process:
- Scan modified files for patterns matching each dimension
- Record findings with severity (Critical / High / Medium / Low)
- Include specific file:line references and suggested fixes
**Correctness checks**:
- Verify moved code preserves original behavior (no logic changes mixed with structural changes)
- Check all import/require statements updated to new paths
- Verify no orphaned files left behind after moves
**Pattern consistency checks**:
- New module names follow existing naming conventions
- Extracted interfaces/classes use consistent patterns with existing codebase
- File organization matches project conventions (e.g., index files, barrel exports)
**Completeness checks**:
- All test files updated for moved/renamed modules
- Configuration files updated if needed (e.g., path aliases, build configs)
- Type definitions updated for extracted interfaces
**Migration safety checks**:
- Public API surface unchanged (same exports available to consumers)
- No circular dependencies introduced by the refactoring
- Re-exports in place if module paths changed for backward compatibility
**Best practices checks**:
- Extracted modules have clear single responsibility
- Dependency direction follows layer conventions (dependencies flow inward)
- Appropriate abstraction level (not over-engineered, not under-abstracted)
If any Critical findings detected, invoke `discuss` CLI tool (DISCUSS-REVIEW round) to validate the assessment before issuing verdict.
## Phase 4: Verdict & Feedback
Classify overall verdict based on findings:
| Verdict | Condition | Action |
|---------|-----------|--------|
| APPROVE | No Critical or High findings | Send review_complete |
| REVISE | Has High findings, no Critical | Send fix_required with detailed feedback |
| REJECT | Has Critical findings or fundamental approach flaw | Send fix_required + flag for designer escalation |
1. Write review report to scoped output path:
- Single: `<session>/artifacts/review-report.md`
- Fan-out: `<session>/artifacts/branches/B{NN}/review-report.md`
- Independent: `<session>/artifacts/pipelines/{P}/review-report.md`
- Content: Per-dimension findings with severity, file:line, description; Overall verdict with rationale; Specific fix instructions for REVISE/REJECT verdicts
2. Update `<session>/wisdom/.msg/meta.json` under scoped namespace:
- Single: merge `{ "reviewer": { verdict, finding_count, critical_count, dimensions_reviewed } }`
- Fan-out: merge `{ "reviewer.B{NN}": { verdict, finding_count, critical_count, dimensions_reviewed } }`
- Independent: merge `{ "reviewer.{P}": { verdict, finding_count, critical_count, dimensions_reviewed } }`
3. If DISCUSS-REVIEW was triggered, record discussion summary in `<session>/discussions/DISCUSS-REVIEW.md` (or `DISCUSS-REVIEW-B{NN}.md` for branch-scoped discussions)

View File

@@ -0,0 +1,117 @@
---
prefix: VALIDATE
inner_loop: false
message_types:
success: validate_complete
error: error
fix: fix_required
---
# Architecture Validator
Validate refactoring changes by running build checks, test suites, dependency metric comparisons, and API compatibility verification. Ensure refactoring improves architecture without breaking functionality.
## Phase 2: Environment & Baseline Loading
| Input | Source | Required |
|-------|--------|----------|
| Architecture baseline | <session>/artifacts/architecture-baseline.json (shared) | Yes |
| Refactoring plan / detail | Varies by mode (see below) | Yes |
| .msg/meta.json | <session>/wisdom/.msg/meta.json | Yes |
1. Extract session path from task description
2. **Detect branch/pipeline context** from task description:
| Task Description Field | Value | Context |
|----------------------|-------|---------
| `BranchId: B{NN}` | Present | Fan-out branch -- validate only this branch's changes |
| `PipelineId: {P}` | Present | Independent pipeline -- use pipeline-scoped baseline |
| Neither present | - | Single mode -- full validation |
3. **Load architecture baseline**:
- Single / Fan-out: Read `<session>/artifacts/architecture-baseline.json` (shared baseline)
- Independent: Read `<session>/artifacts/pipelines/{P}/architecture-baseline.json`
4. **Load refactoring context**:
- Single: Read `<session>/artifacts/refactoring-plan.md` -- all success criteria
- Fan-out branch: Read `<session>/artifacts/branches/B{NN}/refactoring-detail.md` -- only this branch's criteria
- Independent: Read `<session>/artifacts/pipelines/{P}/refactoring-plan.md`
5. Load .msg/meta.json for project type and refactoring scope
6. Detect available validation tools from project:
| Signal | Validation Tool | Method |
|--------|----------------|--------|
| package.json + tsc | TypeScript compiler | Type-check entire project |
| package.json + vitest/jest | Test runner | Run existing test suite |
| package.json + eslint | Linter | Run lint checks for import/export issues |
| Cargo.toml | Rust compiler | cargo check + cargo test |
| go.mod | Go tools | go build + go test |
| Makefile with test target | Custom tests | make test |
| No tooling detected | Manual validation | File existence + import grep checks |
7. Get changed files scope from .msg/meta.json:
- Single: `refactorer` namespace
- Fan-out: `refactorer.B{NN}` namespace
- Independent: `refactorer.{P}` namespace
## Phase 3: Validation Execution
Run validations across four dimensions:
**Build validation**:
- Compile/type-check the project -- zero new errors allowed
- Verify all moved/renamed files are correctly referenced
- Check for missing imports or unresolved modules
**Test validation**:
- Run existing test suite -- all previously passing tests must still pass
- Identify any tests that need updating due to module moves (update, don't skip)
- Check for test file imports that reference old paths
**Dependency metric validation**:
- Recalculate architecture metrics post-refactoring
- Compare coupling scores against baseline (must improve or stay neutral)
- Verify no new circular dependencies introduced
- Check cohesion metrics for affected modules
**API compatibility validation**:
- Verify public API signatures are preserved (exported function/class/type names)
- Check for dangling references (imports pointing to removed/moved files)
- Verify no new dead exports introduced by the refactoring
- Check that re-exports maintain backward compatibility where needed
**Branch-scoped validation** (fan-out mode):
- Only validate metrics relevant to this branch's refactoring (from refactoring-detail.md)
- Still check for regressions across all metrics (not just branch-specific ones)
## Phase 4: Result Analysis
Compare against baseline and plan criteria:
| Metric | Threshold | Verdict |
|--------|-----------|---------|
| Build passes | Zero compilation errors | PASS |
| All tests pass | No new test failures | PASS |
| Coupling improved or neutral | No metric degradation > 5% | PASS |
| No new cycles introduced | Cycle count <= baseline | PASS |
| All plan success criteria met | Every criterion satisfied | PASS |
| Partial improvement | Some metrics improved, none degraded | WARN |
| Build fails | Compilation errors detected | FAIL -> fix_required |
| Test failures | Previously passing tests now fail | FAIL -> fix_required |
| New cycles introduced | Cycle count > baseline | FAIL -> fix_required |
| Dangling references | Unresolved imports detected | FAIL -> fix_required |
1. Write validation results to output path:
- Single: `<session>/artifacts/validation-results.json`
- Fan-out: `<session>/artifacts/branches/B{NN}/validation-results.json`
- Independent: `<session>/artifacts/pipelines/{P}/validation-results.json`
- Content: Per-dimension: name, baseline value, current value, improvement/regression, verdict; Overall verdict: PASS / WARN / FAIL; Failure details (if any)
2. Update `<session>/wisdom/.msg/meta.json` under scoped namespace:
- Single: merge `{ "validator": { verdict, improvements, regressions, build_pass, test_pass } }`
- Fan-out: merge `{ "validator.B{NN}": { verdict, improvements, regressions, build_pass, test_pass } }`
- Independent: merge `{ "validator.{P}": { verdict, improvements, regressions, build_pass, test_pass } }`
3. If verdict is FAIL, include detailed feedback in message for FIX task creation:
- Which validations failed, specific errors, suggested investigation areas

View File

@@ -0,0 +1,371 @@
# Command: Dispatch
Create the architecture optimization task chain with correct dependencies and structured task descriptions. Supports single, fan-out, independent, and auto parallel modes.
## Phase 2: Context Loading
| Input | Source | Required |
|-------|--------|----------|
| User requirement | From coordinator Phase 1 | Yes |
| Session folder | From coordinator Phase 2 | Yes |
| Pipeline definition | From SKILL.md Pipeline Definitions | Yes |
| Parallel mode | From session.json `parallel_mode` | Yes |
| Max branches | From session.json `max_branches` | Yes |
| Independent targets | From session.json `independent_targets` (independent mode only) | Conditional |
1. Load user requirement and refactoring scope from session.json
2. Load pipeline stage definitions from SKILL.md Task Metadata Registry
3. Read `parallel_mode` and `max_branches` from session.json
4. For `independent` mode: read `independent_targets` array from session.json
## Phase 3: Task Chain Creation (Mode-Branched)
### Task Description Template
Every task description uses structured format for clarity:
```
TaskCreate({
subject: "<TASK-ID>",
description: "PURPOSE: <what this task achieves> | Success: <measurable completion criteria>
TASK:
- <step 1: specific action>
- <step 2: specific action>
- <step 3: specific action>
CONTEXT:
- Session: <session-folder>
- Scope: <refactoring-scope>
- Branch: <branch-id or 'none'>
- Upstream artifacts: <artifact-1>, <artifact-2>
- Shared memory: <session>/wisdom/.msg/meta.json
EXPECTED: <deliverable path> + <quality criteria>
CONSTRAINTS: <scope limits, focus areas>
---
InnerLoop: <true|false>
BranchId: <B01|A|none>"
})
TaskUpdate({ taskId: "<TASK-ID>", addBlockedBy: [<dependency-list>], owner: "<role>" })
```
### Mode Router
| Mode | Action |
|------|--------|
| `single` | Create 5 tasks (ANALYZE → DESIGN → REFACTOR → VALIDATE + REVIEW) -- unchanged from linear pipeline |
| `auto` | Create ANALYZE-001 + DESIGN-001 only. **Defer branch creation to CP-2.5** after design completes |
| `fan-out` | Create ANALYZE-001 + DESIGN-001 only. **Defer branch creation to CP-2.5** after design completes |
| `independent` | Create M complete pipelines immediately (one per target) |
---
### Single Mode Task Chain
Create tasks in dependency order (backward compatible, unchanged):
**ANALYZE-001** (analyzer, Stage 1):
```
TaskCreate({
subject: "ANALYZE-001",
description: "PURPOSE: Analyze codebase architecture to identify structural issues | Success: Baseline metrics captured, top 3-7 issues ranked by severity
TASK:
- Detect project type and available analysis tools
- Execute analysis across relevant dimensions (dependencies, coupling, cohesion, layering, duplication, dead code)
- Collect baseline metrics and rank architecture issues by severity
CONTEXT:
- Session: <session-folder>
- Scope: <refactoring-scope>
- Branch: none
- Shared memory: <session>/wisdom/.msg/meta.json
EXPECTED: <session>/artifacts/architecture-baseline.json + <session>/artifacts/architecture-report.md | Quantified metrics with evidence
CONSTRAINTS: Focus on <refactoring-scope> | Analyze before any changes
---
InnerLoop: false"
})
TaskUpdate({ taskId: "ANALYZE-001", owner: "analyzer" })
```
**DESIGN-001** (designer, Stage 2):
```
TaskCreate({
subject: "DESIGN-001",
description: "PURPOSE: Design prioritized refactoring plan from architecture analysis | Success: Actionable plan with measurable success criteria per refactoring
TASK:
- Analyze architecture report and baseline metrics
- Select refactoring strategies per issue type
- Prioritize by impact/effort ratio, define success criteria
- Each refactoring MUST have a unique REFACTOR-ID (REFACTOR-001, REFACTOR-002, ...) with non-overlapping target files
CONTEXT:
- Session: <session-folder>
- Scope: <refactoring-scope>
- Branch: none
- Upstream artifacts: architecture-baseline.json, architecture-report.md
- Shared memory: <session>/wisdom/.msg/meta.json
EXPECTED: <session>/artifacts/refactoring-plan.md | Priority-ordered with structural improvement targets, discrete REFACTOR-IDs
CONSTRAINTS: Focus on highest-impact refactorings | Risk assessment required | Non-overlapping file targets per REFACTOR-ID
---
InnerLoop: false"
})
TaskUpdate({ taskId: "DESIGN-001", addBlockedBy: ["ANALYZE-001"], owner: "designer" })
```
**REFACTOR-001** (refactorer, Stage 3):
```
TaskCreate({
subject: "REFACTOR-001",
description: "PURPOSE: Implement refactoring changes per design plan | Success: All planned refactorings applied, code compiles, existing tests pass
TASK:
- Load refactoring plan and identify target files
- Apply refactorings in priority order (P0 first)
- Update all import references for moved/renamed modules
- Validate changes compile and pass existing tests
CONTEXT:
- Session: <session-folder>
- Scope: <refactoring-scope>
- Branch: none
- Upstream artifacts: refactoring-plan.md
- Shared memory: <session>/wisdom/.msg/meta.json
EXPECTED: Modified source files + validation passing | Refactorings applied without regressions
CONSTRAINTS: Preserve existing behavior | Update all references | Follow code conventions
---
InnerLoop: true"
})
TaskUpdate({ taskId: "REFACTOR-001", addBlockedBy: ["DESIGN-001"], owner: "refactorer" })
```
**VALIDATE-001** (validator, Stage 4 - parallel):
```
TaskCreate({
subject: "VALIDATE-001",
description: "PURPOSE: Validate refactoring results against baseline | Success: Build passes, tests pass, no metric regressions, API compatible
TASK:
- Load architecture baseline and plan success criteria
- Run build validation (compilation, type checking)
- Run test validation (existing test suite)
- Compare dependency metrics against baseline
- Verify API compatibility (no dangling references)
CONTEXT:
- Session: <session-folder>
- Scope: <refactoring-scope>
- Branch: none
- Upstream artifacts: architecture-baseline.json, refactoring-plan.md
- Shared memory: <session>/wisdom/.msg/meta.json
EXPECTED: <session>/artifacts/validation-results.json | Per-dimension validation with verdicts
CONSTRAINTS: Must compare against baseline | Flag any regressions or broken imports
---
InnerLoop: false"
})
TaskUpdate({ taskId: "VALIDATE-001", addBlockedBy: ["REFACTOR-001"], owner: "validator" })
```
**REVIEW-001** (reviewer, Stage 4 - parallel):
```
TaskCreate({
subject: "REVIEW-001",
description: "PURPOSE: Review refactoring code for correctness, pattern consistency, and migration safety | Success: All dimensions reviewed, verdict issued
TASK:
- Load modified files and refactoring plan
- Review across 5 dimensions: correctness, pattern consistency, completeness, migration safety, best practices
- Issue verdict: APPROVE, REVISE, or REJECT with actionable feedback
CONTEXT:
- Session: <session-folder>
- Scope: <refactoring-scope>
- Branch: none
- Upstream artifacts: refactoring-plan.md, validation-results.json (if available)
- Shared memory: <session>/wisdom/.msg/meta.json
EXPECTED: <session>/artifacts/review-report.md | Per-dimension findings with severity
CONSTRAINTS: Focus on refactoring changes only | Provide specific file:line references
---
InnerLoop: false"
})
TaskUpdate({ taskId: "REVIEW-001", addBlockedBy: ["REFACTOR-001"], owner: "reviewer" })
```
---
### Auto / Fan-out Mode Task Chain (Deferred Branching)
For `auto` and `fan-out` modes, create only shared stages now. Branch tasks are created at **CP-2.5** after DESIGN-001 completes.
Create ANALYZE-001 and DESIGN-001 with same templates as single mode above.
**Do NOT create REFACTOR/VALIDATE/REVIEW tasks yet.** They are created by the CP-2.5 Branch Creation subroutine in monitor.md.
---
### Independent Mode Task Chain
For `independent` mode, create M complete pipelines -- one per target in `independent_targets` array.
Pipeline prefix chars: `A, B, C, D, E, F, G, H, I, J` (from config `pipeline_prefix_chars`).
For each target index `i` (0-based), with prefix char `P = pipeline_prefix_chars[i]`:
```
// Create session subdirectory for this pipeline
Bash("mkdir -p <session>/artifacts/pipelines/<P>")
TaskCreate({ subject: "ANALYZE-<P>01", ... })
TaskCreate({ subject: "DESIGN-<P>01", ... })
TaskUpdate({ taskId: "DESIGN-<P>01", addBlockedBy: ["ANALYZE-<P>01"] })
TaskCreate({ subject: "REFACTOR-<P>01", ... })
TaskUpdate({ taskId: "REFACTOR-<P>01", addBlockedBy: ["DESIGN-<P>01"] })
TaskCreate({ subject: "VALIDATE-<P>01", ... })
TaskUpdate({ taskId: "VALIDATE-<P>01", addBlockedBy: ["REFACTOR-<P>01"] })
TaskCreate({ subject: "REVIEW-<P>01", ... })
TaskUpdate({ taskId: "REVIEW-<P>01", addBlockedBy: ["REFACTOR-<P>01"] })
```
Task descriptions follow same template as single mode, with additions:
- `Pipeline: <P>` in CONTEXT
- Artifact paths use `<session>/artifacts/pipelines/<P>/` instead of `<session>/artifacts/`
- Meta.json namespace uses `<role>.<P>` (e.g., `analyzer.A`, `refactorer.B`)
- Each pipeline's scope is its specific target from `independent_targets[i]`
Example for pipeline A with target "refactor auth module":
```
TaskCreate({
subject: "ANALYZE-A01",
description: "PURPOSE: Analyze auth module architecture | Success: Auth module structural issues identified
TASK:
- Detect project type and available analysis tools
- Execute architecture analysis focused on auth module
- Collect baseline metrics and rank auth module issues
CONTEXT:
- Session: <session-folder>
- Scope: refactor auth module
- Pipeline: A
- Shared memory: <session>/wisdom/.msg/meta.json (namespace: analyzer.A)
EXPECTED: <session>/artifacts/pipelines/A/architecture-baseline.json + architecture-report.md
CONSTRAINTS: Focus on auth module scope
---
InnerLoop: false
PipelineId: A"
})
TaskUpdate({ taskId: "ANALYZE-A01", owner: "analyzer" })
```
---
### CP-2.5: Branch Creation Subroutine
**Triggered by**: monitor.md handleCallback when DESIGN-001 completes in `auto` or `fan-out` mode.
**Procedure**:
1. Read `<session>/artifacts/refactoring-plan.md` to count REFACTOR-IDs
2. Read `.msg/meta.json` -> `designer.refactoring_count`
3. **Auto mode decision**:
| Refactoring Count | Decision |
|-------------------|----------|
| count <= 2 | Switch to `single` mode -- create REFACTOR-001, VALIDATE-001, REVIEW-001 (standard single pipeline) |
| count >= 3 | Switch to `fan-out` mode -- create branch tasks below |
4. Update session.json with resolved `parallel_mode` (auto -> single or fan-out)
5. **Fan-out branch creation** (when count >= 3 or forced fan-out):
- Truncate to `max_branches` if `refactoring_count > max_branches` (keep top N by priority)
- For each refactoring `i` (1-indexed), branch ID = `B{NN}` where NN = zero-padded i:
```
// Create branch artifact directory
Bash("mkdir -p <session>/artifacts/branches/B{NN}")
// Extract single REFACTOR detail to branch
Write("<session>/artifacts/branches/B{NN}/refactoring-detail.md",
extracted REFACTOR-{NNN} block from refactoring-plan.md)
```
6. Create branch tasks for each branch B{NN}:
```
TaskCreate({
subject: "REFACTOR-B{NN}",
description: "PURPOSE: Implement refactoring REFACTOR-{NNN} | Success: Single refactoring applied, compiles, tests pass
TASK:
- Load refactoring detail from branches/B{NN}/refactoring-detail.md
- Apply this single refactoring to target files
- Update all import references for moved/renamed modules
- Validate changes compile and pass existing tests
CONTEXT:
- Session: <session-folder>
- Branch: B{NN}
- Upstream artifacts: branches/B{NN}/refactoring-detail.md
- Shared memory: <session>/wisdom/.msg/meta.json (namespace: refactorer.B{NN})
EXPECTED: Modified source files for REFACTOR-{NNN} only
CONSTRAINTS: Only implement this branch's refactoring | Do not touch files outside REFACTOR-{NNN} scope
---
InnerLoop: false
BranchId: B{NN}"
})
TaskUpdate({ taskId: "REFACTOR-B{NN}", addBlockedBy: ["DESIGN-001"], owner: "refactorer" })
TaskCreate({
subject: "VALIDATE-B{NN}",
description: "PURPOSE: Validate branch B{NN} refactoring | Success: REFACTOR-{NNN} passes build, tests, and metric checks
TASK:
- Load architecture baseline and REFACTOR-{NNN} success criteria
- Validate build, tests, dependency metrics, and API compatibility
- Compare against baseline, check for regressions
CONTEXT:
- Session: <session-folder>
- Branch: B{NN}
- Upstream artifacts: architecture-baseline.json, branches/B{NN}/refactoring-detail.md
- Shared memory: <session>/wisdom/.msg/meta.json (namespace: validator.B{NN})
EXPECTED: <session>/artifacts/branches/B{NN}/validation-results.json
CONSTRAINTS: Only validate this branch's changes
---
InnerLoop: false
BranchId: B{NN}"
})
TaskUpdate({ taskId: "VALIDATE-B{NN}", addBlockedBy: ["REFACTOR-B{NN}"], owner: "validator" })
TaskCreate({
subject: "REVIEW-B{NN}",
description: "PURPOSE: Review branch B{NN} refactoring code | Success: Code quality verified for REFACTOR-{NNN}
TASK:
- Load modified files from refactorer.B{NN} namespace in .msg/meta.json
- Review across 5 dimensions for this branch's changes only
- Issue verdict: APPROVE, REVISE, or REJECT
CONTEXT:
- Session: <session-folder>
- Branch: B{NN}
- Upstream artifacts: branches/B{NN}/refactoring-detail.md
- Shared memory: <session>/wisdom/.msg/meta.json (namespace: reviewer.B{NN})
EXPECTED: <session>/artifacts/branches/B{NN}/review-report.md
CONSTRAINTS: Only review this branch's changes
---
InnerLoop: false
BranchId: B{NN}"
})
TaskUpdate({ taskId: "REVIEW-B{NN}", addBlockedBy: ["REFACTOR-B{NN}"], owner: "reviewer" })
```
7. Update session.json:
- `branches`: array of branch IDs (["B01", "B02", ...])
- `fix_cycles`: object keyed by branch ID, all initialized to 0
---
## Phase 4: Validation
Verify task chain integrity:
| Check | Method | Expected |
|-------|--------|----------|
| Task count correct | TaskList count | single: 5, auto/fan-out: 2 (pre-CP-2.5), independent: 5*M |
| Dependencies correct | Trace dependency graph | Acyclic, correct blockedBy |
| No circular dependencies | Trace dependency graph | Acyclic |
| Task IDs use correct prefixes | Pattern check | Match naming rules per mode |
| Structured descriptions complete | Each has PURPOSE/TASK/CONTEXT/EXPECTED/CONSTRAINTS | All present |
| Branch/Pipeline IDs consistent | Cross-check with session.json | Match |
### Naming Rules Summary
| Mode | Stage 3 | Stage 4 | Fix |
|------|---------|---------|-----|
| Single | REFACTOR-001 | VALIDATE-001, REVIEW-001 | FIX-001, FIX-002 |
| Fan-out | REFACTOR-B01 | VALIDATE-B01, REVIEW-B01 | FIX-B01-1, FIX-B01-2 |
| Independent | REFACTOR-A01 | VALIDATE-A01, REVIEW-A01 | FIX-A01-1, FIX-A01-2 |
If validation fails, fix the specific task and re-validate.

View File

@@ -0,0 +1,330 @@
# Command: Monitor
Handle all coordinator monitoring events: worker callbacks, status checks, pipeline advancement, and completion. Supports single, fan-out, and independent parallel modes with per-branch/pipeline tracking.
## Phase 2: Context Loading
| Input | Source | Required |
|-------|--------|----------|
| Session state | <session>/session.json | Yes |
| Task list | TaskList() | Yes |
| Trigger event | From Entry Router detection | Yes |
| Pipeline definition | From SKILL.md | Yes |
1. Load session.json for current state, `parallel_mode`, `branches`, `fix_cycles`
2. Run TaskList() to get current task statuses
3. Identify trigger event type from Entry Router
## Phase 3: Event Handlers
### handleCallback
Triggered when a worker sends completion message.
1. Parse message to identify role, task ID, and **branch/pipeline label**:
| Message Pattern | Branch Detection |
|----------------|-----------------|
| `[refactorer-B01]` or task ID `REFACTOR-B01` | Branch `B01` (fan-out) |
| `[analyzer-A]` or task ID `ANALYZE-A01` | Pipeline `A` (independent) |
| `[analyzer]` or task ID `ANALYZE-001` | No branch (single) |
2. Mark task as completed:
```
TaskUpdate({ taskId: "<task-id>", status: "completed" })
```
3. Record completion in session state
4. **CP-2.5 check** (auto/fan-out mode only):
- If completed task is DESIGN-001 AND `parallel_mode` is `auto` or `fan-out`:
- Execute **CP-2.5 Branch Creation** subroutine from dispatch.md
- After branch creation, proceed to handleSpawnNext (spawns all REFACTOR-B* in parallel)
- STOP after spawning
5. Check if checkpoint feedback is configured for this stage:
| Completed Task | Checkpoint | Action |
|---------------|------------|--------|
| ANALYZE-001 / ANALYZE-{P}01 | CP-1 | Notify user: architecture report ready for review |
| DESIGN-001 / DESIGN-{P}01 | CP-2 | Notify user: refactoring plan ready for review |
| DESIGN-001 (auto/fan-out) | CP-2.5 | Execute branch creation, then notify user with branch count |
| VALIDATE-* or REVIEW-* | CP-3 | Check verdicts per branch (see Review-Fix Cycle below) |
6. Proceed to handleSpawnNext
### handleSpawnNext
Find and spawn the next ready tasks.
1. Scan task list for tasks where:
- Status is "pending"
- All blockedBy tasks have status "completed"
2. For each ready task, spawn team-worker:
```
Agent({
subagent_type: "team-worker",
description: "Spawn <role> worker for <task-id>",
team_name: "arch-opt",
name: "<role>",
run_in_background: true,
prompt: `## Role Assignment
role: <role>
role_spec: .claude/skills/team-arch-opt/role-specs/<role>.md
session: <session-folder>
session_id: <session-id>
team_name: arch-opt
requirement: <task-description>
inner_loop: <true|false>
Read role_spec file to load Phase 2-4 domain instructions.
Execute built-in Phase 1 -> role-spec Phase 2-4 -> built-in Phase 5.`
})
```
3. **Parallel spawn rules by mode**:
| Mode | Scenario | Spawn Behavior |
|------|----------|---------------|
| Single | Stage 4 ready | Spawn VALIDATE-001 + REVIEW-001 in parallel |
| Fan-out (CP-2.5 done) | All REFACTOR-B* unblocked | Spawn ALL REFACTOR-B* in parallel |
| Fan-out (REFACTOR-B{NN} done) | VALIDATE-B{NN} + REVIEW-B{NN} ready | Spawn both for that branch in parallel |
| Independent | Any unblocked task | Spawn all ready tasks across all pipelines in parallel |
4. STOP after spawning -- wait for next callback
### Review-Fix Cycle (CP-3)
**Per-branch/pipeline scoping**: Each branch/pipeline has its own independent fix cycle.
#### Single Mode (unchanged)
When both VALIDATE-001 and REVIEW-001 are completed:
1. Read validation verdict from .msg/meta.json (validator namespace)
2. Read review verdict from .msg/meta.json (reviewer namespace)
| Validate Verdict | Review Verdict | Action |
|-----------------|----------------|--------|
| PASS | APPROVE | -> handleComplete |
| PASS | REVISE | Create FIX task with review feedback |
| FAIL | APPROVE | Create FIX task with validation feedback |
| FAIL | REVISE/REJECT | Create FIX task with combined feedback |
| Any | REJECT | Create FIX task + flag for designer re-evaluation |
#### Fan-out Mode (per-branch)
When both VALIDATE-B{NN} and REVIEW-B{NN} are completed for a specific branch:
1. Read validation verdict from `validator.B{NN}` namespace
2. Read review verdict from `reviewer.B{NN}` namespace
3. Apply same verdict matrix as single mode, but scoped to this branch only
4. **Other branches are unaffected** -- they continue independently
#### Independent Mode (per-pipeline)
When both VALIDATE-{P}01 and REVIEW-{P}01 are completed for a specific pipeline:
1. Read verdicts from `validator.{P}` and `reviewer.{P}` namespaces
2. Apply same verdict matrix, scoped to this pipeline only
#### Fix Cycle Count Tracking
Fix cycles are tracked per branch/pipeline in `session.json`:
```json
// Single mode
{ "fix_cycles": { "main": 0 } }
// Fan-out mode
{ "fix_cycles": { "B01": 0, "B02": 1, "B03": 0 } }
// Independent mode
{ "fix_cycles": { "A": 0, "B": 2 } }
```
| Cycle Count | Action |
|-------------|--------|
| < 3 | Create FIX task, increment cycle count for this branch/pipeline |
| >= 3 | Escalate THIS branch/pipeline to user. Other branches continue |
#### FIX Task Creation (branched)
**Fan-out mode**:
```
TaskCreate({
subject: "FIX-B{NN}-{cycle}",
description: "PURPOSE: Fix issues in branch B{NN} from review/validation | Success: All flagged issues resolved
TASK:
- Address review findings: <specific-findings>
- Fix validation failures: <specific-failures>
- Re-validate after fixes
CONTEXT:
- Session: <session-folder>
- Branch: B{NN}
- Upstream artifacts: branches/B{NN}/review-report.md, branches/B{NN}/validation-results.json
- Shared memory: <session>/wisdom/.msg/meta.json (namespace: refactorer.B{NN})
EXPECTED: Fixed source files for B{NN} only
CONSTRAINTS: Targeted fixes only | Do not touch other branches
---
InnerLoop: false
BranchId: B{NN}"
})
TaskUpdate({ taskId: "FIX-B{NN}-{cycle}", owner: "refactorer" })
```
Create new VALIDATE and REVIEW with retry suffix:
- `VALIDATE-B{NN}-R{cycle}` blocked on `FIX-B{NN}-{cycle}`
- `REVIEW-B{NN}-R{cycle}` blocked on `FIX-B{NN}-{cycle}`
**Independent mode**:
```
TaskCreate({
subject: "FIX-{P}01-{cycle}",
...same pattern with pipeline prefix...
})
TaskUpdate({ taskId: "FIX-{P}01-{cycle}", owner: "refactorer" })
```
Create `VALIDATE-{P}01-R{cycle}` and `REVIEW-{P}01-R{cycle}`.
### handleCheck
Output current pipeline status grouped by branch/pipeline.
**Single mode** (unchanged):
```
Pipeline Status:
[DONE] ANALYZE-001 (analyzer) -> architecture-report.md
[DONE] DESIGN-001 (designer) -> refactoring-plan.md
[RUN] REFACTOR-001 (refactorer) -> refactoring...
[WAIT] VALIDATE-001 (validator) -> blocked by REFACTOR-001
[WAIT] REVIEW-001 (reviewer) -> blocked by REFACTOR-001
Fix Cycles: 0/3
Session: <session-id>
```
**Fan-out mode**:
```
Pipeline Status (fan-out, 3 branches):
Shared Stages:
[DONE] ANALYZE-001 (analyzer) -> architecture-report.md
[DONE] DESIGN-001 (designer) -> refactoring-plan.md (4 REFACTOR-IDs)
Branch B01 (REFACTOR-001: <title>):
[RUN] REFACTOR-B01 (refactorer) -> refactoring...
[WAIT] VALIDATE-B01 (validator) -> blocked by REFACTOR-B01
[WAIT] REVIEW-B01 (reviewer) -> blocked by REFACTOR-B01
Fix Cycles: 0/3
Branch B02 (REFACTOR-002: <title>):
[DONE] REFACTOR-B02 (refactorer) -> done
[RUN] VALIDATE-B02 (validator) -> validating...
[RUN] REVIEW-B02 (reviewer) -> reviewing...
Fix Cycles: 0/3
Branch B03 (REFACTOR-003: <title>):
[FAIL] REFACTOR-B03 (refactorer) -> failed
Fix Cycles: 0/3 [BRANCH FAILED]
Session: <session-id>
```
**Independent mode**:
```
Pipeline Status (independent, 2 pipelines):
Pipeline A (target: refactor auth module):
[DONE] ANALYZE-A01 -> [DONE] DESIGN-A01 -> [RUN] REFACTOR-A01 -> ...
Fix Cycles: 0/3
Pipeline B (target: refactor API layer):
[DONE] ANALYZE-B01 -> [DONE] DESIGN-B01 -> [DONE] REFACTOR-B01 -> ...
Fix Cycles: 1/3
Session: <session-id>
```
Output status -- do NOT advance pipeline.
### handleResume
Resume pipeline after user pause or interruption.
1. Audit task list for inconsistencies:
- Tasks stuck in "in_progress" -> reset to "pending"
- Tasks with completed blockers but still "pending" -> include in spawn list
2. For fan-out/independent: check each branch/pipeline independently
3. Proceed to handleSpawnNext
### handleConsensus
Handle consensus_blocked signals from discuss rounds.
| Severity | Action |
|----------|--------|
| HIGH | Pause pipeline (or branch), notify user with findings summary |
| MEDIUM | Create revision task for the blocked role (scoped to branch if applicable) |
| LOW | Log finding, continue pipeline |
### handleComplete
Triggered when all pipeline tasks are completed and no fix cycles remain.
**Completion check varies by mode**:
| Mode | Completion Condition |
|------|---------------------|
| Single | All 5 tasks (+ any FIX/retry tasks) have status "completed" |
| Fan-out | ALL branches have VALIDATE + REVIEW completed with PASS/APPROVE (or escalated), shared stages done |
| Independent | ALL pipelines have VALIDATE + REVIEW completed with PASS/APPROVE (or escalated) |
**Aggregate results** before transitioning to Phase 5:
1. For fan-out mode: collect per-branch validation results into `<session>/artifacts/aggregate-results.json`:
```json
{
"branches": {
"B01": { "refactor_id": "REFACTOR-001", "validate_verdict": "PASS", "review_verdict": "APPROVE", "improvement": "..." },
"B02": { "refactor_id": "REFACTOR-002", "validate_verdict": "PASS", "review_verdict": "APPROVE", "improvement": "..." },
"B03": { "status": "failed", "reason": "REFACTOR failed" }
},
"overall": { "total_branches": 3, "passed": 2, "failed": 1 }
}
```
2. For independent mode: collect per-pipeline results similarly
3. If any tasks not completed, return to handleSpawnNext
4. If all completed (allowing for failed branches marked as such), transition to coordinator Phase 5
### handleRevise
Triggered by user "revise <TASK-ID> [feedback]" command.
1. Parse target task ID and optional feedback
2. Detect branch/pipeline from task ID pattern
3. Create revision task with same role but updated requirements, scoped to branch
4. Set blockedBy to empty (immediate execution)
5. Cascade: create new downstream tasks within same branch only
6. Proceed to handleSpawnNext
### handleFeedback
Triggered by user "feedback <text>" command.
1. Analyze feedback text to determine impact scope
2. Identify which pipeline stage, role, and branch/pipeline should handle the feedback
3. Create targeted revision task (scoped to branch if applicable)
4. Proceed to handleSpawnNext
## Phase 4: State Persistence
After every handler execution:
1. Update session.json with current state (active tasks, fix cycle counts per branch, last event, resolved parallel_mode)
2. Verify task list consistency
3. STOP and wait for next event

View File

@@ -0,0 +1,303 @@
# Coordinator - Architecture Optimization Team
**Role**: coordinator
**Type**: Orchestrator
**Team**: arch-opt
Orchestrates the architecture optimization pipeline: manages task chains, spawns team-worker agents, handles review-fix cycles, and drives the pipeline to completion.
## Boundaries
### MUST
- Use `team-worker` agent type for all worker spawns (NOT `general-purpose`)
- Follow Command Execution Protocol for dispatch and monitor commands
- Respect pipeline stage dependencies (blockedBy)
- Stop after spawning workers -- wait for callbacks
- Handle review-fix cycles with max 3 iterations
- Execute completion action in Phase 5
### MUST NOT
- Implement domain logic (analyzing, refactoring, reviewing) -- workers handle this
- Spawn workers without creating tasks first
- Skip checkpoints when configured
- Force-advance pipeline past failed review/validation
- Modify source code directly -- delegate to refactorer worker
---
## Command Execution Protocol
When coordinator needs to execute a command (dispatch, monitor):
1. **Read the command file**: `roles/coordinator/commands/<command-name>.md`
2. **Follow the workflow** defined in the command file (Phase 2-4 structure)
3. **Commands are inline execution guides** -- NOT separate agents or subprocesses
4. **Execute synchronously** -- complete the command workflow before proceeding
Example:
```
Phase 3 needs task dispatch
-> Read roles/coordinator/commands/dispatch.md
-> Execute Phase 2 (Context Loading)
-> Execute Phase 3 (Task Chain Creation)
-> Execute Phase 4 (Validation)
-> Continue to Phase 4
```
---
## Entry Router
When coordinator is invoked, detect invocation type:
| Detection | Condition | Handler |
|-----------|-----------|---------|
| Worker callback | Message contains role tag [analyzer], [designer], [refactorer], [validator], [reviewer] | -> handleCallback |
| Branch callback | Message contains branch tag [refactorer-B01], [validator-B02], etc. | -> handleCallback (branch-aware) |
| Pipeline callback | Message contains pipeline tag [analyzer-A], [refactorer-B], etc. | -> handleCallback (pipeline-aware) |
| Consensus blocked | Message contains "consensus_blocked" | -> handleConsensus |
| Status check | Arguments contain "check" or "status" | -> handleCheck |
| Manual resume | Arguments contain "resume" or "continue" | -> handleResume |
| Pipeline complete | All tasks have status "completed" | -> handleComplete |
| Interrupted session | Active/paused session exists | -> Phase 0 (Resume Check) |
| New session | None of above | -> Phase 1 (Requirement Clarification) |
For callback/check/resume/complete: load `commands/monitor.md` and execute matched handler, then STOP.
### Router Implementation
1. **Load session context** (if exists):
- Scan `.workflow/.team/ARCH-OPT-*/.msg/meta.json` for active/paused sessions
- If found, extract session folder path, status, and `parallel_mode`
2. **Parse $ARGUMENTS** for detection keywords:
- Check for role name tags in message content (including branch variants like `[refactorer-B01]`)
- Check for "check", "status", "resume", "continue" keywords
- Check for "consensus_blocked" signal
3. **Route to handler**:
- For monitor handlers: Read `commands/monitor.md`, execute matched handler, STOP
- For Phase 0: Execute Session Resume Check below
- For Phase 1: Execute Requirement Clarification below
---
## Phase 0: Session Resume Check
Triggered when an active/paused session is detected on coordinator entry.
1. Load session.json from detected session folder
2. Audit task list:
```
TaskList()
```
3. Reconcile session state vs task status:
| Task Status | Session Expects | Action |
|-------------|----------------|--------|
| in_progress | Should be running | Reset to pending (worker was interrupted) |
| completed | Already tracked | Skip |
| pending + unblocked | Ready to run | Include in spawn list |
4. Rebuild team if not active:
```
TeamCreate({ team_name: "arch-opt" })
```
5. Spawn workers for ready tasks -> Phase 4 coordination loop
---
## Phase 1: Requirement Clarification
1. Parse user task description from $ARGUMENTS
2. **Parse parallel mode flags**:
| Flag | Value | Default |
|------|-------|---------|
| `--parallel-mode` | `single`, `fan-out`, `independent`, `auto` | `auto` |
| `--max-branches` | integer 1-10 | 5 (from config) |
- For `independent` mode: remaining positional arguments after flags are `independent_targets` array
- Example: `--parallel-mode=independent "refactor auth" "refactor API"` -> targets = ["refactor auth", "refactor API"]
3. Identify architecture optimization target:
| Signal | Target |
|--------|--------|
| Specific file/module mentioned | Scoped refactoring |
| "coupling", "dependency", "structure", generic | Full architecture analysis |
| Specific issue mentioned (cycles, God Class, duplication) | Targeted issue resolution |
| Multiple quoted targets (independent mode) | Per-target scoped refactoring |
4. If target is unclear, ask for clarification:
```
AskUserQuestion({
questions: [{
question: "What should I analyze and refactor? Provide a target scope or describe the architecture issue.",
header: "Scope"
}]
})
```
5. Record refactoring requirement with scope, target issues, parallel_mode, and max_branches
---
## Phase 2: Session & Team Setup
1. Create session directory:
```
Bash("mkdir -p .workflow/<session-id>/artifacts .workflow/<session-id>/explorations .workflow/<session-id>/wisdom .workflow/<session-id>/discussions")
```
For independent mode, also create pipeline subdirectories:
```
// For each target in independent_targets
Bash("mkdir -p .workflow/<session-id>/artifacts/pipelines/A .workflow/<session-id>/artifacts/pipelines/B ...")
```
2. Write session.json with extended fields:
```json
{
"status": "active",
"team_name": "arch-opt",
"requirement": "<requirement>",
"timestamp": "<ISO-8601>",
"parallel_mode": "<auto|single|fan-out|independent>",
"max_branches": 5,
"branches": [],
"independent_targets": [],
"fix_cycles": {}
}
```
- `parallel_mode`: from Phase 1 parsing (default: "auto")
- `max_branches`: from Phase 1 parsing (default: 5)
- `branches`: populated at CP-2.5 for fan-out mode (e.g., ["B01", "B02", "B03"])
- `independent_targets`: populated for independent mode (e.g., ["refactor auth", "refactor API"])
- `fix_cycles`: populated per-branch/pipeline as fix cycles occur
4. Initialize meta.json with pipeline metadata:
```typescript
// Use team_msg to write pipeline metadata to .msg/meta.json
mcp__ccw-tools__team_msg({
operation: "log",
session_id: "<session-id>",
from: "coordinator",
type: "state_update",
summary: "Session initialized",
data: {
pipeline_mode: "<parallel_mode>",
pipeline_stages: ["analyzer", "designer", "refactorer", "validator", "reviewer"],
roles: ["coordinator", "analyzer", "designer", "refactorer", "validator", "reviewer"],
team_name: "arch-opt"
}
})
```
5. Create team:
```
TeamCreate({ team_name: "arch-opt" })
```
---
## Phase 3: Task Chain Creation
Execute `commands/dispatch.md` inline (Command Execution Protocol):
1. Read `roles/coordinator/commands/dispatch.md`
2. Follow dispatch Phase 2 (context loading) -> Phase 3 (task chain creation) -> Phase 4 (validation)
3. Result: all pipeline tasks created with correct blockedBy dependencies
---
## Phase 4: Spawn & Coordination Loop
### Initial Spawn
Find first unblocked task and spawn its worker:
```
Agent({
subagent_type: "team-worker",
description: "Spawn analyzer worker",
team_name: "arch-opt",
name: "analyzer",
run_in_background: true,
prompt: `## Role Assignment
role: analyzer
role_spec: .claude/skills/team-arch-opt/role-specs/analyzer.md
session: <session-folder>
session_id: <session-id>
team_name: arch-opt
requirement: <requirement>
inner_loop: false
Read role_spec file to load Phase 2-4 domain instructions.
Execute built-in Phase 1 -> role-spec Phase 2-4 -> built-in Phase 5.`
})
```
**STOP** after spawning. Wait for worker callback.
### Coordination (via monitor.md handlers)
All subsequent coordination is handled by `commands/monitor.md` handlers triggered by worker callbacks:
- handleCallback -> mark task done -> check pipeline -> handleSpawnNext
- handleSpawnNext -> find ready tasks -> spawn team-worker agents -> STOP
- handleComplete -> all done -> Phase 5
---
## Phase 5: Report + Completion Action
1. Load session state -> count completed tasks, calculate duration
2. List deliverables:
| Deliverable | Path |
|-------------|------|
| Architecture Baseline | <session>/artifacts/architecture-baseline.json |
| Architecture Report | <session>/artifacts/architecture-report.md |
| Refactoring Plan | <session>/artifacts/refactoring-plan.md |
| Validation Results | <session>/artifacts/validation-results.json |
| Review Report | <session>/artifacts/review-report.md |
3. Include discussion summaries if discuss rounds were used
4. Output pipeline summary: task count, duration, improvement metrics from validation results
5. **Completion Action** (interactive):
```
AskUserQuestion({
questions: [{
question: "Team pipeline complete. What would you like to do?",
header: "Completion",
multiSelect: false,
options: [
{ label: "Archive & Clean (Recommended)", description: "Archive session, clean up tasks and team resources" },
{ label: "Keep Active", description: "Keep session active for follow-up work or inspection" },
{ label: "Export Results", description: "Export deliverables to a specified location, then clean" }
]
}]
})
```
6. Handle user choice:
| Choice | Steps |
|--------|-------|
| Archive & Clean | TaskList -> verify all completed -> update session status="completed" -> TeamDelete() -> output final summary with artifact paths |
| Keep Active | Update session status="paused" -> output: "Session paused. Resume with: Skill(skill='team-arch-opt', args='resume')" |
| Export Results | AskUserQuestion for target directory -> copy all artifacts -> Archive & Clean flow |

View File

@@ -0,0 +1,264 @@
{
"version": "5.0.0",
"team_name": "arch-opt",
"team_display_name": "Architecture Optimization",
"skill_name": "team-arch-opt",
"skill_path": ".claude/skills/team-arch-opt/",
"worker_agent": "team-worker",
"pipeline_type": "Linear with Review-Fix Cycle (Parallel-Capable)",
"completion_action": "interactive",
"has_inline_discuss": true,
"has_shared_explore": true,
"has_checkpoint_feedback": true,
"has_session_resume": true,
"roles": [
{
"name": "coordinator",
"type": "orchestrator",
"description": "Orchestrates architecture optimization pipeline, manages task chains, handles review-fix cycles",
"spec_path": "roles/coordinator/role.md",
"tools": ["Task", "TaskCreate", "TaskList", "TaskGet", "TaskUpdate", "TeamCreate", "TeamDelete", "SendMessage", "AskUserQuestion", "Read", "Write", "Bash", "Glob", "Grep"]
},
{
"name": "analyzer",
"type": "orchestration",
"description": "Analyzes architecture: dependency graphs, coupling/cohesion, layering violations, God Classes, dead code",
"role_spec": "role-specs/analyzer.md",
"inner_loop": false,
"frontmatter": {
"prefix": "ANALYZE",
"inner_loop": false,
"additional_prefixes": [],
"discuss_rounds": [],
"cli_tools": ["explore"],
"message_types": {
"success": "analyze_complete",
"error": "error"
}
},
"weight": 1,
"tools": ["Read", "Bash", "Glob", "Grep", "Task", "mcp__ace-tool__search_context"]
},
{
"name": "designer",
"type": "orchestration",
"description": "Designs refactoring strategies from architecture analysis, produces prioritized refactoring plan with discrete REFACTOR-IDs",
"role_spec": "role-specs/designer.md",
"inner_loop": false,
"frontmatter": {
"prefix": "DESIGN",
"inner_loop": false,
"additional_prefixes": [],
"discuss_rounds": ["DISCUSS-REFACTOR"],
"cli_tools": ["discuss"],
"message_types": {
"success": "design_complete",
"error": "error"
}
},
"weight": 2,
"tools": ["Read", "Bash", "Glob", "Grep", "Task", "mcp__ace-tool__search_context"]
},
{
"name": "refactorer",
"type": "code_generation",
"description": "Implements architecture refactoring changes following the design plan",
"role_spec": "role-specs/refactorer.md",
"inner_loop": true,
"frontmatter": {
"prefix": "REFACTOR",
"inner_loop": true,
"additional_prefixes": ["FIX"],
"discuss_rounds": [],
"cli_tools": ["explore"],
"message_types": {
"success": "refactor_complete",
"error": "error",
"fix": "fix_required"
}
},
"weight": 3,
"tools": ["Read", "Write", "Edit", "Bash", "Glob", "Grep", "Task", "mcp__ace-tool__search_context"]
},
{
"name": "validator",
"type": "validation",
"description": "Validates refactoring: build checks, test suites, dependency metrics, API compatibility",
"role_spec": "role-specs/validator.md",
"inner_loop": false,
"frontmatter": {
"prefix": "VALIDATE",
"inner_loop": false,
"additional_prefixes": [],
"discuss_rounds": [],
"cli_tools": [],
"message_types": {
"success": "validate_complete",
"error": "error",
"fix": "fix_required"
}
},
"weight": 4,
"tools": ["Read", "Bash", "Glob", "Grep", "Task"]
},
{
"name": "reviewer",
"type": "read_only_analysis",
"description": "Reviews refactoring code for correctness, pattern consistency, completeness, migration safety, and best practices",
"role_spec": "role-specs/reviewer.md",
"inner_loop": false,
"frontmatter": {
"prefix": "REVIEW",
"inner_loop": false,
"additional_prefixes": ["QUALITY"],
"discuss_rounds": ["DISCUSS-REVIEW"],
"cli_tools": ["discuss"],
"message_types": {
"success": "review_complete",
"error": "error",
"fix": "fix_required"
}
},
"weight": 4,
"tools": ["Read", "Bash", "Glob", "Grep", "Task", "mcp__ace-tool__search_context"]
}
],
"parallel_config": {
"modes": ["single", "fan-out", "independent", "auto"],
"default_mode": "auto",
"max_branches": 5,
"auto_mode_rules": {
"single": "refactoring_count <= 2",
"fan-out": "refactoring_count >= 3"
}
},
"pipeline": {
"stages": [
{
"stage": 1,
"name": "Architecture Analysis",
"roles": ["analyzer"],
"blockedBy": [],
"fast_advance": true
},
{
"stage": 2,
"name": "Refactoring Design",
"roles": ["designer"],
"blockedBy": ["ANALYZE"],
"fast_advance": true
},
{
"stage": 3,
"name": "Code Refactoring",
"roles": ["refactorer"],
"blockedBy": ["DESIGN"],
"fast_advance": false
},
{
"stage": 4,
"name": "Validate & Review",
"roles": ["validator", "reviewer"],
"blockedBy": ["REFACTOR"],
"fast_advance": false,
"parallel": true,
"review_fix_cycle": {
"trigger": "REVIEW or VALIDATE finds issues",
"target_stage": 3,
"max_iterations": 3
}
}
],
"parallel_pipelines": {
"fan-out": {
"shared_stages": [1, 2],
"branch_stages": [3, 4],
"branch_prefix": "B",
"review_fix_cycle": {
"scope": "per_branch",
"max_iterations": 3
}
},
"independent": {
"pipeline_prefix_chars": "ABCDEFGHIJ",
"review_fix_cycle": {
"scope": "per_pipeline",
"max_iterations": 3
}
}
},
"diagram": "See pipeline-diagram section"
},
"cli_tools": [
{
"name": "explore",
"implementation": "ccw cli with analysis mode",
"callable_by": ["analyzer", "refactorer"],
"purpose": "Shared codebase exploration for architecture-critical structures, dependency graphs, and module boundaries",
"has_cache": true,
"cache_domain": "explorations"
},
{
"name": "discuss",
"implementation": "ccw cli with analysis mode",
"callable_by": ["designer", "reviewer"],
"purpose": "Multi-perspective discussion for refactoring approaches and review findings",
"has_cache": false
}
],
"shared_resources": [
{
"name": "Architecture Baseline",
"path": "<session>/artifacts/architecture-baseline.json",
"usage": "Pre-refactoring architecture metrics for comparison",
"scope": "shared (fan-out) / per-pipeline (independent)"
},
{
"name": "Architecture Report",
"path": "<session>/artifacts/architecture-report.md",
"usage": "Analyzer output consumed by designer",
"scope": "shared (fan-out) / per-pipeline (independent)"
},
{
"name": "Refactoring Plan",
"path": "<session>/artifacts/refactoring-plan.md",
"usage": "Designer output consumed by refactorer",
"scope": "shared (fan-out) / per-pipeline (independent)"
},
{
"name": "Validation Results",
"path": "<session>/artifacts/validation-results.json",
"usage": "Validator output consumed by reviewer",
"scope": "per-branch (fan-out) / per-pipeline (independent)"
}
],
"shared_memory_namespacing": {
"single": {
"analyzer": "analyzer",
"designer": "designer",
"refactorer": "refactorer",
"validator": "validator",
"reviewer": "reviewer"
},
"fan-out": {
"analyzer": "analyzer",
"designer": "designer",
"refactorer": "refactorer.B{NN}",
"validator": "validator.B{NN}",
"reviewer": "reviewer.B{NN}"
},
"independent": {
"analyzer": "analyzer.{P}",
"designer": "designer.{P}",
"refactorer": "refactorer.{P}",
"validator": "validator.{P}",
"reviewer": "reviewer.{P}"
}
}
}

View File

@@ -1,7 +1,7 @@
--- ---
name: team-brainstorm name: team-brainstorm
description: Unified team skill for brainstorming team. All roles invoke this skill with --role arg for role-specific execution. Triggers on "team brainstorm". description: Unified team skill for brainstorming team. All roles invoke this skill with --role arg for role-specific execution. Triggers on "team brainstorm".
allowed-tools: TeamCreate(*), TeamDelete(*), SendMessage(*), TaskCreate(*), TaskUpdate(*), TaskList(*), TaskGet(*), Task(*), AskUserQuestion(*), Read(*), Write(*), Edit(*), Bash(*), Glob(*), Grep(*) allowed-tools: TeamCreate(*), TeamDelete(*), SendMessage(*), TaskCreate(*), TaskUpdate(*), TaskList(*), TaskGet(*), Agent(*), AskUserQuestion(*), Read(*), Write(*), Edit(*), Bash(*), Glob(*), Grep(*)
--- ---
# Team Brainstorm # Team Brainstorm
@@ -11,25 +11,34 @@ Unified team skill: multi-angle brainstorming via Generator-Critic loops, shared
## Architecture ## Architecture
``` ```
┌───────────────────────────────────────────────────┐ +---------------------------------------------------+
Skill(skill="team-brainstorm") | Skill(skill="team-brainstorm") |
args="<topic>" or args="--role=xxx" | args="<topic-description>" |
└───────────────────┬───────────────────────────────┘ +-------------------+-------------------------------+
│ Role Router |
┌──── --role present? ────┐ Orchestration Mode (auto -> coordinator)
│ NO │ YES |
↓ ↓ Coordinator (inline)
Orchestration Mode Role Dispatch Phase 0-5 orchestration
(auto → coordinator) (route to role.md) |
+-------+-------+-------+-------+
┌────┴────┬───────────┬───────────┬───────────┐ v v v v
↓ ↓ ↓ [tw] [tw] [tw] [tw]
┌──────────┐┌─────────┐┌──────────┐┌──────────┐┌─────────┐ ideator chall- synthe- evalua-
│coordinator││ ideator ││challenger││synthesizer││evaluator enger sizer tor
│ ││ IDEA-* ││CHALLENGE-*││ SYNTH-* ││ EVAL-* │
└──────────┘└─────────┘└──────────┘└──────────┘└─────────┘ (tw) = team-worker agent
``` ```
## Command Execution Protocol
When coordinator needs to execute a command (dispatch, monitor):
1. **Read the command file**: `roles/coordinator/commands/<command-name>.md`
2. **Follow the workflow** defined in the command file (Phase 2-4 structure)
3. **Commands are inline execution guides** -- NOT separate agents or subprocesses
4. **Execute synchronously** -- complete the command workflow before proceeding
## Role Router ## Role Router
### Input Parsing ### Input Parsing
@@ -38,13 +47,13 @@ Parse `$ARGUMENTS` to extract `--role`. If absent → Orchestration Mode (auto r
### Role Registry ### Role Registry
| Role | File | Task Prefix | Type | Compact | | Role | Spec | Task Prefix | Inner Loop |
|------|------|-------------|------|---------| |------|------|-------------|------------|
| coordinator | [roles/coordinator.md](roles/coordinator.md) | (none) | orchestrator | **⚠️ 压缩后必须重读** | | coordinator | [roles/coordinator/role.md](roles/coordinator/role.md) | (none) | - |
| ideator | [roles/ideator.md](roles/ideator.md) | IDEA-* | pipeline | 压缩后必须重读 | | ideator | [role-specs/ideator.md](role-specs/ideator.md) | IDEA-* | false |
| challenger | [roles/challenger.md](roles/challenger.md) | CHALLENGE-* | pipeline | 压缩后必须重读 | | challenger | [role-specs/challenger.md](role-specs/challenger.md) | CHALLENGE-* | false |
| synthesizer | [roles/synthesizer.md](roles/synthesizer.md) | SYNTH-* | pipeline | 压缩后必须重读 | | synthesizer | [role-specs/synthesizer.md](role-specs/synthesizer.md) | SYNTH-* | false |
| evaluator | [roles/evaluator.md](roles/evaluator.md) | EVAL-* | pipeline | 压缩后必须重读 | | evaluator | [role-specs/evaluator.md](role-specs/evaluator.md) | EVAL-* | false |
> **⚠️ COMPACT PROTECTION**: 角色文件是执行文档,不是参考资料。当 context compression 发生后,角色指令仅剩摘要时,**必须立即 `Read` 对应 role.md 重新加载后再继续执行**。不得基于摘要执行任何 Phase。 > **⚠️ COMPACT PROTECTION**: 角色文件是执行文档,不是参考资料。当 context compression 发生后,角色指令仅剩摘要时,**必须立即 `Read` 对应 role.md 重新加载后再继续执行**。不得基于摘要执行任何 Phase。
@@ -101,10 +110,10 @@ Every worker executes the same task discovery flow on startup:
Standard reporting flow after task completion: Standard reporting flow after task completion:
1. **Message Bus**: Call `mcp__ccw-tools__team_msg` to log message 1. **Message Bus**: Call `mcp__ccw-tools__team_msg` to log message
- Parameters: operation="log", team=**<session-id>**, from=<role>, to="coordinator", type=<message-type>, summary="[<role>] <summary>", ref=<artifact-path> - Parameters: operation="log", session_id=<session-id>, from=<role>, type=<message-type>, data={ref: "<artifact-path>"}
- **CLI fallback**: When MCP unavailable → `ccw team log --team <session-id> --from <role> --to coordinator --type <type> --summary "[<role>] ..." --json` - `to` and `summary` auto-defaulted -- do NOT specify explicitly
- **Note**: `team` must be session ID (e.g., `BRS-xxx-date`), NOT team name. Extract from `Session:` field in task description. - **CLI fallback**: `ccw team log --session-id <session-id> --from <role> --type <type> --json`
2. **SendMessage**: Send result to coordinator (content and summary both prefixed with `[<role>]`) 2. **SendMessage**: Send result to coordinator
3. **TaskUpdate**: Mark task completed 3. **TaskUpdate**: Mark task completed
4. **Loop**: Return to Phase 1 to check next task 4. **Loop**: Return to Phase 1 to check next task
@@ -130,7 +139,7 @@ Cross-task knowledge accumulation. Coordinator creates `wisdom/` directory at se
|---------|-----------| |---------|-----------|
| Process tasks with own prefix | Process tasks with other role prefixes | | Process tasks with own prefix | Process tasks with other role prefixes |
| SendMessage to coordinator | Communicate directly with other workers | | SendMessage to coordinator | Communicate directly with other workers |
| Read/write shared-memory.json (own fields) | Create tasks for other roles | | Share state via team_msg(type="state_update") | Create tasks for other roles |
| Delegate to commands/ files | Modify resources outside own responsibility | | Delegate to commands/ files | Modify resources outside own responsibility |
Coordinator additional restrictions: Do not generate ideas directly, do not evaluate/challenge ideas, do not execute analysis/synthesis, do not bypass workers. Coordinator additional restrictions: Do not generate ideas directly, do not evaluate/challenge ideas, do not execute analysis/synthesis, do not bypass workers.
@@ -143,11 +152,12 @@ All outputs must carry `[role_name]` prefix in both SendMessage content/summary
Every SendMessage **before**, must call `mcp__ccw-tools__team_msg` to log: Every SendMessage **before**, must call `mcp__ccw-tools__team_msg` to log:
**Parameters**: operation="log", team=**<session-id>**, from=<role>, to="coordinator", type=<message-type>, summary="[<role>] <summary>", ref=<artifact-path> **Parameters**: operation="log", session_id=<session-id>, from=<role>, type=<message-type>, data={ref: "<artifact-path>"}
**CLI fallback**: When MCP unavailable → `ccw team log --team <session-id> --from <role> --to coordinator --type <type> --summary "[<role>] ..." --json` `to` and `summary` auto-defaulted -- do NOT specify explicitly.
**CLI fallback**: `ccw team log --session-id <session-id> --from <role> --type <type> --json`
**Note**: `team` must be session ID (e.g., `BRS-xxx-date`), NOT team name. Extract from `Session:` field in task description.
**Message types by role**: **Message types by role**:
@@ -159,12 +169,12 @@ Every SendMessage **before**, must call `mcp__ccw-tools__team_msg` to log:
| synthesizer | `synthesis_ready`, `error` | | synthesizer | `synthesis_ready`, `error` |
| evaluator | `evaluation_ready`, `error` | | evaluator | `evaluation_ready`, `error` |
### Shared Memory ### Shared State
All roles read in Phase 2 and write in Phase 5 to `shared-memory.json`: Cross-role state is shared via `team_msg(type="state_update")` messages, persisted in `.msg/meta.json`:
| Role | Field | | Role | State Key |
|------|-------| |------|-----------|
| ideator | `generated_ideas` | | ideator | `generated_ideas` |
| challenger | `critique_insights` | | challenger | `critique_insights` |
| synthesizer | `synthesis_themes` | | synthesizer | `synthesis_themes` |
@@ -176,7 +186,7 @@ All roles read in Phase 2 and write in Phase 5 to `shared-memory.json`:
|---------|-------| |---------|-------|
| Team name | brainstorm | | Team name | brainstorm |
| Session directory | `.workflow/.team/BRS-<slug>-<date>/` | | Session directory | `.workflow/.team/BRS-<slug>-<date>/` |
| Shared memory | `shared-memory.json` in session dir | | Message store | `.msg/messages.jsonl` + `.msg/meta.json` in session dir |
--- ---
@@ -291,79 +301,61 @@ Beat 1 2 3-4 5 6
## Coordinator Spawn Template ## Coordinator Spawn Template
When coordinator spawns workers, use background mode (Spawn-and-Stop). ### v5 Worker Spawn (all roles)
**Standard spawn** (single agent per role): For Quick/Deep pipeline, spawn one ideator. Challenger, synthesizer, and evaluator are always single agents. When coordinator spawns workers, use `team-worker` agent with role-spec path:
**Parallel spawn** (Full pipeline): For Full pipeline with N idea angles, spawn N ideator agents in parallel (`ideator-1`, `ideator-2`, ...) with `run_in_background: true`. Each parallel ideator only processes tasks where owner matches its agent name. After all parallel ideators complete, proceed with single challenger for batch critique.
**Spawn template**:
``` ```
Task({ Agent({
subagent_type: "general-purpose", subagent_type: "team-worker",
description: "Spawn <role> worker", description: "Spawn <role> worker",
team_name: "brainstorm", team_name: "brainstorm",
name: "<role>", name: "<role>",
run_in_background: true, run_in_background: true,
prompt: `You are team "brainstorm" <ROLE>. prompt: `## Role Assignment
role: <role>
role_spec: .claude/skills/team-brainstorm/role-specs/<role>.md
session: <session-folder>
session_id: <session-id>
team_name: brainstorm
requirement: <topic-description>
inner_loop: <true|false>
## Primary Directive Read role_spec file to load Phase 2-4 domain instructions.
All your work must be executed through Skill to load role definition: Execute built-in Phase 1 (task discovery) -> role-spec Phase 2-4 -> built-in Phase 5 (report).`
Skill(skill="team-brainstorm", args="--role=<role>")
Current topic: <topic-description>
Session: <session-folder>
## Role Guidelines
- Only process <PREFIX>-* tasks, do not execute other role work
- All output prefixed with [<role>] identifier
- Only communicate with coordinator
- Do not use TaskCreate for other roles
- Call mcp__ccw-tools__team_msg before every SendMessage
## Workflow
1. Call Skill -> load role definition and execution logic
2. Follow role.md 5-Phase flow
3. team_msg + SendMessage results to coordinator
4. TaskUpdate completed -> check next task`
}) })
``` ```
**All roles** (ideator, challenger, synthesizer, evaluator): Set `inner_loop: false`.
**Parallel ideator spawn** (Full pipeline with N angles): **Parallel ideator spawn** (Full pipeline with N angles):
> When Full pipeline has N parallel IDEA tasks assigned to ideator role, spawn N distinct agents named `ideator-1`, `ideator-2`, etc. Each agent only processes tasks where owner matches its agent name. > When Full pipeline has N parallel IDEA tasks assigned to ideator role, spawn N distinct team-worker agents named `ideator-1`, `ideator-2`, etc. Each agent only processes tasks where owner matches its agent name.
| Condition | Action | | Condition | Action |
|-----------|--------| |-----------|--------|
| Full pipeline with N idea angles (N > 1) | Spawn N agents: `ideator-1`, `ideator-2`, ... `ideator-N` with `run_in_background: true` | | Full pipeline with N idea angles (N > 1) | Spawn N team-worker agents: `ideator-1`, `ideator-2`, ... `ideator-N` with `run_in_background: true` |
| Quick/Deep pipeline (single ideator) | Standard spawn: single `ideator` agent | | Quick/Deep pipeline (single ideator) | Standard spawn: single `ideator` team-worker agent |
``` ```
Task({ Agent({
subagent_type: "general-purpose", subagent_type: "team-worker",
description: "Spawn ideator-<N> worker", description: "Spawn ideator-<N> worker",
team_name: "brainstorm", team_name: "brainstorm",
name: "ideator-<N>", name: "ideator-<N>",
run_in_background: true, run_in_background: true,
prompt: `You are team "brainstorm" IDEATOR (ideator-<N>). prompt: `## Role Assignment
Your agent name is "ideator-<N>", use this name for task discovery owner matching. role: ideator
role_spec: .claude/skills/team-brainstorm/role-specs/ideator.md
session: <session-folder>
session_id: <session-id>
team_name: brainstorm
requirement: <topic-description>
agent_name: ideator-<N>
inner_loop: false
## Primary Directive Read role_spec file to load Phase 2-4 domain instructions.
Skill(skill="team-brainstorm", args="--role=ideator --agent-name=ideator-<N>") Execute built-in Phase 1 (task discovery, owner=ideator-<N>) -> role-spec Phase 2-4 -> built-in Phase 5 (report).`
Current topic: <topic-description>
Session: <session-folder>
## Role Guidelines
- Only process tasks where owner === "ideator-<N>" with IDEA-* prefix
- All output prefixed with [ideator] identifier
## Workflow
1. TaskList -> find tasks where owner === "ideator-<N>" with IDEA-* prefix
2. Skill -> execute role definition
3. team_msg + SendMessage results to coordinator
4. TaskUpdate completed -> check next task`
}) })
``` ```
@@ -371,12 +363,40 @@ Session: <session-folder>
--- ---
## Completion Action
When the pipeline completes (all tasks done, coordinator Phase 5):
```
AskUserQuestion({
questions: [{
question: "Brainstorm pipeline complete. What would you like to do?",
header: "Completion",
multiSelect: false,
options: [
{ label: "Archive & Clean (Recommended)", description: "Archive session, clean up tasks and team resources" },
{ label: "Keep Active", description: "Keep session active for follow-up work or inspection" },
{ label: "Export Results", description: "Export deliverables to a specified location, then clean" }
]
}]
})
```
| Choice | Action |
|--------|--------|
| Archive & Clean | Update session status="completed" -> TeamDelete() -> output final summary |
| Keep Active | Update session status="paused" -> output resume instructions: `Skill(skill="team-brainstorm", args="resume")` |
| Export Results | AskUserQuestion for target path -> copy deliverables -> Archive & Clean |
---
## Unified Session Directory ## Unified Session Directory
``` ```
.workflow/.team/BRS-<slug>-<YYYY-MM-DD>/ .workflow/.team/BRS-<slug>-<YYYY-MM-DD>/
├── team-session.json # Session state ├── .msg/
├── shared-memory.json # Cumulative: generated_ideas / critique_insights / synthesis_themes / evaluation_scores │ ├── messages.jsonl # Message bus log
│ └── meta.json # Session state + cross-role state
├── wisdom/ # Cross-task knowledge ├── wisdom/ # Cross-task knowledge
│ ├── learnings.md │ ├── learnings.md
│ ├── decisions.md │ ├── decisions.md

View File

@@ -0,0 +1,63 @@
---
prefix: CHALLENGE
inner_loop: false
delegates_to: []
message_types:
success: critique_ready
error: error
---
# Challenger
Devil's advocate role. Assumption challenging, feasibility questioning, risk identification. Acts as the Critic in the Generator-Critic loop.
## Phase 2: Context Loading
| Input | Source | Required |
|-------|--------|----------|
| Session folder | Task description (Session: line) | Yes |
| Ideas | <session>/ideas/*.md files | Yes |
| Previous critiques | <session>/.msg/meta.json critique_insights | No |
1. Extract session path from task description (match "Session: <path>")
2. Glob idea files from <session>/ideas/
3. Read all idea files for analysis
4. Read .msg/meta.json critique_insights to avoid repeating past challenges
## Phase 3: Critical Analysis
**Challenge Dimensions** (apply to each idea):
| Dimension | Focus |
|-----------|-------|
| Assumption Validity | Does the core assumption hold? Counter-examples? |
| Feasibility | Technical/resource/time feasibility? |
| Risk Assessment | Worst case scenario? Hidden risks? |
| Competitive Analysis | Better alternatives already exist? |
**Severity Classification**:
| Severity | Criteria |
|----------|----------|
| CRITICAL | Fundamental issue, idea may need replacement |
| HIGH | Significant flaw, requires revision |
| MEDIUM | Notable weakness, needs consideration |
| LOW | Minor concern, does not invalidate the idea |
**Generator-Critic Signal**:
| Condition | Signal |
|-----------|--------|
| Any CRITICAL or HIGH severity | REVISION_NEEDED |
| All MEDIUM or lower | CONVERGED |
**Output**: Write to `<session>/critiques/critique-<num>.md`
- Sections: Ideas Reviewed, Per-idea challenges with severity, Summary table with counts, GC Signal
## Phase 4: Severity Summary
1. Count challenges by severity level
2. Determine signal: REVISION_NEEDED if critical+high > 0, else CONVERGED
3. Update shared state:
- Append challenges to .msg/meta.json critique_insights
- Each entry: idea, severity, key_challenge, round

View File

@@ -0,0 +1,58 @@
---
prefix: EVAL
inner_loop: false
delegates_to: []
message_types:
success: evaluation_ready
error: error
---
# Evaluator
Scoring, ranking, and final selection. Multi-dimension evaluation of synthesized proposals with weighted scoring and priority recommendations.
## Phase 2: Context Loading
| Input | Source | Required |
|-------|--------|----------|
| Session folder | Task description (Session: line) | Yes |
| Synthesis results | <session>/synthesis/*.md files | Yes |
| All ideas | <session>/ideas/*.md files | No (for context) |
| All critiques | <session>/critiques/*.md files | No (for context) |
1. Extract session path from task description (match "Session: <path>")
2. Glob synthesis files from <session>/synthesis/
3. Read all synthesis files for evaluation
4. Optionally read ideas and critiques for full context
## Phase 3: Evaluation and Scoring
**Scoring Dimensions**:
| Dimension | Weight | Focus |
|-----------|--------|-------|
| Feasibility | 30% | Technical feasibility, resource needs, timeline |
| Innovation | 25% | Novelty, differentiation, breakthrough potential |
| Impact | 25% | Scope of impact, value creation, problem resolution |
| Cost Efficiency | 20% | Implementation cost, risk cost, opportunity cost |
**Weighted Score**: `(Feasibility * 0.30) + (Innovation * 0.25) + (Impact * 0.25) + (Cost * 0.20)`
**Per-Proposal Evaluation**:
- Score each dimension (1-10) with rationale
- Overall recommendation: Strong Recommend / Recommend / Consider / Pass
**Output**: Write to `<session>/evaluation/evaluation-<num>.md`
- Sections: Input summary, Scoring Matrix (ranked table), Detailed Evaluation per proposal, Final Recommendation, Action Items, Risk Summary
## Phase 4: Consistency Check
| Check | Pass Criteria | Action on Failure |
|-------|---------------|-------------------|
| Score spread | max - min >= 0.5 (with >1 proposal) | Re-evaluate differentiators |
| No perfect scores | Not all 10s | Adjust to reflect critique findings |
| Ranking deterministic | Consistent ranking | Verify calculation |
After passing checks, update shared state:
- Set .msg/meta.json evaluation_scores
- Each entry: title, weighted_score, rank, recommendation

View File

@@ -0,0 +1,71 @@
---
prefix: IDEA
inner_loop: false
delegates_to: []
message_types:
success: ideas_ready
error: error
---
# Ideator
Multi-angle idea generator. Divergent thinking, concept exploration, and idea revision as the Generator in the Generator-Critic loop.
## Phase 2: Context Loading
| Input | Source | Required |
|-------|--------|----------|
| Session folder | Task description (Session: line) | Yes |
| Topic | <session>/.msg/meta.json | Yes |
| Angles | <session>/.msg/meta.json | Yes |
| GC Round | <session>/.msg/meta.json | Yes |
| Previous critique | <session>/critiques/*.md | For revision tasks only |
| Previous ideas | <session>/.msg/meta.json generated_ideas | No |
1. Extract session path from task description (match "Session: <path>")
2. Read .msg/meta.json for topic, angles, gc_round
3. Detect task mode:
| Condition | Mode |
|-----------|------|
| Task subject contains "revision" or "fix" | GC Revision |
| Otherwise | Initial Generation |
4. If GC Revision mode:
- Glob critique files from <session>/critiques/
- Read latest critique for revision context
5. Read previous ideas from .msg/meta.json generated_ideas state
## Phase 3: Idea Generation
### Mode Router
| Mode | Focus |
|------|-------|
| Initial Generation | Multi-angle divergent thinking, no prior critique |
| GC Revision | Address HIGH/CRITICAL challenges from critique |
**Initial Generation**:
- For each angle, generate 3+ ideas
- Each idea: title, description (2-3 sentences), key assumption, potential impact, implementation hint
**GC Revision**:
- Focus on HIGH/CRITICAL severity challenges from critique
- Retain unchallenged ideas intact
- Revise ideas with revision rationale
- Replace unsalvageable ideas with new alternatives
**Output**: Write to `<session>/ideas/idea-<num>.md`
- Sections: Topic, Angles, Mode, [Revision Context if applicable], Ideas list, Summary
## Phase 4: Self-Review
| Check | Pass Criteria | Action on Failure |
|-------|---------------|-------------------|
| Minimum count | >= 6 (initial) or >= 3 (revision) | Generate additional ideas |
| No duplicates | All titles unique | Replace duplicates |
| Angle coverage | At least 1 idea per angle | Generate missing angle ideas |
After passing checks, update shared state:
- Append new ideas to .msg/meta.json generated_ideas
- Each entry: id, title, round, revised flag

View File

@@ -0,0 +1,59 @@
---
prefix: SYNTH
inner_loop: false
delegates_to: []
message_types:
success: synthesis_ready
error: error
---
# Synthesizer
Cross-idea integrator. Extracts themes from multiple ideas and challenge feedback, resolves conflicts, generates consolidated proposals.
## Phase 2: Context Loading
| Input | Source | Required |
|-------|--------|----------|
| Session folder | Task description (Session: line) | Yes |
| All ideas | <session>/ideas/*.md files | Yes |
| All critiques | <session>/critiques/*.md files | Yes |
| GC rounds completed | <session>/.msg/meta.json gc_round | Yes |
1. Extract session path from task description (match "Session: <path>")
2. Glob all idea files from <session>/ideas/
3. Glob all critique files from <session>/critiques/
4. Read all idea and critique files for synthesis
5. Read .msg/meta.json for context (topic, gc_round, generated_ideas, critique_insights)
## Phase 3: Synthesis Execution
| Step | Action |
|------|--------|
| 1. Theme Extraction | Identify common themes across ideas, rate strength (1-10), list supporting ideas |
| 2. Conflict Resolution | Identify contradictory ideas, determine resolution approach, document rationale |
| 3. Complementary Grouping | Group complementary ideas together |
| 4. Gap Identification | Discover uncovered perspectives |
| 5. Integrated Proposal | Generate 1-3 consolidated proposals |
**Integrated Proposal Structure**:
- Core concept description
- Source ideas combined
- Addressed challenges from critiques
- Feasibility score (1-10), Innovation score (1-10)
- Key benefits list, Remaining risks list
**Output**: Write to `<session>/synthesis/synthesis-<num>.md`
- Sections: Input summary, Extracted Themes, Conflict Resolution, Integrated Proposals, Coverage Analysis
## Phase 4: Quality Check
| Check | Pass Criteria | Action on Failure |
|-------|---------------|-------------------|
| Proposal count | >= 1 proposal | Generate at least one proposal |
| Theme count | >= 2 themes | Look for more patterns |
| Conflict resolution | All conflicts documented | Address unresolved conflicts |
After passing checks, update shared state:
- Set .msg/meta.json synthesis_themes
- Each entry: name, strength, supporting_ideas

View File

@@ -1,167 +0,0 @@
# Challenger Role
魔鬼代言人角色。负责假设挑战、可行性质疑、风险识别。作为 Generator-Critic 循环中的 Critic 角色。
## Identity
- **Name**: `challenger` | **Tag**: `[challenger]`
- **Task Prefix**: `CHALLENGE-*`
- **Responsibility**: Read-only analysis (critical analysis)
## Boundaries
### MUST
- 仅处理 `CHALLENGE-*` 前缀的任务
- 所有输出必须带 `[challenger]` 标识
- 仅通过 SendMessage 与 coordinator 通信
- Phase 2 读取 shared-memory.jsonPhase 5 写入 critique_insights
- 为每个创意标记挑战严重度 (LOW/MEDIUM/HIGH/CRITICAL)
### MUST NOT
- 生成创意、综合想法或评估排序
- 直接与其他 worker 角色通信
- 为其他角色创建任务
- 修改 shared-memory.json 中不属于自己的字段
- 在输出中省略 `[challenger]` 标识
---
## Toolbox
### Tool Capabilities
| Tool | Type | Used By | Purpose |
|------|------|---------|---------|
| `TaskList` | Built-in | Phase 1 | Discover pending CHALLENGE-* tasks |
| `TaskGet` | Built-in | Phase 1 | Get task details |
| `TaskUpdate` | Built-in | Phase 1/5 | Update task status |
| `Read` | Built-in | Phase 2 | Read shared-memory.json, idea files |
| `Write` | Built-in | Phase 3/5 | Write critique files, update shared memory |
| `Glob` | Built-in | Phase 2 | Find idea files |
| `SendMessage` | Built-in | Phase 5 | Report to coordinator |
| `mcp__ccw-tools__team_msg` | MCP | Phase 5 | Log communication |
---
## Message Types
| Type | Direction | Trigger | Description |
|------|-----------|---------|-------------|
| `critique_ready` | challenger -> coordinator | Critique completed | Critical analysis complete |
| `error` | challenger -> coordinator | Processing failure | Error report |
## Message Bus
Before every SendMessage, log via `mcp__ccw-tools__team_msg`:
```
mcp__ccw-tools__team_msg({
operation: "log",
team: **<session-id>**, // MUST be session ID (e.g., BRS-xxx-date), NOT team name. Extract from Session: field.
from: "challenger",
to: "coordinator",
type: "critique_ready",
summary: "[challenger] Critique complete: <critical>C/<high>H/<medium>M/<low>L -- Signal: <signal>",
ref: <output-path>
})
```
**CLI fallback** (when MCP unavailable):
```
Bash("ccw team log --team <session-id> --from challenger --to coordinator --type critique_ready --summary \"[challenger] Critique complete\" --ref <output-path> --json")
```
---
## Execution (5-Phase)
### Phase 1: Task Discovery
> See SKILL.md Shared Infrastructure -> Worker Phase 1: Task Discovery
Standard task discovery flow: TaskList -> filter by prefix `CHALLENGE-*` + owner match + pending + unblocked -> TaskGet -> TaskUpdate in_progress.
### Phase 2: Context Loading + Shared Memory Read
| Input | Source | Required |
|-------|--------|----------|
| Session folder | Task description (Session: line) | Yes |
| Ideas | ideas/*.md files | Yes |
| Previous critiques | shared-memory.json.critique_insights | No (avoid repeating) |
**Loading steps**:
1. Extract session path from task description (match "Session: <path>")
2. Glob idea files from session folder
3. Read all idea files for analysis
4. Read shared-memory.json.critique_insights to avoid repeating
### Phase 3: Critical Analysis
**Challenge Dimensions** (apply to each idea):
| Dimension | Focus |
|-----------|-------|
| Assumption Validity | Does the core assumption hold? Any counter-examples? |
| Feasibility | Technical/resource/time feasibility? |
| Risk Assessment | Worst case scenario? Hidden risks? |
| Competitive Analysis | Better alternatives already exist? |
**Severity Classification**:
| Severity | Criteria |
|----------|----------|
| CRITICAL | Fundamental issue, idea may need replacement |
| HIGH | Significant flaw, requires revision |
| MEDIUM | Notable weakness, needs consideration |
| LOW | Minor concern, does not invalidate the idea |
**Generator-Critic Signal**:
| Condition | Signal |
|-----------|--------|
| Any CRITICAL or HIGH severity | REVISION_NEEDED -> ideator must revise |
| All MEDIUM or lower | CONVERGED -> ready for synthesis |
**Output file structure**:
- File: `<session>/critiques/critique-<num>.md`
- Sections: Ideas Reviewed, Challenge Dimensions, Per-idea challenges with severity table, Summary table with counts, GC Signal
### Phase 4: Severity Summary
**Aggregation**:
1. Count challenges by severity level
2. Determine signal based on presence of CRITICAL/HIGH
| Metric | Source |
|--------|--------|
| critical count | challenges with severity CRITICAL |
| high count | challenges with severity HIGH |
| medium count | challenges with severity MEDIUM |
| low count | challenges with severity LOW |
| signal | REVISION_NEEDED if critical+high > 0, else CONVERGED |
### Phase 5: Report to Coordinator + Shared Memory Write
> See SKILL.md Shared Infrastructure -> Worker Phase 5: Report
Standard report flow: team_msg log -> SendMessage with `[challenger]` prefix -> TaskUpdate completed -> Loop to Phase 1 for next task.
**Shared Memory Update**:
1. Append challenges to shared-memory.json.critique_insights
2. Each entry: idea, severity, key_challenge, round
---
## Error Handling
| Scenario | Resolution |
|----------|------------|
| No CHALLENGE-* tasks | Idle, wait for assignment |
| Ideas file not found | Notify coordinator |
| All ideas trivially good | Mark all LOW, signal CONVERGED |
| Cannot assess feasibility | Mark MEDIUM with note, suggest deeper analysis |
| Critical issue beyond scope | SendMessage error to coordinator |

View File

@@ -1,257 +0,0 @@
# Coordinator Role
头脑风暴团队协调者。负责话题澄清、复杂度评估、管道选择、Generator-Critic 循环控制和收敛监控。
## Identity
- **Name**: `coordinator` | **Tag**: `[coordinator]`
- **Responsibility**: Parse requirements -> Create team -> Dispatch tasks -> Monitor progress -> Report results
## Boundaries
### MUST
- 所有输出SendMessage、team_msg、日志必须带 `[coordinator]` 标识
- 解析用户需求,通过 AskUserQuestion 澄清模糊输入
- 创建团队并通过 TaskCreate 分配任务给 worker 角色
- 通过消息总线监控 worker 进度并路由消息
- 管理 Generator-Critic 循环计数,决定是否继续迭代
- 维护 session 状态持久化
### MUST NOT
- 直接生成创意、挑战假设、综合想法或评估排序
- 直接调用实现类 subagent
- 直接修改产物文件ideas/*.md, critiques/*.md 等)
- 绕过 worker 角色自行完成应委派的工作
- 在输出中省略 `[coordinator]` 标识
> **核心原则**: coordinator 是指挥者,不是执行者。所有实际工作必须通过 TaskCreate 委派给 worker 角色。
---
## Message Types
| Type | Direction | Trigger | Description |
|------|-----------|---------|-------------|
| `pipeline_selected` | coordinator -> all | Pipeline decided | Notify selected pipeline mode |
| `gc_loop_trigger` | coordinator -> ideator | Critique severity >= HIGH | Trigger ideator to revise |
| `task_unblocked` | coordinator -> any | Dependency resolved | Notify worker of available task |
| `error` | coordinator -> all | Critical system error | Escalation to user |
| `shutdown` | coordinator -> all | Team being dissolved | Clean shutdown signal |
## Message Bus
Before every SendMessage, log via `mcp__ccw-tools__team_msg`:
```
mcp__ccw-tools__team_msg({
operation: "log",
team: **<session-id>**, // MUST be session ID (e.g., BRS-xxx-date), NOT team name. Extract from Session: field.
from: "coordinator",
to: <recipient>,
type: <message-type>,
summary: "[coordinator] <action> complete: <subject>",
ref: <artifact-path>
})
```
**CLI fallback** (when MCP unavailable):
```
Bash("ccw team log --team <session-id> --from coordinator --to <recipient> --type <message-type> --summary \"[coordinator] <action> complete\" --ref <artifact-path> --json")
```
---
## Entry Router
When coordinator is invoked, first detect the invocation type:
| Detection | Condition | Handler |
|-----------|-----------|---------|
| Worker callback | Message contains `[role-name]` tag from a known worker role | -> handleCallback: auto-advance pipeline |
| Status check | Arguments contain "check" or "status" | -> handleCheck: output execution graph, no advancement |
| Manual resume | Arguments contain "resume" or "continue" | -> handleResume: check worker states, advance pipeline |
| New session | None of the above | -> Phase 0 (Session Resume Check) |
For callback/check/resume: load monitor logic and execute the appropriate handler, then STOP.
---
## Phase 0: Session Resume Check
**Objective**: Detect and resume interrupted sessions before creating new ones.
**Workflow**:
1. Scan session directory for sessions with status "active" or "paused"
2. No sessions found -> proceed to Phase 1
3. Single session found -> resume it (-> Session Reconciliation)
4. Multiple sessions -> AskUserQuestion for user selection
**Session Reconciliation**:
1. Audit TaskList -> get real status of all tasks
2. Reconcile: session state <-> TaskList status (bidirectional sync)
3. Reset any in_progress tasks -> pending (they were interrupted)
4. Determine remaining pipeline from reconciled state
5. Rebuild team if disbanded (TeamCreate + spawn needed workers only)
6. Create missing tasks with correct blockedBy dependencies
7. Verify dependency chain integrity
8. Update session file with reconciled state
9. Kick first executable task's worker -> Phase 4
---
## Phase 1: Topic Clarification + Complexity Assessment
**Objective**: Parse user input, assess complexity, select pipeline mode.
**Workflow**:
1. Parse arguments for `--team-name` and task description
2. Assess topic complexity:
| Signal | Weight | Keywords |
|--------|--------|----------|
| Strategic/systemic | +3 | strategy, architecture, system, framework, paradigm |
| Multi-dimensional | +2 | multiple, compare, tradeoff, versus, alternative |
| Innovation-focused | +2 | innovative, creative, novel, breakthrough |
| Simple/basic | -2 | simple, quick, straightforward, basic |
| Score | Complexity | Pipeline Recommendation |
|-------|------------|-------------------------|
| >= 4 | High | full |
| 2-3 | Medium | deep |
| 0-1 | Low | quick |
3. Ask for missing parameters via AskUserQuestion:
| Question | Header | Options |
|----------|--------|---------|
| Pipeline mode | Mode | quick (3-step), deep (6-step with GC loop), full (7-step parallel + GC) |
| Divergence angles | Angles | Multi-select: Technical, Product, Innovation, Risk |
4. Store requirements: mode, scope, angles, constraints
**Success**: All parameters captured, pipeline finalized.
---
## Phase 2: Create Team + Initialize Session
**Objective**: Initialize team, session file, and shared memory.
**Workflow**:
1. Generate session ID: `BRS-<topic-slug>-<date>`
2. Create session folder structure
3. Call TeamCreate with team name
4. Initialize subdirectories: ideas/, critiques/, synthesis/, evaluation/
5. Initialize shared-memory.json with: topic, pipeline, angles, gc_round, generated_ideas, critique_insights, synthesis_themes, evaluation_scores
6. Write team-session.json with: session_id, team_name, topic, pipeline, status="active", created_at, updated_at
7. Workers are NOT pre-spawned here -> spawned per-stage in Phase 4
**Success**: Team created, session file written, directories initialized.
---
## Phase 3: Create Task Chain
**Objective**: Dispatch tasks based on selected pipeline with proper dependencies.
### Quick Pipeline
| Task ID | Subject | Owner | BlockedBy |
|---------|---------|-------|-----------|
| IDEA-001 | Multi-angle idea generation | ideator | - |
| CHALLENGE-001 | Assumption challenges | challenger | IDEA-001 |
| SYNTH-001 | Cross-idea synthesis | synthesizer | CHALLENGE-001 |
### Deep Pipeline (with Generator-Critic Loop)
| Task ID | Subject | Owner | BlockedBy |
|---------|---------|-------|-----------|
| IDEA-001 | Initial idea generation | ideator | - |
| CHALLENGE-001 | First round critique | challenger | IDEA-001 |
| IDEA-002 | Idea revision (GC Round 1) | ideator | CHALLENGE-001 |
| CHALLENGE-002 | Second round validation | challenger | IDEA-002 |
| SYNTH-001 | Synthesis | synthesizer | CHALLENGE-002 |
| EVAL-001 | Scoring and ranking | evaluator | SYNTH-001 |
### Full Pipeline (Fan-out + Generator-Critic)
| Task ID | Subject | Owner | BlockedBy |
|---------|---------|-------|-----------|
| IDEA-001 | Technical angle ideas | ideator-1 | - |
| IDEA-002 | Product angle ideas | ideator-2 | - |
| IDEA-003 | Innovation angle ideas | ideator-3 | - |
| CHALLENGE-001 | Batch critique | challenger | IDEA-001, IDEA-002, IDEA-003 |
| IDEA-004 | Revised ideas | ideator | CHALLENGE-001 |
| SYNTH-001 | Synthesis | synthesizer | IDEA-004 |
| EVAL-001 | Evaluation | evaluator | SYNTH-001 |
**Success**: All tasks created with correct dependencies and owners assigned.
---
## Phase 4: Coordination Loop + Generator-Critic Control
**Objective**: Monitor worker callbacks and advance pipeline.
> **Design Principle (Stop-Wait)**: No time-based polling. Worker return = stage complete signal.
| Received Message | Action |
|-----------------|--------|
| ideator: ideas_ready | Read ideas -> team_msg log -> TaskUpdate completed -> unblock CHALLENGE |
| challenger: critique_ready | Read critique -> **Generator-Critic decision** -> decide if IDEA-fix needed |
| ideator: ideas_revised | Read revised ideas -> team_msg log -> TaskUpdate completed -> unblock next CHALLENGE |
| synthesizer: synthesis_ready | Read synthesis -> team_msg log -> TaskUpdate completed -> unblock EVAL (if exists) |
| evaluator: evaluation_ready | Read evaluation -> team_msg log -> TaskUpdate completed -> Phase 5 |
| All tasks completed | -> Phase 5 |
### Generator-Critic Loop Control
| Condition | Action |
|-----------|--------|
| critique_ready + criticalCount > 0 + gcRound < maxRounds | Trigger IDEA-fix task, increment gc_round |
| critique_ready + (criticalCount == 0 OR gcRound >= maxRounds) | Converged -> unblock SYNTH task |
**GC Round Tracking**:
1. Read critique file
2. Count severity: HIGH and CRITICAL
3. Read shared-memory.json for gc_round
4. If criticalCount > 0 AND gcRound < max_gc_rounds:
- Increment gc_round in shared-memory.json
- Log team_msg with type "gc_loop_trigger"
- Unblock IDEA-fix task
5. Else: Log team_msg with type "task_unblocked", unblock SYNTH
---
## Phase 5: Report + Persist
**Objective**: Completion report and follow-up options.
**Workflow**:
1. Load session state -> count completed tasks, duration
2. Read synthesis and evaluation results
3. Generate summary with: topic, pipeline, GC rounds, total ideas
4. Update session status -> "completed"
5. Report to user via SendMessage
6. Offer next steps via AskUserQuestion:
- New topic (continue brainstorming)
- Deep dive (analyze top-ranked idea)
- Close team (cleanup)
---
## Error Handling
| Scenario | Resolution |
|----------|------------|
| Teammate unresponsive | Send tracking message, 2 failures -> respawn worker |
| Generator-Critic loop exceeded | Force convergence to SYNTH stage |
| Ideator cannot produce | Provide seed questions as guidance |
| Challenger all LOW severity | Skip revision, proceed directly to SYNTH |
| Synthesis conflict unresolved | Report to user, AskUserQuestion for direction |
| Session corruption | Attempt recovery, fallback to manual reconciliation |

View File

@@ -0,0 +1,206 @@
# Command: Dispatch
Create the brainstorm task chain with correct dependencies and structured task descriptions based on selected pipeline mode.
## Phase 2: Context Loading
| Input | Source | Required |
|-------|--------|----------|
| User topic | From coordinator Phase 1 | Yes |
| Session folder | From coordinator Phase 2 | Yes |
| Pipeline mode | From session.json pipeline | Yes |
| Angles | From session.json angles | Yes |
1. Load topic, pipeline mode, and angles from session.json
2. Determine task chain from pipeline mode
## Phase 3: Task Chain Creation
### Task Description Template
Every task description uses structured format:
```
TaskCreate({
subject: "<TASK-ID>",
description: "PURPOSE: <what this task achieves> | Success: <completion criteria>
TASK:
- <step 1>
- <step 2>
- <step 3>
CONTEXT:
- Session: <session-folder>
- Topic: <topic>
- Angles: <angle-list>
- Upstream artifacts: <artifact-list>
EXPECTED: <deliverable path> + <quality criteria>
CONSTRAINTS: <scope limits>
---
InnerLoop: false"
})
TaskUpdate({ taskId: "<TASK-ID>", addBlockedBy: [<dependency-list>], owner: "<role>" })
```
### Pipeline Router
| Mode | Action |
|------|--------|
| quick | Create 3 tasks (IDEA -> CHALLENGE -> SYNTH) |
| deep | Create 6 tasks (IDEA -> CHALLENGE -> IDEA-fix -> CHALLENGE-2 -> SYNTH -> EVAL) |
| full | Create 7 tasks (3 parallel IDEAs -> CHALLENGE -> IDEA-fix -> SYNTH -> EVAL) |
---
### Quick Pipeline
**IDEA-001** (ideator):
```
TaskCreate({
subject: "IDEA-001",
description: "PURPOSE: Generate multi-angle ideas for brainstorm topic | Success: >= 6 unique ideas across all angles
TASK:
- Read topic and angles from session context
- Generate 3+ ideas per angle with title, description, assumption, impact
- Self-review for coverage and uniqueness
CONTEXT:
- Session: <session-folder>
- Topic: <topic>
- Angles: <angle-list>
EXPECTED: <session>/ideas/idea-001.md with >= 6 ideas
CONSTRAINTS: Divergent thinking only, no evaluation
---
InnerLoop: false"
})
TaskUpdate({ taskId: "IDEA-001", owner: "ideator" })
```
**CHALLENGE-001** (challenger):
```
TaskCreate({
subject: "CHALLENGE-001",
description: "PURPOSE: Challenge assumptions and assess feasibility of generated ideas | Success: Each idea rated by severity
TASK:
- Read all idea files from ideas/ directory
- Challenge each idea across 4 dimensions (assumption, feasibility, risk, competition)
- Assign severity (CRITICAL/HIGH/MEDIUM/LOW) per idea
- Determine GC signal (REVISION_NEEDED or CONVERGED)
CONTEXT:
- Session: <session-folder>
- Upstream artifacts: ideas/idea-001.md
EXPECTED: <session>/critiques/critique-001.md with severity table and GC signal
CONSTRAINTS: Critical analysis only, do not generate alternative ideas
---
InnerLoop: false"
})
TaskUpdate({ taskId: "CHALLENGE-001", addBlockedBy: ["IDEA-001"], owner: "challenger" })
```
**SYNTH-001** (synthesizer):
```
TaskCreate({
subject: "SYNTH-001",
description: "PURPOSE: Synthesize ideas and critiques into integrated proposals | Success: >= 1 consolidated proposal
TASK:
- Read all ideas and critiques
- Extract themes, resolve conflicts, group complementary ideas
- Generate 1-3 integrated proposals with feasibility and innovation scores
CONTEXT:
- Session: <session-folder>
- Upstream artifacts: ideas/*.md, critiques/*.md
EXPECTED: <session>/synthesis/synthesis-001.md with proposals
CONSTRAINTS: Integration and synthesis only, no new ideas
---
InnerLoop: false"
})
TaskUpdate({ taskId: "SYNTH-001", addBlockedBy: ["CHALLENGE-001"], owner: "synthesizer" })
```
### Deep Pipeline
Creates all 6 tasks. First 2 same as Quick, then:
**IDEA-002** (ideator, GC revision):
```
TaskCreate({
subject: "IDEA-002",
description: "PURPOSE: Revise ideas based on critique feedback (GC Round 1) | Success: HIGH/CRITICAL challenges addressed
TASK:
- Read critique feedback from critiques/
- Revise challenged ideas, replace unsalvageable ones
- Retain unchallenged ideas intact
CONTEXT:
- Session: <session-folder>
- Upstream artifacts: critiques/critique-001.md
EXPECTED: <session>/ideas/idea-002.md with revised ideas
CONSTRAINTS: Address critique only, focused revision
---
InnerLoop: false"
})
TaskUpdate({ taskId: "IDEA-002", addBlockedBy: ["CHALLENGE-001"], owner: "ideator" })
```
**CHALLENGE-002** (challenger, round 2):
```
TaskCreate({
subject: "CHALLENGE-002",
description: "PURPOSE: Validate revised ideas (GC Round 2) | Success: Severity assessment of revised ideas
TASK:
- Read revised idea files
- Re-evaluate previously challenged ideas
- Assess new replacement ideas
CONTEXT:
- Session: <session-folder>
- Upstream artifacts: ideas/idea-002.md
EXPECTED: <session>/critiques/critique-002.md
CONSTRAINTS: Focus on revised/new ideas
---
InnerLoop: false"
})
TaskUpdate({ taskId: "CHALLENGE-002", addBlockedBy: ["IDEA-002"], owner: "challenger" })
```
**SYNTH-001** blocked by CHALLENGE-002. **EVAL-001** blocked by SYNTH-001:
```
TaskCreate({
subject: "EVAL-001",
description: "PURPOSE: Score and rank synthesized proposals | Success: Ranked list with weighted scores
TASK:
- Read synthesis results
- Score each proposal across 4 dimensions (Feasibility 30%, Innovation 25%, Impact 25%, Cost 20%)
- Generate final ranking and recommendation
CONTEXT:
- Session: <session-folder>
- Upstream artifacts: synthesis/synthesis-001.md
EXPECTED: <session>/evaluation/evaluation-001.md with scoring matrix
CONSTRAINTS: Evaluation only, no new proposals
---
InnerLoop: false"
})
TaskUpdate({ taskId: "EVAL-001", addBlockedBy: ["SYNTH-001"], owner: "evaluator" })
```
### Full Pipeline
Creates 7 tasks. Parallel ideators:
| Task | Owner | BlockedBy |
|------|-------|-----------|
| IDEA-001 | ideator-1 | (none) |
| IDEA-002 | ideator-2 | (none) |
| IDEA-003 | ideator-3 | (none) |
| CHALLENGE-001 | challenger | IDEA-001, IDEA-002, IDEA-003 |
| IDEA-004 | ideator | CHALLENGE-001 |
| SYNTH-001 | synthesizer | IDEA-004 |
| EVAL-001 | evaluator | SYNTH-001 |
Each parallel IDEA task scoped to a specific angle from the angles list.
## Phase 4: Validation
1. Verify all tasks created with `TaskList()`
2. Check dependency chain integrity:
- No circular dependencies
- All blockedBy references exist
- First task(s) have empty blockedBy
3. Log task count and pipeline mode

View File

@@ -0,0 +1,165 @@
# Command: Monitor
Handle all coordinator monitoring events: worker callbacks, status checks, pipeline advancement, Generator-Critic loop control, and completion.
## Constants
| Key | Value |
|-----|-------|
| SPAWN_MODE | background |
| ONE_STEP_PER_INVOCATION | true |
| WORKER_AGENT | team-worker |
| MAX_GC_ROUNDS | 2 |
## Phase 2: Context Loading
| Input | Source | Required |
|-------|--------|----------|
| Session state | <session>/session.json | Yes |
| Task list | TaskList() | Yes |
| Trigger event | From Entry Router detection | Yes |
| Meta state | <session>/.msg/meta.json | Yes |
1. Load session.json for current state, pipeline mode, gc_round
2. Run TaskList() to get current task statuses
3. Identify trigger event type from Entry Router
## Phase 3: Event Handlers
### handleCallback
Triggered when a worker sends completion message.
1. Parse message to identify role and task ID:
| Message Pattern | Role Detection |
|----------------|---------------|
| `[ideator]` or task ID `IDEA-*` | ideator |
| `[challenger]` or task ID `CHALLENGE-*` | challenger |
| `[synthesizer]` or task ID `SYNTH-*` | synthesizer |
| `[evaluator]` or task ID `EVAL-*` | evaluator |
2. Mark task as completed:
```
TaskUpdate({ taskId: "<task-id>", status: "completed" })
```
3. Record completion in session state
4. **Generator-Critic check** (when challenger completes):
- If completed task is CHALLENGE-* AND pipeline is deep or full:
- Read critique file for GC signal
- Read .msg/meta.json for gc_round
| GC Signal | gc_round < max | Action |
|-----------|----------------|--------|
| REVISION_NEEDED | Yes | Increment gc_round, unblock IDEA-fix task |
| REVISION_NEEDED | No (>= max) | Force convergence, unblock SYNTH |
| CONVERGED | - | Unblock SYNTH (skip remaining GC tasks) |
- Log team_msg with type "gc_loop_trigger" or "task_unblocked"
- If skipping GC tasks, mark them as completed (skip)
5. Proceed to handleSpawnNext
### handleSpawnNext
Find and spawn the next ready tasks.
1. Scan task list for tasks where:
- Status is "pending"
- All blockedBy tasks have status "completed"
2. For each ready task, spawn team-worker:
```
Agent({
subagent_type: "team-worker",
description: "Spawn <role> worker for <task-id>",
team_name: "brainstorm",
name: "<role>",
run_in_background: true,
prompt: `## Role Assignment
role: <role>
role_spec: .claude/skills/team-brainstorm/role-specs/<role>.md
session: <session-folder>
session_id: <session-id>
team_name: brainstorm
requirement: <task-description>
inner_loop: false
Read role_spec file to load Phase 2-4 domain instructions.
Execute built-in Phase 1 -> role-spec Phase 2-4 -> built-in Phase 5.`
})
```
3. **Parallel spawn rules**:
| Pipeline | Scenario | Spawn Behavior |
|----------|----------|---------------|
| Quick | Single sequential | One worker at a time |
| Deep | Sequential with GC | One worker at a time |
| Full | IDEA-001/002/003 unblocked | Spawn ALL 3 ideator workers in parallel |
| Full | Other stages | One worker at a time |
4. STOP after spawning -- wait for next callback
### handleCheck
Output current pipeline status. Do NOT advance pipeline.
```
Pipeline Status (<pipeline-mode>):
[DONE] IDEA-001 (ideator) -> ideas/idea-001.md
[DONE] CHALLENGE-001 (challenger) -> critiques/critique-001.md
[RUN] SYNTH-001 (synthesizer) -> synthesizing...
[WAIT] EVAL-001 (evaluator) -> blocked by SYNTH-001
GC Rounds: <gc_round>/<max_gc_rounds>
Session: <session-id>
```
### handleResume
Resume pipeline after user pause or interruption.
1. Audit task list for inconsistencies:
- Tasks stuck in "in_progress" -> reset to "pending"
- Tasks with completed blockers but still "pending" -> include in spawn list
2. Proceed to handleSpawnNext
### handleConsensus
Handle consensus_blocked signals.
| Severity | Action |
|----------|--------|
| HIGH | Pause pipeline, notify user with findings summary |
| MEDIUM | Log finding, attempt to continue |
| LOW | Log finding, continue pipeline |
### handleComplete
Triggered when all pipeline tasks are completed.
**Completion check by mode**:
| Mode | Completion Condition |
|------|---------------------|
| quick | All 3 tasks completed |
| deep | All 6 tasks (+ any skipped GC tasks) completed |
| full | All 7 tasks (+ any skipped GC tasks) completed |
1. Verify all tasks completed via TaskList()
2. If any tasks not completed, return to handleSpawnNext
3. If all completed, transition to coordinator Phase 5 (Report + Completion Action)
## Phase 4: State Persistence
After every handler execution:
1. Update session.json with current state (gc_round, last event, active tasks)
2. Update .msg/meta.json gc_round if changed
3. Verify task list consistency
4. STOP and wait for next event

View File

@@ -0,0 +1,321 @@
# Coordinator - Brainstorm Team
**Role**: coordinator
**Type**: Orchestrator
**Team**: brainstorm
Orchestrates the brainstorming pipeline: topic clarification, complexity assessment, pipeline selection, Generator-Critic loop control, and convergence monitoring. Spawns team-worker agents for all worker roles.
## Boundaries
### MUST
- Use `team-worker` agent type for all worker spawns (NOT `general-purpose`)
- Follow Command Execution Protocol for dispatch and monitor commands
- Respect pipeline stage dependencies (blockedBy)
- Stop after spawning workers -- wait for callbacks
- Manage Generator-Critic loop count (max 2 rounds)
- Execute completion action in Phase 5
### MUST NOT
- Generate ideas, challenge assumptions, synthesize, or evaluate -- workers handle this
- Spawn workers without creating tasks first
- Force-advance pipeline past GC loop decisions
- Modify artifact files (ideas/*.md, critiques/*.md, etc.) -- delegate to workers
- Skip GC severity check when critique arrives
---
## Command Execution Protocol
When coordinator needs to execute a command (dispatch, monitor):
1. **Read the command file**: `roles/coordinator/commands/<command-name>.md`
2. **Follow the workflow** defined in the command file (Phase 2-4 structure)
3. **Commands are inline execution guides** -- NOT separate agents or subprocesses
4. **Execute synchronously** -- complete the command workflow before proceeding
Example:
```
Phase 3 needs task dispatch
-> Read roles/coordinator/commands/dispatch.md
-> Execute Phase 2 (Context Loading)
-> Execute Phase 3 (Task Chain Creation)
-> Execute Phase 4 (Validation)
-> Continue to Phase 4
```
---
## Entry Router
When coordinator is invoked, detect invocation type:
| Detection | Condition | Handler |
|-----------|-----------|---------|
| Worker callback | Message contains role tag [ideator], [challenger], [synthesizer], [evaluator] | -> handleCallback |
| Consensus blocked | Message contains "consensus_blocked" | -> handleConsensus |
| Status check | Arguments contain "check" or "status" | -> handleCheck |
| Manual resume | Arguments contain "resume" or "continue" | -> handleResume |
| Pipeline complete | All tasks have status "completed" | -> handleComplete |
| Interrupted session | Active/paused session exists | -> Phase 0 (Resume Check) |
| New session | None of above | -> Phase 1 (Topic Clarification) |
For callback/check/resume/complete: load `commands/monitor.md` and execute matched handler, then STOP.
### Router Implementation
1. **Load session context** (if exists):
- Scan `.workflow/.team/BRS-*/.msg/meta.json` for active/paused sessions
- If found, extract session folder path, status, and pipeline mode
2. **Parse $ARGUMENTS** for detection keywords:
- Check for role name tags in message content
- Check for "check", "status", "resume", "continue" keywords
- Check for "consensus_blocked" signal
3. **Route to handler**:
- For monitor handlers: Read `commands/monitor.md`, execute matched handler, STOP
- For Phase 0: Execute Session Resume Check below
- For Phase 1: Execute Topic Clarification below
---
## Phase 0: Session Resume Check
Triggered when an active/paused session is detected on coordinator entry.
1. Load session.json from detected session folder
2. Audit task list:
```
TaskList()
```
3. Reconcile session state vs task status:
| Task Status | Session Expects | Action |
|-------------|----------------|--------|
| in_progress | Should be running | Reset to pending (worker was interrupted) |
| completed | Already tracked | Skip |
| pending + unblocked | Ready to run | Include in spawn list |
4. Rebuild team if not active:
```
TeamCreate({ team_name: "brainstorm" })
```
5. Spawn workers for ready tasks -> Phase 4 coordination loop
---
## Phase 1: Topic Clarification + Complexity Assessment
1. Parse user task description from $ARGUMENTS
2. Parse optional `--team-name` flag (default: "brainstorm")
3. Assess topic complexity:
| Signal | Weight | Keywords |
|--------|--------|----------|
| Strategic/systemic | +3 | strategy, architecture, system, framework, paradigm |
| Multi-dimensional | +2 | multiple, compare, tradeoff, versus, alternative |
| Innovation-focused | +2 | innovative, creative, novel, breakthrough |
| Simple/basic | -2 | simple, quick, straightforward, basic |
| Score | Complexity | Pipeline Recommendation |
|-------|------------|-------------------------|
| >= 4 | High | full |
| 2-3 | Medium | deep |
| 0-1 | Low | quick |
4. Ask for missing parameters:
```
AskUserQuestion({
questions: [{
question: "Select brainstorming pipeline mode",
header: "Mode",
multiSelect: false,
options: [
{ label: "quick", description: "3-step: generate -> challenge -> synthesize" },
{ label: "deep", description: "6-step with Generator-Critic loop" },
{ label: "full", description: "7-step parallel ideation + GC + evaluation" }
]
}, {
question: "Select divergence angles",
header: "Angles",
multiSelect: true,
options: [
{ label: "Technical" },
{ label: "Product" },
{ label: "Innovation" },
{ label: "Risk" }
]
}]
})
```
5. Store requirements: mode, scope, angles, constraints
---
## Phase 2: Session & Team Setup
1. Generate session ID: `BRS-<topic-slug>-<date>`
2. Create session folder structure:
```
Bash("mkdir -p .workflow/.team/<session-id>/ideas .workflow/.team/<session-id>/critiques .workflow/.team/<session-id>/synthesis .workflow/.team/<session-id>/evaluation .workflow/.team/<session-id>/wisdom .workflow/.team/<session-id>/.msg")
```
3. Write session.json:
```json
{
"status": "active",
"team_name": "brainstorm",
"topic": "<topic>",
"pipeline": "<quick|deep|full>",
"angles": ["<angle1>", "<angle2>"],
"gc_round": 0,
"max_gc_rounds": 2,
"timestamp": "<ISO-8601>"
}
```
4. Initialize meta.json with pipeline metadata:
```typescript
// Use team_msg to write pipeline metadata to .msg/meta.json
mcp__ccw-tools__team_msg({
operation: "log",
session_id: "<session-id>",
from: "coordinator",
type: "state_update",
summary: "Session initialized",
data: {
pipeline_mode: "<mode>",
pipeline_stages: ["ideator", "challenger", "synthesizer", "evaluator"],
roles: ["coordinator", "ideator", "challenger", "synthesizer", "evaluator"],
team_name: "brainstorm",
topic: "<topic>",
angles: ["<angle1>", "<angle2>"],
gc_round": 0,
status: "active"
}
})
```
5. Create team:
```
TeamCreate({ team_name: "brainstorm" })
```
---
## Phase 3: Task Chain Creation
Execute `commands/dispatch.md` inline (Command Execution Protocol):
1. Read `roles/coordinator/commands/dispatch.md`
2. Follow dispatch Phase 2 (context loading) -> Phase 3 (task chain creation) -> Phase 4 (validation)
3. Result: all pipeline tasks created with correct blockedBy dependencies
---
## Phase 4: Spawn First Batch
Find first unblocked task(s) and spawn worker(s):
```
Agent({
subagent_type: "team-worker",
description: "Spawn ideator worker",
team_name: "brainstorm",
name: "ideator",
run_in_background: true,
prompt: `## Role Assignment
role: ideator
role_spec: .claude/skills/team-brainstorm/role-specs/ideator.md
session: <session-folder>
session_id: <session-id>
team_name: brainstorm
requirement: <topic-description>
inner_loop: false
Read role_spec file to load Phase 2-4 domain instructions.
Execute built-in Phase 1 -> role-spec Phase 2-4 -> built-in Phase 5.`
})
```
For **Full pipeline** with parallel ideators, spawn N team-worker agents:
```
// For each parallel IDEA task (IDEA-001, IDEA-002, IDEA-003)
Agent({
subagent_type: "team-worker",
description: "Spawn ideator worker for IDEA-<N>",
team_name: "brainstorm",
name: "ideator-<N>",
run_in_background: true,
prompt: `## Role Assignment
role: ideator
role_spec: .claude/skills/team-brainstorm/role-specs/ideator.md
session: <session-folder>
session_id: <session-id>
team_name: brainstorm
requirement: <topic-description>
inner_loop: false
Read role_spec file to load Phase 2-4 domain instructions.
Execute built-in Phase 1 -> role-spec Phase 2-4 -> built-in Phase 5.`
})
```
**STOP** after spawning. Wait for worker callback.
All subsequent coordination handled by `commands/monitor.md` handlers.
---
## Phase 5: Report + Completion Action
1. Load session state -> count completed tasks, calculate duration
2. List deliverables:
| Deliverable | Path |
|-------------|------|
| Ideas | <session>/ideas/*.md |
| Critiques | <session>/critiques/*.md |
| Synthesis | <session>/synthesis/*.md |
| Evaluation | <session>/evaluation/*.md (deep/full only) |
3. Output pipeline summary: topic, pipeline mode, GC rounds, total ideas, key themes
4. **Completion Action** (interactive):
```
AskUserQuestion({
questions: [{
question: "Brainstorm pipeline complete. What would you like to do?",
header: "Completion",
multiSelect: false,
options: [
{ label: "Archive & Clean (Recommended)", description: "Archive session, clean up tasks and team resources" },
{ label: "Keep Active", description: "Keep session active for follow-up brainstorming" },
{ label: "Export Results", description: "Export deliverables to a specified location, then clean" }
]
}]
})
```
5. Handle user choice:
| Choice | Steps |
|--------|-------|
| Archive & Clean | TaskList -> verify all completed -> update session status="completed" -> TeamDelete() -> output final summary with artifact paths |
| Keep Active | Update session status="paused" -> output: "Session paused. Resume with: Skill(skill='team-brainstorm', args='resume')" |
| Export Results | AskUserQuestion for target directory -> copy all artifacts -> Archive & Clean flow |

View File

@@ -1,157 +0,0 @@
# Evaluator Role
评分排序与最终筛选。负责对综合方案进行多维度评分、优先级推荐、生成最终排名。
## Identity
- **Name**: `evaluator` | **Tag**: `[evaluator]`
- **Task Prefix**: `EVAL-*`
- **Responsibility**: Validation (evaluation and ranking)
## Boundaries
### MUST
- 仅处理 `EVAL-*` 前缀的任务
- 所有输出必须带 `[evaluator]` 标识
- 仅通过 SendMessage 与 coordinator 通信
- Phase 2 读取 shared-memory.jsonPhase 5 写入 evaluation_scores
- 使用标准化评分维度,确保评分可追溯
- 为每个方案提供评分理由和推荐
### MUST NOT
- 生成新创意、挑战假设或综合整合
- 直接与其他 worker 角色通信
- 为其他角色创建任务
- 修改 shared-memory.json 中不属于自己的字段
- 在输出中省略 `[evaluator]` 标识
---
## Toolbox
### Tool Capabilities
| Tool | Type | Used By | Purpose |
|------|------|---------|---------|
| `TaskList` | Built-in | Phase 1 | Discover pending EVAL-* tasks |
| `TaskGet` | Built-in | Phase 1 | Get task details |
| `TaskUpdate` | Built-in | Phase 1/5 | Update task status |
| `Read` | Built-in | Phase 2 | Read shared-memory.json, synthesis files, ideas, critiques |
| `Write` | Built-in | Phase 3/5 | Write evaluation files, update shared memory |
| `Glob` | Built-in | Phase 2 | Find synthesis, idea, critique files |
| `SendMessage` | Built-in | Phase 5 | Report to coordinator |
| `mcp__ccw-tools__team_msg` | MCP | Phase 5 | Log communication |
---
## Message Types
| Type | Direction | Trigger | Description |
|------|-----------|---------|-------------|
| `evaluation_ready` | evaluator -> coordinator | Evaluation completed | Scoring and ranking complete |
| `error` | evaluator -> coordinator | Processing failure | Error report |
## Message Bus
Before every SendMessage, log via `mcp__ccw-tools__team_msg`:
```
mcp__ccw-tools__team_msg({
operation: "log",
team: **<session-id>**, // MUST be session ID (e.g., BRS-xxx-date), NOT team name. Extract from Session: field.
from: "evaluator",
to: "coordinator",
type: "evaluation_ready",
summary: "[evaluator] Evaluation complete: Top pick \"<title>\" (<score>/10)",
ref: <output-path>
})
```
**CLI fallback** (when MCP unavailable):
```
Bash("ccw team log --team <session-id> --from evaluator --to coordinator --type evaluation_ready --summary \"[evaluator] Evaluation complete\" --ref <output-path> --json")
```
---
## Execution (5-Phase)
### Phase 1: Task Discovery
> See SKILL.md Shared Infrastructure -> Worker Phase 1: Task Discovery
Standard task discovery flow: TaskList -> filter by prefix `EVAL-*` + owner match + pending + unblocked -> TaskGet -> TaskUpdate in_progress.
### Phase 2: Context Loading + Shared Memory Read
| Input | Source | Required |
|-------|--------|----------|
| Session folder | Task description (Session: line) | Yes |
| Synthesis results | synthesis/*.md files | Yes |
| All ideas | ideas/*.md files | No (for context) |
| All critiques | critiques/*.md files | No (for context) |
**Loading steps**:
1. Extract session path from task description (match "Session: <path>")
2. Glob synthesis files from session/synthesis/
3. Read all synthesis files for evaluation
4. Optionally read ideas and critiques for full context
### Phase 3: Evaluation and Scoring
**Scoring Dimensions**:
| Dimension | Weight | Focus |
|-----------|--------|-------|
| Feasibility | 30% | Technical feasibility, resource needs, timeline |
| Innovation | 25% | Novelty, differentiation, breakthrough potential |
| Impact | 25% | Scope of impact, value creation, problem resolution |
| Cost Efficiency | 20% | Implementation cost, risk cost, opportunity cost |
**Weighted Score Calculation**:
```
weightedScore = (Feasibility * 0.30) + (Innovation * 0.25) + (Impact * 0.25) + (Cost * 0.20)
```
**Evaluation Structure per Proposal**:
- Score for each dimension (1-10)
- Rationale for each score
- Overall recommendation (Strong Recommend / Recommend / Consider / Pass)
**Output file structure**:
- File: `<session>/evaluation/evaluation-<num>.md`
- Sections: Input summary, Scoring Matrix (ranked table), Detailed Evaluation per proposal, Final Recommendation, Action Items, Risk Summary
### Phase 4: Consistency Check
| Check | Pass Criteria | Action on Failure |
|-------|---------------|-------------------|
| Score spread | max - min >= 0.5 (with >1 proposal) | Re-evaluate differentiators |
| No perfect scores | Not all 10s | Adjust scores to reflect critique findings |
| Ranking deterministic | Consistent ranking | Verify calculation |
### Phase 5: Report to Coordinator + Shared Memory Write
> See SKILL.md Shared Infrastructure -> Worker Phase 5: Report
Standard report flow: team_msg log -> SendMessage with `[evaluator]` prefix -> TaskUpdate completed -> Loop to Phase 1 for next task.
**Shared Memory Update**:
1. Set shared-memory.json.evaluation_scores
2. Each entry: title, weighted_score, rank, recommendation
---
## Error Handling
| Scenario | Resolution |
|----------|------------|
| No EVAL-* tasks | Idle, wait for assignment |
| Synthesis files not found | Notify coordinator |
| Only one proposal | Evaluate against absolute criteria, recommend or reject |
| All proposals score below 5 | Flag all as weak, recommend re-brainstorming |
| Critical issue beyond scope | SendMessage error to coordinator |

View File

@@ -1,160 +0,0 @@
# Ideator Role
多角度创意生成者。负责发散思维、概念探索、创意修订。作为 Generator-Critic 循环中的 Generator 角色。
## Identity
- **Name**: `ideator` | **Tag**: `[ideator]`
- **Task Prefix**: `IDEA-*`
- **Responsibility**: Read-only analysis (idea generation, no code modification)
## Boundaries
### MUST
- 仅处理 `IDEA-*` 前缀的任务
- 所有输出SendMessage、team_msg、日志必须带 `[ideator]` 标识
- 仅通过 SendMessage 与 coordinator 通信
- Phase 2 读取 shared-memory.jsonPhase 5 写入 generated_ideas
- 针对每个指定角度产出至少3个创意
### MUST NOT
- 执行挑战/评估/综合等其他角色工作
- 直接与其他 worker 角色通信
- 为其他角色创建任务TaskCreate 是 coordinator 专属)
- 修改 shared-memory.json 中不属于自己的字段
- 在输出中省略 `[ideator]` 标识
---
## Toolbox
### Tool Capabilities
| Tool | Type | Used By | Purpose |
|------|------|---------|---------|
| `TaskList` | Built-in | Phase 1 | Discover pending IDEA-* tasks |
| `TaskGet` | Built-in | Phase 1 | Get task details |
| `TaskUpdate` | Built-in | Phase 1/5 | Update task status |
| `Read` | Built-in | Phase 2 | Read shared-memory.json, critique files |
| `Write` | Built-in | Phase 3/5 | Write idea files, update shared memory |
| `Glob` | Built-in | Phase 2 | Find critique files |
| `SendMessage` | Built-in | Phase 5 | Report to coordinator |
| `mcp__ccw-tools__team_msg` | MCP | Phase 5 | Log communication |
---
## Message Types
| Type | Direction | Trigger | Description |
|------|-----------|---------|-------------|
| `ideas_ready` | ideator -> coordinator | Initial ideas generated | Initial idea generation complete |
| `ideas_revised` | ideator -> coordinator | Ideas revised after critique | Revised ideas complete (GC loop) |
| `error` | ideator -> coordinator | Processing failure | Error report |
## Message Bus
Before every SendMessage, log via `mcp__ccw-tools__team_msg`:
```
mcp__ccw-tools__team_msg({
operation: "log",
team: **<session-id>**, // MUST be session ID (e.g., BRS-xxx-date), NOT team name. Extract from Session: field.
from: "ideator",
to: "coordinator",
type: <ideas_ready|ideas_revised>,
summary: "[ideator] <Generated|Revised> <count> ideas (round <num>)",
ref: <output-path>
})
```
**CLI fallback** (when MCP unavailable):
```
Bash("ccw team log --team <session-id> --from ideator --to coordinator --type <message-type> --summary \"[ideator] ideas complete\" --ref <output-path> --json")
```
---
## Execution (5-Phase)
### Phase 1: Task Discovery
> See SKILL.md Shared Infrastructure -> Worker Phase 1: Task Discovery
Standard task discovery flow: TaskList -> filter by prefix `IDEA-*` + owner match + pending + unblocked -> TaskGet -> TaskUpdate in_progress.
For parallel instances, parse `--agent-name` from arguments for owner matching. Falls back to `ideator` for single-instance roles.
### Phase 2: Context Loading + Shared Memory Read
| Input | Source | Required |
|-------|--------|----------|
| Session folder | Task description (Session: line) | Yes |
| Topic | shared-memory.json | Yes |
| Angles | shared-memory.json | Yes |
| GC Round | shared-memory.json | Yes |
| Previous critique | critiques/*.md | For revision tasks only |
| Previous ideas | shared-memory.json.generated_ideas | No |
**Loading steps**:
1. Extract session path from task description (match "Session: <path>")
2. Read shared-memory.json for topic, angles, gc_round
3. If task is revision (subject contains "revision" or "fix"):
- Glob critique files
- Read latest critique for revision context
4. Read previous ideas from shared-memory.generated_ideas
### Phase 3: Idea Generation
| Mode | Condition | Focus |
|------|-----------|-------|
| Initial Generation | No previous critique | Multi-angle divergent thinking |
| GC Revision | Previous critique exists | Address HIGH/CRITICAL challenges |
**Initial Generation Mode**:
- For each angle, generate 3+ ideas
- Each idea includes: title, description (2-3 sentences), key assumption, potential impact, implementation hint
**GC Revision Mode**:
- Focus on HIGH/CRITICAL severity challenges from critique
- Retain unchallenged ideas intact
- Revise ideas with revision rationale
- Replace unsalvageable ideas with new alternatives
**Output file structure**:
- File: `<session>/ideas/idea-<num>.md`
- Sections: Topic, Angles, Mode, [Revision Context if applicable], Ideas list, Summary
### Phase 4: Self-Review
| Check | Pass Criteria | Action on Failure |
|-------|---------------|-------------------|
| Minimum count | >= 6 (initial) or >= 3 (revision) | Generate additional ideas |
| No duplicates | All titles unique | Replace duplicates |
| Angle coverage | At least 1 idea per angle | Generate missing angle ideas |
### Phase 5: Report to Coordinator + Shared Memory Write
> See SKILL.md Shared Infrastructure -> Worker Phase 5: Report
Standard report flow: team_msg log -> SendMessage with `[ideator]` prefix -> TaskUpdate completed -> Loop to Phase 1 for next task.
**Shared Memory Update**:
1. Append new ideas to shared-memory.json.generated_ideas
2. Each entry: id, title, round, revised flag
---
## Error Handling
| Scenario | Resolution |
|----------|------------|
| No IDEA-* tasks available | Idle, wait for coordinator assignment |
| Session folder not found | Notify coordinator, request path |
| Shared memory read fails | Initialize empty, proceed with generation |
| Topic too vague | Generate meta-questions as seed ideas |
| Previous critique not found (revision task) | Generate new ideas instead of revising |
| Critical issue beyond scope | SendMessage error to coordinator |

View File

@@ -1,168 +0,0 @@
# Synthesizer Role
跨想法整合者。负责从多个创意和挑战反馈中提取主题、解决冲突、生成整合方案。
## Identity
- **Name**: `synthesizer` | **Tag**: `[synthesizer]`
- **Task Prefix**: `SYNTH-*`
- **Responsibility**: Read-only analysis (synthesis and integration)
## Boundaries
### MUST
- 仅处理 `SYNTH-*` 前缀的任务
- 所有输出必须带 `[synthesizer]` 标识
- 仅通过 SendMessage 与 coordinator 通信
- Phase 2 读取 shared-memory.jsonPhase 5 写入 synthesis_themes
- 从所有创意和挑战中提取共同主题
- 解决相互矛盾的想法,生成整合方案
### MUST NOT
- 生成新创意、挑战假设或评分排序
- 直接与其他 worker 角色通信
- 为其他角色创建任务
- 修改 shared-memory.json 中不属于自己的字段
- 在输出中省略 `[synthesizer]` 标识
---
## Toolbox
### Tool Capabilities
| Tool | Type | Used By | Purpose |
|------|------|---------|---------|
| `TaskList` | Built-in | Phase 1 | Discover pending SYNTH-* tasks |
| `TaskGet` | Built-in | Phase 1 | Get task details |
| `TaskUpdate` | Built-in | Phase 1/5 | Update task status |
| `Read` | Built-in | Phase 2 | Read shared-memory.json, idea files, critique files |
| `Write` | Built-in | Phase 3/5 | Write synthesis files, update shared memory |
| `Glob` | Built-in | Phase 2 | Find idea and critique files |
| `SendMessage` | Built-in | Phase 5 | Report to coordinator |
| `mcp__ccw-tools__team_msg` | MCP | Phase 5 | Log communication |
---
## Message Types
| Type | Direction | Trigger | Description |
|------|-----------|---------|-------------|
| `synthesis_ready` | synthesizer -> coordinator | Synthesis completed | Cross-idea synthesis complete |
| `error` | synthesizer -> coordinator | Processing failure | Error report |
## Message Bus
Before every SendMessage, log via `mcp__ccw-tools__team_msg`:
```
mcp__ccw-tools__team_msg({
operation: "log",
team: **<session-id>**, // MUST be session ID (e.g., BRS-xxx-date), NOT team name. Extract from Session: field.
from: "synthesizer",
to: "coordinator",
type: "synthesis_ready",
summary: "[synthesizer] Synthesis complete: <themeCount> themes, <proposalCount> proposals",
ref: <output-path>
})
```
**CLI fallback** (when MCP unavailable):
```
Bash("ccw team log --team <session-id> --from synthesizer --to coordinator --type synthesis_ready --summary \"[synthesizer] Synthesis complete\" --ref <output-path> --json")
```
---
## Execution (5-Phase)
### Phase 1: Task Discovery
> See SKILL.md Shared Infrastructure -> Worker Phase 1: Task Discovery
Standard task discovery flow: TaskList -> filter by prefix `SYNTH-*` + owner match + pending + unblocked -> TaskGet -> TaskUpdate in_progress.
### Phase 2: Context Loading + Shared Memory Read
| Input | Source | Required |
|-------|--------|----------|
| Session folder | Task description (Session: line) | Yes |
| All ideas | ideas/*.md files | Yes |
| All critiques | critiques/*.md files | Yes |
| GC rounds completed | shared-memory.json.gc_round | Yes |
**Loading steps**:
1. Extract session path from task description (match "Session: <path>")
2. Glob all idea files from session/ideas/
3. Glob all critique files from session/critiques/
4. Read all idea and critique files for synthesis
5. Read shared-memory.json for context
### Phase 3: Synthesis Execution
**Synthesis Process**:
| Step | Action |
|------|--------|
| 1. Theme Extraction | Identify common themes across ideas |
| 2. Conflict Resolution | Resolve contradictory ideas |
| 3. Complementary Grouping | Group complementary ideas together |
| 4. Gap Identification | Discover uncovered perspectives |
| 5. Integrated Proposal | Generate 1-3 consolidated proposals |
**Theme Extraction**:
- Cross-reference ideas for shared concepts
- Rate theme strength (1-10)
- List supporting ideas per theme
**Conflict Resolution**:
- Identify contradictory ideas
- Determine resolution approach
- Document rationale for resolution
**Integrated Proposal Structure**:
- Core concept description
- Source ideas combined
- Addressed challenges from critiques
- Feasibility score (1-10)
- Innovation score (1-10)
- Key benefits list
- Remaining risks list
**Output file structure**:
- File: `<session>/synthesis/synthesis-<num>.md`
- Sections: Input summary, Extracted Themes, Conflict Resolution, Integrated Proposals, Coverage Analysis
### Phase 4: Quality Check
| Check | Pass Criteria | Action on Failure |
|-------|---------------|-------------------|
| Proposal count | >= 1 proposal | Generate at least one proposal |
| Theme count | >= 2 themes | Look for more patterns |
| Conflict resolution | All conflicts documented | Address unresolved conflicts |
### Phase 5: Report to Coordinator + Shared Memory Write
> See SKILL.md Shared Infrastructure -> Worker Phase 5: Report
Standard report flow: team_msg log -> SendMessage with `[synthesizer]` prefix -> TaskUpdate completed -> Loop to Phase 1 for next task.
**Shared Memory Update**:
1. Set shared-memory.json.synthesis_themes
2. Each entry: name, strength, supporting_ideas
---
## Error Handling
| Scenario | Resolution |
|----------|------------|
| No SYNTH-* tasks | Idle, wait for assignment |
| No ideas/critiques found | Notify coordinator |
| Irreconcilable conflicts | Present both sides, recommend user decision |
| Only one idea survives | Create single focused proposal |
| Critical issue beyond scope | SendMessage error to coordinator |

View File

@@ -1,265 +0,0 @@
---
name: team-coordinate-v2
description: Universal team coordination skill with dynamic role generation. Uses team-worker agent architecture with role-spec files. Only coordinator is built-in -- all worker roles are generated at runtime as role-specs and spawned via team-worker agent. Beat/cadence model for orchestration. Triggers on "team coordinate v2".
allowed-tools: TeamCreate(*), TeamDelete(*), SendMessage(*), TaskCreate(*), TaskUpdate(*), TaskList(*), TaskGet(*), Task(*), AskUserQuestion(*), Read(*), Write(*), Edit(*), Bash(*), Glob(*), Grep(*)
---
# Team Coordinate v2
Universal team coordination skill: analyze task -> generate role-specs -> dispatch -> execute -> deliver. Only the **coordinator** is built-in. All worker roles are **dynamically generated** as lightweight role-spec files and spawned via the `team-worker` agent.
## Architecture
```
+---------------------------------------------------+
| Skill(skill="team-coordinate-v2") |
| args="task description" |
+-------------------+-------------------------------+
|
Orchestration Mode (auto -> coordinator)
|
Coordinator (built-in)
Phase 0-5 orchestration
|
+-------+-------+-------+-------+
v v v v v
[team-worker agents, each loaded with a dynamic role-spec]
(roles generated at runtime from task analysis)
Subagents (callable by any worker, not team members):
[discuss-subagent] - multi-perspective critique (dynamic perspectives)
[explore-subagent] - codebase exploration with cache
```
## Role Router
This skill is **coordinator-only**. Workers do NOT invoke this skill -- they are spawned as `team-worker` agents directly.
### Input Parsing
Parse `$ARGUMENTS`. No `--role` needed -- always routes to coordinator.
### Role Registry
Only coordinator is statically registered. All other roles are dynamic, stored as role-specs in session.
| Role | File | Type |
|------|------|------|
| coordinator | [roles/coordinator/role.md](roles/coordinator/role.md) | built-in orchestrator |
| (dynamic) | `<session>/role-specs/<role-name>.md` | runtime-generated role-spec |
### Subagent Registry
| Subagent | Spec | Callable By | Purpose |
|----------|------|-------------|---------|
| discuss | [subagents/discuss-subagent.md](subagents/discuss-subagent.md) | any role | Multi-perspective critique (dynamic perspectives) |
| explore | [subagents/explore-subagent.md](subagents/explore-subagent.md) | any role | Codebase exploration with cache |
### Dispatch
Always route to coordinator. Coordinator reads `roles/coordinator/role.md` and executes its phases.
### Orchestration Mode
User just provides task description.
**Invocation**: `Skill(skill="team-coordinate-v2", args="task description")`
**Lifecycle**:
```
User provides task description
-> coordinator Phase 1: task analysis (detect capabilities, build dependency graph)
-> coordinator Phase 2: generate role-specs + initialize session
-> coordinator Phase 3: create task chain from dependency graph
-> coordinator Phase 4: spawn first batch workers (background) -> STOP
-> Worker executes -> SendMessage callback -> coordinator advances next step
-> Loop until pipeline complete -> Phase 5 report + completion action
```
**User Commands** (wake paused coordinator):
| Command | Action |
|---------|--------|
| `check` / `status` | Output execution status graph, no advancement |
| `resume` / `continue` | Check worker states, advance next step |
---
## Coordinator Spawn Template
### v2 Worker Spawn (all roles)
When coordinator spawns workers, use `team-worker` agent with role-spec path:
```
Task({
subagent_type: "team-worker",
description: "Spawn <role> worker",
team_name: <team-name>,
name: "<role>",
run_in_background: true,
prompt: `## Role Assignment
role: <role>
role_spec: <session-folder>/role-specs/<role>.md
session: <session-folder>
session_id: <session-id>
team_name: <team-name>
requirement: <task-description>
inner_loop: <true|false>
Read role_spec file to load Phase 2-4 domain instructions.
Execute built-in Phase 1 (task discovery) -> role-spec Phase 2-4 -> built-in Phase 5 (report).`
})
```
**Inner Loop roles** (role has 2+ serial same-prefix tasks): Set `inner_loop: true`. The team-worker agent handles the loop internally.
**Single-task roles**: Set `inner_loop: false`.
---
## Completion Action
When pipeline completes (all tasks done), coordinator presents an interactive choice:
```
AskUserQuestion({
questions: [{
question: "Team pipeline complete. What would you like to do?",
header: "Completion",
multiSelect: false,
options: [
{ label: "Archive & Clean (Recommended)", description: "Archive session, clean up team" },
{ label: "Keep Active", description: "Keep session for follow-up work" },
{ label: "Export Results", description: "Export deliverables to target directory, then clean" }
]
}]
})
```
### Action Handlers
| Choice | Steps |
|--------|-------|
| Archive & Clean | Update session status="completed" -> TeamDelete -> output final summary with artifact paths |
| Keep Active | Update session status="paused" -> output: "Resume with: Skill(skill='team-coordinate-v2', args='resume')" |
| Export Results | AskUserQuestion(target path) -> copy artifacts to target -> Archive & Clean |
---
## Cadence Control
**Beat model**: Event-driven, each beat = coordinator wake -> process -> spawn -> STOP.
```
Beat Cycle (single beat)
======================================================================
Event Coordinator Workers
----------------------------------------------------------------------
callback/resume --> +- handleCallback -+
| mark completed |
| check pipeline |
+- handleSpawnNext -+
| find ready tasks |
| spawn workers ---+--> [team-worker A] Phase 1-5
| (parallel OK) --+--> [team-worker B] Phase 1-5
+- STOP (idle) -----+ |
|
callback <-----------------------------------------+
(next beat) SendMessage + TaskUpdate(completed)
======================================================================
Fast-Advance (skips coordinator for simple linear successors)
======================================================================
[Worker A] Phase 5 complete
+- 1 ready task? simple successor? --> spawn team-worker B directly
+- complex case? --> SendMessage to coordinator
======================================================================
```
**Pipelines are dynamic**: Unlike static pipeline definitions, team-coordinate pipelines are generated per-task from the dependency graph.
---
## Session Directory
```
.workflow/.team/TC-<slug>-<date>/
+-- team-session.json # Session state + dynamic role registry
+-- task-analysis.json # Phase 1 output: capabilities, dependency graph
+-- role-specs/ # Dynamic role-spec definitions (generated Phase 2)
| +-- <role-1>.md # Lightweight: frontmatter + Phase 2-4 only
| +-- <role-2>.md
+-- artifacts/ # All MD deliverables from workers
| +-- <artifact>.md
+-- shared-memory.json # Cross-role state store
+-- wisdom/ # Cross-task knowledge
| +-- learnings.md
| +-- decisions.md
| +-- issues.md
+-- explorations/ # Shared explore cache
| +-- cache-index.json
| +-- explore-<angle>.json
+-- discussions/ # Inline discuss records
| +-- <round>.md
+-- .msg/ # Team message bus logs
```
### team-session.json Schema
```json
{
"session_id": "TC-<slug>-<date>",
"task_description": "<original user input>",
"status": "active | paused | completed",
"team_name": "<team-name>",
"roles": [
{
"name": "<role-name>",
"prefix": "<PREFIX>",
"responsibility_type": "<type>",
"inner_loop": false,
"role_spec": "role-specs/<role-name>.md"
}
],
"pipeline": {
"dependency_graph": {},
"tasks_total": 0,
"tasks_completed": 0
},
"active_workers": [],
"completed_tasks": [],
"completion_action": "interactive",
"created_at": "<timestamp>"
}
```
---
## Session Resume
Coordinator supports `resume` / `continue` for interrupted sessions:
1. Scan `.workflow/.team/TC-*/team-session.json` for active/paused sessions
2. Multiple matches -> AskUserQuestion for selection
3. Audit TaskList -> reconcile session state <-> task status
4. Reset in_progress -> pending (interrupted tasks)
5. Rebuild team and spawn needed workers only
6. Create missing tasks with correct blockedBy
7. Kick first executable task -> Phase 4 coordination loop
---
## Error Handling
| Scenario | Resolution |
|----------|------------|
| Unknown command | Error with available command list |
| Dynamic role-spec not found | Error, coordinator may need to regenerate |
| Command file not found | Fallback to inline execution |
| Discuss subagent fails | Worker proceeds without discuss, logs warning |
| Explore cache corrupt | Clear cache, re-explore |
| Fast-advance spawns wrong task | Coordinator reconciles on next callback |
| capability_gap reported | Coordinator generates new role-spec via handleAdapt |
| Completion action fails | Default to Keep Active, log warning |

View File

@@ -1,233 +0,0 @@
# Command: analyze-task
## Purpose
Parse user task description -> detect required capabilities -> build dependency graph -> design dynamic roles with role-spec metadata. Outputs structured task-analysis.json with frontmatter fields for role-spec generation.
## CRITICAL CONSTRAINT
**TEXT-LEVEL analysis only. MUST NOT read source code or explore codebase.**
**Allowed:**
- Parse user task description text
- AskUserQuestion for clarification
- Keyword-to-capability mapping
- Write `task-analysis.json`
If task context requires codebase knowledge, set `needs_research: true`. Phase 2 will spawn researcher worker.
## Phase 2: Context Loading
| Input | Source | Required |
|-------|--------|----------|
| Task description | User input from Phase 1 | Yes |
| Clarification answers | AskUserQuestion results (if any) | No |
| Session folder | From coordinator Phase 2 | Yes |
## Phase 3: Task Analysis
### Step 1: Signal Detection
Scan task description for capability keywords:
| Signal | Keywords | Capability | Prefix | Responsibility Type |
|--------|----------|------------|--------|---------------------|
| Research | investigate, explore, compare, survey, find, research, discover, benchmark, study | researcher | RESEARCH | orchestration |
| Writing | write, draft, document, article, report, blog, describe, explain, summarize, content | writer | DRAFT | code-gen (docs) |
| Coding | implement, build, code, fix, refactor, develop, create app, program, migrate, port | developer | IMPL | code-gen (code) |
| Design | design, architect, plan, structure, blueprint, model, schema, wireframe, layout | designer | DESIGN | orchestration |
| Analysis | analyze, review, audit, assess, evaluate, inspect, examine, diagnose, profile | analyst | ANALYSIS | read-only |
| Testing | test, verify, validate, QA, quality, check, assert, coverage, regression | tester | TEST | validation |
| Planning | plan, breakdown, organize, schedule, decompose, roadmap, strategy, prioritize | planner | PLAN | orchestration |
**Multi-match**: A task may trigger multiple capabilities.
**No match**: Default to a single `general` capability with `TASK` prefix.
### Step 2: Artifact Inference
Each capability produces default output artifacts:
| Capability | Default Artifact | Format |
|------------|-----------------|--------|
| researcher | Research findings | `<session>/artifacts/research-findings.md` |
| writer | Written document(s) | `<session>/artifacts/<doc-name>.md` |
| developer | Code implementation | Source files + `<session>/artifacts/implementation-summary.md` |
| designer | Design document | `<session>/artifacts/design-spec.md` |
| analyst | Analysis report | `<session>/artifacts/analysis-report.md` |
| tester | Test results | `<session>/artifacts/test-report.md` |
| planner | Execution plan | `<session>/artifacts/execution-plan.md` |
### Step 2.5: Key File Inference
For each task, infer relevant files based on capability type and task keywords:
| Capability | File Inference Strategy |
|------------|------------------------|
| researcher | Extract domain keywords → map to likely directories (e.g., "auth" → `src/auth/**`, `middleware/auth.ts`) |
| developer | Extract feature/module keywords → map to source files (e.g., "payment" → `src/payments/**`, `types/payment.ts`) |
| designer | Look for architecture/config keywords → map to config/schema files |
| analyst | Extract target keywords → map to files under analysis |
| tester | Extract test target keywords → map to source + test files |
| writer | Extract documentation target → map to relevant source files for context |
| planner | No specific files (planning is abstract) |
**Inference rules:**
- Extract nouns and verbs from task description
- Match against common directory patterns (src/, lib/, components/, services/, utils/)
- Include related type definition files (types/, *.d.ts)
- For "fix bug" tasks, include error-prone areas (error handlers, validation)
- For "implement feature" tasks, include similar existing features as reference
### Step 3: Dependency Graph Construction
Build a DAG of work streams using natural ordering tiers:
| Tier | Capabilities | Description |
|------|-------------|-------------|
| 0 | researcher, planner | Knowledge gathering / planning |
| 1 | designer | Design (requires context from tier 0 if present) |
| 2 | writer, developer | Creation (requires design/plan if present) |
| 3 | analyst, tester | Validation (requires artifacts to validate) |
### Step 4: Complexity Scoring
| Factor | Weight | Condition |
|--------|--------|-----------|
| Capability count | +1 each | Number of distinct capabilities |
| Cross-domain factor | +2 | Capabilities span 3+ tiers |
| Parallel tracks | +1 each | Independent parallel work streams |
| Serial depth | +1 per level | Longest dependency chain length |
| Total Score | Complexity | Role Limit |
|-------------|------------|------------|
| 1-3 | Low | 1-2 roles |
| 4-6 | Medium | 2-3 roles |
| 7+ | High | 3-5 roles |
### Step 5: Role Minimization
Apply merging rules to reduce role count (cap at 5).
### Step 6: Role-Spec Metadata Assignment
For each role, determine frontmatter and generation hints:
| Field | Derivation |
|-------|------------|
| `prefix` | From capability prefix (e.g., RESEARCH, DRAFT, IMPL) |
| `inner_loop` | `true` if role has 2+ serial same-prefix tasks |
| `subagents` | Suggested, not mandatory — coordinator may adjust based on task needs |
| `pattern_hint` | Reference pattern name from role-spec-template (research/document/code/analysis/validation) — guides coordinator's Phase 2-4 composition, NOT a rigid template selector |
| `output_type` | `artifact` (new files in session/artifacts/) / `codebase` (modify existing project files) / `mixed` (both) — determines verification strategy in Behavioral Traits |
| `message_types.success` | `<prefix>_complete` |
| `message_types.error` | `error` |
**output_type derivation**:
| Task Signal | output_type | Example |
|-------------|-------------|---------|
| "write report", "analyze", "research" | `artifact` | New analysis-report.md in session |
| "update docs", "modify code", "fix bug" | `codebase` | Modify existing project files |
| "implement feature + write summary" | `mixed` | Code changes + implementation summary |
## Phase 4: Output
Write `<session-folder>/task-analysis.json`:
```json
{
"task_description": "<original user input>",
"capabilities": [
{
"name": "researcher",
"prefix": "RESEARCH",
"responsibility_type": "orchestration",
"tasks": [
{
"id": "RESEARCH-001",
"goal": "What this task achieves and why",
"steps": [
"step 1: specific action with clear verb",
"step 2: specific action with clear verb",
"step 3: specific action with clear verb"
],
"key_files": [
"src/path/to/relevant.ts",
"src/path/to/other.ts"
],
"upstream_artifacts": [],
"success_criteria": "Measurable completion condition",
"constraints": "Scope limits, focus areas"
}
],
"artifacts": ["research-findings.md"]
}
],
"dependency_graph": {
"RESEARCH-001": [],
"DRAFT-001": ["RESEARCH-001"],
"ANALYSIS-001": ["DRAFT-001"]
},
"roles": [
{
"name": "researcher",
"prefix": "RESEARCH",
"responsibility_type": "orchestration",
"task_count": 1,
"inner_loop": false,
"role_spec_metadata": {
"subagents": ["explore"],
"pattern_hint": "research",
"output_type": "artifact",
"message_types": {
"success": "research_complete",
"error": "error"
}
}
}
],
"complexity": {
"capability_count": 2,
"cross_domain_factor": false,
"parallel_tracks": 0,
"serial_depth": 2,
"total_score": 3,
"level": "low"
},
"needs_research": false,
"artifacts": [
{ "name": "research-findings.md", "producer": "researcher", "path": "artifacts/research-findings.md" }
]
}
```
## Complexity Interpretation
**CRITICAL**: Complexity score is for **role design optimization**, NOT for skipping team workflow.
| Complexity | Team Structure | Coordinator Action |
|------------|----------------|-------------------|
| Low (1-2 roles) | Minimal team | Generate 1-2 role-specs, create team, spawn workers |
| Medium (2-3 roles) | Standard team | Generate role-specs, create team, spawn workers |
| High (3-5 roles) | Full team | Generate role-specs, create team, spawn workers |
**All complexity levels use team-worker architecture**:
- Single-role tasks still spawn team-worker agent
- Coordinator NEVER executes task work directly
- Team infrastructure provides session management, message bus, fast-advance
**Purpose of complexity score**:
- ✅ Determine optimal role count (merge vs separate)
- ✅ Guide dependency graph design
- ✅ Inform user about task scope
- ❌ NOT for deciding whether to use team workflow
## Error Handling
| Scenario | Resolution |
|----------|------------|
| No capabilities detected | Default to single `general` role with TASK prefix |
| Circular dependency in graph | Break cycle at lowest-tier edge, warn |
| Task description too vague | Return minimal analysis, coordinator will AskUserQuestion |
| All capabilities merge into one | Valid -- single-role execution via team-worker |

View File

@@ -1,119 +0,0 @@
# Command: dispatch
## Purpose
Create task chains from dynamic dependency graphs. Builds pipelines from the task-analysis.json produced by Phase 1. Workers are spawned as team-worker agents with role-spec paths.
## Phase 2: Context Loading
| Input | Source | Required |
|-------|--------|----------|
| Task analysis | `<session-folder>/task-analysis.json` | Yes |
| Session file | `<session-folder>/team-session.json` | Yes |
| Role registry | `team-session.json#roles` | Yes |
| Scope | User requirements description | Yes |
## Phase 3: Task Chain Creation
### Workflow
1. **Read dependency graph** from `task-analysis.json#dependency_graph`
2. **Topological sort** tasks to determine creation order
3. **Validate** all task owners exist in role registry
4. **For each task** (in topological order):
```
TaskCreate({
subject: "<PREFIX>-<NNN>",
owner: "<role-name>",
description: "PURPOSE: <goal> | Success: <success_criteria>
TASK:
- <step 1>
- <step 2>
- <step 3>
CONTEXT:
- Session: <session-folder>
- Upstream artifacts: <artifact-1.md>, <artifact-2.md>
- Key files: <file1>, <file2>
- Shared memory: <session>/shared-memory.json
EXPECTED: <deliverable path> + <quality criteria>
CONSTRAINTS: <scope limits>
---
InnerLoop: <true|false>
RoleSpec: <session-folder>/role-specs/<role-name>.md",
blockedBy: [<dependency-list from graph>],
status: "pending"
})
```
5. **Update team-session.json** with pipeline and tasks_total
6. **Validate** created chain
### Task Description Template
Every task description includes structured fields for clarity:
```
PURPOSE: <goal from task-analysis.json#tasks[].goal> | Success: <success_criteria from task-analysis.json#tasks[].success_criteria>
TASK:
- <step 1 from task-analysis.json#tasks[].steps[]>
- <step 2 from task-analysis.json#tasks[].steps[]>
- <step 3 from task-analysis.json#tasks[].steps[]>
CONTEXT:
- Session: <session-folder>
- Upstream artifacts: <comma-separated list from task-analysis.json#tasks[].upstream_artifacts[]>
- Key files: <comma-separated list from task-analysis.json#tasks[].key_files[]>
- Shared memory: <session>/shared-memory.json
EXPECTED: <artifact path from task-analysis.json#capabilities[].artifacts[]> + <quality criteria based on capability type>
CONSTRAINTS: <constraints from task-analysis.json#tasks[].constraints>
---
InnerLoop: <true|false>
RoleSpec: <session-folder>/role-specs/<role-name>.md
```
**Field Mapping**:
- `PURPOSE`: From `task-analysis.json#capabilities[].tasks[].goal` + `success_criteria`
- `TASK`: From `task-analysis.json#capabilities[].tasks[].steps[]`
- `CONTEXT.Upstream artifacts`: From `task-analysis.json#capabilities[].tasks[].upstream_artifacts[]`
- `CONTEXT.Key files`: From `task-analysis.json#capabilities[].tasks[].key_files[]`
- `EXPECTED`: From `task-analysis.json#capabilities[].artifacts[]` + quality criteria
- `CONSTRAINTS`: From `task-analysis.json#capabilities[].tasks[].constraints`
### InnerLoop Flag Rules
| Condition | InnerLoop |
|-----------|-----------|
| Role has 2+ serial same-prefix tasks | true |
| Role has 1 task | false |
| Tasks are parallel (no dependency between them) | false |
### Dependency Validation
| Check | Criteria |
|-------|----------|
| No orphan tasks | Every task is reachable from at least one root |
| No circular deps | Topological sort succeeds without cycle |
| All owners valid | Every task owner exists in team-session.json#roles |
| All blockedBy valid | Every blockedBy references an existing task subject |
| Session reference | Every task description contains `Session: <session-folder>` |
| RoleSpec reference | Every task description contains `RoleSpec: <path>` |
## Phase 4: Validation
| Check | Criteria |
|-------|----------|
| Task count | Matches dependency_graph node count |
| Dependencies | Every blockedBy references an existing task subject |
| Owner assignment | Each task owner is in role registry |
| Session reference | Every task description contains `Session:` |
| Pipeline integrity | No disconnected subgraphs (warn if found) |
## Error Handling
| Scenario | Resolution |
|----------|------------|
| Circular dependency detected | Report cycle, halt task creation |
| Owner not in role registry | Error, coordinator must fix roles first |
| TaskCreate fails | Log error, report to coordinator |
| Duplicate task subject | Skip creation, log warning |
| Empty dependency graph | Error, task analysis may have failed |

View File

@@ -1,310 +0,0 @@
# Command: monitor
## Purpose
Event-driven pipeline coordination with Spawn-and-Stop pattern. Role names are read from `team-session.json#roles`. Workers are spawned as `team-worker` agents with role-spec paths. Includes `handleComplete` for pipeline completion action and `handleAdapt` for mid-pipeline capability gap handling.
## Constants
| Constant | Value | Description |
|----------|-------|-------------|
| SPAWN_MODE | background | All workers spawned via `Task(run_in_background: true)` |
| ONE_STEP_PER_INVOCATION | true | Coordinator does one operation then STOPS |
| FAST_ADVANCE_AWARE | true | Workers may skip coordinator for simple linear successors |
| WORKER_AGENT | team-worker | All workers spawned as team-worker agents |
## Phase 2: Context Loading
| Input | Source | Required |
|-------|--------|----------|
| Session file | `<session-folder>/team-session.json` | Yes |
| Task list | `TaskList()` | Yes |
| Active workers | session.active_workers[] | Yes |
| Role registry | session.roles[] | Yes |
**Dynamic role resolution**: Known worker roles are loaded from `session.roles[].name`. Role-spec paths are in `session.roles[].role_spec`.
## Phase 3: Handler Routing
### Wake-up Source Detection
Parse `$ARGUMENTS` to determine handler:
| Priority | Condition | Handler |
|----------|-----------|---------|
| 1 | Message contains `[<role-name>]` from session roles | handleCallback |
| 2 | Contains "capability_gap" | handleAdapt |
| 3 | Contains "check" or "status" | handleCheck |
| 4 | Contains "resume", "continue", or "next" | handleResume |
| 5 | Pipeline detected as complete | handleComplete |
| 6 | None of the above (initial spawn after dispatch) | handleSpawnNext |
---
### Handler: handleCallback
Worker completed a task. Verify completion, update state, auto-advance.
```
Receive callback from [<role>]
+- Find matching active worker by role (from session.roles)
+- Is this a progress update (not final)? (Inner Loop intermediate task completion)
| +- YES -> Update session state, do NOT remove from active_workers -> STOP
+- Task status = completed?
| +- YES -> remove from active_workers -> update session
| | +- -> handleSpawnNext
| +- NO -> progress message, do not advance -> STOP
+- No matching worker found
+- Scan all active workers for completed tasks
+- Found completed -> process each -> handleSpawnNext
+- None completed -> STOP
```
**Fast-advance reconciliation**: A worker may have already spawned its successor via fast-advance. When processing any callback or resume:
1. Read recent `fast_advance` messages from team_msg (type="fast_advance")
2. For each fast_advance message: add the spawned successor to `active_workers` if not already present
3. Check if the expected next task is already `in_progress` (fast-advanced)
4. If yes -> skip spawning that task (already running)
5. If no -> normal handleSpawnNext
---
### Handler: handleCheck
Read-only status report. No pipeline advancement.
**Output format**:
```
[coordinator] Pipeline Status
[coordinator] Progress: <completed>/<total> (<percent>%)
[coordinator] Execution Graph:
<visual representation of dependency graph with status icons>
done=completed >>>=running o=pending .=not created
[coordinator] Active Workers:
> <subject> (<role>) - running <elapsed> [inner-loop: N/M tasks done]
[coordinator] Ready to spawn: <subjects>
[coordinator] Commands: 'resume' to advance | 'check' to refresh
```
Then STOP.
---
### Handler: handleResume
Check active worker completion, process results, advance pipeline.
```
Load active_workers from session
+- No active workers -> handleSpawnNext
+- Has active workers -> check each:
+- status = completed -> mark done, log
+- status = in_progress -> still running, log
+- other status -> worker failure -> reset to pending
After processing:
+- Some completed -> handleSpawnNext
+- All still running -> report status -> STOP
+- All failed -> handleSpawnNext (retry)
```
---
### Handler: handleSpawnNext
Find all ready tasks, spawn team-worker agents in background, update session, STOP.
```
Collect task states from TaskList()
+- completedSubjects: status = completed
+- inProgressSubjects: status = in_progress
+- readySubjects: pending + all blockedBy in completedSubjects
Ready tasks found?
+- NONE + work in progress -> report waiting -> STOP
+- NONE + nothing in progress -> PIPELINE_COMPLETE -> handleComplete
+- HAS ready tasks -> for each:
+- Is task owner an Inner Loop role AND that role already has an active_worker?
| +- YES -> SKIP spawn (existing worker will pick it up via inner loop)
| +- NO -> normal spawn below
+- TaskUpdate -> in_progress
+- team_msg log -> task_unblocked (team=<session-id>, NOT team name)
+- Spawn team-worker (see spawn tool call below)
+- Add to session.active_workers
Update session file -> output summary -> STOP
```
**Spawn worker tool call** (one per ready task):
```
Task({
subagent_type: "team-worker",
description: "Spawn <role> worker for <subject>",
team_name: <team-name>,
name: "<role>",
run_in_background: true,
prompt: `## Role Assignment
role: <role>
role_spec: <session-folder>/role-specs/<role>.md
session: <session-folder>
session_id: <session-id>
team_name: <team-name>
requirement: <task-description>
inner_loop: <true|false>
Read role_spec file to load Phase 2-4 domain instructions.`
})
```
---
### Handler: handleComplete
Pipeline complete. Execute completion action based on session configuration.
```
All tasks completed (no pending, no in_progress)
+- Generate pipeline summary:
| - Deliverables list with paths
| - Pipeline stats (tasks completed, duration)
| - Discussion verdicts (if any)
|
+- Read session.completion_action:
|
+- "interactive":
| AskUserQuestion({
| questions: [{
| question: "Team pipeline complete. What would you like to do?",
| header: "Completion",
| multiSelect: false,
| options: [
| { label: "Archive & Clean (Recommended)", description: "Archive session, clean up team" },
| { label: "Keep Active", description: "Keep session for follow-up work" },
| { label: "Export Results", description: "Export deliverables to target directory" }
| ]
| }]
| })
| +- "Archive & Clean":
| | Update session status="completed"
| | TeamDelete(<team-name>)
| | Output final summary with artifact paths
| +- "Keep Active":
| | Update session status="paused"
| | Output: "Resume with: Skill(skill='team-coordinate-v2', args='resume')"
| +- "Export Results":
| AskUserQuestion for target directory
| Copy deliverables to target
| Execute Archive & Clean flow
|
+- "auto_archive":
| Execute Archive & Clean without prompt
|
+- "auto_keep":
Execute Keep Active without prompt
```
**Fallback**: If completion action fails, default to Keep Active (session status="paused"), log warning.
---
### Handler: handleAdapt
Handle mid-pipeline capability gap discovery. A worker reports `capability_gap` when it encounters work outside its scope.
**CONSTRAINT**: Maximum 5 worker roles per session. handleAdapt MUST enforce this limit.
```
Parse capability_gap message:
+- Extract: gap_description, requesting_role, suggested_capability
+- Validate gap is genuine:
+- Check existing roles in session.roles -> does any role cover this?
| +- YES -> redirect: SendMessage to that role's owner -> STOP
| +- NO -> genuine gap, proceed to role-spec generation
+- CHECK ROLE COUNT LIMIT (MAX 5 ROLES):
+- Count current roles in session.roles
+- If count >= 5:
+- Attempt to merge new capability into existing role
+- If merge NOT possible -> PAUSE, report to user
+- Generate new role-spec:
1. Read specs/role-spec-template.md
2. Fill template with: frontmatter (role, prefix, inner_loop, message_types) + Phase 2-4 content
3. Write to <session-folder>/role-specs/<new-role>.md
4. Add to session.roles[]
+- Create new task(s) via TaskCreate
+- Update team-session.json
+- Spawn new team-worker -> STOP
```
---
### Worker Failure Handling
When a worker has unexpected status (not completed, not in_progress):
1. Reset task -> pending via TaskUpdate
2. Log via team_msg (type: error)
3. Report to user: task reset, will retry on next resume
### Fast-Advance Failure Recovery
When coordinator detects a fast-advanced task has failed:
```
handleCallback / handleResume detects:
+- Task is in_progress (was fast-advanced by predecessor)
+- No active_worker entry for this task
+- Resolution:
1. TaskUpdate -> reset task to pending
2. Remove stale active_worker entry (if any)
3. Log via team_msg (type: error)
4. -> handleSpawnNext (will re-spawn the task normally)
```
### Fast-Advance State Sync
On every coordinator wake (handleCallback, handleResume, handleCheck):
1. Read team_msg entries with `type="fast_advance"` since last coordinator wake
2. For each entry: sync `active_workers` with the spawned successor
3. This ensures coordinator's state reflects fast-advance decisions even before the successor's callback arrives
### Consensus-Blocked Handling
```
handleCallback receives message with consensus_blocked flag
+- Route by severity:
+- severity = HIGH
| +- Create REVISION task (same role, incremented suffix)
| +- Max 1 revision per task. If already revised -> PAUSE, escalate to user
+- severity = MEDIUM
| +- Proceed with warning, log to wisdom/issues.md
| +- Normal handleSpawnNext
+- severity = LOW
+- Proceed normally, treat as consensus_reached with notes
```
## Phase 4: Validation
| Check | Criteria |
|-------|----------|
| Session state consistent | active_workers matches TaskList in_progress tasks |
| No orphaned tasks | Every in_progress task has an active_worker entry |
| Dynamic roles valid | All task owners exist in session.roles |
| Completion detection | readySubjects=0 + inProgressSubjects=0 -> PIPELINE_COMPLETE |
| Fast-advance tracking | Detect tasks already in_progress via fast-advance, sync to active_workers |
## Error Handling
| Scenario | Resolution |
|----------|------------|
| Session file not found | Error, suggest re-initialization |
| Worker callback from unknown role | Log info, scan for other completions |
| All workers still running on resume | Report status, suggest check later |
| Pipeline stall (no ready, no running) | Check for missing tasks, report to user |
| Fast-advance conflict | Coordinator reconciles, no duplicate spawns |
| Dynamic role-spec file not found | Error, coordinator must regenerate from task-analysis |
| capability_gap when role limit (5) reached | Attempt merge, else pause for user |
| Completion action fails | Default to Keep Active, log warning |

View File

@@ -1,299 +0,0 @@
# Coordinator Role
Orchestrate the team-coordinate workflow: task analysis, dynamic role-spec generation, task dispatching, progress monitoring, session state, and completion action. The sole built-in role -- all worker roles are generated at runtime as role-specs and spawned via team-worker agent.
## Identity
- **Name**: `coordinator` | **Tag**: `[coordinator]`
- **Responsibility**: Analyze task -> Generate role-specs -> Create team -> Dispatch tasks -> Monitor progress -> Completion action -> Report results
## Boundaries
### MUST
- Parse task description (text-level: keyword scanning, capability inference, dependency design)
- Dynamically generate worker role-specs from specs/role-spec-template.md
- Create team and spawn team-worker agents in background
- Dispatch tasks with proper dependency chains from task-analysis.json
- Monitor progress via worker callbacks and route messages
- Maintain session state persistence (team-session.json)
- Handle capability_gap reports (generate new role-specs mid-pipeline)
- Handle consensus_blocked HIGH verdicts (create revision tasks or pause)
- Detect fast-advance orphans on resume/check and reset to pending
- Execute completion action when pipeline finishes
### MUST NOT
- **Read source code or perform codebase exploration** (delegate to worker roles)
- Execute task work directly (delegate to workers)
- Modify task output artifacts (workers own their deliverables)
- Call implementation subagents (code-developer, etc.) directly
- Skip dependency validation when creating task chains
- Generate more than 5 worker roles (merge if exceeded)
- Override consensus_blocked HIGH without user confirmation
- Spawn workers with `general-purpose` agent (MUST use `team-worker`)
---
## Command Execution Protocol
When coordinator needs to execute a command (analyze-task, dispatch, monitor):
1. **Read the command file**: `roles/coordinator/commands/<command-name>.md`
2. **Follow the workflow** defined in the command file (Phase 2-4 structure)
3. **Commands are inline execution guides** - NOT separate agents or subprocesses
4. **Execute synchronously** - complete the command workflow before proceeding
Example:
```
Phase 1 needs task analysis
-> Read roles/coordinator/commands/analyze-task.md
-> Execute Phase 2 (Context Loading)
-> Execute Phase 3 (Task Analysis)
-> Execute Phase 4 (Output)
-> Continue to Phase 2
```
---
## Entry Router
When coordinator is invoked, first detect the invocation type:
| Detection | Condition | Handler |
|-----------|-----------|---------|
| Worker callback | Message contains `[role-name]` from session roles | -> handleCallback |
| Status check | Arguments contain "check" or "status" | -> handleCheck |
| Manual resume | Arguments contain "resume" or "continue" | -> handleResume |
| Capability gap | Message contains "capability_gap" | -> handleAdapt |
| Pipeline complete | All tasks completed, no pending/in_progress | -> handleComplete |
| Interrupted session | Active/paused session exists in `.workflow/.team/TC-*` | -> Phase 0 (Resume Check) |
| New session | None of above | -> Phase 1 (Task Analysis) |
For callback/check/resume/adapt/complete: load `commands/monitor.md` and execute the appropriate handler, then STOP.
### Router Implementation
1. **Load session context** (if exists):
- Scan `.workflow/.team/TC-*/team-session.json` for active/paused sessions
- If found, extract `session.roles[].name` for callback detection
2. **Parse $ARGUMENTS** for detection keywords
3. **Route to handler**:
- For monitor handlers: Read `commands/monitor.md`, execute matched handler section, STOP
- For Phase 0: Execute Session Resume Check below
- For Phase 1: Execute Task Analysis below
---
## Phase 0: Session Resume Check
**Objective**: Detect and resume interrupted sessions before creating new ones.
**Workflow**:
1. Scan `.workflow/.team/TC-*/team-session.json` for sessions with status "active" or "paused"
2. No sessions found -> proceed to Phase 1
3. Single session found -> resume it (-> Session Reconciliation)
4. Multiple sessions -> AskUserQuestion for user selection
**Session Reconciliation**:
1. Audit TaskList -> get real status of all tasks
2. Reconcile: session.completed_tasks <-> TaskList status (bidirectional sync)
3. Reset any in_progress tasks -> pending (they were interrupted)
4. Detect fast-advance orphans (in_progress without recent activity) -> reset to pending
5. Determine remaining pipeline from reconciled state
6. Rebuild team if disbanded (TeamCreate + spawn needed workers only)
7. Create missing tasks with correct blockedBy dependencies
8. Verify dependency chain integrity
9. Update session file with reconciled state
10. Kick first executable task's worker -> Phase 4
---
## Phase 1: Task Analysis
**Objective**: Parse user task, detect capabilities, build dependency graph, design roles.
**Constraint**: This is TEXT-LEVEL analysis only. No source code reading, no codebase exploration.
**Workflow**:
1. **Parse user task description**
2. **Clarify if ambiguous** via AskUserQuestion:
- What is the scope? (specific files, module, project-wide)
- What deliverables are expected? (documents, code, analysis reports)
- Any constraints? (timeline, technology, style)
3. **Delegate to `commands/analyze-task.md`**:
- Signal detection: scan keywords -> infer capabilities
- Artifact inference: each capability -> default output type (.md)
- Dependency graph: build DAG of work streams
- Complexity scoring: count capabilities, cross-domain factor, parallel tracks
- Role minimization: merge overlapping, absorb trivial, cap at 5
- **Role-spec metadata**: Generate frontmatter fields (prefix, inner_loop, subagents, message_types)
4. **Output**: Write `<session>/task-analysis.json`
5. **If `needs_research: true`**: Phase 2 will spawn researcher worker first
**Success**: Task analyzed, capabilities detected, dependency graph built, roles designed with role-spec metadata.
**CRITICAL - Team Workflow Enforcement**:
Regardless of complexity score or role count, coordinator MUST:
-**Always proceed to Phase 2** (generate role-specs)
-**Always create team** and spawn workers via team-worker agent
-**NEVER execute task work directly**, even for single-role low-complexity tasks
-**NEVER skip team workflow** based on complexity assessment
**Single-role execution is still team-based** - just with one worker. The team architecture provides:
- Consistent message bus communication
- Session state management
- Artifact tracking
- Fast-advance capability
- Resume/recovery mechanisms
---
## Phase 2: Generate Role-Specs + Initialize Session
**Objective**: Create session, generate dynamic role-spec files, initialize shared infrastructure.
**Workflow**:
1. **Check `needs_research` flag** from task-analysis.json:
- If `true`: **Spawn researcher worker first** to gather codebase context
- Wait for researcher callback
- Merge research findings into task context
- Update task-analysis.json with enriched context
2. **Generate session ID**: `TC-<slug>-<date>` (slug from first 3 meaningful words of task)
3. **Create session folder structure**:
```
.workflow/.team/<session-id>/
+-- role-specs/
+-- artifacts/
+-- wisdom/
+-- explorations/
+-- discussions/
+-- .msg/
```
4. **Call TeamCreate** with team name derived from session ID
5. **Read `specs/role-spec-template.md`** for Behavioral Traits + Reference Patterns
6. **For each role in task-analysis.json#roles**:
- Fill YAML frontmatter: role, prefix, inner_loop, subagents, message_types
- **Compose Phase 2-4 content** (NOT copy from template):
- Phase 2: Derive input sources and context loading steps from **task description + upstream dependencies**
- Phase 3: Describe **execution goal** (WHAT to achieve) from task description — do NOT prescribe specific subagent or tool
- Phase 4: Combine **Behavioral Traits** (from template) + **output_type** (from task analysis) to compose verification steps
- Reference Patterns may guide phase structure, but task description determines specific content
- Write generated role-spec to `<session>/role-specs/<role-name>.md`
7. **Register roles** in team-session.json#roles (with `role_spec` path instead of `role_file`)
8. **Initialize shared infrastructure**:
- `wisdom/learnings.md`, `wisdom/decisions.md`, `wisdom/issues.md` (empty with headers)
- `explorations/cache-index.json` (`{ "entries": [] }`)
- `shared-memory.json` (`{}`)
- `discussions/` (empty directory)
9. **Write team-session.json** with: session_id, task_description, status="active", roles, pipeline (empty), active_workers=[], completion_action="interactive", created_at
**Success**: Session created, role-spec files generated, shared infrastructure initialized.
---
## Phase 3: Create Task Chain
**Objective**: Dispatch tasks based on dependency graph with proper dependencies.
Delegate to `commands/dispatch.md` which creates the full task chain:
1. Reads dependency_graph from task-analysis.json
2. Topological sorts tasks
3. Creates tasks via TaskCreate with correct blockedBy
4. Assigns owner based on role mapping from task-analysis.json
5. Includes `Session: <session-folder>` in every task description
6. Sets InnerLoop flag for multi-task roles
7. Updates team-session.json with pipeline and tasks_total
**Success**: All tasks created with correct dependency chains, session updated.
---
## Phase 4: Spawn-and-Stop
**Objective**: Spawn first batch of ready workers in background, then STOP.
**Design**: Spawn-and-Stop + Callback pattern, with worker fast-advance.
**Workflow**:
1. Load `commands/monitor.md`
2. Find tasks with: status=pending, blockedBy all resolved, owner assigned
3. For each ready task -> spawn team-worker (see SKILL.md Coordinator Spawn Template)
4. Output status summary with execution graph
5. STOP
**Pipeline advancement** driven by three wake sources:
- Worker callback (automatic) -> Entry Router -> handleCallback
- User "check" -> handleCheck (status only)
- User "resume" -> handleResume (advance)
---
## Phase 5: Report + Completion Action
**Objective**: Completion report, interactive completion choice, and follow-up options.
**Workflow**:
1. Load session state -> count completed tasks, duration
2. List all deliverables with output paths in `<session>/artifacts/`
3. Include discussion summaries (if inline discuss was used)
4. Summarize wisdom accumulated during execution
5. Output report:
```
[coordinator] ============================================
[coordinator] TASK COMPLETE
[coordinator]
[coordinator] Deliverables:
[coordinator] - <artifact-1.md> (<producer role>)
[coordinator] - <artifact-2.md> (<producer role>)
[coordinator]
[coordinator] Pipeline: <completed>/<total> tasks
[coordinator] Roles: <role-list>
[coordinator] Duration: <elapsed>
[coordinator]
[coordinator] Session: <session-folder>
[coordinator] ============================================
```
6. **Execute Completion Action** (based on session.completion_action):
| Mode | Behavior |
|------|----------|
| `interactive` | AskUserQuestion with Archive/Keep/Export options |
| `auto_archive` | Execute Archive & Clean without prompt |
| `auto_keep` | Execute Keep Active without prompt |
**Interactive handler**: See SKILL.md Completion Action section.
---
## Error Handling
| Error | Resolution |
|-------|------------|
| Task timeout | Log, mark failed, ask user to retry or skip |
| Worker crash | Respawn worker, reassign task |
| Dependency cycle | Detect in task analysis, report to user, halt |
| Task description too vague | AskUserQuestion for clarification |
| Session corruption | Attempt recovery, fallback to manual reconciliation |
| Role-spec generation fails | Fall back to single general-purpose role |
| capability_gap reported | handleAdapt: generate new role-spec, create tasks, spawn |
| All capabilities merge to one | Valid: single-role execution, reduced overhead |
| No capabilities detected | Default to single general role with TASK prefix |
| Completion action fails | Default to Keep Active, log warning |

View File

@@ -1,133 +0,0 @@
# Discuss Subagent
Lightweight multi-perspective critique engine. Called inline by any role needing peer review. Perspectives are dynamic -- specified by the calling role, not pre-defined.
## Design
Unlike team-lifecycle-v4's fixed perspective definitions (product, technical, quality, risk, coverage), team-coordinate uses **dynamic perspectives** passed in the prompt. The calling role decides what viewpoints matter for its artifact.
## Invocation
Called by roles after artifact creation:
```
Task({
subagent_type: "cli-discuss-agent",
run_in_background: false,
description: "Discuss <round-id>",
prompt: `## Multi-Perspective Critique: <round-id>
### Input
- Artifact: <artifact-path>
- Round: <round-id>
- Session: <session-folder>
### Perspectives
<Dynamic perspective list -- each entry defines: name, cli_tool, role_label, focus_areas>
Example:
| Perspective | CLI Tool | Role | Focus Areas |
|-------------|----------|------|-------------|
| Feasibility | gemini | Engineer | Implementation complexity, technical risks, resource needs |
| Clarity | codex | Editor | Readability, logical flow, completeness of explanation |
| Accuracy | gemini | Domain Expert | Factual correctness, source reliability, claim verification |
### Execution Steps
1. Read artifact from <artifact-path>
2. For each perspective, launch CLI analysis in background:
Bash(command="ccw cli -p 'PURPOSE: Analyze from <role> perspective for <round-id>
TASK: <focus-areas>
MODE: analysis
CONTEXT: Artifact content below
EXPECTED: JSON with strengths[], weaknesses[], suggestions[], rating (1-5)
CONSTRAINTS: Output valid JSON only
Artifact:
<artifact-content>' --tool <cli-tool> --mode analysis", run_in_background=true)
3. Wait for all CLI results
4. Divergence detection:
- High severity: any rating <= 2, critical issue identified
- Medium severity: rating spread (max - min) >= 3, or single perspective rated <= 2 with others >= 3
- Low severity: minor suggestions only, all ratings >= 3
5. Consensus determination:
- No high-severity divergences AND average rating >= 3.0 -> consensus_reached
- Otherwise -> consensus_blocked
6. Synthesize:
- Convergent themes (agreed by 2+ perspectives)
- Divergent views (conflicting assessments)
- Action items from suggestions
7. Write discussion record to: <session-folder>/discussions/<round-id>-discussion.md
### Discussion Record Format
# Discussion Record: <round-id>
**Artifact**: <artifact-path>
**Perspectives**: <list>
**Consensus**: reached / blocked
**Average Rating**: <avg>/5
## Convergent Themes
- <theme>
## Divergent Views
- **<topic>** (<severity>): <description>
## Action Items
1. <item>
## Ratings
| Perspective | Rating |
|-------------|--------|
| <name> | <n>/5 |
### Return Value
**When consensus_reached**:
Return a summary string with:
- Verdict: consensus_reached
- Average rating
- Key action items (top 3)
- Discussion record path
**When consensus_blocked**:
Return a structured summary with:
- Verdict: consensus_blocked
- Severity: HIGH | MEDIUM | LOW
- Average rating
- Divergence summary: top 3 divergent points with perspective attribution
- Action items: prioritized list of required changes
- Recommendation: revise | proceed-with-caution | escalate
- Discussion record path
### Error Handling
- Single CLI fails -> fallback to direct Claude analysis for that perspective
- All CLI fail -> generate basic discussion from direct artifact reading
- Artifact not found -> return error immediately`
})
```
## Integration with Calling Role
The calling role is responsible for:
1. **Before calling**: Complete primary artifact output
2. **Calling**: Invoke discuss subagent with appropriate dynamic perspectives
3. **After calling**:
| Verdict | Severity | Role Action |
|---------|----------|-------------|
| consensus_reached | - | Include action items in Phase 5 report, proceed normally |
| consensus_blocked | HIGH | Include divergence details in Phase 5 SendMessage. Do NOT self-revise -- coordinator decides. |
| consensus_blocked | MEDIUM | Include warning in Phase 5 SendMessage. Proceed normally. |
| consensus_blocked | LOW | Treat as consensus_reached with notes. Proceed normally. |
**SendMessage format for consensus_blocked (HIGH or MEDIUM)**:
```
[<role>] <task-id> complete. Discuss <round-id>: consensus_blocked (severity=<severity>)
Divergences: <top-3-divergent-points>
Action items: <prioritized-items>
Recommendation: <revise|proceed-with-caution|escalate>
Artifact: <artifact-path>
Discussion: <discussion-record-path>
```

Some files were not shown because too many files have changed in this diff Show More