Compare commits

...

98 Commits

Author SHA1 Message Date
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
827 changed files with 120353 additions and 68431 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,32 @@
---
title: "Architecture Constraints"
dimension: specs
category: planning
keywords:
- architecture
- module
- layer
- pattern
readMode: required
priority: high
---
# 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,38 @@
---
title: "Coding Conventions"
dimension: specs
category: general
keywords:
- typescript
- naming
- style
- convention
readMode: required
priority: high
---
# 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

@@ -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-plan "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
@@ -149,7 +152,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
@@ -501,7 +504,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 +566,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
@@ -846,7 +850,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 +859,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

@@ -18,25 +18,17 @@ Main process orchestrator: intent analysis → workflow selection → command ch
| `workflow-lite-plan` | 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实现 0→1 开发|
## Core Concept: Self-Contained Skills (自包含 Skill)
@@ -53,22 +45,17 @@ Main process orchestrator: intent analysis → workflow selection → command ch
|---------|-------|------|
| 轻量 Plan+Execute | `workflow-lite-plan` | 内部完成 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-plan` | 协作分析产物自动传递给 lite-plan |
| 头脑风暴→规划 | `workflow:brainstorm-with-file` `workflow-lite-plan` | 头脑风暴产物自动传递给 lite-plan |
| 协作规划 | `workflow:collaborative-plan-with-file``workflow:unified-execute-with-file` | 多 agent 协作规划→通用执行 |
| 需求路线图 | `workflow:roadmap-with-file``team-planex` | 需求拆解→issue 创建→wave pipeline 执行 |
| 集成测试循环 | `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 +123,21 @@ 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)
'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|需求.*规划|需求.*拆解|requirement.*plan|progressive.*plan|路线.*图/,
'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 +146,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 +184,29 @@ 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
// With-File workflows → auto chain to lite-plan
'brainstorm': { level: 4, flow: 'brainstorm-to-plan' }, // brainstorm-with-file → lite-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
'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' },
@@ -281,18 +258,15 @@ function buildCommandChain(workflow, analysis) {
{ cmd: 'workflow-lite-plan', 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-plan', 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-lite-plan', args: '' } // auto receives brainstorm artifacts (brainstorm.md)
],
'debug-with-file': [
@@ -300,32 +274,22 @@ 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' }
],
// 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 +302,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 +338,7 @@ function buildCommandChain(workflow, analysis) {
{ cmd: 'workflow-execute', args: '' }
],
// Level 4 - Full
// Level 4 - Full Exploration
'full': [
{ cmd: 'brainstorm', args: `"${analysis.goal}"` },
{ cmd: 'workflow-plan', args: '' },
@@ -370,6 +348,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 +365,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}"` }
]
};
@@ -607,7 +566,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)
|
@@ -639,26 +598,20 @@ Phase 5: Execute Command Chain
| "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 |
| "协作分析: 认证架构" | analyze-file | 3 | analyze-with-file → workflow-lite-plan |
| "深度调试 WebSocket" | debug-file | 3 | workflow:debug-with-file |
| "协作分析: 认证架构优化" | analyze-file | 3 | workflow:analyze-with-file |
| "头脑风暴: 通知系统" | brainstorm | 4 | brainstorm-with-file workflow-lite-plan |
| "从头脑风暴创建 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 |
| "需求路线图: 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 +621,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
---
@@ -715,114 +669,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-plan", "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-lite-plan (auto) | `.workflow/.brainstorm/` |
| **debug-with-file** | Hypothesis-driven debugging | Standalone (self-contained) | `.workflow/.debug/` |
| **analyze-with-file** | Collaborative analysis | → workflow-lite-plan (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` or `brainstorm-with-file` completes, its artifacts (discussion.md / brainstorm.md) are automatically passed to `workflow-lite-plan` as context input. No user intervention needed.
**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 +722,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 +740,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 +752,31 @@ 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
# With-File workflows → auto chain to lite-plan
/ccw "协作分析: 理解现有认证架构的设计决策" # → analyze-with-file → workflow-lite-plan
/ccw "头脑风暴: 用户通知系统重新设计" # → brainstorm-with-file → workflow-lite-plan
/ccw "深度调试: 系统随机崩溃问题" # → debug-with-file (standalone)
/ccw "从头脑风暴 BS-通知系统-2025-01-28 创建 issue" # → brainstorm-to-issue (bridge)
/ccw "深度调试: 系统随机崩溃问题" # → debug-with-file
/ccw "协作分析: 理解现有认证架构的设计决策" # → analyze-with-file
# 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)
# 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 "需求路线图: 用户认证 OAuth + 2FA" # → roadmap-with-file → team-planex
/ccw "roadmap: 数据导出功能路线图" # → roadmap-with-file → team-planex
# 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"
}
```

View File

@@ -107,24 +107,24 @@ 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-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: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 +133,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-plan", description: "Lightweight bug diagnosis and fix (with --bugfix flag)" },
{ label: "/workflow:debug-with-file", description: "Hypothesis-driven debugging with documentation" }
],
'Brainstorm': [
@@ -303,10 +303,10 @@ 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-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-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 +318,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 +336,10 @@ 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-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-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 +351,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-plan", "args": "--hotfix \"{{goal}}\"", "unit": "standalone", "execution": { "type": "slash-command", "mode": "mainprocess" }, "contextHint": "Emergency hotfix mode" }
]
}
```
@@ -363,9 +363,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 +379,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 +392,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 +420,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-plan", "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 +486,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 +502,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-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-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" }
]
}
```
@@ -656,9 +656,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

@@ -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)
@@ -508,11 +542,53 @@ 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
3. **Post-Completion Options**
```javascript
const hasActionableRecs = conclusions.recommendations?.some(r => r.priority === 'high' || r.priority === 'medium')
const nextStep = AskUserQuestion({
questions: [{
question: "Analysis complete. What's next?",
header: "Next Step",
multiSelect: false,
options: [
{ label: hasActionableRecs ? "生成任务 (Recommended)" : "生成任务", description: "Launch workflow-lite-plan with analysis context" },
{ label: "创建Issue", description: "Launch issue-discover with conclusions" },
{ label: "导出报告", description: "Generate standalone analysis report" },
{ label: "完成", description: "No further action" }
]
}]
})
```
**Handle "生成任务"**:
```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. Call lite-plan with enriched task description (no special flags)
Skill(skill="workflow-lite-plan", args=`"${taskDescription}\n\n${contextLines.join('\n')}"`)
}
```
**conclusions.json Schema**:
- `session_id`: Session identifier
@@ -525,10 +601,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
@@ -691,6 +769,8 @@ User agrees with current direction, wants deeper code analysis
- 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

