Compare commits

...

32 Commits

Author SHA1 Message Date
catlog22
3341a2e772 chore: release v7.2.4 2026-03-08 23:44:55 +08:00
catlog22
61ea9d47a6 Enhance UX and Coordinator Role Constraints in Skills Documentation
- Added detailed constraints for the Coordinator role in the team UX improvement skill, emphasizing orchestration responsibilities and workflow management.
- Updated test cases in DashboardToolbar, useIssues, and useWebSocket to improve reliability and clarity.
- Introduced new tests for configStore and ignore patterns in Codex Lens to ensure proper functionality and configuration handling.
- Enhanced smart search functionality with improved embedding selection logic and added tests for various scenarios.
- Updated installation and usage documentation to reflect changes in directory structure and role specifications.
2026-03-08 23:43:44 +08:00
catlog22
f3ae78f95e fix(configStore): add type guard for CLI tool type validation
- Add isValidType type guard to ensure type safety
- Validate tool type against allowed values before assignment
- Fixes TypeScript compilation error in build
2026-03-08 21:43:43 +08:00
catlog22
334f82eaad feat(app): sync backend config on app initialization
- Call syncConfigStoreFromBackend() on app mount
- Export __testables from smart-search for testing
- Complements configStore refactoring
2026-03-08 21:41:27 +08:00
catlog22
1c1a4afd23 chore: release v7.2.3 2026-03-08 21:39:31 +08:00
catlog22
c014c0568a refactor(configStore): extract backend config sync logic into reusable function
- Extract onRehydrateStorage fetch logic into syncConfigStoreFromBackend()
- Add helper functions: getBackendConfigUrl() and extractCliToolsFromBackend()
- Add promise deduplication to prevent concurrent sync requests
- Improve type safety and error handling
2026-03-08 21:39:30 +08:00
catlog22
62d8aa3623 Add unit tests for various components and stores in the terminal dashboard
- Implement tests for AssociationHighlight, DashboardToolbar, QueuePanel, SessionGroupTree, and TerminalDashboardPage to ensure proper functionality and state management.
- Create tests for cliSessionStore, issueQueueIntegrationStore, queueExecutionStore, queueSchedulerStore, sessionManagerStore, and terminalGridStore to validate state resets and workspace scoping.
- Mock necessary dependencies and state management hooks to isolate tests and ensure accurate behavior.
2026-03-08 21:38:20 +08:00
catlog22
9aa07e8d01 Add comprehensive tests for CLI functionality and CodexLens compatibility
- Introduced tests for stale running fallback in CLI watch functionality to ensure proper handling of saved conversations.
- Added compatibility tests for CodexLens CLI to verify index initialization despite compatibility conflicts.
- Implemented tests for Smart Search MCP usage to validate default settings and path handling.
- Created tests for UV Manager to ensure Python preference handling works as expected.
- Added a detailed guide for CCW/Codex commands and skills, covering core commands, execution modes, and templates.
2026-03-08 17:30:39 +08:00
catlog22
4254eeeaa7 docs: update CCW Commands & Skills reference with 8-field format
- Add CCW-COMMANDS-SKILLS-REFERENCE.md with comprehensive documentation
- Update docs/reference/commands-skills.md (English)
- Update docs/zh/reference/commands-skills.md (Chinese)
- Include 55 Slash Commands and 41 Skills
- Each entry follows 8-field format: Who, When, What, How, Output, Done, Failure & Recovery, Impact & Boundary
- Exclude academic skills (scholar-*, journal-paper-writing, software-manual)
2026-03-08 17:09:23 +08:00
catlog22
6a47447e3a chore: release v7.2.2 2026-03-07 23:33:10 +08:00
catlog22
723c1b0e38 fix(AppShell): handle store rehydration errors gracefully and improve initialization logic 2026-03-07 23:30:37 +08:00
catlog22
80d8954b7a Add roles for fixer, reproducer, tester, verifier, and supervisor with detailed workflows
- Introduced `fixer` role for implementing code fixes based on RCA reports, including phases for parsing RCA, planning fixes, implementing changes, and documenting results.
- Added `reproducer` role for bug reproduction and evidence collection using Chrome DevTools, detailing steps for navigating to target URLs, executing reproduction steps, and capturing evidence.
- Created `tester` role for feature-driven testing, outlining processes for parsing feature lists, executing test scenarios, and reporting discovered issues.
- Established `verifier` role for fix verification, focusing on re-executing reproduction steps and comparing evidence before and after fixes.
- Implemented `supervisor` role for overseeing pipeline phase transitions, ensuring consistency across artifacts and compliance with processes.
- Added specifications for debug tools and pipeline definitions to standardize usage patterns and task management across roles.
2026-03-07 22:52:40 +08:00
catlog22
0d01e7bc50 feat: 添加架构约束和编码规范文档,增强项目文档的完整性 2026-03-07 19:34:08 +08:00
catlog22
8b07d52323 Merge PR #138: 修复codex调用无输出问题
- Fix prompt input priority (stdin demoted to #4 to prevent blocking in host CLI)
- Add auto-stream in Claude Code task environment (CLAUDECODE + non-TTY)
- Add codex JSONL passthrough with command_execution filtering
- Add rawLine field to CliOutputUnit for pass-through streaming
- Add deepwiki-service getStats() (kept HEAD's extended version)
- Add comprehensive tests for non-TTY and Claude Code scenarios
- Remove deprecated sync-version.mjs script
2026-03-07 19:04:23 +08:00
catlog22
e368f9f8cc fix(ddd): address critical issues from code review
Critical fixes for DDD artifact structure enhancements:

TASK-003 (links{} navigation):
- Fixed relative path calculation in plan.md
- Changed doc_index path from ../../.doc-index/doc-index.json to ../../../doc-index.json
- Changed feature_maps path from ../../.doc-index/feature-maps/auth.md to ../../../feature-maps/auth.md
- Paths now correctly resolve from .workflow/.doc-index/planning/{session}/.task/

TASK-006 (schema versioning):
- Implemented schema_version check in plan.md Phase 1.0
- Implemented schema_version check in sync.md Phase 0.1
- Both commands now validate doc-index schema compatibility before processing
- Enables safe schema evolution and migration detection

TASK-005 (overview docs):
- Made sessions/_index.md update explicit in sync.md Phase 4.4
- Changed vague "Update _index.md files" to explicit "Update sessions/_index.md with new planning sessions"
- Ensures sessions index is properly maintained during sync operations

Session structure:
- Added .process/ directory to session folder structure documentation
- Clarifies where doc-context-package.json is stored
- Prevents first-run failures due to missing directory

All fixes maintain backward compatibility and follow graceful degradation patterns.
2026-03-07 18:17:10 +08:00
catlog22
eaaadcd164 feat: 添加执行ID和子命令功能,增强CLI工具的输出选项和文档生成 2026-03-07 17:57:30 +08:00
catlog22
ece4afcac8 feat: Implement DeepWiki generator and CLI integration
- Added `deepwiki_generator.py` for generating documentation from source code.
- Integrated symbol extraction and markdown generation for supported file types.
- Implemented database migration for legacy timestamp formats in DeepWikiStore.
- Enhanced debug logging for better traceability during conversation and store operations.
- Updated dependencies in `PKG-INFO` and `requires.txt` for compatibility.
- Added new tests for the DeepWiki generator and storage functionalities.
- Refactored existing code for improved readability and maintainability.
2026-03-07 17:05:49 +08:00
catlog22
75d5f7f230 feat: 添加参数模式不匹配检测功能,提供用户友好的错误信息
fix: 更新数据库字段类型,确保时间戳使用REAL类型
refactor: 优化DeepWiki服务和存储的查询逻辑,支持批量路径处理
refactor: 移除无用的worker_agent字段,简化团队配置
2026-03-07 14:36:12 +08:00
catlog22
29a1fea467 feat: Add templates for epics, product brief, and requirements documentation
- Introduced a comprehensive template for generating epics and stories in Phase 5, including an index and individual epic files.
- Created a product brief template for Phase 2 to summarize product vision, goals, and target users.
- Developed a requirements PRD template for Phase 3, outlining functional and non-functional requirements, along with traceability matrices.

feat: Implement tech debt roles for assessment, execution, planning, scanning, validation, and analysis

- Added roles for tech debt assessment, executor, planner, scanner, validator, and analyst, each with defined phases and processes for managing technical debt.
- Each role includes structured input requirements, processing strategies, and output formats to ensure consistency and clarity in tech debt management.
2026-03-07 13:32:04 +08:00
catlog22
7ee9b579fa feat: add DDD scan, sync, and update commands for document indexing
- Implemented `/ddd:scan` command to analyze existing codebases and generate document indices without specifications. This includes phases for project structure analysis, component discovery, feature inference, and requirement extraction.
- Introduced `/ddd:sync` command for post-task synchronization, updating document indices, generating action logs, and refreshing feature/component documentation after development tasks.
- Added `/ddd:update` command for lightweight incremental updates to the document index, allowing for quick impact checks during development and pre-commit validation.
- Created `execute.md` for the coordinator role in the team lifecycle, detailing the spawning of executor team-workers for IMPL tasks.
- Added `useHasHydrated` hook to determine if the Zustand workflow store has been rehydrated from localStorage, improving state management reliability.
2026-03-07 00:00:18 +08:00
catlog22
a9469a5e3b feat: add spec-setup command for project initialization and interactive configuration
- Introduced a new command `spec-setup` to initialize project-level state.
- Generates `.workflow/project-tech.json` and `.ccw/specs/*.md` files.
- Implements a multi-round interactive questionnaire for configuring project guidelines.
- Supports flags for regeneration, skipping specs, and resetting existing content.
- Integrates analysis via `cli-explore-agent` for comprehensive project understanding.
- Provides detailed execution process and error handling for various scenarios.
2026-03-06 16:49:35 +08:00
qinsehm1128
e87e3feba8 修复codex调用无输出问题 2026-03-06 16:17:13 +08:00
catlog22
f2d4364c69 Refactor multi-CLI planning documentation, enhance analyze-with-file skill, and implement timeout for DeepWiki API requests
- Updated SKILL.md for workflow-multi-cli-plan to streamline sections, clarify processes, and improve user decision points.
- Enhanced analyze-with-file skill to include hypothesis impact in key findings and refined recording principles for better documentation.
- Added fetchWithTimeout function to DeepWiki API calls to handle request timeouts, ensuring more robust error handling.
- Introduced new DeepWiki routes in server.ts to manage API requests effectively.
- Updated tsconfig.tsbuildinfo to reflect recent changes in the codebase structure.
2026-03-06 15:54:40 +08:00
catlog22
88149b6154 fix: 使用127.0.0.1替代localhost以确保IPv4连接,避免IPv6解析问题 2026-03-06 11:43:14 +08:00
catlog22
33cc451b61 feat: Add role specifications for 三省六部 architecture
- Introduced role specifications for 尚书省 (shangshu), 刑部 (xingbu), and 中书省 (zhongshu) to facilitate task management and execution flow.
- Implemented quality gates for each phase of the process to ensure compliance and quality assurance.
- Established a coordinator role to manage the overall workflow and task distribution among the departments.
- Created a team configuration file to define roles, responsibilities, and routing rules for task execution.
- Added localization support for DeepWiki in both English and Chinese, enhancing accessibility for users.
2026-03-06 11:26:27 +08:00
catlog22
56c06ecf3d Rename workflow-lite-planex to workflow-lite-plan across documentation and code references for consistency and clarity. Update related examples, command references, and workflow comparisons to reflect the new naming convention. 2026-03-05 21:14:52 +08:00
catlog22
cff1e16441 feat: 更新A2UIButton组件以支持A2UI快速操作和可用性检查;增强InjectionControlTab和QueueExecutionListView组件的错误处理和用户提示 2026-03-05 20:02:46 +08:00
catlog22
3fd55ebd4b feat: Add Role Analysis Reviewer Agent and validation template
- Introduced Role Analysis Reviewer Agent to validate role analysis outputs against templates and quality standards.
- Created a detailed validation ruleset for the system-architect role, including mandatory and recommended sections.
- Added JSON validation report structure for output.
- Implemented execution command for validation process.

test: Add UX tests for HookCard component

- Created comprehensive tests for HookCard component, focusing on delete confirmation UX pattern.
- Verified confirmation dialog appearance, deletion functionality, and button interactions.
- Ensured proper handling of state updates and visual feedback for enabled/disabled status.

test: Add UX tests for ThemeSelector component

- Developed tests for ThemeSelector component, emphasizing delete confirmation UX pattern.
- Validated confirmation dialog display, deletion actions, and toast notifications for undo functionality.
- Ensured proper management of theme slots and state updates.

feat: Implement useDebounce hook

- Added useDebounce hook to delay expensive computations or API calls, enhancing performance.

feat: Create System Architect Analysis Template

- Developed a comprehensive template for system architect role analysis, covering required sections such as architecture overview, data model, state machine, error handling strategy, observability requirements, configuration model, and boundary scenarios.
- Included examples and templates for each section to guide users in producing SPEC.md-level precision modeling.
2026-03-05 19:58:10 +08:00
catlog22
bc7a556985 feat: 增加DeepWiki页面和侧边栏导航支持,更新Hook管理功能以支持作用域和索引 2026-03-05 18:53:24 +08:00
catlog22
fb4f6e718e feat: Implement DeepWiki documentation generation tools
- Added `__init__.py` in `codexlens/tools` for documentation generation.
- Created `deepwiki_generator.py` to handle symbol extraction and markdown generation.
- Introduced `MockMarkdownGenerator` for testing purposes.
- Implemented `DeepWikiGenerator` class for managing documentation generation and file processing.
- Added unit tests for `DeepWikiStore` to ensure proper functionality and error handling.
- Created tests for DeepWiki TypeScript types matching.
2026-03-05 18:30:56 +08:00
catlog22
0bfae3fd1a feat: 更新CodexLens描述,增加操作和参数说明 2026-03-05 16:43:42 +08:00
catlog22
3d92478772 feat: Implement UX improvement pipeline with role specifications and task management
- Added role specifications for explorer, implementer, scanner, tester, and diagnoser.
- Created dispatch and monitor commands for orchestrating task execution.
- Defined team configuration for the UX improvement pipeline, including roles and responsibilities.
- Established structured task descriptions for scanning, diagnosing, designing, implementing, and testing UI components.
- Introduced caching mechanisms for exploration results and context accumulation for implementer tasks.
- Enhanced error handling and validation processes across roles.
2026-03-05 16:42:56 +08:00
697 changed files with 83782 additions and 51156 deletions

View File

@@ -1,27 +0,0 @@
---
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

@@ -1,25 +0,0 @@
---
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

@@ -1,33 +1,6 @@
---
title: "Architecture Constraints"
dimension: specs
category: planning
keywords:
- architecture
- module
- layer
- pattern
readMode: required
priority: high
scope: project
---
# Architecture Constraints
## Module Boundaries
## Schema Evolution
- 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
- [compatibility] When enhancing existing schemas, use optional fields and additionalProperties rather than creating new schemas. Avoid breaking changes.
- [portability] Use relative paths for cross-artifact navigation to ensure portability across different environments and installations.

View File

@@ -1,39 +1,17 @@
---
title: "Coding Conventions"
dimension: specs
category: general
keywords:
- typescript
- naming
- style
- convention
readMode: required
priority: high
scope: project
---
# Coding Conventions
## Naming
## Navigation & Path Handling
- Use camelCase for variables and functions
- Use PascalCase for classes and interfaces
- Use UPPER_SNAKE_CASE for constants
- [navigation] When creating navigation links between artifacts, always compute relative paths from the artifact's actual location, not from an assumed location. Test path resolution before committing. (learned: 2026-03-07)
- [schema] Always include schema_version field in index/registry files to enable safe evolution and migration detection. (learned: 2026-03-07)
- [error-handling] When adding version checks or validation, always continue with degraded functionality rather than failing hard. Log warnings but don't block execution. (learned: 2026-03-07)
## Formatting
## Document Generation
- 2-space indentation
- Single quotes for strings
- Trailing commas in multi-line constructs
- [architecture] For document generation systems, adopt Layer 3→2→1 pattern (components → features → indexes) for efficient incremental updates. (learned: 2026-03-07)
## Patterns
## Implementation Quality
- 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
- [validation] Path calculation errors are subtle and hard to spot in static review. Always verify path resolution from the actual file location, not from documentation. (learned: 2026-03-07)
- [implementation] Declaring "add X to Y" in documentation is not enough - the actual logic must be implemented in the target files. (learned: 2026-03-07)
- [clarity] Explicit instructions are better than implicit ones. Vague instructions like "Update _index.md files" should be made explicit (e.g., "Update sessions/_index.md"). (learned: 2026-03-07)

View File

@@ -216,7 +216,7 @@ rg "export.*Component" --files-with-matches --type ts
CONTEXT: @components/Auth.tsx @types/auth.d.ts | Memory: Previous type refactoring
# Step 3: Execute CLI
ccw cli -p "..." --tool <tool-id> --mode analysis --cd src
ccw cli -p "..." --tool <tool-id> --mode analysis --cd "src"
```
### --rule Configuration
@@ -313,14 +313,20 @@ ccw cli -p "..." --tool gemini --mode analysis --rule analysis-review-architectu
- Description: Model override
- Default: Tool's primaryModel from config
- **`--cd <path>`**
- Description: Working directory
- **`--cd "<path>"`**
- Description: Working directory (quote if path contains spaces)
- Default: current
- **`--includeDirs <dirs>`**
- Description: Additional directories (comma-separated)
- **`--includeDirs "<dirs>"`**
- Description: Additional directories (comma-separated, quote if paths contain spaces)
- Default: none
- **`--id <id>`**
- Description: Execution ID (recommended, auto-generated if omitted)
- Default: Auto-generated in format `{prefix}-{HHmmss}-{rand4}` (e.g., `gem-143022-x7k2`)
- Prefix mapping: gemini→gem, qwen→qwn, codex→cdx, claude→cld, opencode→opc
- Note: ID is always output to stderr as `[CCW_EXEC_ID=<id>]` for programmatic capture
- **`--resume [id]`**
- Description: Resume previous session
- Default: -
@@ -347,10 +353,10 @@ When using `--cd`:
```bash
# Single directory
ccw cli -p "CONTEXT: @**/* @../shared/**/*" --tool <tool-id> --mode analysis --cd src/auth --includeDirs ../shared
ccw cli -p "CONTEXT: @**/* @../shared/**/*" --tool <tool-id> --mode analysis --cd "src/auth" --includeDirs "../shared"
# Multiple directories
ccw cli -p "..." --tool <tool-id> --mode analysis --cd src/auth --includeDirs ../shared,../types,../utils
ccw cli -p "..." --tool <tool-id> --mode analysis --cd "src/auth" --includeDirs "../shared,../types,../utils"
```
**Rule**: If CONTEXT contains `@../dir/**/*`, MUST include `--includeDirs ../dir`
@@ -385,6 +391,65 @@ ASSISTANT RESPONSE: [Previous output]
[Your new prompt]
```
### Subcommands
#### `show` — List All Executions
```bash
ccw cli show # Active + recent completed executions
ccw cli show --all # Include full history
```
Displays a unified table of running and recent executions with: ID, Tool, Mode, Status, Duration, Prompt Preview.
#### `watch <id>` — Stream Execution Output
```bash
ccw cli watch <id> # Stream until completion (output to stderr)
ccw cli watch <id> --timeout 120 # Auto-exit after 120 seconds
```
Behavior:
- Output written to **stderr** (does not pollute stdout)
- Exit code: 0 = success, 1 = error, 2 = timeout
- Callers can `ccw cli watch <id> 2>/dev/null` to silently wait
#### `output <id>` — Get Execution Output
```bash
ccw cli output <id> # Final result only (default)
ccw cli output <id> --verbose # Full metadata + raw output
ccw cli output <id> --raw # Raw stdout (for piping)
```
Default returns `finalOutput > parsedOutput > stdout` — agent's final response text only.
`--verbose` shows full metadata (ID, turn, status, project) plus raw stdout/stderr.
#### ID Workflow Example
```bash
# Execute with auto-generated ID
ccw cli -p "analyze code" --tool gemini --mode analysis
# stderr outputs: [CCW_EXEC_ID=gem-143022-x7k2]
# Execute with custom ID
ccw cli -p "implement feature" --tool gemini --mode write --id my-task-1
# stderr outputs: [CCW_EXEC_ID=my-task-1]
# Check status
ccw cli show
# Watch running execution
ccw cli watch gem-143022-x7k2
# Get final result
ccw cli output gem-143022-x7k2
# Capture ID programmatically
EXEC_ID=$(ccw cli -p "test" --tool gemini --mode analysis 2>&1 | grep -oP 'CCW_EXEC_ID=\K[^\]]+')
ccw cli output $EXEC_ID
```
### Command Examples
#### Task-Type Specific Templates
@@ -397,7 +462,7 @@ MODE: analysis
CONTEXT: @src/auth/**/* @src/middleware/auth.ts | Memory: Using bcrypt for passwords, JWT for sessions
EXPECTED: Security report with: severity matrix, file:line references, CVE mappings where applicable, remediation code snippets prioritized by risk
CONSTRAINTS: Focus on authentication | Ignore test files
" --tool gemini --mode analysis --rule analysis-assess-security-risks --cd src/auth
" --tool gemini --mode analysis --rule analysis-assess-security-risks --cd "src/auth"
```
**Implementation Task** (New Feature):
@@ -419,7 +484,7 @@ MODE: analysis
CONTEXT: @src/websocket/**/* @src/services/connection-manager.ts | Memory: Using ws library, ~5000 concurrent connections in production
EXPECTED: Root cause analysis with: memory profile, leak source (file:line), fix recommendation with code, verification steps
CONSTRAINTS: Focus on resource cleanup
" --tool gemini --mode analysis --rule analysis-diagnose-bug-root-cause --cd src
" --tool gemini --mode analysis --rule analysis-diagnose-bug-root-cause --cd "src"
```
**Refactoring Task**:

View File

@@ -783,7 +783,7 @@ All workflows use the same file structure definition regardless of complexity. *
**Examples**:
*Workflow Commands (lightweight):*
- `/workflow-lite-planex "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

@@ -0,0 +1,293 @@
---
name: team-supervisor
description: |
Message-driven resident agent for pipeline supervision. Spawned once per session,
stays alive across checkpoint tasks, woken by coordinator via SendMessage.
Unlike team-worker (task-discovery lifecycle), team-supervisor uses a message-driven
lifecycle: Init → idle → wake → execute → idle → ... → shutdown.
Reads message bus + artifacts (read-only), produces supervision reports.
Examples:
- Context: Coordinator spawns supervisor at session start
user: "role: supervisor\nrole_spec: .../supervisor/role.md\nsession: .workflow/.team/TLV4-xxx"
assistant: "Loading role spec, initializing baseline context, reporting ready, going idle"
commentary: Agent initializes once, then waits for checkpoint assignments via SendMessage
- Context: Coordinator wakes supervisor for checkpoint
user: (SendMessage) "## Checkpoint Request\ntask_id: CHECKPOINT-001\nscope: [DRAFT-001, DRAFT-002]"
assistant: "Claiming task, loading incremental context, executing checks, reporting verdict"
commentary: Agent wakes, executes one checkpoint, reports, goes idle again
color: cyan
---
You are a **resident pipeline supervisor**. You observe the pipeline's health across checkpoint boundaries, maintaining context continuity in-memory.
**You are NOT a team-worker.** Your lifecycle is fundamentally different:
- team-worker: discover task → execute → report → STOP
- team-supervisor: init → idle → [wake → execute → idle]* → shutdown
---
## Prompt Input Parsing
Parse the following fields from your prompt:
| Field | Required | Description |
|-------|----------|-------------|
| `role` | Yes | Always `supervisor` |
| `role_spec` | Yes | Path to supervisor role.md |
| `session` | Yes | Session folder path |
| `session_id` | Yes | Session ID for message bus operations |
| `team_name` | Yes | Team name for SendMessage |
| `requirement` | Yes | Original task/requirement description |
| `recovery` | No | `true` if respawned after crash — triggers recovery protocol |
---
## Lifecycle
```
Entry:
Parse prompt → extract fields
Read role_spec → load checkpoint definitions (Phase 2-4 instructions)
Init Phase:
Load baseline context (all role states, wisdom, session state)
context_accumulator = []
SendMessage(coordinator, "ready")
→ idle
Wake Cycle (coordinator sends checkpoint request):
Parse message → task_id, scope
TaskUpdate(task_id, in_progress)
Incremental context load (only new data since last wake)
Execute checkpoint checks (from role_spec)
Write report artifact
TaskUpdate(task_id, completed)
team_msg state_update
Accumulate to context_accumulator
SendMessage(coordinator, checkpoint report)
→ idle
Shutdown (coordinator sends shutdown_request):
shutdown_response(approve: true)
→ die
```
---
## Init Phase
Run once at spawn. Build baseline understanding of the pipeline.
### Step 1: Load Role Spec
```
Read role_spec path → parse frontmatter + body
```
Body contains checkpoint-specific check definitions (CHECKPOINT-001, 002, 003).
### Step 2: Load Baseline Context
```
team_msg(operation="get_state", session_id=<session_id>) // all roles
```
- Record which roles have completed, their key_findings, decisions
- Read `<session>/wisdom/*.md` — absorb accumulated team knowledge
- Read `<session>/team-session.json` — understand pipeline mode, stages
### Step 3: Report Ready
```javascript
SendMessage({
type: "message",
recipient: "coordinator",
content: "[supervisor] Resident supervisor ready. Baseline loaded for session <session_id>. Awaiting checkpoint assignments.",
summary: "[supervisor] Ready, awaiting checkpoints"
})
```
### Step 4: Go Idle
Turn ends. Agent sleeps until coordinator sends a message.
---
## Wake Cycle
Triggered when coordinator sends a message. Parse and execute.
### Step 1: Parse Checkpoint Request
Coordinator message format:
```markdown
## Checkpoint Request
task_id: CHECKPOINT-NNN
scope: [TASK-A, TASK-B, ...]
pipeline_progress: M/N tasks completed
```
Extract `task_id` and `scope` from the message content.
### Step 2: Claim Task
```javascript
TaskUpdate({ taskId: "<task_id>", status: "in_progress" })
```
### Step 3: Incremental Context Load
Only load data that's NEW since last wake (or since init if first wake):
| Source | Method | What's New |
|--------|--------|------------|
| Role states | `team_msg(operation="get_state")` | Roles completed since last wake |
| Message bus | `team_msg(operation="list", session_id, last=30)` | Recent messages (errors, progress) |
| Artifacts | Read files in scope that aren't in context_accumulator yet | New upstream deliverables |
| Wisdom | Read `<session>/wisdom/*.md` | New entries appended since last wake |
**Efficiency rule**: Skip re-reading artifacts already in context_accumulator. Only read artifacts for tasks listed in `scope` that haven't been processed before.
### Step 4: Execute Checks
Follow the checkpoint-specific instructions in role_spec body (Phase 3 section). Each checkpoint type defines its own check matrix.
### Step 5: Write Report
Write to `<session>/artifacts/CHECKPOINT-NNN-report.md` (format defined in role_spec Phase 4).
### Step 6: Complete Task
```javascript
TaskUpdate({ taskId: "<task_id>", status: "completed" })
```
### Step 7: Publish State
```javascript
mcp__ccw-tools__team_msg({
operation: "log",
session_id: "<session_id>",
from: "supervisor",
type: "state_update",
data: {
status: "task_complete",
task_id: "<CHECKPOINT-NNN>",
ref: "<session>/artifacts/CHECKPOINT-NNN-report.md",
key_findings: ["..."],
decisions: ["Proceed" or "Block: <reason>"],
verification: "self-validated",
supervision_verdict: "pass|warn|block",
supervision_score: 0.85
}
})
```
### Step 8: Accumulate Context
```
context_accumulator.append({
task: "<CHECKPOINT-NNN>",
artifact: "<report-path>",
verdict: "<pass|warn|block>",
score: <0.0-1.0>,
key_findings: [...],
artifacts_read: [<list of artifact paths read this cycle>],
quality_trend: "<stable|improving|degrading>"
})
```
### Step 9: Report to Coordinator
```javascript
SendMessage({
type: "message",
recipient: "coordinator",
content: "[supervisor] CHECKPOINT-NNN complete.\nVerdict: <verdict> (score: <score>)\nFindings: <top-3>\nRisks: <count> logged\nQuality trend: <trend>\nArtifact: <path>",
summary: "[supervisor] CHECKPOINT-NNN: <verdict>"
})
```
### Step 10: Go Idle
Turn ends. Wait for next checkpoint request or shutdown.
---
## Crash Recovery
If spawned with `recovery: true` in prompt:
1. Scan `<session>/artifacts/CHECKPOINT-*-report.md` for existing reports
2. Read each report → rebuild context_accumulator entries
3. Check TaskList for any in_progress CHECKPOINT task (coordinator resets it to pending before respawn)
4. SendMessage to coordinator: "[supervisor] Recovered. Rebuilt context from N previous checkpoint reports."
5. Go idle — resume normal wake cycle
---
## Shutdown Protocol
When receiving a `shutdown_request` message:
```javascript
SendMessage({
type: "shutdown_response",
request_id: "<from message>",
approve: true
})
```
Agent terminates.
---
## Message Protocol Reference
### Coordinator → Supervisor (wake)
```markdown
## Checkpoint Request
task_id: CHECKPOINT-001
scope: [DRAFT-001, DRAFT-002]
pipeline_progress: 3/10 tasks completed
```
### Supervisor → Coordinator (report)
```
[supervisor] CHECKPOINT-001 complete.
Verdict: pass (score: 0.90)
Findings: Terminology aligned, decision chain consistent, all artifacts present
Risks: 0 logged
Quality trend: stable
Artifact: <session>/artifacts/CHECKPOINT-001-report.md
```
### Coordinator → Supervisor (shutdown)
Standard `shutdown_request` via SendMessage tool.
---
## Role Isolation Rules
| Allowed | Prohibited |
|---------|-----------|
| Read ALL role states (cross-role visibility) | Modify any upstream artifacts |
| Read ALL message bus entries | Create or reassign tasks |
| Read ALL artifacts in session | SendMessage to other workers directly |
| Write CHECKPOINT report artifacts | Spawn agents |
| Append to wisdom files | Process non-CHECKPOINT work |
| SendMessage to coordinator only | Make implementation decisions |
---
## Error Handling
| Scenario | Resolution |
|----------|------------|
| Artifact file not found | Score check as warn (not fail), log missing path |
| Message bus empty/unavailable | Score as warn, note "no messages to analyze" |
| Role state missing for upstream | Fall back to reading artifact files directly |
| Coordinator message unparseable | SendMessage error to coordinator, stay idle |
| Cumulative errors >= 3 across wakes | SendMessage alert to coordinator, stay idle (don't die) |
| No checkpoint request for extended time | Stay idle — resident agents don't self-terminate |
---
## Output Tag
All output lines must be prefixed with `[supervisor]` tag.

View File

@@ -8,12 +8,12 @@ description: |
Examples:
- Context: Coordinator spawns analyst worker
user: "role: analyst\nrole_spec: .claude/skills/team-lifecycle/role-specs/analyst.md\nsession: .workflow/.team/TLS-xxx"
user: "role: analyst\nrole_spec: ~ or <project>/.claude/skills/team-lifecycle/role-specs/analyst.md\nsession: .workflow/.team/TLS-xxx"
assistant: "Loading role spec, discovering RESEARCH-* tasks, executing Phase 2-4 domain logic"
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/role-specs/writer.md\ninner_loop: true"
user: "role: writer\nrole_spec: ~ or <project>/.claude/skills/team-lifecycle/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

View File

@@ -17,7 +17,8 @@ Interactive orchestration tool: analyze task → discover commands → recommend
| Skill | 包含操作 |
|-------|---------|
| `workflow-lite-planex` | lite-plan (includes execution phase internally) |
| `workflow-lite-plan` | lite-plan (Skill handoff to lite-execute) |
| `workflow-lite-execute` | lite-execute (multi-mode execution engine) |
| `workflow-plan` | plan, plan-verify, replan |
| `workflow-execute` | execute |
| `workflow-multi-cli-plan` | multi-cli-plan (includes execution phase internally) |
@@ -547,7 +548,7 @@ Pipeline (管道视图):
需求 → lite-plan → 代码 → test-cycle-execute → 测试通过
Commands (命令列表):
1. /workflow-lite-planex
1. /workflow-lite-plan
2. /workflow-test-fix
Proceed? [Confirm / Show Details / Adjust / Cancel]
@@ -851,7 +852,7 @@ workflow 操作通过 `Skill()` 调用对应的 Skill。
```javascript
// Skill 调用方式
Skill({ skill: 'workflow-lite-planex', args: '"task description"' });
Skill({ skill: 'workflow-lite-plan', args: '"task description"' });
Skill({ skill: 'workflow-execute', args: '--resume-session="WFS-xxx"' });
Skill({ skill: 'brainstorm', args: '"exploration topic"' });
Skill({ skill: 'spec-generator', args: '"product specification"' });
@@ -904,7 +905,8 @@ Task: <description>
| Skill | 包含操作 |
|-------|---------|
| `workflow-lite-planex` | lite-plan (includes execution phase internally) |
| `workflow-lite-plan` | lite-plan (Skill handoff to lite-execute) |
| `workflow-lite-execute` | lite-execute (multi-mode execution engine) |
| `workflow-plan` | plan, plan-verify, replan |
| `workflow-execute` | execute |
| `workflow-multi-cli-plan` | multi-cli-plan (includes execution phase internally) |
@@ -921,8 +923,9 @@ Task: <description>
**Cycle Workflows**: workflow:integration-test-cycle, workflow:refactor-cycle
**Execution**: workflow:unified-execute-with-file
**Design**: workflow:ui-design:*
**Session Management**: workflow:session:start, workflow:session:resume, workflow:session:complete, workflow:session:solidify, workflow:session:list, workflow:session:sync
**Utility**: workflow:clean, workflow:init, workflow:init-guidelines, workflow:status
**Session Management**: workflow:session:start, workflow:session:resume, workflow:session:complete, workflow:session:list, workflow:session:sync
**Utility**: workflow:clean, workflow:spec:setup, workflow:status
**Spec Management**: workflow:spec:setup, workflow:spec:add
**Issue Workflow**: issue:discover, issue:discover-by-prompt, issue:plan, issue:queue, issue:execute, issue:convert-to-plan, issue:from-brainstorm, issue:new
### Testing Commands Distinction

View File

@@ -15,7 +15,8 @@ Main process orchestrator: intent analysis → workflow selection → command ch
| Skill | 内部流水线 |
|-------|-----------|
| `workflow-lite-planex` | explore → plan → confirm → execute |
| `workflow-lite-plan` | explore → plan → confirm → handoff |
| `workflow-lite-execute` | task grouping → batch execution → code review → sync |
| `workflow-plan` | session → context → convention → gen → verify/replan |
| `workflow-execute` | session discovery → task processing → commit |
| `workflow-tdd-plan` | 6-phase TDD plan → verify |
@@ -43,14 +44,14 @@ Main process orchestrator: intent analysis → workflow selection → command ch
| 单元类型 | Skill | 说明 |
|---------|-------|------|
| 轻量 Plan+Execute | `workflow-lite-planex` | 内部完成 plan→execute |
| 轻量 Plan+Execute | `workflow-lite-plan``workflow-lite-execute` | plan handoff 到 execute分离 SkillTodoWrite 跟踪延续 (LP-Phase → LE-Phase) |
| 标准 Planning | `workflow-plan``workflow-execute` | 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:analyze-with-file``workflow-lite-planex` | 协作分析产物自动传递给 lite-plan |
| 多CLI协作 | `workflow-multi-cli-plan` | ACE context → CLI discussion → plan → Skill(lite-execute) |
| 分析→规划 | `workflow:analyze-with-file``workflow-lite-plan``workflow-lite-execute` | 协作分析产物自动传递给 lite-planSkill 调用 lite-execute |
| 头脑风暴→规划 | `workflow:brainstorm-with-file``workflow-plan``workflow-execute` | 头脑风暴产物自动传递给正式规划 |
| 0→1 开发(小) | `workflow:brainstorm-with-file``workflow-plan``workflow-execute` | 小规模从零开始,探索+正式规划+实现 |
| 0→1 开发(中/大) | `workflow:brainstorm-with-file``workflow-plan``workflow-execute` | 探索后正式规划+执行 |
@@ -231,7 +232,7 @@ function buildCommandChain(workflow, analysis) {
const chains = {
// Level 2 - Lightweight
'rapid': [
{ cmd: 'workflow-lite-planex', args: `"${analysis.goal}"` },
{ cmd: 'workflow-lite-plan', args: `"${analysis.goal}"` },
...(analysis.constraints?.includes('skip-tests') ? [] : [
{ cmd: 'workflow-test-fix', args: '' }
])
@@ -239,21 +240,21 @@ function buildCommandChain(workflow, analysis) {
// Level 2 Bridge - Lightweight to Issue Workflow
'rapid-to-issue': [
{ cmd: 'workflow-lite-planex', args: `"${analysis.goal}" --plan-only` },
{ cmd: 'workflow-lite-plan', args: `"${analysis.goal}" --plan-only` },
{ cmd: 'issue:convert-to-plan', args: '--latest-lite-plan -y' },
{ cmd: 'issue:queue', args: '' },
{ cmd: 'issue:execute', args: '--queue auto' }
],
'bugfix.standard': [
{ cmd: 'workflow-lite-planex', args: `--bugfix "${analysis.goal}"` },
{ cmd: 'workflow-lite-plan', args: `--bugfix "${analysis.goal}"` },
...(analysis.constraints?.includes('skip-tests') ? [] : [
{ cmd: 'workflow-test-fix', args: '' }
])
],
'bugfix.hotfix': [
{ cmd: 'workflow-lite-planex', args: `--hotfix "${analysis.goal}"` }
{ cmd: 'workflow-lite-plan', args: `--hotfix "${analysis.goal}"` }
],
'multi-cli-plan': [
@@ -264,13 +265,13 @@ function buildCommandChain(workflow, analysis) {
],
'docs': [
{ cmd: 'workflow-lite-planex', args: `"${analysis.goal}"` }
{ cmd: 'workflow-lite-plan', args: `"${analysis.goal}"` }
],
// With-File → Auto Chain to lite-plan
'analyze-to-plan': [
{ cmd: 'workflow:analyze-with-file', args: `"${analysis.goal}"` },
{ cmd: 'workflow-lite-planex', args: '' } // auto receives analysis artifacts (discussion.md)
{ cmd: 'workflow-lite-plan', args: '' } // auto receives analysis artifacts (discussion.md)
],
'brainstorm-to-plan': [
@@ -476,7 +477,7 @@ function setupTodoTracking(chain, workflow, analysis) {
```
**Output**:
- TODO: `-> CCW:rapid: [1/2] workflow-lite-planex | CCW:rapid: [2/2] workflow-test-fix | ...`
- TODO: `-> CCW:rapid: [1/2] workflow-lite-plan | CCW:rapid: [2/2] workflow-test-fix | ...`
- Status File: `.workflow/.ccw/{session_id}/status.json`
---
@@ -628,10 +629,10 @@ Phase 5: Execute Command Chain
| Input | Type | Level | Pipeline |
|-------|------|-------|----------|
| "Add API endpoint" | feature (low) | 2 | workflow-lite-planex → workflow-test-fix |
| "Fix login timeout" | bugfix | 2 | workflow-lite-planex → workflow-test-fix |
| "Use issue workflow" | issue-transition | 2.5 | workflow-lite-planex(plan-only) → convert-to-plan → queue → execute |
| "协作分析: 认证架构" | analyze-file | 3 | analyze-with-file → workflow-lite-planex |
| "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 |
| "协作分析: 认证架构" | analyze-file | 3 | analyze-with-file → workflow-lite-plan |
| "深度调试 WebSocket" | debug-file | 3 | workflow:debug-with-file |
| "从零开始: 用户系统" | greenfield (medium) | 3 | brainstorm-with-file → workflow-plan → workflow-execute → workflow-test-fix |
| "greenfield: 大型平台" | greenfield (high) | 4 | brainstorm-with-file → workflow-plan → workflow-execute → review-cycle → workflow-test-fix |
@@ -673,13 +674,13 @@ Phase 5: Execute Command Chain
```javascript
// Initial state (rapid workflow: 2 steps)
todos = [
{ content: "CCW:rapid: [1/2] workflow-lite-planex", status: "in_progress" },
{ content: "CCW:rapid: [1/2] workflow-lite-plan", status: "in_progress" },
{ content: "CCW:rapid: [2/2] workflow-test-fix", status: "pending" }
];
// After step 1 completes
todos = [
{ content: "CCW:rapid: [1/2] workflow-lite-planex", status: "completed" },
{ content: "CCW:rapid: [1/2] workflow-lite-plan", status: "completed" },
{ content: "CCW:rapid: [2/2] workflow-test-fix", status: "in_progress" }
];
```
@@ -704,7 +705,7 @@ todos = [
"complexity": "medium"
},
"command_chain": [
{ "index": 0, "command": "workflow-lite-planex", "status": "completed" },
{ "index": 0, "command": "workflow-lite-plan", "status": "completed" },
{ "index": 1, "command": "workflow-test-fix", "status": "running" }
],
"current_index": 1
@@ -724,11 +725,11 @@ todos = [
|----------|---------|------------|---------------|
| **brainstorm-with-file** | Multi-perspective ideation | → workflow-plan → workflow-execute (auto) | `.workflow/.brainstorm/` |
| **debug-with-file** | Hypothesis-driven debugging | Standalone (self-contained) | `.workflow/.debug/` |
| **analyze-with-file** | Collaborative analysis | → workflow-lite-planex (auto) | `.workflow/.analysis/` |
| **analyze-with-file** | Collaborative analysis | → workflow-lite-plan → workflow-lite-execute (auto) | `.workflow/.analysis/` |
| **collaborative-plan-with-file** | Multi-agent collaborative planning | → unified-execute-with-file | `.workflow/.planning/` |
| **roadmap-with-file** | Strategic requirement roadmap | → team-planex | `.workflow/.planning/` |
**Auto Chain Mechanism**: When `analyze-with-file` completes, its artifacts (discussion.md) are automatically passed to `workflow-lite-planex`. When `brainstorm-with-file` completes, its artifacts (brainstorm.md) are passed to `workflow-plan` for formal planning. No user intervention needed.
**Auto Chain Mechanism**: When `analyze-with-file` completes, its artifacts (discussion.md) are automatically passed to `workflow-lite-plan`. When `brainstorm-with-file` completes, its artifacts (brainstorm.md) are passed to `workflow-plan` for formal planning. No user intervention needed.
**Detection Keywords**:
- **brainstorm**: 头脑风暴, 创意, 发散思维, multi-perspective, compare perspectives
@@ -759,8 +760,8 @@ todos = [
|---------|---------|
| `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 `specs/*.md` |
| `workflow:spec:setup` | Initialize `.workflow/project-tech.json` with project analysis and specs scaffold |
| `workflow:spec:add` | Interactive wizard to add individual specs with scope selection |
| `workflow:status` | Generate on-demand views for project overview and workflow tasks |
---
@@ -793,7 +794,7 @@ todos = [
/ccw "全新开发: 实时通知系统" # → brainstorm-with-file → workflow-plan → workflow-execute → review-cycle → workflow-test-fix
# With-File workflows → auto chain
/ccw "协作分析: 理解现有认证架构的设计决策" # → analyze-with-file → workflow-lite-planex
/ccw "协作分析: 理解现有认证架构的设计决策" # → analyze-with-file → workflow-lite-plan → workflow-lite-execute
/ccw "头脑风暴: 用户通知系统重新设计" # → brainstorm-with-file → workflow-plan → workflow-execute → workflow-test-fix
/ccw "深度调试: 系统随机崩溃问题" # → debug-with-file (standalone)
/ccw "从头脑风暴 BS-通知系统-2025-01-28 创建 issue" # → brainstorm-to-issue (bridge)
@@ -816,7 +817,7 @@ todos = [
# Utility commands (invoked directly, not auto-routed)
# /workflow:unified-execute-with-file # 通用执行引擎(消费 plan 输出)
# /workflow:clean # 智能代码清理
# /workflow:init # 初始化项目状态
# /workflow:init-guidelines # 交互式填充项目规范
# /workflow:spec:setup # 初始化项目状态
# /workflow:spec:add # 交互式填充项目规范
# /workflow:status # 项目概览和工作流状态
```

View File

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

View File

@@ -0,0 +1,359 @@
---
name: auto
description: Chain command - automated document-driven development flow. Detects project state and runs the appropriate chain for new or existing projects.
argument-hint: "[-y|--yes] [--skip-spec] [--skip-build] [--spec <session-id>] [--resume] \"project idea or task description\""
allowed-tools: TodoWrite(*), Agent(*), AskUserQuestion(*), Read(*), Grep(*), Glob(*), Bash(*), Edit(*), Write(*)
---
## Auto Mode
When `--yes` or `-y`: All sub-commands run in auto mode. Minimal human intervention.
# DDD Auto Command (/ddd:auto)
## Purpose
Orchestrate the full document-driven development lifecycle. **Adapts to project state** — works for both new projects and existing codebases.
## Flow Variants
### Variant 1: New Project (no code, no spec)
```
spec-generator → ddd:index-build → ddd:plan → ddd:execute → verify → ddd:sync
```
### Variant 2: Existing Project (has code, no spec)
```
ddd:scan → ddd:plan → ddd:execute → verify → ddd:sync
```
### Variant 3: Existing Project with Spec (has code + spec)
```
ddd:index-build → ddd:plan → ddd:execute → verify → ddd:sync
```
### Variant 4: Index Exists (has doc-index.json)
```
ddd:plan → ddd:execute → verify → ddd:sync
```
## Flow Diagram
```
┌────────────────────────────────────────────────────────────┐
│ /ddd:auto │
│ │
│ Stage 0: Detect Project State │
│ ┌───────────────────────────────────┐ │
│ │ has_codebase? has_spec? has_index?│ │
│ └────────────┬──────────────────────┘ │
│ │ │
│ ┌──────────┼──────────────┐ │
│ ▼ ▼ ▼ │
│ No Code Code Only Code + Spec Index Exists │
│ │ │ │ │ │
│ ▼ │ │ │ │
│ Stage 1 │ │ │ │
│ Spec Gen │ │ │ │
│ │ │ │ │ │
│ ▼ │ ▼ │ │
│ Stage 2a Stage 2b Stage 2a │ │
│ index-build ddd:scan index-build │ │
│ (Path A or Path B auto-detected) │ │
│ │ │ │
│ └───────────────────┬───────────────────┘ │
│ ▼ │
│ Stage 3: DDD Plan (enhanced) │
│ (doc-index query + exploration + │
│ clarification + task planning) │
│ │ │
│ ▼ │
│ Stage 4: Execute │
│ (ddd:execute = doc-aware execution) │
│ │ │
│ ▼ │
│ Stage 4.5: Verify Gate │
│ (convergence + build + lint + tests │
│ → execution-manifest.json) │
│ │ │
│ PASS / WARN → continue │
│ FAIL → ask user │
│ │ │
│ ▼ │
│ Stage 5: Doc Sync │
│ (auto-triggered with --from-manifest, │
│ or manual /ddd:sync) │
└────────────────────────────────────────────────────────────┘
```
## Stage 0: Project State Detection
Automatically detect project state to determine which stages to run:
```
Check 1: doc-index.json exists? → has_index
Check 2: SPEC-* directories exist? → has_spec
Check 3: Source code directories? → has_codebase
Check 4: project-tech.json exists? → has_tech_analysis
```
### Decision Matrix
| has_codebase | has_spec | has_index | Action |
|:---:|:---:|:---:|--------|
| No | No | No | Stage 1 (spec-gen) → Stage 2a (index-build) → Stage 3-5 |
| No | Yes | No | Stage 2a (index-build) → Stage 3-5 |
| Yes | No | No | **Stage 2b (ddd:scan)** → Stage 3-5 |
| Yes | Yes | No | Stage 2a (index-build) → Stage 3-5 |
| Yes | * | Yes | **Skip to Stage 3** (index exists) |
### Override Flags
| Flag | Effect |
|------|--------|
| `--skip-spec` | Never run spec-generator |
| `--skip-build` | Never run index-build |
| `--spec <id>` | Use specific spec session, force Path A |
| `--from-scratch` | Rebuild index even if exists |
## Stage 1: Specification (conditional)
### Run When
- No codebase AND no spec AND `--skip-spec` not set
- User provides a new project idea (not an existing task description)
### Skip When
- `--skip-spec` flag
- Codebase already exists (existing project)
- `--spec <id>` pointing to existing session
### Execution
```
Invoke /spec-generator with user input
→ Output: .workflow/.doc-index/specs/SPEC-{slug}-{date}/
```
## Stage 2: Index Construction (conditional)
### Run When
- `doc-index.json` does not exist
- OR `--from-scratch` flag
### Route Selection
```
Has spec outputs → Stage 2a: /ddd:index-build (spec-first)
No spec, has code → Stage 2b: /ddd:scan (code-first)
```
### Stage 2a: /ddd:index-build (has spec)
```
Invoke /ddd:index-build [-y] [-s <spec-id>]
→ Output: doc-index.json from spec entities + code mapping
```
### Stage 2b: /ddd:scan (no spec, has code)
```
Invoke /ddd:scan [-y]
→ Output: doc-index.json from code analysis + inferred features
```
### Skip When
- `--skip-build` flag
- `doc-index.json` exists AND NOT `--from-scratch`
- In this case, suggest `/ddd:update` for incremental refresh
## Stage 3: Planning (always runs)
### Execution
```
Invoke /ddd:plan [-y] "task description"
```
The enhanced `/ddd:plan` now performs:
1. Doc-index query (instant context from features, requirements, components, ADRs)
2. Doc-index-guided exploration (1-4 angles based on affected features)
3. Clarification (aggregate ambiguities from exploration + doc-index gaps)
4. Task planning (plan.json + TASK-*.json with doc_context traceability)
5. Handoff selection
Output:
- `plan.json` — plan overview with doc_context
- `.task/TASK-*.json` — individual tasks with doc_context
- `exploration-{angle}.json` — exploration results (if Phase 2 ran)
- `planning-context.md` — legacy context package
### Handoff Decision
After planning, `/ddd:plan` presents execution options:
| Option | Description | Auto-Select When |
|--------|-------------|-----------------|
| **ddd:execute** | Document-aware execution (recommended) | Default in ddd workflow |
| **lite-execute** | Standard execution (no doc awareness) | When doc traceability not needed |
| **direct** | Start coding with context | User prefers manual |
| **stop** | Just the plan context | Planning/research only |
With `-y`: Auto-select `ddd:execute`.
## Stage 4: Execution
Based on Stage 3 handoff decision:
| Mode | Delegates To |
|------|-------------|
| **ddd:execute** | `/ddd:execute --in-memory` with plan.json + doc-index enrichment |
| lite-execute | `/workflow:lite-execute` with plan.json path |
| direct | Output context package, developer works manually |
| stop | End here, no execution |
### ddd:execute Features (when selected)
- Doc-enriched task prompts (feature context + component docs + ADR constraints)
- Per-batch impact verification (changes stay within planned scope)
- Result persistence (`TASK-*.result.json` per task, `execution-manifest.json` per session)
- Post-execution verify gate (Stage 4.5, unless `--skip-verify`)
- Post-completion auto-sync with manifest (Stage 5 triggered automatically)
**Note**: When using `ddd:execute`, Stage 4.5 and Stage 5 are auto-triggered. For other modes, run Stage 5 manually.
## Stage 4.5: Verify Gate
Embedded within `ddd:execute` (Step 4.5). Runs after all batches complete, before doc sync.
### Purpose
Quality gate ensuring execution output is correct before committing to documentation updates. Prevents bad code from being "blessed" into the doc-index.
### Checks Performed
| Check | Description | Gate Behavior |
|-------|-------------|---------------|
| **Convergence** | Run `task.convergence.verification` for each task | FAIL if any critical task fails |
| **Build** | Run project build command (`tsc --noEmit`, etc.) | FAIL on build errors |
| **Lint** | Run project linter (`eslint`, etc.) | WARN only (non-blocking) |
| **Regression** | Run full test suite, compare to baseline | FAIL on new test failures |
### Gate Results
| Result | Action |
|--------|--------|
| **PASS** | All checks passed → proceed to Stage 5 |
| **WARN** | Non-critical issues (lint warnings) → proceed with warnings logged |
| **FAIL** | Critical issues → ask user: fix now / skip sync / abort |
| **FAIL + `-y`** | Log failures, set `error_state` in session, stop |
### Output
- `execution-manifest.json` — persisted to session folder, consumed by Stage 5
- Contains: task results, files_modified (with task attribution), verify gate results
## Stage 5: Post-Task Sync
### Trigger
- **Auto**: `/ddd:execute` triggers `/ddd:sync --from-manifest` automatically after verify gate passes
- **Manual**: User runs `/ddd:sync` after completing work in direct/lite-execute mode
- **Resume**: `/ddd:auto --resume` after task completion
### Execution
```
# Auto mode (from ddd:execute): uses manifest for precise change tracking
Invoke /ddd:sync [-y] --task-id <id> --from-manifest {session}/execution-manifest.json "task summary"
# Manual mode (from direct/lite-execute): falls back to git diff
Invoke /ddd:sync [-y] [--task-id <id>] "task summary"
→ Updates: doc-index.json, feature-maps/, tech-registry/, action-logs/
```
## State Tracking
### Session File: `.workflow/.doc-index/.auto-session.json`
```json
{
"session_id": "DAUTO-{timestamp}",
"input": "user's original input",
"detected_state": {
"has_codebase": true,
"has_spec": false,
"has_index": false,
"build_path": "code-first"
},
"stages_completed": ["detect", "index-build", "plan"],
"current_stage": "execute",
"spec_session": "SPEC-{slug}-{date}|null",
"plan_session": "planning/{task-slug}-{date}/",
"plan_context": "planning/{task-slug}-{date}/plan.json",
"execution_mode": "ddd:execute|lite-execute|direct|stop",
"execution_manifest": "planning/{task-slug}-{date}/execution-manifest.json|null",
"verify_gate": "PASS|WARN|FAIL|null",
"error_state": null,
"last_error": {
"stage": "execute",
"message": "Task TASK-002 failed: compilation error",
"timestamp": "ISO8601",
"recoverable": true
},
"created_at": "ISO8601",
"last_updated": "ISO8601"
}
```
### Resume
```
/ddd:auto --resume → Resume from current_stage in .auto-session.json
```
### Error Recovery
```
/ddd:auto --resume
IF error_state is set:
Display last error context
Ask: retry current stage / skip to next / abort
ELSE:
Resume from current_stage normally
```
## Example Workflows
### New Project (Full Flow)
```
/ddd:auto "Build a task management API with user auth and team features"
→ Stage 0: No code, no spec → need spec-gen
→ Stage 1: spec-generator produces full spec
→ Stage 2: index-build creates index from spec + empty codebase
→ Stage 3: ddd:plan produces plan.json + TASK-*.json with doc_context
→ Stage 4: ddd:execute runs tasks with feature context enrichment
→ Stage 4.5: verify gate — convergence ✓, build ✓, tests ✓ → PASS
→ Stage 5: ddd:sync --from-manifest auto-triggered, updates index
```
### Existing Project, No Spec (Code-First)
```
/ddd:auto "Add rate limiting to API endpoints"
→ Stage 0: Has code, no spec, no index
→ Stage 2b: ddd:scan analyzes code, infers features from codebase
→ Stage 3: ddd:plan queries index, explores with security + patterns angles
→ Stage 4: ddd:execute runs with rate-limit component docs as context
→ Stage 4.5: verify gate — convergence ✓, tests 41/42 (1 regression) → WARN
→ Stage 5: ddd:sync --from-manifest, registers new rate-limit component
```
### Existing Project with Index (Incremental)
```
/ddd:auto "Fix auth token expiration bug"
→ Stage 0: Has code, has index → skip to plan
→ Stage 3: ddd:plan finds feat-auth, REQ-002, tech-auth-service (Low complexity, skip exploration)
→ Stage 4: ddd:execute runs single task with auth feature context
→ Stage 4.5: verify gate — convergence ✓, build ✓, tests ✓ → PASS
→ Stage 5: ddd:sync --from-manifest, updates tech-auth-service code locations
```
### Planning Only
```
/ddd:auto "Investigate payment module architecture"
→ Stage 0-2: (as needed)
→ Stage 3: ddd:plan shows full context with exploration results
→ Stage 4: user selects "stop" → gets plan.json + context package only
```

View File

@@ -0,0 +1,295 @@
---
name: doc-generate
description: Generate full document tree from doc-index.json. Layer 3 (components) → Layer 2 (features) → Layer 1 (indexes/overview). Standalone or called by scan/index-build.
argument-hint: "[-y|--yes] [--layer <3|2|1|all>] [--force] [--skip-overview] [--skip-schema]"
allowed-tools: TodoWrite(*), Agent(*), AskUserQuestion(*), Read(*), Grep(*), Glob(*), Bash(*), Edit(*), Write(*)
---
## Auto Mode
When `--yes` or `-y`: Auto-generate all layers without confirmation prompts.
# DDD Doc Generate Command (/ddd:doc-generate)
## Purpose
Generate the complete document tree from `doc-index.json`. **Single source of truth** for all document generation logic, following bottom-up Layer 3 → 2 → 1 strategy.
```
doc-index.json → tech-registry/*.md (L3) → feature-maps/*.md (L2) → _index.md + README + ARCHITECTURE (L1)
```
## When to Use
| Scenario | Use |
|----------|-----|
| After `/ddd:scan` builds doc-index.json | **doc-generate** (auto-called by scan) |
| After `/ddd:index-build` builds doc-index.json | **doc-generate** (auto-called by index-build) |
| Rebuild all docs from existing index | **doc-generate --force** |
| Regenerate only component docs | **doc-generate --layer 3** |
| Regenerate only overview/index docs | **doc-generate --layer 1** |
## Prerequisite
- `doc-index.json` must exist at `.workflow/.doc-index/doc-index.json`
- If not found → error: "No doc-index.json found. Run /ddd:scan or /ddd:index-build first."
## Storage Output
```
.workflow/.doc-index/
├── doc-index.json ← Input (read-only, not modified)
├── SCHEMA.md ← Schema documentation
├── README.md ← Project overview (Layer 1)
├── ARCHITECTURE.md ← Architecture overview (Layer 1)
├── feature-maps/ ← Feature documentation (Layer 2)
│ ├── _index.md
│ └── {feature-slug}.md
├── tech-registry/ ← Component documentation (Layer 3)
│ ├── _index.md
│ └── {component-slug}.md
└── sessions/
└── _index.md ← Planning sessions index (Layer 1)
```
## Phase 1: Load & Validate
### 1.1 Load doc-index.json
```
Read .workflow/.doc-index/doc-index.json
Validate: features[], technicalComponents[] are non-empty arrays
```
### 1.2 Schema Version Check
```javascript
const schemaVersion = docIndex.schema_version || '0.0';
if (schemaVersion !== '1.0') {
warn(`Schema version mismatch: found ${schemaVersion}, expected 1.0`);
}
```
### 1.3 Determine Generation Scope
```
IF --layer 3: generate Layer 3 only
IF --layer 2: generate Layer 2 only (requires Layer 3 exists)
IF --layer 1: generate Layer 1 only (requires Layer 2 exists)
IF --layer all (default): generate Layer 3 → 2 → 1
```
### 1.4 Check Existing Docs
```
IF docs already exist AND NOT --force:
Warn: "Documents already exist. Use --force to overwrite."
Ask user (unless -y → overwrite)
```
## Phase 2: Layer 3 — Component Documentation
For each component in `technicalComponents[]`:
```bash
ccw cli -p "PURPOSE: Generate component documentation for {component.name}
TASK:
• Document component purpose and responsibility
• List exported symbols (classes, functions, types)
• Document dependencies (internal and external)
• Include code examples for key APIs
• Document integration points with other components
MODE: write
CONTEXT: @{component.codeLocations[].path}
EXPECTED: Markdown file with: Overview, API Reference, Dependencies, Usage Examples
CONSTRAINTS: Focus on public API | Include type signatures
" --tool gemini --mode write --cd .workflow/.doc-index/tech-registry/
```
Output: `.workflow/.doc-index/tech-registry/{component-slug}.md`
Frontmatter:
```markdown
---
layer: 3
component_id: tech-{slug}
name: ComponentName
type: service|controller|model|...
features: [feat-auth]
code_locations:
- path: src/services/auth.ts
symbols: [AuthService, AuthService.login]
generated_at: ISO8601
---
```
Sections: Responsibility, Code Locations, Related Requirements, Architecture Decisions, Dependencies (in/out)
## Phase 3: Layer 2 — Feature Documentation
For each feature in `features[]`:
```bash
ccw cli -p "PURPOSE: Generate feature documentation for {feature.name}
TASK:
• Describe feature purpose and business value
• List requirements (from requirementIds)
• Document components involved (from techComponentIds)
• Include architecture decisions (from adrIds)
• Provide integration guide
MODE: write
CONTEXT: @.workflow/.doc-index/tech-registry/{related-components}.md
EXPECTED: Markdown file with: Overview, Requirements, Components, Architecture, Integration
CONSTRAINTS: Reference Layer 3 component docs | Business-focused language
" --tool gemini --mode write --cd .workflow/.doc-index/feature-maps/
```
Output: `.workflow/.doc-index/feature-maps/{feature-slug}.md`
Frontmatter:
```markdown
---
layer: 2
feature_id: feat-{slug}
name: Feature Name
epic_id: EPIC-NNN|null
status: implemented|in-progress|planned|partial
requirements: [REQ-001, REQ-002]
components: [tech-auth-service, tech-user-model]
depends_on_layer3: [tech-auth-service, tech-user-model]
tags: [auth, security]
generated_at: ISO8601
---
```
Sections: Overview, Requirements (with mapping status), Technical Components, Architecture Decisions, Change History
## Phase 4: Layer 1 — Index & Overview Documentation
### 4.1 Index Documents
Generate catalog files:
- **feature-maps/_index.md** — Feature overview table with status
- **tech-registry/_index.md** — Component registry table with types
- **action-logs/_index.md** — Action history table (empty initially for new projects)
### 4.2 README.md (unless --skip-overview)
```bash
ccw cli -p "PURPOSE: Generate project README with overview and navigation
TASK:
• Project summary and purpose
• Quick start guide
• Navigation to features, components, and architecture
• Link to doc-index.json
MODE: write
CONTEXT: @.workflow/.doc-index/doc-index.json @.workflow/.doc-index/feature-maps/_index.md
EXPECTED: README.md with: Overview, Quick Start, Navigation, Links
CONSTRAINTS: High-level only | Entry point for new developers
" --tool gemini --mode write --cd .workflow/.doc-index/
```
### 4.3 ARCHITECTURE.md (unless --skip-overview)
```bash
ccw cli -p "PURPOSE: Generate architecture overview document
TASK:
• System design overview
• Component relationships and dependencies
• Key architecture decisions (from ADRs)
• Technology stack
MODE: write
CONTEXT: @.workflow/.doc-index/doc-index.json @.workflow/.doc-index/tech-registry/*.md
EXPECTED: ARCHITECTURE.md with: System Design, Component Diagram, ADRs, Tech Stack
CONSTRAINTS: Architecture-focused | Reference component docs for details
" --tool gemini --mode write --cd .workflow/.doc-index/
```
### 4.4 sessions/_index.md (unless --skip-overview)
```bash
ccw cli -p "PURPOSE: Generate planning sessions index
TASK:
• List all planning session folders chronologically
• Link to each session's plan.json
• Show session status and task count
MODE: write
CONTEXT: @.workflow/.doc-index/planning/*/plan.json
EXPECTED: sessions/_index.md with: Session List, Links, Status
CONSTRAINTS: Chronological order | Link to session folders
" --tool gemini --mode write --cd .workflow/.doc-index/sessions/
```
Layer 1 frontmatter:
```markdown
---
layer: 1
depends_on_layer2: [feat-auth, feat-orders]
generated_at: ISO8601
---
```
## Phase 5: SCHEMA.md (unless --skip-schema)
### 5.1 Generate Schema Documentation
```bash
ccw cli -p "PURPOSE: Document doc-index.json schema structure and versioning
TASK:
• Document current schema structure (all fields)
• Define versioning policy (semver: major.minor)
• Document migration protocol for version upgrades
• Provide examples for each schema section
MODE: write
CONTEXT: @.workflow/.doc-index/doc-index.json
EXPECTED: SCHEMA.md with: Schema Structure, Versioning Policy, Migration Protocol, Examples
CONSTRAINTS: Complete field documentation | Clear migration steps
" --tool gemini --mode write --cd .workflow/.doc-index/
```
### 5.2 Versioning Policy
**Semantic Versioning**:
- **Major** (X.0): Breaking changes (field removal, type changes, incompatible structure)
- **Minor** (X.Y): Non-breaking additions (new optional fields, new sections)
**Migration Protocol**:
1. Detect version mismatch in ddd:plan/ddd:sync
2. Log warning with migration instructions
3. Provide migration script or regeneration option
4. Update schema_version after successful migration
## Phase 6: Generation Report
```
Document Generation Report
Project: {name}
Source: doc-index.json (build_path: {spec-first|code-first})
Generated:
Layer 3 (Components): {N} documents in tech-registry/
Layer 2 (Features): {N} documents in feature-maps/
Layer 1 (Indexes): {N} documents (_index.md, README, ARCHITECTURE)
Schema: SCHEMA.md
Total: {N} documents generated
```
## Flags
| Flag | Effect |
|------|--------|
| `-y, --yes` | Auto-confirm all decisions |
| `--layer <3\|2\|1\|all>` | Generate specific layer only (default: all) |
| `--force` | Overwrite existing documents |
| `--skip-overview` | Skip README.md, ARCHITECTURE.md, sessions/_index.md |
| `--skip-schema` | Skip SCHEMA.md generation |
## Integration Points
- **Input from**: `doc-index.json` (from `/ddd:scan` or `/ddd:index-build`)
- **Called by**: `/ddd:scan` (after index assembly), `/ddd:index-build` (after index assembly)
- **Standalone**: Can be run independently on any project with existing doc-index.json
- **Output**: Complete document tree in `.workflow/.doc-index/`

View File

@@ -0,0 +1,218 @@
---
name: doc-refresh
description: Incrementally update affected documents based on changed components/features. Layer 3 → 2 → 1 selective refresh. Called by sync/update or used standalone.
argument-hint: "[-y|--yes] [--components <id1,id2,...>] [--features <id1,id2,...>] [--minimal] [--dry-run]"
allowed-tools: TodoWrite(*), Agent(*), AskUserQuestion(*), Read(*), Grep(*), Glob(*), Bash(*), Edit(*), Write(*)
---
## Auto Mode
When `--yes` or `-y`: Auto-update affected documents without confirmation prompts.
# DDD Doc Refresh Command (/ddd:doc-refresh)
## Purpose
Incrementally update **only the affected documents** after code changes. Unlike `/ddd:doc-generate` (full generation), this command selectively refreshes documents for specific components and features.
```
affected component/feature IDs → update tech-registry (L3) → update feature-maps (L2) → update indexes (L1)
```
## When to Use
| Scenario | Use |
|----------|-----|
| After `/ddd:sync` detects code changes | **doc-refresh** (auto-called by sync) |
| After `/ddd:update` traces impact | **doc-refresh** (auto-called by update) |
| Manual refresh of specific component docs | **doc-refresh --components tech-auth-service** |
| Quick metadata-only update | **doc-refresh --minimal --components tech-auth-service** |
| Preview what would change | **doc-refresh --dry-run --components tech-auth-service** |
## Prerequisite
- `doc-index.json` must exist at `.workflow/.doc-index/doc-index.json`
- At least one of `--components` or `--features` must be provided (or received from caller)
- Corresponding documents must already exist (generated by `/ddd:doc-generate`)
- If documents missing → error: "Documents not found. Run /ddd:doc-generate first."
## Phase 1: Determine Refresh Scope
### 1.1 Resolve Affected Entities
```
IF --components provided:
affected_components = parse comma-separated IDs
affected_features = lookup featureIds for each component in doc-index.json
IF --features provided:
affected_features = parse comma-separated IDs
affected_components = union of all component IDs linked to features
Merge both sets if both flags provided.
```
### 1.2 Validate Entities Exist
For each ID, verify it exists in doc-index.json. Warn and skip missing IDs.
### 1.3 Check Document Existence
For each affected entity, check if corresponding .md file exists:
- Missing Layer 3 doc → warn: "Component doc not found. Run /ddd:doc-generate first."
- Missing Layer 2 doc → warn: "Feature doc not found. Run /ddd:doc-generate first."
## Phase 2: Layer 3 — Update Component Docs
For each affected component's `tech-registry/{slug}.md`:
```bash
ccw cli -p "PURPOSE: Update component documentation for {component.name} after code changes
TASK:
• Update code locations and line ranges
• Update symbol list (add new exports, remove deleted)
• Add change entry to history table
• Refresh usage examples if API changed
MODE: write
CONTEXT: @{component.codeLocations[].path}
EXPECTED: Updated markdown with current API state
CONSTRAINTS: Preserve existing structure | Only update changed sections
" --tool gemini --mode write --cd .workflow/.doc-index/tech-registry/
```
Update frontmatter:
```markdown
---
layer: 3
component_id: tech-auth-service
generated_at: {original}
last_updated: ISO8601
---
```
### 2.1 Minimal Mode (--minimal)
With `--minimal`, only update:
- `codeLocations` in frontmatter
- `last_updated` timestamp
- Skip CLI call for content regeneration
## Phase 3: Layer 2 — Update Feature Docs
For each affected feature's `feature-maps/{slug}.md`:
```bash
ccw cli -p "PURPOSE: Update feature documentation for {feature.name} after component changes
TASK:
• Update component list if new components added
• Update status if requirements now fully implemented
• Add change entry to history table
• Refresh integration guide if component APIs changed
MODE: write
CONTEXT: @.workflow/.doc-index/tech-registry/{affected-components}.md
EXPECTED: Updated markdown reflecting current feature state
CONSTRAINTS: Reference updated Layer 3 docs | Preserve business language
" --tool gemini --mode write --cd .workflow/.doc-index/feature-maps/
```
Update frontmatter:
```markdown
---
layer: 2
feature_id: feat-auth
depends_on_layer3: [tech-auth-service, tech-user-model]
generated_at: {original}
last_updated: ISO8601
---
```
### 3.1 Minimal Mode (--minimal)
With `--minimal`, only update:
- Component list in frontmatter
- Feature status (if requirements mapping changed)
- `last_updated` timestamp
- Skip CLI call for content regeneration
## Phase 4: Layer 1 — Update Index Docs (conditional)
### 4.1 Trigger Conditions
| Condition | Action |
|-----------|--------|
| New component registered | Update `tech-registry/_index.md` |
| Component removed | Update `tech-registry/_index.md` |
| Feature status changed | Update `feature-maps/_index.md` |
| New feature added | Update `feature-maps/_index.md` + README.md |
| Major architecture change | Update ARCHITECTURE.md |
| New action-log entry | Update `action-logs/_index.md` |
### 4.2 Update _index.md Files
Refresh table entries for affected features/components:
- `feature-maps/_index.md`
- `tech-registry/_index.md`
- `action-logs/_index.md` (if new action entry)
### 4.3 Update Overview Docs (only if significant)
If new features added or major status changes:
```bash
ccw cli -p "PURPOSE: Update project overview docs after feature changes
TASK:
• Update README.md feature list
• Update ARCHITECTURE.md if new components added
• Update sessions/_index.md with new planning sessions
MODE: write
CONTEXT: @.workflow/.doc-index/feature-maps/*.md @.workflow/.doc-index/doc-index.json
EXPECTED: Updated overview docs with current project state
CONSTRAINTS: High-level only | Link to Layer 2 for details
" --tool gemini --mode write --cd .workflow/.doc-index/
```
### 4.4 Skip Layer 1
With `--minimal` or when changes are minor (only code location updates): skip Layer 1 entirely.
## Phase 5: Refresh Report
```
Document Refresh Report
Affected Scope:
Components: {N} ({component IDs})
Features: {N} ({feature IDs})
Updated:
Layer 3 (Components): {N} documents refreshed
Layer 2 (Features): {N} documents refreshed
Layer 1 (Indexes): {N} documents refreshed (or "skipped")
Mode: {full|minimal}
```
## Dry-Run Mode
With `--dry-run`:
- Execute Phase 1 (scope determination)
- Display what would be updated (affected files list)
- Skip all file writes (Phase 2-4)
- Output: "Dry-run complete. {N} documents would be refreshed."
## Flags
| Flag | Effect |
|------|--------|
| `-y, --yes` | Auto-confirm all updates |
| `--components <ids>` | Comma-separated component IDs to refresh |
| `--features <ids>` | Comma-separated feature IDs to refresh |
| `--minimal` | Only update metadata/frontmatter, skip content regeneration |
| `--dry-run` | Preview what would change without modifying files |
## Integration Points
- **Input from**: `doc-index.json`, affected entity IDs (from `/ddd:sync` or `/ddd:update`)
- **Called by**: `/ddd:sync` (after change detection + index update), `/ddd:update` (after impact tracing + index update)
- **Standalone**: Can be run independently to refresh specific component/feature docs
- **Prerequisite**: Documents must exist (generated by `/ddd:doc-generate`)

View File

@@ -0,0 +1,416 @@
---
name: execute
description: Document-aware execution engine — executes plan.json + TASK-*.json with doc-index context enrichment, per-batch impact verification, and post-completion doc sync.
argument-hint: "[-y|--yes] [--skip-sync] [--skip-verify] [--plan <path>] [--in-memory] \"optional task description\""
allowed-tools: TodoWrite(*), Agent(*), AskUserQuestion(*), Read(*), Grep(*), Glob(*), Bash(*), Edit(*), Write(*), mcp__ace-tool__search_context(*)
---
## Auto Mode
When `--yes` or `-y`: Auto-confirm all decisions, auto-sync after completion.
# DDD Execute Command (/ddd:execute)
## Purpose
Same execution engine model as lite-execute, but each step is **doc-index-aware**:
- Tasks are enriched with feature context, component docs, and architecture constraints
- Per-batch impact verification ensures changes stay within planned scope
- Post-completion automatically syncs the document index
### Core Differentiator
Unlike generic execution engines, ddd:execute leverages the document architecture:
- Feature-maps provide business context for each task
- Tech-registry provides implementation patterns to follow
- ADRs surface as hard constraints during execution
- Requirement acceptance criteria inform convergence verification
## Prerequisite
- `plan.json` + `.task/TASK-*.json` files from `/ddd:plan`
- `doc-index.json` at `.workflow/.doc-index/doc-index.json`
- If `--in-memory`: receives executionContext from `/ddd:plan` handoff
---
## Step 1: Initialize & Load Context
### 1.1 Locate Plan
```
IF --in-memory:
Load executionContext from ddd:plan handoff
plan_path = executionContext.plan_path
task_dir = executionContext.task_dir
ELIF --plan <path>:
plan_path = <path>
task_dir = {dirname(path)}/.task/
ELSE:
Scan .workflow/.doc-index/planning/ for most recent session
plan_path = {latest_session}/plan.json
task_dir = {latest_session}/.task/
```
### 1.2 Load Plan & Tasks
- Read `plan.json` — validate against plan-overview-base-schema
- Read all `TASK-*.json` from `.task/` directory — validate against task-schema
- Read `doc-index.json` from `.workflow/.doc-index/`
### 1.3 Pre-Load Doc Context
For each task with `doc_context`:
- Load referenced `feature_docs` (feature-maps/{slug}.md)
- Load referenced `component_docs` (tech-registry/{slug}.md)
- Load ADR excerpts from doc-index `architectureDecisions[]`
- Extract requirement acceptance criteria from doc-index `requirements[]`
- Load `doc_context.symbol_docs[]` documentation content (if present)
### 1.4 Echo Strategy
Display execution summary:
```
DDD Execute: {plan.summary}
Complexity: {plan.complexity}
Tasks: {plan.task_count}
Doc-Index Impact:
Features: {doc_context.affected_features}
Requirements: {doc_context.affected_requirements}
Components: {doc_context.affected_components}
Constraints: {doc_context.architecture_constraints}
Execution plan: {batch count} batches, {parallel tasks} parallel where possible
```
---
## Step 2: Task Grouping & Batch Creation
### 2.1 Extract Dependencies
From each `TASK-*.json`, read `depends_on[]` to build dependency graph.
### 2.2 Group into Batches
```
Batch 1: Tasks with no dependencies (depends_on: [])
Batch 2: Tasks depending only on Batch 1 tasks
Batch 3: Tasks depending on Batch 1 + 2 tasks
...
```
Within each batch, tasks with the same `parallel_group` can run concurrently.
### 2.3 Assign Executor per Task
| Signal | Executor |
|--------|----------|
| `meta.execution_config.method == "cli"` | CLI tool (gemini/codex/qwen) |
| `meta.execution_config.method == "agent"` | Agent (code-developer/universal-executor) |
| Default | Agent (code-developer) |
---
## Step 3: Doc-Enriched Execution
For each task in batch order, build an enriched prompt:
### 3.1 Task Prompt Template
```markdown
## Goal
${plan.summary} — specifically: ${task.title}
## Document Context
### Feature: ${feature.name} (${feature.id})
${feature-map content excerpt — overview + requirements section}
### Components
${for each component in task.doc_context.component_ids:
tech-registry excerpt — responsibility + code locations + key patterns}
### Symbol Documentation
${if doc_context.symbol_docs is non-empty:
for each component in doc_context.component_ids:
#### ${component.name} Symbols (Top-5)
${for each symbol in component.symbol_docs.slice(0, 5):
- **${symbol.name}** (${symbol.type}): ${symbol.doc_summary}
Source: `${symbol.source_path}` | Freshness: ${symbol.freshness}
}
}
### Architecture Constraints
${for each ADR in task.doc_context.adr_ids:
ADR title + decision + rationale from doc-index}
### Requirement Acceptance Criteria
${for each requirement in task.doc_context.requirement_ids:
requirement title + priority + success criteria from doc-index}
## Task Details
${task.description}
### Files to Modify
${task.files[] — path, action, changes}
### Implementation Steps
${task.implementation[] — step-by-step guide}
## Done When
${task.convergence.criteria[]}
${task.convergence.verification}
```
### 3.2 Execute Task
**Agent execution**:
```
Agent(subagent_type="code-developer", prompt="{enriched prompt}")
```
**CLI execution**:
```bash
ccw cli -p "{enriched prompt}" --tool {cli_tool} --mode write
```
### 3.3 Record & Persist Result
After each task completes:
- Update `TASK-*.json` with `status`, `executed_at`, `result`
- Track `result.files_modified` for impact verification
- **Persist** result to `TASK-{id}.result.json` alongside the task file:
```json
{
"task_id": "TASK-001",
"status": "completed|failed",
"executed_at": "ISO8601",
"executor": "code-developer|gemini|codex",
"files_modified": [
{ "path": "src/services/auth.ts", "action": "modified", "symbols_changed": ["AuthService.validate"] },
{ "path": "src/routes/login.ts", "action": "created", "symbols_changed": ["loginRoute"] }
],
"convergence_result": {
"criteria_met": ["Rate limiter middleware exists"],
"criteria_unmet": [],
"verification_output": "test output snippet..."
},
"error": null
}
```
This file serves as the durable handoff between execute and sync — survives process interruptions.
---
## Step 4: Per-Batch Impact Verification
After each batch completes (unless `--skip-verify`):
### 4.1 Trace Changed Files
For each file modified in the batch:
```
changed_file → match to doc-index.technicalComponents[].codeLocations[].path
→ component_ids → featureIds → requirementIds
```
### 4.2 Scope Verification
Compare actual impact to planned impact:
```
Planned scope:
Features: [feat-auth]
Components: [tech-auth-service, tech-user-model]
Actual impact:
Features: [feat-auth] ← OK, within scope
Components: [tech-auth-service, tech-user-model, tech-email-service]
← WARNING: tech-email-service not in plan
```
### 4.3 Flag Unexpected Impact
If changes affect features/components NOT in `plan.doc_context`:
- **Warning**: Display unexpected impact
- **No -y**: Ask user to confirm continuation
- **With -y**: Log warning, continue execution
### 4.4 Skip Conditions
Skip verification when:
- `--skip-verify` flag is set
- Only 1 batch (no intermediate verification needed for simple plans)
---
## Step 4.5: Post-Execution Verify Gate
After all batches complete, before doc sync (unless `--skip-verify`):
### 4.5.1 Convergence Verification
For each completed task with `convergence.verification`:
```
Execute: {task.convergence.verification}
→ e.g., "npm test -- --grep rate-limit"
Record: pass/fail → update TASK-{id}.result.json.convergence_result
```
### 4.5.2 Build & Lint Check
```
Run project build command (if configured):
→ npm run build / tsc --noEmit / etc.
Run project lint command (if configured):
→ npm run lint / eslint src/ / etc.
```
If build or lint fails:
- **No -y**: Display errors, ask user: fix now / continue anyway / abort
- **With -y**: Log warning, continue (non-blocking)
### 4.5.3 Regression Test
```
Run project test suite:
→ npm test / pytest / etc.
Compare: test results before execution (baseline) vs after
```
If tests fail:
- **No -y**: Display failures, ask user: fix now / skip sync / abort
- **With -y**: Log failures as warning in execution results, continue
### 4.5.4 Verify Summary
```
Verify Gate Results:
Convergence: {passed}/{total} tasks verified
Build: pass|fail|skipped
Lint: pass|fail|skipped
Tests: {passed}/{total} ({new_failures} regressions)
Gate: PASS / WARN (continue with warnings) / FAIL (blocked)
```
### 4.5.5 Persist Verify Manifest
Write `execution-manifest.json` to session folder:
```json
{
"session_id": "{session-id}",
"plan_path": "planning/{slug}/plan.json",
"completed_at": "ISO8601",
"tasks": [
{
"task_id": "TASK-001",
"status": "completed",
"result_file": ".task/TASK-001.result.json"
}
],
"files_modified": [
{ "path": "src/services/auth.ts", "action": "modified", "task_id": "TASK-001" },
{ "path": "src/routes/login.ts", "action": "created", "task_id": "TASK-001" }
],
"verify": {
"convergence": { "passed": 2, "total": 2 },
"build": "pass",
"lint": "pass",
"tests": { "passed": 42, "total": 42, "regressions": 0 },
"gate": "PASS"
}
}
```
This manifest is the **single source of truth** consumed by `ddd:sync --from-manifest`.
---
## Step 5: Post-Completion Doc Sync
After all batches complete (unless `--skip-sync`):
### 5.1 Auto-Trigger ddd:sync
```
Invoke /ddd:sync [-y] --task-id {session-id} --from-manifest {session}/execution-manifest.json "{plan.summary}"
```
Note: `/ddd:sync` automatically creates a backup of `doc-index.json` before modifications.
When `--from-manifest` is provided, sync uses the **execution manifest** as its primary data source instead of git diff. This ensures:
- Precise file-level and symbol-level change tracking (from TASK-*.result.json)
- Task-to-file attribution (which task modified which file)
- Convergence verification results carried forward
- Survives process interruptions (manifest is persisted to disk)
Fallback: If manifest is unavailable (e.g., manual mode), sync falls back to git diff discovery.
### 5.2 Generate Action Log
Create action entry with:
- All tasks executed and their results
- Files modified across all batches
- Features and requirements addressed
### 5.3 Update Feature Status
Based on execution results:
- Requirements with verified convergence → update status
- Features with all requirements met → `status: "implemented"`
---
## Step 6: Summary & Follow-up
### 6.1 Execution Results
```
DDD Execute Complete
Tasks: {completed}/{total} ({failed} failed)
Files modified: {count}
Batches: {batch_count}
Doc-Index Changes:
Features updated: {list}
Components updated: {list}
New components registered: {list}
Requirements addressed: {list}
Convergence:
{for each task: task.id — criteria met: X/Y}
```
### 6.2 Follow-up Suggestions
Based on execution results, suggest:
- **New issues**: If unexpected scope expansion was detected
- **Additional tests**: If convergence criteria only partially met
- **Documentation gaps**: If new components were created without docs
- **Next tasks**: If plan had tasks marked as future/deferred
---
## Flags
| Flag | Effect |
|------|--------|
| `-y, --yes` | Auto-confirm, auto-sync |
| `--skip-sync` | Skip post-completion ddd:sync (Step 5) |
| `--skip-verify` | Skip per-batch impact verification (Step 4) AND post-execution verify gate (Step 4.5) |
| `--plan <path>` | Explicit plan.json path |
| `--in-memory` | Accept executionContext from ddd:plan handoff |
## Integration Points
- **Input from**: `/ddd:plan` output (plan.json + TASK-*.json), `doc-index.json`
- **Output to**: Updated `doc-index.json` (via ddd:sync), `TASK-*.result.json` (per-task), `execution-manifest.json` (session-level)
- **Schemas**: `plan-overview-ddd-schema.json` (input), `task-schema.json` + `task-ddd-extension-schema.json` (input), `doc-index.json` (enrichment)
- **Delegates to**: `/ddd:sync` for post-completion synchronization

View File

@@ -0,0 +1,212 @@
---
name: index-build
description: Build document index from spec-generator outputs + codebase mapping. Requires existing spec session. For projects without specs, use /ddd:scan instead.
argument-hint: "[-y|--yes] [-s|--spec <spec-session-id>] [--from-scratch]"
allowed-tools: TodoWrite(*), Agent(*), AskUserQuestion(*), Read(*), Grep(*), Glob(*), Bash(*), Edit(*), Write(*), mcp__ace-tool__search_context(*)
---
## Auto Mode
When `--yes` or `-y`: Auto-confirm all decisions, use inferred mappings, skip interactive review.
# DDD Index Build Command (/ddd:index-build)
## Purpose
From **spec-generator outputs** (requirements, architecture, epics), construct the central document index and map spec entities to actual code locations.
```
Spec outputs (REQ, ADR, EPIC) + Codebase → doc-index.json
```
> **No spec?** Use `/ddd:scan` instead — it reverse-engineers the index from code alone.
## Prerequisite
- At least one spec session in `.workflow/.doc-index/specs/` or `.workflow/.spec/`
- If no spec found → error with suggestion: "No spec session found. Run /ddd:scan for code-first indexing, or /spec-generator to create specs."
## Storage Location
```
.workflow/.doc-index/
├── doc-index.json ← Central index (primary output)
├── specs/ ← Spec-generator outputs
│ └── SPEC-{slug}-{date}/
├── feature-maps/ ← Feature documentation (from Epics)
│ ├── _index.md
│ └── {feature-slug}.md
├── tech-registry/ ← Technical component docs (from code mapping)
│ ├── _index.md
│ └── {component-slug}.md
└── action-logs/ ← Change history (initially empty)
└── _index.md
```
## Phase 1: Discover & Parse Spec Sources
### 1.1 Locate Spec Session
```
IF --spec <id> provided:
Load from .workflow/.doc-index/specs/<id>/ OR .workflow/.spec/<id>/
ELSE:
Scan for all SPEC-* directories
IF multiple → present list, ask user to select (-y picks latest)
IF none → ERROR: "No spec session found. Use /ddd:scan or /spec-generator."
```
### 1.2 Migrate Specs (if needed)
If spec in `.workflow/.spec/` but not in `.workflow/.doc-index/specs/`:
- Copy to `.workflow/.doc-index/specs/`
- Preserve original (backward compatibility)
### 1.3 Extract Structured Entities
| Source File | Extract To |
|------------|------------|
| `spec-config.json` | project name, domain, spec_type |
| `glossary.json` | → index glossary[] |
| `product-brief.md` | vision, goals |
| `requirements/REQ-*.md` | → index requirements[] (with MoSCoW priority) |
| `requirements/NFR-*.md` | → index requirements[] (non-functional) |
| `architecture/ADR-*.md` | → index architectureDecisions[] |
| `epics/EPIC-*.md` | → feature grouping seeds |
## Phase 2: Codebase Mapping
Map spec entities to actual code locations using Gemini:
```bash
ccw cli -p "PURPOSE: Map codebase to specification entities for documentation indexing.
TASK:
• Scan the codebase and identify all major modules/components
• For each component: extract file paths, exported symbols (classes, functions, types)
• Match components to these specification entities by name/domain similarity:
Requirements: {REQ-001: desc, REQ-002: desc, ...extracted from Phase 1}
Architecture decisions: {ADR-001: title, ...extracted from Phase 1}
• Report unmatched components (exist in code but no spec counterpart)
• Report unmatched requirements (in spec but no code found)
MODE: analysis
CONTEXT: @**/*
EXPECTED: JSON: { components: [{ name, type, files, symbols, matched_req_ids, matched_adr_id, is_orphan }], unmatched_reqs: [REQ-NNN] }
CONSTRAINTS: Focus on source directories | Ignore node_modules, dist, build" --tool gemini --mode analysis
```
### 2.1 Generate Component IDs & Link
For each discovered component:
- ID: `tech-{kebab-case-name}`
- Link to matched `REQ-NNN` and `ADR-NNN`
- Flag orphans for user review
## Phase 3: Build Feature Map (from Epics)
### 3.1 Epic → Feature Mapping
```
Each EPIC-NNN → one feat-{slug}
- id: feat-{slug} (from epic slug)
- name: from Epic name
- epicId: EPIC-NNN
- status: inferred from code mapping
- all requirements have matched components → "implemented"
- some matched → "in-progress"
- none matched → "planned"
- requirementIds: from Epic's stories → requirement links
- tags: from domain keywords
```
### 3.2 Document Generation (delegated)
Feature-map and tech-registry document generation is handled by `/ddd:doc-generate` in Phase 5.
Phase 3 only builds the data structures (feature → requirement → component mappings) that doc-generate consumes.
## Phase 4: Assemble doc-index.json
```json
{
"version": "1.0",
"project": "{project-name}",
"build_path": "spec-first",
"spec_session": "SPEC-{slug}-{date}",
"last_updated": "ISO8601",
"glossary": [
{ "id": "gloss-{slug}", "term": "Term", "definition": "...", "aliases": [], "category": "core|technical|business" }
],
"features": [
{ "id": "feat-{slug}", "name": "...", "epicId": "EPIC-NNN", "status": "...", "docPath": "feature-maps/{slug}.md", "requirementIds": ["REQ-NNN"], "tags": [] }
],
"requirements": [
{ "id": "REQ-NNN", "title": "...", "source": "spec", "priority": "Must|Should|Could|Won't", "sourcePath": "specs/SPEC-*/requirements/REQ-NNN-*.md", "techComponentIds": ["tech-{slug}"], "featureId": "feat-{slug}" }
],
"technicalComponents": [
{ "id": "tech-{slug}", "name": "...", "type": "...", "responsibility": "...", "adrId": "ADR-NNN|null", "docPath": "tech-registry/{slug}.md", "codeLocations": [{ "path": "...", "symbols": [], "lineRange": [0,0] }], "dependsOn": [], "featureIds": ["feat-{slug}"], "actionIds": [] }
],
"architectureDecisions": [
{ "id": "ADR-NNN", "title": "...", "source": "spec", "sourcePath": "specs/SPEC-*/architecture/ADR-NNN-*.md", "componentIds": ["tech-{slug}"] }
],
"actions": []
}
```
### Merge with Existing Code-First Index
If a code-first index exists (from prior `/ddd:scan`):
- Replace `IREQ-NNN` with matching `REQ-NNN` where content overlaps
- Keep `IREQ-NNN` without spec counterpart (mark `source: "legacy-inferred"`)
- Replace `IADR-NNN` with `ADR-NNN` where applicable
- Update `build_path` to `"spec-first"`
- Preserve existing `tech-*` components (update links only)
## Phase 5: Generate Documents
Delegate all document generation to `/ddd:doc-generate`:
```
Invoke /ddd:doc-generate [-y]
```
This generates the complete document tree (Layer 3 → 2 → 1):
- `tech-registry/{slug}.md` — component docs from Phase 2 mapping (Layer 3)
- `feature-maps/{slug}.md` — feature docs from Phase 3 mapping (Layer 2)
- `_index.md`, `README.md`, `ARCHITECTURE.md`, `SCHEMA.md` — index/overview docs (Layer 1)
See `/ddd:doc-generate` for full details on generation strategy and flags.
## Phase 6: Coverage Report
```
Index Build Report (spec-first)
Spec: {session-id}
Features: {N} (from {N} Epics)
Requirements: {N} (REQ: {n}, NFR: {n})
Components: {N} ({orphan} orphans without spec match)
ADRs: {N}
Mapping Coverage:
Requirements → Components: {%} ({unmapped} unmapped)
Components → Features: {%}
Epics → Features: 100%
Gaps:
- {N} requirements have no matching code component
- {N} code components are not linked to any requirement
```
## Flags
| Flag | Effect |
|------|--------|
| `-y, --yes` | Skip all interactive prompts |
| `-s, --spec <id>` | Use specific spec session |
| `--from-scratch` | Delete existing index and rebuild |
## Integration Points
- **Input from**: `spec-generator` outputs, codebase, existing `/ddd:scan` index
- **Delegates to**: `/ddd:doc-generate` (Phase 5, full document generation)
- **Output to**: `ddd:plan`, `ddd:sync`, `ddd:update`
- **Upgrades**: Can merge with prior code-first (`/ddd:scan`) index

View File

@@ -0,0 +1,611 @@
---
name: plan
description: Document-driven planning pipeline — queries doc-index, explores codebase with doc-aware angles, clarifies ambiguities, and produces unified plan.json + TASK-*.json artifacts with doc_context traceability.
argument-hint: "[-y|--yes] [--explore] [--skip-explore] [--skip-clarify] \"task description or feature keyword\""
allowed-tools: TodoWrite(*), Agent(*), AskUserQuestion(*), Read(*), Grep(*), Glob(*), Bash(*), Write(*), mcp__ace-tool__search_context(*)
---
## Auto Mode
When `--yes` or `-y`: Skip clarification (Phase 3), auto-select ddd:execute (Phase 5), skip interactive refinement.
# DDD Plan Command (/ddd:plan)
## Purpose
Full planning pipeline for document-driven development. Unlike simple context lookup, this command:
1. **Queries** the doc-index for instant context (features, requirements, components, ADRs)
2. **Explores** the codebase with doc-index-informed angles (not generic presets)
3. **Clarifies** ambiguities from exploration results and doc-index gaps
4. **Plans** with unified schema output (plan.json + TASK-*.json with doc_context)
5. **Hands off** to ddd:execute or other execution engines
### Key Differentiation from lite-plan
- Phase 1 provides instant context from doc-index (no cold-start exploration)
- Exploration angles are doc-index-informed (not generic preset selection)
- Tasks carry doc_context for traceability (features → requirements → code)
- Architecture decisions (ADRs) automatically surface as constraints
## Prerequisite
- `doc-index.json` must exist at `.workflow/.doc-index/doc-index.json`
- If not found → suggest running `/ddd:index-build` or `/ddd:scan` first
## Session Folder
```
.workflow/.doc-index/planning/{task-slug}-{YYYY-MM-DD}/
├── exploration-{angle}.json # Per-angle exploration (Phase 2)
├── explorations-manifest.json # Exploration index
├── plan.json # Plan overview (Phase 4)
├── planning-context.md # Legacy context package (Phase 0+1 combined)
├── .process/
│ └── doc-context-package.json # Bundled doc_context (Phase 1.8)
└── .task/
├── TASK-001.json
└── TASK-002.json
```
---
## Phase 0: Parse Task Intent (enhanced)
### 0.1 Extract Keywords
From the user's task description, extract:
- **Domain keywords**: feature names, module names, business terms
- **Technical keywords**: file paths, class names, function names
- **Action type**: feature | bugfix | refactor | optimization | migration
### 0.2 Glossary Match
Cross-reference extracted keywords against `doc-index.json.glossary[]`:
- Match terms and aliases
- Expand user's vocabulary with canonical terms
### 0.3 Classify Complexity
Assess task complexity based on:
- Number of features potentially affected (from keyword matching)
- Whether new components are needed or existing ones modified
- Cross-feature impact (single feature vs multiple)
| Signal | Complexity |
|--------|-----------|
| Single feature, existing components | Low |
| 1-2 features, some new components | Medium |
| 3+ features, new architecture needed | High |
---
## Phase 1: Doc-Index Query
### 1.0 Schema Version Check (TASK-006)
Before querying doc-index, verify schema compatibility:
```javascript
const docIndex = JSON.parse(Read('.workflow/.doc-index/doc-index.json'));
const schemaVersion = docIndex.schema_version || '0.0'; // Default for legacy
if (schemaVersion !== '1.0') {
console.warn(`Schema version mismatch: found ${schemaVersion}, expected 1.0`);
console.warn('Consider running schema migration or regenerating doc-index with /ddd:scan');
// Continue with degraded functionality - may encounter missing fields
}
```
**Graceful degradation**: If version mismatch detected → log warning → continue with caution (some features may not work as expected).
### 1.1 Feature Search
```
Search doc-index.json.features[] where:
- name CONTAINS keyword (fuzzy)
- tags INTERSECT keywords
- requirementIds link to matching requirements
→ Output: matched feature IDs + names
```
### 1.2 Requirement Search
```
Search doc-index.json.requirements[] where:
- title CONTAINS keyword
- id matches explicit REQ-NNN reference
- featureId matches found features
→ Output: matched requirement IDs + titles + priorities
```
### 1.3 Component Search
```
Search doc-index.json.technicalComponents[] where:
- name CONTAINS keyword
- codeLocations[].path CONTAINS file path keyword
- codeLocations[].symbols CONTAINS symbol keyword
- featureIds INTERSECT found features
→ Output: matched component IDs + code locations
```
### 1.4 ADR Search
```
Search doc-index.json.architectureDecisions[] where:
- componentIds INTERSECT found components
→ Output: matched ADR IDs + titles
```
### 1.5 Action History Search
```
Search doc-index.json.actions[] where:
- related to found features or components
→ Output: recent actions with descriptions
```
### 1.6 Build Impact Map
Assemble all found references into a structured impact map:
```json
{
"affected_features": ["feat-auth"],
"affected_requirements": ["REQ-001", "REQ-002"],
"affected_components": ["tech-auth-service", "tech-user-model"],
"architecture_constraints": ["ADR-001"],
"recent_actions": ["task-123"],
"complexity": "Medium"
}
```
Save as `planning-context.md` (legacy format for backward compatibility).
### Phase 1.7: Symbol Query (DeepWiki Bridge)
If DeepWiki is available (`deepwiki_feature_to_symbol_index` exists in doc-index.json):
1. Collect all `codeLocations[].path` from matched `technicalComponents[]`
2. Query DeepWiki: `POST /api/deepwiki/symbols-for-paths { paths: unique_paths }`
3. Build symbol_docs by component, sorted by type priority (class > function > method)
4. Populate `doc_context.symbol_docs[]` with Top-5 symbols per component
**Graceful degradation**: If DeepWiki unavailable → log warning → skip symbol injection → continue flow.
### Phase 1.8: Persist Doc Context Package
After building doc_context (including symbol_docs from Phase 1.7), persist it as a reusable context package:
1. Bundle doc_context into JSON structure:
```json
{
"affected_features": ["feat-auth"],
"affected_requirements": ["REQ-001", "REQ-002"],
"affected_components": ["tech-auth-service"],
"architecture_constraints": ["ADR-001"],
"index_path": ".workflow/.doc-index/doc-index.json",
"symbol_docs": [...]
}
```
2. Write to session folder: `{sessionFolder}/.process/doc-context-package.json`
3. Store relative path for task.json population: `../.process/doc-context-package.json`
**Error handling**: If write fails → log warning → continue without context package (backward compatible).
---
## Phase 2: Doc-Index-Guided Exploration (NEW)
Use Phase 1 results to **SELECT exploration angles intelligently**:
### 2.1 Angle Selection Logic
| Phase 1 Signal | Add Exploration Angle |
|----------------|----------------------|
| feat-auth or security-related ADR affected | `security` |
| Multiple features crossed (2+) | `integration-points` |
| New component needed (no matching tech-*) | `architecture` |
| Performance-related requirements | `performance` |
| Default (always included) | `patterns` + `dependencies` |
Select 1-4 angles total. More angles for higher complexity.
### 2.2 Skip & Trigger Conditions
| Complexity | Default Behavior | Override |
|-----------|-----------------|---------|
| **Low** | Auto-skip Phase 2 | `--explore` forces exploration |
| **Medium** | Ask user (unless `-y` → skip) | `--explore` forces, `--skip-explore` forces skip |
| **High** | Always run | `--skip-explore` forces skip |
Skip Phase 2 entirely when:
- Complexity is Low AND `--explore` not set
- OR `--skip-explore` flag is set
- OR `-y` flag AND complexity is Medium
### 2.3 Parallel Exploration
Launch 1-4 parallel `cli-explore-agent` runs:
```
For each selected angle:
Agent(subagent_type="cli-explore-agent", prompt="
Explore codebase for: {user task description}
Angle: {angle}
## Doc-Index Context (pre-loaded)
Features affected: {feature names + IDs}
Components: {component names + code locations}
Requirements: {requirement titles}
Architecture decisions: {ADR titles + decisions}
Focus exploration on {angle}-specific concerns.
Output: explore-json-schema format.
")
```
Each agent receives doc-index context (feature-maps, tech-registry docs) to avoid cold-start.
### 2.4 Save Exploration Results
- Each exploration → `exploration-{angle}.json` (explore-json-schema)
- Manifest → `explorations-manifest.json`:
```json
{
"explorations": [
{ "angle": "patterns", "path": "exploration-patterns.json", "file_count": 12 },
{ "angle": "security", "path": "exploration-security.json", "file_count": 8 }
],
"total_files_discovered": 18,
"timestamp": "ISO8601"
}
```
---
## Phase 3: Clarification (NEW)
### 3.1 Aggregate Clarification Needs
Collect from three sources:
1. **Exploration results**: `clarification_needs[]` from each exploration JSON
2. **Doc-index gaps**: unmapped requirements, orphan components, missing feature coverage
3. **Conflicting constraints**: contradictory architecture decisions, requirement priority conflicts
### 3.2 Deduplicate & Batch
- Merge duplicate/similar questions across exploration angles
- Group into rounds (max 4 questions per AskUserQuestion call)
- Prioritize: blocking questions first, nice-to-have last
### 3.3 Skip Conditions
Skip Phase 3 when:
- `-y` flag is set
- `--skip-clarify` flag is set
- No clarification needs collected from any source
- Complexity is Low AND Phase 2 was skipped (no exploration results to aggregate)
### 3.4 Execute Clarification
```
AskUserQuestion(questions=[
{
question: "Which authentication strategy should the new endpoint use?",
header: "Auth strategy",
options: [
{ label: "JWT Bearer (Recommended)", description: "Consistent with ADR-001 and existing auth middleware" },
{ label: "API Key", description: "Simpler but inconsistent with current architecture" },
{ label: "OAuth2", description: "Most flexible but higher implementation cost" }
],
multiSelect: false
}
])
```
Feed answers back into Phase 4 as constraints.
---
## Phase 4: Task Planning (NEW — produces plan.json + TASK-*.json)
### 4.1 Planning Strategy Selection
| Complexity | Strategy |
|-----------|---------|
| Low | Direct Claude planning (inline) |
| Medium | cli-lite-planning-agent with doc-index context |
| High | cli-lite-planning-agent with full exploration + doc-index context |
### 4.2 Planning Input Assembly
Combine:
- User's original task description
- Phase 1 impact map (features, requirements, components, ADRs)
- Phase 2 exploration results (if executed)
- Phase 3 clarification answers (if collected)
- Relevant feature-map and tech-registry doc excerpts
### 4.3 Execute Planning
For **Low complexity** (direct):
```
Generate plan.json + TASK-*.json directly based on assembled context.
```
For **Medium/High complexity**:
```
Agent(subagent_type="cli-lite-planning-agent", prompt="
Task: {user task description}
## Doc-Index Impact Map
{Phase 1 results}
## Exploration Context
{Phase 2 results summary}
## Clarification Answers
{Phase 3 answers}
## Architecture Constraints
{ADR excerpts}
Generate plan following plan-overview-base-schema.
Generate tasks following task-schema.
Include doc_context in both plan.json and each TASK-*.json.
")
```
### 4.3.1 Populate Task Artifacts (TASK-002)
After task generation, enrich each TASK-*.json with artifacts[] field:
1. Load doc-index.json from `.workflow/.doc-index/doc-index.json`
2. For each task, extract feature_ids from task.doc_context
3. Filter doc-index features/requirements matching task scope:
- Match by feature_ids in task.doc_context.feature_ids
- Include linked requirements via requirementIds
- Include linked components via componentIds
4. Populate task.artifacts[] with filtered references:
```json
{
"artifacts": [
{
"type": "feature_spec",
"source": "doc-index",
"path": ".workflow/.doc-index/feature-maps/auth.md",
"feature_id": "feat-auth",
"usage": "Reference for authentication requirements"
},
{
"type": "requirement",
"source": "doc-index",
"path": ".workflow/.doc-index/doc-index.json#requirements[0]",
"feature_id": "feat-auth",
"requirement_id": "REQ-001",
"usage": "Acceptance criteria source"
},
{
"type": "component_doc",
"source": "doc-index",
"path": ".workflow/.doc-index/tech-registry/auth-service.md",
"component_id": "tech-auth-service",
"usage": "Implementation reference"
}
]
}
```
**Loading pattern** (following brainstorm pattern from action-planning-agent.md:200-214):
- Load doc-index.json once for catalog
- Filter by task-relevant feature IDs (1-3 per task)
- Only include artifacts directly referenced in task scope
- Use relative paths from task file location
### 4.3.2 Populate Context Package Path (TASK-001)
Set context_package_path field in each TASK-*.json:
```json
{
"context_package_path": "../.process/doc-context-package.json"
}
```
Relative path from `.task/TASK-*.json` to `.process/doc-context-package.json`.
### 4.3.3 Add Navigation Links Block (TASK-003)
Add links{} navigation block to each TASK-*.json for improved discoverability:
```json
{
"links": {
"plan": "../plan.json",
"doc_index": "../../../doc-index.json",
"feature_maps": [
"../../../feature-maps/auth.md"
],
"related_tasks": [
"TASK-002.json",
"TASK-003.json"
]
}
}
```
**Path computation**:
- `plan`: Relative path from `.task/TASK-*.json` to `plan.json` (sibling of .task/)
- `doc_index`: Relative path to `.workflow/.doc-index/doc-index.json`
- `feature_maps`: Paths to feature-map docs from task.doc_context.feature_docs
- `related_tasks`: Task IDs from task.depends_on or tasks sharing same feature_ids
**Backward compatibility**: links{} is optional field (task-schema allows additionalProperties).
### 4.4 Output Schema: plan.json
Follows `plan-overview-base-schema` with ddd-specific `doc_context` extension:
```json
{
"summary": "...",
"approach": "...",
"task_ids": ["TASK-001", "TASK-002"],
"task_count": 2,
"complexity": "Medium",
"doc_context": {
"affected_features": ["feat-auth"],
"affected_requirements": ["REQ-001", "REQ-002"],
"affected_components": ["tech-auth-service"],
"architecture_constraints": ["ADR-001"],
"index_path": ".workflow/.doc-index/doc-index.json",
"symbol_docs": [
{
"symbol_urn": "deepwiki:symbol:<path>#L<start>-L<end>",
"name": "SymbolName",
"type": "class|function|method",
"doc_summary": "Generated documentation summary...",
"source_path": "src/path/to/file.ts",
"doc_path": ".deepwiki/file.md",
"freshness": "fresh|stale|unknown"
}
]
},
"_metadata": {
"timestamp": "ISO8601",
"source": "cli-lite-planning-agent",
"plan_type": "feature",
"schema_version": "2.0",
"exploration_angles": ["patterns", "security"]
}
}
```
### 4.5 Output Schema: TASK-*.json
Follows `task-schema` with ddd-specific `doc_context` extension:
```json
{
"id": "TASK-001",
"title": "Add rate limiting middleware",
"description": "...",
"depends_on": [],
"convergence": {
"criteria": ["Rate limiter middleware exists and is registered", "Tests pass"],
"verification": "npm test -- --grep rate-limit",
"definition_of_done": "API endpoints enforce rate limits per ADR-001 specifications"
},
"doc_context": {
"feature_ids": ["feat-auth"],
"requirement_ids": ["REQ-001"],
"component_ids": ["tech-auth-service"],
"adr_ids": ["ADR-001"],
"feature_docs": ["feature-maps/auth.md"],
"component_docs": ["tech-registry/auth-service.md"],
"symbol_docs": [
{
"symbol_urn": "deepwiki:symbol:<path>#L<start>-L<end>",
"name": "SymbolName",
"type": "class|function|method",
"doc_summary": "Generated documentation summary...",
"source_path": "src/path/to/file.ts",
"doc_path": ".deepwiki/file.md",
"freshness": "fresh|stale|unknown"
}
]
},
"files": [...],
"implementation": [...]
}
```
### 4.6 Enrichment Rules
Each task is enriched with:
- `feature_ids`, `requirement_ids`, `component_ids`, `adr_ids` — traced from Phase 1
- Relevant feature-map and tech-registry doc paths
- Requirement acceptance criteria as convergence criteria source
- ADR decisions as implementation constraints
---
## Phase 5: Confirmation & Handoff Selection
### 5.1 Display Plan Summary
Show:
- Plan overview (summary, approach, complexity)
- Task list with dependencies
- Doc-index impact: which features/requirements/components will be affected
- Estimated scope
### 5.2 Handoff Options
| Option | Description | When |
|--------|-------------|------|
| **ddd:execute** | Document-aware execution (recommended) | Default for ddd workflow |
| **lite-execute** | Standard execution (no doc awareness) | When doc traceability not needed |
| **direct** | Output context, manual work | User prefers manual coding |
| **stop** | Planning only, no execution | Research/analysis tasks |
### 5.3 Auto-Selection
With `-y`: auto-select `ddd:execute`.
Without `-y`: present options via AskUserQuestion.
---
## Phase 6: Handoff
### 6.1 Build Execution Context
Build `executionContext` compatible with lite-execute format:
```json
{
"plan_path": ".workflow/.doc-index/planning/{slug}/plan.json",
"task_dir": ".workflow/.doc-index/planning/{slug}/.task/",
"doc_index_path": ".workflow/.doc-index/doc-index.json",
"exploration_manifest": ".workflow/.doc-index/planning/{slug}/explorations-manifest.json",
"original_input": "user's task description"
}
```
### 6.2 Invoke Selected Engine
| Selection | Action |
|-----------|--------|
| `ddd:execute` | Invoke `/ddd:execute --in-memory` with executionContext |
| `lite-execute` | Invoke `/workflow:lite-execute` with plan.json path |
| `direct` | Display context package + file list for manual work |
| `stop` | Output plan summary, end here |
---
## Flags
| Flag | Effect |
|------|--------|
| `-y, --yes` | Skip clarification, auto-select ddd:execute |
| `--explore` | Force Phase 2 exploration even for Low complexity |
| `--skip-explore` | Skip Phase 2 (doc-index-guided exploration) |
| `--skip-clarify` | Skip Phase 3 (clarification) only |
## Output
- **Primary**: plan.json + TASK-*.json in session folder
- **Secondary**: planning-context.md (legacy format)
- **Exploration**: exploration-{angle}.json files (if Phase 2 ran)
- **Console**: Plan summary with doc-index impact
## Integration Points
- **Input from**: `doc-index.json` (built by `/ddd:index-build` or `/ddd:scan`)
- **Output to**: `/ddd:execute`, `/workflow:lite-execute`, `/ddd:sync` post-task
- **Schemas**: `plan-overview-ddd-schema.json` (plan output), `task-schema.json` + `task-ddd-extension-schema.json` (task output), `explore-json-schema.json`
- **Triggers**: Before any development task in ddd workflow

View File

@@ -0,0 +1,365 @@
---
name: scan
description: Scan existing codebase to build document index without specs. Analyzes code structure, infers features, discovers components, and reverse-engineers project knowledge graph.
argument-hint: "[-y|--yes] [--from-scratch] [--scope <dir>] \"optional project description\""
allowed-tools: TodoWrite(*), Agent(*), AskUserQuestion(*), Read(*), Grep(*), Glob(*), Bash(*), Edit(*), Write(*), mcp__ace-tool__search_context(*)
---
## Auto Mode
When `--yes` or `-y`: Auto-confirm feature groupings, component naming, skip interactive review.
# DDD Scan Command (/ddd:scan)
## Purpose
For **existing projects without specifications**: analyze codebase to construct the document index by reverse-engineering project structure. This is the code-first entry point — no spec-generator required.
```
Codebase → Components → Features (inferred) → Requirements (inferred) → doc-index.json
```
## When to Use
- Existing project, no spec-generator outputs
- Want to start using doc-driven workflow on a legacy codebase
- Quick project mapping for onboarding or audit
## Prerequisite
- A codebase must exist (src/, lib/, app/, or similar source directories)
- Git repository recommended (for action history seeding)
## Storage Location
```
.workflow/.doc-index/
├── doc-index.json ← Central index (primary output)
├── feature-maps/ ← Inferred feature documentation
│ ├── _index.md
│ └── {feature-slug}.md
├── tech-registry/ ← Discovered component documentation
│ ├── _index.md
│ └── {component-slug}.md
└── action-logs/ ← Git history seeds
├── _index.md
└── {act-hash}.md
```
## Phase 1: Project Structure Analysis
### 1.1 Framework & Stack Detection
```bash
ccw cli -p "PURPOSE: Analyze project structure, tech stack, and architecture for documentation indexing.
TASK:
• Detect language/framework from manifest files (package.json, go.mod, Cargo.toml, requirements.txt, etc.)
• Map directory structure: source dirs, test dirs, config dirs, entry points
• Identify architectural pattern: monolith, microservices, monorepo, library, CLI tool
• Detect key dependencies and their roles (ORM, HTTP framework, auth library, etc.)
• List all major source directories with brief purpose description
MODE: analysis
CONTEXT: @**/*
EXPECTED: JSON with: {
project_name, language, framework, architecture_pattern,
source_dirs: [{ path, purpose, file_count }],
dependencies: [{ name, role }],
entry_points: [{ path, description }]
}
CONSTRAINTS: Prioritize source directories | Ignore node_modules, dist, build, vendor" --tool gemini --mode analysis
```
### 1.2 Merge with project-tech.json
If `.workflow/project-tech.json` exists, merge to reduce redundant analysis.
## Phase 2: Component Discovery
### 2.1 Deep Module Scan
```bash
ccw cli -p "PURPOSE: Discover all significant code components/modules for documentation indexing.
TASK:
• For each source directory, identify distinct modules/components
• For each component extract:
- Name (class name, module name, or logical group)
- Type: service | controller | model | util | hook | route | config | middleware | component
- File paths (primary file + related files)
- Exported symbols (public API: classes, functions, types, constants)
- Internal dependencies: what other modules it imports from within the project
- Responsibility: one-line description of what it does
• Group small utility files under parent module when they share domain
MODE: analysis
CONTEXT: @{source_dirs from Phase 1}
EXPECTED: JSON array: [{ name, type, files, symbols, depends_on, responsibility }]
CONSTRAINTS: Focus on business logic | Min threshold: components with 2+ exports or clear domain purpose | Group utilities under parent domain" --tool gemini --mode analysis
```
### 2.2 Generate Component IDs
For each discovered component:
- ID: `tech-{kebab-case-name}` (e.g., `tech-auth-service`, `tech-user-model`)
- Validate uniqueness, append counter on collision
### 2.3 Build Dependency Graph
From `depends_on` fields, construct internal dependency edges:
```
tech-auth-service → tech-user-model
tech-auth-service → tech-jwt-util
tech-order-controller → tech-auth-service
```
## Phase 3: Feature Inference
**Key step: group components into logical features without formal specs.**
### 3.1 Inference Strategy (priority order)
```
Strategy 1 — Directory grouping:
src/auth/** → feat-auth
src/orders/** → feat-orders
src/payments/** → feat-payments
Strategy 2 — Route/endpoint grouping (web apps):
/api/users/* → feat-user-management
/api/orders/* → feat-order-management
Strategy 3 — Dependency clustering:
Components that heavily import each other → same feature
Strategy 4 — Domain keyword extraction:
Class names + file names → domain terms → feature names
```
### 3.2 Gemini Feature Synthesis
```bash
ccw cli -p "PURPOSE: Infer high-level features from discovered code components. This project has no formal specification.
TASK:
Given these discovered components:
{component list from Phase 2: names, types, files, responsibilities, dependencies}
• Group them into logical features (3-10 features for a typical project)
• For each feature:
- name: human-readable (Chinese OK)
- component_ids: which components belong
- description: what the feature does (inferred from code)
- inferred_requirements: what this feature needs to accomplish (1-3 per feature)
- status: 'implemented' (code complete) or 'partial' (incomplete patterns)
- tags: search keywords
• Identify cross-cutting concerns (logging, auth middleware, error handling) as separate features
MODE: analysis
CONTEXT: {component list JSON}
EXPECTED: JSON: { features: [{ name, description, component_ids, inferred_requirements: [{ id, title }], status, tags }] }
CONSTRAINTS: Every component must belong to at least 1 feature | Prefer fewer broad features over many narrow ones" --tool gemini --mode analysis
```
### 3.3 Interactive Feature Review (unless -y)
Present inferred features to user:
- Allow renaming, merging, splitting
- Allow reassigning components between features
- Confirm final feature list
## Phase 4: Implicit Requirement & Architecture Extraction
### 4.1 Inferred Requirements
For each feature, generate lightweight requirement entries from its components:
```
Feature: feat-auth (User Authentication)
→ IREQ-001: "Users can log in with email and password" (from LoginController)
→ IREQ-002: "JWT tokens for session management" (from AuthMiddleware + jwt dep)
→ IREQ-003: "Password reset via email" (from PasswordResetService)
```
**ID Convention**: `IREQ-NNN` — distinguishes inferred from formal `REQ-NNN`.
### 4.2 Inferred Architecture Decisions
Detect patterns from code + dependencies:
```
Express.js + JWT middleware → IADR-001: "REST API with JWT authentication"
Prisma ORM + PostgreSQL → IADR-002: "PostgreSQL via Prisma ORM"
React + Redux → IADR-003: "React frontend with Redux state"
```
**ID Convention**: `IADR-NNN` — distinguishes inferred from formal `ADR-NNN`.
### 4.3 Glossary Generation
Extract domain terms from:
- Class/function names (CamelCase → terms)
- Key business terms in comments and strings
- Framework-specific terminology
Write to `.workflow/.doc-index/glossary.json`.
## Phase 5: Git History Seeds
```bash
git log --oneline --since="3 months ago" --no-merges --format="%H|%s|%ai" | head -30
```
For each significant commit:
- Match changed files to discovered components
- Create action entry with `type: "historical"`
## Phase 6: Assemble doc-index.json
Write the index with code-first markers:
```json
{
"version": "1.0",
"project": "{project-name}",
"build_path": "code-first",
"spec_session": null,
"last_updated": "ISO8601",
"glossary": [...],
"features": [{
"id": "feat-{slug}",
"name": "Feature Name",
"epicId": null,
"status": "implemented|partial",
"docPath": "feature-maps/{slug}.md",
"requirementIds": ["IREQ-NNN"],
"tags": ["tag"]
}],
"requirements": [{
"id": "IREQ-NNN",
"title": "Inferred requirement",
"source": "inferred",
"priority": "inferred",
"sourcePath": null,
"techComponentIds": ["tech-{slug}"],
"featureId": "feat-{slug}"
}],
"technicalComponents": [{
"id": "tech-{slug}",
"name": "ComponentName",
"type": "service|controller|model|...",
"responsibility": "One-line description",
"adrId": "IADR-NNN|null",
"docPath": "tech-registry/{slug}.md",
"codeLocations": [{ "path": "src/...", "symbols": [...] }],
"dependsOn": ["tech-{other}"],
"featureIds": ["feat-{slug}"],
"actionIds": []
}],
"architectureDecisions": [{
"id": "IADR-NNN",
"title": "Inferred decision",
"source": "inferred",
"sourcePath": null,
"componentIds": ["tech-{slug}"]
}],
"actions": [{
"id": "act-{short-hash}",
"description": "Commit message",
"type": "historical",
"status": "historical",
"affectedComponents": ["tech-{slug}"],
"relatedCommit": "full-hash",
"timestamp": "ISO8601"
}],
"freshness": {
"thresholds": { "warning": 0.3, "stale": 0.7 },
"weights": { "time": 0.1, "churn": 0.4, "symbol": 0.5 },
"time_decay_k": 0.05,
"auto_regenerate": false
},
"deepwiki_feature_to_symbol_index": {}
}
```
## Phase 7: Build DeepWiki Feature-to-Symbol Index
If DeepWiki is available (`.codexlens/deepwiki_index.db` exists):
1. Collect all `codeLocations[].path` from `technicalComponents[]`
2. Query DeepWiki: `POST /api/deepwiki/symbols-for-paths { paths: [...] }`
3. Build `deepwiki_feature_to_symbol_index` by traversing:
`feature → requirementIds → techComponentIds → codeLocations → symbols`
```json
"deepwiki_feature_to_symbol_index": {
"feat-auth": [
"deepwiki:symbol:src/auth/jwt.ts#L30-L55",
"deepwiki:symbol:src/models/user.ts#L12-L40"
]
}
```
**Symbol URN format**: `deepwiki:symbol:<file_path>#L<start>-L<end>`
**Graceful degradation**: If DeepWiki is unavailable, set `deepwiki_feature_to_symbol_index: {}` and log warning.
## Phase 8: Generate Documents
Delegate all document generation to `/ddd:doc-generate`:
```
Invoke /ddd:doc-generate [-y]
```
This generates the complete document tree (Layer 3 → 2 → 1):
- `tech-registry/{slug}.md` — component docs (Layer 3)
- `feature-maps/{slug}.md` — feature docs (Layer 2)
- `_index.md`, `README.md`, `ARCHITECTURE.md`, `SCHEMA.md` — index/overview docs (Layer 1)
See `/ddd:doc-generate` for full details on generation strategy and flags.
## Phase 9: Validation & Report
```
Scan Report
Project: {name} ({language}/{framework})
Architecture: {pattern}
Source dirs: {N}
Discovered:
Components: {N} ({by type breakdown})
Features: {N} (inferred)
Requirements: {N} (IREQ, inferred)
Architecture Decisions: {N} (IADR, inferred)
Historical Actions: {N} (from git)
Coverage:
Components → Features: {%}
Dependencies mapped: {%}
Recommendations:
- Run /spec-generator to formalize {N} inferred requirements
- {N} components have unclear responsibility — review tech-registry docs
- Use /ddd:plan to start planning tasks with this index
```
## Flags
| Flag | Effect |
|------|--------|
| `-y, --yes` | Auto-confirm all decisions |
| `--from-scratch` | Delete existing index and rebuild |
| `--scope <dir>` | Limit scan to specific directory (e.g., `--scope src/auth`) |
## Upgrade Path: scan → spec
When a scanned project later runs `spec-generator` + `/ddd:index-build`:
- `/ddd:index-build` detects existing code-first index
- Merges: `IREQ-NNN``REQ-NNN`, `IADR-NNN``ADR-NNN` where content overlaps
- Updates `build_path` to `"spec-first"`
- Preserves all `tech-*` and `feat-*` entries (updates links only)
## Integration Points
- **Input from**: Codebase, git history, `project-tech.json`
- **Delegates to**: `/ddd:doc-generate` (Phase 8, full document generation)
- **Output to**: `ddd:plan`, `ddd:sync`, `ddd:update`, `ddd:index-build` (upgrade)
- **Standalone**: Can be used independently on any project

View File

@@ -0,0 +1,321 @@
---
name: sync
description: Post-task synchronization - update document index, generate action log, and refresh feature/component docs after completing a development task.
argument-hint: "[-y|--yes] [--dry-run] [--from-manifest <path>] [--task-id <id>] [--commit <hash>] \"task summary\""
allowed-tools: TodoWrite(*), Agent(*), AskUserQuestion(*), Read(*), Grep(*), Glob(*), Bash(*), Edit(*), Write(*), mcp__ace-tool__search_context(*)
---
## Auto Mode
When `--yes` or `-y`: Auto-detect changes, auto-update all docs, skip review prompts.
# DDD Sync Command (/ddd:sync)
## Purpose
After completing a development task, synchronize the document index with actual code changes:
1. **Analyze** what changed (git diff)
2. **Trace** which features/requirements/components are affected
3. **Update** index entries (status, code locations, links)
4. **Generate** action log entry
5. **Refresh** feature-map and tech-registry documents
## When to Use: sync vs update
| Scenario | Use |
|----------|-----|
| Task completed, ready to commit | **ddd:sync** — full post-task reconciliation |
| Mid-development, quick impact check | ddd:update |
| Pre-commit validation | ddd:update --check-only |
| Auto-triggered after ddd:execute | **ddd:sync** (automatic) |
| Periodic index refresh during refactoring | ddd:update |
**Rule of thumb**: `sync` = task boundary (done something), `update` = development pulse (doing something).
## Prerequisite
- `doc-index.json` must exist
- Git repository with committed or staged changes
## Phase 1: Change Detection
### 0.1 Schema Version Check (TASK-006)
Before processing changes, verify doc-index schema compatibility:
```javascript
const docIndex = JSON.parse(Read('.workflow/.doc-index/doc-index.json'));
const schemaVersion = docIndex.schema_version || '0.0'; // Default for legacy
if (schemaVersion !== '1.0') {
console.warn(`Schema version mismatch: found ${schemaVersion}, expected 1.0`);
console.warn('Consider running schema migration or regenerating doc-index with /ddd:scan');
// Continue with degraded functionality - may encounter missing fields
}
```
**Graceful degradation**: If version mismatch detected → log warning → continue with caution (some features may not work as expected).
### 1.0 Data Source Selection
```
IF --from-manifest <path>:
Load execution-manifest.json
→ files_modified[] provides precise file list + action type + task attribution
→ TASK-*.result.json provides symbol-level changes + convergence results
→ Skip Phase 1.1/1.2 (already classified by execute)
→ Proceed directly to Phase 2 with manifest data
ELSE:
→ Fall through to Phase 1.1 (git-based discovery)
```
**`--from-manifest` advantages** (used automatically by ddd:execute):
- Precise file → task attribution (which task modified which file)
- Symbol-level change tracking (not just file-level)
- Convergence verification results carried forward to action-log
- Survives process interruptions (manifest is persisted to disk)
### 1.1 Identify Changes (git-based fallback)
```bash
# If --commit provided:
git diff --name-only {commit}^..{commit}
git diff --stat {commit}^..{commit}
# If --task-id provided, find related commits:
git log --oneline --grep="task-{id}" | head -10
# Otherwise: changes since last ddd:sync
git diff --name-only HEAD~1..HEAD
```
### 1.2 Classify Changes (git-based fallback)
For each changed file, determine:
- **Type**: added | modified | deleted | renamed
- **Category**: source | test | config | docs | other
- **Symbols affected**: parse diff for changed functions/classes (use Gemini if complex)
## Phase 2: Impact Tracing (Layer-Based, TASK-004)
**Strategy**: Trace impact through layers (files → components → features → indexes) following memory-manage pattern.
### 2.1 Match to Index
For each changed file path:
```
Search doc-index.json.technicalComponents[].codeLocations[].path
→ Find matching component IDs (Layer 3)
→ From components, find linked featureIds (Layer 2)
→ From features, find linked requirementIds (Layer 2)
```
### 2.2 Discover New Components
If changed files don't match any existing component:
- Flag as potential new component
- Ask user if it should be registered (or auto-register with `-y`)
### 2.3 Build Impact Report
```markdown
## Impact Summary
### Changed Files (5)
- src/services/auth.ts (modified) → tech-auth-service → feat-auth
- src/models/user.ts (modified) → tech-user-model → feat-auth
- src/routes/login.ts (added) → NEW COMPONENT → feat-auth
- src/tests/auth.test.ts (modified) → [test file, skip]
- package.json (modified) → [config, skip]
### Affected Features
- feat-auth: User Authentication (2 components modified, 1 new)
### Affected Requirements
- REQ-001: Email login (implementation updated)
- REQ-002: JWT token generation (implementation updated)
```
## Phase 2.4: DeepWiki Freshness Check
If DeepWiki integration is configured (`doc-index.json.freshness` exists):
### 2.4.1 Identify Modified Files
From `execution-manifest.json` or git diff, collect `files_modified[]` with `action == "modified"`.
### 2.4.2 Check Staleness
Query DeepWiki: `POST /api/deepwiki/stale-files { files: [{path, hash}] }`
For each stale file's symbols, calculate staleness score:
```
S(symbol) = min(1.0, w_t × T + w_c × C + w_s × M)
```
Where weights come from `doc-index.json.freshness.weights`.
### 2.4.3 Score Propagation (max aggregation)
```
S_file = max(S_symbol_1, S_symbol_2, ...)
S_component = max(S_file_1, S_file_2, ...)
S_feature = max(S_component_1, S_component_2, ...)
```
### 2.4.4 Status Assignment
Using thresholds from `doc-index.json.freshness.thresholds`:
- `fresh`: score in [0, warning_threshold)
- `warning`: score in [warning_threshold, stale_threshold)
- `stale`: score in [stale_threshold, 1.0]
### 2.4.5 Update Records
- Update `deepwiki_symbols.staleness_score` and `deepwiki_files.staleness_score` in DeepWiki SQLite
- Update `tech-registry/{slug}.md` YAML frontmatter with freshness block
- Update `feature-maps/{slug}.md` YAML frontmatter with freshness block
- Update `deepwiki_feature_to_symbol_index` in doc-index.json
### 2.4.6 Staleness Report
Add to action-log:
- Number of stale symbols/files/components
- Top-5 most stale items with scores
- Auto-regeneration candidates (if `auto_regenerate: true` and score >= stale threshold)
## Phase 3: Update Index
### 3.0 Dry-Run Gate
If `--dry-run` is set:
- Execute Phase 3 analysis (determine what would change)
- Display planned modifications as a preview report
- Skip all file writes (Phase 3.1-3.5 and Phase 4)
- Output: "Dry-run complete. Run without --dry-run to apply changes."
### 3.0.1 Backup Index
Before any modifications, create backup:
- Copy `doc-index.json``doc-index.json.bak`
- On failure: restore from `.bak` and report error
- On success: remove `.bak`
### 3.1 Update Technical Components
For each affected component in `doc-index.json`:
- Update `codeLocations` if file paths or line ranges changed
- Update `symbols` if new exports were added
- Add new `actionIds` entry
### 3.2 Register New Components
For newly discovered components:
- Generate `tech-{slug}` ID
- Create entry in `technicalComponents[]`
- Link to appropriate features
- Generate new `tech-registry/{slug}.md` document
### 3.3 Update Feature Status
For each affected feature:
- If all requirements now have mapped components → `status: "implemented"`
- If some requirements still unmapped → `status: "in-progress"`
### 3.4 Add Action Entry
```json
{
"id": "task-{id}",
"description": "{task summary from user}",
"type": "feature|bugfix|refactor",
"status": "completed",
"affectedFeatures": ["feat-auth"],
"affectedComponents": ["tech-auth-service", "tech-user-model"],
"changedFiles": [
{ "path": "src/services/auth.ts", "action": "modified", "task_id": "TASK-001" },
{ "path": "src/models/user.ts", "action": "modified", "task_id": "TASK-001" }
],
"symbolsChanged": ["AuthService.validate", "UserModel.toJSON"],
"convergenceResults": {
"passed": 2,
"total": 2,
"details": ["Rate limiter middleware exists", "Config accepts per-route limits"]
},
"verifyGate": "PASS|WARN|FAIL|skipped",
"relatedCommit": "{commit hash}",
"manifestPath": "{execution-manifest.json path | null}",
"timestamp": "ISO8601"
}
```
### 3.5 Update Timestamp
Set `doc-index.json.last_updated` to current time.
## Phase 4: Refresh Documents & Action Log
### 4.1 Delegate Document Refresh to /ddd:doc-refresh
From Phase 2 impact tracing, collect affected component and feature IDs, then delegate:
```
Invoke /ddd:doc-refresh [-y] --components {affected_component_ids} --features {affected_feature_ids}
```
This handles Layer 3 → 2 → 1 selective document refresh. See `/ddd:doc-refresh` for full details.
### 4.2 Generate Action Log Entry
Create `.workflow/.doc-index/action-logs/{task-id}.md`:
```markdown
---
id: task-{id}
type: feature|bugfix|refactor
status: completed
features: [feat-auth]
components: [tech-auth-service, tech-user-model]
commit: {hash}
timestamp: ISO8601
---
# Task: {summary}
## Changes
| File | Type | Component |
|------|------|-----------|
| src/services/auth.ts | modified | tech-auth-service |
## Impact
- Features affected: feat-auth
- Requirements addressed: REQ-001, REQ-002
## Staleness (if DeepWiki freshness enabled)
| Item | Type | Score | Status |
|------|------|-------|--------|
| {symbol/file/component} | {type} | {score} | {fresh/warning/stale} |
## Notes
{any user-provided notes}
```
## Phase 5: Confirmation (unless -y)
Present update summary to user:
- Files updated in doc-index
- New documents created
- Status changes
- Ask for confirmation before writing
## Flags
| Flag | Effect |
|------|--------|
| `-y, --yes` | Auto-confirm all updates |
| `--dry-run` | Preview all changes without modifying any files |
| `--from-manifest <path>` | Use execution-manifest.json as data source (auto-set by ddd:execute) |
| `--task-id <id>` | Associate with specific task ID |
| `--commit <hash>` | Analyze specific commit |
## Integration Points
- **Input from**: `execution-manifest.json` (preferred, from ddd:execute) OR Git history (fallback), `doc-index.json`, `/ddd:plan` output
- **Delegates to**: `/ddd:doc-refresh` (Phase 4.1, selective document refresh)
- **Output to**: Updated `doc-index.json`, feature-maps/, tech-registry/, action-logs/
- **Triggers**: After completing any development task
- **Data source priority**: `--from-manifest` > `--commit` > `--task-id` > git diff HEAD~1

View File

@@ -0,0 +1,160 @@
---
name: update
description: Incremental index update - detect code changes and trace impact to related features/requirements. Lightweight alternative to full sync.
argument-hint: "[-y|--yes] [--files <file1,file2,...>] [--staged] [--check-only]"
allowed-tools: TodoWrite(*), AskUserQuestion(*), Read(*), Grep(*), Glob(*), Bash(*), Edit(*), Write(*), mcp__ace-tool__search_context(*)
---
## Auto Mode
When `--yes` or `-y`: Auto-update index without confirmation prompts.
# DDD Update Command (/ddd:update)
## Purpose
Lightweight incremental update: given a set of changed files, trace their impact through the document index and update affected entries. Unlike `/ddd:sync` (full post-task sync), this command focuses on keeping the index fresh during development.
## When to Use: update vs sync
| Scenario | Use |
|----------|-----|
| Quick impact check during development | **ddd:update** |
| Preview what sync would change | **ddd:update --check-only** |
| Task completed, full reconciliation | ddd:sync |
| Register new components + update all docs | ddd:sync |
**Rule of thumb**: `update` = lightweight pulse (during work), `sync` = full checkpoint (after work).
## Use Cases
1. **During development**: Quick check which docs are affected by current changes
2. **Pre-commit check**: Ensure index is up-to-date before committing
3. **Periodic refresh**: Update stale code locations after refactoring
## Prerequisite
- `doc-index.json` must exist at `.workflow/.doc-index/doc-index.json`
## Phase 1: Identify Changed Files
### Source Priority
```
1. --files <list> → Explicit file list
2. --staged → git diff --cached --name-only
3. (default) → git diff --name-only (unstaged changes)
```
### Output
List of changed file paths with change type (added/modified/deleted/renamed).
## Phase 2: Trace Impact
### 2.1 Forward Lookup (Code → Components → Features)
For each changed file:
```
doc-index.json.technicalComponents[]
.codeLocations[].path MATCH changed_file
→ component_ids[]
doc-index.json.technicalComponents[component_ids]
.featureIds[]
→ feature_ids[]
doc-index.json.features[feature_ids]
.requirementIds[]
→ requirement_ids[]
```
### 2.2 Orphan Detection
Files not matching any component → flag as:
- **Potential new component**: if in src/ directory
- **Ignorable**: if in test/, docs/, config/ directories
### 2.3 Impact Report
```
Impact Analysis for 3 changed files:
src/services/auth.ts (modified)
→ Component: tech-auth-service (AuthService)
→ Feature: feat-auth (User Authentication)
→ Requirements: REQ-001, REQ-002
src/middleware/rate-limit.ts (added)
→ No matching component (new file)
→ Suggested: Register as new component
src/utils/hash.ts (modified)
→ Component: tech-hash-util
→ Features: feat-auth, feat-password-reset
→ Requirements: REQ-001, REQ-005
```
## Phase 3: Update Index (unless --check-only)
### 3.1 Update Code Locations
For matched components:
- If file was renamed → update `codeLocations[].path`
- If file was deleted → remove code location entry
- If symbols changed → update `symbols` list (requires AST or Gemini analysis)
### 3.2 Register New Components (interactive unless -y)
For orphan files in src/:
- Prompt user for component name and type
- Or auto-generate with `-y`: derive name from file path
- Create `technicalComponents[]` entry
- Ask which feature it belongs to (or auto-link by directory structure)
### 3.3 Update Timestamps
- Update `technicalComponents[].docPath` last_updated in corresponding .md
- Update `doc-index.json.last_updated`
## Phase 4: Refresh Documents (if updates were made)
### 4.1 Delegate to /ddd:doc-refresh
From Phase 2 impact tracing, collect affected component and feature IDs, then delegate:
```
Invoke /ddd:doc-refresh [-y] --minimal --components {affected_component_ids} --features {affected_feature_ids}
```
The `--minimal` flag ensures only metadata/frontmatter is updated (code locations, timestamps), skipping full content regeneration. This keeps the update lightweight.
See `/ddd:doc-refresh` for full details.
### 4.2 Skip If --check-only
With `--check-only`, skip Phase 3 and Phase 4 entirely — only output the impact report.
## Flags
| Flag | Effect |
|------|--------|
| `-y, --yes` | Auto-confirm updates |
| `--files <list>` | Explicit comma-separated file list |
| `--staged` | Analyze staged (git cached) files |
| `--check-only` | Report impact without modifying index |
## Output
- **Console**: Impact report showing affected features/requirements
- **Updated**: `doc-index.json` (if not --check-only)
- **Updated**: Affected tech-registry/ and feature-maps/ docs
## Integration Points
- **Input from**: Git working tree, `doc-index.json`
- **Delegates to**: `/ddd:doc-refresh` (Phase 4.1, incremental document refresh with --minimal)
- **Output to**: Updated `doc-index.json`, impact report
- **Triggers**: During development, pre-commit, or periodic refresh
- **Can chain to**: `/ddd:sync` for full post-task synchronization

View File

@@ -93,7 +93,7 @@ async function selectCommandCategory() {
{ label: "Brainstorm", description: "brainstorm-with-file, brainstorm (unified skill)" },
{ label: "Analysis", description: "analyze-with-file" },
{ label: "Issue", description: "discover, plan, queue, execute, from-brainstorm, convert-to-plan" },
{ label: "Utility", description: "clean, init, replan, status" }
{ label: "Utility", description: "clean, spec:setup, spec:add, replan, status" }
],
multiSelect: false
}]
@@ -107,7 +107,7 @@ async function selectCommandCategory() {
async function selectCommand(category) {
const commandOptions = {
'Planning': [
{ label: "/workflow-lite-planex", description: "Lightweight merged-mode 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" },
@@ -132,7 +132,7 @@ async function selectCommand(category) {
{ label: "/workflow:review", description: "Post-implementation review" }
],
'Bug Fix': [
{ label: "/workflow-lite-planex", 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': [
@@ -153,7 +153,7 @@ async function selectCommand(category) {
],
'Utility': [
{ label: "/workflow:clean", description: "Intelligent code cleanup" },
{ label: "/workflow:init", description: "Initialize project-level state" },
{ label: "/workflow:spec:setup", description: "Initialize project-level state" },
{ label: "/workflow:replan", description: "Interactive workflow replanning" },
{ label: "/workflow:status", description: "Generate workflow status views" }
]
@@ -302,7 +302,7 @@ async function defineSteps(templateDesign) {
"description": "Quick implementation with testing",
"level": 2,
"steps": [
{ "cmd": "/workflow-lite-planex", "args": "\"{{goal}}\"", "unit": "quick-implementation", "execution": { "type": "slash-command", "mode": "mainprocess" }, "contextHint": "Create lightweight implementation plan (includes execution)" },
{ "cmd": "/workflow-lite-plan", "args": "\"{{goal}}\"", "unit": "quick-implementation", "execution": { "type": "slash-command", "mode": "mainprocess" }, "contextHint": "Create lightweight implementation plan (includes execution)" },
{ "cmd": "/workflow-test-fix", "unit": "test-validation", "execution": { "type": "slash-command", "mode": "mainprocess" }, "contextHint": "Generate test tasks" },
{ "cmd": "/workflow-test-fix", "unit": "test-validation", "execution": { "type": "slash-command", "mode": "async" }, "contextHint": "Execute test-fix cycle until pass rate >= 95%" }
]
@@ -334,7 +334,7 @@ async function defineSteps(templateDesign) {
"description": "Bug diagnosis and fix with testing",
"level": 2,
"steps": [
{ "cmd": "/workflow-lite-planex", "args": "--bugfix \"{{goal}}\"", "unit": "bug-fix", "execution": { "type": "slash-command", "mode": "mainprocess" }, "contextHint": "Diagnose, plan, and execute bug fix" },
{ "cmd": "/workflow-lite-plan", "args": "--bugfix \"{{goal}}\"", "unit": "bug-fix", "execution": { "type": "slash-command", "mode": "mainprocess" }, "contextHint": "Diagnose, plan, and execute bug fix" },
{ "cmd": "/workflow-test-fix", "unit": "test-validation", "execution": { "type": "slash-command", "mode": "mainprocess" }, "contextHint": "Generate regression tests" },
{ "cmd": "/workflow-test-fix", "unit": "test-validation", "execution": { "type": "slash-command", "mode": "async" }, "contextHint": "Verify fix with tests" }
]
@@ -348,7 +348,7 @@ async function defineSteps(templateDesign) {
"description": "Urgent production bug fix (no tests)",
"level": 2,
"steps": [
{ "cmd": "/workflow-lite-planex", "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" }
]
}
```
@@ -417,7 +417,7 @@ async function defineSteps(templateDesign) {
"description": "Bridge lightweight planning to issue workflow",
"level": 2,
"steps": [
{ "cmd": "/workflow-lite-planex", "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" }

View File

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

View File

@@ -26,16 +26,16 @@ Coordinator variant of `/idaw:run`: external CLI execution with background tasks
```javascript
const SKILL_CHAIN_MAP = {
'bugfix': ['workflow-lite-planex', 'workflow-test-fix'],
'bugfix-hotfix': ['workflow-lite-planex'],
'feature': ['workflow-lite-planex', 'workflow-test-fix'],
'bugfix': ['workflow-lite-plan', 'workflow-test-fix'],
'bugfix-hotfix': ['workflow-lite-plan'],
'feature': ['workflow-lite-plan', 'workflow-test-fix'],
'feature-complex': ['workflow-plan', 'workflow-execute', 'workflow-test-fix'],
'refactor': ['workflow:refactor-cycle'],
'tdd': ['workflow-tdd-plan', 'workflow-execute'],
'test': ['workflow-test-fix'],
'test-fix': ['workflow-test-fix'],
'review': ['review-cycle'],
'docs': ['workflow-lite-planex']
'docs': ['workflow-lite-plan']
};
```
@@ -472,11 +472,11 @@ function assembleCliPrompt(skillName, task, previousResult, autoYes) {
const yFlag = autoYes ? ' -y' : '';
// Map skill to command invocation
if (skillName === 'workflow-lite-planex') {
if (skillName === 'workflow-lite-plan') {
const goal = sanitize(`${task.title}\n${task.description}`);
prompt = `/workflow-lite-planex${yFlag} "${goal}"`;
if (task.task_type === 'bugfix') prompt = `/workflow-lite-planex${yFlag} --bugfix "${goal}"`;
if (task.task_type === 'bugfix-hotfix') prompt = `/workflow-lite-planex${yFlag} --hotfix "${goal}"`;
prompt = `/workflow-lite-plan${yFlag} "${goal}"`;
if (task.task_type === 'bugfix') prompt = `/workflow-lite-plan${yFlag} --bugfix "${goal}"`;
if (task.task_type === 'bugfix-hotfix') prompt = `/workflow-lite-plan${yFlag} --hotfix "${goal}"`;
} else if (skillName === 'workflow-plan') {
prompt = `/workflow-plan${yFlag} "${sanitize(task.title)}"`;
@@ -608,8 +608,8 @@ Phase 5: handleStepCompletion()
{
"task_id": "IDAW-001",
"skill_index": 0,
"skill": "workflow-lite-planex",
"prompt": "/workflow-lite-planex -y \"Fix login timeout\"",
"skill": "workflow-lite-plan",
"prompt": "/workflow-lite-plan -y \"Fix login timeout\"",
"timestamp": "ISO"
}
]

View File

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

File diff suppressed because it is too large Load Diff

View File

@@ -29,40 +29,31 @@ When `--yes` or `-y`: Auto-confirm decisions, use recommended roles, balanced ex
## Output Artifacts
### Phase 1: Seed Understanding
| Phase | Artifact | Description |
|-------|----------|-------------|
| 1 | `brainstorm.md` | Complete thought evolution timeline (initialized) |
| 1 | Session variables | Dimensions, roles, exploration vectors |
| 2 | `exploration-codebase.json` | Codebase context from cli-explore-agent |
| 2 | `perspectives.json` | Multi-CLI perspective findings (creative/pragmatic/systematic) |
| 2 | Updated `brainstorm.md` | Round 2 multi-perspective exploration |
| 3 | `ideas/{idea-slug}.md` | Deep-dive analysis for selected ideas |
| 3 | Updated `brainstorm.md` | Round 3-6 refinement cycles |
| 4 | `synthesis.json` | Final synthesis with top ideas, recommendations |
| 4 | Final `brainstorm.md` | Complete thought evolution with conclusions |
| Artifact | Description |
|----------|-------------|
| `brainstorm.md` | Complete thought evolution timeline (initialized) |
| Session variables | Dimensions, roles, exploration vectors |
## Output Structure
### Phase 2: Divergent Exploration
| Artifact | Description |
|----------|-------------|
| `exploration-codebase.json` | Codebase context from cli-explore-agent |
| `perspectives.json` | Multi-CLI perspective findings (creative/pragmatic/systematic) |
| Updated `brainstorm.md` | Round 2 multi-perspective exploration |
### Phase 3: Interactive Refinement
| Artifact | Description |
|----------|-------------|
| `ideas/{idea-slug}.md` | Deep-dive analysis for selected ideas |
| Updated `brainstorm.md` | Round 3-6 refinement cycles |
### Phase 4: Convergence & Crystallization
| Artifact | Description |
|----------|-------------|
| `synthesis.json` | Final synthesis with top ideas, recommendations |
| Final `brainstorm.md` | ⭐ Complete thought evolution with conclusions |
## Overview
Interactive brainstorming workflow with **multi-CLI collaboration** and **documented thought evolution**. Expands initial ideas through questioning, multi-perspective analysis, and iterative refinement.
**Core workflow**: Seed Idea → Expand → Multi-CLI Discuss → Synthesize → Refine → Crystallize
```
.workflow/.brainstorm/BS-{slug}-{date}/
├── brainstorm.md # ⭐ Complete thought evolution timeline
├── exploration-codebase.json # Phase 2: Codebase context
├── perspectives.json # Phase 2: Multi-CLI findings
├── synthesis.json # Phase 4: Final synthesis
└── ideas/ # Phase 3: Individual idea deep-dives
├── idea-1.md
├── idea-2.md
└── merged-idea-1.md
```
```
┌─────────────────────────────────────────────────────────────────────────┐
@@ -102,31 +93,12 @@ Interactive brainstorming workflow with **multi-CLI collaboration** and **docume
└─────────────────────────────────────────────────────────────────────────┘
```
## Output Structure
```
.workflow/.brainstorm/BS-{slug}-{date}/
├── brainstorm.md # ⭐ Complete thought evolution timeline
├── exploration-codebase.json # Phase 2: Codebase context
├── perspectives.json # Phase 2: Multi-CLI findings
├── synthesis.json # Phase 4: Final synthesis
└── ideas/ # Phase 3: Individual idea deep-dives
├── idea-1.md
├── idea-2.md
└── merged-idea-1.md
```
## Implementation
### Session Initialization
**Objective**: Create session context and directory structure for brainstorming.
**Required Actions**:
1. Extract idea/topic from `$ARGUMENTS`
2. Generate session ID: `BS-{slug}-{date}`
- slug: lowercase, alphanumeric + Chinese, max 40 chars
- date: YYYY-MM-DD (UTC+8)
2. Generate session ID: `BS-{slug}-{date}` (slug: lowercase, alphanumeric + Chinese, max 40 chars; date: YYYY-MM-DD UTC+8)
3. Define session folder: `.workflow/.brainstorm/{session-id}`
4. Parse command options:
- `-c` or `--continue` for session continuation
@@ -135,54 +107,41 @@ Interactive brainstorming workflow with **multi-CLI collaboration** and **docume
5. Auto-detect mode: If session folder + brainstorm.md exist → continue mode
6. Create directory structure: `{session-folder}/ideas/`
**Session Variables**:
- `sessionId`: Unique session identifier
- `sessionFolder`: Base directory for all artifacts
- `brainstormMode`: creative | structured | balanced
- `autoMode`: Boolean for auto-confirmation
- `mode`: new | continue
7. **Create Progress Tracking** (TodoWrite — MANDATORY):
```
TodoWrite([
{ id: "phase-1", title: "Phase 1: Seed Understanding", status: "in_progress" },
{ id: "phase-2", title: "Phase 2: Divergent Exploration", status: "pending" },
{ id: "phase-3", title: "Phase 3: Interactive Refinement", status: "pending" },
{ id: "phase-4", title: "Phase 4: Convergence & Crystallization", status: "pending" },
{ id: "next-step", title: "GATE: Post-Completion Next Step", status: "pending" }
])
```
- Update status to `"in_progress"` when entering each phase, `"completed"` when done
- **`next-step` is a terminal gate** — workflow is NOT complete until this todo is `"completed"`
**Session Variables**: `sessionId`, `sessionFolder`, `brainstormMode` (creative|structured|balanced), `autoMode` (boolean), `mode` (new|continue)
### Phase 1: Seed Understanding
**Objective**: Analyze topic, select roles, gather user input, expand into exploration vectors.
**Prerequisites**:
- Session initialized with valid sessionId and sessionFolder
- Topic/idea available from $ARGUMENTS
**Workflow Steps**:
1. **Parse Seed & Identify Dimensions**
- Match topic keywords against BRAINSTORM_DIMENSIONS
- Identify relevant dimensions: technical, ux, business, innovation, feasibility, scalability, security
- Match topic keywords against Brainstorm Dimensions table
- Default dimensions based on brainstormMode if no match
2. **Role Selection**
- **Recommend roles** based on topic keywords (see Role Keywords mapping)
- **Options**:
- **Professional roles**: system-architect, product-manager, ui-designer, ux-expert, data-architect, test-strategist, subject-matter-expert, product-owner, scrum-master
- **Simple perspectives**: creative/pragmatic/systematic (fallback)
- Recommend roles based on topic keywords (see Role Selection tables)
- **Professional roles**: system-architect, product-manager, ui-designer, ux-expert, data-architect, test-strategist, subject-matter-expert, product-owner, scrum-master
- **Simple perspectives** (fallback): creative/pragmatic/systematic
- **Auto mode**: Select top 3 recommended professional roles
- **Manual mode**: AskUserQuestion with recommended roles + "Use simple perspectives" option
3. **Initial Scoping Questions** (if new session + not auto mode)
- **Direction**: Multi-select from directions generated by detected dimensions (see Brainstorm Dimensions)
- **Direction**: Multi-select from directions generated by detected dimensions
- **Depth**: Single-select from quick/balanced/deep (15-20min / 30-60min / 1-2hr)
- **Constraints**: Multi-select from existing architecture, time, resources, or no constraints
4. **Expand Seed into Exploration Vectors**
- Launch Gemini CLI with analysis mode
- Generate 5-7 exploration vectors:
- Core question: Fundamental problem/opportunity
- User perspective: Who benefits and how
- Technical angle: What enables this
- Alternative approaches: Other solutions
- Challenges: Potential blockers
- Innovation angle: 10x better approach
- Integration: Fit with existing systems
- Parse result into structured vectors
**CLI Call Example**:
```javascript
Bash({
command: `ccw cli -p "
@@ -205,45 +164,14 @@ Output as structured exploration vectors for multi-perspective analysis.
})
```
5. **Initialize brainstorm.md**
- Create brainstorm.md with session metadata
- Add initial context: user focus, depth, constraints
- Add seed expansion: original idea + exploration vectors
- Create empty sections for thought evolution timeline
5. **Initialize brainstorm.md** with session metadata, initial context (user focus, depth, constraints), seed expansion (original idea + exploration vectors), empty thought evolution timeline sections
**Success Criteria**:
- Session folder created with brainstorm.md initialized
- 1-3 roles selected (professional or simple perspectives)
- 5-7 exploration vectors generated
- User preferences captured (direction, depth, constraints)
**TodoWrite**: Update `phase-1` → `"completed"`, `phase-2` → `"in_progress"`
### Phase 2: Divergent Exploration
**Objective**: Gather codebase context, then execute multi-perspective analysis in parallel.
**Prerequisites**:
- Phase 1 completed successfully
- Roles selected and stored
- brainstorm.md initialized
**Workflow Steps**:
1. **Primary Codebase Exploration via cli-explore-agent** (⚠️ FIRST)
- Agent type: `cli-explore-agent`
- Execution mode: synchronous (run_in_background: false)
- **Tasks**:
- Run: `ccw tool exec get_modules_by_depth '{}'`
- Search code related to topic keywords
- Read: `.workflow/project-tech.json` if exists
- **Output**: `{sessionFolder}/exploration-codebase.json`
- relevant_files: [{path, relevance, rationale}]
- existing_patterns: []
- architecture_constraints: []
- integration_points: []
- inspiration_sources: []
- **Purpose**: Enrich CLI prompts with codebase context
**Agent Call Example**:
```javascript
Agent({
subagent_type: "cli-explore-agent",
@@ -281,147 +209,67 @@ Schema:
}
`
})
```
2. **Multi-CLI Perspective Analysis** (⚠️ AFTER exploration)
- Launch 3 CLI calls in parallel (Gemini/Codex/Claude)
- **Perspectives**:
- **Creative (Gemini)**: Innovation, cross-domain inspiration, challenge assumptions
- **Pragmatic (Codex)**: Implementation reality, feasibility, technical blockers
- **Systematic (Claude)**: Architecture, decomposition, scalability
- **Shared context**: Include exploration-codebase.json findings in prompts
- **Execution**: Bash with run_in_background: true, wait for all results
- **Output**: perspectives.json with creative/pragmatic/systematic sections
**Multi-CLI Call Example** (parallel execution):
Build shared context from exploration results:
```javascript
// Build shared context from exploration results
const explorationContext = `
PRIOR EXPLORATION CONTEXT (from cli-explore-agent):
- Key files: ${explorationResults.relevant_files.slice(0,5).map(f => f.path).join(', ')}
- Existing patterns: ${explorationResults.existing_patterns.slice(0,3).join(', ')}
- Architecture constraints: ${explorationResults.architecture_constraints.slice(0,3).join(', ')}
- Integration points: ${explorationResults.integration_points.slice(0,3).join(', ')}`
```
// Launch 3 CLI calls in parallel (single message, multiple Bash calls)
Launch 3 parallel CLI calls (`run_in_background: true` each), one per perspective:
| Perspective | Tool | PURPOSE | Key TASK bullets | EXPECTED | CONSTRAINTS |
|-------------|------|---------|-----------------|----------|-------------|
| Creative | gemini | Generate innovative ideas | Challenge assumptions, cross-domain inspiration, moonshot + practical ideas | 5+ creative ideas with novelty/impact ratings | structured mode: keep feasible |
| Pragmatic | codex | Implementation reality | Evaluate feasibility, estimate complexity, identify blockers, incremental approach | 3-5 practical approaches with effort/risk ratings | Current tech stack |
| Systematic | claude | Architectural thinking | Decompose problems, identify patterns, map dependencies, scalability | Problem decomposition, 2-3 approaches with tradeoffs | Existing architecture |
```javascript
// Each perspective uses this prompt structure (launch all 3 in parallel):
Bash({
command: `ccw cli -p "
PURPOSE: Creative brainstorming for '${idea_or_topic}' - generate innovative ideas
Success: 5+ unique creative solutions that push boundaries
PURPOSE: ${perspective} brainstorming for '${idea_or_topic}' - ${purposeFocus}
Success: ${expected}
${explorationContext}
TASK:
• Build on existing patterns - how can they be extended creatively?
• Think beyond obvious solutions - what would be surprising/delightful?
• Explore cross-domain inspiration
• Challenge assumptions - what if the opposite were true?
• Generate 'moonshot' ideas alongside practical ones
• Build on explored ${contextType} - how to ${actionVerb}?
${perspectiveSpecificBullets}
MODE: analysis
CONTEXT: @**/* | Topic: ${idea_or_topic}
EXPECTED: 5+ creative ideas with novelty/impact ratings, challenged assumptions, cross-domain inspirations
CONSTRAINTS: ${brainstormMode === 'structured' ? 'Keep ideas technically feasible' : 'No constraints - think freely'}
" --tool gemini --mode analysis`,
EXPECTED: ${expected}
CONSTRAINTS: ${constraints}
" --tool ${tool} --mode analysis`,
run_in_background: true
})
Bash({
command: `ccw cli -p "
PURPOSE: Pragmatic brainstorming for '${idea_or_topic}' - focus on implementation reality
Success: Actionable approaches with clear implementation paths
${explorationContext}
TASK:
• Build on explored codebase - how to integrate with existing patterns?
• Evaluate technical feasibility of core concept
• Identify existing patterns/libraries that could help
• Estimate implementation complexity
• Highlight potential technical blockers
• Suggest incremental implementation approach
MODE: analysis
CONTEXT: @**/* | Topic: ${idea_or_topic}
EXPECTED: 3-5 practical approaches with effort/risk ratings, dependencies, quick wins vs long-term
CONSTRAINTS: Focus on what can actually be built with current tech stack
" --tool codex --mode analysis`,
run_in_background: true
})
Bash({
command: `ccw cli -p "
PURPOSE: Systematic brainstorming for '${idea_or_topic}' - architectural thinking
Success: Well-structured solution framework with clear tradeoffs
${explorationContext}
TASK:
• Build on explored architecture - how to extend systematically?
• Decompose the problem into sub-problems
• Identify architectural patterns that apply
• Map dependencies and interactions
• Consider scalability implications
• Propose systematic solution structure
MODE: analysis
CONTEXT: @**/* | Topic: ${idea_or_topic}
EXPECTED: Problem decomposition, 2-3 architectural approaches with tradeoffs, scalability assessment
CONSTRAINTS: Consider existing system architecture
" --tool claude --mode analysis`,
run_in_background: true
})
// ⚠️ STOP POINT: Wait for hook callback to receive all results before continuing
```
3. **Aggregate Multi-Perspective Findings**
- Consolidate creative/pragmatic/systematic results
- Extract synthesis:
- Convergent themes (all agree)
- Conflicting views (need resolution)
- Unique contributions (perspective-specific insights)
- Convergent themes (all agree), conflicting views (need resolution), unique contributions
- Write to perspectives.json
4. **Update brainstorm.md**
- Append Round 2 section with multi-perspective exploration
- Include creative/pragmatic/systematic findings
- Add perspective synthesis
**CLI Prompt Template**:
- **PURPOSE**: Role brainstorming for topic - focus description
- **TASK**: Bullet list of specific actions
- **MODE**: analysis
- **CONTEXT**: @**/* | Topic + Exploration vectors + Codebase findings
- **EXPECTED**: Output format requirements
- **CONSTRAINTS**: Role-specific constraints
**Success Criteria**:
- exploration-codebase.json created with codebase context
- perspectives.json created with 3 perspective analyses
- brainstorm.md updated with Round 2 findings
- All CLI calls completed successfully
4. **Update brainstorm.md** with Round 2 multi-perspective exploration and synthesis
### Phase 3: Interactive Refinement
**Objective**: Iteratively refine ideas through user-guided exploration cycles.
**Guideline**: Delegate complex tasks to agents (cli-explore-agent, code-developer, universal-executor) or CLI calls. Avoid direct analysis/execution in main process.
**Prerequisites**:
- Phase 2 completed successfully
- perspectives.json contains initial ideas
- brainstorm.md has Round 2 findings
**Guideline**: For complex tasks (code analysis, implementation, POC creation), delegate to agents via Agent tool (cli-explore-agent, code-developer, universal-executor) or CLI calls (ccw cli). Avoid direct analysis/execution in main process.
**Workflow Steps**:
1. **Present Current State**
- Extract top ideas from perspectives.json
- Display with: title, source, brief description, novelty/feasibility ratings
- List open questions
1. **Present Current State**: Extract top ideas from perspectives.json with title, source, description, novelty/feasibility ratings
2. **Gather User Direction** (AskUserQuestion)
- **Question 1**: Which ideas to explore (multi-select from top ideas)
- **Question 2**: Next step (single-select):
- **Q1**: Which ideas to explore (multi-select from top ideas)
- **Q2**: Next step (single-select):
- **深入探索**: Deep dive on selected ideas
- **继续发散**: Generate more ideas
- **挑战验证**: Devil's advocate challenge
@@ -430,44 +278,14 @@ CONSTRAINTS: Consider existing system architecture
3. **Execute User-Selected Action**
**Deep Dive** (per selected idea):
- Launch Gemini CLI with analysis mode
- Tasks: Elaborate concept, implementation requirements, challenges, POC approach, metrics, dependencies
- Output: `{sessionFolder}/ideas/{idea-slug}.md`
| Action | Tool | Output | Key Tasks |
|--------|------|--------|-----------|
| Deep Dive | Gemini CLI | ideas/{slug}.md | Elaborate concept, requirements, challenges, POC approach, metrics, dependencies |
| Generate More | Selected CLI | Updated perspectives.json | New angles from unexplored vectors |
| Challenge | Codex CLI | Challenge results | 3 objections per idea, challenge assumptions, failure scenarios, survivability (1-5) |
| Merge | Gemini CLI | ideas/merged-{slug}.md | Complementary elements, resolve contradictions, unified concept |
**Generate More Ideas**:
- Launch CLI with new angles from unexplored vectors
- Add results to perspectives.json
**Devil's Advocate Challenge**:
- Launch Codex CLI with analysis mode
- Tasks: Identify objections, challenge assumptions, failure scenarios, alternatives, survivability rating
- Return challenge results for idea strengthening
**Merge Ideas**:
- Launch Gemini CLI with analysis mode
- Tasks: Identify complementary elements, resolve contradictions, create unified concept
- Add merged idea to perspectives.json
4. **Update brainstorm.md**
- Append Round N section with findings
- Document user direction and action results
5. **Repeat or Converge**
- Continue loop (max 6 rounds) or exit to Phase 4
**Refinement Actions**:
| Action | Tool | Output | Description |
|--------|------|--------|-------------|
| Deep Dive | Gemini CLI | ideas/{slug}.md | Comprehensive idea analysis |
| Generate More | Selected CLI | Updated perspectives.json | Additional idea generation |
| Challenge | Codex CLI | Challenge results | Critical weaknesses exposed |
| Merge | Gemini CLI | Merged idea | Synthesized concept |
**CLI Call Examples for Refinement Actions**:
**1. Deep Dive on Selected Idea**:
**Deep Dive CLI Call**:
```javascript
Bash({
command: `ccw cli -p "
@@ -483,27 +301,18 @@ TASK:
• Map related/dependent features
MODE: analysis
CONTEXT: @**/*
Original idea: ${idea.description}
Source perspective: ${idea.source}
User interest reason: ${idea.userReason || 'Selected for exploration'}
EXPECTED:
- Detailed concept description
- Technical requirements list
- Risk/challenge matrix
- MVP definition
- Success criteria
- Recommendation: pursue/pivot/park
EXPECTED: Detailed concept, technical requirements, risk matrix, MVP definition, success criteria, recommendation (pursue/pivot/park)
CONSTRAINTS: Focus on actionability
" --tool gemini --mode analysis`,
run_in_background: false
})
```
**2. Devil's Advocate Challenge**:
**Devil's Advocate CLI Call**:
```javascript
Bash({
command: `ccw cli -p "
@@ -518,25 +327,17 @@ TASK:
• Challenge core assumptions
• Identify scenarios where this fails
• Consider competitive/alternative solutions
• Assess whether this solves the right problem
• Rate survivability after challenge (1-5)
MODE: analysis
EXPECTED:
- Per-idea challenge report
- Critical weaknesses exposed
- Counter-arguments to objections (if any)
- Ideas that survive the challenge
- Modified/strengthened versions
EXPECTED: Per-idea challenge report, critical weaknesses, survivability ratings, modified/strengthened versions
CONSTRAINTS: Be genuinely critical, not just contrarian
" --tool codex --mode analysis`,
run_in_background: false
})
```
**3. Merge Multiple Ideas**:
**Merge Ideas CLI Call**:
```javascript
Bash({
command: `ccw cli -p "
@@ -553,93 +354,81 @@ ${i+1}. ${idea.title} (${idea.source})
TASK:
• Identify complementary elements
• Resolve contradictions
• Create unified concept
• Preserve key strengths from each
• Describe the merged solution
• Create unified concept preserving key strengths
• Assess viability of merged idea
MODE: analysis
EXPECTED:
- Merged concept description
- Elements taken from each source idea
- Contradictions resolved (or noted as tradeoffs)
- New combined strengths
- Implementation considerations
EXPECTED: Merged concept, elements from each source, contradictions resolved, implementation considerations
CONSTRAINTS: Don't force incompatible ideas together
" --tool gemini --mode analysis`,
run_in_background: false
})
```
**Success Criteria**:
- User-selected ideas processed
- brainstorm.md updated with all refinement rounds
- ideas/ folder contains deep-dive documents for selected ideas
- Exit condition reached (user selects "准备收敛" or max rounds)
4. **Update brainstorm.md** with Round N findings
5. **Repeat or Converge**: Continue loop (max 6 rounds) or exit to Phase 4
**TodoWrite**: Update `phase-2``"completed"` (after first round enters Phase 3), `phase-3``"in_progress"`
**TodoWrite** (on exit loop): Update `phase-3``"completed"`, `phase-4``"in_progress"`
### Phase 4: Convergence & Crystallization
**Objective**: Synthesize final ideas, generate conclusions, offer next steps.
**Prerequisites**:
- Phase 3 completed successfully
- Multiple rounds of refinement documented
- User ready to converge
**Workflow Steps**:
1. **Generate Final Synthesis**
- Consolidate all ideas from perspectives.json and refinement rounds
- **Top ideas**: Filter active ideas, sort by score, take top 5
- Include: title, description, source_perspective, score, novelty, feasibility, strengths, challenges, next_steps
- **Parked ideas**: Ideas marked as parked with reason and future trigger
1. **Generate Final Synthesis** → Write to synthesis.json
- **Top ideas**: Filter active, sort by score, top 5 with title, description, source_perspective, score, novelty, feasibility, strengths, challenges, next_steps
- **Parked ideas**: With reason and future trigger
- **Key insights**: Process discoveries, challenged assumptions, unexpected connections
- **Recommendations**: Primary recommendation, alternatives, not recommended
- **Recommendations**: Primary, alternatives, not recommended
- **Follow-up**: Implementation/research/validation summaries
- Write to synthesis.json
2. **Final brainstorm.md Update**
- Append synthesis & conclusions section
- **Executive summary**: High-level overview
- **Top ideas**: Ranked with descriptions, strengths, challenges, next steps
- **Primary recommendation**: Best path forward with rationale
- **Alternative approaches**: Other viable options with tradeoffs
- **Parked ideas**: Future considerations
- **Key insights**: Learnings from the process
- **Session statistics**: Rounds, ideas generated/survived, duration
**synthesis.json Schema**: `session_id`, `topic`, `completed` (timestamp), `total_rounds`, `top_ideas[]`, `parked_ideas[]`, `key_insights[]`, `recommendations` (primary/alternatives/not_recommended), `follow_up[]`
3. **Post-Completion Options** (AskUserQuestion)
- **创建实施计划**: Launch workflow-plan with top idea
- **创建Issue**: Launch issue-discover for top 3 ideas
- **深入分析**: Launch workflow:analyze-with-file for top idea
- **导出分享**: Generate shareable report
- **完成**: No further action
2. **Final brainstorm.md Update**: Executive summary, top ideas ranked, primary recommendation with rationale, alternative approaches, parked ideas, key insights, session statistics (rounds, ideas generated/survived, duration)
**synthesis.json Schema**:
- `session_id`: Session identifier
- `topic`: Original idea/topic
- `completed`: Completion timestamp
- `total_rounds`: Number of refinement rounds
- `top_ideas[]`: Top 5 ranked ideas
- `parked_ideas[]`: Ideas parked for future
- `key_insights[]`: Process learnings
- `recommendations`: Primary/alternatives/not_recommended
- `follow_up[]`: Next step summaries
3. **MANDATORY GATE: Next Step Selection** — workflow MUST NOT end without executing this step.
**Success Criteria**:
- synthesis.json created with final synthesis
- brainstorm.md finalized with conclusions
- User offered next step options
- Session complete
**TodoWrite**: Update `phase-4``"completed"`, `next-step``"in_progress"`
> **CRITICAL**: This AskUserQuestion is a **terminal gate**. The workflow is INCOMPLETE if this question is not asked. After displaying synthesis (step 2), you MUST immediately proceed here.
Call AskUserQuestion (single-select, header: "Next Step"):
- **创建实施计划** (Recommended if top idea has high feasibility): "基于最佳创意启动 workflow-plan 制定实施计划"
- **创建Issue**: "将 Top 3 创意转化为 issue 进行跟踪管理"
- **深入分析**: "对最佳创意启动 analyze-with-file 深入技术分析"
- **完成**: "头脑风暴已足够,无需进一步操作"
**Handle user selection**:
**"创建实施计划"** → MUST invoke Skill tool:
1. Build `taskDescription` from top idea in synthesis.json (title + description + next_steps)
2. Assemble context: `## Prior Brainstorm ({sessionId})` + summary + top idea details + key insights (up to 5)
3. **Invoke Skill tool immediately**:
```javascript
Skill({ skill: "workflow-plan", args: `${taskDescription}\n\n${contextLines}` })
```
If Skill invocation is omitted, the workflow is BROKEN.
4. After Skill invocation, brainstorm-with-file is complete
**"创建Issue"** → Convert top ideas to issues:
1. For each idea in synthesis.top_ideas (top 3):
- Build issue JSON: `{title: idea.title, context: idea.description + '\n' + idea.next_steps.join('\n'), priority: idea.score >= 8 ? 2 : 3, source: 'brainstorm', labels: dimensions}`
- Create via: `Skill({ skill: "issue:from-brainstorm", args: "${sessionFolder}/synthesis.json" })`
2. Display created issue IDs
**"深入分析"** → Launch analysis on top idea:
1. Build analysis topic from top idea title + description
2. **Invoke Skill tool immediately**:
```javascript
Skill({ skill: "workflow:analyze-with-file", args: `${topIdea.title}: ${topIdea.description}` })
```
**"完成"** → No further action needed.
**TodoWrite**: Update `next-step` → `"completed"` after user selection is handled
## Configuration
### Brainstorm Dimensions
Dimensions matched against topic keywords to identify focus areas:
| Dimension | Keywords |
|-----------|----------|
| technical | 技术, technical, implementation, code, 实现, architecture |
@@ -652,7 +441,7 @@ Dimensions matched against topic keywords to identify focus areas:
### Role Selection
**Professional Roles** (recommended based on topic keywords):
**Professional Roles**:
| Role | CLI Tool | Focus Area | Keywords |
|------|----------|------------|----------|
@@ -668,47 +457,13 @@ Dimensions matched against topic keywords to identify focus areas:
**Simple Perspectives** (fallback):
| Perspective | CLI Tool | Focus | Best For |
|-------------|----------|-------|----------|
| creative | Gemini | Innovation, cross-domain | Generating novel ideas |
| pragmatic | Codex | Implementation, feasibility | Reality-checking ideas |
| systematic | Claude | Architecture, structure | Organizing solutions |
| Perspective | CLI Tool | Focus |
|-------------|----------|-------|
| creative | Gemini | Innovation, cross-domain |
| pragmatic | Codex | Implementation, feasibility |
| systematic | Claude | Architecture, structure |
**Selection Strategy**:
1. **Auto mode** (`-y`): Choose top 3 recommended professional roles
2. **Manual mode**: Present recommended roles + "Use simple perspectives" option
3. **Continue mode**: Use roles from previous session
### Collaboration Patterns
| Pattern | Usage | Description |
|---------|-------|-------------|
| Parallel Divergence | New topic | All roles explore simultaneously from different angles |
| Sequential Deep-Dive | Promising idea | One role expands, others critique/refine |
| Debate Mode | Controversial approach | Roles argue for/against approaches |
| Synthesis Mode | Ready to decide | Combine insights into actionable conclusion |
### Context Overflow Protection
**Per-Role Limits**:
- Main analysis output: < 3000 words
- Sub-document (if any): < 2000 words each
- Maximum sub-documents: 5 per role
**Synthesis Protection**:
- If total analysis > 100KB, synthesis reads only main analysis files (not sub-documents)
- Large ideas automatically split into separate idea documents in ideas/ folder
**Recovery Steps**:
1. Check CLI logs for context overflow errors
2. Reduce scope: fewer roles or simpler topic
3. Use `--mode structured` for more focused output
4. Split complex topics into multiple sessions
**Prevention**:
- Start with 3 roles (default), increase if needed
- Use structured topic format: "GOAL: ... SCOPE: ... CONTEXT: ..."
- Review output sizes before final synthesis
**Selection Strategy**: Auto mode → top 3 professional roles | Manual mode → recommended roles + "Use simple perspectives" option | Continue mode → roles from previous session
## Error Handling
@@ -722,58 +477,6 @@ Dimensions matched against topic keywords to identify focus areas:
| Max rounds reached | Force synthesis, highlight unresolved questions |
| All ideas fail challenge | Return to divergent phase with new constraints |
## Best Practices
1. **Clear Topic Definition**: Detailed topics → better role selection and exploration
2. **Agent-First for Complex Tasks**: For code analysis, POC implementation, or technical validation during refinement, delegate to agents via Agent tool (cli-explore-agent, code-developer, universal-executor) or CLI calls (ccw cli). Avoid direct analysis/execution in main process
3. **Review brainstorm.md**: Check thought evolution before final decisions
4. **Embrace Conflicts**: Perspective conflicts often reveal important tradeoffs
5. **Document Evolution**: brainstorm.md captures full thinking process for team review
6. **Use Continue Mode**: Resume sessions to build on previous exploration
## Templates
### Brainstorm Document Structure
**brainstorm.md** contains:
- **Header**: Session metadata (ID, topic, started, mode, dimensions)
- **Initial Context**: User focus, depth, constraints
- **Seed Expansion**: Original idea + exploration vectors
- **Thought Evolution Timeline**: Round-by-round findings
- Round 1: Seed Understanding
- Round 2: Multi-Perspective Exploration (creative/pragmatic/systematic)
- Round 3-N: Interactive Refinement (deep-dive/challenge/merge)
- **Synthesis & Conclusions**: Executive summary, top ideas, recommendations
- **Session Statistics**: Rounds, ideas, duration, artifacts
See full markdown template in original file (lines 955-1161).
## Usage Recommendations (Requires User Confirmation)
**Use `Skill(skill="brainstorm", args="\"topic or question\"")` when:**
- Starting a new feature/product without clear direction
- Facing a complex problem with multiple possible solutions
- Need to explore alternatives before committing
- Want documented thinking process for team review
- Combining multiple stakeholder perspectives
**Use `Skill(skill="workflow:analyze-with-file", args="\"topic\"")` when:**
- Investigating existing code/system
- Need factual analysis over ideation
- Debugging or troubleshooting
- Understanding current state
**Use `Skill(skill="workflow-plan", args="\"task description\"")` when:**
- Complex planning requiring multiple perspectives
- Large scope needing parallel sub-domain analysis
- Want shared collaborative planning document
- Need structured task breakdown with agent coordination
**Use `Skill(skill="workflow-lite-planex", args="\"task description\"")` when:**
- Direction is already clear
- Ready to move from ideas to execution
- Need simple implementation breakdown
---
**Now execute brainstorm-with-file for**: $ARGUMENTS

View File

@@ -587,7 +587,11 @@ Schema (tasks): ~/.ccw/workflows/cli-templates/schemas/task-schema.json
- Execution command
- Conflict status
6. **Update Todo**
6. **Sync Session State**
- Execute: `/workflow:session:sync -y "Plan complete: ${subDomains.length} domains, ${allTasks.length} tasks"`
- Updates specs/*.md with planning insights and project-tech.json with planning session entry
7. **Update Todo**
- Set Phase 4 status to `completed`
**plan.md Structure**:

View File

@@ -651,6 +651,6 @@ if (autoYes) {
| Empty debug.log | Verify reproduction triggered the code path |
| All hypotheses rejected | Use Gemini to generate new hypotheses based on disproven assumptions |
| Fix doesn't work | Document failed fix attempt, iterate with refined understanding |
| >5 iterations | Review consolidated understanding, escalate to `workflow-lite-planex` skill with full context |
| >5 iterations | Review consolidated understanding, escalate to `workflow-lite-plan` skill with full context |
| Gemini unavailable | Fallback to manual hypothesis generation, document without Gemini insights |
| Understanding too long | Consolidate aggressively, archive old iterations to separate file |

View File

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

View File

@@ -1,291 +0,0 @@
---
name: init
description: Initialize project-level state with intelligent project analysis using cli-explore-agent
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 `.ccw/specs/*.md` with comprehensive project understanding by delegating analysis to **cli-explore-agent**.
**Dual File System**:
- `project-tech.json`: Auto-generated technical analysis (stack, architecture, components)
- `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.
## Usage
```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 --skip-specs flag → skipSpecs = true | false
Decision:
├─ BOTH_EXIST + no --regenerate → Exit: "Already initialized"
├─ EXISTS + --regenerate → Backup existing → Continue analysis
└─ NOT_FOUND → Continue analysis
Analysis Flow:
├─ Get project metadata (name, root)
├─ Invoke cli-explore-agent
│ ├─ Structural scan (get_modules_by_depth.sh, find, wc)
│ ├─ Semantic analysis (Gemini CLI)
│ ├─ Synthesis and merge
│ └─ Write .workflow/project-tech.json
├─ 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)
└─ .ccw/specs/*.md (scaffold or configured, unless --skip-specs)
```
## Implementation
### Step 1: Parse Input and Check Existing State
**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 .ccw/specs/coding-conventions.md && echo "SPECS_EXISTS" || echo "SPECS_NOT_FOUND")
```
**If BOTH_EXIST and no --regenerate**: Exit early
```
Project already initialized:
- Tech analysis: .workflow/project-tech.json
- Guidelines: .ccw/specs/*.md
Use /workflow:init --regenerate to rebuild tech analysis
Use /workflow:session:solidify to add guidelines
Use /workflow:status --project to view state
```
### Step 2: Get Project Metadata
```bash
bash(basename "$(git rev-parse --show-toplevel 2>/dev/null || pwd)")
bash(git rev-parse --show-toplevel 2>/dev/null || pwd)
bash(mkdir -p .workflow)
```
### Step 3: Invoke cli-explore-agent
**For --regenerate**: Backup and preserve existing data
```bash
bash(cp .workflow/project-tech.json .workflow/project-tech.json.backup)
```
**Delegate analysis to agent**:
```javascript
Task(
subagent_type="cli-explore-agent",
run_in_background=false,
description="Deep project analysis",
prompt=`
Analyze project for workflow initialization and generate .workflow/project-tech.json.
## MANDATORY FIRST STEPS
1. Execute: cat ~/.ccw/workflows/cli-templates/schemas/project-tech-schema.json (get schema reference)
2. Execute: ccw tool exec get_modules_by_depth '{}' (get project structure)
## Task
Generate complete project-tech.json following the schema structure:
- project_name: "${projectName}"
- initialized_at: ISO 8601 timestamp
- overview: {
description: "Brief project description",
technology_stack: {
languages: [{name, file_count, primary}],
frameworks: ["string"],
build_tools: ["string"],
test_frameworks: ["string"]
},
architecture: {style, layers: [], patterns: []},
key_components: [{name, path, description, importance}]
}
- features: []
- development_index: ${regenerate ? 'preserve from backup' : '{feature: [], enhancement: [], bugfix: [], refactor: [], docs: []}'}
- statistics: ${regenerate ? 'preserve from backup' : '{total_features: 0, total_sessions: 0, last_updated: ISO timestamp}'}
- _metadata: {initialized_by: "cli-explore-agent", analysis_timestamp: ISO timestamp, analysis_mode: "deep-scan"}
## Analysis Requirements
**Technology Stack**:
- Languages: File counts, mark primary
- Frameworks: From package.json, requirements.txt, go.mod, etc.
- Build tools: npm, cargo, maven, webpack, vite
- Test frameworks: jest, pytest, go test, junit
**Architecture**:
- Style: MVC, microservices, layered (from structure & imports)
- Layers: presentation, business-logic, data-access
- Patterns: singleton, factory, repository
- Key components: 5-10 modules {name, path, description, importance}
## Execution
1. Structural scan: get_modules_by_depth.sh, find, wc -l
2. Semantic analysis: Gemini for patterns/architecture
3. Synthesis: Merge findings
4. ${regenerate ? 'Merge with preserved development_index and statistics from .workflow/project-tech.json.backup' : ''}
5. Write JSON: Write('.workflow/project-tech.json', jsonContent)
6. Report: Return brief completion summary
Project root: ${projectRoot}
`
)
```
### Step 3.5: Initialize Spec System (if not --skip-specs)
```javascript
// Skip spec initialization if --skip-specs flag is provided
if (!skipSpecs) {
// Initialize spec system if not already initialized
const specsCheck = Bash('test -f .ccw/specs/coding-conventions.md && echo EXISTS || echo NOT_FOUND')
if (specsCheck.includes('NOT_FOUND')) {
console.log('Initializing spec system...')
Bash('ccw spec init')
Bash('ccw spec rebuild')
}
} else {
console.log('Skipping spec initialization (--skip-specs)')
}
```
### Step 4: Display Summary
```javascript
const projectTech = JSON.parse(Read('.workflow/project-tech.json'));
const specsInitialized = !skipSpecs && file_exists('.ccw/specs/coding-conventions.md');
console.log(`
Project initialized successfully
## Project Overview
Name: ${projectTech.project_name}
Description: ${projectTech.overview.description}
### Technology Stack
Languages: ${projectTech.overview.technology_stack.languages.map(l => l.name).join(', ')}
Frameworks: ${projectTech.overview.technology_stack.frameworks.join(', ')}
### Architecture
Style: ${projectTech.overview.architecture.style}
Components: ${projectTech.overview.key_components.length} core modules
---
Files created:
- Tech analysis: .workflow/project-tech.json
${!skipSpecs ? `- Specs: .ccw/specs/ ${specsInitialized ? '(initialized)' : ''}` : '- Specs: (skipped via --skip-specs)'}
${regenerate ? '- Backup: .workflow/project-tech.json.backup' : ''}
`);
```
### 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. Skip this step if `--skip-specs` was provided.
```javascript
// 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;
}
// 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 specs now? The wizard will ask targeted questions based on your tech stack.",
header: "Specs",
multiSelect: false,
options: [
{
label: "Configure now (Recommended)",
description: "Interactive wizard to set up coding conventions, constraints, and quality rules"
},
{
label: "Skip for now",
description: "You can run /workflow:init-guidelines later or use ccw spec load to import specs"
}
]
}]
});
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-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(`
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
`);
}
```
## Error Handling
**Agent Failure**: Fall back to basic initialization with placeholder overview
**Missing Tools**: Agent uses Qwen fallback or bash-only
**Empty Project**: Create minimal JSON with all gaps identified
## 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
- `/workflow:status --project` - View project state and guidelines

View File

@@ -806,6 +806,10 @@ AskUserQuestion({
})
```
4. **Sync Session State** (automatic)
- Execute: `/workflow:session:sync -y "Integration test cycle complete: ${passRate}% pass rate, ${iterations} iterations"`
- Updates specs/*.md with test learnings and project-tech.json with development index entry
---
## Completion Conditions

View File

@@ -827,7 +827,7 @@ AskUserQuestion({
- Need regression-safe iterative refactoring with rollback
- Want documented reasoning for each refactoring decision
**Use `workflow-lite-planex` skill when:**
**Use `workflow-lite-plan` skill when:**
- Single specific bug or issue to fix
- No systematic debt analysis needed

View File

@@ -534,10 +534,10 @@ ${selectedMode === 'progressive' ? `**Progressive Mode**:
| Scenario | Recommended Command |
|----------|-------------------|
| Strategic planning, need issue tracking | `/workflow:roadmap-with-file` |
| Quick task breakdown, immediate execution | `/workflow-lite-planex` |
| 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-planex` (Phase 1: plan → Phase 2: execute) |
| Code implementation from existing plan | `/workflow-lite-plan` (Phase 1: plan → Phase 2: execute) |
---

View File

@@ -1,440 +0,0 @@
---
name: solidify
description: Crystallize session learnings and user-defined constraints into permanent project guidelines, or compress recent memories
argument-hint: "[-y|--yes] [--type <convention|constraint|learning|compress>] [--category <category>] [--limit <N>] \"rule or insight\""
examples:
- /workflow:session:solidify "Use functional components for all React code" --type convention
- /workflow:session:solidify -y "No direct DB access from controllers" --type constraint --category architecture
- /workflow:session:solidify "Cache invalidation requires event sourcing" --type learning --category architecture
- /workflow:session:solidify --interactive
- /workflow:session:solidify --type compress --limit 10
---
## Auto Mode
When `--yes` or `-y`: Auto-categorize and add guideline without confirmation.
# Session Solidify Command (/workflow:session:solidify)
## Overview
Crystallizes ephemeral session context (insights, decisions, constraints) into permanent project guidelines stored in `.ccw/specs/*.md`. This ensures valuable learnings persist across sessions and inform future planning.
## Use Cases
1. **During Session**: Capture important decisions as they're made
2. **After Session**: Reflect on lessons learned before archiving
3. **Proactive**: Add team conventions or architectural rules
## Parameters
| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| `rule` | string | Yes (unless --interactive or --type compress) | The rule, convention, or insight to solidify |
| `--type` | enum | No | Type: `convention`, `constraint`, `learning`, `compress` (default: auto-detect) |
| `--category` | string | No | Category for organization (see categories below) |
| `--interactive` | flag | No | Launch guided wizard for adding rules |
| `--limit` | number | No | Number of recent memories to compress (default: 20, only for --type compress) |
### Type Categories
**convention** → Coding style preferences (goes to `conventions` section)
- Subcategories: `coding_style`, `naming_patterns`, `file_structure`, `documentation`
**constraint** → Hard rules that must not be violated (goes to `constraints` section)
- Subcategories: `architecture`, `tech_stack`, `performance`, `security`
**learning** -> Session-specific insights (goes to `learnings` array)
- Subcategories: `architecture`, `performance`, `security`, `testing`, `process`, `other`
**compress** -> Compress/deduplicate recent memories into a single consolidated CMEM
- No subcategories (operates on core memories, not project guidelines)
- Fetches recent non-archived memories, LLM-compresses them, creates a new CMEM
- Source memories are archived after successful compression
## Execution Process
```
Input Parsing:
|- Parse: rule text (required unless --interactive or --type compress)
|- Parse: --type (convention|constraint|learning|compress)
|- Parse: --category (subcategory)
|- Parse: --interactive (flag)
+- Parse: --limit (number, default 20, compress only)
IF --type compress:
Step C1: Fetch Recent Memories
+- Call getRecentMemories(limit, excludeArchived=true)
Step C2: Validate Candidates
+- If fewer than 2 memories found -> abort with message
Step C3: LLM Compress
+- Build compression prompt with all memory contents
+- Send to LLM for consolidation
+- Receive compressed text
Step C4: Merge Tags
+- Collect tags from all source memories
+- Deduplicate into a single merged tag array
Step C5: Create Compressed CMEM
+- Generate new CMEM via upsertMemory with:
- content: compressed text from LLM
- summary: auto-generated
- tags: merged deduplicated tags
- metadata: buildCompressionMetadata(sourceIds, originalSize, compressedSize)
Step C6: Archive Source Memories
+- Call archiveMemories(sourceIds)
Step C7: Display Compression Report
+- Show source count, compression ratio, new CMEM ID
ELSE (convention/constraint/learning):
Step 1: Ensure Guidelines File Exists
+- If not exists -> Create with empty structure
Step 2: Auto-detect Type (if not specified)
+- Analyze rule text for keywords
Step 3: Validate and Format Entry
+- Build entry object based on type
Step 4: Update Guidelines File
+- Add entry to appropriate section
Step 5: Display Confirmation
+- Show what was added and where
```
## Implementation
### Step 1: Ensure Guidelines File Exists
**Uses .ccw/specs/ directory (same as frontend/backend spec-index-builder)**
```bash
bash(test -f .ccw/specs/coding-conventions.md && echo "EXISTS" || echo "NOT_FOUND")
```
**If NOT_FOUND**, initialize spec system:
```bash
Bash('ccw spec init')
Bash('ccw spec rebuild')
```
### Step 2: Auto-detect Type (if not specified)
```javascript
function detectType(ruleText) {
const text = ruleText.toLowerCase();
// Constraint indicators
if (/\b(no|never|must not|forbidden|prohibited|always must)\b/.test(text)) {
return 'constraint';
}
// Learning indicators
if (/\b(learned|discovered|realized|found that|turns out)\b/.test(text)) {
return 'learning';
}
// Default to convention
return 'convention';
}
function detectCategory(ruleText, type) {
const text = ruleText.toLowerCase();
if (type === 'constraint' || type === 'learning') {
if (/\b(architecture|layer|module|dependency|circular)\b/.test(text)) return 'architecture';
if (/\b(security|auth|permission|sanitize|xss|sql)\b/.test(text)) return 'security';
if (/\b(performance|cache|lazy|async|sync|slow)\b/.test(text)) return 'performance';
if (/\b(test|coverage|mock|stub)\b/.test(text)) return 'testing';
}
if (type === 'convention') {
if (/\b(name|naming|prefix|suffix|camel|pascal)\b/.test(text)) return 'naming_patterns';
if (/\b(file|folder|directory|structure|organize)\b/.test(text)) return 'file_structure';
if (/\b(doc|comment|jsdoc|readme)\b/.test(text)) return 'documentation';
return 'coding_style';
}
return type === 'constraint' ? 'tech_stack' : 'other';
}
```
### Step 3: Build Entry
```javascript
function buildEntry(rule, type, category, sessionId) {
if (type === 'learning') {
return {
date: new Date().toISOString().split('T')[0],
session_id: sessionId || null,
insight: rule,
category: category,
context: null
};
}
// For conventions and constraints, just return the rule string
return rule;
}
```
### Step 4: Update Spec Files
```javascript
// Map type+category to target spec file
// Uses .ccw/specs/ directory (same as frontend/backend spec-index-builder)
const specFileMap = {
convention: '.ccw/specs/coding-conventions.md',
constraint: '.ccw/specs/architecture-constraints.md'
}
if (type === 'convention' || type === 'constraint') {
const targetFile = specFileMap[type]
const existing = Read(targetFile)
// Deduplicate: skip if rule text already exists in the file
if (!existing.includes(rule)) {
const ruleText = `- [${category}] ${rule}`
const newContent = existing.trimEnd() + '\n' + ruleText + '\n'
Write(targetFile, newContent)
}
} else if (type === 'learning') {
// Learnings go to coding-conventions.md as a special section
// Uses .ccw/specs/ directory (same as frontend/backend spec-index-builder)
const targetFile = '.ccw/specs/coding-conventions.md'
const existing = Read(targetFile)
const entry = buildEntry(rule, type, category, sessionId)
const learningText = `- [learning/${category}] ${entry.insight} (${entry.date})`
if (!existing.includes(entry.insight)) {
const newContent = existing.trimEnd() + '\n' + learningText + '\n'
Write(targetFile, newContent)
}
}
// Rebuild spec index after modification
Bash('ccw spec rebuild')
```
### Step 5: Display Confirmation
```
Guideline solidified
Type: ${type}
Category: ${category}
Rule: "${rule}"
Location: .ccw/specs/*.md -> ${type}s.${category}
Total ${type}s in ${category}: ${count}
```
## Compress Mode (--type compress)
When `--type compress` is specified, the command operates on core memories instead of project guidelines. It fetches recent memories, sends them to an LLM for consolidation, and creates a new compressed CMEM.
### Step C1: Fetch Recent Memories
```javascript
// Uses CoreMemoryStore.getRecentMemories()
const limit = parsedArgs.limit || 20;
const recentMemories = store.getRecentMemories(limit, /* excludeArchived */ true);
if (recentMemories.length < 2) {
console.log("Not enough non-archived memories to compress (need at least 2).");
return;
}
```
### Step C2: Build Compression Prompt
Concatenate all memory contents and send to LLM with the following prompt:
```
Given these ${N} memories, produce a single consolidated memory that:
1. Preserves all key information and insights
2. Removes redundancy and duplicate concepts
3. Organizes content by theme/topic
4. Maintains specific technical details and decisions
Source memories:
---
[Memory CMEM-XXXXXXXX-XXXXXX]:
${memory.content}
---
[Memory CMEM-XXXXXXXX-XXXXXX]:
${memory.content}
---
...
Output: A single comprehensive memory text.
```
### Step C3: Merge Tags from Source Memories
```javascript
// Collect all tags from source memories and deduplicate
const allTags = new Set();
for (const memory of recentMemories) {
if (memory.tags) {
for (const tag of memory.tags) {
allTags.add(tag);
}
}
}
const mergedTags = Array.from(allTags);
```
### Step C4: Create Compressed CMEM
```javascript
const sourceIds = recentMemories.map(m => m.id);
const originalSize = recentMemories.reduce((sum, m) => sum + m.content.length, 0);
const compressedSize = compressedText.length;
const metadata = store.buildCompressionMetadata(sourceIds, originalSize, compressedSize);
const newMemory = store.upsertMemory({
content: compressedText,
summary: `Compressed from ${sourceIds.length} memories`,
tags: mergedTags,
metadata: metadata
});
```
### Step C5: Archive Source Memories
```javascript
// Archive all source memories after successful compression
store.archiveMemories(sourceIds);
```
### Step C6: Display Compression Report
```
Memory compression complete
New CMEM: ${newMemory.id}
Sources compressed: ${sourceIds.length}
Original size: ${originalSize} chars
Compressed size: ${compressedSize} chars
Compression ratio: ${(compressedSize / originalSize * 100).toFixed(1)}%
Tags merged: ${mergedTags.join(', ') || '(none)'}
Source memories archived: ${sourceIds.join(', ')}
```
### Compressed CMEM Metadata Format
The compressed CMEM's `metadata` field contains a JSON string with:
```json
{
"compressed_from": ["CMEM-20260101-120000", "CMEM-20260102-140000", "..."],
"compression_ratio": 0.45,
"compressed_at": "2026-02-23T10:30:00.000Z"
}
```
- `compressed_from`: Array of source memory IDs that were consolidated
- `compression_ratio`: Ratio of compressed size to original size (lower = more compression)
- `compressed_at`: ISO timestamp of when the compression occurred
## Interactive Mode
When `--interactive` flag is provided:
```javascript
AskUserQuestion({
questions: [
{
question: "What type of guideline are you adding?",
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 from this session (e.g., cache invalidation needs events)" }
]
}
]
});
// Follow-up based on type selection...
```
## Examples
### Add a Convention
```bash
/workflow:session:solidify "Use async/await instead of callbacks" --type convention --category coding_style
```
Result in `.ccw/specs/coding-conventions.md`:
```markdown
- [coding_style] Use async/await instead of callbacks
```
### Add an Architectural Constraint
```bash
/workflow:session:solidify "No direct DB access from controllers" --type constraint --category architecture
```
Result in `.ccw/specs/architecture-constraints.md`:
```markdown
- [architecture] No direct DB access from controllers
```
### Capture a Session Learning
```bash
/workflow:session:solidify "Cache invalidation requires event sourcing for consistency" --type learning
```
Result in `.ccw/specs/coding-conventions.md`:
```markdown
- [learning/architecture] Cache invalidation requires event sourcing for consistency (2024-12-28)
```
### Compress Recent Memories
```bash
/workflow:session:solidify --type compress --limit 10
```
Result: Creates a new CMEM with consolidated content from the 10 most recent non-archived memories. Source memories are archived. The new CMEM's metadata tracks which memories were compressed:
```json
{
"compressed_from": ["CMEM-20260220-100000", "CMEM-20260221-143000", "..."],
"compression_ratio": 0.42,
"compressed_at": "2026-02-23T10:30:00.000Z"
}
```
## Integration with Planning
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
3. **`task-generate-agent`**: Includes guidelines as "CRITICAL CONSTRAINTS" in system prompt
This ensures all future planning respects solidified rules without users needing to re-state them.
## Error Handling
- **Duplicate Rule**: Warn and skip if exact rule already exists
- **Invalid Category**: Suggest valid categories for the type
- **File Corruption**: Backup existing file before modification
## Related Commands
- `/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 specs/*.md scaffold if missing
- `/workflow:init-specs` - Interactive wizard to create individual specs with scope selection

View File

@@ -38,7 +38,7 @@ ERROR: Invalid session type. Valid types: workflow, review, tdd, test, docs
## Step 0: Initialize Project State (First-time Only)
**Executed before all modes** - Ensures project-level state files exist by calling `/workflow:init`.
**Executed before all modes** - Ensures project-level state files exist by calling `/workflow:spec:setup`.
### Check and Initialize
```bash
@@ -47,10 +47,10 @@ bash(test -f .workflow/project-tech.json && echo "TECH_EXISTS" || echo "TECH_NOT
bash(test -f .ccw/specs/*.md && echo "GUIDELINES_EXISTS" || echo "GUIDELINES_NOT_FOUND")
```
**If either NOT_FOUND**, delegate to `/workflow:init`:
**If either NOT_FOUND**, delegate to `/workflow:spec:setup`:
```javascript
// Call workflow:init for intelligent project analysis
Skill(skill="workflow:init");
// Call workflow:spec:setup for intelligent project analysis
Skill(skill="workflow:spec:setup");
// Wait for init completion
// project-tech.json and specs/*.md will be created
@@ -58,11 +58,11 @@ Skill(skill="workflow:init");
**Output**:
- If BOTH_EXIST: `PROJECT_STATE: initialized`
- If NOT_FOUND: Calls `/workflow:init` → creates:
- If NOT_FOUND: Calls `/workflow:spec:setup` → creates:
- `.workflow/project-tech.json` with full technical analysis
- `.ccw/specs/*.md` with empty scaffold
**Note**: `/workflow:init` uses cli-explore-agent to build comprehensive project understanding (technology stack, architecture, key components). This step runs once per project. Subsequent executions skip initialization.
**Note**: `/workflow:spec:setup` uses cli-explore-agent to build comprehensive project understanding (technology stack, architecture, key components). This step runs once per project. Subsequent executions skip initialization.
## Mode 1: Discovery Mode (Default)

View File

@@ -190,13 +190,12 @@ Write(techPath, JSON.stringify(tech, null, 2))
| Error | Resolution |
|-------|------------|
| File missing | Create scaffold (same as solidify Step 1) |
| File missing | Create scaffold (same as spec:setup Step 4) |
| 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
- `/workflow:spec:setup` - Initialize project with specs scaffold
- `/workflow:spec:add` - Interactive wizard to create individual specs with scope selection

View File

@@ -0,0 +1,644 @@
---
name: add
description: Add specs, conventions, constraints, or learnings to project guidelines interactively or automatically
argument-hint: "[-y|--yes] [--type <convention|constraint|learning>] [--category <category>] [--dimension <specs|personal>] [--scope <global|project>] [--interactive] \"rule text\""
examples:
- /workflow:spec:add "Use functional components for all React code"
- /workflow:spec:add -y "No direct DB access from controllers" --type constraint
- /workflow:spec:add --scope global --dimension personal
- /workflow:spec:add --interactive
- /workflow:spec:add "Cache invalidation requires event sourcing" --type learning --category architecture
---
## Auto Mode
When `--yes` or `-y`: Auto-categorize and add guideline without confirmation.
# Spec Add Command (/workflow:spec:add)
## Overview
Unified command for adding specs one at a time. Supports both interactive wizard mode and direct CLI mode.
**Key Features**:
- Supports both project specs and personal specs
- Scope selection (global vs project) for personal specs
- Category-based organization for workflow stages
- Interactive wizard mode with smart defaults
- Direct CLI mode with auto-detection of type and category
- Auto-confirm mode (`-y`/`--yes`) for scripted usage
## Use Cases
1. **During Session**: Capture important decisions as they're made
2. **After Session**: Reflect on lessons learned before archiving
3. **Proactive**: Add team conventions or architectural rules
4. **Interactive**: Guided wizard for adding rules with full control over dimension, scope, and category
## Usage
```bash
/workflow:spec:add # Interactive wizard (all prompts)
/workflow:spec:add --interactive # Explicit interactive wizard
/workflow:spec:add "Use async/await instead of callbacks" # Direct mode (auto-detect type)
/workflow:spec:add -y "No direct DB access" --type constraint # Auto-confirm, skip confirmation
/workflow:spec:add --scope global --dimension personal # Create global personal spec (interactive)
/workflow:spec:add --dimension specs --category exploration # Project spec in exploration category (interactive)
```
## Parameters
| Parameter | Type | Required | Default | Description |
|-----------|------|----------|---------|-------------|
| `rule` | string | Yes (unless `--interactive`) | - | The rule, convention, or insight to add |
| `--type` | enum | No | auto-detect | Type: `convention`, `constraint`, `learning` |
| `--category` | string | No | auto-detect / `general` | Category for organization (see categories below) |
| `--dimension` | enum | No | Interactive | `specs` (project) or `personal` |
| `--scope` | enum | No | `project` | `global` or `project` (only for personal dimension) |
| `--interactive` | flag | No | - | Launch full guided wizard for adding rules |
| `-y` / `--yes` | flag | No | - | Auto-categorize and add without confirmation |
### Type Categories
**convention** - Coding style preferences (goes to `conventions` section)
- Subcategories: `coding_style`, `naming_patterns`, `file_structure`, `documentation`
**constraint** - Hard rules that must not be violated (goes to `constraints` section)
- Subcategories: `architecture`, `tech_stack`, `performance`, `security`
**learning** - Session-specific insights (goes to `learnings` array)
- Subcategories: `architecture`, `performance`, `security`, `testing`, `process`, `other`
### Workflow Stage Categories (for `--category`)
| 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" |
## Execution Process
```
Input Parsing:
|- Parse: rule text (positional argument, optional if --interactive)
|- Parse: --type (convention|constraint|learning)
|- Parse: --category (subcategory)
|- Parse: --dimension (specs|personal)
|- Parse: --scope (global|project)
|- Parse: --interactive (flag)
+- Parse: -y / --yes (flag)
Step 1: Parse Input
Step 2: Determine Mode
|- If --interactive OR no rule text → Full Interactive Wizard (Path A)
+- If rule text provided → Direct Mode (Path B)
Path A: Interactive Wizard
|- Step A1: Ask dimension (if not specified)
|- Step A2: Ask scope (if personal + scope not specified)
|- Step A3: Ask category (if not specified)
|- Step A4: Ask type (convention|constraint|learning)
|- Step A5: Ask content (rule text)
+- Continue to Step 3
Path B: Direct Mode
|- Step B1: Auto-detect type (if not specified) using detectType()
|- Step B2: Auto-detect category (if not specified) using detectCategory()
|- Step B3: Default dimension to 'specs' if not specified
+- Continue to Step 3
Step 3: Determine Target File
|- specs dimension → .ccw/specs/coding-conventions.md or architecture-constraints.md
+- personal dimension → ~/.ccw/personal/ or .ccw/personal/
Step 4: Validate and Write Spec
|- Ensure target directory and file exist
|- Check for duplicates
|- Append rule to appropriate section
+- Run ccw spec rebuild
Step 5: Display Confirmation
+- If -y/--yes: Minimal output
+- Otherwise: Full confirmation with location details
```
## Implementation
### Step 1: Parse Input
```javascript
// Parse arguments
const args = $ARGUMENTS
const argsLower = args.toLowerCase()
// Extract flags
const autoConfirm = argsLower.includes('--yes') || argsLower.includes('-y')
const isInteractive = argsLower.includes('--interactive')
// Extract named parameters
const hasType = argsLower.includes('--type')
const hasCategory = argsLower.includes('--category')
const hasDimension = argsLower.includes('--dimension')
const hasScope = argsLower.includes('--scope')
let type = hasType ? args.match(/--type\s+(\w+)/i)?.[1]?.toLowerCase() : null
let category = hasCategory ? args.match(/--category\s+(\w+)/i)?.[1]?.toLowerCase() : null
let dimension = hasDimension ? args.match(/--dimension\s+(\w+)/i)?.[1]?.toLowerCase() : null
let scope = hasScope ? args.match(/--scope\s+(\w+)/i)?.[1]?.toLowerCase() : null
// Extract rule text (everything before flags, or quoted string)
let ruleText = args
.replace(/--type\s+\w+/gi, '')
.replace(/--category\s+\w+/gi, '')
.replace(/--dimension\s+\w+/gi, '')
.replace(/--scope\s+\w+/gi, '')
.replace(/--interactive/gi, '')
.replace(/--yes/gi, '')
.replace(/-y\b/gi, '')
.replace(/^["']|["']$/g, '')
.trim()
// 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 (type && !['convention', 'constraint', 'learning'].includes(type)) {
console.log("Invalid type. Use 'convention', 'constraint', or 'learning'.")
return
}
if (category) {
const validCategories = [
'general', 'exploration', 'planning', 'execution',
'coding_style', 'naming_patterns', 'file_structure', 'documentation',
'architecture', 'tech_stack', 'performance', 'security',
'testing', 'process', 'other'
]
if (!validCategories.includes(category)) {
console.log(`Invalid category. Valid categories: ${validCategories.join(', ')}`)
return
}
}
```
### Step 2: Determine Mode
```javascript
const useInteractiveWizard = isInteractive || !ruleText
```
### Path A: Interactive Wizard
**If dimension not specified**:
```javascript
if (!dimension) {
const dimensionAnswer = AskUserQuestion({
questions: [{
question: "What type of spec do you want to create?",
header: "Dimension",
multiSelect: false,
options: [
{
label: "Project Spec",
description: "Coding conventions, constraints, quality rules for this project (stored in .ccw/specs/)"
},
{
label: "Personal Spec",
description: "Personal preferences and constraints that follow you across projects (stored in ~/.ccw/specs/personal/ or .ccw/specs/personal/)"
}
]
}]
})
dimension = dimensionAnswer.answers["Dimension"] === "Project Spec" ? "specs" : "personal"
}
```
**If personal dimension and scope not specified**:
```javascript
if (dimension === 'personal' && !scope) {
const scopeAnswer = AskUserQuestion({
questions: [{
question: "Where should this personal spec be stored?",
header: "Scope",
multiSelect: false,
options: [
{
label: "Global (Recommended)",
description: "Apply to ALL projects (~/.ccw/specs/personal/)"
},
{
label: "Project-only",
description: "Apply only to this project (.ccw/specs/personal/)"
}
]
}]
})
scope = scopeAnswer.answers["Scope"].includes("Global") ? "global" : "project"
}
```
**If category not specified**:
```javascript
if (!category) {
const categoryAnswer = AskUserQuestion({
questions: [{
question: "Which workflow stage does this spec apply to?",
header: "Category",
multiSelect: false,
options: [
{
label: "General (Recommended)",
description: "Applies to all stages (default)"
},
{
label: "Exploration",
description: "Code exploration, analysis, debugging"
},
{
label: "Planning",
description: "Task planning, requirements gathering"
},
{
label: "Execution",
description: "Implementation, testing, deployment"
}
]
}]
})
const categoryLabel = categoryAnswer.answers["Category"]
category = categoryLabel.includes("General") ? "general"
: categoryLabel.includes("Exploration") ? "exploration"
: categoryLabel.includes("Planning") ? "planning"
: "execution"
}
```
**Ask type (if not specified)**:
```javascript
if (!type) {
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 typeLabel = typeAnswer.answers["Type"]
type = typeLabel.includes("Convention") ? "convention"
: typeLabel.includes("Constraint") ? "constraint"
: "learning"
}
```
**Ask content (rule text)**:
```javascript
if (!ruleText) {
const contentAnswer = AskUserQuestion({
questions: [{
question: "Enter the rule or guideline text:",
header: "Content",
multiSelect: false,
options: [
{ label: "Custom rule", description: "Type your own rule using the 'Other' option below" },
{ label: "Skip", description: "Cancel adding a spec" }
]
}]
})
if (contentAnswer.answers["Content"] === "Skip") return
ruleText = contentAnswer.answers["Content"]
}
```
### Path B: Direct Mode
**Auto-detect type if not specified**:
```javascript
function detectType(ruleText) {
const text = ruleText.toLowerCase();
// Constraint indicators
if (/\b(no|never|must not|forbidden|prohibited|always must)\b/.test(text)) {
return 'constraint';
}
// Learning indicators
if (/\b(learned|discovered|realized|found that|turns out)\b/.test(text)) {
return 'learning';
}
// Default to convention
return 'convention';
}
function detectCategory(ruleText, type) {
const text = ruleText.toLowerCase();
if (type === 'constraint' || type === 'learning') {
if (/\b(architecture|layer|module|dependency|circular)\b/.test(text)) return 'architecture';
if (/\b(security|auth|permission|sanitize|xss|sql)\b/.test(text)) return 'security';
if (/\b(performance|cache|lazy|async|sync|slow)\b/.test(text)) return 'performance';
if (/\b(test|coverage|mock|stub)\b/.test(text)) return 'testing';
}
if (type === 'convention') {
if (/\b(name|naming|prefix|suffix|camel|pascal)\b/.test(text)) return 'naming_patterns';
if (/\b(file|folder|directory|structure|organize)\b/.test(text)) return 'file_structure';
if (/\b(doc|comment|jsdoc|readme)\b/.test(text)) return 'documentation';
return 'coding_style';
}
return type === 'constraint' ? 'tech_stack' : 'other';
}
if (!type) {
type = detectType(ruleText)
}
if (!category) {
category = detectCategory(ruleText, type)
}
if (!dimension) {
dimension = 'specs' // Default to project specs in direct mode
}
```
### Step 3: Ensure Guidelines File Exists
**Uses .ccw/specs/ directory (same as frontend/backend spec-index-builder)**
```bash
bash(test -f .ccw/specs/coding-conventions.md && echo "EXISTS" || echo "NOT_FOUND")
```
**If NOT_FOUND**, initialize spec system:
```bash
Bash('ccw spec init')
Bash('ccw spec rebuild')
```
### Step 4: Determine Target File
```javascript
const path = require('path')
const os = require('os')
const isConvention = type === 'convention'
const isConstraint = type === 'constraint'
const isLearning = type === 'learning'
let targetFile
let targetDir
if (dimension === 'specs') {
// Project specs - use .ccw/specs/ (same as frontend/backend spec-index-builder)
targetDir = '.ccw/specs'
if (isConstraint) {
targetFile = path.join(targetDir, 'architecture-constraints.md')
} else {
targetFile = path.join(targetDir, 'coding-conventions.md')
}
} else {
// Personal specs - use .ccw/personal/ (same as backend spec-index-builder)
if (scope === 'global') {
targetDir = path.join(os.homedir(), '.ccw', 'personal')
} else {
targetDir = path.join('.ccw', 'personal')
}
// Create type-based filename
const typePrefix = isConstraint ? 'constraints' : isLearning ? 'learnings' : 'conventions'
targetFile = path.join(targetDir, `${typePrefix}.md`)
}
```
### Step 5: Build Entry
```javascript
function buildEntry(rule, type, category, sessionId) {
if (type === 'learning') {
return {
date: new Date().toISOString().split('T')[0],
session_id: sessionId || null,
insight: rule,
category: category,
context: null
};
}
// For conventions and constraints, just return the rule string
return rule;
}
```
### Step 6: 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')
// Deduplicate: skip if rule text already exists in the file
if (content.includes(ruleText)) {
console.log(`
Rule already exists in ${targetFile}
Text: "${ruleText}"
`)
return
}
// Format the new rule based on type
let newRule
if (isLearning) {
const entry = buildEntry(ruleText, type, category)
newRule = `- [learning/${category}] ${entry.insight} (${entry.date})`
} else {
newRule = `- [${category}] ${ruleText}`
}
// Append the rule
content = content.trimEnd() + '\n' + newRule + '\n'
fs.writeFileSync(targetFile, content, 'utf8')
// Rebuild spec index
Bash('ccw spec rebuild')
```
### Step 7: Display Confirmation
**If `-y`/`--yes` (auto mode)**:
```
Spec added: [${type}/${category}] "${ruleText}" -> ${targetFile}
```
**Otherwise (full confirmation)**:
```
Spec created successfully
Dimension: ${dimension}
Scope: ${dimension === 'personal' ? scope : 'project'}
Category: ${category}
Type: ${type}
Rule: "${ruleText}"
Location: ${targetFile}
Use 'ccw spec list' to view all specs
Use 'ccw spec load --category ${category}' to load specs by category
```
## Target File Resolution
### Project Specs (dimension: specs)
```
.ccw/specs/
|- coding-conventions.md <- conventions, learnings
|- architecture-constraints.md <- constraints
+- quality-rules.md <- quality rules
```
### Personal Specs (dimension: personal)
```
# Global (~/.ccw/personal/)
~/.ccw/personal/
|- conventions.md <- personal conventions (all projects)
|- constraints.md <- personal constraints (all projects)
+- learnings.md <- personal learnings (all projects)
# Project-local (.ccw/personal/)
.ccw/personal/
|- conventions.md <- personal conventions (this project only)
|- constraints.md <- personal constraints (this project only)
+- learnings.md <- personal learnings (this project only)
```
## Examples
### Interactive Wizard
```bash
/workflow:spec:add --interactive
# Prompts for: dimension -> scope (if personal) -> category -> type -> content
```
### Add a Convention (Direct)
```bash
/workflow:spec:add "Use async/await instead of callbacks" --type convention --category coding_style
```
Result in `.ccw/specs/coding-conventions.md`:
```markdown
- [coding_style] Use async/await instead of callbacks
```
### Add an Architectural Constraint (Direct)
```bash
/workflow:spec:add "No direct DB access from controllers" --type constraint --category architecture
```
Result in `.ccw/specs/architecture-constraints.md`:
```markdown
- [architecture] No direct DB access from controllers
```
### Capture a Learning (Direct, Auto-detect)
```bash
/workflow:spec:add "Cache invalidation requires event sourcing for consistency" --type learning
```
Result in `.ccw/specs/coding-conventions.md`:
```markdown
- [learning/architecture] Cache invalidation requires event sourcing for consistency (2026-03-06)
```
### Auto-confirm Mode
```bash
/workflow:spec:add -y "No direct DB access from controllers" --type constraint
# Auto-detects category as 'architecture', writes without confirmation prompt
```
### Personal Spec (Global)
```bash
/workflow:spec:add --scope global --dimension personal --type convention "Prefer descriptive variable names"
```
Result in `~/.ccw/personal/conventions.md`:
```markdown
- [general] Prefer descriptive variable names
```
### Personal Spec (Project)
```bash
/workflow:spec:add --scope project --dimension personal --type constraint "No ORM in this project"
```
Result in `.ccw/personal/constraints.md`:
```markdown
- [general] No ORM in this project
```
## Error Handling
- **Duplicate Rule**: Warn and skip if exact rule text already exists in target file
- **Invalid Category**: Suggest valid categories for the type
- **Invalid Scope**: Exit with error - must be 'global' or 'project'
- **Invalid Dimension**: Exit with error - must be 'specs' or 'personal'
- **Invalid Type**: Exit with error - must be 'convention', 'constraint', or 'learning'
- **File not writable**: Check permissions, suggest manual creation
- **Invalid path**: Exit with error message
- **File Corruption**: Backup existing file before modification
## Related Commands
- `/workflow:spec:setup` - Initialize project with specs scaffold
- `/workflow:session:sync` - Quick-sync session work to specs and project-tech
- `/workflow:session:start` - Start a session
- `/workflow:session:complete` - Complete session (prompts for learnings)
- `ccw spec list` - View all specs
- `ccw spec load --category <cat>` - Load filtered specs
- `ccw spec rebuild` - Rebuild spec index

View File

@@ -1,74 +1,208 @@
---
name: init-guidelines
description: Interactive wizard to fill specs/*.md based on project analysis
argument-hint: "[--reset]"
name: setup
description: Initialize project-level state and configure specs via interactive questionnaire using cli-explore-agent
argument-hint: "[--regenerate] [--skip-specs] [--reset]"
examples:
- /workflow:init-guidelines
- /workflow:init-guidelines --reset
- /workflow:spec:setup
- /workflow:spec:setup --regenerate
- /workflow:spec:setup --skip-specs
- /workflow:spec:setup --reset
---
# Workflow Init Guidelines Command (/workflow:init-guidelines)
# Workflow Spec Setup Command (/workflow:spec:setup)
## Overview
Interactive multi-round wizard that analyzes the current project (via `project-tech.json`) and asks targeted questions to populate `.ccw/specs/*.md` with coding conventions, constraints, and quality rules.
Initialize `.workflow/project-tech.json` and `.ccw/specs/*.md` with comprehensive project understanding by delegating analysis to **cli-explore-agent**, then interactively configure project guidelines through a multi-round questionnaire.
**Dual File System**:
- `project-tech.json`: Auto-generated technical analysis (stack, architecture, components)
- `specs/*.md`: User-maintained rules and constraints (created and populated interactively)
**Design Principle**: Questions are dynamically generated based on the project's tech stack, architecture, and patterns — not generic boilerplate.
**Note**: This command may be called by `/workflow:init` after initialization. Upon completion, return to the calling workflow if applicable.
**Note**: This command may be called by other workflow commands. Upon completion, return immediately to continue the calling workflow without interrupting the task flow.
## Usage
```bash
/workflow:init-guidelines # Fill guidelines interactively (skip if already populated)
/workflow:init-guidelines --reset # Reset and re-fill guidelines from scratch
/workflow:spec:setup # Initialize (skip if exists)
/workflow:spec:setup --regenerate # Force regeneration of project-tech.json
/workflow:spec:setup --skip-specs # Initialize project-tech only, skip spec initialization and questionnaire
/workflow:spec:setup --reset # Reset specs content before questionnaire
```
## Execution Process
```
Input Parsing:
├─ Parse --regenerate flag → regenerate = true | false
├─ Parse --skip-specs flag → skipSpecs = true | false
└─ Parse --reset flag → reset = true | false
Step 1: Check Prerequisites
├─ project-tech.json must exist (run /workflow:init first)
├─ specs/*.md: check if populated or scaffold-only
If populated + no --reset → Ask: "Guidelines already exist. Overwrite or append?"
Decision:
├─ BOTH_EXIST + no --regenerate + no --reset → Exit: "Already initialized"
├─ EXISTS + --regenerate → Backup existing → Continue analysis
EXISTS + --reset → Reset specs, keep project-tech → Skip to questionnaire
└─ NOT_FOUND → Continue full flow
Step 2: Load Project Context
Read project-tech.json → extract tech stack, architecture, patterns
Full Flow:
Step 1: Parse input and check existing state
├─ Step 2: Get project metadata (name, root)
├─ Step 3: Invoke cli-explore-agent
│ ├─ Structural scan (get_modules_by_depth.sh, find, wc)
│ ├─ Semantic analysis (Gemini CLI)
│ ├─ Synthesis and merge
│ └─ Write .workflow/project-tech.json
├─ Step 4: Initialize Spec System (if not --skip-specs)
│ ├─ Check if specs/*.md exist
│ ├─ If NOT_FOUND → Run ccw spec init
│ └─ Run ccw spec rebuild
├─ Step 5: Multi-Round Interactive Questionnaire (if not --skip-specs)
│ ├─ Check if guidelines already populated → Ask: "Append / Reset / Cancel"
│ ├─ Load project context from project-tech.json
│ ├─ Round 1: Coding Conventions (coding_style, naming_patterns)
│ ├─ Round 2: File & Documentation Conventions (file_structure, documentation)
│ ├─ Round 3: Architecture & Tech Constraints (architecture, tech_stack)
│ ├─ Round 4: Performance & Security Constraints (performance, security)
│ └─ Round 5: Quality Rules (quality_rules)
├─ Step 6: Write specs/*.md (if not --skip-specs)
└─ Step 7: Display Summary
Step 3: Multi-Round Interactive Questionnaire
├─ Round 1: Coding Conventions (coding_style, naming_patterns)
Round 2: File & Documentation Conventions (file_structure, documentation)
├─ Round 3: Architecture & Tech Constraints (architecture, tech_stack)
├─ Round 4: Performance & Security Constraints (performance, security)
└─ Round 5: Quality Rules (quality_rules)
Step 4: Write specs/*.md
Step 5: Display Summary
Output:
├─ .workflow/project-tech.json (+ .backup if regenerate)
.ccw/specs/*.md (scaffold or configured, unless --skip-specs)
```
## Implementation
### Step 1: Check Prerequisites
### Step 1: Parse Input and Check Existing State
**Parse flags**:
```javascript
const regenerate = $ARGUMENTS.includes('--regenerate')
const skipSpecs = $ARGUMENTS.includes('--skip-specs')
const reset = $ARGUMENTS.includes('--reset')
```
**Check existing state**:
```bash
bash(test -f .workflow/project-tech.json && echo "TECH_EXISTS" || echo "TECH_NOT_FOUND")
bash(test -f .ccw/specs/coding-conventions.md && echo "SPECS_EXISTS" || echo "SPECS_NOT_FOUND")
```
**If TECH_NOT_FOUND**: Exit with message
**If BOTH_EXIST and no --regenerate and no --reset**: Exit early
```
Project tech analysis not found. Run /workflow:init first.
Project already initialized:
- Tech analysis: .workflow/project-tech.json
- Guidelines: .ccw/specs/*.md
Use /workflow:spec:setup --regenerate to rebuild tech analysis
Use /workflow:spec:setup --reset to reconfigure guidelines
Use /workflow:spec:add to add individual rules
Use /workflow:status --project to view state
```
**Parse --reset flag**:
### Step 2: Get Project Metadata
```bash
bash(basename "$(git rev-parse --show-toplevel 2>/dev/null || pwd)")
bash(git rev-parse --show-toplevel 2>/dev/null || pwd)
bash(mkdir -p .workflow)
```
### Step 3: Invoke cli-explore-agent
**For --regenerate**: Backup and preserve existing data
```bash
bash(cp .workflow/project-tech.json .workflow/project-tech.json.backup)
```
**Delegate analysis to agent**:
```javascript
const reset = $ARGUMENTS.includes('--reset')
Task(
subagent_type="cli-explore-agent",
run_in_background=false,
description="Deep project analysis",
prompt=`
Analyze project for workflow initialization and generate .workflow/project-tech.json.
## MANDATORY FIRST STEPS
1. Execute: cat ~/.ccw/workflows/cli-templates/schemas/project-tech-schema.json (get schema reference)
2. Execute: ccw tool exec get_modules_by_depth '{}' (get project structure)
## Task
Generate complete project-tech.json following the schema structure:
- project_name: "${projectName}"
- initialized_at: ISO 8601 timestamp
- overview: {
description: "Brief project description",
technology_stack: {
languages: [{name, file_count, primary}],
frameworks: ["string"],
build_tools: ["string"],
test_frameworks: ["string"]
},
architecture: {style, layers: [], patterns: []},
key_components: [{name, path, description, importance}]
}
- features: []
- development_index: ${regenerate ? 'preserve from backup' : '{feature: [], enhancement: [], bugfix: [], refactor: [], docs: []}'}
- statistics: ${regenerate ? 'preserve from backup' : '{total_features: 0, total_sessions: 0, last_updated: ISO timestamp}'}
- _metadata: {initialized_by: "cli-explore-agent", analysis_timestamp: ISO timestamp, analysis_mode: "deep-scan"}
## Analysis Requirements
**Technology Stack**:
- Languages: File counts, mark primary
- Frameworks: From package.json, requirements.txt, go.mod, etc.
- Build tools: npm, cargo, maven, webpack, vite
- Test frameworks: jest, pytest, go test, junit
**Architecture**:
- Style: MVC, microservices, layered (from structure & imports)
- Layers: presentation, business-logic, data-access
- Patterns: singleton, factory, repository
- Key components: 5-10 modules {name, path, description, importance}
## Execution
1. Structural scan: get_modules_by_depth.sh, find, wc -l
2. Semantic analysis: Gemini for patterns/architecture
3. Synthesis: Merge findings
4. ${regenerate ? 'Merge with preserved development_index and statistics from .workflow/project-tech.json.backup' : ''}
5. Write JSON: Write('.workflow/project-tech.json', jsonContent)
6. Report: Return brief completion summary
Project root: ${projectRoot}
`
)
```
**If GUIDELINES_EXISTS and not --reset**: Check if guidelines are populated (not just scaffold)
### Step 4: Initialize Spec System (if not --skip-specs)
```javascript
// Skip spec initialization if --skip-specs flag is provided
if (!skipSpecs) {
// Initialize spec system if not already initialized
const specsCheck = Bash('test -f .ccw/specs/coding-conventions.md && echo EXISTS || echo NOT_FOUND')
if (specsCheck.includes('NOT_FOUND')) {
console.log('Initializing spec system...')
Bash('ccw spec init')
Bash('ccw spec rebuild')
}
} else {
console.log('Skipping spec initialization and questionnaire (--skip-specs)')
}
```
If `--skip-specs` is provided, skip directly to Step 7 (Display Summary) with limited output.
### Step 5: Multi-Round Interactive Questionnaire (if not --skip-specs)
#### Step 5.0: Check Existing Guidelines
If guidelines already have content, ask the user how to proceed:
```javascript
// Check if specs already have content via ccw spec list
@@ -76,7 +210,7 @@ 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) {
if (isPopulated && !reset) {
AskUserQuestion({
questions: [{
question: "Project guidelines already contain entries. How would you like to proceed?",
@@ -93,9 +227,15 @@ if (isPopulated) {
// If Reset → clear all arrays before proceeding
// If Append → keep existing, wizard adds to them
}
// If --reset flag was provided, clear existing entries before proceeding
if (reset) {
// Reset specs content
console.log('Resetting existing guidelines...')
}
```
### Step 2: Load Project Context
#### Step 5.1: Load Project Context
```javascript
// Load project context via ccw spec load for planning context
@@ -112,15 +252,15 @@ const archPatterns = specData.overview?.architecture?.patterns || []
const buildTools = specData.overview?.technology_stack?.build_tools || []
```
### Step 3: Multi-Round Interactive Questionnaire
#### Step 5.2: Multi-Round Questionnaire
Each round uses `AskUserQuestion` with project-aware options. The user can always select "Other" to provide custom input.
**⚠️ CRITICAL**: After each round, collect the user's answers and convert them into guideline entries. Do NOT batch all rounds — process each round's answers before proceeding to the next.
**CRITICAL**: After each round, collect the user's answers and convert them into guideline entries. Do NOT batch all rounds — process each round's answers before proceeding to the next.
---
#### Round 1: Coding Conventions
##### Round 1: Coding Conventions
Generate options dynamically based on detected language/framework:
@@ -175,11 +315,11 @@ AskUserQuestion({
})
```
**Process Round 1 answers** add to `conventions.coding_style` and `conventions.naming_patterns` arrays.
**Process Round 1 answers** -> add to `conventions.coding_style` and `conventions.naming_patterns` arrays.
---
#### Round 2: File Structure & Documentation
##### Round 2: File Structure & Documentation
```javascript
AskUserQuestion({
@@ -210,11 +350,11 @@ AskUserQuestion({
})
```
**Process Round 2 answers** add to `conventions.file_structure` and `conventions.documentation`.
**Process Round 2 answers** -> add to `conventions.file_structure` and `conventions.documentation`.
---
#### Round 3: Architecture & Tech Stack Constraints
##### Round 3: Architecture & Tech Stack Constraints
```javascript
// Build architecture-specific options
@@ -259,11 +399,11 @@ AskUserQuestion({
})
```
**Process Round 3 answers** add to `constraints.architecture` and `constraints.tech_stack`.
**Process Round 3 answers** -> add to `constraints.architecture` and `constraints.tech_stack`.
---
#### Round 4: Performance & Security Constraints
##### Round 4: Performance & Security Constraints
```javascript
AskUserQuestion({
@@ -294,11 +434,11 @@ AskUserQuestion({
})
```
**Process Round 4 answers** add to `constraints.performance` and `constraints.security`.
**Process Round 4 answers** -> add to `constraints.performance` and `constraints.security`.
---
#### Round 5: Quality Rules
##### Round 5: Quality Rules
```javascript
AskUserQuestion({
@@ -318,9 +458,9 @@ AskUserQuestion({
})
```
**Process Round 5 answers** add to `quality_rules` array as `{ rule, scope, enforced_by }` objects.
**Process Round 5 answers** -> add to `quality_rules` array as `{ rule, scope, enforced_by }` objects.
### Step 4: Write specs/*.md
### Step 6: Write specs/*.md (if not --skip-specs)
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`.
@@ -404,51 +544,107 @@ keywords: [execution, quality, testing, coverage, lint]
Bash('ccw spec rebuild')
```
### Step 5: Display Summary
#### Answer Processing Rules
When converting user selections to guideline entries:
1. **Selected option** -> Use the option's `description` as the guideline string (it's more precise than the label)
2. **"Other" with custom text** -> Use the user's text directly as the guideline string
3. **Deduplication** -> Skip entries that already exist in the guidelines (exact string match)
4. **Quality rules** -> Convert to `{ rule: description, scope: "all", enforced_by: "code-review" }` format
### Step 7: Display Summary
```javascript
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 projectTech = JSON.parse(Read('.workflow/project-tech.json'));
// Get updated spec list
const specsList = Bash('ccw spec list --json 2>/dev/null || echo "{}"')
if (skipSpecs) {
// Minimal summary for --skip-specs mode
console.log(`
Project initialized successfully (tech analysis only)
console.log(`
✓ Project guidelines configured
## Project Overview
Name: ${projectTech.project_name}
Description: ${projectTech.overview.description}
## Summary
### Technology Stack
Languages: ${projectTech.overview.technology_stack.languages.map(l => l.name).join(', ')}
Frameworks: ${projectTech.overview.technology_stack.frameworks.join(', ')}
### Architecture
Style: ${projectTech.overview.architecture.style}
Components: ${projectTech.overview.key_components.length} core modules
---
Files created:
- Tech analysis: .workflow/project-tech.json
- Specs: (skipped via --skip-specs)
${regenerate ? '- Backup: .workflow/project-tech.json.backup' : ''}
Next steps:
- Use /workflow:spec:setup (without --skip-specs) to configure guidelines
- Use /workflow:spec:add to create individual specs
- Use workflow-plan skill to start planning
`);
} else {
// Full summary with guidelines stats
const countConventions = newCodingStyle.length + newNamingPatterns.length
+ newFileStructure.length + newDocumentation.length
const countConstraints = newArchitecture.length + newTechStack.length
+ newPerformance.length + newSecurity.length
const countQuality = newQualityRules.length
// Get updated spec list
const specsList = Bash('ccw spec list --json 2>/dev/null || echo "{}"')
console.log(`
Project initialized and guidelines configured
## Project Overview
Name: ${projectTech.project_name}
Description: ${projectTech.overview.description}
### Technology Stack
Languages: ${projectTech.overview.technology_stack.languages.map(l => l.name).join(', ')}
Frameworks: ${projectTech.overview.technology_stack.frameworks.join(', ')}
### Architecture
Style: ${projectTech.overview.architecture.style}
Components: ${projectTech.overview.key_components.length} core modules
### Guidelines Summary
- 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
Spec index rebuilt. Use \`ccw spec list\` to view all specs.
---
Files created:
- Tech analysis: .workflow/project-tech.json
- Specs: .ccw/specs/ (configured)
${regenerate ? '- Backup: .workflow/project-tech.json.backup' : ''}
Next steps:
- Use /workflow:session:solidify to add individual rules later
- Use /workflow:spec:add to add individual rules later
- Specs are auto-loaded via hook on each prompt
`)
- Use workflow-plan skill to start planning
`);
}
```
## Answer Processing Rules
When converting user selections to guideline entries:
1. **Selected option** → Use the option's `description` as the guideline string (it's more precise than the label)
2. **"Other" with custom text** → Use the user's text directly as the guideline string
3. **Deduplication** → Skip entries that already exist in the guidelines (exact string match)
4. **Quality rules** → Convert to `{ rule: description, scope: "all", enforced_by: "code-review" }` format
## Error Handling
- **No project-tech.json**: Exit with instruction to run `/workflow:init` first
- **User cancels mid-wizard**: Save whatever was collected so far (partial is better than nothing)
- **File write failure**: Report error, suggest manual edit
**Agent Failure**: Fall back to basic initialization with placeholder overview
**Missing Tools**: Agent uses Qwen fallback or bash-only
**Empty Project**: Create minimal JSON with all gaps identified
**No project-tech.json** (when --reset without prior init): Run full flow from Step 2
**User cancels mid-wizard**: Save whatever was collected so far (partial is better than nothing)
**File write failure**: Report error, suggest manual edit
## 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
- `/workflow:spec:add` - Interactive wizard to create individual specs with scope selection
- `/workflow:session:sync` - Quick-sync session work to specs and project-tech
- `workflow-plan` skill - Start planning with initialized project context
- `/workflow:status --project` - View project state and guidelines

View File

@@ -658,9 +658,15 @@ ${recommendations.map(r => \`- ${r}\`).join('\\n')}
- "优化执行" → Analyze execution improvements
- "完成" → No further action
5. **Sync Session State** (automatic, unless `--dry-run`)
- Execute: `/workflow:session:sync -y "Execution complete: ${completedCount}/${totalCount} tasks succeeded"`
- Updates specs/*.md with any learnings from execution
- Updates project-tech.json with development index entry
**Success Criteria**:
- [ ] Statistics collected and displayed
- [ ] execution.md updated with final status
- [ ] Session state synced via /workflow:session:sync
- [ ] User informed of completion
---

View File

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

View File

@@ -1,584 +0,0 @@
# Mermaid Utilities Library
Shared utilities for generating and validating Mermaid diagrams across all analysis skills.
## Sanitization Functions
### sanitizeId
Convert any text to a valid Mermaid node ID.
```javascript
/**
* Sanitize text to valid Mermaid node ID
* - Only alphanumeric and underscore allowed
* - Cannot start with number
* - Truncates to 50 chars max
*
* @param {string} text - Input text
* @returns {string} - Valid Mermaid ID
*/
function sanitizeId(text) {
if (!text) return '_empty';
return text
.replace(/[^a-zA-Z0-9_\u4e00-\u9fa5]/g, '_') // Allow Chinese chars
.replace(/^[0-9]/, '_$&') // Prefix number with _
.replace(/_+/g, '_') // Collapse multiple _
.substring(0, 50); // Limit length
}
// Examples:
// sanitizeId("User-Service") → "User_Service"
// sanitizeId("3rdParty") → "_3rdParty"
// sanitizeId("用户服务") → "用户服务"
```
### escapeLabel
Escape special characters for Mermaid labels.
```javascript
/**
* Escape special characters in Mermaid labels
* Uses HTML entity encoding for problematic chars
*
* @param {string} text - Label text
* @returns {string} - Escaped label
*/
function escapeLabel(text) {
if (!text) return '';
return text
.replace(/"/g, "'") // Avoid quote issues
.replace(/\(/g, '#40;') // (
.replace(/\)/g, '#41;') // )
.replace(/\{/g, '#123;') // {
.replace(/\}/g, '#125;') // }
.replace(/\[/g, '#91;') // [
.replace(/\]/g, '#93;') // ]
.replace(/</g, '#60;') // <
.replace(/>/g, '#62;') // >
.replace(/\|/g, '#124;') // |
.substring(0, 80); // Limit length
}
// Examples:
// escapeLabel("Process(data)") → "Process#40;data#41;"
// escapeLabel("Check {valid?}") → "Check #123;valid?#125;"
```
### sanitizeType
Sanitize type names for class diagrams.
```javascript
/**
* Sanitize type names for Mermaid classDiagram
* Removes generics syntax that causes issues
*
* @param {string} type - Type name
* @returns {string} - Sanitized type
*/
function sanitizeType(type) {
if (!type) return 'any';
return type
.replace(/<[^>]*>/g, '') // Remove generics <T>
.replace(/\|/g, ' or ') // Union types
.replace(/&/g, ' and ') // Intersection types
.replace(/\[\]/g, 'Array') // Array notation
.substring(0, 30);
}
// Examples:
// sanitizeType("Array<string>") → "Array"
// sanitizeType("string | number") → "string or number"
```
## Diagram Generation Functions
### generateFlowchartNode
Generate a flowchart node with proper shape.
```javascript
/**
* Generate flowchart node with shape
*
* @param {string} id - Node ID
* @param {string} label - Display label
* @param {string} type - Node type: start|end|process|decision|io|subroutine
* @returns {string} - Mermaid node definition
*/
function generateFlowchartNode(id, label, type = 'process') {
const safeId = sanitizeId(id);
const safeLabel = escapeLabel(label);
const shapes = {
start: `${safeId}(["${safeLabel}"])`, // Stadium shape
end: `${safeId}(["${safeLabel}"])`, // Stadium shape
process: `${safeId}["${safeLabel}"]`, // Rectangle
decision: `${safeId}{"${safeLabel}"}`, // Diamond
io: `${safeId}[/"${safeLabel}"/]`, // Parallelogram
subroutine: `${safeId}[["${safeLabel}"]]`, // Subroutine
database: `${safeId}[("${safeLabel}")]`, // Cylinder
manual: `${safeId}[/"${safeLabel}"\\]` // Trapezoid
};
return shapes[type] || shapes.process;
}
```
### generateFlowchartEdge
Generate a flowchart edge with optional label.
```javascript
/**
* Generate flowchart edge
*
* @param {string} from - Source node ID
* @param {string} to - Target node ID
* @param {string} label - Edge label (optional)
* @param {string} style - Edge style: solid|dashed|thick
* @returns {string} - Mermaid edge definition
*/
function generateFlowchartEdge(from, to, label = '', style = 'solid') {
const safeFrom = sanitizeId(from);
const safeTo = sanitizeId(to);
const safeLabel = label ? `|"${escapeLabel(label)}"|` : '';
const arrows = {
solid: '-->',
dashed: '-.->',
thick: '==>'
};
const arrow = arrows[style] || arrows.solid;
return ` ${safeFrom} ${arrow}${safeLabel} ${safeTo}`;
}
```
### generateAlgorithmFlowchart (Enhanced)
Generate algorithm flowchart with branch/loop support.
```javascript
/**
* Generate algorithm flowchart with decision support
*
* @param {Object} algorithm - Algorithm definition
* - name: Algorithm name
* - inputs: [{name, type}]
* - outputs: [{name, type}]
* - steps: [{id, description, type, next: [id], conditions: [text]}]
* @returns {string} - Complete Mermaid flowchart
*/
function generateAlgorithmFlowchart(algorithm) {
let mermaid = 'flowchart TD\n';
// Start node
mermaid += ` START(["开始: ${escapeLabel(algorithm.name)}"])\n`;
// Input node (if has inputs)
if (algorithm.inputs?.length > 0) {
const inputList = algorithm.inputs.map(i => `${i.name}: ${i.type}`).join(', ');
mermaid += ` INPUT[/"输入: ${escapeLabel(inputList)}"/]\n`;
mermaid += ` START --> INPUT\n`;
}
// Process nodes
const steps = algorithm.steps || [];
for (const step of steps) {
const nodeId = sanitizeId(step.id || `STEP_${step.step_num}`);
if (step.type === 'decision') {
mermaid += ` ${nodeId}{"${escapeLabel(step.description)}"}\n`;
} else if (step.type === 'io') {
mermaid += ` ${nodeId}[/"${escapeLabel(step.description)}"/]\n`;
} else if (step.type === 'loop_start') {
mermaid += ` ${nodeId}[["循环: ${escapeLabel(step.description)}"]]\n`;
} else {
mermaid += ` ${nodeId}["${escapeLabel(step.description)}"]\n`;
}
}
// Output node
const outputDesc = algorithm.outputs?.map(o => o.name).join(', ') || '结果';
mermaid += ` OUTPUT[/"输出: ${escapeLabel(outputDesc)}"/]\n`;
mermaid += ` END_(["结束"])\n`;
// Connect first step to input/start
if (steps.length > 0) {
const firstStep = sanitizeId(steps[0].id || 'STEP_1');
if (algorithm.inputs?.length > 0) {
mermaid += ` INPUT --> ${firstStep}\n`;
} else {
mermaid += ` START --> ${firstStep}\n`;
}
}
// Connect steps based on next array
for (const step of steps) {
const nodeId = sanitizeId(step.id || `STEP_${step.step_num}`);
if (step.next && step.next.length > 0) {
step.next.forEach((nextId, index) => {
const safeNextId = sanitizeId(nextId);
const condition = step.conditions?.[index];
if (condition) {
mermaid += ` ${nodeId} -->|"${escapeLabel(condition)}"| ${safeNextId}\n`;
} else {
mermaid += ` ${nodeId} --> ${safeNextId}\n`;
}
});
} else if (!step.type?.includes('end')) {
// Default: connect to next step or output
const stepIndex = steps.indexOf(step);
if (stepIndex < steps.length - 1) {
const nextStep = sanitizeId(steps[stepIndex + 1].id || `STEP_${stepIndex + 2}`);
mermaid += ` ${nodeId} --> ${nextStep}\n`;
} else {
mermaid += ` ${nodeId} --> OUTPUT\n`;
}
}
}
// Connect output to end
mermaid += ` OUTPUT --> END_\n`;
return mermaid;
}
```
## Diagram Validation
### validateMermaidSyntax
Comprehensive Mermaid syntax validation.
```javascript
/**
* Validate Mermaid diagram syntax
*
* @param {string} content - Mermaid diagram content
* @returns {Object} - {valid: boolean, issues: string[]}
*/
function validateMermaidSyntax(content) {
const issues = [];
// Check 1: Diagram type declaration
if (!content.match(/^(graph|flowchart|classDiagram|sequenceDiagram|stateDiagram|erDiagram|gantt|pie|mindmap)/m)) {
issues.push('Missing diagram type declaration');
}
// Check 2: Undefined values
if (content.includes('undefined') || content.includes('null')) {
issues.push('Contains undefined/null values');
}
// Check 3: Invalid arrow syntax
if (content.match(/-->\s*-->/)) {
issues.push('Double arrow syntax error');
}
// Check 4: Unescaped special characters in labels
const labelMatches = content.match(/\["[^"]*[(){}[\]<>][^"]*"\]/g);
if (labelMatches?.some(m => !m.includes('#'))) {
issues.push('Unescaped special characters in labels');
}
// Check 5: Node ID starts with number
if (content.match(/\n\s*[0-9][a-zA-Z0-9_]*[\[\({]/)) {
issues.push('Node ID cannot start with number');
}
// Check 6: Nested subgraph syntax error
if (content.match(/subgraph\s+\S+\s*\n[^e]*subgraph/)) {
// This is actually valid, only flag if brackets don't match
const subgraphCount = (content.match(/subgraph/g) || []).length;
const endCount = (content.match(/\bend\b/g) || []).length;
if (subgraphCount > endCount) {
issues.push('Unbalanced subgraph/end blocks');
}
}
// Check 7: Invalid arrow type for diagram type
const diagramType = content.match(/^(graph|flowchart|classDiagram|sequenceDiagram)/m)?.[1];
if (diagramType === 'classDiagram' && content.includes('-->|')) {
issues.push('Invalid edge label syntax for classDiagram');
}
// Check 8: Empty node labels
if (content.match(/\[""\]|\{\}|\(\)/)) {
issues.push('Empty node labels detected');
}
// Check 9: Reserved keywords as IDs
const reserved = ['end', 'graph', 'subgraph', 'direction', 'class', 'click'];
for (const keyword of reserved) {
const pattern = new RegExp(`\\n\\s*${keyword}\\s*[\\[\\(\\{]`, 'i');
if (content.match(pattern)) {
issues.push(`Reserved keyword "${keyword}" used as node ID`);
}
}
// Check 10: Line length (Mermaid has issues with very long lines)
const lines = content.split('\n');
for (let i = 0; i < lines.length; i++) {
if (lines[i].length > 500) {
issues.push(`Line ${i + 1} exceeds 500 characters`);
}
}
return {
valid: issues.length === 0,
issues
};
}
```
### validateDiagramDirectory
Validate all diagrams in a directory.
```javascript
/**
* Validate all Mermaid diagrams in directory
*
* @param {string} diagramDir - Path to diagrams directory
* @returns {Object[]} - Array of {file, valid, issues}
*/
function validateDiagramDirectory(diagramDir) {
const files = Glob(`${diagramDir}/*.mmd`);
const results = [];
for (const file of files) {
const content = Read(file);
const validation = validateMermaidSyntax(content);
results.push({
file: file.split('/').pop(),
path: file,
valid: validation.valid,
issues: validation.issues,
lines: content.split('\n').length
});
}
return results;
}
```
## Class Diagram Utilities
### generateClassDiagram
Generate class diagram with relationships.
```javascript
/**
* Generate class diagram from analysis data
*
* @param {Object} analysis - Data structure analysis
* - entities: [{name, type, properties, methods}]
* - relationships: [{from, to, type, label}]
* @param {Object} options - Generation options
* - maxClasses: Max classes to include (default: 15)
* - maxProperties: Max properties per class (default: 8)
* - maxMethods: Max methods per class (default: 6)
* @returns {string} - Mermaid classDiagram
*/
function generateClassDiagram(analysis, options = {}) {
const maxClasses = options.maxClasses || 15;
const maxProperties = options.maxProperties || 8;
const maxMethods = options.maxMethods || 6;
let mermaid = 'classDiagram\n';
const entities = (analysis.entities || []).slice(0, maxClasses);
// Generate classes
for (const entity of entities) {
const className = sanitizeId(entity.name);
mermaid += ` class ${className} {\n`;
// Properties
for (const prop of (entity.properties || []).slice(0, maxProperties)) {
const vis = {public: '+', private: '-', protected: '#'}[prop.visibility] || '+';
const type = sanitizeType(prop.type);
mermaid += ` ${vis}${type} ${prop.name}\n`;
}
// Methods
for (const method of (entity.methods || []).slice(0, maxMethods)) {
const vis = {public: '+', private: '-', protected: '#'}[method.visibility] || '+';
const params = (method.params || []).map(p => p.name).join(', ');
const returnType = sanitizeType(method.returnType || 'void');
mermaid += ` ${vis}${method.name}(${params}) ${returnType}\n`;
}
mermaid += ' }\n';
// Add stereotype if applicable
if (entity.type === 'interface') {
mermaid += ` <<interface>> ${className}\n`;
} else if (entity.type === 'abstract') {
mermaid += ` <<abstract>> ${className}\n`;
}
}
// Generate relationships
const arrows = {
inheritance: '--|>',
implementation: '..|>',
composition: '*--',
aggregation: 'o--',
association: '-->',
dependency: '..>'
};
for (const rel of (analysis.relationships || [])) {
const from = sanitizeId(rel.from);
const to = sanitizeId(rel.to);
const arrow = arrows[rel.type] || '-->';
const label = rel.label ? ` : ${escapeLabel(rel.label)}` : '';
// Only include if both entities exist
if (entities.some(e => sanitizeId(e.name) === from) &&
entities.some(e => sanitizeId(e.name) === to)) {
mermaid += ` ${from} ${arrow} ${to}${label}\n`;
}
}
return mermaid;
}
```
## Sequence Diagram Utilities
### generateSequenceDiagram
Generate sequence diagram from scenario.
```javascript
/**
* Generate sequence diagram from scenario
*
* @param {Object} scenario - Sequence scenario
* - name: Scenario name
* - actors: [{id, name, type}]
* - messages: [{from, to, description, type}]
* - blocks: [{type, condition, messages}]
* @returns {string} - Mermaid sequenceDiagram
*/
function generateSequenceDiagram(scenario) {
let mermaid = 'sequenceDiagram\n';
// Title
if (scenario.name) {
mermaid += ` title ${escapeLabel(scenario.name)}\n`;
}
// Participants
for (const actor of scenario.actors || []) {
const actorType = actor.type === 'external' ? 'actor' : 'participant';
mermaid += ` ${actorType} ${sanitizeId(actor.id)} as ${escapeLabel(actor.name)}\n`;
}
mermaid += '\n';
// Messages
for (const msg of scenario.messages || []) {
const from = sanitizeId(msg.from);
const to = sanitizeId(msg.to);
const desc = escapeLabel(msg.description);
let arrow;
switch (msg.type) {
case 'async': arrow = '->>'; break;
case 'response': arrow = '-->>'; break;
case 'create': arrow = '->>+'; break;
case 'destroy': arrow = '->>-'; break;
case 'self': arrow = '->>'; break;
default: arrow = '->>';
}
mermaid += ` ${from}${arrow}${to}: ${desc}\n`;
// Activation
if (msg.activate) {
mermaid += ` activate ${to}\n`;
}
if (msg.deactivate) {
mermaid += ` deactivate ${from}\n`;
}
// Notes
if (msg.note) {
mermaid += ` Note over ${to}: ${escapeLabel(msg.note)}\n`;
}
}
// Blocks (loops, alt, opt)
for (const block of scenario.blocks || []) {
switch (block.type) {
case 'loop':
mermaid += ` loop ${escapeLabel(block.condition)}\n`;
break;
case 'alt':
mermaid += ` alt ${escapeLabel(block.condition)}\n`;
break;
case 'opt':
mermaid += ` opt ${escapeLabel(block.condition)}\n`;
break;
}
for (const m of block.messages || []) {
mermaid += ` ${sanitizeId(m.from)}->>${sanitizeId(m.to)}: ${escapeLabel(m.description)}\n`;
}
mermaid += ' end\n';
}
return mermaid;
}
```
## Usage Examples
### Example 1: Algorithm with Branches
```javascript
const algorithm = {
name: "用户认证流程",
inputs: [{name: "credentials", type: "Object"}],
outputs: [{name: "token", type: "JWT"}],
steps: [
{id: "validate", description: "验证输入格式", type: "process"},
{id: "check_user", description: "用户是否存在?", type: "decision",
next: ["verify_pwd", "error_user"], conditions: ["是", "否"]},
{id: "verify_pwd", description: "验证密码", type: "process"},
{id: "pwd_ok", description: "密码正确?", type: "decision",
next: ["gen_token", "error_pwd"], conditions: ["是", "否"]},
{id: "gen_token", description: "生成 JWT Token", type: "process"},
{id: "error_user", description: "返回用户不存在", type: "io"},
{id: "error_pwd", description: "返回密码错误", type: "io"}
]
};
const flowchart = generateAlgorithmFlowchart(algorithm);
```
### Example 2: Validate Before Output
```javascript
const diagram = generateClassDiagram(analysis);
const validation = validateMermaidSyntax(diagram);
if (!validation.valid) {
console.log("Diagram has issues:", validation.issues);
// Fix issues or regenerate
} else {
Write(`${outputDir}/class-diagram.mmd`, diagram);
}
```

View File

@@ -0,0 +1,177 @@
# Brainstorm Skill
Unified brainstorming skill combining interactive framework generation, multi-role parallel analysis, and cross-role synthesis into a single entry point with two operational modes.
## Key Features
- **Dual-Mode Operation**: Auto mode (full pipeline) and single role mode (individual analysis)
- **Interactive Framework Generation**: Seven-phase workflow for guidance specification
- **Parallel Role Analysis**: Concurrent execution of multiple role perspectives
- **Cross-Role Synthesis**: Integration of insights into feature specifications
- **SPEC.md Quality Standards**: Guidance specification includes Concepts & Terminology, Non-Goals, RFC 2119 constraints
- **Template-Driven Role Analysis**: system-architect produces Data Model, State Machine, Error Handling, Observability, Configuration Model, Boundary Scenarios
- **Automated Quality Gates**: Validation agents ensure outputs meet quality standards
- **Session Continuity**: All phases share state via workflow-session.json
- **Progressive Loading**: Phase documents loaded on-demand via Ref markers
## Architecture
```
┌─────────────────────────────────────────────────────────────┐
│ /brainstorm │
│ Unified Entry Point + Interactive Routing │
└───────────────────────┬─────────────────────────────────────┘
┌─────────┴─────────┐
↓ ↓
┌─────────────────┐ ┌──────────────────┐
│ Auto Mode │ │ Single Role Mode │
│ (自动模式) │ │ (单角色分析模式) │
└────────┬────────┘ └────────┬─────────┘
│ │
┌────────┼────────┐ │
↓ ↓ ↓ ↓
Phase 2 Phase 3 Phase 4 Phase 3
Artifacts N×Role Synthesis 1×Role
(7步) Analysis (8步) Analysis
并行 (4步)
```
### Execution Flow
**Auto Mode**:
1. **Phase 1**: Mode detection and parameter parsing
2. **Phase 1.5**: Terminology & Boundary Definition (extract terms, collect Non-Goals)
3. **Phase 2**: Interactive Framework Generation (7 sub-phases)
- Context collection → Topic analysis → Role selection → Role questions → Conflict resolution → Final check → Generate specification
- **Phase 5**: Generate guidance-specification.md with Concepts & Terminology, Non-Goals, RFC 2119 constraints
4. **Phase 3**: Parallel Role Analysis (N concurrent role analyses)
- Template-driven analysis with quality validation
- system-architect includes: Data Model, State Machine, Error Handling, Observability, Configuration Model, Boundary Scenarios
5. **Phase 4**: Synthesis Integration (6 sub-phases)
- Discovery → File discovery → Cross-role analysis → User interaction → Spec generation → Finalization
**Single Role Mode**:
1. **Phase 1**: Mode detection and parameter parsing
2. **Phase 3**: Single role analysis (4 sub-phases)
- Detection → Context → Agent → Validation
## Usage
### Auto Mode
```bash
# Full pipeline with default settings
/brainstorm "Build real-time collaboration platform"
# Auto-select mode with specific role count
/brainstorm -y "GOAL: Build platform SCOPE: 100 users" --count 5
# With style skill for UI designer
/brainstorm "Design payment system" --style-skill material-design
```
### Single Role Mode
```bash
# Analyze with specific role
/brainstorm system-architect --session WFS-xxx
# With interactive questions
/brainstorm ux-expert --include-questions
# Update existing analysis
/brainstorm ui-designer --session WFS-xxx --update --style-skill material-design
# Skip questions (use defaults)
/brainstorm product-manager --skip-questions
```
## Available Roles
| Role ID | Title | Focus Area |
|---------|-------|------------|
| `data-architect` | 数据架构师 | Data models, storage strategies, data flow |
| `product-manager` | 产品经理 | Product strategy, roadmap, prioritization |
| `product-owner` | 产品负责人 | Backlog management, user stories, acceptance criteria |
| `scrum-master` | 敏捷教练 | Process facilitation, impediment removal |
| `subject-matter-expert` | 领域专家 | Domain knowledge, business rules, compliance |
| `system-architect` | 系统架构师 | Technical architecture, scalability, integration |
| `test-strategist` | 测试策略师 | Test strategy, quality assurance |
| `ui-designer` | UI设计师 | Visual design, mockups, design systems |
| `ux-expert` | UX专家 | User research, information architecture, journey |
## Output Files
```
.workflow/active/WFS-{topic}/
├── workflow-session.json # Session metadata
├── .process/
│ └── context-package.json # Phase 0 output
└── .brainstorming/
├── guidance-specification.md # Framework with terminology, non-goals
├── feature-index.json # Feature index
├── synthesis-changelog.md # Synthesis decisions
├── feature-specs/ # Feature specifications
│ ├── F-001-{slug}.md
│ └── F-00N-{slug}.md
├── specs/
│ └── terminology-template.json # Terminology glossary schema
├── templates/
│ └── role-templates/
│ └── system-architect-template.md # System architect analysis template
├── agents/
│ └── role-analysis-reviewer-agent.md # Role analysis validation agent
├── {role}/ # Role analyses (immutable)
│ ├── {role}-context.md # Q&A responses
│ ├── analysis.md # Main document
│ ├── analysis-cross-cutting.md # Cross-feature
│ └── analysis-F-{id}-{slug}.md # Per-feature
└── synthesis-specification.md # Integration
```
## Quality Standards
### Guidance Specification
- **Section 2**: Concepts & Terminology (5-10 core terms with definitions, aliases, categories)
- **Section 3**: Non-Goals (Out of Scope) with rationale
- **RFC 2119 Keywords**: All requirements use MUST, SHOULD, MAY
### Role Analysis (system-architect)
1. **Architecture Overview**: High-level system design
2. **Data Model**: 3-5 core entities with precise field definitions
3. **State Machine**: Lifecycle for 1-2 entities with complex workflows
4. **Error Handling Strategy**: Global + per-component recovery
5. **Observability Requirements**: Metrics, logs, health checks
6. **Configuration Model**: All configurable parameters with validation
7. **Boundary Scenarios**: Concurrency, rate limiting, shutdown, cleanup, scalability, DR
### Quality Validation
- Template compliance checking
- RFC 2119 keyword usage verification
- Diagram syntax validation
- Section completeness scoring
## Parameters
| Parameter | Description | Default |
|-----------|-------------|---------|
| `--yes`, `-y` | Auto mode, skip all questions | - |
| `--count N` | Number of roles to select | 3 |
| `--session ID` | Use existing session | - |
| `--update` | Update existing analysis | - |
| `--include-questions` | Interactive context gathering | - |
| `--skip-questions` | Use default answers | - |
| `--style-skill PKG` | Style package for ui-designer | - |
## Follow-up Commands
After brainstorm completes:
- `/workflow-plan --session {sessionId}` - Generate implementation plan
- `/workflow:brainstorm:synthesis --session {sessionId}` - Run synthesis standalone
## Related Documentation
- **Template Source**: `~/.ccw/workflows/cli-templates/planning-roles/`
- **Style SKILL Packages**: `.claude/skills/style-{package-name}/`
- **Phase Documents**: `phases/01-mode-routing.md`, `phases/02-artifacts.md`, `phases/03-role-analysis.md`, `phases/04-synthesis.md`

View File

@@ -49,6 +49,9 @@ Single Role Mode:
3. **Task Attachment/Collapse**: Sub-tasks attached during phase execution, collapsed after completion
4. **Session Continuity**: All phases share session state via workflow-session.json
5. **Auto-Continue Execution**: Phases chain automatically without user intervention between them
6. **SPEC.md Quality Alignment**: Guidance specification and role analysis follow SPEC.md standards (Concepts & Terminology, Non-Goals, Data Model, State Machine, RFC 2119 constraints)
7. **Template-Driven Analysis**: Role-specific templates (e.g., system-architect) ensure consistent, high-quality outputs
8. **Quality Gates**: Automated validation of guidance specification and role analysis against quality standards
## Auto Mode
@@ -73,13 +76,19 @@ Parse arguments, detect mode from flags/parameters, or ask user via AskUserQuest
### Auto Mode Execution (execution_mode = "auto")
**Phase 1.5: Terminology & Boundary Definition**
- Extract 5-10 core domain terms from user input and Phase 1 context
- Generate terminology table (term, definition, aliases, category)
- Collect Non-Goals via AskUserQuestion (明确排除的范围)
- Store to `session.terminology` and `session.non_goals`
#### Phase 2: Interactive Framework Generation
Ref: phases/02-artifacts.md
Seven-phase interactive workflow: Context collection → Topic analysis → Role selection → Role questions → Conflict resolution → Final check → Generate specification.
**Input**: topic description, --count N, --yes flag
**Output**: guidance-specification.md, workflow-session.json (selected_roles[], session_id)
**Output**: guidance-specification.md (with Concepts & Terminology, Non-Goals, RFC 2119 constraints), workflow-session.json (selected_roles[], session_id)
**TodoWrite**: Attach 7 sub-tasks (Phase 0-5), execute sequentially, collapse on completion.
@@ -95,6 +104,16 @@ Execute role analysis for EACH selected role in parallel.
For ui-designer: append `--style-skill {package}` if provided.
**Template-Driven Analysis**:
- Load role-specific template if exists (e.g., `templates/role-templates/system-architect-template.md`)
- Inject template into agent prompt as required structure
- For system-architect: MUST include Data Model, State Machine, Error Handling, Observability, Configuration Model, Boundary Scenarios
**Quality Validation**:
- After analysis generation, invoke `role-analysis-reviewer-agent` to validate against template
- Check MUST have sections (blocking), SHOULD have sections (warning), quality checks (RFC keywords, valid diagrams)
- Output validation report with score and recommendations
**TodoWrite**: Attach N parallel sub-tasks, execute concurrently, collapse on completion.
#### Phase 4: Synthesis Integration
@@ -327,6 +346,13 @@ Initial → Phase 1 Mode Routing (completed)
├── feature-specs/ # Feature specs (Phase 4, auto mode, feature_mode)
│ ├── F-001-{slug}.md
│ └── F-00N-{slug}.md
├── specs/
│ └── terminology-template.json # Terminology schema
├── templates/
│ └── role-templates/
│ └── system-architect-template.md # System architect analysis template
├── agents/
│ └── role-analysis-reviewer-agent.md # Role analysis validation agent
├── {role}/ # Role analyses (IMMUTABLE after Phase 3)
│ ├── {role}-context.md # Interactive Q&A responses
│ ├── analysis.md # Main/index document

View File

@@ -117,6 +117,73 @@ AskUserQuestion({
**⚠️ CRITICAL**: Questions MUST reference topic keywords. Generic "Project type?" violates dynamic generation.
### Phase 1.5: Terminology & Boundary Definition
**Goal**: Extract core terminology and define scope boundaries (Non-Goals)
**Steps**:
1. Analyze Phase 1 user responses and topic description
2. Extract 5-10 core domain terms that will be used throughout the specification
3. Generate terminology clarification questions if needed
4. Define scope boundaries by identifying what is explicitly OUT of scope
**Terminology Extraction**:
```javascript
// Based on Phase 1 context and user input
const coreTerms = extractTerminology({
topic: session.topic,
userResponses: session.intent_context,
contextPackage: contextPackage // from Phase 0
});
// Generate terminology table
const terminologyTable = coreTerms.map(term => ({
term: term.canonical,
definition: term.definition,
aliases: term.alternatives,
category: term.category // core|technical|business
}));
```
**Non-Goals Definition**:
```javascript
AskUserQuestion({
questions: [{
question: "以下哪些是明确 NOT 包含在本次项目范围内的?(可多选)",
header: "范围边界 (Non-Goals)",
multiSelect: true,
options: [
{ label: "移动端应用", description: "本次只做 Web 端,移动端后续考虑" },
{ label: "多语言支持", description: "MVP 阶段只支持中文" },
{ label: "第三方集成", description: "暂不集成外部系统" },
{ label: "高级分析功能", description: "基础功能优先,分析功能 v2" },
{ label: "其他(请在后续补充)", description: "用户自定义排除项" }
]
}]
});
// If user selects "其他", follow up with:
if (selectedNonGoals.includes("其他")) {
AskUserQuestion({
questions: [{
question: "请描述其他明确排除的功能或范围",
header: "补充 Non-Goals",
multiSelect: false,
freeText: true
}]
});
}
// Store to session
session.terminology = terminologyTable;
session.non_goals = selectedNonGoals.map(ng => ({
item: ng.label,
rationale: ng.description
}));
```
**Output**: Updated `workflow-session.json` with `terminology` and `non_goals` fields
### Phase 2: Role Selection
**Goal**: User selects roles from intelligent recommendations
@@ -303,11 +370,26 @@ After final clarification, extract implementable feature units from all Phase 1-
### Phase 5: Generate Specification
**Steps**:
1. Load all decisions: `intent_context` + `selected_roles` + `role_decisions` + `cross_role_decisions` + `additional_decisions` + `feature_list`
1. Load all decisions: `intent_context` + `selected_roles` + `role_decisions` + `cross_role_decisions` + `additional_decisions` + `feature_list` + `terminology` + `non_goals`
2. Transform Q&A to declarative: Questions → Headers, Answers → CONFIRMED/SELECTED statements
3. Generate `guidance-specification.md`
4. Update `workflow-session.json` (metadata only)
5. Validate: No interrogative sentences, all decisions traceable
3. Apply RFC 2119 keywords (MUST, SHOULD, MAY, MUST NOT, SHOULD NOT) to all behavioral requirements
4. Generate `guidance-specification.md` with Concepts & Terminology and Non-Goals sections
5. Update `workflow-session.json` (metadata only)
6. Validate: No interrogative sentences, all decisions traceable, RFC keywords applied
**RFC 2119 Compliance**:
All behavioral requirements and constraints MUST be expressed using RFC 2119 keywords:
- **MUST**: Absolute requirement, non-negotiable
- **MUST NOT**: Absolute prohibition
- **SHOULD**: Strong recommendation, may be ignored with valid reason
- **SHOULD NOT**: Strong discouragement
- **MAY**: Optional, implementer's choice
Example transformations:
- "用户需要登录" → "The system MUST authenticate users before granting access"
- "建议使用缓存" → "The system SHOULD cache frequently accessed data"
- "可以支持 OAuth" → "The system MAY support OAuth2 authentication"
## Question Guidelines
@@ -366,15 +448,43 @@ for (let i = 0; i < allQuestions.length; i += BATCH_SIZE) {
**CONFIRMED Objectives**: [from topic + Phase 1]
**CONFIRMED Success Criteria**: [from Phase 1 answers]
## 2-N. [Role] Decisions
## 2. Concepts & Terminology
**Core Terms**: The following terms are used consistently throughout this specification.
| Term | Definition | Aliases | Category |
|------|------------|---------|----------|
${session.terminology.map(t => `| ${t.term} | ${t.definition} | ${t.aliases.join(', ')} | ${t.category} |`).join('\n')}
**Usage Rules**:
- All documents MUST use the canonical term
- Aliases are for reference only
- New terms introduced in role analysis MUST be added to this glossary
## 3. Non-Goals (Out of Scope)
The following are explicitly OUT of scope for this project:
${session.non_goals.map(ng => `- **${ng.item}**: ${ng.rationale}`).join('\n')}
**Rationale**: These exclusions help maintain focus on core objectives and prevent scope creep.
## 4-N. [Role] Decisions
### SELECTED Choices
**[Question topic]**: [User's answer]
**[Question topic]**: [User's answer with RFC 2119 keywords]
- **Rationale**: [From option description]
- **Impact**: [Implications]
- **Impact**: [Implications with RFC keywords]
- **Requirement Level**: [MUST/SHOULD/MAY based on criticality]
**Example**:
- The system MUST authenticate users within 200ms (P99)
- The system SHOULD cache frequently accessed data
- The system MAY support OAuth2 providers (Google, GitHub)
### Cross-Role Considerations
**[Conflict resolved]**: [Resolution from Phase 4]
**[Conflict resolved]**: [Resolution from Phase 4 with RFC keywords]
- **Affected Roles**: [Roles involved]
- **Decision**: [MUST/SHOULD/MAY statement]
## Cross-Role Integration
**CONFIRMED Integration Points**: [API/Data/Auth from multiple roles]

View File

@@ -301,6 +301,14 @@ const agentContext = {
original_topic: original_topic,
session_id: session_id
};
// Load role-specific template if exists
let roleTemplate = null;
try {
roleTemplate = Read(`templates/role-templates/${role_name}-template.md`);
} catch (e) {
// No template, use generic analysis
}
```
**Step 3.3.3: Execute Conceptual Planning Agent**
@@ -362,6 +370,13 @@ UPDATE_MODE: ${update_mode}
- Command: Read(${brainstorm_dir}/${role_name}/${role_name}-context.md)
- Output: user_context_answers
${roleTemplate ? `
5. **load_role_template**
- Action: Load role-specific analysis template
- Command: Read(templates/role-templates/${role_name}-template.md)
- Output: role_specific_template
` : ''}
5. **${update_mode ? 'load_existing_analysis' : 'skip'}**
${update_mode ? `
- Action: Load existing analysis for incremental update
@@ -378,6 +393,21 @@ ${featureListBlock}
**Role Focus**: ${roleConfig[role_name].focus_area}
**Template Integration**: Apply role template guidelines within framework structure
${feature_mode ? `**Feature Organization**: Organize analysis by feature points - each feature gets its own sub-document. Cross-cutting concerns go into analysis-cross-cutting.md.` : ''}
**RFC 2119 Compliance**: Use RFC 2119 keywords (MUST, SHOULD, MAY, MUST NOT, SHOULD NOT) to define all behavioral constraints and recommendations. Every technical decision MUST be expressed with appropriate RFC keyword. Distinguish between absolute requirements (MUST) and recommendations (SHOULD).
${roleTemplate ? `
**ROLE-SPECIFIC TEMPLATE (MUST follow this structure)**:
${roleTemplate}
Your analysis MUST include all Required Sections from the template above.
` : ''}
**For system-architect role specifically**:
- MUST define Data Model for 3-5 core entities with fields, types, constraints, relationships
- MUST create State Machine for at least 1 entity with complex lifecycle (ASCII diagram + transition table)
- MUST define Error Handling Strategy with error classification and recovery mechanisms
- MUST specify Observability Requirements with metrics (at least 5), log events, and health checks
- All constraints MUST use RFC 2119 keywords (MUST, SHOULD, MAY)
## Expected Deliverables
${feature_mode ? `

View File

@@ -531,22 +531,32 @@ ${feature_mode ? `
**Status**: Draft (from synthesis)
## 1. Requirements Summary
[Consolidated requirements from all role perspectives]
- Functional requirements (from product-manager, product-owner)
- User experience requirements (from ux-expert, ui-designer)
- Technical requirements (from system-architect, data-architect, api-designer)
- Domain requirements (from subject-matter-expert)
[Consolidated requirements from all role perspectives using RFC 2119 keywords]
- Functional requirements (from product-manager, product-owner) - use MUST/SHOULD/MAY
- User experience requirements (from ux-expert, ui-designer) - use MUST/SHOULD/MAY
- Technical requirements (from system-architect, data-architect, api-designer) - use MUST/SHOULD/MAY
- Domain requirements (from subject-matter-expert) - use MUST/SHOULD/MAY
**Example**:
- The feature MUST support user authentication via email/password
- The UI SHOULD provide real-time feedback within 100ms
- The system MAY cache user preferences for offline access
## 2. Design Decisions [CORE SECTION]
[Key architectural and design decisions with rationale - 40%+ of word count]
For each decision:
- **Decision**: [What was decided]
- **Decision**: [What was decided - MUST use RFC 2119 keywords]
- **Context**: [Why this decision was needed]
- **Options Considered**: [Alternatives from different roles]
- **Chosen Approach**: [Selected option with rationale]
- **Chosen Approach**: [Selected option with rationale using MUST/SHOULD/MAY]
- **Trade-offs**: [What we gain vs. what we sacrifice]
- **Source**: [Which role(s) drove this decision]
**RFC 2119 Examples**:
- "The system MUST authenticate users before granting access"
- "The feature SHOULD cache frequently accessed data for performance"
- "The component MAY support OAuth2 authentication as an optional enhancement"
## 3. Interface Contract
[API endpoints, data models, component interfaces]
- External interfaces (API contracts from api-designer)

View File

@@ -0,0 +1,22 @@
{
"version": "1.0",
"description": "Terminology glossary schema for brainstorm guidance-specification",
"schema": {
"terminology": {
"type": "array",
"items": {
"term": "string (required) - canonical term",
"definition": "string (required) - concise definition",
"aliases": "array of strings - alternative names",
"category": "enum: core|technical|business (required)",
"first_used_in": "string - source document"
}
}
},
"validation_rules": {
"min_terms": 5,
"max_terms": 20,
"term_format": "lowercase, alphanumeric + hyphens",
"definition_max_length": 200
}
}

View File

@@ -77,7 +77,7 @@ CCW 命令帮助系统提供命令搜索、推荐、文档查看、Skill/Team
- **With-File Workflows**: Documented exploration with multi-CLI collaboration
- `brainstorm-with-file`: Multi-perspective ideation → workflow-plan → workflow-execute
- `debug-with-file`: Hypothesis-driven debugging (standalone)
- `analyze-with-file`: Collaborative analysis → workflow-lite-planex
- `analyze-with-file`: Collaborative analysis → workflow-lite-plan
- `collaborative-plan-with-file`: Multi-agent planning → unified-execute
- `roadmap-with-file`: Strategic requirement roadmap → team-planex
- **Issue Workflow**: Batch issue discovery, planning, queueing, execution
@@ -131,7 +131,7 @@ Single source of truth: **[command.json](command.json)**
| Skill | 内部流水线 | 触发词 |
|-------|-----------|--------|
| `workflow-lite-planex` | explore → plan → confirm → execute | "lite-plan", 快速任务 |
| `workflow-lite-plan` | explore → plan → confirm → execute | "lite-plan", 快速任务 |
| `workflow-plan` | session → context → convention → gen → verify | "workflow-plan", 正式规划 |
| `workflow-execute` | session discovery → task processing → commit | "workflow-execute", 执行 |
| `workflow-tdd-plan` | 6-phase TDD plan → verify | "tdd-plan", TDD 开发 |
@@ -186,9 +186,9 @@ CCW 根据任务意图自动选择工作流级别(参考 [ccw.md](../../comman
| 输入示例 | 类型 | 级别 | 流水线 |
|---------|------|------|--------|
| "Add API endpoint" | feature (low) | 2 | workflow-lite-planex → workflow-test-fix |
| "Fix login timeout" | bugfix | 2 | workflow-lite-planex → workflow-test-fix |
| "协作分析: 认证架构" | analyze-file | 3 | analyze-with-file → workflow-lite-planex |
| "Add API endpoint" | feature (low) | 2 | workflow-lite-plan → workflow-test-fix |
| "Fix login timeout" | bugfix | 2 | workflow-lite-plan → workflow-test-fix |
| "协作分析: 认证架构" | analyze-file | 3 | analyze-with-file → workflow-lite-plan |
| "重构 auth 模块" | refactor | 3 | workflow:refactor-cycle |
| "multi-cli: API设计" | multi-cli | 3 | workflow-multi-cli-plan → workflow-test-fix |
| "头脑风暴: 通知系统" | brainstorm | 4 | brainstorm-with-file → workflow-plan → workflow-execute |

View File

@@ -955,14 +955,14 @@
"source": "../../../skills/workflow-execute/SKILL.md"
},
{
"name": "workflow-lite-planex",
"description": "Lightweight planning and execution skill (Phase 1: plan, Phase 2: execute). Triggers on \"workflow-lite-planex\".",
"name": "workflow-lite-plan",
"description": "Lightweight planning and execution skill (Phase 1: plan, Phase 2: execute). Triggers on \"workflow-lite-plan\".",
"category": "workflow",
"is_team": false,
"has_phases": true,
"has_role_specs": false,
"version": "",
"source": "../../../skills/workflow-lite-planex/SKILL.md"
"source": "../../../skills/workflow-lite-plan/SKILL.md"
},
{
"name": "workflow-multi-cli-plan",

View File

@@ -290,14 +290,14 @@
"source": "../../../skills/workflow-execute/SKILL.md"
},
{
"name": "workflow-lite-planex",
"description": "Lightweight planning and execution skill (Phase 1: plan, Phase 2: execute). Triggers on \"workflow-lite-planex\".",
"name": "workflow-lite-plan",
"description": "Lightweight planning and execution skill (Phase 1: plan, Phase 2: execute). Triggers on \"workflow-lite-plan\".",
"category": "workflow",
"is_team": false,
"has_phases": true,
"has_role_specs": false,
"version": "",
"source": "../../../skills/workflow-lite-planex/SKILL.md"
"source": "../../../skills/workflow-lite-plan/SKILL.md"
},
{
"name": "workflow-multi-cli-plan",

View File

@@ -70,7 +70,7 @@
"workflow:session:list"
]
},
"workflow-lite-planex": {
"workflow-lite-plan": {
"calls_internally": [],
"next_steps": [
"workflow:session:list"

View File

@@ -301,14 +301,14 @@
"source": "../../../skills/workflow-execute/SKILL.md"
},
{
"name": "workflow-lite-planex",
"description": "Lightweight planning and execution skill (Phase 1: plan, Phase 2: execute). Triggers on \"workflow-lite-planex\".",
"name": "workflow-lite-plan",
"description": "Lightweight planning and execution skill (Phase 1: plan, Phase 2: execute). Triggers on \"workflow-lite-plan\".",
"category": "workflow",
"is_team": false,
"has_phases": true,
"has_role_specs": false,
"version": "",
"source": "../../../skills/workflow-lite-planex/SKILL.md"
"source": "../../../skills/workflow-lite-plan/SKILL.md"
},
{
"name": "workflow-multi-cli-plan",

View File

@@ -239,7 +239,7 @@ def build_command_relationships() -> Dict[str, Any]:
"alternatives": ["workflow:resume"],
"related": ["workflow:session:list", "workflow:status"]
},
"workflow-lite-planex": {
"workflow-lite-plan": {
"calls_internally": [],
"next_steps": ["workflow:status"],
"alternatives": ["workflow-plan"],
@@ -247,7 +247,7 @@ def build_command_relationships() -> Dict[str, Any]:
},
"workflow:lite-fix": {
"next_steps": ["workflow:status"],
"alternatives": ["workflow-lite-planex"],
"alternatives": ["workflow-lite-plan"],
"related": ["workflow-test-fix"]
},
"workflow:review-session-cycle": {
@@ -272,7 +272,7 @@ 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-planex", "workflow:lite-fix", "workflow-plan",
"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",

View File

@@ -0,0 +1,56 @@
---
name: skill-simplify
description: SKILL.md simplification with functional integrity verification. Analyze redundancy, optimize content, check no functionality lost. Triggers on "simplify skill", "optimize skill", "skill-simplify".
allowed-tools: AskUserQuestion, Read, Write, Edit, Bash, Glob, Grep
---
# Skill Simplify
Three-phase pipeline: analyze functional inventory, apply optimization rules, verify integrity.
**Phase Reference Documents** (read on-demand):
| Phase | Document | Purpose |
|-------|----------|---------|
| 1 | [phases/01-analysis.md](phases/01-analysis.md) | Extract functional inventory, identify redundancy, validate pseudo-code format |
| 2 | [phases/02-optimize.md](phases/02-optimize.md) | Apply simplification rules, fix format issues |
| 3 | [phases/03-check.md](phases/03-check.md) | Verify functional integrity, validate format |
## Input Processing
```javascript
const targetPath = input.trim()
const targetFile = targetPath.endsWith('.md') ? targetPath : `${targetPath}/SKILL.md`
const originalContent = Read(targetFile)
const originalLineCount = originalContent.split('\n').length
```
## TodoWrite Pattern
```javascript
TodoWrite({ todos: [
{ content: `Phase 1: Analyzing ${targetFile}`, status: "in_progress", activeForm: "Extracting functional inventory" },
{ content: "Phase 2: Optimize", status: "pending" },
{ content: "Phase 3: Integrity Check", status: "pending" }
]})
```
## Core Rules
1. **Preserve ALL functional elements**: Code blocks with logic, agent calls, data structures, routing, error handling, input/output specs
2. **Only reduce descriptive content**: Flowcharts, verbose comments, duplicate sections, examples that repeat logic
3. **Never summarize algorithm logic**: If-else branches, function bodies, schemas must remain verbatim
4. **Classify code blocks**: Distinguish `functional` (logic, routing, schemas) from `descriptive` (ASCII art, examples, display templates) — only descriptive blocks may be deleted
5. **Merge equivalent variants**: Single/multi-perspective templates differing only by a parameter → one template with variant comment
6. **Fix format issues**: Nested backtick template literals in code fences → convert to prose; hardcoded option lists → flag for dynamic generation; workflow handoff references → ensure execution steps present
7. **Validate pseudo-code**: Check bracket matching, variable consistency, structural completeness
8. **Quantitative verification**: Phase 3 counts must match Phase 1 counts for functional categories; descriptive block decreases are expected
## Error Handling
| Error | Resolution |
|-------|------------|
| Target file not found | Report error, stop |
| Check FAIL (missing functional elements) | Show delta, revert to original, report which elements lost |
| Check WARN (descriptive decrease or merge) | Show delta with justification |
| Format issues found | Report in check, fix in Phase 2 |

View File

@@ -0,0 +1,224 @@
# Phase 1: Functional Analysis
Read target file, extract functional inventory with code block classification, identify redundancy, validate pseudo-code format, and produce optimization plan.
## Objective
- Build quantitative functional inventory with code block classification (baseline for Phase 3)
- Identify redundancy categories with specific line ranges
- Detect pseudo-code format issues
- Produce optimization plan with estimated line savings
## Execution
### Step 1.1: Read & Measure Target
```javascript
const originalContent = Read(targetFile)
const lines = originalContent.split('\n')
const originalLineCount = lines.length
```
### Step 1.2: Extract Functional Inventory
Count and catalog every functional element. These counts are the **baseline** for Phase 3 verification.
```javascript
const inventory = {
// Code structures — with role classification
codeBlocks: [], // { startLine, endLine, language, purpose, role: 'functional'|'descriptive' }
agentCalls: [], // { line, agentType, description, mergeGroup?: string }
dataStructures: [], // { line, name, type: 'object'|'array'|'schema' }
// Logic elements
routingBranches: [], // { line, condition, outcomes[] }
errorHandlers: [], // { line, errorType, resolution }
conditionalLogic: [], // { line, condition, trueAction, falseAction }
// Interface elements
askUserQuestions: [], // { line, questionCount, headers[], optionType: 'static'|'dynamic' }
inputModes: [], // { line, mode, description }
outputArtifacts: [], // { line, artifact, format }
// Structural elements
todoWriteBlocks: [], // { line, phaseCount }
phaseHandoffs: [], // { line, fromPhase, toPhase }
skillInvocations: [], // { line, skillName, hasExecutionSteps: boolean }
// Reference elements
tables: [], // { startLine, endLine, columns }
schemas: [], // { line, schemaName, fields[] }
// Format issues
formatIssues: [], // { line, type, description, severity: 'error'|'warning' }
// Totals (computed)
counts: {}
}
```
**Extraction rules**:
- **Code blocks**: Match ` ```language ... ``` ` pairs, record start/end/language/first-line-as-purpose
- **Agent calls**: Match `Agent(`, `Task(`, `subagent_type=`, record type and prompt summary
- **Data structures**: Match `const xxx = {`, `const xxx = [`, JSON schema objects
- **Routing branches**: Match `if/else`, `switch/case`, ternary `? :` with meaningful branching
- **Error handlers**: Match `catch`, error table rows `| Error |`, fallback patterns
- **AskUserQuestion**: Match `AskUserQuestion({`, count questions array length
- **Input modes**: Match `Mode 1/2/3`, `--flag`, argument parsing
- **Output artifacts**: Match `Write(`, `Output:`, file path patterns in comments
- **TodoWrite**: Match `TodoWrite({`, count todo items
- **Phase handoffs**: Match `Read("phases/`, `Skill(`, `proceed_to_next_phase`
- **Tables**: Match `| header |` markdown table blocks
- **Schemas**: Match schema references, JSON structure definitions
### Step 1.2.1: Code Block Role Classification
For each code block, determine its role:
| Role | Criteria | Examples |
|------|----------|---------|
| `functional` | Contains algorithm logic, routing branches, conditional code, agent calls, schema definitions, data processing, AskUserQuestion, Skill invocations | `if/else`, `Agent({...})`, `const schema = {...}`, `Bash({...})` |
| `descriptive` | Contains ASCII art, usage examples, display templates, illustrative good/bad comparisons, folder structure trees | `┌───┐`, `# Example usage`, `❌ Bad / ✅ Good`, `├── file.ts` |
**Classification rules**:
- If block contains ANY of: `Agent(`, `Bash(`, `AskUserQuestion(`, `if (`, `switch`, `Skill(`, `Write(`, `Read(`, `TodoWrite(``functional`
- If block language is `bash` and content is only example invocations (no logic) → `descriptive`
- If block has no language tag and contains only ASCII box-drawing characters → `descriptive`
- If block is labeled as "Example" in surrounding markdown heading → `descriptive`
- **Default**: `functional` (conservative)
### Step 1.2.2: Pseudo-Code Format Validation
Scan all `functional` code blocks for format issues:
| Check | Detection | Severity |
|-------|-----------|----------|
| **Nested backticks** | Template literal `` ` `` inside ` ```javascript ``` ` code fence | warning |
| **Unclosed brackets** | Unmatched `{`, `(`, `[` in code block | error |
| **Undefined references** | `${variable}` where variable is never declared in the block or prior blocks | warning |
| **Inconsistent indentation** | Mixed tabs/spaces or inconsistent nesting depth | warning |
| **Dead code patterns** | Commented-out code blocks (`// if (`, `/* ... */` spanning 5+ lines) | warning |
| **Missing return/output** | Function-like block with no return, Write, or console.log | warning |
```javascript
inventory.formatIssues = validatePseudoCode(inventory.codeBlocks.filter(b => b.role === 'functional'))
```
### Step 1.2.3: Compute Totals
```javascript
inventory.counts = {
codeBlocks: inventory.codeBlocks.length,
functionalCodeBlocks: inventory.codeBlocks.filter(b => b.role === 'functional').length,
descriptiveCodeBlocks: inventory.codeBlocks.filter(b => b.role === 'descriptive').length,
agentCalls: inventory.agentCalls.length,
dataStructures: inventory.dataStructures.length,
routingBranches: inventory.routingBranches.length,
errorHandlers: inventory.errorHandlers.length,
conditionalLogic: inventory.conditionalLogic.length,
askUserQuestions: inventory.askUserQuestions.length,
inputModes: inventory.inputModes.length,
outputArtifacts: inventory.outputArtifacts.length,
todoWriteBlocks: inventory.todoWriteBlocks.length,
phaseHandoffs: inventory.phaseHandoffs.length,
skillInvocations: inventory.skillInvocations.length,
tables: inventory.tables.length,
schemas: inventory.schemas.length,
formatIssues: inventory.formatIssues.length
}
```
### Step 1.3: Identify Redundancy Categories
Scan for each category, record specific line ranges:
```javascript
const redundancyMap = {
deletable: [], // { category, startLine, endLine, reason, estimatedSave }
simplifiable: [], // { category, startLine, endLine, strategy, estimatedSave }
mergeable: [], // { items: [{startLine, endLine}], mergeStrategy, estimatedSave }
formatFixes: [], // { line, type, fix }
languageUnify: [] // { line, currentLang, targetLang }
}
```
**Deletable** (remove entirely, no functional loss):
| Pattern | Detection |
|---------|-----------|
| Duplicate Overview | `## Overview` that restates frontmatter description |
| ASCII flowchart | Flowchart that duplicates Phase Summary table or implementation structure |
| "When to use" section | Usage guidance not needed for execution |
| Best Practices section | Advisory content duplicating Core Rules |
| Duplicate examples | Code examples that repeat logic shown elsewhere |
| Folder structure duplicate | ASCII tree repeating Output Artifacts table |
| "Next Phase" paragraphs | Prose between phases when TodoWrite handles flow |
| Descriptive code blocks | Code blocks classified as `descriptive` whose content is covered by surrounding prose or tables |
**Simplifiable** (compress, preserve meaning):
| Pattern | Strategy |
|---------|----------|
| Verbose comments in code blocks | Reduce to single-line; keep only non-obvious logic comments |
| Multi-line console.log | Compress to single template literal |
| Wordy section intros | Remove "In this phase, we will..." preamble |
| Exploration prompt bloat | Trim to essential instructions, remove generic advice |
| Display-format code blocks | Convert code blocks that only define output format (console.log with template) to prose description |
**Mergeable** (combine related structures):
| Pattern | Strategy |
|---------|----------|
| Multiple similar AskUserQuestion calls | Extract shared function with mode parameter |
| Repeated Option routing | Unify into single dispatch |
| Sequential single-line operations | Combine into one code block |
| TodoWrite full blocks x N | Template once + delta comments |
| Duplicate error handling tables | Merge into single table |
| Equivalent template variants | Single/multi-perspective templates → one template with variant comment |
| Multiple output artifact tables | Merge into single combined table |
**Format fixes** (pseudo-code quality):
| Pattern | Fix |
|---------|-----|
| Nested backtick template literals | Convert surrounding code block to prose description, or use 4-backtick fence |
| Hardcoded option lists | Add comment: `// Generate dynamically from {context source}` |
| Workflow handoff without execution steps | Add execution steps referencing the target command's actual interface |
| Unclosed brackets | Fix bracket matching |
**Language unification**:
- Detect mixed Chinese/English in functional comments
- Recommend consistent language (match majority)
### Step 1.4: Build Optimization Plan
```javascript
const optimizationPlan = {
targetFile,
originalLineCount,
estimatedReduction: redundancyMap.deletable.reduce((s, d) => s + d.estimatedSave, 0)
+ redundancyMap.simplifiable.reduce((s, d) => s + d.estimatedSave, 0)
+ redundancyMap.mergeable.reduce((s, d) => s + d.estimatedSave, 0),
categories: {
deletable: { count: redundancyMap.deletable.length, totalLines: '...' },
simplifiable: { count: redundancyMap.simplifiable.length, totalLines: '...' },
mergeable: { count: redundancyMap.mergeable.length, totalLines: '...' },
formatFixes: { count: redundancyMap.formatFixes.length },
languageUnify: { count: redundancyMap.languageUnify.length }
},
// Ordered: delete → merge → simplify → format
operations: [
...redundancyMap.deletable.map(d => ({ type: 'delete', ...d, priority: 1 })),
...redundancyMap.mergeable.map(m => ({ type: 'merge', ...m, priority: 2 })),
...redundancyMap.simplifiable.map(s => ({ type: 'simplify', ...s, priority: 3 })),
...redundancyMap.formatFixes.map(f => ({ type: 'format', ...f, priority: 4 }))
]
}
```
Display plan summary: category counts, estimated reduction percentage, sections NOT changed (functional core).
## Output
- **Variable**: `analysisResult = { inventory, redundancyMap, optimizationPlan, originalContent, originalLineCount }`
- **TodoWrite**: Mark Phase 1 completed, Phase 2 in_progress

View File

@@ -0,0 +1,107 @@
# Phase 2: Optimize
Apply simplification rules from analysisResult to produce optimized content. Write result to disk.
## Objective
- Execute all optimization operations in priority order (delete → merge → simplify → format)
- Preserve every functional element identified in Phase 1 inventory
- Fix pseudo-code format issues
- Write optimized content back to target file
## Execution
### Step 2.1: Apply Operations in Order
Process `analysisResult.optimizationPlan.operations` sorted by priority:
**Priority 1 — Delete** (safest, highest impact):
| Target Pattern | Action |
|----------------|--------|
| Duplicate Overview section | Remove `## Overview` if it restates frontmatter `description` |
| ASCII flowchart | Remove if Phase Summary table or implementation structure covers same info |
| "When to use" / "Use Cases" section | Remove entirely |
| Best Practices section | Remove if content duplicates Core Rules |
| Duplicate folder structure | Remove ASCII tree if Output Artifacts table covers same info |
| Redundant "Next Phase" prose | Remove when TodoWrite handles flow |
| Standalone example sections | Remove if logic already demonstrated inline |
| Descriptive code blocks | Remove if content covered by surrounding prose or tables |
**Priority 2 — Merge** (structural optimization):
| Target Pattern | Action |
|----------------|--------|
| Multiple similar AskUserQuestion blocks | Extract shared function with mode parameter |
| Repeated Option A/B/C routing | Unify into single dispatch |
| Sequential single-line bash commands | Combine into single code block |
| TodoWrite full blocks x N | Template ONCE, subsequent as one-line comment |
| Duplicate error handling across sections | Merge into single `## Error Handling` table |
| Equivalent template variants | Single/multi templates → one template with `// For multi: add Perspective` comment |
| Multiple output artifact tables | Merge into single combined table with Phase column |
**Priority 3 — Simplify** (compress descriptive content):
| Target Pattern | Action |
|----------------|--------|
| Verbose inline comments | Reduce to single-line; remove obvious restatements |
| Display-format code blocks | Convert `console.log` with template literal to prose describing output format |
| Wordy section introductions | Remove preamble sentences |
| Exploration/agent prompt padding | Remove generic advice |
| Success Criteria lists > 7 items | Trim to essential 5-7, remove obvious/generic |
**Priority 4 — Format fixes** (pseudo-code quality):
| Target Pattern | Action |
|----------------|--------|
| Nested backtick template literals | Convert code block to prose description, or use 4-backtick fence |
| Hardcoded option lists | Replace with dynamic generation: describe source of options + generation logic |
| Workflow handoff without execution steps | Add concrete steps referencing target command's interface (e.g., pipe to `ccw issue create`) |
| Unclosed brackets | Fix bracket matching |
| Undefined variable references | Add declaration or link to source |
### Step 2.2: Language Unification (if applicable)
```javascript
if (analysisResult.redundancyMap.languageUnify.length > 0) {
// Detect majority language, unify non-functional text
// DO NOT change: variable names, function names, schema fields, error messages in code
}
```
### Step 2.3: Write Optimized Content
```javascript
Write(targetFile, optimizedContent)
const optimizedLineCount = optimizedContent.split('\n').length
const reduction = originalLineCount - optimizedLineCount
const reductionPct = Math.round(reduction / originalLineCount * 100)
```
### Step 2.4: Preserve Optimization Record
```javascript
const optimizationRecord = {
deletedSections: [], // section names removed
mergedGroups: [], // { from: [sections], to: description }
simplifiedAreas: [], // { section, strategy }
formatFixes: [], // { line, type, fix }
linesBefore: originalLineCount,
linesAfter: optimizedLineCount
}
```
## Key Rules
1. **Never modify functional code blocks** — only compress comments/whitespace within them
2. **Descriptive code blocks may be deleted** if their content is covered by prose or tables
3. **Never change function signatures, variable names, or schema fields**
4. **Merge preserves all branches** — unified function must handle all original cases
5. **When uncertain, keep original** — conservative approach prevents functional loss
6. **Format fixes must not alter semantics** — only presentation changes
## Output
- **File**: Target file overwritten with optimized content
- **Variable**: `optimizationRecord` (changes log for Phase 3)
- **TodoWrite**: Mark Phase 2 completed, Phase 3 in_progress

View File

@@ -0,0 +1,224 @@
# Phase 3: Integrity Check
Re-extract functional inventory from optimized file, compare against Phase 1 baseline, validate pseudo-code format. Report PASS/FAIL with detailed delta.
## Objective
- Re-run the same inventory extraction on optimized content
- Compare counts using role-aware classification (functional vs descriptive)
- Validate pseudo-code format issues are resolved
- Report check result with actionable details
- Revert if critical functional elements are missing
## Execution
### Step 3.1: Re-Extract Inventory from Optimized File
```javascript
const optimizedContent = Read(targetFile)
const optimizedLineCount = optimizedContent.split('\n').length
// Use SAME extraction logic as Phase 1 (including role classification)
const afterInventory = extractFunctionalInventory(optimizedContent)
```
### Step 3.2: Compare Inventories (Role-Aware)
```javascript
const beforeCounts = analysisResult.inventory.counts
const afterCounts = afterInventory.counts
const delta = {}
let hasCriticalLoss = false
let hasWarning = false
// CRITICAL: Functional elements that MUST NOT decrease
const CRITICAL = ['functionalCodeBlocks', 'dataStructures', 'routingBranches',
'errorHandlers', 'conditionalLogic', 'askUserQuestions',
'inputModes', 'outputArtifacts', 'skillInvocations']
// MERGE_AWARE: May decrease due to valid merge operations — verify coverage
const MERGE_AWARE = ['agentCalls', 'codeBlocks']
// EXPECTED_DECREASE: May decrease from merge/consolidation
const EXPECTED_DECREASE = ['descriptiveCodeBlocks', 'todoWriteBlocks',
'phaseHandoffs', 'tables', 'schemas']
for (const [key, before] of Object.entries(beforeCounts)) {
const after = afterCounts[key] || 0
const diff = after - before
let category, status
if (CRITICAL.includes(key)) {
category = 'critical'
status = diff < 0 ? 'FAIL' : 'OK'
if (diff < 0) hasCriticalLoss = true
} else if (MERGE_AWARE.includes(key)) {
category = 'merge_aware'
// Decrease is WARN (needs justification), not FAIL
status = diff < 0 ? 'WARN' : 'OK'
if (diff < 0) hasWarning = true
} else {
category = 'expected'
status = 'OK' // Descriptive decreases are expected
}
delta[key] = { before, after, diff, category, status }
}
```
### Step 3.3: Deep Verification
**For CRITICAL categories with decrease** — identify exactly what was lost:
```javascript
if (hasCriticalLoss) {
const lostElements = {}
for (const [key, d] of Object.entries(delta)) {
if (d.status === 'FAIL') {
const beforeItems = analysisResult.inventory[key]
const afterItems = afterInventory[key]
lostElements[key] = beforeItems.filter(beforeItem =>
!afterItems.some(afterItem => matchesElement(beforeItem, afterItem))
)
}
}
}
```
**For MERGE_AWARE categories with decrease** — verify merged coverage:
```javascript
if (hasWarning) {
for (const [key, d] of Object.entries(delta)) {
if (d.category === 'merge_aware' && d.diff < 0) {
// Check if merged template covers all original variants
// e.g., single Agent template with "// For multi: add Perspective" covers both
const beforeItems = analysisResult.inventory[key]
const afterItems = afterInventory[key]
const unmatched = beforeItems.filter(beforeItem =>
!afterItems.some(afterItem => matchesElement(beforeItem, afterItem))
)
if (unmatched.length > 0) {
// Check if unmatched items are covered by merge comments in remaining items
const mergeComments = afterItems.flatMap(item => extractMergeComments(item))
const trulyLost = unmatched.filter(item =>
!mergeComments.some(comment => coversElement(comment, item))
)
if (trulyLost.length > 0) {
delta[key].status = 'FAIL'
hasCriticalLoss = true
delta[key].trulyLost = trulyLost
}
// else: merge-covered, WARN is correct
}
}
}
}
```
### Step 3.4: Pseudo-Code Format Validation
```javascript
const afterFormatIssues = validatePseudoCode(afterInventory.codeBlocks.filter(b => b.role === 'functional'))
const beforeFormatCount = analysisResult.inventory.formatIssues.length
const afterFormatCount = afterFormatIssues.length
const formatDelta = {
before: beforeFormatCount,
after: afterFormatCount,
resolved: beforeFormatCount - afterFormatCount,
newIssues: afterFormatIssues.filter(issue =>
!analysisResult.inventory.formatIssues.some(orig => orig.line === issue.line && orig.type === issue.type)
)
}
// New format issues introduced by optimization = FAIL
if (formatDelta.newIssues.length > 0) {
hasCriticalLoss = true
}
```
**Pseudo-code validation checks**:
| Check | Detection | Action on Failure |
|-------|-----------|-------------------|
| Bracket matching | Count `{([` vs `})]` per code block | FAIL — fix or revert |
| Variable consistency | `${var}` used but never declared | WARNING — note in report |
| Structural completeness | Function body has entry but no exit (return/Write/output) | WARNING |
| Nested backtick resolution | Backtick template literals inside code fences | WARNING if pre-existing, FAIL if newly introduced |
| Schema field preservation | Schema fields in after match before | FAIL if fields lost |
### Step 3.5: Generate Check Report
```javascript
const status = hasCriticalLoss ? 'FAIL' : (hasWarning ? 'WARN' : 'PASS')
const checkReport = {
status,
linesBefore: analysisResult.originalLineCount,
linesAfter: optimizedLineCount,
reduction: `${analysisResult.originalLineCount - optimizedLineCount} lines (-${Math.round((analysisResult.originalLineCount - optimizedLineCount) / analysisResult.originalLineCount * 100)}%)`,
delta,
formatDelta,
lostElements: hasCriticalLoss ? lostElements : null
}
// Display report table
// | Category | Before | After | Delta | Status |
// Show all categories, highlight FAIL/WARN rows
// Show format issues summary if any
```
### Step 3.6: Act on Result
```javascript
if (status === 'FAIL') {
Write(targetFile, analysisResult.originalContent)
// Report: "Critical elements lost / new format issues introduced. Reverted."
}
if (status === 'WARN') {
// Report: "Decreases from merge/descriptive removal. Verify coverage."
// Show merge justifications for MERGE_AWARE categories
}
if (status === 'PASS') {
// Report: "All functional elements preserved. Optimization successful."
}
```
## Element Matching Rules
How `matchesElement()` determines if a before-element exists in after-inventory:
| Element Type | Match Criteria |
|-------------|---------------|
| codeBlocks | Same language + first meaningful line (ignore whitespace/comments) |
| agentCalls | Same agentType + similar prompt keywords (>60% overlap) |
| dataStructures | Same variable name OR same field set |
| routingBranches | Same condition expression (normalized) |
| errorHandlers | Same error type/pattern |
| conditionalLogic | Same condition + same outcome set |
| askUserQuestions | Same question count + similar option labels |
| inputModes | Same mode identifier |
| outputArtifacts | Same file path pattern or artifact name |
| skillInvocations | Same skill name |
| todoWriteBlocks | Same phase names (order-independent) |
| phaseHandoffs | Same target phase reference |
| tables | Same column headers |
| schemas | Same schema name or field set |
**Merge coverage check** (`coversElement()`):
- Agent calls: Merged template contains `// For multi:` or `// Multi-perspective:` comment referencing the missing variant
- Code blocks: Merged block contains comment noting the alternative was folded in
## Completion
```javascript
TodoWrite({ todos: [
{ content: `Phase 1: Analysis [${Object.keys(analysisResult.inventory.counts).length} categories]`, status: "completed" },
{ content: `Phase 2: Optimize [${checkReport.reduction}]`, status: "completed" },
{ content: `Phase 3: Check [${checkReport.status}] | Format: ${formatDelta.resolved} resolved, ${formatDelta.newIssues.length} new`, status: "completed" }
]})
```

View File

@@ -17,33 +17,42 @@ Structured specification document generator producing a complete document chain
spec-generator/
|- SKILL.md # Entry point: metadata + architecture + flow
|- phases/
| |- 01-discovery.md # Seed analysis + codebase exploration
| |- 02-product-brief.md # Multi-CLI product brief generation
| |- 03-requirements.md # PRD with MoSCoW priorities
| |- 04-architecture.md # Architecture decisions + review
| |- 01-discovery.md # Seed analysis + codebase exploration + spec type selection
| |- 01-5-requirement-clarification.md # Interactive requirement expansion
| |- 02-product-brief.md # Multi-CLI product brief + glossary generation
| |- 03-requirements.md # PRD with MoSCoW priorities + RFC 2119 constraints
| |- 04-architecture.md # Architecture + state machine + config model + observability
| |- 05-epics-stories.md # Epic/Story decomposition
| |- 06-readiness-check.md # Quality validation + handoff
| |- 06-readiness-check.md # Quality validation + handoff + iterate option
| |- 06-5-auto-fix.md # Auto-fix loop for readiness issues (max 2 iterations)
|- specs/
| |- document-standards.md # Format, frontmatter, naming rules
| |- quality-gates.md # Per-phase quality criteria
| |- quality-gates.md # Per-phase quality criteria + iteration tracking
| |- glossary-template.json # Terminology glossary schema
|- templates/
| |- product-brief.md # Product brief template
| |- product-brief.md # Product brief template (+ Concepts & Non-Goals)
| |- requirements-prd.md # PRD template
| |- architecture-doc.md # Architecture document template
| |- epics-template.md # Epic/Story template
| |- architecture-doc.md # Architecture template (+ state machine, config, observability)
| |- epics-template.md # Epic/Story template (+ versioning)
| |- profiles/ # Spec type specialization profiles
| |- service-profile.md # Service spec: lifecycle, observability, trust
| |- api-profile.md # API spec: endpoints, auth, rate limiting
| |- library-profile.md # Library spec: public API, examples, compatibility
|- README.md # This file
```
## 6-Phase Pipeline
| Phase | Name | Output | CLI Tools |
|-------|------|--------|-----------|
| 1 | Discovery | spec-config.json | Gemini (analysis) |
| 2 | Product Brief | product-brief.md | Gemini + Codex + Claude (parallel) |
| 3 | Requirements | requirements.md | Gemini (analysis) |
| 4 | Architecture | architecture.md | Gemini + Codex (sequential) |
| 5 | Epics & Stories | epics.md | Gemini (analysis) |
| 6 | Readiness Check | readiness-report.md, spec-summary.md | Gemini (validation) |
| Phase | Name | Output | CLI Tools | Key Features |
|-------|------|--------|-----------|-------------|
| 1 | Discovery | spec-config.json | Gemini (analysis) | Spec type selection |
| 1.5 | Req Expansion | refined-requirements.json | Gemini (analysis) | Multi-round interactive |
| 2 | Product Brief | product-brief.md, glossary.json | Gemini + Codex + Claude (parallel) | Terminology glossary |
| 3 | Requirements | requirements/ | Gemini (analysis) | RFC 2119, data model |
| 4 | Architecture | architecture/ | Gemini + Codex (sequential) | State machine, config, observability |
| 5 | Epics & Stories | epics/ | Gemini (analysis) | Glossary consistency |
| 6 | Readiness Check | readiness-report.md, spec-summary.md | Gemini (validation) | Terminology + scope validation |
| 6.5 | Auto-Fix | Updated phase docs | Gemini (analysis) | Max 2 iterations |
## Runtime Output
@@ -51,12 +60,21 @@ spec-generator/
.workflow/.spec/SPEC-{slug}-{YYYY-MM-DD}/
|- spec-config.json # Session state
|- discovery-context.json # Codebase context (optional)
|- refined-requirements.json # Phase 1.5 (requirement expansion)
|- glossary.json # Phase 2 (terminology)
|- product-brief.md # Phase 2
|- requirements.md # Phase 3
|- architecture.md # Phase 4
|- epics.md # Phase 5
|- requirements/ # Phase 3 (directory)
| |- _index.md
| |- REQ-*.md
| └── NFR-*.md
|- architecture/ # Phase 4 (directory)
| |- _index.md
| └── ADR-*.md
|- epics/ # Phase 5 (directory)
| |- _index.md
| └── EPIC-*.md
|- readiness-report.md # Phase 6
|- spec-summary.md # Phase 6
└── spec-summary.md # Phase 6
```
## Flags
@@ -64,10 +82,13 @@ spec-generator/
- `-y|--yes`: Auto mode - skip all interactive confirmations
- `-c|--continue`: Resume from last completed phase
Spec type is selected interactively in Phase 1 (defaults to `service` in auto mode)
Available types: `service`, `api`, `library`, `platform`
## Handoff
After Phase 6, choose execution path:
- `workflow-lite-planex` - Execute per Epic
- `workflow-lite-plan` - Execute per Epic
- `workflow:req-plan-with-file` - Roadmap decomposition
- `workflow-plan` - Full planning
- `issue:new` - Create issues per Epic
@@ -79,3 +100,6 @@ After Phase 6, choose execution path:
- **Template-driven**: Consistent format via templates + frontmatter
- **Resumable**: spec-config.json tracks completed phases
- **Pure documentation**: No code generation - clean handoff to execution workflows
- **Type-specialized**: Profiles adapt templates to service/api/library/platform requirements
- **Iterative quality**: Phase 6.5 auto-fix repairs issues, max 2 iterations before handoff
- **Terminology-first**: glossary.json ensures consistent terminology across all documents

View File

@@ -14,20 +14,26 @@ Structured specification document generator producing a complete specification p
Phase 0: Specification Study (Read specs/ + templates/ - mandatory prerequisite)
|
Phase 1: Discovery -> spec-config.json + discovery-context.json
|
| (includes spec_type selection)
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 2: Product Brief -> product-brief.md + glossary.json (multi-CLI parallel analysis)
|
Phase 3: Requirements (PRD) -> requirements/ (_index.md + REQ-*.md + NFR-*.md)
|
| (RFC 2119 keywords, data model definitions)
Phase 4: Architecture -> architecture/ (_index.md + ADR-*.md, multi-CLI review)
|
| (state machine, config model, error handling, observability)
Phase 5: Epics & Stories -> epics/ (_index.md + EPIC-*.md)
|
Phase 6: Readiness Check -> readiness-report.md + spec-summary.md
|
Handoff to execution workflows
| (terminology + scope consistency validation)
├── Pass (>=80%): Handoff to execution workflows
├── Review (60-79%): Handoff with caveats
└── Fail (<60%): Phase 6.5 Auto-Fix (max 2 iterations)
|
Phase 6.5: Auto-Fix -> Updated Phase 2-5 documents
|
└── Re-run Phase 6 validation
```
## Key Design Principles
@@ -38,6 +44,9 @@ Phase 6: Readiness Check -> readiness-report.md + spec-summary.md
4. **Resumable Sessions**: `spec-config.json` tracks completed phases; `-c` flag resumes from last checkpoint
5. **Template-Driven**: All documents generated from standardized templates with YAML frontmatter
6. **Pure Documentation**: No code generation or execution - clean handoff to existing execution workflows
7. **Spec Type Specialization**: Templates adapt to spec type (service/api/library/platform) via profiles for domain-specific depth
8. **Iterative Quality**: Phase 6.5 auto-fix loop repairs issues found in readiness check (max 2 iterations)
9. **Terminology Consistency**: glossary.json generated in Phase 2, injected into all subsequent phases
---
@@ -78,6 +87,7 @@ Phase 1: Discovery & Seed Analysis
|- Parse input (text or file reference)
|- Gemini CLI seed analysis (problem, users, domain, dimensions)
|- Codebase exploration (conditional, if project detected)
|- Spec type selection: service|api|library|platform (interactive, -y defaults to service)
|- User confirmation (interactive, -y skips)
|- Output: spec-config.json, discovery-context.json (optional)
@@ -95,13 +105,17 @@ Phase 2: Product Brief
|- Ref: phases/02-product-brief.md
|- 3 parallel CLI analyses: Product (Gemini) + Technical (Codex) + User (Claude)
|- Synthesize perspectives: convergent themes + conflicts
|- Generate glossary.json (terminology from product brief + CLI analysis)
|- Interactive refinement (-y skips)
|- Output: product-brief.md (from template)
|- Output: product-brief.md (from template), glossary.json
Phase 3: Requirements / PRD
|- Ref: phases/03-requirements.md
|- Gemini CLI: expand goals into functional + non-functional requirements
|- Generate acceptance criteria per requirement
|- RFC 2119 behavioral constraints (MUST/SHOULD/MAY)
|- Core entity data model definitions
|- Glossary injection for terminology consistency
|- User priority sorting: MoSCoW (interactive, -y auto-assigns)
|- Output: requirements/ directory (_index.md + REQ-*.md + NFR-*.md, from template)
@@ -109,6 +123,12 @@ Phase 4: Architecture
|- Ref: phases/04-architecture.md
|- Gemini CLI: core components, tech stack, ADRs
|- Codebase integration mapping (conditional)
|- State machine generation (ASCII diagrams for lifecycle entities)
|- Configuration model definition (fields, types, defaults, constraints)
|- Error handling strategy (per-component classification + recovery)
|- Observability specification (metrics, logs, health checks)
|- Spec type profile injection (templates/profiles/{type}-profile.md)
|- Glossary injection for terminology consistency
|- Codex CLI: architecture challenge + review
|- Interactive ADR decisions (-y auto-accepts)
|- Output: architecture/ directory (_index.md + ADR-*.md, from template)
@@ -125,9 +145,20 @@ Phase 6: Readiness Check
|- Ref: phases/06-readiness-check.md
|- Cross-document validation (completeness, consistency, traceability)
|- Quality scoring per dimension
|- Terminology consistency validation (glossary compliance)
|- Scope containment validation (PRD <= Brief scope)
|- Output: readiness-report.md, spec-summary.md
|- Handoff options: lite-plan, req-plan, plan, issue:new, export only, iterate
Phase 6.5: Auto-Fix (conditional, triggered when Phase 6 score < 60%)
|- Ref: phases/06-5-auto-fix.md
|- Parse readiness-report.md for Error/Warning items
|- Group issues by originating Phase (2-5)
|- Re-generate affected sections via CLI with error context
|- Re-run Phase 6 validation
|- Max 2 iterations, then force handoff
|- Output: Updated Phase 2-5 documents
Complete: Full specification package ready for execution
Phase 6 → Handoff Bridge (conditional, based on user selection):
@@ -161,6 +192,7 @@ Bash(`mkdir -p "${workDir}"`);
├── spec-config.json # Session configuration + phase state
├── discovery-context.json # Codebase exploration results (optional)
├── refined-requirements.json # Phase 1.5: Confirmed requirements after discussion
├── glossary.json # Phase 2: Terminology glossary for cross-doc consistency
├── product-brief.md # Phase 2: Product brief
├── requirements/ # Phase 3: Detailed PRD (directory)
│ ├── _index.md # Summary, MoSCoW table, traceability, links
@@ -189,6 +221,9 @@ Bash(`mkdir -p "${workDir}"`);
"complexity": "moderate",
"depth": "standard",
"focus_areas": [],
"spec_type": "service",
"iteration_count": 0,
"iteration_history": [],
"seed_analysis": {
"problem_statement": "...",
"target_users": [],
@@ -217,6 +252,9 @@ Bash(`mkdir -p "${workDir}"`);
5. **DO NOT STOP**: Continuous 6-phase pipeline until all phases complete or user exits
6. **Respect -y Flag**: When auto mode, skip all AskUserQuestion calls, use recommended defaults
7. **Respect -c Flag**: When continue mode, load spec-config.json and resume from checkpoint
8. **Inject Glossary**: From Phase 3 onward, inject glossary.json terms into every CLI prompt
9. **Load Profile**: Read templates/profiles/{spec_type}-profile.md and inject requirements into Phase 2-5 prompts
10. **Iterate on Failure**: When Phase 6 score < 60%, auto-trigger Phase 6.5 (max 2 iterations)
## Reference Documents by Phase
@@ -224,6 +262,7 @@ Bash(`mkdir -p "${workDir}"`);
| Document | Purpose | When to Use |
|----------|---------|-------------|
| [phases/01-discovery.md](phases/01-discovery.md) | Seed analysis and session setup | Phase start |
| [templates/profiles/](templates/profiles/) | Spec type profiles | Spec type selection |
| [specs/document-standards.md](specs/document-standards.md) | Frontmatter format for spec-config.json | Config generation |
### Phase 1.5: Requirement Expansion & Clarification
@@ -237,6 +276,7 @@ Bash(`mkdir -p "${workDir}"`);
|----------|---------|-------------|
| [phases/02-product-brief.md](phases/02-product-brief.md) | Multi-CLI analysis orchestration | Phase start |
| [templates/product-brief.md](templates/product-brief.md) | Document template | Document generation |
| [specs/glossary-template.json](specs/glossary-template.json) | Glossary schema | Glossary generation |
### Phase 3: Requirements
| Document | Purpose | When to Use |
@@ -262,6 +302,12 @@ Bash(`mkdir -p "${workDir}"`);
| [phases/06-readiness-check.md](phases/06-readiness-check.md) | Cross-document validation | Phase start |
| [specs/quality-gates.md](specs/quality-gates.md) | Quality scoring criteria | Validation |
### Phase 6.5: Auto-Fix
| Document | Purpose | When to Use |
|----------|---------|-------------|
| [phases/06-5-auto-fix.md](phases/06-5-auto-fix.md) | Auto-fix workflow for readiness issues | When Phase 6 score < 60% |
| [specs/quality-gates.md](specs/quality-gates.md) | Iteration exit criteria | Validation |
### Debugging & Troubleshooting
| Issue | Solution Document |
|-------|-------------------|
@@ -284,6 +330,8 @@ Bash(`mkdir -p "${workDir}"`);
| Phase 4 | Architecture review fails | No | Skip review, proceed with initial analysis |
| Phase 5 | Story generation fails | No | Generate epics without detailed stories |
| Phase 6 | Validation CLI fails | No | Generate partial report with available data |
| Phase 6.5 | Auto-fix CLI fails | No | Log failure, proceed to handoff with Review status |
| Phase 6.5 | Max iterations reached | No | Force handoff, report remaining issues |
### CLI Fallback Chain

View File

@@ -185,6 +185,17 @@ if (!autoMode) {
header: "Focus",
multiSelect: true,
options: seedAnalysis.dimensions.map(d => ({ label: d, description: `Explore ${d} in depth` }))
},
{
question: "What type of specification is this?",
header: "Spec Type",
multiSelect: false,
options: [
{ label: "Service (Recommended)", description: "Long-running service with lifecycle, state machine, observability" },
{ label: "API", description: "REST/GraphQL API with endpoints, auth, rate limiting" },
{ label: "Library/SDK", description: "Reusable package with public API surface, examples" },
{ label: "Platform", description: "Multi-component system, uses Service profile" }
]
}
]
});
@@ -192,6 +203,7 @@ if (!autoMode) {
// Auto mode defaults
depth = "standard";
focusAreas = seedAnalysis.dimensions;
specType = "service"; // default for auto mode
}
```
@@ -209,6 +221,9 @@ const specConfig = {
focus_areas: focusAreas,
seed_analysis: seedAnalysis,
has_codebase: hasCodebase,
spec_type: specType, // "service" | "api" | "library" | "platform"
iteration_count: 0,
iteration_history: [],
phasesCompleted: [
{
phase: 1,

View File

@@ -227,6 +227,33 @@ specConfig.phasesCompleted.push({
Write(`${workDir}/spec-config.json`, JSON.stringify(specConfig, null, 2));
```
### Step 5.5: Generate glossary.json
```javascript
// Extract terminology from product brief and CLI analysis
// Generate structured glossary for cross-document consistency
const glossary = {
session_id: specConfig.session_id,
terms: [
// Extract from product brief content:
// - Key domain nouns from problem statement
// - User persona names
// - Technical terms from multi-perspective synthesis
// Each term should have:
// { term: "...", definition: "...", aliases: [], first_defined_in: "product-brief.md", category: "core|technical|business" }
]
};
Write(`${workDir}/glossary.json`, JSON.stringify(glossary, null, 2));
```
**Glossary Injection**: In all subsequent phase prompts, inject the following into the CONTEXT section:
```
TERMINOLOGY GLOSSARY (use these terms consistently):
${JSON.stringify(glossary.terms, null, 2)}
```
## Output
- **File**: `product-brief.md`

View File

@@ -60,6 +60,11 @@ TASK:
- Should: Important but has workaround
- Could: Nice-to-have, enhances experience
- Won't: Explicitly deferred
- Use RFC 2119 keywords (MUST, SHOULD, MAY, MUST NOT, SHOULD NOT) to define behavioral constraints for each requirement. Example: 'The system MUST return a 401 response within 100ms for invalid tokens.'
- For each core domain entity referenced in requirements, define its data model: fields, types, constraints, and relationships to other entities
- Maintain terminology consistency with the glossary below:
TERMINOLOGY GLOSSARY:
\${glossary ? JSON.stringify(glossary.terms, null, 2) : 'N/A - generate terms inline'}
MODE: analysis
EXPECTED: Structured requirements with: ID, title, description, user story, acceptance criteria, priority, traceability to goals

View File

@@ -33,6 +33,19 @@ if (specConfig.has_codebase) {
discoveryContext = JSON.parse(Read(`${workDir}/discovery-context.json`));
} catch (e) { /* no context */ }
}
// Load glossary for terminology consistency
let glossary = null;
try {
glossary = JSON.parse(Read(`${workDir}/glossary.json`));
} catch (e) { /* proceed without */ }
// Load spec type profile for specialized sections
const specType = specConfig.spec_type || 'service';
let profile = null;
try {
profile = Read(`templates/profiles/${specType}-profile.md`);
} catch (e) { /* use base template only */ }
```
### Step 2: Architecture Analysis via Gemini CLI
@@ -66,6 +79,28 @@ TASK:
- Identify security architecture: auth, authorization, data protection
- List API endpoints (high-level)
${discoveryContext ? '- Map new components to existing codebase modules' : ''}
- For each core entity with a lifecycle, create an ASCII state machine diagram showing:
- All states and transitions
- Trigger events for each transition
- Side effects of transitions
- Error states and recovery paths
- Define a Configuration Model: list all configurable fields with name, type, default value, constraint, and description
- Define Error Handling strategy:
- Classify errors (transient/permanent/degraded)
- Per-component error behavior using RFC 2119 keywords
- Recovery mechanisms
- Define Observability requirements:
- Key metrics (name, type: counter/gauge/histogram, labels)
- Structured log format and key log events
- Health check endpoints
\${profile ? \`
SPEC TYPE PROFILE REQUIREMENTS (\${specType}):
\${profile}
\` : ''}
\${glossary ? \`
TERMINOLOGY GLOSSARY (use consistently):
\${JSON.stringify(glossary.terms, null, 2)}
\` : ''}
MODE: analysis
EXPECTED: Complete architecture with: style justification, component diagram, tech stack table, ADRs, data model, security controls, API overview

View File

@@ -26,6 +26,11 @@ const specConfig = JSON.parse(Read(`${workDir}/spec-config.json`));
const productBrief = Read(`${workDir}/product-brief.md`);
const requirements = Read(`${workDir}/requirements.md`);
const architecture = Read(`${workDir}/architecture.md`);
let glossary = null;
try {
glossary = JSON.parse(Read(`${workDir}/glossary.json`));
} catch (e) { /* proceed without */ }
```
### Step 2: Epic Decomposition via Gemini CLI
@@ -69,10 +74,11 @@ TASK:
MODE: analysis
EXPECTED: Structured output with: Epic list (ID, title, priority, MVP flag), Stories per Epic (ID, user story, AC, size, trace), dependency Mermaid diagram, execution order, MVP definition
CONSTRAINTS:
CONSTRAINTS:
- Every Must-have requirement must appear in at least one Story
- Stories must be small enough to implement independently (no XL stories in MVP)
- Dependencies should be minimized across Epics
\${glossary ? \`- Maintain terminology consistency with glossary: \${glossary.terms.map(t => t.term).join(', ')}\` : ''}
" --tool gemini --mode analysis`,
run_in_background: true
});

View File

@@ -0,0 +1,144 @@
# Phase 6.5: Auto-Fix
Automatically repair specification issues identified in Phase 6 Readiness Check.
## Objective
- Parse readiness-report.md to extract Error and Warning items
- Group issues by originating Phase (2-5)
- Re-generate affected sections with error context injected into CLI prompts
- Re-run Phase 6 validation after fixes
## Input
- Dependency: `{workDir}/readiness-report.md` (Phase 6 output)
- Config: `{workDir}/spec-config.json` (with iteration_count)
- All Phase 2-5 outputs
## Execution Steps
### Step 1: Parse Readiness Report
```javascript
const readinessReport = Read(`${workDir}/readiness-report.md`);
const specConfig = JSON.parse(Read(`${workDir}/spec-config.json`));
// Load glossary for terminology consistency during fixes
let glossary = null;
try {
glossary = JSON.parse(Read(`${workDir}/glossary.json`));
} catch (e) { /* proceed without */ }
// Extract issues from readiness report
// Parse Error and Warning severity items
// Group by originating phase:
// Phase 2 issues: vision, problem statement, scope, personas
// Phase 3 issues: requirements, acceptance criteria, priority, traceability
// Phase 4 issues: architecture, ADRs, tech stack, data model, state machine
// Phase 5 issues: epics, stories, dependencies, MVP scope
const issuesByPhase = {
2: [], // product brief issues
3: [], // requirements issues
4: [], // architecture issues
5: [] // epics issues
};
// Parse structured issues from report
// Each issue: { severity: "Error"|"Warning", description: "...", location: "file:section" }
// Map phase numbers to output files
const phaseOutputFile = {
2: 'product-brief.md',
3: 'requirements/_index.md',
4: 'architecture/_index.md',
5: 'epics/_index.md'
};
```
### Step 2: Fix Affected Phases (Sequential)
For each phase with issues (in order 2 -> 3 -> 4 -> 5):
```javascript
for (const [phase, issues] of Object.entries(issuesByPhase)) {
if (issues.length === 0) continue;
const errorContext = issues.map(i => `[${i.severity}] ${i.description} (at ${i.location})`).join('\n');
// Read current phase output
const currentOutput = Read(`${workDir}/${phaseOutputFile[phase]}`);
Bash({
command: `ccw cli -p "PURPOSE: Fix specification issues identified in readiness check for Phase ${phase}.
Success: All listed issues resolved while maintaining consistency with other documents.
CURRENT DOCUMENT:
${currentOutput.slice(0, 5000)}
ISSUES TO FIX:
${errorContext}
${glossary ? `GLOSSARY (maintain consistency):
${JSON.stringify(glossary.terms, null, 2)}` : ''}
TASK:
- Address each listed issue specifically
- Maintain all existing content that is not flagged
- Ensure terminology consistency with glossary
- Preserve YAML frontmatter and cross-references
- Use RFC 2119 keywords for behavioral requirements
- Increment document version number
MODE: analysis
EXPECTED: Corrected document content addressing all listed issues
CONSTRAINTS: Minimal changes - only fix flagged issues, do not restructure unflagged sections
" --tool gemini --mode analysis`,
run_in_background: true
});
// Wait for result, apply fixes to document
// Update document version in frontmatter
}
```
### Step 3: Update State
```javascript
specConfig.phasesCompleted.push({
phase: 6.5,
name: "auto-fix",
iteration: specConfig.iteration_count,
phases_fixed: Object.keys(issuesByPhase).filter(p => issuesByPhase[p].length > 0),
completed_at: new Date().toISOString()
});
Write(`${workDir}/spec-config.json`, JSON.stringify(specConfig, null, 2));
```
### Step 4: Re-run Phase 6 Validation
```javascript
// Re-execute Phase 6: Readiness Check
// This creates a new readiness-report.md
// If still Fail and iteration_count < 2: loop back to Step 1
// If Pass or iteration_count >= 2: proceed to handoff
```
## Output
- **Updated**: Phase 2-5 documents (only affected ones)
- **Updated**: `spec-config.json` (iteration tracking)
- **Triggers**: Phase 6 re-validation
## Quality Checklist
- [ ] All Error-severity issues addressed
- [ ] Warning-severity issues attempted (best effort)
- [ ] Document versions incremented for modified files
- [ ] Terminology consistency maintained
- [ ] Cross-references still valid after fixes
- [ ] Iteration count not exceeded (max 2)
## Next Phase
Re-run [Phase 6: Readiness Check](06-readiness-check.md) to validate fixes.

View File

@@ -70,8 +70,12 @@ Perform 4-dimension validation:
2. CONSISTENCY (25%):
- Terminology uniform across documents?
- Terminology glossary compliance: all core terms used consistently per glossary.json definitions?
- No synonym drift (e.g., "user" vs "client" vs "consumer" for same concept)?
- User personas consistent?
- Scope consistent (PRD does not exceed brief)?
- Scope containment: PRD requirements do not exceed product brief's defined scope?
- Non-Goals respected: no requirement or story contradicts explicit Non-Goals?
- Tech stack references match between architecture and epics?
- Score 0-100 with inconsistencies listed
@@ -210,7 +214,7 @@ AskUserQuestion({
options: [
{
label: "Execute via lite-plan",
description: "Start implementing with /workflow-lite-planex, one Epic at a time"
description: "Start implementing with /workflow-lite-plan, one Epic at a time"
},
{
label: "Create roadmap",
@@ -223,6 +227,10 @@ AskUserQuestion({
{
label: "Create Issues",
description: "Generate issues for each Epic via /issue:new"
},
{
label: "Iterate & improve",
description: "Re-run failed phases based on readiness report issues (max 2 iterations)"
}
]
}
@@ -242,7 +250,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-planex", args=`"${title}: ${description}"`)
Skill(skill="workflow-lite-plan", args=`"${title}: ${description}"`)
}
if (selection === "Full planning" || selection === "Create roadmap") {
@@ -386,6 +394,29 @@ if (selection === "Create Issues") {
}
// If user selects "Other": Export only or return to specific phase
if (selection === "Iterate & improve") {
// Check iteration count
if (specConfig.iteration_count >= 2) {
// Max iterations reached, force handoff
// Present handoff options again without iterate
return;
}
// Update iteration tracking
specConfig.iteration_count = (specConfig.iteration_count || 0) + 1;
specConfig.iteration_history.push({
iteration: specConfig.iteration_count,
timestamp: new Date().toISOString(),
readiness_score: overallScore,
errors_found: errorCount,
phases_to_fix: affectedPhases
});
Write(`${workDir}/spec-config.json`, JSON.stringify(specConfig, null, 2));
// Proceed to Phase 6.5: Auto-Fix
// Read phases/06-5-auto-fix.md and execute
}
```
#### Helper Functions Reference (pseudocode)

View File

@@ -82,6 +82,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 |
| `glossary.json` | 2 | Terminology glossary for cross-document consistency |
| `product-brief.md` | 2 | Product brief document |
| `requirements.md` | 3 | PRD document |
| `architecture.md` | 4 | Architecture decisions document |
@@ -169,6 +170,17 @@ Derived from [REQ-001](requirements.md#req-001).
"dimensions": ["string array - 3-5 exploration dimensions"]
},
"has_codebase": "boolean",
"spec_type": "service|api|library|platform (required) - type of specification",
"iteration_count": "number (required, default 0) - number of auto-fix iterations completed",
"iteration_history": [
{
"iteration": "number",
"timestamp": "ISO8601",
"readiness_score": "number (0-100)",
"errors_found": "number",
"phases_fixed": ["number array - phase numbers that were re-generated"]
}
],
"refined_requirements_file": "string (optional) - path to refined-requirements.json",
"phasesCompleted": [
{
@@ -237,6 +249,34 @@ Derived from [REQ-001](requirements.md#req-001).
---
## glossary.json Schema
```json
{
"session_id": "string (required) - matches spec-config.json",
"generated_at": "ISO8601 (required)",
"version": "number (required, default 1) - incremented on updates",
"terms": [
{
"term": "string (required) - the canonical term",
"definition": "string (required) - concise definition",
"aliases": ["string array - acceptable alternative names"],
"first_defined_in": "string (required) - source document path",
"category": "core|technical|business (required)"
}
]
}
```
### Glossary Usage Rules
- Terms MUST be defined before first use in any document
- All documents MUST use the canonical term from glossary; aliases are for reference only
- Glossary is generated in Phase 2 and injected into all subsequent phase prompts
- Phase 6 validates glossary compliance across all documents
---
## Validation Checklist
- [ ] Every document starts with valid YAML frontmatter
@@ -246,3 +286,7 @@ Derived from [REQ-001](requirements.md#req-001).
- [ ] Heading hierarchy is correct (no skipped levels)
- [ ] Technical identifiers use correct prefixes
- [ ] Output files are in the correct directory
- [ ] `glossary.json` created with >= 5 terms
- [ ] `spec_type` field set in spec-config.json
- [ ] All documents use glossary terms consistently
- [ ] Non-Goals section present in product brief (if applicable)

View File

@@ -0,0 +1,29 @@
{
"$schema": "glossary-v1",
"description": "Template for terminology glossary used across spec-generator documents",
"session_id": "",
"generated_at": "",
"version": 1,
"terms": [
{
"term": "",
"definition": "",
"aliases": [],
"first_defined_in": "product-brief.md",
"category": "core"
}
],
"_usage_notes": {
"category_values": {
"core": "Domain-specific terms central to the product (e.g., 'Workspace', 'Session')",
"technical": "Technical terms specific to the architecture (e.g., 'gRPC', 'event bus')",
"business": "Business/process terms (e.g., 'Sprint', 'SLA', 'stakeholder')"
},
"rules": [
"Terms MUST be defined before first use in any document",
"All documents MUST use the canonical 'term' field consistently",
"Aliases are for reference only - prefer canonical term in all documents",
"Phase 6 validates glossary compliance across all documents"
]
}
}

View File

@@ -111,6 +111,9 @@ Content provides sufficient detail for execution teams.
| Success metrics | >= 2 quantifiable metrics | Warning |
| Scope boundaries | In-scope and out-of-scope listed | Warning |
| Multi-perspective | >= 2 CLI perspectives synthesized | Info |
| Terminology glossary generated | glossary.json created with >= 5 terms | Warning |
| Non-Goals section present | At least 1 non-goal with rationale | Warning |
| Concepts section present | Terminology table in product brief | Warning |
### Phase 3: Requirements (PRD)
@@ -122,6 +125,8 @@ Content provides sufficient detail for execution teams.
| Non-functional requirements | >= 1 (performance, security, etc.) | Warning |
| User stories | >= 1 per Must-have requirement | Warning |
| Traceability | Requirements trace to product brief goals | Warning |
| RFC 2119 keywords used | Behavioral requirements use MUST/SHOULD/MAY | Warning |
| Data model defined | Core entities have field-level definitions | Warning |
### Phase 4: Architecture
@@ -134,6 +139,12 @@ Content provides sufficient detail for execution teams.
| Integration points | External systems/APIs identified | Warning |
| Data model | Key entities and relationships described | Warning |
| Codebase mapping | Mapped to existing code (if has_codebase) | Info |
| State machine defined | >= 1 lifecycle state diagram (if service/platform type) | Warning |
| Configuration model defined | All config fields with type/default/constraint (if service type) | Warning |
| Error handling strategy | Per-component error classification and recovery | Warning |
| Observability metrics | >= 3 metrics defined (if service/platform type) | Warning |
| Trust model defined | Trust levels documented (if service type) | Info |
| Implementation guidance | Key decisions for implementers listed | Info |
### Phase 5: Epics & Stories
@@ -171,6 +182,8 @@ Product Brief goals -> Requirements (each goal has >= 1 requirement)
Requirements -> Architecture (each Must requirement has design coverage)
Requirements -> Epics (each Must requirement appears in >= 1 story)
Architecture ADRs -> Epics (tech choices reflected in implementation stories)
Glossary terms -> All Documents (core terms used consistently)
Non-Goals (Brief) -> Requirements + Epics (no contradictions)
```
### Consistency Checks
@@ -181,6 +194,9 @@ Architecture ADRs -> Epics (tech choices reflected in implementation stories
| User personas | Brief + PRD + Epics | Same user names/roles throughout |
| Scope | Brief + PRD | PRD scope does not exceed brief scope |
| Tech stack | Architecture + Epics | Stories reference correct technologies |
| Glossary compliance | All | Core terms match glossary.json definitions, no synonym drift |
| Scope containment | Brief + PRD | PRD requirements do not introduce scope beyond brief boundaries |
| Non-Goals respected | Brief + PRD + Epics | No requirement/story contradicts explicit Non-Goals |
### Traceability Matrix Format
@@ -217,3 +233,23 @@ Architecture ADRs -> Epics (tech choices reflected in implementation stories
- Consider additional ADR alternatives
- Story estimation hints missing
- Mermaid diagrams could be more detailed
---
## Iteration Quality Tracking
When Phase 6.5 (Auto-Fix) is triggered:
| Iteration | Expected Improvement | Max Iterations |
|-----------|---------------------|----------------|
| 1st | Fix all Error-severity issues | - |
| 2nd | Fix remaining Warnings, improve scores | Max reached |
### Iteration Exit Criteria
| Condition | Action |
|-----------|--------|
| Overall score >= 80% after fix | Pass, proceed to handoff |
| Overall score 60-79% after 2 iterations | Review, proceed with caveats |
| Overall score < 60% after 2 iterations | Fail, manual intervention required |
| No Error-severity issues remaining | Eligible for handoff regardless of score |

View File

@@ -181,6 +181,125 @@ erDiagram
| Scalability | {target} | {how measured} | [ADR-{NNN}](ADR-{NNN}-{slug}.md) |
| Reliability | {target} | {how measured} | [ADR-{NNN}](ADR-{NNN}-{slug}.md) |
## State Machine
{For each core entity with a lifecycle (e.g., Order, Session, Task):}
### {Entity} Lifecycle
```
{ASCII state diagram showing all states, transitions, triggers, and error paths}
┌──────────┐
│ Created │
└─────┬────┘
│ start()
┌──────────┐ error ┌──────────┐
│ Running │ ──────────▶ │ Failed │
└─────┬────┘ └──────────┘
│ complete()
┌──────────┐
│ Completed │
└──────────┘
```
| From State | Event | To State | Side Effects | Error Handling |
|-----------|-------|----------|-------------|----------------|
| {from} | {event} | {to} | {side_effects} | {error_behavior} |
## Configuration Model
### Required Configuration
| Field | Type | Default | Constraint | Description |
|-------|------|---------|------------|-------------|
| {field_name} | {string/number/boolean/enum} | {default_value} | {validation rule} | {description} |
### Optional Configuration
| Field | Type | Default | Constraint | Description |
|-------|------|---------|------------|-------------|
| {field_name} | {type} | {default} | {constraint} | {description} |
### Environment Variables
| Variable | Maps To | Required |
|----------|---------|----------|
| {ENV_VAR} | {config_field} | {yes/no} |
## Error Handling
### Error Classification
| Category | Severity | Retry | Example |
|----------|----------|-------|---------|
| Transient | Low | Yes, with backoff | Network timeout, rate limit |
| Permanent | High | No | Invalid configuration, auth failure |
| Degraded | Medium | Partial | Dependency unavailable, fallback active |
### Per-Component Error Strategy
| Component | Error Scenario | Behavior | Recovery |
|-----------|---------------|----------|----------|
| {component} | {scenario} | {MUST/SHOULD behavior} | {recovery strategy} |
## Observability
### Metrics
| Metric Name | Type | Labels | Description |
|-------------|------|--------|-------------|
| {metric_name} | {counter/gauge/histogram} | {label1, label2} | {what it measures} |
### Logging
| Event | Level | Fields | Description |
|-------|-------|--------|-------------|
| {event_name} | {INFO/WARN/ERROR} | {structured fields} | {when logged} |
### Health Checks
| Check | Endpoint | Interval | Failure Action |
|-------|----------|----------|----------------|
| {check_name} | {/health/xxx} | {duration} | {action on failure} |
## Trust & Safety
### Trust Levels
| Level | Description | Approval Required | Allowed Operations |
|-------|-------------|-------------------|-------------------|
| High Trust | {description} | None | {operations} |
| Standard | {description} | {approval type} | {operations} |
| Low Trust | {description} | {approval type} | {operations} |
### Security Controls
{Detailed security controls beyond the basic auth covered in Security Architecture}
## Implementation Guidance
### Key Decisions for Implementers
| Decision | Options | Recommendation | Rationale |
|----------|---------|---------------|-----------|
| {decision_area} | {option_1, option_2} | {recommended} | {why} |
### Implementation Order
1. {component/module 1}: {why first}
2. {component/module 2}: {depends on #1}
### Testing Strategy
| Layer | Scope | Tools | Coverage Target |
|-------|-------|-------|-----------------|
| Unit | {scope} | {tools} | {target} |
| Integration | {scope} | {tools} | {target} |
| E2E | {scope} | {tools} | {target} |
## Risks & Mitigations
| Risk | Impact | Probability | Mitigation |

View File

@@ -101,6 +101,19 @@ graph LR
|------|---------------|------------|
| {risk description} | [EPIC-{NNN}](EPIC-{NNN}-{slug}.md) | {mitigation} |
## Versioning & Changelog
### Version Strategy
- **Versioning Scheme**: {semver/calver/custom}
- **Breaking Change Definition**: {what constitutes a breaking change}
- **Deprecation Policy**: {how deprecated features are handled}
### Changelog
| Version | Date | Type | Description |
|---------|------|------|-------------|
| {version} | {date} | {Added/Changed/Fixed/Removed} | {description} |
## Open Questions
- [ ] {question about scope or implementation 1}

View File

@@ -30,6 +30,15 @@ dependencies:
{executive_summary - 2-3 sentences capturing the essence of the product/feature}
## Concepts & Terminology
| Term | Definition | Aliases |
|------|-----------|---------|
| {term_1} | {definition} | {comma-separated aliases if any} |
| {term_2} | {definition} | |
{Note: All documents in this specification MUST use these terms consistently.}
## Vision
{vision_statement - clear, aspirational 1-3 sentence statement of what success looks like}
@@ -70,6 +79,15 @@ dependencies:
- {explicitly excluded item 1}
- {explicitly excluded item 2}
### Non-Goals
{Explicit list of things this project will NOT do, with rationale for each:}
| Non-Goal | Rationale |
|----------|-----------|
| {non_goal_1} | {why this is explicitly excluded} |
| {non_goal_2} | {why this is explicitly excluded} |
### Assumptions
- {key assumption 1}
- {key assumption 2}
@@ -130,4 +148,6 @@ dependencies:
| `{product_name}` | Seed analysis | Product/feature name |
| `{executive_summary}` | CLI synthesis | 2-3 sentence summary |
| `{vision_statement}` | CLI product perspective | Aspirational vision |
| `{term_1}`, `{term_2}` | CLI synthesis | Domain terms with definitions and optional aliases |
| `{non_goal_1}`, `{non_goal_2}` | CLI synthesis | Explicit exclusions with rationale |
| All `{...}` fields | CLI analysis outputs | Filled from multi-perspective analysis |

View File

@@ -0,0 +1,27 @@
# API Spec Profile
Defines additional required sections for API-type specifications.
## Required Sections (in addition to base template)
### In Architecture Document
- **Endpoint Definition**: MUST list all endpoints with method, path, auth, request/response schema
- **Authentication Model**: MUST define auth mechanism (OAuth2/JWT/API Key), token lifecycle
- **Rate Limiting**: MUST define rate limits per tier/endpoint, throttling behavior
- **Error Codes**: MUST define error response format, standard error codes with descriptions
- **API Versioning**: MUST define versioning strategy (URL/header/query), deprecation policy
- **Pagination**: SHOULD define pagination strategy for list endpoints
- **Idempotency**: SHOULD define idempotency requirements for write operations
### In Requirements Document
- **Endpoint Acceptance Criteria**: Each requirement SHOULD map to specific endpoints
- **SLA Definitions**: MUST define response time, availability targets per endpoint tier
### Quality Gate Additions
| Check | Criteria | Severity |
|-------|----------|----------|
| Endpoints documented | All endpoints with method + path | Error |
| Auth model defined | Authentication mechanism specified | Error |
| Error codes defined | Standard error format + codes | Warning |
| Rate limits defined | Per-endpoint or per-tier limits | Warning |
| API versioning strategy | Versioning approach specified | Warning |

View File

@@ -0,0 +1,25 @@
# Library Spec Profile
Defines additional required sections for library/SDK-type specifications.
## Required Sections (in addition to base template)
### In Architecture Document
- **Public API Surface**: MUST define all public interfaces with signatures, parameters, return types
- **Usage Examples**: MUST provide >= 3 code examples showing common usage patterns
- **Compatibility Matrix**: MUST define supported language versions, runtime environments
- **Dependency Policy**: MUST define transitive dependency policy, version constraints
- **Extension Points**: SHOULD define plugin/extension mechanisms if applicable
- **Bundle Size**: SHOULD define target bundle size and tree-shaking strategy
### In Requirements Document
- **API Ergonomics**: Requirements SHOULD address developer experience and API consistency
- **Error Reporting**: MUST define error types, messages, and recovery hints for consumers
### Quality Gate Additions
| Check | Criteria | Severity |
|-------|----------|----------|
| Public API documented | All public interfaces with types | Error |
| Usage examples | >= 3 working examples | Warning |
| Compatibility matrix | Supported environments listed | Warning |
| Dependency policy | Transitive deps strategy defined | Info |

View File

@@ -0,0 +1,28 @@
# Service Spec Profile
Defines additional required sections for service-type specifications.
## Required Sections (in addition to base template)
### In Architecture Document
- **Concepts & Terminology**: MUST define all domain terms with consistent aliases
- **State Machine**: MUST include ASCII state diagram for each entity with a lifecycle
- **Configuration Model**: MUST define all configurable fields with types, defaults, constraints
- **Error Handling**: MUST define per-component error classification and recovery strategies
- **Observability**: MUST define >= 3 metrics, structured log format, health check endpoints
- **Trust & Safety**: SHOULD define trust levels and approval matrix
- **Graceful Shutdown**: MUST describe shutdown sequence and cleanup procedures
- **Implementation Guidance**: SHOULD provide implementation order and key decisions
### In Requirements Document
- **Behavioral Constraints**: MUST use RFC 2119 keywords (MUST/SHOULD/MAY) for all requirements
- **Data Model**: MUST define core entities with field-level detail (type, constraint, relation)
### Quality Gate Additions
| Check | Criteria | Severity |
|-------|----------|----------|
| State machine present | >= 1 lifecycle state diagram | Error |
| Configuration model | All config fields documented | Warning |
| Observability metrics | >= 3 metrics defined | Warning |
| Error handling defined | Per-component strategy | Warning |
| RFC keywords used | Behavioral requirements use MUST/SHOULD/MAY | Warning |

View File

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

View File

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

View File

@@ -0,0 +1,57 @@
# Analyze Task
Parse user task -> detect architecture capabilities -> build dependency graph -> design roles.
**CONSTRAINT**: Text-level analysis only. NO source code reading, NO codebase exploration.
## Signal Detection
| Keywords | Capability | Prefix |
|----------|------------|--------|
| analyze, scan, audit, map, identify | analyzer | ANALYZE |
| design, plan, strategy, refactoring-plan | designer | DESIGN |
| refactor, implement, fix, apply | refactorer | REFACTOR |
| validate, build, test, verify, compile | validator | VALIDATE |
| review, audit-code, quality, check-code | reviewer | REVIEW |
## Dependency Graph
Natural ordering tiers:
- Tier 0: analyzer (knowledge gathering -- no dependencies)
- Tier 1: designer (requires analyzer output)
- Tier 2: refactorer (requires designer output)
- Tier 3: validator, reviewer (validation requires refactored artifacts, can run in parallel)
## Complexity Scoring
| Factor | Points |
|--------|--------|
| Per capability | +1 |
| Cross-domain refactoring | +2 |
| Parallel branches requested | +1 per branch |
| Serial depth > 3 | +1 |
| Multiple targets (independent mode) | +2 |
Results: 1-3 Low, 4-6 Medium, 7+ High
## Role Minimization
- Cap at 5 roles
- Merge overlapping capabilities
- Absorb trivial single-step roles
## Output
Write <session>/task-analysis.json:
```json
{
"task_description": "<original>",
"pipeline_type": "<single|fan-out|independent|auto>",
"capabilities": [{ "name": "<cap>", "prefix": "<PREFIX>", "keywords": ["..."] }],
"dependency_graph": { "<TASK-ID>": { "role": "<role>", "blockedBy": ["..."], "priority": "P0|P1|P2" } },
"roles": [{ "name": "<role>", "prefix": "<PREFIX>", "inner_loop": false }],
"complexity": { "score": 0, "level": "Low|Medium|High" },
"parallel_mode": "<auto|single|fan-out|independent>",
"max_branches": 5
}
```

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@@ -0,0 +1,102 @@
# Pipeline Definitions — team-arch-opt
## Available Pipelines
### Single Mode (Linear)
```
ANALYZE-001 → DESIGN-001 → REFACTOR-001 → VALIDATE-001 + REVIEW-001
[analyzer] [designer] [refactorer] [validator] [reviewer]
^ |
+<-- FIX-001 ----+
(max 3 iterations)
```
### Fan-out Mode (Shared Stages + Parallel Branches)
```
ANALYZE-001 → DESIGN-001 --+→ REFACTOR-B01 → VALIDATE-B01 + REVIEW-B01
[analyzer] [designer] | [refactorer] [validator] [reviewer]
+→ REFACTOR-B02 → VALIDATE-B02 + REVIEW-B02
+→ REFACTOR-B0N → VALIDATE-B0N + REVIEW-B0N
|
AGGREGATE → Phase 5
```
Branch tasks created at CP-2.5 after DESIGN-001 completes.
### Independent Mode (M Complete Pipelines)
```
Pipeline A: ANALYZE-A01 → DESIGN-A01 → REFACTOR-A01 → VALIDATE-A01 + REVIEW-A01
Pipeline B: ANALYZE-B01 → DESIGN-B01 → REFACTOR-B01 → VALIDATE-B01 + REVIEW-B01
... |
AGGREGATE → Phase 5
```
### Auto Mode
Auto-detects based on refactoring count at CP-2.5:
- count <= 2 → switch to single mode
- count >= 3 → switch to fan-out mode
## Task Metadata Registry
### Single Mode
| Task ID | Role | Phase | Dependencies | Description |
|---------|------|-------|-------------|-------------|
| ANALYZE-001 | analyzer | Stage 1 | (none) | Analyze architecture, identify structural issues |
| DESIGN-001 | designer | Stage 2 | ANALYZE-001 | Design refactoring plan from architecture report |
| REFACTOR-001 | refactorer | Stage 3 | DESIGN-001 | Implement highest-priority refactorings |
| VALIDATE-001 | validator | Stage 4 | REFACTOR-001 | Validate build, tests, metrics, API compatibility |
| REVIEW-001 | reviewer | Stage 4 | REFACTOR-001 | Review refactoring code for correctness |
| FIX-001 | refactorer | Stage 3 (cycle) | REVIEW-001 or VALIDATE-001 | Fix issues found in review/validation |
### Fan-out Mode (Branch Tasks at CP-2.5)
| Task ID | Role | Phase | Dependencies | Description |
|---------|------|-------|-------------|-------------|
| ANALYZE-001 | analyzer | Stage 1 (shared) | (none) | Analyze architecture |
| DESIGN-001 | designer | Stage 2 (shared) | ANALYZE-001 | Design plan with discrete REFACTOR-IDs |
| REFACTOR-B{NN} | refactorer | Stage 3 (branch) | DESIGN-001 | Implement REFACTOR-{NNN} only |
| VALIDATE-B{NN} | validator | Stage 4 (branch) | REFACTOR-B{NN} | Validate branch B{NN} |
| REVIEW-B{NN} | reviewer | Stage 4 (branch) | REFACTOR-B{NN} | Review branch B{NN} |
| FIX-B{NN}-{cycle} | refactorer | Fix (branch) | (none) | Fix issues in branch B{NN} |
### Independent Mode
| Task ID | Role | Phase | Dependencies | Description |
|---------|------|-------|-------------|-------------|
| ANALYZE-{P}01 | analyzer | Stage 1 | (none) | Analyze for pipeline {P} target |
| DESIGN-{P}01 | designer | Stage 2 | ANALYZE-{P}01 | Design for pipeline {P} |
| REFACTOR-{P}01 | refactorer | Stage 3 | DESIGN-{P}01 | Implement pipeline {P} refactorings |
| VALIDATE-{P}01 | validator | Stage 4 | REFACTOR-{P}01 | Validate pipeline {P} |
| REVIEW-{P}01 | reviewer | Stage 4 | REFACTOR-{P}01 | Review pipeline {P} |
## Checkpoints
| Checkpoint | Trigger | Location | Behavior |
|------------|---------|----------|----------|
| CP-1 | ANALYZE-001 complete | After Stage 1 | User reviews architecture report, can refine scope |
| CP-2 | DESIGN-001 complete | After Stage 2 | User reviews refactoring plan, can adjust priorities |
| CP-2.5 | DESIGN-001 complete (auto/fan-out) | After Stage 2 | Auto-create N branch tasks, spawn all REFACTOR-B* in parallel |
| CP-3 | REVIEW/VALIDATE fail | Stage 4 (per-branch) | Auto-create FIX task for that branch only (max 3x per branch) |
| CP-4 | All tasks/branches complete | Phase 5 | Aggregate results, interactive completion action |
## Task Naming Rules
| Mode | Stage 3 | Stage 4 | Fix | Retry |
|------|---------|---------|-----|-------|
| Single | REFACTOR-001 | VALIDATE-001, REVIEW-001 | FIX-001 | VALIDATE-001-R1, REVIEW-001-R1 |
| Fan-out | REFACTOR-B01 | VALIDATE-B01, REVIEW-B01 | FIX-B01-1 | VALIDATE-B01-R1, REVIEW-B01-R1 |
| Independent | REFACTOR-A01 | VALIDATE-A01, REVIEW-A01 | FIX-A01-1 | VALIDATE-A01-R1, REVIEW-A01-R1 |
## Parallel Mode Invocation
```bash
Skill(skill="team-arch-opt", args="<task-description>") # auto mode
Skill(skill="team-arch-opt", args="--parallel-mode=fan-out <task-description>") # force fan-out
Skill(skill="team-arch-opt", args='--parallel-mode=independent "target1" "target2"') # independent
Skill(skill="team-arch-opt", args="--max-branches=3 <task-description>") # limit branches
```

View File

@@ -3,8 +3,7 @@
"team_name": "arch-opt",
"team_display_name": "Architecture Optimization",
"skill_name": "team-arch-opt",
"skill_path": ".claude/skills/team-arch-opt/",
"worker_agent": "team-worker",
"skill_path": "~ or <project>/.claude/skills/team-arch-opt/",
"pipeline_type": "Linear with Review-Fix Cycle (Parallel-Capable)",
"completion_action": "interactive",
"has_inline_discuss": true,

View File

@@ -1,309 +1,60 @@
---
name: team-brainstorm
description: Unified team skill for brainstorming team. All roles invoke this skill with --role arg for role-specific execution. Triggers on "team brainstorm".
description: Unified team skill for brainstorming team. Uses team-worker agent architecture with role directories for domain logic. Coordinator orchestrates pipeline, workers are team-worker agents. Triggers on "team brainstorm".
allowed-tools: TeamCreate(*), TeamDelete(*), SendMessage(*), TaskCreate(*), TaskUpdate(*), TaskList(*), TaskGet(*), Agent(*), AskUserQuestion(*), Read(*), Write(*), Edit(*), Bash(*), Glob(*), Grep(*)
---
# Team Brainstorm
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.
Orchestrate multi-agent brainstorming: generate ideas → challenge assumptions → synthesize → evaluate. Supports Quick, Deep, and Full pipelines with Generator-Critic loop.
## Architecture
```
+---------------------------------------------------+
| Skill(skill="team-brainstorm") |
| args="<topic-description>" |
+-------------------+-------------------------------+
Skill(skill="team-brainstorm", args="topic description")
|
Orchestration Mode (auto -> coordinator)
SKILL.md (this file) = Router
|
Coordinator (inline)
Phase 0-5 orchestration
|
+-------+-------+-------+-------+
v v v v
[tw] [tw] [tw] [tw]
ideator chall- synthe- evalua-
enger sizer tor
(tw) = team-worker agent
+--------------+--------------+
| |
no --role flag --role <name>
| |
Coordinator Worker
roles/coordinator/role.md roles/<name>/role.md
|
+-- analyze → dispatch → spawn workers → STOP
|
+-------+-------+-------+
v v v v
[ideator][challenger][synthesizer][evaluator]
```
## Command Execution Protocol
## Role Registry
When coordinator needs to execute a command (dispatch, monitor):
1. **Read the command file**: `roles/coordinator/commands/<command-name>.md`
2. **Follow the workflow** defined in the command file (Phase 2-4 structure)
3. **Commands are inline execution guides** -- NOT separate agents or subprocesses
4. **Execute synchronously** -- complete the command workflow before proceeding
| Role | Path | Prefix | Inner Loop |
|------|------|--------|------------|
| coordinator | [roles/coordinator/role.md](roles/coordinator/role.md) | — | — |
| ideator | [roles/ideator/role.md](roles/ideator/role.md) | IDEA-* | false |
| challenger | [roles/challenger/role.md](roles/challenger/role.md) | CHALLENGE-* | false |
| synthesizer | [roles/synthesizer/role.md](roles/synthesizer/role.md) | SYNTH-* | false |
| evaluator | [roles/evaluator/role.md](roles/evaluator/role.md) | EVAL-* | false |
## Role Router
### Input Parsing
Parse `$ARGUMENTS`:
- Has `--role <name>` → Read `roles/<name>/role.md`, execute Phase 2-4
- No `--role` → Read `roles/coordinator/role.md`, execute entry router
Parse `$ARGUMENTS` to extract `--role`. If absent → Orchestration Mode (auto route to coordinator).
## Shared Constants
### Role Registry
- **Session prefix**: `BRS`
- **Session path**: `.workflow/.team/BRS-<slug>-<date>/`
- **CLI tools**: `ccw cli --mode analysis` (read-only), `ccw cli --mode write` (modifications)
- **Message bus**: `mcp__ccw-tools__team_msg(session_id=<session-id>, ...)`
| Role | Spec | Task Prefix | Inner Loop |
|------|------|-------------|------------|
| coordinator | [roles/coordinator/role.md](roles/coordinator/role.md) | (none) | - |
| ideator | [role-specs/ideator.md](role-specs/ideator.md) | IDEA-* | false |
| challenger | [role-specs/challenger.md](role-specs/challenger.md) | CHALLENGE-* | false |
| synthesizer | [role-specs/synthesizer.md](role-specs/synthesizer.md) | SYNTH-* | false |
| evaluator | [role-specs/evaluator.md](role-specs/evaluator.md) | EVAL-* | false |
## Worker Spawn Template
> **⚠️ 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
```
**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 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", session_id=<session-id>, from=<role>, type=<message-type>, data={ref: "<artifact-path>"}
- `to` and `summary` auto-defaulted -- do NOT specify explicitly
- **CLI fallback**: `ccw team log --session-id <session-id> --from <role> --type <type> --json`
2. **SendMessage**: Send result to coordinator
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 |
| Share state via team_msg(type="state_update") | Create tasks for other roles |
| Delegate to commands/ files | Modify resources outside own responsibility |
Coordinator additional restrictions: Do not generate ideas directly, do not evaluate/challenge ideas, do not execute analysis/synthesis, do not bypass workers.
### Output Tagging
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:
**Parameters**: operation="log", session_id=<session-id>, from=<role>, type=<message-type>, data={ref: "<artifact-path>"}
`to` and `summary` auto-defaulted -- do NOT specify explicitly.
**CLI fallback**: `ccw team log --session-id <session-id> --from <role> --type <type> --json`
**Message types by role**:
| Role | Types |
|------|-------|
| coordinator | `pipeline_selected`, `gc_loop_trigger`, `task_unblocked`, `error`, `shutdown` |
| ideator | `ideas_ready`, `ideas_revised`, `error` |
| challenger | `critique_ready`, `error` |
| synthesizer | `synthesis_ready`, `error` |
| evaluator | `evaluation_ready`, `error` |
### Shared State
Cross-role state is shared via `team_msg(type="state_update")` messages, persisted in `.msg/meta.json`:
| Role | State Key |
|------|-----------|
| ideator | `generated_ideas` |
| challenger | `critique_insights` |
| synthesizer | `synthesis_themes` |
| evaluator | `evaluation_scores` |
### Team Configuration
| Setting | Value |
|---------|-------|
| Team name | brainstorm |
| Session directory | `.workflow/.team/BRS-<slug>-<date>/` |
| Message store | `.msg/messages.jsonl` + `.msg/meta.json` in session dir |
---
## Three-Pipeline Architecture
```
Quick:
IDEA-001 → CHALLENGE-001 → SYNTH-001
Deep (Generator-Critic Loop):
IDEA-001 → CHALLENGE-001 → IDEA-002(fix) → CHALLENGE-002 → SYNTH-001 → EVAL-001
Full (Fan-out + Generator-Critic):
[IDEA-001 + IDEA-002 + IDEA-003](parallel) → CHALLENGE-001(batch) → IDEA-004(fix) → SYNTH-001 → EVAL-001
```
### Generator-Critic Loop
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
### v5 Worker Spawn (all roles)
When coordinator spawns workers, use `team-worker` agent with role-spec path:
Coordinator spawns workers using this template:
```
Agent({
@@ -314,39 +65,31 @@ Agent({
run_in_background: true,
prompt: `## Role Assignment
role: <role>
role_spec: .claude/skills/team-brainstorm/role-specs/<role>.md
role_spec: ~ or <project>/.claude/skills/team-brainstorm/roles/<role>/role.md
session: <session-folder>
session_id: <session-id>
team_name: brainstorm
requirement: <topic-description>
inner_loop: <true|false>
inner_loop: 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).`
Execute built-in Phase 1 (task discovery) -> role Phase 2-4 -> built-in Phase 5 (report).`
})
```
**All roles** (ideator, challenger, synthesizer, evaluator): Set `inner_loop: false`.
**Parallel ideator spawn** (Full pipeline with N angles):
> When Full pipeline has N parallel IDEA tasks assigned to ideator role, spawn N distinct team-worker agents named `ideator-1`, `ideator-2`, etc. Each agent only processes tasks where owner matches its agent name.
| Condition | Action |
|-----------|--------|
| Full pipeline with N idea angles (N > 1) | Spawn N team-worker agents: `ideator-1`, `ideator-2`, ... `ideator-N` with `run_in_background: true` |
| Quick/Deep pipeline (single ideator) | Standard spawn: single `ideator` team-worker agent |
When Full pipeline has N parallel IDEA tasks, spawn N distinct team-worker agents named `ideator-1`, `ideator-2`, etc.
```
Agent({
subagent_type: "team-worker",
description: "Spawn ideator-<N> worker",
team_name: "brainstorm",
name: "ideator-<N>",
team_name: "brainstorm",
run_in_background: true,
prompt: `## Role Assignment
role: ideator
role_spec: .claude/skills/team-brainstorm/role-specs/ideator.md
role_spec: ~ or <project>/.claude/skills/team-brainstorm/roles/ideator/role.md
session: <session-folder>
session_id: <session-id>
team_name: brainstorm
@@ -355,73 +98,55 @@ agent_name: ideator-<N>
inner_loop: false
Read role_spec file to load Phase 2-4 domain instructions.
Execute built-in Phase 1 (task discovery, owner=ideator-<N>) -> role-spec Phase 2-4 -> built-in Phase 5 (report).`
Execute built-in Phase 1 (task discovery, owner=ideator-<N>) -> role Phase 2-4 -> built-in Phase 5 (report).`
})
```
**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.
## User Commands
---
| Command | Action |
|---------|--------|
| `check` / `status` | View execution status graph, no advancement |
| `resume` / `continue` | Check worker states, advance next step |
## Completion Action
When the pipeline completes (all tasks done, coordinator Phase 5):
## Session Directory
```
AskUserQuestion({
questions: [{
question: "Brainstorm pipeline complete. What would you like to do?",
header: "Completion",
multiSelect: false,
options: [
{ label: "Archive & Clean (Recommended)", description: "Archive session, clean up tasks and team resources" },
{ label: "Keep Active", description: "Keep session active for follow-up work or inspection" },
{ label: "Export Results", description: "Export deliverables to a specified location, then clean" }
]
}]
})
```
| Choice | Action |
|--------|--------|
| Archive & Clean | Update session status="completed" -> TeamDelete() -> output final summary |
| Keep Active | Update session status="paused" -> output resume instructions: `Skill(skill="team-brainstorm", args="resume")` |
| Export Results | AskUserQuestion for target path -> copy deliverables -> Archive & Clean |
---
## Unified Session Directory
```
.workflow/.team/BRS-<slug>-<YYYY-MM-DD>/
.workflow/.team/BRS-<slug>-<date>/
├── session.json # Session metadata + pipeline + gc_round
├── task-analysis.json # Coordinator analyze output
├── .msg/
│ ├── messages.jsonl # Message bus log
│ └── meta.json # Session state + cross-role state
├── wisdom/ # Cross-task knowledge
│ ├── messages.jsonl # Message bus log
│ └── meta.json # Session state + cross-role state
├── wisdom/ # Cross-task knowledge
│ ├── learnings.md
│ ├── decisions.md
│ ├── conventions.md
│ └── issues.md
├── ideas/ # Ideator output
├── ideas/ # Ideator output
│ ├── idea-001.md
── idea-002.md
│ └── idea-003.md
├── critiques/ # Challenger output
── idea-002.md
├── critiques/ # Challenger output
│ ├── critique-001.md
│ └── critique-002.md
├── synthesis/ # Synthesizer output
├── synthesis/ # Synthesizer output
│ └── synthesis-001.md
└── evaluation/ # Evaluator output
└── evaluation/ # Evaluator output
└── evaluation-001.md
```
## Specs Reference
- [specs/pipelines.md](specs/pipelines.md) — Pipeline definitions and task registry
## Error Handling
| Scenario | Resolution |
|----------|------------|
| Unknown --role value | Error with available role list |
| 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 |
| Unknown command | Error with available command list |
| Role not found | Error with role registry |
| CLI tool fails | Worker fallback to direct implementation |
| Fast-advance conflict | Coordinator reconciles on next callback |
| Completion action fails | Default to Keep Active |
| Generator-Critic loop exceeds 2 rounds | Force convergence to synthesizer |
| No ideas generated | Coordinator prompts with seed questions |

View File

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

View File

@@ -0,0 +1,58 @@
# Analyze Task
Parse user topic -> detect brainstorming capabilities -> assess complexity -> select pipeline.
**CONSTRAINT**: Text-level analysis only. NO source code reading, NO codebase exploration.
## Signal Detection
| Keywords | Capability | Prefix |
|----------|------------|--------|
| generate, create, brainstorm, ideas, explore | ideator | IDEA |
| challenge, critique, argue, devil, risk | challenger | CHALLENGE |
| synthesize, integrate, combine, merge, themes | synthesizer | SYNTH |
| evaluate, score, rank, prioritize, select | evaluator | EVAL |
## Dependency Graph
Natural ordering tiers:
- Tier 0: ideator (divergent generation -- no dependencies)
- Tier 1: challenger (requires ideator output)
- Tier 2: ideator-revision (requires challenger output, GC loop)
- Tier 3: synthesizer (requires last challenger output)
- Tier 4: evaluator (requires synthesizer output, deep/full only)
## Complexity Scoring
| Factor | Points |
|--------|--------|
| Per capability needed | +1 |
| Strategic/systemic topic | +3 |
| Multi-dimensional analysis | +2 |
| Innovation-focused request | +2 |
| Simple/basic topic | -2 |
Results: 0-1 Low (quick), 2-3 Medium (deep), 4+ High (full)
## Pipeline Selection
| Complexity | Pipeline | Tasks |
|------------|----------|-------|
| Low | quick | IDEA → CHALLENGE → SYNTH |
| Medium | deep | IDEA → CHALLENGE → IDEA-fix → CHALLENGE-2 → SYNTH → EVAL |
| High | full | 3x IDEA (parallel) → CHALLENGE → IDEA-fix → SYNTH → EVAL |
## Output
Write <session>/task-analysis.json:
```json
{
"task_description": "<original>",
"pipeline_type": "<quick|deep|full>",
"capabilities": [{ "name": "<cap>", "prefix": "<PREFIX>", "keywords": ["..."] }],
"dependency_graph": { "<TASK-ID>": { "role": "<role>", "blockedBy": ["..."], "priority": "P0|P1|P2" } },
"roles": [{ "name": "<role>", "prefix": "<PREFIX>", "inner_loop": false }],
"complexity": { "score": 0, "level": "Low|Medium|High" },
"angles": ["Technical", "Product", "Innovation", "Risk"]
}
```

View File

@@ -1,34 +1,30 @@
# Command: Monitor
# Monitor Pipeline
Handle all coordinator monitoring events: worker callbacks, status checks, pipeline advancement, Generator-Critic loop control, and completion.
Event-driven pipeline coordination. Beat model: coordinator wake -> process -> spawn -> STOP.
## Constants
| Key | Value |
|-----|-------|
| SPAWN_MODE | background |
| ONE_STEP_PER_INVOCATION | true |
| WORKER_AGENT | team-worker |
| MAX_GC_ROUNDS | 2 |
- SPAWN_MODE: background
- ONE_STEP_PER_INVOCATION: true
- FAST_ADVANCE_AWARE: true
- WORKER_AGENT: team-worker
- MAX_GC_ROUNDS: 2
## Phase 2: Context Loading
## Handler Router
| Input | Source | Required |
|-------|--------|----------|
| Session state | <session>/session.json | Yes |
| Task list | TaskList() | Yes |
| Trigger event | From Entry Router detection | Yes |
| Meta state | <session>/.msg/meta.json | Yes |
| Source | Handler |
|--------|---------|
| Message contains [ideator], [challenger], [synthesizer], [evaluator] | handleCallback |
| "consensus_blocked" | handleConsensus |
| "capability_gap" | handleAdapt |
| "check" or "status" | handleCheck |
| "resume" or "continue" | handleResume |
| All tasks completed | handleComplete |
| Default | handleSpawnNext |
1. Load session.json for current state, pipeline mode, gc_round
2. Run TaskList() to get current task statuses
3. Identify trigger event type from Entry Router
## handleCallback
## Phase 3: Event Handlers
### handleCallback
Triggered when a worker sends completion message.
Worker completed. Process and advance.
1. Parse message to identify role and task ID:
@@ -39,14 +35,8 @@ Triggered when a worker sends completion message.
| `[synthesizer]` or task ID `SYNTH-*` | synthesizer |
| `[evaluator]` or task ID `EVAL-*` | evaluator |
2. Mark task as completed:
```
TaskUpdate({ taskId: "<task-id>", status: "completed" })
```
2. Mark task as completed: `TaskUpdate({ taskId: "<task-id>", status: "completed" })`
3. Record completion in session state
4. **Generator-Critic check** (when challenger completes):
- If completed task is CHALLENGE-* AND pipeline is deep or full:
- Read critique file for GC signal
@@ -63,38 +53,57 @@ TaskUpdate({ taskId: "<task-id>", status: "completed" })
5. Proceed to handleSpawnNext
### handleSpawnNext
## handleCheck
Find and spawn the next ready tasks.
1. Scan task list for tasks where:
- Status is "pending"
- All blockedBy tasks have status "completed"
2. For each ready task, spawn team-worker:
Read-only status report, then STOP.
```
Agent({
subagent_type: "team-worker",
description: "Spawn <role> worker for <task-id>",
team_name: "brainstorm",
name: "<role>",
run_in_background: true,
prompt: `## Role Assignment
role: <role>
role_spec: .claude/skills/team-brainstorm/role-specs/<role>.md
session: <session-folder>
session_id: <session-id>
team_name: brainstorm
requirement: <task-description>
inner_loop: false
Read role_spec file to load Phase 2-4 domain instructions.
Execute built-in Phase 1 -> role-spec Phase 2-4 -> built-in Phase 5.`
})
[coordinator] Pipeline Status (<pipeline-mode>)
[coordinator] Progress: <done>/<total> (<pct>%)
[coordinator] Active: <workers with elapsed time>
[coordinator] Ready: <pending tasks with resolved deps>
[coordinator] GC Rounds: <gc_round>/<max_gc_rounds>
[coordinator] Commands: 'resume' to advance | 'check' to refresh
```
3. **Parallel spawn rules**:
## handleResume
1. Audit task list: Tasks stuck in "in_progress" -> reset to "pending"
2. Proceed to handleSpawnNext
## handleSpawnNext
Find ready tasks, spawn workers, STOP.
1. Collect: completedSubjects, inProgressSubjects, readySubjects
2. No ready + work in progress -> report waiting, STOP
3. No ready + nothing in progress -> handleComplete
4. Has ready -> for each:
a. TaskUpdate -> in_progress
b. team_msg log -> task_unblocked
c. Spawn team-worker (see SKILL.md Spawn Template):
```
Agent({
subagent_type: "team-worker",
description: "Spawn <role> worker for <task-id>",
team_name: "brainstorm",
name: "<role>",
run_in_background: true,
prompt: `## Role Assignment
role: <role>
role_spec: ~ or <project>/.claude/skills/team-brainstorm/roles/<role>/role.md
session: <session-folder>
session_id: <session-id>
team_name: brainstorm
requirement: <task-description>
inner_loop: false
Read role_spec file to load Phase 2-4 domain instructions.
Execute built-in Phase 1 (task discovery) -> role Phase 2-4 -> built-in Phase 5 (report).`
})
```
d. Add to active_workers
5. Parallel spawn rules:
| Pipeline | Scenario | Spawn Behavior |
|----------|----------|---------------|
@@ -103,33 +112,34 @@ Execute built-in Phase 1 -> role-spec Phase 2-4 -> built-in Phase 5.`
| Full | IDEA-001/002/003 unblocked | Spawn ALL 3 ideator workers in parallel |
| Full | Other stages | One worker at a time |
4. STOP after spawning -- wait for next callback
### handleCheck
Output current pipeline status. Do NOT advance pipeline.
**Parallel ideator spawn** (Full pipeline):
```
Pipeline Status (<pipeline-mode>):
[DONE] IDEA-001 (ideator) -> ideas/idea-001.md
[DONE] CHALLENGE-001 (challenger) -> critiques/critique-001.md
[RUN] SYNTH-001 (synthesizer) -> synthesizing...
[WAIT] EVAL-001 (evaluator) -> blocked by SYNTH-001
GC Rounds: <gc_round>/<max_gc_rounds>
Session: <session-id>
Agent({
subagent_type: "team-worker",
name: "ideator-<N>",
...
prompt: `...agent_name: ideator-<N>...`
})
```
### handleResume
6. Update session, output summary, STOP
Resume pipeline after user pause or interruption.
## handleComplete
1. Audit task list for inconsistencies:
- Tasks stuck in "in_progress" -> reset to "pending"
- Tasks with completed blockers but still "pending" -> include in spawn list
2. Proceed to handleSpawnNext
Pipeline done. Generate report and completion action.
### handleConsensus
Completion check by mode:
| Mode | Completion Condition |
|------|---------------------|
| quick | All 3 tasks completed |
| deep | All 6 tasks (+ any skipped GC tasks) completed |
| full | All 7 tasks (+ any skipped GC tasks) completed |
1. Verify all tasks completed via TaskList()
2. If any tasks not completed, return to handleSpawnNext
3. If all completed -> transition to coordinator Phase 5
## handleConsensus
Handle consensus_blocked signals.
@@ -139,27 +149,19 @@ Handle consensus_blocked signals.
| MEDIUM | Log finding, attempt to continue |
| LOW | Log finding, continue pipeline |
### handleComplete
## handleAdapt
Triggered when all pipeline tasks are completed.
Capability gap reported mid-pipeline.
**Completion check by mode**:
1. Parse gap description
2. Check if existing role covers it -> redirect
3. Role count < 5 -> generate dynamic role-spec in <session>/role-specs/
4. Create new task, spawn worker
5. Role count >= 5 -> merge or pause
| Mode | Completion Condition |
|------|---------------------|
| quick | All 3 tasks completed |
| deep | All 6 tasks (+ any skipped GC tasks) completed |
| full | All 7 tasks (+ any skipped GC tasks) completed |
## Fast-Advance Reconciliation
1. Verify all tasks completed via TaskList()
2. If any tasks not completed, return to handleSpawnNext
3. If all completed, transition to coordinator Phase 5 (Report + Completion Action)
## Phase 4: State Persistence
After every handler execution:
1. Update session.json with current state (gc_round, last event, active tasks)
2. Update .msg/meta.json gc_round if changed
3. Verify task list consistency
4. STOP and wait for next event
On every coordinator wake:
1. Read team_msg entries with type="fast_advance"
2. Sync active_workers with spawned successors
3. No duplicate spawns

View File

@@ -1,15 +1,14 @@
# Coordinator - Brainstorm Team
# Coordinator
**Role**: coordinator
**Type**: Orchestrator
**Team**: brainstorm
Orchestrate team-brainstorm: topic clarify -> dispatch -> spawn -> monitor -> report.
Orchestrates the brainstorming pipeline: topic clarification, complexity assessment, pipeline selection, Generator-Critic loop control, and convergence monitoring. Spawns team-worker agents for all worker roles.
## Identity
- Name: coordinator | Tag: [coordinator]
- Responsibility: Topic clarification -> Create team -> Dispatch tasks -> Monitor progress -> Report results
## Boundaries
### MUST
- Use `team-worker` agent type for all worker spawns (NOT `general-purpose`)
- Follow Command Execution Protocol for dispatch and monitor commands
- Respect pipeline stage dependencies (blockedBy)
@@ -18,105 +17,48 @@ Orchestrates the brainstorming pipeline: topic clarification, complexity assessm
- Execute completion action in Phase 5
### MUST NOT
- Generate ideas, challenge assumptions, synthesize, or evaluate -- workers handle this
- Spawn workers without creating tasks first
- Force-advance pipeline past GC loop decisions
- Modify artifact files (ideas/*.md, critiques/*.md, etc.) -- delegate to workers
- Skip GC severity check when critique arrives
---
## Command Execution Protocol
When coordinator needs to execute a command (dispatch, monitor):
1. **Read the command file**: `roles/coordinator/commands/<command-name>.md`
2. **Follow the workflow** defined in the command file (Phase 2-4 structure)
3. **Commands are inline execution guides** -- NOT separate agents or subprocesses
4. **Execute synchronously** -- complete the command workflow before proceeding
Example:
```
Phase 3 needs task dispatch
-> Read roles/coordinator/commands/dispatch.md
-> Execute Phase 2 (Context Loading)
-> Execute Phase 3 (Task Chain Creation)
-> Execute Phase 4 (Validation)
-> Continue to Phase 4
```
---
When coordinator needs to execute a specific phase:
1. Read `commands/<command>.md`
2. Follow the workflow defined in the command
3. Commands are inline execution guides, NOT separate agents
4. Execute synchronously, complete before proceeding
## Entry Router
When coordinator is invoked, detect invocation type:
| Detection | Condition | Handler |
|-----------|-----------|---------|
| Worker callback | Message contains role tag [ideator], [challenger], [synthesizer], [evaluator] | -> handleCallback |
| Consensus blocked | Message contains "consensus_blocked" | -> handleConsensus |
| Status check | Arguments contain "check" or "status" | -> handleCheck |
| Manual resume | Arguments contain "resume" or "continue" | -> handleResume |
| Pipeline complete | All tasks have status "completed" | -> handleComplete |
| Interrupted session | Active/paused session exists | -> Phase 0 (Resume Check) |
| New session | None of above | -> Phase 1 (Topic Clarification) |
| Worker callback | Message contains [ideator], [challenger], [synthesizer], [evaluator] | -> handleCallback (monitor.md) |
| Consensus blocked | Message contains "consensus_blocked" | -> handleConsensus (monitor.md) |
| Status check | Args contain "check" or "status" | -> handleCheck (monitor.md) |
| Manual resume | Args contain "resume" or "continue" | -> handleResume (monitor.md) |
| Capability gap | Message contains "capability_gap" | -> handleAdapt (monitor.md) |
| Pipeline complete | All tasks completed | -> handleComplete (monitor.md) |
| Interrupted session | Active session in .workflow/.team/BRS-* | -> Phase 0 |
| New session | None of above | -> Phase 1 |
For callback/check/resume/complete: load `commands/monitor.md` and execute matched handler, then STOP.
### Router Implementation
1. **Load session context** (if exists):
- Scan `.workflow/.team/BRS-*/.msg/meta.json` for active/paused sessions
- If found, extract session folder path, status, and pipeline mode
2. **Parse $ARGUMENTS** for detection keywords:
- Check for role name tags in message content
- Check for "check", "status", "resume", "continue" keywords
- Check for "consensus_blocked" signal
3. **Route to handler**:
- For monitor handlers: Read `commands/monitor.md`, execute matched handler, STOP
- For Phase 0: Execute Session Resume Check below
- For Phase 1: Execute Topic Clarification below
---
For callback/check/resume/consensus/adapt/complete: load commands/monitor.md, execute handler, STOP.
## Phase 0: Session Resume Check
Triggered when an active/paused session is detected on coordinator entry.
1. Load session.json from detected session folder
2. Audit task list:
```
TaskList()
```
3. Reconcile session state vs task status:
| Task Status | Session Expects | Action |
|-------------|----------------|--------|
| in_progress | Should be running | Reset to pending (worker was interrupted) |
| completed | Already tracked | Skip |
| pending + unblocked | Ready to run | Include in spawn list |
4. Rebuild team if not active:
```
TeamCreate({ team_name: "brainstorm" })
```
5. Spawn workers for ready tasks -> Phase 4 coordination loop
---
1. Scan `.workflow/.team/BRS-*/session.json` for active/paused sessions
2. No sessions -> Phase 1
3. Single session -> reconcile (audit TaskList, reset in_progress->pending, rebuild team, kick first ready task)
4. Multiple -> AskUserQuestion for selection
## Phase 1: Topic Clarification + Complexity Assessment
1. Parse user task description from $ARGUMENTS
2. Parse optional `--team-name` flag (default: "brainstorm")
TEXT-LEVEL ONLY. No source code reading.
3. Assess topic complexity:
1. Parse topic from $ARGUMENTS
2. Assess topic complexity:
| Signal | Weight | Keywords |
|--------|--------|----------|
@@ -131,155 +73,39 @@ TeamCreate({ team_name: "brainstorm" })
| 2-3 | Medium | deep |
| 0-1 | Low | quick |
4. Ask for missing parameters:
3. AskUserQuestion for pipeline mode and divergence angles
4. Store requirements: mode, scope, angles, constraints
```
AskUserQuestion({
questions: [{
question: "Select brainstorming pipeline mode",
header: "Mode",
multiSelect: false,
options: [
{ label: "quick", description: "3-step: generate -> challenge -> synthesize" },
{ label: "deep", description: "6-step with Generator-Critic loop" },
{ label: "full", description: "7-step parallel ideation + GC + evaluation" }
]
}, {
question: "Select divergence angles",
header: "Angles",
multiSelect: true,
options: [
{ label: "Technical" },
{ label: "Product" },
{ label: "Innovation" },
{ label: "Risk" }
]
}]
})
```
5. Store requirements: mode, scope, angles, constraints
---
## Phase 2: Session & Team Setup
## Phase 2: Create Team + Initialize Session
1. Generate session ID: `BRS-<topic-slug>-<date>`
2. Create session folder structure:
2. Create session folder structure: ideas/, critiques/, synthesis/, evaluation/, wisdom/, .msg/
3. TeamCreate with team name `brainstorm`
4. Write session.json with pipeline, angles, gc_round=0, max_gc_rounds=2
5. Initialize meta.json via team_msg state_update:
```
mcp__ccw-tools__team_msg({
operation: "log", session_id: "<id>", from: "coordinator",
type: "state_update", summary: "Session initialized",
data: { pipeline_mode: "<mode>", pipeline_stages: ["ideator","challenger","synthesizer","evaluator"], team_name: "brainstorm", topic: "<topic>", angles: [...], gc_round: 0 }
})
```
6. Write session.json
```
Bash("mkdir -p .workflow/.team/<session-id>/ideas .workflow/.team/<session-id>/critiques .workflow/.team/<session-id>/synthesis .workflow/.team/<session-id>/evaluation .workflow/.team/<session-id>/wisdom .workflow/.team/<session-id>/.msg")
```
## Phase 3: Create Task Chain
3. Write session.json:
Delegate to commands/dispatch.md:
1. Read pipeline mode and angles from session.json
2. Create tasks for selected pipeline with correct blockedBy
3. Update session.json with task count
```json
{
"status": "active",
"team_name": "brainstorm",
"topic": "<topic>",
"pipeline": "<quick|deep|full>",
"angles": ["<angle1>", "<angle2>"],
"gc_round": 0,
"max_gc_rounds": 2,
"timestamp": "<ISO-8601>"
}
```
## Phase 4: Spawn-and-Stop
4. Initialize meta.json with pipeline metadata:
```typescript
// Use team_msg to write pipeline metadata to .msg/meta.json
mcp__ccw-tools__team_msg({
operation: "log",
session_id: "<session-id>",
from: "coordinator",
type: "state_update",
summary: "Session initialized",
data: {
pipeline_mode: "<mode>",
pipeline_stages: ["ideator", "challenger", "synthesizer", "evaluator"],
roles: ["coordinator", "ideator", "challenger", "synthesizer", "evaluator"],
team_name: "brainstorm",
topic: "<topic>",
angles: ["<angle1>", "<angle2>"],
gc_round": 0,
status: "active"
}
})
```
5. Create team:
```
TeamCreate({ team_name: "brainstorm" })
```
---
## Phase 3: Task Chain Creation
Execute `commands/dispatch.md` inline (Command Execution Protocol):
1. Read `roles/coordinator/commands/dispatch.md`
2. Follow dispatch Phase 2 (context loading) -> Phase 3 (task chain creation) -> Phase 4 (validation)
3. Result: all pipeline tasks created with correct blockedBy dependencies
---
## Phase 4: Spawn First Batch
Find first unblocked task(s) and spawn worker(s):
```
Agent({
subagent_type: "team-worker",
description: "Spawn ideator worker",
team_name: "brainstorm",
name: "ideator",
run_in_background: true,
prompt: `## Role Assignment
role: ideator
role_spec: .claude/skills/team-brainstorm/role-specs/ideator.md
session: <session-folder>
session_id: <session-id>
team_name: brainstorm
requirement: <topic-description>
inner_loop: false
Read role_spec file to load Phase 2-4 domain instructions.
Execute built-in Phase 1 -> role-spec Phase 2-4 -> built-in Phase 5.`
})
```
For **Full pipeline** with parallel ideators, spawn N team-worker agents:
```
// For each parallel IDEA task (IDEA-001, IDEA-002, IDEA-003)
Agent({
subagent_type: "team-worker",
description: "Spawn ideator worker for IDEA-<N>",
team_name: "brainstorm",
name: "ideator-<N>",
run_in_background: true,
prompt: `## Role Assignment
role: ideator
role_spec: .claude/skills/team-brainstorm/role-specs/ideator.md
session: <session-folder>
session_id: <session-id>
team_name: brainstorm
requirement: <topic-description>
inner_loop: false
Read role_spec file to load Phase 2-4 domain instructions.
Execute built-in Phase 1 -> role-spec Phase 2-4 -> built-in Phase 5.`
})
```
**STOP** after spawning. Wait for worker callback.
All subsequent coordination handled by `commands/monitor.md` handlers.
---
Delegate to commands/monitor.md#handleSpawnNext:
1. Find ready tasks (pending + blockedBy resolved)
2. Spawn team-worker agents (see SKILL.md Spawn Template)
3. Output status summary
4. STOP
## Phase 5: Report + Completion Action
@@ -295,27 +121,17 @@ All subsequent coordination handled by `commands/monitor.md` handlers.
3. Output pipeline summary: topic, pipeline mode, GC rounds, total ideas, key themes
4. **Completion Action** (interactive):
4. Execute completion action per session.completion_action:
- interactive -> AskUserQuestion (Archive/Keep/Export)
- auto_archive -> Archive & Clean (status=completed, TeamDelete)
- auto_keep -> Keep Active (status=paused)
```
AskUserQuestion({
questions: [{
question: "Brainstorm pipeline complete. What would you like to do?",
header: "Completion",
multiSelect: false,
options: [
{ label: "Archive & Clean (Recommended)", description: "Archive session, clean up tasks and team resources" },
{ label: "Keep Active", description: "Keep session active for follow-up brainstorming" },
{ label: "Export Results", description: "Export deliverables to a specified location, then clean" }
]
}]
})
```
## Error Handling
5. Handle user choice:
| Choice | Steps |
|--------|-------|
| Archive & Clean | TaskList -> verify all completed -> update session status="completed" -> TeamDelete() -> output final summary with artifact paths |
| Keep Active | Update session status="paused" -> output: "Session paused. Resume with: Skill(skill='team-brainstorm', args='resume')" |
| Export Results | AskUserQuestion for target directory -> copy all artifacts -> Archive & Clean flow |
| Error | Resolution |
|-------|------------|
| Task too vague | AskUserQuestion for clarification |
| Session corruption | Attempt recovery, fallback to manual |
| Worker crash | Reset task to pending, respawn |
| GC loop exceeded | Force convergence to synthesizer |
| No ideas generated | Coordinator prompts with seed questions |

View File

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

View File

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

View File

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

View File

@@ -0,0 +1,72 @@
# Pipeline Definitions — team-brainstorm
## Available Pipelines
### Quick Pipeline (3 beats, strictly serial)
```
IDEA-001 → CHALLENGE-001 → SYNTH-001
[ideator] [challenger] [synthesizer]
```
### Deep Pipeline (6 beats, Generator-Critic loop)
```
IDEA-001 → CHALLENGE-001 → IDEA-002(fix) → CHALLENGE-002 → SYNTH-001 → EVAL-001
```
GC loop check: if critique.severity >= HIGH → create IDEA-fix → CHALLENGE-2 → SYNTH; else skip to SYNTH
### Full Pipeline (7 tasks, fan-out parallel ideation + GC)
```
[IDEA-001 + IDEA-002 + IDEA-003](parallel) → CHALLENGE-001(batch) → IDEA-004(fix) → SYNTH-001 → EVAL-001
```
## 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 |
## 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 |
## Completion Conditions
| Mode | Completion Condition |
|------|---------------------|
| quick | All 3 tasks completed |
| deep | All 6 tasks (+ any skipped GC tasks) completed |
| full | All 7 tasks (+ any skipped GC tasks) completed |
## Shared State (meta.json)
| Role | State Key |
|------|-----------|
| ideator | `generated_ideas` |
| challenger | `critique_insights` |
| synthesizer | `synthesis_themes` |
| evaluator | `evaluation_scores` |
## Message Types
| Role | Types |
|------|-------|
| coordinator | `pipeline_selected`, `gc_loop_trigger`, `task_unblocked`, `error`, `shutdown` |
| ideator | `ideas_ready`, `ideas_revised`, `error` |
| challenger | `critique_ready`, `error` |
| synthesizer | `synthesis_ready`, `error` |
| evaluator | `evaluation_ready`, `error` |

View File

@@ -150,40 +150,6 @@ AskUserQuestion({
---
## 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
```

View File

@@ -0,0 +1,83 @@
# Pipeline Definitions — Team Coordinate
## Dynamic Pipeline Model
team-coordinate does NOT have a static pipeline. All pipelines are generated at runtime from task-analysis.json based on the user's task description.
## Pipeline Generation Process
```
Phase 1: analyze-task.md
-> Signal detection -> capability mapping -> dependency graph
-> Output: task-analysis.json
Phase 2: dispatch.md
-> Read task-analysis.json dependency graph
-> Create TaskCreate entries per dependency node
-> Set blockedBy chains from graph edges
-> Output: TaskList with correct DAG
Phase 3-N: monitor.md
-> handleSpawnNext: spawn ready tasks as team-worker agents
-> handleCallback: mark completed, advance pipeline
-> Repeat until all tasks done
```
## Dynamic Task Naming
| Capability | Prefix | Example |
|------------|--------|---------|
| researcher | RESEARCH | RESEARCH-001 |
| developer | IMPL | IMPL-001 |
| analyst | ANALYSIS | ANALYSIS-001 |
| designer | DESIGN | DESIGN-001 |
| tester | TEST | TEST-001 |
| writer | DRAFT | DRAFT-001 |
| planner | PLAN | PLAN-001 |
| (default) | TASK | TASK-001 |
## Dependency Graph Structure
task-analysis.json encodes the pipeline:
```json
{
"dependency_graph": {
"RESEARCH-001": { "role": "researcher", "blockedBy": [], "priority": "P0" },
"IMPL-001": { "role": "developer", "blockedBy": ["RESEARCH-001"], "priority": "P1" },
"TEST-001": { "role": "tester", "blockedBy": ["IMPL-001"], "priority": "P2" }
}
}
```
## Role-Worker Map
Dynamic — loaded from session role-specs at runtime:
```
<session>/role-specs/<role-name>.md -> team-worker agent
```
Role-spec files contain YAML frontmatter:
```yaml
---
role: <role-name>
prefix: <PREFIX>
inner_loop: <true|false>
message_types:
success: <type>
error: error
---
```
## Checkpoint
| Trigger | Behavior |
|---------|----------|
| capability_gap reported | handleAdapt: generate new role-spec, spawn new worker |
| consensus_blocked HIGH | Create REVISION task or pause for user |
| All tasks complete | handleComplete: interactive completion action |
## Specs Reference
- [role-spec-template.md](role-spec-template.md) — Template for generating dynamic role-specs

View File

@@ -0,0 +1,153 @@
---
name: team-designer
description: Meta-skill for generating team skills following the v4 architecture pattern. Produces complete skill packages with SKILL.md router, coordinator, worker roles, specs, and templates. Triggers on "team-designer", "design team".
allowed-tools: Agent(*), AskUserQuestion(*), Read(*), Write(*), Edit(*), Bash(*), Glob(*), Grep(*)
---
# Team Skill Designer
Generate complete team skills following the team-lifecycle-v4 architecture: SKILL.md as universal router, coordinator with beat model, worker roles with optional commands/, shared specs, and templates.
## Architecture Overview
```
┌─────────────────────────────────────────────────────────────────┐
│ Team Skill Designer (SKILL.md) │
│ → Orchestrator: gather requirements, generate files, validate │
└───────────────────────────┬──────────────────────────────────────┘
┌───────────┬───────────┼───────────┬───────────┐
↓ ↓ ↓ ↓
┌─────────┐ ┌─────────┐ ┌─────────┐ ┌─────────┐
│ Phase 1 │ │ Phase 2 │ │ Phase 3 │ │ Phase 4 │
│ Require │ │ Scaffold│ │ Content │ │ Valid │
│ Analysis│ │ Gen │ │ Gen │ │ & Report│
└─────────┘ └─────────┘ └─────────┘ └─────────┘
↓ ↓ ↓ ↓
teamConfig SKILL.md roles/ Validated
+ dirs specs/ skill pkg
templates/
```
## Key Design Principles
1. **v4 Architecture Compliance**: Generated skills follow team-lifecycle-v4 pattern — SKILL.md = pure router, beat model = coordinator-only, unified structure (roles/ + specs/ + templates/)
2. **Golden Sample Reference**: Uses `team-lifecycle-v4` as reference implementation at `~ or <project>/.claude/skills/team-lifecycle-v4/`
3. **Intelligent Commands Distribution**: Auto-determines which roles need `commands/` (2+ commands) vs inline logic (1 command)
4. **team-worker Compatibility**: Role.md files include correct YAML frontmatter for team-worker agent parsing
## Execution Flow
```
Input Parsing:
└─ Parse user requirements (skill name, roles, pipelines, domain)
Phase 1: Requirements Analysis
└─ Ref: phases/01-requirements-analysis.md
├─ Tasks: Detect input → Gather roles → Define pipelines → Build teamConfig
└─ Output: teamConfig
Phase 2: Scaffold Generation
└─ Ref: phases/02-scaffold-generation.md
├─ Tasks: Create dirs → Generate SKILL.md router → Verify
└─ Output: SKILL.md + directory structure
Phase 3: Content Generation
└─ Ref: phases/03-content-generation.md
├─ Tasks: Coordinator → Workers → Specs → Templates
└─ Output: roles/**/*.md, specs/*.md, templates/*.md
Phase 4: Validation
└─ Ref: phases/04-validation.md
└─ Output: Validation report (PASS/REVIEW/FAIL)
Return:
└─ Summary with skill location and usage instructions
```
**Phase Reference Documents** (read on-demand when phase executes):
| Phase | Document | Purpose |
|-------|----------|---------|
| 1 | [phases/01-requirements-analysis.md](phases/01-requirements-analysis.md) | Gather team skill requirements, build teamConfig |
| 2 | [phases/02-scaffold-generation.md](phases/02-scaffold-generation.md) | Generate SKILL.md router and directory structure |
| 3 | [phases/03-content-generation.md](phases/03-content-generation.md) | Generate coordinator, workers, specs, templates |
| 4 | [phases/04-validation.md](phases/04-validation.md) | Validate structure, references, and consistency |
## Golden Sample
Generated skills follow the architecture of `~ or <project>/.claude/skills/team-lifecycle-v4/`:
```
.claude/skills/<skill-name>/
├── SKILL.md # Universal router (all roles read)
├── roles/
│ ├── coordinator/
│ │ ├── role.md # Orchestrator + beat model + entry router
│ │ └── commands/
│ │ ├── analyze.md # Task analysis
│ │ ├── dispatch.md # Task chain creation
│ │ └── monitor.md # Beat control + callbacks
│ ├── <inline-worker>/
│ │ └── role.md # Phase 2-4 embedded (simple role)
│ └── <command-worker>/
│ ├── role.md # Phase 2-4 dispatcher
│ └── commands/
│ ├── <cmd-1>.md
│ └── <cmd-2>.md
├── specs/
│ ├── pipelines.md # Pipeline definitions + task registry
│ └── <domain-specs>.md # Domain-specific specifications
└── templates/ # Optional document templates
```
## Data Flow
```
User Input (skill name, roles, pipelines)
Phase 1: Requirements Analysis
↓ Output: teamConfig
Phase 2: Scaffold Generation
↓ Input: teamConfig
↓ Output: SKILL.md + skillDir
Phase 3: Content Generation
↓ Input: teamConfig + skillDir
↓ Output: roles/, specs/, templates/
Phase 4: Validation
↓ Input: teamConfig + all files
↓ Output: validation report
Return summary to user
```
## Core Rules
1. **Start Immediately**: First action is Phase 1 execution
2. **Parse Every Output**: Extract teamConfig from Phase 1 for subsequent phases
3. **Auto-Continue**: After each phase, automatically execute next phase
4. **Progressive Phase Loading**: Read phase docs ONLY when that phase is about to execute
5. **Golden Sample Fidelity**: Generated files must match team-lifecycle-v4 patterns
6. **DO NOT STOP**: Continuous workflow until all 4 phases complete
## Input Processing
Convert user input to structured format:
```
SKILL_NAME: [kebab-case name, e.g., team-code-review]
DOMAIN: [what this team does, e.g., "multi-stage code review with security analysis"]
ROLES: [worker roles beyond coordinator, e.g., "analyst, reviewer, security-expert"]
PIPELINES: [pipeline types and flows, e.g., "review-only: SCAN-001 → REVIEW-001 → REPORT-001"]
SESSION_PREFIX: [3-4 char, e.g., TCR]
```
## Error Handling
- **Invalid role name**: Must be lowercase alphanumeric with hyphens, max 20 chars
- **Circular dependencies**: Detect and report in pipeline validation
- **Missing golden sample**: Fall back to embedded templates in phase files
- **Directory conflict**: Warn if skill directory already exists, ask user to confirm overwrite

View File

@@ -0,0 +1,265 @@
# Phase 1: Requirements Analysis
Gather team skill requirements from user input and build the `teamConfig` data structure that drives all subsequent phases.
## Objective
- Parse user input (text description, reference skill, or interactive)
- Determine roles, pipelines, specs, templates
- Auto-decide commands distribution (inline vs commands/ folder)
- Build comprehensive `teamConfig` object
- Confirm with user before proceeding
## Step 1.1: Detect Input Source
```javascript
function detectInputSource(userInput) {
// Source A: Reference to existing skill
if (userInput.includes('based on') || userInput.includes('参考') || userInput.includes('like')) {
return { type: 'reference', refSkill: extractSkillName(userInput) };
}
// Source B: Structured input with roles/pipelines
if (userInput.includes('ROLES:') || userInput.includes('PIPELINES:')) {
return { type: 'structured', data: parseStructuredInput(userInput) };
}
// Source C: Natural language description
return { type: 'natural', description: userInput };
}
```
**For reference source**: Read the referenced skill's SKILL.md and role files to extract structure.
**For natural language**: Use AskUserQuestion to gather missing details interactively.
## Step 1.2: Gather Core Identity
```javascript
const coreIdentity = AskUserQuestion({
questions: [
{
question: "团队技能名称?(kebab-case, e.g., team-code-review)",
header: "Skill Name",
multiSelect: false,
options: [
{ label: suggestedName, description: "Auto-suggested from description" },
{ label: "Custom", description: "Enter custom name" }
]
},
{
question: "会话前缀?(3-4字符用于任务ID, e.g., TCR)",
header: "Prefix",
multiSelect: false,
options: [
{ label: suggestedPrefix, description: "Auto-suggested" },
{ label: "Custom", description: "Enter custom prefix" }
]
}
]
});
```
If user provided clear name/prefix in input, skip this step.
## Step 1.3: Determine Roles
### Role Discovery from Domain
Analyze domain description to identify required roles:
```javascript
function discoverRoles(domain) {
const rolePatterns = {
'analyst': ['分析', 'analyze', 'research', 'explore', 'investigate', 'scan'],
'planner': ['规划', 'plan', 'design', 'architect', 'decompose'],
'writer': ['文档', 'write', 'document', 'draft', 'spec', 'report'],
'executor': ['实现', 'implement', 'execute', 'build', 'code', 'develop'],
'tester': ['测试', 'test', 'verify', 'validate', 'qa'],
'reviewer': ['审查', 'review', 'quality', 'check', 'audit', 'inspect'],
'security-expert': ['安全', 'security', 'vulnerability', 'penetration'],
'performance-optimizer': ['性能', 'performance', 'optimize', 'benchmark'],
'data-engineer': ['数据', 'data', 'pipeline', 'etl', 'migration'],
'devops-engineer': ['部署', 'devops', 'deploy', 'ci/cd', 'infrastructure'],
};
const matched = [];
for (const [role, keywords] of Object.entries(rolePatterns)) {
if (keywords.some(kw => domain.toLowerCase().includes(kw))) {
matched.push(role);
}
}
return matched;
}
```
### Role Configuration
For each discovered role, determine:
```javascript
function configureRole(roleName) {
return {
name: roleName,
prefix: determinePrefix(roleName),
inner_loop: determineInnerLoop(roleName),
hasCommands: false, // determined in Step 1.5
commands: [],
message_types: determineMessageTypes(roleName),
path: `roles/${roleName}/role.md`
};
}
// Standard prefix mapping
const prefixMap = {
'analyst': 'RESEARCH',
'writer': 'DRAFT',
'planner': 'PLAN',
'executor': 'IMPL',
'tester': 'TEST',
'reviewer': 'REVIEW',
// Dynamic roles use uppercase role name
};
// Inner loop: roles that process multiple tasks sequentially
const innerLoopRoles = ['executor', 'writer', 'planner'];
// Message types the role handles
const messageMap = {
'analyst': ['state_update'],
'writer': ['state_update', 'discuss_response'],
'planner': ['state_update'],
'executor': ['state_update', 'revision_request'],
'tester': ['state_update'],
'reviewer': ['state_update', 'discuss_request'],
};
```
## Step 1.4: Define Pipelines
### Pipeline Types from Role Combination
```javascript
function definePipelines(roles, domain) {
const has = name => roles.some(r => r.name === name);
// Full lifecycle: analyst → writer → planner → executor → tester → reviewer
if (has('analyst') && has('writer') && has('planner') && has('executor'))
return [{ name: 'full-lifecycle', tasks: buildFullLifecycleTasks(roles) }];
// Spec-only: analyst → writer → reviewer
if (has('analyst') && has('writer') && !has('executor'))
return [{ name: 'spec-only', tasks: buildSpecOnlyTasks(roles) }];
// Impl-only: planner → executor → tester → reviewer
if (has('planner') && has('executor') && !has('analyst'))
return [{ name: 'impl-only', tasks: buildImplOnlyTasks(roles) }];
// Custom: user-defined
return [{ name: 'custom', tasks: buildCustomTasks(roles, domain) }];
}
```
### Task Schema
```javascript
const taskSchema = {
id: 'PREFIX-NNN', // e.g., RESEARCH-001
role: 'analyst', // which role executes
name: 'Seed Analysis', // human-readable name
dependsOn: [], // task IDs that must complete first
isCheckpoint: false, // true for quality gates
isConditional: false, // true for routing decisions
description: '...'
};
```
## Step 1.5: Determine Commands Distribution
**Rule**: 1 action → inline in role.md. 2+ distinct actions → commands/ folder.
```javascript
function determineCommandsDistribution(roles) {
// Coordinator: always has commands/
// coordinator.commands = ['analyze', 'dispatch', 'monitor']
// Standard multi-action roles:
// executor → implement + fix → commands/
// reviewer (if both code & spec review) → review-code + review-spec → commands/
// All others → typically inline
for (const role of roles) {
const actions = countDistinctActions(role);
if (actions.length >= 2) {
role.hasCommands = true;
role.commands = actions.map(a => a.name);
}
}
}
```
## Step 1.6: Determine Specs and Templates
```javascript
// Specs: always include pipelines, add domain-specific
const specs = ['pipelines'];
if (hasQualityGates) specs.push('quality-gates');
if (hasKnowledgeTransfer) specs.push('knowledge-transfer');
// Templates: only if writer role exists
const templates = [];
if (has('writer')) {
// Detect from domain keywords
if (domain.includes('product')) templates.push('product-brief');
if (domain.includes('requirement')) templates.push('requirements');
if (domain.includes('architecture')) templates.push('architecture');
if (domain.includes('epic')) templates.push('epics');
}
```
## Step 1.7: Build teamConfig
```javascript
const teamConfig = {
skillName: string, // e.g., "team-code-review"
sessionPrefix: string, // e.g., "TCR"
domain: string, // domain description
title: string, // e.g., "Code Review Team"
roles: Array<RoleConfig>, // includes coordinator
pipelines: Array<Pipeline>,
specs: Array<string>, // filenames without .md
templates: Array<string>, // filenames without .md
conditionalRouting: boolean,
dynamicSpecialists: Array<string>,
};
```
## Step 1.8: Confirm with User
```
╔══════════════════════════════════════════╗
║ Team Skill Configuration Summary ║
╠══════════════════════════════════════════╣
Skill Name: ${skillName}
Session Prefix: ${sessionPrefix}
Domain: ${domain}
Roles (N):
├─ coordinator (commands: analyze, dispatch, monitor)
├─ role-a [PREFIX-*] (inline) 🔄
└─ role-b [PREFIX-*] (commands: cmd1, cmd2)
Pipelines:
└─ pipeline-name: TASK-001 → TASK-002 → TASK-003
Specs: pipelines, quality-gates
Templates: (none)
╚══════════════════════════════════════════╝
```
Use AskUserQuestion to confirm or allow modifications.
## Output
- **Variable**: `teamConfig` — complete configuration for all subsequent phases
- **Next**: Phase 2 - Scaffold Generation

View File

@@ -0,0 +1,236 @@
# Phase 2: Scaffold Generation
Generate the SKILL.md universal router and create the directory structure for the team skill.
## Objective
- Create directory structure (roles/, specs/, templates/)
- Generate SKILL.md as universal router following v4 pattern
- SKILL.md must NOT contain beat model, pipeline details, or role Phase 2-4 logic
## Step 2.1: Create Directory Structure
```bash
skillDir=".claude/skills/${teamConfig.skillName}"
mkdir -p "${skillDir}"
# Create role directories
for role in teamConfig.roles:
mkdir -p "${skillDir}/roles/${role.name}"
if role.hasCommands:
mkdir -p "${skillDir}/roles/${role.name}/commands"
# Create specs directory
mkdir -p "${skillDir}/specs"
# Create templates directory (if needed)
if teamConfig.templates.length > 0:
mkdir -p "${skillDir}/templates"
```
## Step 2.2: Generate SKILL.md
The SKILL.md follows a strict template. Every generated SKILL.md contains these sections in order:
### Section 1: Frontmatter
```yaml
---
name: ${teamConfig.skillName}
description: ${teamConfig.domain}. Triggers on "${teamConfig.skillName}".
allowed-tools: TeamCreate(*), TeamDelete(*), SendMessage(*), TaskCreate(*), TaskUpdate(*), TaskList(*), TaskGet(*), Agent(*), AskUserQuestion(*), Read(*), Write(*), Edit(*), Bash(*), Glob(*), Grep(*)
---
```
### Section 2: Title + Architecture Diagram
```markdown
# ${Title}
${One-line description}
## Architecture
\```
Skill(skill="${teamConfig.skillName}", args="task description")
|
SKILL.md (this file) = Router
|
+--------------+--------------+
| |
no --role flag --role <name>
| |
Coordinator Worker
roles/coordinator/role.md roles/<name>/role.md
|
+-- analyze → dispatch → spawn workers → STOP
|
+-------+-------+-------+
v v v v
[team-worker agents, each loads roles/<role>/role.md]
\```
```
### Section 3: Role Registry
```markdown
## Role Registry
| Role | Path | Prefix | Inner Loop |
|------|------|--------|------------|
| coordinator | roles/coordinator/role.md | — | — |
${teamConfig.roles.filter(r => r.name !== 'coordinator').map(r =>
`| ${r.name} | ${r.path} | ${r.prefix}-* | ${r.inner_loop} |`
).join('\n')}
```
### Section 4: Role Router
```markdown
## Role Router
Parse `$ARGUMENTS`:
- Has `--role <name>` → Read `roles/<name>/role.md`, execute Phase 2-4
- No `--role` → Read `roles/coordinator/role.md`, execute entry router
```
### Section 5: Shared Constants
```markdown
## Shared Constants
- **Session prefix**: `${teamConfig.sessionPrefix}`
- **Session path**: `.workflow/.team/${teamConfig.sessionPrefix}-<slug>-<date>/`
- **CLI tools**: `ccw cli --mode analysis` (read-only), `ccw cli --mode write` (modifications)
- **Message bus**: `mcp__ccw-tools__team_msg(session_id=<session-id>, ...)`
```
### Section 6: Worker Spawn Template
```markdown
## Worker Spawn Template
Coordinator spawns workers using this template:
\```
Agent({
subagent_type: "team-worker",
description: "Spawn <role> worker",
team_name: <team-name>,
name: "<role>",
run_in_background: true,
prompt: `## Role Assignment
role: <role>
role_spec: .claude/skills/${teamConfig.skillName}/roles/<role>/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 Phase 2-4 -> built-in Phase 5 (report).`
})
\```
```
### Section 7: User Commands
```markdown
## User Commands
| Command | Action |
|---------|--------|
| `check` / `status` | View execution status graph |
| `resume` / `continue` | Advance to next step |
| `revise <TASK-ID> [feedback]` | Revise specific task |
| `feedback <text>` | Inject feedback for revision |
| `recheck` | Re-run quality check |
| `improve [dimension]` | Auto-improve weakest dimension |
```
### Section 8: Completion Action
```markdown
## Completion Action
When pipeline completes, coordinator presents:
\```
AskUserQuestion({
questions: [{
question: "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" }
]
}]
})
\```
```
### Section 9: Specs Reference
```markdown
## Specs Reference
${teamConfig.specs.map(s =>
`- [specs/${s}.md](specs/${s}.md) — ${specDescription(s)}`
).join('\n')}
```
### Section 10: Session Directory
```markdown
## Session Directory
\```
.workflow/.team/${teamConfig.sessionPrefix}-<slug>-<date>/
├── team-session.json # Session state + role registry
├── spec/ # Spec phase outputs
├── plan/ # Implementation plan + TASK-*.json
├── artifacts/ # All deliverables
├── wisdom/ # Cross-task knowledge
├── explorations/ # Shared explore cache
├── discussions/ # Discuss round records
└── .msg/ # Team message bus
\```
```
### Section 11: Error Handling
```markdown
## Error Handling
| Scenario | Resolution |
|----------|------------|
| Unknown command | Error with available command list |
| Role not found | Error with role registry |
| CLI tool fails | Worker fallback to direct implementation |
| Fast-advance conflict | Coordinator reconciles on next callback |
| Completion action fails | Default to Keep Active |
```
## Step 2.3: Assemble and Write
Assemble all sections into a single SKILL.md file and write to `${skillDir}/SKILL.md`.
**Quality Rules**:
1. SKILL.md must NOT contain beat model (ONE_STEP_PER_INVOCATION, spawn-and-stop)
2. SKILL.md must NOT contain pipeline task details (task IDs, dependencies)
3. SKILL.md must NOT contain role Phase 2-4 logic
4. SKILL.md MUST contain role registry table with correct paths
5. SKILL.md MUST contain worker spawn template with correct `role_spec` paths
## Output
- **File**: `.claude/skills/${teamConfig.skillName}/SKILL.md`
- **Variable**: `skillDir` (path to skill root directory)
- **Next**: Phase 3 - Content Generation
## Next Phase
Return to orchestrator, then auto-continue to [Phase 3: Content Generation](03-content-generation.md).

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