Compare commits

...

139 Commits

Author SHA1 Message Date
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
catlog22
4d17bb02a4 chore: release v7.1.0 2026-03-01 23:17:52 +08:00
catlog22
5cab8ae8a5 fix: CSRF token accessibility and hook installation status
- Remove HttpOnly from XSRF-TOKEN cookie for JavaScript readability
- Add hook installation status detection in system settings API
- Update InjectionControlTab to show installed hooks status
- Add brace expansion support in globToRegex utility
2026-03-01 23:17:37 +08:00
catlog22
ffe3b427ce feat(docs): 添加技能/团队命令对比表和代码审查报告 2026-03-01 21:01:26 +08:00
catlog22
8c953b287d feat(idaw): add run-coordinate command for external CLI execution with hook callbacks 2026-03-01 20:58:26 +08:00
catlog22
b1e321267e docs: fix command invocation syntax accuracy [IDAW-004]
- Fix /workflow-tdd → /workflow-tdd-plan (correct skill name)
- Fix /workflow:test-fix → /workflow-test-fix (skill, not command)
- Fix /workflow:skill-designer → /workflow-skill-designer (skill)
- Fix /workflow:plan → /workflow-plan (skill, not command)
- Remove non-existent /workflow:wave-plan reference
- Update both English and Chinese documentation
2026-03-01 20:50:30 +08:00
catlog22
d0275f14b2 feat(idaw): add CLI-assisted analysis for pre-task context and error recovery
- Pre-task context analysis via gemini for bugfix/complex tasks
- CLI-assisted error diagnosis before retry on skill failure
- Consistent implementation across run.md and resume.md
2026-03-01 20:47:19 +08:00
catlog22
ee4dc367d9 docs: fix 404 errors - add missing zh guide files and fix zh-CN config [IDAW-002]
- Add docs/zh/guide/first-workflow.md (Chinese translation)
- Add docs/zh/guide/cli-tools.md (Chinese translation)
- Fix zh-CN locale config to only show existing files (dashboard, terminal, queue)
- Remove non-existent zh-CN sidebar entries that caused 404 errors
2026-03-01 20:34:11 +08:00
catlog22
a63fb370aa docs: fix repository URLs in getting started guide [IDAW-001]
Replace placeholder URLs with actual repository URL:
https://github.com/catlog22/Claude-Code-Workflow.git
2026-03-01 20:24:20 +08:00
catlog22
da19a6ec89 feat: Implement IDAW commands and update favicon/logo SVGs
- Added IDAW (Independent Development Autonomous Workflow) commands for batch task execution, including `/idaw:add`, `/idaw:run`, `/idaw:status`, and `/idaw:resume`.
- Updated documentation for IDAW commands in both English and Chinese.
- Modified favicon and logo SVGs to reflect new orbital design with dynamic colors.
- Incremented package version from 7.0.6 to 7.0.9.
2026-03-01 20:05:44 +08:00
catlog22
bf84a157ea chore: bump version to 7.0.9
feat(idaw): Independent Development Autonomous Workflow
- /idaw:add — manual task creation + import from ccw issue
- /idaw:run — 6-phase serial orchestrator with git checkpoints
- /idaw:status — read-only progress viewer
- /idaw:resume — resume interrupted sessions from last checkpoint
2026-03-01 19:50:27 +08:00
catlog22
41f990ddd4 Enhance shell safety in skill argument assembly and add animated orbital motion demo
- Updated `assembleSkillArgs` function in `resume.md` and `run.md` to sanitize task goal for shell safety by escaping special characters.
- Introduced a new animated orbital motion demo in `icon-concepts.html`, showcasing agents orbiting with varying speeds and a breathing core effect.
2026-03-01 19:48:50 +08:00
catlog22
3463bc8e27 feat(idaw): add resume, run, and status commands for task management
- Implemented /idaw:resume to resume interrupted sessions with task handling and auto mode.
- Created /idaw:run for executing task skill chains with git checkpoints and session management.
- Added /idaw:status for viewing task and session progress, including overview and specific session details.
- Introduced helper functions for task type inference and skill argument assembly.
- Enhanced task management with session tracking, progress reporting, and error handling.
2026-03-01 19:40:05 +08:00
catlog22
9ad755e225 feat: add comprehensive analysis report for Hook templates compliance with official standards
- Introduced a detailed report outlining compliance issues and recommendations for the `ccw/frontend` implementation of Hook templates.
- Identified critical issues regarding command structure and input reading methods.
- Highlighted errors related to cross-platform compatibility of Bash scripts on Windows.
- Documented warnings regarding matcher formats and exit code usage.
- Provided a summary of supported trigger types and outlined missing triggers.
- Included a section on completed fixes and references to affected files for easier tracking.
2026-03-01 15:12:44 +08:00
catlog22
8799a9c2fd refactor(team-planex): redesign skill with inverted control and beat model
- Delete executor agent (main flow IS the executor now)
- Rewrite SKILL.md: delegated planning + inline execution
- Input accepts issues.jsonl / roadmap session from roadmap-with-file
- Single reusable planner agent via send_input (Pattern 2.3)
- Interleaved plan-execute loop with eager delegation
- Follow codex v3 conventions (decision tables, placeholders)
- Remove complexity assessment and dynamic splitting
2026-03-01 15:06:06 +08:00
catlog22
1f859ae4b9 fix: align spec paths and add missing translation keys 2026-03-01 13:42:25 +08:00
catlog22
ecf4e4d848 fix: align spec paths from .workflow/specs to .ccw/specs
- Fix path mismatch between command files and frontend/backend spec-index-builder
- Update init-specs.md, init-guidelines.md, sync.md, solidify.md to use .ccw/specs/
- Update init.md, start.md, clean.md, unified-execute-with-file.md, collaborative-plan-with-file.md
- Add scope field to architecture-constraints.md and coding-conventions.md
- Ensures specs created by commands are visible in frontend Spec Settings page
2026-03-01 13:28:54 +08:00
catlog22
8ceae6d6fd Add Chinese documentation for custom skills development and reference guide
- Created a new document for custom skills development (`custom.md`) detailing the structure, creation, implementation, and best practices for developing custom CCW skills.
- Added an index document (`index.md`) summarizing all built-in skills, their categories, and usage examples.
- Introduced a reference guide (`reference.md`) providing a quick reference for all 33 built-in CCW skills, including triggers and purposes.
2026-03-01 13:08:12 +08:00
catlog22
2fb93d20e0 feat: add queue management and terminal dashboard documentation in Chinese
- Introduced comprehensive documentation for the queue management feature, detailing its pain points, core functionalities, and component structure.
- Added terminal dashboard documentation, highlighting its layout, core features, and usage examples.
- Created an index page in Chinese for Claude Code Workflow, summarizing its purpose and core features, along with quick links to installation and guides.
2026-03-01 10:52:46 +08:00
catlog22
a753327acc chore: bump version to 7.0.8
feat(team-coordinate-v2): enhance task descriptions with structured format
- Add PURPOSE/TASK/CONTEXT/EXPECTED/CONSTRAINTS sections
- Include goal, actionable steps, key files, and success criteria
- Add Step 2.5: Key File Inference in analyze-task.md
- Update dispatch.md with structured task description template

feat(team-lifecycle-v5): adopt structured task descriptions
- Update task description template in dispatch.md
- Apply structured format to revision and improvement tasks
- Improve worker context with clear goals and file references

feat(team-skill-designer-v4): enforce structured task format
- Add task description template specification in phase 3
- Update quality standards to verify structured format
- Add integration verification checks for new format
- Ensure all generated v5 skills use structured descriptions

Benefits:
- Workers receive clearer context upfront
- Backward compatible with existing team-worker Phase 1
- Consistent format across all v5 team workflows
2026-02-28 23:51:25 +08:00
catlog22
f61a3da957 feat(dispatch): update task description template for improved clarity and structure 2026-02-28 23:49:59 +08:00
catlog22
b0fb899675 feat(dispatch): enhance task description structure with detailed fields and context 2026-02-28 23:45:20 +08:00
catlog22
0a49dc0675 feat: add comprehensive CCWMCP guide and installation instructions 2026-02-28 23:40:51 +08:00
catlog22
096fc1c380 docs: fix installation guide and update MCP recommendations
- Fix installation method to use `ccw install` command
- Update repository URL to correct GitHub location
- Reduce MCP recommendations to 3 servers (ace-tool, chrome-devtools, exa)
- Add ccwmcp documentation guide
- Align documentation with actual CLI and frontend implementation
2026-02-28 23:40:45 +08:00
catlog22
29f0a6cdb8 chore: bump version to 7.0.7 2026-02-28 23:10:11 +08:00
catlog22
e83414abf3 feat(theme): implement dynamic theme logo with reactive color updates 2026-02-28 23:08:27 +08:00
catlog22
e42597b1bc refactor(team): add fast-advance notification and knowledge transfer protocol
- team-worker: add fast_advance message bus log after spawning successor,
  closing coordinator state blind spot during fast-advance
- team-worker: add Knowledge Transfer section with upstream loading,
  downstream publishing, and context_accumulator conventions
- role-spec-template: add Knowledge Transfer Protocol with Transfer
  Channels table and shared-memory.json namespaced write convention
- monitor.md (v2+v5): add fast-advance reconciliation step reading
  fast_advance messages, add State Sync section for coordinator wake
- lifecycle-v5 SKILL.md: update cadence diagram with fast_advance log
2026-02-28 22:53:56 +08:00
catlog22
67b2129f3c Refactor code structure for improved readability and maintainability 2026-02-28 22:32:07 +08:00
catlog22
19fb4d86c7 fix: add -y auto mode bypass for all ccw-coordinator referenced skills
Harmonize orchestrator files (ccw.md, ccw-coordinator.md) with cross-file
consistency fixes, and add missing -y/--yes non-interactive bypass gates
to 7 skills that declared auto mode support but had blocking AskUserQuestion
calls: team-planex, issue:discover, issue:plan, issue:queue, issue:execute,
workflow:debug-with-file, issue:from-brainstorm.
2026-02-28 21:29:38 +08:00
catlog22
65763c76e9 Add TDD Structure Validation and Verification Phases with Comprehensive Reporting
- Introduced Phase 6: TDD Structure Validation to ensure compliance with TDD workflow standards, including task structure validation, dependency checks, and user configuration verification.
- Implemented Phase 7: TDD Verification for full compliance checks, including task chain structure validation, coverage analysis, and TDD cycle verification.
- Generated detailed TDD compliance reports with quality gate recommendations based on objective criteria.
- Added documentation for new commands and workflows in the Claude Commands index.
2026-02-28 20:41:06 +08:00
catlog22
4a89f626fc Refactor documentation for code commands and workflows
- Updated command syntax formatting to use code blocks for clarity in `prep.md`, `review.md`, and `spec.md`.
- Enhanced architectural diagrams in `ch01-what-is-claude-dms3.md` and core concepts in `ch03-core-concepts.md` using mermaid syntax for better visualization.
- Improved workflow diagrams in `ch04-workflow-basics.md` and `4-level.md` to provide clearer representations of processes.
- Added troubleshooting section in `installation.md` to address common installation issues and provide quick start examples.
- Revised skill documentation in `claude-meta.md` and `claude-workflow.md` to standardize command triggers and output structures.
- Updated best practices and workflow index documentation to enhance readability and understanding of workflow levels and practices.
2026-02-28 19:53:24 +08:00
catlog22
b0bfdb907a chore: bump version to 7.0.6 2026-02-28 17:42:48 +08:00
catlog22
39bbf960c2 feat(docs): update examples and enhance language support in configuration 2026-02-28 17:40:48 +08:00
catlog22
5e35da32e8 docs: enhance documentation with examples and fix package names
- Fix incorrect package names (@ccw/cli, @anthropic/claude-code-workflow) to claude-code-workflow
- Add workflow examples page with 8 practical artifact samples
- Optimize sidebar navigation with emoji icons and second-level grouping
- Add usage examples to commands and skills documentation
- Update qa/issues.md with current status
- Sync Chinese documentation changes
2026-02-28 17:20:37 +08:00
catlog22
84610661ca fix(docs): resolve VitePress build errors with custom HTML tags
- Fix custom tags (Good, Bad, Before, After, Tip, Note, Warning) in skill docs
- Replace placeholder variables with HTML entities to prevent Vue parser errors
- Allow manual workflow_dispatch to trigger docs deployment
2026-02-28 16:53:26 +08:00
catlog22
cd54c10256 feat(discovery): add FindingDrawer component and restructure i18n keys
- Add FindingDrawer component for displaying finding details when no
  associated issue exists
- Refactor i18n keys for better organization:
  - status.* → session.status.* (session-related)
  - severity.* → findings.severity.* (finding-related)
- Update DiscoveryDetail to show FindingDrawer for orphan findings
- Add severity/priority mapping in discovery-routes for compatibility
2026-02-28 16:26:11 +08:00
catlog22
c3ddf7e322 docs: add VitePress documentation site
- Add docs directory with VitePress configuration
- Add GitHub Actions workflow for docs build and deploy
- Support bilingual (English/Chinese) documentation
- Include search, custom theme, and responsive design
2026-02-28 16:14:09 +08:00
catlog22
ab65caec45 feat: enhance wave pipeline skills with rich task fields and cross-file consistency
- Add 7 new CSV columns (test, acceptance_criteria, scope, hints,
  execution_directives, tests_passed, acceptance_met) to tasks.csv
  schema across all 3 pipeline skills
- Create .codex/skills/wave-plan-pipeline as Codex version of
  workflow-wave-plan with spawn_agents_on_csv calling conventions
- Align instruction templates with MANDATORY FIRST STEPS and 11-step
  execution protocol across all files
- Standardize context.md reports with Waves metric and Dependencies row
- Unify Discovery Board protocol with Dedup Key table and test_command
- Add Best Practices and Usage Recommendations to workflow-wave-plan
2026-02-28 16:02:05 +08:00
catlog22
3788ba1268 refactor: team-planex dual-version optimization with v5 architecture
Claude version: add coordinator role with Spawn-and-Stop beat model,
replace role-routed planner/executor with team-worker agents using
lightweight role-specs (~80-110 lines each).

Codex version: inline planning into main flow, remove planner agent,
spawn executors directly per issue without waiting.

Both versions preserve 3 input types (Issue IDs / --text / --plan).
2026-02-28 15:31:03 +08:00
catlog22
d14a710797 chore: bump version to 7.0.5 in package-lock.json 2026-02-28 11:56:04 +08:00
catlog22
92ac9897f2 chore: bump version to 7.0.5 2026-02-28 11:40:57 +08:00
catlog22
67e78b132c feat: add workflow-wave-plan skill and A2UI debug logging
- Add CSV Wave planning and execution skill (explore via wave → conflict
  resolution → execution CSV with linked exploration context)
- Add debug NDJSON logging for A2UI submit-all and multi-answer polling
2026-02-28 11:40:28 +08:00
catlog22
0a37bc3eaf fix: update getBuiltinTemplatesDir() and docs for React SPA migration
- Fix getBuiltinTemplatesDir() to safely handle missing templates directory
- Return null when no builtin templates exist instead of non-existent path
- Update listBuiltinTemplates() to handle null return value
- Update outdated docs referencing deleted dashboard-js/dashboard-css files
- Replace references to vanilla JS frontend with React SPA paths

Related: commit bcb73670 removed old vanilla JS/CSS frontend
2026-02-28 11:39:16 +08:00
catlog22
604f89b7aa chore: bump version to 7.0.4 2026-02-28 10:01:08 +08:00
catlog22
46989dcbad fix(frontend): add missing i18n keys and improve workspace switch cache invalidation
- Add common.status.ready i18n key for zh/en locales
- Add ready/initialized/archived/failed status colors to dashboard widgets
- Expand QueryInvalidator to invalidate projectOverview, workflowStatusCounts,
  and dashboardStats queries on workspace switch
2026-02-28 10:00:36 +08:00
catlog22
4763edb0e4 feat: update project overview hook to include projectPath in queryKey
docs: add team lifecycle orchestrator skill documentation with detailed architecture, agent registry, and execution phases

docs: introduce team planex skill for issue-by-issue execution with Codex CLI, including input parsing and session management
2026-02-28 09:39:35 +08:00
catlog22
7d349a64fb fix: replace empty array with EMPTY_ITEMS in selectQueueItems and selectSchedulerProgress 2026-02-28 09:28:16 +08:00
catlog22
22a98b7b6c chore: bump version to 7.0.3
- Add .ccw/ to npm package files
- Add .claude/CLAUDE.md to npm package files
- Exclude .claude/skills_lib from package
2026-02-28 09:27:42 +08:00
catlog22
a59a86fb9b chore: bump version to 7.0.2 2026-02-28 08:55:46 +08:00
catlog22
101417e028 feat: add csv-wave-pipeline skill for wave-based CSV batch execution with context propagation 2026-02-28 08:55:21 +08:00
catlog22
902ee8528a fix(frontend): include frontend/dist in npm package and support static file serving
- Add ccw/frontend/dist/ to package.json files field
- Modify react-frontend.ts to detect and use production build
- Add static file serving to server.ts with MIME type support
- Update prepublishOnly to build frontend before publishing
- Fix unused import in TerminalDashboardPage.tsx

This fixes the 'Could not find React frontend directory' error when users install from npm.
2026-02-28 08:39:07 +08:00
catlog22
54f15b6bda feat: add csv-batch-execute skill for CSV-based batch task execution with context propagation 2026-02-27 23:09:26 +08:00
catlog22
690d524aee docs: update README and WORKFLOW_GUIDE with simplified content
- Streamline README documentation
- Update workflow guide with current best practices
2026-02-27 22:52:28 +08:00
catlog22
b02c8497c7 fix(team-skills): resolve skill name inconsistency and add command execution protocol
team-coordinate-v2:
- Fix skill name mismatch: update all doc examples to use "team-coordinate-v2"
- This was the root cause of v2 failing to invoke teams

team-lifecycle-v3/v4:
- Add Command Execution Protocol section before Entry Router
- Fix Entry Router logic: distinguish interrupted vs new sessions
- Add Router Implementation subsection with concrete steps
2026-02-27 22:51:46 +08:00
catlog22
be061dd2a2 Refactor and optimize various components and files
- Removed deprecated `ccw-contentPattern-optimization-summary.md` and related files.
- Updated `A2UIPopupCard.tsx` to clarify comments on interaction handling.
- Enhanced `QueueListColumn.tsx` and `QueuePanel.tsx` to handle potential undefined values for `config`.
- Added `useEffect` in `QueuePanel.tsx` to load scheduler state on mount.
- Improved `SchedulerPanel.tsx` to handle potential undefined values for `sessionPool`.
- Introduced auto-initialization logic in `queueSchedulerStore.ts` to prevent multiple initialization calls.
- Updated `A2UIWebSocketHandler.ts` to refine selection handling logic.
- Enhanced `hooks-routes.ts` to support multi-question surfaces.
- Added submit and cancel buttons in `ask-question.ts` for better user interaction.
- Deleted `codex_prompt.md` and `contentPattern-library-options.md` as part of cleanup.
- Removed `status-reference.md` to streamline documentation.
2026-02-27 22:35:05 +08:00
catlog22
9be35ed5fb feat: implement infinite scrolling for native sessions and add reset functionality to queue scheduler 2026-02-27 21:24:44 +08:00
catlog22
a581a2e62b feat: upgrade to v7.0.0 with major new features including Team Architecture v2 and Queue Scheduler
- Updated version in README and package.json to v7.0.0
- Added new features in WORKFLOW_GUIDE and WORKFLOW_GUIDE_CN
- Introduced session lifecycle commands for managing workflow sessions
- Enhanced NativeSessionPanel to support loading sessions by path or execution ID
- Created useNativeSessionByPath hook for fetching session content by file path
- Improved session metadata structure in API definitions
- Increased stale and garbage collection times for session hooks
- Refactored HistoryPage to utilize new session handling logic
2026-02-27 21:07:16 +08:00
catlog22
5c158d9a64 feat(commands): add create button and file browser to commands page
- Add "New Command" button to CommandsManagerPage header
- Integrate CommandCreateDialog for creating/importing commands
- Add file browser button to source path input in CommandCreateDialog
  - Uses FloatingFileBrowser component for file selection
  - Supports browsing project directory for .md command files
- Add i18n keys for browse file button (en/zh)

Users can now create commands via:
1. Import existing .md file (with visual file picker)
2. AI-generate new command from description
2026-02-27 21:03:37 +08:00
catlog22
75173312c1 feat(queue): implement queue scheduler service and API routes
- Added QueueSchedulerService to manage task queue lifecycle, including state machine, dependency resolution, and session management.
- Implemented HTTP API endpoints for queue scheduling:
  - POST /api/queue/execute: Submit items to the scheduler.
  - GET /api/queue/scheduler/state: Retrieve full scheduler state.
  - POST /api/queue/scheduler/start: Start scheduling loop with items.
  - POST /api/queue/scheduler/pause: Pause scheduling.
  - POST /api/queue/scheduler/stop: Graceful stop of the scheduler.
  - POST /api/queue/scheduler/config: Update scheduler configuration.
- Introduced types for queue items, scheduler state, and WebSocket messages to ensure type safety and compatibility with the backend.
- Added static model lists for LiteLLM as a fallback for available models.
2026-02-27 20:53:46 +08:00
catlog22
5b54f38aa3 feat: add team-coordinate-v2 and team-executor-v2 with team-worker agent architecture
v2 upgrades using the unified team-worker agent pattern:
- Replace general-purpose + Skill spawn with team-worker agent
- Use lightweight role-spec files (~80 lines, Phase 2-4 only) instead of full role.md (~250 lines)
- Add interactive completion action (Archive/Keep/Export) via handleComplete handler
- Remove shared infrastructure from SKILL.md (now in team-worker agent)

team-coordinate-v2 (8 files):
- SKILL.md: coordinator-only, team-worker spawn template
- specs/role-spec-template.md: lightweight Phase 2-4 template
- roles/coordinator/: updated for role-spec generation
- subagents/: discuss + explore (unchanged)

team-executor-v2 (4 files):
- SKILL.md: executor-only, team-worker spawn
- specs/session-schema.md: validates role-specs (not roles/)
- roles/executor/: updated for team-worker spawn + handleComplete
2026-02-27 20:47:03 +08:00
catlog22
61f929005c fix(ci): add GitHub Actions release workflows and fix visual test
- Add release.yml for manual npm publishing on GitHub Release
- Add release-canary.yml for automated canary releases (every 20 commits)
- Fix visual test template path (use homedir() instead of ~)
- Update visual test baselines
- Add sync-version.mjs script for version synchronization
- Add sync-version npm script to package.json
2026-02-27 19:06:34 +08:00
catlog22
47fe0d3bec feat: add team-lifecycle-v5 with unified team-worker agent architecture
Replace v4's per-role boilerplate (7 role.md files sharing 60% code) with
a single team-worker agent that handles Phase 1/5, message bus, consensus,
and inner loop. Role-specific Phase 2-4 logic lives in lightweight role-spec
files. Workers spawn as team-worker agents directly instead of general-purpose
+ Skill indirection, reducing total worker content by ~64%.
2026-02-27 19:02:22 +08:00
catlog22
017b258223 test: add integration and E2E tests for command creation feature
- Add backend integration tests for POST /api/commands/create endpoint
  - Validation tests (mode, location, required fields)
  - Security tests (path traversal prevention)
  - Upload mode tests (file creation, path handling)
  - Edge cases (special characters, unicode, nested paths)

- Add frontend E2E tests for CommandCreateDialog component
  - Dialog open/close tests
  - Mode switching (import/generate)
  - Location selection (project/user)
  - API success/error handling
  - Loading states and validation

Tests verify dual-mode command creation functionality with proper
error handling and security validation.
2026-02-27 18:52:39 +08:00
catlog22
93041402f2 feat: add team-executor skill with enhanced validation
- Create team-executor skill for resuming existing team-coordinate sessions
- Add SKILL.md with role router and session validation
- Add roles/executor/role.md with simplified coordinator lifecycle
- Add commands/monitor.md with LIMITED handleAdapt (no role generation)
- Add specs/session-schema.md with comprehensive validation

Enhancements from code review:
- Add role file structural validation (required sections check)
- Add JSON schema field validation for team-session.json and task-analysis.json
- Add 5-role limit enforcement in handleAdapt (team-coordinate)
2026-02-27 18:51:21 +08:00
catlog22
8566e3af44 fix(team): use session-id instead of team-name in team_msg across all skills
Root cause: team_msg --team parameter maps directly to filesystem path
.workflow/.team/{value}/.msg/, so using team-name creates wrong directory.

Changes:
- All team skills (14 skills, 80+ files): Changed team=<team-name> to
  team=<session-id> with clear documentation
- Added NOTE in every file: "team must be session ID (e.g., TLS-xxx-date),
  NOT team name. Extract from Session: field in task description."
- CLI fallback examples updated: --team brainstorm -> --team <session-id>

Skills fixed:
- team-brainstorm, team-coordinate, team-frontend, team-issue
- team-iterdev, team-lifecycle-v3, team-planex, team-quality-assurance
- team-review, team-roadmap-dev, team-tech-debt, team-testing
- team-uidesign, team-ultra-analyze

Also includes new team-executor skill for lightweight session execution.
2026-02-27 18:48:39 +08:00
catlog22
3b92bfae8c feat: add Discuss and Explore subagents for dynamic critique and code exploration
- Implement Discuss Subagent for multi-perspective critique with dynamic perspectives.
- Create Explore Subagent for shared codebase exploration with centralized caching.
- Add tests for CcwToolsMcpCard component to ensure enabled tools are preserved on config save.
- Introduce SessionPreviewPanel component for previewing and selecting sessions for Memory V2 extraction.
- Develop CommandCreateDialog component for creating/importing commands with import and CLI generate modes.
2026-02-27 17:25:52 +08:00
catlog22
3db74cc7b0 feat: Enhance team lifecycle roles with checkpoint handling and inner loop execution
- Added checkpoint gate handling to the coordinator role, defining behavior based on quality gate results.
- Updated planner role to utilize inner loop pattern for structured implementation planning and reporting.
- Revised writer role to implement inner loop for document generation, delegating CLI execution to a subagent.
- Introduced a new doc-generation subagent for isolated CLI calls and document generation strategies.
- Enhanced UI components in the frontend to display job statuses, last run times, and improved error handling.
- Updated localization files to include new strings for job details and status banners.
- Improved CSS styles for markdown previews to enhance readability and presentation.
2026-02-27 14:45:38 +08:00
catlog22
b449b225fe feat(hook): add display name to template ID mapping and improve translation fallback logic 2026-02-27 13:58:45 +08:00
catlog22
e61f539d44 docs(roadmap): fix issue query interface documentation
- Replace non-existent `--tag` and `--session` options with actual commands
- Update to use `ccw issue list --status` and queue-based workflow
- Sync changes across both Claude and Codex versions
2026-02-27 13:48:06 +08:00
catlog22
20eef5cd2d feat: update styles and improve Chinese localization in CLI manager 2026-02-27 13:39:08 +08:00
catlog22
dd72e95e4d feat: add templates for epics, product brief, and requirements PRD
- Created a new directory structure for epics and stories with templates for individual epics and an index file.
- Added a product brief template for generating product brief documents in Phase 2.
- Introduced a requirements PRD template for generating a Product Requirements Document as a directory of individual requirement files in Phase 3.

feat: implement V2PipelineTab component for Memory V2 management

- Developed the V2PipelineTab component to manage extraction and consolidation processes.
- Included ExtractionCard and ConsolidationCard components to handle respective functionalities.
- Added JobsList component to display job statuses and allow filtering by job kind.

feat: create hooks for Memory V2 pipeline

- Implemented custom hooks for managing extraction and consolidation statuses, as well as job listings.
- Added mutation hooks to trigger extraction and consolidation processes with automatic query invalidation on success.
2026-02-27 13:27:27 +08:00
catlog22
99a3561f71 feat(workflow): add unified workflow spec command system
- Add /workflow:init-specs command for interactive spec creation with scope selection (global/project)
- Update /workflow:init to chain solidify and add --skip-specs flag
- Add category field support to generated specs frontmatter
- Add GET /api/project-tech/stats endpoint for development progress stats
- Add devProgressInjection settings to system configuration
- Add development progress injection control card to GlobalSettingsTab
- Add i18n keys for new settings in en/zh locales
2026-02-27 12:25:26 +08:00
catlog22
4d755ff9b4 feat(workflow): add lightweight interactive planning workflow with in-memory execution and code exploration
- Introduced `lite-plan` command for intelligent task analysis and planning.
- Implemented dynamic exploration and clarification phases based on task complexity.
- Added support for auto mode and forced exploration flags.
- Defined output artifacts and session structure for planning results.
- Enhanced execution process with context handoff to `lite-execute`.

chore(temp): create temporary memory content and import script

- Added `.temp-memory-content.txt` to store session details and execution plan.
- Implemented `temp-import-memory.cjs` to handle memory import using core-memory command.
- Ensured cleanup of temporary files after execution.
2026-02-27 11:43:44 +08:00
catlog22
07452e57b7 refactor(skill): replace compact protection with TodoWrite-driven compact recovery
Redesign Pattern 9 from "forbid compression" to smart dual-layer approach:
- Layer 1: TodoWrite in_progress phase preserved by compact, completed phases compressible
- Layer 2: Compact sentinel in phase files as fallback re-read trigger

Applied to 6 workflow skills: skill-designer, lite-plan, multi-cli-plan, plan, tdd, test-fix
2026-02-27 11:13:50 +08:00
catlog22
3f25dbb11b feat: add injection preview functionality and enhance specs management
- Implemented injection preview feature in InjectionControlTab with file listing and content preview.
- Added new API endpoint for fetching injection preview data.
- Introduced content length caching for performance optimization.
- Enhanced spec loading to support category filtering.
- Updated localization files for new features and terms.
- Created new personal and project specs for coding style and architecture constraints.
- Improved CLI options for category selection in spec commands.
2026-02-27 09:45:28 +08:00
catlog22
dfa8e0d9f5 feat: add category and scope to specs for enhanced filtering and organization
- Introduced SpecCategory and SpecScope types to categorize specs by workflow stage and scope (global/project).
- Updated Spec interface to include category and scope properties.
- Enhanced SpecCard component to display category and scope badges.
- Implemented category and scope filtering in SpecsSettingsPage.
- Updated localization files to support new category and scope labels.
- Modified spec loading commands to utilize category instead of keywords.
- Adjusted spec index builder to handle category and scope during spec parsing.
- Updated seed documents to include category information.
2026-02-26 23:43:55 +08:00
catlog22
052e25dddb feat: add SpecContentDialog component for viewing and editing spec content 2026-02-26 23:20:18 +08:00
catlog22
fa8bae52f1 refactor(spec): remove obsolete dimensions and update CLI options 2026-02-26 23:19:41 +08:00
catlog22
ffe79d28e2 refactor(spec): update folder structure and dimensions
- Change folder from .workflow/ to .ccw/
- Reduce dimensions from 4 to 2: specs, personal
- Remove changelog and roadmap dimensions
- Update help text and examples

Folder structure:
- .ccw/specs/ - Project rules and conventions
- .ccw/personal/ - Personal preferences (supports global ~/.ccw/personal/)
- .ccw/.spec-index/ - Index cache

Keyword categories for workflow stages:
- exploration - Code exploration, analysis, debugging
- planning - Task planning, requirements
- execution - Implementation, testing, deployment
2026-02-26 23:13:00 +08:00
catlog22
151b81ee4a feat: Enhance spec management with new hooks and settings features
- Updated test cycle execution steps to streamline agent execution.
- Improved HookDialog component with enhanced validation messages and localization.
- Introduced SpecDialog component for better spec management.
- Added new hooks for fetching and updating specs list and frontmatter.
- Implemented API functions for specs list retrieval and index rebuilding.
- Added localization support for new specs settings and hooks.
- Enhanced SpecsSettingsPage to manage project and personal specs effectively.
- Updated CLI commands to support keyword-based spec loading.
- Improved spec index builder to categorize specs by workflow stages.
2026-02-26 22:52:33 +08:00
catlog22
6155fcc7b8 feat: add SpecDialog component for editing spec frontmatter
- Implement SpecDialog for managing spec details including title, read mode, priority, and keywords.
- Add validation and keyword management functionality.
- Integrate SpecDialog into SpecsSettingsPage for editing specs.

feat: create index file for specs components

- Export SpecCard, SpecDialog, and related types from a new index file for better organization.

feat: implement SpecsSettingsPage for managing specs and hooks

- Create main settings page with tabs for Project Specs, Personal Specs, Hooks, Injection, and Settings.
- Integrate SpecDialog and HookDialog for editing specs and hooks.
- Add search functionality and mock data for specs and hooks.

feat: add spec management API routes

- Implement API endpoints for listing specs, getting spec details, updating frontmatter, rebuilding indices, and initializing the spec system.
- Handle errors and responses appropriately for each endpoint.
2026-02-26 22:03:13 +08:00
catlog22
430d817e43 feat(skills): update 12 team skills to v3 design patterns
- Update all 12 team-* SKILL.md files with v3 structure:
  - Replace JS pseudocode with text decision tables
  - Add Role Registry with Compact column
  - Add COMPACT PROTECTION blocks
  - Add Cadence Control sections
  - Add Wisdom Accumulation sections
  - Add Task Metadata Registry
  - Add Orchestration Mode user commands

- Update 58 role files (SKILL.md + roles/*):
  - Flat-file skills: team-brainstorm, team-issue, team-testing,
    team-uidesign, team-planex, team-iterdev
  - Folder-based skills: team-review, team-roadmap-dev, team-frontend,
    team-quality-assurance, team-tech-debt, team-ultra-analyze

- Preserve special architectures:
  - team-planex: 2-member (planner + executor only)
  - team-tech-debt: Stop-Wait strategy (run_in_background:false)
  - team-iterdev: 7 behavior protocol tables in coordinator

- All 12 teams reviewed for content completeness (PASS)
2026-02-26 21:14:45 +08:00
catlog22
e228b8b273 Remove obsolete documentation and configuration files for team lifecycle specifications
- Deleted document standards for spec-generator outputs.
- Removed quality gates criteria and scoring dimensions.
- Eliminated team configuration JSON file.
- Cleared architecture document template for generating ADRs.
- Purged epics and stories template for breakdown generation.
- Erased product brief template for Phase 2 documentation.
- Removed requirements PRD template for Phase 3 documentation.
2026-02-26 16:48:21 +08:00
catlog22
79cdd47be5 chore: remove skills_lib from remote tracking
- Add .claude/skills_lib/ to .gitignore
- Remove folder from git index (local files preserved)
2026-02-26 16:35:01 +08:00
catlog22
1a1ca389f4 Add role and skill router templates for v3 style execution
- Introduced a comprehensive role template for generating per-role execution detail files, including purpose, style rules, and structured phases.
- Added a skill router template to facilitate role-based routing in SKILL.md, detailing input parsing, role registry, orchestration mode, and shared infrastructure.
- Both templates adhere to v3 conventions, emphasizing clarity and structured decision-making through markdown tables and diagrams.
2026-02-26 16:32:17 +08:00
catlog22
653ad10475 feat(analysis): enhance AnalysisPage with filters, grid layout and fullscreen mode
- Add status filter tabs (all/in_progress/completed)
- Add date filter tabs (all/today/week/month)
- Add date quick filter bubbles with session counts
- Change layout from list to 4-column grid (16 items per page)
- Add fullscreen/immersive mode toggle
- Make cards compact with smaller font and more content
- Add clickable status badges for quick filtering
- Reduce padding for consistency with other pages
- Show session ID, status, date and conclusions indicator on cards
2026-02-26 16:05:48 +08:00
catlog22
2487a8330c feat: 更新分析会话 API,支持分页和并发处理 2026-02-26 14:31:30 +08:00
catlog22
a94c790c4f feat: Enhance workflow execution and documentation processes
- Added compact protection directives to execution phases to ensure critical instructions are preserved during context compression.
- Introduced checkpoints in execution steps to verify active memory of execution protocols.
- Created new command files for team lifecycle roles:
  - `dispatch.md`: Manage task chains based on execution modes.
  - `monitor.md`: Event-driven pipeline coordination with worker callbacks.
  - `critique.md`: Multi-perspective CLI critique for structured analysis.
  - `implement.md`: Multi-backend code implementation with retry and fallback mechanisms.
  - `explore.md`: Complexity-driven codebase exploration for task planning.
  - `generate-doc.md`: Multi-CLI document generation for various document types.
- Updated SKILL.md to include compact protection patterns and phase reference documentation.
2026-02-26 14:10:00 +08:00
catlog22
f10351ee50 Merge branch 'main' of https://github.com/catlog22/Claude-Code-Workflow 2026-02-26 14:05:40 +08:00
AXC00
12be252e8e feat(analysis): 添加分析查看器页面 (#122)
- 新增 AnalysisPage 页面查看 /workflow:analyze-with-file 分析结果
- 支持 Tab 分组展示:讨论记录、结论、代码探索、视角分析
- Markdown 内容富文本渲染,JSON 数据结构化卡片展示
- 添加后端 API 路由 /api/analysis
- 添加侧边栏导航入口和中英文翻译

Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
2026-02-26 14:04:41 +08:00
catlog22
4ad05f8217 feat: add templates for architecture documents, epics, product briefs, and requirements PRD
- Introduced architecture document template for Phase 4, including structure and individual ADR records.
- Added epics & stories template for Phase 5, detailing epic breakdown and dependencies.
- Created product brief template for Phase 2, summarizing product vision, problem statement, and target users.
- Developed requirements PRD template for Phase 3, outlining functional and non-functional requirements with traceability.
- Implemented spec command for project spec management with subcommands for loading, listing, rebuilding, and initializing specs.
2026-02-26 13:59:47 +08:00
catlog22
2b5c334bc4 feat: Implement recursive core-memory database discovery and project listing
- Added `findAllCoreMemoryDatabases` function to recursively locate core-memory databases in nested project structures.
- Updated `listAllProjects` to utilize the new recursive function for improved project listing.
- Enhanced `getMemoriesFromProject` and `findMemoryAcrossProjects` to support nested project structures.

feat: Introduce spec context injection in hooks configuration

- Added a new hook configuration for "Spec Context Injection" to load project specs based on prompt keywords.

chore: Add gray-matter dependency for YAML frontmatter parsing

- Included `gray-matter` package in `package.json` for parsing YAML frontmatter in markdown files.

feat: Create Spec Index Builder tool for managing project specs

- Implemented `spec-index-builder.ts` to scan markdown files, extract YAML frontmatter, and generate index cache files for different spec dimensions.

feat: Develop Spec Init tool for initializing spec directories and seed documents

- Created `spec-init.ts` to set up the directory structure and seed documents for the spec system.

feat: Build Spec Keyword Extractor for keyword extraction from prompts

- Added `spec-keyword-extractor.ts` to extract keywords from user prompts, supporting both English and Chinese text.

feat: Implement Spec Loader for loading and filtering specs based on keywords

- Developed `spec-loader.ts` to handle loading of specs, filtering by read mode and keyword matches, and formatting output for CLI or hooks.
2026-02-26 12:51:29 +08:00
catlog22
a35fb0fe8f fix(workflow): bridge analyze-with-file to lite-plan handoff and lower agent planning threshold
- Add Post-Completion implementation in analyze-with-file Phase 4: write
  handoff-lite-plan.json and call Skill with --from-analysis flag
- Add --from-analysis parsing in SKILL.md router (Step 0) to inject
  analysisHandoff into workflowPreferences
- Reconstruct exploration context in lite-plan Phase 1 from upstream
  analysis artifacts, skipping redundant exploration and clarification
- Tighten Low complexity criteria to truly trivial changes only
- Expand agent trigger: analysisHandoff or multi-angle exploration
  forces cli-lite-planning-agent regardless of complexity
2026-02-26 11:20:06 +08:00
catlog22
bf02f653ca fix(types): add runtime validation for GitHub API response in skill-hub-routes
- Replace GitHubTreeEntry with GitHubContentEntry matching actual API response
- Add runtime array validation to prevent unexpected response formats
- Normalize GitHub API types ('file'/'dir') to internal types ('blob'/'tree')
- Validate required fields (name, path, type) for each entry

This fixes potential runtime errors when GitHub API response structure
differs from expected type definition.
2026-02-26 10:28:33 +08:00
catlog22
b6f4864530 refactor: remove 'executions' case from IssueHubPage rendering logic 2026-02-26 10:15:45 +08:00
catlog22
2623b5a633 refactor: remove 'executions' tab and related components from Issue Hub 2026-02-26 10:02:53 +08:00
catlog22
21e3647331 feat(security): implement path validation to prevent traversal attacks in session handling 2026-02-26 09:56:35 +08:00
catlog22
519efe9783 feat(hooks): add hook management and session timeline features
- Add hook quick templates component with configurable templates
- Refactor NativeSessionPanel to use new SessionTimeline component
- Add OpenCode session parser for parsing OpenCode CLI sessions
- Enhance API with session-related endpoints
- Add locale translations for hooks and native session features
- Update hook commands and routes for better hook management
2026-02-25 23:21:35 +08:00
catlog22
25f442b329 fix(build): add postbuild hook to set executable permissions on Mac/Linux
Add chmod 755 for ccw/bin/ccw.js and ccw-mcp.js after TypeScript compilation.
This fixes the issue where ccw CLI cannot be executed directly on Mac/Linux
after npm run build due to missing execute permissions.
2026-02-25 23:19:25 +08:00
catlog22
b4d3426e6a feat: add CLI config preview API for Codex and Gemini
- Implemented `fetchCodexConfigPreview` and `fetchGeminiConfigPreview` functions in the API layer to retrieve masked configuration files.
- Added new interfaces `CodexConfigPreviewResponse` and `GeminiConfigPreviewResponse` to define the structure of the API responses.
- Created utility functions to read and mask sensitive values from `config.toml` and `auth.json` for Codex, and `settings.json` for Gemini.
- Updated CLI settings routes to handle new preview endpoints.
- Enhanced session content parser to support Claude JSONL format.
- Updated UI components to reflect changes in history page and navigation, including new tabs for observability.
- Localized changes for English and Chinese languages to reflect "CLI History" terminology.
2026-02-25 22:37:30 +08:00
catlog22
c92754505a fix(clean): correct project-tech field references and add sync vs clean disambiguation
- Fix Step 4.3: project.features → project.development_index,
  project.statistics → project._metadata
- Add project-guidelines.json learnings cleanup on session deletion
- Add sync vs clean disambiguation table explaining write vs reclaim
2026-02-25 22:34:15 +08:00
catlog22
f96febe09a feat: add /workflow:session:sync command and integrate auto-sync into execution pipelines
Add a new session sync command that updates both project-guidelines.json
and project-tech.json from session context in one shot. Replace inline
Step 6 (Update Development Index) in lite-execute with sync call, and
add auto-sync to Post-Completion Expansion across 6 execution commands.
Simplify session/complete by replacing Phase 4+5 with single sync call.
2026-02-25 22:32:33 +08:00
catlog22
b2b8688d26 feat: add CLI settings export/import functionality
- Implemented exportSettings and importSettings APIs for CLI settings.
- Added hooks useExportSettings and useImportSettings for managing export/import operations in the frontend.
- Updated SettingsPage to include buttons for exporting and importing CLI settings.
- Enhanced backend to handle export and import requests, including validation and conflict resolution.
- Introduced new data structures for exported settings and import options.
- Updated localization files to support new export/import features.
- Refactored CLI tool configurations to remove hardcoded model defaults, allowing dynamic model retrieval.
2026-02-25 21:40:24 +08:00
catlog22
4c2bf31525 feat(spec-generator): add Phase 1.5 requirement expansion & clarification
Insert interactive requirement discussion stage between Discovery and
Product Brief to address missing requirement depth analysis. Phase 1.5
uses Gemini CLI for gap analysis, supports multi-round interactive
discussion (max 5 rounds), and outputs refined-requirements.json as
high-quality input for downstream phases. Compatible with -y auto mode.
2026-02-25 19:42:45 +08:00
catlog22
eb9a62e085 feat: enhance project context loading and feature flag support in dashboard components 2026-02-25 18:59:49 +08:00
catlog22
db5797faa3 refactor(agents): deduplicate agent invocation prompts and strengthen project artifact consumption
Remove duplicated content from caller prompts that repeat agent spec definitions:
- EXECUTION METHOD MAPPING, CLI EXECUTION ID strategies, Quantification Rules
- MANDATORY FIRST STEPS (now internalized in cli-explore-agent)
- relevant_files schema details, Phase execution flow re-specifications
- plan.json/task JSON field listings (reference schemas instead)

Strengthen project-tech.json and project-guidelines.json consumption:
- context-search-agent: add Phase 1.1b mandatory project context loading
- cli-explore-agent: add Autonomous Initialization with 4 self-contained steps
- action-planning-agent: strengthen Phase 1 Step 0 with detailed usage guidance
- All caller prompts: add/reinforce PROJECT CONTEXT (MANDATORY) sections

Agent specs modified: action-planning-agent, cli-explore-agent, context-search-agent
Caller prompts slimmed: 04-task-generation, 05-tdd-task-generation,
  02-context-gathering, 01-lite-plan, collaborative-plan-with-file,
  05-test-cycle-execute
2026-02-25 18:44:51 +08:00
catlog22
5c51315a7e fix(codex-skill): rename team-planex orchestrator.md to SKILL.md and fix frontmatter
Codex skills require SKILL.md as entry file. Renamed orchestrator.md,
added allowed-tools and argument-hint, removed non-standard fields.
2026-02-25 18:05:06 +08:00
catlog22
d6acbaf30f feat(cli-settings): support multi-provider settings for Claude, Codex, and Gemini
Decouple CLI settings architecture from Claude-only to support multiple
providers. Each provider has independent settings UI and backend handling.

- Add CliProvider type discriminator ('claude' | 'codex' | 'gemini')
- Add CodexCliSettings (profile, authJson, configToml) and GeminiCliSettings types
- Update EndpointSettings with provider field (defaults 'claude' for backward compat)
- Refactor CliSettingsModal with provider selector and provider-specific forms
- Remove includeCoAuthoredBy field across all layers
- Extend CliConfigModal to show Config Profile for all tools (not just claude)
- Add provider-aware argument injection in cli-session-manager (--settings/--profile/env)
- Rename addClaudeCustomEndpoint to addCustomEndpoint (old name kept as deprecated alias)
- Replace providerBasedCount/directCount with per-provider counts in useCliSettings hook
- Update CliSettingsList with provider badges and per-provider stat cards
- Add Codex and Gemini test cases for validateSettings and createDefaultSettings
2026-02-25 17:40:43 +08:00
catlog22
c11596c038 Merge branch 'main' of https://github.com/catlog22/Claude-Code-Workflow 2026-02-25 11:14:28 +08:00
Copilot
b669dcba24 fix: replace npmmirror.com registry URLs with registry.npmjs.org in package-lock.json
Fixes npm install failures after git clone by replacing 14 Chinese mirror URLs with standard registry URLs
2026-02-25 11:13:46 +08:00
catlog22
7ebe674b62 feat(issue-panel): add multi-select functionality and send to terminal feature
feat(config-store): add dashboard feature flags to initial state
fix(skill-hub-routes): update skill index path for GitHub configuration
2026-02-25 10:38:47 +08:00
catlog22
e315e2315c Remove temporary verbose JSON file and cleanup script for VSCode bridge 2026-02-25 10:30:19 +08:00
catlog22
092b8e20dc feat(cleanup): remove ccw-vscode-bridge and related files 2026-02-25 10:22:55 +08:00
catlog22
45c61186c4 feat(server): add regression test for handling empty request bodies
feat(terminal): focus terminal on click
fix(vite): update API proxy path to avoid frontend route conflicts
2026-02-25 09:59:54 +08:00
catlog22
6c16c121d2 feat(skills): add team-roadmap-dev skill with phased execution pipeline
Roadmap-driven development team skill with coordinator/planner/executor/verifier
roles. Features action-planning-agent integration (IMPL-*.json task format),
convergence criteria verification, pause/resume support, and wave-based execution.
2026-02-24 23:32:32 +08:00
catlog22
dadcc1af5e feat(ccw-litellm): enhance status checks and add file preview functionality 2026-02-24 21:46:25 +08:00
catlog22
33e12a31ac feat(skills): add skill deletion and improve UI/UX
- Add skill deletion functionality with confirmation dialog
- Protect builtin skills from deletion
- Optimize skill card layout (badge and enable button near menu)
- Change enable button to icon-only with theme color
- Improve card selection and hover states
- Fix skill hub installation state tracking (per-skill)
- Add proper i18n for delete feature (en/zh)
- Add loading states to delete confirmation dialog
- Remove manual refetch calls (use query invalidation)
2026-02-24 21:06:34 +08:00
894 changed files with 146260 additions and 69701 deletions

View File

@@ -0,0 +1,27 @@
---
title: "Personal Coding Style"
dimension: personal
category: general
keywords:
- style
- preference
readMode: optional
priority: medium
---
# Personal Coding Style
## Preferences
- Describe your preferred coding style here
- Example: verbose variable names vs terse, functional vs imperative
## Patterns I Prefer
- List patterns you reach for most often
- Example: builder pattern, factory functions, tagged unions
## Things I Avoid
- List anti-patterns or approaches you dislike
- Example: deep inheritance hierarchies, magic strings

View File

@@ -0,0 +1,25 @@
---
title: "Tool Preferences"
dimension: personal
category: general
keywords:
- tool
- cli
- editor
readMode: optional
priority: low
---
# Tool Preferences
## Editor
- Preferred editor and key extensions/plugins
## CLI Tools
- Preferred shell, package manager, build tools
## Debugging
- Preferred debugging approach and tools

View File

@@ -0,0 +1,33 @@
---
title: "Architecture Constraints"
dimension: specs
category: planning
keywords:
- architecture
- module
- layer
- pattern
readMode: required
priority: high
scope: project
---
# Architecture Constraints
## Module Boundaries
- Each module owns its data and exposes a public API
- No circular dependencies between modules
- Shared utilities live in a dedicated shared layer
## Layer Separation
- Presentation layer must not import data layer directly
- Business logic must be independent of framework specifics
- Configuration must be externalized, not hardcoded
## Dependency Rules
- External dependencies require justification
- Prefer standard library when available
- Pin dependency versions for reproducibility

View File

@@ -0,0 +1,39 @@
---
title: "Coding Conventions"
dimension: specs
category: general
keywords:
- typescript
- naming
- style
- convention
readMode: required
priority: high
scope: project
---
# Coding Conventions
## Naming
- Use camelCase for variables and functions
- Use PascalCase for classes and interfaces
- Use UPPER_SNAKE_CASE for constants
## Formatting
- 2-space indentation
- Single quotes for strings
- Trailing commas in multi-line constructs
## Patterns
- Prefer composition over inheritance
- Use early returns to reduce nesting
- Keep functions under 30 lines when practical
## Error Handling
- Always handle errors explicitly
- Prefer typed errors over generic catch-all
- Log errors with sufficient context

View File

@@ -301,7 +301,7 @@ Document known constraints that affect planning:
[Continue for all major feature groups]
**Note**: Detailed task breakdown into executable work items is handled by `/workflow:plan``IMPL_PLAN.md`
**Note**: Detailed task breakdown into executable work items is handled by `/workflow-plan``IMPL_PLAN.md`
---

View File

@@ -43,7 +43,7 @@ Core requirements, objectives, technical approach summary (2-3 paragraphs max).
**Quality Gates**:
- concept-verify: ✅ Passed (0 ambiguities remaining) | ⏭️ Skipped (user decision) | ⏳ Pending
- plan-verify: ⏳ Pending (recommended before /workflow:execute)
- plan-verify: ⏳ Pending (recommended before /workflow-execute)
**Context Package Summary**:
- **Focus Paths**: {list key directories from context-package.json}

View File

@@ -30,6 +30,7 @@ RULES: [templates | additional constraints]
## Execution Flow
0. **Load Project Specs** - MANDATORY first step: run `ccw spec load` to retrieve project specifications and constraints before any analysis. Adapt analysis scope and standards based on loaded specs
1. **Parse** all 6 fields (PURPOSE, TASK, MODE, CONTEXT, EXPECTED, RULES)
2. **Read** and analyze CONTEXT files thoroughly
3. **Identify** patterns, issues, and dependencies
@@ -40,6 +41,7 @@ RULES: [templates | additional constraints]
## Core Requirements
**ALWAYS**:
- Run `ccw spec load` FIRST to obtain project specifications before starting any work
- Analyze ALL CONTEXT files completely
- Apply RULES (templates + constraints) exactly
- Provide code evidence with `file:line` references

View File

@@ -24,6 +24,7 @@ RULES: [templates | additional constraints]
## Execution Flow
### MODE: write
0. **Load Project Specs** - MANDATORY first step: run `ccw spec load` to retrieve project specifications and constraints before any implementation. Apply loaded specs to guide coding standards, architecture decisions, and quality gates
1. **Parse** all 6 fields (PURPOSE, TASK, MODE, CONTEXT, EXPECTED, RULES)
2. **Read** CONTEXT files, find 3+ similar patterns
3. **Plan** implementation following RULES
@@ -34,6 +35,7 @@ RULES: [templates | additional constraints]
## Core Requirements
**ALWAYS**:
- Run `ccw spec load` FIRST to obtain project specifications before starting any work
- Study CONTEXT files - find 3+ similar patterns before implementing
- Apply RULES exactly
- Test continuously (auto mode)

View File

@@ -63,6 +63,35 @@
"type": "array",
"items": {"type": "string"},
"description": "Key symbols (functions, classes, types) in this file relevant to the task. Example: ['AuthService', 'login', 'TokenPayload']"
},
"key_code": {
"type": "array",
"items": {
"type": "object",
"required": ["symbol", "description"],
"properties": {
"symbol": {
"type": "string",
"description": "Symbol identifier (function, class, method, type). Example: 'AuthService.login()'"
},
"location": {
"type": "string",
"description": "Line range in file. Example: 'L45-L78'"
},
"description": {
"type": "string",
"minLength": 10,
"description": "What this code does and why it matters. Example: 'JWT token generation with bcrypt verification, returns {token, refreshToken} pair'"
}
},
"additionalProperties": false
},
"description": "Key code constructs with descriptions. Richer complement to key_symbols. Populate for files with relevance >= 0.7."
},
"topic_relation": {
"type": "string",
"minLength": 15,
"description": "How this file relates to the exploration ANGLE/TOPIC. Must reference the angle explicitly. Example: 'Security exploration targets this file because JWT generation lacks token rotation'. Distinct from rationale (WHY selected) - topic_relation explains the CONNECTION to the exploration perspective."
}
},
"additionalProperties": false

View File

@@ -1,7 +1,7 @@
{
"$schema": "http://json-schema.org/draft-07/schema#",
"title": "Project Guidelines Schema",
"description": "Schema for project-guidelines.json - user-maintained rules and constraints",
"description": "Legacy schema - project guidelines now managed by spec system (`ccw spec load --dimension specs`)",
"type": "object",
"required": ["conventions", "constraints", "_metadata"],
"properties": {

View File

@@ -155,7 +155,7 @@
},
"development_index": {
"type": "object",
"description": "Categorized development history (lite-plan/lite-execute)",
"description": "Categorized development history (lite-planex sessions)",
"properties": {
"feature": { "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
# 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
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 --tool codex --mode review --commit <hash>
# Tag-based auto-selection (future)
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`**
- Permission: Read-only (code review output)
- Use For: Git-aware code review of uncommitted changes, branch diffs, specific commits
- Specification: **codex only** - uses `codex review` subcommand
- Tool Behavior:
- `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
- Specification: **codex only** - uses `codex review` subcommand. Other tools MUST NOT use this mode
- **Constraint**: Target flags (`--uncommitted`, `--base`, `--commit`) are **codex-only** and mutually exclusive with prompt
- 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)
@@ -309,7 +307,7 @@ ccw cli -p "..." --tool gemini --mode analysis --rule analysis-review-architectu
- **`--mode <mode>`**
- Description: **REQUIRED**: analysis, write, review
- 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>`**
- Description: Model override
@@ -446,7 +444,7 @@ ccw cli --tool codex --mode review --base main
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.
**Mode Hierarchy**:
- `analysis`: Read-only, safe for auto-execution
- `write`: Create/Modify/Delete files, full operations - requires explicit `--mode write`
- `review`: Git-aware code review (codex only), read-only output - requires explicit `--mode review`
- `analysis`: Read-only, safe for auto-execution. Available for all tools
- `write`: Create/Modify/Delete files, full operations - requires explicit `--mode write`. Available for all tools
- `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"
---

View File

@@ -711,7 +711,7 @@ All workflows use the same file structure definition regardless of complexity. *
│ ├── [.chat/] # CLI interaction sessions (created when analysis is run)
│ │ ├── chat-*.md # Saved chat sessions
│ │ └── analysis-*.md # Analysis results
│ ├── [.process/] # Planning analysis results (created by /workflow:plan)
│ ├── [.process/] # Planning analysis results (created by /workflow-plan)
│ │ └── ANALYSIS_RESULTS.md # Analysis results and planning artifacts
│ ├── IMPL_PLAN.md # Planning document (REQUIRED)
│ ├── TODO_LIST.md # Progress tracking (REQUIRED)
@@ -783,7 +783,7 @@ All workflows use the same file structure definition regardless of complexity. *
**Examples**:
*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`
> **Note**: Direct CLI commands (`/cli:analyze`, `/cli:execute`, etc.) have been replaced by semantic invocation and workflow commands.

View File

@@ -56,7 +56,23 @@ color: yellow
**Step-by-step execution**:
```
0. Load planning notes → Extract phase-level constraints (NEW)
0. Load project context (MANDATORY - from init.md products)
a. Read .workflow/project-tech.json (if exists)
→ tech_stack, architecture_type, key_components, build_system, test_framework
→ Usage: Populate plan.json shared_context, set correct build/test commands,
align task tech choices with actual project stack
→ If missing: Fall back to context-package.project_context fields
b. Read .workflow/specs/*.md (if exists)
→ coding_conventions, naming_rules, forbidden_patterns, quality_gates, custom_constraints
→ Usage: Apply as HARD CONSTRAINTS on all tasks — implementation steps,
acceptance criteria, and convergence.verification MUST respect these rules
→ If empty/missing: No additional constraints (proceed normally)
NOTE: These files provide project-level context that supplements (not replaces)
session-specific context from planning-notes.md and context-package.json.
1. Load planning notes → Extract phase-level constraints (NEW)
Commands: Read('.workflow/active/{session-id}/planning-notes.md')
Output: Consolidated constraints from all workflow phases
Structure:
@@ -67,16 +83,16 @@ color: yellow
USAGE: This is the PRIMARY source of constraints. All task generation MUST respect these constraints.
1. Load session metadata → Extract user input
2. Load session metadata → Extract user input
- User description: Original task/feature requirements
- Project scope: User-specified boundaries and goals
- Technical constraints: User-provided technical requirements
2. Load context package → Extract structured context
3. Load context package → Extract structured context
Commands: Read({{context_package_path}})
Output: Complete context package object
3. Check existing plan (if resuming)
4. Check existing plan (if resuming)
- If IMPL_PLAN.md exists: Read for continuity
- If task JSONs exist: Load for context
@@ -989,7 +1005,8 @@ Use `analysis_results.complexity` or task count to determine structure:
### 3.4 Guidelines Checklist
**ALWAYS:**
- **Load planning-notes.md FIRST**: Read planning-notes.md before context-package.json. Use its Consolidated Constraints as primary constraint source for all task generation
- **Load project context FIRST**: Read `.workflow/project-tech.json` and `.workflow/specs/*.md` before any session-specific files. Apply specs/*.md as hard constraints on all tasks
- **Load planning-notes.md SECOND**: Read planning-notes.md before context-package.json. Use its Consolidated Constraints as primary constraint source for all task generation
- **Record N+1 Context**: Update `## N+1 Context` section with key decisions and deferred items
- **Search Tool Priority**: ACE (`mcp__ace-tool__search_context`) → CCW (`mcp__ccw-tools__smart_search`) / Built-in (`Grep`, `Glob`, `Read`)
- Apply Quantification Requirements to all requirements, acceptance criteria, and modification points

View File

@@ -39,6 +39,33 @@ Phase 4: Output Generation
## Phase 1: Task Understanding
### Autonomous Initialization (execute before any analysis)
**These steps are MANDATORY and self-contained** -- the agent executes them regardless of caller prompt content. Callers do NOT need to repeat these instructions.
1. **Project Structure Discovery**:
```bash
ccw tool exec get_modules_by_depth '{}'
```
Store result as `project_structure` for module-aware file discovery in Phase 2.
2. **Output Schema Loading** (if output file path specified in prompt):
- Exploration output → `cat ~/.ccw/workflows/cli-templates/schemas/explore-json-schema.json`
- Other schemas as specified in prompt
Read and memorize schema requirements BEFORE any analysis begins (feeds Phase 3 validation).
3. **Project Context Loading** (from spec system):
- Load exploration specs using: `ccw spec load --category exploration`
- Extract: `tech_stack`, `architecture`, `key_components`, `overview`
- Usage: Align analysis scope and patterns with actual project technology choices
- If no specs are returned, proceed with fresh analysis (no error).
4. **Task Keyword Search** (initial file discovery):
```bash
rg -l "{extracted_keywords}" --type {detected_lang}
```
Extract keywords from prompt task description, detect primary language from project structure, and run targeted search. Store results as `keyword_files` for Phase 2 scoping.
**Extract from prompt**:
- Analysis target and scope
- Analysis mode (quick-scan / deep-scan / dependency-map)
@@ -96,7 +123,10 @@ RULES: {from prompt, if template specified} | analysis=READ-ONLY
2. Gemini results: Semantic understanding, design intent → `discovery_source: "cli-analysis"`
3. ACE search: Semantic code search → `discovery_source: "ace-search"`
4. Dependency tracing: Import/export graph → `discovery_source: "dependency-trace"`
5. Merge with source attribution and generate rationale for each file
5. Merge with source attribution and generate for each file:
- `rationale`: WHY the file was selected (selection basis)
- `topic_relation`: HOW the file connects to the exploration angle/topic
- `key_code`: Detailed descriptions of key symbols with locations (for relevance >= 0.7)
---
@@ -128,6 +158,12 @@ Every file entry MUST have:
- BAD: "Related to auth" or "Relevant file"
- `role` (required, enum): Structural classification of why it was selected
- `discovery_source` (optional but recommended): How the file was found
- `key_code` (strongly recommended for relevance >= 0.7): Array of {symbol, location?, description}
- GOOD: [{"symbol": "AuthService.login()", "location": "L45-L78", "description": "JWT token generation with bcrypt verification, returns token pair"}]
- BAD: [{"symbol": "login", "description": "login function"}]
- `topic_relation` (strongly recommended for relevance >= 0.7): Connection from exploration angle perspective
- GOOD: "Security exploration targets this file because JWT generation lacks token rotation"
- BAD: "Related to security"
**Step 4: Pre-Output Validation Checklist**
@@ -141,6 +177,8 @@ Before writing ANY JSON output, verify:
- [ ] Data types correct (string, integer, array, object)
- [ ] Every file in relevant_files has: path + relevance + rationale + role
- [ ] Every rationale is specific (>10 chars, not generic)
- [ ] Files with relevance >= 0.7 have key_code with symbol + description (minLength 10)
- [ ] Files with relevance >= 0.7 have topic_relation explaining connection to angle (minLength 15)
---
@@ -189,6 +227,8 @@ Brief summary:
9. **Every file MUST have rationale**: Specific selection basis tied to the topic (not generic)
10. **Every file MUST have role**: Classify as modify_target/dependency/pattern_reference/test_target/type_definition/integration_point/config/context_only
11. **Track discovery source**: Record how each file was found (bash-scan/cli-analysis/ace-search/dependency-trace/manual)
12. **Populate key_code for high-relevance files**: relevance >= 0.7 → key_code array with symbol, location, description
13. **Populate topic_relation for high-relevance files**: relevance >= 0.7 → topic_relation explaining file-to-angle connection
**Bash Tool**:
- Use `run_in_background=false` for all Bash/CLI calls to ensure foreground execution

View File

@@ -54,6 +54,9 @@ When invoked with `process_docs: true` in input context:
## Input Context
**Project Context** (loaded from spec system at startup):
- Load specs using: `ccw spec load --category "exploration architecture"` → tech_stack, architecture, key_components, conventions, constraints, quality_rules
```javascript
{
// Required
@@ -123,10 +126,11 @@ const planObject = generatePlanFromSchema(schema, context)
Phase 1: Schema & Context Loading
├─ Read schema reference (plan-overview-base-schema or plan-overview-fix-schema)
├─ 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
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)
└─ Timeout: 60 minutes
@@ -149,7 +153,7 @@ Phase 5: Plan Quality Check (MANDATORY)
│ ├─ Dependency correctness (no circular deps, proper ordering)
│ ├─ Acceptance criteria quality (quantified, testable)
│ ├─ Implementation steps sufficiency (2+ steps per task)
│ └─ Constraint compliance (follows project-guidelines.json)
│ └─ Constraint compliance (follows specs/*.md)
├─ Parse check results and categorize issues
└─ Decision:
├─ No issues → Return plan to orchestrator
@@ -170,7 +174,7 @@ TASK:
• Identify dependencies and execution phases
• Generate complexity-appropriate fields (rationale, verification, risks, code_skeleton, data_flow)
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:
## Summary
[overview]
@@ -226,9 +230,9 @@ EXPECTED:
**Total**: [time]
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)
- Complexity determines required fields:
- Complexity determines required sections:
* Low: base fields only
* Medium: + rationale + verification + design_decisions
* High: + risks + code_skeleton + data_flow
@@ -253,8 +257,8 @@ function extractSection(cliOutput, header) {
// Parse structured tasks from CLI output
function extractStructuredTasks(cliOutput, complexity) {
const tasks = []
// Split by task headers (supports both TASK-NNN and T\d+ formats)
const taskBlocks = cliOutput.split(/### (TASK-\d+|T\d+):/).slice(1)
// Split by task headers (flexible: 1-3 #, optional colon, supports TASK-NNN and T\d+)
const taskBlocks = cliOutput.split(/#{1,3}\s*(TASK-\d+|T\d+):?\s*/).slice(1)
for (let i = 0; i < taskBlocks.length; i += 2) {
const rawId = taskBlocks[i].trim()
@@ -501,7 +505,7 @@ function parseCLIOutput(cliOutput) {
```javascript
// NOTE: relevant_files items are structured objects:
// {path, relevance, rationale, role, discovery_source?, key_symbols?}
// {path, relevance, rationale, role, discovery_source?, key_symbols?, key_code?, topic_relation?}
function buildEnrichedContext(explorationsContext, explorationAngles) {
const enriched = { relevant_files: [], patterns: [], dependencies: [], integration_points: [], constraints: [] }
@@ -563,6 +567,7 @@ function inferAction(title) {
}
// NOTE: relevant_files items are structured objects with .path property
// New fields: key_code? (array of {symbol, location?, description}), topic_relation? (string)
function inferFile(task, ctx) {
const files = ctx?.relevant_files || []
const getPath = f => typeof f === 'string' ? f : f.path
@@ -816,8 +821,8 @@ function validateTask(task) {
- **Write BOTH plan.json AND .task/*.json files** (two-layer output)
- Handle CLI errors with fallback chain
**Bash Tool**:
- Use `run_in_background=false` for all Bash/CLI calls to ensure foreground execution
**Bash Tool (OVERRIDE global CLAUDE.md default)**:
- **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**:
- Execute implementation (return plan only)
@@ -846,7 +851,7 @@ After generating plan.json, **MUST** execute CLI quality check before returning
| **Dependencies** | No circular deps, correct ordering | Yes |
| **Convergence Criteria** | Quantified and testable (not vague) | No |
| **Implementation Steps** | 2+ actionable steps per task | No |
| **Constraint Compliance** | Follows project-guidelines.json | Yes |
| **Constraint Compliance** | Follows specs/*.md | Yes |
### CLI Command Format
@@ -855,7 +860,7 @@ Use `ccw cli` with analysis mode to validate plan against quality dimensions:
```bash
ccw cli -p "Validate plan quality: completeness, granularity, dependencies, convergence criteria, implementation steps, constraint compliance" \
--tool gemini --mode analysis \
--context "@{plan_json_path} @{task_dir}/*.json @.workflow/project-guidelines.json"
--context "@{plan_json_path} @{task_dir}/*.json @.workflow/specs/*.md"
```
**Expected Output Structure**:

View File

@@ -37,6 +37,8 @@ jq --arg ts "$(date -Iseconds)" '.status="in_progress" | .status_history += [{"f
- Existing documentation and code examples
- Project CLAUDE.md standards
- **context-package.json** (when available in workflow tasks)
- **project-tech.json** (if exists) → tech_stack, architecture, key_components
- **specs/*.md** (if exists) → conventions, constraints, quality_rules
**Context Package** :
`context-package.json` provides artifact paths - read using Read tool or ccw session:
@@ -453,7 +455,7 @@ function buildCliCommand(task, cliTool, cliPrompt) {
**Auto-Check Workflow Context**:
- Verify session context paths are provided in agent prompt
- If missing, request session context from workflow:execute
- If missing, request session context from workflow-execute
- Never assume default paths without explicit session context
### 5. Problem-Solving

View File

@@ -75,6 +75,20 @@ if (file_exists(contextPackagePath)) {
}
```
**1.1b Project Context Loading** (MANDATORY):
```javascript
// Load project-level context (from spec system)
// These provide foundational constraints for ALL context gathering
const projectSpecs = Bash('ccw spec load --category "exploration architecture" --stdin');
const projectTech = projectSpecs?.tech_stack ? projectSpecs : null;
const projectGuidelines = projectSpecs?.coding_conventions ? projectSpecs : null;
// Usage:
// - projectTech → Populate project_context fields (tech_stack, architecture_patterns)
// - projectGuidelines → Apply as constraints during relevance scoring and conflict detection
// - If missing: Proceed with fresh analysis (discover from codebase)
```
**1.2 Foundation Setup**:
```javascript
// 1. Initialize CodexLens (if available)
@@ -275,6 +289,10 @@ score = (0.4 × direct_match) + // Filename/path match
(0.1 × dependency_link) // Connection strength
// Filter: Include only score > 0.5
// Apply projectGuidelines constraints (from 1.1b) when available:
// - Boost files matching projectGuidelines.quality_gates patterns
// - Penalize files matching projectGuidelines.forbidden_patterns
```
**3.2 Dependency Graph**
@@ -292,19 +310,23 @@ Merge with conflict resolution:
```javascript
const context = {
// Priority: Project docs > Existing code > Web examples
architecture: ref_docs.patterns || code.structure,
// Priority: projectTech/projectGuidelines (1.1b) > Project docs > Existing code > Web examples
architecture: projectTech?.architecture_type || ref_docs.patterns || code.structure,
conventions: {
naming: ref_docs.standards || code.actual_patterns,
error_handling: ref_docs.standards || code.patterns || web.best_practices
naming: projectGuidelines?.naming_rules || ref_docs.standards || code.actual_patterns,
error_handling: ref_docs.standards || code.patterns || web.best_practices,
forbidden_patterns: projectGuidelines?.forbidden_patterns || [],
quality_gates: projectGuidelines?.quality_gates || []
},
tech_stack: {
// Actual (package.json) takes precedence
language: code.actual.language,
frameworks: merge_unique([ref_docs.declared, code.actual]),
libraries: code.actual.libraries
// projectTech provides authoritative baseline; actual (package.json) fills gaps
language: projectTech?.tech_stack?.language || code.actual.language,
frameworks: merge_unique([projectTech?.tech_stack?.frameworks, ref_docs.declared, code.actual]),
libraries: merge_unique([projectTech?.tech_stack?.libraries, code.actual.libraries]),
build_system: projectTech?.build_system || code.actual.build_system,
test_framework: projectTech?.test_framework || code.actual.test_framework
},
// Web examples fill gaps
@@ -314,9 +336,9 @@ const context = {
```
**Conflict Resolution**:
1. Architecture: Docs > Code > Web
2. Conventions: Declared > Actual > Industry
3. Tech Stack: Actual (package.json) > Declared
1. Architecture: projectTech > Docs > Code > Web
2. Conventions: projectGuidelines > Declared > Actual > Industry
3. Tech Stack: projectTech > Actual (package.json) > Declared
4. Missing: Use web examples
**3.5 Brainstorm Artifacts Integration**
@@ -381,6 +403,8 @@ Calculate risk level based on:
- Existing file count (<5: low, 5-15: medium, >15: high)
- API/architecture/data model changes
- Breaking changes identification
- Violations of projectGuidelines.forbidden_patterns (from 1.1b, if available)
- Deviations from projectGuidelines.coding_conventions (from 1.1b, if available)
**3.7 Context Packaging & Output**

View File

@@ -35,6 +35,9 @@ Phase 5: Fix & Verification
## Phase 1: Bug Analysis
**Load Project Context** (from spec system):
- Load exploration specs using: `ccw spec load --category exploration` for tech stack context and coding constraints
**Session Setup**:
```javascript
const bugSlug = bug_description.toLowerCase().replace(/[^a-z0-9]+/g, '-').substring(0, 30)

View File

@@ -26,6 +26,10 @@ color: green
### 1.1 Input Context
**Project Context** (load at startup):
- Read `.workflow/project-tech.json` (if exists) → tech_stack, architecture
- Read `.workflow/specs/*.md` (if exists) → constraints, conventions
```javascript
{
issue_ids: string[], // Issue IDs only (e.g., ["GH-123", "GH-124"])

View File

@@ -0,0 +1,501 @@
---
name: team-worker
description: |
Unified worker agent for team-lifecycle-v5. Contains all shared team behavior
(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
role_spec markdown file passed in the prompt.
Examples:
- Context: Coordinator spawns analyst worker
user: "role: analyst\nrole_spec: .claude/skills/team-lifecycle-v5/role-specs/analyst.md\nsession: .workflow/.team/TLS-xxx"
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
- 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"
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
color: green
---
You are a **team-lifecycle-v5 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.
- **Role-specific phases** (Phase 2-4): Loaded from a role_spec markdown file.
---
## Prompt Input Parsing
Parse the following fields from your prompt:
| Field | Required | Description |
|-------|----------|-------------|
| `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 |
| `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`) |
| `team_name` | Yes | Team name for SendMessage |
| `requirement` | Yes | Original task/requirement description |
| `inner_loop` | Yes | `true` or `false` — whether to loop through same-prefix tasks |
---
## Role Spec Loading
1. `Read` the file at `role_spec` path
2. Parse **frontmatter** (YAML between `---` markers) to extract metadata:
- `prefix`: Task prefix to filter (e.g., `RESEARCH`, `DRAFT`, `IMPL`)
- `inner_loop`: Override from frontmatter if present
- `discuss_rounds`: Array of discuss round IDs this role handles
- `subagents`: Array of subagent types this role may call
- `message_types`: Success/error/fix message type mappings
3. Parse **body** (content after frontmatter) to get Phase 2-4 execution instructions
4. Store parsed metadata and instructions for use in execution phases
---
## Main Execution Loop
```
Entry:
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 body → store Phase 2-4 instructions
Load wisdom files from <session>/wisdom/ (if exist)
Main Loop:
Phase 1: Task Discovery [built-in]
Phase 2-4: Execute Role Spec [from .md]
Phase 5: Report [built-in]
inner_loop AND more same-prefix tasks? → Phase 5-L → back to Phase 1
no more tasks? → Phase 5-F → STOP
```
---
## Phase 1: Task Discovery (Built-in)
Execute on every loop iteration:
1. Call `TaskList()` to get all tasks
2. **Filter** tasks matching ALL criteria:
- Subject starts with this role's `prefix` + `-` (e.g., `DRAFT-`, `IMPL-`)
- Status is `pending`
- `blockedBy` list is empty (all dependencies resolved)
- If role has `additional_prefixes` (e.g., reviewer handles REVIEW-* + QUALITY-* + IMPROVE-*), check all prefixes
3. **No matching tasks?**
- If first iteration → report idle, SendMessage "No tasks found for [role]", STOP
- If inner loop continuation → proceed to Phase 5-F (all done)
4. **Has matching tasks** → pick first by ID order
5. `TaskGet(taskId)` → read full task details
6. `TaskUpdate(taskId, status="in_progress")` → claim the task
### Resume Artifact Check
After claiming a task, check if output artifacts already exist (indicates resume after crash):
- Parse expected artifact path from task description or role_spec conventions
- Artifact exists AND appears complete → skip to Phase 5 (mark completed)
- Artifact missing or incomplete → proceed to Phase 2
---
## Phase 2-4: Role-Specific Execution
**Execute the instructions loaded from role_spec body.**
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
When role_spec instructs to call a subagent, use these templates:
**Discuss subagent** (for inline discuss rounds):
```
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>
- Perspectives: <perspective-list-from-role-spec>
- Session: <session-folder>
- Discovery Context: <session-folder>/spec/discovery-context.json
### Perspective Routing
| Perspective | CLI Tool | Role | Focus Areas |
|-------------|----------|------|-------------|
| Product | gemini | Product Manager | Market fit, user value, business viability |
| Technical | codex | Tech Lead | Feasibility, tech debt, performance, security |
| Quality | claude | QA Lead | Completeness, testability, consistency |
| Risk | gemini | Risk Analyst | Risk identification, dependencies, failure modes |
| Coverage | gemini | Requirements Analyst | Requirement completeness vs discovery-context |
### Execution Steps
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[] }`
})
```
### Consensus Handling
After a discuss subagent returns, handle the verdict:
| Verdict | Severity | Action |
|---------|----------|--------|
| consensus_reached | - | Include action items in report, proceed to Phase 5 |
| consensus_blocked | HIGH | Phase 5 SendMessage includes structured format (see below). Do NOT self-revise. |
| consensus_blocked | MEDIUM | Phase 5 SendMessage includes warning. Proceed normally. |
| consensus_blocked | LOW | Treat as consensus_reached with notes. |
**consensus_blocked SendMessage format**:
```
[<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: <session-folder>/discussions/<round-id>-discussion.md
```
---
## Phase 5: Report + Fast-Advance (Built-in)
After Phase 4 completes, determine Phase 5 variant:
### Phase 5-L: Loop Completion (when inner_loop=true AND more same-prefix tasks pending)
1. **TaskUpdate**: Mark current task `completed`
2. **Message Bus**: Log completion with verification evidence
```
mcp__ccw-tools__team_msg(
operation="log",
team=<session_id>,
from=<role>,
to="coordinator",
type=<message_types.success>,
summary="[<role>] <task-id> complete. <brief-summary>. Verified: <verification_method>",
ref=<artifact-path>
)
```
**CLI fallback**: `ccw team log --team <session_id> --from <role> --to coordinator --type <type> --summary "[<role>] ..." --json`
3. **Accumulate summary** to context_accumulator (in-memory):
```
context_accumulator.append({
task: "<task-id>",
artifact: "<output-path>",
key_decisions: <from Phase 4>,
discuss_verdict: <from Phase 4 or "none">,
discuss_rating: <from Phase 4 or null>,
summary: "<brief summary>"
})
```
4. **Interrupt check**:
- consensus_blocked HIGH → SendMessage to coordinator → STOP
- 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-F: Final Report (when no more same-prefix tasks OR inner_loop=false)
1. **TaskUpdate**: Mark current task `completed`
2. **Message Bus**: Log completion (same as Phase 5-L step 2)
3. **Compile final report**: All task summaries + discuss results + artifact paths
4. **Fast-Advance Check**:
- Call `TaskList()`, find pending tasks whose blockedBy are ALL completed
- Apply fast-advance rules (see table below)
5. **SendMessage** to coordinator OR **spawn successor** directly
### Fast-Advance Rules
| Condition | Action |
|-----------|--------|
| 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 |
| Multiple ready tasks (parallel window) | SendMessage to coordinator (needs orchestration) |
| No ready tasks + others running | SendMessage to coordinator (status update) |
| 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) |
### Fast-Advance Spawn Template
When fast-advancing to a different-prefix successor:
```
Task({
subagent_type: "team-worker",
description: "Spawn <successor-role> worker",
team_name: <team_name>,
name: "<successor-role>",
run_in_background: true,
prompt: `## Role Assignment
role: <successor-role>
role_spec: <derive from SKILL path>/role-specs/<successor-role>.md
session: <session>
session_id: <session_id>
team_name: <team_name>
requirement: <requirement>
inner_loop: <true|false based on successor role>`
})
```
### Fast-Advance Notification
After spawning a successor via fast-advance, MUST log to message bus:
```
mcp__ccw-tools__team_msg(
operation="log",
team=<session_id>,
from=<role>,
to="coordinator",
type="fast_advance",
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`.
### 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
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)
When executing Phase 2 of a role-spec, the worker MUST load available cross-role context:
| Source | Path | Load Method |
|--------|------|-------------|
| Upstream artifacts | `<session>/artifacts/*.md` | Read files listed in task description or dependency chain |
| Shared memory | `<session>/shared-memory.json` | Read and parse JSON |
| Wisdom | `<session>/wisdom/*.md` | Read all wisdom files |
| Exploration cache | `<session>/explorations/cache-index.json` | Check before new explorations |
### Downstream Context Publishing (Phase 4)
After Phase 4 verification, the worker MUST publish its contributions:
1. **Artifact**: Write deliverable to `<session>/artifacts/<prefix>-<task-id>-<name>.md`
2. **shared-memory.json**: Read-merge-write under role namespace
```json
{ "<role>": { "key_findings": [...], "decisions": [...], "files_modified": [...] } }
```
3. **Wisdom**: Append new patterns to `learnings.md`, decisions to `decisions.md`, issues to `issues.md`
### Inner Loop Context Accumulator
For `inner_loop: true` roles, `context_accumulator` is maintained in-memory:
```
context_accumulator.append({
task: "<task-id>",
artifact: "<output-path>",
key_decisions: [...],
summary: "<brief>",
files_modified: [...]
})
```
Pass the full accumulator to each subsequent task's Phase 3 subagent as `## Prior Context`.
---
## Message Bus Protocol
Always use `mcp__ccw-tools__team_msg` for logging. Parameters:
| Param | Value |
|-------|-------|
| operation | "log" |
| team | `<session_id>` (NOT team_name) |
| from | `<role>` |
| to | "coordinator" |
| type | From role_spec message_types |
| 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.
**CLI fallback** (if MCP tool unavailable):
```
ccw team log --team <session_id> --from <role> --to coordinator --type <type> --summary "[<role>] ..." --json
```
---
## Role Isolation Rules
| Allowed | Prohibited |
|---------|-----------|
| Process own prefix tasks | Process other role's prefix tasks |
| SendMessage to coordinator | Directly communicate with other workers |
| Use declared subagents (discuss, explore, doc-gen) | Create tasks for other roles |
| Fast-advance simple successors | Spawn parallel worker batches |
| Write to own artifacts + wisdom | Modify resources outside own scope |
---
## Error Handling
| Scenario | Resolution |
|----------|------------|
| 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 |
| 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 |
| No tasks found | SendMessage idle status, STOP |
| Context missing (prior doc, template) | Request from coordinator via SendMessage |
| Agent crash mid-loop | Self-healing: coordinator resets orphaned task, re-spawns |
---
## Output Tag
All output lines must be prefixed with `[<role>]` tag for coordinator message routing.

File diff suppressed because it is too large Load Diff

View File

@@ -15,28 +15,20 @@ Main process orchestrator: intent analysis → workflow selection → command ch
| Skill | 内部流水线 |
|-------|-----------|
| `workflow-lite-plan` | explore → plan → confirm → execute |
| `workflow-lite-planex` | explore → plan → confirm → execute |
| `workflow-plan` | session → context → convention → gen → verify/replan |
| `workflow-execute` | session discovery → task processing → commit |
| `workflow-tdd` | 6-phase TDD plan → verify |
| `workflow-tdd-plan` | 6-phase TDD plan → verify |
| `workflow-test-fix` | session → context → analysis → gen → cycle |
| `workflow-multi-cli-plan` | ACE context → CLI discussion → plan → execute |
| `review-cycle` | session/module review → fix orchestration |
| `brainstorm` | auto/single-role → artifacts → analysis → synthesis |
| `spec-generator` | product-brief → PRD → architecture → epics |
| `workflow:collaborative-plan-with-file` | understanding agent → parallel agents → plan-note.md |
| `workflow:req-plan-with-file` | requirement decomposition → 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:refactor-cycle` | tech debt discovery → prioritize → execute → validate |
| `team-planex` | planner + executor wave pipeline边规划边执行|
| `team-iterdev` | 迭代开发团队planner → developer → reviewer 循环)|
| `team-lifecycle` | 全生命周期团队spec → impl → test|
| `team-issue` | issue 解决团队discover → plan → execute|
| `team-testing` | 测试团队strategy → generate → execute → analyze|
| `team-quality-assurance` | QA 团队scout → strategist → generator → executor → analyst|
| `team-brainstorm` | 团队头脑风暴facilitator → participants → synthesizer|
| `team-uidesign` | UI 设计团队designer → implementer dual-track|
独立命令(仍使用 colon 格式workflow:brainstorm-with-file, workflow:debug-with-file, workflow:analyze-with-file, workflow:collaborative-plan-with-file, workflow:req-plan-with-file, workflow:integration-test-cycle, workflow:refactor-cycle, workflow:unified-execute-with-file, workflow:clean, workflow:init, workflow:init-guidelines, workflow:ui-design:*, issue:*, workflow:session:*
| `team-planex` | planner + executor wave pipeline适合大量零散 issue 或 roadmap 产出的清晰 issue|
## Core Concept: Self-Contained Skills (自包含 Skill)
@@ -51,24 +43,21 @@ Main process orchestrator: intent analysis → workflow selection → command ch
| 单元类型 | Skill | 说明 |
|---------|-------|------|
| 轻量 Plan+Execute | `workflow-lite-plan` | 内部完成 plan→execute |
| 轻量 Plan+Execute | `workflow-lite-planex` | 内部完成 plan→execute |
| 标准 Planning | `workflow-plan``workflow-execute` | plan 和 execute 是独立 Skill |
| TDD Planning | `workflow-tdd``workflow-execute` | tdd-plan 和 execute 是独立 Skill |
| TDD Planning | `workflow-tdd-plan``workflow-execute` | tdd-plan 和 execute 是独立 Skill |
| 规格驱动 | `spec-generator``workflow-plan``workflow-execute` | 规格文档驱动完整开发 |
| 测试流水线 | `workflow-test-fix` | 内部完成 gen→cycle |
| 代码审查 | `review-cycle` | 内部完成 review→fix |
| 多CLI协作 | `workflow-multi-cli-plan` | ACE context → CLI discussion → plan → execute |
| 协作规划 | `workflow:collaborative-plan-with-file` | 多 agent 协作生成 plan-note.md |
| 需求路线图 | `workflow:req-plan-with-file` | 需求拆解→issue 创建→执行计划 |
| 分析→规划 | `workflow:analyze-with-file``workflow-lite-planex` | 协作分析产物自动传递给 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:roadmap-with-file``team-planex` | 需求拆解→issue 创建→wave pipeline 执行(需明确 roadmap 关键词)|
| 集成测试循环 | `workflow:integration-test-cycle` | 自迭代集成测试闭环 |
| 重构循环 | `workflow:refactor-cycle` | 技术债务发现→重构→验证 |
| 团队 Plan+Execute | `team-planex` | 2 人团队 wave pipeline边规划边执行 |
| 团队迭代开发 | `team-iterdev` | 多角色迭代开发闭环 |
| 团队全生命周期 | `team-lifecycle` | spec→impl→test 全流程 |
| 团队 Issue | `team-issue` | 多角色协作 issue 解决 |
| 团队测试 | `team-testing` | 多角色测试流水线 |
| 团队 QA | `team-quality-assurance` | 多角色质量保障闭环 |
| 团队头脑风暴 | `team-brainstorm` | 多角色协作头脑风暴 |
| 团队 UI 设计 | `team-uidesign` | dual-track 设计+实现 |
## Execution Model
@@ -136,27 +125,23 @@ function analyzeIntent(input) {
function detectTaskType(text) {
const patterns = {
'bugfix-hotfix': /urgent|production|critical/ && /fix|bug/,
// With-File workflows (documented exploration with multi-CLI collaboration)
// 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-to-issue': /brainstorm.*issue|头脑风暴.*issue|idea.*issue|想法.*issue|从.*头脑风暴|convert.*brainstorm/,
'debug-file': /debug.*document|hypothesis.*debug|troubleshoot.*track|investigate.*log|调试.*记录|假设.*验证|systematic debug|深度调试/,
'analyze-file': /analyze.*document|explore.*concept|understand.*architecture|investigate.*discuss|collaborative analysis|分析.*讨论|深度.*理解|协作.*分析/,
'collaborative-plan': /collaborative.*plan|协作.*规划|多人.*规划|multi.*agent.*plan|Plan Note|分工.*规划/,
'req-plan': /roadmap|需求.*规划|需求.*拆解|requirement.*plan|req.*plan|progressive.*plan|路线.*图/,
'roadmap': /roadmap|路线.*图/, // Narrowed: only explicit roadmap keywords (需求规划/需求拆解 moved to greenfield routing)
'spec-driven': /spec.*gen|specification|PRD|产品需求|产品文档|产品规格/,
// Cycle workflows (self-iterating with reflection)
'integration-test': /integration.*test|集成测试|端到端.*测试|e2e.*test|integration.*cycle/,
'refactor': /refactor|重构|tech.*debt|技术债务/,
// Team workflows (multi-role collaboration, explicit "team" keyword required)
// Team workflows (kept: team-planex only)
'team-planex': /team.*plan.*exec|team.*planex|团队.*规划.*执行|并行.*规划.*执行|wave.*pipeline/,
'team-iterdev': /team.*iter|team.*iterdev|迭代.*开发.*团队|iterative.*dev.*team/,
'team-lifecycle': /team.*lifecycle|全生命周期|full.*lifecycle|spec.*impl.*test.*team/,
'team-issue': /team.*issue.*resolv|团队.*issue|team.*resolve.*issue/,
'team-testing': /team.*test|测试团队|comprehensive.*test.*team|全面.*测试.*团队/,
'team-qa': /team.*qa|quality.*assurance.*team|QA.*团队|质量.*保障.*团队|团队.*质量/,
'team-brainstorm': /team.*brainstorm|团队.*头脑风暴|team.*ideation|多人.*头脑风暴/,
'team-uidesign': /team.*ui.*design|UI.*设计.*团队|dual.*track.*design|团队.*UI/,
// Standard workflows
'multi-cli-plan': /multi.*cli|多.*CLI|多模型.*协作|multi.*model.*collab/,
'multi-cli': /multi.*cli|多.*CLI|多模型.*协作|multi.*model.*collab/,
'bugfix': /fix|bug|error|crash|fail|debug/,
'issue-batch': /issues?|batch/ && /fix|resolve/,
'issue-transition': /issue workflow|structured workflow|queue|multi-stage/,
@@ -165,6 +150,7 @@ function detectTaskType(text) {
'ui-design': /ui|design|component|style/,
'tdd': /tdd|test-driven|test first/,
'test-fix': /test fail|fix test|failing test/,
'test-gen': /generate test|写测试|add test|补充测试/,
'review': /review|code review/,
'documentation': /docs|documentation|readme/
};
@@ -202,34 +188,34 @@ async function clarifyRequirements(analysis) {
function selectWorkflow(analysis) {
const levelMap = {
'bugfix-hotfix': { level: 2, flow: 'bugfix.hotfix' },
// With-File workflows (documented exploration with multi-CLI collaboration)
'brainstorm': { level: 4, flow: 'brainstorm-with-file' }, // Multi-perspective ideation
'brainstorm-to-issue': { level: 4, flow: 'brainstorm-to-issue' }, // Brainstorm → Issue workflow
'debug-file': { level: 3, flow: 'debug-with-file' }, // Hypothesis-driven debugging
'analyze-file': { level: 3, flow: 'analyze-with-file' }, // Collaborative analysis
// 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
'brainstorm': { level: 4, flow: 'brainstorm-to-plan' }, // brainstorm-with-file → workflow-plan
'brainstorm-to-issue': { level: 4, flow: 'brainstorm-to-issue' }, // Brainstorm → Issue workflow
'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
'collaborative-plan': { level: 3, flow: 'collaborative-plan' }, // Multi-agent collaborative planning
'req-plan': { level: 4, flow: 'req-plan' }, // Requirement-level roadmap planning
'roadmap': { level: 4, flow: 'roadmap' }, // roadmap → team-planex (explicit roadmap only)
'spec-driven': { level: 4, flow: 'spec-driven' }, // spec-generator → plan → execute
// Cycle workflows (self-iterating with reflection)
'integration-test': { level: 3, flow: 'integration-test-cycle' }, // Self-iterating integration test
'refactor': { level: 3, flow: 'refactor-cycle' }, // Tech debt discovery and refactoring
// Team workflows (multi-role collaboration)
'integration-test': { level: 3, flow: 'integration-test-cycle' },
'refactor': { level: 3, flow: 'refactor-cycle' },
// Team workflows (kept: team-planex only)
'team-planex': { level: 'Team', flow: 'team-planex' },
'team-iterdev': { level: 'Team', flow: 'team-iterdev' },
'team-lifecycle': { level: 'Team', flow: 'team-lifecycle' },
'team-issue': { level: 'Team', flow: 'team-issue' },
'team-testing': { level: 'Team', flow: 'team-testing' },
'team-qa': { level: 'Team', flow: 'team-qa' },
'team-brainstorm': { level: 'Team', flow: 'team-brainstorm' },
'team-uidesign': { level: 'Team', flow: 'team-uidesign' },
// Standard workflows
'multi-cli-plan': { level: 3, flow: 'multi-cli-plan' }, // Multi-CLI collaborative planning
'multi-cli': { level: 3, flow: 'multi-cli-plan' },
'bugfix': { level: 2, flow: 'bugfix.standard' },
'issue-batch': { level: 'Issue', flow: 'issue' },
'issue-transition': { level: 2.5, flow: 'rapid-to-issue' }, // Bridge workflow
'issue-transition': { level: 2.5, flow: 'rapid-to-issue' },
'exploration': { level: 4, flow: 'full' },
'quick-task': { level: 2, flow: 'rapid' },
'ui-design': { level: analysis.complexity === 'high' ? 4 : 3, flow: 'ui' },
'tdd': { level: 3, flow: 'tdd' },
'test-gen': { level: 3, flow: 'test-gen' },
'test-fix': { level: 3, flow: 'test-fix-gen' },
'review': { level: 3, flow: 'review-cycle-fix' },
'documentation': { level: 2, flow: 'docs' },
@@ -245,7 +231,7 @@ function buildCommandChain(workflow, analysis) {
const chains = {
// Level 2 - Lightweight
'rapid': [
{ cmd: 'workflow-lite-plan', args: `"${analysis.goal}"` },
{ cmd: 'workflow-lite-planex', args: `"${analysis.goal}"` },
...(analysis.constraints?.includes('skip-tests') ? [] : [
{ cmd: 'workflow-test-fix', args: '' }
])
@@ -253,21 +239,21 @@ function buildCommandChain(workflow, analysis) {
// Level 2 Bridge - Lightweight to Issue Workflow
'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:queue', args: '' },
{ cmd: 'issue:execute', args: '--queue auto' }
],
'bugfix.standard': [
{ cmd: 'workflow-lite-plan', args: `--bugfix "${analysis.goal}"` },
{ cmd: 'workflow-lite-planex', args: `--bugfix "${analysis.goal}"` },
...(analysis.constraints?.includes('skip-tests') ? [] : [
{ cmd: 'workflow-test-fix', args: '' }
])
],
'bugfix.hotfix': [
{ cmd: 'workflow-lite-plan', args: `--hotfix "${analysis.goal}"` }
{ cmd: 'workflow-lite-planex', args: `--hotfix "${analysis.goal}"` }
],
'multi-cli-plan': [
@@ -278,21 +264,22 @@ function buildCommandChain(workflow, analysis) {
],
'docs': [
{ cmd: 'workflow-lite-plan', args: `"${analysis.goal}"` }
{ cmd: 'workflow-lite-planex', args: `"${analysis.goal}"` }
],
// With-File workflows (documented exploration with multi-CLI collaboration)
'brainstorm-with-file': [
{ cmd: 'workflow:brainstorm-with-file', args: `"${analysis.goal}"` }
// Note: Has built-in post-completion options (create plan, create issue, deep analysis)
// With-File → Auto Chain to lite-plan
'analyze-to-plan': [
{ cmd: 'workflow:analyze-with-file', args: `"${analysis.goal}"` },
{ cmd: 'workflow-lite-planex', args: '' } // auto receives analysis artifacts (discussion.md)
],
// Brainstorm-to-Issue workflow (bridge from brainstorm to issue execution)
'brainstorm-to-issue': [
// Note: Assumes brainstorm session already exists, or run brainstorm first
{ cmd: 'issue:from-brainstorm', args: `SESSION="${extractBrainstormSession(analysis)}" --auto` },
{ cmd: 'issue:queue', args: '' },
{ cmd: 'issue:execute', args: '--queue auto' }
'brainstorm-to-plan': [
{ cmd: 'workflow:brainstorm-with-file', args: `"${analysis.goal}"` },
{ 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': [
@@ -300,32 +287,42 @@ function buildCommandChain(workflow, analysis) {
// Note: Self-contained with hypothesis-driven iteration and Gemini validation
],
'analyze-with-file': [
{ cmd: 'workflow:analyze-with-file', args: `"${analysis.goal}"` }
// Note: Self-contained with multi-round discussion and CLI exploration
// Brainstorm-to-Issue workflow (bridge from brainstorm to issue execution)
'brainstorm-to-issue': [
{ cmd: 'issue:from-brainstorm', args: `SESSION="${extractBrainstormSession(analysis)}" --auto` },
{ cmd: 'issue:queue', args: '' },
{ 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
'collaborative-plan': [
{ cmd: 'workflow:collaborative-plan-with-file', args: `"${analysis.goal}"` },
{ cmd: 'workflow:unified-execute-with-file', args: '' }
// Note: Plan Note → unified execution engine
],
'req-plan': [
{ cmd: 'workflow:req-plan-with-file', args: `"${analysis.goal}"` },
'roadmap': [
{ cmd: 'workflow:roadmap-with-file', args: `"${analysis.goal}"` },
{ cmd: 'team-planex', args: '' }
// Note: Requirement decomposition → issue creation → team-planex wave execution
],
// Cycle workflows (self-iterating with reflection)
'integration-test-cycle': [
{ cmd: 'workflow:integration-test-cycle', args: `"${analysis.goal}"` }
// Note: Self-contained explore → test → fix cycle with reflection
],
'refactor-cycle': [
{ cmd: 'workflow:refactor-cycle', args: `"${analysis.goal}"` }
// Note: Self-contained tech debt discovery → refactor → validate
],
// Level 3 - Standard
@@ -338,11 +335,25 @@ function buildCommandChain(workflow, analysis) {
])
],
// Level 4 - Spec-Driven Full Pipeline
'spec-driven': [
{ cmd: 'spec-generator', args: `"${analysis.goal}"` },
{ cmd: 'workflow-plan', args: '' },
{ cmd: 'workflow-execute', args: '' },
...(analysis.constraints?.includes('skip-tests') ? [] : [
{ cmd: 'workflow-test-fix', args: '' }
])
],
'tdd': [
{ cmd: 'workflow-tdd', args: `"${analysis.goal}"` },
{ cmd: 'workflow-tdd-plan', args: `"${analysis.goal}"` },
{ cmd: 'workflow-execute', args: '' }
],
'test-gen': [
{ cmd: 'workflow-test-fix', args: `"${analysis.goal}"` }
],
'test-fix-gen': [
{ cmd: 'workflow-test-fix', args: `"${analysis.goal}"` }
],
@@ -360,7 +371,7 @@ function buildCommandChain(workflow, analysis) {
{ cmd: 'workflow-execute', args: '' }
],
// Level 4 - Full
// Level 4 - Full Exploration (brainstorm → formal planning → execute)
'full': [
{ cmd: 'brainstorm', args: `"${analysis.goal}"` },
{ cmd: 'workflow-plan', args: '' },
@@ -370,6 +381,15 @@ function buildCommandChain(workflow, analysis) {
])
],
// Cycle workflows (self-iterating with reflection)
'integration-test-cycle': [
{ cmd: 'workflow:integration-test-cycle', args: `"${analysis.goal}"` }
],
'refactor-cycle': [
{ cmd: 'workflow:refactor-cycle', args: `"${analysis.goal}"` }
],
// Issue Workflow
'issue': [
{ cmd: 'issue:discover', args: '' },
@@ -378,37 +398,9 @@ function buildCommandChain(workflow, analysis) {
{ cmd: 'issue:execute', args: '' }
],
// Team Workflows (multi-role collaboration, self-contained)
// Team Workflows (kept: team-planex only)
'team-planex': [
{ cmd: 'team-planex', args: `"${analysis.goal}"` }
],
'team-iterdev': [
{ cmd: 'team-iterdev', args: `"${analysis.goal}"` }
],
'team-lifecycle': [
{ cmd: 'team-lifecycle', args: `"${analysis.goal}"` }
],
'team-issue': [
{ cmd: 'team-issue', args: `"${analysis.goal}"` }
],
'team-testing': [
{ cmd: 'team-testing', args: `"${analysis.goal}"` }
],
'team-qa': [
{ cmd: 'team-quality-assurance', args: `"${analysis.goal}"` }
],
'team-brainstorm': [
{ cmd: 'team-brainstorm', args: `"${analysis.goal}"` }
],
'team-uidesign': [
{ cmd: 'team-uidesign', args: `"${analysis.goal}"` }
]
};
@@ -484,7 +476,7 @@ function setupTodoTracking(chain, workflow, analysis) {
```
**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`
---
@@ -607,7 +599,7 @@ Phase 1: Analyze Intent
+-- If clarity < 2 -> Phase 1.5: Clarify Requirements
|
Phase 2: Select Workflow & Build Chain
|-- Map task_type -> Level (1/2/3/4/Issue)
|-- Map task_type -> Level (2/3/4/Issue/Team)
|-- Select flow based on complexity
+-- Build command chain (Skill-based)
|
@@ -636,29 +628,25 @@ Phase 5: Execute Command Chain
| Input | Type | Level | Pipeline |
|-------|------|-------|----------|
| "Add API endpoint" | feature (low) | 2 | workflow-lite-plan → workflow-test-fix |
| "Fix login timeout" | bugfix | 2 | workflow-lite-plan → workflow-test-fix |
| "Use issue workflow" | issue-transition | 2.5 | workflow-lite-plan(plan-only) → convert-to-plan → queue → execute |
| "头脑风暴: 通知系统重构" | brainstorm | 4 | workflow:brainstorm-with-file |
| "从头脑风暴创建 issue" | brainstorm-to-issue | 4 | issue:from-brainstorm → issue:queue → issue:execute |
| "Add API endpoint" | feature (low) | 2 | workflow-lite-planex → workflow-test-fix |
| "Fix login timeout" | bugfix | 2 | workflow-lite-planex → workflow-test-fix |
| "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-planex |
| "深度调试 WebSocket" | debug-file | 3 | workflow:debug-with-file |
| "协作分析: 认证架构优化" | analyze-file | 3 | workflow:analyze-with-file |
| "从零开始: 用户系统" | 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 |
| "协作规划: 实时通知系统" | collaborative-plan | 3 | collaborative-plan-with-file → unified-execute-with-file |
| "需求规划: OAuth + 2FA" | req-plan | 4 | req-plan-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 |
| "集成测试: 支付流程" | integration-test | 3 | workflow:integration-test-cycle |
| "重构 auth 模块" | refactor | 3 | workflow:refactor-cycle |
| "multi-cli plan: API设计" | multi-cli-plan | 3 | workflow-multi-cli-plan → workflow-test-fix |
| "OAuth2 system" | feature (high) | 3 | workflow-plan → workflow-execute → review-cycle → workflow-test-fix |
| "Implement with TDD" | tdd | 3 | workflow-tdd → workflow-execute |
| "Implement with TDD" | tdd | 3 | workflow-tdd-plan → workflow-execute |
| "Uncertain: real-time" | exploration | 4 | brainstorm → workflow-plan → workflow-execute → workflow-test-fix |
| "team planex: 用户系统" | team-planex | Team | team-planex |
| "迭代开发团队: 支付模块" | team-iterdev | Team | team-iterdev |
| "全生命周期: 通知服务" | team-lifecycle | Team | team-lifecycle |
| "team resolve issue #42" | team-issue | Team | team-issue |
| "测试团队: 全面测试认证" | team-testing | Team | team-testing |
| "QA 团队: 质量保障支付" | team-qa | Team | team-quality-assurance |
| "团队头脑风暴: API 设计" | team-brainstorm | Team | team-brainstorm |
| "团队 UI 设计: 仪表盘" | team-uidesign | Team | team-uidesign |
---
@@ -668,10 +656,11 @@ Phase 5: Execute Command Chain
2. **Intent-Driven** - Auto-select workflow based on task intent
3. **Skill-Based Chaining** - Build command chain by composing independent Skills
4. **Self-Contained Skills** - 每个 Skill 内部处理完整流水线,是天然的最小执行单元
5. **Progressive Clarification** - Low clarity triggers clarification phase
6. **TODO Tracking** - Use CCW prefix to isolate workflow todos
7. **Error Handling** - Retry/skip/abort at Skill level
8. **User Control** - Optional user confirmation at each phase
5. **Auto Chain** - With-File 产物自动传递给下游 Skill如 analyze → lite-plan
6. **Progressive Clarification** - Low clarity triggers clarification phase
7. **TODO Tracking** - Use CCW prefix to isolate workflow todos
8. **Error Handling** - Retry/skip/abort at Skill level
9. **User Control** - Optional user confirmation at each phase
---
@@ -684,13 +673,13 @@ Phase 5: Execute Command Chain
```javascript
// Initial state (rapid workflow: 2 steps)
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" }
];
// After step 1 completes
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" }
];
```
@@ -715,114 +704,51 @@ todos = [
"complexity": "medium"
},
"command_chain": [
{
"index": 0,
"command": "workflow-lite-plan",
"status": "completed"
},
{
"index": 1,
"command": "workflow-test-fix",
"status": "running"
}
{ "index": 0, "command": "workflow-lite-planex", "status": "completed" },
{ "index": 1, "command": "workflow-test-fix", "status": "running" }
],
"current_index": 1
}
```
**Status Values**:
- `running`: Workflow executing commands
- `completed`: All commands finished
- `failed`: User aborted or unrecoverable error
- `error`: Command execution failed (during error handling)
**Command Status Values**:
- `pending`: Not started
- `running`: Currently executing
- `completed`: Successfully finished
- `failed`: Execution failed
**Status Values**: `running` | `completed` | `failed` | `error`
**Command Status Values**: `pending` | `running` | `completed` | `failed`
---
## With-File Workflows
**With-File workflows** provide documented exploration with multi-CLI collaboration. They are self-contained and generate comprehensive session artifacts.
**With-File workflows** provide documented exploration with multi-CLI collaboration. They generate comprehensive session artifacts and can auto-chain to lite-plan for implementation.
| Workflow | Purpose | Key Features | Output Folder |
|----------|---------|--------------|---------------|
| **brainstorm-with-file** | Multi-perspective ideation | Gemini/Codex/Claude perspectives, diverge-converge cycles | `.workflow/.brainstorm/` |
| **debug-with-file** | Hypothesis-driven debugging | Gemini validation, understanding evolution, NDJSON logging | `.workflow/.debug/` |
| **analyze-with-file** | Collaborative analysis | Multi-round Q&A, CLI exploration, documented discussions | `.workflow/.analysis/` |
| **collaborative-plan-with-file** | Multi-agent collaborative planning | Understanding agent + parallel agents, Plan Note shared doc | `.workflow/.planning/` |
| **req-plan-with-file** | Requirement roadmap planning | Requirement decomposition, issue creation, execution-plan.json | `.workflow/.planning/` |
| Workflow | Purpose | Auto Chain | Output Folder |
|----------|---------|------------|---------------|
| **brainstorm-with-file** | Multi-perspective ideation | → workflow-plan → workflow-execute (auto) | `.workflow/.brainstorm/` |
| **debug-with-file** | Hypothesis-driven debugging | Standalone (self-contained) | `.workflow/.debug/` |
| **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/` |
| **roadmap-with-file** | Strategic requirement roadmap | → team-planex | `.workflow/.planning/` |
**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**:
- **brainstorm**: 头脑风暴, 创意, 发散思维, multi-perspective, compare perspectives
- **debug-file**: 深度调试, 假设验证, systematic debug, hypothesis debug
- **analyze-file**: 协作分析, 深度理解, collaborative analysis, explore concept
- **collaborative-plan**: 协作规划, 多人规划, collaborative plan, multi-agent plan, Plan Note
- **req-plan**: roadmap, 需求规划, 需求拆解, requirement plan, progressive plan
**Characteristics**:
1. **Self-Contained**: Each workflow handles its own iteration loop
2. **Documented Process**: Creates evolving documents (brainstorm.md, understanding.md, discussion.md)
3. **Multi-CLI**: Uses Gemini/Codex/Claude for different perspectives
4. **Built-in Post-Completion**: Offers follow-up options (create plan, issue, etc.)
---
## Team Workflows
**Team workflows** provide multi-role collaboration for complex tasks. Each team skill is self-contained with internal role routing via `--role=xxx`.
| Workflow | Roles | Pipeline | Use Case |
|----------|-------|----------|----------|
| **team-planex** | planner + executor | wave pipeline边规划边执行| 需要并行规划和执行的任务 |
| **team-iterdev** | planner → developer → reviewer | 迭代开发循环 | 需要多轮迭代的开发任务 |
| **team-lifecycle** | spec → impl → test | 全生命周期 | 从需求到测试的完整流程 |
| **team-issue** | discover → plan → execute | issue 解决 | 多角色协作解决 issue |
| **team-testing** | strategy → generate → execute → analyze | 测试流水线 | 全面测试覆盖 |
| **team-quality-assurance** | scout → strategist → generator → executor → analyst | QA 闭环 | 质量保障全流程 |
| **team-brainstorm** | facilitator → participants → synthesizer | 团队头脑风暴 | 多角色协作头脑风暴 |
| **team-uidesign** | designer → implementer | dual-track 设计+实现 | UI 设计与实现并行 |
**Detection Keywords**:
- **team-planex**: team planex, 团队规划执行, wave pipeline
- **team-iterdev**: team iterdev, 迭代开发团队, iterative dev team
- **team-lifecycle**: team lifecycle, 全生命周期, full lifecycle
- **team-issue**: team issue, 团队 issue, team resolve issue
- **team-testing**: team test, 测试团队, comprehensive test team
- **team-qa**: team qa, QA 团队, 质量保障团队
- **team-brainstorm**: team brainstorm, 团队头脑风暴, team ideation
- **team-uidesign**: team ui design, UI 设计团队, dual track design
**Characteristics**:
1. **Self-Contained**: Each team skill handles internal role coordination
2. **Role-Based Routing**: All roles invoke the same skill with `--role=xxx`
3. **Shared Memory**: Roles communicate via shared-memory.json and message bus
4. **Auto Mode Support**: All team skills support `-y`/`--yes` for skip confirmations
- **roadmap**: roadmap, 需求规划, 需求拆解, requirement plan, progressive plan
- **spec-driven**: specification, PRD, 产品需求, 产品文档
---
## Cycle Workflows
**Cycle workflows** provide self-iterating development cycles with reflection-driven strategy adjustment. Each cycle is autonomous with built-in test-fix loops and quality gates.
**Cycle workflows** provide self-iterating development cycles with reflection-driven strategy adjustment.
| Workflow | Pipeline | Key Features | Output Folder |
|----------|----------|--------------|---------------|
| **integration-test-cycle** | explore → test dev → test-fix → reflection | Self-iterating with max-iterations, auto continue | `.workflow/.test-cycle/` |
| **refactor-cycle** | discover → prioritize → execute → validate | Multi-dimensional analysis, regression validation | `.workflow/.refactor-cycle/` |
**Detection Keywords**:
- **integration-test**: integration test, 集成测试, 端到端测试, e2e test
- **refactor**: refactor, 重构, tech debt, 技术债务
**Characteristics**:
1. **Self-Iterating**: Autonomous test-fix loops until quality gate passes
2. **Reflection-Driven**: Strategy adjusts based on previous iteration results
3. **Continue Support**: `--continue` flag to resume interrupted sessions
4. **Auto Mode Support**: `-y`/`--yes` for fully autonomous execution
---
## Utility Commands
@@ -831,10 +757,11 @@ todos = [
| Command | Purpose |
|---------|---------|
| `workflow:unified-execute-with-file` | Universal execution engine - consumes plan output from collaborative-plan, req-plan, brainstorm |
| `workflow:unified-execute-with-file` | Universal execution engine - consumes plan output from collaborative-plan, roadmap, brainstorm |
| `workflow:clean` | Intelligent code cleanup - mainline detection, stale artifact removal |
| `workflow:init` | Initialize `.workflow/project-tech.json` with project analysis |
| `workflow:init-guidelines` | Interactive wizard to fill `project-guidelines.json` |
| `workflow:init-guidelines` | Interactive wizard to fill `specs/*.md` |
| `workflow:status` | Generate on-demand views for project overview and workflow tasks |
---
@@ -848,9 +775,6 @@ todos = [
/ccw -y "Add user authentication"
/ccw --yes "Fix memory leak in WebSocket handler"
# Complex requirement (triggers clarification)
/ccw "Optimize system performance"
# Bug fix
/ccw "Fix memory leak in WebSocket handler"
@@ -863,35 +787,36 @@ todos = [
# Multi-CLI collaborative planning
/ccw "multi-cli plan: 支付网关API设计" # → workflow-multi-cli-plan → workflow-test-fix
# With-File workflows (documented exploration with multi-CLI collaboration)
/ccw "头脑风暴: 用户通知系统重新设计" # → brainstorm-with-file
/ccw "从头脑风暴 BS-通知系统-2025-01-28 创建 issue" # → brainstorm-to-issue (bridge)
/ccw "深度调试: 系统随机崩溃问题" # → debug-with-file
/ccw "协作分析: 理解现有认证架构的设计决策" # → analyze-with-file
# 0→1 Greenfield development (exploration-first)
/ccw "从零开始: 用户认证系统" # → brainstorm-with-file → workflow-plan → workflow-execute → workflow-test-fix
/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
# Team workflows (multi-role collaboration)
/ccw "team planex: 用户认证系统" # → team-planex (planner + executor wave pipeline)
/ccw "迭代开发团队: 支付模块重构" # → team-iterdev (planner → developer → reviewer)
/ccw "全生命周期: 通知服务开发" # → team-lifecycle (spec → impl → test)
/ccw "team resolve issue #42" # → team-issue (discover → plan → execute)
/ccw "测试团队: 全面测试认证模块" # → team-testing (strategy → generate → execute → analyze)
/ccw "QA 团队: 质量保障支付流程" # → team-quality-assurance (scout → strategist → generator → executor → analyst)
/ccw "团队头脑风暴: API 网关设计" # → team-brainstorm (facilitator → participants → synthesizer)
/ccw "团队 UI 设计: 管理后台仪表盘" # → team-uidesign (designer → implementer dual-track)
# 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 "从头脑风暴 BS-通知系统-2025-01-28 创建 issue" # → brainstorm-to-issue (bridge)
# Spec-driven full pipeline
/ccw "specification: 用户认证系统产品文档" # → spec-generator → workflow-plan → workflow-execute → workflow-test-fix
# Collaborative planning & requirement workflows
/ccw "协作规划: 实时通知系统架构" # → collaborative-plan-with-file → unified-execute
/ccw "需求规划: 用户认证 OAuth + 2FA" # → req-plan-with-file → team-planex
/ccw "roadmap: 数据导出功能路线图" # → req-plan-with-file → team-planex
/ccw "roadmap: 用户认证 OAuth + 2FA 路线图" # → roadmap-with-file → team-planex (explicit roadmap only)
/ccw "roadmap: 数据导出功能路线图" # → roadmap-with-file → team-planex (explicit roadmap only)
# Team workflows (kept: team-planex)
/ccw "team planex: 用户认证系统" # → team-planex (planner + executor wave pipeline)
# Cycle workflows (self-iterating)
/ccw "集成测试: 支付流程端到端" # → integration-test-cycle
/ccw "重构 auth 模块的技术债务" # → refactor-cycle
/ccw "tech debt: 清理支付服务" # → refactor-cycle
# Utility commands (invoked directly, not auto-routed)
# /workflow:unified-execute-with-file # 通用执行引擎(消费 plan 输出)
# /workflow:clean # 智能代码清理
# /workflow:init # 初始化项目状态
# /workflow:init-guidelines # 交互式填充项目规范
# /workflow:status # 项目概览和工作流状态
```

View File

@@ -33,7 +33,7 @@ Creates tool-specific configuration directories:
- `.gemini/settings.json`:
```json
{
"contextfilename": ["CLAUDE.md","GEMINI.md"]
"contextfilename": "CLAUDE.md"
}
```
@@ -41,7 +41,7 @@ Creates tool-specific configuration directories:
- `.qwen/settings.json`:
```json
{
"contextfilename": ["CLAUDE.md","QWEN.md"]
"contextfilename": "CLAUDE.md"
}
```
@@ -378,7 +378,7 @@ docker-compose.override.yml
## Integration Points
### 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
### CLI Tool Integration

View File

@@ -86,7 +86,7 @@ async function selectCommandCategory() {
header: "Category",
options: [
{ 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: "Review", description: "review-session-cycle, review-module-cycle, review-cycle-fix" },
{ label: "Bug Fix", description: "lite-plan --bugfix, debug-with-file" },
@@ -107,24 +107,23 @@ async function selectCommandCategory() {
async function selectCommand(category) {
const commandOptions = {
'Planning': [
{ label: "/workflow:lite-plan", description: "Lightweight merged-mode planning" },
{ label: "/workflow:plan", description: "Full planning with architecture design" },
{ 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-lite-planex", description: "Lightweight merged-mode planning" },
{ label: "/workflow-plan", description: "Full planning with architecture design" },
{ 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:quick-plan-with-file", description: "Rapid planning with minimal docs" },
{ label: "/workflow:plan-verify", description: "Verify plan against requirements" },
{ label: "/workflow-plan-verify", description: "Verify plan against requirements" },
{ label: "/workflow:replan", description: "Update plan and execute changes" }
],
'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" }
],
'Testing': [
{ label: "/workflow:test-fix-gen", description: "Generate test tasks for specific issues" },
{ label: "/workflow:test-cycle-execute", description: "Execute iterative test-fix cycle (>=95% pass)" },
{ label: "/workflow-test-fix", description: "Generate test tasks for specific issues" },
{ label: "/workflow-test-fix", description: "Execute iterative test-fix cycle (>=95% pass)" },
{ label: "/workflow:test-gen", description: "Generate comprehensive test suite" },
{ label: "/workflow:tdd-verify", description: "Verify TDD workflow compliance" }
{ label: "/workflow-tdd-verify", description: "Verify TDD workflow compliance" }
],
'Review': [
{ label: "/workflow:review-session-cycle", description: "Session-based multi-dimensional code review" },
@@ -133,7 +132,7 @@ async function selectCommand(category) {
{ label: "/workflow:review", description: "Post-implementation review" }
],
'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" }
],
'Brainstorm': [
@@ -181,8 +180,8 @@ async function selectExecutionUnit() {
header: "Unit",
options: [
// Planning + Execution Units
{ label: "quick-implementation", description: "【lite-plan → lite-execute】" },
{ label: "multi-cli-planning", description: "【multi-cli-plan → lite-execute】" },
{ label: "quick-implementation", description: "【lite-plan】" },
{ label: "multi-cli-planning", description: "【multi-cli-plan】" },
{ label: "full-planning-execution", description: "【plan → execute】" },
{ label: "verified-planning-execution", description: "【plan → plan-verify → execute】" },
{ label: "replanning-execution", description: "【replan → execute】" },
@@ -193,7 +192,7 @@ async function selectExecutionUnit() {
// Review Units
{ label: "code-review", description: "【review-*-cycle → review-cycle-fix】" },
// Bug Fix Units
{ label: "bug-fix", description: "【lite-plan --bugfix → lite-execute】" },
{ label: "bug-fix", description: "【lite-plan --bugfix】" },
// Issue Units
{ label: "issue-workflow", description: "【discover → plan → queue → execute】" },
{ label: "rapid-to-issue", description: "【lite-plan → convert-to-plan → queue → execute】" },
@@ -303,10 +302,9 @@ async function defineSteps(templateDesign) {
"description": "Quick implementation with testing",
"level": 2,
"steps": [
{ "cmd": "/workflow:lite-plan", "args": "\"{{goal}}\"", "unit": "quick-implementation", "execution": { "type": "slash-command", "mode": "mainprocess" }, "contextHint": "Create lightweight implementation plan" },
{ "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-gen", "unit": "test-validation", "execution": { "type": "slash-command", "mode": "mainprocess" }, "contextHint": "Generate test tasks" },
{ "cmd": "/workflow:test-cycle-execute", "unit": "test-validation", "execution": { "type": "slash-command", "mode": "async" }, "contextHint": "Execute test-fix cycle until pass rate >= 95%" }
{ "cmd": "/workflow-lite-planex", "args": "\"{{goal}}\"", "unit": "quick-implementation", "execution": { "type": "slash-command", "mode": "mainprocess" }, "contextHint": "Create lightweight implementation plan (includes execution)" },
{ "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%" }
]
}
```
@@ -318,13 +316,13 @@ async function defineSteps(templateDesign) {
"description": "Full workflow with verification, review, and testing",
"level": 3,
"steps": [
{ "cmd": "/workflow:plan", "args": "\"{{goal}}\"", "unit": "verified-planning-execution", "execution": { "type": "slash-command", "mode": "mainprocess" }, "contextHint": "Create detailed implementation plan" },
{ "cmd": "/workflow:plan-verify", "unit": "verified-planning-execution", "execution": { "type": "slash-command", "mode": "mainprocess" }, "contextHint": "Verify plan against requirements" },
{ "cmd": "/workflow:execute", "unit": "verified-planning-execution", "execution": { "type": "slash-command", "mode": "async" }, "contextHint": "Execute implementation" },
{ "cmd": "/workflow-plan", "args": "\"{{goal}}\"", "unit": "verified-planning-execution", "execution": { "type": "slash-command", "mode": "mainprocess" }, "contextHint": "Create detailed implementation plan" },
{ "cmd": "/workflow-plan-verify", "unit": "verified-planning-execution", "execution": { "type": "slash-command", "mode": "mainprocess" }, "contextHint": "Verify plan against requirements" },
{ "cmd": "/workflow-execute", "unit": "verified-planning-execution", "execution": { "type": "slash-command", "mode": "async" }, "contextHint": "Execute implementation" },
{ "cmd": "/workflow:review-session-cycle", "unit": "code-review", "execution": { "type": "slash-command", "mode": "mainprocess" }, "contextHint": "Multi-dimensional code review" },
{ "cmd": "/workflow:review-cycle-fix", "unit": "code-review", "execution": { "type": "slash-command", "mode": "mainprocess" }, "contextHint": "Fix review findings" },
{ "cmd": "/workflow:test-fix-gen", "unit": "test-validation", "execution": { "type": "slash-command", "mode": "mainprocess" }, "contextHint": "Generate test tasks" },
{ "cmd": "/workflow:test-cycle-execute", "unit": "test-validation", "execution": { "type": "slash-command", "mode": "async" }, "contextHint": "Execute test-fix cycle" }
{ "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" }
]
}
```
@@ -336,10 +334,9 @@ async function defineSteps(templateDesign) {
"description": "Bug diagnosis and fix with testing",
"level": 2,
"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-execute", "args": "--in-memory", "unit": "bug-fix", "execution": { "type": "slash-command", "mode": "mainprocess" }, "contextHint": "Execute bug fix" },
{ "cmd": "/workflow:test-fix-gen", "unit": "test-validation", "execution": { "type": "slash-command", "mode": "mainprocess" }, "contextHint": "Generate regression tests" },
{ "cmd": "/workflow:test-cycle-execute", "unit": "test-validation", "execution": { "type": "slash-command", "mode": "async" }, "contextHint": "Verify fix with tests" }
{ "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-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" }
]
}
```
@@ -351,7 +348,7 @@ async function defineSteps(templateDesign) {
"description": "Urgent production bug fix (no tests)",
"level": 2,
"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" }
]
}
```
@@ -363,9 +360,9 @@ async function defineSteps(templateDesign) {
"description": "Test-driven development with Red-Green-Refactor",
"level": 3,
"steps": [
{ "cmd": "/workflow:tdd-plan", "args": "\"{{goal}}\"", "unit": "tdd-planning-execution", "execution": { "type": "slash-command", "mode": "mainprocess" }, "contextHint": "Create TDD task chain" },
{ "cmd": "/workflow:execute", "unit": "tdd-planning-execution", "execution": { "type": "slash-command", "mode": "async" }, "contextHint": "Execute TDD cycle" },
{ "cmd": "/workflow:tdd-verify", "unit": "standalone", "execution": { "type": "slash-command", "mode": "mainprocess" }, "contextHint": "Verify TDD compliance" }
{ "cmd": "/workflow-tdd-plan", "args": "\"{{goal}}\"", "unit": "tdd-planning-execution", "execution": { "type": "slash-command", "mode": "mainprocess" }, "contextHint": "Create TDD task chain" },
{ "cmd": "/workflow-execute", "unit": "tdd-planning-execution", "execution": { "type": "slash-command", "mode": "async" }, "contextHint": "Execute TDD cycle" },
{ "cmd": "/workflow-tdd-verify", "unit": "standalone", "execution": { "type": "slash-command", "mode": "mainprocess" }, "contextHint": "Verify TDD compliance" }
]
}
```
@@ -379,8 +376,8 @@ async function defineSteps(templateDesign) {
"steps": [
{ "cmd": "/workflow:review-session-cycle", "unit": "code-review", "execution": { "type": "slash-command", "mode": "mainprocess" }, "contextHint": "Multi-dimensional code review" },
{ "cmd": "/workflow:review-cycle-fix", "unit": "code-review", "execution": { "type": "slash-command", "mode": "mainprocess" }, "contextHint": "Fix review findings" },
{ "cmd": "/workflow:test-fix-gen", "unit": "test-validation", "execution": { "type": "slash-command", "mode": "mainprocess" }, "contextHint": "Generate tests for fixes" },
{ "cmd": "/workflow:test-cycle-execute", "unit": "test-validation", "execution": { "type": "slash-command", "mode": "async" }, "contextHint": "Verify fixes pass tests" }
{ "cmd": "/workflow-test-fix", "unit": "test-validation", "execution": { "type": "slash-command", "mode": "mainprocess" }, "contextHint": "Generate tests for fixes" },
{ "cmd": "/workflow-test-fix", "unit": "test-validation", "execution": { "type": "slash-command", "mode": "async" }, "contextHint": "Verify fixes pass tests" }
]
}
```
@@ -392,8 +389,8 @@ async function defineSteps(templateDesign) {
"description": "Fix failing tests",
"level": 3,
"steps": [
{ "cmd": "/workflow:test-fix-gen", "args": "\"{{goal}}\"", "unit": "test-validation", "execution": { "type": "slash-command", "mode": "mainprocess" }, "contextHint": "Generate test fix tasks" },
{ "cmd": "/workflow:test-cycle-execute", "unit": "test-validation", "execution": { "type": "slash-command", "mode": "async" }, "contextHint": "Execute test-fix cycle" }
{ "cmd": "/workflow-test-fix", "args": "\"{{goal}}\"", "unit": "test-validation", "execution": { "type": "slash-command", "mode": "mainprocess" }, "contextHint": "Generate test fix tasks" },
{ "cmd": "/workflow-test-fix", "unit": "test-validation", "execution": { "type": "slash-command", "mode": "async" }, "contextHint": "Execute test-fix cycle" }
]
}
```
@@ -420,7 +417,7 @@ async function defineSteps(templateDesign) {
"description": "Bridge lightweight planning to issue workflow",
"level": 2,
"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: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" }
@@ -486,11 +483,11 @@ async function defineSteps(templateDesign) {
"level": 4,
"steps": [
{ "cmd": "/brainstorm", "args": "\"{{goal}}\"", "unit": "standalone", "execution": { "type": "slash-command", "mode": "mainprocess" }, "contextHint": "Unified brainstorming with multi-perspective exploration" },
{ "cmd": "/workflow:plan", "unit": "verified-planning-execution", "execution": { "type": "slash-command", "mode": "mainprocess" }, "contextHint": "Create detailed plan from brainstorm" },
{ "cmd": "/workflow:plan-verify", "unit": "verified-planning-execution", "execution": { "type": "slash-command", "mode": "mainprocess" }, "contextHint": "Verify plan quality" },
{ "cmd": "/workflow:execute", "unit": "verified-planning-execution", "execution": { "type": "slash-command", "mode": "async" }, "contextHint": "Execute implementation" },
{ "cmd": "/workflow:test-fix-gen", "unit": "test-validation", "execution": { "type": "slash-command", "mode": "mainprocess" }, "contextHint": "Generate comprehensive tests" },
{ "cmd": "/workflow:test-cycle-execute", "unit": "test-validation", "execution": { "type": "slash-command", "mode": "async" }, "contextHint": "Execute test cycle" }
{ "cmd": "/workflow-plan", "unit": "verified-planning-execution", "execution": { "type": "slash-command", "mode": "mainprocess" }, "contextHint": "Create detailed plan from brainstorm" },
{ "cmd": "/workflow-plan-verify", "unit": "verified-planning-execution", "execution": { "type": "slash-command", "mode": "mainprocess" }, "contextHint": "Verify plan quality" },
{ "cmd": "/workflow-execute", "unit": "verified-planning-execution", "execution": { "type": "slash-command", "mode": "async" }, "contextHint": "Execute implementation" },
{ "cmd": "/workflow-test-fix", "unit": "test-validation", "execution": { "type": "slash-command", "mode": "mainprocess" }, "contextHint": "Generate comprehensive tests" },
{ "cmd": "/workflow-test-fix", "unit": "test-validation", "execution": { "type": "slash-command", "mode": "async" }, "contextHint": "Execute test cycle" }
]
}
```
@@ -502,10 +499,10 @@ async function defineSteps(templateDesign) {
"description": "Multi-CLI collaborative planning with cross-verification",
"level": 3,
"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:lite-execute", "args": "--in-memory", "unit": "multi-cli-planning", "execution": { "type": "slash-command", "mode": "mainprocess" }, "contextHint": "Execute converged plan" },
{ "cmd": "/workflow:test-fix-gen", "unit": "test-validation", "execution": { "type": "slash-command", "mode": "mainprocess" }, "contextHint": "Generate tests" },
{ "cmd": "/workflow:test-cycle-execute", "unit": "test-validation", "execution": { "type": "slash-command", "mode": "async" }, "contextHint": "Execute test cycle" }
{ "cmd": "/workflow-multi-cli-plan", "args": "\"{{goal}}\"", "unit": "multi-cli-planning", "execution": { "type": "slash-command", "mode": "mainprocess" }, "contextHint": "Gemini+Codex+Claude collaborative planning" },
// 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": "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 |
| replan | session, feedback | replan | replanning-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) |
| **Testing** |
| 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 |
|-----------|----------|---------|
| **quick-implementation** | lite-plan → lite-execute | Lightweight plan and execution |
| **multi-cli-planning** | multi-cli-plan → lite-execute | Multi-perspective planning and execution |
| **bug-fix** | lite-plan --bugfix → lite-execute | Bug diagnosis and fix |
| **quick-implementation** | lite-plan (Phase 1: plan → Phase 2: execute) | Lightweight plan and execution |
| **multi-cli-planning** | multi-cli-plan (Phase 1: plan → Phase 2: execute) | Multi-perspective planning and execution |
| **bug-fix** | lite-plan --bugfix (Phase 1: plan → Phase 2: execute) | Bug diagnosis and fix |
| **full-planning-execution** | plan → execute | Detailed planning and execution |
| **verified-planning-execution** | plan → plan-verify → execute | Planning with verification |
| **replanning-execution** | replan → execute | Update plan and execute |
@@ -656,9 +653,9 @@ async function generateTemplate(design, steps, outputPath) {
→ Level: 3 (Standard)
→ Steps: Customize
→ Step 1: /brainstorm (standalone, mainprocess)
→ Step 2: /workflow:plan (verified-planning-execution, mainprocess)
→ Step 3: /workflow:plan-verify (verified-planning-execution, mainprocess)
→ Step 4: /workflow:execute (verified-planning-execution, async)
→ Step 2: /workflow-plan (verified-planning-execution, mainprocess)
→ Step 3: /workflow-plan-verify (verified-planning-execution, mainprocess)
→ Step 4: /workflow-execute (verified-planning-execution, async)
→ Step 5: /workflow:review-session-cycle (code-review, mainprocess)
→ Step 6: /workflow:review-cycle-fix (code-review, mainprocess)
→ Done

View File

@@ -0,0 +1,287 @@
---
name: add
description: Add IDAW tasks - manual creation or import from ccw issue
argument-hint: "[-y|--yes] [--from-issue <id>[,<id>,...]] \"description\" [--type <task_type>] [--priority <1-5>]"
allowed-tools: AskUserQuestion(*), Read(*), Bash(*), Write(*), Glob(*)
---
# IDAW Add Command (/idaw:add)
## Auto Mode
When `--yes` or `-y`: Skip clarification questions, create task with inferred details.
## IDAW Task Schema
```json
{
"id": "IDAW-001",
"title": "string",
"description": "string",
"status": "pending",
"priority": 2,
"task_type": null,
"skill_chain": null,
"context": {
"affected_files": [],
"acceptance_criteria": [],
"constraints": [],
"references": []
},
"source": {
"type": "manual|import-issue",
"issue_id": null,
"issue_snapshot": null
},
"execution": {
"session_id": null,
"started_at": null,
"completed_at": null,
"skill_results": [],
"git_commit": null,
"error": null
},
"created_at": "ISO",
"updated_at": "ISO"
}
```
**Valid task_type values**: `bugfix|bugfix-hotfix|feature|feature-complex|refactor|tdd|test|test-fix|review|docs`
## Implementation
### Phase 1: Parse Arguments
```javascript
const args = $ARGUMENTS;
const autoYes = /(-y|--yes)\b/.test(args);
const fromIssue = args.match(/--from-issue\s+([\w,-]+)/)?.[1];
const typeFlag = args.match(/--type\s+([\w-]+)/)?.[1];
const priorityFlag = args.match(/--priority\s+(\d)/)?.[1];
// Extract description: content inside quotes (preferred), or fallback to stripping flags
const quotedMatch = args.match(/(?:^|\s)["']([^"']+)["']/);
const description = quotedMatch
? quotedMatch[1].trim()
: args.replace(/(-y|--yes|--from-issue\s+[\w,-]+|--type\s+[\w-]+|--priority\s+\d)/g, '').trim();
```
### Phase 2: Route — Import or Manual
```
--from-issue present?
├─ YES → Import Mode (Phase 3A)
└─ NO → Manual Mode (Phase 3B)
```
### Phase 3A: Import Mode (from ccw issue)
```javascript
const issueIds = fromIssue.split(',');
// Fetch all issues once (outside loop)
let issues = [];
try {
const issueJson = Bash(`ccw issue list --json`);
issues = JSON.parse(issueJson).issues || [];
} catch (e) {
console.log(`Error fetching CCW issues: ${e.message || e}`);
console.log('Ensure ccw is installed and issues exist. Use /issue:new to create issues first.');
return;
}
for (const issueId of issueIds) {
// 1. Find issue data
const issue = issues.find(i => i.id === issueId.trim());
if (!issue) {
console.log(`Warning: Issue ${issueId} not found, skipping`);
continue;
}
// 2. Check duplicate (same issue_id already imported)
const existing = Glob('.workflow/.idaw/tasks/IDAW-*.json');
for (const f of existing) {
const data = JSON.parse(Read(f));
if (data.source?.issue_id === issueId.trim()) {
console.log(`Warning: Issue ${issueId} already imported as ${data.id}, skipping`);
continue; // skip to next issue
}
}
// 3. Generate next IDAW ID
const nextId = generateNextId();
// 4. Map issue → IDAW task
const task = {
id: nextId,
title: issue.title,
description: issue.context || issue.title,
status: 'pending',
priority: parseInt(priorityFlag) || issue.priority || 3,
task_type: typeFlag || inferTaskType(issue.title, issue.context || ''),
skill_chain: null,
context: {
affected_files: issue.affected_components || [],
acceptance_criteria: [],
constraints: [],
references: issue.source_url ? [issue.source_url] : []
},
source: {
type: 'import-issue',
issue_id: issue.id,
issue_snapshot: {
id: issue.id,
title: issue.title,
status: issue.status,
context: issue.context,
priority: issue.priority,
created_at: issue.created_at
}
},
execution: {
session_id: null,
started_at: null,
completed_at: null,
skill_results: [],
git_commit: null,
error: null
},
created_at: new Date().toISOString(),
updated_at: new Date().toISOString()
};
// 5. Write task file
Bash('mkdir -p .workflow/.idaw/tasks');
Write(`.workflow/.idaw/tasks/${nextId}.json`, JSON.stringify(task, null, 2));
console.log(`Created ${nextId} from issue ${issueId}: ${issue.title}`);
}
```
### Phase 3B: Manual Mode
```javascript
// 1. Validate description
if (!description && !autoYes) {
const answer = AskUserQuestion({
questions: [{
question: 'Please provide a task description:',
header: 'Task',
multiSelect: false,
options: [
{ label: 'Provide description', description: 'What needs to be done?' }
]
}]
});
// Use custom text from "Other"
description = answer.customText || '';
}
if (!description) {
console.log('Error: No description provided. Usage: /idaw:add "task description"');
return;
}
// 2. Generate next IDAW ID
const nextId = generateNextId();
// 3. Build title from first sentence
const title = description.split(/[.\n]/)[0].substring(0, 80).trim();
// 4. Determine task_type
const taskType = typeFlag || null; // null → inferred at run time
// 5. Create task
const task = {
id: nextId,
title: title,
description: description,
status: 'pending',
priority: parseInt(priorityFlag) || 3,
task_type: taskType,
skill_chain: null,
context: {
affected_files: [],
acceptance_criteria: [],
constraints: [],
references: []
},
source: {
type: 'manual',
issue_id: null,
issue_snapshot: null
},
execution: {
session_id: null,
started_at: null,
completed_at: null,
skill_results: [],
git_commit: null,
error: null
},
created_at: new Date().toISOString(),
updated_at: new Date().toISOString()
};
Bash('mkdir -p .workflow/.idaw/tasks');
Write(`.workflow/.idaw/tasks/${nextId}.json`, JSON.stringify(task, null, 2));
console.log(`Created ${nextId}: ${title}`);
```
## Helper Functions
### ID Generation
```javascript
function generateNextId() {
const files = Glob('.workflow/.idaw/tasks/IDAW-*.json') || [];
if (files.length === 0) return 'IDAW-001';
const maxNum = files
.map(f => parseInt(f.match(/IDAW-(\d+)/)?.[1] || '0'))
.reduce((max, n) => Math.max(max, n), 0);
return `IDAW-${String(maxNum + 1).padStart(3, '0')}`;
}
```
### Task Type Inference (deferred — used at run time if task_type is null)
```javascript
function inferTaskType(title, description) {
const text = `${title} ${description}`.toLowerCase();
if (/urgent|production|critical/.test(text) && /fix|bug/.test(text)) return 'bugfix-hotfix';
if (/refactor|重构|tech.*debt/.test(text)) return 'refactor';
if (/tdd|test-driven|test first/.test(text)) return 'tdd';
if (/test fail|fix test|failing test/.test(text)) return 'test-fix';
if (/generate test|写测试|add test/.test(text)) return 'test';
if (/review|code review/.test(text)) return 'review';
if (/docs|documentation|readme/.test(text)) return 'docs';
if (/fix|bug|error|crash|fail/.test(text)) return 'bugfix';
if (/complex|multi-module|architecture/.test(text)) return 'feature-complex';
return 'feature';
}
```
## Examples
```bash
# Manual creation
/idaw:add "Fix login timeout bug" --type bugfix --priority 2
/idaw:add "Add rate limiting to API endpoints" --priority 1
/idaw:add "Refactor auth module to use strategy pattern"
# Import from ccw issue
/idaw:add --from-issue ISS-20260128-001
/idaw:add --from-issue ISS-20260128-001,ISS-20260128-002 --priority 1
# Auto mode (skip clarification)
/idaw:add -y "Quick fix for typo in header"
```
## Output
```
Created IDAW-001: Fix login timeout bug
Type: bugfix | Priority: 2 | Source: manual
→ Next: /idaw:run or /idaw:status
```

View File

@@ -0,0 +1,442 @@
---
name: resume
description: Resume interrupted IDAW session from last checkpoint
argument-hint: "[-y|--yes] [session-id]"
allowed-tools: Skill(*), TodoWrite(*), AskUserQuestion(*), Read(*), Write(*), Bash(*), Glob(*)
---
# IDAW Resume Command (/idaw:resume)
## Auto Mode
When `--yes` or `-y`: Auto-skip interrupted task, continue with remaining.
## Skill Chain Mapping
```javascript
const SKILL_CHAIN_MAP = {
'bugfix': ['workflow-lite-planex', 'workflow-test-fix'],
'bugfix-hotfix': ['workflow-lite-planex'],
'feature': ['workflow-lite-planex', 'workflow-test-fix'],
'feature-complex': ['workflow-plan', 'workflow-execute', 'workflow-test-fix'],
'refactor': ['workflow:refactor-cycle'],
'tdd': ['workflow-tdd-plan', 'workflow-execute'],
'test': ['workflow-test-fix'],
'test-fix': ['workflow-test-fix'],
'review': ['review-cycle'],
'docs': ['workflow-lite-planex']
};
```
## Task Type Inference
```javascript
function inferTaskType(title, description) {
const text = `${title} ${description}`.toLowerCase();
if (/urgent|production|critical/.test(text) && /fix|bug/.test(text)) return 'bugfix-hotfix';
if (/refactor|重构|tech.*debt/.test(text)) return 'refactor';
if (/tdd|test-driven|test first/.test(text)) return 'tdd';
if (/test fail|fix test|failing test/.test(text)) return 'test-fix';
if (/generate test|写测试|add test/.test(text)) return 'test';
if (/review|code review/.test(text)) return 'review';
if (/docs|documentation|readme/.test(text)) return 'docs';
if (/fix|bug|error|crash|fail/.test(text)) return 'bugfix';
if (/complex|multi-module|architecture/.test(text)) return 'feature-complex';
return 'feature';
}
```
## Implementation
### Phase 1: Find Resumable Session
```javascript
const args = $ARGUMENTS;
const autoYes = /(-y|--yes)/.test(args);
const targetSessionId = args.replace(/(-y|--yes)/g, '').trim();
let session = null;
let sessionDir = null;
if (targetSessionId) {
// Load specific session
sessionDir = `.workflow/.idaw/sessions/${targetSessionId}`;
try {
session = JSON.parse(Read(`${sessionDir}/session.json`));
} catch {
console.log(`Session "${targetSessionId}" not found.`);
console.log('Use /idaw:status to list sessions, or /idaw:run to start a new one.');
return;
}
} else {
// Find most recent running session
const sessionFiles = Glob('.workflow/.idaw/sessions/IDA-*/session.json') || [];
for (const f of sessionFiles) {
try {
const s = JSON.parse(Read(f));
if (s.status === 'running') {
session = s;
sessionDir = f.replace(/\/session\.json$/, '').replace(/\\session\.json$/, '');
break;
}
} catch {
// Skip malformed
}
}
if (!session) {
console.log('No running sessions found to resume.');
console.log('Use /idaw:run to start a new execution.');
return;
}
}
console.log(`Resuming session: ${session.session_id}`);
```
### Phase 2: Handle Interrupted Task
```javascript
// Find the task that was in_progress when interrupted
let currentTaskId = session.current_task;
let currentTask = null;
if (currentTaskId) {
try {
currentTask = JSON.parse(Read(`.workflow/.idaw/tasks/${currentTaskId}.json`));
} catch {
console.log(`Warning: Could not read task ${currentTaskId}`);
currentTaskId = null;
}
}
if (currentTask && currentTask.status === 'in_progress') {
if (autoYes) {
// Auto: skip interrupted task
currentTask.status = 'skipped';
currentTask.execution.error = 'Skipped on resume (auto mode)';
currentTask.execution.completed_at = new Date().toISOString();
currentTask.updated_at = new Date().toISOString();
Write(`.workflow/.idaw/tasks/${currentTaskId}.json`, JSON.stringify(currentTask, null, 2));
session.skipped.push(currentTaskId);
console.log(`Skipped interrupted task: ${currentTaskId}`);
} else {
const answer = AskUserQuestion({
questions: [{
question: `Task ${currentTaskId} was interrupted: "${currentTask.title}". How to proceed?`,
header: 'Resume',
multiSelect: false,
options: [
{ label: 'Retry', description: 'Reset to pending, re-execute from beginning' },
{ label: 'Skip', description: 'Mark as skipped, move to next task' }
]
}]
});
if (answer.answers?.Resume === 'Skip') {
currentTask.status = 'skipped';
currentTask.execution.error = 'Skipped on resume (user choice)';
currentTask.execution.completed_at = new Date().toISOString();
currentTask.updated_at = new Date().toISOString();
Write(`.workflow/.idaw/tasks/${currentTaskId}.json`, JSON.stringify(currentTask, null, 2));
session.skipped.push(currentTaskId);
} else {
// Retry: reset to pending
currentTask.status = 'pending';
currentTask.execution.started_at = null;
currentTask.execution.completed_at = null;
currentTask.execution.skill_results = [];
currentTask.execution.error = null;
currentTask.updated_at = new Date().toISOString();
Write(`.workflow/.idaw/tasks/${currentTaskId}.json`, JSON.stringify(currentTask, null, 2));
}
}
}
```
### Phase 3: Build Remaining Task Queue
```javascript
// Collect remaining tasks (pending, or the retried current task)
const allTaskIds = session.tasks;
const completedSet = new Set([...session.completed, ...session.failed, ...session.skipped]);
const remainingTasks = [];
for (const taskId of allTaskIds) {
if (completedSet.has(taskId)) continue;
try {
const task = JSON.parse(Read(`.workflow/.idaw/tasks/${taskId}.json`));
if (task.status === 'pending') {
remainingTasks.push(task);
}
} catch {
console.log(`Warning: Could not read task ${taskId}, skipping`);
}
}
if (remainingTasks.length === 0) {
console.log('No remaining tasks to execute. Session complete.');
session.status = 'completed';
session.current_task = null;
session.updated_at = new Date().toISOString();
Write(`${sessionDir}/session.json`, JSON.stringify(session, null, 2));
return;
}
// Sort: priority ASC, then ID ASC
remainingTasks.sort((a, b) => {
if (a.priority !== b.priority) return a.priority - b.priority;
return a.id.localeCompare(b.id);
});
console.log(`Remaining tasks: ${remainingTasks.length}`);
// Append resume marker to progress.md
const progressFile = `${sessionDir}/progress.md`;
try {
const currentProgress = Read(progressFile);
Write(progressFile, currentProgress + `\n---\n**Resumed**: ${new Date().toISOString()}\n\n`);
} catch {
Write(progressFile, `# IDAW Progress — ${session.session_id}\n\n---\n**Resumed**: ${new Date().toISOString()}\n\n`);
}
// Update TodoWrite
TodoWrite({
todos: remainingTasks.map((t, i) => ({
content: `IDAW:[${i + 1}/${remainingTasks.length}] ${t.title}`,
status: i === 0 ? 'in_progress' : 'pending',
activeForm: `Executing ${t.title}`
}))
});
```
### Phase 4-6: Execute Remaining (reuse run.md main loop)
Execute remaining tasks using the same Phase 4-6 logic from `/idaw:run`:
```javascript
// Phase 4: Main Loop — identical to run.md Phase 4
for (let taskIdx = 0; taskIdx < remainingTasks.length; taskIdx++) {
const task = remainingTasks[taskIdx];
// Resolve skill chain
const resolvedType = task.task_type || inferTaskType(task.title, task.description);
const chain = task.skill_chain || SKILL_CHAIN_MAP[resolvedType] || SKILL_CHAIN_MAP['feature'];
// Update task → in_progress
task.status = 'in_progress';
task.task_type = resolvedType;
task.execution.started_at = new Date().toISOString();
Write(`.workflow/.idaw/tasks/${task.id}.json`, JSON.stringify(task, null, 2));
session.current_task = task.id;
session.updated_at = new Date().toISOString();
Write(`${sessionDir}/session.json`, JSON.stringify(session, null, 2));
console.log(`\n--- [${taskIdx + 1}/${remainingTasks.length}] ${task.id}: ${task.title} ---`);
console.log(`Chain: ${chain.join(' → ')}`);
// ━━━ Pre-Task CLI Context Analysis (for complex/bugfix tasks) ━━━
if (['bugfix', 'bugfix-hotfix', 'feature-complex'].includes(resolvedType)) {
console.log(` Pre-analysis: gathering context for ${resolvedType} task...`);
const affectedFiles = (task.context?.affected_files || []).join(', ');
const preAnalysisPrompt = `PURPOSE: Pre-analyze codebase context for IDAW task before execution.
TASK: • Understand current state of: ${affectedFiles || 'files related to: ' + task.title} • Identify dependencies and risk areas • Note existing patterns to follow
MODE: analysis
CONTEXT: @**/*
EXPECTED: Brief context summary (affected modules, dependencies, risk areas) in 3-5 bullet points
CONSTRAINTS: Keep concise | Focus on execution-relevant context`;
const preAnalysis = Bash(`ccw cli -p '${preAnalysisPrompt.replace(/'/g, "'\\''")}' --tool gemini --mode analysis 2>&1 || echo "Pre-analysis skipped"`);
task.execution.skill_results.push({
skill: 'cli-pre-analysis',
status: 'completed',
context_summary: preAnalysis?.substring(0, 500),
timestamp: new Date().toISOString()
});
}
// Execute skill chain
let previousResult = null;
let taskFailed = false;
for (let skillIdx = 0; skillIdx < chain.length; skillIdx++) {
const skillName = chain[skillIdx];
const skillArgs = assembleSkillArgs(skillName, task, previousResult, autoYes, skillIdx === 0);
console.log(` [${skillIdx + 1}/${chain.length}] ${skillName}`);
try {
const result = Skill({ skill: skillName, args: skillArgs });
previousResult = result;
task.execution.skill_results.push({
skill: skillName,
status: 'completed',
timestamp: new Date().toISOString()
});
} catch (error) {
// ━━━ CLI-Assisted Error Recovery ━━━
console.log(` Diagnosing failure: ${skillName}...`);
const diagnosisPrompt = `PURPOSE: Diagnose why skill "${skillName}" failed during IDAW task execution.
TASK: • Analyze error: ${String(error).substring(0, 300)} • Check affected files: ${(task.context?.affected_files || []).join(', ') || 'unknown'} • Identify root cause • Suggest fix strategy
MODE: analysis
CONTEXT: @**/* | Memory: IDAW task ${task.id}: ${task.title}
EXPECTED: Root cause + actionable fix recommendation (1-2 sentences)
CONSTRAINTS: Focus on actionable diagnosis`;
const diagnosisResult = Bash(`ccw cli -p '${diagnosisPrompt.replace(/'/g, "'\\''")}' --tool gemini --mode analysis --rule analysis-diagnose-bug-root-cause 2>&1 || echo "CLI diagnosis unavailable"`);
task.execution.skill_results.push({
skill: `cli-diagnosis:${skillName}`,
status: 'completed',
diagnosis: diagnosisResult?.substring(0, 500),
timestamp: new Date().toISOString()
});
// Retry with diagnosis context
console.log(` Retry with diagnosis: ${skillName}`);
try {
const retryResult = Skill({ skill: skillName, args: skillArgs });
previousResult = retryResult;
task.execution.skill_results.push({
skill: skillName,
status: 'completed-retry-with-diagnosis',
timestamp: new Date().toISOString()
});
} catch (retryError) {
task.execution.skill_results.push({
skill: skillName,
status: 'failed',
error: String(retryError).substring(0, 200),
timestamp: new Date().toISOString()
});
if (autoYes) {
taskFailed = true;
break;
}
const answer = AskUserQuestion({
questions: [{
question: `${skillName} failed after CLI diagnosis + retry: ${String(retryError).substring(0, 100)}`,
header: 'Error',
multiSelect: false,
options: [
{ label: 'Skip task', description: 'Mark as failed, continue' },
{ label: 'Abort', description: 'Stop run' }
]
}]
});
if (answer.answers?.Error === 'Abort') {
task.status = 'failed';
task.execution.error = String(retryError).substring(0, 200);
Write(`.workflow/.idaw/tasks/${task.id}.json`, JSON.stringify(task, null, 2));
session.failed.push(task.id);
session.status = 'failed';
session.updated_at = new Date().toISOString();
Write(`${sessionDir}/session.json`, JSON.stringify(session, null, 2));
return;
}
taskFailed = true;
break;
}
}
}
// Phase 5: Checkpoint
if (taskFailed) {
task.status = 'failed';
task.execution.error = 'Skill chain failed after retry';
task.execution.completed_at = new Date().toISOString();
session.failed.push(task.id);
} else {
// Git commit
const commitMsg = `feat(idaw): ${task.title} [${task.id}]`;
const diffCheck = Bash('git diff --stat HEAD 2>/dev/null || echo ""');
const untrackedCheck = Bash('git ls-files --others --exclude-standard 2>/dev/null || echo ""');
if (diffCheck?.trim() || untrackedCheck?.trim()) {
Bash('git add -A');
Bash(`git commit -m "$(cat <<'EOF'\n${commitMsg}\nEOF\n)"`);
const commitHash = Bash('git rev-parse --short HEAD 2>/dev/null')?.trim();
task.execution.git_commit = commitHash;
} else {
task.execution.git_commit = 'no-commit';
}
task.status = 'completed';
task.execution.completed_at = new Date().toISOString();
session.completed.push(task.id);
}
task.updated_at = new Date().toISOString();
Write(`.workflow/.idaw/tasks/${task.id}.json`, JSON.stringify(task, null, 2));
session.updated_at = new Date().toISOString();
Write(`${sessionDir}/session.json`, JSON.stringify(session, null, 2));
// Append progress
const chain_str = chain.join(' → ');
const progressEntry = `## ${task.id}${task.title}\n- Status: ${task.status}\n- Chain: ${chain_str}\n- Commit: ${task.execution.git_commit || '-'}\n\n`;
const currentProgress = Read(`${sessionDir}/progress.md`);
Write(`${sessionDir}/progress.md`, currentProgress + progressEntry);
}
// Phase 6: Report
session.status = session.failed.length > 0 && session.completed.length === 0 ? 'failed' : 'completed';
session.current_task = null;
session.updated_at = new Date().toISOString();
Write(`${sessionDir}/session.json`, JSON.stringify(session, null, 2));
const summary = `\n---\n## Summary (Resumed)\n- Completed: ${session.completed.length}\n- Failed: ${session.failed.length}\n- Skipped: ${session.skipped.length}\n`;
const finalProgress = Read(`${sessionDir}/progress.md`);
Write(`${sessionDir}/progress.md`, finalProgress + summary);
console.log('\n=== IDAW Resume Complete ===');
console.log(`Session: ${session.session_id}`);
console.log(`Completed: ${session.completed.length} | Failed: ${session.failed.length} | Skipped: ${session.skipped.length}`);
```
## Helper Functions
### assembleSkillArgs
```javascript
function assembleSkillArgs(skillName, task, previousResult, autoYes, isFirst) {
let args = '';
if (isFirst) {
// Sanitize for shell safety
const goal = `${task.title}\n${task.description}`
.replace(/\\/g, '\\\\')
.replace(/"/g, '\\"')
.replace(/\$/g, '\\$')
.replace(/`/g, '\\`');
args = `"${goal}"`;
if (task.task_type === 'bugfix-hotfix') args += ' --hotfix';
} else if (previousResult?.session_id) {
args = `--session="${previousResult.session_id}"`;
}
if (autoYes && !args.includes('-y') && !args.includes('--yes')) {
args = args ? `${args} -y` : '-y';
}
return args;
}
```
## Examples
```bash
# Resume most recent running session (interactive)
/idaw:resume
# Resume specific session
/idaw:resume IDA-auth-fix-20260301
# Resume with auto mode (skip interrupted, continue)
/idaw:resume -y
# Resume specific session with auto mode
/idaw:resume -y IDA-auth-fix-20260301
```

View File

@@ -0,0 +1,648 @@
---
name: run-coordinate
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>]"
allowed-tools: Task(*), AskUserQuestion(*), Read(*), Write(*), Bash(*), Glob(*), Grep(*)
---
# IDAW Run Coordinate Command (/idaw:run-coordinate)
Coordinator variant of `/idaw:run`: external CLI execution with background tasks and hook callbacks.
**Execution Model**: `ccw cli -p "..." --tool <tool> --mode write` in background → hook callback → next step.
**vs `/idaw:run`**: Direct `Skill()` calls (blocking, main process) vs `ccw cli` (background, external process).
## When to Use
| Scenario | Use |
|----------|-----|
| Standard IDAW execution (main process) | `/idaw:run` |
| External CLI execution (background, hook-driven) | `/idaw:run-coordinate` |
| Need `claude` or `gemini` as execution tool | `/idaw:run-coordinate --tool claude` |
| Long-running tasks, avoid context window pressure | `/idaw:run-coordinate` |
## Skill Chain Mapping
```javascript
const SKILL_CHAIN_MAP = {
'bugfix': ['workflow-lite-planex', 'workflow-test-fix'],
'bugfix-hotfix': ['workflow-lite-planex'],
'feature': ['workflow-lite-planex', 'workflow-test-fix'],
'feature-complex': ['workflow-plan', 'workflow-execute', 'workflow-test-fix'],
'refactor': ['workflow:refactor-cycle'],
'tdd': ['workflow-tdd-plan', 'workflow-execute'],
'test': ['workflow-test-fix'],
'test-fix': ['workflow-test-fix'],
'review': ['review-cycle'],
'docs': ['workflow-lite-planex']
};
```
## Task Type Inference
```javascript
function inferTaskType(title, description) {
const text = `${title} ${description}`.toLowerCase();
if (/urgent|production|critical/.test(text) && /fix|bug/.test(text)) return 'bugfix-hotfix';
if (/refactor|重构|tech.*debt/.test(text)) return 'refactor';
if (/tdd|test-driven|test first/.test(text)) return 'tdd';
if (/test fail|fix test|failing test/.test(text)) return 'test-fix';
if (/generate test|写测试|add test/.test(text)) return 'test';
if (/review|code review/.test(text)) return 'review';
if (/docs|documentation|readme/.test(text)) return 'docs';
if (/fix|bug|error|crash|fail/.test(text)) return 'bugfix';
if (/complex|multi-module|architecture/.test(text)) return 'feature-complex';
return 'feature';
}
```
## 6-Phase Execution (Coordinator Model)
### Phase 1: Load Tasks
```javascript
const args = $ARGUMENTS;
const autoYes = /(-y|--yes)/.test(args);
const dryRun = /--dry-run/.test(args);
const taskFilter = args.match(/--task\s+([\w,-]+)/)?.[1]?.split(',') || null;
const cliTool = args.match(/--tool\s+(\w+)/)?.[1] || 'claude';
// Load task files
const taskFiles = Glob('.workflow/.idaw/tasks/IDAW-*.json') || [];
if (taskFiles.length === 0) {
console.log('No IDAW tasks found. Use /idaw:add to create tasks.');
return;
}
// Parse and filter
let tasks = taskFiles.map(f => JSON.parse(Read(f)));
if (taskFilter) {
tasks = tasks.filter(t => taskFilter.includes(t.id));
} else {
tasks = tasks.filter(t => t.status === 'pending');
}
if (tasks.length === 0) {
console.log('No pending tasks to execute. Use /idaw:add to add tasks or --task to specify IDs.');
return;
}
// Sort: priority ASC (1=critical first), then ID ASC
tasks.sort((a, b) => {
if (a.priority !== b.priority) return a.priority - b.priority;
return a.id.localeCompare(b.id);
});
```
### Phase 2: Session Setup
```javascript
// Generate session ID: IDA-{slug}-YYYYMMDD
const slug = tasks[0].title
.toLowerCase()
.replace(/[^a-z0-9]+/g, '-')
.substring(0, 20)
.replace(/-$/, '');
const dateStr = new Date().toISOString().slice(0, 10).replace(/-/g, '');
let sessionId = `IDA-${slug}-${dateStr}`;
// Check collision
const existingSession = Glob(`.workflow/.idaw/sessions/${sessionId}/session.json`);
if (existingSession?.length > 0) {
sessionId = `${sessionId}-2`;
}
const sessionDir = `.workflow/.idaw/sessions/${sessionId}`;
Bash(`mkdir -p "${sessionDir}"`);
const session = {
session_id: sessionId,
mode: 'coordinate', // ★ Marks this as coordinator-mode session
cli_tool: cliTool,
status: 'running',
created_at: new Date().toISOString(),
updated_at: new Date().toISOString(),
tasks: tasks.map(t => t.id),
current_task: null,
current_skill_index: 0,
completed: [],
failed: [],
skipped: [],
prompts_used: []
};
Write(`${sessionDir}/session.json`, JSON.stringify(session, null, 2));
// Initialize progress.md
const progressHeader = `# IDAW Progress — ${sessionId} (coordinate mode)\nStarted: ${session.created_at}\nCLI Tool: ${cliTool}\n\n`;
Write(`${sessionDir}/progress.md`, progressHeader);
```
### Phase 3: Startup Protocol
```javascript
// Check for existing running sessions
const runningSessions = Glob('.workflow/.idaw/sessions/IDA-*/session.json')
?.map(f => { try { return JSON.parse(Read(f)); } catch { return null; } })
.filter(s => s && s.status === 'running' && s.session_id !== sessionId) || [];
if (runningSessions.length > 0 && !autoYes) {
const answer = AskUserQuestion({
questions: [{
question: `Found running session: ${runningSessions[0].session_id}. How to proceed?`,
header: 'Conflict',
multiSelect: false,
options: [
{ label: 'Resume existing', description: 'Use /idaw:resume instead' },
{ label: 'Start fresh', description: 'Continue with new session' },
{ label: 'Abort', description: 'Cancel this run' }
]
}]
});
if (answer.answers?.Conflict === 'Resume existing') {
console.log(`Use: /idaw:resume ${runningSessions[0].session_id}`);
return;
}
if (answer.answers?.Conflict === 'Abort') return;
}
// Check git status
const gitStatus = Bash('git status --porcelain 2>/dev/null');
if (gitStatus?.trim() && !autoYes) {
const answer = AskUserQuestion({
questions: [{
question: 'Working tree has uncommitted changes. How to proceed?',
header: 'Git',
multiSelect: false,
options: [
{ label: 'Continue', description: 'Proceed with dirty tree' },
{ label: 'Stash', description: 'git stash before running' },
{ label: 'Abort', description: 'Stop and handle manually' }
]
}]
});
if (answer.answers?.Git === 'Stash') Bash('git stash push -m "idaw-pre-run"');
if (answer.answers?.Git === 'Abort') return;
}
// Dry run
if (dryRun) {
console.log(`# Dry Run — ${sessionId} (coordinate mode, tool: ${cliTool})\n`);
for (const task of tasks) {
const taskType = task.task_type || inferTaskType(task.title, task.description);
const chain = task.skill_chain || SKILL_CHAIN_MAP[taskType] || SKILL_CHAIN_MAP['feature'];
console.log(`## ${task.id}: ${task.title}`);
console.log(` Type: ${taskType} | Priority: ${task.priority}`);
console.log(` Chain: ${chain.join(' → ')}`);
console.log(` CLI: ccw cli --tool ${cliTool} --mode write\n`);
}
console.log(`Total: ${tasks.length} tasks`);
return;
}
```
### Phase 4: Launch First Task (then wait for hook)
```javascript
// Start with the first task, first skill
const firstTask = tasks[0];
const resolvedType = firstTask.task_type || inferTaskType(firstTask.title, firstTask.description);
const chain = firstTask.skill_chain || SKILL_CHAIN_MAP[resolvedType] || SKILL_CHAIN_MAP['feature'];
// Update task → in_progress
firstTask.status = 'in_progress';
firstTask.task_type = resolvedType;
firstTask.execution.started_at = new Date().toISOString();
Write(`.workflow/.idaw/tasks/${firstTask.id}.json`, JSON.stringify(firstTask, null, 2));
// Update session
session.current_task = firstTask.id;
session.current_skill_index = 0;
session.updated_at = new Date().toISOString();
Write(`${sessionDir}/session.json`, JSON.stringify(session, null, 2));
// ━━━ Pre-Task CLI Context Analysis (for complex/bugfix tasks) ━━━
if (['bugfix', 'bugfix-hotfix', 'feature-complex'].includes(resolvedType)) {
console.log(`Pre-analysis: gathering context for ${resolvedType} task...`);
const affectedFiles = (firstTask.context?.affected_files || []).join(', ');
const preAnalysisPrompt = `PURPOSE: Pre-analyze codebase context for IDAW task.
TASK: • Understand current state of: ${affectedFiles || 'files related to: ' + firstTask.title} • Identify dependencies and risk areas
MODE: analysis
CONTEXT: @**/*
EXPECTED: Brief context summary in 3-5 bullet points
CONSTRAINTS: Keep concise`;
Bash(`ccw cli -p '${preAnalysisPrompt.replace(/'/g, "'\\''")}' --tool gemini --mode analysis 2>&1 || echo "Pre-analysis skipped"`);
}
// Assemble prompt for first skill
const skillName = chain[0];
const prompt = assembleCliPrompt(skillName, firstTask, null, autoYes);
session.prompts_used.push({
task_id: firstTask.id,
skill_index: 0,
skill: skillName,
prompt: prompt,
timestamp: new Date().toISOString()
});
session.updated_at = new Date().toISOString();
Write(`${sessionDir}/session.json`, JSON.stringify(session, null, 2));
// Launch via ccw cli in background
console.log(`[1/${tasks.length}] ${firstTask.id}: ${firstTask.title}`);
console.log(` Chain: ${chain.join(' → ')}`);
console.log(` Launching: ${skillName} via ccw cli --tool ${cliTool}`);
Bash(
`ccw cli -p "${escapeForShell(prompt)}" --tool ${cliTool} --mode write`,
{ run_in_background: true }
);
// ★ STOP HERE — wait for hook callback
// Hook callback will trigger handleStepCompletion() below
```
### Phase 5: Hook Callback Handler (per-step completion)
```javascript
// Called by hook when background CLI completes
async function handleStepCompletion(sessionId, cliOutput) {
const sessionDir = `.workflow/.idaw/sessions/${sessionId}`;
const session = JSON.parse(Read(`${sessionDir}/session.json`));
const taskId = session.current_task;
const task = JSON.parse(Read(`.workflow/.idaw/tasks/${taskId}.json`));
const resolvedType = task.task_type || inferTaskType(task.title, task.description);
const chain = task.skill_chain || SKILL_CHAIN_MAP[resolvedType] || SKILL_CHAIN_MAP['feature'];
const skillIdx = session.current_skill_index;
const skillName = chain[skillIdx];
// Parse CLI output for session ID
const parsedOutput = parseCliOutput(cliOutput);
// Record skill result
task.execution.skill_results.push({
skill: skillName,
status: parsedOutput.success ? 'completed' : 'failed',
session_id: parsedOutput.sessionId,
timestamp: new Date().toISOString()
});
// ━━━ Handle failure with CLI diagnosis ━━━
if (!parsedOutput.success) {
console.log(` ${skillName} failed. Running CLI diagnosis...`);
const diagnosisPrompt = `PURPOSE: Diagnose why skill "${skillName}" failed during IDAW task.
TASK: • Analyze error output • Check affected files: ${(task.context?.affected_files || []).join(', ') || 'unknown'}
MODE: analysis
CONTEXT: @**/* | Memory: IDAW task ${task.id}: ${task.title}
EXPECTED: Root cause + fix recommendation
CONSTRAINTS: Actionable diagnosis`;
Bash(`ccw cli -p '${diagnosisPrompt.replace(/'/g, "'\\''")}' --tool gemini --mode analysis --rule analysis-diagnose-bug-root-cause 2>&1 || true`);
task.execution.skill_results.push({
skill: `cli-diagnosis:${skillName}`,
status: 'completed',
timestamp: new Date().toISOString()
});
// Retry once
console.log(` Retrying: ${skillName}`);
const retryPrompt = assembleCliPrompt(skillName, task, parsedOutput, true);
session.prompts_used.push({
task_id: taskId,
skill_index: skillIdx,
skill: `${skillName}-retry`,
prompt: retryPrompt,
timestamp: new Date().toISOString()
});
Write(`${sessionDir}/session.json`, JSON.stringify(session, null, 2));
Write(`.workflow/.idaw/tasks/${taskId}.json`, JSON.stringify(task, null, 2));
Bash(
`ccw cli -p "${escapeForShell(retryPrompt)}" --tool ${session.cli_tool} --mode write`,
{ run_in_background: true }
);
return; // Wait for retry hook
}
// ━━━ Skill succeeded — advance ━━━
const nextSkillIdx = skillIdx + 1;
if (nextSkillIdx < chain.length) {
// More skills in this task's chain → launch next skill
session.current_skill_index = nextSkillIdx;
session.updated_at = new Date().toISOString();
const nextSkill = chain[nextSkillIdx];
const nextPrompt = assembleCliPrompt(nextSkill, task, parsedOutput, true);
session.prompts_used.push({
task_id: taskId,
skill_index: nextSkillIdx,
skill: nextSkill,
prompt: nextPrompt,
timestamp: new Date().toISOString()
});
Write(`${sessionDir}/session.json`, JSON.stringify(session, null, 2));
Write(`.workflow/.idaw/tasks/${taskId}.json`, JSON.stringify(task, null, 2));
console.log(` Next skill: ${nextSkill}`);
Bash(
`ccw cli -p "${escapeForShell(nextPrompt)}" --tool ${session.cli_tool} --mode write`,
{ run_in_background: true }
);
return; // Wait for next hook
}
// ━━━ Task chain complete — git checkpoint ━━━
const commitMsg = `feat(idaw): ${task.title} [${task.id}]`;
const diffCheck = Bash('git diff --stat HEAD 2>/dev/null || echo ""');
const untrackedCheck = Bash('git ls-files --others --exclude-standard 2>/dev/null || echo ""');
if (diffCheck?.trim() || untrackedCheck?.trim()) {
Bash('git add -A');
Bash(`git commit -m "$(cat <<'EOF'\n${commitMsg}\nEOF\n)"`);
const commitHash = Bash('git rev-parse --short HEAD 2>/dev/null')?.trim();
task.execution.git_commit = commitHash;
} else {
task.execution.git_commit = 'no-commit';
}
task.status = 'completed';
task.execution.completed_at = new Date().toISOString();
task.updated_at = new Date().toISOString();
Write(`.workflow/.idaw/tasks/${taskId}.json`, JSON.stringify(task, null, 2));
session.completed.push(taskId);
// Append progress
const progressEntry = `## ${task.id}${task.title}\n` +
`- Status: completed\n` +
`- Type: ${task.task_type}\n` +
`- Chain: ${chain.join(' → ')}\n` +
`- Commit: ${task.execution.git_commit || '-'}\n` +
`- Mode: coordinate (${session.cli_tool})\n\n`;
const currentProgress = Read(`${sessionDir}/progress.md`);
Write(`${sessionDir}/progress.md`, currentProgress + progressEntry);
// ━━━ Advance to next task ━━━
const allTaskIds = session.tasks;
const completedSet = new Set([...session.completed, ...session.failed, ...session.skipped]);
const nextTaskId = allTaskIds.find(id => !completedSet.has(id));
if (nextTaskId) {
// Load next task
const nextTask = JSON.parse(Read(`.workflow/.idaw/tasks/${nextTaskId}.json`));
const nextType = nextTask.task_type || inferTaskType(nextTask.title, nextTask.description);
const nextChain = nextTask.skill_chain || SKILL_CHAIN_MAP[nextType] || SKILL_CHAIN_MAP['feature'];
nextTask.status = 'in_progress';
nextTask.task_type = nextType;
nextTask.execution.started_at = new Date().toISOString();
Write(`.workflow/.idaw/tasks/${nextTaskId}.json`, JSON.stringify(nextTask, null, 2));
session.current_task = nextTaskId;
session.current_skill_index = 0;
session.updated_at = new Date().toISOString();
Write(`${sessionDir}/session.json`, JSON.stringify(session, null, 2));
// Pre-analysis for complex tasks
if (['bugfix', 'bugfix-hotfix', 'feature-complex'].includes(nextType)) {
const affectedFiles = (nextTask.context?.affected_files || []).join(', ');
Bash(`ccw cli -p 'PURPOSE: Pre-analyze context for ${nextTask.title}. TASK: Check ${affectedFiles || "related files"}. MODE: analysis. EXPECTED: 3-5 bullet points.' --tool gemini --mode analysis 2>&1 || true`);
}
const nextSkillName = nextChain[0];
const nextPrompt = assembleCliPrompt(nextSkillName, nextTask, null, true);
session.prompts_used.push({
task_id: nextTaskId,
skill_index: 0,
skill: nextSkillName,
prompt: nextPrompt,
timestamp: new Date().toISOString()
});
Write(`${sessionDir}/session.json`, JSON.stringify(session, null, 2));
const taskNum = session.completed.length + 1;
const totalTasks = session.tasks.length;
console.log(`\n[${taskNum}/${totalTasks}] ${nextTaskId}: ${nextTask.title}`);
console.log(` Chain: ${nextChain.join(' → ')}`);
Bash(
`ccw cli -p "${escapeForShell(nextPrompt)}" --tool ${session.cli_tool} --mode write`,
{ run_in_background: true }
);
return; // Wait for hook
}
// ━━━ All tasks complete — Phase 6: Report ━━━
session.status = session.failed.length > 0 && session.completed.length === 0 ? 'failed' : 'completed';
session.current_task = null;
session.updated_at = new Date().toISOString();
Write(`${sessionDir}/session.json`, JSON.stringify(session, null, 2));
const summary = `\n---\n## Summary (coordinate mode)\n` +
`- CLI Tool: ${session.cli_tool}\n` +
`- Completed: ${session.completed.length}\n` +
`- Failed: ${session.failed.length}\n` +
`- Skipped: ${session.skipped.length}\n` +
`- Total: ${session.tasks.length}\n`;
const finalProgress = Read(`${sessionDir}/progress.md`);
Write(`${sessionDir}/progress.md`, finalProgress + summary);
console.log('\n=== IDAW Coordinate Complete ===');
console.log(`Session: ${sessionId}`);
console.log(`Completed: ${session.completed.length}/${session.tasks.length}`);
if (session.failed.length > 0) console.log(`Failed: ${session.failed.join(', ')}`);
}
```
## Helper Functions
### assembleCliPrompt
```javascript
function assembleCliPrompt(skillName, task, previousResult, autoYes) {
let prompt = '';
const yFlag = autoYes ? ' -y' : '';
// Map skill to command invocation
if (skillName === 'workflow-lite-planex') {
const goal = sanitize(`${task.title}\n${task.description}`);
prompt = `/workflow-lite-planex${yFlag} "${goal}"`;
if (task.task_type === 'bugfix') prompt = `/workflow-lite-planex${yFlag} --bugfix "${goal}"`;
if (task.task_type === 'bugfix-hotfix') prompt = `/workflow-lite-planex${yFlag} --hotfix "${goal}"`;
} else if (skillName === 'workflow-plan') {
prompt = `/workflow-plan${yFlag} "${sanitize(task.title)}"`;
} else if (skillName === 'workflow-execute') {
if (previousResult?.sessionId) {
prompt = `/workflow-execute${yFlag} --resume-session="${previousResult.sessionId}"`;
} else {
prompt = `/workflow-execute${yFlag}`;
}
} else if (skillName === 'workflow-test-fix') {
if (previousResult?.sessionId) {
prompt = `/workflow-test-fix${yFlag} "${previousResult.sessionId}"`;
} else {
prompt = `/workflow-test-fix${yFlag} "${sanitize(task.title)}"`;
}
} else if (skillName === 'workflow-tdd-plan') {
prompt = `/workflow-tdd-plan${yFlag} "${sanitize(task.title)}"`;
} else if (skillName === 'workflow:refactor-cycle') {
prompt = `/workflow:refactor-cycle${yFlag} "${sanitize(task.title)}"`;
} else if (skillName === 'review-cycle') {
if (previousResult?.sessionId) {
prompt = `/review-cycle${yFlag} --session="${previousResult.sessionId}"`;
} else {
prompt = `/review-cycle${yFlag}`;
}
} else {
// Generic fallback
prompt = `/${skillName}${yFlag} "${sanitize(task.title)}"`;
}
// Append task context
prompt += `\n\nTask: ${task.title}\nDescription: ${task.description}`;
if (task.context?.affected_files?.length > 0) {
prompt += `\nAffected files: ${task.context.affected_files.join(', ')}`;
}
if (task.context?.acceptance_criteria?.length > 0) {
prompt += `\nAcceptance criteria: ${task.context.acceptance_criteria.join('; ')}`;
}
return prompt;
}
```
### sanitize & escapeForShell
```javascript
function sanitize(text) {
return text
.replace(/\\/g, '\\\\')
.replace(/"/g, '\\"')
.replace(/\$/g, '\\$')
.replace(/`/g, '\\`');
}
function escapeForShell(prompt) {
return prompt.replace(/'/g, "'\\''");
}
```
### parseCliOutput
```javascript
function parseCliOutput(output) {
// Extract session ID from CLI output (e.g., WFS-xxx, session-xxx)
const sessionMatch = output.match(/(?:session|WFS|Session ID)[:\s]*([\w-]+)/i);
const success = !/(?:error|failed|fatal)/i.test(output) || /completed|success/i.test(output);
return {
success,
sessionId: sessionMatch?.[1] || null,
raw: output?.substring(0, 500)
};
}
```
## CLI-Assisted Analysis
Same as `/idaw:run` — integrated at two points:
### Pre-Task Context Analysis
For `bugfix`, `bugfix-hotfix`, `feature-complex` tasks: auto-invoke `ccw cli --tool gemini --mode analysis` before launching skill chain.
### Error Recovery with CLI Diagnosis
When a skill's CLI execution fails: invoke diagnosis → retry once → if still fails, mark failed and advance.
```
Skill CLI fails → CLI diagnosis (gemini) → Retry CLI → Still fails → mark failed → next task
```
## State Flow
```
Phase 4: Launch first skill
ccw cli --tool claude --mode write (background)
★ STOP — wait for hook callback
Phase 5: handleStepCompletion()
├─ Skill succeeded + more in chain → launch next skill → STOP
├─ Skill succeeded + chain complete → git checkpoint → next task → STOP
├─ Skill failed → CLI diagnosis → retry → STOP
└─ All tasks done → Phase 6: Report
```
## Session State (session.json)
```json
{
"session_id": "IDA-fix-login-20260301",
"mode": "coordinate",
"cli_tool": "claude",
"status": "running|waiting|completed|failed",
"created_at": "ISO",
"updated_at": "ISO",
"tasks": ["IDAW-001", "IDAW-002"],
"current_task": "IDAW-001",
"current_skill_index": 0,
"completed": [],
"failed": [],
"skipped": [],
"prompts_used": [
{
"task_id": "IDAW-001",
"skill_index": 0,
"skill": "workflow-lite-planex",
"prompt": "/workflow-lite-planex -y \"Fix login timeout\"",
"timestamp": "ISO"
}
]
}
```
## Differences from /idaw:run
| Aspect | /idaw:run | /idaw:run-coordinate |
|--------|-----------|---------------------|
| Execution | `Skill()` blocking in main process | `ccw cli` background + hook callback |
| Context window | Shared (each skill uses main context) | Isolated (each CLI gets fresh context) |
| Concurrency | Sequential blocking | Sequential non-blocking (hook-driven) |
| State tracking | session.json + task.json | session.json + task.json + prompts_used |
| Tool selection | N/A (Skill native) | `--tool claude\|gemini\|qwen` |
| Resume | Via `/idaw:resume` (same) | Via `/idaw:resume` (same, detects mode) |
| Best for | Short chains, interactive | Long chains, autonomous, context-heavy |
## Examples
```bash
# Execute all pending tasks via claude CLI
/idaw:run-coordinate -y
# Use specific CLI tool
/idaw:run-coordinate -y --tool gemini
# Execute specific tasks
/idaw:run-coordinate --task IDAW-001,IDAW-003 --tool claude
# Dry run (show plan without executing)
/idaw:run-coordinate --dry-run
# Interactive mode
/idaw:run-coordinate
```

View File

@@ -0,0 +1,539 @@
---
name: run
description: IDAW orchestrator - execute task skill chains serially with git checkpoints
argument-hint: "[-y|--yes] [--task <id>[,<id>,...]] [--dry-run]"
allowed-tools: Skill(*), TodoWrite(*), AskUserQuestion(*), Read(*), Write(*), Bash(*), Glob(*)
---
# IDAW Run Command (/idaw:run)
## Auto Mode
When `--yes` or `-y`: Skip all confirmations, auto-skip on failure, proceed with dirty git.
## Skill Chain Mapping
```javascript
const SKILL_CHAIN_MAP = {
'bugfix': ['workflow-lite-planex', 'workflow-test-fix'],
'bugfix-hotfix': ['workflow-lite-planex'],
'feature': ['workflow-lite-planex', 'workflow-test-fix'],
'feature-complex': ['workflow-plan', 'workflow-execute', 'workflow-test-fix'],
'refactor': ['workflow:refactor-cycle'],
'tdd': ['workflow-tdd-plan', 'workflow-execute'],
'test': ['workflow-test-fix'],
'test-fix': ['workflow-test-fix'],
'review': ['review-cycle'],
'docs': ['workflow-lite-planex']
};
```
## Task Type Inference
```javascript
function inferTaskType(title, description) {
const text = `${title} ${description}`.toLowerCase();
if (/urgent|production|critical/.test(text) && /fix|bug/.test(text)) return 'bugfix-hotfix';
if (/refactor|重构|tech.*debt/.test(text)) return 'refactor';
if (/tdd|test-driven|test first/.test(text)) return 'tdd';
if (/test fail|fix test|failing test/.test(text)) return 'test-fix';
if (/generate test|写测试|add test/.test(text)) return 'test';
if (/review|code review/.test(text)) return 'review';
if (/docs|documentation|readme/.test(text)) return 'docs';
if (/fix|bug|error|crash|fail/.test(text)) return 'bugfix';
if (/complex|multi-module|architecture/.test(text)) return 'feature-complex';
return 'feature';
}
```
## 6-Phase Execution
### Phase 1: Load Tasks
```javascript
const args = $ARGUMENTS;
const autoYes = /(-y|--yes)/.test(args);
const dryRun = /--dry-run/.test(args);
const taskFilter = args.match(/--task\s+([\w,-]+)/)?.[1]?.split(',') || null;
// Load task files
const taskFiles = Glob('.workflow/.idaw/tasks/IDAW-*.json') || [];
if (taskFiles.length === 0) {
console.log('No IDAW tasks found. Use /idaw:add to create tasks.');
return;
}
// Parse and filter
let tasks = taskFiles.map(f => JSON.parse(Read(f)));
if (taskFilter) {
tasks = tasks.filter(t => taskFilter.includes(t.id));
} else {
tasks = tasks.filter(t => t.status === 'pending');
}
if (tasks.length === 0) {
console.log('No pending tasks to execute. Use /idaw:add to add tasks or --task to specify IDs.');
return;
}
// Sort: priority ASC (1=critical first), then ID ASC
tasks.sort((a, b) => {
if (a.priority !== b.priority) return a.priority - b.priority;
return a.id.localeCompare(b.id);
});
```
### Phase 2: Session Setup
```javascript
// Generate session ID: IDA-{slug}-YYYYMMDD
const slug = tasks[0].title
.toLowerCase()
.replace(/[^a-z0-9]+/g, '-')
.substring(0, 20)
.replace(/-$/, '');
const dateStr = new Date().toISOString().slice(0, 10).replace(/-/g, '');
let sessionId = `IDA-${slug}-${dateStr}`;
// Check collision
const existingSession = Glob(`.workflow/.idaw/sessions/${sessionId}/session.json`);
if (existingSession?.length > 0) {
sessionId = `${sessionId}-2`;
}
const sessionDir = `.workflow/.idaw/sessions/${sessionId}`;
Bash(`mkdir -p "${sessionDir}"`);
const session = {
session_id: sessionId,
status: 'running',
created_at: new Date().toISOString(),
updated_at: new Date().toISOString(),
tasks: tasks.map(t => t.id),
current_task: null,
completed: [],
failed: [],
skipped: []
};
Write(`${sessionDir}/session.json`, JSON.stringify(session, null, 2));
// Initialize progress.md
const progressHeader = `# IDAW Progress — ${sessionId}\nStarted: ${session.created_at}\n\n`;
Write(`${sessionDir}/progress.md`, progressHeader);
// TodoWrite
TodoWrite({
todos: tasks.map((t, i) => ({
content: `IDAW:[${i + 1}/${tasks.length}] ${t.title}`,
status: i === 0 ? 'in_progress' : 'pending',
activeForm: `Executing ${t.title}`
}))
});
```
### Phase 3: Startup Protocol
```javascript
// Check for existing running sessions
const runningSessions = Glob('.workflow/.idaw/sessions/IDA-*/session.json')
?.map(f => JSON.parse(Read(f)))
.filter(s => s.status === 'running' && s.session_id !== sessionId) || [];
if (runningSessions.length > 0) {
if (!autoYes) {
const answer = AskUserQuestion({
questions: [{
question: `Found running session: ${runningSessions[0].session_id}. How to proceed?`,
header: 'Conflict',
multiSelect: false,
options: [
{ label: 'Resume existing', description: 'Use /idaw:resume instead' },
{ label: 'Start fresh', description: 'Continue with new session' },
{ label: 'Abort', description: 'Cancel this run' }
]
}]
});
if (answer.answers?.Conflict === 'Resume existing') {
console.log(`Use: /idaw:resume ${runningSessions[0].session_id}`);
return;
}
if (answer.answers?.Conflict === 'Abort') return;
}
// autoYes or "Start fresh": proceed
}
// Check git status
const gitStatus = Bash('git status --porcelain 2>/dev/null');
if (gitStatus?.trim()) {
if (!autoYes) {
const answer = AskUserQuestion({
questions: [{
question: 'Working tree has uncommitted changes. How to proceed?',
header: 'Git',
multiSelect: false,
options: [
{ label: 'Continue', description: 'Proceed with dirty tree' },
{ label: 'Stash', description: 'git stash before running' },
{ label: 'Abort', description: 'Stop and handle manually' }
]
}]
});
if (answer.answers?.Git === 'Stash') {
Bash('git stash push -m "idaw-pre-run"');
}
if (answer.answers?.Git === 'Abort') return;
}
// autoYes: proceed silently
}
// Dry run: show plan and exit
if (dryRun) {
console.log(`# Dry Run — ${sessionId}\n`);
for (const task of tasks) {
const taskType = task.task_type || inferTaskType(task.title, task.description);
const chain = task.skill_chain || SKILL_CHAIN_MAP[taskType] || SKILL_CHAIN_MAP['feature'];
console.log(`## ${task.id}: ${task.title}`);
console.log(` Type: ${taskType} | Priority: ${task.priority}`);
console.log(` Chain: ${chain.join(' → ')}\n`);
}
console.log(`Total: ${tasks.length} tasks`);
return;
}
```
### Phase 4: Main Loop (serial, one task at a time)
```javascript
for (let taskIdx = 0; taskIdx < tasks.length; taskIdx++) {
const task = tasks[taskIdx];
// Skip completed/failed/skipped
if (['completed', 'failed', 'skipped'].includes(task.status)) continue;
// Resolve skill chain
const resolvedType = task.task_type || inferTaskType(task.title, task.description);
const chain = task.skill_chain || SKILL_CHAIN_MAP[resolvedType] || SKILL_CHAIN_MAP['feature'];
// Update task status → in_progress
task.status = 'in_progress';
task.task_type = resolvedType; // persist inferred type
task.execution.started_at = new Date().toISOString();
Write(`.workflow/.idaw/tasks/${task.id}.json`, JSON.stringify(task, null, 2));
// Update session
session.current_task = task.id;
session.updated_at = new Date().toISOString();
Write(`${sessionDir}/session.json`, JSON.stringify(session, null, 2));
console.log(`\n--- [${taskIdx + 1}/${tasks.length}] ${task.id}: ${task.title} ---`);
console.log(`Chain: ${chain.join(' → ')}`);
// ━━━ Pre-Task CLI Context Analysis (for complex/bugfix tasks) ━━━
if (['bugfix', 'bugfix-hotfix', 'feature-complex'].includes(resolvedType)) {
console.log(` Pre-analysis: gathering context for ${resolvedType} task...`);
const affectedFiles = (task.context?.affected_files || []).join(', ');
const preAnalysisPrompt = `PURPOSE: Pre-analyze codebase context for IDAW task before execution.
TASK: • Understand current state of: ${affectedFiles || 'files related to: ' + task.title} • Identify dependencies and risk areas • Note existing patterns to follow
MODE: analysis
CONTEXT: @**/*
EXPECTED: Brief context summary (affected modules, dependencies, risk areas) in 3-5 bullet points
CONSTRAINTS: Keep concise | Focus on execution-relevant context`;
const preAnalysis = Bash(`ccw cli -p '${preAnalysisPrompt.replace(/'/g, "'\\''")}' --tool gemini --mode analysis 2>&1 || echo "Pre-analysis skipped"`);
task.execution.skill_results.push({
skill: 'cli-pre-analysis',
status: 'completed',
context_summary: preAnalysis?.substring(0, 500),
timestamp: new Date().toISOString()
});
}
// Execute each skill in chain
let previousResult = null;
let taskFailed = false;
for (let skillIdx = 0; skillIdx < chain.length; skillIdx++) {
const skillName = chain[skillIdx];
const skillArgs = assembleSkillArgs(skillName, task, previousResult, autoYes, skillIdx === 0);
console.log(` [${skillIdx + 1}/${chain.length}] ${skillName}`);
try {
const result = Skill({ skill: skillName, args: skillArgs });
previousResult = result;
task.execution.skill_results.push({
skill: skillName,
status: 'completed',
timestamp: new Date().toISOString()
});
} catch (error) {
// ━━━ CLI-Assisted Error Recovery ━━━
// Step 1: Invoke CLI diagnosis (auto-invoke trigger: self-repair fails)
console.log(` Diagnosing failure: ${skillName}...`);
const diagnosisPrompt = `PURPOSE: Diagnose why skill "${skillName}" failed during IDAW task execution.
TASK: • Analyze error: ${String(error).substring(0, 300)} • Check affected files: ${(task.context?.affected_files || []).join(', ') || 'unknown'} • Identify root cause • Suggest fix strategy
MODE: analysis
CONTEXT: @**/* | Memory: IDAW task ${task.id}: ${task.title}
EXPECTED: Root cause + actionable fix recommendation (1-2 sentences)
CONSTRAINTS: Focus on actionable diagnosis`;
const diagnosisResult = Bash(`ccw cli -p '${diagnosisPrompt.replace(/'/g, "'\\''")}' --tool gemini --mode analysis --rule analysis-diagnose-bug-root-cause 2>&1 || echo "CLI diagnosis unavailable"`);
task.execution.skill_results.push({
skill: `cli-diagnosis:${skillName}`,
status: 'completed',
diagnosis: diagnosisResult?.substring(0, 500),
timestamp: new Date().toISOString()
});
// Step 2: Retry with diagnosis context
console.log(` Retry with diagnosis: ${skillName}`);
try {
const retryResult = Skill({ skill: skillName, args: skillArgs });
previousResult = retryResult;
task.execution.skill_results.push({
skill: skillName,
status: 'completed-retry-with-diagnosis',
timestamp: new Date().toISOString()
});
} catch (retryError) {
// Step 3: Failed after CLI-assisted retry
task.execution.skill_results.push({
skill: skillName,
status: 'failed',
error: String(retryError).substring(0, 200),
timestamp: new Date().toISOString()
});
if (autoYes) {
taskFailed = true;
break;
} else {
const answer = AskUserQuestion({
questions: [{
question: `${skillName} failed after CLI diagnosis + retry: ${String(retryError).substring(0, 100)}. How to proceed?`,
header: 'Error',
multiSelect: false,
options: [
{ label: 'Skip task', description: 'Mark task as failed, continue to next' },
{ label: 'Abort', description: 'Stop entire run' }
]
}]
});
if (answer.answers?.Error === 'Abort') {
task.status = 'failed';
task.execution.error = String(retryError).substring(0, 200);
Write(`.workflow/.idaw/tasks/${task.id}.json`, JSON.stringify(task, null, 2));
session.failed.push(task.id);
session.status = 'failed';
session.updated_at = new Date().toISOString();
Write(`${sessionDir}/session.json`, JSON.stringify(session, null, 2));
return;
}
taskFailed = true;
break;
}
}
}
}
// Phase 5: Checkpoint (per task) — inline
if (taskFailed) {
task.status = 'failed';
task.execution.error = 'Skill chain failed after retry';
task.execution.completed_at = new Date().toISOString();
session.failed.push(task.id);
} else {
// Git commit checkpoint
const commitMsg = `feat(idaw): ${task.title} [${task.id}]`;
const diffCheck = Bash('git diff --stat HEAD 2>/dev/null || echo ""');
const untrackedCheck = Bash('git ls-files --others --exclude-standard 2>/dev/null || echo ""');
if (diffCheck?.trim() || untrackedCheck?.trim()) {
Bash('git add -A');
const commitResult = Bash(`git commit -m "$(cat <<'EOF'\n${commitMsg}\nEOF\n)"`);
const commitHash = Bash('git rev-parse --short HEAD 2>/dev/null')?.trim();
task.execution.git_commit = commitHash;
} else {
task.execution.git_commit = 'no-commit';
}
task.status = 'completed';
task.execution.completed_at = new Date().toISOString();
session.completed.push(task.id);
}
// Write task + session state
task.updated_at = new Date().toISOString();
Write(`.workflow/.idaw/tasks/${task.id}.json`, JSON.stringify(task, null, 2));
session.updated_at = new Date().toISOString();
Write(`${sessionDir}/session.json`, JSON.stringify(session, null, 2));
// Append to progress.md
const duration = task.execution.started_at && task.execution.completed_at
? formatDuration(new Date(task.execution.completed_at) - new Date(task.execution.started_at))
: 'unknown';
const progressEntry = `## ${task.id}${task.title}\n` +
`- Status: ${task.status}\n` +
`- Type: ${task.task_type}\n` +
`- Chain: ${chain.join(' → ')}\n` +
`- Commit: ${task.execution.git_commit || '-'}\n` +
`- Duration: ${duration}\n\n`;
const currentProgress = Read(`${sessionDir}/progress.md`);
Write(`${sessionDir}/progress.md`, currentProgress + progressEntry);
// Update TodoWrite
if (taskIdx + 1 < tasks.length) {
TodoWrite({
todos: tasks.map((t, i) => ({
content: `IDAW:[${i + 1}/${tasks.length}] ${t.title}`,
status: i < taskIdx + 1 ? 'completed' : (i === taskIdx + 1 ? 'in_progress' : 'pending'),
activeForm: `Executing ${t.title}`
}))
});
}
}
```
### Phase 6: Report
```javascript
session.status = session.failed.length > 0 && session.completed.length === 0 ? 'failed' : 'completed';
session.current_task = null;
session.updated_at = new Date().toISOString();
Write(`${sessionDir}/session.json`, JSON.stringify(session, null, 2));
// Final progress summary
const summary = `\n---\n## Summary\n` +
`- Completed: ${session.completed.length}\n` +
`- Failed: ${session.failed.length}\n` +
`- Skipped: ${session.skipped.length}\n` +
`- Total: ${tasks.length}\n`;
const finalProgress = Read(`${sessionDir}/progress.md`);
Write(`${sessionDir}/progress.md`, finalProgress + summary);
// Display report
console.log('\n=== IDAW Run Complete ===');
console.log(`Session: ${sessionId}`);
console.log(`Completed: ${session.completed.length}/${tasks.length}`);
if (session.failed.length > 0) console.log(`Failed: ${session.failed.join(', ')}`);
if (session.skipped.length > 0) console.log(`Skipped: ${session.skipped.join(', ')}`);
// List git commits
for (const taskId of session.completed) {
const t = JSON.parse(Read(`.workflow/.idaw/tasks/${taskId}.json`));
if (t.execution.git_commit && t.execution.git_commit !== 'no-commit') {
console.log(` ${t.execution.git_commit} ${t.title}`);
}
}
```
## Helper Functions
### assembleSkillArgs
```javascript
function assembleSkillArgs(skillName, task, previousResult, autoYes, isFirst) {
let args = '';
if (isFirst) {
// First skill: pass task goal — sanitize for shell safety
const goal = `${task.title}\n${task.description}`
.replace(/\\/g, '\\\\')
.replace(/"/g, '\\"')
.replace(/\$/g, '\\$')
.replace(/`/g, '\\`');
args = `"${goal}"`;
// bugfix-hotfix: add --hotfix
if (task.task_type === 'bugfix-hotfix') {
args += ' --hotfix';
}
} else if (previousResult?.session_id) {
// Subsequent skills: chain session
args = `--session="${previousResult.session_id}"`;
}
// Propagate -y
if (autoYes && !args.includes('-y') && !args.includes('--yes')) {
args = args ? `${args} -y` : '-y';
}
return args;
}
```
### formatDuration
```javascript
function formatDuration(ms) {
const seconds = Math.floor(ms / 1000);
const minutes = Math.floor(seconds / 60);
const remainingSeconds = seconds % 60;
if (minutes > 0) return `${minutes}m ${remainingSeconds}s`;
return `${seconds}s`;
}
```
## CLI-Assisted Analysis
IDAW integrates `ccw cli` (Gemini) for intelligent analysis at two key points:
### Pre-Task Context Analysis
For `bugfix`, `bugfix-hotfix`, and `feature-complex` tasks, IDAW automatically invokes CLI analysis **before** executing the skill chain to gather codebase context:
```
Task starts → CLI pre-analysis (gemini) → Context gathered → Skill chain executes
```
- Identifies dependencies and risk areas
- Notes existing patterns to follow
- Results stored in `task.execution.skill_results` as `cli-pre-analysis`
### Error Recovery with CLI Diagnosis
When a skill fails, instead of blind retry, IDAW uses CLI-assisted diagnosis:
```
Skill fails → CLI diagnosis (gemini, analysis-diagnose-bug-root-cause)
→ Root cause identified → Retry with diagnosis context
→ Still fails → Skip (autoYes) or Ask user (interactive)
```
- Uses `--rule analysis-diagnose-bug-root-cause` template
- Diagnosis results stored in `task.execution.skill_results` as `cli-diagnosis:{skill}`
- Follows CLAUDE.md auto-invoke trigger pattern: "self-repair fails → invoke CLI analysis"
### Execution Flow (with CLI analysis)
```
Phase 4 Main Loop (per task):
├─ [bugfix/complex only] CLI pre-analysis → context summary
├─ Skill 1: execute
│ ├─ Success → next skill
│ └─ Failure → CLI diagnosis → retry → success/fail
├─ Skill 2: execute ...
└─ Phase 5: git checkpoint
```
## Examples
```bash
# Execute all pending tasks
/idaw:run -y
# Execute specific tasks
/idaw:run --task IDAW-001,IDAW-003
# Dry run (show plan without executing)
/idaw:run --dry-run
# Interactive mode (confirm at each step)
/idaw:run
```

View File

@@ -0,0 +1,182 @@
---
name: status
description: View IDAW task and session progress
argument-hint: "[session-id]"
allowed-tools: Read(*), Glob(*), Bash(*)
---
# IDAW Status Command (/idaw:status)
## Overview
Read-only command to view IDAW task queue and execution session progress.
## Implementation
### Phase 1: Determine View Mode
```javascript
const sessionId = $ARGUMENTS?.trim();
if (sessionId) {
// Specific session view
showSession(sessionId);
} else {
// Overview: pending tasks + latest session
showOverview();
}
```
### Phase 2: Show Overview
```javascript
function showOverview() {
// 1. Load all tasks
const taskFiles = Glob('.workflow/.idaw/tasks/IDAW-*.json') || [];
if (taskFiles.length === 0) {
console.log('No IDAW tasks found. Use /idaw:add to create tasks.');
return;
}
const tasks = taskFiles.map(f => JSON.parse(Read(f)));
// 2. Group by status
const byStatus = {
pending: tasks.filter(t => t.status === 'pending'),
in_progress: tasks.filter(t => t.status === 'in_progress'),
completed: tasks.filter(t => t.status === 'completed'),
failed: tasks.filter(t => t.status === 'failed'),
skipped: tasks.filter(t => t.status === 'skipped')
};
// 3. Display task summary table
console.log('# IDAW Tasks\n');
console.log('| ID | Title | Type | Priority | Status |');
console.log('|----|-------|------|----------|--------|');
// Sort: priority ASC, then ID ASC
const sorted = [...tasks].sort((a, b) => {
if (a.priority !== b.priority) return a.priority - b.priority;
return a.id.localeCompare(b.id);
});
for (const t of sorted) {
const type = t.task_type || '(infer)';
console.log(`| ${t.id} | ${t.title.substring(0, 40)} | ${type} | ${t.priority} | ${t.status} |`);
}
console.log(`\nTotal: ${tasks.length} | Pending: ${byStatus.pending.length} | Completed: ${byStatus.completed.length} | Failed: ${byStatus.failed.length}`);
// 4. Show latest session (if any)
const sessionDirs = Glob('.workflow/.idaw/sessions/IDA-*/session.json') || [];
if (sessionDirs.length > 0) {
// Sort by modification time (newest first) — Glob returns sorted by mtime
const latestSessionFile = sessionDirs[0];
const session = JSON.parse(Read(latestSessionFile));
console.log(`\n## Latest Session: ${session.session_id}`);
console.log(`Status: ${session.status} | Tasks: ${session.tasks?.length || 0}`);
console.log(`Completed: ${session.completed?.length || 0} | Failed: ${session.failed?.length || 0} | Skipped: ${session.skipped?.length || 0}`);
}
}
```
### Phase 3: Show Specific Session
```javascript
function showSession(sessionId) {
const sessionFile = `.workflow/.idaw/sessions/${sessionId}/session.json`;
const progressFile = `.workflow/.idaw/sessions/${sessionId}/progress.md`;
// Try reading session
try {
const session = JSON.parse(Read(sessionFile));
console.log(`# IDAW Session: ${session.session_id}\n`);
console.log(`Status: ${session.status}`);
console.log(`Created: ${session.created_at}`);
console.log(`Updated: ${session.updated_at}`);
console.log(`Current Task: ${session.current_task || 'none'}\n`);
// Task detail table
console.log('| ID | Title | Status | Commit |');
console.log('|----|-------|--------|--------|');
for (const taskId of session.tasks) {
const taskFile = `.workflow/.idaw/tasks/${taskId}.json`;
try {
const task = JSON.parse(Read(taskFile));
const commit = task.execution?.git_commit?.substring(0, 7) || '-';
console.log(`| ${task.id} | ${task.title.substring(0, 40)} | ${task.status} | ${commit} |`);
} catch {
console.log(`| ${taskId} | (file not found) | unknown | - |`);
}
}
console.log(`\nCompleted: ${session.completed?.length || 0} | Failed: ${session.failed?.length || 0} | Skipped: ${session.skipped?.length || 0}`);
// Show progress.md if exists
try {
const progress = Read(progressFile);
console.log('\n---\n');
console.log(progress);
} catch {
// No progress file yet
}
} catch {
// Session not found — try listing all sessions
console.log(`Session "${sessionId}" not found.\n`);
listSessions();
}
}
```
### Phase 4: List All Sessions
```javascript
function listSessions() {
const sessionFiles = Glob('.workflow/.idaw/sessions/IDA-*/session.json') || [];
if (sessionFiles.length === 0) {
console.log('No IDAW sessions found. Use /idaw:run to start execution.');
return;
}
console.log('# IDAW Sessions\n');
console.log('| Session ID | Status | Tasks | Completed | Failed |');
console.log('|------------|--------|-------|-----------|--------|');
for (const f of sessionFiles) {
try {
const session = JSON.parse(Read(f));
console.log(`| ${session.session_id} | ${session.status} | ${session.tasks?.length || 0} | ${session.completed?.length || 0} | ${session.failed?.length || 0} |`);
} catch {
// Skip malformed
}
}
console.log('\nUse /idaw:status <session-id> for details.');
}
```
## Examples
```bash
# Show overview (pending tasks + latest session)
/idaw:status
# Show specific session details
/idaw:status IDA-auth-fix-20260301
# Output example:
# IDAW Tasks
#
# | ID | Title | Type | Priority | Status |
# |----------|------------------------------------|--------|----------|-----------|
# | IDAW-001 | Fix auth token refresh | bugfix | 1 | completed |
# | IDAW-002 | Add rate limiting | feature| 2 | pending |
# | IDAW-003 | Refactor payment module | refact | 3 | pending |
#
# Total: 3 | Pending: 2 | Completed: 1 | Failed: 0
```

View File

@@ -252,6 +252,17 @@ await updateDiscoveryState(outputDir, {
const hasHighPriority = issues.some(i => i.priority === 'critical' || i.priority === 'high');
const hasMediumFindings = prioritizedFindings.some(f => f.priority === 'medium');
// Auto mode: auto-select recommended action
if (autoYes) {
if (hasHighPriority) {
await appendJsonl('.workflow/issues/issues.jsonl', issues);
console.log(`Exported ${issues.length} issues. Run /issue:plan to continue.`);
} else {
console.log('Discovery complete. No significant issues found.');
}
return;
}
await AskUserQuestion({
questions: [{
question: `Discovery complete: ${issues.length} issues generated, ${prioritizedFindings.length} total findings. What would you like to do next?`,

View File

@@ -152,6 +152,12 @@ if (!QUEUE_ID) {
return;
}
// Auto mode: auto-select if exactly one active queue
if (autoYes && activeQueues.length === 1) {
QUEUE_ID = activeQueues[0].id;
console.log(`Auto-selected queue: ${QUEUE_ID}`);
} else {
// Display and prompt user
console.log('\nAvailable Queues:');
console.log('ID'.padEnd(22) + 'Status'.padEnd(12) + 'Progress'.padEnd(12) + 'Issues');
@@ -176,6 +182,7 @@ if (!QUEUE_ID) {
});
QUEUE_ID = answer['Queue'];
} // end else (multi-queue prompt)
}
console.log(`\n## Executing Queue: ${QUEUE_ID}\n`);
@@ -203,6 +210,13 @@ console.log(`
- Parallel in batch 1: ${dag.parallel_batches[0]?.length || 0}
`);
// Auto mode: use recommended defaults (Codex + Execute + Worktree)
if (autoYes) {
var executor = 'codex';
var isDryRun = false;
var useWorktree = true;
} else {
// Interactive selection via AskUserQuestion
const answer = AskUserQuestion({
questions: [
@@ -237,9 +251,10 @@ const answer = AskUserQuestion({
]
});
const executor = answer['Executor'].toLowerCase().split(' ')[0]; // codex|gemini|agent
const isDryRun = answer['Mode'].includes('Dry-run');
const useWorktree = answer['Worktree'].includes('Yes');
var executor = answer['Executor'].toLowerCase().split(' ')[0]; // codex|gemini|agent
var isDryRun = answer['Mode'].includes('Dry-run');
var useWorktree = answer['Worktree'].includes('Yes');
} // end else (interactive selection)
// Dry run mode
if (isDryRun) {
@@ -451,27 +466,33 @@ if (refreshedDag.ready_count > 0) {
if (useWorktree && refreshedDag.ready_count === 0 && refreshedDag.completed_count === refreshedDag.total) {
console.log('\n## All Solutions Completed - Worktree Cleanup');
const answer = AskUserQuestion({
questions: [{
question: `Queue complete. What to do with worktree branch "${worktreeBranch}"?`,
header: 'Merge',
multiSelect: false,
options: [
{ label: 'Create PR (Recommended)', description: 'Push branch and create pull request' },
{ label: 'Merge to main', description: 'Merge all commits and cleanup worktree' },
{ label: 'Keep branch', description: 'Cleanup worktree, keep branch for manual handling' }
]
}]
});
// Auto mode: Create PR (recommended)
if (autoYes) {
var mergeAction = 'Create PR';
} else {
const answer = AskUserQuestion({
questions: [{
question: `Queue complete. What to do with worktree branch "${worktreeBranch}"?`,
header: 'Merge',
multiSelect: false,
options: [
{ label: 'Create PR (Recommended)', description: 'Push branch and create pull request' },
{ label: 'Merge to main', description: 'Merge all commits and cleanup worktree' },
{ label: 'Keep branch', description: 'Cleanup worktree, keep branch for manual handling' }
]
}]
});
var mergeAction = answer['Merge'];
}
const repoRoot = Bash('git rev-parse --show-toplevel').trim();
if (answer['Merge'].includes('Create PR')) {
if (mergeAction.includes('Create PR')) {
Bash(`git -C "${worktreePath}" push -u origin "${worktreeBranch}"`);
Bash(`gh pr create --title "Queue ${dag.queue_id}" --body "Issue queue execution - all solutions completed" --head "${worktreeBranch}"`);
Bash(`git worktree remove "${worktreePath}"`);
console.log(`PR created for branch: ${worktreeBranch}`);
} else if (answer['Merge'].includes('Merge to main')) {
} else if (mergeAction.includes('Merge to main')) {
// Check main is clean
const mainDirty = Bash('git status --porcelain').trim();
if (mainDirty) {

View File

@@ -154,8 +154,8 @@ Phase 6: Bind Solution
├─ Update issue status to 'planned'
└─ Returns: SOL-{issue-id}-{uid}
Phase 7: Next Steps
└─ Offer: Form queue | Convert another idea | View details | Done
Phase 7: Next Steps (skip in auto mode)
└─ Auto mode: complete directly | Interactive: Form queue | Convert another | Done
```
## Context Enrichment Logic

View File

@@ -160,7 +160,7 @@ ${issueList}
### Project Context (MANDATORY)
1. Read: .workflow/project-tech.json (technology stack, architecture)
2. Read: .workflow/project-guidelines.json (constraints and conventions)
2. Read: .workflow/specs/*.md (constraints and conventions)
### Workflow
1. Fetch issue details: ccw issue status <id> --json
@@ -263,6 +263,14 @@ for (let i = 0; i < agentTasks.length; i += MAX_PARALLEL) {
for (const pending of pendingSelections) {
if (pending.solutions.length === 0) continue;
// Auto mode: auto-bind first (highest-ranked) solution
if (autoYes) {
const solId = pending.solutions[0].id;
Bash(`ccw issue bind ${pending.issue_id} ${solId}`);
console.log(`${pending.issue_id}: ${solId} bound (auto)`);
continue;
}
const options = pending.solutions.slice(0, 4).map(sol => ({
label: `${sol.id} (${sol.task_count} tasks)`,
description: sol.description || sol.approach || 'No description'

View File

@@ -273,6 +273,17 @@ const allClarifications = results.flatMap((r, i) =>
```javascript
if (allClarifications.length > 0) {
for (const clarification of allClarifications) {
// Auto mode: use recommended resolution (first option)
if (autoYes) {
const autoAnswer = clarification.options[0]?.label || 'skip';
Task(
subagent_type="issue-queue-agent",
resume=clarification.agent_id,
prompt=`Conflict ${clarification.conflict_id} resolved: ${autoAnswer}`
);
continue;
}
// Present to user via AskUserQuestion
const answer = AskUserQuestion({
questions: [{
@@ -345,6 +356,14 @@ ccw issue queue list --brief
**AskUserQuestion:**
```javascript
// Auto mode: merge into existing queue
if (autoYes) {
Bash(`ccw issue queue merge ${newQueueId} --queue ${activeQueueId}`);
Bash(`ccw issue queue delete ${newQueueId}`);
console.log(`Auto-merged new queue into ${activeQueueId}`);
return;
}
AskUserQuestion({
questions: [{
question: "Active queue exists. How would you like to proceed?",

View File

@@ -451,7 +451,20 @@ CONSTRAINTS: ${perspective.constraints}
- Corrected assumptions
- New insights
5. **Repeat or Converge**
5. **📌 Intent Drift Check** (every round ≥ 2)
- Re-read "User Intent" from discussion.md header
- For each original intent item, check: addressed / in-progress / not yet discussed / implicitly absorbed
- If any item is "implicitly absorbed" (addressed by a different solution than originally envisioned), explicitly note this in discussion.md:
```markdown
#### Intent Coverage Check
- ✅ Intent 1: [addressed in Round N]
- 🔄 Intent 2: [in-progress, current focus]
- ⚠️ Intent 3: [implicitly absorbed by X — needs explicit confirmation]
- ❌ Intent 4: [not yet discussed]
```
- If any item is ❌ or ⚠️ after 3+ rounds, surface it to the user in the next round's presentation
6. **Repeat or Converge**
- Continue loop (max 5 rounds) or exit to Phase 4
**Discussion Actions**:
@@ -482,7 +495,28 @@ CONSTRAINTS: ${perspective.constraints}
**Workflow Steps**:
1. **Consolidate Insights**
1. **📌 Intent Coverage Verification** (MANDATORY before synthesis)
- Re-read all original "User Intent" items from discussion.md header
- For EACH intent item, determine coverage status:
- **✅ Addressed**: Explicitly discussed and concluded with clear design/recommendation
- **🔀 Transformed**: Original intent evolved into a different solution — document the transformation chain
- **⚠️ Absorbed**: Implicitly covered by a broader solution — flag for explicit confirmation
- **❌ Missed**: Not discussed — MUST be either addressed now or explicitly listed as out-of-scope with reason
- Write "Intent Coverage Matrix" to discussion.md:
```markdown
### Intent Coverage Matrix
| # | Original Intent | Status | Where Addressed | Notes |
|---|----------------|--------|-----------------|-------|
| 1 | [intent text] | ✅ Addressed | Round N, Conclusion #M | |
| 2 | [intent text] | 🔀 Transformed | Round N → Round M | Original: X → Final: Y |
| 3 | [intent text] | ❌ Missed | — | Reason for omission |
```
- **Gate**: If any item is ❌ Missed, MUST either:
- (a) Add a dedicated discussion round to address it before continuing, OR
- (b) Explicitly confirm with user that it is intentionally deferred
- Add `intent_coverage[]` to conclusions.json
2. **Consolidate Insights**
- Extract all findings from discussion timeline
- **📌 Compile Decision Trail**: Aggregate all Decision Records from Phases 1-3 into a consolidated decision log
- **Key conclusions**: Main points with evidence and confidence levels (high/medium/low)
@@ -492,7 +526,7 @@ CONSTRAINTS: ${perspective.constraints}
- **📌 Decision summary**: How key decisions shaped the final conclusions (link conclusions back to decisions)
- Write to conclusions.json
2. **Final discussion.md Update**
3. **Final discussion.md Update**
- Append conclusions section:
- **Summary**: High-level overview
- **Key Conclusions**: Ranked with evidence and confidence
@@ -508,11 +542,86 @@ CONSTRAINTS: ${perspective.constraints}
- **Trade-offs Made**: Key trade-offs and why certain paths were chosen over others
- Add session statistics: rounds, duration, sources, artifacts, **decision count**
3. **Post-Completion Options** (AskUserQuestion)
- **创建Issue**: Launch issue-discover with conclusions
- **生成任务**: Launch workflow-lite-plan for implementation
- **导出报告**: Generate standalone analysis report
- **完成**: No further action
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
const hasActionableRecs = conclusions.recommendations?.some(r => r.priority === 'high' || r.priority === 'medium')
const nextStep = AskUserQuestion({
questions: [{
question: "Report generated. What would you like to do next?",
header: "Next Step",
multiSelect: false,
options: [
{ label: hasActionableRecs ? "执行任务 (Recommended)" : "执行任务", description: "Launch workflow-lite-planex to plan & execute" },
{ label: "产出Issue", description: "Launch issue-discover with conclusions" },
{ label: "完成", description: "No further action" }
]
}]
})
```
**Handle "执行任务"** (⚠️ TERMINAL — analyze-with-file ends here, lite-plan takes over exclusively):
```javascript
if (nextStep.includes("执行任务")) {
// 1. Build task description from high/medium priority recommendations
const taskDescription = conclusions.recommendations
.filter(r => r.priority === 'high' || r.priority === 'medium')
.map(r => r.action)
.join('\n') || conclusions.summary
// 2. Assemble compact analysis context as inline memory block
const contextLines = [
`## Prior Analysis (${sessionId})`,
`**Summary**: ${conclusions.summary}`
]
const codebasePath = `${sessionFolder}/exploration-codebase.json`
if (file_exists(codebasePath)) {
const data = JSON.parse(Read(codebasePath))
const files = (data.relevant_files || []).slice(0, 8).map(f => f.path || f.file || f).filter(Boolean)
const findings = (data.key_findings || []).slice(0, 5)
if (files.length) contextLines.push(`**Key Files**: ${files.join(', ')}`)
if (findings.length) contextLines.push(`**Key Findings**:\n${findings.map(f => `- ${f}`).join('\n')}`)
}
// 3. ⛔ SESSION TERMINATION — output explicit boundary
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
}
```
**conclusions.json Schema**:
- `session_id`: Session identifier
@@ -525,10 +634,12 @@ CONSTRAINTS: ${perspective.constraints}
- `open_questions[]`: Unresolved questions
- `follow_up_suggestions[]`: {type, summary}
- `decision_trail[]`: {round, decision, context, options_considered, chosen, reason, impact}
- `intent_coverage[]`: {intent, status, where_addressed, notes}
**Success Criteria**:
- conclusions.json created with final synthesis
- discussion.md finalized with conclusions and decision trail
- **📌 Intent Coverage Matrix** verified — all original intents accounted for (no ❌ Missed without explicit user deferral)
- User offered next step options
- Session complete
- **📌 Complete decision trail** documented and traceable from initial scoping to final conclusions
@@ -686,11 +797,13 @@ User agrees with current direction, wants deeper code analysis
- Quick information gathering without multi-round iteration
- 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)
- Need simple task breakdown
- 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.
---
**Now execute analyze-with-file for**: $ARGUMENTS

View File

@@ -769,7 +769,7 @@ See full markdown template in original file (lines 955-1161).
- Want shared collaborative planning document
- 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
- Ready to move from ideas to execution
- Need simple implementation breakdown

View File

@@ -475,21 +475,43 @@ if (selectedCategories.includes('Sessions')) {
}
}
// Update project-tech.json if features referenced deleted sessions
// Update project-tech.json: remove development_index entries referencing deleted sessions
const projectPath = '.workflow/project-tech.json'
if (fileExists(projectPath)) {
const project = JSON.parse(Read(projectPath))
const deletedPaths = new Set(results.deleted)
const deletedSessionIds = results.deleted
.filter(p => p.match(/WFS-|lite-plan/))
.map(p => p.split('/').pop())
project.features = project.features.filter(f =>
!deletedPaths.has(f.traceability?.archive_path)
)
project.statistics.total_features = project.features.length
project.statistics.last_updated = getUtc8ISOString()
if (project.development_index) {
for (const category of Object.keys(project.development_index)) {
project.development_index[category] = project.development_index[category].filter(entry =>
!deletedSessionIds.includes(entry.session_id)
)
}
}
project._metadata.last_updated = getUtc8ISOString()
Write(projectPath, JSON.stringify(project, null, 2))
}
// Update specs/*.md: remove learnings referencing deleted sessions
const guidelinesPath = '.ccw/specs/*.md'
if (fileExists(guidelinesPath)) {
const guidelines = JSON.parse(Read(guidelinesPath))
const deletedSessionIds = results.deleted
.filter(p => p.match(/WFS-|lite-plan/))
.map(p => p.split('/').pop())
if (guidelines.learnings) {
guidelines.learnings = guidelines.learnings.filter(l =>
!deletedSessionIds.includes(l.session_id)
)
}
guidelines._metadata.updated_at = getUtc8ISOString()
Write(guidelinesPath, JSON.stringify(guidelines, null, 2))
}
```
**Step 4.4: Report Results**
@@ -541,8 +563,10 @@ Cleanup manifest archived to: ${sessionFolder}/cleanup-manifest.json
| Manifest parse error | Regenerate from filesystem scan |
| Empty discovery | Report "codebase is clean" |
## Related Commands
- `/workflow:session:sync` - Sync session work to specs/*.md + project-tech (正向写入)
- `/workflow:session:complete` - Properly archive active sessions
- `memory-capture` skill - Save session memory before cleanup
- `workflow-execute` skill - View current workflow state

View File

@@ -205,6 +205,11 @@ Task(
1. **Prioritize Latest Documentation**: Search for and reference latest README, design docs, architecture guides when available
2. **Handle Ambiguities**: When requirement ambiguities exist, ask user for clarification (use AskUserQuestion) instead of assuming interpretations
### Project Context (MANDATORY)
Read and incorporate:
- \`.workflow/project-tech.json\` (if exists): Technology stack, architecture
- \`.ccw/specs/*.md\` (if exists): Constraints, conventions -- apply as HARD CONSTRAINTS on sub-domain splitting and plan structure
### Input Requirements
${taskDescription}
@@ -349,21 +354,19 @@ subDomains.map(sub =>
**TASK ID Range**: ${sub.task_id_range[0]}-${sub.task_id_range[1]}
**Session**: ${sessionId}
### Project Context (MANDATORY)
Read and incorporate:
- \`.workflow/project-tech.json\` (if exists): Technology stack, architecture
- \`.ccw/specs/*.md\` (if exists): Constraints, conventions -- apply as HARD CONSTRAINTS
## Dual Output Tasks
### Task 1: Generate Two-Layer Plan Output
Output: ${sessionFolder}/agents/${sub.focus_area}/plan.json (overview with task_ids[])
Output: ${sessionFolder}/agents/${sub.focus_area}/.task/TASK-*.json (independent task files)
Output: ${sessionFolder}/agents/${sub.focus_area}/plan.json
Output: ${sessionFolder}/agents/${sub.focus_area}/.task/TASK-*.json
Schema (plan): ~/.ccw/workflows/cli-templates/schemas/plan-overview-base-schema.json
Schema (tasks): ~/.ccw/workflows/cli-templates/schemas/task-schema.json
**Two-Layer Output Format**:
- plan.json: Overview with task_ids[] referencing .task/ files (NO tasks[] array)
- .task/TASK-*.json: Independent task files following task-schema.json
- plan.json required: summary, approach, task_ids, task_count, _metadata (with plan_type)
- Task files required: id, title, description, depends_on, convergence (with criteria[])
- Task fields: files[].change (not modification_points), convergence.criteria (not acceptance), test (not verification)
### Task 2: Sync Summary to plan-note.md
**Locate Your Sections**:

View File

@@ -630,6 +630,16 @@ Why is config value None during update?
## Post-Completion Expansion
**Auto-sync**: 执行 `/workflow:session:sync -y "{summary}"` 更新 specs/*.md + project-tech。
```javascript
// Auto mode: skip expansion question, complete session directly
if (autoYes) {
console.log('Debug session complete. Auto mode: skipping expansion.');
return;
}
```
完成后询问用户是否扩展为issue(test/enhance/refactor/doc),选中项调用 `/issue:new "{summary} - {dimension}"`
---
@@ -641,6 +651,6 @@ Why is config value None during update?
| Empty debug.log | Verify reproduction triggered the code path |
| 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 |
| >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 |
| Understanding too long | Consolidate aggressively, archive old iterations to separate file |

View File

@@ -1,6 +1,6 @@
---
name: init-guidelines
description: Interactive wizard to fill project-guidelines.json based on project analysis
description: Interactive wizard to fill specs/*.md based on project analysis
argument-hint: "[--reset]"
examples:
- /workflow:init-guidelines
@@ -11,7 +11,7 @@ examples:
## Overview
Interactive multi-round wizard that analyzes the current project (via `project-tech.json`) and asks targeted questions to populate `.workflow/project-guidelines.json` with coding conventions, constraints, and quality rules.
Interactive multi-round wizard that analyzes the current project (via `project-tech.json`) and asks targeted questions to populate `.ccw/specs/*.md` with coding conventions, constraints, and quality rules.
**Design Principle**: Questions are dynamically generated based on the project's tech stack, architecture, and patterns — not generic boilerplate.
@@ -31,7 +31,7 @@ Input Parsing:
Step 1: Check Prerequisites
├─ project-tech.json must exist (run /workflow:init first)
├─ project-guidelines.json: check if populated or scaffold-only
├─ specs/*.md: check if populated or scaffold-only
└─ If populated + no --reset → Ask: "Guidelines already exist. Overwrite or append?"
Step 2: Load Project Context
@@ -44,7 +44,7 @@ Step 3: Multi-Round Interactive Questionnaire
├─ Round 4: Performance & Security Constraints (performance, security)
└─ Round 5: Quality Rules (quality_rules)
Step 4: Write project-guidelines.json
Step 4: Write specs/*.md
Step 5: Display Summary
```
@@ -55,7 +55,7 @@ Step 5: Display Summary
```bash
bash(test -f .workflow/project-tech.json && echo "TECH_EXISTS" || echo "TECH_NOT_FOUND")
bash(test -f .workflow/project-guidelines.json && echo "GUIDELINES_EXISTS" || echo "GUIDELINES_NOT_FOUND")
bash(test -f .ccw/specs/coding-conventions.md && echo "SPECS_EXISTS" || echo "SPECS_NOT_FOUND")
```
**If TECH_NOT_FOUND**: Exit with message
@@ -71,12 +71,10 @@ const reset = $ARGUMENTS.includes('--reset')
**If GUIDELINES_EXISTS and not --reset**: Check if guidelines are populated (not just scaffold)
```javascript
const guidelines = JSON.parse(Read('.workflow/project-guidelines.json'))
const isPopulated =
guidelines.conventions.coding_style.length > 0 ||
guidelines.conventions.naming_patterns.length > 0 ||
guidelines.constraints.architecture.length > 0 ||
guidelines.constraints.tech_stack.length > 0
// Check if specs already have content via ccw spec list
const specsList = Bash('ccw spec list --json 2>/dev/null || echo "{}"')
const specsData = JSON.parse(specsList)
const isPopulated = (specsData.total || 0) > 5 // More than seed docs
if (isPopulated) {
AskUserQuestion({
@@ -100,22 +98,18 @@ if (isPopulated) {
### Step 2: Load Project Context
```javascript
const projectTech = JSON.parse(Read('.workflow/project-tech.json'))
// Load project context via ccw spec load for planning context
const projectContext = Bash('ccw spec load --category planning 2>/dev/null || echo "{}"')
const specData = JSON.parse(projectContext)
// Extract key info for generating smart questions
const languages = projectTech.technology_analysis?.technology_stack?.languages
|| projectTech.overview?.technology_stack?.languages || []
// Extract key info from loaded specs for generating smart questions
const languages = specData.overview?.technology_stack?.languages || []
const primaryLang = languages.find(l => l.primary)?.name || languages[0]?.name || 'Unknown'
const frameworks = projectTech.technology_analysis?.technology_stack?.frameworks
|| projectTech.overview?.technology_stack?.frameworks || []
const testFrameworks = projectTech.technology_analysis?.technology_stack?.test_frameworks
|| projectTech.overview?.technology_stack?.test_frameworks || []
const archStyle = projectTech.technology_analysis?.architecture?.style
|| projectTech.overview?.architecture?.style || 'Unknown'
const archPatterns = projectTech.technology_analysis?.architecture?.patterns
|| projectTech.overview?.architecture?.patterns || []
const buildTools = projectTech.technology_analysis?.technology_stack?.build_tools
|| projectTech.overview?.technology_stack?.build_tools || []
const frameworks = specData.overview?.technology_stack?.frameworks || []
const testFrameworks = specData.overview?.technology_stack?.test_frameworks || []
const archStyle = specData.overview?.architecture?.style || 'Unknown'
const archPatterns = specData.overview?.architecture?.patterns || []
const buildTools = specData.overview?.technology_stack?.build_tools || []
```
### Step 3: Multi-Round Interactive Questionnaire
@@ -326,64 +320,115 @@ AskUserQuestion({
**Process Round 5 answers** → add to `quality_rules` array as `{ rule, scope, enforced_by }` objects.
### Step 4: Write project-guidelines.json
### Step 4: Write specs/*.md
For each category of collected answers, append rules to the corresponding spec MD file. Each spec file uses YAML frontmatter with `readMode`, `priority`, `category`, and `keywords`.
**Category Assignment**: Based on the round and question type:
- Round 1-2 (conventions): `category: general` (applies to all stages)
- Round 3 (architecture/tech): `category: planning` (planning phase)
- Round 4 (performance/security): `category: execution` (implementation phase)
- Round 5 (quality): `category: execution` (testing phase)
```javascript
// Build the final guidelines object
const finalGuidelines = {
conventions: {
coding_style: existingCodingStyle.concat(newCodingStyle),
naming_patterns: existingNamingPatterns.concat(newNamingPatterns),
file_structure: existingFileStructure.concat(newFileStructure),
documentation: existingDocumentation.concat(newDocumentation)
},
constraints: {
architecture: existingArchitecture.concat(newArchitecture),
tech_stack: existingTechStack.concat(newTechStack),
performance: existingPerformance.concat(newPerformance),
security: existingSecurity.concat(newSecurity)
},
quality_rules: existingQualityRules.concat(newQualityRules),
learnings: existingLearnings, // Preserve existing learnings
_metadata: {
created_at: existingMetadata?.created_at || new Date().toISOString(),
version: "1.0.0",
last_updated: new Date().toISOString(),
updated_by: "workflow:init-guidelines"
// Helper: append rules to a spec MD file with category support
// Uses .ccw/specs/ directory (same as frontend/backend spec-index-builder)
function appendRulesToSpecFile(filePath, rules, defaultCategory = 'general') {
if (rules.length === 0) return
// Ensure .ccw/specs/ directory exists
const specDir = path.dirname(filePath)
if (!fs.existsSync(specDir)) {
fs.mkdirSync(specDir, { recursive: true })
}
// Check if file exists
if (!file_exists(filePath)) {
// Create file with frontmatter including category
const frontmatter = `---
title: ${filePath.includes('conventions') ? 'Coding Conventions' : filePath.includes('constraints') ? 'Architecture Constraints' : 'Quality Rules'}
readMode: optional
priority: medium
category: ${defaultCategory}
scope: project
dimension: specs
keywords: [${defaultCategory}, ${filePath.includes('conventions') ? 'convention' : filePath.includes('constraints') ? 'constraint' : 'quality'}]
---
# ${filePath.includes('conventions') ? 'Coding Conventions' : filePath.includes('constraints') ? 'Architecture Constraints' : 'Quality Rules'}
`
Write(filePath, frontmatter)
}
const existing = Read(filePath)
// Append new rules as markdown list items after existing content
const newContent = existing.trimEnd() + '\n' + rules.map(r => `- ${r}`).join('\n') + '\n'
Write(filePath, newContent)
}
Write('.workflow/project-guidelines.json', JSON.stringify(finalGuidelines, null, 2))
// Write conventions (general category) - use .ccw/specs/ (same as frontend/backend)
appendRulesToSpecFile('.ccw/specs/coding-conventions.md',
[...newCodingStyle, ...newNamingPatterns, ...newFileStructure, ...newDocumentation],
'general')
// Write constraints (planning category)
appendRulesToSpecFile('.ccw/specs/architecture-constraints.md',
[...newArchitecture, ...newTechStack, ...newPerformance, ...newSecurity],
'planning')
// Write quality rules (execution category)
if (newQualityRules.length > 0) {
const qualityPath = '.ccw/specs/quality-rules.md'
if (!file_exists(qualityPath)) {
Write(qualityPath, `---
title: Quality Rules
readMode: required
priority: high
category: execution
scope: project
dimension: specs
keywords: [execution, quality, testing, coverage, lint]
---
# Quality Rules
`)
}
appendRulesToSpecFile(qualityPath,
newQualityRules.map(q => `${q.rule} (scope: ${q.scope}, enforced by: ${q.enforced_by})`),
'execution')
}
// Rebuild spec index after writing
Bash('ccw spec rebuild')
```
### Step 5: Display Summary
```javascript
const countConventions = finalGuidelines.conventions.coding_style.length
+ finalGuidelines.conventions.naming_patterns.length
+ finalGuidelines.conventions.file_structure.length
+ finalGuidelines.conventions.documentation.length
const countConventions = newCodingStyle.length + newNamingPatterns.length
+ newFileStructure.length + newDocumentation.length
const countConstraints = newArchitecture.length + newTechStack.length
+ newPerformance.length + newSecurity.length
const countQuality = newQualityRules.length
const countConstraints = finalGuidelines.constraints.architecture.length
+ finalGuidelines.constraints.tech_stack.length
+ finalGuidelines.constraints.performance.length
+ finalGuidelines.constraints.security.length
const countQuality = finalGuidelines.quality_rules.length
// Get updated spec list
const specsList = Bash('ccw spec list --json 2>/dev/null || echo "{}"')
console.log(`
✓ Project guidelines configured
## Summary
- Conventions: ${countConventions} rules (coding: ${cs}, naming: ${np}, files: ${fs}, docs: ${doc})
- Constraints: ${countConstraints} rules (arch: ${ar}, tech: ${ts}, perf: ${pf}, security: ${sc})
- Quality rules: ${countQuality}
- Conventions: ${countConventions} rules added to coding-conventions.md
- Constraints: ${countConstraints} rules added to architecture-constraints.md
- Quality rules: ${countQuality} rules added to quality-rules.md
File: .workflow/project-guidelines.json
Spec index rebuilt. Use \`ccw spec list\` to view all specs.
Next steps:
- Use /workflow:session:solidify to add individual rules later
- Guidelines will be auto-loaded by /workflow:plan for task generation
- Specs are auto-loaded via hook on each prompt
`)
```
@@ -405,4 +450,5 @@ When converting user selections to guideline entries:
## Related Commands
- `/workflow:init` - Creates scaffold; optionally calls this command
- `/workflow:init-specs` - Interactive wizard to create individual specs with scope selection
- `/workflow:session:solidify` - Add individual rules one at a time

View File

@@ -0,0 +1,380 @@
---
name: init-specs
description: Interactive wizard to create individual specs or personal constraints with scope selection
argument-hint: "[--scope <global|project>] [--dimension <specs|personal>] [--category <general|exploration|planning|execution>]"
examples:
- /workflow:init-specs
- /workflow:init-specs --scope global --dimension personal
- /workflow:init-specs --scope project --dimension specs
---
# Workflow Init Specs Command (/workflow:init-specs)
## Overview
Interactive wizard for creating individual specs or personal constraints with scope selection. This command provides a guided experience for adding new rules to the spec system.
**Key Features**:
- Supports both project specs and personal specs
- Scope selection (global vs project) for personal specs
- Category-based organization for workflow stages
- Interactive mode with smart defaults
## Usage
```bash
/workflow:init-specs # Interactive mode (all prompts)
/workflow:init-specs --scope global # Create global personal spec
/workflow:init-specs --scope project # Create project spec (default)
/workflow:init-specs --dimension specs # Project conventions/constraints
/workflow:init-specs --dimension personal # Personal preferences
/workflow:init-specs --category exploration # Workflow stage category
```
## Parameters
| Parameter | Values | Default | Description |
|-----------|--------|---------|-------------|
| `--scope` | `global`, `project` | `project` | Where to store the spec (only for personal dimension) |
| `--dimension` | `specs`, `personal` | Interactive | Type of spec to create |
| `--category` | `general`, `exploration`, `planning`, `execution` | `general` | Workflow stage category |
## Execution Process
```
Input Parsing:
├─ Parse --scope (global | project)
├─ Parse --dimension (specs | personal)
└─ Parse --category (general | exploration | planning | execution)
Step 1: Gather Requirements (Interactive)
├─ If dimension not specified → Ask dimension
├─ If personal + scope not specified → Ask scope
├─ If category not specified → Ask category
├─ Ask type (convention | constraint | learning)
└─ Ask content (rule text)
Step 2: Determine Target File
├─ specs dimension → .ccw/specs/coding-conventions.md or architecture-constraints.md
└─ personal dimension → ~/.ccw/specs/personal/ or .ccw/specs/personal/
Step 3: Write Spec
├─ Check if file exists, create if needed with proper frontmatter
├─ Append rule to appropriate section
└─ Run ccw spec rebuild
Step 4: Display Confirmation
```
## Implementation
### Step 1: Parse Input and Gather Requirements
```javascript
// Parse arguments
const args = $ARGUMENTS.toLowerCase()
const hasScope = args.includes('--scope')
const hasDimension = args.includes('--dimension')
const hasCategory = args.includes('--category')
// Extract values from arguments
let scope = hasScope ? args.match(/--scope\s+(\w+)/)?.[1] : null
let dimension = hasDimension ? args.match(/--dimension\s+(\w+)/)?.[1] : null
let category = hasCategory ? args.match(/--category\s+(\w+)/)?.[1] : null
// Validate values
if (scope && !['global', 'project'].includes(scope)) {
console.log("Invalid scope. Use 'global' or 'project'.")
return
}
if (dimension && !['specs', 'personal'].includes(dimension)) {
console.log("Invalid dimension. Use 'specs' or 'personal'.")
return
}
if (category && !['general', 'exploration', 'planning', 'execution'].includes(category)) {
console.log("Invalid category. Use 'general', 'exploration', 'planning', or 'execution'.")
return
}
```
### Step 2: Interactive Questions
**If dimension not specified**:
```javascript
if (!dimension) {
const dimensionAnswer = AskUserQuestion({
questions: [{
question: "What type of spec do you want to create?",
header: "Dimension",
multiSelect: false,
options: [
{
label: "Project Spec",
description: "Coding conventions, constraints, quality rules for this project (stored in .ccw/specs/)"
},
{
label: "Personal Spec",
description: "Personal preferences and constraints that follow you across projects (stored in ~/.ccw/specs/personal/ or .ccw/specs/personal/)"
}
]
}]
})
dimension = dimensionAnswer.answers["Dimension"] === "Project Spec" ? "specs" : "personal"
}
```
**If personal dimension and scope not specified**:
```javascript
if (dimension === 'personal' && !scope) {
const scopeAnswer = AskUserQuestion({
questions: [{
question: "Where should this personal spec be stored?",
header: "Scope",
multiSelect: false,
options: [
{
label: "Global (Recommended)",
description: "Apply to ALL projects (~/.ccw/specs/personal/)"
},
{
label: "Project-only",
description: "Apply only to this project (.ccw/specs/personal/)"
}
]
}]
})
scope = scopeAnswer.answers["Scope"].includes("Global") ? "global" : "project"
}
```
**If category not specified**:
```javascript
if (!category) {
const categoryAnswer = AskUserQuestion({
questions: [{
question: "Which workflow stage does this spec apply to?",
header: "Category",
multiSelect: false,
options: [
{
label: "General (Recommended)",
description: "Applies to all stages (default)"
},
{
label: "Exploration",
description: "Code exploration, analysis, debugging"
},
{
label: "Planning",
description: "Task planning, requirements gathering"
},
{
label: "Execution",
description: "Implementation, testing, deployment"
}
]
}]
})
const categoryLabel = categoryAnswer.answers["Category"]
category = categoryLabel.includes("General") ? "general"
: categoryLabel.includes("Exploration") ? "exploration"
: categoryLabel.includes("Planning") ? "planning"
: "execution"
}
```
**Ask type**:
```javascript
const typeAnswer = AskUserQuestion({
questions: [{
question: "What type of rule is this?",
header: "Type",
multiSelect: false,
options: [
{
label: "Convention",
description: "Coding style preference (e.g., use functional components)"
},
{
label: "Constraint",
description: "Hard rule that must not be violated (e.g., no direct DB access)"
},
{
label: "Learning",
description: "Insight or lesson learned (e.g., cache invalidation needs events)"
}
]
}]
})
const type = typeAnswer.answers["Type"]
const isConvention = type.includes("Convention")
const isConstraint = type.includes("Constraint")
const isLearning = type.includes("Learning")
```
**Ask content**:
```javascript
const contentAnswer = AskUserQuestion({
questions: [{
question: "Enter the rule or guideline text:",
header: "Content",
multiSelect: false,
options: []
}]
})
const ruleText = contentAnswer.answers["Content"]
```
### Step 3: Determine Target File
```javascript
const path = require('path')
const os = require('os')
let targetFile: string
let targetDir: string
if (dimension === 'specs') {
// Project specs - use .ccw/specs/ (same as frontend/backend spec-index-builder)
targetDir = '.ccw/specs'
if (isConstraint) {
targetFile = path.join(targetDir, 'architecture-constraints.md')
} else {
targetFile = path.join(targetDir, 'coding-conventions.md')
}
} else {
// Personal specs - use .ccw/personal/ (same as backend spec-index-builder)
if (scope === 'global') {
targetDir = path.join(os.homedir(), '.ccw', 'personal')
} else {
targetDir = path.join('.ccw', 'personal')
}
// Create category-based filename
const typePrefix = isConstraint ? 'constraints' : isLearning ? 'learnings' : 'conventions'
targetFile = path.join(targetDir, `${typePrefix}.md`)
}
```
### Step 4: Write Spec
```javascript
const fs = require('fs')
// Ensure directory exists
if (!fs.existsSync(targetDir)) {
fs.mkdirSync(targetDir, { recursive: true })
}
// Check if file exists
const fileExists = fs.existsSync(targetFile)
if (!fileExists) {
// Create new file with frontmatter
const frontmatter = `---
title: ${dimension === 'specs' ? 'Project' : 'Personal'} ${isConstraint ? 'Constraints' : isLearning ? 'Learnings' : 'Conventions'}
readMode: optional
priority: medium
category: ${category}
scope: ${dimension === 'personal' ? scope : 'project'}
dimension: ${dimension}
keywords: [${category}, ${isConstraint ? 'constraint' : isLearning ? 'learning' : 'convention'}]
---
# ${dimension === 'specs' ? 'Project' : 'Personal'} ${isConstraint ? 'Constraints' : isLearning ? 'Learnings' : 'Conventions'}
`
fs.writeFileSync(targetFile, frontmatter, 'utf8')
}
// Read existing content
let content = fs.readFileSync(targetFile, 'utf8')
// Format the new rule
const timestamp = new Date().toISOString().split('T')[0]
const rulePrefix = isLearning ? `- [learning] ` : `- [${category}] `
const ruleSuffix = isLearning ? ` (${timestamp})` : ''
const newRule = `${rulePrefix}${ruleText}${ruleSuffix}`
// Check for duplicate
if (content.includes(ruleText)) {
console.log(`
Rule already exists in ${targetFile}
Text: "${ruleText}"
`)
return
}
// Append the rule
content = content.trimEnd() + '\n' + newRule + '\n'
fs.writeFileSync(targetFile, content, 'utf8')
// Rebuild spec index
Bash('ccw spec rebuild')
```
### Step 5: Display Confirmation
```
Spec created successfully
Dimension: ${dimension}
Scope: ${dimension === 'personal' ? scope : 'project'}
Category: ${category}
Type: ${type}
Rule: "${ruleText}"
Location: ${targetFile}
Use 'ccw spec list' to view all specs
Use 'ccw spec load --category ${category}' to load specs by category
```
## Target File Resolution
### Project Specs (dimension: specs)
```
.ccw/specs/
├── coding-conventions.md ← conventions, learnings
├── architecture-constraints.md ← constraints
└── quality-rules.md ← quality rules
```
### Personal Specs (dimension: personal)
```
# Global (~/.ccw/personal/)
~/.ccw/personal/
├── conventions.md ← personal conventions (all projects)
├── constraints.md ← personal constraints (all projects)
└── learnings.md ← personal learnings (all projects)
# Project-local (.ccw/personal/)
.ccw/personal/
├── conventions.md ← personal conventions (this project only)
├── constraints.md ← personal constraints (this project only)
└── learnings.md ← personal learnings (this project only)
```
## Category Field Usage
The `category` field in frontmatter enables filtered loading:
| Category | Use Case | Example Rules |
|----------|----------|---------------|
| `general` | Applies to all stages | "Use TypeScript strict mode" |
| `exploration` | Code exploration, debugging | "Always trace the call stack before modifying" |
| `planning` | Task planning, requirements | "Break down tasks into 2-hour chunks" |
| `execution` | Implementation, testing | "Run tests after each file modification" |
## Error Handling
- **File not writable**: Check permissions, suggest manual creation
- **Duplicate rule**: Warn and skip (don't add duplicates)
- **Invalid path**: Exit with error message
## Related Commands
- `/workflow:init` - Initialize project with specs scaffold
- `/workflow:init-guidelines` - Interactive wizard to fill specs
- `/workflow:session:solidify` - Add rules during/after sessions
- `ccw spec list` - View all specs
- `ccw spec load --category <cat>` - Load filtered specs

View File

@@ -1,20 +1,21 @@
---
name: init
description: Initialize project-level state with intelligent project analysis using cli-explore-agent
argument-hint: "[--regenerate]"
argument-hint: "[--regenerate] [--skip-specs]"
examples:
- /workflow:init
- /workflow:init --regenerate
- /workflow:init --skip-specs
---
# Workflow Init Command (/workflow:init)
## Overview
Initialize `.workflow/project-tech.json` and `.workflow/project-guidelines.json` with comprehensive project understanding by delegating analysis to **cli-explore-agent**.
Initialize `.workflow/project-tech.json` and `.ccw/specs/*.md` with comprehensive project understanding by delegating analysis to **cli-explore-agent**.
**Dual File System**:
- `project-tech.json`: Auto-generated technical analysis (stack, architecture, components)
- `project-guidelines.json`: User-maintained rules and constraints (created as scaffold)
- `specs/*.md`: User-maintained rules and constraints (created as scaffold)
**Note**: This command may be called by other workflow commands. Upon completion, return immediately to continue the calling workflow without interrupting the task flow.
@@ -22,13 +23,15 @@ Initialize `.workflow/project-tech.json` and `.workflow/project-guidelines.json`
```bash
/workflow:init # Initialize (skip if exists)
/workflow:init --regenerate # Force regeneration
/workflow:init --skip-specs # Initialize project-tech only, skip spec initialization
```
## Execution Process
```
Input Parsing:
─ Parse --regenerate flag → regenerate = true | false
─ Parse --regenerate flag → regenerate = true | false
└─ Parse --skip-specs flag → skipSpecs = true | false
Decision:
├─ BOTH_EXIST + no --regenerate → Exit: "Already initialized"
@@ -42,41 +45,44 @@ Analysis Flow:
│ ├─ Semantic analysis (Gemini CLI)
│ ├─ Synthesis and merge
│ └─ Write .workflow/project-tech.json
├─ Create guidelines scaffold (if not exists)
Write .workflow/project-guidelines.json (empty structure)
├─ Display summary
└─ Ask about guidelines configuration
├─ If guidelines empty → Ask user: "Configure now?" or "Skip"
├─ Configure now → Skill(skill="workflow:init-guidelines")
Skip → Show next steps
└─ If guidelines populated → Show next steps only
├─ Spec Initialization (if not --skip-specs)
Check if specs/*.md exist
├─ If NOT_FOUND → Run ccw spec init
│ ├─ Run ccw spec rebuild
└─ Ask about guidelines configuration
├─ If guidelines empty → Ask user: "Configure now?" or "Skip"
Configure now → Skill(skill="workflow:init-guidelines")
│ └─ Skip → Show next steps
│ └─ If guidelines populated → Show next steps only
└─ Display summary
Output:
├─ .workflow/project-tech.json (+ .backup if regenerate)
└─ .workflow/project-guidelines.json (scaffold or configured)
└─ .ccw/specs/*.md (scaffold or configured, unless --skip-specs)
```
## Implementation
### Step 1: Parse Input and Check Existing State
**Parse --regenerate flag**:
**Parse flags**:
```javascript
const regenerate = $ARGUMENTS.includes('--regenerate')
const skipSpecs = $ARGUMENTS.includes('--skip-specs')
```
**Check existing state**:
```bash
bash(test -f .workflow/project-tech.json && echo "TECH_EXISTS" || echo "TECH_NOT_FOUND")
bash(test -f .workflow/project-guidelines.json && echo "GUIDELINES_EXISTS" || echo "GUIDELINES_NOT_FOUND")
bash(test -f .ccw/specs/coding-conventions.md && echo "SPECS_EXISTS" || echo "SPECS_NOT_FOUND")
```
**If BOTH_EXIST and no --regenerate**: Exit early
```
Project already initialized:
- Tech analysis: .workflow/project-tech.json
- Guidelines: .workflow/project-guidelines.json
- Guidelines: .ccw/specs/*.md
Use /workflow:init --regenerate to rebuild tech analysis
Use /workflow:session:solidify to add guidelines
@@ -159,33 +165,20 @@ Project root: ${projectRoot}
)
```
### Step 3.5: Create Guidelines Scaffold (if not exists)
### Step 3.5: Initialize Spec System (if not --skip-specs)
```javascript
// Only create if not exists (never overwrite user guidelines)
if (!file_exists('.workflow/project-guidelines.json')) {
const guidelinesScaffold = {
conventions: {
coding_style: [],
naming_patterns: [],
file_structure: [],
documentation: []
},
constraints: {
architecture: [],
tech_stack: [],
performance: [],
security: []
},
quality_rules: [],
learnings: [],
_metadata: {
created_at: new Date().toISOString(),
version: "1.0.0"
}
};
Write('.workflow/project-guidelines.json', JSON.stringify(guidelinesScaffold, null, 2));
// Skip spec initialization if --skip-specs flag is provided
if (!skipSpecs) {
// Initialize spec system if not already initialized
const specsCheck = Bash('test -f .ccw/specs/coding-conventions.md && echo EXISTS || echo NOT_FOUND')
if (specsCheck.includes('NOT_FOUND')) {
console.log('Initializing spec system...')
Bash('ccw spec init')
Bash('ccw spec rebuild')
}
} else {
console.log('Skipping spec initialization (--skip-specs)')
}
```
@@ -193,10 +186,10 @@ if (!file_exists('.workflow/project-guidelines.json')) {
```javascript
const projectTech = JSON.parse(Read('.workflow/project-tech.json'));
const guidelinesExists = file_exists('.workflow/project-guidelines.json');
const specsInitialized = !skipSpecs && file_exists('.ccw/specs/coding-conventions.md');
console.log(`
Project initialized successfully
Project initialized successfully
## Project Overview
Name: ${projectTech.project_name}
@@ -213,30 +206,37 @@ Components: ${projectTech.overview.key_components.length} core modules
---
Files created:
- Tech analysis: .workflow/project-tech.json
- Guidelines: .workflow/project-guidelines.json ${guidelinesExists ? '(scaffold)' : ''}
${!skipSpecs ? `- Specs: .ccw/specs/ ${specsInitialized ? '(initialized)' : ''}` : '- Specs: (skipped via --skip-specs)'}
${regenerate ? '- Backup: .workflow/project-tech.json.backup' : ''}
`);
```
### Step 5: Ask About Guidelines Configuration
### Step 5: Ask About Guidelines Configuration (if not --skip-specs)
After displaying the summary, ask the user if they want to configure project guidelines interactively.
After displaying the summary, ask the user if they want to configure project guidelines interactively. Skip this step if `--skip-specs` was provided.
```javascript
// Check if guidelines are just a scaffold (empty) or already populated
const guidelines = JSON.parse(Read('.workflow/project-guidelines.json'));
const isGuidelinesPopulated =
guidelines.conventions.coding_style.length > 0 ||
guidelines.conventions.naming_patterns.length > 0 ||
guidelines.constraints.architecture.length > 0 ||
guidelines.constraints.security.length > 0;
// Skip guidelines configuration if --skip-specs was provided
if (skipSpecs) {
console.log(`
Next steps:
- Use /workflow:init-specs to create individual specs
- Use /workflow:init-guidelines to configure specs interactively
- Use /workflow-plan to start planning
`);
return;
}
// Only ask if guidelines are not yet populated
if (!isGuidelinesPopulated) {
// Check if specs have user content beyond seed documents
const specsList = Bash('ccw spec list --json');
const specsCount = JSON.parse(specsList).total || 0;
// Only ask if specs are just seeds
if (specsCount <= 5) {
const userChoice = AskUserQuestion({
questions: [{
question: "Would you like to configure project guidelines now? The wizard will ask targeted questions based on your tech stack.",
header: "Guidelines",
question: "Would you like to configure project specs now? The wizard will ask targeted questions based on your tech stack.",
header: "Specs",
multiSelect: false,
options: [
{
@@ -245,31 +245,33 @@ if (!isGuidelinesPopulated) {
},
{
label: "Skip for now",
description: "You can run /workflow:init-guidelines later or use /workflow:session:solidify to add rules individually"
description: "You can run /workflow:init-guidelines later or use ccw spec load to import specs"
}
]
}]
});
if (userChoice.answers["Guidelines"] === "Configure now (Recommended)") {
console.log("\n🔧 Starting guidelines configuration wizard...\n");
if (userChoice.answers["Specs"] === "Configure now (Recommended)") {
console.log("\nStarting specs configuration wizard...\n");
Skill(skill="workflow:init-guidelines");
} else {
console.log(`
Next steps:
- Use /workflow:init-guidelines to configure guidelines interactively
- Use /workflow:session:solidify to add individual rules
- Use /workflow:plan to start planning
- Use /workflow:init-specs to create individual specs
- Use /workflow:init-guidelines to configure specs interactively
- Use ccw spec load to import specs from external sources
- Use /workflow-plan to start planning
`);
}
} else {
console.log(`
Guidelines already configured (${guidelines.conventions.coding_style.length + guidelines.constraints.architecture.length}+ rules).
Specs already configured (${specsCount} spec files).
Next steps:
- Use /workflow:init-specs to create additional specs
- Use /workflow:init-guidelines --reset to reconfigure
- Use /workflow:session:solidify to add individual rules
- Use /workflow:plan to start planning
- Use /workflow-plan to start planning
`);
}
```
@@ -282,6 +284,7 @@ Next steps:
## Related Commands
- `/workflow:init-specs` - Interactive wizard to create individual specs with scope selection
- `/workflow:init-guidelines` - Interactive wizard to configure project guidelines (called after init)
- `/workflow:session:solidify` - Add individual rules/constraints one at a time
- `workflow-plan` skill - Start planning with initialized project context

View File

@@ -923,7 +923,7 @@ Single evolving state file — each phase writes its section:
- Already have a completed implementation session (WFS-*)
- Only need unit/component level tests
**Use `workflow-tdd` skill when:**
**Use `workflow-tdd-plan` skill when:**
- Building new features with test-first approach
- Red-Green-Refactor cycle

View File

@@ -39,7 +39,7 @@ Closed-loop tech debt lifecycle: **Discover → Assess → Plan → Refactor →
**vs Existing Commands**:
- **workflow:lite-fix**: Single bug fix, no systematic debt analysis
- **workflow:plan + execute**: Generic implementation, no debt-aware prioritization or regression validation
- **workflow-plan + execute**: Generic implementation, no debt-aware prioritization or regression validation
- **This command**: Full debt lifecycle — discovery through multi-dimensional scan, prioritized execution with per-item regression validation
### Value Proposition
@@ -827,7 +827,7 @@ AskUserQuestion({
- Need regression-safe iterative refactoring with rollback
- 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
- No systematic debt analysis needed
@@ -843,6 +843,8 @@ AskUserQuestion({
## Post-Completion Expansion
**Auto-sync**: 执行 `/workflow:session:sync -y "{summary}"` 更新 specs/*.md + project-tech。
完成后询问用户是否扩展为issue(test/enhance/refactor/doc),选中项调用 `/issue:new "{summary} - {dimension}"`
---

View File

@@ -1,620 +0,0 @@
---
name: req-plan-with-file
description: Requirement-level progressive roadmap planning with issue creation. Decomposes requirements into convergent layers or task sequences, creates issues via ccw issue create, and generates roadmap.md for human review. Issues stored in .workflow/issues/issues.jsonl (single source of truth).
argument-hint: "[-y|--yes] [-c|--continue] [-m|--mode progressive|direct|auto] \"requirement description\""
allowed-tools: TodoWrite(*), Task(*), AskUserQuestion(*), Read(*), Grep(*), Glob(*), Bash(*), Edit(*), Write(*)
---
## Auto Mode
When `--yes` or `-y`: Auto-confirm strategy selection, use recommended mode, skip interactive validation rounds.
# Workflow Req-Plan Command (/workflow:req-plan-with-file)
## Quick Start
```bash
# Basic usage
/workflow:req-plan-with-file "Implement user authentication system with OAuth and 2FA"
# With mode selection
/workflow:req-plan-with-file -m progressive "Build real-time notification system" # Layered MVP→iterations
/workflow:req-plan-with-file -m direct "Refactor payment module" # Topologically-sorted task sequence
/workflow:req-plan-with-file -m auto "Add data export feature" # Auto-select strategy
# Continue existing session
/workflow:req-plan-with-file --continue "user authentication system"
# Auto mode
/workflow:req-plan-with-file -y "Implement caching layer"
```
**Context Source**: cli-explore-agent (optional) + requirement analysis
**Output Directory**: `.workflow/.req-plan/{session-id}/`
**Core Innovation**: Requirement decomposition → issue creation via `ccw issue create`. Issues stored in `.workflow/issues/issues.jsonl` (single source of truth). Wave/dependency info embedded in issue tags (`wave-N`) and `extended_context.notes.depends_on_issues`. team-planex consumes issues directly by ID or tag query.
## Overview
Requirement-level layered roadmap planning command. Decomposes a requirement into **convergent layers or task sequences**, creates issues via `ccw issue create`. Issues are the single source of truth in `.workflow/issues/issues.jsonl`; wave and dependency info is embedded in issue tags and `extended_context.notes`.
**Dual Modes**:
- **Progressive**: Layered MVP→iterations, suitable for high-uncertainty requirements (validate first, then refine)
- **Direct**: Topologically-sorted task sequence, suitable for low-uncertainty requirements (clear tasks, directly ordered)
- **Auto**: Automatically selects based on uncertainty level
**Core Workflow**: Requirement Understanding → Strategy Selection → Context Collection (optional) → Decomposition + Issue Creation → Validation → team-planex Handoff
```
┌─────────────────────────────────────────────────────────────────────────┐
│ REQ-PLAN ROADMAP WORKFLOW │
├─────────────────────────────────────────────────────────────────────────┤
│ │
│ Phase 1: Requirement Understanding & Strategy Selection │
│ ├─ Parse requirement: goal / constraints / stakeholders │
│ ├─ Assess uncertainty level │
│ │ ├─ High uncertainty → recommend progressive │
│ │ └─ Low uncertainty → recommend direct │
│ ├─ User confirms strategy (-m skips, -y auto-selects recommended) │
│ └─ Initialize strategy-assessment.json + roadmap.md skeleton │
│ │
│ Phase 2: Context Collection (Optional) │
│ ├─ Detect codebase: package.json / go.mod / src / ... │
│ ├─ Has codebase → cli-explore-agent explores relevant modules │
│ └─ No codebase → skip, pure requirement decomposition │
│ │
│ Phase 3: Decomposition & Issue Creation (cli-roadmap-plan-agent) │
│ ├─ Progressive: define 2-4 layers, each with full convergence │
│ ├─ Direct: vertical slicing + topological sort, each with convergence│
│ ├─ Create issues via ccw issue create (ISS-xxx IDs) │
│ └─ Generate roadmap.md (with issue ID references) │
│ │
│ Phase 4: Validation & team-planex Handoff │
│ ├─ Display decomposition results (tabular + convergence criteria) │
│ ├─ User feedback loop (up to 5 rounds) │
│ └─ Next steps: team-planex full execution / wave-by-wave / view │
│ │
└─────────────────────────────────────────────────────────────────────────┘
```
## Output
```
.workflow/.req-plan/RPLAN-{slug}-{YYYY-MM-DD}/
├── roadmap.md # Human-readable roadmap with issue ID references
├── strategy-assessment.json # Strategy assessment result
└── exploration-codebase.json # Codebase context (optional)
```
| File | Phase | Description |
|------|-------|-------------|
| `strategy-assessment.json` | 1 | Uncertainty analysis + mode recommendation + extracted goal/constraints/stakeholders |
| `roadmap.md` (skeleton) | 1 | Initial skeleton with placeholders, finalized in Phase 3 |
| `exploration-codebase.json` | 2 | Codebase context: relevant modules, patterns, integration points (only when codebase exists) |
| `roadmap.md` (final) | 3 | Human-readable roadmap with issue ID references, convergence details, team-planex execution guide |
**roadmap.md template**:
```markdown
# Requirement Roadmap
**Session**: RPLAN-{slug}-{date}
**Requirement**: {requirement}
**Strategy**: {progressive|direct}
**Generated**: {timestamp}
## Strategy Assessment
- Uncertainty level: {high|medium|low}
- Decomposition mode: {progressive|direct}
- Assessment basis: {factors summary}
## Roadmap
{Tabular display of layers/tasks}
## Convergence Criteria Details
{Expanded convergence for each layer/task}
## Risks
{Aggregated risks}
## Next Steps
{Execution guidance}
```
## Configuration
| Flag | Default | Description |
|------|---------|-------------|
| `-y, --yes` | false | Auto-confirm all decisions |
| `-c, --continue` | false | Continue existing session |
| `-m, --mode` | auto | Decomposition strategy: progressive / direct / auto |
**Session ID format**: `RPLAN-{slug}-{YYYY-MM-DD}`
- slug: lowercase, alphanumeric + CJK characters, max 40 chars
- date: YYYY-MM-DD (UTC+8)
- Auto-detect continue: session folder + roadmap.md exists → continue mode
## JSONL Schema Design
### Issue Format
Each line in `issues.jsonl` follows the standard `issues-jsonl-schema.json` (see `.ccw/workflows/cli-templates/schemas/issues-jsonl-schema.json`).
**Key fields per issue**:
| Field | Source | Description |
|-------|--------|-------------|
| `id` | `ccw issue create` | Formal ISS-YYYYMMDD-NNN ID |
| `title` | Layer/task mapping | `[LayerName] goal` or `[TaskType] title` |
| `context` | Convergence fields | Markdown with goal, scope, convergence criteria, verification, DoD |
| `priority` | Effort mapping | small→4, medium→3, large→2 |
| `source` | Fixed | `"text"` |
| `tags` | Auto-generated | `["req-plan", mode, name/type, "wave-N"]` |
| `extended_context.notes` | Metadata JSON | session, strategy, original_id, wave, depends_on_issues |
| `lifecycle_requirements` | Fixed | test_strategy, regression_scope, acceptance_type, commit_strategy |
### Convergence Criteria (in issue context)
Each issue's `context` field contains convergence information:
| Section | Purpose | Requirement |
|---------|---------|-------------|
| `## Convergence Criteria` | List of checkable specific conditions | **Testable** (can be written as assertions or manual steps) |
| `## Verification` | How to verify these conditions | **Executable** (command, script, or explicit steps) |
| `## Definition of Done` | One-sentence completion definition | **Business language** (non-technical person can judge) |
## Implementation
### Session Initialization
**Objective**: Create session context and directory structure.
```javascript
const getUtc8ISOString = () => new Date(Date.now() + 8 * 60 * 60 * 1000).toISOString()
// Parse flags
const autoYes = $ARGUMENTS.includes('--yes') || $ARGUMENTS.includes('-y')
const continueMode = $ARGUMENTS.includes('--continue') || $ARGUMENTS.includes('-c')
const modeMatch = $ARGUMENTS.match(/(?:--mode|-m)\s+(progressive|direct|auto)/)
const requestedMode = modeMatch ? modeMatch[1] : 'auto'
// Clean requirement text (remove flags)
const requirement = $ARGUMENTS
.replace(/--yes|-y|--continue|-c|--mode\s+\w+|-m\s+\w+/g, '')
.trim()
const slug = requirement.toLowerCase()
.replace(/[^a-z0-9\u4e00-\u9fa5]+/g, '-')
.substring(0, 40)
const dateStr = getUtc8ISOString().substring(0, 10)
const sessionId = `RPLAN-${slug}-${dateStr}`
const sessionFolder = `.workflow/.req-plan/${sessionId}`
// Auto-detect continue: session folder + roadmap.md exists → continue mode
Bash(`mkdir -p ${sessionFolder}`)
```
### Phase 1: Requirement Understanding & Strategy Selection
**Objective**: Parse requirement, assess uncertainty, select decomposition strategy.
**Prerequisites**: Session initialized, requirement description available.
**Steps**:
1. **Parse Requirement**
- Extract core goal (what to achieve)
- Identify constraints (tech stack, timeline, compatibility, etc.)
- Identify stakeholders (users, admins, developers, etc.)
- Identify keywords to determine domain
2. **Assess Uncertainty Level**
```javascript
const uncertaintyFactors = {
scope_clarity: 'low|medium|high',
technical_risk: 'low|medium|high',
dependency_unknown: 'low|medium|high',
domain_familiarity: 'low|medium|high',
requirement_stability: 'low|medium|high'
}
// high uncertainty (>=3 high) → progressive
// low uncertainty (>=3 low) → direct
// otherwise → ask user preference
```
3. **Strategy Selection** (skip if `-m` already specified)
```javascript
if (requestedMode !== 'auto') {
selectedMode = requestedMode
} else if (autoYes) {
selectedMode = recommendedMode
} else {
AskUserQuestion({
questions: [{
question: `Decomposition strategy selection:\n\nUncertainty assessment: ${uncertaintyLevel}\nRecommended strategy: ${recommendedMode}\n\nSelect decomposition strategy:`,
header: "Strategy",
multiSelect: false,
options: [
{
label: recommendedMode === 'progressive' ? "Progressive (Recommended)" : "Progressive",
description: "Layered MVP→iterations, validate core first then refine progressively. Suitable for high-uncertainty requirements needing quick validation"
},
{
label: recommendedMode === 'direct' ? "Direct (Recommended)" : "Direct",
description: "Topologically-sorted task sequence with explicit dependencies. Suitable for clear requirements with confirmed technical approach"
}
]
}]
})
}
```
4. **Generate strategy-assessment.json**
```javascript
const strategyAssessment = {
session_id: sessionId,
requirement: requirement,
timestamp: getUtc8ISOString(),
uncertainty_factors: uncertaintyFactors,
uncertainty_level: uncertaintyLevel, // 'high' | 'medium' | 'low'
recommended_mode: recommendedMode,
selected_mode: selectedMode,
goal: extractedGoal,
constraints: extractedConstraints,
stakeholders: extractedStakeholders,
domain_keywords: extractedKeywords
}
Write(`${sessionFolder}/strategy-assessment.json`, JSON.stringify(strategyAssessment, null, 2))
```
5. **Initialize roadmap.md skeleton** (placeholder sections, finalized in Phase 4)
```javascript
const roadmapMdSkeleton = `# Requirement Roadmap
**Session**: ${sessionId}
**Requirement**: ${requirement}
**Strategy**: ${selectedMode}
**Status**: Planning
**Created**: ${getUtc8ISOString()}
## Strategy Assessment
- Uncertainty level: ${uncertaintyLevel}
- Decomposition mode: ${selectedMode}
## Roadmap
> To be populated after Phase 3 decomposition
## Convergence Criteria Details
> To be populated after Phase 3 decomposition
## Risk Items
> To be populated after Phase 3 decomposition
## Next Steps
> To be populated after Phase 4 validation
`
Write(`${sessionFolder}/roadmap.md`, roadmapMdSkeleton)
```
**Success Criteria**:
- Requirement goal, constraints, stakeholders identified
- Uncertainty level assessed
- Strategy selected (progressive or direct)
- strategy-assessment.json generated
- roadmap.md skeleton initialized
### Phase 2: Context Collection (Optional)
**Objective**: If a codebase exists, collect relevant context to enhance decomposition quality.
**Prerequisites**: Phase 1 complete.
**Steps**:
1. **Detect Codebase**
```javascript
const hasCodebase = Bash(`
test -f package.json && echo "nodejs" ||
test -f go.mod && echo "golang" ||
test -f Cargo.toml && echo "rust" ||
test -f pyproject.toml && echo "python" ||
test -f pom.xml && echo "java" ||
test -d src && echo "generic" ||
echo "none"
`).trim()
```
2. **Codebase Exploration** (only when hasCodebase !== 'none')
```javascript
if (hasCodebase !== 'none') {
Task({
subagent_type: "cli-explore-agent",
run_in_background: false,
description: `Explore codebase: ${slug}`,
prompt: `
## Exploration Context
Requirement: ${requirement}
Strategy: ${selectedMode}
Project Type: ${hasCodebase}
Session: ${sessionFolder}
## MANDATORY FIRST STEPS
1. Run: ccw tool exec get_modules_by_depth '{}'
2. Execute relevant searches based on requirement keywords
3. Read: .workflow/project-tech.json (if exists)
4. Read: .workflow/project-guidelines.json (if exists)
## Exploration Focus
- Identify modules/components related to the requirement
- Find existing patterns that should be followed
- Locate integration points for new functionality
- Assess current architecture constraints
## Output
Write findings to: ${sessionFolder}/exploration-codebase.json
Schema: {
project_type: "${hasCodebase}",
relevant_modules: [{name, path, relevance}],
existing_patterns: [{pattern, files, description}],
integration_points: [{location, description, risk}],
architecture_constraints: [string],
tech_stack: {languages, frameworks, tools},
_metadata: {timestamp, exploration_scope}
}
`
})
}
// No codebase → skip, proceed directly to Phase 3
```
**Success Criteria**:
- Codebase detection complete
- When codebase exists, exploration-codebase.json generated
- When no codebase, skipped and logged
### Phase 3: Decomposition & Issue Creation
**Objective**: Execute requirement decomposition via `cli-roadmap-plan-agent`, creating issues and generating roadmap.md.
**Prerequisites**: Phase 1, Phase 2 complete. Strategy selected. Context collected (if applicable).
**Agent**: `cli-roadmap-plan-agent` (dedicated requirement roadmap planning agent, supports CLI-assisted decomposition + issue creation + built-in quality checks)
**Steps**:
1. **Prepare Context**
```javascript
const strategy = JSON.parse(Read(`${sessionFolder}/strategy-assessment.json`))
let explorationContext = null
if (file_exists(`${sessionFolder}/exploration-codebase.json`)) {
explorationContext = JSON.parse(Read(`${sessionFolder}/exploration-codebase.json`))
}
```
2. **Invoke cli-roadmap-plan-agent**
The agent internally executes a 5-phase flow:
- Phase 1: Context loading + requirement analysis
- Phase 2: CLI-assisted decomposition (Gemini → Qwen → manual fallback)
- Phase 3: Record enhancement + validation (schema compliance, dependency checks, convergence quality)
- Phase 4: Issue creation + roadmap generation (ccw issue create → roadmap.md)
- Phase 5: CLI decomposition quality check (**MANDATORY** - requirement coverage, convergence criteria quality, dependency correctness)
```javascript
Task({
subagent_type: "cli-roadmap-plan-agent",
run_in_background: false,
description: `Roadmap decomposition: ${slug}`,
prompt: `
## Roadmap Decomposition Task
### Input Context
- **Requirement**: ${requirement}
- **Selected Mode**: ${selectedMode}
- **Session ID**: ${sessionId}
- **Session Folder**: ${sessionFolder}
### Strategy Assessment
${JSON.stringify(strategy, null, 2)}
### Codebase Context
${explorationContext
? `File: ${sessionFolder}/exploration-codebase.json\n${JSON.stringify(explorationContext, null, 2)}`
: 'No codebase detected - pure requirement decomposition'}
### Issue Creation
- Use \`ccw issue create\` for each decomposed item
- Issue format: issues-jsonl-schema (id, title, status, priority, context, source, tags, extended_context)
- Update \`roadmap.md\` with issue ID references
### CLI Configuration
- Primary tool: gemini
- Fallback: qwen
- Timeout: 60000ms
### Expected Output
1. **${sessionFolder}/roadmap.md** - Human-readable roadmap with issue references
2. Issues created in \`.workflow/issues/issues.jsonl\` via ccw issue create
### Mode-Specific Requirements
${selectedMode === 'progressive' ? `**Progressive Mode**:
- 2-4 layers from MVP to full implementation
- Each layer: id (L0-L3), name, goal, scope, excludes, convergence, risks, effort, depends_on
- L0 (MVP) must be a self-contained closed loop with no dependencies
- Scope: each feature belongs to exactly ONE layer (no overlap)
- Layer names: MVP / Usable / Refined / Optimized` :
`**Direct Mode**:
- Topologically-sorted task sequence
- Each task: id (T1-Tn), title, type, scope, inputs, outputs, convergence, depends_on, parallel_group
- Inputs must come from preceding task outputs or existing resources
- Tasks in same parallel_group must be truly independent`}
### Convergence Quality Requirements
- criteria[]: MUST be testable (can write assertions or manual verification steps)
- verification: MUST be executable (command, script, or explicit steps)
- definition_of_done: MUST use business language (non-technical person can judge)
### Execution
1. Analyze requirement and build decomposition context
2. Execute CLI-assisted decomposition (Gemini, fallback Qwen)
3. Parse output, validate records, enhance convergence quality
4. Create issues via ccw issue create, generate roadmap.md
5. Execute mandatory quality check (Phase 5)
6. Return brief completion summary
`
})
```
**Success Criteria**:
- Issues created via `ccw issue create`, each with formal ISS-xxx ID
- roadmap.md generated with issue ID references
- Agent's internal quality check passed
- No circular dependencies
- Progressive: 2-4 layers, no scope overlap
- Direct: tasks have explicit inputs/outputs, parallel_group assigned
### Phase 4: Validation & team-planex Handoff
**Objective**: Display decomposition results, collect user feedback, provide team-planex execution options.
**Prerequisites**: Phase 3 complete, issues created, roadmap.md generated.
**Steps**:
1. **Display Decomposition Results** (tabular format)
```javascript
// Use issueIdMap from Phase 3 for display
const issueIds = Object.values(issueIdMap)
```
**Progressive Mode**:
```markdown
## Roadmap Overview
| Wave | Issue ID | Name | Goal | Priority |
|------|----------|------|------|----------|
| 1 | ISS-xxx | MVP | ... | 2 |
| 2 | ISS-yyy | Usable | ... | 3 |
### Convergence Criteria
**Wave 1 - MVP (ISS-xxx)**:
- Criteria: [criteria list]
- Verification: [verification]
- Definition of Done: [definition_of_done]
```
**Direct Mode**:
```markdown
## Task Sequence
| Wave | Issue ID | Title | Type | Dependencies |
|------|----------|-------|------|--------------|
| 1 | ISS-xxx | ... | infrastructure | - |
| 2 | ISS-yyy | ... | feature | ISS-xxx |
### Convergence Criteria
**Wave 1 - ISS-xxx**:
- Criteria: [criteria list]
- Verification: [verification]
- Definition of Done: [definition_of_done]
```
2. **User Feedback Loop** (up to 5 rounds, skipped when autoYes)
```javascript
if (!autoYes) {
let round = 0
let continueLoop = true
while (continueLoop && round < 5) {
round++
const feedback = AskUserQuestion({
questions: [{
question: `Roadmap validation (round ${round}):\nAny feedback on the current decomposition?`,
header: "Feedback",
multiSelect: false,
options: [
{ label: "Approve", description: "Decomposition is reasonable, proceed to next steps" },
{ label: "Adjust Scope", description: "Some issue scopes need adjustment" },
{ label: "Modify Convergence", description: "Convergence criteria are not specific or testable enough" },
{ label: "Re-decompose", description: "Overall strategy or layering approach needs change" }
]
}]
})
if (feedback === 'Approve') {
continueLoop = false
} else {
// Handle adjustment based on feedback type
// After adjustment, re-display and return to loop top
}
}
}
```
3. **Post-Completion Options**
```javascript
if (!autoYes) {
AskUserQuestion({
questions: [{
question: `路线图已生成,${issueIds.length} 个 issues 已创建。下一步:`,
header: "Next Step",
multiSelect: false,
options: [
{ label: "Execute with team-planex", description: `启动 team-planex 执行全部 ${issueIds.length} 个 issues` },
{ label: "Execute first wave", description: "仅执行 Wave 1按 wave-1 tag 筛选)" },
{ label: "View issues", description: "查看已创建的 issue 详情" },
{ label: "Done", description: "保存路线图,稍后执行" }
]
}]
})
}
```
| Selection | Action |
|-----------|--------|
| Execute with team-planex | `Skill(skill="team-planex", args="${issueIds.join(' ')}")` |
| Execute first wave | Filter issues by `wave-1` tag, pass to team-planex |
| View issues | Display issues summary from `.workflow/issues/issues.jsonl` |
| Done | Display file paths, end |
**Success Criteria**:
- User feedback processed (or skipped via autoYes)
- Post-completion options provided
- team-planex handoff available via issue IDs
## Error Handling
| Error | Resolution |
|-------|------------|
| cli-explore-agent failure | Skip code exploration, proceed with pure requirement decomposition |
| No codebase | Normal flow, skip Phase 2 |
| Circular dependency detected | Prompt user to adjust dependencies, re-decompose |
| User feedback timeout | Save current state, display `--continue` recovery command |
| Max feedback rounds reached | Use current version to generate final artifacts |
| Session folder conflict | Append timestamp suffix |
## Best Practices
1. **Clear requirement description**: Detailed description → more accurate uncertainty assessment and decomposition
2. **Validate MVP first**: In progressive mode, L0 should be the minimum verifiable closed loop
3. **Testable convergence**: criteria must be writable as assertions or manual steps; definition_of_done should be judgeable by non-technical stakeholders (see Convergence Criteria in JSONL Schema Design)
4. **Agent-First for Exploration**: Delegate codebase exploration to cli-explore-agent, do not analyze directly in main flow
5. **Incremental validation**: Use `--continue` to iterate on existing roadmaps
6. **team-planex integration**: Issues created follow standard issues-jsonl-schema, directly consumable by team-planex via issue IDs and tags
---
**Now execute req-plan-with-file for**: $ARGUMENTS

View File

@@ -0,0 +1,544 @@
---
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.
argument-hint: "[-y|--yes] [-c|--continue] [-m progressive|direct|auto] \"requirement description\""
allowed-tools: TodoWrite(*), Task(*), AskUserQuestion(*), Read(*), Grep(*), Glob(*), Bash(*), Edit(*), Write(*)
---
## Auto Mode
When `--yes` or `-y`: Auto-confirm strategy selection, use recommended mode, skip interactive rounds.
# Workflow Roadmap Command (/workflow:roadmap-with-file)
## Quick Start
```bash
# Basic usage
/workflow:roadmap-with-file "Implement user authentication system with OAuth and 2FA"
# With mode selection
/workflow:roadmap-with-file -m progressive "Build real-time notification system" # MVP→iterations
/workflow:roadmap-with-file -m direct "Refactor payment module" # Topological sequence
/workflow:roadmap-with-file -m auto "Add data export feature" # Auto-select
# Continue existing session
/workflow:roadmap-with-file --continue "auth system"
# Auto mode
/workflow:roadmap-with-file -y "Implement caching layer"
```
**Context Source**: cli-explore-agent (optional) + requirement analysis
**Output Directory**: `.workflow/.roadmap/{session-id}/`
**Core Output**: `roadmap.md` (single source, human-readable) + `issues.jsonl` (global, machine-executable)
## Output Artifacts
### Single Source of Truth
| Artifact | Purpose | Consumer |
|----------|---------|----------|
| `roadmap.md` | ⭐ Human-readable strategic roadmap with all context | Human review, team-planex handoff |
| `.workflow/issues/issues.jsonl` | Global issue store (appended) | team-planex, issue commands |
### Why No Separate JSON Files?
| Original File | Why Removed | Where Content Goes |
|---------------|-------------|-------------------|
| `strategy-assessment.json` | Duplicates roadmap.md content | Embedded in `roadmap.md` Strategy Assessment section |
| `exploration-codebase.json` | Single-use intermediate | Embedded in `roadmap.md` Codebase Context appendix |
## Overview
Strategic requirement roadmap with **iterative decomposition**. Creates a single `roadmap.md` that evolves through discussion, with issues persisted to global `issues.jsonl` for execution.
**Core workflow**: Understand → Decompose → Iterate → Validate → Handoff
```
┌─────────────────────────────────────────────────────────────────────────┐
│ ROADMAP ITERATIVE WORKFLOW │
├─────────────────────────────────────────────────────────────────────────┤
│ │
│ Phase 1: Requirement Understanding & Strategy │
│ ├─ Parse requirement: goal / constraints / stakeholders │
│ ├─ Assess uncertainty level → recommend mode │
│ ├─ User confirms strategy (-m skips, -y auto-selects) │
│ └─ Initialize roadmap.md with Strategy Assessment │
│ │
│ Phase 2: Decomposition & Issue Creation │
│ ├─ cli-roadmap-plan-agent executes decomposition │
│ ├─ Progressive: 2-4 layers (MVP→Optimized) with convergence │
│ ├─ Direct: Topological task sequence with convergence │
│ ├─ Create issues via ccw issue create → issues.jsonl │
│ └─ Update roadmap.md with Roadmap table + Issue references │
│ │
│ Phase 3: Iterative Refinement (Multi-Round) │
│ ├─ Present roadmap to user │
│ ├─ Feedback: Approve | Adjust Scope | Modify Convergence | Replan │
│ ├─ Update roadmap.md with each round │
│ └─ Repeat until approved (max 5 rounds) │
│ │
│ Phase 4: Handoff │
│ ├─ Final roadmap.md with Issue ID references │
│ ├─ Options: team-planex | first wave | view issues | done │
│ └─ Issues ready in .workflow/issues/issues.jsonl │
│ │
└─────────────────────────────────────────────────────────────────────────┘
```
## Dual Modes
| Mode | Strategy | Best For | Decomposition |
|------|----------|----------|---------------|
| **Progressive** | MVP → Usable → Refined → Optimized | High uncertainty, need validation | 2-4 layers, each with full convergence |
| **Direct** | Topological task sequence | Clear requirements, confirmed tech | Tasks with explicit inputs/outputs |
**Auto-selection logic**:
- ≥3 high uncertainty factors → Progressive
- ≥3 low uncertainty factors → Direct
- Otherwise → Ask user preference
## Output Structure
```
.workflow/.roadmap/RMAP-{slug}-{date}/
└── roadmap.md # ⭐ Single source of truth
# - Strategy Assessment (embedded)
# - Roadmap Table
# - Convergence Criteria per Issue
# - Codebase Context (appendix, if applicable)
# - Iteration History
.workflow/issues/issues.jsonl # Global issue store (appended)
# - One JSON object per line
# - Consumed by team-planex, issue commands
```
## roadmap.md Template
```markdown
# Requirement Roadmap
**Session**: RMAP-{slug}-{date}
**Requirement**: {requirement}
**Strategy**: {progressive|direct}
**Status**: {Planning|Refining|Ready}
**Created**: {timestamp}
---
## Strategy Assessment
- **Uncertainty Level**: {high|medium|low}
- **Decomposition Mode**: {progressive|direct}
- **Assessment Basis**: {factors summary}
- **Goal**: {extracted goal}
- **Constraints**: {extracted constraints}
- **Stakeholders**: {extracted stakeholders}
---
## Roadmap
### Progressive Mode
| Wave | Issue ID | Layer | Goal | Priority | Dependencies |
|------|----------|-------|------|----------|--------------|
| 1 | ISS-xxx | MVP | ... | 2 | - |
| 2 | ISS-yyy | Usable | ... | 3 | ISS-xxx |
### Direct Mode
| Wave | Issue ID | Title | Type | Dependencies |
|------|----------|-------|------|--------------|
| 1 | ISS-xxx | ... | infrastructure | - |
| 2 | ISS-yyy | ... | feature | ISS-xxx |
---
## Convergence Criteria
### ISS-xxx: {Issue Title}
- **Criteria**: [testable conditions]
- **Verification**: [executable steps/commands]
- **Definition of Done**: [business language, non-technical]
### ISS-yyy: {Issue Title}
...
---
## Risks
| Risk | Severity | Mitigation |
|------|----------|------------|
| ... | ... | ... |
---
## Iteration History
### Round 1 - {timestamp}
**User Feedback**: {feedback summary}
**Changes Made**: {adjustments}
**Status**: {approved|continue iteration}
---
## Codebase Context (Optional)
*Included when codebase exploration was performed*
- **Relevant Modules**: [...]
- **Existing Patterns**: [...]
- **Integration Points**: [...]
```
## Issues JSONL Specification
### Location & Format
```
Path: .workflow/issues/issues.jsonl
Format: JSONL (one complete JSON object per line)
Encoding: UTF-8
Mode: Append-only (new issues appended to end)
```
### Record Schema
```json
{
"id": "ISS-YYYYMMDD-NNN",
"title": "[LayerName] goal or [TaskType] title",
"status": "pending",
"priority": 2,
"context": "Markdown with goal, scope, convergence, verification, DoD",
"source": "text",
"tags": ["roadmap", "progressive|direct", "wave-N", "layer-name"],
"extended_context": {
"notes": {
"session": "RMAP-{slug}-{date}",
"strategy": "progressive|direct",
"wave": 1,
"depends_on_issues": []
}
},
"lifecycle_requirements": {
"test_strategy": "unit",
"regression_scope": "affected",
"acceptance_type": "automated",
"commit_strategy": "per-issue"
}
}
```
### Query Interface
```bash
# By ID (detail view)
ccw issue list ISS-20260227-001
# List all with status filter
ccw issue list --status planned,queued
ccw issue list --brief # JSON minimal output
# Queue operations (wave-based execution)
ccw issue queue list # List all queues
ccw issue queue dag # Get dependency graph (JSON)
ccw issue next --queue <queue-id> # Get next task
# Execute
ccw issue queue add <issue-id> # Add to active queue
ccw issue done <item-id> # Mark completed
```
> **Note**: Issues are tagged with `wave-N` in `tags[]` field for filtering. Use `--brief` for programmatic parsing.
### Consumers
| Consumer | Usage |
|----------|-------|
| `team-planex` | Load by ID or tag, execute in wave order |
| `issue-manage` | CRUD operations on issues |
| `issue:execute` | DAG-based parallel execution |
| `issue:queue` | Form execution queue from solutions |
## Implementation
### Session Initialization
```javascript
const getUtc8ISOString = () => new Date(Date.now() + 8 * 60 * 60 * 1000).toISOString()
// Parse flags
const autoYes = $ARGUMENTS.includes('--yes') || $ARGUMENTS.includes('-y')
const continueMode = $ARGUMENTS.includes('--continue') || $ARGUMENTS.includes('-c')
const modeMatch = $ARGUMENTS.match(/(?:--mode|-m)\s+(progressive|direct|auto)/)
const requestedMode = modeMatch ? modeMatch[1] : 'auto'
// Clean requirement text
const requirement = $ARGUMENTS
.replace(/--yes|-y|--continue|-c|--mode\s+\w+|-m\s+\w+/g, '')
.trim()
const slug = requirement.toLowerCase()
.replace(/[^a-z0-9\u4e00-\u9fa5]+/g, '-')
.substring(0, 40)
const dateStr = getUtc8ISOString().substring(0, 10)
const sessionId = `RMAP-${slug}-${dateStr}`
const sessionFolder = `.workflow/.roadmap/${sessionId}`
// Auto-detect continue
if (continueMode || file_exists(`${sessionFolder}/roadmap.md`)) {
// Resume existing session
}
Bash(`mkdir -p ${sessionFolder}`)
```
### Phase 1: Requirement Understanding & Strategy
**Objective**: Parse requirement, assess uncertainty, select decomposition strategy, initialize roadmap.md.
**Steps**:
1. **Parse Requirement**
- Extract: goal, constraints, stakeholders, keywords
2. **Assess Uncertainty**
```javascript
const uncertaintyFactors = {
scope_clarity: 'low|medium|high',
technical_risk: 'low|medium|high',
dependency_unknown: 'low|medium|high',
domain_familiarity: 'low|medium|high',
requirement_stability: 'low|medium|high'
}
// ≥3 high → progressive, ≥3 low → direct, else → ask
```
3. **Strategy Selection** (skip if `-m` specified or autoYes)
```javascript
AskUserQuestion({
questions: [{
question: `Decomposition strategy:\nUncertainty: ${uncertaintyLevel}\nRecommended: ${recommendedMode}`,
header: "Strategy",
multiSelect: false,
options: [
{ label: recommendedMode === 'progressive' ? "Progressive (Recommended)" : "Progressive",
description: "MVP→iterations, validate core first" },
{ label: recommendedMode === 'direct' ? "Direct (Recommended)" : "Direct",
description: "Topological task sequence, clear dependencies" }
]
}]
})
```
4. **Initialize roadmap.md** with Strategy Assessment section
**Success Criteria**:
- roadmap.md created with Strategy Assessment
- Strategy selected (progressive or direct)
- Uncertainty factors documented
### Phase 2: Decomposition & Issue Creation
**Objective**: Execute decomposition via `cli-roadmap-plan-agent`, create issues, update roadmap.md.
**Agent**: `cli-roadmap-plan-agent`
**Agent Tasks**:
1. Analyze requirement with strategy context
2. Execute CLI-assisted decomposition (Gemini → Qwen fallback)
3. Create issues via `ccw issue create`
4. Generate roadmap table with Issue ID references
5. Update roadmap.md
**Agent Prompt Template**:
```javascript
Task({
subagent_type: "cli-roadmap-plan-agent",
run_in_background: false,
description: `Roadmap decomposition: ${slug}`,
prompt: `
## Roadmap Decomposition Task
### Input Context
- **Requirement**: ${requirement}
- **Strategy**: ${selectedMode}
- **Session**: ${sessionId}
- **Folder**: ${sessionFolder}
### Mode-Specific Requirements
${selectedMode === 'progressive' ? `**Progressive Mode**:
- 2-4 layers: MVP / Usable / Refined / Optimized
- Each layer: goal, scope, excludes, convergence, risks, effort
- L0 (MVP) must be self-contained, no dependencies
- Scope: each feature in exactly ONE layer (no overlap)` :
`**Direct Mode**:
- Topologically-sorted task sequence
- Each task: title, type, scope, inputs, outputs, convergence, depends_on
- Inputs from preceding outputs or existing resources
- parallel_group for truly independent tasks`}
### Convergence Quality Requirements
- criteria[]: MUST be testable
- verification: MUST be executable
- definition_of_done: MUST use business language
### Output
1. **${sessionFolder}/roadmap.md** - Update with Roadmap table + Convergence sections
2. **Append to .workflow/issues/issues.jsonl** via ccw issue create
### CLI Configuration
- Primary: gemini, Fallback: qwen, Timeout: 60000ms
`
})
```
**Success Criteria**:
- Issues created in `.workflow/issues/issues.jsonl`
- roadmap.md updated with Issue references
- No circular dependencies
- Convergence criteria testable
### Phase 3: Iterative Refinement
**Objective**: Multi-round user feedback to refine roadmap.
**Workflow Steps**:
1. **Present Roadmap**
- Display Roadmap table + key Convergence criteria
- Show issue count and wave breakdown
2. **Gather Feedback** (skip if autoYes)
```javascript
const feedback = AskUserQuestion({
questions: [{
question: `Roadmap validation (round ${round}):\n${issueCount} issues across ${waveCount} waves. Feedback?`,
header: "Feedback",
multiSelect: false,
options: [
{ label: "Approve", description: "Proceed to handoff" },
{ label: "Adjust Scope", description: "Modify issue scopes" },
{ label: "Modify Convergence", description: "Refine criteria/verification" },
{ label: "Re-decompose", description: "Change strategy/layering" }
]
}]
})
```
3. **Process Feedback**
- **Approve**: Exit loop, proceed to Phase 4
- **Adjust Scope**: Modify issue context, update roadmap.md
- **Modify Convergence**: Refine criteria/verification, update roadmap.md
- **Re-decompose**: Return to Phase 2 with new strategy
4. **Update roadmap.md**
- Append to Iteration History section
- Update Roadmap table if changed
- Increment round counter
5. **Loop** (max 5 rounds, then force proceed)
**Success Criteria**:
- User approved OR max rounds reached
- All changes recorded in Iteration History
- roadmap.md reflects final state
### Phase 4: Handoff
**Objective**: Present final roadmap, offer execution options.
**Steps**:
1. **Display Summary**
```markdown
## Roadmap Complete
- **Session**: RMAP-{slug}-{date}
- **Strategy**: {progressive|direct}
- **Issues Created**: {count} across {waves} waves
- **Roadmap**: .workflow/.roadmap/RMAP-{slug}-{date}/roadmap.md
| Wave | Issue Count | Layer/Type |
|------|-------------|------------|
| 1 | 2 | MVP / infrastructure |
| 2 | 3 | Usable / feature |
```
2. **Offer Options** (skip if autoYes)
```javascript
AskUserQuestion({
questions: [{
question: `${issueIds.length} issues ready. Next step:`,
header: "Next Step",
multiSelect: false,
options: [
{ label: "Execute with team-planex (Recommended)",
description: `Run all ${issueIds.length} issues via team-planex` },
{ label: "Execute first wave",
description: "Run wave-1 issues only" },
{ label: "View issues",
description: "Display issue details from issues.jsonl" },
{ label: "Done",
description: "Save and exit, execute later" }
]
}]
})
```
3. **Execute Selection**
| Selection | Action |
|-----------|--------|
| Execute with team-planex | `Skill(skill="team-planex", args="${issueIds.join(' ')}")` |
| Execute first wave | Filter by `wave-1` tag, pass to team-planex |
| View issues | Display from `.workflow/issues/issues.jsonl` |
| Done | Output paths, end |
## Configuration
| Flag | Default | Description |
|------|---------|-------------|
| `-y, --yes` | false | Auto-confirm all decisions |
| `-c, --continue` | false | Continue existing session |
| `-m, --mode` | auto | Strategy: progressive / direct / auto |
**Session ID format**: `RMAP-{slug}-{YYYY-MM-DD}`
## Error Handling
| Error | Resolution |
|-------|------------|
| cli-roadmap-plan-agent fails | Retry once, fallback to manual decomposition |
| No codebase | Skip exploration, pure requirement decomposition |
| Circular dependency detected | Prompt user, re-decompose |
| User feedback timeout | Save roadmap.md, show `--continue` command |
| Max rounds reached | Force proceed with current roadmap |
| Session folder conflict | Append timestamp suffix |
## Best Practices
1. **Clear Requirements**: Detailed description → better decomposition
2. **Iterate on Roadmap**: Use feedback rounds to refine convergence criteria
3. **Testable Convergence**: criteria = assertions, DoD = business language
4. **Use Continue Mode**: Resume to iterate on existing roadmap
5. **Wave Execution**: Start with wave-1 (MVP) to validate before full execution
## Usage Recommendations
**When to Use Roadmap vs Other Commands:**
| Scenario | Recommended Command |
|----------|-------------------|
| Strategic planning, need issue tracking | `/workflow:roadmap-with-file` |
| Quick task breakdown, immediate execution | `/workflow-lite-planex` |
| Collaborative multi-agent planning | `/workflow:collaborative-plan-with-file` |
| Full specification documents | `spec-generator` skill |
| Code implementation from existing plan | `/workflow-lite-planex` (Phase 1: plan → Phase 2: execute) |
---
**Now execute roadmap-with-file for**: $ARGUMENTS

View File

@@ -109,79 +109,16 @@ rm -f .workflow/archives/$SESSION_ID/.archiving
Manifest: Updated with N total sessions
```
### Phase 4: Update project-tech.json (Optional)
### Phase 4: Auto-Sync Project State
**Skip if**: `.workflow/project-tech.json` doesn't exist
Execute `/workflow:session:sync -y "{description}"` to update both `specs/*.md` and `project-tech.json` from session context.
```bash
# Check
test -f .workflow/project-tech.json || echo "SKIP"
```
**If exists**, add feature entry:
```json
{
"id": "<slugified title>",
"title": "<from IMPL_PLAN.md>",
"status": "completed",
"tags": ["<from Phase 2>"],
"timeline": { "implemented_at": "<date>" },
"traceability": { "session_id": "<SESSION_ID>", "archive_path": "<path>" }
}
```
**Output**:
```
✓ Feature added to project registry
```
### Phase 5: Ask About Solidify (Always)
After successful archival, prompt user to capture learnings:
```javascript
// Parse --yes flag
const autoYes = $ARGUMENTS.includes('--yes') || $ARGUMENTS.includes('-y')
if (autoYes) {
// Auto mode: Skip solidify
console.log(`[--yes] Auto-selecting: Skip solidify`)
console.log(`Session archived successfully.`)
// Done - no solidify
} else {
// Interactive mode: Ask user
AskUserQuestion({
questions: [{
question: "Would you like to solidify learnings from this session into project guidelines?",
header: "Solidify",
options: [
{ label: "Yes, solidify now", description: "Extract learnings and update project-guidelines.json" },
{ label: "Skip", description: "Archive complete, no learnings to capture" }
],
multiSelect: false
}]
})
// **If "Yes, solidify now"**: Execute `/workflow:session:solidify` with the archived session ID.
}
```
Description 取自 Phase 2 的 `workflow-session.json` description 字段。
## Auto Mode Defaults
When `--yes` or `-y` flag is used:
- **Solidify Learnings**: Auto-selected "Skip" (archive only, no solidify)
**Flag Parsing**:
```javascript
const autoYes = $ARGUMENTS.includes('--yes') || $ARGUMENTS.includes('-y')
```
**Output**:
```
Session archived successfully.
→ Run /workflow:session:solidify to capture learnings (recommended)
```
- **Sync**: Auto-executed with `-y` (no confirmation)
## Error Recovery
@@ -198,6 +135,5 @@ Session archived successfully.
Phase 1: find session → create .archiving marker
Phase 2: read key files → build manifest entry (no writes)
Phase 3: mkdir → mv → update manifest.json → rm marker
Phase 4: update project-tech.json features array (optional)
Phase 5: ask user → solidify learnings (optional)
Phase 4: /workflow:session:sync -y → update specs/*.md + project-tech
```

View File

@@ -57,5 +57,5 @@ Session WFS-user-auth resumed
- Status: active
- Paused at: 2025-09-15T14:30:00Z
- Resumed at: 2025-09-15T15:45:00Z
- Ready for: /workflow:execute
- Ready for: /workflow-execute
```

View File

@@ -18,7 +18,7 @@ When `--yes` or `-y`: Auto-categorize and add guideline without confirmation.
## Overview
Crystallizes ephemeral session context (insights, decisions, constraints) into permanent project guidelines stored in `.workflow/project-guidelines.json`. This ensures valuable learnings persist across sessions and inform future planning.
Crystallizes ephemeral session context (insights, decisions, constraints) into permanent project guidelines stored in `.ccw/specs/*.md`. This ensures valuable learnings persist across sessions and inform future planning.
## Use Cases
@@ -112,35 +112,17 @@ ELSE (convention/constraint/learning):
### Step 1: Ensure Guidelines File Exists
**Uses .ccw/specs/ directory (same as frontend/backend spec-index-builder)**
```bash
bash(test -f .workflow/project-guidelines.json && echo "EXISTS" || echo "NOT_FOUND")
bash(test -f .ccw/specs/coding-conventions.md && echo "EXISTS" || echo "NOT_FOUND")
```
**If NOT_FOUND**, create scaffold:
**If NOT_FOUND**, initialize spec system:
```javascript
const scaffold = {
conventions: {
coding_style: [],
naming_patterns: [],
file_structure: [],
documentation: []
},
constraints: {
architecture: [],
tech_stack: [],
performance: [],
security: []
},
quality_rules: [],
learnings: [],
_metadata: {
created_at: new Date().toISOString(),
version: "1.0.0"
}
};
Write('.workflow/project-guidelines.json', JSON.stringify(scaffold, null, 2));
```bash
Bash('ccw spec init')
Bash('ccw spec rebuild')
```
### Step 2: Auto-detect Type (if not specified)
@@ -203,33 +185,42 @@ function buildEntry(rule, type, category, sessionId) {
}
```
### Step 4: Update Guidelines File
### Step 4: Update Spec Files
```javascript
const guidelines = JSON.parse(Read('.workflow/project-guidelines.json'));
if (type === 'convention') {
if (!guidelines.conventions[category]) {
guidelines.conventions[category] = [];
}
if (!guidelines.conventions[category].includes(rule)) {
guidelines.conventions[category].push(rule);
}
} else if (type === 'constraint') {
if (!guidelines.constraints[category]) {
guidelines.constraints[category] = [];
}
if (!guidelines.constraints[category].includes(rule)) {
guidelines.constraints[category].push(rule);
}
} else if (type === 'learning') {
guidelines.learnings.push(buildEntry(rule, type, category, sessionId));
// Map type+category to target spec file
// Uses .ccw/specs/ directory (same as frontend/backend spec-index-builder)
const specFileMap = {
convention: '.ccw/specs/coding-conventions.md',
constraint: '.ccw/specs/architecture-constraints.md'
}
guidelines._metadata.updated_at = new Date().toISOString();
guidelines._metadata.last_solidified_by = sessionId;
if (type === 'convention' || type === 'constraint') {
const targetFile = specFileMap[type]
const existing = Read(targetFile)
Write('.workflow/project-guidelines.json', JSON.stringify(guidelines, null, 2));
// Deduplicate: skip if rule text already exists in the file
if (!existing.includes(rule)) {
const ruleText = `- [${category}] ${rule}`
const newContent = existing.trimEnd() + '\n' + ruleText + '\n'
Write(targetFile, newContent)
}
} else if (type === 'learning') {
// Learnings go to coding-conventions.md as a special section
// Uses .ccw/specs/ directory (same as frontend/backend spec-index-builder)
const targetFile = '.ccw/specs/coding-conventions.md'
const existing = Read(targetFile)
const entry = buildEntry(rule, type, category, sessionId)
const learningText = `- [learning/${category}] ${entry.insight} (${entry.date})`
if (!existing.includes(entry.insight)) {
const newContent = existing.trimEnd() + '\n' + learningText + '\n'
Write(targetFile, newContent)
}
}
// Rebuild spec index after modification
Bash('ccw spec rebuild')
```
### Step 5: Display Confirmation
@@ -241,7 +232,7 @@ Type: ${type}
Category: ${category}
Rule: "${rule}"
Location: .workflow/project-guidelines.json -> ${type}s.${category}
Location: .ccw/specs/*.md -> ${type}s.${category}
Total ${type}s in ${category}: ${count}
```
@@ -386,13 +377,9 @@ AskUserQuestion({
/workflow:session:solidify "Use async/await instead of callbacks" --type convention --category coding_style
```
Result in `project-guidelines.json`:
```json
{
"conventions": {
"coding_style": ["Use async/await instead of callbacks"]
}
}
Result in `.ccw/specs/coding-conventions.md`:
```markdown
- [coding_style] Use async/await instead of callbacks
```
### Add an Architectural Constraint
@@ -400,13 +387,9 @@ Result in `project-guidelines.json`:
/workflow:session:solidify "No direct DB access from controllers" --type constraint --category architecture
```
Result:
```json
{
"constraints": {
"architecture": ["No direct DB access from controllers"]
}
}
Result in `.ccw/specs/architecture-constraints.md`:
```markdown
- [architecture] No direct DB access from controllers
```
### Capture a Session Learning
@@ -414,18 +397,9 @@ Result:
/workflow:session:solidify "Cache invalidation requires event sourcing for consistency" --type learning
```
Result:
```json
{
"learnings": [
{
"date": "2024-12-28",
"session_id": "WFS-auth-feature",
"insight": "Cache invalidation requires event sourcing for consistency",
"category": "architecture"
}
]
}
Result in `.ccw/specs/coding-conventions.md`:
```markdown
- [learning/architecture] Cache invalidation requires event sourcing for consistency (2024-12-28)
```
### Compress Recent Memories
@@ -444,7 +418,7 @@ Result: Creates a new CMEM with consolidated content from the 10 most recent non
## Integration with Planning
The `project-guidelines.json` is consumed by:
The `specs/*.md` is consumed by:
1. **`workflow-plan` skill (context-gather phase)**: Loads guidelines into context-package.json
2. **`workflow-plan` skill**: Passes guidelines to task generation agent
@@ -462,4 +436,5 @@ This ensures all future planning respects solidified rules without users needing
- `/workflow:session:start` - Start a session (may prompt for solidify at end)
- `/workflow:session:complete` - Complete session (prompts for learnings to solidify)
- `/workflow:init` - Creates project-guidelines.json scaffold if missing
- `/workflow:init` - Creates specs/*.md scaffold if missing
- `/workflow:init-specs` - Interactive wizard to create individual specs with scope selection

View File

@@ -27,7 +27,7 @@ The `--type` parameter classifies sessions for CCW dashboard organization:
|------|-------------|-------------|
| `workflow` | Standard implementation (default) | `workflow-plan` skill |
| `review` | Code review sessions | `review-cycle` skill |
| `tdd` | TDD-based development | `workflow-tdd` skill |
| `tdd` | TDD-based development | `workflow-tdd-plan` skill |
| `test` | Test generation/fix sessions | `workflow-test-fix` skill |
| `docs` | Documentation sessions | `memory-manage` skill |
@@ -44,7 +44,7 @@ ERROR: Invalid session type. Valid types: workflow, review, tdd, test, docs
```bash
# Check if project state exists (both files required)
bash(test -f .workflow/project-tech.json && echo "TECH_EXISTS" || echo "TECH_NOT_FOUND")
bash(test -f .workflow/project-guidelines.json && echo "GUIDELINES_EXISTS" || echo "GUIDELINES_NOT_FOUND")
bash(test -f .ccw/specs/*.md && echo "GUIDELINES_EXISTS" || echo "GUIDELINES_NOT_FOUND")
```
**If either NOT_FOUND**, delegate to `/workflow:init`:
@@ -53,14 +53,14 @@ bash(test -f .workflow/project-guidelines.json && echo "GUIDELINES_EXISTS" || ec
Skill(skill="workflow:init");
// Wait for init completion
// project-tech.json and project-guidelines.json will be created
// project-tech.json and specs/*.md will be created
```
**Output**:
- If BOTH_EXIST: `PROJECT_STATE: initialized`
- If NOT_FOUND: Calls `/workflow:init` → creates:
- `.workflow/project-tech.json` with full technical analysis
- `.workflow/project-guidelines.json` with empty scaffold
- `.ccw/specs/*.md` with empty scaffold
**Note**: `/workflow:init` uses cli-explore-agent to build comprehensive project understanding (technology stack, architecture, key components). This step runs once per project. Subsequent executions skip initialization.

View File

@@ -0,0 +1,202 @@
---
name: sync
description: Quick-sync session work to specs/*.md and project-tech
argument-hint: "[-y|--yes] [\"what was done\"]"
allowed-tools: Bash(*), Read(*), Write(*), Edit(*)
---
# Session Sync (/workflow:session:sync)
One-shot update `specs/*.md` + `project-tech.json` from current session context.
**Design**: Scan context → extract → write. No interactive wizards.
## Auto Mode
`--yes` or `-y`: Skip confirmation, auto-write both files.
## Process
```
Step 1: Gather Context
├─ git diff --stat HEAD~3..HEAD (recent changes)
├─ Active session folder (.workflow/.lite-plan/*) if exists
└─ User summary ($ARGUMENTS or auto-generate from git log)
Step 2: Extract Updates
├─ Guidelines: conventions / constraints / learnings
└─ Tech: development_index entry
Step 3: Preview & Confirm (skip if --yes)
Step 4: Write both files
Step 5: One-line confirmation
```
## Step 1: Gather Context
```javascript
const autoYes = $ARGUMENTS.includes('--yes') || $ARGUMENTS.includes('-y')
const userSummary = $ARGUMENTS.replace(/--yes|-y/g, '').trim()
// Recent changes
const gitStat = Bash('git diff --stat HEAD~3..HEAD 2>/dev/null || git diff --stat HEAD 2>/dev/null')
const gitLog = Bash('git log --oneline -5')
// Active session (optional)
const sessionFolders = Glob('.workflow/.lite-plan/*/plan.json')
let sessionContext = null
if (sessionFolders.length > 0) {
const latest = sessionFolders[sessionFolders.length - 1]
sessionContext = JSON.parse(Read(latest))
}
// Build summary
const summary = userSummary
|| sessionContext?.summary
|| gitLog.split('\n')[0].replace(/^[a-f0-9]+ /, '')
```
## Step 2: Extract Updates
Analyze context and produce two update payloads. Use LLM reasoning (current agent) — no CLI calls.
```javascript
// ── Guidelines extraction ──
// Scan git diff + session for:
// - New patterns adopted → convention
// - Restrictions discovered → constraint
// - Surprises / gotchas → learning
//
// Output: array of { type, category, text }
// RULE: Only extract genuinely reusable insights. Skip trivial/obvious items.
// RULE: Deduplicate against existing guidelines before adding.
// Load existing specs via ccw spec load
const existingSpecs = Bash('ccw spec load --dimension specs 2>/dev/null || echo ""')
const guidelineUpdates = [] // populated by agent analysis
// ── Tech extraction ──
// Build one development_index entry from session work
function detectCategory(text) {
text = text.toLowerCase()
if (/\b(fix|bug|error|crash)\b/.test(text)) return 'bugfix'
if (/\b(refactor|cleanup|reorganize)\b/.test(text)) return 'refactor'
if (/\b(doc|readme|comment)\b/.test(text)) return 'docs'
if (/\b(add|new|create|implement)\b/.test(text)) return 'feature'
return 'enhancement'
}
function detectSubFeature(gitStat) {
// Most-changed directory from git diff --stat
const dirs = gitStat.match(/\S+\//g) || []
const counts = {}
dirs.forEach(d => {
const seg = d.split('/').filter(Boolean).slice(-2, -1)[0] || 'general'
counts[seg] = (counts[seg] || 0) + 1
})
return Object.entries(counts).sort((a, b) => b[1] - a[1])[0]?.[0] || 'general'
}
const techEntry = {
title: summary.slice(0, 60),
sub_feature: detectSubFeature(gitStat),
date: new Date().toISOString().split('T')[0],
description: summary.slice(0, 100),
status: 'completed',
session_id: sessionContext ? sessionFolders[sessionFolders.length - 1].match(/lite-plan\/([^/]+)/)?.[1] : null
}
```
## Step 3: Preview & Confirm
```javascript
// Show preview
console.log(`
── Sync Preview ──
Guidelines (${guidelineUpdates.length} items):
${guidelineUpdates.map(g => ` [${g.type}/${g.category}] ${g.text}`).join('\n') || ' (none)'}
Tech [${detectCategory(summary)}]:
${techEntry.title}
Target files:
.ccw/specs/*.md
.workflow/project-tech.json
`)
if (!autoYes) {
const confirm = AskUserQuestion("Apply these updates? (modify/skip items if needed)")
// User can say "skip guidelines" or "change category to bugfix" etc.
}
```
## Step 4: Write
```javascript
// ── Update specs/*.md ──
// Uses .ccw/specs/ directory (same as frontend/backend spec-index-builder)
if (guidelineUpdates.length > 0) {
// Map guideline types to spec files
const specFileMap = {
convention: '.ccw/specs/coding-conventions.md',
constraint: '.ccw/specs/architecture-constraints.md',
learning: '.ccw/specs/coding-conventions.md' // learnings appended to conventions
}
for (const g of guidelineUpdates) {
const targetFile = specFileMap[g.type]
const existing = Read(targetFile)
const ruleText = g.type === 'learning'
? `- [${g.category}] ${g.text} (learned: ${new Date().toISOString().split('T')[0]})`
: `- [${g.category}] ${g.text}`
// Deduplicate: skip if text already in file
if (!existing.includes(g.text)) {
const newContent = existing.trimEnd() + '\n' + ruleText + '\n'
Write(targetFile, newContent)
}
}
// Rebuild spec index after writing
Bash('ccw spec rebuild')
}
// ── Update project-tech.json ──
const techPath = '.workflow/project-tech.json'
const tech = JSON.parse(Read(techPath))
if (!tech.development_index) {
tech.development_index = { feature: [], enhancement: [], bugfix: [], refactor: [], docs: [] }
}
const category = detectCategory(summary)
tech.development_index[category].push(techEntry)
tech._metadata.last_updated = new Date().toISOString()
Write(techPath, JSON.stringify(tech, null, 2))
```
## Step 5: Confirm
```
✓ Synced: ${guidelineUpdates.length} guidelines + 1 tech entry [${category}]
```
## Error Handling
| Error | Resolution |
|-------|------------|
| File missing | Create scaffold (same as solidify Step 1) |
| No git history | Use user summary or session context only |
| No meaningful updates | Skip guidelines, still add tech entry |
| Duplicate entry | Skip silently (dedup check in Step 4) |
## Related Commands
- `/workflow:init` - Initialize project with specs scaffold
- `/workflow:init-specs` - Interactive wizard to create individual specs with scope selection
- `/workflow:session:solidify` - Add individual rules one at a time

View File

@@ -1,6 +1,6 @@
---
name: design-sync
description: Synchronize finalized design system references to brainstorming artifacts, preparing them for /workflow:plan consumption
description: Synchronize finalized design system references to brainstorming artifacts, preparing them for /workflow-plan consumption
argument-hint: --session <session_id> [--selected-prototypes "<list>"]
allowed-tools: Read(*), Write(*), Edit(*), TodoWrite(*), Glob(*), Bash(*)
---
@@ -351,10 +351,10 @@ Updated artifacts:
✓ {role_count} role analysis.md files - Design system references
✓ ui-designer/design-system-reference.md - Design system reference guide
Design system assets ready for /workflow:plan:
Design system assets ready for /workflow-plan:
- design-tokens.json | style-guide.md | {prototype_count} reference prototypes
Next: /workflow:plan [--agent] "<task description>"
Next: /workflow-plan [--agent] "<task description>"
The plan phase will automatically discover and utilize the design system.
```
@@ -394,7 +394,7 @@ Next: /workflow:plan [--agent] "<task description>"
@../../{design_id}/prototypes/{prototype}.html
```
## Integration with /workflow:plan
## Integration with /workflow-plan
After this update, `workflow-plan` skill will discover design assets through:

View File

@@ -606,7 +606,7 @@ Total workflow time: ~{estimate_total_time()} minutes
{IF session_id:
2. Create implementation tasks:
/workflow:plan --session {session_id}
/workflow-plan --session {session_id}
3. Generate tests (if needed):
/workflow:test-gen {session_id}
@@ -741,5 +741,5 @@ Design Quality:
- Design token driven
- {generated_count} assembled prototypes
Next: [/workflow:execute] OR [Open compare.html → /workflow:plan]
Next: [/workflow-execute] OR [Open compare.html → /workflow-plan]
```

View File

@@ -471,11 +471,26 @@ ${recommendations.map(r => \`- ${r}\`).join('\\n')}
2. **Build Execution Context**
**Load Project Context** (from init.md products):
```javascript
// Read project-tech.json (if exists)
const projectTech = file_exists('.workflow/project-tech.json')
? JSON.parse(Read('.workflow/project-tech.json')) : null
// Read specs/*.md (if exists)
const projectGuidelines = file_exists('.ccw/specs/*.md')
? JSON.parse(Read('.ccw/specs/*.md')) : null
```
```javascript
const executionContext = `
⚠️ Execution Notes from Previous Tasks
${relevantNotes} // Categorized notes with severity
📋 Project Context (from init.md)
- Tech Stack: ${projectTech?.technology_analysis?.technology_stack || 'N/A'}
- Architecture: ${projectTech?.technology_analysis?.architecture?.style || 'N/A'}
- Constraints: ${projectGuidelines?.constraints || 'None defined'}
Current Task: ${task.id}
- Original ID: ${task.original_id}
- Source Plan: ${task.source_plan}

View File

@@ -43,19 +43,19 @@ function getExistingCommandSources() {
// These commands were migrated to skills but references were never updated
const COMMAND_TO_SKILL_MAP = {
// workflow commands → skills
'/workflow:plan': 'workflow-plan',
'/workflow:execute': 'workflow-execute',
'/workflow:lite-plan': 'workflow-lite-plan',
'/workflow:lite-execute': 'workflow-lite-plan', // lite-execute is part of lite-plan skill
'/workflow:lite-fix': 'workflow-lite-plan', // lite-fix is part of lite-plan skill
'/workflow:multi-cli-plan': 'workflow-multi-cli-plan',
'/workflow:plan-verify': 'workflow-plan', // plan-verify is a phase of workflow-plan
'/workflow-plan': 'workflow-plan',
'/workflow-execute': 'workflow-execute',
'/workflow-lite-planex': 'workflow-lite-planex',
'/workflow:lite-execute': 'workflow-lite-planex', // lite-execute 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-plan-verify': 'workflow-plan', // plan-verify is a phase of workflow-plan
'/workflow:replan': 'workflow-plan', // replan is a phase of workflow-plan
'/workflow:tdd-plan': 'workflow-tdd',
'/workflow:tdd-verify': 'workflow-tdd', // tdd-verify is a phase of workflow-tdd
'/workflow:test-fix-gen': 'workflow-test-fix',
'/workflow-tdd-plan': 'workflow-tdd-plan',
'/workflow-tdd-verify': 'workflow-tdd-plan', // tdd-verify is a phase of workflow-tdd-plan
'/workflow-test-fix': 'workflow-test-fix',
'/workflow:test-gen': 'workflow-test-fix',
'/workflow:test-cycle-execute': 'workflow-test-fix',
'/workflow-test-fix': 'workflow-test-fix',
'/workflow:review': 'review-cycle',
'/workflow:review-session-cycle': 'review-cycle',
'/workflow:review-module-cycle': 'review-cycle',
@@ -70,8 +70,8 @@ const COMMAND_TO_SKILL_MAP = {
'/workflow:tools:context-gather': 'workflow-plan',
'/workflow:tools:conflict-resolution': 'workflow-plan',
'/workflow:tools:task-generate-agent': 'workflow-plan',
'/workflow:tools:task-generate-tdd': 'workflow-tdd',
'/workflow:tools:tdd-coverage-analysis': 'workflow-tdd',
'/workflow:tools:task-generate-tdd': 'workflow-tdd-plan',
'/workflow:tools:tdd-coverage-analysis': 'workflow-tdd-plan',
'/workflow:tools:test-concept-enhanced': 'workflow-test-fix',
'/workflow:tools:test-context-gather': 'workflow-test-fix',
'/workflow:tools:test-task-generate': 'workflow-test-fix',
@@ -87,7 +87,7 @@ const COMMAND_TO_SKILL_MAP = {
// general commands
'/ccw-debug': 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)
'/workflow:ui-design:auto': '/workflow:ui-design:explore-auto',
'/workflow:ui-design:update': '/workflow:ui-design:generate',
@@ -302,8 +302,8 @@ function fixBrokenReferences() {
"skill='compact'": "skill='memory-capture'",
'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-plan'",
'skill="workflow:lite-execute"': 'skill="workflow-lite-planex"',
"skill='workflow:lite-execute'": "skill='workflow-lite-planex'",
};
for (const [oldCall, newCall] of Object.entries(skillCallFixes)) {
@@ -319,17 +319,17 @@ function fixBrokenReferences() {
// Pattern: `/ command:name` references that point to non-existent commands
// These are documentation references - update to point to skill names
const proseRefFixes = {
'`/workflow:plan`': '`workflow-plan` skill',
'`/workflow:execute`': '`workflow-execute` skill',
'`/workflow:lite-execute`': '`workflow-lite-plan` skill',
'`/workflow:lite-fix`': '`workflow-lite-plan` skill',
'`/workflow:plan-verify`': '`workflow-plan` skill (plan-verify phase)',
'`/workflow-plan`': '`workflow-plan` skill',
'`/workflow-execute`': '`workflow-execute` skill',
'`/workflow:lite-execute`': '`workflow-lite-planex` skill',
'`/workflow:lite-fix`': '`workflow-lite-planex` skill',
'`/workflow-plan-verify`': '`workflow-plan` skill (plan-verify phase)',
'`/workflow:replan`': '`workflow-plan` skill (replan phase)',
'`/workflow:tdd-plan`': '`workflow-tdd` skill',
'`/workflow:tdd-verify`': '`workflow-tdd` skill (tdd-verify phase)',
'`/workflow:test-fix-gen`': '`workflow-test-fix` skill',
'`/workflow-tdd-plan`': '`workflow-tdd-plan` skill',
'`/workflow-tdd-verify`': '`workflow-tdd-plan` skill (tdd-verify phase)',
'`/workflow-test-fix`': '`workflow-test-fix` skill',
'`/workflow:test-gen`': '`workflow-test-fix` skill',
'`/workflow:test-cycle-execute`': '`workflow-test-fix` skill',
'`/workflow-test-fix`': '`workflow-test-fix` skill',
'`/workflow:review`': '`review-cycle` skill',
'`/workflow:review-session-cycle`': '`review-cycle` skill',
'`/workflow:review-module-cycle`': '`review-cycle` skill',
@@ -346,9 +346,9 @@ function fixBrokenReferences() {
'`/workflow:tools:task-generate`': '`workflow-plan` skill (task-generate phase)',
'`/workflow:ui-design:auto`': '`/workflow:ui-design:explore-auto`',
'`/workflow:ui-design:update`': '`/workflow:ui-design:generate`',
'`/workflow:multi-cli-plan`': '`workflow-multi-cli-plan` skill',
'`/workflow:lite-plan`': '`workflow-lite-plan` skill',
'`/cli:plan`': '`workflow-lite-plan` skill',
'`/workflow-multi-cli-plan`': '`workflow-multi-cli-plan` skill',
'`/workflow-lite-planex`': '`workflow-lite-planex` skill',
'`/cli:plan`': '`workflow-lite-planex` skill',
'`/test-cycle-execute`': '`workflow-test-fix` skill',
};

View File

@@ -123,7 +123,7 @@
| **命令调用语法** | 转换为 Phase 文件的相对路径 | `/workflow:session:start``phases/01-session-discovery.md` |
| **命令路径引用** | 转换为 Skill 目录内路径 | `commands/workflow/tools/``phases/` |
| **跨命令引用** | 转换为 Phase 间文件引用 | `workflow-plan` skill (context-gather phase) → `phases/02-context-gathering.md` |
| **命令参数说明** | 移除或转为 Phase Prerequisites | `usage: /workflow:plan [session-id]` → Phase Prerequisites 中说明 |
| **命令参数说明** | 移除或转为 Phase Prerequisites | `usage: /workflow-plan [session-id]` → Phase Prerequisites 中说明 |
**转换示例**

View File

@@ -373,7 +373,7 @@ Initial → Phase 1 Mode Routing (completed)
- `/workflow:session:start` - Start a new workflow session (optional, brainstorm creates its own)
**Follow-ups** (after brainstorm completes):
- `/workflow:plan --session {sessionId}` - Generate implementation plan
- `/workflow-plan --session {sessionId}` - Generate implementation plan
- `/workflow:brainstorm:synthesis --session {sessionId}` - Run synthesis standalone (if skipped)
## Reference Information

View File

@@ -469,7 +469,7 @@ ${selected_roles.length > 1 ? `
- Run synthesis: /brainstorm --session ${session_id} (auto mode)
` : `
- Clarify insights: /brainstorm --session ${session_id} (auto mode)
- Generate plan: /workflow:plan --session ${session_id}
- Generate plan: /workflow-plan --session ${session_id}
`}
```

View File

@@ -744,7 +744,7 @@ Write(context_pkg_path, JSON.stringify(context_pkg))
**Changelog**: .brainstorming/synthesis-changelog.md
### Next Steps
PROCEED: `/workflow:plan --session {session-id}`
PROCEED: `/workflow-plan --session {session-id}`
```
## Output

View File

@@ -1,18 +1,18 @@
---
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
version: 7.0.0
version: 8.0.0
---
# CCW-Help Skill
CCW 命令帮助系统,提供命令搜索、推荐、文档查看功能。
CCW 命令帮助系统,提供命令搜索、推荐、文档查看、Skill/Team 浏览功能。
## Trigger Conditions
- 关键词: "ccw-help", "ccw-issue", "帮助", "命令", "怎么用", "ccw 怎么用", "工作流"
- 场景: 询问命令用法、搜索命令、请求下一步建议、询问任务应该用哪个工作流
- 关键词: "ccw-help", "ccw-issue", "帮助", "命令", "怎么用", "ccw 怎么用", "工作流", "skill", "team"
- 场景: 询问命令用法、搜索命令、请求下一步建议、询问任务应该用哪个工作流、浏览 Skill/Team 目录
## Operation Modes
@@ -61,7 +61,7 @@ CCW 命令帮助系统,提供命令搜索、推荐、文档查看功能。
4. Get user confirmation
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 2** (Rapid/Hotfix): Bug fixes, simple features, documentation
- **Level 2.5** (Rapid-to-Issue): Bridge from quick planning to issue workflow
@@ -71,12 +71,17 @@ CCW 命令帮助系统,提供命令搜索、推荐、文档查看功能。
- Test-fix workflows (debug failing tests)
- Review workflows (code review and fixes)
- UI design workflows
- Multi-CLI collaborative workflows
- Cycle workflows (integration-test, refactor)
- **Level 4** (Full): Exploratory tasks with brainstorming
- **With-File Workflows**: Documented exploration with multi-CLI collaboration
- `brainstorm-with-file`: Multi-perspective ideation
- `debug-with-file`: Hypothesis-driven debugging
- `analyze-with-file`: Collaborative analysis
- `brainstorm-with-file`: Multi-perspective ideation → workflow-plan → workflow-execute
- `debug-with-file`: Hypothesis-driven debugging (standalone)
- `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
- **Team Workflow**: team-planex wave pipeline for parallel execution
### Mode 6: Issue Reporting
@@ -86,6 +91,16 @@ CCW 命令帮助系统,提供命令搜索、推荐、文档查看功能。
1. Use AskUserQuestion to gather context
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
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[].flow` | Relationships (next_steps, prerequisites) |
| `commands[].essential` | Essential flag for onboarding |
| `agents[]` | Agent directory |
| `skills[]` | Skill directory with categories |
| `skills[].is_team` | Whether skill uses team architecture |
| `essential_commands[]` | Core commands list |
### 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-v5` | 完整生命周期 (spec/impl/test) | team-worker agents with role-specs |
| `team-lifecycle-v4` | 优化版生命周期 | Optimized pipeline |
| `team-lifecycle-v3` | 基础版生命周期 | All roles invoke unified skill |
| `team-coordinate-v2` | 通用动态团队协调 | 运行时动态生成 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` | 轻量执行 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
```bash
@@ -116,6 +203,8 @@ Single source of truth: **[command.json](command.json)**
/ccw-help # General help entry
/ccw-help search <keyword> # Search commands
/ccw-help next <command> # Get next step suggestions
/ccw-help skills # Browse skill catalog
/ccw-help teams # Browse team skills
/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 debug-file, use debug-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
@@ -135,6 +227,7 @@ Single source of truth: **[command.json](command.json)**
### Update Mechanism
CCW-Help skill supports manual updates through user confirmation dialog.
Script scans `commands/`, `agents/`, and `skills/` directories to regenerate all indexes.
#### How to Update
@@ -153,18 +246,33 @@ cd D:/Claude_dms3/.claude/skills/ccw-help
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
- **`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
- **Commands**: 50+
- **Agents**: 16
- **Workflows**: 6 main levels + 3 with-file variants
- **Agents**: 22
- **Skills**: 36+ (7 workflow, 19 team, 10+ standalone/utility)
- **Workflows**: 6 main levels + 5 with-file variants + 2 cycle variants
- **Essential**: 10 core commands
## Core Principle

File diff suppressed because it is too large Load Diff

View File

@@ -29,6 +29,11 @@
"description": "|",
"source": "../../../agents/cli-planning-agent.md"
},
{
"name": "cli-roadmap-plan-agent",
"description": "|",
"source": "../../../agents/cli-roadmap-plan-agent.md"
},
{
"name": "code-developer",
"description": "|",
@@ -74,6 +79,16 @@
"description": "|",
"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",
"description": "|",

View File

@@ -43,6 +43,72 @@
"difficulty": "Intermediate",
"source": "../../../commands/cli/codex-review.md"
},
{
"name": "flow-create",
"command": "/flow-create",
"description": "",
"arguments": "",
"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",
"command": "/issue:convert-to-plan",
@@ -131,6 +197,17 @@
"difficulty": "Intermediate",
"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",
"command": "/memory:style-skill-memory",
@@ -175,6 +252,17 @@
"difficulty": "Intermediate",
"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",
"command": "/workflow:debug-with-file",
@@ -186,17 +274,72 @@
"difficulty": "Intermediate",
"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",
"command": "/workflow:init",
"description": "Initialize project-level state with intelligent project analysis using cli-explore-agent",
"arguments": "[--regenerate]",
"arguments": "[--regenerate] [--skip-specs]",
"category": "workflow",
"subcategory": null,
"usage_scenario": "general",
"difficulty": "Intermediate",
"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",
"command": "/workflow:session:complete",
@@ -233,8 +376,8 @@
{
"name": "solidify",
"command": "/workflow:session:solidify",
"description": "Crystallize session learnings and user-defined constraints into permanent project guidelines",
"arguments": "[-y|--yes] [--type <convention|constraint|learning>] [--category <category>] \\\"rule or insight\\",
"description": "Crystallize session learnings and user-defined constraints into permanent project guidelines, or compress recent memories",
"arguments": "[-y|--yes] [--type <convention|constraint|learning|compress>] [--category <category>] [--limit <N>] \\\"rule or insight\\",
"category": "workflow",
"subcategory": "session",
"usage_scenario": "general",
@@ -252,6 +395,17 @@
"difficulty": "Intermediate",
"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",
"command": "/workflow:ui-design:animation-extract",
@@ -277,7 +431,7 @@
{
"name": "design-sync",
"command": "/workflow:ui-design:design-sync",
"description": "Synchronize finalized design system references to brainstorming artifacts, preparing them for /workflow:plan consumption",
"description": "Synchronize finalized design system references to brainstorming artifacts, preparing them for /workflow-plan consumption",
"arguments": "--session <session_id> [--selected-prototypes \"<list>\"]",
"category": "workflow",
"subcategory": "ui-design",
@@ -366,11 +520,11 @@
"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\\\"]",
"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"
}
]
]

View File

@@ -0,0 +1,362 @@
[
{
"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": "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-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. Only coordinator is built-in -- all worker roles are generated at runtime based on task analysis. 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-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\".",
"category": "team",
"is_team": true,
"has_phases": false,
"has_role_specs": false,
"version": "",
"source": "../../../skills/team-coordinate-v2/SKILL.md"
},
{
"name": "team-executor",
"description": "Lightweight session execution skill. Resumes existing team-coordinate sessions for pure execution. 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-executor-v2",
"description": "Lightweight session execution skill. Resumes existing team-coordinate-v2 sessions for pure execution via team-worker agents. No analysis, no role generation -- only loads and executes. Session path required. Triggers on \"team executor v2\".",
"category": "team",
"is_team": true,
"has_phases": false,
"has_role_specs": false,
"version": "",
"source": "../../../skills/team-executor-v2/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-v3",
"description": "Unified team skill for full lifecycle - spec/impl/test. All roles invoke this skill with --role arg for role-specific execution. Triggers on \"team lifecycle\".",
"category": "team",
"is_team": true,
"has_phases": false,
"has_role_specs": false,
"version": "",
"source": "../../../skills/team-lifecycle-v3/SKILL.md"
},
{
"name": "team-lifecycle-v4",
"description": "Unified team skill for full lifecycle - spec/impl/test. Optimized cadence with inline discuss subagent and shared explore. All roles invoke this skill with --role arg for role-specific execution. Triggers on \"team lifecycle\".",
"category": "team",
"is_team": true,
"has_phases": false,
"has_role_specs": false,
"version": "",
"source": "../../../skills/team-lifecycle-v4/SKILL.md"
},
{
"name": "team-lifecycle-v5",
"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-v5/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-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",
"difficulty": "Intermediate",
"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": {
"_root": [
{
@@ -145,6 +215,17 @@
},
"memory": {
"_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",
"command": "/memory:style-skill-memory",
@@ -193,6 +274,17 @@
"difficulty": "Intermediate",
"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",
"command": "/workflow:debug-with-file",
@@ -204,22 +296,77 @@
"difficulty": "Intermediate",
"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",
"command": "/workflow:init",
"description": "Initialize project-level state with intelligent project analysis using cli-explore-agent",
"arguments": "[--regenerate]",
"arguments": "[--regenerate] [--skip-specs]",
"category": "workflow",
"subcategory": null,
"usage_scenario": "general",
"difficulty": "Intermediate",
"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",
"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\\\"]",
"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",
@@ -264,8 +411,8 @@
{
"name": "solidify",
"command": "/workflow:session:solidify",
"description": "Crystallize session learnings and user-defined constraints into permanent project guidelines",
"arguments": "[-y|--yes] [--type <convention|constraint|learning>] [--category <category>] \\\"rule or insight\\",
"description": "Crystallize session learnings and user-defined constraints into permanent project guidelines, or compress recent memories",
"arguments": "[-y|--yes] [--type <convention|constraint|learning|compress>] [--category <category>] [--limit <N>] \\\"rule or insight\\",
"category": "workflow",
"subcategory": "session",
"usage_scenario": "general",
@@ -282,6 +429,17 @@
"usage_scenario": "general",
"difficulty": "Intermediate",
"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": [
@@ -310,7 +468,7 @@
{
"name": "design-sync",
"command": "/workflow:ui-design:design-sync",
"description": "Synchronize finalized design system references to brainstorming artifacts, preparing them for /workflow:plan consumption",
"description": "Synchronize finalized design system references to brainstorming artifacts, preparing them for /workflow-plan consumption",
"arguments": "--session <session_id> [--selected-prototypes \"<list>\"]",
"category": "workflow",
"subcategory": "ui-design",
@@ -397,4 +555,4 @@
}
]
}
}
}

View File

@@ -33,6 +33,39 @@
"difficulty": "Intermediate",
"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",
"command": "/issue:discover-by-prompt",
@@ -77,6 +110,17 @@
"difficulty": "Intermediate",
"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",
"command": "/workflow:clean",
@@ -99,17 +143,61 @@
"difficulty": "Intermediate",
"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",
"command": "/workflow:init",
"description": "Initialize project-level state with intelligent project analysis using cli-explore-agent",
"arguments": "[--regenerate]",
"arguments": "[--regenerate] [--skip-specs]",
"category": "workflow",
"subcategory": null,
"usage_scenario": "general",
"difficulty": "Intermediate",
"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",
"command": "/workflow:session:list",
@@ -124,8 +212,8 @@
{
"name": "solidify",
"command": "/workflow:session:solidify",
"description": "Crystallize session learnings and user-defined constraints into permanent project guidelines",
"arguments": "[-y|--yes] [--type <convention|constraint|learning>] [--category <category>] \\\"rule or insight\\",
"description": "Crystallize session learnings and user-defined constraints into permanent project guidelines, or compress recent memories",
"arguments": "[-y|--yes] [--type <convention|constraint|learning|compress>] [--category <category>] [--limit <N>] \\\"rule or insight\\",
"category": "workflow",
"subcategory": "session",
"usage_scenario": "general",
@@ -143,6 +231,17 @@
"difficulty": "Intermediate",
"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",
"command": "/workflow:ui-design:animation-extract",
@@ -223,6 +322,98 @@
"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": [
{
"name": "convert-to-plan",
@@ -268,6 +459,17 @@
"difficulty": "Intermediate",
"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",
"command": "/workflow:ui-design:codify-style",
@@ -282,7 +484,7 @@
{
"name": "design-sync",
"command": "/workflow:ui-design:design-sync",
"description": "Synchronize finalized design system references to brainstorming artifacts, preparing them for /workflow:plan consumption",
"description": "Synchronize finalized design system references to brainstorming artifacts, preparing them for /workflow-plan consumption",
"arguments": "--session <session_id> [--selected-prototypes \"<list>\"]",
"category": "workflow",
"subcategory": "ui-design",
@@ -313,41 +515,6 @@
"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": [
{
"name": "style-skill-memory",
@@ -361,28 +528,17 @@
"source": "../../../commands/memory/style-skill-memory.md"
}
],
"session-management": [
"testing": [
{
"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]",
"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": "session",
"usage_scenario": "session-management",
"subcategory": null,
"usage_scenario": "testing",
"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"
"source": "../../../commands/workflow/integration-test-cycle.md"
}
]
}
}

View File

@@ -1,15 +1,146 @@
{
"workflow-plan": {
"calls_internally": [
"workflow:session:start",
"workflow:tools:context-gather",
"workflow:tools:conflict-resolution",
"workflow:tools:task-generate-agent"
],
"next_steps": [
"workflow-plan-verify",
"workflow:status",
"workflow-execute"
],
"alternatives": [
"workflow-tdd-plan"
],
"prerequisites": []
},
"workflow-tdd-plan": {
"calls_internally": [
"workflow:session:start",
"workflow:tools:context-gather",
"workflow:tools:task-generate-tdd"
],
"next_steps": [
"workflow-tdd-verify",
"workflow:status",
"workflow-execute"
],
"alternatives": [
"workflow-plan"
],
"prerequisites": []
},
"workflow-execute": {
"prerequisites": [
"workflow-plan",
"workflow-tdd-plan"
],
"related": [
"workflow:status",
"workflow:resume"
],
"next_steps": [
"workflow:review",
"workflow-tdd-verify"
]
},
"workflow-plan-verify": {
"prerequisites": [
"workflow-plan"
],
"next_steps": [
"workflow-execute"
],
"related": [
"workflow:status"
]
},
"workflow-tdd-verify": {
"prerequisites": [
"workflow-execute"
],
"related": [
"workflow:tools:tdd-coverage-analysis"
]
},
"workflow:session:start": {
"next_steps": [],
"next_steps": [
"workflow-plan",
"workflow-execute"
],
"related": [
"workflow:session:list",
"workflow:session:resume"
]
},
"workflow:session:resume": {
"alternatives": [],
"alternatives": [
"workflow:resume"
],
"related": [
"workflow:session:list"
"workflow:session:list",
"workflow:status"
]
},
"workflow-lite-planex": {
"calls_internally": [],
"next_steps": [
"workflow:status"
],
"alternatives": [
"workflow-plan"
],
"prerequisites": []
},
"workflow:lite-fix": {
"next_steps": [
"workflow:status"
],
"alternatives": [
"workflow-lite-planex"
],
"related": [
"workflow-test-fix"
]
},
"workflow:review-session-cycle": {
"prerequisites": [
"workflow-execute"
],
"next_steps": [
"workflow:review-fix"
],
"related": [
"workflow:review-module-cycle"
]
},
"workflow:review-fix": {
"prerequisites": [
"workflow:review-module-cycle",
"workflow:review-session-cycle"
],
"related": [
"workflow-test-fix"
]
},
"memory:docs": {
"calls_internally": [
"workflow:session:start",
"workflow:tools:context-gather"
],
"next_steps": [
"workflow-execute"
]
},
"memory:skill-memory": {
"next_steps": [
"workflow-plan",
"cli:analyze"
],
"related": [
"memory:load-skill-memory"
]
}
}
}

View File

@@ -10,4 +10,4 @@
"difficulty": "Intermediate",
"source": "../../../commands/workflow/session/start.md"
}
]
]

View File

@@ -0,0 +1,374 @@
{
"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": "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-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. Only coordinator is built-in -- all worker roles are generated at runtime based on task analysis. 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-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\".",
"category": "team",
"is_team": true,
"has_phases": false,
"has_role_specs": false,
"version": "",
"source": "../../../skills/team-coordinate-v2/SKILL.md"
},
{
"name": "team-executor",
"description": "Lightweight session execution skill. Resumes existing team-coordinate sessions for pure execution. 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-executor-v2",
"description": "Lightweight session execution skill. Resumes existing team-coordinate-v2 sessions for pure execution via team-worker agents. No analysis, no role generation -- only loads and executes. Session path required. Triggers on \"team executor v2\".",
"category": "team",
"is_team": true,
"has_phases": false,
"has_role_specs": false,
"version": "",
"source": "../../../skills/team-executor-v2/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-v3",
"description": "Unified team skill for full lifecycle - spec/impl/test. All roles invoke this skill with --role arg for role-specific execution. Triggers on \"team lifecycle\".",
"category": "team",
"is_team": true,
"has_phases": false,
"has_role_specs": false,
"version": "",
"source": "../../../skills/team-lifecycle-v3/SKILL.md"
},
{
"name": "team-lifecycle-v4",
"description": "Unified team skill for full lifecycle - spec/impl/test. Optimized cadence with inline discuss subagent and shared explore. All roles invoke this skill with --role arg for role-specific execution. Triggers on \"team lifecycle\".",
"category": "team",
"is_team": true,
"has_phases": false,
"has_role_specs": false,
"version": "",
"source": "../../../skills/team-lifecycle-v4/SKILL.md"
},
{
"name": "team-lifecycle-v5",
"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-v5/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-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
"""
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).
"""
import os
import re
import json
from pathlib import Path
from collections import defaultdict
@@ -15,9 +14,13 @@ from typing import Dict, List, Any
BASE_DIR = Path("D:/Claude_dms3/.claude")
COMMANDS_DIR = BASE_DIR / "commands"
AGENTS_DIR = BASE_DIR / "agents"
SKILLS_DIR = BASE_DIR / "skills"
SKILL_DIR = BASE_DIR / "skills" / "ccw-help"
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]:
"""Extract YAML frontmatter from markdown content."""
frontmatter = {}
@@ -139,73 +142,129 @@ def analyze_agent_file(file_path: Path) -> Dict[str, Any]:
"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]:
"""Build command relationship mappings."""
return {
"workflow:plan": {
"workflow-plan": {
"calls_internally": ["workflow:session:start", "workflow:tools:context-gather", "workflow:tools:conflict-resolution", "workflow:tools:task-generate-agent"],
"next_steps": ["workflow:plan-verify", "workflow:status", "workflow:execute"],
"alternatives": ["workflow:tdd-plan"],
"next_steps": ["workflow-plan-verify", "workflow:status", "workflow-execute"],
"alternatives": ["workflow-tdd-plan"],
"prerequisites": []
},
"workflow:tdd-plan": {
"workflow-tdd-plan": {
"calls_internally": ["workflow:session:start", "workflow:tools:context-gather", "workflow:tools:task-generate-tdd"],
"next_steps": ["workflow:tdd-verify", "workflow:status", "workflow:execute"],
"alternatives": ["workflow:plan"],
"next_steps": ["workflow-tdd-verify", "workflow:status", "workflow-execute"],
"alternatives": ["workflow-plan"],
"prerequisites": []
},
"workflow:execute": {
"prerequisites": ["workflow:plan", "workflow:tdd-plan"],
"workflow-execute": {
"prerequisites": ["workflow-plan", "workflow-tdd-plan"],
"related": ["workflow:status", "workflow:resume"],
"next_steps": ["workflow:review", "workflow:tdd-verify"]
"next_steps": ["workflow:review", "workflow-tdd-verify"]
},
"workflow:plan-verify": {
"prerequisites": ["workflow:plan"],
"next_steps": ["workflow:execute"],
"workflow-plan-verify": {
"prerequisites": ["workflow-plan"],
"next_steps": ["workflow-execute"],
"related": ["workflow:status"]
},
"workflow:tdd-verify": {
"prerequisites": ["workflow:execute"],
"workflow-tdd-verify": {
"prerequisites": ["workflow-execute"],
"related": ["workflow:tools:tdd-coverage-analysis"]
},
"workflow:session:start": {
"next_steps": ["workflow:plan", "workflow:execute"],
"next_steps": ["workflow-plan", "workflow-execute"],
"related": ["workflow:session:list", "workflow:session:resume"]
},
"workflow:session:resume": {
"alternatives": ["workflow:resume"],
"related": ["workflow:session:list", "workflow:status"]
},
"workflow:lite-plan": {
"calls_internally": ["workflow:lite-execute"],
"next_steps": ["workflow:lite-execute", "workflow:status"],
"alternatives": ["workflow:plan"],
"workflow-lite-planex": {
"calls_internally": [],
"next_steps": ["workflow:status"],
"alternatives": ["workflow-plan"],
"prerequisites": []
},
"workflow:lite-fix": {
"next_steps": ["workflow:lite-execute", "workflow:status"],
"alternatives": ["workflow:lite-plan"],
"related": ["workflow:test-cycle-execute"]
},
"workflow:lite-execute": {
"prerequisites": ["workflow:lite-plan", "workflow:lite-fix"],
"related": ["workflow:execute", "workflow:status"]
"next_steps": ["workflow:status"],
"alternatives": ["workflow-lite-planex"],
"related": ["workflow-test-fix"]
},
"workflow:review-session-cycle": {
"prerequisites": ["workflow:execute"],
"prerequisites": ["workflow-execute"],
"next_steps": ["workflow:review-fix"],
"related": ["workflow:review-module-cycle"]
},
"workflow:review-fix": {
"prerequisites": ["workflow:review-module-cycle", "workflow:review-session-cycle"],
"related": ["workflow:test-cycle-execute"]
"related": ["workflow-test-fix"]
},
"memory:docs": {
"calls_internally": ["workflow:session:start", "workflow:tools:context-gather"],
"next_steps": ["workflow:execute"]
"next_steps": ["workflow-execute"]
},
"memory:skill-memory": {
"next_steps": ["workflow:plan", "cli:analyze"],
"next_steps": ["workflow-plan", "cli:analyze"],
"related": ["memory:load-skill-memory"]
}
}
@@ -213,11 +272,11 @@ def build_command_relationships() -> Dict[str, Any]:
def identify_essential_commands(all_commands: List[Dict]) -> List[Dict]:
"""Identify the most essential commands for beginners."""
essential_names = [
"workflow:lite-plan", "workflow:lite-fix", "workflow:plan",
"workflow:execute", "workflow:status", "workflow:session:start",
"workflow-lite-planex", "workflow:lite-fix", "workflow-plan",
"workflow-execute", "workflow:status", "workflow:session:start",
"workflow:review-session-cycle", "cli:analyze", "cli:chat",
"memory:docs", "workflow:brainstorm:artifacts",
"workflow:plan-verify", "workflow:resume", "version"
"workflow-plan-verify", "workflow:resume", "version"
]
essential = []
@@ -267,7 +326,24 @@ def main():
except Exception as 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
INDEX_DIR.mkdir(parents=True, exist_ok=True)
@@ -320,15 +396,62 @@ def main():
json.dump(relationships, f, indent=2, ensure_ascii=False)
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("\n=== Summary ===")
print(f"Commands: {len(all_commands)}")
print(f"Agents: {len(all_agents)}")
print(f"Skills: {len(all_skills)}")
print(f"Essential: {len(essential)}")
print(f"\nBy category:")
print(f"\nCommands by category:")
for cat in sorted(by_category.keys()):
total = sum(len(cmds) for cmds in by_category[cat].values())
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("=== Complete ===")

View File

@@ -0,0 +1,190 @@
---
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".
allowed-tools: Read, Write, Edit, Bash, Glob
---
# Command Generator
CLI-based command file generator producing Claude Code command .md files through a structured 5-phase workflow. Supports both project-level (`.claude/commands/`) and user-level (`~/.claude/commands/`) command locations.
## Architecture Overview
```
+-----------------------------------------------------------+
| Command Generator |
| |
| Input: skillName, description, location, [group], [hint] |
| | |
| +-------------------------------------------------+ |
| | Phase 1-5: Sequential Pipeline | |
| | | |
| | [P1] --> [P2] --> [P3] --> [P4] --> [P5] | |
| | Param Target Template Content File | |
| | Valid Path Loading Format Gen | |
| +-------------------------------------------------+ |
| | |
| Output: {scope}/.claude/commands/{group}/{name}.md |
| |
+-----------------------------------------------------------+
```
## Key Design Principles
1. **Single Responsibility**: Generates one command file per invocation
2. **Scope Awareness**: Supports project and user-level command locations
3. **Template-Driven**: Uses consistent template for all generated commands
4. **Validation First**: Validates all required parameters before file operations
5. **Non-Destructive**: Warns if command file already exists
---
## Execution Flow
```
Phase 1: Parameter Validation
- Ref: phases/01-parameter-validation.md
- Validate: skillName (required), description (required), location (required)
- Optional: group, argumentHint
- Output: validated params object
Phase 2: Target Path Resolution
- Ref: phases/02-target-path-resolution.md
- Resolve: location -> target commands directory
- Support: project (.claude/commands/) vs user (~/.claude/commands/)
- Handle: group subdirectory if provided
- Output: targetPath string
Phase 3: Template Loading
- Ref: phases/03-template-loading.md
- Load: templates/command-md.md
- Template contains YAML frontmatter with placeholders
- Output: templateContent string
Phase 4: Content Formatting
- Ref: phases/04-content-formatting.md
- Substitute: {{name}}, {{description}}, {{group}}, {{argumentHint}}
- Handle: optional fields (group, argumentHint)
- Output: formattedContent string
Phase 5: File Generation
- Ref: phases/05-file-generation.md
- Check: file existence (warn if exists)
- Write: formatted content to target path
- Output: success confirmation with file path
```
## Usage Examples
### Basic Command (Project Scope)
```javascript
Skill(skill="command-generator", args={
skillName: "deploy",
description: "Deploy application to production environment",
location: "project"
})
// Output: .claude/commands/deploy.md
```
### Grouped Command with Argument Hint
```javascript
Skill(skill="command-generator", args={
skillName: "create",
description: "Create new issue from GitHub URL or text",
location: "project",
group: "issue",
argumentHint: "[-y|--yes] <github-url | text-description> [--priority 1-5]"
})
// Output: .claude/commands/issue/create.md
```
### User-Level Command
```javascript
Skill(skill="command-generator", args={
skillName: "global-status",
description: "Show global Claude Code status",
location: "user"
})
// Output: ~/.claude/commands/global-status.md
```
---
## Reference Documents by Phase
### Phase 1: Parameter Validation
| Document | Purpose | When to Use |
|----------|---------|-------------|
| [phases/01-parameter-validation.md](phases/01-parameter-validation.md) | Validate required parameters | Phase 1 execution |
### Phase 2: Target Path Resolution
| Document | Purpose | When to Use |
|----------|---------|-------------|
| [phases/02-target-path-resolution.md](phases/02-target-path-resolution.md) | Resolve target directory | Phase 2 execution |
### Phase 3: Template Loading
| Document | Purpose | When to Use |
|----------|---------|-------------|
| [phases/03-template-loading.md](phases/03-template-loading.md) | Load command template | Phase 3 execution |
| [templates/command-md.md](templates/command-md.md) | Command file template | Template reference |
### Phase 4: Content Formatting
| Document | Purpose | When to Use |
|----------|---------|-------------|
| [phases/04-content-formatting.md](phases/04-content-formatting.md) | Format content with params | Phase 4 execution |
### Phase 5: File Generation
| Document | Purpose | When to Use |
|----------|---------|-------------|
| [phases/05-file-generation.md](phases/05-file-generation.md) | Write final file | Phase 5 execution |
### Design Specifications
| Document | Purpose | When to Use |
|----------|---------|-------------|
| [specs/command-design-spec.md](specs/command-design-spec.md) | Command design guidelines | Understanding best practices |
---
## Output Structure
### Generated Command File
```markdown
---
name: {skillName}
description: {description}
{group} {argumentHint}
---
# {skillName} Command
## Overview
{Auto-generated placeholder for command overview}
## Usage
{Auto-generated placeholder for usage examples}
## Execution Flow
{Auto-generated placeholder for execution steps}
```
---
## Error Handling
| Error | Stage | Action |
|-------|-------|--------|
| Missing skillName | Phase 1 | Error: "skillName is required" |
| Missing description | Phase 1 | Error: "description is required" |
| Missing location | Phase 1 | Error: "location is required (project or user)" |
| Invalid location | Phase 2 | Error: "location must be 'project' or 'user'" |
| Template not found | Phase 3 | Error: "Command template not found" |
| File exists | Phase 5 | Warning: "Command file already exists, will overwrite" |
| Write failure | Phase 5 | Error: "Failed to write command file" |
---
## Related Skills
- **skill-generator**: Create complete skills with phases, templates, and specs
- **flow-coordinator**: Orchestrate multi-step command workflows

View File

@@ -0,0 +1,174 @@
# Phase 1: Parameter Validation
Validate all required parameters for command generation.
## Objective
Ensure all required parameters are provided before proceeding with command generation:
- **skillName**: Command identifier (required)
- **description**: Command description (required)
- **location**: Target scope - "project" or "user" (required)
- **group**: Optional grouping subdirectory
- **argumentHint**: Optional argument hint string
## Input
Parameters received from skill invocation:
- `skillName`: string (required)
- `description`: string (required)
- `location`: "project" | "user" (required)
- `group`: string (optional)
- `argumentHint`: string (optional)
## Validation Rules
### Required Parameters
```javascript
const requiredParams = {
skillName: {
type: 'string',
minLength: 1,
pattern: /^[a-z][a-z0-9-]*$/, // lowercase, alphanumeric, hyphens
error: 'skillName must be lowercase alphanumeric with hyphens, starting with a letter'
},
description: {
type: 'string',
minLength: 10,
error: 'description must be at least 10 characters'
},
location: {
type: 'string',
enum: ['project', 'user'],
error: 'location must be "project" or "user"'
}
};
```
### Optional Parameters
```javascript
const optionalParams = {
group: {
type: 'string',
pattern: /^[a-z][a-z0-9-]*$/,
default: null,
error: 'group must be lowercase alphanumeric with hyphens'
},
argumentHint: {
type: 'string',
default: '',
error: 'argumentHint must be a string'
}
};
```
## Execution Steps
### Step 1: Extract Parameters
```javascript
// Extract from skill args
const params = {
skillName: args.skillName,
description: args.description,
location: args.location,
group: args.group || null,
argumentHint: args.argumentHint || ''
};
```
### Step 2: Validate Required Parameters
```javascript
function validateRequired(params, rules) {
const errors = [];
for (const [key, rule] of Object.entries(rules)) {
const value = params[key];
// Check existence
if (value === undefined || value === null || value === '') {
errors.push(`${key} is required`);
continue;
}
// Check type
if (typeof value !== rule.type) {
errors.push(`${key} must be a ${rule.type}`);
continue;
}
// Check minLength
if (rule.minLength && value.length < rule.minLength) {
errors.push(`${key} must be at least ${rule.minLength} characters`);
}
// Check pattern
if (rule.pattern && !rule.pattern.test(value)) {
errors.push(rule.error);
}
// Check enum
if (rule.enum && !rule.enum.includes(value)) {
errors.push(`${key} must be one of: ${rule.enum.join(', ')}`);
}
}
return errors;
}
const requiredErrors = validateRequired(params, requiredParams);
if (requiredErrors.length > 0) {
throw new Error(`Validation failed:\n${requiredErrors.join('\n')}`);
}
```
### Step 3: Validate Optional Parameters
```javascript
function validateOptional(params, rules) {
const warnings = [];
for (const [key, rule] of Object.entries(rules)) {
const value = params[key];
if (value !== null && value !== undefined && value !== '') {
if (rule.pattern && !rule.pattern.test(value)) {
warnings.push(`${key}: ${rule.error}`);
}
}
}
return warnings;
}
const optionalWarnings = validateOptional(params, optionalParams);
// Log warnings but continue
```
### Step 4: Normalize Parameters
```javascript
const validatedParams = {
skillName: params.skillName.trim().toLowerCase(),
description: params.description.trim(),
location: params.location.trim().toLowerCase(),
group: params.group ? params.group.trim().toLowerCase() : null,
argumentHint: params.argumentHint ? params.argumentHint.trim() : ''
};
```
## Output
```javascript
{
status: 'validated',
params: validatedParams,
warnings: optionalWarnings
}
```
## Next Phase
Proceed to [Phase 2: Target Path Resolution](02-target-path-resolution.md) with `validatedParams`.

View File

@@ -0,0 +1,171 @@
# Phase 2: Target Path Resolution
Resolve the target commands directory based on location parameter.
## Objective
Determine the correct target path for the command file based on:
- **location**: "project" or "user" scope
- **group**: Optional subdirectory for command organization
- **skillName**: Command filename (with .md extension)
## Input
From Phase 1 validation:
```javascript
{
skillName: string, // e.g., "create"
description: string,
location: "project" | "user",
group: string | null, // e.g., "issue"
argumentHint: string
}
```
## Path Resolution Rules
### Location Mapping
```javascript
const locationMap = {
project: '.claude/commands',
user: '~/.claude/commands' // Expands to user home directory
};
```
### Path Construction
```javascript
function resolveTargetPath(params) {
const baseDir = locationMap[params.location];
if (!baseDir) {
throw new Error(`Invalid location: ${params.location}. Must be "project" or "user".`);
}
// Expand ~ to user home if present
const expandedBase = baseDir.startsWith('~')
? path.join(os.homedir(), baseDir.slice(1))
: baseDir;
// Build full path
let targetPath;
if (params.group) {
// Grouped command: .claude/commands/{group}/{skillName}.md
targetPath = path.join(expandedBase, params.group, `${params.skillName}.md`);
} else {
// Top-level command: .claude/commands/{skillName}.md
targetPath = path.join(expandedBase, `${params.skillName}.md`);
}
return targetPath;
}
```
## Execution Steps
### Step 1: Get Base Directory
```javascript
const location = validatedParams.location;
const baseDir = locationMap[location];
if (!baseDir) {
throw new Error(`Invalid location: ${location}. Must be "project" or "user".`);
}
```
### Step 2: Expand User Path (if applicable)
```javascript
const os = require('os');
const path = require('path');
let expandedBase = baseDir;
if (baseDir.startsWith('~')) {
expandedBase = path.join(os.homedir(), baseDir.slice(1));
}
```
### Step 3: Construct Full Path
```javascript
let targetPath;
let targetDir;
if (validatedParams.group) {
// Command with group subdirectory
targetDir = path.join(expandedBase, validatedParams.group);
targetPath = path.join(targetDir, `${validatedParams.skillName}.md`);
} else {
// Top-level command
targetDir = expandedBase;
targetPath = path.join(targetDir, `${validatedParams.skillName}.md`);
}
```
### Step 4: Ensure Target Directory Exists
```javascript
// Check and create directory if needed
Bash(`mkdir -p "${targetDir}"`);
```
### Step 5: Check File Existence
```javascript
const fileExists = Bash(`test -f "${targetPath}" && echo "EXISTS" || echo "NOT_FOUND"`);
if (fileExists.includes('EXISTS')) {
console.warn(`Warning: Command file already exists at ${targetPath}. Will overwrite.`);
}
```
## Output
```javascript
{
status: 'resolved',
targetPath: targetPath, // Full path to command file
targetDir: targetDir, // Directory containing command
fileName: `${skillName}.md`,
fileExists: fileExists.includes('EXISTS'),
params: validatedParams // Pass through to next phase
}
```
## Path Examples
### Project Scope (No Group)
```
location: "project"
skillName: "deploy"
-> .claude/commands/deploy.md
```
### Project Scope (With Group)
```
location: "project"
skillName: "create"
group: "issue"
-> .claude/commands/issue/create.md
```
### User Scope (No Group)
```
location: "user"
skillName: "global-status"
-> ~/.claude/commands/global-status.md
```
### User Scope (With Group)
```
location: "user"
skillName: "sync"
group: "session"
-> ~/.claude/commands/session/sync.md
```
## Next Phase
Proceed to [Phase 3: Template Loading](03-template-loading.md) with `targetPath` and `params`.

View File

@@ -0,0 +1,123 @@
# Phase 3: Template Loading
Load the command template file for content generation.
## Objective
Load the command template from the skill's templates directory. The template provides:
- YAML frontmatter structure
- Placeholder variables for substitution
- Standard command file sections
## Input
From Phase 2:
```javascript
{
targetPath: string,
targetDir: string,
fileName: string,
fileExists: boolean,
params: {
skillName: string,
description: string,
location: string,
group: string | null,
argumentHint: string
}
}
```
## Template Location
```
.claude/skills/command-generator/templates/command-md.md
```
## Execution Steps
### Step 1: Locate Template File
```javascript
// Template is located in the skill's templates directory
const skillDir = '.claude/skills/command-generator';
const templatePath = `${skillDir}/templates/command-md.md`;
```
### Step 2: Read Template Content
```javascript
const templateContent = Read(templatePath);
if (!templateContent) {
throw new Error(`Command template not found at ${templatePath}`);
}
```
### Step 3: Validate Template Structure
```javascript
// Verify template contains expected placeholders
const requiredPlaceholders = ['{{name}}', '{{description}}'];
const optionalPlaceholders = ['{{group}}', '{{argumentHint}}'];
for (const placeholder of requiredPlaceholders) {
if (!templateContent.includes(placeholder)) {
throw new Error(`Template missing required placeholder: ${placeholder}`);
}
}
```
### Step 4: Store Template for Next Phase
```javascript
const template = {
content: templateContent,
requiredPlaceholders: requiredPlaceholders,
optionalPlaceholders: optionalPlaceholders
};
```
## Template Format Reference
The template should follow this structure:
```markdown
---
name: {{name}}
description: {{description}}
{{#if group}}group: {{group}}{{/if}}
{{#if argumentHint}}argument-hint: {{argumentHint}}{{/if}}
---
# {{name}} Command
[Template content with placeholders]
```
## Output
```javascript
{
status: 'loaded',
template: {
content: templateContent,
requiredPlaceholders: requiredPlaceholders,
optionalPlaceholders: optionalPlaceholders
},
targetPath: targetPath,
params: params
}
```
## Error Handling
| Error | Action |
|-------|--------|
| Template file not found | Throw error with path |
| Missing required placeholder | Throw error with missing placeholder name |
| Empty template | Throw error |
## Next Phase
Proceed to [Phase 4: Content Formatting](04-content-formatting.md) with `template`, `targetPath`, and `params`.

View File

@@ -0,0 +1,184 @@
# Phase 4: Content Formatting
Format template content by substituting placeholders with parameter values.
## Objective
Replace all placeholder variables in the template with validated parameter values:
- `{{name}}` -> skillName
- `{{description}}` -> description
- `{{group}}` -> group (if provided)
- `{{argumentHint}}` -> argumentHint (if provided)
## Input
From Phase 3:
```javascript
{
template: {
content: string,
requiredPlaceholders: string[],
optionalPlaceholders: string[]
},
targetPath: string,
params: {
skillName: string,
description: string,
location: string,
group: string | null,
argumentHint: string
}
}
```
## Placeholder Mapping
```javascript
const placeholderMap = {
'{{name}}': params.skillName,
'{{description}}': params.description,
'{{group}}': params.group || '',
'{{argumentHint}}': params.argumentHint || ''
};
```
## Execution Steps
### Step 1: Initialize Content
```javascript
let formattedContent = template.content;
```
### Step 2: Substitute Required Placeholders
```javascript
// These must always be replaced
formattedContent = formattedContent.replace(/\{\{name\}\}/g, params.skillName);
formattedContent = formattedContent.replace(/\{\{description\}\}/g, params.description);
```
### Step 3: Handle Optional Placeholders
```javascript
// Group placeholder
if (params.group) {
formattedContent = formattedContent.replace(/\{\{group\}\}/g, params.group);
} else {
// Remove group line if not provided
formattedContent = formattedContent.replace(/^group: \{\{group\}\}\n?/gm, '');
formattedContent = formattedContent.replace(/\{\{group\}\}/g, '');
}
// Argument hint placeholder
if (params.argumentHint) {
formattedContent = formattedContent.replace(/\{\{argumentHint\}\}/g, params.argumentHint);
} else {
// Remove argument-hint line if not provided
formattedContent = formattedContent.replace(/^argument-hint: \{\{argumentHint\}\}\n?/gm, '');
formattedContent = formattedContent.replace(/\{\{argumentHint\}\}/g, '');
}
```
### Step 4: Handle Conditional Sections
```javascript
// Remove empty frontmatter lines (caused by missing optional fields)
formattedContent = formattedContent.replace(/\n{3,}/g, '\n\n');
// Handle {{#if group}} style conditionals
if (formattedContent.includes('{{#if')) {
// Process group conditional
if (params.group) {
formattedContent = formattedContent.replace(/\{\{#if group\}\}([\s\S]*?)\{\{\/if\}\}/g, '$1');
} else {
formattedContent = formattedContent.replace(/\{\{#if group\}\}[\s\S]*?\{\{\/if\}\}/g, '');
}
// Process argumentHint conditional
if (params.argumentHint) {
formattedContent = formattedContent.replace(/\{\{#if argumentHint\}\}([\s\S]*?)\{\{\/if\}\}/g, '$1');
} else {
formattedContent = formattedContent.replace(/\{\{#if argumentHint\}\}[\s\S]*?\{\{\/if\}\}/g, '');
}
}
```
### Step 5: Validate Final Content
```javascript
// Ensure no unresolved placeholders remain
const unresolvedPlaceholders = formattedContent.match(/\{\{[^}]+\}\}/g);
if (unresolvedPlaceholders) {
console.warn(`Warning: Unresolved placeholders found: ${unresolvedPlaceholders.join(', ')}`);
}
// Ensure frontmatter is valid
const frontmatterMatch = formattedContent.match(/^---\n([\s\S]*?)\n---/);
if (!frontmatterMatch) {
throw new Error('Generated content has invalid frontmatter structure');
}
```
### Step 6: Generate Summary
```javascript
const summary = {
name: params.skillName,
description: params.description.substring(0, 50) + (params.description.length > 50 ? '...' : ''),
location: params.location,
group: params.group,
hasArgumentHint: !!params.argumentHint
};
```
## Output
```javascript
{
status: 'formatted',
content: formattedContent,
targetPath: targetPath,
summary: summary
}
```
## Content Example
### Input Template
```markdown
---
name: {{name}}
description: {{description}}
{{#if group}}group: {{group}}{{/if}}
{{#if argumentHint}}argument-hint: {{argumentHint}}{{/if}}
---
# {{name}} Command
```
### Output (with all fields)
```markdown
---
name: create
description: Create structured issue from GitHub URL or text description
group: issue
argument-hint: [-y|--yes] <github-url | text-description> [--priority 1-5]
---
# create Command
```
### Output (minimal fields)
```markdown
---
name: deploy
description: Deploy application to production environment
---
# deploy Command
```
## Next Phase
Proceed to [Phase 5: File Generation](05-file-generation.md) with `content` and `targetPath`.

View File

@@ -0,0 +1,185 @@
# Phase 5: File Generation
Write the formatted content to the target command file.
## Objective
Generate the final command file by:
1. Checking for existing file (warn if present)
2. Writing formatted content to target path
3. Confirming successful generation
## Input
From Phase 4:
```javascript
{
status: 'formatted',
content: string,
targetPath: string,
summary: {
name: string,
description: string,
location: string,
group: string | null,
hasArgumentHint: boolean
}
}
```
## Execution Steps
### Step 1: Pre-Write Check
```javascript
// Check if file already exists
const fileExists = Bash(`test -f "${targetPath}" && echo "EXISTS" || echo "NOT_FOUND"`);
if (fileExists.includes('EXISTS')) {
console.warn(`
WARNING: Command file already exists at: ${targetPath}
The file will be overwritten with new content.
`);
}
```
### Step 2: Ensure Directory Exists
```javascript
// Get directory from target path
const targetDir = path.dirname(targetPath);
// Create directory if it doesn't exist
Bash(`mkdir -p "${targetDir}"`);
```
### Step 3: Write File
```javascript
// Write the formatted content
Write(targetPath, content);
```
### Step 4: Verify Write
```javascript
// Confirm file was created
const verifyExists = Bash(`test -f "${targetPath}" && echo "SUCCESS" || echo "FAILED"`);
if (!verifyExists.includes('SUCCESS')) {
throw new Error(`Failed to create command file at ${targetPath}`);
}
// Verify content was written
const writtenContent = Read(targetPath);
if (!writtenContent || writtenContent.length === 0) {
throw new Error(`Command file created but appears to be empty`);
}
```
### Step 5: Generate Success Report
```javascript
const report = {
status: 'completed',
file: {
path: targetPath,
name: summary.name,
location: summary.location,
group: summary.group,
size: writtenContent.length,
created: new Date().toISOString()
},
command: {
name: summary.name,
description: summary.description,
hasArgumentHint: summary.hasArgumentHint
},
nextSteps: [
`Edit ${targetPath} to add implementation details`,
'Add usage examples and execution flow',
'Test the command with Claude Code'
]
};
```
## Output
### Success Output
```javascript
{
status: 'completed',
file: {
path: '.claude/commands/issue/create.md',
name: 'create',
location: 'project',
group: 'issue',
size: 1234,
created: '2026-02-27T12:00:00.000Z'
},
command: {
name: 'create',
description: 'Create structured issue from GitHub URL...',
hasArgumentHint: true
},
nextSteps: [
'Edit .claude/commands/issue/create.md to add implementation details',
'Add usage examples and execution flow',
'Test the command with Claude Code'
]
}
```
### Console Output
```
Command generated successfully!
File: .claude/commands/issue/create.md
Name: create
Description: Create structured issue from GitHub URL...
Location: project
Group: issue
Next Steps:
1. Edit .claude/commands/issue/create.md to add implementation details
2. Add usage examples and execution flow
3. Test the command with Claude Code
```
## Error Handling
| Error | Action |
|-------|--------|
| Directory creation failed | Throw error with directory path |
| File write failed | Throw error with target path |
| Empty file detected | Throw error and attempt cleanup |
| Permission denied | Throw error with permission hint |
## Cleanup on Failure
```javascript
// If any step fails, attempt to clean up partial artifacts
function cleanup(targetPath) {
try {
Bash(`rm -f "${targetPath}"`);
} catch (e) {
// Ignore cleanup errors
}
}
```
## Completion
The command file has been successfully generated. The skill execution is complete.
### Usage Example
```bash
# Use the generated command
/issue:create https://github.com/owner/repo/issues/123
# Or with the group prefix
/issue:create "Login fails with special chars"
```

View File

@@ -0,0 +1,160 @@
# Command Design Specification
Guidelines and best practices for designing Claude Code command files.
## Command File Structure
### YAML Frontmatter
Every command file must start with YAML frontmatter containing:
```yaml
---
name: command-name # Required: Command identifier (lowercase, hyphens)
description: Description # Required: Brief description of command purpose
argument-hint: "[args]" # Optional: Argument format hint
allowed-tools: Tool1, Tool2 # Optional: Restricted tool set
examples: # Optional: Usage examples
- /command:example1
- /command:example2 --flag
---
```
### Frontmatter Fields
| Field | Required | Description |
|-------|----------|-------------|
| `name` | Yes | Command identifier, lowercase with hyphens |
| `description` | Yes | Brief description, appears in command listings |
| `argument-hint` | No | Usage hint for arguments (shown in help) |
| `allowed-tools` | No | Restrict available tools for this command |
| `examples` | No | Array of usage examples |
## Naming Conventions
### Command Names
- Use lowercase letters only
- Separate words with hyphens (`create-issue`, not `createIssue`)
- Keep names short but descriptive (2-3 words max)
- Use verbs for actions (`deploy`, `create`, `analyze`)
### Group Names
- Groups organize related commands
- Use singular nouns (`issue`, `session`, `workflow`)
- Common groups: `issue`, `workflow`, `session`, `memory`, `cli`
### Path Examples
```
.claude/commands/deploy.md # Top-level command
.claude/commands/issue/create.md # Grouped command
.claude/commands/workflow/init.md # Grouped command
```
## Content Sections
### Required Sections
1. **Overview**: Brief description of command purpose
2. **Usage**: Command syntax and examples
3. **Execution Flow**: High-level process diagram
### Recommended Sections
4. **Implementation**: Code examples for each phase
5. **Error Handling**: Error cases and recovery
6. **Related Commands**: Links to related functionality
## Best Practices
### 1. Clear Purpose
Each command should do one thing well:
```
Good: /issue:create - Create a new issue
Bad: /issue:manage - Create, update, delete issues (too broad)
```
### 2. Consistent Structure
Follow the same pattern across all commands in a group:
```markdown
# All issue commands should have:
- Overview
- Usage with examples
- Phase-based implementation
- Error handling table
```
### 3. Progressive Detail
Start simple, add detail in phases:
```
Phase 1: Quick overview
Phase 2: Implementation details
Phase 3: Edge cases and errors
```
### 4. Reusable Patterns
Use consistent patterns for common operations:
```javascript
// Input parsing pattern
const args = parseArguments($ARGUMENTS);
const flags = parseFlags($ARGUMENTS);
// Validation pattern
if (!args.required) {
throw new Error('Required argument missing');
}
```
## Scope Guidelines
### Project Commands (`.claude/commands/`)
- Project-specific workflows
- Team conventions
- Integration with project tools
### User Commands (`~/.claude/commands/`)
- Personal productivity tools
- Cross-project utilities
- Global configuration
## Error Messages
### Good Error Messages
```
Error: GitHub issue URL required
Usage: /issue:create <github-url>
Example: /issue:create https://github.com/owner/repo/issues/123
```
### Bad Error Messages
```
Error: Invalid input
```
## Testing Commands
After creating a command, test:
1. **Basic invocation**: Does it run without arguments?
2. **Argument parsing**: Does it handle valid arguments?
3. **Error cases**: Does it show helpful errors for invalid input?
4. **Help text**: Is the usage clear?
## Related Documentation
- [SKILL-DESIGN-SPEC.md](../_shared/SKILL-DESIGN-SPEC.md) - Full skill design specification
- [../skill-generator/SKILL.md](../skill-generator/SKILL.md) - Meta-skill for creating skills

View File

@@ -0,0 +1,75 @@
---
name: {{name}}
description: {{description}}
{{#if argumentHint}}argument-hint: {{argumentHint}}
{{/if}}---
# {{name}} Command
## Overview
[Describe the command purpose and what it does]
## Usage
```bash
/{{#if group}}{{group}}:{{/if}}{{name}} [arguments]
```
**Examples**:
```bash
# Example 1: Basic usage
/{{#if group}}{{group}}:{{/if}}{{name}}
# Example 2: With arguments
/{{#if group}}{{group}}:{{/if}}{{name}} --option value
```
## Execution Flow
```
Phase 1: Input Parsing
- Parse arguments and flags
- Validate input parameters
Phase 2: Core Processing
- Execute main logic
- Handle edge cases
Phase 3: Output Generation
- Format results
- Display to user
```
## Implementation
### Phase 1: Input Parsing
```javascript
// Parse command arguments
const args = parseArguments($ARGUMENTS);
```
### Phase 2: Core Processing
```javascript
// TODO: Implement core logic
```
### Phase 3: Output Generation
```javascript
// TODO: Format and display output
```
## Error Handling
| Error | Action |
|-------|--------|
| Invalid input | Show usage and error message |
| Processing failure | Log error and suggest recovery |
## Related Commands
- [Related command 1]
- [Related command 2]

View File

@@ -736,6 +736,8 @@ TodoWrite({
## Post-Completion Expansion
**Auto-sync**: 执行 `/workflow:session:sync -y "{summary}"` 更新 specs/*.md + project-tech。
完成后询问用户是否扩展为issue(test/enhance/refactor/doc),选中项调用 `/issue:new "{summary} - {dimension}"`
## Best Practices

View File

@@ -403,7 +403,7 @@ Task(
3. Validate file access: bash(ls -la ${targetFiles.join(' ')})
4. Execute: cat ~/.ccw/workflows/cli-templates/schemas/review-dimension-results-schema.json (get output schema reference)
5. Read: .workflow/project-tech.json (technology stack and architecture context)
6. Read: .workflow/project-guidelines.json (user-defined constraints and conventions to validate against)
6. Read: .workflow/specs/*.md (user-defined constraints and conventions to validate against)
## Review Context
- Review Type: module (independent)
@@ -507,7 +507,7 @@ Task(
4. Read test files: bash(find ${projectDir}/tests -name "*${basename(file, '.ts')}*" -type f)
5. Execute: cat ~/.ccw/workflows/cli-templates/schemas/review-deep-dive-results-schema.json (get output schema reference)
6. Read: .workflow/project-tech.json (technology stack and architecture context)
7. Read: .workflow/project-guidelines.json (user-defined constraints for remediation compliance)
7. Read: .workflow/specs/*.md (user-defined constraints for remediation compliance)
## CLI Configuration
- Tool Priority: gemini → qwen → codex

View File

@@ -414,7 +414,7 @@ Task(
4. Read review state: ${reviewStateJsonPath}
5. Execute: cat ~/.ccw/workflows/cli-templates/schemas/review-dimension-results-schema.json (get output schema reference)
6. Read: .workflow/project-tech.json (technology stack and architecture context)
7. Read: .workflow/project-guidelines.json (user-defined constraints and conventions to validate against)
7. Read: .workflow/specs/*.md (user-defined constraints and conventions to validate against)
## Session Context
- Session ID: ${sessionId}
@@ -518,7 +518,7 @@ Task(
4. Read test files: bash(find ${workflowDir}/tests -name "*${basename(file, '.ts')}*" -type f)
5. Execute: cat ~/.ccw/workflows/cli-templates/schemas/review-deep-dive-results-schema.json (get output schema reference)
6. Read: .workflow/project-tech.json (technology stack and architecture context)
7. Read: .workflow/project-guidelines.json (user-defined constraints for remediation compliance)
7. Read: .workflow/specs/*.md (user-defined constraints for remediation compliance)
## CLI Configuration
- Tool Priority: gemini → qwen → codex

View File

@@ -67,9 +67,9 @@ spec-generator/
## Handoff
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:plan` - Full planning
- `workflow-plan` - Full planning
- `issue:new` - Create issues per Epic
## Design Principles

View File

@@ -11,21 +11,23 @@ Structured specification document generator producing a complete specification p
## Architecture Overview
```
Phase 0: Specification Study (Read specs/ + templates/ - mandatory prerequisite)
|
Phase 1: Discovery -> spec-config.json + discovery-context.json
|
Phase 2: Product Brief -> product-brief.md (multi-CLI parallel analysis)
|
Phase 3: Requirements (PRD) -> requirements/ (_index.md + REQ-*.md + NFR-*.md)
|
Phase 4: Architecture -> architecture/ (_index.md + ADR-*.md, multi-CLI review)
|
Phase 5: Epics & Stories -> epics/ (_index.md + EPIC-*.md)
|
Phase 6: Readiness Check -> readiness-report.md + spec-summary.md
|
Handoff to execution workflows
Phase 0: Specification Study (Read specs/ + templates/ - mandatory prerequisite)
|
Phase 1: Discovery -> spec-config.json + discovery-context.json
|
Phase 1.5: Req Expansion -> refined-requirements.json (interactive discussion + CLI gap analysis)
| (-y auto mode: auto-expansion, skip interaction)
Phase 2: Product Brief -> product-brief.md (multi-CLI parallel analysis)
|
Phase 3: Requirements (PRD) -> requirements/ (_index.md + REQ-*.md + NFR-*.md)
|
Phase 4: Architecture -> architecture/ (_index.md + ADR-*.md, multi-CLI review)
|
Phase 5: Epics & Stories -> epics/ (_index.md + EPIC-*.md)
|
Phase 6: Readiness Check -> readiness-report.md + spec-summary.md
|
Handoff to execution workflows
```
## Key Design Principles
@@ -79,6 +81,16 @@ Phase 1: Discovery & Seed Analysis
|- User confirmation (interactive, -y skips)
|- Output: spec-config.json, discovery-context.json (optional)
Phase 1.5: Requirement Expansion & Clarification
|- Ref: phases/01-5-requirement-clarification.md
|- CLI gap analysis: completeness scoring, missing dimensions detection
|- Multi-round interactive discussion (max 5 rounds)
| |- Round 1: present gap analysis + expansion suggestions
| |- Round N: follow-up refinement based on user responses
|- User final confirmation of requirements
|- Auto mode (-y): CLI auto-expansion without interaction
|- Output: refined-requirements.json
Phase 2: Product Brief
|- Ref: phases/02-product-brief.md
|- 3 parallel CLI analyses: Product (Gemini) + Technical (Codex) + User (Claude)
@@ -148,6 +160,7 @@ Bash(`mkdir -p "${workDir}"`);
.workflow/.spec/SPEC-{slug}-{YYYY-MM-DD}/
├── spec-config.json # Session configuration + phase state
├── discovery-context.json # Codebase exploration results (optional)
├── refined-requirements.json # Phase 1.5: Confirmed requirements after discussion
├── product-brief.md # Phase 2: Product brief
├── requirements/ # Phase 3: Detailed PRD (directory)
│ ├── _index.md # Summary, MoSCoW table, traceability, links
@@ -184,8 +197,10 @@ Bash(`mkdir -p "${workDir}"`);
"dimensions": []
},
"has_codebase": false,
"refined_requirements_file": "refined-requirements.json",
"phasesCompleted": [
{ "phase": 1, "name": "discovery", "output_file": "spec-config.json", "completed_at": "ISO8601" },
{ "phase": 1.5, "name": "requirement-clarification", "output_file": "refined-requirements.json", "discussion_rounds": 2, "completed_at": "ISO8601" },
{ "phase": 3, "name": "requirements", "output_dir": "requirements/", "output_index": "requirements/_index.md", "file_count": 8, "completed_at": "ISO8601" }
]
}
@@ -211,6 +226,12 @@ Bash(`mkdir -p "${workDir}"`);
| [phases/01-discovery.md](phases/01-discovery.md) | Seed analysis and session setup | Phase start |
| [specs/document-standards.md](specs/document-standards.md) | Frontmatter format for spec-config.json | Config generation |
### Phase 1.5: Requirement Expansion & Clarification
| Document | Purpose | When to Use |
|----------|---------|-------------|
| [phases/01-5-requirement-clarification.md](phases/01-5-requirement-clarification.md) | Interactive requirement discussion workflow | Phase start |
| [specs/quality-gates.md](specs/quality-gates.md) | Quality criteria for refined requirements | Validation |
### Phase 2: Product Brief
| Document | Purpose | When to Use |
|----------|---------|-------------|
@@ -254,6 +275,9 @@ Bash(`mkdir -p "${workDir}"`);
|-------|-------|-----------|--------|
| Phase 1 | Empty input | Yes | Error and exit |
| Phase 1 | CLI seed analysis fails | No | Use basic parsing fallback |
| Phase 1.5 | Gap analysis CLI fails | No | Skip to user questions with basic prompts |
| Phase 1.5 | User skips discussion | No | Proceed with seed_analysis as-is |
| Phase 1.5 | Max rounds reached (5) | No | Force confirmation with current state |
| Phase 2 | Single CLI perspective fails | No | Continue with available perspectives |
| Phase 2 | All CLI calls fail | No | Generate basic brief from seed analysis |
| Phase 3 | Gemini CLI fails | No | Use codex fallback |

View File

@@ -0,0 +1,404 @@
# Phase 1.5: Requirement Expansion & Clarification
在进入正式文档生成前,通过多轮交互讨论对原始需求进行深度挖掘、扩展和确认。
## Objective
- 识别原始需求中的模糊点、遗漏和潜在风险
- 通过 CLI 辅助分析需求完整性,生成深度探测问题
- 支持多轮交互讨论,逐步细化需求
- 生成经用户确认的 `refined-requirements.json` 作为后续阶段的高质量输入
## Input
- Dependency: `{workDir}/spec-config.json` (Phase 1 output)
- Optional: `{workDir}/discovery-context.json` (codebase context)
## Execution Steps
### Step 1: Load Phase 1 Context
```javascript
const specConfig = JSON.parse(Read(`${workDir}/spec-config.json`));
const { seed_analysis, seed_input, focus_areas, has_codebase, depth } = specConfig;
let discoveryContext = null;
if (has_codebase) {
try {
discoveryContext = JSON.parse(Read(`${workDir}/discovery-context.json`));
} catch (e) { /* proceed without */ }
}
```
### Step 2: CLI Gap Analysis & Question Generation
调用 Gemini CLI 分析原始需求的完整性,识别模糊点并生成探测问题。
```javascript
Bash({
command: `ccw cli -p "PURPOSE: 深度分析用户的初始需求,识别模糊点、遗漏和需要澄清的领域。
Success: 生成 3-5 个高质量的探测问题,覆盖功能范围、边界条件、非功能性需求、用户场景等维度。
ORIGINAL SEED INPUT:
${seed_input}
SEED ANALYSIS:
${JSON.stringify(seed_analysis, null, 2)}
FOCUS AREAS: ${focus_areas.join(', ')}
${discoveryContext ? `
CODEBASE CONTEXT:
- Existing patterns: ${discoveryContext.existing_patterns?.slice(0,5).join(', ') || 'none'}
- Tech stack: ${JSON.stringify(discoveryContext.tech_stack || {})}
` : ''}
TASK:
1. 评估当前需求描述的完整性1-10 分,列出缺失维度)
2. 识别 3-5 个关键模糊区域,每个区域包含:
- 模糊点描述(为什么不清楚)
- 1-2 个开放式探测问题
- 1-2 个扩展建议(基于领域最佳实践)
3. 检查以下维度是否有遗漏:
- 功能范围边界(什么在范围内/外?)
- 核心用户场景和流程
- 非功能性需求(性能、安全、可用性、可扩展性)
- 集成点和外部依赖
- 数据模型和存储需求
- 错误处理和异常场景
4. 基于领域经验提供需求扩展建议
MODE: analysis
EXPECTED: JSON output:
{
\"completeness_score\": 7,
\"missing_dimensions\": [\"Performance requirements\", \"Error handling\"],
\"clarification_areas\": [
{
\"area\": \"Scope boundary\",
\"rationale\": \"Input does not clarify...\",
\"questions\": [\"Question 1?\", \"Question 2?\"],
\"suggestions\": [\"Suggestion 1\", \"Suggestion 2\"]
}
],
\"expansion_recommendations\": [
{
\"category\": \"Non-functional\",
\"recommendation\": \"Consider adding...\",
\"priority\": \"high|medium|low\"
}
]
}
CONSTRAINTS: 问题必须是开放式的,建议必须具体可执行,使用用户输入的语言
" --tool gemini --mode analysis`,
run_in_background: true
});
// Wait for CLI result before continuing
```
解析 CLI 输出为结构化数据:
```javascript
const gapAnalysis = {
completeness_score: 0,
missing_dimensions: [],
clarification_areas: [],
expansion_recommendations: []
};
// Parse from CLI output
```
### Step 3: Interactive Discussion Loop
核心多轮交互循环。每轮:展示分析结果 → 用户回应 → 更新需求状态 → 判断是否继续。
```javascript
// Initialize requirement state
let requirementState = {
problem_statement: seed_analysis.problem_statement,
target_users: seed_analysis.target_users,
domain: seed_analysis.domain,
constraints: seed_analysis.constraints,
confirmed_features: [],
non_functional_requirements: [],
boundary_conditions: [],
integration_points: [],
key_assumptions: [],
discussion_rounds: 0
};
let discussionLog = [];
let userSatisfied = false;
// === Round 1: Present gap analysis results ===
// Display completeness_score, clarification_areas, expansion_recommendations
// Then ask user to respond
while (!userSatisfied && requirementState.discussion_rounds < 5) {
requirementState.discussion_rounds++;
if (requirementState.discussion_rounds === 1) {
// --- First round: present initial gap analysis ---
// Format questions and suggestions from gapAnalysis for display
// Present as a structured summary to the user
AskUserQuestion({
questions: [
{
question: buildDiscussionPrompt(gapAnalysis, requirementState),
header: "Req Expand",
multiSelect: false,
options: [
{ label: "I'll answer", description: "I have answers/feedback to provide (type in 'Other')" },
{ label: "Accept all suggestions", description: "Accept all expansion recommendations as-is" },
{ label: "Skip to generation", description: "Requirements are clear enough, proceed directly" }
]
}
]
});
} else {
// --- Subsequent rounds: refine based on user feedback ---
// Call CLI with accumulated context for follow-up analysis
Bash({
command: `ccw cli -p "PURPOSE: 基于用户最新回应,更新需求理解,识别剩余模糊点。
CURRENT REQUIREMENT STATE:
${JSON.stringify(requirementState, null, 2)}
DISCUSSION HISTORY:
${JSON.stringify(discussionLog, null, 2)}
USER'S LATEST RESPONSE:
${lastUserResponse}
TASK:
1. 将用户回应整合到需求状态中
2. 识别 1-3 个仍需澄清或可扩展的领域
3. 生成后续问题(如有必要)
4. 如果需求已充分,输出最终需求摘要
MODE: analysis
EXPECTED: JSON output:
{
\"updated_fields\": { /* fields to merge into requirementState */ },
\"status\": \"need_more_discussion\" | \"ready_for_confirmation\",
\"follow_up\": {
\"remaining_areas\": [{\"area\": \"...\", \"questions\": [\"...\"]}],
\"summary\": \"...\"
}
}
CONSTRAINTS: 避免重复已回答的问题,聚焦未覆盖的领域
" --tool gemini --mode analysis`,
run_in_background: true
});
// Wait for CLI result, parse and continue
// If status === "ready_for_confirmation", break to confirmation step
// If status === "need_more_discussion", present follow-up questions
AskUserQuestion({
questions: [
{
question: buildFollowUpPrompt(followUpAnalysis, requirementState),
header: "Follow-up",
multiSelect: false,
options: [
{ label: "I'll answer", description: "I have more feedback (type in 'Other')" },
{ label: "Looks good", description: "Requirements are sufficiently clear now" },
{ label: "Accept suggestions", description: "Accept remaining suggestions" }
]
}
]
});
}
// Process user response
// - "Skip to generation" / "Looks good" → userSatisfied = true
// - "Accept all suggestions" → merge suggestions into requirementState, userSatisfied = true
// - "I'll answer" (with Other text) → record in discussionLog, continue loop
// - User selects Other with custom text → parse and record
discussionLog.push({
round: requirementState.discussion_rounds,
agent_prompt: currentPrompt,
user_response: userResponse,
timestamp: new Date().toISOString()
});
}
```
#### Helper: Build Discussion Prompt
```javascript
function buildDiscussionPrompt(gapAnalysis, state) {
let prompt = `## Requirement Analysis Results\n\n`;
prompt += `**Completeness Score**: ${gapAnalysis.completeness_score}/10\n`;
if (gapAnalysis.missing_dimensions.length > 0) {
prompt += `**Missing Dimensions**: ${gapAnalysis.missing_dimensions.join(', ')}\n\n`;
}
prompt += `### Key Questions\n\n`;
gapAnalysis.clarification_areas.forEach((area, i) => {
prompt += `**${i+1}. ${area.area}**\n`;
prompt += ` ${area.rationale}\n`;
area.questions.forEach(q => { prompt += ` - ${q}\n`; });
if (area.suggestions.length > 0) {
prompt += ` Suggestions: ${area.suggestions.join('; ')}\n`;
}
prompt += `\n`;
});
if (gapAnalysis.expansion_recommendations.length > 0) {
prompt += `### Expansion Recommendations\n\n`;
gapAnalysis.expansion_recommendations.forEach(rec => {
prompt += `- [${rec.priority}] **${rec.category}**: ${rec.recommendation}\n`;
});
}
prompt += `\nPlease answer the questions above, or choose an option below.`;
return prompt;
}
```
### Step 4: Auto Mode Handling
```javascript
if (autoMode) {
// Skip interactive discussion
// CLI generates default requirement expansion based on seed_analysis
Bash({
command: `ccw cli -p "PURPOSE: 基于种子分析自动生成需求扩展,无需用户交互。
SEED ANALYSIS:
${JSON.stringify(seed_analysis, null, 2)}
SEED INPUT: ${seed_input}
DEPTH: ${depth}
${discoveryContext ? `CODEBASE: ${JSON.stringify(discoveryContext.tech_stack || {})}` : ''}
TASK:
1. 基于领域最佳实践,自动扩展功能需求清单
2. 推断合理的非功能性需求
3. 识别明显的边界条件
4. 列出关键假设
MODE: analysis
EXPECTED: JSON output matching refined-requirements.json schema
CONSTRAINTS: 保守推断,只添加高置信度的扩展
" --tool gemini --mode analysis`,
run_in_background: true
});
// Parse output directly into refined-requirements.json
}
```
### Step 5: Generate Requirement Confirmation Summary
在写入文件前,向用户展示最终的需求确认摘要(非 auto mode
```javascript
if (!autoMode) {
// Build confirmation summary from requirementState
const summary = buildConfirmationSummary(requirementState);
AskUserQuestion({
questions: [
{
question: `## Requirement Confirmation\n\n${summary}\n\nConfirm and proceed to specification generation?`,
header: "Confirm",
multiSelect: false,
options: [
{ label: "Confirm & proceed", description: "Requirements confirmed, start spec generation" },
{ label: "Need adjustments", description: "Go back and refine further" }
]
}
]
});
// If "Need adjustments" → loop back to Step 3
// If "Confirm & proceed" → continue to Step 6
}
```
### Step 6: Write refined-requirements.json
```javascript
const refinedRequirements = {
session_id: specConfig.session_id,
phase: "1.5",
generated_at: new Date().toISOString(),
source: autoMode ? "auto-expansion" : "interactive-discussion",
discussion_rounds: requirementState.discussion_rounds,
// Core requirement content
clarified_problem_statement: requirementState.problem_statement,
confirmed_target_users: requirementState.target_users.map(u =>
typeof u === 'string' ? { name: u, needs: [], pain_points: [] } : u
),
confirmed_domain: requirementState.domain,
confirmed_features: requirementState.confirmed_features.map(f => ({
name: f.name,
description: f.description,
acceptance_criteria: f.acceptance_criteria || [],
edge_cases: f.edge_cases || [],
priority: f.priority || "unset"
})),
non_functional_requirements: requirementState.non_functional_requirements.map(nfr => ({
type: nfr.type, // Performance, Security, Usability, Scalability, etc.
details: nfr.details,
measurable_criteria: nfr.measurable_criteria || ""
})),
boundary_conditions: {
in_scope: requirementState.boundary_conditions.filter(b => b.scope === 'in'),
out_of_scope: requirementState.boundary_conditions.filter(b => b.scope === 'out'),
constraints: requirementState.constraints
},
integration_points: requirementState.integration_points,
key_assumptions: requirementState.key_assumptions,
// Traceability
discussion_log: autoMode ? [] : discussionLog
};
Write(`${workDir}/refined-requirements.json`, JSON.stringify(refinedRequirements, null, 2));
```
### Step 7: Update spec-config.json
```javascript
specConfig.refined_requirements_file = "refined-requirements.json";
specConfig.phasesCompleted.push({
phase: 1.5,
name: "requirement-clarification",
output_file: "refined-requirements.json",
discussion_rounds: requirementState.discussion_rounds,
completed_at: new Date().toISOString()
});
Write(`${workDir}/spec-config.json`, JSON.stringify(specConfig, null, 2));
```
## Output
- **File**: `refined-requirements.json`
- **Format**: JSON
- **Updated**: `spec-config.json` (added `refined_requirements_file` field and phase 1.5 to `phasesCompleted`)
## Quality Checklist
- [ ] Problem statement refined (>= 30 characters, more specific than seed)
- [ ] At least 2 confirmed features with descriptions
- [ ] At least 1 non-functional requirement identified
- [ ] Boundary conditions defined (in-scope + out-of-scope)
- [ ] Key assumptions listed (>= 1)
- [ ] Discussion rounds recorded (>= 1 in interactive mode)
- [ ] User explicitly confirmed requirements (non-auto mode)
- [ ] `refined-requirements.json` written with valid JSON
- [ ] `spec-config.json` updated with phase 1.5 completion
## Next Phase
Proceed to [Phase 2: Product Brief](02-product-brief.md). Phase 2 should load `refined-requirements.json` as primary input instead of relying solely on `spec-config.json.seed_analysis`.

View File

@@ -13,6 +13,7 @@ Generate a product brief through multi-perspective CLI analysis, establishing "w
## Input
- Dependency: `{workDir}/spec-config.json`
- Primary: `{workDir}/refined-requirements.json` (Phase 1.5 output, preferred over raw seed_analysis)
- Optional: `{workDir}/discovery-context.json`
- Config: `{workDir}/spec-config.json`
- Template: `templates/product-brief.md`
@@ -25,6 +26,14 @@ Generate a product brief through multi-perspective CLI analysis, establishing "w
const specConfig = JSON.parse(Read(`${workDir}/spec-config.json`));
const { seed_analysis, seed_input, has_codebase, depth, focus_areas } = specConfig;
// Load refined requirements (Phase 1.5 output) - preferred over raw seed_analysis
let refinedReqs = null;
try {
refinedReqs = JSON.parse(Read(`${workDir}/refined-requirements.json`));
} catch (e) {
// No refined requirements, fall back to seed_analysis
}
let discoveryContext = null;
if (has_codebase) {
try {
@@ -35,13 +44,25 @@ if (has_codebase) {
}
// Build shared context string for CLI prompts
// Prefer refined requirements over raw seed_analysis
const problem = refinedReqs?.clarified_problem_statement || seed_analysis.problem_statement;
const users = refinedReqs?.confirmed_target_users?.map(u => u.name || u).join(', ')
|| seed_analysis.target_users.join(', ');
const domain = refinedReqs?.confirmed_domain || seed_analysis.domain;
const constraints = refinedReqs?.boundary_conditions?.constraints?.join(', ')
|| seed_analysis.constraints.join(', ');
const features = refinedReqs?.confirmed_features?.map(f => f.name).join(', ') || '';
const nfrs = refinedReqs?.non_functional_requirements?.map(n => `${n.type}: ${n.details}`).join('; ') || '';
const sharedContext = `
SEED: ${seed_input}
PROBLEM: ${seed_analysis.problem_statement}
TARGET USERS: ${seed_analysis.target_users.join(', ')}
DOMAIN: ${seed_analysis.domain}
CONSTRAINTS: ${seed_analysis.constraints.join(', ')}
PROBLEM: ${problem}
TARGET USERS: ${users}
DOMAIN: ${domain}
CONSTRAINTS: ${constraints}
FOCUS AREAS: ${focus_areas.join(', ')}
${features ? `CONFIRMED FEATURES: ${features}` : ''}
${nfrs ? `NON-FUNCTIONAL REQUIREMENTS: ${nfrs}` : ''}
${discoveryContext ? `
CODEBASE CONTEXT:
- Existing patterns: ${discoveryContext.existing_patterns?.slice(0,5).join(', ') || 'none'}

View File

@@ -210,7 +210,7 @@ AskUserQuestion({
options: [
{
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",
@@ -218,7 +218,7 @@ AskUserQuestion({
},
{
label: "Full planning",
description: "Detailed planning with /workflow:plan for the full scope"
description: "Detailed planning with /workflow-plan for the full scope"
},
{
label: "Create Issues",
@@ -242,7 +242,7 @@ if (selection === "Execute via lite-plan") {
const epicContent = Read(firstMvpFile);
const title = extractTitle(epicContent); // First # heading
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") {
@@ -368,7 +368,7 @@ ${extractSection(epicContent, "Architecture")}
// → context-package.json.brainstorm_artifacts populated
// → action-planning-agent loads guidance_specification (P1) + feature_index (P2)
if (selection === "Full planning") {
Skill(skill="workflow:plan", args=`"${structuredDesc}"`)
Skill(skill="workflow-plan", args=`"${structuredDesc}"`)
} else {
Skill(skill="workflow:req-plan-with-file", args=`"${extractGoal(specSummary)}"`)
}

View File

@@ -81,6 +81,7 @@ Examples:
|------|-------|-------------|
| `spec-config.json` | 1 | Session configuration and state |
| `discovery-context.json` | 1 | Codebase exploration results (optional) |
| `refined-requirements.json` | 1.5 | Confirmed requirements after discussion |
| `product-brief.md` | 2 | Product brief document |
| `requirements.md` | 3 | PRD document |
| `architecture.md` | 4 | Architecture decisions document |
@@ -168,6 +169,7 @@ Derived from [REQ-001](requirements.md#req-001).
"dimensions": ["string array - 3-5 exploration dimensions"]
},
"has_codebase": "boolean",
"refined_requirements_file": "string (optional) - path to refined-requirements.json",
"phasesCompleted": [
{
"phase": "number (1-6)",
@@ -181,6 +183,60 @@ Derived from [REQ-001](requirements.md#req-001).
---
## refined-requirements.json Schema
```json
{
"session_id": "string (required) - matches spec-config.json",
"phase": "1.5",
"generated_at": "ISO8601 (required)",
"source": "interactive-discussion|auto-expansion (required)",
"discussion_rounds": "number (required) - 0 for auto mode",
"clarified_problem_statement": "string (required) - refined problem statement",
"confirmed_target_users": [
{
"name": "string",
"needs": ["string array"],
"pain_points": ["string array"]
}
],
"confirmed_domain": "string",
"confirmed_features": [
{
"name": "string",
"description": "string",
"acceptance_criteria": ["string array"],
"edge_cases": ["string array"],
"priority": "must|should|could|unset"
}
],
"non_functional_requirements": [
{
"type": "Performance|Security|Usability|Scalability|Reliability|...",
"details": "string",
"measurable_criteria": "string (optional)"
}
],
"boundary_conditions": {
"in_scope": ["string array"],
"out_of_scope": ["string array"],
"constraints": ["string array"]
},
"integration_points": ["string array"],
"key_assumptions": ["string array"],
"discussion_log": [
{
"round": "number",
"agent_prompt": "string",
"user_response": "string",
"timestamp": "ISO8601"
}
]
}
```
---
## Validation Checklist
- [ ] Every document starts with valid YAML frontmatter

View File

@@ -88,6 +88,18 @@ Content provides sufficient detail for execution teams.
| Dimensions generated | 3-5 exploration dimensions | Warning |
| Constraints listed | >= 0 (can be empty with justification) | Info |
### Phase 1.5: Requirement Expansion & Clarification
| Check | Criteria | Severity |
|-------|----------|----------|
| Problem statement refined | More specific than seed, >= 30 characters | Error |
| Confirmed features | >= 2 features with descriptions | Error |
| Non-functional requirements | >= 1 identified (performance, security, etc.) | Warning |
| Boundary conditions | In-scope and out-of-scope defined | Warning |
| Key assumptions | >= 1 assumption listed | Warning |
| User confirmation | Explicit user confirmation recorded (non-auto mode) | Info |
| Discussion rounds | >= 1 round of interaction (non-auto mode) | Info |
### Phase 2: Product Brief
| Check | Criteria | Severity |

View File

@@ -0,0 +1,474 @@
---
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: Task, 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
Subagents (callable by workers, not team members):
[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 |
### Subagent Registry
| Subagent | Spec | Callable By | Purpose |
|----------|------|-------------|---------|
| explore | [subagents/explore-subagent.md](subagents/explore-subagent.md) | analyzer, refactorer | Shared codebase exploration for architecture-critical structures and dependency graphs |
| discuss | [subagents/discuss-subagent.md](subagents/discuss-subagent.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:
```
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: .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(arch-opt) -> 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
| +-- shared-memory.json # Cross-role structured data
+-- 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 |
| Subagent spec not found | Error with expected path (subagents/<name>-subagent.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 |
| Shared-memory 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
subagents: [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 |
| shared-memory.json | <session>/wisdom/shared-memory.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` subagent 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/shared-memory.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]
subagents: [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 |
| shared-memory.json | <session>/wisdom/shared-memory.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 shared-memory.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` subagent (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/shared-memory.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]
subagents: [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) |
| shared-memory.json | <session>/wisdom/shared-memory.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` subagent to load implementation context for target files
6. For inner loop (single mode only): load context_accumulator from prior REFACTOR/FIX tasks
**Shared-memory 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]
subagents: [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 |
| shared-memory.json | <session>/wisdom/shared-memory.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 shared-memory.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` subagent (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/shared-memory.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 |
| shared-memory.json | <session>/wisdom/shared-memory.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 shared-memory.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 shared-memory:
- 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/shared-memory.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,376 @@
# 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>",
owner: "<role>",
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/shared-memory.json
EXPECTED: <deliverable path> + <quality criteria>
CONSTRAINTS: <scope limits, focus areas>
---
InnerLoop: <true|false>
BranchId: <B01|A|none>",
blockedBy: [<dependency-list>],
status: "pending"
})
```
### 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/shared-memory.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",
status: "pending"
})
```
**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/shared-memory.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",
blockedBy: ["ANALYZE-001"],
status: "pending"
})
```
**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/shared-memory.json
EXPECTED: Modified source files + validation passing | Refactorings applied without regressions
CONSTRAINTS: Preserve existing behavior | Update all references | Follow code conventions
---
InnerLoop: true",
blockedBy: ["DESIGN-001"],
status: "pending"
})
```
**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/shared-memory.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",
blockedBy: ["REFACTOR-001"],
status: "pending"
})
```
**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/shared-memory.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",
blockedBy: ["REFACTOR-001"],
status: "pending"
})
```
---
### 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", ... }) // blockedBy: []
TaskCreate({ subject: "DESIGN-<P>01", ... }) // blockedBy: ["ANALYZE-<P>01"]
TaskCreate({ subject: "REFACTOR-<P>01", ... }) // blockedBy: ["DESIGN-<P>01"]
TaskCreate({ subject: "VALIDATE-<P>01", ... }) // blockedBy: ["REFACTOR-<P>01"]
TaskCreate({ subject: "REVIEW-<P>01", ... }) // blockedBy: ["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/`
- Shared-memory 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/shared-memory.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",
status: "pending"
})
```
---
### 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 `shared-memory.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/shared-memory.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}",
blockedBy: ["DESIGN-001"],
status: "pending"
})
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/shared-memory.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}",
blockedBy: ["REFACTOR-B{NN}"],
status: "pending"
})
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} shared-memory namespace
- 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/shared-memory.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}",
blockedBy: ["REFACTOR-B{NN}"],
status: "pending"
})
```
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,332 @@
# 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:
```
Task({
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 shared-memory (validator namespace)
2. Read review verdict from shared-memory (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/shared-memory.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}",
blockedBy: [],
status: "pending"
})
```
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...
blockedBy: [],
status: "pending"
})
```
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,291 @@
# 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-*/team-session.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
3. Initialize shared-memory.json:
```
Write("<session>/wisdom/shared-memory.json", { "session_id": "<session-id>", "requirement": "<requirement>", "parallel_mode": "<mode>" })
```
4. 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:
```
Task({
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("arch-opt") -> 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": [],
"subagents": ["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"],
"subagents": ["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": [],
"subagents": ["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": [],
"subagents": [],
"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"],
"subagents": ["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"
},
"subagents": [
{
"name": "explore",
"agent_type": "cli-explore-agent",
"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",
"agent_type": "cli-discuss-agent",
"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

@@ -0,0 +1,89 @@
# Discuss Subagent
Multi-perspective discussion for evaluating refactoring strategies and reviewing code change quality. Used by designer (DISCUSS-REFACTOR) and reviewer (DISCUSS-REVIEW) when complex trade-offs require multi-angle analysis.
## Design Rationale
Complex refactoring decisions (e.g., choosing between dependency inversion vs mediator pattern to break a cycle) and nuanced code review findings (e.g., evaluating whether a temporary coupling increase is acceptable) benefit from structured multi-perspective analysis. This subagent provides that analysis inline without spawning additional team members.
## Invocation
Called by designer, reviewer after their primary analysis when complexity warrants multi-perspective evaluation:
```
Task({
subagent_type: "cli-discuss-agent",
run_in_background: false,
description: "Discuss <round-id>: <topic> for architecture optimization",
prompt: `Conduct a multi-perspective discussion on the following topic.
Round: <round-id>
Topic: <discussion-topic>
Session: <session-folder>
Context:
<relevant-context-from-calling-role>
Perspectives to consider:
- Architecture impact: Will this actually improve the target structural metric?
- Risk assessment: What could break? Dangling references? Behavioral changes? Migration risk?
- Maintainability: Is the refactored code more understandable and maintainable?
- Alternative approaches: Are there simpler or safer ways to achieve the same structural improvement?
Evaluate trade-offs and provide a structured recommendation with:
- Consensus verdict: proceed / revise / escalate
- Confidence level: high / medium / low
- Key trade-offs identified
- Recommended approach with rationale
- Dissenting perspectives (if any)`
})
```
## Round Configuration
| Round | Artifact | Parameters | Calling Role |
|-------|----------|------------|-------------|
| DISCUSS-REFACTOR | <session>/discussions/DISCUSS-REFACTOR.md | Refactoring strategy trade-offs | designer |
| DISCUSS-REVIEW | <session>/discussions/DISCUSS-REVIEW.md | Code review finding validation | reviewer |
## Integration with Calling Role
The calling role is responsible for:
1. **Before calling**: Complete primary analysis, identify the specific trade-off or finding needing discussion
2. **Calling**: Invoke subagent with round ID, topic, and relevant context
3. **After calling**:
| Result | Action |
|--------|--------|
| consensus_reached (proceed) | Incorporate recommendation into output, continue |
| consensus_reached (revise) | Adjust findings/strategy based on discussion insights |
| consensus_blocked (HIGH) | Report to coordinator via message with severity |
| consensus_blocked (MEDIUM) | Include in output with recommendation for revision |
| consensus_blocked (LOW) | Note in output, proceed with original assessment |
## Output Schema
```json
{
"round_id": "<DISCUSS-REFACTOR|DISCUSS-REVIEW>",
"topic": "<discussion-topic>",
"verdict": "<proceed|revise|escalate>",
"confidence": "<high|medium|low>",
"trade_offs": [
{ "dimension": "<architecture|risk|maintainability>", "pro": "<benefit>", "con": "<cost>" }
],
"recommendation": "<recommended-approach>",
"rationale": "<reasoning>",
"dissenting_views": ["<alternative-perspective>"]
}
```
## Error Handling
| Scenario | Resolution |
|----------|------------|
| Single perspective analysis fails | Continue with partial perspectives |
| All analyses fail | Return basic recommendation from calling role's primary analysis |
| Artifact not found | Return error immediately |
| Discussion inconclusive | Return "revise" verdict with low confidence |

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