@@ -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 = '.workflow/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
- \`.workflow/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
- \`.workflow/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}"`
---

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 `.workflow/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 .workflow/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,108 @@ 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
function appendRulesToSpecFile(filePath, rules, defaultCategory = 'general') {
if (rules.length === 0) return
// 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)
appendRulesToSpecFile('.workflow/specs/coding-conventions.md',
[...newCodingStyle, ...newNamingPatterns, ...newFileStructure, ...newDocumentation],
'general')
// Write constraints (planning category)
appendRulesToSpecFile('.workflow/specs/architecture-constraints.md',
[...newArchitecture, ...newTechStack, ...newPerformance, ...newSecurity],
'planning')
// Write quality rules (execution category)
if (newQualityRules.length > 0) {
const qualityPath = '.workflow/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 +443,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 → .workflow/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 .workflow/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
targetDir = '.workflow/specs'
if (isConstraint) {
targetFile = path.join(targetDir, 'architecture-constraints.md')
} else {
targetFile = path.join(targetDir, 'coding-conventions.md')
}
} else {
// Personal specs
if (scope === 'global') {
targetDir = path.join(os.homedir(), '.ccw', 'specs', 'personal')
} else {
targetDir = path.join('.ccw', 'specs', '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)
```
.workflow/specs/
├── coding-conventions.md ← conventions, learnings
├── architecture-constraints.md ← constraints
└── quality-rules.md ← quality rules
```
### Personal Specs (dimension: personal)
```
# Global (~/.ccw/specs/personal/)
~/.ccw/specs/personal/
├── conventions.md ← personal conventions (all projects)
├── constraints.md ← personal constraints (all projects)
└── learnings.md ← personal learnings (all projects)
# Project-local (.ccw/specs/personal/)
.ccw/specs/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 `.workflow/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)
└─ .workflow/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 .workflow/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: .workflow/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 .workflow/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('.workflow/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: .workflow/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
@@ -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-plan` |
| Collaborative multi-agent planning | `/workflow:collaborative-plan-with-file` |
| Full specification documents | `spec-generator` skill |
| Code implementation from existing plan | `/workflow:lite-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 `.workflow/specs/*.md`. This ensures valuable learnings persist across sessions and inform future planning.
## Use Cases
@@ -113,34 +113,14 @@ ELSE (convention/constraint/learning):
### Step 1: Ensure Guidelines File Exists
```bash
bash(test -f .workflow/project-guidelines.json && echo "EXISTS" || echo "NOT_FOUND")
bash(test -f .workflow/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 +183,40 @@ 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
const specFileMap = {
convention: '.workflow/specs/coding-conventions.md',
constraint: '.workflow/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
const targetFile = '.workflow/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 +228,7 @@ Type: ${type}
Category: ${category}
Rule: "${rule}"
Location: .workflow/project-guidelines.json -> ${type}s.${category}
Location: .workflow/specs/*.md -> ${type}s.${category}
Total ${type}s in ${category}: ${count}
```
@@ -386,7 +373,7 @@ AskUserQuestion({
/workflow:session:solidify "Use async/await instead of callbacks" --type convention --category coding_style
```
Result in `project-guidelines.json`:
Result in `specs/*.md`:
```json
{
"conventions": {
@@ -444,7 +431,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 +449,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 .workflow/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
- `.workflow/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,201 @@
---
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:
.workflow/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 ──
if (guidelineUpdates.length > 0) {
// Map guideline types to spec files
const specFileMap = {
convention: '.workflow/specs/coding-conventions.md',
constraint: '.workflow/specs/architecture-constraints.md',
learning: '.workflow/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('.workflow/specs/*.md')
? JSON.parse(Read('.workflow/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-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-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',
@@ -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-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-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,8 +346,8 @@ 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',
'`/workflow-multi-cli-plan`': '`workflow-multi-cli-plan` skill',
'`/workflow-lite-plan`': '`workflow-lite-plan` skill',
'`/cli:plan`': '`workflow-lite-plan` 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

@@ -341,7 +341,7 @@
},
{
"name": "execute",
"command": "/workflow:execute",
"command": "/workflow-execute",
"description": "Coordinate agent execution for workflow tasks with automatic session discovery, parallel task processing, and status tracking",
"arguments": "[-y|--yes] [--resume-session=\\\"session-id\\\"]",
"category": "workflow",
@@ -396,7 +396,7 @@
},
{
"name": "lite-plan",
"command": "/workflow:lite-plan",
"command": "/workflow-lite-plan",
"description": "Lightweight interactive planning workflow with in-memory planning, code exploration, and execution execute to lite-execute after user confirmation",
"arguments": "[-y|--yes] [-e|--explore] \\\"task description\\\"|file.md",
"category": "workflow",
@@ -406,8 +406,8 @@
"source": "../../commands/workflow/lite-plan.md"
},
{
"name": "workflow:multi-cli-plan",
"command": "/workflow:multi-cli-plan",
"name": "workflow-multi-cli-plan",
"command": "/workflow-multi-cli-plan",
"description": "Multi-CLI collaborative planning workflow with ACE context gathering and iterative cross-verification. Uses cli-discuss-agent for Gemini+Codex+Claude analysis to converge on optimal execution plan.",
"arguments": "[-y|--yes] <task description> [--max-rounds=3] [--tools=gemini,codex] [--mode=parallel|serial]",
"category": "workflow",
@@ -418,7 +418,7 @@
},
{
"name": "plan-verify",
"command": "/workflow:plan-verify",
"command": "/workflow-plan-verify",
"description": "Perform READ-ONLY verification analysis between IMPL_PLAN.md, task JSONs, and brainstorming artifacts. Generates structured report with quality gate recommendation. Does NOT modify any files.",
"arguments": "[optional: --session session-id]",
"category": "workflow",
@@ -429,7 +429,7 @@
},
{
"name": "plan",
"command": "/workflow:plan",
"command": "/workflow-plan",
"description": "5-phase planning workflow with action-planning-agent task generation, outputs IMPL_PLAN.md and task JSONs",
"arguments": "[-y|--yes] \\\"text description\\\"|file.md",
"category": "workflow",
@@ -550,7 +550,7 @@
},
{
"name": "tdd-plan",
"command": "/workflow:tdd-plan",
"command": "/workflow-tdd-plan",
"description": "TDD workflow planning with Red-Green-Refactor task chain generation, test-first development structure, and cycle tracking",
"arguments": "\\\"feature description\\\"|file.md",
"category": "workflow",
@@ -561,7 +561,7 @@
},
{
"name": "tdd-verify",
"command": "/workflow:tdd-verify",
"command": "/workflow-tdd-verify",
"description": "Verify TDD workflow compliance against Red-Green-Refactor cycles. Generates quality report with coverage analysis and quality gate recommendation. Orchestrates sub-commands for comprehensive validation.",
"arguments": "[optional: --session WFS-session-id]",
"category": "workflow",
@@ -572,7 +572,7 @@
},
{
"name": "test-cycle-execute",
"command": "/workflow:test-cycle-execute",
"command": "/workflow-test-fix",
"description": "Execute test-fix workflow with dynamic task generation and iterative fix cycles until test pass rate >= 95% or max iterations reached. Uses @cli-planning-agent for failure analysis and task generation.",
"arguments": "[--resume-session=\\\"session-id\\\"] [--max-iterations=N]",
"category": "workflow",
@@ -583,7 +583,7 @@
},
{
"name": "test-fix-gen",
"command": "/workflow:test-fix-gen",
"command": "/workflow-test-fix",
"description": "Create test-fix workflow session from session ID, description, or file path with test strategy generation and task planning",
"arguments": "(source-session-id | \\\"feature description\\\" | /path/to/file.md)",
"category": "workflow",
@@ -716,7 +716,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",

View File

@@ -277,7 +277,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",

View File

@@ -310,7 +310,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",

View File

@@ -282,7 +282,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",

View File

@@ -142,70 +142,70 @@ def analyze_agent_file(file_path: Path) -> Dict[str, Any]:
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": {
"workflow-lite-plan": {
"calls_internally": ["workflow:lite-execute"],
"next_steps": ["workflow:lite-execute", "workflow:status"],
"alternatives": ["workflow:plan"],
"alternatives": ["workflow-plan"],
"prerequisites": []
},
"workflow:lite-fix": {
"next_steps": ["workflow:lite-execute", "workflow:status"],
"alternatives": ["workflow:lite-plan"],
"related": ["workflow:test-cycle-execute"]
"alternatives": ["workflow-lite-plan"],
"related": ["workflow-test-fix"]
},
"workflow:lite-execute": {
"prerequisites": ["workflow:lite-plan", "workflow:lite-fix"],
"related": ["workflow:execute", "workflow:status"]
"prerequisites": ["workflow-lite-plan", "workflow:lite-fix"],
"related": ["workflow-execute", "workflow:status"]
},
"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 +213,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-plan", "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 = []

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-plan` - 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-plan, 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-plan", 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

@@ -6,157 +6,148 @@ allowed-tools: TeamCreate(*), TeamDelete(*), SendMessage(*), TaskCreate(*), Task
# Team Brainstorm
头脑风暴团队技能。通过 Generator-Critic 循环、共享记忆和动态管道选择,实现多角度创意发散、挑战验证和收敛筛选。所有团队成员通过 `--role=xxx` 路由到角色执行逻辑。
Unified team skill: multi-angle brainstorming via Generator-Critic loops, shared memory, and dynamic pipeline selection. All team members invoke with `--role=xxx` to route to role-specific execution.
## Architecture Overview
## Architecture
```
┌───────────────────────────────────────────────────┐
│ Skill(skill="team-brainstorm", args="--role=xxx")
│ Skill(skill="team-brainstorm")
│ args="<topic>" or args="--role=xxx" │
└───────────────────┬───────────────────────────────┘
│ Role Router
┌───────────┬───┼───────────┬───────────┐
↓ ↓
┌──────────┐┌───────┐┌──────────┐┌──────────┐┌─────────┐
│coordinator││ideator││challenger││synthesizer││evaluator│
│ roles/ ││roles/ ││ roles/ ││ roles/ ││ roles/ │
└──────────┘└───────┘└──────────┘└──────────┘└─────────┘
┌──── --role present? ────┐
│ NO │ YES
↓ ↓
Orchestration Mode Role Dispatch
(auto → coordinator) (route to role.md)
┌────┴────┬───────────┬───────────┬───────────┐
↓ ↓ ↓ ↓ ↓
┌──────────┐┌─────────┐┌──────────┐┌──────────┐┌─────────┐
│coordinator││ ideator ││challenger││synthesizer││evaluator│
│ ││ IDEA-* ││CHALLENGE-*││ SYNTH-* ││ EVAL-* │
└──────────┘└─────────┘└──────────┘└──────────┘└─────────┘
```
## Role Router
### Input Parsing
Parse `$ARGUMENTS` to extract `--role`:
Parse `$ARGUMENTS` to extract `--role`. If absent → Orchestration Mode (auto route to coordinator).
```javascript
const args = "$ARGUMENTS"
const roleMatch = args.match(/--role[=\s]+(\w+)/)
### Role Registry
if (!roleMatch) {
throw new Error("Missing --role argument. Available roles: coordinator, ideator, challenger, synthesizer, evaluator")
}
| Role | File | Task Prefix | Type | Compact |
|------|------|-------------|------|---------|
| coordinator | [roles/coordinator.md](roles/coordinator.md) | (none) | orchestrator | **⚠️ 压缩后必须重读** |
| ideator | [roles/ideator.md](roles/ideator.md) | IDEA-* | pipeline | 压缩后必须重读 |
| challenger | [roles/challenger.md](roles/challenger.md) | CHALLENGE-* | pipeline | 压缩后必须重读 |
| synthesizer | [roles/synthesizer.md](roles/synthesizer.md) | SYNTH-* | pipeline | 压缩后必须重读 |
| evaluator | [roles/evaluator.md](roles/evaluator.md) | EVAL-* | pipeline | 压缩后必须重读 |
const role = roleMatch[1]
const teamName = args.match(/--team[=\s]+([\w-]+)/)?.[1] || "brainstorm"
const agentName = args.match(/--agent-name[=\s]+([\w-]+)/)?.[1] || role
> **⚠️ COMPACT PROTECTION**: 角色文件是执行文档,不是参考资料。当 context compression 发生后,角色指令仅剩摘要时,**必须立即 `Read` 对应 role.md 重新加载后再继续执行**。不得基于摘要执行任何 Phase。
### Dispatch
1. Extract `--role` from arguments
2. If no `--role` → route to coordinator (Orchestration Mode)
3. Look up role in registry → Read the role file → Execute its phases
### Orchestration Mode
When invoked without `--role`, coordinator auto-starts. User just provides topic description.
**Invocation**: `Skill(skill="team-brainstorm", args="<topic-description>")`
**Lifecycle**:
```
User provides topic description
→ coordinator Phase 1-3: Topic clarification → TeamCreate → Create task chain
→ coordinator Phase 4: spawn first batch workers (background) → STOP
→ Worker executes → SendMessage callback → coordinator advances next step
→ Loop until pipeline complete → Phase 5 report
```
### Role Dispatch
**User Commands** (wake paused coordinator):
```javascript
const VALID_ROLES = {
"coordinator": { file: "roles/coordinator.md", prefix: null },
"ideator": { file: "roles/ideator.md", prefix: "IDEA" },
"challenger": { file: "roles/challenger.md", prefix: "CHALLENGE" },
"synthesizer": { file: "roles/synthesizer.md", prefix: "SYNTH" },
"evaluator": { file: "roles/evaluator.md", prefix: "EVAL" }
}
| Command | Action |
|---------|--------|
| `check` / `status` | Output execution status graph, no advancement |
| `resume` / `continue` | Check worker states, advance next step |
if (!VALID_ROLES[role]) {
throw new Error(`Unknown role: ${role}. Available: ${Object.keys(VALID_ROLES).join(', ')}`)
}
// Read and execute role-specific logic
Read(VALID_ROLES[role].file)
// → Execute the 5-phase process defined in that file
```
### Available Roles
| Role | Task Prefix | Responsibility | Role File |
|------|-------------|----------------|-----------|
| `coordinator` | N/A | 话题澄清、复杂度评估、管道选择、收敛监控 | [roles/coordinator.md](roles/coordinator.md) |
| `ideator` | IDEA-* | 多角度创意生成、概念探索、发散思维 | [roles/ideator.md](roles/ideator.md) |
| `challenger` | CHALLENGE-* | 魔鬼代言人、假设挑战、可行性质疑 | [roles/challenger.md](roles/challenger.md) |
| `synthesizer` | SYNTH-* | 跨想法整合、主题提取、冲突解决 | [roles/synthesizer.md](roles/synthesizer.md) |
| `evaluator` | EVAL-* | 评分排序、优先级推荐、最终筛选 | [roles/evaluator.md](roles/evaluator.md) |
---
## Shared Infrastructure
The following templates apply to all worker roles. Each role.md only needs to write **Phase 2-4** role-specific logic.
### Worker Phase 1: Task Discovery (shared by all workers)
Every worker executes the same task discovery flow on startup:
1. Call `TaskList()` to get all tasks
2. Filter: subject matches this role's prefix + owner is this role + status is pending + blockedBy is empty
3. No tasks → idle wait
4. Has tasks → `TaskGet` for details → `TaskUpdate` mark in_progress
**Resume Artifact Check** (prevent duplicate output after resume):
- Check whether this task's output artifact already exists
- Artifact complete → skip to Phase 5 report completion
- Artifact incomplete or missing → normal Phase 2-4 execution
### Worker Phase 5: Report (shared by all workers)
Standard reporting flow after task completion:
1. **Message Bus**: Call `mcp__ccw-tools__team_msg` to log message
- Parameters: operation="log", team=**<session-id>**, from=<role>, to="coordinator", type=<message-type>, summary="[<role>] <summary>", ref=<artifact-path>
- **CLI fallback**: When MCP unavailable → `ccw team log --team <session-id> --from <role> --to coordinator --type <type> --summary "[<role>] ..." --json`
- **Note**: `team` must be session ID (e.g., `BRS-xxx-date`), NOT team name. Extract from `Session:` field in task description.
2. **SendMessage**: Send result to coordinator (content and summary both prefixed with `[<role>]`)
3. **TaskUpdate**: Mark task completed
4. **Loop**: Return to Phase 1 to check next task
### Wisdom Accumulation (all roles)
Cross-task knowledge accumulation. Coordinator creates `wisdom/` directory at session initialization.
**Directory**:
```
<session-folder>/wisdom/
├── learnings.md # Patterns and insights
├── decisions.md # Architecture and design decisions
├── conventions.md # Codebase conventions
└── issues.md # Known risks and issues
```
**Worker Load** (Phase 2): Extract `Session: <path>` from task description, read wisdom directory files.
**Worker Contribute** (Phase 4/5): Write this task's discoveries to corresponding wisdom files.
### Role Isolation Rules
**核心原则**: 每个角色仅能执行自己职责范围内的工作。
| Allowed | Forbidden |
|---------|-----------|
| Process tasks with own prefix | Process tasks with other role prefixes |
| SendMessage to coordinator | Communicate directly with other workers |
| Read/write shared-memory.json (own fields) | Create tasks for other roles |
| Delegate to commands/ files | Modify resources outside own responsibility |
#### Output Tagging强制
Coordinator additional restrictions: Do not generate ideas directly, do not evaluate/challenge ideas, do not execute analysis/synthesis, do not bypass workers.
所有角色的输出必须带 `[role_name]` 标识前缀:
### Output Tagging
```javascript
// SendMessage — content 和 summary 都必须带标识
SendMessage({
content: `## [${role}] ...`,
summary: `[${role}] ...`
})
// team_msg — summary 必须带标识
mcp__ccw-tools__team_msg({
summary: `[${role}] ...`
})
```
#### Coordinator 隔离
| 允许 | 禁止 |
|------|------|
| 需求澄清 (AskUserQuestion) | ❌ 直接生成创意 |
| 创建任务链 (TaskCreate) | ❌ 直接评估/挑战想法 |
| 分发任务给 worker | ❌ 直接执行分析/综合 |
| 监控进度 (消息总线) | ❌ 绕过 worker 自行完成任务 |
| 汇报结果给用户 | ❌ 修改源代码或产物文件 |
#### Worker 隔离
| 允许 | 禁止 |
|------|------|
| 处理自己前缀的任务 | ❌ 处理其他角色前缀的任务 |
| SendMessage 给 coordinator | ❌ 直接与其他 worker 通信 |
| 读取 shared-memory.json | ❌ 为其他角色创建任务 (TaskCreate) |
| 写入 shared-memory.json (自己的字段) | ❌ 修改不属于本职责的资源 |
### Team Configuration
```javascript
const TEAM_CONFIG = {
name: "brainstorm",
sessionDir: ".workflow/.team/BRS-{slug}-{date}/",
sharedMemory: "shared-memory.json"
}
```
### Shared Memory (创新模式)
所有角色在 Phase 2 读取、Phase 5 写入 `shared-memory.json`
```javascript
// Phase 2: 读取共享记忆
const memoryPath = `${sessionFolder}/shared-memory.json`
let sharedMemory = {}
try { sharedMemory = JSON.parse(Read(memoryPath)) } catch {}
// Phase 5: 写入共享记忆(仅更新自己负责的字段)
// ideator → sharedMemory.generated_ideas
// challenger → sharedMemory.critique_insights
// synthesizer → sharedMemory.synthesis_themes
// evaluator → sharedMemory.evaluation_scores
Write(memoryPath, JSON.stringify(sharedMemory, null, 2))
```
All outputs must carry `[role_name]` prefix in both SendMessage content/summary and team_msg summary.
### Message Bus (All Roles)
Every SendMessage **before**, must call `mcp__ccw-tools__team_msg` to log:
```javascript
mcp__ccw-tools__team_msg({
operation: "log",
team: teamName,
from: role,
to: "coordinator",
type: "<type>",
summary: `[${role}] <summary>`,
ref: "<file_path>"
})
```
**Parameters**: operation="log", team=**<session-id>**, from=<role>, to="coordinator", type=<message-type>, summary="[<role>] <summary>", ref=<artifact-path>
**CLI fallback**: When MCP unavailable → `ccw team log --team <session-id> --from <role> --to coordinator --type <type> --summary "[<role>] ..." --json`
**Note**: `team` must be session ID (e.g., `BRS-xxx-date`), NOT team name. Extract from `Session:` field in task description.
**Message types by role**:
@@ -168,36 +159,26 @@ mcp__ccw-tools__team_msg({
| synthesizer | `synthesis_ready`, `error` |
| evaluator | `evaluation_ready`, `error` |
### CLI Fallback
### Shared Memory
When `mcp__ccw-tools__team_msg` MCP is unavailable:
All roles read in Phase 2 and write in Phase 5 to `shared-memory.json`:
```javascript
Bash(`ccw team log --team "${teamName}" --from "${role}" --to "coordinator" --type "<type>" --summary "<summary>" --json`)
```
| Role | Field |
|------|-------|
| ideator | `generated_ideas` |
| challenger | `critique_insights` |
| synthesizer | `synthesis_themes` |
| evaluator | `evaluation_scores` |
### Task Lifecycle (All Worker Roles)
### Team Configuration
```javascript
const tasks = TaskList()
const myTasks = tasks.filter(t =>
t.subject.startsWith(`${VALID_ROLES[role].prefix}-`) &&
t.owner === agentName && // Use agentName (e.g., 'ideator-1') instead of role
t.status === 'pending' &&
t.blockedBy.length === 0
)
if (myTasks.length === 0) return // idle
const task = TaskGet({ taskId: myTasks[0].id })
TaskUpdate({ taskId: task.id, status: 'in_progress' })
| Setting | Value |
|---------|-------|
| Team name | brainstorm |
| Session directory | `.workflow/.team/BRS-<slug>-<date>/` |
| Shared memory | `shared-memory.json` in session dir |
// Phase 2-4: Role-specific (see roles/{role}.md)
// Phase 5: Report + Loop — 所有输出必须带 [role] 标识
mcp__ccw-tools__team_msg({ operation: "log", team: teamName, from: role, to: "coordinator", type: "...", summary: `[${role}] ...` })
SendMessage({ type: "message", recipient: "coordinator", content: `## [${role}] ...`, summary: `[${role}] ...` })
TaskUpdate({ taskId: task.id, status: 'completed' })
// Check for next task → back to Phase 1
```
---
## Three-Pipeline Architecture
@@ -214,19 +195,193 @@ Full (Fan-out + Generator-Critic):
### Generator-Critic Loop
ideator challenger 循环最多2轮
ideator <-> challenger loop, max 2 rounds:
```
IDEA → CHALLENGE → (if critique.severity >= HIGH) → IDEA-fix → CHALLENGE-2 → SYNTH
(if critique.severity < HIGH) → SYNTH
```
### Cadence Control
**Beat model**: Event-driven, each beat = coordinator wake → process → spawn → STOP. Brainstorm beat: generate → challenge → synthesize → evaluate.
```
Beat Cycle (single beat)
═══════════════════════════════════════════════════════════
Event Coordinator Workers
───────────────────────────────────────────────────────────
callback/resume ──→ ┌─ handleCallback ─┐
│ mark completed │
│ check pipeline │
├─ handleSpawnNext ─┤
│ find ready tasks │
│ spawn workers ───┼──→ [Worker A] Phase 1-5
│ (parallel OK) ──┼──→ [Worker B] Phase 1-5
└─ STOP (idle) ─────┘ │
callback ←─────────────────────────────────────────┘
(next beat) SendMessage + TaskUpdate(completed)
═══════════════════════════════════════════════════════════
```
**Pipeline beat views**:
```
Quick (3 beats, strictly serial)
──────────────────────────────────────────────────────────
Beat 1 2 3
│ │ │
IDEA → CHALLENGE ──→ SYNTH
▲ ▲
pipeline pipeline
start done
IDEA=ideator CHALLENGE=challenger SYNTH=synthesizer
Deep (5-6 beats, with Generator-Critic loop)
──────────────────────────────────────────────────────────
Beat 1 2 3 4 5 6
│ │ │ │ │ │
IDEA → CHALLENGE → (GC loop?) → IDEA-fix → SYNTH → EVAL
severity check
(< HIGH → skip to SYNTH)
Full (4-7 beats, fan-out + Generator-Critic)
──────────────────────────────────────────────────────────
Beat 1 2 3-4 5 6
┌────┴────┐ │ │ │ │
IDEA-1 ∥ IDEA-2 ∥ IDEA-3 → CHALLENGE → (GC loop) → SYNTH → EVAL
▲ ▲
parallel pipeline
window done
```
**Checkpoints**:
| Trigger | Location | Behavior |
|---------|----------|----------|
| Generator-Critic loop | After CHALLENGE-* | If severity >= HIGH → create IDEA-fix task; else proceed to SYNTH |
| GC loop limit | Max 2 rounds | Exceeds limit → force convergence to SYNTH |
| Pipeline stall | No ready + no running | Check missing tasks, report to user |
**Stall Detection** (coordinator `handleCheck` executes):
| Check | Condition | Resolution |
|-------|-----------|------------|
| Worker no response | in_progress task no callback | Report waiting task list, suggest user `resume` |
| Pipeline deadlock | no ready + no running + has pending | Check blockedBy dependency chain, report blocking point |
| GC loop exceeded | ideator/challenger iteration > 2 rounds | Terminate loop, force convergence to synthesizer |
### Task Metadata Registry
| Task ID | Role | Phase | Dependencies | Description |
|---------|------|-------|-------------|-------------|
| IDEA-001 | ideator | generate | (none) | Multi-angle idea generation |
| IDEA-002 | ideator | generate | (none) | Parallel angle (Full pipeline only) |
| IDEA-003 | ideator | generate | (none) | Parallel angle (Full pipeline only) |
| CHALLENGE-001 | challenger | challenge | IDEA-001 (or all IDEA-*) | Devil's advocate critique and feasibility challenge |
| IDEA-004 | ideator | gc-fix | CHALLENGE-001 | Revision based on critique (GC loop, if triggered) |
| CHALLENGE-002 | challenger | gc-fix | IDEA-004 | Re-critique of revised ideas (GC loop round 2) |
| SYNTH-001 | synthesizer | synthesize | last CHALLENGE-* | Cross-idea integration, theme extraction, conflict resolution |
| EVAL-001 | evaluator | evaluate | SYNTH-001 | Scoring, ranking, priority recommendation, final selection |
---
## Coordinator Spawn Template
When coordinator spawns workers, use background mode (Spawn-and-Stop).
**Standard spawn** (single agent per role): For Quick/Deep pipeline, spawn one ideator. Challenger, synthesizer, and evaluator are always single agents.
**Parallel spawn** (Full pipeline): For Full pipeline with N idea angles, spawn N ideator agents in parallel (`ideator-1`, `ideator-2`, ...) with `run_in_background: true`. Each parallel ideator only processes tasks where owner matches its agent name. After all parallel ideators complete, proceed with single challenger for batch critique.
**Spawn template**:
```
Task({
subagent_type: "general-purpose",
description: "Spawn <role> worker",
team_name: "brainstorm",
name: "<role>",
run_in_background: true,
prompt: `You are team "brainstorm" <ROLE>.
## Primary Directive
All your work must be executed through Skill to load role definition:
Skill(skill="team-brainstorm", args="--role=<role>")
Current topic: <topic-description>
Session: <session-folder>
## Role Guidelines
- Only process <PREFIX>-* tasks, do not execute other role work
- All output prefixed with [<role>] identifier
- Only communicate with coordinator
- Do not use TaskCreate for other roles
- Call mcp__ccw-tools__team_msg before every SendMessage
## Workflow
1. Call Skill -> load role definition and execution logic
2. Follow role.md 5-Phase flow
3. team_msg + SendMessage results to coordinator
4. TaskUpdate completed -> check next task`
})
```
**Parallel ideator spawn** (Full pipeline with N angles):
> When Full pipeline has N parallel IDEA tasks assigned to ideator role, spawn N distinct agents named `ideator-1`, `ideator-2`, etc. Each agent only processes tasks where owner matches its agent name.
| Condition | Action |
|-----------|--------|
| Full pipeline with N idea angles (N > 1) | Spawn N agents: `ideator-1`, `ideator-2`, ... `ideator-N` with `run_in_background: true` |
| Quick/Deep pipeline (single ideator) | Standard spawn: single `ideator` agent |
```
Task({
subagent_type: "general-purpose",
description: "Spawn ideator-<N> worker",
team_name: "brainstorm",
name: "ideator-<N>",
run_in_background: true,
prompt: `You are team "brainstorm" IDEATOR (ideator-<N>).
Your agent name is "ideator-<N>", use this name for task discovery owner matching.
## Primary Directive
Skill(skill="team-brainstorm", args="--role=ideator --agent-name=ideator-<N>")
Current topic: <topic-description>
Session: <session-folder>
## Role Guidelines
- Only process tasks where owner === "ideator-<N>" with IDEA-* prefix
- All output prefixed with [ideator] identifier
## Workflow
1. TaskList -> find tasks where owner === "ideator-<N>" with IDEA-* prefix
2. Skill -> execute role definition
3. team_msg + SendMessage results to coordinator
4. TaskUpdate completed -> check next task`
})
```
**Dispatch must match agent names**: When dispatching parallel IDEA tasks, coordinator sets each task's owner to the corresponding instance name (`ideator-1`, `ideator-2`, etc.). In role.md, task discovery uses `--agent-name` for owner matching.
---
## Unified Session Directory
```
.workflow/.team/BRS-{slug}-{YYYY-MM-DD}/
.workflow/.team/BRS-<slug>-<YYYY-MM-DD>/
├── team-session.json # Session state
├── shared-memory.json # 累积: generated_ideas / critique_insights / synthesis_themes / evaluation_scores
├── shared-memory.json # Cumulative: generated_ideas / critique_insights / synthesis_themes / evaluation_scores
├── wisdom/ # Cross-task knowledge
│ ├── learnings.md
│ ├── decisions.md
│ ├── conventions.md
│ └── issues.md
├── ideas/ # Ideator output
│ ├── idea-001.md
│ ├── idea-002.md
@@ -240,154 +395,13 @@ IDEA → CHALLENGE → (if critique.severity >= HIGH) → IDEA-fix → CHALLENGE
└── evaluation-001.md
```
## Coordinator Spawn Template
```javascript
TeamCreate({ team_name: teamName })
// Ideator — conditional parallel spawn for Full pipeline (multiple angles)
const isFullPipeline = selectedPipeline === 'full'
const ideaAngles = selectedAngles || []
if (isFullPipeline && ideaAngles.length > 1) {
// Full pipeline: spawn N ideators for N parallel angle tasks
for (let i = 0; i < ideaAngles.length; i++) {
const agentName = `ideator-${i + 1}`
Task({
subagent_type: "general-purpose",
team_name: teamName,
name: agentName,
prompt: `你是 team "${teamName}" 的 IDEATOR (${agentName})。
你的 agent 名称是 "${agentName}",任务发现时用此名称匹配 owner。
当你收到 IDEA-* 任务时,调用 Skill(skill="team-brainstorm", args="--role=ideator --agent-name=${agentName}") 执行。
当前话题: ${taskDescription}
约束: ${constraints}
## 角色准则(强制)
- 你只能处理 owner 为 "${agentName}" 的 IDEA-* 前缀任务
- 所有输出SendMessage、team_msg必须带 [ideator] 标识前缀
- 仅与 coordinator 通信,不得直接联系其他 worker
- 不得使用 TaskCreate 为其他角色创建任务
## 消息总线(必须)
每次 SendMessage 前,先调用 mcp__ccw-tools__team_msg 记录。
工作流程:
1. TaskList → 找到 owner === "${agentName}" 的 IDEA-* 任务
2. Skill(skill="team-brainstorm", args="--role=ideator --agent-name=${agentName}") 执行
3. team_msg log + SendMessage 结果给 coordinator带 [ideator] 标识)
4. TaskUpdate completed → 检查下一个任务`
})
}
} else {
// Quick/Deep pipeline: single ideator
Task({
subagent_type: "general-purpose",
team_name: teamName,
name: "ideator",
prompt: `你是 team "${teamName}" 的 IDEATOR。
当你收到 IDEA-* 任务时,调用 Skill(skill="team-brainstorm", args="--role=ideator") 执行。
当前话题: ${taskDescription}
约束: ${constraints}
## 角色准则(强制)
- 你只能处理 IDEA-* 前缀的任务,不得执行其他角色的工作
- 所有输出SendMessage、team_msg必须带 [ideator] 标识前缀
- 仅与 coordinator 通信,不得直接联系其他 worker
- 不得使用 TaskCreate 为其他角色创建任务
## 消息总线(必须)
每次 SendMessage 前,先调用 mcp__ccw-tools__team_msg 记录。
工作流程:
1. TaskList → 找到 IDEA-* 任务
2. Skill(skill="team-brainstorm", args="--role=ideator") 执行
3. team_msg log + SendMessage 结果给 coordinator带 [ideator] 标识)
4. TaskUpdate completed → 检查下一个任务`
})
}
// Challenger
Task({
subagent_type: "general-purpose",
team_name: teamName,
name: "challenger",
prompt: `你是 team "${teamName}" 的 CHALLENGER。
当你收到 CHALLENGE-* 任务时,调用 Skill(skill="team-brainstorm", args="--role=challenger") 执行。
当前话题: ${taskDescription}
## 角色准则(强制)
- 你只能处理 CHALLENGE-* 前缀的任务
- 所有输出必须带 [challenger] 标识前缀
- 仅与 coordinator 通信
## 消息总线(必须)
每次 SendMessage 前,先调用 mcp__ccw-tools__team_msg 记录。
工作流程:
1. TaskList → 找到 CHALLENGE-* 任务
2. Skill(skill="team-brainstorm", args="--role=challenger") 执行
3. team_msg log + SendMessage 结果给 coordinator带 [challenger] 标识)
4. TaskUpdate completed → 检查下一个任务`
})
// Synthesizer
Task({
subagent_type: "general-purpose",
team_name: teamName,
name: "synthesizer",
prompt: `你是 team "${teamName}" 的 SYNTHESIZER。
当你收到 SYNTH-* 任务时,调用 Skill(skill="team-brainstorm", args="--role=synthesizer") 执行。
当前话题: ${taskDescription}
## 角色准则(强制)
- 你只能处理 SYNTH-* 前缀的任务
- 所有输出必须带 [synthesizer] 标识前缀
- 仅与 coordinator 通信
## 消息总线(必须)
每次 SendMessage 前,先调用 mcp__ccw-tools__team_msg 记录。
工作流程:
1. TaskList → 找到 SYNTH-* 任务
2. Skill(skill="team-brainstorm", args="--role=synthesizer") 执行
3. team_msg log + SendMessage 结果给 coordinator带 [synthesizer] 标识)
4. TaskUpdate completed → 检查下一个任务`
})
// Evaluator
Task({
subagent_type: "general-purpose",
team_name: teamName,
name: "evaluator",
prompt: `你是 team "${teamName}" 的 EVALUATOR。
当你收到 EVAL-* 任务时,调用 Skill(skill="team-brainstorm", args="--role=evaluator") 执行。
当前话题: ${taskDescription}
## 角色准则(强制)
- 你只能处理 EVAL-* 前缀的任务
- 所有输出必须带 [evaluator] 标识前缀
- 仅与 coordinator 通信
## 消息总线(必须)
每次 SendMessage 前,先调用 mcp__ccw-tools__team_msg 记录。
工作流程:
1. TaskList → 找到 EVAL-* 任务
2. Skill(skill="team-brainstorm", args="--role=evaluator") 执行
3. team_msg log + SendMessage 结果给 coordinator带 [evaluator] 标识)
4. TaskUpdate completed → 检查下一个任务`
})
```
## Error Handling
| Scenario | Resolution |
|----------|------------|
| Unknown --role value | Error with available role list |
| Missing --role arg | Error with usage hint |
| Role file not found | Error with expected path (roles/{name}.md) |
| Missing --role arg | Orchestration Mode → auto route to coordinator |
| Role file not found | Error with expected path (roles/<name>.md) |
| Task prefix conflict | Log warning, proceed |
| Generator-Critic loop exceeds 2 rounds | Force convergence → SYNTH |
| No ideas generated | Coordinator prompts with seed questions |

View File

@@ -1,16 +1,14 @@
# Role: challenger
# Challenger Role
魔鬼代言人角色。负责假设挑战、可行性质疑、风险识别。作为 Generator-Critic 循环中的 Critic 角色。
## Role Identity
## Identity
- **Name**: `challenger`
- **Name**: `challenger` | **Tag**: `[challenger]`
- **Task Prefix**: `CHALLENGE-*`
- **Responsibility**: Read-only analysis (批判性分析)
- **Communication**: SendMessage to coordinator only
- **Output Tag**: `[challenger]`
- **Responsibility**: Read-only analysis (critical analysis)
## Role Boundaries
## Boundaries
### MUST
@@ -22,181 +20,141 @@
### MUST NOT
- 生成创意、综合想法或评估排序
- 直接与其他 worker 角色通信
- 为其他角色创建任务
- 修改 shared-memory.json 中不属于自己的字段
- 生成创意、综合想法或评估排序
- 直接与其他 worker 角色通信
- 为其他角色创建任务
- 修改 shared-memory.json 中不属于自己的字段
- 在输出中省略 `[challenger]` 标识
---
## Toolbox
### Tool Capabilities
| Tool | Type | Used By | Purpose |
|------|------|---------|---------|
| `TaskList` | Built-in | Phase 1 | Discover pending CHALLENGE-* tasks |
| `TaskGet` | Built-in | Phase 1 | Get task details |
| `TaskUpdate` | Built-in | Phase 1/5 | Update task status |
| `Read` | Built-in | Phase 2 | Read shared-memory.json, idea files |
| `Write` | Built-in | Phase 3/5 | Write critique files, update shared memory |
| `Glob` | Built-in | Phase 2 | Find idea files |
| `SendMessage` | Built-in | Phase 5 | Report to coordinator |
| `mcp__ccw-tools__team_msg` | MCP | Phase 5 | Log communication |
---
## Message Types
| Type | Direction | Trigger | Description |
|------|-----------|---------|-------------|
| `critique_ready` | challenger coordinator | Critique completed | 挑战分析完成 |
| `error` | challenger coordinator | Processing failure | 错误上报 |
| `critique_ready` | challenger -> coordinator | Critique completed | Critical analysis complete |
| `error` | challenger -> coordinator | Processing failure | Error report |
## Message Bus
Before every SendMessage, log via `mcp__ccw-tools__team_msg`:
```
mcp__ccw-tools__team_msg({
operation: "log",
team: **<session-id>**, // MUST be session ID (e.g., BRS-xxx-date), NOT team name. Extract from Session: field.
from: "challenger",
to: "coordinator",
type: "critique_ready",
summary: "[challenger] Critique complete: <critical>C/<high>H/<medium>M/<low>L -- Signal: <signal>",
ref: <output-path>
})
```
**CLI fallback** (when MCP unavailable):
```
Bash("ccw team log --team <session-id> --from challenger --to coordinator --type critique_ready --summary \"[challenger] Critique complete\" --ref <output-path> --json")
```
---
## Execution (5-Phase)
### Phase 1: Task Discovery
```javascript
const tasks = TaskList()
const myTasks = tasks.filter(t =>
t.subject.startsWith('CHALLENGE-') &&
t.owner === 'challenger' &&
t.status === 'pending' &&
t.blockedBy.length === 0
)
> See SKILL.md Shared Infrastructure -> Worker Phase 1: Task Discovery
if (myTasks.length === 0) return
const task = TaskGet({ taskId: myTasks[0].id })
TaskUpdate({ taskId: task.id, status: 'in_progress' })
```
Standard task discovery flow: TaskList -> filter by prefix `CHALLENGE-*` + owner match + pending + unblocked -> TaskGet -> TaskUpdate in_progress.
### Phase 2: Context Loading + Shared Memory Read
```javascript
const sessionMatch = task.description.match(/Session:\s*([^\n]+)/)
const sessionFolder = sessionMatch?.[1]?.trim()
| Input | Source | Required |
|-------|--------|----------|
| Session folder | Task description (Session: line) | Yes |
| Ideas | ideas/*.md files | Yes |
| Previous critiques | shared-memory.json.critique_insights | No (avoid repeating) |
const memoryPath = `${sessionFolder}/shared-memory.json`
let sharedMemory = {}
try { sharedMemory = JSON.parse(Read(memoryPath)) } catch {}
**Loading steps**:
// Read all idea files referenced in task
const ideaFiles = Glob({ pattern: `${sessionFolder}/ideas/*.md` })
const ideas = ideaFiles.map(f => Read(f))
// Read previous critiques for context (avoid repeating)
const prevCritiques = sharedMemory.critique_insights || []
```
1. Extract session path from task description (match "Session: <path>")
2. Glob idea files from session folder
3. Read all idea files for analysis
4. Read shared-memory.json.critique_insights to avoid repeating
### Phase 3: Critical Analysis
```javascript
// For each idea, apply 4 challenge dimensions:
// 1. Assumption Validity — 核心假设是否成立?有什么反例?
// 2. Feasibility — 技术/资源/时间上是否可行?
// 3. Risk Assessment — 最坏情况是什么?有什么隐藏风险?
// 4. Competitive Analysis — 已有更好的替代方案吗?
**Challenge Dimensions** (apply to each idea):
// Severity classification:
// LOW — Minor concern, does not invalidate the idea
// MEDIUM — Notable weakness, needs consideration
// HIGH — Significant flaw, requires revision
// CRITICAL — Fundamental issue, idea may need replacement
| Dimension | Focus |
|-----------|-------|
| Assumption Validity | Does the core assumption hold? Any counter-examples? |
| Feasibility | Technical/resource/time feasibility? |
| Risk Assessment | Worst case scenario? Hidden risks? |
| Competitive Analysis | Better alternatives already exist? |
const challengeNum = task.subject.match(/CHALLENGE-(\d+)/)?.[1] || '001'
const outputPath = `${sessionFolder}/critiques/critique-${challengeNum}.md`
**Severity Classification**:
const critiqueContent = `# Critique — Round ${challengeNum}
| Severity | Criteria |
|----------|----------|
| CRITICAL | Fundamental issue, idea may need replacement |
| HIGH | Significant flaw, requires revision |
| MEDIUM | Notable weakness, needs consideration |
| LOW | Minor concern, does not invalidate the idea |
**Ideas Reviewed**: ${ideas.length} files
**Challenge Dimensions**: Assumption Validity, Feasibility, Risk, Competition
**Generator-Critic Signal**:
## Challenges
| Condition | Signal |
|-----------|--------|
| Any CRITICAL or HIGH severity | REVISION_NEEDED -> ideator must revise |
| All MEDIUM or lower | CONVERGED -> ready for synthesis |
${challenges.map((c, i) => `### Idea: ${c.ideaTitle}
**Severity**: ${c.severity}
| Dimension | Finding |
|-----------|---------|
| Assumption Validity | ${c.assumption} |
| Feasibility | ${c.feasibility} |
| Risk Assessment | ${c.risk} |
| Competitive Analysis | ${c.competition} |
**Key Challenge**: ${c.keyChallenge}
**Suggested Direction**: ${c.suggestion}
`).join('\n')}
## Summary
| Severity | Count |
|----------|-------|
| CRITICAL | ${challenges.filter(c => c.severity === 'CRITICAL').length} |
| HIGH | ${challenges.filter(c => c.severity === 'HIGH').length} |
| MEDIUM | ${challenges.filter(c => c.severity === 'MEDIUM').length} |
| LOW | ${challenges.filter(c => c.severity === 'LOW').length} |
**Generator-Critic Signal**: ${
challenges.some(c => c.severity === 'CRITICAL' || c.severity === 'HIGH')
? 'REVISION_NEEDED — Critical/High issues require ideator revision'
: 'CONVERGED — No critical issues, ready for synthesis'
}
`
Write(outputPath, critiqueContent)
```
**Output file structure**:
- File: `<session>/critiques/critique-<num>.md`
- Sections: Ideas Reviewed, Challenge Dimensions, Per-idea challenges with severity table, Summary table with counts, GC Signal
### Phase 4: Severity Summary
```javascript
// Aggregate severity counts for coordinator decision
const severitySummary = {
critical: challenges.filter(c => c.severity === 'CRITICAL').length,
high: challenges.filter(c => c.severity === 'HIGH').length,
medium: challenges.filter(c => c.severity === 'MEDIUM').length,
low: challenges.filter(c => c.severity === 'LOW').length,
signal: (challenges.some(c => c.severity === 'CRITICAL' || c.severity === 'HIGH'))
? 'REVISION_NEEDED' : 'CONVERGED'
}
```
**Aggregation**:
1. Count challenges by severity level
2. Determine signal based on presence of CRITICAL/HIGH
| Metric | Source |
|--------|--------|
| critical count | challenges with severity CRITICAL |
| high count | challenges with severity HIGH |
| medium count | challenges with severity MEDIUM |
| low count | challenges with severity LOW |
| signal | REVISION_NEEDED if critical+high > 0, else CONVERGED |
### Phase 5: Report to Coordinator + Shared Memory Write
```javascript
// Update shared memory
sharedMemory.critique_insights = [
...sharedMemory.critique_insights,
...challenges.map(c => ({
idea: c.ideaTitle,
severity: c.severity,
key_challenge: c.keyChallenge,
round: parseInt(challengeNum)
}))
]
Write(memoryPath, JSON.stringify(sharedMemory, null, 2))
> See SKILL.md Shared Infrastructure -> Worker Phase 5: Report
mcp__ccw-tools__team_msg({
operation: "log",
team: teamName,
from: "challenger",
to: "coordinator",
type: "critique_ready",
summary: `[challenger] Critique complete: ${severitySummary.critical}C/${severitySummary.high}H/${severitySummary.medium}M/${severitySummary.low}L — Signal: ${severitySummary.signal}`,
ref: outputPath
})
Standard report flow: team_msg log -> SendMessage with `[challenger]` prefix -> TaskUpdate completed -> Loop to Phase 1 for next task.
SendMessage({
type: "message",
recipient: "coordinator",
content: `## [challenger] Critique Results
**Shared Memory Update**:
1. Append challenges to shared-memory.json.critique_insights
2. Each entry: idea, severity, key_challenge, round
**Task**: ${task.subject}
**Signal**: ${severitySummary.signal}
**Severity**: ${severitySummary.critical} Critical, ${severitySummary.high} High, ${severitySummary.medium} Medium, ${severitySummary.low} Low
**Output**: ${outputPath}
${severitySummary.signal === 'REVISION_NEEDED'
? '### Requires Revision\n' + challenges.filter(c => ['CRITICAL', 'HIGH'].includes(c.severity)).map(c => `- **${c.ideaTitle}** (${c.severity}): ${c.keyChallenge}`).join('\n')
: '### All Clear — Ready for Synthesis'}`,
summary: `[challenger] Critique: ${severitySummary.signal}`
})
TaskUpdate({ taskId: task.id, status: 'completed' })
// Check for next task
const nextTasks = TaskList().filter(t =>
t.subject.startsWith('CHALLENGE-') &&
t.owner === 'challenger' &&
t.status === 'pending' &&
t.blockedBy.length === 0
)
if (nextTasks.length > 0) {
// back to Phase 1
}
```
---
## Error Handling
@@ -206,3 +164,4 @@ if (nextTasks.length > 0) {
| Ideas file not found | Notify coordinator |
| All ideas trivially good | Mark all LOW, signal CONVERGED |
| Cannot assess feasibility | Mark MEDIUM with note, suggest deeper analysis |
| Critical issue beyond scope | SendMessage error to coordinator |

View File

@@ -1,315 +1,257 @@
# Role: coordinator
# Coordinator Role
头脑风暴团队协调者。负责话题澄清、复杂度评估、管道选择、Generator-Critic 循环控制和收敛监控。
## Role Identity
## Identity
- **Name**: `coordinator`
- **Task Prefix**: N/A (coordinator creates tasks, doesn't receive them)
- **Responsibility**: Orchestration
- **Communication**: SendMessage to all teammates
- **Output Tag**: `[coordinator]`
- **Name**: `coordinator` | **Tag**: `[coordinator]`
- **Responsibility**: Parse requirements -> Create team -> Dispatch tasks -> Monitor progress -> Report results
## Role Boundaries
## Boundaries
### MUST
- 所有输出SendMessage、team_msg、日志必须带 `[coordinator]` 标识
- 仅负责话题澄清、任务创建/分发、进度监控、结果汇报
- 通过 TaskCreate 创建任务并分配给 worker 角色
- 解析用户需求,通过 AskUserQuestion 澄清模糊输入
- 创建团队并通过 TaskCreate 分配任务给 worker 角色
- 通过消息总线监控 worker 进度并路由消息
- 管理 Generator-Critic 循环计数,决定是否继续迭代
- 维护 session 状态持久化
### MUST NOT
- **直接生成创意、挑战假设、综合想法或评估排序**
- 直接调用实现类 subagent
- 直接修改产物文件ideas/*.md, critiques/*.md 等)
- 绕过 worker 角色自行完成应委派的工作
- 在输出中省略 `[coordinator]` 标识
- 直接生成创意、挑战假设、综合想法或评估排序
- 直接调用实现类 subagent
- 直接修改产物文件ideas/*.md, critiques/*.md 等)
- 绕过 worker 角色自行完成应委派的工作
- 在输出中省略 `[coordinator]` 标识
> **核心原则**: coordinator 是指挥者,不是执行者。所有实际工作必须通过 TaskCreate 委派给 worker 角色。
---
## Message Types
| Type | Direction | Trigger | Description |
|------|-----------|---------|-------------|
| `pipeline_selected` | coordinator all | Pipeline decided | Notify selected pipeline mode |
| `gc_loop_trigger` | coordinator ideator | Critique severity >= HIGH | Trigger ideator to revise |
| `task_unblocked` | coordinator any | Dependency resolved | Notify worker of available task |
| `error` | coordinator all | Critical system error | Escalation to user |
| `shutdown` | coordinator all | Team being dissolved | Clean shutdown signal |
| `pipeline_selected` | coordinator -> all | Pipeline decided | Notify selected pipeline mode |
| `gc_loop_trigger` | coordinator -> ideator | Critique severity >= HIGH | Trigger ideator to revise |
| `task_unblocked` | coordinator -> any | Dependency resolved | Notify worker of available task |
| `error` | coordinator -> all | Critical system error | Escalation to user |
| `shutdown` | coordinator -> all | Team being dissolved | Clean shutdown signal |
## Execution
## Message Bus
### Phase 1: Topic Clarification + Complexity Assessment
Before every SendMessage, log via `mcp__ccw-tools__team_msg`:
```javascript
const args = "$ARGUMENTS"
const teamNameMatch = args.match(/--team-name[=\s]+([\w-]+)/)
const teamName = teamNameMatch ? teamNameMatch[1] : `brainstorm-${Date.now().toString(36)}`
const taskDescription = args.replace(/--team-name[=\s]+[\w-]+/, '').replace(/--role[=\s]+\w+/, '').trim()
```
Assess topic complexity and select pipeline:
```javascript
function assessComplexity(topic) {
let score = 0
if (/strategy|architecture|system|framework|paradigm/.test(topic)) score += 3
if (/multiple|compare|tradeoff|versus|alternative/.test(topic)) score += 2
if (/innovative|creative|novel|breakthrough/.test(topic)) score += 2
if (/simple|quick|straightforward|basic/.test(topic)) score -= 2
return score >= 4 ? 'high' : score >= 2 ? 'medium' : 'low'
}
const complexity = assessComplexity(taskDescription)
```
```javascript
AskUserQuestion({
questions: [
{
question: "选择头脑风暴模式:",
header: "Mode",
multiSelect: false,
options: [
{ label: complexity === 'low' ? "quick (推荐)" : "quick", description: "快速模式创意→挑战→综合3步" },
{ label: complexity === 'medium' ? "deep (推荐)" : "deep", description: "深度模式:含 Generator-Critic 循环6步" },
{ label: complexity === 'high' ? "full (推荐)" : "full", description: "完整模式:并行发散 + 循环 + 评估7步" }
]
},
{
question: "创意发散角度:",
header: "Angles",
multiSelect: true,
options: [
{ label: "技术视角", description: "技术可行性、实现方案、架构设计" },
{ label: "产品视角", description: "用户需求、市场定位、商业模式" },
{ label: "创新视角", description: "颠覆性思路、跨领域借鉴、未来趋势" },
{ label: "风险视角", description: "潜在问题、约束条件、替代方案" }
]
}
]
mcp__ccw-tools__team_msg({
operation: "log",
team: **<session-id>**, // MUST be session ID (e.g., BRS-xxx-date), NOT team name. Extract from Session: field.
from: "coordinator",
to: <recipient>,
type: <message-type>,
summary: "[coordinator] <action> complete: <subject>",
ref: <artifact-path>
})
```
### Phase 2: Create Team + Initialize Session
**CLI fallback** (when MCP unavailable):
```javascript
TeamCreate({ team_name: teamName })
const topicSlug = taskDescription.toLowerCase().replace(/[^a-z0-9]+/g, '-').substring(0, 40)
const dateStr = new Date(Date.now() + 8 * 60 * 60 * 1000).toISOString().substring(0, 10)
const sessionId = `BRS-${topicSlug}-${dateStr}`
const sessionFolder = `.workflow/.team/${sessionId}`
Bash(`mkdir -p "${sessionFolder}/ideas" "${sessionFolder}/critiques" "${sessionFolder}/synthesis" "${sessionFolder}/evaluation"`)
// Initialize shared memory
const sharedMemory = {
topic: taskDescription,
pipeline: selectedPipeline,
angles: selectedAngles,
gc_round: 0,
max_gc_rounds: 2,
generated_ideas: [],
critique_insights: [],
synthesis_themes: [],
evaluation_scores: []
}
Write(`${sessionFolder}/shared-memory.json`, JSON.stringify(sharedMemory, null, 2))
// Create team-session.json
const teamSession = {
session_id: sessionId,
team_name: teamName,
topic: taskDescription,
pipeline: selectedPipeline,
status: "active",
created_at: new Date().toISOString(),
updated_at: new Date().toISOString(),
gc_round: 0,
completed_tasks: []
}
Write(`${sessionFolder}/team-session.json`, JSON.stringify(teamSession, null, 2))
```
Bash("ccw team log --team <session-id> --from coordinator --to <recipient> --type <message-type> --summary \"[coordinator] <action> complete\" --ref <artifact-path> --json")
```
// ⚠️ Workers are NOT pre-spawned here.
// Workers are spawned per-stage in Phase 4 via Stop-Wait Task(run_in_background: false).
// See SKILL.md Coordinator Spawn Template for worker prompt templates.
---
### Phase 3: Create Task Chain
## Entry Router
Task chain depends on the selected pipeline.
When coordinator is invoked, first detect the invocation type:
#### Quick Pipeline
| Detection | Condition | Handler |
|-----------|-----------|---------|
| Worker callback | Message contains `[role-name]` tag from a known worker role | -> handleCallback: auto-advance pipeline |
| Status check | Arguments contain "check" or "status" | -> handleCheck: output execution graph, no advancement |
| Manual resume | Arguments contain "resume" or "continue" | -> handleResume: check worker states, advance pipeline |
| New session | None of the above | -> Phase 0 (Session Resume Check) |
```javascript
// IDEA-001: 创意生成
TaskCreate({ subject: "IDEA-001: 多角度创意生成", description: `话题: ${taskDescription}\n\nSession: ${sessionFolder}\n角度: ${selectedAngles.join(', ')}\n输出: ${sessionFolder}/ideas/idea-001.md\n\n要求: 每个角度至少产出3个创意总计不少于6个`, activeForm: "生成创意中" })
TaskUpdate({ taskId: ideaId, owner: "ideator" })
For callback/check/resume: load monitor logic and execute the appropriate handler, then STOP.
// CHALLENGE-001: 挑战质疑 (blockedBy IDEA-001)
TaskCreate({ subject: "CHALLENGE-001: 假设挑战与可行性质疑", description: `对 IDEA-001 的创意进行批判性分析\n\nSession: ${sessionFolder}\n输入: ${sessionFolder}/ideas/idea-001.md\n输出: ${sessionFolder}/critiques/critique-001.md\n\n要求: 标记每个创意的挑战严重度 (LOW/MEDIUM/HIGH/CRITICAL)`, activeForm: "挑战创意中" })
TaskUpdate({ taskId: challengeId, owner: "challenger", addBlockedBy: [ideaId] })
---
// SYNTH-001: 综合整合 (blockedBy CHALLENGE-001)
TaskCreate({ subject: "SYNTH-001: 跨想法整合与主题提取", description: `整合所有创意和挑战反馈\n\nSession: ${sessionFolder}\n输入: ideas/ + critiques/\n输出: ${sessionFolder}/synthesis/synthesis-001.md\n\n要求: 提取核心主题、解决冲突、生成整合方案`, activeForm: "综合整合中" })
TaskUpdate({ taskId: synthId, owner: "synthesizer", addBlockedBy: [challengeId] })
```
## Phase 0: Session Resume Check
#### Deep Pipeline (with Generator-Critic Loop)
**Objective**: Detect and resume interrupted sessions before creating new ones.
```javascript
// IDEA-001 → CHALLENGE-001 → IDEA-002(fix) → CHALLENGE-002 → SYNTH-001 → EVAL-001
**Workflow**:
1. Scan session directory for sessions with status "active" or "paused"
2. No sessions found -> proceed to Phase 1
3. Single session found -> resume it (-> Session Reconciliation)
4. Multiple sessions -> AskUserQuestion for user selection
TaskCreate({ subject: "IDEA-001: 初始创意生成", description: `话题: ${taskDescription}\n\nSession: ${sessionFolder}\n输出: ${sessionFolder}/ideas/idea-001.md`, activeForm: "生成创意中" })
TaskUpdate({ taskId: idea1Id, owner: "ideator" })
**Session Reconciliation**:
1. Audit TaskList -> get real status of all tasks
2. Reconcile: session state <-> TaskList status (bidirectional sync)
3. Reset any in_progress tasks -> pending (they were interrupted)
4. Determine remaining pipeline from reconciled state
5. Rebuild team if disbanded (TeamCreate + spawn needed workers only)
6. Create missing tasks with correct blockedBy dependencies
7. Verify dependency chain integrity
8. Update session file with reconciled state
9. Kick first executable task's worker -> Phase 4
TaskCreate({ subject: "CHALLENGE-001: 第一轮挑战", description: `挑战 IDEA-001 的创意\n\nSession: ${sessionFolder}\n输入: ideas/idea-001.md\n输出: critiques/critique-001.md\n标记严重度`, activeForm: "挑战中" })
TaskUpdate({ taskId: challenge1Id, owner: "challenger", addBlockedBy: [idea1Id] })
---
TaskCreate({ subject: "IDEA-002: 创意修订Generator-Critic Round 1", description: `基于 CHALLENGE-001 的反馈修订创意\n\nSession: ${sessionFolder}\n输入: ideas/idea-001.md + critiques/critique-001.md\n输出: ideas/idea-002.md\n\n要求: 针对 HIGH/CRITICAL 严重度的挑战进行修订或替换`, activeForm: "修订创意中" })
TaskUpdate({ taskId: idea2Id, owner: "ideator", addBlockedBy: [challenge1Id] })
## Phase 1: Topic Clarification + Complexity Assessment
TaskCreate({ subject: "CHALLENGE-002: 第二轮验证", description: `验证修订后的创意\n\nSession: ${sessionFolder}\n输入: ideas/idea-002.md + critiques/critique-001.md\n输出: critiques/critique-002.md`, activeForm: "验证中" })
TaskUpdate({ taskId: challenge2Id, owner: "challenger", addBlockedBy: [idea2Id] })
**Objective**: Parse user input, assess complexity, select pipeline mode.
TaskCreate({ subject: "SYNTH-001: 综合整合", description: `整合全部创意和挑战反馈\n\nSession: ${sessionFolder}\n输入: ideas/ + critiques/\n输出: synthesis/synthesis-001.md`, activeForm: "综合中" })
TaskUpdate({ taskId: synthId, owner: "synthesizer", addBlockedBy: [challenge2Id] })
**Workflow**:
TaskCreate({ subject: "EVAL-001: 评分排序与最终筛选", description: `对综合方案评分排序\n\nSession: ${sessionFolder}\n输入: synthesis/synthesis-001.md + shared-memory.json\n输出: evaluation/evaluation-001.md\n\n评分维度: 可行性(30%) + 创新性(25%) + 影响力(25%) + 实施成本(20%)`, activeForm: "评估中" })
TaskUpdate({ taskId: evalId, owner: "evaluator", addBlockedBy: [synthId] })
```
1. Parse arguments for `--team-name` and task description
#### Full Pipeline (Fan-out + Generator-Critic)
2. Assess topic complexity:
```javascript
// 并行创意: IDEA-001 + IDEA-002 + IDEA-003 (no dependencies between them)
// Each gets a distinct agent owner for true parallel execution
const ideaAngles = selectedAngles.slice(0, 3)
ideaAngles.forEach((angle, i) => {
const ideatorName = ideaAngles.length > 1 ? `ideator-${i+1}` : 'ideator'
TaskCreate({ subject: `IDEA-00${i+1}: ${angle}角度创意生成`, description: `话题: ${taskDescription}\n角度: ${angle}\n\nSession: ${sessionFolder}\n输出: ideas/idea-00${i+1}.md`, activeForm: `${angle}创意生成中` })
TaskUpdate({ taskId: ideaIds[i], owner: ideatorName })
})
| Signal | Weight | Keywords |
|--------|--------|----------|
| Strategic/systemic | +3 | strategy, architecture, system, framework, paradigm |
| Multi-dimensional | +2 | multiple, compare, tradeoff, versus, alternative |
| Innovation-focused | +2 | innovative, creative, novel, breakthrough |
| Simple/basic | -2 | simple, quick, straightforward, basic |
// CHALLENGE-001: 批量挑战 (blockedBy all IDEA-001..003)
TaskCreate({ subject: "CHALLENGE-001: 批量创意挑战", description: `批量挑战所有角度的创意\n\nSession: ${sessionFolder}\n输入: ideas/idea-001..003.md\n输出: critiques/critique-001.md`, activeForm: "批量挑战中" })
TaskUpdate({ taskId: challenge1Id, owner: "challenger", addBlockedBy: ideaIds })
| Score | Complexity | Pipeline Recommendation |
|-------|------------|-------------------------|
| >= 4 | High | full |
| 2-3 | Medium | deep |
| 0-1 | Low | quick |
// IDEA-004: 修订 (blockedBy CHALLENGE-001)
TaskCreate({ subject: "IDEA-004: 创意修订", description: `基于批量挑战反馈修订\n\nSession: ${sessionFolder}\n输入: ideas/ + critiques/critique-001.md\n输出: ideas/idea-004.md`, activeForm: "修订中" })
TaskUpdate({ taskId: idea4Id, owner: "ideator", addBlockedBy: [challenge1Id] })
3. Ask for missing parameters via AskUserQuestion:
// SYNTH-001 (blockedBy IDEA-004)
TaskCreate({ subject: "SYNTH-001: 综合整合", description: `整合全部创意\n\nSession: ${sessionFolder}\n输入: ideas/ + critiques/\n输出: synthesis/synthesis-001.md`, activeForm: "综合中" })
TaskUpdate({ taskId: synthId, owner: "synthesizer", addBlockedBy: [idea4Id] })
| Question | Header | Options |
|----------|--------|---------|
| Pipeline mode | Mode | quick (3-step), deep (6-step with GC loop), full (7-step parallel + GC) |
| Divergence angles | Angles | Multi-select: Technical, Product, Innovation, Risk |
// EVAL-001 (blockedBy SYNTH-001)
TaskCreate({ subject: "EVAL-001: 评分排序", description: `最终评估\n\nSession: ${sessionFolder}\n输入: synthesis/ + shared-memory.json\n输出: evaluation/evaluation-001.md`, activeForm: "评估中" })
TaskUpdate({ taskId: evalId, owner: "evaluator", addBlockedBy: [synthId] })
```
4. Store requirements: mode, scope, angles, constraints
### Phase 4: Coordination Loop + Generator-Critic Control
**Success**: All parameters captured, pipeline finalized.
> **设计原则Stop-Wait**: 模型执行没有时间概念,禁止任何形式的轮询等待。
> - ❌ 禁止: `while` 循环 + `sleep` + 检查状态
> - ✅ 采用: 同步 `Task(run_in_background: false)` 调用Worker 返回 = 阶段完成信号
>
> 按 Phase 3 创建的任务链顺序,逐阶段 spawn worker 同步执行。
> Worker prompt 使用 SKILL.md Coordinator Spawn Template。
---
## Phase 2: Create Team + Initialize Session
**Objective**: Initialize team, session file, and shared memory.
**Workflow**:
1. Generate session ID: `BRS-<topic-slug>-<date>`
2. Create session folder structure
3. Call TeamCreate with team name
4. Initialize subdirectories: ideas/, critiques/, synthesis/, evaluation/
5. Initialize shared-memory.json with: topic, pipeline, angles, gc_round, generated_ideas, critique_insights, synthesis_themes, evaluation_scores
6. Write team-session.json with: session_id, team_name, topic, pipeline, status="active", created_at, updated_at
7. Workers are NOT pre-spawned here -> spawned per-stage in Phase 4
**Success**: Team created, session file written, directories initialized.
---
## Phase 3: Create Task Chain
**Objective**: Dispatch tasks based on selected pipeline with proper dependencies.
### Quick Pipeline
| Task ID | Subject | Owner | BlockedBy |
|---------|---------|-------|-----------|
| IDEA-001 | Multi-angle idea generation | ideator | - |
| CHALLENGE-001 | Assumption challenges | challenger | IDEA-001 |
| SYNTH-001 | Cross-idea synthesis | synthesizer | CHALLENGE-001 |
### Deep Pipeline (with Generator-Critic Loop)
| Task ID | Subject | Owner | BlockedBy |
|---------|---------|-------|-----------|
| IDEA-001 | Initial idea generation | ideator | - |
| CHALLENGE-001 | First round critique | challenger | IDEA-001 |
| IDEA-002 | Idea revision (GC Round 1) | ideator | CHALLENGE-001 |
| CHALLENGE-002 | Second round validation | challenger | IDEA-002 |
| SYNTH-001 | Synthesis | synthesizer | CHALLENGE-002 |
| EVAL-001 | Scoring and ranking | evaluator | SYNTH-001 |
### Full Pipeline (Fan-out + Generator-Critic)
| Task ID | Subject | Owner | BlockedBy |
|---------|---------|-------|-----------|
| IDEA-001 | Technical angle ideas | ideator-1 | - |
| IDEA-002 | Product angle ideas | ideator-2 | - |
| IDEA-003 | Innovation angle ideas | ideator-3 | - |
| CHALLENGE-001 | Batch critique | challenger | IDEA-001, IDEA-002, IDEA-003 |
| IDEA-004 | Revised ideas | ideator | CHALLENGE-001 |
| SYNTH-001 | Synthesis | synthesizer | IDEA-004 |
| EVAL-001 | Evaluation | evaluator | SYNTH-001 |
**Success**: All tasks created with correct dependencies and owners assigned.
---
## Phase 4: Coordination Loop + Generator-Critic Control
**Objective**: Monitor worker callbacks and advance pipeline.
> **Design Principle (Stop-Wait)**: No time-based polling. Worker return = stage complete signal.
| Received Message | Action |
|-----------------|--------|
| ideator: ideas_ready | Read ideas team_msg log TaskUpdate completed unblock CHALLENGE |
| challenger: critique_ready | Read critique **Generator-Critic 判断** → 决定是否触发 IDEA-fix |
| ideator: ideas_revised | Read revised ideas team_msg log TaskUpdate completed unblock CHALLENGE-2 |
| synthesizer: synthesis_ready | Read synthesis team_msg log TaskUpdate completed unblock EVAL (if exists) |
| evaluator: evaluation_ready | Read evaluation team_msg log TaskUpdate completed Phase 5 |
| All tasks completed | Phase 5 |
| ideator: ideas_ready | Read ideas -> team_msg log -> TaskUpdate completed -> unblock CHALLENGE |
| challenger: critique_ready | Read critique -> **Generator-Critic decision** -> decide if IDEA-fix needed |
| ideator: ideas_revised | Read revised ideas -> team_msg log -> TaskUpdate completed -> unblock next CHALLENGE |
| synthesizer: synthesis_ready | Read synthesis -> team_msg log -> TaskUpdate completed -> unblock EVAL (if exists) |
| evaluator: evaluation_ready | Read evaluation -> team_msg log -> TaskUpdate completed -> Phase 5 |
| All tasks completed | -> Phase 5 |
#### Generator-Critic Loop Control
### Generator-Critic Loop Control
```javascript
if (msgType === 'critique_ready') {
const critique = Read(`${sessionFolder}/critiques/critique-${round}.md`)
const sharedMemory = JSON.parse(Read(`${sessionFolder}/shared-memory.json`))
// Count HIGH/CRITICAL severity challenges
const criticalCount = (critique.match(/severity:\s*(HIGH|CRITICAL)/gi) || []).length
const gcRound = sharedMemory.gc_round || 0
if (criticalCount > 0 && gcRound < sharedMemory.max_gc_rounds) {
// Trigger another ideator round
sharedMemory.gc_round = gcRound + 1
Write(`${sessionFolder}/shared-memory.json`, JSON.stringify(sharedMemory, null, 2))
mcp__ccw-tools__team_msg({
operation: "log", team: teamName, from: "coordinator", to: "ideator",
type: "gc_loop_trigger",
summary: `[coordinator] Generator-Critic round ${gcRound + 1}: ${criticalCount} critical challenges need revision`
})
// Unblock IDEA-fix task
} else {
// Converged → unblock SYNTH
mcp__ccw-tools__team_msg({
operation: "log", team: teamName, from: "coordinator", to: "synthesizer",
type: "task_unblocked",
summary: `[coordinator] Critique converged (round ${gcRound}), proceeding to synthesis`
})
}
}
```
| Condition | Action |
|-----------|--------|
| critique_ready + criticalCount > 0 + gcRound < maxRounds | Trigger IDEA-fix task, increment gc_round |
| critique_ready + (criticalCount == 0 OR gcRound >= maxRounds) | Converged -> unblock SYNTH task |
### Phase 5: Report + Persist
**GC Round Tracking**:
1. Read critique file
2. Count severity: HIGH and CRITICAL
3. Read shared-memory.json for gc_round
4. If criticalCount > 0 AND gcRound < max_gc_rounds:
- Increment gc_round in shared-memory.json
- Log team_msg with type "gc_loop_trigger"
- Unblock IDEA-fix task
5. Else: Log team_msg with type "task_unblocked", unblock SYNTH
```javascript
// Read final results
const synthesis = Read(`${sessionFolder}/synthesis/synthesis-001.md`)
const evaluation = selectedPipeline !== 'quick' ? Read(`${sessionFolder}/evaluation/evaluation-001.md`) : null
const sharedMemory = JSON.parse(Read(`${sessionFolder}/shared-memory.json`))
---
// Report to user
SendMessage({
content: `## [coordinator] 头脑风暴完成
## Phase 5: Report + Persist
**话题**: ${taskDescription}
**管道**: ${selectedPipeline}
**Generator-Critic 轮次**: ${sharedMemory.gc_round}
**创意总数**: ${sharedMemory.generated_ideas.length}
**Objective**: Completion report and follow-up options.
### 综合结果
${synthesis}
**Workflow**:
1. Load session state -> count completed tasks, duration
2. Read synthesis and evaluation results
3. Generate summary with: topic, pipeline, GC rounds, total ideas
4. Update session status -> "completed"
5. Report to user via SendMessage
6. Offer next steps via AskUserQuestion:
- New topic (continue brainstorming)
- Deep dive (analyze top-ranked idea)
- Close team (cleanup)
${evaluation ? `### 评估排序\n${evaluation}` : ''}`,
summary: `[coordinator] Brainstorm complete: ${sharedMemory.generated_ideas.length} ideas, ${sharedMemory.gc_round} GC rounds`
})
// Update session
updateSession(sessionFolder, { status: 'completed', completed_at: new Date().toISOString() })
AskUserQuestion({
questions: [{
question: "头脑风暴已完成。下一步:",
header: "Next",
multiSelect: false,
options: [
{ label: "新话题", description: "继续头脑风暴新话题" },
{ label: "深化探索", description: "对排名最高的创意进行深入分析" },
{ label: "关闭团队", description: "关闭所有 teammate 并清理" }
]
}]
})
```
---
## Error Handling
| Scenario | Resolution |
|----------|------------|
| Teammate 无响应 | 发追踪消息2次无响应 → 重新 spawn |
| Generator-Critic 循环超限 | 强制收敛到 SYNTH 阶段 |
| Ideator 无法产出 | Coordinator 提供种子问题引导 |
| Challenger 全部标记 LOW | 直接进入 SYNTH,跳过修订 |
| 综合冲突无法解决 | 上报用户,AskUserQuestion 决定方向 |
| Teammate unresponsive | Send tracking message, 2 failures -> respawn worker |
| Generator-Critic loop exceeded | Force convergence to SYNTH stage |
| Ideator cannot produce | Provide seed questions as guidance |
| Challenger all LOW severity | Skip revision, proceed directly to SYNTH |
| Synthesis conflict unresolved | Report to user, AskUserQuestion for direction |
| Session corruption | Attempt recovery, fallback to manual reconciliation |

View File

@@ -1,16 +1,14 @@
# Role: evaluator
# Evaluator Role
评分排序与最终筛选。负责对综合方案进行多维度评分、优先级推荐、生成最终排名。
## Role Identity
## Identity
- **Name**: `evaluator`
- **Name**: `evaluator` | **Tag**: `[evaluator]`
- **Task Prefix**: `EVAL-*`
- **Responsibility**: Validation (评估验证)
- **Communication**: SendMessage to coordinator only
- **Output Tag**: `[evaluator]`
- **Responsibility**: Validation (evaluation and ranking)
## Role Boundaries
## Boundaries
### MUST
@@ -19,171 +17,134 @@
- 仅通过 SendMessage 与 coordinator 通信
- Phase 2 读取 shared-memory.jsonPhase 5 写入 evaluation_scores
- 使用标准化评分维度,确保评分可追溯
- 为每个方案提供评分理由和推荐
### MUST NOT
- 生成新创意、挑战假设或综合整合
- 直接与其他 worker 角色通信
- 为其他角色创建任务
- 修改 shared-memory.json 中不属于自己的字段
- 生成新创意、挑战假设或综合整合
- 直接与其他 worker 角色通信
- 为其他角色创建任务
- 修改 shared-memory.json 中不属于自己的字段
- 在输出中省略 `[evaluator]` 标识
---
## Toolbox
### Tool Capabilities
| Tool | Type | Used By | Purpose |
|------|------|---------|---------|
| `TaskList` | Built-in | Phase 1 | Discover pending EVAL-* tasks |
| `TaskGet` | Built-in | Phase 1 | Get task details |
| `TaskUpdate` | Built-in | Phase 1/5 | Update task status |
| `Read` | Built-in | Phase 2 | Read shared-memory.json, synthesis files, ideas, critiques |
| `Write` | Built-in | Phase 3/5 | Write evaluation files, update shared memory |
| `Glob` | Built-in | Phase 2 | Find synthesis, idea, critique files |
| `SendMessage` | Built-in | Phase 5 | Report to coordinator |
| `mcp__ccw-tools__team_msg` | MCP | Phase 5 | Log communication |
---
## Message Types
| Type | Direction | Trigger | Description |
|------|-----------|---------|-------------|
| `evaluation_ready` | evaluator coordinator | Evaluation completed | 评估排序完成 |
| `error` | evaluator coordinator | Processing failure | 错误上报 |
| `evaluation_ready` | evaluator -> coordinator | Evaluation completed | Scoring and ranking complete |
| `error` | evaluator -> coordinator | Processing failure | Error report |
## Message Bus
Before every SendMessage, log via `mcp__ccw-tools__team_msg`:
```
mcp__ccw-tools__team_msg({
operation: "log",
team: **<session-id>**, // MUST be session ID (e.g., BRS-xxx-date), NOT team name. Extract from Session: field.
from: "evaluator",
to: "coordinator",
type: "evaluation_ready",
summary: "[evaluator] Evaluation complete: Top pick \"<title>\" (<score>/10)",
ref: <output-path>
})
```
**CLI fallback** (when MCP unavailable):
```
Bash("ccw team log --team <session-id> --from evaluator --to coordinator --type evaluation_ready --summary \"[evaluator] Evaluation complete\" --ref <output-path> --json")
```
---
## Execution (5-Phase)
### Phase 1: Task Discovery
```javascript
const tasks = TaskList()
const myTasks = tasks.filter(t =>
t.subject.startsWith('EVAL-') &&
t.owner === 'evaluator' &&
t.status === 'pending' &&
t.blockedBy.length === 0
)
> See SKILL.md Shared Infrastructure -> Worker Phase 1: Task Discovery
if (myTasks.length === 0) return
const task = TaskGet({ taskId: myTasks[0].id })
TaskUpdate({ taskId: task.id, status: 'in_progress' })
```
Standard task discovery flow: TaskList -> filter by prefix `EVAL-*` + owner match + pending + unblocked -> TaskGet -> TaskUpdate in_progress.
### Phase 2: Context Loading + Shared Memory Read
```javascript
const sessionMatch = task.description.match(/Session:\s*([^\n]+)/)
const sessionFolder = sessionMatch?.[1]?.trim()
| Input | Source | Required |
|-------|--------|----------|
| Session folder | Task description (Session: line) | Yes |
| Synthesis results | synthesis/*.md files | Yes |
| All ideas | ideas/*.md files | No (for context) |
| All critiques | critiques/*.md files | No (for context) |
const memoryPath = `${sessionFolder}/shared-memory.json`
let sharedMemory = {}
try { sharedMemory = JSON.parse(Read(memoryPath)) } catch {}
**Loading steps**:
// Read synthesis results
const synthesisFiles = Glob({ pattern: `${sessionFolder}/synthesis/*.md` })
const synthesis = synthesisFiles.map(f => Read(f))
1. Extract session path from task description (match "Session: <path>")
2. Glob synthesis files from session/synthesis/
3. Read all synthesis files for evaluation
4. Optionally read ideas and critiques for full context
// Read all ideas and critiques for full context
const ideaFiles = Glob({ pattern: `${sessionFolder}/ideas/*.md` })
const critiqueFiles = Glob({ pattern: `${sessionFolder}/critiques/*.md` })
### Phase 3: Evaluation and Scoring
**Scoring Dimensions**:
| Dimension | Weight | Focus |
|-----------|--------|-------|
| Feasibility | 30% | Technical feasibility, resource needs, timeline |
| Innovation | 25% | Novelty, differentiation, breakthrough potential |
| Impact | 25% | Scope of impact, value creation, problem resolution |
| Cost Efficiency | 20% | Implementation cost, risk cost, opportunity cost |
**Weighted Score Calculation**:
```
weightedScore = (Feasibility * 0.30) + (Innovation * 0.25) + (Impact * 0.25) + (Cost * 0.20)
```
### Phase 3: Evaluation & Scoring
**Evaluation Structure per Proposal**:
- Score for each dimension (1-10)
- Rationale for each score
- Overall recommendation (Strong Recommend / Recommend / Consider / Pass)
```javascript
// Scoring dimensions:
// 1. Feasibility (30%) — 技术可行性、资源需求、时间框架
// 2. Innovation (25%) — 新颖性、差异化、突破性
// 3. Impact (25%) — 影响范围、价值创造、问题解决度
// 4. Cost (20%) — 实施成本、风险成本、机会成本
const evalNum = task.subject.match(/EVAL-(\d+)/)?.[1] || '001'
const outputPath = `${sessionFolder}/evaluation/evaluation-${evalNum}.md`
const evaluationContent = `# Evaluation — Round ${evalNum}
**Input**: ${synthesisFiles.length} synthesis files
**Scoring Dimensions**: Feasibility(30%), Innovation(25%), Impact(25%), Cost(20%)
## Scoring Matrix
| Rank | Proposal | Feasibility | Innovation | Impact | Cost | **Weighted Score** |
|------|----------|-------------|------------|--------|------|-------------------|
${scoredProposals.map((p, i) => `| ${i + 1} | ${p.title} | ${p.feasibility}/10 | ${p.innovation}/10 | ${p.impact}/10 | ${p.cost}/10 | **${p.weightedScore.toFixed(1)}** |`).join('\n')}
## Detailed Evaluation
${scoredProposals.map((p, i) => `### ${i + 1}. ${p.title} (Score: ${p.weightedScore.toFixed(1)}/10)
**Feasibility** (${p.feasibility}/10):
${p.feasibilityRationale}
**Innovation** (${p.innovation}/10):
${p.innovationRationale}
**Impact** (${p.impact}/10):
${p.impactRationale}
**Cost Efficiency** (${p.cost}/10):
${p.costRationale}
**Recommendation**: ${p.recommendation}
`).join('\n')}
## Final Recommendation
**Top Pick**: ${scoredProposals[0].title}
**Runner-up**: ${scoredProposals.length > 1 ? scoredProposals[1].title : 'N/A'}
### Action Items
${actionItems.map((item, i) => `${i + 1}. ${item}`).join('\n')}
### Risk Summary
${riskSummary.map(r => `- **${r.risk}**: ${r.mitigation}`).join('\n')}
`
Write(outputPath, evaluationContent)
```
**Output file structure**:
- File: `<session>/evaluation/evaluation-<num>.md`
- Sections: Input summary, Scoring Matrix (ranked table), Detailed Evaluation per proposal, Final Recommendation, Action Items, Risk Summary
### Phase 4: Consistency Check
```javascript
// Verify scoring consistency
// - No proposal should have all 10s
// - Scores should reflect critique findings
// - Rankings should be deterministic
const maxScore = Math.max(...scoredProposals.map(p => p.weightedScore))
const minScore = Math.min(...scoredProposals.map(p => p.weightedScore))
const spread = maxScore - minScore
if (spread < 0.5 && scoredProposals.length > 1) {
// Too close — re-evaluate differentiators
}
```
| Check | Pass Criteria | Action on Failure |
|-------|---------------|-------------------|
| Score spread | max - min >= 0.5 (with >1 proposal) | Re-evaluate differentiators |
| No perfect scores | Not all 10s | Adjust scores to reflect critique findings |
| Ranking deterministic | Consistent ranking | Verify calculation |
### Phase 5: Report to Coordinator + Shared Memory Write
```javascript
sharedMemory.evaluation_scores = scoredProposals.map(p => ({
title: p.title,
weighted_score: p.weightedScore,
rank: p.rank,
recommendation: p.recommendation
}))
Write(memoryPath, JSON.stringify(sharedMemory, null, 2))
> See SKILL.md Shared Infrastructure -> Worker Phase 5: Report
mcp__ccw-tools__team_msg({
operation: "log",
team: teamName,
from: "evaluator",
to: "coordinator",
type: "evaluation_ready",
summary: `[evaluator] Evaluation complete: Top pick "${scoredProposals[0].title}" (${scoredProposals[0].weightedScore.toFixed(1)}/10)`,
ref: outputPath
})
Standard report flow: team_msg log -> SendMessage with `[evaluator]` prefix -> TaskUpdate completed -> Loop to Phase 1 for next task.
SendMessage({
type: "message",
recipient: "coordinator",
content: `## [evaluator] Evaluation Results
**Shared Memory Update**:
1. Set shared-memory.json.evaluation_scores
2. Each entry: title, weighted_score, rank, recommendation
**Task**: ${task.subject}
**Proposals Evaluated**: ${scoredProposals.length}
**Output**: ${outputPath}
### Rankings
${scoredProposals.map((p, i) => `${i + 1}. **${p.title}** — ${p.weightedScore.toFixed(1)}/10 (${p.recommendation})`).join('\n')}
### Top Pick: ${scoredProposals[0].title}
${scoredProposals[0].feasibilityRationale}`,
summary: `[evaluator] Top: ${scoredProposals[0].title} (${scoredProposals[0].weightedScore.toFixed(1)}/10)`
})
TaskUpdate({ taskId: task.id, status: 'completed' })
```
---
## Error Handling
@@ -193,3 +154,4 @@ TaskUpdate({ taskId: task.id, status: 'completed' })
| Synthesis files not found | Notify coordinator |
| Only one proposal | Evaluate against absolute criteria, recommend or reject |
| All proposals score below 5 | Flag all as weak, recommend re-brainstorming |
| Critical issue beyond scope | SendMessage error to coordinator |

View File

@@ -1,16 +1,14 @@
# Role: ideator
# Ideator Role
多角度创意生成者。负责发散思维、概念探索、创意修订。作为 Generator-Critic 循环中的 Generator 角色。
## Role Identity
## Identity
- **Name**: `ideator`
- **Name**: `ideator` | **Tag**: `[ideator]`
- **Task Prefix**: `IDEA-*`
- **Responsibility**: Read-only analysis (创意生成不修改代码)
- **Communication**: SendMessage to coordinator only
- **Output Tag**: `[ideator]`
- **Responsibility**: Read-only analysis (idea generation, no code modification)
## Role Boundaries
## Boundaries
### MUST
@@ -18,205 +16,137 @@
- 所有输出SendMessage、team_msg、日志必须带 `[ideator]` 标识
- 仅通过 SendMessage 与 coordinator 通信
- Phase 2 读取 shared-memory.jsonPhase 5 写入 generated_ideas
- 针对每个指定角度产出至少3个创意
### MUST NOT
- 执行挑战/评估/综合等其他角色工作
- 直接与其他 worker 角色通信
- 为其他角色创建任务TaskCreate 是 coordinator 专属)
- 修改 shared-memory.json 中不属于自己的字段
- 执行挑战/评估/综合等其他角色工作
- 直接与其他 worker 角色通信
- 为其他角色创建任务TaskCreate 是 coordinator 专属)
- 修改 shared-memory.json 中不属于自己的字段
- 在输出中省略 `[ideator]` 标识
---
## Toolbox
### Tool Capabilities
| Tool | Type | Used By | Purpose |
|------|------|---------|---------|
| `TaskList` | Built-in | Phase 1 | Discover pending IDEA-* tasks |
| `TaskGet` | Built-in | Phase 1 | Get task details |
| `TaskUpdate` | Built-in | Phase 1/5 | Update task status |
| `Read` | Built-in | Phase 2 | Read shared-memory.json, critique files |
| `Write` | Built-in | Phase 3/5 | Write idea files, update shared memory |
| `Glob` | Built-in | Phase 2 | Find critique files |
| `SendMessage` | Built-in | Phase 5 | Report to coordinator |
| `mcp__ccw-tools__team_msg` | MCP | Phase 5 | Log communication |
---
## Message Types
| Type | Direction | Trigger | Description |
|------|-----------|---------|-------------|
| `ideas_ready` | ideator coordinator | Initial ideas generated | 初始创意完成 |
| `ideas_revised` | ideator coordinator | Ideas revised after critique | 修订创意完成 (GC 循环) |
| `error` | ideator coordinator | Processing failure | 错误上报 |
| `ideas_ready` | ideator -> coordinator | Initial ideas generated | Initial idea generation complete |
| `ideas_revised` | ideator -> coordinator | Ideas revised after critique | Revised ideas complete (GC loop) |
| `error` | ideator -> coordinator | Processing failure | Error report |
## Message Bus
Before every SendMessage, log via `mcp__ccw-tools__team_msg`:
```
mcp__ccw-tools__team_msg({
operation: "log",
team: **<session-id>**, // MUST be session ID (e.g., BRS-xxx-date), NOT team name. Extract from Session: field.
from: "ideator",
to: "coordinator",
type: <ideas_ready|ideas_revised>,
summary: "[ideator] <Generated|Revised> <count> ideas (round <num>)",
ref: <output-path>
})
```
**CLI fallback** (when MCP unavailable):
```
Bash("ccw team log --team <session-id> --from ideator --to coordinator --type <message-type> --summary \"[ideator] ideas complete\" --ref <output-path> --json")
```
---
## Execution (5-Phase)
### Phase 1: Task Discovery
```javascript
// Parse agent name for parallel instances (e.g., ideator-1, ideator-2)
const agentNameMatch = args.match(/--agent-name[=\s]+([\w-]+)/)
const agentName = agentNameMatch ? agentNameMatch[1] : 'ideator'
> See SKILL.md Shared Infrastructure -> Worker Phase 1: Task Discovery
const tasks = TaskList()
const myTasks = tasks.filter(t =>
t.subject.startsWith('IDEA-') &&
t.owner === agentName && // Use agentName (e.g., 'ideator-1') instead of hardcoded 'ideator'
t.status === 'pending' &&
t.blockedBy.length === 0
)
Standard task discovery flow: TaskList -> filter by prefix `IDEA-*` + owner match + pending + unblocked -> TaskGet -> TaskUpdate in_progress.
if (myTasks.length === 0) return // idle
const task = TaskGet({ taskId: myTasks[0].id })
TaskUpdate({ taskId: task.id, status: 'in_progress' })
```
For parallel instances, parse `--agent-name` from arguments for owner matching. Falls back to `ideator` for single-instance roles.
### Phase 2: Context Loading + Shared Memory Read
```javascript
// Extract session folder from task description
const sessionMatch = task.description.match(/Session:\s*([^\n]+)/)
const sessionFolder = sessionMatch?.[1]?.trim()
| Input | Source | Required |
|-------|--------|----------|
| Session folder | Task description (Session: line) | Yes |
| Topic | shared-memory.json | Yes |
| Angles | shared-memory.json | Yes |
| GC Round | shared-memory.json | Yes |
| Previous critique | critiques/*.md | For revision tasks only |
| Previous ideas | shared-memory.json.generated_ideas | No |
// Read shared memory
const memoryPath = `${sessionFolder}/shared-memory.json`
let sharedMemory = {}
try { sharedMemory = JSON.parse(Read(memoryPath)) } catch {}
**Loading steps**:
const topic = sharedMemory.topic || task.description
const angles = sharedMemory.angles || ['技术', '产品', '创新']
const gcRound = sharedMemory.gc_round || 0
// If this is a revision task (GC loop), read previous critique
let previousCritique = null
if (task.subject.includes('修订') || task.subject.includes('fix')) {
const critiqueFiles = Glob({ pattern: `${sessionFolder}/critiques/*.md` })
if (critiqueFiles.length > 0) {
previousCritique = Read(critiqueFiles[critiqueFiles.length - 1])
}
}
// Read previous ideas for context
const previousIdeas = sharedMemory.generated_ideas || []
```
1. Extract session path from task description (match "Session: <path>")
2. Read shared-memory.json for topic, angles, gc_round
3. If task is revision (subject contains "revision" or "fix"):
- Glob critique files
- Read latest critique for revision context
4. Read previous ideas from shared-memory.generated_ideas
### Phase 3: Idea Generation
```javascript
// Determine generation mode
const isRevision = !!previousCritique
| Mode | Condition | Focus |
|------|-----------|-------|
| Initial Generation | No previous critique | Multi-angle divergent thinking |
| GC Revision | Previous critique exists | Address HIGH/CRITICAL challenges |
if (isRevision) {
// === Generator-Critic Revision Mode ===
// Focus on HIGH/CRITICAL severity challenges
// Revise or replace challenged ideas
// Keep unchallenged ideas intact
// Output structure:
// - Retained ideas (unchallenged)
// - Revised ideas (with revision rationale)
// - New replacement ideas (for unsalvageable ones)
} else {
// === Initial Generation Mode ===
// For each angle, generate 3+ ideas
// Each idea includes:
// - Title
// - Description (2-3 sentences)
// - Key assumption
// - Potential impact
// - Implementation hint
}
**Initial Generation Mode**:
- For each angle, generate 3+ ideas
- Each idea includes: title, description (2-3 sentences), key assumption, potential impact, implementation hint
// Write ideas to file
const ideaNum = task.subject.match(/IDEA-(\d+)/)?.[1] || '001'
const outputPath = `${sessionFolder}/ideas/idea-${ideaNum}.md`
**GC Revision Mode**:
- Focus on HIGH/CRITICAL severity challenges from critique
- Retain unchallenged ideas intact
- Revise ideas with revision rationale
- Replace unsalvageable ideas with new alternatives
const ideaContent = `# ${isRevision ? 'Revised' : 'Initial'} Ideas — Round ${ideaNum}
**Topic**: ${topic}
**Angles**: ${angles.join(', ')}
**Mode**: ${isRevision ? 'Generator-Critic Revision (Round ' + gcRound + ')' : 'Initial Generation'}
${isRevision ? `## Revision Context\n\nBased on critique feedback:\n${previousCritique}\n\n` : ''}
## Ideas
${generatedIdeas.map((idea, i) => `### Idea ${i + 1}: ${idea.title}
**Description**: ${idea.description}
**Key Assumption**: ${idea.assumption}
**Potential Impact**: ${idea.impact}
**Implementation Hint**: ${idea.implementation}
${isRevision ? `**Revision Note**: ${idea.revision_note || 'New idea'}` : ''}
`).join('\n')}
## Summary
- Total ideas: ${generatedIdeas.length}
- ${isRevision ? `Retained: ${retainedCount}, Revised: ${revisedCount}, New: ${newCount}` : `Per angle: ${angles.map(a => `${a}: ${countByAngle[a]}`).join(', ')}`}
`
Write(outputPath, ideaContent)
```
**Output file structure**:
- File: `<session>/ideas/idea-<num>.md`
- Sections: Topic, Angles, Mode, [Revision Context if applicable], Ideas list, Summary
### Phase 4: Self-Review
```javascript
// Verify minimum idea count
const ideaCount = generatedIdeas.length
const minimumRequired = isRevision ? 3 : 6
if (ideaCount < minimumRequired) {
// Generate additional ideas to meet minimum
}
// Verify no duplicate ideas
const titles = generatedIdeas.map(i => i.title.toLowerCase())
const duplicates = titles.filter((t, i) => titles.indexOf(t) !== i)
if (duplicates.length > 0) {
// Replace duplicates
}
```
| Check | Pass Criteria | Action on Failure |
|-------|---------------|-------------------|
| Minimum count | >= 6 (initial) or >= 3 (revision) | Generate additional ideas |
| No duplicates | All titles unique | Replace duplicates |
| Angle coverage | At least 1 idea per angle | Generate missing angle ideas |
### Phase 5: Report to Coordinator + Shared Memory Write
```javascript
// Update shared memory
sharedMemory.generated_ideas = [
...sharedMemory.generated_ideas,
...generatedIdeas.map(i => ({
id: `idea-${ideaNum}-${i.index}`,
title: i.title,
round: parseInt(ideaNum),
revised: isRevision
}))
]
Write(memoryPath, JSON.stringify(sharedMemory, null, 2))
> See SKILL.md Shared Infrastructure -> Worker Phase 5: Report
// Log message
mcp__ccw-tools__team_msg({
operation: "log",
team: teamName,
from: "ideator",
to: "coordinator",
type: isRevision ? "ideas_revised" : "ideas_ready",
summary: `[ideator] ${isRevision ? 'Revised' : 'Generated'} ${ideaCount} ideas (round ${ideaNum})`,
ref: outputPath
})
Standard report flow: team_msg log -> SendMessage with `[ideator]` prefix -> TaskUpdate completed -> Loop to Phase 1 for next task.
SendMessage({
type: "message",
recipient: "coordinator",
content: `## [ideator] ${isRevision ? 'Ideas Revised' : 'Ideas Generated'}
**Shared Memory Update**:
1. Append new ideas to shared-memory.json.generated_ideas
2. Each entry: id, title, round, revised flag
**Task**: ${task.subject}
**Ideas**: ${ideaCount}
**Output**: ${outputPath}
### Highlights
${generatedIdeas.slice(0, 3).map(i => `- **${i.title}**: ${i.description.substring(0, 100)}...`).join('\n')}`,
summary: `[ideator] ${ideaCount} ideas ${isRevision ? 'revised' : 'generated'}`
})
TaskUpdate({ taskId: task.id, status: 'completed' })
// Check for next task
const nextTasks = TaskList().filter(t =>
t.subject.startsWith('IDEA-') &&
t.owner === agentName && // Use agentName for parallel instance filtering
t.status === 'pending' &&
t.blockedBy.length === 0
)
if (nextTasks.length > 0) {
// Continue with next task → back to Phase 1
}
```
---
## Error Handling
@@ -226,4 +156,5 @@ if (nextTasks.length > 0) {
| Session folder not found | Notify coordinator, request path |
| Shared memory read fails | Initialize empty, proceed with generation |
| Topic too vague | Generate meta-questions as seed ideas |
| Previous critique not found (revision) | Generate new ideas instead of revising |
| Previous critique not found (revision task) | Generate new ideas instead of revising |
| Critical issue beyond scope | SendMessage error to coordinator |

View File

@@ -1,16 +1,14 @@
# Role: synthesizer
# Synthesizer Role
跨想法整合者。负责从多个创意和挑战反馈中提取主题、解决冲突、生成整合方案。
## Role Identity
## Identity
- **Name**: `synthesizer`
- **Name**: `synthesizer` | **Tag**: `[synthesizer]`
- **Task Prefix**: `SYNTH-*`
- **Responsibility**: Read-only analysis (综合整合)
- **Communication**: SendMessage to coordinator only
- **Output Tag**: `[synthesizer]`
- **Responsibility**: Read-only analysis (synthesis and integration)
## Role Boundaries
## Boundaries
### MUST
@@ -18,182 +16,146 @@
- 所有输出必须带 `[synthesizer]` 标识
- 仅通过 SendMessage 与 coordinator 通信
- Phase 2 读取 shared-memory.jsonPhase 5 写入 synthesis_themes
- 从所有创意和挑战中提取共同主题
- 解决相互矛盾的想法,生成整合方案
### MUST NOT
- 生成新创意、挑战假设或评分排序
- 直接与其他 worker 角色通信
- 为其他角色创建任务
- 修改 shared-memory.json 中不属于自己的字段
- 生成新创意、挑战假设或评分排序
- 直接与其他 worker 角色通信
- 为其他角色创建任务
- 修改 shared-memory.json 中不属于自己的字段
- 在输出中省略 `[synthesizer]` 标识
---
## Toolbox
### Tool Capabilities
| Tool | Type | Used By | Purpose |
|------|------|---------|---------|
| `TaskList` | Built-in | Phase 1 | Discover pending SYNTH-* tasks |
| `TaskGet` | Built-in | Phase 1 | Get task details |
| `TaskUpdate` | Built-in | Phase 1/5 | Update task status |
| `Read` | Built-in | Phase 2 | Read shared-memory.json, idea files, critique files |
| `Write` | Built-in | Phase 3/5 | Write synthesis files, update shared memory |
| `Glob` | Built-in | Phase 2 | Find idea and critique files |
| `SendMessage` | Built-in | Phase 5 | Report to coordinator |
| `mcp__ccw-tools__team_msg` | MCP | Phase 5 | Log communication |
---
## Message Types
| Type | Direction | Trigger | Description |
|------|-----------|---------|-------------|
| `synthesis_ready` | synthesizer coordinator | Synthesis completed | 综合整合完成 |
| `error` | synthesizer coordinator | Processing failure | 错误上报 |
| `synthesis_ready` | synthesizer -> coordinator | Synthesis completed | Cross-idea synthesis complete |
| `error` | synthesizer -> coordinator | Processing failure | Error report |
## Message Bus
Before every SendMessage, log via `mcp__ccw-tools__team_msg`:
```
mcp__ccw-tools__team_msg({
operation: "log",
team: **<session-id>**, // MUST be session ID (e.g., BRS-xxx-date), NOT team name. Extract from Session: field.
from: "synthesizer",
to: "coordinator",
type: "synthesis_ready",
summary: "[synthesizer] Synthesis complete: <themeCount> themes, <proposalCount> proposals",
ref: <output-path>
})
```
**CLI fallback** (when MCP unavailable):
```
Bash("ccw team log --team <session-id> --from synthesizer --to coordinator --type synthesis_ready --summary \"[synthesizer] Synthesis complete\" --ref <output-path> --json")
```
---
## Execution (5-Phase)
### Phase 1: Task Discovery
```javascript
const tasks = TaskList()
const myTasks = tasks.filter(t =>
t.subject.startsWith('SYNTH-') &&
t.owner === 'synthesizer' &&
t.status === 'pending' &&
t.blockedBy.length === 0
)
> See SKILL.md Shared Infrastructure -> Worker Phase 1: Task Discovery
if (myTasks.length === 0) return
const task = TaskGet({ taskId: myTasks[0].id })
TaskUpdate({ taskId: task.id, status: 'in_progress' })
```
Standard task discovery flow: TaskList -> filter by prefix `SYNTH-*` + owner match + pending + unblocked -> TaskGet -> TaskUpdate in_progress.
### Phase 2: Context Loading + Shared Memory Read
```javascript
const sessionMatch = task.description.match(/Session:\s*([^\n]+)/)
const sessionFolder = sessionMatch?.[1]?.trim()
| Input | Source | Required |
|-------|--------|----------|
| Session folder | Task description (Session: line) | Yes |
| All ideas | ideas/*.md files | Yes |
| All critiques | critiques/*.md files | Yes |
| GC rounds completed | shared-memory.json.gc_round | Yes |
const memoryPath = `${sessionFolder}/shared-memory.json`
let sharedMemory = {}
try { sharedMemory = JSON.parse(Read(memoryPath)) } catch {}
**Loading steps**:
// Read all ideas and critiques
const ideaFiles = Glob({ pattern: `${sessionFolder}/ideas/*.md` })
const critiqueFiles = Glob({ pattern: `${sessionFolder}/critiques/*.md` })
const allIdeas = ideaFiles.map(f => Read(f))
const allCritiques = critiqueFiles.map(f => Read(f))
```
1. Extract session path from task description (match "Session: <path>")
2. Glob all idea files from session/ideas/
3. Glob all critique files from session/critiques/
4. Read all idea and critique files for synthesis
5. Read shared-memory.json for context
### Phase 3: Synthesis Execution
```javascript
// Synthesis process:
// 1. Theme Extraction — 识别跨创意的共同主题
// 2. Conflict Resolution — 解决相互矛盾的想法
// 3. Complementary Grouping — 将互补的创意组合
// 4. Gap Identification — 发现未覆盖的视角
// 5. Integrated Proposal — 生成1-3个整合方案
**Synthesis Process**:
const synthNum = task.subject.match(/SYNTH-(\d+)/)?.[1] || '001'
const outputPath = `${sessionFolder}/synthesis/synthesis-${synthNum}.md`
| Step | Action |
|------|--------|
| 1. Theme Extraction | Identify common themes across ideas |
| 2. Conflict Resolution | Resolve contradictory ideas |
| 3. Complementary Grouping | Group complementary ideas together |
| 4. Gap Identification | Discover uncovered perspectives |
| 5. Integrated Proposal | Generate 1-3 consolidated proposals |
const synthesisContent = `# Synthesis — Round ${synthNum}
**Theme Extraction**:
- Cross-reference ideas for shared concepts
- Rate theme strength (1-10)
- List supporting ideas per theme
**Input**: ${ideaFiles.length} idea files, ${critiqueFiles.length} critique files
**GC Rounds Completed**: ${sharedMemory.gc_round || 0}
**Conflict Resolution**:
- Identify contradictory ideas
- Determine resolution approach
- Document rationale for resolution
## Extracted Themes
**Integrated Proposal Structure**:
- Core concept description
- Source ideas combined
- Addressed challenges from critiques
- Feasibility score (1-10)
- Innovation score (1-10)
- Key benefits list
- Remaining risks list
${themes.map((theme, i) => `### Theme ${i + 1}: ${theme.name}
**Description**: ${theme.description}
**Supporting Ideas**: ${theme.supportingIdeas.join(', ')}
**Strength**: ${theme.strength}/10
`).join('\n')}
## Conflict Resolution
${conflicts.map(c => `### ${c.idea1} vs ${c.idea2}
**Nature**: ${c.nature}
**Resolution**: ${c.resolution}
**Rationale**: ${c.rationale}
`).join('\n')}
## Integrated Proposals
${proposals.map((p, i) => `### Proposal ${i + 1}: ${p.title}
**Core Concept**: ${p.concept}
**Combines**: ${p.sourceIdeas.join(' + ')}
**Addresses Challenges**: ${p.addressedChallenges.join(', ')}
**Feasibility**: ${p.feasibility}/10
**Innovation**: ${p.innovation}/10
**Description**:
${p.description}
**Key Benefits**:
${p.benefits.map(b => `- ${b}`).join('\n')}
**Remaining Risks**:
${p.risks.map(r => `- ${r}`).join('\n')}
`).join('\n')}
## Coverage Analysis
| Aspect | Covered | Gaps |
|--------|---------|------|
${coverageAnalysis.map(a => `| ${a.aspect} | ${a.covered ? '✅' : '❌'} | ${a.gap || '—'} |`).join('\n')}
`
Write(outputPath, synthesisContent)
```
**Output file structure**:
- File: `<session>/synthesis/synthesis-<num>.md`
- Sections: Input summary, Extracted Themes, Conflict Resolution, Integrated Proposals, Coverage Analysis
### Phase 4: Quality Check
```javascript
// Verify synthesis quality
const proposalCount = proposals.length
const themeCount = themes.length
if (proposalCount === 0) {
// At least one proposal required
}
if (themeCount < 2) {
// May need to look for more patterns
}
```
| Check | Pass Criteria | Action on Failure |
|-------|---------------|-------------------|
| Proposal count | >= 1 proposal | Generate at least one proposal |
| Theme count | >= 2 themes | Look for more patterns |
| Conflict resolution | All conflicts documented | Address unresolved conflicts |
### Phase 5: Report to Coordinator + Shared Memory Write
```javascript
sharedMemory.synthesis_themes = themes.map(t => ({
name: t.name,
strength: t.strength,
supporting_ideas: t.supportingIdeas
}))
Write(memoryPath, JSON.stringify(sharedMemory, null, 2))
> See SKILL.md Shared Infrastructure -> Worker Phase 5: Report
mcp__ccw-tools__team_msg({
operation: "log",
team: teamName,
from: "synthesizer",
to: "coordinator",
type: "synthesis_ready",
summary: `[synthesizer] Synthesis complete: ${themeCount} themes, ${proposalCount} proposals`,
ref: outputPath
})
Standard report flow: team_msg log -> SendMessage with `[synthesizer]` prefix -> TaskUpdate completed -> Loop to Phase 1 for next task.
SendMessage({
type: "message",
recipient: "coordinator",
content: `## [synthesizer] Synthesis Results
**Shared Memory Update**:
1. Set shared-memory.json.synthesis_themes
2. Each entry: name, strength, supporting_ideas
**Task**: ${task.subject}
**Themes**: ${themeCount}
**Proposals**: ${proposalCount}
**Conflicts Resolved**: ${conflicts.length}
**Output**: ${outputPath}
### Top Proposals
${proposals.slice(0, 3).map((p, i) => `${i + 1}. **${p.title}** — ${p.concept} (Feasibility: ${p.feasibility}/10, Innovation: ${p.innovation}/10)`).join('\n')}`,
summary: `[synthesizer] ${themeCount} themes, ${proposalCount} proposals`
})
TaskUpdate({ taskId: task.id, status: 'completed' })
const nextTasks = TaskList().filter(t =>
t.subject.startsWith('SYNTH-') && t.owner === 'synthesizer' &&
t.status === 'pending' && t.blockedBy.length === 0
)
if (nextTasks.length > 0) { /* back to Phase 1 */ }
```
---
## Error Handling
@@ -203,3 +165,4 @@ if (nextTasks.length > 0) { /* back to Phase 1 */ }
| No ideas/critiques found | Notify coordinator |
| Irreconcilable conflicts | Present both sides, recommend user decision |
| Only one idea survives | Create single focused proposal |
| Critical issue beyond scope | SendMessage error to coordinator |

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@@ -0,0 +1,179 @@
# Dynamic Role-Spec Template
Template used by coordinator to generate lightweight worker role-spec files at runtime. Each generated role-spec is written to `<session>/role-specs/<role-name>.md`.
**Key difference from v1**: Role-specs contain ONLY Phase 2-4 domain logic + YAML frontmatter. All shared behavior (Phase 1 Task Discovery, Phase 5 Report/Fast-Advance, Message Bus, Consensus, Inner Loop) is built into the `team-worker` agent.
## Template
```markdown
---
role: <role_name>
prefix: <PREFIX>
inner_loop: <true|false>
subagents: [<subagent-names>]
message_types:
success: <prefix>_complete
error: error
---
# <Role Name> — Phase 2-4
## Phase 2: <phase2_name>
<phase2_content>
## Phase 3: <phase3_name>
<phase3_content>
## Phase 4: <phase4_name>
<phase4_content>
## Error Handling
| Scenario | Resolution |
|----------|------------|
<error_entries>
```
## Frontmatter Fields
| Field | Required | Description |
|-------|----------|-------------|
| `role` | Yes | Role name matching session registry |
| `prefix` | Yes | Task prefix to filter (e.g., RESEARCH, DRAFT, IMPL) |
| `inner_loop` | Yes | Whether team-worker loops through same-prefix tasks |
| `subagents` | No | Array of subagent types this role may call |
| `message_types` | Yes | Message type mapping for team_msg |
| `message_types.success` | Yes | Type string for successful completion |
| `message_types.error` | Yes | Type string for errors (usually "error") |
## Design Rules
| Rule | Description |
|------|-------------|
| Phase 2-4 only | No Phase 1 (Task Discovery) or Phase 5 (Report) — team-worker handles these |
| No message bus code | No team_msg calls — team-worker handles logging |
| No consensus handling | No consensus_reached/blocked logic — team-worker handles routing |
| No inner loop logic | No Phase 5-L/5-F — team-worker handles looping |
| ~80 lines target | Lightweight, domain-focused |
| No pseudocode | Decision tables + text + tool calls only |
| `<placeholder>` notation | Use angle brackets for variable substitution |
| Reference subagents by name | team-worker resolves invocation from its delegation templates |
## Behavioral Traits
All dynamically generated role-specs MUST embed these traits into Phase 4. Coordinator copies this section verbatim into every generated role-spec as a Phase 4 appendix.
**Design principle**: Constrain behavioral characteristics (accuracy, feedback, quality gates), NOT specific actions (which tool, which subagent, which path). Tasks are diverse — the coordinator composes task-specific Phase 2-3 instructions, while these traits ensure execution quality regardless of task type.
### Accuracy — outputs must be verifiable
- Files claimed as **created** → Read to confirm file exists and has content
- Files claimed as **modified** → Read to confirm content actually changed
- Analysis claimed as **complete** → artifact file exists in `<session>/artifacts/`
### Feedback Contract — completion report must include evidence
Phase 4 must produce a verification summary with these fields:
| Field | When Required | Content |
|-------|---------------|---------|
| `files_produced` | New files created | Path list |
| `files_modified` | Existing files changed | Path + before/after line count |
| `artifacts_written` | Always | Paths in `<session>/artifacts/` |
| `verification_method` | Always | How verified: Read confirm / syntax check / diff |
### Quality Gate — verify before reporting complete
- Phase 4 MUST verify Phase 3's **actual output** (not planned output)
- Verification fails → retry Phase 3 (max 2 retries)
- Still fails → report `partial_completion` with details, NOT `completed`
- Update `shared-memory.json` with key findings after verification passes
### Error Protocol
- Primary approach fails → try alternative (different subagent / different tool)
- 2 retries exhausted → escalate to coordinator with failure details
- NEVER: skip verification and report completed
---
## Reference Patterns
Coordinator MAY reference these patterns when composing Phase 2-4 content for a role-spec. These are **structural guidance, not mandatory templates**. The task description determines specific behavior — patterns only suggest common phase structures.
### Research / Exploration
- Phase 2: Define exploration scope + load prior knowledge from shared-memory and wisdom
- Phase 3: Explore via subagents, direct tool calls, or codebase search — approach chosen by agent
- Phase 4: Verify findings documented (Behavioral Traits) + update shared-memory
### Document / Content
- Phase 2: Load upstream artifacts + read target files (if modifying existing docs)
- Phase 3: Create new documents OR modify existing documents — determined by task, not template
- Phase 4: Verify documents exist with expected content (Behavioral Traits) + update shared-memory
### Code Implementation
- Phase 2: Load design/spec artifacts from upstream
- Phase 3: Implement code changes — subagent choice and approach determined by task complexity
- Phase 4: Syntax check + file verification (Behavioral Traits) + update shared-memory
### Analysis / Audit
- Phase 2: Load analysis targets (artifacts or source files)
- Phase 3: Multi-dimension analysis — perspectives and depth determined by task
- Phase 4: Verify report exists + severity classification (Behavioral Traits) + update shared-memory
### Validation / Testing
- Phase 2: Detect test framework + identify changed files from upstream
- Phase 3: Run test-fix cycle — iteration count and strategy determined by task
- Phase 4: Verify pass rate + coverage (Behavioral Traits) + update shared-memory
---
## Knowledge Transfer Protocol
How context flows between roles. Coordinator MUST reference this when composing Phase 2 of any role-spec.
### Transfer Channels
| Channel | Scope | Mechanism | When to Use |
|---------|-------|-----------|-------------|
| **Artifacts** | Producer -> Consumer | Write to `<session>/artifacts/<name>.md`, consumer reads in Phase 2 | Structured deliverables (reports, plans, specs) |
| **shared-memory.json** | Cross-role | Read-merge-write `<session>/shared-memory.json` | Key findings, decisions, metadata (small, structured data) |
| **Wisdom** | Cross-task | Append to `<session>/wisdom/{learnings,decisions,conventions,issues}.md` | Patterns, conventions, risks discovered during execution |
| **context_accumulator** | Intra-role (inner loop) | In-memory array, passed to each subsequent task in same-prefix loop | Prior task summaries within same role's inner loop |
| **Exploration cache** | Cross-role | `<session>/explorations/cache-index.json` + per-angle JSON | Codebase discovery results, prevents duplicate exploration |
### Phase 2 Context Loading (role-spec must specify)
Every generated role-spec Phase 2 MUST declare which upstream sources to load:
```
1. Extract session path from task description
2. Read upstream artifacts: <list which artifacts from which upstream role>
3. Read shared-memory.json for cross-role decisions
4. Load wisdom files for accumulated knowledge
5. For inner_loop roles: load context_accumulator from prior tasks
6. Check exploration cache before running new explorations
```
### shared-memory.json Usage Convention
- **Read-merge-write**: Read current content -> merge new keys -> write back (NOT overwrite)
- **Namespaced keys**: Each role writes under its own namespace: `{ "<role_name>": { ... } }`
- **Small data only**: Key findings, decision summaries, metadata. NOT full documents
- **Example**:
```json
{
"researcher": { "key_findings": [...], "scope": "..." },
"writer": { "documents_created": [...], "style_decisions": [...] },
"developer": { "files_changed": [...], "patterns_used": [...] }
}
```

View File

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

View File

@@ -0,0 +1,120 @@
# Explore Subagent
Shared codebase exploration utility with centralized caching. Callable by any role needing code context.
## Invocation
```
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
## Exploration
<angle-specific-focus-from-table-below>
## Output
Write JSON to: <session-folder>/explorations/explore-<angle>.json
Update cache-index.json with new entry
## Output Schema
{
"angle": "<angle>",
"query": "<query>",
"relevant_files": [
{ "path": "...", "rationale": "...", "role": "...", "discovery_source": "...", "key_symbols": [] }
],
"patterns": [],
"dependencies": [],
"external_refs": [],
"_metadata": { "created_by": "<calling-role>", "timestamp": "...", "cache_key": "..." }
}
Return summary: file count, pattern count, top 5 files, output path`
})
```
## Cache Mechanism
### Cache Index Schema
`<session-folder>/explorations/cache-index.json`:
```json
{
"entries": [
{
"angle": "architecture",
"keywords": ["auth", "middleware"],
"file": "explore-architecture.json",
"created_by": "analyst",
"created_at": "2026-02-27T10:00:00Z",
"file_count": 15
}
]
}
```
### Cache Lookup Rules
| Condition | Action |
|-----------|--------|
| Exact angle match exists | Return cached result |
| No match | Execute exploration, cache result |
| Cache file missing but index has entry | Remove stale entry, re-explore |
### Cache Invalidation
Cache is session-scoped. No explicit invalidation needed -- each session starts fresh. If a role suspects stale data, it can pass `force_refresh: true` in the prompt to bypass cache.
## Angle Focus Guide
| Angle | Focus Points | Typical Caller |
|-------|-------------|----------------|
| architecture | Layer boundaries, design patterns, component responsibilities, ADRs | any |
| dependencies | Import chains, external libraries, circular dependencies, shared utilities | any |
| modularity | Module interfaces, separation of concerns, extraction opportunities | any |
| integration-points | API endpoints, data flow between modules, event systems | any |
| security | Auth/authz logic, input validation, sensitive data handling, middleware | any |
| dataflow | Data transformations, state propagation, validation points | any |
| performance | Bottlenecks, N+1 queries, blocking operations, algorithm complexity | any |
| error-handling | Try-catch blocks, error propagation, recovery strategies, logging | any |
| patterns | Code conventions, design patterns, naming conventions, best practices | any |
| testing | Test files, coverage gaps, test patterns, mocking strategies | any |
| general | Broad semantic search for topic-related code | any |
## Exploration Strategies
### Low Complexity (direct search)
For simple queries, use ACE semantic search:
```
mcp__ace-tool__search_context(project_root_path="<project-root>", query="<query>")
```
ACE failure fallback: `rg -l '<keywords>' --type ts`
### Medium/High Complexity (multi-angle)
For complex queries, call cli-explore-agent per angle. The calling role determines complexity and selects angles.
## Search Tool Priority
| Tool | Priority | Use Case |
|------|----------|----------|
| mcp__ace-tool__search_context | P0 | Semantic search |
| Grep / Glob | P1 | Pattern matching |
| cli-explore-agent | Deep | Multi-angle exploration |
| WebSearch | P3 | External docs |

View File

@@ -0,0 +1,445 @@
---
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".
allowed-tools: TeamCreate(*), TeamDelete(*), SendMessage(*), TaskCreate(*), TaskUpdate(*), TaskList(*), TaskGet(*), Task(*), AskUserQuestion(*), Read(*), Write(*), Edit(*), Bash(*), Glob(*), Grep(*)
---
# Team Coordinate
Universal team coordination skill: analyze task -> generate roles -> dispatch -> execute -> deliver. Only the **coordinator** is built-in. All worker roles are **dynamically generated** based on task analysis.
## Architecture
```
+---------------------------------------------------+
| Skill(skill="team-coordinate") |
| args="task description" |
| args="--role=coordinator" |
| args="--role=<dynamic> --session=<path>" |
+-------------------+-------------------------------+
| Role Router
+---- --role present? ----+
| NO | YES
v v
Orchestration Mode Role Dispatch
(auto -> coordinator) (route to role file)
| |
coordinator +-------+-------+
(built-in) | --role=coordinator?
| |
YES | | NO
v | v
built-in | Dynamic Role
role.md | <session>/roles/<role>.md
Subagents (callable by any role, not team members):
[discuss-subagent] - multi-perspective critique (dynamic perspectives)
[explore-subagent] - codebase exploration with cache
```
## Role Router
### Input Parsing
Parse `$ARGUMENTS` to extract `--role` and `--session`. If no `--role` -> Orchestration Mode (auto route to coordinator).
### Role Registry
Only coordinator is statically registered. All other roles are dynamic, stored in `team-session.json#roles`.
| Role | File | Type |
|------|------|------|
| coordinator | [roles/coordinator/role.md](roles/coordinator/role.md) | built-in orchestrator |
| (dynamic) | `<session>/roles/<role-name>.md` | runtime-generated worker |
> **COMPACT PROTECTION**: Role files are execution documents. After context compression, role instructions become summaries only -- **MUST immediately `Read` the role.md to reload before continuing**. Never execute any Phase based on summaries.
### Subagent Registry
| Subagent | Spec | Callable By | Purpose |
|----------|------|-------------|---------|
| discuss | [subagents/discuss-subagent.md](subagents/discuss-subagent.md) | any role | Multi-perspective critique (dynamic perspectives) |
| explore | [subagents/explore-subagent.md](subagents/explore-subagent.md) | any role | Codebase exploration with cache |
### Dispatch
1. Extract `--role` and `--session` from arguments
2. If no `--role` -> route to coordinator (Orchestration Mode)
3. If `--role=coordinator` -> Read built-in `roles/coordinator/role.md` -> Execute its phases
4. If `--role=<other>`:
- **`--session` is REQUIRED** for dynamic roles. Error if not provided.
- Read `<session>/roles/<role>.md` -> Execute its phases
- If role file not found at path -> Error with expected path
### Orchestration Mode
When invoked without `--role`, coordinator auto-starts. User just provides task description.
**Invocation**: `Skill(skill="team-coordinate", args="task description")`
**Lifecycle**:
```
User provides task description
-> coordinator Phase 1: task analysis (detect capabilities, build dependency graph)
-> coordinator Phase 2: generate roles + initialize session
-> coordinator Phase 3: create task chain from dependency graph
-> coordinator Phase 4: spawn first batch workers (background) -> STOP
-> Worker executes -> SendMessage callback -> coordinator advances next step
-> Loop until pipeline complete -> Phase 5 report
```
**User Commands** (wake paused coordinator):
| Command | Action |
|---------|--------|
| `check` / `status` | Output execution status graph, no advancement |
| `resume` / `continue` | Check worker states, advance next step |
---
## Shared Infrastructure
The following templates apply to all worker roles. Each generated role.md only needs to define **Phase 2-4** role-specific logic.
### Worker Phase 1: Task Discovery (all workers shared)
Each worker on startup executes the same task discovery flow:
1. Call `TaskList()` to get all tasks
2. Filter: subject matches this role's prefix + owner is this role + status is pending + blockedBy is empty
3. No tasks -> idle wait
4. Has tasks -> `TaskGet` for details -> `TaskUpdate` mark in_progress
**Resume Artifact Check** (prevent duplicate output after resume):
- Check if this task's output artifacts already exist
- Artifacts complete -> skip to Phase 5 report completion
- Artifacts incomplete or missing -> normal Phase 2-4 execution
### Worker Phase 5: Report + Fast-Advance (all workers shared)
Task completion with optional fast-advance to skip coordinator round-trip:
1. **Message Bus**: Call `mcp__ccw-tools__team_msg` to log message
- Params: operation="log", team=**<session-id>**, from=<role>, to="coordinator", type=<message-type>, summary="[<role>] <summary>", ref=<artifact-path>
- **`team` must be session ID** (e.g., `TC-my-project-2026-02-27`), NOT team name. Extract from task description `Session:` field -> take folder name.
- **CLI fallback**: `ccw team log --team <session-id> --from <role> --to coordinator --type <type> --summary "[<role>] ..." --json`
2. **TaskUpdate**: Mark task completed
3. **Fast-Advance Check**:
- Call `TaskList()`, find pending tasks whose blockedBy are ALL completed
- If exactly 1 ready task AND its owner matches a simple successor pattern -> **spawn it directly** (skip coordinator)
- Otherwise -> **SendMessage** to coordinator for orchestration
4. **Loop**: Back to Phase 1 to check for next task
**Fast-Advance Rules**:
| Condition | Action |
|-----------|--------|
| Same-prefix successor (Inner Loop role) | Do not spawn, main agent inner loop (Phase 5-L) |
| 1 ready task, simple linear successor, different prefix | Spawn directly via Task(run_in_background: true) |
| 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) |
**Fast-advance failure recovery**: If a fast-advanced task fails, the coordinator detects it as an orphaned in_progress task on next `resume`/`check` and resets it to pending for re-spawn. Self-healing. See [monitor.md](roles/coordinator/commands/monitor.md).
### Worker Inner Loop (roles with multiple same-prefix serial tasks)
When a role has **2+ serial same-prefix tasks**, it loops internally instead of spawning new agents:
**Inner Loop flow**:
```
Phase 1: Discover task (first time)
|
+- Found task -> Phase 2-3: Load context + Execute work
| |
| v
| Phase 4: Validation (+ optional Inline Discuss)
| |
| v
| Phase 5-L: Loop Completion
| |
| +- TaskUpdate completed
| +- team_msg log
| +- Accumulate summary to context_accumulator
| |
| +- More same-prefix tasks?
| | +- YES -> back to Phase 1 (inner loop)
| | +- NO -> Phase 5-F: Final Report
| |
| +- Interrupt conditions?
| +- consensus_blocked HIGH -> SendMessage -> STOP
| +- Errors >= 3 -> SendMessage -> STOP
|
+- Phase 5-F: Final Report
+- SendMessage (all task summaries)
+- STOP
```
**Phase 5-L vs Phase 5-F**:
| Step | Phase 5-L (looping) | Phase 5-F (final) |
|------|---------------------|-------------------|
| TaskUpdate completed | YES | YES |
| team_msg log | YES | YES |
| Accumulate summary | YES | - |
| SendMessage to coordinator | NO | YES (all tasks summary) |
| Fast-Advance to next prefix | - | YES (check cross-prefix successors) |
### Inline Discuss Protocol (optional for any role)
After completing primary output, roles may call the discuss subagent inline. Unlike v4's fixed perspective definitions, team-coordinate uses **dynamic perspectives** specified by the coordinator when generating each role.
```
Task({
subagent_type: "cli-discuss-agent",
run_in_background: false,
description: "Discuss <round-id>",
prompt: <see subagents/discuss-subagent.md for prompt template>
})
```
**Consensus handling**:
| Verdict | Severity | Role Action |
|---------|----------|-------------|
| consensus_reached | - | Include action items in report, proceed to Phase 5 |
| consensus_blocked | HIGH | SendMessage with structured format. Do NOT self-revise. |
| consensus_blocked | MEDIUM | SendMessage with warning. Proceed normally. |
| consensus_blocked | LOW | Treat as consensus_reached with notes. |
### Shared Explore Utility
Any role needing codebase context calls the explore subagent:
```
Task({
subagent_type: "cli-explore-agent",
run_in_background: false,
description: "Explore <angle>",
prompt: <see subagents/explore-subagent.md for prompt template>
})
```
**Cache**: Results stored in `explorations/` with `cache-index.json`. Before exploring, always check cache first.
### Wisdom Accumulation (all roles)
Cross-task knowledge accumulation. Coordinator creates `wisdom/` directory at session init.
**Directory**:
```
<session-folder>/wisdom/
+-- learnings.md # Patterns and insights
+-- decisions.md # Design and strategy decisions
+-- issues.md # Known risks and issues
```
**Worker load** (Phase 2): Extract `Session: <path>` from task description, read wisdom files.
**Worker contribute** (Phase 4/5): Write discoveries to corresponding wisdom files.
### Role Isolation Rules
| Allowed | Prohibited |
|---------|-----------|
| Process own prefix tasks | Process other role's prefix tasks |
| SendMessage to coordinator | Directly communicate with other workers |
| Use tools appropriate to responsibility | Create tasks for other roles |
| Call discuss/explore subagents | Modify resources outside own scope |
| Fast-advance simple successors | Spawn parallel worker batches |
| Report capability_gap to coordinator | Attempt work outside scope |
Coordinator additionally prohibited: directly write/modify deliverable artifacts, call implementation subagents directly, directly execute analysis/test/review.
---
## 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 ---+--> [Worker A] Phase 1-5
| (parallel OK) --+--> [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 Worker B directly
+- complex case? --> SendMessage to coordinator
======================================================================
```
**Pipelines are dynamic**: Unlike v4's predefined pipeline beat views (spec-only, impl-only, etc.), team-coordinate pipelines are generated per-task from the dependency graph. The beat model is the same -- only the pipeline shape varies.
---
## Coordinator Spawn Template
### Standard Worker (single-task role)
```
Task({
subagent_type: "general-purpose",
description: "Spawn <role> worker",
team_name: <team-name>,
name: "<role>",
run_in_background: true,
prompt: `You are team "<team-name>" <ROLE>.
## Primary Instruction
All your work MUST be executed by calling Skill to get role definition:
Skill(skill="team-coordinate", args="--role=<role> --session=<session-folder>")
Current requirement: <task-description>
Session: <session-folder>
## Role Guidelines
- Only process <PREFIX>-* tasks, do not execute other role work
- All output prefixed with [<role>] tag
- Only communicate with coordinator
- Do not use TaskCreate to create tasks for other roles
- Before each SendMessage, call mcp__ccw-tools__team_msg to log (team=<session-id> from Session field, NOT team name)
- After task completion, check for fast-advance opportunity (see SKILL.md Phase 5)
## Workflow
1. Call Skill -> get role definition and execution logic
2. Follow role.md 5-Phase flow
3. team_msg(team=<session-id>) + SendMessage results to coordinator
4. TaskUpdate completed -> check next task or fast-advance`
})
```
### Inner Loop Worker (multi-task role)
```
Task({
subagent_type: "general-purpose",
description: "Spawn <role> worker (inner loop)",
team_name: <team-name>,
name: "<role>",
run_in_background: true,
prompt: `You are team "<team-name>" <ROLE>.
## Primary Instruction
All your work MUST be executed by calling Skill to get role definition:
Skill(skill="team-coordinate", args="--role=<role> --session=<session-folder>")
Current requirement: <task-description>
Session: <session-folder>
## Inner Loop Mode
You will handle ALL <PREFIX>-* tasks in this session, not just the first one.
After completing each task, loop back to find the next <PREFIX>-* task.
Only SendMessage to coordinator when:
- All <PREFIX>-* tasks are done
- A consensus_blocked HIGH occurs
- Errors accumulate (>= 3)
## Role Guidelines
- Only process <PREFIX>-* tasks, do not execute other role work
- All output prefixed with [<role>] tag
- Only communicate with coordinator
- Do not use TaskCreate to create tasks for other roles
- Before each SendMessage, call mcp__ccw-tools__team_msg to log (team=<session-id> from Session field, NOT team name)
- Use subagent calls for heavy work, retain summaries in context`
})
```
---
## Session Directory
```
.workflow/.team/TC-<slug>-<date>/
+-- team-session.json # Session state + dynamic role registry
+-- task-analysis.json # Phase 1 output: capabilities, dependency graph
+-- roles/ # Dynamic role definitions (generated Phase 2)
| +-- <role-1>.md
| +-- <role-2>.md
+-- artifacts/ # All MD deliverables from workers
| +-- <artifact>.md
+-- shared-memory.json # Cross-role state store
+-- wisdom/ # Cross-task knowledge
| +-- learnings.md
| +-- decisions.md
| +-- issues.md
+-- explorations/ # Shared explore cache
| +-- cache-index.json
| +-- explore-<angle>.json
+-- discussions/ # Inline discuss records
| +-- <round>.md
+-- .msg/ # Team message bus logs
```
### team-session.json Schema
```json
{
"session_id": "TC-<slug>-<date>",
"task_description": "<original user input>",
"status": "active | paused | completed",
"team_name": "<team-name>",
"roles": [
{
"name": "<role-name>",
"prefix": "<PREFIX>",
"responsibility_type": "<type>",
"inner_loop": false,
"role_file": "roles/<role-name>.md"
}
],
"pipeline": {
"dependency_graph": {},
"tasks_total": 0,
"tasks_completed": 0
},
"active_workers": [],
"completed_tasks": [],
"created_at": "<timestamp>"
}
```
---
## Session Resume
Coordinator supports `--resume` / `--continue` for interrupted sessions:
1. Scan `.workflow/.team/TC-*/team-session.json` for active/paused sessions
2. Multiple matches -> AskUserQuestion for selection
3. Audit TaskList -> reconcile session state <-> task status
4. Reset in_progress -> pending (interrupted tasks)
5. Rebuild team and spawn needed workers only
6. Create missing tasks with correct blockedBy
7. Kick first executable task -> Phase 4 coordination loop
---
## Error Handling
| Scenario | Resolution |
|----------|------------|
| Unknown --role value | Check if `<session>/roles/<role>.md` exists; error with message if not |
| Missing --role arg | Orchestration Mode -> coordinator |
| Dynamic role file not found | Error with expected path, coordinator may need to regenerate |
| Built-in role file not found | Error with expected path |
| Command file not found | Fallback to inline execution |
| Discuss subagent fails | Role proceeds without discuss, logs warning |
| Explore cache corrupt | Clear cache, re-explore |
| Fast-advance spawns wrong task | Coordinator reconciles on next callback |
| Session path not provided (dynamic role) | Error: `--session` is required for dynamic roles. Coordinator must always pass `--session=<session-folder>` when spawning workers. |
| capability_gap reported | Coordinator generates new role via handleAdapt |

View File

@@ -0,0 +1,197 @@
# Command: analyze-task
## Purpose
Parse user task description -> detect required capabilities -> build dependency graph -> design dynamic roles. This replaces v4's static mode selection with intelligent task decomposition.
## Phase 2: Context Loading
| Input | Source | Required |
|-------|--------|----------|
| Task description | User input from Phase 1 | Yes |
| Clarification answers | AskUserQuestion results (if any) | No |
| Session folder | From coordinator Phase 2 | Yes |
## Phase 3: Task Analysis
### Step 1: Signal Detection
Scan task description for capability keywords:
| Signal | Keywords | Capability | Prefix | Responsibility Type |
|--------|----------|------------|--------|---------------------|
| Research | investigate, explore, compare, survey, find, research, discover, benchmark, study | researcher | RESEARCH | orchestration |
| Writing | write, draft, document, article, report, blog, describe, explain, summarize, content | writer | DRAFT | code-gen (docs) |
| Coding | implement, build, code, fix, refactor, develop, create app, program, migrate, port | developer | IMPL | code-gen (code) |
| Design | design, architect, plan, structure, blueprint, model, schema, wireframe, layout | designer | DESIGN | orchestration |
| Analysis | analyze, review, audit, assess, evaluate, inspect, examine, diagnose, profile | analyst | ANALYSIS | read-only |
| Testing | test, verify, validate, QA, quality, check, assert, coverage, regression | tester | TEST | validation |
| Planning | plan, breakdown, organize, schedule, decompose, roadmap, strategy, prioritize | planner | PLAN | orchestration |
**Multi-match**: A task may trigger multiple capabilities. E.g., "research and write a technical article" triggers both `researcher` and `writer`.
**No match**: If no keywords match, default to a single `general` capability with `TASK` prefix.
### Step 2: Artifact Inference
Each capability produces default output artifacts:
| Capability | Default Artifact | Format |
|------------|-----------------|--------|
| researcher | Research findings | `<session>/artifacts/research-findings.md` |
| writer | Written document(s) | `<session>/artifacts/<doc-name>.md` |
| developer | Code implementation | Source files + `<session>/artifacts/implementation-summary.md` |
| designer | Design document | `<session>/artifacts/design-spec.md` |
| analyst | Analysis report | `<session>/artifacts/analysis-report.md` |
| tester | Test results | `<session>/artifacts/test-report.md` |
| planner | Execution plan | `<session>/artifacts/execution-plan.md` |
### Step 3: Dependency Graph Construction
Build a DAG of work streams using these inference rules:
| Pattern | Shape | Example |
|---------|-------|---------|
| Knowledge -> Creation | research blockedBy nothing, creation blockedBy research | RESEARCH-001 -> DRAFT-001 |
| Design -> Build | design first, build after | DESIGN-001 -> IMPL-001 |
| Build -> Validate | build first, test/review after | IMPL-001 -> TEST-001 + ANALYSIS-001 |
| Plan -> Execute | plan first, execute after | PLAN-001 -> IMPL-001 |
| Independent parallel | no dependency between them | DRAFT-001 || IMPL-001 |
| Analysis -> Revise | analysis finds issues, revise artifact | ANALYSIS-001 -> DRAFT-002 |
**Graph construction algorithm**:
1. Group capabilities by natural ordering: knowledge-gathering -> design/planning -> creation -> validation
2. Within same tier: capabilities are parallel unless task description implies sequence
3. Between tiers: downstream blockedBy upstream
4. Single-capability tasks: one node, no dependencies
**Natural ordering tiers**:
| Tier | Capabilities | Description |
|------|-------------|-------------|
| 0 | researcher, planner | Knowledge gathering / planning |
| 1 | designer | Design (requires context from tier 0 if present) |
| 2 | writer, developer | Creation (requires design/plan if present) |
| 3 | analyst, tester | Validation (requires artifacts to validate) |
### Step 4: Complexity Scoring
| Factor | Weight | Condition |
|--------|--------|-----------|
| Capability count | +1 each | Number of distinct capabilities |
| Cross-domain factor | +2 | Capabilities span 3+ tiers |
| Parallel tracks | +1 each | Independent parallel work streams |
| Serial depth | +1 per level | Longest dependency chain length |
| Total Score | Complexity | Role Limit |
|-------------|------------|------------|
| 1-3 | Low | 1-2 roles |
| 4-6 | Medium | 2-3 roles |
| 7+ | High | 3-5 roles |
### Step 5: Role Minimization
Apply merging rules to reduce role count:
| Rule | Condition | Action |
|------|-----------|--------|
| Absorb trivial | Capability has exactly 1 task AND no explore needed | Merge into nearest related role |
| Merge overlap | Two capabilities share >50% keywords from task description | Combine into single role |
| Cap at 5 | More than 5 roles after initial assignment | Merge lowest-priority pairs (priority: researcher > designer > developer > writer > analyst > planner > tester) |
**Merge priority** (when two must merge, keep the higher-priority one as the role name):
1. developer (code-gen is hardest to merge)
2. researcher (context-gathering is foundational)
3. writer (document generation has specific patterns)
4. designer (design has specific outputs)
5. analyst (analysis can be absorbed by reviewer pattern)
6. planner (planning can be merged with researcher or designer)
7. tester (can be absorbed by developer or analyst)
**IMPORTANT**: Even after merging, coordinator MUST spawn workers for all roles. Single-role tasks still use team architecture.
## Phase 4: Output
Write `<session-folder>/task-analysis.json`:
```json
{
"task_description": "<original user input>",
"capabilities": [
{
"name": "researcher",
"prefix": "RESEARCH",
"responsibility_type": "orchestration",
"tasks": [
{ "id": "RESEARCH-001", "description": "..." }
],
"artifacts": ["research-findings.md"]
}
],
"dependency_graph": {
"RESEARCH-001": [],
"DRAFT-001": ["RESEARCH-001"],
"ANALYSIS-001": ["DRAFT-001"]
},
"roles": [
{
"name": "researcher",
"prefix": "RESEARCH",
"responsibility_type": "orchestration",
"task_count": 1,
"inner_loop": false
},
{
"name": "writer",
"prefix": "DRAFT",
"responsibility_type": "code-gen (docs)",
"task_count": 1,
"inner_loop": false
}
],
"complexity": {
"capability_count": 2,
"cross_domain_factor": false,
"parallel_tracks": 0,
"serial_depth": 2,
"total_score": 3,
"level": "low"
},
"artifacts": [
{ "name": "research-findings.md", "producer": "researcher", "path": "artifacts/research-findings.md" },
{ "name": "article-draft.md", "producer": "writer", "path": "artifacts/article-draft.md" }
]
}
```
## Complexity Interpretation
**CRITICAL**: Complexity score is for **role design optimization**, NOT for skipping team workflow.
| Complexity | Team Structure | Coordinator Action |
|------------|----------------|-------------------|
| Low (1-2 roles) | Minimal team | Generate 1-2 roles, create team, spawn workers |
| Medium (2-3 roles) | Standard team | Generate roles, create team, spawn workers |
| High (3-5 roles) | Full team | Generate roles, create team, spawn workers |
**All complexity levels use team architecture**:
- Single-role tasks still spawn worker via Skill
- Coordinator NEVER executes task work directly
- Team infrastructure provides session management, message bus, fast-advance
**Purpose of complexity score**:
- ✅ Determine optimal role count (merge vs separate)
- ✅ Guide dependency graph design
- ✅ Inform user about task scope
- ❌ NOT for deciding whether to use team workflow
## Error Handling
| Scenario | Resolution |
|----------|------------|
| No capabilities detected | Default to single `general` role with TASK prefix |
| Circular dependency in graph | Break cycle at lowest-tier edge, warn |
| Task description too vague | Return minimal analysis, coordinator will AskUserQuestion |
| All capabilities merge into one | Valid -- single-role execution via team worker |

View File

@@ -0,0 +1,85 @@
# Command: dispatch
## Purpose
Create task chains from dynamic dependency graphs. Unlike v4's static mode-to-pipeline mapping, team-coordinate builds pipelines from the task-analysis.json produced by Phase 1.
## Phase 2: Context Loading
| Input | Source | Required |
|-------|--------|----------|
| Task analysis | `<session-folder>/task-analysis.json` | Yes |
| Session file | `<session-folder>/team-session.json` | Yes |
| Role registry | `team-session.json#roles` | Yes |
| Scope | User requirements description | Yes |
## Phase 3: Task Chain Creation
### Workflow
1. **Read dependency graph** from `task-analysis.json#dependency_graph`
2. **Topological sort** tasks to determine creation order
3. **Validate** all task owners exist in role registry
4. **For each task** (in topological order):
```
TaskCreate({
subject: "<PREFIX>-<NNN>",
owner: "<role-name>",
description: "<task description from task-analysis>\nSession: <session-folder>\nScope: <scope>\nInnerLoop: <true|false>",
blockedBy: [<dependency-list from graph>],
status: "pending"
})
```
5. **Update team-session.json** with pipeline and tasks_total
6. **Validate** created chain
### Task Description Template
Every task description includes session path and inner loop flag:
```
<task description>
Session: <session-folder>
Scope: <scope>
InnerLoop: <true|false>
```
### InnerLoop Flag Rules
| Condition | InnerLoop |
|-----------|-----------|
| Role has 2+ serial same-prefix tasks | true |
| Role has 1 task | false |
| Tasks are parallel (no dependency between them) | false |
### Dependency Validation
| Check | Criteria |
|-------|----------|
| No orphan tasks | Every task is reachable from at least one root |
| No circular deps | Topological sort succeeds without cycle |
| All owners valid | Every task owner exists in team-session.json#roles |
| All blockedBy valid | Every blockedBy references an existing task subject |
| Session reference | Every task description contains `Session: <session-folder>` |
## Phase 4: Validation
| Check | Criteria |
|-------|----------|
| Task count | Matches dependency_graph node count |
| Dependencies | Every blockedBy references an existing task subject |
| Owner assignment | Each task owner is in role registry |
| Session reference | Every task description contains `Session:` |
| Pipeline integrity | No disconnected subgraphs (warn if found) |
## Error Handling
| Scenario | Resolution |
|----------|------------|
| Circular dependency detected | Report cycle, halt task creation |
| Owner not in role registry | Error, coordinator must fix roles first |
| TaskCreate fails | Log error, report to coordinator |
| Duplicate task subject | Skip creation, log warning |
| Empty dependency graph | Error, task analysis may have failed |

View File

@@ -0,0 +1,296 @@
# Command: monitor
## Purpose
Event-driven pipeline coordination with Spawn-and-Stop pattern. Adapted from v4 for dynamic roles -- role names are read from `team-session.json#roles` instead of hardcoded. Includes `handleAdapt` for mid-pipeline capability gap handling.
## Constants
| Constant | Value | Description |
|----------|-------|-------------|
| SPAWN_MODE | background | All workers spawned via `Task(run_in_background: true)` |
| ONE_STEP_PER_INVOCATION | true | Coordinator does one operation then STOPS |
| FAST_ADVANCE_AWARE | true | Workers may skip coordinator for simple linear successors |
## Phase 2: Context Loading
| Input | Source | Required |
|-------|--------|----------|
| Session file | `<session-folder>/team-session.json` | Yes |
| Task list | `TaskList()` | Yes |
| Active workers | session.active_workers[] | Yes |
| Role registry | session.roles[] | Yes |
**Dynamic role resolution**: Known worker roles are loaded from `session.roles[].name` rather than a static list. This is the key difference from v4.
## Phase 3: Handler Routing
### Wake-up Source Detection
Parse `$ARGUMENTS` to determine handler:
| Priority | Condition | Handler |
|----------|-----------|---------|
| 1 | Message contains `[<role-name>]` from session roles | handleCallback |
| 2 | Contains "capability_gap" | handleAdapt |
| 3 | Contains "check" or "status" | handleCheck |
| 4 | Contains "resume", "continue", or "next" | handleResume |
| 5 | None of the above (initial spawn after dispatch) | handleSpawnNext |
---
### Handler: handleCallback
Worker completed a task. Verify completion, update state, auto-advance.
```
Receive callback from [<role>]
+- Find matching active worker by role (from session.roles)
+- Is this a progress update (not final)? (Inner Loop intermediate task completion)
| +- YES -> Update session state, do NOT remove from active_workers -> STOP
+- Task status = completed?
| +- YES -> remove from active_workers -> update session
| | +- -> handleSpawnNext
| +- NO -> progress message, do not advance -> STOP
+- No matching worker found
+- Scan all active workers for completed tasks
+- Found completed -> process each -> handleSpawnNext
+- None completed -> STOP
```
**Fast-advance note**: A worker may have already spawned its successor via fast-advance. When processing a callback:
1. Check if the expected next task is already `in_progress` (fast-advanced)
2. If yes -> skip spawning that task, update active_workers to include the fast-advanced worker
3. If no -> normal handleSpawnNext
---
### Handler: handleCheck
Read-only status report. No pipeline advancement.
**Output format**:
```
[coordinator] Pipeline Status
[coordinator] Progress: <completed>/<total> (<percent>%)
[coordinator] Execution Graph:
<visual representation of dependency graph with status icons>
done=completed >>>=running o=pending .=not created
[coordinator] Active Workers:
> <subject> (<role>) - running <elapsed> [inner-loop: N/M tasks done]
[coordinator] Ready to spawn: <subjects>
[coordinator] Commands: 'resume' to advance | 'check' to refresh
```
**Icon mapping**: completed=done, in_progress=>>>, pending=o, not created=.
**Graph rendering**: Read dependency_graph from task-analysis.json, render each node with status icon. Show parallel branches side-by-side.
Then STOP.
---
### Handler: handleResume
Check active worker completion, process results, advance pipeline.
```
Load active_workers from session
+- No active workers -> handleSpawnNext
+- Has active workers -> check each:
+- status = completed -> mark done, log
+- status = in_progress -> still running, log
+- other status -> worker failure -> reset to pending
After processing:
+- Some completed -> handleSpawnNext
+- All still running -> report status -> STOP
+- All failed -> handleSpawnNext (retry)
```
---
### Handler: handleSpawnNext
Find all ready tasks, spawn workers in background, update session, STOP.
```
Collect task states from TaskList()
+- completedSubjects: status = completed
+- inProgressSubjects: status = in_progress
+- readySubjects: pending + all blockedBy in completedSubjects
Ready tasks found?
+- NONE + work in progress -> report waiting -> STOP
+- NONE + nothing in progress -> PIPELINE_COMPLETE -> Phase 5
+- HAS ready tasks -> for each:
+- Is task owner an Inner Loop role AND that role already has an active_worker?
| +- YES -> SKIP spawn (existing worker will pick it up via inner loop)
| +- NO -> normal spawn below
+- TaskUpdate -> in_progress
+- team_msg log -> task_unblocked (team=<session-id>, NOT team name)
+- Spawn worker (see spawn tool call below)
+- Add to session.active_workers
Update session file -> output summary -> STOP
```
**Spawn worker tool call** (one per ready task):
```
Task({
subagent_type: "general-purpose",
description: "Spawn <role> worker for <subject>",
team_name: <team-name>,
name: "<role>",
run_in_background: true,
prompt: "<worker prompt from SKILL.md Coordinator Spawn Template>"
})
```
---
### Handler: handleAdapt
Handle mid-pipeline capability gap discovery. A worker reports `capability_gap` when it encounters work outside its scope.
**CONSTRAINT**: Maximum 5 worker roles per session (per coordinator/role.md). handleAdapt MUST enforce this limit.
```
Parse capability_gap message:
+- Extract: gap_description, requesting_role, suggested_capability
+- Validate gap is genuine:
+- Check existing roles in session.roles -> does any role cover this?
| +- YES -> redirect: SendMessage to that role's owner -> STOP
| +- NO -> genuine gap, proceed to role generation
+- CHECK ROLE COUNT LIMIT (MAX 5 ROLES):
+- Count current roles in session.roles
+- If count >= 5:
+- Attempt to merge new capability into existing role:
+- Find best-fit role by responsibility_type
+- If merge possible:
+- Update existing role file with new capability
+- Create task assigned to existing role
+- Log via team_msg (type: warning, summary: "Capability merged into existing role")
+- STOP
+- If merge NOT possible:
+- PAUSE session
+- Report to user:
"Role limit (5) reached. Cannot generate new role for: <gap_description>
Options:
1. Manually extend an existing role
2. Re-run team-coordinate with refined task to consolidate roles
3. Accept limitation and continue without this capability"
+- STOP
+- Generate new role:
1. Read specs/role-template.md
2. Fill template with capability details from gap description
3. Write new role file to <session-folder>/roles/<new-role>.md
4. Add to session.roles[]
+- Create new task(s):
TaskCreate({
subject: "<NEW-PREFIX>-001",
owner: "<new-role>",
description: "<gap_description>\nSession: <session-folder>\nInnerLoop: false",
blockedBy: [<requesting task if sequential>],
status: "pending"
})
+- Update team-session.json: add role, increment tasks_total
+- Spawn new worker -> STOP
```
---
### Worker Failure Handling
When a worker has unexpected status (not completed, not in_progress):
1. Reset task -> pending via TaskUpdate
2. Log via team_msg (type: error)
3. Report to user: task reset, will retry on next resume
### Fast-Advance Failure Recovery
When coordinator detects a fast-advanced task has failed (task in_progress but no callback and worker gone):
```
handleCallback / handleResume detects:
+- Task is in_progress (was fast-advanced by predecessor)
+- No active_worker entry for this task
+- Original fast-advancing worker has already completed and exited
+- Resolution:
1. TaskUpdate -> reset task to pending
2. Remove stale active_worker entry (if any)
3. Log via team_msg (type: error, summary: "Fast-advanced task <ID> failed, resetting for retry")
4. -> handleSpawnNext (will re-spawn the task normally)
```
**Detection in handleResume**:
```
For each in_progress task in TaskList():
+- Has matching active_worker? -> normal, skip
+- No matching active_worker? -> orphaned (likely fast-advance failure)
+- Check creation time: if > 5 minutes with no progress callback
+- Reset to pending -> handleSpawnNext
```
**Prevention**: Fast-advance failures are self-healing. The coordinator reconciles orphaned tasks on every `resume`/`check` cycle.
### Consensus-Blocked Handling
When a worker reports `consensus_blocked` in its callback:
```
handleCallback receives message with consensus_blocked flag
+- Extract: divergence_severity, blocked_round, action_recommendation
+- Route by severity:
|
+- severity = HIGH
| +- Create REVISION task:
| +- Same role, same doc type, incremented suffix (e.g., DRAFT-001-R1)
| +- Description includes: divergence details + action items from discuss
| +- blockedBy: none (immediate execution)
| +- Max 1 revision per task (DRAFT-001 -> DRAFT-001-R1, no R2)
| +- If already revised once -> PAUSE, escalate to user
| +- Update session: mark task as "revised", log revision chain
|
+- severity = MEDIUM
| +- Proceed with warning: include divergence in next task's context
| +- Log action items to wisdom/issues.md
| +- Normal handleSpawnNext
|
+- severity = LOW
+- Proceed normally: treat as consensus_reached with notes
+- Normal handleSpawnNext
```
## Phase 4: Validation
| Check | Criteria |
|-------|----------|
| Session state consistent | active_workers matches TaskList in_progress tasks |
| No orphaned tasks | Every in_progress task has an active_worker entry |
| Dynamic roles valid | All task owners exist in session.roles |
| Completion detection | readySubjects=0 + inProgressSubjects=0 -> PIPELINE_COMPLETE |
| Fast-advance tracking | Detect tasks already in_progress via fast-advance, sync to active_workers |
| Fast-advance orphan check | in_progress tasks without active_worker entry -> reset to pending |
## Error Handling
| Scenario | Resolution |
|----------|------------|
| Session file not found | Error, suggest re-initialization |
| Worker callback from unknown role | Log info, scan for other completions |
| All workers still running on resume | Report status, suggest check later |
| Pipeline stall (no ready, no running) | Check for missing tasks, report to user |
| Fast-advance conflict | Coordinator reconciles, no duplicate spawns |
| Fast-advance task orphaned | Reset to pending, re-spawn via handleSpawnNext |
| Dynamic role file not found | Error, coordinator must regenerate from task-analysis |
| capability_gap from completed role | Validate gap, generate role if genuine |
| capability_gap when role limit (5) reached | Attempt merge into existing role, else pause for user |
| consensus_blocked HIGH | Create revision task (max 1) or pause for user |
| consensus_blocked MEDIUM | Proceed with warning, log to wisdom/issues.md |

View File

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

View File

@@ -0,0 +1,434 @@
# Dynamic Role Template
Template used by coordinator to generate worker role.md files at runtime. Each generated role is written to `<session>/roles/<role-name>.md`.
## Template
```markdown
# Role: <role_name>
<role_description>
## Identity
- **Name**: `<role_name>` | **Tag**: `[<role_name>]`
- **Task Prefix**: `<prefix>-*`
- **Responsibility**: <responsibility_type>
<if inner_loop>
- **Mode**: Inner Loop (handle all `<prefix>-*` tasks in single agent)
</if>
## Boundaries
### MUST
- Only process `<prefix>-*` prefixed tasks
- All output (SendMessage, team_msg, logs) must carry `[<role_name>]` identifier
- Only communicate with coordinator via SendMessage
- Work strictly within <responsibility_type> responsibility scope
- Use fast-advance for simple linear successors (see SKILL.md Phase 5)
- Produce MD artifacts in `<session>/artifacts/`
<if inner_loop>
- Use subagent for heavy work (do not execute CLI/generation in main agent context)
- Maintain context_accumulator across tasks within the inner loop
- Loop through all `<prefix>-*` tasks before reporting to coordinator
</if>
### MUST NOT
- Execute work outside this role's responsibility scope
- Communicate directly with other worker roles (must go through coordinator)
- Create tasks for other roles (TaskCreate is coordinator-exclusive)
- Modify files or resources outside this role's scope
- Omit `[<role_name>]` identifier in any output
- Fast-advance when multiple tasks are ready or at checkpoint boundaries
<if inner_loop>
- Execute heavy work (CLI calls, large document generation) in main agent (delegate to subagent)
- SendMessage to coordinator mid-loop (unless consensus_blocked HIGH or error count >= 3)
</if>
## Toolbox
| Tool | Purpose |
|------|---------|
<tools based on responsibility_type -- see reference sections below>
## Message Types
| Type | Direction | Description |
|------|-----------|-------------|
| `<prefix>_complete` | -> coordinator | Task completed with artifact path |
| `<prefix>_error` | -> coordinator | Error encountered |
| `capability_gap` | -> coordinator | Work outside role scope discovered |
## Message Bus
Before every SendMessage, log via `mcp__ccw-tools__team_msg`:
```
mcp__ccw-tools__team_msg({
operation: "log",
team: <session-id>,
from: "<role_name>",
to: "coordinator",
type: <message-type>,
summary: "[<role_name>] <prefix> complete: <task-subject>",
ref: <artifact-path>
})
```
**`team` must be session ID** (e.g., `TC-my-project-2026-02-27`), NOT team name. Extract from task description `Session:` field -> take folder name.
**CLI fallback** (when MCP unavailable):
```
Bash("ccw team log --team <session-id> --from <role_name> --to coordinator --type <message-type> --summary \"[<role_name>] <prefix> complete\" --ref <artifact-path> --json")
```
---
## Execution (5-Phase)
### Phase 1: Task Discovery
> See SKILL.md Shared Infrastructure -> Worker Phase 1: Task Discovery
Standard task discovery flow: TaskList -> filter by prefix `<prefix>-*` + owner match + pending + unblocked -> TaskGet -> TaskUpdate in_progress.
### Phase 2: <phase2_name>
<phase2_content -- generated by coordinator based on responsibility type>
### Phase 3: <phase3_name>
<phase3_content -- generated by coordinator based on task specifics>
### Phase 4: <phase4_name>
<phase4_content -- generated by coordinator based on responsibility type>
<if inline_discuss>
### Phase 4b: Inline Discuss (optional)
After primary work, optionally call discuss subagent:
```
Task({
subagent_type: "cli-discuss-agent",
run_in_background: false,
description: "Discuss <round-id>",
prompt: "## Multi-Perspective Critique: <round-id>
See subagents/discuss-subagent.md for prompt template.
Perspectives: <specified by coordinator when generating this role>"
})
```
| Verdict | Severity | Action |
|---------|----------|--------|
| consensus_reached | - | Include action items in report, proceed to Phase 5 |
| consensus_blocked | HIGH | Phase 5 SendMessage includes structured consensus_blocked format. Do NOT self-revise. |
| consensus_blocked | MEDIUM | Phase 5 SendMessage includes warning. Proceed normally. |
| consensus_blocked | LOW | Treat as consensus_reached with notes. |
</if>
<if inner_loop>
### Phase 5-L: Loop Completion (Inner Loop)
When more same-prefix tasks remain:
1. **TaskUpdate**: Mark current task completed
2. **team_msg**: Log task completion
3. **Accumulate summary**:
```
context_accumulator.append({
task: "<task-id>",
artifact: "<output-path>",
key_decisions: <from subagent return>,
discuss_verdict: <from Phase 4>,
summary: <from subagent return>
})
```
4. **Interrupt check**:
- consensus_blocked HIGH -> SendMessage -> STOP
- Error count >= 3 -> SendMessage -> STOP
5. **Loop**: Back to Phase 1
**Does NOT**: SendMessage to coordinator, Fast-Advance spawn.
### Phase 5-F: Final Report (Inner Loop)
When all same-prefix tasks are done:
1. **TaskUpdate**: Mark last task completed
2. **team_msg**: Log completion
3. **Summary report**: All tasks summary + discuss results + artifact paths
4. **Fast-Advance check**: Check cross-prefix successors
5. **SendMessage** or **spawn successor**
> See SKILL.md Shared Infrastructure -> Worker Phase 5: Report + Fast-Advance
<else>
### Phase 5: Report + Fast-Advance
> See SKILL.md Shared Infrastructure -> Worker Phase 5: Report + Fast-Advance
Standard report flow: team_msg log -> SendMessage with `[<role_name>]` prefix -> TaskUpdate completed -> Fast-Advance Check -> Loop to Phase 1 for next task.
</if>
---
## Error Handling
| Scenario | Resolution |
|----------|------------|
| No <prefix>-* tasks available | Idle, wait for coordinator assignment |
| Context file not found | Notify coordinator, request location |
| Subagent fails | Retry once with fallback; still fails -> log error, continue next task |
| Fast-advance spawn fails | Fall back to SendMessage to coordinator |
<if inner_loop>
| Cumulative 3 task failures | SendMessage to coordinator, STOP inner loop |
| Agent crash mid-loop | Coordinator detects orphan on resume -> re-spawn -> resume from interrupted task |
</if>
| Work outside scope discovered | SendMessage capability_gap to coordinator |
| Critical issue beyond scope | SendMessage fix_required to coordinator |
```
---
## Phase 2-4 Content by Responsibility Type
Reference sections for coordinator to fill when generating roles. Select the matching section based on `responsibility_type`.
### orchestration
**Phase 2: Context Assessment**
```
| Input | Source | Required |
|-------|--------|----------|
| Task description | From TaskGet | Yes |
| Shared memory | <session>/shared-memory.json | No |
| Prior artifacts | <session>/artifacts/ | No |
| Wisdom | <session>/wisdom/ | No |
Loading steps:
1. Extract session path from task description
2. Read shared-memory.json for cross-role context
3. Read prior artifacts (if any exist from upstream tasks)
4. Load wisdom files for accumulated knowledge
5. Optionally call explore subagent for codebase context
```
**Phase 3: Subagent Execution**
```
Delegate to appropriate subagent based on task:
Task({
subagent_type: "general-purpose",
run_in_background: false,
description: "<task-type> for <task-id>",
prompt: "## Task
- <task description>
- Session: <session-folder>
## Context
<prior artifacts + shared memory + explore results>
## Expected Output
Write artifact to: <session>/artifacts/<artifact-name>.md
Return JSON summary: { artifact_path, summary, key_decisions[], warnings[] }"
})
```
**Phase 4: Result Aggregation**
```
1. Verify subagent output artifact exists
2. Read artifact, validate structure/completeness
3. Update shared-memory.json with key findings
4. Write insights to wisdom/ files
```
### code-gen (docs)
**Phase 2: Load Prior Context**
```
| Input | Source | Required |
|-------|--------|----------|
| Task description | From TaskGet | Yes |
| Prior artifacts | <session>/artifacts/ from upstream tasks | Conditional |
| Shared memory | <session>/shared-memory.json | No |
| Wisdom | <session>/wisdom/ | No |
Loading steps:
1. Extract session path from task description
2. Read upstream artifacts (e.g., research findings for a writer)
3. Read shared-memory.json for cross-role context
4. Load wisdom for accumulated decisions
```
**Phase 3: Document Generation**
```
Task({
subagent_type: "universal-executor",
run_in_background: false,
description: "Generate <doc-type> for <task-id>",
prompt: "## Task
- Generate: <document type>
- Session: <session-folder>
## Prior Context
<upstream artifacts + shared memory>
## Instructions
<task-specific writing instructions from coordinator>
## Expected Output
Write document to: <session>/artifacts/<doc-name>.md
Return JSON: { artifact_path, summary, key_decisions[], sections_generated[], warnings[] }"
})
```
**Phase 4: Structure Validation**
```
1. Verify document artifact exists
2. Check document has expected sections
3. Validate no placeholder text remains
4. Update shared-memory.json with document metadata
```
### code-gen (code)
**Phase 2: Load Plan/Specs**
```
| Input | Source | Required |
|-------|--------|----------|
| Task description | From TaskGet | Yes |
| Plan/design artifacts | <session>/artifacts/ | Conditional |
| Shared memory | <session>/shared-memory.json | No |
| Wisdom | <session>/wisdom/ | No |
Loading steps:
1. Extract session path from task description
2. Read plan/design artifacts from upstream
3. Load shared-memory.json for implementation context
4. Load wisdom for conventions and patterns
```
**Phase 3: Code Implementation**
```
Task({
subagent_type: "code-developer",
run_in_background: false,
description: "Implement <task-id>",
prompt: "## Task
- <implementation description>
- Session: <session-folder>
## Plan/Design Context
<upstream artifacts>
## Instructions
<task-specific implementation instructions>
## Expected Output
Implement code changes.
Write summary to: <session>/artifacts/implementation-summary.md
Return JSON: { artifact_path, summary, files_changed[], key_decisions[], warnings[] }"
})
```
**Phase 4: Syntax Validation**
```
1. Run syntax check (tsc --noEmit or equivalent)
2. Verify all planned files exist
3. Check no broken imports
4. If validation fails -> attempt auto-fix (max 2 attempts)
5. Write implementation summary to artifacts/
```
### read-only
**Phase 2: Target Loading**
```
| Input | Source | Required |
|-------|--------|----------|
| Task description | From TaskGet | Yes |
| Target artifacts/files | From task description or upstream | Yes |
| Shared memory | <session>/shared-memory.json | No |
Loading steps:
1. Extract session path and target files from task description
2. Read target artifacts or source files for analysis
3. Load shared-memory.json for context
```
**Phase 3: Multi-Dimension Analysis**
```
Task({
subagent_type: "general-purpose",
run_in_background: false,
description: "Analyze <target> for <task-id>",
prompt: "## Task
- Analyze: <target description>
- Dimensions: <analysis dimensions from coordinator>
- Session: <session-folder>
## Target Content
<artifact content or file content>
## Expected Output
Write report to: <session>/artifacts/analysis-report.md
Return JSON: { artifact_path, summary, findings[], severity_counts: {critical, high, medium, low} }"
})
```
**Phase 4: Severity Classification**
```
1. Verify analysis report exists
2. Classify findings by severity (Critical/High/Medium/Low)
3. Update shared-memory.json with key findings
4. Write issues to wisdom/issues.md
```
### validation
**Phase 2: Environment Detection**
```
| Input | Source | Required |
|-------|--------|----------|
| Task description | From TaskGet | Yes |
| Implementation artifacts | Upstream code changes | Yes |
Loading steps:
1. Detect test framework from project files
2. Get changed files from implementation
3. Identify test command and coverage tool
```
**Phase 3: Test-Fix Cycle**
```
Task({
subagent_type: "test-fix-agent",
run_in_background: false,
description: "Test-fix for <task-id>",
prompt: "## Task
- Run tests and fix failures
- Session: <session-folder>
- Max iterations: 5
## Changed Files
<from upstream implementation>
## Expected Output
Write report to: <session>/artifacts/test-report.md
Return JSON: { artifact_path, pass_rate, coverage, iterations_used, remaining_failures[] }"
})
```
**Phase 4: Result Analysis**
```
1. Check pass rate >= 95%
2. Check coverage meets threshold
3. Generate test report with pass/fail counts
4. Update shared-memory.json with test results
```

View File

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

View File

@@ -0,0 +1,120 @@
# Explore Subagent
Shared codebase exploration utility with centralized caching. Callable by any role needing code context.
## Invocation
```
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
## Exploration
<angle-specific-focus-from-table-below>
## Output
Write JSON to: <session-folder>/explorations/explore-<angle>.json
Update cache-index.json with new entry
## Output Schema
{
"angle": "<angle>",
"query": "<query>",
"relevant_files": [
{ "path": "...", "rationale": "...", "role": "...", "discovery_source": "...", "key_symbols": [] }
],
"patterns": [],
"dependencies": [],
"external_refs": [],
"_metadata": { "created_by": "<calling-role>", "timestamp": "...", "cache_key": "..." }
}
Return summary: file count, pattern count, top 5 files, output path`
})
```
## Cache Mechanism
### Cache Index Schema
`<session-folder>/explorations/cache-index.json`:
```json
{
"entries": [
{
"angle": "architecture",
"keywords": ["auth", "middleware"],
"file": "explore-architecture.json",
"created_by": "analyst",
"created_at": "2026-02-27T10:00:00Z",
"file_count": 15
}
]
}
```
### Cache Lookup Rules
| Condition | Action |
|-----------|--------|
| Exact angle match exists | Return cached result |
| No match | Execute exploration, cache result |
| Cache file missing but index has entry | Remove stale entry, re-explore |
### Cache Invalidation
Cache is session-scoped. No explicit invalidation needed -- each session starts fresh. If a role suspects stale data, it can pass `force_refresh: true` in the prompt to bypass cache.
## Angle Focus Guide
| Angle | Focus Points | Typical Caller |
|-------|-------------|----------------|
| architecture | Layer boundaries, design patterns, component responsibilities, ADRs | any |
| dependencies | Import chains, external libraries, circular dependencies, shared utilities | any |
| modularity | Module interfaces, separation of concerns, extraction opportunities | any |
| integration-points | API endpoints, data flow between modules, event systems | any |
| security | Auth/authz logic, input validation, sensitive data handling, middleware | any |
| dataflow | Data transformations, state propagation, validation points | any |
| performance | Bottlenecks, N+1 queries, blocking operations, algorithm complexity | any |
| error-handling | Try-catch blocks, error propagation, recovery strategies, logging | any |
| patterns | Code conventions, design patterns, naming conventions, best practices | any |
| testing | Test files, coverage gaps, test patterns, mocking strategies | any |
| general | Broad semantic search for topic-related code | any |
## Exploration Strategies
### Low Complexity (direct search)
For simple queries, use ACE semantic search:
```
mcp__ace-tool__search_context(project_root_path="<project-root>", query="<query>")
```
ACE failure fallback: `rg -l '<keywords>' --type ts`
### Medium/High Complexity (multi-angle)
For complex queries, call cli-explore-agent per angle. The calling role determines complexity and selects angles.
## Search Tool Priority
| Tool | Priority | Use Case |
|------|----------|----------|
| mcp__ace-tool__search_context | P0 | Semantic search |
| Grep / Glob | P1 | Pattern matching |
| cli-explore-agent | Deep | Multi-angle exploration |
| WebSearch | P3 | External docs |

View File

@@ -0,0 +1,215 @@
---
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".
allowed-tools: TeamCreate(*), TeamDelete(*), SendMessage(*), TaskCreate(*), TaskUpdate(*), TaskList(*), TaskGet(*), Task(*), AskUserQuestion(*), Read(*), Write(*), Edit(*), Bash(*), Glob(*), Grep(*)
---
# Team Executor v2
Lightweight session execution skill: load session -> reconcile state -> spawn team-worker agents -> execute -> deliver. **No analysis, no role generation** -- only executes existing team-coordinate sessions.
## Architecture
```
+---------------------------------------------------+
| Skill(skill="team-executor") |
| args="--session=<path>" [REQUIRED] |
+-------------------+-------------------------------+
| Session Validation
+---- --session valid? ----+
| NO | YES
v v
Error immediately Orchestration Mode
(no session) -> executor
|
+-------+-------+-------+
v v v v
[team-worker agents loaded from session role-specs]
```
---
## Session Validation (BEFORE routing)
**CRITICAL**: Session validation MUST occur before any execution.
### Parse Arguments
Extract from `$ARGUMENTS`:
- `--session=<path>`: Path to team-coordinate session folder (REQUIRED)
### Validation Steps
1. **Check `--session` provided**:
- If missing -> **ERROR**: "Session required. Usage: --session=<path-to-TC-folder>"
2. **Validate session structure** (see specs/session-schema.md):
- Directory exists at path
- `team-session.json` exists and valid JSON
- `task-analysis.json` exists and valid JSON
- `role-specs/` directory has at least one `.md` file
- Each role in `team-session.json#roles` has corresponding `.md` file in `role-specs/`
3. **Validation failure**:
- Report specific missing component
- Suggest re-running team-coordinate or checking path
---
## Role Router
This skill is **executor-only**. Workers do NOT invoke this skill -- they are spawned as `team-worker` agents directly.
### Dispatch Logic
| Scenario | Action |
|----------|--------|
| No `--session` | **ERROR** immediately |
| `--session` invalid | **ERROR** with specific reason |
| Valid session | Orchestration Mode -> executor |
### Orchestration Mode
**Invocation**: `Skill(skill="team-executor", args="--session=<session-folder>")`
**Lifecycle**:
```
Validate session
-> executor Phase 0: Reconcile state (reset interrupted, detect orphans)
-> executor Phase 1: Spawn first batch team-worker agents (background) -> STOP
-> Worker executes -> SendMessage callback -> executor advances next step
-> Loop until pipeline complete -> Phase 2 report + completion action
```
**User Commands** (wake paused executor):
| Command | Action |
|---------|--------|
| `check` / `status` | Output execution status graph, no advancement |
| `resume` / `continue` | Check worker states, advance next step |
---
## Role Registry
| Role | File | Type |
|------|------|------|
| executor | [roles/executor/role.md](roles/executor/role.md) | built-in orchestrator |
| (dynamic) | `<session>/role-specs/<role-name>.md` | loaded from session |
---
## Executor Spawn Template
### v2 Worker Spawn (all roles)
When executor spawns workers, use `team-worker` agent with role-spec path:
```
Task({
subagent_type: "team-worker",
description: "Spawn <role> worker",
team_name: <team-name>,
name: "<role>",
run_in_background: true,
prompt: `## Role Assignment
role: <role>
role_spec: <session-folder>/role-specs/<role>.md
session: <session-folder>
session_id: <session-id>
team_name: <team-name>
requirement: <task-description>
inner_loop: <true|false>
Read role_spec file to load Phase 2-4 domain instructions.`
})
```
---
## Completion Action
When pipeline completes (all tasks done), executor presents an interactive choice:
```
AskUserQuestion({
questions: [{
question: "Team pipeline complete. What would you like to do?",
header: "Completion",
multiSelect: false,
options: [
{ label: "Archive & Clean (Recommended)", description: "Archive session, clean up team" },
{ label: "Keep Active", description: "Keep session for follow-up work" },
{ label: "Export Results", description: "Export deliverables to target directory, then clean" }
]
}]
})
```
### Action Handlers
| Choice | Steps |
|--------|-------|
| Archive & Clean | Update session status="completed" -> TeamDelete -> output final summary with artifact paths |
| Keep Active | Update session status="paused" -> output: "Resume with: Skill(skill='team-executor', args='--session=<path>')" |
| Export Results | AskUserQuestion(target path) -> copy artifacts to target -> Archive & Clean |
---
## Cadence Control
**Beat model**: Event-driven, each beat = executor wake -> process -> spawn -> STOP.
```
Beat Cycle (single beat)
======================================================================
Event Executor 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 executor for simple linear successors)
======================================================================
[Worker A] Phase 5 complete
+- 1 ready task? simple successor? --> spawn team-worker B directly
+- complex case? --> SendMessage to executor
======================================================================
```
---
## Integration with team-coordinate
| Scenario | Skill |
|----------|-------|
| New task, no session | team-coordinate |
| Existing session, resume execution | **team-executor** |
| Session needs new roles | team-coordinate (with resume) |
| Pure execution, no analysis | **team-executor** |
---
## Error Handling
| Scenario | Resolution |
|----------|------------|
| No --session provided | ERROR immediately with usage message |
| Session directory not found | ERROR with path, suggest checking path |
| team-session.json missing | ERROR, session incomplete, suggest re-run team-coordinate |
| task-analysis.json missing | ERROR, session incomplete, suggest re-run team-coordinate |
| No role-specs in session | ERROR, session incomplete, suggest re-run team-coordinate |
| Role-spec file not found | ERROR with expected path |
| capability_gap reported | Warn only, cannot generate new role-specs |
| Fast-advance spawns wrong task | Executor reconciles on next callback |
| Completion action fails | Default to Keep Active, log warning |

View File

@@ -0,0 +1,239 @@
# Command: monitor
## Purpose
Event-driven pipeline coordination with Spawn-and-Stop pattern for team-executor v2. Role names are read from `team-session.json#roles`. Workers are spawned as `team-worker` agents with role-spec paths. **handleAdapt is LIMITED**: only warns, cannot generate new role-specs. Includes `handleComplete` for pipeline completion action.
## Constants
| Constant | Value | Description |
|----------|-------|-------------|
| SPAWN_MODE | background | All workers spawned via `Task(run_in_background: true)` |
| ONE_STEP_PER_INVOCATION | true | Executor does one operation then STOPS |
| FAST_ADVANCE_AWARE | true | Workers may skip executor for simple linear successors |
| ROLE_GENERATION | disabled | handleAdapt cannot generate new role-specs |
| WORKER_AGENT | team-worker | All workers spawned as team-worker agents |
## Phase 2: Context Loading
| Input | Source | Required |
|-------|--------|----------|
| Session file | `<session-folder>/team-session.json` | Yes |
| Task list | `TaskList()` | Yes |
| Active workers | session.active_workers[] | Yes |
| Role registry | session.roles[] | Yes |
**Dynamic role resolution**: Known worker roles are loaded from `session.roles[].name`. Role-spec paths are in `session.roles[].role_spec`.
## Phase 3: Handler Routing
### Wake-up Source Detection
Parse `$ARGUMENTS` to determine handler:
| Priority | Condition | Handler |
|----------|-----------|---------|
| 1 | Message contains `[<role-name>]` from session roles | handleCallback |
| 2 | Contains "capability_gap" | handleAdapt |
| 3 | Contains "check" or "status" | handleCheck |
| 4 | Contains "resume", "continue", or "next" | handleResume |
| 5 | Pipeline detected as complete | handleComplete |
| 6 | None of the above (initial spawn after dispatch) | handleSpawnNext |
---
### Handler: handleCallback
Worker completed a task. Verify completion, update state, auto-advance.
```
Receive callback from [<role>]
+- Find matching active worker by role (from session.roles)
+- Is this a progress update (not final)?
| +- YES -> Update session state, do NOT remove from active_workers -> STOP
+- Task status = completed?
| +- YES -> remove from active_workers -> update session
| | +- -> handleSpawnNext
| +- NO -> progress message, do not advance -> STOP
+- No matching worker found
+- Scan all active workers for completed tasks
+- Found completed -> process each -> handleSpawnNext
+- None completed -> STOP
```
**Fast-advance note**: Check if expected next task is already `in_progress` (fast-advanced). If yes -> skip spawning, sync active_workers.
---
### Handler: handleCheck
Read-only status report. No pipeline advancement.
```
[executor] Pipeline Status
[executor] Progress: <completed>/<total> (<percent>%)
[executor] Execution Graph:
<visual representation with status icons>
done=completed >>>=running o=pending .=not created
[executor] Active Workers:
> <subject> (<role>) - running <elapsed>
[executor] Ready to spawn: <subjects>
[executor] Commands: 'resume' to advance | 'check' to refresh
```
Then STOP.
---
### Handler: handleResume
Check active worker completion, process results, advance pipeline.
```
Load active_workers from session
+- No active workers -> handleSpawnNext
+- Has active workers -> check each:
+- status = completed -> mark done, log
+- status = in_progress -> still running, log
+- other status -> worker failure -> reset to pending
After processing:
+- Some completed -> handleSpawnNext
+- All still running -> report status -> STOP
+- All failed -> handleSpawnNext (retry)
```
---
### Handler: handleSpawnNext
Find all ready tasks, spawn team-worker agents in background, update session, STOP.
```
Collect task states from TaskList()
+- completedSubjects: status = completed
+- inProgressSubjects: status = in_progress
+- readySubjects: pending + all blockedBy in completedSubjects
Ready tasks found?
+- NONE + work in progress -> report waiting -> STOP
+- NONE + nothing in progress -> PIPELINE_COMPLETE -> handleComplete
+- HAS ready tasks -> for each:
+- Is task owner an Inner Loop role AND already has active_worker?
| +- YES -> SKIP spawn (existing worker picks it up)
| +- NO -> normal spawn below
+- TaskUpdate -> in_progress
+- team_msg log -> task_unblocked (team=<session-id>)
+- Spawn team-worker (see spawn tool call below)
+- Add to session.active_workers
Update session file -> output summary -> STOP
```
**Spawn worker tool call**:
```
Task({
subagent_type: "team-worker",
description: "Spawn <role> worker for <subject>",
team_name: <team-name>,
name: "<role>",
run_in_background: true,
prompt: `## Role Assignment
role: <role>
role_spec: <session-folder>/role-specs/<role>.md
session: <session-folder>
session_id: <session-id>
team_name: <team-name>
requirement: <task-description>
inner_loop: <true|false>
Read role_spec file to load Phase 2-4 domain instructions.`
})
```
---
### Handler: handleComplete
Pipeline complete. Execute completion action.
```
All tasks completed (no pending, no in_progress)
+- Generate pipeline summary (deliverables, stats, duration)
+- Read session.completion_action:
|
+- "interactive":
| AskUserQuestion -> user choice:
| +- "Archive & Clean": session status="completed" -> TeamDelete -> summary
| +- "Keep Active": session status="paused" -> resume command
| +- "Export Results": copy artifacts -> Archive & Clean
|
+- "auto_archive": Execute Archive & Clean
+- "auto_keep": Execute Keep Active
```
**Fallback**: If completion action fails, default to Keep Active, log warning.
---
### Handler: handleAdapt (LIMITED)
**UNLIKE team-coordinate, executor CANNOT generate new role-specs.**
```
Receive capability_gap from [<role>]
+- Log via team_msg (type: warning)
+- Check existing roles -> does any cover this?
| +- YES -> redirect to that role -> STOP
| +- NO -> genuine gap, report to user:
| "Capability gap detected. team-executor cannot generate new role-specs.
| Options: 1. Continue 2. Re-run team-coordinate 3. Manually add role-spec"
+- Continue execution with existing roles
```
---
### Worker Failure Handling
1. Reset task -> pending via TaskUpdate
2. Log via team_msg (type: error)
3. Report to user: task reset, will retry on next resume
### Fast-Advance Failure Recovery
Detect orphaned tasks (in_progress without active_worker, > 5 minutes) -> reset to pending -> handleSpawnNext.
### Consensus-Blocked Handling
```
Route by severity:
+- HIGH: Create REVISION task (max 1). Already revised -> PAUSE for user
+- MEDIUM: Proceed with warning, log to wisdom/issues.md
+- LOW: Proceed normally as consensus_reached with notes
```
## Phase 4: Validation
| Check | Criteria |
|-------|----------|
| Session state consistent | active_workers matches TaskList in_progress tasks |
| No orphaned tasks | Every in_progress task has an active_worker entry |
| Dynamic roles valid | All task owners exist in session.roles |
| Completion detection | readySubjects=0 + inProgressSubjects=0 -> PIPELINE_COMPLETE |
| Fast-advance tracking | Detect fast-advanced tasks, sync to active_workers |
## Error Handling
| Scenario | Resolution |
|----------|------------|
| Session file not found | Error, suggest re-run team-coordinate |
| Worker callback from unknown role | Log info, scan for other completions |
| All workers still running on resume | Report status, suggest check later |
| Pipeline stall | Check for missing tasks, report to user |
| Fast-advance conflict | Executor reconciles, no duplicate spawns |
| Role-spec file not found | Error, cannot proceed |
| capability_gap | WARN only, cannot generate new role-specs |
| Completion action fails | Default to Keep Active, log warning |

View File

@@ -0,0 +1,171 @@
# Executor Role
Orchestrate the team-executor workflow: session validation, state reconciliation, team-worker dispatch, progress monitoring, completion action. The sole built-in role -- all worker roles are loaded from session role-specs and spawned via team-worker agent.
## Identity
- **Name**: `executor` | **Tag**: `[executor]`
- **Responsibility**: Validate session -> Reconcile state -> Create team -> Dispatch team-worker agents -> Monitor progress -> Completion action -> Report results
## Boundaries
### MUST
- Validate session structure before any execution
- Reconcile session state with TaskList on startup
- Reset in_progress tasks to pending (interrupted tasks)
- Detect fast-advance orphans and reset to pending
- Spawn team-worker agents in background (NOT general-purpose)
- Monitor progress via worker callbacks and route messages
- Maintain session state persistence (team-session.json)
- Handle capability_gap reports with warning only (cannot generate role-specs)
- Execute completion action when pipeline finishes
### MUST NOT
- Execute task work directly (delegate to workers)
- Modify task output artifacts (workers own their deliverables)
- Call implementation subagents (code-developer, etc.) directly
- Generate new role-specs (use existing session role-specs only)
- Skip session validation
- Override consensus_blocked HIGH without user confirmation
- Spawn workers with `general-purpose` agent (MUST use `team-worker`)
> **Core principle**: executor is the orchestrator, not the executor. All actual work is delegated to session-defined worker roles via team-worker agents. Unlike team-coordinate coordinator, executor CANNOT generate new role-specs.
---
## Entry Router
When executor is invoked, first detect the invocation type:
| Detection | Condition | Handler |
|-----------|-----------|---------|
| Worker callback | Message contains `[role-name]` from session roles | -> handleCallback |
| Status check | Arguments contain "check" or "status" | -> handleCheck |
| Manual resume | Arguments contain "resume" or "continue" | -> handleResume |
| Capability gap | Message contains "capability_gap" | -> handleAdapt |
| Pipeline complete | All tasks completed, no pending/in_progress | -> handleComplete |
| New execution | None of above | -> Phase 0 |
For callback/check/resume/adapt/complete: load `commands/monitor.md` and execute the appropriate handler, then STOP.
---
## Phase 0: Session Validation + State Reconciliation
**Objective**: Validate session structure and reconcile session state with actual task status.
### Step 1: Session Validation
Validate session structure (see SKILL.md Session Validation):
- [ ] Directory exists at session path
- [ ] `team-session.json` exists and parses
- [ ] `task-analysis.json` exists and parses
- [ ] `role-specs/` directory has >= 1 .md files
- [ ] All roles in team-session.json#roles have corresponding role-spec .md files
- [ ] Role-spec files have valid YAML frontmatter + Phase 2-4 sections
If validation fails -> ERROR with specific reason -> STOP
### Step 2: Load Session State
Read team-session.json and task-analysis.json.
### Step 3: Reconcile with TaskList
Compare TaskList() with session.completed_tasks, bidirectional sync.
### Step 4: Reset Interrupted Tasks
Reset any in_progress tasks to pending.
### Step 5: Detect Fast-Advance Orphans
In_progress tasks without matching active_worker + created > 5 minutes -> reset to pending.
### Step 6: Create Missing Tasks (if needed)
For each task in task-analysis, check if exists in TaskList, create if missing.
### Step 7: Update Session File
Write reconciled team-session.json.
### Step 8: Team Setup
TeamCreate if team does not exist.
**Success**: Session validated, state reconciled, team ready -> Phase 1
---
## Phase 1: Spawn-and-Stop
**Objective**: Spawn first batch of ready workers as team-worker agents in background, then STOP.
**Workflow**:
1. Load `commands/monitor.md`
2. Find tasks with: status=pending, blockedBy all resolved, owner assigned
3. For each ready task -> spawn team-worker (see SKILL.md Executor Spawn Template)
4. Output status summary with execution graph
5. STOP
**Pipeline advancement** driven by three wake sources:
- Worker callback (automatic) -> Entry Router -> handleCallback
- User "check" -> handleCheck (status only)
- User "resume" -> handleResume (advance)
---
## Phase 2: Report + Completion Action
**Objective**: Completion report, interactive completion choice, and follow-up options.
**Workflow**:
1. Load session state -> count completed tasks, duration
2. List all deliverables with output paths in `<session>/artifacts/`
3. Include discussion summaries (if inline discuss was used)
4. Summarize wisdom accumulated during execution
5. Output report:
```
[executor] ============================================
[executor] TASK COMPLETE
[executor]
[executor] Deliverables:
[executor] - <artifact-1.md> (<producer role>)
[executor] - <artifact-2.md> (<producer role>)
[executor]
[executor] Pipeline: <completed>/<total> tasks
[executor] Roles: <role-list>
[executor] Duration: <elapsed>
[executor]
[executor] Session: <session-folder>
[executor] ============================================
```
6. **Execute Completion Action** (based on session.completion_action):
| Mode | Behavior |
|------|----------|
| `interactive` | AskUserQuestion with Archive/Keep/Export options |
| `auto_archive` | Execute Archive & Clean without prompt |
| `auto_keep` | Execute Keep Active without prompt |
**Interactive handler**: See SKILL.md Completion Action section.
---
## Error Handling
| Error | Resolution |
|-------|------------|
| Session validation fails | ERROR with specific reason, suggest re-run team-coordinate |
| Task timeout | Log, mark failed, ask user to retry or skip |
| Worker crash | Respawn worker, reassign task |
| Session corruption | Attempt recovery, fallback to manual reconciliation |
| capability_gap reported | handleAdapt: WARN only, cannot generate new role-specs |
| All workers still running on resume | Report status, suggest check later |
| Pipeline stall (no ready, no running) | Check for missing tasks, report to user |
| Fast-advance conflict | Executor reconciles, no duplicate spawns |
| Role-spec file not found | ERROR, cannot proceed without role definition |
| Completion action fails | Default to Keep Active, log warning |

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