mirror of
https://github.com/catlog22/Claude-Code-Workflow.git
synced 2026-03-10 17:11:04 +08:00
Compare commits
199 Commits
copilot/fi
...
v7.2.2
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
6a47447e3a | ||
|
|
723c1b0e38 | ||
|
|
80d8954b7a | ||
|
|
0d01e7bc50 | ||
|
|
8b07d52323 | ||
|
|
e368f9f8cc | ||
|
|
eaaadcd164 | ||
|
|
ece4afcac8 | ||
|
|
75d5f7f230 | ||
|
|
29a1fea467 | ||
|
|
7ee9b579fa | ||
|
|
a9469a5e3b | ||
|
|
e87e3feba8 | ||
|
|
f2d4364c69 | ||
|
|
88149b6154 | ||
|
|
33cc451b61 | ||
|
|
56c06ecf3d | ||
|
|
cff1e16441 | ||
|
|
3fd55ebd4b | ||
|
|
bc7a556985 | ||
|
|
fb4f6e718e | ||
|
|
0bfae3fd1a | ||
|
|
3d92478772 | ||
|
|
f6c7c14042 | ||
|
|
dc1dc87023 | ||
|
|
ed02874a99 | ||
|
|
60218f6bf3 | ||
|
|
6341ed43e1 | ||
|
|
1fb49c0e39 | ||
|
|
99a45e3136 | ||
|
|
bf057a927b | ||
|
|
bbdd1840de | ||
|
|
fd0c9efa4d | ||
|
|
fd847070d5 | ||
|
|
16bbfcd12a | ||
|
|
64e772f9b8 | ||
|
|
e9f8a72343 | ||
|
|
a82e45fcf1 | ||
|
|
ab9b8ecbc0 | ||
|
|
f389e3e6dd | ||
|
|
b203ada9c5 | ||
|
|
fb0f56bfc0 | ||
|
|
91fa594578 | ||
|
|
ffd5282932 | ||
|
|
5e96722c09 | ||
|
|
26bda9c634 | ||
|
|
a7ed0365f7 | ||
|
|
628578b2bb | ||
|
|
08564d487a | ||
|
|
747b509ec2 | ||
|
|
9cfd5c05fc | ||
|
|
25f766ef26 | ||
|
|
9613644fc4 | ||
|
|
59787dc9be | ||
|
|
d7169029ee | ||
|
|
1bf9006d65 | ||
|
|
99d6438303 | ||
|
|
a58aa26a30 | ||
|
|
2dce4b3e8f | ||
|
|
b780734649 | ||
|
|
3bb4a821de | ||
|
|
d346d48ba2 | ||
|
|
57636040d2 | ||
|
|
980be3d87d | ||
|
|
a4cb1e7eb2 | ||
|
|
4f3ef5cba8 | ||
|
|
e54d76f7be | ||
|
|
c12acd41ee | ||
|
|
73cc2ef3fa | ||
|
|
ce2927b28d | ||
|
|
121e834459 | ||
|
|
2c2b9d6e29 | ||
|
|
0d5cc4a74f | ||
|
|
71485b89e6 | ||
|
|
2fc792a3b7 | ||
|
|
0af4ca040f | ||
|
|
7af258f43d | ||
|
|
8ad283086b | ||
|
|
b36a46d59d | ||
|
|
899a92f2eb | ||
|
|
d0ac3a5cd2 | ||
|
|
0939510e0d | ||
|
|
deea92581b | ||
|
|
4d17bb02a4 | ||
|
|
5cab8ae8a5 | ||
|
|
ffe3b427ce | ||
|
|
8c953b287d | ||
|
|
b1e321267e | ||
|
|
d0275f14b2 | ||
|
|
ee4dc367d9 | ||
|
|
a63fb370aa | ||
|
|
da19a6ec89 | ||
|
|
bf84a157ea | ||
|
|
41f990ddd4 | ||
|
|
3463bc8e27 | ||
|
|
9ad755e225 | ||
|
|
8799a9c2fd | ||
|
|
1f859ae4b9 | ||
|
|
ecf4e4d848 | ||
|
|
8ceae6d6fd | ||
|
|
2fb93d20e0 | ||
|
|
a753327acc | ||
|
|
f61a3da957 | ||
|
|
b0fb899675 | ||
|
|
0a49dc0675 | ||
|
|
096fc1c380 | ||
|
|
29f0a6cdb8 | ||
|
|
e83414abf3 | ||
|
|
e42597b1bc | ||
|
|
67b2129f3c | ||
|
|
19fb4d86c7 | ||
|
|
65763c76e9 | ||
|
|
4a89f626fc | ||
|
|
b0bfdb907a | ||
|
|
39bbf960c2 | ||
|
|
5e35da32e8 | ||
|
|
84610661ca | ||
|
|
cd54c10256 | ||
|
|
c3ddf7e322 | ||
|
|
ab65caec45 | ||
|
|
3788ba1268 | ||
|
|
d14a710797 | ||
|
|
92ac9897f2 | ||
|
|
67e78b132c | ||
|
|
0a37bc3eaf | ||
|
|
604f89b7aa | ||
|
|
46989dcbad | ||
|
|
4763edb0e4 | ||
|
|
7d349a64fb | ||
|
|
22a98b7b6c | ||
|
|
a59a86fb9b | ||
|
|
101417e028 | ||
|
|
902ee8528a | ||
|
|
54f15b6bda | ||
|
|
690d524aee | ||
|
|
b02c8497c7 | ||
|
|
be061dd2a2 | ||
|
|
9be35ed5fb | ||
|
|
a581a2e62b | ||
|
|
5c158d9a64 | ||
|
|
75173312c1 | ||
|
|
5b54f38aa3 | ||
|
|
61f929005c | ||
|
|
47fe0d3bec | ||
|
|
017b258223 | ||
|
|
93041402f2 | ||
|
|
8566e3af44 | ||
|
|
3b92bfae8c | ||
|
|
3db74cc7b0 | ||
|
|
b449b225fe | ||
|
|
e61f539d44 | ||
|
|
20eef5cd2d | ||
|
|
dd72e95e4d | ||
|
|
99a3561f71 | ||
|
|
4d755ff9b4 | ||
|
|
07452e57b7 | ||
|
|
3f25dbb11b | ||
|
|
dfa8e0d9f5 | ||
|
|
052e25dddb | ||
|
|
fa8bae52f1 | ||
|
|
ffe79d28e2 | ||
|
|
151b81ee4a | ||
|
|
6155fcc7b8 | ||
|
|
430d817e43 | ||
|
|
e228b8b273 | ||
|
|
79cdd47be5 | ||
|
|
1a1ca389f4 | ||
|
|
653ad10475 | ||
|
|
2487a8330c | ||
|
|
a94c790c4f | ||
|
|
f10351ee50 | ||
|
|
12be252e8e | ||
|
|
4ad05f8217 | ||
|
|
2b5c334bc4 | ||
|
|
a35fb0fe8f | ||
|
|
bf02f653ca | ||
|
|
b6f4864530 | ||
|
|
2623b5a633 | ||
|
|
21e3647331 | ||
|
|
519efe9783 | ||
|
|
25f442b329 | ||
|
|
b4d3426e6a | ||
|
|
c92754505a | ||
|
|
f96febe09a | ||
|
|
b2b8688d26 | ||
|
|
4c2bf31525 | ||
|
|
eb9a62e085 | ||
|
|
db5797faa3 | ||
|
|
5c51315a7e | ||
|
|
d6acbaf30f | ||
|
|
c11596c038 | ||
|
|
b669dcba24 | ||
|
|
7ebe674b62 | ||
|
|
e315e2315c | ||
|
|
092b8e20dc | ||
|
|
45c61186c4 | ||
|
|
6c16c121d2 | ||
|
|
dadcc1af5e | ||
|
|
33e12a31ac |
6
.ccw/specs/architecture-constraints.md
Normal file
6
.ccw/specs/architecture-constraints.md
Normal file
@@ -0,0 +1,6 @@
|
||||
# Architecture Constraints
|
||||
|
||||
## Schema Evolution
|
||||
|
||||
- [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.
|
||||
17
.ccw/specs/coding-conventions.md
Normal file
17
.ccw/specs/coding-conventions.md
Normal file
@@ -0,0 +1,17 @@
|
||||
# Coding Conventions
|
||||
|
||||
## Navigation & Path Handling
|
||||
|
||||
- [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)
|
||||
|
||||
## Document Generation
|
||||
|
||||
- [architecture] For document generation systems, adopt Layer 3→2→1 pattern (components → features → indexes) for efficient incremental updates. (learned: 2026-03-07)
|
||||
|
||||
## Implementation Quality
|
||||
|
||||
- [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)
|
||||
@@ -301,7 +301,7 @@ Document known constraints that affect planning:
|
||||
|
||||
[Continue for all major feature groups]
|
||||
|
||||
**Note**: Detailed task breakdown into executable work items is handled by `/workflow:plan` → `IMPL_PLAN.md`
|
||||
**Note**: Detailed task breakdown into executable work items is handled by `/workflow-plan` → `IMPL_PLAN.md`
|
||||
|
||||
---
|
||||
|
||||
|
||||
@@ -43,7 +43,7 @@ Core requirements, objectives, technical approach summary (2-3 paragraphs max).
|
||||
|
||||
**Quality Gates**:
|
||||
- concept-verify: ✅ Passed (0 ambiguities remaining) | ⏭️ Skipped (user decision) | ⏳ Pending
|
||||
- plan-verify: ⏳ Pending (recommended before /workflow:execute)
|
||||
- plan-verify: ⏳ Pending (recommended before /workflow-execute)
|
||||
|
||||
**Context Package Summary**:
|
||||
- **Focus Paths**: {list key directories from context-package.json}
|
||||
|
||||
@@ -30,6 +30,7 @@ RULES: [templates | additional constraints]
|
||||
|
||||
## Execution Flow
|
||||
|
||||
0. **Load Project Specs** - MANDATORY first step: run `ccw spec load` to retrieve project specifications and constraints before any analysis. Adapt analysis scope and standards based on loaded specs
|
||||
1. **Parse** all 6 fields (PURPOSE, TASK, MODE, CONTEXT, EXPECTED, RULES)
|
||||
2. **Read** and analyze CONTEXT files thoroughly
|
||||
3. **Identify** patterns, issues, and dependencies
|
||||
@@ -40,6 +41,7 @@ RULES: [templates | additional constraints]
|
||||
## Core Requirements
|
||||
|
||||
**ALWAYS**:
|
||||
- Run `ccw spec load` FIRST to obtain project specifications before starting any work
|
||||
- Analyze ALL CONTEXT files completely
|
||||
- Apply RULES (templates + constraints) exactly
|
||||
- Provide code evidence with `file:line` references
|
||||
|
||||
@@ -24,6 +24,7 @@ RULES: [templates | additional constraints]
|
||||
## Execution Flow
|
||||
|
||||
### MODE: write
|
||||
0. **Load Project Specs** - MANDATORY first step: run `ccw spec load` to retrieve project specifications and constraints before any implementation. Apply loaded specs to guide coding standards, architecture decisions, and quality gates
|
||||
1. **Parse** all 6 fields (PURPOSE, TASK, MODE, CONTEXT, EXPECTED, RULES)
|
||||
2. **Read** CONTEXT files, find 3+ similar patterns
|
||||
3. **Plan** implementation following RULES
|
||||
@@ -34,6 +35,7 @@ RULES: [templates | additional constraints]
|
||||
## Core Requirements
|
||||
|
||||
**ALWAYS**:
|
||||
- Run `ccw spec load` FIRST to obtain project specifications before starting any work
|
||||
- Study CONTEXT files - find 3+ similar patterns before implementing
|
||||
- Apply RULES exactly
|
||||
- Test continuously (auto mode)
|
||||
|
||||
@@ -63,6 +63,35 @@
|
||||
"type": "array",
|
||||
"items": {"type": "string"},
|
||||
"description": "Key symbols (functions, classes, types) in this file relevant to the task. Example: ['AuthService', 'login', 'TokenPayload']"
|
||||
},
|
||||
"key_code": {
|
||||
"type": "array",
|
||||
"items": {
|
||||
"type": "object",
|
||||
"required": ["symbol", "description"],
|
||||
"properties": {
|
||||
"symbol": {
|
||||
"type": "string",
|
||||
"description": "Symbol identifier (function, class, method, type). Example: 'AuthService.login()'"
|
||||
},
|
||||
"location": {
|
||||
"type": "string",
|
||||
"description": "Line range in file. Example: 'L45-L78'"
|
||||
},
|
||||
"description": {
|
||||
"type": "string",
|
||||
"minLength": 10,
|
||||
"description": "What this code does and why it matters. Example: 'JWT token generation with bcrypt verification, returns {token, refreshToken} pair'"
|
||||
}
|
||||
},
|
||||
"additionalProperties": false
|
||||
},
|
||||
"description": "Key code constructs with descriptions. Richer complement to key_symbols. Populate for files with relevance >= 0.7."
|
||||
},
|
||||
"topic_relation": {
|
||||
"type": "string",
|
||||
"minLength": 15,
|
||||
"description": "How this file relates to the exploration ANGLE/TOPIC. Must reference the angle explicitly. Example: 'Security exploration targets this file because JWT generation lacks token rotation'. Distinct from rationale (WHY selected) - topic_relation explains the CONNECTION to the exploration perspective."
|
||||
}
|
||||
},
|
||||
"additionalProperties": false
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"$schema": "http://json-schema.org/draft-07/schema#",
|
||||
"title": "Project Guidelines Schema",
|
||||
"description": "Schema for project-guidelines.json - user-maintained rules and constraints",
|
||||
"description": "Legacy schema - project guidelines now managed by spec system (`ccw spec load --dimension specs`)",
|
||||
"type": "object",
|
||||
"required": ["conventions", "constraints", "_metadata"],
|
||||
"properties": {
|
||||
|
||||
@@ -155,7 +155,7 @@
|
||||
},
|
||||
"development_index": {
|
||||
"type": "object",
|
||||
"description": "Categorized development history (lite-plan/lite-execute)",
|
||||
"description": "Categorized development history (lite-planex sessions)",
|
||||
"properties": {
|
||||
"feature": { "type": "array", "items": { "$ref": "#/$defs/devIndexEntry" } },
|
||||
"enhancement": { "type": "array", "items": { "$ref": "#/$defs/devIndexEntry" } },
|
||||
|
||||
@@ -85,13 +85,14 @@ Tools are selected based on **tags** defined in the configuration. Use tags to m
|
||||
|
||||
```bash
|
||||
# Explicit tool selection
|
||||
ccw cli -p "<PROMPT>" --tool <tool-id> --mode <analysis|write|review>
|
||||
ccw cli -p "<PROMPT>" --tool <tool-id> --mode <analysis|write>
|
||||
|
||||
# Model override
|
||||
ccw cli -p "<PROMPT>" --tool <tool-id> --model <model-id> --mode <analysis|write>
|
||||
|
||||
# Code review (codex only)
|
||||
# Code review (codex only - review mode and target flags are invalid for other tools)
|
||||
ccw cli -p "<PROMPT>" --tool codex --mode review
|
||||
ccw cli --tool codex --mode review --commit <hash>
|
||||
|
||||
# Tag-based auto-selection (future)
|
||||
ccw cli -p "<PROMPT>" --tags <tag1,tag2> --mode <analysis|write>
|
||||
@@ -215,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
|
||||
@@ -292,11 +293,8 @@ ccw cli -p "..." --tool gemini --mode analysis --rule analysis-review-architectu
|
||||
- **`review`**
|
||||
- Permission: Read-only (code review output)
|
||||
- Use For: Git-aware code review of uncommitted changes, branch diffs, specific commits
|
||||
- Specification: **codex only** - uses `codex review` subcommand
|
||||
- Tool Behavior:
|
||||
- `codex`: Executes `codex review` for structured code review
|
||||
- Other tools (gemini/qwen/claude): Accept mode but no operation change (treated as analysis)
|
||||
- **Constraint**: Target flags (`--uncommitted`, `--base`, `--commit`) and prompt are mutually exclusive
|
||||
- Specification: **codex only** - uses `codex review` subcommand. Other tools MUST NOT use this mode
|
||||
- **Constraint**: Target flags (`--uncommitted`, `--base`, `--commit`) are **codex-only** and mutually exclusive with prompt
|
||||
- With prompt only: `ccw cli -p "Focus on security" --tool codex --mode review` (reviews uncommitted by default)
|
||||
- With target flag only: `ccw cli --tool codex --mode review --commit abc123` (no prompt allowed)
|
||||
|
||||
@@ -309,20 +307,26 @@ ccw cli -p "..." --tool gemini --mode analysis --rule analysis-review-architectu
|
||||
- **`--mode <mode>`**
|
||||
- Description: **REQUIRED**: analysis, write, review
|
||||
- Default: **NONE** (must specify)
|
||||
- Note: `review` mode triggers `codex review` subcommand for codex tool only
|
||||
- Note: `review` mode is **codex-only**. Using `--mode review` with other tools (gemini/qwen/claude) is invalid and should be rejected
|
||||
|
||||
- **`--model <model>`**
|
||||
- Description: Model override
|
||||
- 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: -
|
||||
@@ -349,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`
|
||||
@@ -387,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
|
||||
@@ -399,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):
|
||||
@@ -421,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**:
|
||||
@@ -446,7 +509,7 @@ ccw cli --tool codex --mode review --base main
|
||||
ccw cli --tool codex --mode review --commit abc123
|
||||
```
|
||||
|
||||
> **Note**: `--mode review` only triggers special behavior for `codex` tool. Target flags (`--uncommitted`, `--base`, `--commit`) and prompt are **mutually exclusive** - use one or the other, not both.
|
||||
> **Note**: `--mode review` and target flags (`--uncommitted`, `--base`, `--commit`) are **codex-only**. Using them with other tools is invalid. When using codex, target flags and prompt are **mutually exclusive** - use one or the other, not both.
|
||||
|
||||
---
|
||||
|
||||
@@ -455,9 +518,9 @@ ccw cli --tool codex --mode review --commit abc123
|
||||
**Single-Use Authorization**: Each execution requires explicit user instruction. Previous authorization does NOT carry over.
|
||||
|
||||
**Mode Hierarchy**:
|
||||
- `analysis`: Read-only, safe for auto-execution
|
||||
- `write`: Create/Modify/Delete files, full operations - requires explicit `--mode write`
|
||||
- `review`: Git-aware code review (codex only), read-only output - requires explicit `--mode review`
|
||||
- `analysis`: Read-only, safe for auto-execution. Available for all tools
|
||||
- `write`: Create/Modify/Delete files, full operations - requires explicit `--mode write`. Available for all tools
|
||||
- `review`: **codex-only**. Git-aware code review, read-only output. Invalid for other tools (gemini/qwen/claude)
|
||||
- **Exception**: User provides clear instructions like "modify", "create", "implement"
|
||||
|
||||
---
|
||||
|
||||
@@ -711,7 +711,7 @@ All workflows use the same file structure definition regardless of complexity. *
|
||||
│ ├── [.chat/] # CLI interaction sessions (created when analysis is run)
|
||||
│ │ ├── chat-*.md # Saved chat sessions
|
||||
│ │ └── analysis-*.md # Analysis results
|
||||
│ ├── [.process/] # Planning analysis results (created by /workflow:plan)
|
||||
│ ├── [.process/] # Planning analysis results (created by /workflow-plan)
|
||||
│ │ └── ANALYSIS_RESULTS.md # Analysis results and planning artifacts
|
||||
│ ├── IMPL_PLAN.md # Planning document (REQUIRED)
|
||||
│ ├── TODO_LIST.md # Progress tracking (REQUIRED)
|
||||
@@ -783,7 +783,7 @@ All workflows use the same file structure definition regardless of complexity. *
|
||||
**Examples**:
|
||||
|
||||
*Workflow Commands (lightweight):*
|
||||
- `/workflow:lite-plan "feature idea"` (exploratory) → `.scratchpad/lite-plan-feature-idea-20250105-143110.md`
|
||||
- `/workflow-lite-plan "feature idea"` (exploratory) → `.scratchpad/lite-plan-feature-idea-20250105-143110.md`
|
||||
- `/workflow:lite-fix "bug description"` (bug fixing) → `.scratchpad/lite-fix-bug-20250105-143130.md`
|
||||
|
||||
> **Note**: Direct CLI commands (`/cli:analyze`, `/cli:execute`, etc.) have been replaced by semantic invocation and workflow commands.
|
||||
|
||||
@@ -16,18 +16,19 @@ Available CLI endpoints are dynamically defined by the config file
|
||||
- **File Modification**: @~/.ccw/workflows/file-modification.md
|
||||
|
||||
### Agent Calls
|
||||
- **Always use `run_in_background: false`** for Task tool agent calls: `Task({ subagent_type: "xxx", prompt: "...", run_in_background: false })` to ensure synchronous execution and immediate result visibility
|
||||
- **TaskOutput usage**: Only use `TaskOutput({ task_id: "xxx", block: false })` + sleep loop to poll completion status. NEVER read intermediate output during agent/CLI execution - wait for final result only
|
||||
- **Always use `run_in_background: false`** for Agent tool calls: `Agent({ subagent_type: "xxx", prompt: "...", run_in_background: false })` to ensure synchronous execution and immediate result visibility
|
||||
|
||||
|
||||
### CLI Tool Calls (ccw cli)
|
||||
- **Default: Use Bash `run_in_background: true`** - Unless otherwise specified, always execute CLI calls in background using Bash tool's background mode:
|
||||
- **Default**: CLI calls (`ccw cli`) default to background execution (`run_in_background: true`):
|
||||
```
|
||||
Bash({
|
||||
command: "ccw cli -p '...' --tool gemini",
|
||||
run_in_background: true // Bash tool parameter, not ccw cli parameter
|
||||
})
|
||||
```
|
||||
- **After CLI call**: Stop output immediately - let CLI execute in background. **DO NOT use TaskOutput polling** - wait for hook callback to receive results
|
||||
- **CRITICAL — Agent-specific instructions ALWAYS override this default.** If an agent's definition file (`.claude/agents/*.md`) specifies `run_in_background: false`, that instruction takes highest priority. Subagents (Agent tool agents) CANNOT receive hook callbacks, so they MUST use `run_in_background: false` for CLI calls that produce required results.
|
||||
- **After CLI call (main conversation only)**: Stop output immediately - let CLI execute in background. **DO NOT use TaskOutput polling** - wait for hook callback to receive results
|
||||
|
||||
### CLI Analysis Calls
|
||||
- **Wait for results**: MUST wait for CLI analysis to complete before taking any write action. Do NOT proceed with fixes while analysis is running
|
||||
|
||||
@@ -56,7 +56,23 @@ color: yellow
|
||||
**Step-by-step execution**:
|
||||
|
||||
```
|
||||
0. Load planning notes → Extract phase-level constraints (NEW)
|
||||
0. Load project context (MANDATORY - from init.md products)
|
||||
a. Read .workflow/project-tech.json (if exists)
|
||||
→ tech_stack, architecture_type, key_components, build_system, test_framework
|
||||
→ Usage: Populate plan.json shared_context, set correct build/test commands,
|
||||
align task tech choices with actual project stack
|
||||
→ If missing: Fall back to context-package.project_context fields
|
||||
|
||||
b. Read .workflow/specs/*.md (if exists)
|
||||
→ coding_conventions, naming_rules, forbidden_patterns, quality_gates, custom_constraints
|
||||
→ Usage: Apply as HARD CONSTRAINTS on all tasks — implementation steps,
|
||||
acceptance criteria, and convergence.verification MUST respect these rules
|
||||
→ If empty/missing: No additional constraints (proceed normally)
|
||||
|
||||
NOTE: These files provide project-level context that supplements (not replaces)
|
||||
session-specific context from planning-notes.md and context-package.json.
|
||||
|
||||
1. Load planning notes → Extract phase-level constraints (NEW)
|
||||
Commands: Read('.workflow/active/{session-id}/planning-notes.md')
|
||||
Output: Consolidated constraints from all workflow phases
|
||||
Structure:
|
||||
@@ -67,16 +83,16 @@ color: yellow
|
||||
|
||||
USAGE: This is the PRIMARY source of constraints. All task generation MUST respect these constraints.
|
||||
|
||||
1. Load session metadata → Extract user input
|
||||
2. Load session metadata → Extract user input
|
||||
- User description: Original task/feature requirements
|
||||
- Project scope: User-specified boundaries and goals
|
||||
- Technical constraints: User-provided technical requirements
|
||||
|
||||
2. Load context package → Extract structured context
|
||||
3. Load context package → Extract structured context
|
||||
Commands: Read({{context_package_path}})
|
||||
Output: Complete context package object
|
||||
|
||||
3. Check existing plan (if resuming)
|
||||
4. Check existing plan (if resuming)
|
||||
- If IMPL_PLAN.md exists: Read for continuity
|
||||
- If task JSONs exist: Load for context
|
||||
|
||||
@@ -989,7 +1005,8 @@ Use `analysis_results.complexity` or task count to determine structure:
|
||||
### 3.4 Guidelines Checklist
|
||||
|
||||
**ALWAYS:**
|
||||
- **Load planning-notes.md FIRST**: Read planning-notes.md before context-package.json. Use its Consolidated Constraints as primary constraint source for all task generation
|
||||
- **Load project context FIRST**: Read `.workflow/project-tech.json` and `.workflow/specs/*.md` before any session-specific files. Apply specs/*.md as hard constraints on all tasks
|
||||
- **Load planning-notes.md SECOND**: Read planning-notes.md before context-package.json. Use its Consolidated Constraints as primary constraint source for all task generation
|
||||
- **Record N+1 Context**: Update `## N+1 Context` section with key decisions and deferred items
|
||||
- **Search Tool Priority**: ACE (`mcp__ace-tool__search_context`) → CCW (`mcp__ccw-tools__smart_search`) / Built-in (`Grep`, `Glob`, `Read`)
|
||||
- Apply Quantification Requirements to all requirements, acceptance criteria, and modification points
|
||||
|
||||
@@ -39,6 +39,33 @@ Phase 4: Output Generation
|
||||
|
||||
## Phase 1: Task Understanding
|
||||
|
||||
### Autonomous Initialization (execute before any analysis)
|
||||
|
||||
**These steps are MANDATORY and self-contained** -- the agent executes them regardless of caller prompt content. Callers do NOT need to repeat these instructions.
|
||||
|
||||
1. **Project Structure Discovery**:
|
||||
```bash
|
||||
ccw tool exec get_modules_by_depth '{}'
|
||||
```
|
||||
Store result as `project_structure` for module-aware file discovery in Phase 2.
|
||||
|
||||
2. **Output Schema Loading** (if output file path specified in prompt):
|
||||
- Exploration output → `cat ~/.ccw/workflows/cli-templates/schemas/explore-json-schema.json`
|
||||
- Other schemas as specified in prompt
|
||||
Read and memorize schema requirements BEFORE any analysis begins (feeds Phase 3 validation).
|
||||
|
||||
3. **Project Context Loading** (from spec system):
|
||||
- Load exploration specs using: `ccw spec load --category exploration`
|
||||
- Extract: `tech_stack`, `architecture`, `key_components`, `overview`
|
||||
- Usage: Align analysis scope and patterns with actual project technology choices
|
||||
- If no specs are returned, proceed with fresh analysis (no error).
|
||||
|
||||
4. **Task Keyword Search** (initial file discovery):
|
||||
```bash
|
||||
rg -l "{extracted_keywords}" --type {detected_lang}
|
||||
```
|
||||
Extract keywords from prompt task description, detect primary language from project structure, and run targeted search. Store results as `keyword_files` for Phase 2 scoping.
|
||||
|
||||
**Extract from prompt**:
|
||||
- Analysis target and scope
|
||||
- Analysis mode (quick-scan / deep-scan / dependency-map)
|
||||
@@ -96,7 +123,10 @@ RULES: {from prompt, if template specified} | analysis=READ-ONLY
|
||||
2. Gemini results: Semantic understanding, design intent → `discovery_source: "cli-analysis"`
|
||||
3. ACE search: Semantic code search → `discovery_source: "ace-search"`
|
||||
4. Dependency tracing: Import/export graph → `discovery_source: "dependency-trace"`
|
||||
5. Merge with source attribution and generate rationale for each file
|
||||
5. Merge with source attribution and generate for each file:
|
||||
- `rationale`: WHY the file was selected (selection basis)
|
||||
- `topic_relation`: HOW the file connects to the exploration angle/topic
|
||||
- `key_code`: Detailed descriptions of key symbols with locations (for relevance >= 0.7)
|
||||
|
||||
---
|
||||
|
||||
@@ -128,6 +158,12 @@ Every file entry MUST have:
|
||||
- BAD: "Related to auth" or "Relevant file"
|
||||
- `role` (required, enum): Structural classification of why it was selected
|
||||
- `discovery_source` (optional but recommended): How the file was found
|
||||
- `key_code` (strongly recommended for relevance >= 0.7): Array of {symbol, location?, description}
|
||||
- GOOD: [{"symbol": "AuthService.login()", "location": "L45-L78", "description": "JWT token generation with bcrypt verification, returns token pair"}]
|
||||
- BAD: [{"symbol": "login", "description": "login function"}]
|
||||
- `topic_relation` (strongly recommended for relevance >= 0.7): Connection from exploration angle perspective
|
||||
- GOOD: "Security exploration targets this file because JWT generation lacks token rotation"
|
||||
- BAD: "Related to security"
|
||||
|
||||
**Step 4: Pre-Output Validation Checklist**
|
||||
|
||||
@@ -141,6 +177,8 @@ Before writing ANY JSON output, verify:
|
||||
- [ ] Data types correct (string, integer, array, object)
|
||||
- [ ] Every file in relevant_files has: path + relevance + rationale + role
|
||||
- [ ] Every rationale is specific (>10 chars, not generic)
|
||||
- [ ] Files with relevance >= 0.7 have key_code with symbol + description (minLength 10)
|
||||
- [ ] Files with relevance >= 0.7 have topic_relation explaining connection to angle (minLength 15)
|
||||
|
||||
---
|
||||
|
||||
@@ -189,6 +227,8 @@ Brief summary:
|
||||
9. **Every file MUST have rationale**: Specific selection basis tied to the topic (not generic)
|
||||
10. **Every file MUST have role**: Classify as modify_target/dependency/pattern_reference/test_target/type_definition/integration_point/config/context_only
|
||||
11. **Track discovery source**: Record how each file was found (bash-scan/cli-analysis/ace-search/dependency-trace/manual)
|
||||
12. **Populate key_code for high-relevance files**: relevance >= 0.7 → key_code array with symbol, location, description
|
||||
13. **Populate topic_relation for high-relevance files**: relevance >= 0.7 → topic_relation explaining file-to-angle connection
|
||||
|
||||
**Bash Tool**:
|
||||
- Use `run_in_background=false` for all Bash/CLI calls to ensure foreground execution
|
||||
|
||||
@@ -54,6 +54,9 @@ When invoked with `process_docs: true` in input context:
|
||||
|
||||
## Input Context
|
||||
|
||||
**Project Context** (loaded from spec system at startup):
|
||||
- Load specs using: `ccw spec load --category "exploration architecture"` → tech_stack, architecture, key_components, conventions, constraints, quality_rules
|
||||
|
||||
```javascript
|
||||
{
|
||||
// Required
|
||||
@@ -123,10 +126,11 @@ const planObject = generatePlanFromSchema(schema, context)
|
||||
Phase 1: Schema & Context Loading
|
||||
├─ Read schema reference (plan-overview-base-schema or plan-overview-fix-schema)
|
||||
├─ Aggregate multi-angle context (explorations or diagnoses)
|
||||
├─ If no explorations: use "## Prior Analysis" block from task description as primary context
|
||||
└─ Determine output structure from schema
|
||||
|
||||
Phase 2: CLI Execution
|
||||
├─ Construct CLI command with planning template
|
||||
├─ Construct CLI command with planning template (include Prior Analysis context when no explorations)
|
||||
├─ Execute Gemini (fallback: Qwen → degraded mode)
|
||||
└─ Timeout: 60 minutes
|
||||
|
||||
@@ -149,7 +153,7 @@ Phase 5: Plan Quality Check (MANDATORY)
|
||||
│ ├─ Dependency correctness (no circular deps, proper ordering)
|
||||
│ ├─ Acceptance criteria quality (quantified, testable)
|
||||
│ ├─ Implementation steps sufficiency (2+ steps per task)
|
||||
│ └─ Constraint compliance (follows project-guidelines.json)
|
||||
│ └─ Constraint compliance (follows specs/*.md)
|
||||
├─ Parse check results and categorize issues
|
||||
└─ Decision:
|
||||
├─ No issues → Return plan to orchestrator
|
||||
@@ -170,7 +174,7 @@ TASK:
|
||||
• Identify dependencies and execution phases
|
||||
• Generate complexity-appropriate fields (rationale, verification, risks, code_skeleton, data_flow)
|
||||
MODE: analysis
|
||||
CONTEXT: @**/* | Memory: {context_summary}
|
||||
CONTEXT: @**/* | Memory: {context_summary}. If task description contains '## Prior Analysis', treat it as primary planning context with pre-analyzed files, findings, and recommendations.
|
||||
EXPECTED:
|
||||
## Summary
|
||||
[overview]
|
||||
@@ -226,9 +230,9 @@ EXPECTED:
|
||||
**Total**: [time]
|
||||
|
||||
CONSTRAINTS:
|
||||
- Follow schema structure from {schema_path}
|
||||
- Output as structured markdown text following the EXPECTED format above
|
||||
- Task IDs use format TASK-001, TASK-002, etc. (FIX-001 for fix-plan)
|
||||
- Complexity determines required fields:
|
||||
- Complexity determines required sections:
|
||||
* Low: base fields only
|
||||
* Medium: + rationale + verification + design_decisions
|
||||
* High: + risks + code_skeleton + data_flow
|
||||
@@ -253,8 +257,8 @@ function extractSection(cliOutput, header) {
|
||||
// Parse structured tasks from CLI output
|
||||
function extractStructuredTasks(cliOutput, complexity) {
|
||||
const tasks = []
|
||||
// Split by task headers (supports both TASK-NNN and T\d+ formats)
|
||||
const taskBlocks = cliOutput.split(/### (TASK-\d+|T\d+):/).slice(1)
|
||||
// Split by task headers (flexible: 1-3 #, optional colon, supports TASK-NNN and T\d+)
|
||||
const taskBlocks = cliOutput.split(/#{1,3}\s*(TASK-\d+|T\d+):?\s*/).slice(1)
|
||||
|
||||
for (let i = 0; i < taskBlocks.length; i += 2) {
|
||||
const rawId = taskBlocks[i].trim()
|
||||
@@ -501,7 +505,7 @@ function parseCLIOutput(cliOutput) {
|
||||
|
||||
```javascript
|
||||
// NOTE: relevant_files items are structured objects:
|
||||
// {path, relevance, rationale, role, discovery_source?, key_symbols?}
|
||||
// {path, relevance, rationale, role, discovery_source?, key_symbols?, key_code?, topic_relation?}
|
||||
function buildEnrichedContext(explorationsContext, explorationAngles) {
|
||||
const enriched = { relevant_files: [], patterns: [], dependencies: [], integration_points: [], constraints: [] }
|
||||
|
||||
@@ -563,6 +567,7 @@ function inferAction(title) {
|
||||
}
|
||||
|
||||
// NOTE: relevant_files items are structured objects with .path property
|
||||
// New fields: key_code? (array of {symbol, location?, description}), topic_relation? (string)
|
||||
function inferFile(task, ctx) {
|
||||
const files = ctx?.relevant_files || []
|
||||
const getPath = f => typeof f === 'string' ? f : f.path
|
||||
@@ -816,8 +821,8 @@ function validateTask(task) {
|
||||
- **Write BOTH plan.json AND .task/*.json files** (two-layer output)
|
||||
- Handle CLI errors with fallback chain
|
||||
|
||||
**Bash Tool**:
|
||||
- Use `run_in_background=false` for all Bash/CLI calls to ensure foreground execution
|
||||
**Bash Tool (OVERRIDE global CLAUDE.md default)**:
|
||||
- **MUST use `run_in_background: false`** for ALL Bash/CLI calls — results are required before proceeding. This overrides any global `run_in_background: true` default.
|
||||
|
||||
**NEVER**:
|
||||
- Execute implementation (return plan only)
|
||||
@@ -846,7 +851,7 @@ After generating plan.json, **MUST** execute CLI quality check before returning
|
||||
| **Dependencies** | No circular deps, correct ordering | Yes |
|
||||
| **Convergence Criteria** | Quantified and testable (not vague) | No |
|
||||
| **Implementation Steps** | 2+ actionable steps per task | No |
|
||||
| **Constraint Compliance** | Follows project-guidelines.json | Yes |
|
||||
| **Constraint Compliance** | Follows specs/*.md | Yes |
|
||||
|
||||
### CLI Command Format
|
||||
|
||||
@@ -855,7 +860,7 @@ Use `ccw cli` with analysis mode to validate plan against quality dimensions:
|
||||
```bash
|
||||
ccw cli -p "Validate plan quality: completeness, granularity, dependencies, convergence criteria, implementation steps, constraint compliance" \
|
||||
--tool gemini --mode analysis \
|
||||
--context "@{plan_json_path} @{task_dir}/*.json @.workflow/project-guidelines.json"
|
||||
--context "@{plan_json_path} @{task_dir}/*.json @.workflow/specs/*.md"
|
||||
```
|
||||
|
||||
**Expected Output Structure**:
|
||||
|
||||
@@ -37,6 +37,8 @@ jq --arg ts "$(date -Iseconds)" '.status="in_progress" | .status_history += [{"f
|
||||
- Existing documentation and code examples
|
||||
- Project CLAUDE.md standards
|
||||
- **context-package.json** (when available in workflow tasks)
|
||||
- **project-tech.json** (if exists) → tech_stack, architecture, key_components
|
||||
- **specs/*.md** (if exists) → conventions, constraints, quality_rules
|
||||
|
||||
**Context Package** :
|
||||
`context-package.json` provides artifact paths - read using Read tool or ccw session:
|
||||
@@ -453,7 +455,7 @@ function buildCliCommand(task, cliTool, cliPrompt) {
|
||||
|
||||
**Auto-Check Workflow Context**:
|
||||
- Verify session context paths are provided in agent prompt
|
||||
- If missing, request session context from workflow:execute
|
||||
- If missing, request session context from workflow-execute
|
||||
- Never assume default paths without explicit session context
|
||||
|
||||
### 5. Problem-Solving
|
||||
|
||||
@@ -75,6 +75,20 @@ if (file_exists(contextPackagePath)) {
|
||||
}
|
||||
```
|
||||
|
||||
**1.1b Project Context Loading** (MANDATORY):
|
||||
```javascript
|
||||
// Load project-level context (from spec system)
|
||||
// These provide foundational constraints for ALL context gathering
|
||||
const projectSpecs = Bash('ccw spec load --category "exploration architecture" --stdin');
|
||||
const projectTech = projectSpecs?.tech_stack ? projectSpecs : null;
|
||||
const projectGuidelines = projectSpecs?.coding_conventions ? projectSpecs : null;
|
||||
|
||||
// Usage:
|
||||
// - projectTech → Populate project_context fields (tech_stack, architecture_patterns)
|
||||
// - projectGuidelines → Apply as constraints during relevance scoring and conflict detection
|
||||
// - If missing: Proceed with fresh analysis (discover from codebase)
|
||||
```
|
||||
|
||||
**1.2 Foundation Setup**:
|
||||
```javascript
|
||||
// 1. Initialize CodexLens (if available)
|
||||
@@ -275,6 +289,10 @@ score = (0.4 × direct_match) + // Filename/path match
|
||||
(0.1 × dependency_link) // Connection strength
|
||||
|
||||
// Filter: Include only score > 0.5
|
||||
|
||||
// Apply projectGuidelines constraints (from 1.1b) when available:
|
||||
// - Boost files matching projectGuidelines.quality_gates patterns
|
||||
// - Penalize files matching projectGuidelines.forbidden_patterns
|
||||
```
|
||||
|
||||
**3.2 Dependency Graph**
|
||||
@@ -292,19 +310,23 @@ Merge with conflict resolution:
|
||||
|
||||
```javascript
|
||||
const context = {
|
||||
// Priority: Project docs > Existing code > Web examples
|
||||
architecture: ref_docs.patterns || code.structure,
|
||||
// Priority: projectTech/projectGuidelines (1.1b) > Project docs > Existing code > Web examples
|
||||
architecture: projectTech?.architecture_type || ref_docs.patterns || code.structure,
|
||||
|
||||
conventions: {
|
||||
naming: ref_docs.standards || code.actual_patterns,
|
||||
error_handling: ref_docs.standards || code.patterns || web.best_practices
|
||||
naming: projectGuidelines?.naming_rules || ref_docs.standards || code.actual_patterns,
|
||||
error_handling: ref_docs.standards || code.patterns || web.best_practices,
|
||||
forbidden_patterns: projectGuidelines?.forbidden_patterns || [],
|
||||
quality_gates: projectGuidelines?.quality_gates || []
|
||||
},
|
||||
|
||||
tech_stack: {
|
||||
// Actual (package.json) takes precedence
|
||||
language: code.actual.language,
|
||||
frameworks: merge_unique([ref_docs.declared, code.actual]),
|
||||
libraries: code.actual.libraries
|
||||
// projectTech provides authoritative baseline; actual (package.json) fills gaps
|
||||
language: projectTech?.tech_stack?.language || code.actual.language,
|
||||
frameworks: merge_unique([projectTech?.tech_stack?.frameworks, ref_docs.declared, code.actual]),
|
||||
libraries: merge_unique([projectTech?.tech_stack?.libraries, code.actual.libraries]),
|
||||
build_system: projectTech?.build_system || code.actual.build_system,
|
||||
test_framework: projectTech?.test_framework || code.actual.test_framework
|
||||
},
|
||||
|
||||
// Web examples fill gaps
|
||||
@@ -314,9 +336,9 @@ const context = {
|
||||
```
|
||||
|
||||
**Conflict Resolution**:
|
||||
1. Architecture: Docs > Code > Web
|
||||
2. Conventions: Declared > Actual > Industry
|
||||
3. Tech Stack: Actual (package.json) > Declared
|
||||
1. Architecture: projectTech > Docs > Code > Web
|
||||
2. Conventions: projectGuidelines > Declared > Actual > Industry
|
||||
3. Tech Stack: projectTech > Actual (package.json) > Declared
|
||||
4. Missing: Use web examples
|
||||
|
||||
**3.5 Brainstorm Artifacts Integration**
|
||||
@@ -381,6 +403,8 @@ Calculate risk level based on:
|
||||
- Existing file count (<5: low, 5-15: medium, >15: high)
|
||||
- API/architecture/data model changes
|
||||
- Breaking changes identification
|
||||
- Violations of projectGuidelines.forbidden_patterns (from 1.1b, if available)
|
||||
- Deviations from projectGuidelines.coding_conventions (from 1.1b, if available)
|
||||
|
||||
**3.7 Context Packaging & Output**
|
||||
|
||||
|
||||
@@ -35,6 +35,9 @@ Phase 5: Fix & Verification
|
||||
|
||||
## Phase 1: Bug Analysis
|
||||
|
||||
**Load Project Context** (from spec system):
|
||||
- Load exploration specs using: `ccw spec load --category exploration` for tech stack context and coding constraints
|
||||
|
||||
**Session Setup**:
|
||||
```javascript
|
||||
const bugSlug = bug_description.toLowerCase().replace(/[^a-z0-9]+/g, '-').substring(0, 30)
|
||||
|
||||
@@ -26,6 +26,10 @@ color: green
|
||||
|
||||
### 1.1 Input Context
|
||||
|
||||
**Project Context** (load at startup):
|
||||
- Read `.workflow/project-tech.json` (if exists) → tech_stack, architecture
|
||||
- Read `.workflow/specs/*.md` (if exists) → constraints, conventions
|
||||
|
||||
```javascript
|
||||
{
|
||||
issue_ids: string[], // Issue IDs only (e.g., ["GH-123", "GH-124"])
|
||||
|
||||
293
.claude/agents/team-supervisor.md
Normal file
293
.claude/agents/team-supervisor.md
Normal 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.
|
||||
403
.claude/agents/team-worker.md
Normal file
403
.claude/agents/team-worker.md
Normal file
@@ -0,0 +1,403 @@
|
||||
---
|
||||
name: team-worker
|
||||
description: |
|
||||
Unified worker agent for team-lifecycle. Contains all shared team behavior
|
||||
(Phase 1 Task Discovery, Phase 5 Report + Fast-Advance, Message Bus, Consensus
|
||||
Handling, Inner Loop lifecycle). Loads role-specific Phase 2-4 logic from a
|
||||
role_spec markdown file passed in the prompt.
|
||||
|
||||
Examples:
|
||||
- Context: Coordinator spawns analyst worker
|
||||
user: "role: analyst\nrole_spec: .claude/skills/team-lifecycle/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"
|
||||
assistant: "Loading role spec, processing all DRAFT-* tasks in inner loop"
|
||||
commentary: Agent detects inner_loop=true, loops Phase 1-5 for each same-prefix task
|
||||
color: green
|
||||
---
|
||||
|
||||
You are a **team-lifecycle worker agent**. You execute a specific role within a team pipeline. Your behavior is split into:
|
||||
|
||||
- **Built-in phases** (Phase 1, Phase 5): Task discovery, reporting, fast-advance, inner loop — defined below.
|
||||
- **Role-specific phases** (Phase 2-4): Loaded from a role_spec markdown file.
|
||||
|
||||
---
|
||||
|
||||
## Prompt Input Parsing
|
||||
|
||||
Parse the following fields from your prompt:
|
||||
|
||||
| Field | Required | Description |
|
||||
|-------|----------|-------------|
|
||||
| `role` | Yes | Role name (analyst, writer, planner, executor, tester, reviewer, architect, fe-developer, fe-qa) |
|
||||
| `role_spec` | Yes | Path to role-spec .md file containing Phase 2-4 instructions |
|
||||
| `session` | Yes | Session folder path (e.g., `.workflow/.team/TLS-xxx-2026-02-27`) |
|
||||
| `session_id` | Yes | Session ID (folder name, e.g., `TLS-xxx-2026-02-27`). Used directly as `session_id` param for all message bus operations |
|
||||
| `team_name` | Yes | Team name for SendMessage |
|
||||
| `requirement` | Yes | Original task/requirement description |
|
||||
| `inner_loop` | Yes | `true` or `false` — whether to loop through same-prefix tasks |
|
||||
|
||||
---
|
||||
|
||||
## Role Spec Loading
|
||||
|
||||
1. `Read` the file at `role_spec` path
|
||||
2. Parse **frontmatter** (YAML between `---` markers) to extract metadata:
|
||||
- `prefix`: Task prefix to filter (e.g., `RESEARCH`, `DRAFT`, `IMPL`)
|
||||
- `inner_loop`: Override from frontmatter if present
|
||||
- `discuss_rounds`: Array of discuss round IDs this role handles
|
||||
- `delegates_to`: (DEPRECATED - team workers cannot delegate to other agents) Array for documentation only
|
||||
- `message_types`: Success/error/fix message type mappings
|
||||
3. Parse **body** (content after frontmatter) to get Phase 2-4 execution instructions
|
||||
4. Store parsed metadata and instructions for use in execution phases
|
||||
|
||||
---
|
||||
|
||||
## Execution Flow
|
||||
|
||||
```
|
||||
Entry:
|
||||
Parse prompt → extract role, role_spec, session, session_id, team_name, inner_loop
|
||||
Read role_spec → parse frontmatter + body (Phase 2-4 instructions)
|
||||
Load wisdom files from <session>/wisdom/ (if exist)
|
||||
|
||||
context_accumulator = [] ← inner_loop only, in-memory across iterations
|
||||
|
||||
Main Loop:
|
||||
Phase 1: Task Discovery [built-in]
|
||||
Phase 2-4: Execute Role Spec [from .md]
|
||||
Phase 5: Report [built-in]
|
||||
inner_loop=true AND more same-prefix tasks? → Phase 5-L → back to Phase 1
|
||||
inner_loop=false OR no more tasks? → Phase 5-F → STOP
|
||||
```
|
||||
|
||||
**Inner loop** (`inner_loop=true`): Processes ALL same-prefix tasks sequentially in a single agent instance. `context_accumulator` maintains context across task iterations for knowledge continuity.
|
||||
|
||||
| Step | Phase 5-L (loop) | Phase 5-F (final) |
|
||||
|------|-----------------|------------------|
|
||||
| TaskUpdate completed | YES | YES |
|
||||
| team_msg state_update | YES | YES |
|
||||
| Accumulate summary | YES | - |
|
||||
| SendMessage to coordinator | NO | YES (all tasks) |
|
||||
| Fast-Advance check | - | YES |
|
||||
|
||||
**Interrupt conditions** (break inner loop immediately):
|
||||
- consensus_blocked HIGH → SendMessage → STOP
|
||||
- Cumulative errors >= 3 → SendMessage → STOP
|
||||
|
||||
---
|
||||
|
||||
## Phase 1: Task Discovery (Built-in)
|
||||
|
||||
Execute on every loop iteration:
|
||||
|
||||
1. Call `TaskList()` to get all tasks
|
||||
2. **Filter** tasks matching ALL criteria:
|
||||
- Subject starts with this role's `prefix` + `-` (e.g., `DRAFT-`, `IMPL-`)
|
||||
- Status is `pending`
|
||||
- `blockedBy` list is empty (all dependencies resolved)
|
||||
- If role has `additional_prefixes` (e.g., reviewer handles REVIEW-* + QUALITY-* + IMPROVE-*), check all prefixes
|
||||
3. **No matching tasks?**
|
||||
- If first iteration → report idle, SendMessage "No tasks found for [role]", STOP
|
||||
- If inner loop continuation → proceed to Phase 5-F (all done)
|
||||
4. **Has matching tasks** → pick first by ID order
|
||||
5. `TaskGet(taskId)` → read full task details
|
||||
6. `TaskUpdate({ taskId: taskId, status: "in_progress" })` → claim the task
|
||||
|
||||
### Resume Artifact Check
|
||||
|
||||
After claiming a task, check if output artifacts already exist (indicates resume after crash):
|
||||
|
||||
- Parse expected artifact path from task description or role_spec conventions
|
||||
- Artifact exists AND appears complete → skip to Phase 5 (mark completed)
|
||||
- Artifact missing or incomplete → proceed to Phase 2
|
||||
|
||||
---
|
||||
|
||||
## Phase 2-4: Role-Specific Execution
|
||||
|
||||
**Execute the instructions loaded from role_spec body.**
|
||||
|
||||
The role_spec contains Phase 2, Phase 3, and Phase 4 sections with domain-specific logic. Follow those instructions exactly. Key integration points with built-in infrastructure:
|
||||
|
||||
## CRITICAL LIMITATION: No Agent Delegation
|
||||
|
||||
**Team workers CANNOT call the Agent() tool to spawn other agents.**
|
||||
|
||||
Test evidence shows that team members spawned via Agent tool do not have access to the Agent tool themselves. Only the coordinator (main conversation context) can spawn agents.
|
||||
|
||||
### Alternatives for Team Workers
|
||||
|
||||
When role-spec instructions require analysis or exploration:
|
||||
|
||||
**Option A: CLI Tools** (Recommended)
|
||||
```javascript
|
||||
Bash(`ccw cli -p "..." --tool gemini --mode analysis`, { run_in_background: false })
|
||||
```
|
||||
|
||||
**Option B: Direct Tools**
|
||||
Use Read, Grep, Glob, mcp__ace-tool__search_context directly.
|
||||
|
||||
**Option C: Request Coordinator Help**
|
||||
Send message to coordinator requesting agent delegation:
|
||||
```javascript
|
||||
mcp__ccw-tools__team_msg({
|
||||
operation: "log",
|
||||
session_id: sessionId,
|
||||
from: role,
|
||||
to: "coordinator",
|
||||
type: "agent_request",
|
||||
summary: "Request exploration agent for X",
|
||||
data: { reason: "...", scope: "..." }
|
||||
})
|
||||
SendMessage({ recipient: "coordinator", content: "..." })
|
||||
```
|
||||
|
||||
### Consensus Handling
|
||||
|
||||
When role-spec instructions require consensus/discussion, handle the verdict:
|
||||
|
||||
| Verdict | Severity | Action |
|
||||
|---------|----------|--------|
|
||||
| consensus_reached | - | Include action items in report, proceed to Phase 5 |
|
||||
| consensus_blocked | HIGH | Phase 5 SendMessage includes structured format (see below). Do NOT self-revise. |
|
||||
| consensus_blocked | MEDIUM | Phase 5 SendMessage includes warning. Proceed normally. |
|
||||
| consensus_blocked | LOW | Treat as consensus_reached with notes. |
|
||||
|
||||
**consensus_blocked SendMessage format**:
|
||||
|
||||
```
|
||||
[<role>] <task-id> complete. Discuss <round-id>: consensus_blocked (severity=<severity>)
|
||||
Divergences: <top-3-divergent-points>
|
||||
Action items: <prioritized-items>
|
||||
Recommendation: <revise|proceed-with-caution|escalate>
|
||||
Artifact: <artifact-path>
|
||||
Discussion: <session-folder>/discussions/<round-id>-discussion.md
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Phase 5: Report + Fast-Advance (Built-in)
|
||||
|
||||
After Phase 4 completes, determine Phase 5 variant (see Execution Flow for decision table).
|
||||
|
||||
### Phase 5-L: Loop Completion (inner_loop=true AND more same-prefix tasks pending)
|
||||
|
||||
1. **TaskUpdate**: Mark current task `completed`
|
||||
2. **Message Bus**: Log state_update (combines state publish + audit log)
|
||||
```
|
||||
mcp__ccw-tools__team_msg(
|
||||
operation="log",
|
||||
session_id=<session_id>,
|
||||
from=<role>,
|
||||
type="state_update",
|
||||
data={
|
||||
status: "task_complete",
|
||||
task_id: "<task-id>",
|
||||
ref: "<artifact-path>",
|
||||
key_findings: <from Phase 4>,
|
||||
decisions: <from Phase 4>,
|
||||
files_modified: <from Phase 4>,
|
||||
artifact_path: "<artifact-path>",
|
||||
verification: "<verification_method>"
|
||||
}
|
||||
)
|
||||
```
|
||||
> `to` defaults to "coordinator", `summary` auto-generated. `type="state_update"` auto-syncs data to `meta.json.role_state[<role>]`.
|
||||
3. **Accumulate** to `context_accumulator` (in-memory):
|
||||
```
|
||||
context_accumulator.append({
|
||||
task: "<task-id>",
|
||||
artifact: "<output-path>",
|
||||
key_decisions: <from Phase 4>,
|
||||
discuss_verdict: <from Phase 4 or "none">,
|
||||
discuss_rating: <from Phase 4 or null>,
|
||||
summary: "<brief summary>",
|
||||
files_modified: <from Phase 4>
|
||||
})
|
||||
```
|
||||
4. **Interrupt check**: consensus_blocked HIGH or errors >= 3 → SendMessage → STOP
|
||||
5. **Loop**: Return to Phase 1
|
||||
|
||||
**Phase 5-L does NOT**: SendMessage to coordinator, Fast-Advance, spawn successors.
|
||||
|
||||
### Phase 5-F: Final Report (no more same-prefix tasks OR inner_loop=false)
|
||||
|
||||
1. **TaskUpdate**: Mark current task `completed`
|
||||
2. **Message Bus**: Log state_update (same call as Phase 5-L step 2)
|
||||
3. **Compile final report** and **SendMessage** to coordinator:
|
||||
```javascript
|
||||
SendMessage({
|
||||
type: "message",
|
||||
recipient: "coordinator",
|
||||
content: "[<role>] <final-report>",
|
||||
summary: "[<role>] Final report delivered"
|
||||
})
|
||||
```
|
||||
Report contents: tasks completed (count + list), artifacts produced (paths), files modified (with evidence), discuss results (verdicts + ratings), key decisions (from context_accumulator), verification summary, warnings/issues.
|
||||
4. **Fast-Advance Check**: Call `TaskList()`, find pending tasks whose blockedBy are ALL completed, apply rules:
|
||||
|
||||
| Condition | Action |
|
||||
|-----------|--------|
|
||||
| Same-prefix successor (inner loop role) | Do NOT spawn — main agent handles via inner loop |
|
||||
| 1 ready task, simple linear successor, different prefix | Spawn directly via `Agent(run_in_background: true)` + log `fast_advance` |
|
||||
| Multiple ready tasks (parallel window) | SendMessage to coordinator (needs orchestration) |
|
||||
| No ready tasks + others running | SendMessage to coordinator (status update) |
|
||||
| No ready tasks + nothing running | SendMessage to coordinator (pipeline may be complete) |
|
||||
| Checkpoint task (e.g., spec->impl transition) | SendMessage to coordinator (needs user confirmation) |
|
||||
|
||||
### Fast-Advance Spawn
|
||||
|
||||
When fast-advancing to a different-prefix successor:
|
||||
|
||||
```
|
||||
Agent({
|
||||
subagent_type: "team-worker",
|
||||
description: "Spawn <successor-role> worker",
|
||||
team_name: <team_name>,
|
||||
name: "<successor-role>",
|
||||
run_in_background: true,
|
||||
prompt: `## Role Assignment
|
||||
role: <successor-role>
|
||||
role_spec: <derive from SKILL path>/role-specs/<successor-role>.md
|
||||
session: <session>
|
||||
session_id: <session_id>
|
||||
team_name: <team_name>
|
||||
requirement: <requirement>
|
||||
inner_loop: <true|false based on successor role>`
|
||||
})
|
||||
```
|
||||
|
||||
After spawning, MUST log to message bus (passive log, NOT a SendMessage):
|
||||
|
||||
```
|
||||
mcp__ccw-tools__team_msg(
|
||||
operation="log",
|
||||
session_id=<session_id>,
|
||||
from=<role>,
|
||||
type="fast_advance",
|
||||
summary="[<role>] fast-advanced <completed-task-id> → spawned <successor-role> for <successor-task-id>"
|
||||
)
|
||||
```
|
||||
|
||||
Coordinator reads this on next callback to reconcile `active_workers`.
|
||||
|
||||
---
|
||||
|
||||
## Knowledge Transfer & Wisdom
|
||||
|
||||
### Upstream Context Loading (Phase 2)
|
||||
|
||||
The worker MUST load available cross-role context before executing role-spec Phase 2:
|
||||
|
||||
| Source | Method | Priority |
|
||||
|--------|--------|----------|
|
||||
| Upstream role state | `team_msg(operation="get_state", role=<upstream_role>)` | **Primary** — O(1) from meta.json |
|
||||
| Upstream artifacts | Read files referenced in the state's artifact paths | Secondary — for large content |
|
||||
| Wisdom files | Read `<session>/wisdom/*.md` | Always load if exists |
|
||||
| Exploration cache | Check `<session>/explorations/cache-index.json` | Before new explorations |
|
||||
|
||||
> **Legacy fallback**: If `get_state` returns null (older sessions), fall back to reading `<session>/shared-memory.json`.
|
||||
|
||||
### Downstream Context Publishing (Phase 4)
|
||||
|
||||
After Phase 4 verification, the worker MUST publish its contributions:
|
||||
|
||||
1. **Artifact**: Write deliverable to `<session>/artifacts/<prefix>-<task-id>-<name>.md`
|
||||
2. **State data**: Prepare payload for Phase 5 `state_update` message (see Phase 5-L step 2 for schema)
|
||||
3. **Wisdom**: Append new patterns to `learnings.md`, decisions to `decisions.md`, issues to `issues.md`
|
||||
4. **Context accumulator** (inner_loop only): Append summary (see Phase 5-L step 3 for schema). Maintain full accumulator for context continuity across iterations.
|
||||
|
||||
### Wisdom Files
|
||||
|
||||
```
|
||||
<session>/wisdom/learnings.md ← New patterns discovered
|
||||
<session>/wisdom/decisions.md ← Architecture/design decisions
|
||||
<session>/wisdom/conventions.md ← Codebase conventions
|
||||
<session>/wisdom/issues.md ← Risks and known issues
|
||||
```
|
||||
|
||||
Load in Phase 2 to inform execution. Contribute in Phase 4/5 with discoveries.
|
||||
|
||||
---
|
||||
|
||||
## Message Bus Protocol
|
||||
|
||||
Always use `mcp__ccw-tools__team_msg` for team communication.
|
||||
|
||||
### log (with state_update) — Primary for Phase 5
|
||||
|
||||
| Param | Value |
|
||||
|-------|-------|
|
||||
| operation | "log" |
|
||||
| session_id | `<session_id>` (NOT team_name) |
|
||||
| from | `<role>` |
|
||||
| type | "state_update" for completion; or role_spec message_types for non-state messages |
|
||||
| data | structured state payload (auto-synced to meta.json when type="state_update"). Use `data.ref` for artifact paths |
|
||||
|
||||
> **Defaults**: `to` defaults to "coordinator", `summary` auto-generated as `[<from>] <type> → <to>`.
|
||||
> When `type="state_update"`: data is auto-synced to `meta.json.role_state[<role>]`. Top-level keys (`pipeline_mode`, `pipeline_stages`, `team_name`, `task_description`) are promoted to meta root.
|
||||
|
||||
### get_state — Primary for Phase 2
|
||||
|
||||
```
|
||||
mcp__ccw-tools__team_msg(
|
||||
operation="get_state",
|
||||
session_id=<session_id>,
|
||||
role=<upstream_role> // omit to get ALL role states
|
||||
)
|
||||
```
|
||||
|
||||
Returns `role_state[<role>]` from meta.json.
|
||||
|
||||
### broadcast — For team-wide signals
|
||||
|
||||
```
|
||||
mcp__ccw-tools__team_msg(
|
||||
operation="broadcast",
|
||||
session_id=<session_id>,
|
||||
from=<role>,
|
||||
type=<type>
|
||||
)
|
||||
```
|
||||
|
||||
Equivalent to `log` with `to="all"`. Summary auto-generated.
|
||||
|
||||
**CLI fallback** (if MCP tool unavailable):
|
||||
```
|
||||
ccw team log --session-id <session_id> --from <role> --type <type> --json
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Role Isolation Rules
|
||||
|
||||
| Allowed | Prohibited |
|
||||
|---------|-----------|
|
||||
| Process own prefix tasks | Process other role's prefix tasks |
|
||||
| SendMessage to coordinator | Directly communicate with other workers |
|
||||
| Use CLI tools for analysis/exploration | Create tasks for other roles |
|
||||
| Fast-advance simple successors | Spawn parallel worker batches |
|
||||
| Write to own artifacts + wisdom | Modify resources outside own scope |
|
||||
|
||||
---
|
||||
|
||||
## Error Handling
|
||||
|
||||
| Scenario | Resolution |
|
||||
|----------|------------|
|
||||
| Role spec file not found | Report error via SendMessage, STOP |
|
||||
| CLI tool failure | Retry once. Still fails → log warning, continue with available data |
|
||||
| Cumulative errors >= 3 | SendMessage to coordinator with error summary, STOP |
|
||||
| No tasks found | SendMessage idle status, STOP |
|
||||
| Context missing (prior doc, template) | Request from coordinator via SendMessage |
|
||||
| Agent crash mid-loop | Self-healing: completed tasks are safe (TaskUpdate + artifacts on disk). Coordinator detects orphaned in_progress task on resume, resets to pending, re-spawns. New agent resumes via Resume Artifact Check. |
|
||||
|
||||
---
|
||||
|
||||
## Output Tag
|
||||
|
||||
All output lines must be prefixed with `[<role>]` tag for coordinator message routing.
|
||||
File diff suppressed because it is too large
Load Diff
@@ -15,28 +15,21 @@ Main process orchestrator: intent analysis → workflow selection → command ch
|
||||
|
||||
| Skill | 内部流水线 |
|
||||
|-------|-----------|
|
||||
| `workflow-lite-plan` | 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` | 6-phase TDD plan → verify |
|
||||
| `workflow-tdd-plan` | 6-phase TDD plan → verify |
|
||||
| `workflow-test-fix` | session → context → analysis → gen → cycle |
|
||||
| `workflow-multi-cli-plan` | ACE context → CLI discussion → plan → execute |
|
||||
| `review-cycle` | session/module review → fix orchestration |
|
||||
| `brainstorm` | auto/single-role → artifacts → analysis → synthesis |
|
||||
| `spec-generator` | product-brief → PRD → architecture → epics |
|
||||
| `workflow:collaborative-plan-with-file` | understanding agent → parallel agents → plan-note.md |
|
||||
| `workflow:req-plan-with-file` | requirement decomposition → issue creation → execution-plan.json |
|
||||
| `workflow:roadmap-with-file` | strategic requirement roadmap → issue creation → execution-plan.json |
|
||||
| `workflow:integration-test-cycle` | explore → test dev → test-fix cycle → reflection |
|
||||
| `workflow:refactor-cycle` | tech debt discovery → prioritize → execute → validate |
|
||||
| `team-planex` | planner + executor wave pipeline(边规划边执行)|
|
||||
| `team-iterdev` | 迭代开发团队(planner → developer → reviewer 循环)|
|
||||
| `team-lifecycle` | 全生命周期团队(spec → impl → test)|
|
||||
| `team-issue` | issue 解决团队(discover → plan → execute)|
|
||||
| `team-testing` | 测试团队(strategy → generate → execute → analyze)|
|
||||
| `team-quality-assurance` | QA 团队(scout → strategist → generator → executor → analyst)|
|
||||
| `team-brainstorm` | 团队头脑风暴(facilitator → participants → synthesizer)|
|
||||
| `team-uidesign` | UI 设计团队(designer → implementer dual-track)|
|
||||
|
||||
独立命令(仍使用 colon 格式):workflow:brainstorm-with-file, workflow:debug-with-file, workflow:analyze-with-file, workflow:collaborative-plan-with-file, workflow:req-plan-with-file, workflow:integration-test-cycle, workflow:refactor-cycle, workflow:unified-execute-with-file, workflow:clean, workflow:init, workflow:init-guidelines, workflow:ui-design:*, issue:*, workflow:session:*
|
||||
| `team-planex` | planner + executor wave pipeline(适合大量零散 issue 或 roadmap 产出的清晰 issue)|
|
||||
|
||||
## Core Concept: Self-Contained Skills (自包含 Skill)
|
||||
|
||||
@@ -51,24 +44,21 @@ Main process orchestrator: intent analysis → workflow selection → command ch
|
||||
|
||||
| 单元类型 | Skill | 说明 |
|
||||
|---------|-------|------|
|
||||
| 轻量 Plan+Execute | `workflow-lite-plan` | 内部完成 plan→execute |
|
||||
| 轻量 Plan+Execute | `workflow-lite-plan` → `workflow-lite-execute` | plan handoff 到 execute,分离 Skill,TodoWrite 跟踪延续 (LP-Phase → LE-Phase) |
|
||||
| 标准 Planning | `workflow-plan` → `workflow-execute` | plan 和 execute 是独立 Skill |
|
||||
| TDD Planning | `workflow-tdd` → `workflow-execute` | tdd-plan 和 execute 是独立 Skill |
|
||||
| TDD Planning | `workflow-tdd-plan` → `workflow-execute` | tdd-plan 和 execute 是独立 Skill |
|
||||
| 规格驱动 | `spec-generator` → `workflow-plan` → `workflow-execute` | 规格文档驱动完整开发 |
|
||||
| 测试流水线 | `workflow-test-fix` | 内部完成 gen→cycle |
|
||||
| 代码审查 | `review-cycle` | 内部完成 review→fix |
|
||||
| 多CLI协作 | `workflow-multi-cli-plan` | ACE context → CLI discussion → plan → execute |
|
||||
| 协作规划 | `workflow:collaborative-plan-with-file` | 多 agent 协作生成 plan-note.md |
|
||||
| 需求路线图 | `workflow:req-plan-with-file` | 需求拆解→issue 创建→执行计划 |
|
||||
| 多CLI协作 | `workflow-multi-cli-plan` | ACE context → CLI discussion → plan → Skill(lite-execute) |
|
||||
| 分析→规划 | `workflow:analyze-with-file` → `workflow-lite-plan` → `workflow-lite-execute` | 协作分析产物自动传递给 lite-plan,Skill 调用 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` | 探索后正式规划+执行 |
|
||||
| 协作规划 | `workflow:collaborative-plan-with-file` → `workflow:unified-execute-with-file` | 多 agent 协作规划→通用执行 |
|
||||
| 需求路线图 | `workflow:roadmap-with-file` → `team-planex` | 需求拆解→issue 创建→wave pipeline 执行(需明确 roadmap 关键词)|
|
||||
| 集成测试循环 | `workflow:integration-test-cycle` | 自迭代集成测试闭环 |
|
||||
| 重构循环 | `workflow:refactor-cycle` | 技术债务发现→重构→验证 |
|
||||
| 团队 Plan+Execute | `team-planex` | 2 人团队 wave pipeline,边规划边执行 |
|
||||
| 团队迭代开发 | `team-iterdev` | 多角色迭代开发闭环 |
|
||||
| 团队全生命周期 | `team-lifecycle` | spec→impl→test 全流程 |
|
||||
| 团队 Issue | `team-issue` | 多角色协作 issue 解决 |
|
||||
| 团队测试 | `team-testing` | 多角色测试流水线 |
|
||||
| 团队 QA | `team-quality-assurance` | 多角色质量保障闭环 |
|
||||
| 团队头脑风暴 | `team-brainstorm` | 多角色协作头脑风暴 |
|
||||
| 团队 UI 设计 | `team-uidesign` | dual-track 设计+实现 |
|
||||
|
||||
## Execution Model
|
||||
|
||||
@@ -136,27 +126,23 @@ function analyzeIntent(input) {
|
||||
function detectTaskType(text) {
|
||||
const patterns = {
|
||||
'bugfix-hotfix': /urgent|production|critical/ && /fix|bug/,
|
||||
// With-File workflows (documented exploration with multi-CLI collaboration)
|
||||
// With-File workflows (documented exploration → auto chain to lite-plan)
|
||||
// 0→1 Greenfield detection (priority over brainstorm/roadmap)
|
||||
'greenfield': /从零开始|from scratch|0.*to.*1|greenfield|全新.*开发|新项目|new project|build.*from.*ground/,
|
||||
'brainstorm': /brainstorm|ideation|头脑风暴|创意|发散思维|creative thinking|multi-perspective.*think|compare perspectives|探索.*可能/,
|
||||
'brainstorm-to-issue': /brainstorm.*issue|头脑风暴.*issue|idea.*issue|想法.*issue|从.*头脑风暴|convert.*brainstorm/,
|
||||
'debug-file': /debug.*document|hypothesis.*debug|troubleshoot.*track|investigate.*log|调试.*记录|假设.*验证|systematic debug|深度调试/,
|
||||
'analyze-file': /analyze.*document|explore.*concept|understand.*architecture|investigate.*discuss|collaborative analysis|分析.*讨论|深度.*理解|协作.*分析/,
|
||||
'collaborative-plan': /collaborative.*plan|协作.*规划|多人.*规划|multi.*agent.*plan|Plan Note|分工.*规划/,
|
||||
'req-plan': /roadmap|需求.*规划|需求.*拆解|requirement.*plan|req.*plan|progressive.*plan|路线.*图/,
|
||||
'roadmap': /roadmap|路线.*图/, // Narrowed: only explicit roadmap keywords (需求规划/需求拆解 moved to greenfield routing)
|
||||
'spec-driven': /spec.*gen|specification|PRD|产品需求|产品文档|产品规格/,
|
||||
// Cycle workflows (self-iterating with reflection)
|
||||
'integration-test': /integration.*test|集成测试|端到端.*测试|e2e.*test|integration.*cycle/,
|
||||
'refactor': /refactor|重构|tech.*debt|技术债务/,
|
||||
// Team workflows (multi-role collaboration, explicit "team" keyword required)
|
||||
// Team workflows (kept: team-planex only)
|
||||
'team-planex': /team.*plan.*exec|team.*planex|团队.*规划.*执行|并行.*规划.*执行|wave.*pipeline/,
|
||||
'team-iterdev': /team.*iter|team.*iterdev|迭代.*开发.*团队|iterative.*dev.*team/,
|
||||
'team-lifecycle': /team.*lifecycle|全生命周期|full.*lifecycle|spec.*impl.*test.*team/,
|
||||
'team-issue': /team.*issue.*resolv|团队.*issue|team.*resolve.*issue/,
|
||||
'team-testing': /team.*test|测试团队|comprehensive.*test.*team|全面.*测试.*团队/,
|
||||
'team-qa': /team.*qa|quality.*assurance.*team|QA.*团队|质量.*保障.*团队|团队.*质量/,
|
||||
'team-brainstorm': /team.*brainstorm|团队.*头脑风暴|team.*ideation|多人.*头脑风暴/,
|
||||
'team-uidesign': /team.*ui.*design|UI.*设计.*团队|dual.*track.*design|团队.*UI/,
|
||||
// Standard workflows
|
||||
'multi-cli-plan': /multi.*cli|多.*CLI|多模型.*协作|multi.*model.*collab/,
|
||||
'multi-cli': /multi.*cli|多.*CLI|多模型.*协作|multi.*model.*collab/,
|
||||
'bugfix': /fix|bug|error|crash|fail|debug/,
|
||||
'issue-batch': /issues?|batch/ && /fix|resolve/,
|
||||
'issue-transition': /issue workflow|structured workflow|queue|multi-stage/,
|
||||
@@ -165,6 +151,7 @@ function detectTaskType(text) {
|
||||
'ui-design': /ui|design|component|style/,
|
||||
'tdd': /tdd|test-driven|test first/,
|
||||
'test-fix': /test fail|fix test|failing test/,
|
||||
'test-gen': /generate test|写测试|add test|补充测试/,
|
||||
'review': /review|code review/,
|
||||
'documentation': /docs|documentation|readme/
|
||||
};
|
||||
@@ -202,34 +189,34 @@ async function clarifyRequirements(analysis) {
|
||||
function selectWorkflow(analysis) {
|
||||
const levelMap = {
|
||||
'bugfix-hotfix': { level: 2, flow: 'bugfix.hotfix' },
|
||||
// With-File workflows (documented exploration with multi-CLI collaboration)
|
||||
'brainstorm': { level: 4, flow: 'brainstorm-with-file' }, // Multi-perspective ideation
|
||||
'brainstorm-to-issue': { level: 4, flow: 'brainstorm-to-issue' }, // Brainstorm → Issue workflow
|
||||
'debug-file': { level: 3, flow: 'debug-with-file' }, // Hypothesis-driven debugging
|
||||
'analyze-file': { level: 3, flow: 'analyze-with-file' }, // Collaborative analysis
|
||||
// 0→1 Greenfield (complexity-adaptive routing)
|
||||
'greenfield': { level: analysis.complexity === 'high' ? 4 : 3,
|
||||
flow: analysis.complexity === 'high' ? 'greenfield-phased' // large: brainstorm → workflow-plan → execute
|
||||
: analysis.complexity === 'medium' ? 'greenfield-plan' // medium: brainstorm → workflow-plan → execute
|
||||
: 'brainstorm-to-plan' }, // small: brainstorm → workflow-plan
|
||||
// With-File workflows → auto chain to lite-plan
|
||||
'brainstorm': { level: 4, flow: 'brainstorm-to-plan' }, // brainstorm-with-file → workflow-plan
|
||||
'brainstorm-to-issue': { level: 4, flow: 'brainstorm-to-issue' }, // Brainstorm → Issue workflow
|
||||
'debug-file': { level: 3, flow: 'debug-with-file' }, // Hypothesis-driven debugging (standalone)
|
||||
'analyze-file': { level: 3, flow: 'analyze-to-plan' }, // analyze-with-file → lite-plan
|
||||
'collaborative-plan': { level: 3, flow: 'collaborative-plan' }, // Multi-agent collaborative planning
|
||||
'req-plan': { level: 4, flow: 'req-plan' }, // Requirement-level roadmap planning
|
||||
'roadmap': { level: 4, flow: 'roadmap' }, // roadmap → team-planex (explicit roadmap only)
|
||||
'spec-driven': { level: 4, flow: 'spec-driven' }, // spec-generator → plan → execute
|
||||
// Cycle workflows (self-iterating with reflection)
|
||||
'integration-test': { level: 3, flow: 'integration-test-cycle' }, // Self-iterating integration test
|
||||
'refactor': { level: 3, flow: 'refactor-cycle' }, // Tech debt discovery and refactoring
|
||||
// Team workflows (multi-role collaboration)
|
||||
'integration-test': { level: 3, flow: 'integration-test-cycle' },
|
||||
'refactor': { level: 3, flow: 'refactor-cycle' },
|
||||
// Team workflows (kept: team-planex only)
|
||||
'team-planex': { level: 'Team', flow: 'team-planex' },
|
||||
'team-iterdev': { level: 'Team', flow: 'team-iterdev' },
|
||||
'team-lifecycle': { level: 'Team', flow: 'team-lifecycle' },
|
||||
'team-issue': { level: 'Team', flow: 'team-issue' },
|
||||
'team-testing': { level: 'Team', flow: 'team-testing' },
|
||||
'team-qa': { level: 'Team', flow: 'team-qa' },
|
||||
'team-brainstorm': { level: 'Team', flow: 'team-brainstorm' },
|
||||
'team-uidesign': { level: 'Team', flow: 'team-uidesign' },
|
||||
// Standard workflows
|
||||
'multi-cli-plan': { level: 3, flow: 'multi-cli-plan' }, // Multi-CLI collaborative planning
|
||||
'multi-cli': { level: 3, flow: 'multi-cli-plan' },
|
||||
'bugfix': { level: 2, flow: 'bugfix.standard' },
|
||||
'issue-batch': { level: 'Issue', flow: 'issue' },
|
||||
'issue-transition': { level: 2.5, flow: 'rapid-to-issue' }, // Bridge workflow
|
||||
'issue-transition': { level: 2.5, flow: 'rapid-to-issue' },
|
||||
'exploration': { level: 4, flow: 'full' },
|
||||
'quick-task': { level: 2, flow: 'rapid' },
|
||||
'ui-design': { level: analysis.complexity === 'high' ? 4 : 3, flow: 'ui' },
|
||||
'tdd': { level: 3, flow: 'tdd' },
|
||||
'test-gen': { level: 3, flow: 'test-gen' },
|
||||
'test-fix': { level: 3, flow: 'test-fix-gen' },
|
||||
'review': { level: 3, flow: 'review-cycle-fix' },
|
||||
'documentation': { level: 2, flow: 'docs' },
|
||||
@@ -281,18 +268,19 @@ function buildCommandChain(workflow, analysis) {
|
||||
{ cmd: 'workflow-lite-plan', args: `"${analysis.goal}"` }
|
||||
],
|
||||
|
||||
// With-File workflows (documented exploration with multi-CLI collaboration)
|
||||
'brainstorm-with-file': [
|
||||
{ cmd: 'workflow:brainstorm-with-file', args: `"${analysis.goal}"` }
|
||||
// Note: Has built-in post-completion options (create plan, create issue, deep analysis)
|
||||
// With-File → Auto Chain to lite-plan
|
||||
'analyze-to-plan': [
|
||||
{ cmd: 'workflow:analyze-with-file', args: `"${analysis.goal}"` },
|
||||
{ cmd: 'workflow-lite-plan', args: '' } // auto receives analysis artifacts (discussion.md)
|
||||
],
|
||||
|
||||
// Brainstorm-to-Issue workflow (bridge from brainstorm to issue execution)
|
||||
'brainstorm-to-issue': [
|
||||
// Note: Assumes brainstorm session already exists, or run brainstorm first
|
||||
{ cmd: 'issue:from-brainstorm', args: `SESSION="${extractBrainstormSession(analysis)}" --auto` },
|
||||
{ cmd: 'issue:queue', args: '' },
|
||||
{ cmd: 'issue:execute', args: '--queue auto' }
|
||||
'brainstorm-to-plan': [
|
||||
{ cmd: 'workflow:brainstorm-with-file', args: `"${analysis.goal}"` },
|
||||
{ cmd: 'workflow-plan', args: '' }, // formal planning with brainstorm artifacts
|
||||
{ cmd: 'workflow-execute', args: '' },
|
||||
...(analysis.constraints?.includes('skip-tests') ? [] : [
|
||||
{ cmd: 'workflow-test-fix', args: '' }
|
||||
])
|
||||
],
|
||||
|
||||
'debug-with-file': [
|
||||
@@ -300,32 +288,42 @@ function buildCommandChain(workflow, analysis) {
|
||||
// Note: Self-contained with hypothesis-driven iteration and Gemini validation
|
||||
],
|
||||
|
||||
'analyze-with-file': [
|
||||
{ cmd: 'workflow:analyze-with-file', args: `"${analysis.goal}"` }
|
||||
// Note: Self-contained with multi-round discussion and CLI exploration
|
||||
// Brainstorm-to-Issue workflow (bridge from brainstorm to issue execution)
|
||||
'brainstorm-to-issue': [
|
||||
{ cmd: 'issue:from-brainstorm', args: `SESSION="${extractBrainstormSession(analysis)}" --auto` },
|
||||
{ cmd: 'issue:queue', args: '' },
|
||||
{ cmd: 'issue:execute', args: '--queue auto' }
|
||||
],
|
||||
|
||||
// 0→1 Greenfield (complexity-adaptive)
|
||||
'greenfield-plan': [
|
||||
{ cmd: 'workflow:brainstorm-with-file', args: `"${analysis.goal}"` },
|
||||
{ cmd: 'workflow-plan', args: '' }, // formal planning after exploration
|
||||
{ cmd: 'workflow-execute', args: '' },
|
||||
...(analysis.constraints?.includes('skip-tests') ? [] : [
|
||||
{ cmd: 'workflow-test-fix', args: '' }
|
||||
])
|
||||
],
|
||||
|
||||
'greenfield-phased': [
|
||||
{ cmd: 'workflow:brainstorm-with-file', args: `"${analysis.goal}"` },
|
||||
{ cmd: 'workflow-plan', args: '' }, // formal planning after exploration
|
||||
{ cmd: 'workflow-execute', args: '' },
|
||||
{ cmd: 'review-cycle', args: '' },
|
||||
...(analysis.constraints?.includes('skip-tests') ? [] : [
|
||||
{ cmd: 'workflow-test-fix', args: '' }
|
||||
])
|
||||
],
|
||||
|
||||
// Universal Plan+Execute
|
||||
'collaborative-plan': [
|
||||
{ cmd: 'workflow:collaborative-plan-with-file', args: `"${analysis.goal}"` },
|
||||
{ cmd: 'workflow:unified-execute-with-file', args: '' }
|
||||
// Note: Plan Note → unified execution engine
|
||||
],
|
||||
|
||||
'req-plan': [
|
||||
{ cmd: 'workflow:req-plan-with-file', args: `"${analysis.goal}"` },
|
||||
'roadmap': [
|
||||
{ cmd: 'workflow:roadmap-with-file', args: `"${analysis.goal}"` },
|
||||
{ cmd: 'team-planex', args: '' }
|
||||
// Note: Requirement decomposition → issue creation → team-planex wave execution
|
||||
],
|
||||
|
||||
// Cycle workflows (self-iterating with reflection)
|
||||
'integration-test-cycle': [
|
||||
{ cmd: 'workflow:integration-test-cycle', args: `"${analysis.goal}"` }
|
||||
// Note: Self-contained explore → test → fix cycle with reflection
|
||||
],
|
||||
|
||||
'refactor-cycle': [
|
||||
{ cmd: 'workflow:refactor-cycle', args: `"${analysis.goal}"` }
|
||||
// Note: Self-contained tech debt discovery → refactor → validate
|
||||
],
|
||||
|
||||
// Level 3 - Standard
|
||||
@@ -338,11 +336,25 @@ function buildCommandChain(workflow, analysis) {
|
||||
])
|
||||
],
|
||||
|
||||
// Level 4 - Spec-Driven Full Pipeline
|
||||
'spec-driven': [
|
||||
{ cmd: 'spec-generator', args: `"${analysis.goal}"` },
|
||||
{ cmd: 'workflow-plan', args: '' },
|
||||
{ cmd: 'workflow-execute', args: '' },
|
||||
...(analysis.constraints?.includes('skip-tests') ? [] : [
|
||||
{ cmd: 'workflow-test-fix', args: '' }
|
||||
])
|
||||
],
|
||||
|
||||
'tdd': [
|
||||
{ cmd: 'workflow-tdd', args: `"${analysis.goal}"` },
|
||||
{ cmd: 'workflow-tdd-plan', args: `"${analysis.goal}"` },
|
||||
{ cmd: 'workflow-execute', args: '' }
|
||||
],
|
||||
|
||||
'test-gen': [
|
||||
{ cmd: 'workflow-test-fix', args: `"${analysis.goal}"` }
|
||||
],
|
||||
|
||||
'test-fix-gen': [
|
||||
{ cmd: 'workflow-test-fix', args: `"${analysis.goal}"` }
|
||||
],
|
||||
@@ -360,7 +372,7 @@ function buildCommandChain(workflow, analysis) {
|
||||
{ cmd: 'workflow-execute', args: '' }
|
||||
],
|
||||
|
||||
// Level 4 - Full
|
||||
// Level 4 - Full Exploration (brainstorm → formal planning → execute)
|
||||
'full': [
|
||||
{ cmd: 'brainstorm', args: `"${analysis.goal}"` },
|
||||
{ cmd: 'workflow-plan', args: '' },
|
||||
@@ -370,6 +382,15 @@ function buildCommandChain(workflow, analysis) {
|
||||
])
|
||||
],
|
||||
|
||||
// Cycle workflows (self-iterating with reflection)
|
||||
'integration-test-cycle': [
|
||||
{ cmd: 'workflow:integration-test-cycle', args: `"${analysis.goal}"` }
|
||||
],
|
||||
|
||||
'refactor-cycle': [
|
||||
{ cmd: 'workflow:refactor-cycle', args: `"${analysis.goal}"` }
|
||||
],
|
||||
|
||||
// Issue Workflow
|
||||
'issue': [
|
||||
{ cmd: 'issue:discover', args: '' },
|
||||
@@ -378,37 +399,9 @@ function buildCommandChain(workflow, analysis) {
|
||||
{ cmd: 'issue:execute', args: '' }
|
||||
],
|
||||
|
||||
// Team Workflows (multi-role collaboration, self-contained)
|
||||
// Team Workflows (kept: team-planex only)
|
||||
'team-planex': [
|
||||
{ cmd: 'team-planex', args: `"${analysis.goal}"` }
|
||||
],
|
||||
|
||||
'team-iterdev': [
|
||||
{ cmd: 'team-iterdev', args: `"${analysis.goal}"` }
|
||||
],
|
||||
|
||||
'team-lifecycle': [
|
||||
{ cmd: 'team-lifecycle', args: `"${analysis.goal}"` }
|
||||
],
|
||||
|
||||
'team-issue': [
|
||||
{ cmd: 'team-issue', args: `"${analysis.goal}"` }
|
||||
],
|
||||
|
||||
'team-testing': [
|
||||
{ cmd: 'team-testing', args: `"${analysis.goal}"` }
|
||||
],
|
||||
|
||||
'team-qa': [
|
||||
{ cmd: 'team-quality-assurance', args: `"${analysis.goal}"` }
|
||||
],
|
||||
|
||||
'team-brainstorm': [
|
||||
{ cmd: 'team-brainstorm', args: `"${analysis.goal}"` }
|
||||
],
|
||||
|
||||
'team-uidesign': [
|
||||
{ cmd: 'team-uidesign', args: `"${analysis.goal}"` }
|
||||
]
|
||||
};
|
||||
|
||||
@@ -607,7 +600,7 @@ Phase 1: Analyze Intent
|
||||
+-- If clarity < 2 -> Phase 1.5: Clarify Requirements
|
||||
|
|
||||
Phase 2: Select Workflow & Build Chain
|
||||
|-- Map task_type -> Level (1/2/3/4/Issue)
|
||||
|-- Map task_type -> Level (2/3/4/Issue/Team)
|
||||
|-- Select flow based on complexity
|
||||
+-- Build command chain (Skill-based)
|
||||
|
|
||||
@@ -639,26 +632,22 @@ Phase 5: Execute Command Chain
|
||||
| "Add API endpoint" | feature (low) | 2 | workflow-lite-plan → workflow-test-fix |
|
||||
| "Fix login timeout" | bugfix | 2 | workflow-lite-plan → workflow-test-fix |
|
||||
| "Use issue workflow" | issue-transition | 2.5 | workflow-lite-plan(plan-only) → convert-to-plan → queue → execute |
|
||||
| "头脑风暴: 通知系统重构" | brainstorm | 4 | workflow:brainstorm-with-file |
|
||||
| "从头脑风暴创建 issue" | brainstorm-to-issue | 4 | issue:from-brainstorm → issue:queue → issue:execute |
|
||||
| "协作分析: 认证架构" | analyze-file | 3 | analyze-with-file → workflow-lite-plan |
|
||||
| "深度调试 WebSocket" | debug-file | 3 | workflow:debug-with-file |
|
||||
| "协作分析: 认证架构优化" | analyze-file | 3 | workflow:analyze-with-file |
|
||||
| "从零开始: 用户系统" | greenfield (medium) | 3 | brainstorm-with-file → workflow-plan → workflow-execute → workflow-test-fix |
|
||||
| "greenfield: 大型平台" | greenfield (high) | 4 | brainstorm-with-file → workflow-plan → workflow-execute → review-cycle → workflow-test-fix |
|
||||
| "头脑风暴: 通知系统" | brainstorm | 4 | brainstorm-with-file → workflow-plan → workflow-execute → workflow-test-fix |
|
||||
| "从头脑风暴创建 issue" | brainstorm-to-issue | 4 | issue:from-brainstorm → issue:queue → issue:execute |
|
||||
| "协作规划: 实时通知系统" | collaborative-plan | 3 | collaborative-plan-with-file → unified-execute-with-file |
|
||||
| "需求规划: OAuth + 2FA" | req-plan | 4 | req-plan-with-file → team-planex |
|
||||
| "roadmap: OAuth + 2FA" | roadmap | 4 | roadmap-with-file → team-planex |
|
||||
| "specification: 用户系统" | spec-driven | 4 | spec-generator → workflow-plan → workflow-execute → workflow-test-fix |
|
||||
| "集成测试: 支付流程" | integration-test | 3 | workflow:integration-test-cycle |
|
||||
| "重构 auth 模块" | refactor | 3 | workflow:refactor-cycle |
|
||||
| "multi-cli plan: API设计" | multi-cli-plan | 3 | workflow-multi-cli-plan → workflow-test-fix |
|
||||
| "OAuth2 system" | feature (high) | 3 | workflow-plan → workflow-execute → review-cycle → workflow-test-fix |
|
||||
| "Implement with TDD" | tdd | 3 | workflow-tdd → workflow-execute |
|
||||
| "Implement with TDD" | tdd | 3 | workflow-tdd-plan → workflow-execute |
|
||||
| "Uncertain: real-time" | exploration | 4 | brainstorm → workflow-plan → workflow-execute → workflow-test-fix |
|
||||
| "team planex: 用户系统" | team-planex | Team | team-planex |
|
||||
| "迭代开发团队: 支付模块" | team-iterdev | Team | team-iterdev |
|
||||
| "全生命周期: 通知服务" | team-lifecycle | Team | team-lifecycle |
|
||||
| "team resolve issue #42" | team-issue | Team | team-issue |
|
||||
| "测试团队: 全面测试认证" | team-testing | Team | team-testing |
|
||||
| "QA 团队: 质量保障支付" | team-qa | Team | team-quality-assurance |
|
||||
| "团队头脑风暴: API 设计" | team-brainstorm | Team | team-brainstorm |
|
||||
| "团队 UI 设计: 仪表盘" | team-uidesign | Team | team-uidesign |
|
||||
|
||||
---
|
||||
|
||||
@@ -668,10 +657,11 @@ Phase 5: Execute Command Chain
|
||||
2. **Intent-Driven** - Auto-select workflow based on task intent
|
||||
3. **Skill-Based Chaining** - Build command chain by composing independent Skills
|
||||
4. **Self-Contained Skills** - 每个 Skill 内部处理完整流水线,是天然的最小执行单元
|
||||
5. **Progressive Clarification** - Low clarity triggers clarification phase
|
||||
6. **TODO Tracking** - Use CCW prefix to isolate workflow todos
|
||||
7. **Error Handling** - Retry/skip/abort at Skill level
|
||||
8. **User Control** - Optional user confirmation at each phase
|
||||
5. **Auto Chain** - With-File 产物自动传递给下游 Skill(如 analyze → lite-plan)
|
||||
6. **Progressive Clarification** - Low clarity triggers clarification phase
|
||||
7. **TODO Tracking** - Use CCW prefix to isolate workflow todos
|
||||
8. **Error Handling** - Retry/skip/abort at Skill level
|
||||
9. **User Control** - Optional user confirmation at each phase
|
||||
|
||||
---
|
||||
|
||||
@@ -715,114 +705,51 @@ todos = [
|
||||
"complexity": "medium"
|
||||
},
|
||||
"command_chain": [
|
||||
{
|
||||
"index": 0,
|
||||
"command": "workflow-lite-plan",
|
||||
"status": "completed"
|
||||
},
|
||||
{
|
||||
"index": 1,
|
||||
"command": "workflow-test-fix",
|
||||
"status": "running"
|
||||
}
|
||||
{ "index": 0, "command": "workflow-lite-plan", "status": "completed" },
|
||||
{ "index": 1, "command": "workflow-test-fix", "status": "running" }
|
||||
],
|
||||
"current_index": 1
|
||||
}
|
||||
```
|
||||
|
||||
**Status Values**:
|
||||
- `running`: Workflow executing commands
|
||||
- `completed`: All commands finished
|
||||
- `failed`: User aborted or unrecoverable error
|
||||
- `error`: Command execution failed (during error handling)
|
||||
|
||||
**Command Status Values**:
|
||||
- `pending`: Not started
|
||||
- `running`: Currently executing
|
||||
- `completed`: Successfully finished
|
||||
- `failed`: Execution failed
|
||||
**Status Values**: `running` | `completed` | `failed` | `error`
|
||||
**Command Status Values**: `pending` | `running` | `completed` | `failed`
|
||||
|
||||
---
|
||||
|
||||
## With-File Workflows
|
||||
|
||||
**With-File workflows** provide documented exploration with multi-CLI collaboration. They are self-contained and generate comprehensive session artifacts.
|
||||
**With-File workflows** provide documented exploration with multi-CLI collaboration. They generate comprehensive session artifacts and can auto-chain to lite-plan for implementation.
|
||||
|
||||
| Workflow | Purpose | Key Features | Output Folder |
|
||||
|----------|---------|--------------|---------------|
|
||||
| **brainstorm-with-file** | Multi-perspective ideation | Gemini/Codex/Claude perspectives, diverge-converge cycles | `.workflow/.brainstorm/` |
|
||||
| **debug-with-file** | Hypothesis-driven debugging | Gemini validation, understanding evolution, NDJSON logging | `.workflow/.debug/` |
|
||||
| **analyze-with-file** | Collaborative analysis | Multi-round Q&A, CLI exploration, documented discussions | `.workflow/.analysis/` |
|
||||
| **collaborative-plan-with-file** | Multi-agent collaborative planning | Understanding agent + parallel agents, Plan Note shared doc | `.workflow/.planning/` |
|
||||
| **req-plan-with-file** | Requirement roadmap planning | Requirement decomposition, issue creation, execution-plan.json | `.workflow/.planning/` |
|
||||
| Workflow | Purpose | Auto Chain | Output Folder |
|
||||
|----------|---------|------------|---------------|
|
||||
| **brainstorm-with-file** | Multi-perspective ideation | → workflow-plan → workflow-execute (auto) | `.workflow/.brainstorm/` |
|
||||
| **debug-with-file** | Hypothesis-driven debugging | Standalone (self-contained) | `.workflow/.debug/` |
|
||||
| **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-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
|
||||
- **debug-file**: 深度调试, 假设验证, systematic debug, hypothesis debug
|
||||
- **analyze-file**: 协作分析, 深度理解, collaborative analysis, explore concept
|
||||
- **collaborative-plan**: 协作规划, 多人规划, collaborative plan, multi-agent plan, Plan Note
|
||||
- **req-plan**: roadmap, 需求规划, 需求拆解, requirement plan, progressive plan
|
||||
|
||||
**Characteristics**:
|
||||
1. **Self-Contained**: Each workflow handles its own iteration loop
|
||||
2. **Documented Process**: Creates evolving documents (brainstorm.md, understanding.md, discussion.md)
|
||||
3. **Multi-CLI**: Uses Gemini/Codex/Claude for different perspectives
|
||||
4. **Built-in Post-Completion**: Offers follow-up options (create plan, issue, etc.)
|
||||
|
||||
---
|
||||
|
||||
## Team Workflows
|
||||
|
||||
**Team workflows** provide multi-role collaboration for complex tasks. Each team skill is self-contained with internal role routing via `--role=xxx`.
|
||||
|
||||
| Workflow | Roles | Pipeline | Use Case |
|
||||
|----------|-------|----------|----------|
|
||||
| **team-planex** | planner + executor | wave pipeline(边规划边执行)| 需要并行规划和执行的任务 |
|
||||
| **team-iterdev** | planner → developer → reviewer | 迭代开发循环 | 需要多轮迭代的开发任务 |
|
||||
| **team-lifecycle** | spec → impl → test | 全生命周期 | 从需求到测试的完整流程 |
|
||||
| **team-issue** | discover → plan → execute | issue 解决 | 多角色协作解决 issue |
|
||||
| **team-testing** | strategy → generate → execute → analyze | 测试流水线 | 全面测试覆盖 |
|
||||
| **team-quality-assurance** | scout → strategist → generator → executor → analyst | QA 闭环 | 质量保障全流程 |
|
||||
| **team-brainstorm** | facilitator → participants → synthesizer | 团队头脑风暴 | 多角色协作头脑风暴 |
|
||||
| **team-uidesign** | designer → implementer | dual-track 设计+实现 | UI 设计与实现并行 |
|
||||
|
||||
**Detection Keywords**:
|
||||
- **team-planex**: team planex, 团队规划执行, wave pipeline
|
||||
- **team-iterdev**: team iterdev, 迭代开发团队, iterative dev team
|
||||
- **team-lifecycle**: team lifecycle, 全生命周期, full lifecycle
|
||||
- **team-issue**: team issue, 团队 issue, team resolve issue
|
||||
- **team-testing**: team test, 测试团队, comprehensive test team
|
||||
- **team-qa**: team qa, QA 团队, 质量保障团队
|
||||
- **team-brainstorm**: team brainstorm, 团队头脑风暴, team ideation
|
||||
- **team-uidesign**: team ui design, UI 设计团队, dual track design
|
||||
|
||||
**Characteristics**:
|
||||
1. **Self-Contained**: Each team skill handles internal role coordination
|
||||
2. **Role-Based Routing**: All roles invoke the same skill with `--role=xxx`
|
||||
3. **Shared Memory**: Roles communicate via shared-memory.json and message bus
|
||||
4. **Auto Mode Support**: All team skills support `-y`/`--yes` for skip confirmations
|
||||
- **roadmap**: roadmap, 需求规划, 需求拆解, requirement plan, progressive plan
|
||||
- **spec-driven**: specification, PRD, 产品需求, 产品文档
|
||||
|
||||
---
|
||||
|
||||
## Cycle Workflows
|
||||
|
||||
**Cycle workflows** provide self-iterating development cycles with reflection-driven strategy adjustment. Each cycle is autonomous with built-in test-fix loops and quality gates.
|
||||
**Cycle workflows** provide self-iterating development cycles with reflection-driven strategy adjustment.
|
||||
|
||||
| Workflow | Pipeline | Key Features | Output Folder |
|
||||
|----------|----------|--------------|---------------|
|
||||
| **integration-test-cycle** | explore → test dev → test-fix → reflection | Self-iterating with max-iterations, auto continue | `.workflow/.test-cycle/` |
|
||||
| **refactor-cycle** | discover → prioritize → execute → validate | Multi-dimensional analysis, regression validation | `.workflow/.refactor-cycle/` |
|
||||
|
||||
**Detection Keywords**:
|
||||
- **integration-test**: integration test, 集成测试, 端到端测试, e2e test
|
||||
- **refactor**: refactor, 重构, tech debt, 技术债务
|
||||
|
||||
**Characteristics**:
|
||||
1. **Self-Iterating**: Autonomous test-fix loops until quality gate passes
|
||||
2. **Reflection-Driven**: Strategy adjusts based on previous iteration results
|
||||
3. **Continue Support**: `--continue` flag to resume interrupted sessions
|
||||
4. **Auto Mode Support**: `-y`/`--yes` for fully autonomous execution
|
||||
|
||||
---
|
||||
|
||||
## Utility Commands
|
||||
@@ -831,10 +758,11 @@ todos = [
|
||||
|
||||
| Command | Purpose |
|
||||
|---------|---------|
|
||||
| `workflow:unified-execute-with-file` | Universal execution engine - consumes plan output from collaborative-plan, req-plan, brainstorm |
|
||||
| `workflow:unified-execute-with-file` | Universal execution engine - consumes plan output from collaborative-plan, roadmap, brainstorm |
|
||||
| `workflow:clean` | Intelligent code cleanup - mainline detection, stale artifact removal |
|
||||
| `workflow:init` | Initialize `.workflow/project-tech.json` with project analysis |
|
||||
| `workflow:init-guidelines` | Interactive wizard to fill `project-guidelines.json` |
|
||||
| `workflow: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 |
|
||||
|
||||
---
|
||||
|
||||
@@ -848,9 +776,6 @@ todos = [
|
||||
/ccw -y "Add user authentication"
|
||||
/ccw --yes "Fix memory leak in WebSocket handler"
|
||||
|
||||
# Complex requirement (triggers clarification)
|
||||
/ccw "Optimize system performance"
|
||||
|
||||
# Bug fix
|
||||
/ccw "Fix memory leak in WebSocket handler"
|
||||
|
||||
@@ -863,35 +788,36 @@ todos = [
|
||||
# Multi-CLI collaborative planning
|
||||
/ccw "multi-cli plan: 支付网关API设计" # → workflow-multi-cli-plan → workflow-test-fix
|
||||
|
||||
# With-File workflows (documented exploration with multi-CLI collaboration)
|
||||
/ccw "头脑风暴: 用户通知系统重新设计" # → brainstorm-with-file
|
||||
/ccw "从头脑风暴 BS-通知系统-2025-01-28 创建 issue" # → brainstorm-to-issue (bridge)
|
||||
/ccw "深度调试: 系统随机崩溃问题" # → debug-with-file
|
||||
/ccw "协作分析: 理解现有认证架构的设计决策" # → analyze-with-file
|
||||
# 0→1 Greenfield development (exploration-first)
|
||||
/ccw "从零开始: 用户认证系统" # → brainstorm-with-file → workflow-plan → workflow-execute → workflow-test-fix
|
||||
/ccw "new project: 数据导出模块" # → brainstorm-with-file → workflow-plan → workflow-execute → workflow-test-fix
|
||||
/ccw "全新开发: 实时通知系统" # → brainstorm-with-file → workflow-plan → workflow-execute → review-cycle → workflow-test-fix
|
||||
|
||||
# Team workflows (multi-role collaboration)
|
||||
/ccw "team planex: 用户认证系统" # → team-planex (planner + executor wave pipeline)
|
||||
/ccw "迭代开发团队: 支付模块重构" # → team-iterdev (planner → developer → reviewer)
|
||||
/ccw "全生命周期: 通知服务开发" # → team-lifecycle (spec → impl → test)
|
||||
/ccw "team resolve issue #42" # → team-issue (discover → plan → execute)
|
||||
/ccw "测试团队: 全面测试认证模块" # → team-testing (strategy → generate → execute → analyze)
|
||||
/ccw "QA 团队: 质量保障支付流程" # → team-quality-assurance (scout → strategist → generator → executor → analyst)
|
||||
/ccw "团队头脑风暴: API 网关设计" # → team-brainstorm (facilitator → participants → synthesizer)
|
||||
/ccw "团队 UI 设计: 管理后台仪表盘" # → team-uidesign (designer → implementer dual-track)
|
||||
# With-File workflows → auto chain
|
||||
/ccw "协作分析: 理解现有认证架构的设计决策" # → analyze-with-file → workflow-lite-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)
|
||||
|
||||
# Spec-driven full pipeline
|
||||
/ccw "specification: 用户认证系统产品文档" # → spec-generator → workflow-plan → workflow-execute → workflow-test-fix
|
||||
|
||||
# Collaborative planning & requirement workflows
|
||||
/ccw "协作规划: 实时通知系统架构" # → collaborative-plan-with-file → unified-execute
|
||||
/ccw "需求规划: 用户认证 OAuth + 2FA" # → req-plan-with-file → team-planex
|
||||
/ccw "roadmap: 数据导出功能路线图" # → req-plan-with-file → team-planex
|
||||
/ccw "roadmap: 用户认证 OAuth + 2FA 路线图" # → roadmap-with-file → team-planex (explicit roadmap only)
|
||||
/ccw "roadmap: 数据导出功能路线图" # → roadmap-with-file → team-planex (explicit roadmap only)
|
||||
|
||||
# Team workflows (kept: team-planex)
|
||||
/ccw "team planex: 用户认证系统" # → team-planex (planner + executor wave pipeline)
|
||||
|
||||
# Cycle workflows (self-iterating)
|
||||
/ccw "集成测试: 支付流程端到端" # → integration-test-cycle
|
||||
/ccw "重构 auth 模块的技术债务" # → refactor-cycle
|
||||
/ccw "tech debt: 清理支付服务" # → refactor-cycle
|
||||
|
||||
# Utility commands (invoked directly, not auto-routed)
|
||||
# /workflow:unified-execute-with-file # 通用执行引擎(消费 plan 输出)
|
||||
# /workflow:clean # 智能代码清理
|
||||
# /workflow:init # 初始化项目状态
|
||||
# /workflow:init-guidelines # 交互式填充项目规范
|
||||
# /workflow:spec:setup # 初始化项目状态
|
||||
# /workflow:spec:add # 交互式填充项目规范
|
||||
# /workflow:status # 项目概览和工作流状态
|
||||
```
|
||||
|
||||
@@ -33,7 +33,7 @@ Creates tool-specific configuration directories:
|
||||
- `.gemini/settings.json`:
|
||||
```json
|
||||
{
|
||||
"contextfilename": ["CLAUDE.md","GEMINI.md"]
|
||||
"contextfilename": "CLAUDE.md"
|
||||
}
|
||||
```
|
||||
|
||||
@@ -41,7 +41,7 @@ Creates tool-specific configuration directories:
|
||||
- `.qwen/settings.json`:
|
||||
```json
|
||||
{
|
||||
"contextfilename": ["CLAUDE.md","QWEN.md"]
|
||||
"contextfilename": "CLAUDE.md"
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
359
.claude/commands/ddd/auto.md
Normal file
359
.claude/commands/ddd/auto.md
Normal 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
|
||||
```
|
||||
295
.claude/commands/ddd/doc-generate.md
Normal file
295
.claude/commands/ddd/doc-generate.md
Normal 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/`
|
||||
218
.claude/commands/ddd/doc-refresh.md
Normal file
218
.claude/commands/ddd/doc-refresh.md
Normal 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`)
|
||||
416
.claude/commands/ddd/execute.md
Normal file
416
.claude/commands/ddd/execute.md
Normal 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
|
||||
212
.claude/commands/ddd/index-build.md
Normal file
212
.claude/commands/ddd/index-build.md
Normal 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
|
||||
611
.claude/commands/ddd/plan.md
Normal file
611
.claude/commands/ddd/plan.md
Normal 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
|
||||
365
.claude/commands/ddd/scan.md
Normal file
365
.claude/commands/ddd/scan.md
Normal 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
|
||||
321
.claude/commands/ddd/sync.md
Normal file
321
.claude/commands/ddd/sync.md
Normal 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
|
||||
160
.claude/commands/ddd/update.md
Normal file
160
.claude/commands/ddd/update.md
Normal 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
|
||||
@@ -86,14 +86,14 @@ async function selectCommandCategory() {
|
||||
header: "Category",
|
||||
options: [
|
||||
{ label: "Planning", description: "lite-plan, plan, multi-cli-plan, tdd-plan, quick-plan-with-file" },
|
||||
{ label: "Execution", description: "lite-execute, execute, unified-execute-with-file" },
|
||||
{ label: "Execution", description: "execute, unified-execute-with-file" },
|
||||
{ label: "Testing", description: "test-fix-gen, test-cycle-execute, test-gen, tdd-verify" },
|
||||
{ label: "Review", description: "review-session-cycle, review-module-cycle, review-cycle-fix" },
|
||||
{ label: "Bug Fix", description: "lite-plan --bugfix, debug-with-file" },
|
||||
{ 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,24 +107,23 @@ async function selectCommandCategory() {
|
||||
async function selectCommand(category) {
|
||||
const commandOptions = {
|
||||
'Planning': [
|
||||
{ label: "/workflow:lite-plan", description: "Lightweight merged-mode planning" },
|
||||
{ label: "/workflow:plan", description: "Full planning with architecture design" },
|
||||
{ label: "/workflow:multi-cli-plan", description: "Multi-CLI collaborative planning (Gemini+Codex+Claude)" },
|
||||
{ label: "/workflow:tdd-plan", description: "TDD workflow planning with Red-Green-Refactor" },
|
||||
{ label: "/workflow-lite-plan", description: "Lightweight merged-mode planning" },
|
||||
{ label: "/workflow-plan", description: "Full planning with architecture design" },
|
||||
{ label: "/workflow-multi-cli-plan", description: "Multi-CLI collaborative planning (Gemini+Codex+Claude)" },
|
||||
{ label: "/workflow-tdd-plan", description: "TDD workflow planning with Red-Green-Refactor" },
|
||||
{ label: "/workflow:quick-plan-with-file", description: "Rapid planning with minimal docs" },
|
||||
{ label: "/workflow:plan-verify", description: "Verify plan against requirements" },
|
||||
{ label: "/workflow-plan-verify", description: "Verify plan against requirements" },
|
||||
{ label: "/workflow:replan", description: "Update plan and execute changes" }
|
||||
],
|
||||
'Execution': [
|
||||
{ label: "/workflow:lite-execute", description: "Execute from in-memory plan" },
|
||||
{ label: "/workflow:execute", description: "Execute from planning session" },
|
||||
{ label: "/workflow-execute", description: "Execute from planning session" },
|
||||
{ label: "/workflow:unified-execute-with-file", description: "Universal execution engine" }
|
||||
],
|
||||
'Testing': [
|
||||
{ label: "/workflow:test-fix-gen", description: "Generate test tasks for specific issues" },
|
||||
{ label: "/workflow:test-cycle-execute", description: "Execute iterative test-fix cycle (>=95% pass)" },
|
||||
{ label: "/workflow-test-fix", description: "Generate test tasks for specific issues" },
|
||||
{ label: "/workflow-test-fix", description: "Execute iterative test-fix cycle (>=95% pass)" },
|
||||
{ label: "/workflow:test-gen", description: "Generate comprehensive test suite" },
|
||||
{ label: "/workflow:tdd-verify", description: "Verify TDD workflow compliance" }
|
||||
{ label: "/workflow-tdd-verify", description: "Verify TDD workflow compliance" }
|
||||
],
|
||||
'Review': [
|
||||
{ label: "/workflow:review-session-cycle", description: "Session-based multi-dimensional code review" },
|
||||
@@ -133,7 +132,7 @@ async function selectCommand(category) {
|
||||
{ label: "/workflow:review", description: "Post-implementation review" }
|
||||
],
|
||||
'Bug Fix': [
|
||||
{ label: "/workflow:lite-plan", description: "Lightweight bug diagnosis and fix (with --bugfix flag)" },
|
||||
{ label: "/workflow-lite-plan", description: "Lightweight bug diagnosis and fix (with --bugfix flag)" },
|
||||
{ label: "/workflow:debug-with-file", description: "Hypothesis-driven debugging with documentation" }
|
||||
],
|
||||
'Brainstorm': [
|
||||
@@ -154,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" }
|
||||
]
|
||||
@@ -181,8 +180,8 @@ async function selectExecutionUnit() {
|
||||
header: "Unit",
|
||||
options: [
|
||||
// Planning + Execution Units
|
||||
{ label: "quick-implementation", description: "【lite-plan → lite-execute】" },
|
||||
{ label: "multi-cli-planning", description: "【multi-cli-plan → lite-execute】" },
|
||||
{ label: "quick-implementation", description: "【lite-plan】" },
|
||||
{ label: "multi-cli-planning", description: "【multi-cli-plan】" },
|
||||
{ label: "full-planning-execution", description: "【plan → execute】" },
|
||||
{ label: "verified-planning-execution", description: "【plan → plan-verify → execute】" },
|
||||
{ label: "replanning-execution", description: "【replan → execute】" },
|
||||
@@ -193,7 +192,7 @@ async function selectExecutionUnit() {
|
||||
// Review Units
|
||||
{ label: "code-review", description: "【review-*-cycle → review-cycle-fix】" },
|
||||
// Bug Fix Units
|
||||
{ label: "bug-fix", description: "【lite-plan --bugfix → lite-execute】" },
|
||||
{ label: "bug-fix", description: "【lite-plan --bugfix】" },
|
||||
// Issue Units
|
||||
{ label: "issue-workflow", description: "【discover → plan → queue → execute】" },
|
||||
{ label: "rapid-to-issue", description: "【lite-plan → convert-to-plan → queue → execute】" },
|
||||
@@ -303,10 +302,9 @@ async function defineSteps(templateDesign) {
|
||||
"description": "Quick implementation with testing",
|
||||
"level": 2,
|
||||
"steps": [
|
||||
{ "cmd": "/workflow:lite-plan", "args": "\"{{goal}}\"", "unit": "quick-implementation", "execution": { "type": "slash-command", "mode": "mainprocess" }, "contextHint": "Create lightweight implementation plan" },
|
||||
{ "cmd": "/workflow:lite-execute", "args": "--in-memory", "unit": "quick-implementation", "execution": { "type": "slash-command", "mode": "mainprocess" }, "contextHint": "Execute implementation based on plan" },
|
||||
{ "cmd": "/workflow:test-fix-gen", "unit": "test-validation", "execution": { "type": "slash-command", "mode": "mainprocess" }, "contextHint": "Generate test tasks" },
|
||||
{ "cmd": "/workflow:test-cycle-execute", "unit": "test-validation", "execution": { "type": "slash-command", "mode": "async" }, "contextHint": "Execute test-fix cycle until pass rate >= 95%" }
|
||||
{ "cmd": "/workflow-lite-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%" }
|
||||
]
|
||||
}
|
||||
```
|
||||
@@ -318,13 +316,13 @@ async function defineSteps(templateDesign) {
|
||||
"description": "Full workflow with verification, review, and testing",
|
||||
"level": 3,
|
||||
"steps": [
|
||||
{ "cmd": "/workflow:plan", "args": "\"{{goal}}\"", "unit": "verified-planning-execution", "execution": { "type": "slash-command", "mode": "mainprocess" }, "contextHint": "Create detailed implementation plan" },
|
||||
{ "cmd": "/workflow:plan-verify", "unit": "verified-planning-execution", "execution": { "type": "slash-command", "mode": "mainprocess" }, "contextHint": "Verify plan against requirements" },
|
||||
{ "cmd": "/workflow:execute", "unit": "verified-planning-execution", "execution": { "type": "slash-command", "mode": "async" }, "contextHint": "Execute implementation" },
|
||||
{ "cmd": "/workflow-plan", "args": "\"{{goal}}\"", "unit": "verified-planning-execution", "execution": { "type": "slash-command", "mode": "mainprocess" }, "contextHint": "Create detailed implementation plan" },
|
||||
{ "cmd": "/workflow-plan-verify", "unit": "verified-planning-execution", "execution": { "type": "slash-command", "mode": "mainprocess" }, "contextHint": "Verify plan against requirements" },
|
||||
{ "cmd": "/workflow-execute", "unit": "verified-planning-execution", "execution": { "type": "slash-command", "mode": "async" }, "contextHint": "Execute implementation" },
|
||||
{ "cmd": "/workflow:review-session-cycle", "unit": "code-review", "execution": { "type": "slash-command", "mode": "mainprocess" }, "contextHint": "Multi-dimensional code review" },
|
||||
{ "cmd": "/workflow:review-cycle-fix", "unit": "code-review", "execution": { "type": "slash-command", "mode": "mainprocess" }, "contextHint": "Fix review findings" },
|
||||
{ "cmd": "/workflow:test-fix-gen", "unit": "test-validation", "execution": { "type": "slash-command", "mode": "mainprocess" }, "contextHint": "Generate test tasks" },
|
||||
{ "cmd": "/workflow:test-cycle-execute", "unit": "test-validation", "execution": { "type": "slash-command", "mode": "async" }, "contextHint": "Execute test-fix cycle" }
|
||||
{ "cmd": "/workflow-test-fix", "unit": "test-validation", "execution": { "type": "slash-command", "mode": "mainprocess" }, "contextHint": "Generate test tasks" },
|
||||
{ "cmd": "/workflow-test-fix", "unit": "test-validation", "execution": { "type": "slash-command", "mode": "async" }, "contextHint": "Execute test-fix cycle" }
|
||||
]
|
||||
}
|
||||
```
|
||||
@@ -336,10 +334,9 @@ async function defineSteps(templateDesign) {
|
||||
"description": "Bug diagnosis and fix with testing",
|
||||
"level": 2,
|
||||
"steps": [
|
||||
{ "cmd": "/workflow:lite-plan", "args": "--bugfix \"{{goal}}\"", "unit": "bug-fix", "execution": { "type": "slash-command", "mode": "mainprocess" }, "contextHint": "Diagnose and plan bug fix" },
|
||||
{ "cmd": "/workflow:lite-execute", "args": "--in-memory", "unit": "bug-fix", "execution": { "type": "slash-command", "mode": "mainprocess" }, "contextHint": "Execute bug fix" },
|
||||
{ "cmd": "/workflow:test-fix-gen", "unit": "test-validation", "execution": { "type": "slash-command", "mode": "mainprocess" }, "contextHint": "Generate regression tests" },
|
||||
{ "cmd": "/workflow:test-cycle-execute", "unit": "test-validation", "execution": { "type": "slash-command", "mode": "async" }, "contextHint": "Verify fix with tests" }
|
||||
{ "cmd": "/workflow-lite-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" }
|
||||
]
|
||||
}
|
||||
```
|
||||
@@ -351,7 +348,7 @@ async function defineSteps(templateDesign) {
|
||||
"description": "Urgent production bug fix (no tests)",
|
||||
"level": 2,
|
||||
"steps": [
|
||||
{ "cmd": "/workflow:lite-plan", "args": "--hotfix \"{{goal}}\"", "unit": "standalone", "execution": { "type": "slash-command", "mode": "mainprocess" }, "contextHint": "Emergency hotfix mode" }
|
||||
{ "cmd": "/workflow-lite-plan", "args": "--hotfix \"{{goal}}\"", "unit": "standalone", "execution": { "type": "slash-command", "mode": "mainprocess" }, "contextHint": "Emergency hotfix mode" }
|
||||
]
|
||||
}
|
||||
```
|
||||
@@ -363,9 +360,9 @@ async function defineSteps(templateDesign) {
|
||||
"description": "Test-driven development with Red-Green-Refactor",
|
||||
"level": 3,
|
||||
"steps": [
|
||||
{ "cmd": "/workflow:tdd-plan", "args": "\"{{goal}}\"", "unit": "tdd-planning-execution", "execution": { "type": "slash-command", "mode": "mainprocess" }, "contextHint": "Create TDD task chain" },
|
||||
{ "cmd": "/workflow:execute", "unit": "tdd-planning-execution", "execution": { "type": "slash-command", "mode": "async" }, "contextHint": "Execute TDD cycle" },
|
||||
{ "cmd": "/workflow:tdd-verify", "unit": "standalone", "execution": { "type": "slash-command", "mode": "mainprocess" }, "contextHint": "Verify TDD compliance" }
|
||||
{ "cmd": "/workflow-tdd-plan", "args": "\"{{goal}}\"", "unit": "tdd-planning-execution", "execution": { "type": "slash-command", "mode": "mainprocess" }, "contextHint": "Create TDD task chain" },
|
||||
{ "cmd": "/workflow-execute", "unit": "tdd-planning-execution", "execution": { "type": "slash-command", "mode": "async" }, "contextHint": "Execute TDD cycle" },
|
||||
{ "cmd": "/workflow-tdd-verify", "unit": "standalone", "execution": { "type": "slash-command", "mode": "mainprocess" }, "contextHint": "Verify TDD compliance" }
|
||||
]
|
||||
}
|
||||
```
|
||||
@@ -379,8 +376,8 @@ async function defineSteps(templateDesign) {
|
||||
"steps": [
|
||||
{ "cmd": "/workflow:review-session-cycle", "unit": "code-review", "execution": { "type": "slash-command", "mode": "mainprocess" }, "contextHint": "Multi-dimensional code review" },
|
||||
{ "cmd": "/workflow:review-cycle-fix", "unit": "code-review", "execution": { "type": "slash-command", "mode": "mainprocess" }, "contextHint": "Fix review findings" },
|
||||
{ "cmd": "/workflow:test-fix-gen", "unit": "test-validation", "execution": { "type": "slash-command", "mode": "mainprocess" }, "contextHint": "Generate tests for fixes" },
|
||||
{ "cmd": "/workflow:test-cycle-execute", "unit": "test-validation", "execution": { "type": "slash-command", "mode": "async" }, "contextHint": "Verify fixes pass tests" }
|
||||
{ "cmd": "/workflow-test-fix", "unit": "test-validation", "execution": { "type": "slash-command", "mode": "mainprocess" }, "contextHint": "Generate tests for fixes" },
|
||||
{ "cmd": "/workflow-test-fix", "unit": "test-validation", "execution": { "type": "slash-command", "mode": "async" }, "contextHint": "Verify fixes pass tests" }
|
||||
]
|
||||
}
|
||||
```
|
||||
@@ -392,8 +389,8 @@ async function defineSteps(templateDesign) {
|
||||
"description": "Fix failing tests",
|
||||
"level": 3,
|
||||
"steps": [
|
||||
{ "cmd": "/workflow:test-fix-gen", "args": "\"{{goal}}\"", "unit": "test-validation", "execution": { "type": "slash-command", "mode": "mainprocess" }, "contextHint": "Generate test fix tasks" },
|
||||
{ "cmd": "/workflow:test-cycle-execute", "unit": "test-validation", "execution": { "type": "slash-command", "mode": "async" }, "contextHint": "Execute test-fix cycle" }
|
||||
{ "cmd": "/workflow-test-fix", "args": "\"{{goal}}\"", "unit": "test-validation", "execution": { "type": "slash-command", "mode": "mainprocess" }, "contextHint": "Generate test fix tasks" },
|
||||
{ "cmd": "/workflow-test-fix", "unit": "test-validation", "execution": { "type": "slash-command", "mode": "async" }, "contextHint": "Execute test-fix cycle" }
|
||||
]
|
||||
}
|
||||
```
|
||||
@@ -420,7 +417,7 @@ async function defineSteps(templateDesign) {
|
||||
"description": "Bridge lightweight planning to issue workflow",
|
||||
"level": 2,
|
||||
"steps": [
|
||||
{ "cmd": "/workflow:lite-plan", "args": "\"{{goal}}\"", "unit": "rapid-to-issue", "execution": { "type": "slash-command", "mode": "mainprocess" }, "contextHint": "Create lightweight plan" },
|
||||
{ "cmd": "/workflow-lite-plan", "args": "\"{{goal}}\"", "unit": "rapid-to-issue", "execution": { "type": "slash-command", "mode": "mainprocess" }, "contextHint": "Create lightweight plan" },
|
||||
{ "cmd": "/issue:convert-to-plan", "args": "--latest-lite-plan -y", "unit": "rapid-to-issue", "execution": { "type": "slash-command", "mode": "mainprocess" }, "contextHint": "Convert to issue plan" },
|
||||
{ "cmd": "/issue:queue", "unit": "rapid-to-issue", "execution": { "type": "slash-command", "mode": "mainprocess" }, "contextHint": "Form execution queue" },
|
||||
{ "cmd": "/issue:execute", "args": "--queue auto", "unit": "rapid-to-issue", "execution": { "type": "slash-command", "mode": "async" }, "contextHint": "Execute issue queue" }
|
||||
@@ -486,11 +483,11 @@ async function defineSteps(templateDesign) {
|
||||
"level": 4,
|
||||
"steps": [
|
||||
{ "cmd": "/brainstorm", "args": "\"{{goal}}\"", "unit": "standalone", "execution": { "type": "slash-command", "mode": "mainprocess" }, "contextHint": "Unified brainstorming with multi-perspective exploration" },
|
||||
{ "cmd": "/workflow:plan", "unit": "verified-planning-execution", "execution": { "type": "slash-command", "mode": "mainprocess" }, "contextHint": "Create detailed plan from brainstorm" },
|
||||
{ "cmd": "/workflow:plan-verify", "unit": "verified-planning-execution", "execution": { "type": "slash-command", "mode": "mainprocess" }, "contextHint": "Verify plan quality" },
|
||||
{ "cmd": "/workflow:execute", "unit": "verified-planning-execution", "execution": { "type": "slash-command", "mode": "async" }, "contextHint": "Execute implementation" },
|
||||
{ "cmd": "/workflow:test-fix-gen", "unit": "test-validation", "execution": { "type": "slash-command", "mode": "mainprocess" }, "contextHint": "Generate comprehensive tests" },
|
||||
{ "cmd": "/workflow:test-cycle-execute", "unit": "test-validation", "execution": { "type": "slash-command", "mode": "async" }, "contextHint": "Execute test cycle" }
|
||||
{ "cmd": "/workflow-plan", "unit": "verified-planning-execution", "execution": { "type": "slash-command", "mode": "mainprocess" }, "contextHint": "Create detailed plan from brainstorm" },
|
||||
{ "cmd": "/workflow-plan-verify", "unit": "verified-planning-execution", "execution": { "type": "slash-command", "mode": "mainprocess" }, "contextHint": "Verify plan quality" },
|
||||
{ "cmd": "/workflow-execute", "unit": "verified-planning-execution", "execution": { "type": "slash-command", "mode": "async" }, "contextHint": "Execute implementation" },
|
||||
{ "cmd": "/workflow-test-fix", "unit": "test-validation", "execution": { "type": "slash-command", "mode": "mainprocess" }, "contextHint": "Generate comprehensive tests" },
|
||||
{ "cmd": "/workflow-test-fix", "unit": "test-validation", "execution": { "type": "slash-command", "mode": "async" }, "contextHint": "Execute test cycle" }
|
||||
]
|
||||
}
|
||||
```
|
||||
@@ -502,10 +499,10 @@ async function defineSteps(templateDesign) {
|
||||
"description": "Multi-CLI collaborative planning with cross-verification",
|
||||
"level": 3,
|
||||
"steps": [
|
||||
{ "cmd": "/workflow:multi-cli-plan", "args": "\"{{goal}}\"", "unit": "multi-cli-planning", "execution": { "type": "slash-command", "mode": "mainprocess" }, "contextHint": "Gemini+Codex+Claude collaborative planning" },
|
||||
{ "cmd": "/workflow:lite-execute", "args": "--in-memory", "unit": "multi-cli-planning", "execution": { "type": "slash-command", "mode": "mainprocess" }, "contextHint": "Execute converged plan" },
|
||||
{ "cmd": "/workflow:test-fix-gen", "unit": "test-validation", "execution": { "type": "slash-command", "mode": "mainprocess" }, "contextHint": "Generate tests" },
|
||||
{ "cmd": "/workflow:test-cycle-execute", "unit": "test-validation", "execution": { "type": "slash-command", "mode": "async" }, "contextHint": "Execute test cycle" }
|
||||
{ "cmd": "/workflow-multi-cli-plan", "args": "\"{{goal}}\"", "unit": "multi-cli-planning", "execution": { "type": "slash-command", "mode": "mainprocess" }, "contextHint": "Gemini+Codex+Claude collaborative planning" },
|
||||
// lite-execute is now an internal phase of multi-cli-plan (not invoked separately)
|
||||
{ "cmd": "/workflow-test-fix", "unit": "test-validation", "execution": { "type": "slash-command", "mode": "mainprocess" }, "contextHint": "Generate tests" },
|
||||
{ "cmd": "/workflow-test-fix", "unit": "test-validation", "execution": { "type": "slash-command", "mode": "async" }, "contextHint": "Execute test cycle" }
|
||||
]
|
||||
}
|
||||
```
|
||||
@@ -530,7 +527,7 @@ Each command has input/output ports for pipeline composition:
|
||||
| tdd-plan | requirement | tdd-tasks | tdd-planning-execution |
|
||||
| replan | session, feedback | replan | replanning-execution |
|
||||
| **Execution** |
|
||||
| lite-execute | plan, multi-cli-plan | code | (multiple) |
|
||||
| ~~lite-execute~~ | _(internal phase of lite-plan/multi-cli-plan, not standalone)_ | code | — |
|
||||
| execute | detailed-plan, verified-plan, replan, tdd-tasks | code | (multiple) |
|
||||
| **Testing** |
|
||||
| test-fix-gen | failing-tests, session | test-tasks | test-validation |
|
||||
@@ -563,9 +560,9 @@ Each command has input/output ports for pipeline composition:
|
||||
|
||||
| Unit Name | Commands | Purpose |
|
||||
|-----------|----------|---------|
|
||||
| **quick-implementation** | lite-plan → lite-execute | Lightweight plan and execution |
|
||||
| **multi-cli-planning** | multi-cli-plan → lite-execute | Multi-perspective planning and execution |
|
||||
| **bug-fix** | lite-plan --bugfix → lite-execute | Bug diagnosis and fix |
|
||||
| **quick-implementation** | lite-plan (Phase 1: plan → Phase 2: execute) | Lightweight plan and execution |
|
||||
| **multi-cli-planning** | multi-cli-plan (Phase 1: plan → Phase 2: execute) | Multi-perspective planning and execution |
|
||||
| **bug-fix** | lite-plan --bugfix (Phase 1: plan → Phase 2: execute) | Bug diagnosis and fix |
|
||||
| **full-planning-execution** | plan → execute | Detailed planning and execution |
|
||||
| **verified-planning-execution** | plan → plan-verify → execute | Planning with verification |
|
||||
| **replanning-execution** | replan → execute | Update plan and execute |
|
||||
@@ -656,9 +653,9 @@ async function generateTemplate(design, steps, outputPath) {
|
||||
→ Level: 3 (Standard)
|
||||
→ Steps: Customize
|
||||
→ Step 1: /brainstorm (standalone, mainprocess)
|
||||
→ Step 2: /workflow:plan (verified-planning-execution, mainprocess)
|
||||
→ Step 3: /workflow:plan-verify (verified-planning-execution, mainprocess)
|
||||
→ Step 4: /workflow:execute (verified-planning-execution, async)
|
||||
→ Step 2: /workflow-plan (verified-planning-execution, mainprocess)
|
||||
→ Step 3: /workflow-plan-verify (verified-planning-execution, mainprocess)
|
||||
→ Step 4: /workflow-execute (verified-planning-execution, async)
|
||||
→ Step 5: /workflow:review-session-cycle (code-review, mainprocess)
|
||||
→ Step 6: /workflow:review-cycle-fix (code-review, mainprocess)
|
||||
→ Done
|
||||
|
||||
287
.claude/commands/idaw/add.md
Normal file
287
.claude/commands/idaw/add.md
Normal file
@@ -0,0 +1,287 @@
|
||||
---
|
||||
name: add
|
||||
description: Add IDAW tasks - manual creation or import from ccw issue
|
||||
argument-hint: "[-y|--yes] [--from-issue <id>[,<id>,...]] \"description\" [--type <task_type>] [--priority <1-5>]"
|
||||
allowed-tools: AskUserQuestion(*), Read(*), Bash(*), Write(*), Glob(*)
|
||||
---
|
||||
|
||||
# IDAW Add Command (/idaw:add)
|
||||
|
||||
## Auto Mode
|
||||
|
||||
When `--yes` or `-y`: Skip clarification questions, create task with inferred details.
|
||||
|
||||
## IDAW Task Schema
|
||||
|
||||
```json
|
||||
{
|
||||
"id": "IDAW-001",
|
||||
"title": "string",
|
||||
"description": "string",
|
||||
"status": "pending",
|
||||
"priority": 2,
|
||||
"task_type": null,
|
||||
"skill_chain": null,
|
||||
"context": {
|
||||
"affected_files": [],
|
||||
"acceptance_criteria": [],
|
||||
"constraints": [],
|
||||
"references": []
|
||||
},
|
||||
"source": {
|
||||
"type": "manual|import-issue",
|
||||
"issue_id": null,
|
||||
"issue_snapshot": null
|
||||
},
|
||||
"execution": {
|
||||
"session_id": null,
|
||||
"started_at": null,
|
||||
"completed_at": null,
|
||||
"skill_results": [],
|
||||
"git_commit": null,
|
||||
"error": null
|
||||
},
|
||||
"created_at": "ISO",
|
||||
"updated_at": "ISO"
|
||||
}
|
||||
```
|
||||
|
||||
**Valid task_type values**: `bugfix|bugfix-hotfix|feature|feature-complex|refactor|tdd|test|test-fix|review|docs`
|
||||
|
||||
## Implementation
|
||||
|
||||
### Phase 1: Parse Arguments
|
||||
|
||||
```javascript
|
||||
const args = $ARGUMENTS;
|
||||
const autoYes = /(-y|--yes)\b/.test(args);
|
||||
const fromIssue = args.match(/--from-issue\s+([\w,-]+)/)?.[1];
|
||||
const typeFlag = args.match(/--type\s+([\w-]+)/)?.[1];
|
||||
const priorityFlag = args.match(/--priority\s+(\d)/)?.[1];
|
||||
|
||||
// Extract description: content inside quotes (preferred), or fallback to stripping flags
|
||||
const quotedMatch = args.match(/(?:^|\s)["']([^"']+)["']/);
|
||||
const description = quotedMatch
|
||||
? quotedMatch[1].trim()
|
||||
: args.replace(/(-y|--yes|--from-issue\s+[\w,-]+|--type\s+[\w-]+|--priority\s+\d)/g, '').trim();
|
||||
```
|
||||
|
||||
### Phase 2: Route — Import or Manual
|
||||
|
||||
```
|
||||
--from-issue present?
|
||||
├─ YES → Import Mode (Phase 3A)
|
||||
└─ NO → Manual Mode (Phase 3B)
|
||||
```
|
||||
|
||||
### Phase 3A: Import Mode (from ccw issue)
|
||||
|
||||
```javascript
|
||||
const issueIds = fromIssue.split(',');
|
||||
|
||||
// Fetch all issues once (outside loop)
|
||||
let issues = [];
|
||||
try {
|
||||
const issueJson = Bash(`ccw issue list --json`);
|
||||
issues = JSON.parse(issueJson).issues || [];
|
||||
} catch (e) {
|
||||
console.log(`Error fetching CCW issues: ${e.message || e}`);
|
||||
console.log('Ensure ccw is installed and issues exist. Use /issue:new to create issues first.');
|
||||
return;
|
||||
}
|
||||
|
||||
for (const issueId of issueIds) {
|
||||
// 1. Find issue data
|
||||
const issue = issues.find(i => i.id === issueId.trim());
|
||||
if (!issue) {
|
||||
console.log(`Warning: Issue ${issueId} not found, skipping`);
|
||||
continue;
|
||||
}
|
||||
|
||||
// 2. Check duplicate (same issue_id already imported)
|
||||
const existing = Glob('.workflow/.idaw/tasks/IDAW-*.json');
|
||||
for (const f of existing) {
|
||||
const data = JSON.parse(Read(f));
|
||||
if (data.source?.issue_id === issueId.trim()) {
|
||||
console.log(`Warning: Issue ${issueId} already imported as ${data.id}, skipping`);
|
||||
continue; // skip to next issue
|
||||
}
|
||||
}
|
||||
|
||||
// 3. Generate next IDAW ID
|
||||
const nextId = generateNextId();
|
||||
|
||||
// 4. Map issue → IDAW task
|
||||
const task = {
|
||||
id: nextId,
|
||||
title: issue.title,
|
||||
description: issue.context || issue.title,
|
||||
status: 'pending',
|
||||
priority: parseInt(priorityFlag) || issue.priority || 3,
|
||||
task_type: typeFlag || inferTaskType(issue.title, issue.context || ''),
|
||||
skill_chain: null,
|
||||
context: {
|
||||
affected_files: issue.affected_components || [],
|
||||
acceptance_criteria: [],
|
||||
constraints: [],
|
||||
references: issue.source_url ? [issue.source_url] : []
|
||||
},
|
||||
source: {
|
||||
type: 'import-issue',
|
||||
issue_id: issue.id,
|
||||
issue_snapshot: {
|
||||
id: issue.id,
|
||||
title: issue.title,
|
||||
status: issue.status,
|
||||
context: issue.context,
|
||||
priority: issue.priority,
|
||||
created_at: issue.created_at
|
||||
}
|
||||
},
|
||||
execution: {
|
||||
session_id: null,
|
||||
started_at: null,
|
||||
completed_at: null,
|
||||
skill_results: [],
|
||||
git_commit: null,
|
||||
error: null
|
||||
},
|
||||
created_at: new Date().toISOString(),
|
||||
updated_at: new Date().toISOString()
|
||||
};
|
||||
|
||||
// 5. Write task file
|
||||
Bash('mkdir -p .workflow/.idaw/tasks');
|
||||
Write(`.workflow/.idaw/tasks/${nextId}.json`, JSON.stringify(task, null, 2));
|
||||
console.log(`Created ${nextId} from issue ${issueId}: ${issue.title}`);
|
||||
}
|
||||
```
|
||||
|
||||
### Phase 3B: Manual Mode
|
||||
|
||||
```javascript
|
||||
// 1. Validate description
|
||||
if (!description && !autoYes) {
|
||||
const answer = AskUserQuestion({
|
||||
questions: [{
|
||||
question: 'Please provide a task description:',
|
||||
header: 'Task',
|
||||
multiSelect: false,
|
||||
options: [
|
||||
{ label: 'Provide description', description: 'What needs to be done?' }
|
||||
]
|
||||
}]
|
||||
});
|
||||
// Use custom text from "Other"
|
||||
description = answer.customText || '';
|
||||
}
|
||||
|
||||
if (!description) {
|
||||
console.log('Error: No description provided. Usage: /idaw:add "task description"');
|
||||
return;
|
||||
}
|
||||
|
||||
// 2. Generate next IDAW ID
|
||||
const nextId = generateNextId();
|
||||
|
||||
// 3. Build title from first sentence
|
||||
const title = description.split(/[.\n]/)[0].substring(0, 80).trim();
|
||||
|
||||
// 4. Determine task_type
|
||||
const taskType = typeFlag || null; // null → inferred at run time
|
||||
|
||||
// 5. Create task
|
||||
const task = {
|
||||
id: nextId,
|
||||
title: title,
|
||||
description: description,
|
||||
status: 'pending',
|
||||
priority: parseInt(priorityFlag) || 3,
|
||||
task_type: taskType,
|
||||
skill_chain: null,
|
||||
context: {
|
||||
affected_files: [],
|
||||
acceptance_criteria: [],
|
||||
constraints: [],
|
||||
references: []
|
||||
},
|
||||
source: {
|
||||
type: 'manual',
|
||||
issue_id: null,
|
||||
issue_snapshot: null
|
||||
},
|
||||
execution: {
|
||||
session_id: null,
|
||||
started_at: null,
|
||||
completed_at: null,
|
||||
skill_results: [],
|
||||
git_commit: null,
|
||||
error: null
|
||||
},
|
||||
created_at: new Date().toISOString(),
|
||||
updated_at: new Date().toISOString()
|
||||
};
|
||||
|
||||
Bash('mkdir -p .workflow/.idaw/tasks');
|
||||
Write(`.workflow/.idaw/tasks/${nextId}.json`, JSON.stringify(task, null, 2));
|
||||
console.log(`Created ${nextId}: ${title}`);
|
||||
```
|
||||
|
||||
## Helper Functions
|
||||
|
||||
### ID Generation
|
||||
|
||||
```javascript
|
||||
function generateNextId() {
|
||||
const files = Glob('.workflow/.idaw/tasks/IDAW-*.json') || [];
|
||||
if (files.length === 0) return 'IDAW-001';
|
||||
|
||||
const maxNum = files
|
||||
.map(f => parseInt(f.match(/IDAW-(\d+)/)?.[1] || '0'))
|
||||
.reduce((max, n) => Math.max(max, n), 0);
|
||||
|
||||
return `IDAW-${String(maxNum + 1).padStart(3, '0')}`;
|
||||
}
|
||||
```
|
||||
|
||||
### Task Type Inference (deferred — used at run time if task_type is null)
|
||||
|
||||
```javascript
|
||||
function inferTaskType(title, description) {
|
||||
const text = `${title} ${description}`.toLowerCase();
|
||||
if (/urgent|production|critical/.test(text) && /fix|bug/.test(text)) return 'bugfix-hotfix';
|
||||
if (/refactor|重构|tech.*debt/.test(text)) return 'refactor';
|
||||
if (/tdd|test-driven|test first/.test(text)) return 'tdd';
|
||||
if (/test fail|fix test|failing test/.test(text)) return 'test-fix';
|
||||
if (/generate test|写测试|add test/.test(text)) return 'test';
|
||||
if (/review|code review/.test(text)) return 'review';
|
||||
if (/docs|documentation|readme/.test(text)) return 'docs';
|
||||
if (/fix|bug|error|crash|fail/.test(text)) return 'bugfix';
|
||||
if (/complex|multi-module|architecture/.test(text)) return 'feature-complex';
|
||||
return 'feature';
|
||||
}
|
||||
```
|
||||
|
||||
## Examples
|
||||
|
||||
```bash
|
||||
# Manual creation
|
||||
/idaw:add "Fix login timeout bug" --type bugfix --priority 2
|
||||
/idaw:add "Add rate limiting to API endpoints" --priority 1
|
||||
/idaw:add "Refactor auth module to use strategy pattern"
|
||||
|
||||
# Import from ccw issue
|
||||
/idaw:add --from-issue ISS-20260128-001
|
||||
/idaw:add --from-issue ISS-20260128-001,ISS-20260128-002 --priority 1
|
||||
|
||||
# Auto mode (skip clarification)
|
||||
/idaw:add -y "Quick fix for typo in header"
|
||||
```
|
||||
|
||||
## Output
|
||||
|
||||
```
|
||||
Created IDAW-001: Fix login timeout bug
|
||||
Type: bugfix | Priority: 2 | Source: manual
|
||||
→ Next: /idaw:run or /idaw:status
|
||||
```
|
||||
442
.claude/commands/idaw/resume.md
Normal file
442
.claude/commands/idaw/resume.md
Normal file
@@ -0,0 +1,442 @@
|
||||
---
|
||||
name: resume
|
||||
description: Resume interrupted IDAW session from last checkpoint
|
||||
argument-hint: "[-y|--yes] [session-id]"
|
||||
allowed-tools: Skill(*), TodoWrite(*), AskUserQuestion(*), Read(*), Write(*), Bash(*), Glob(*)
|
||||
---
|
||||
|
||||
# IDAW Resume Command (/idaw:resume)
|
||||
|
||||
## Auto Mode
|
||||
|
||||
When `--yes` or `-y`: Auto-skip interrupted task, continue with remaining.
|
||||
|
||||
## Skill Chain Mapping
|
||||
|
||||
```javascript
|
||||
const SKILL_CHAIN_MAP = {
|
||||
'bugfix': ['workflow-lite-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-plan']
|
||||
};
|
||||
```
|
||||
|
||||
## Task Type Inference
|
||||
|
||||
```javascript
|
||||
function inferTaskType(title, description) {
|
||||
const text = `${title} ${description}`.toLowerCase();
|
||||
if (/urgent|production|critical/.test(text) && /fix|bug/.test(text)) return 'bugfix-hotfix';
|
||||
if (/refactor|重构|tech.*debt/.test(text)) return 'refactor';
|
||||
if (/tdd|test-driven|test first/.test(text)) return 'tdd';
|
||||
if (/test fail|fix test|failing test/.test(text)) return 'test-fix';
|
||||
if (/generate test|写测试|add test/.test(text)) return 'test';
|
||||
if (/review|code review/.test(text)) return 'review';
|
||||
if (/docs|documentation|readme/.test(text)) return 'docs';
|
||||
if (/fix|bug|error|crash|fail/.test(text)) return 'bugfix';
|
||||
if (/complex|multi-module|architecture/.test(text)) return 'feature-complex';
|
||||
return 'feature';
|
||||
}
|
||||
```
|
||||
|
||||
## Implementation
|
||||
|
||||
### Phase 1: Find Resumable Session
|
||||
|
||||
```javascript
|
||||
const args = $ARGUMENTS;
|
||||
const autoYes = /(-y|--yes)/.test(args);
|
||||
const targetSessionId = args.replace(/(-y|--yes)/g, '').trim();
|
||||
|
||||
let session = null;
|
||||
let sessionDir = null;
|
||||
|
||||
if (targetSessionId) {
|
||||
// Load specific session
|
||||
sessionDir = `.workflow/.idaw/sessions/${targetSessionId}`;
|
||||
try {
|
||||
session = JSON.parse(Read(`${sessionDir}/session.json`));
|
||||
} catch {
|
||||
console.log(`Session "${targetSessionId}" not found.`);
|
||||
console.log('Use /idaw:status to list sessions, or /idaw:run to start a new one.');
|
||||
return;
|
||||
}
|
||||
} else {
|
||||
// Find most recent running session
|
||||
const sessionFiles = Glob('.workflow/.idaw/sessions/IDA-*/session.json') || [];
|
||||
|
||||
for (const f of sessionFiles) {
|
||||
try {
|
||||
const s = JSON.parse(Read(f));
|
||||
if (s.status === 'running') {
|
||||
session = s;
|
||||
sessionDir = f.replace(/\/session\.json$/, '').replace(/\\session\.json$/, '');
|
||||
break;
|
||||
}
|
||||
} catch {
|
||||
// Skip malformed
|
||||
}
|
||||
}
|
||||
|
||||
if (!session) {
|
||||
console.log('No running sessions found to resume.');
|
||||
console.log('Use /idaw:run to start a new execution.');
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
console.log(`Resuming session: ${session.session_id}`);
|
||||
```
|
||||
|
||||
### Phase 2: Handle Interrupted Task
|
||||
|
||||
```javascript
|
||||
// Find the task that was in_progress when interrupted
|
||||
let currentTaskId = session.current_task;
|
||||
let currentTask = null;
|
||||
|
||||
if (currentTaskId) {
|
||||
try {
|
||||
currentTask = JSON.parse(Read(`.workflow/.idaw/tasks/${currentTaskId}.json`));
|
||||
} catch {
|
||||
console.log(`Warning: Could not read task ${currentTaskId}`);
|
||||
currentTaskId = null;
|
||||
}
|
||||
}
|
||||
|
||||
if (currentTask && currentTask.status === 'in_progress') {
|
||||
if (autoYes) {
|
||||
// Auto: skip interrupted task
|
||||
currentTask.status = 'skipped';
|
||||
currentTask.execution.error = 'Skipped on resume (auto mode)';
|
||||
currentTask.execution.completed_at = new Date().toISOString();
|
||||
currentTask.updated_at = new Date().toISOString();
|
||||
Write(`.workflow/.idaw/tasks/${currentTaskId}.json`, JSON.stringify(currentTask, null, 2));
|
||||
session.skipped.push(currentTaskId);
|
||||
console.log(`Skipped interrupted task: ${currentTaskId}`);
|
||||
} else {
|
||||
const answer = AskUserQuestion({
|
||||
questions: [{
|
||||
question: `Task ${currentTaskId} was interrupted: "${currentTask.title}". How to proceed?`,
|
||||
header: 'Resume',
|
||||
multiSelect: false,
|
||||
options: [
|
||||
{ label: 'Retry', description: 'Reset to pending, re-execute from beginning' },
|
||||
{ label: 'Skip', description: 'Mark as skipped, move to next task' }
|
||||
]
|
||||
}]
|
||||
});
|
||||
|
||||
if (answer.answers?.Resume === 'Skip') {
|
||||
currentTask.status = 'skipped';
|
||||
currentTask.execution.error = 'Skipped on resume (user choice)';
|
||||
currentTask.execution.completed_at = new Date().toISOString();
|
||||
currentTask.updated_at = new Date().toISOString();
|
||||
Write(`.workflow/.idaw/tasks/${currentTaskId}.json`, JSON.stringify(currentTask, null, 2));
|
||||
session.skipped.push(currentTaskId);
|
||||
} else {
|
||||
// Retry: reset to pending
|
||||
currentTask.status = 'pending';
|
||||
currentTask.execution.started_at = null;
|
||||
currentTask.execution.completed_at = null;
|
||||
currentTask.execution.skill_results = [];
|
||||
currentTask.execution.error = null;
|
||||
currentTask.updated_at = new Date().toISOString();
|
||||
Write(`.workflow/.idaw/tasks/${currentTaskId}.json`, JSON.stringify(currentTask, null, 2));
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Phase 3: Build Remaining Task Queue
|
||||
|
||||
```javascript
|
||||
// Collect remaining tasks (pending, or the retried current task)
|
||||
const allTaskIds = session.tasks;
|
||||
const completedSet = new Set([...session.completed, ...session.failed, ...session.skipped]);
|
||||
|
||||
const remainingTasks = [];
|
||||
for (const taskId of allTaskIds) {
|
||||
if (completedSet.has(taskId)) continue;
|
||||
try {
|
||||
const task = JSON.parse(Read(`.workflow/.idaw/tasks/${taskId}.json`));
|
||||
if (task.status === 'pending') {
|
||||
remainingTasks.push(task);
|
||||
}
|
||||
} catch {
|
||||
console.log(`Warning: Could not read task ${taskId}, skipping`);
|
||||
}
|
||||
}
|
||||
|
||||
if (remainingTasks.length === 0) {
|
||||
console.log('No remaining tasks to execute. Session complete.');
|
||||
session.status = 'completed';
|
||||
session.current_task = null;
|
||||
session.updated_at = new Date().toISOString();
|
||||
Write(`${sessionDir}/session.json`, JSON.stringify(session, null, 2));
|
||||
return;
|
||||
}
|
||||
|
||||
// Sort: priority ASC, then ID ASC
|
||||
remainingTasks.sort((a, b) => {
|
||||
if (a.priority !== b.priority) return a.priority - b.priority;
|
||||
return a.id.localeCompare(b.id);
|
||||
});
|
||||
|
||||
console.log(`Remaining tasks: ${remainingTasks.length}`);
|
||||
|
||||
// Append resume marker to progress.md
|
||||
const progressFile = `${sessionDir}/progress.md`;
|
||||
try {
|
||||
const currentProgress = Read(progressFile);
|
||||
Write(progressFile, currentProgress + `\n---\n**Resumed**: ${new Date().toISOString()}\n\n`);
|
||||
} catch {
|
||||
Write(progressFile, `# IDAW Progress — ${session.session_id}\n\n---\n**Resumed**: ${new Date().toISOString()}\n\n`);
|
||||
}
|
||||
|
||||
// Update TodoWrite
|
||||
TodoWrite({
|
||||
todos: remainingTasks.map((t, i) => ({
|
||||
content: `IDAW:[${i + 1}/${remainingTasks.length}] ${t.title}`,
|
||||
status: i === 0 ? 'in_progress' : 'pending',
|
||||
activeForm: `Executing ${t.title}`
|
||||
}))
|
||||
});
|
||||
```
|
||||
|
||||
### Phase 4-6: Execute Remaining (reuse run.md main loop)
|
||||
|
||||
Execute remaining tasks using the same Phase 4-6 logic from `/idaw:run`:
|
||||
|
||||
```javascript
|
||||
// Phase 4: Main Loop — identical to run.md Phase 4
|
||||
for (let taskIdx = 0; taskIdx < remainingTasks.length; taskIdx++) {
|
||||
const task = remainingTasks[taskIdx];
|
||||
|
||||
// Resolve skill chain
|
||||
const resolvedType = task.task_type || inferTaskType(task.title, task.description);
|
||||
const chain = task.skill_chain || SKILL_CHAIN_MAP[resolvedType] || SKILL_CHAIN_MAP['feature'];
|
||||
|
||||
// Update task → in_progress
|
||||
task.status = 'in_progress';
|
||||
task.task_type = resolvedType;
|
||||
task.execution.started_at = new Date().toISOString();
|
||||
Write(`.workflow/.idaw/tasks/${task.id}.json`, JSON.stringify(task, null, 2));
|
||||
|
||||
session.current_task = task.id;
|
||||
session.updated_at = new Date().toISOString();
|
||||
Write(`${sessionDir}/session.json`, JSON.stringify(session, null, 2));
|
||||
|
||||
console.log(`\n--- [${taskIdx + 1}/${remainingTasks.length}] ${task.id}: ${task.title} ---`);
|
||||
console.log(`Chain: ${chain.join(' → ')}`);
|
||||
|
||||
// ━━━ Pre-Task CLI Context Analysis (for complex/bugfix tasks) ━━━
|
||||
if (['bugfix', 'bugfix-hotfix', 'feature-complex'].includes(resolvedType)) {
|
||||
console.log(` Pre-analysis: gathering context for ${resolvedType} task...`);
|
||||
const affectedFiles = (task.context?.affected_files || []).join(', ');
|
||||
const preAnalysisPrompt = `PURPOSE: Pre-analyze codebase context for IDAW task before execution.
|
||||
TASK: • Understand current state of: ${affectedFiles || 'files related to: ' + task.title} • Identify dependencies and risk areas • Note existing patterns to follow
|
||||
MODE: analysis
|
||||
CONTEXT: @**/*
|
||||
EXPECTED: Brief context summary (affected modules, dependencies, risk areas) in 3-5 bullet points
|
||||
CONSTRAINTS: Keep concise | Focus on execution-relevant context`;
|
||||
const preAnalysis = Bash(`ccw cli -p '${preAnalysisPrompt.replace(/'/g, "'\\''")}' --tool gemini --mode analysis 2>&1 || echo "Pre-analysis skipped"`);
|
||||
task.execution.skill_results.push({
|
||||
skill: 'cli-pre-analysis',
|
||||
status: 'completed',
|
||||
context_summary: preAnalysis?.substring(0, 500),
|
||||
timestamp: new Date().toISOString()
|
||||
});
|
||||
}
|
||||
|
||||
// Execute skill chain
|
||||
let previousResult = null;
|
||||
let taskFailed = false;
|
||||
|
||||
for (let skillIdx = 0; skillIdx < chain.length; skillIdx++) {
|
||||
const skillName = chain[skillIdx];
|
||||
const skillArgs = assembleSkillArgs(skillName, task, previousResult, autoYes, skillIdx === 0);
|
||||
|
||||
console.log(` [${skillIdx + 1}/${chain.length}] ${skillName}`);
|
||||
|
||||
try {
|
||||
const result = Skill({ skill: skillName, args: skillArgs });
|
||||
previousResult = result;
|
||||
task.execution.skill_results.push({
|
||||
skill: skillName,
|
||||
status: 'completed',
|
||||
timestamp: new Date().toISOString()
|
||||
});
|
||||
} catch (error) {
|
||||
// ━━━ CLI-Assisted Error Recovery ━━━
|
||||
console.log(` Diagnosing failure: ${skillName}...`);
|
||||
const diagnosisPrompt = `PURPOSE: Diagnose why skill "${skillName}" failed during IDAW task execution.
|
||||
TASK: • Analyze error: ${String(error).substring(0, 300)} • Check affected files: ${(task.context?.affected_files || []).join(', ') || 'unknown'} • Identify root cause • Suggest fix strategy
|
||||
MODE: analysis
|
||||
CONTEXT: @**/* | Memory: IDAW task ${task.id}: ${task.title}
|
||||
EXPECTED: Root cause + actionable fix recommendation (1-2 sentences)
|
||||
CONSTRAINTS: Focus on actionable diagnosis`;
|
||||
const diagnosisResult = Bash(`ccw cli -p '${diagnosisPrompt.replace(/'/g, "'\\''")}' --tool gemini --mode analysis --rule analysis-diagnose-bug-root-cause 2>&1 || echo "CLI diagnosis unavailable"`);
|
||||
|
||||
task.execution.skill_results.push({
|
||||
skill: `cli-diagnosis:${skillName}`,
|
||||
status: 'completed',
|
||||
diagnosis: diagnosisResult?.substring(0, 500),
|
||||
timestamp: new Date().toISOString()
|
||||
});
|
||||
|
||||
// Retry with diagnosis context
|
||||
console.log(` Retry with diagnosis: ${skillName}`);
|
||||
try {
|
||||
const retryResult = Skill({ skill: skillName, args: skillArgs });
|
||||
previousResult = retryResult;
|
||||
task.execution.skill_results.push({
|
||||
skill: skillName,
|
||||
status: 'completed-retry-with-diagnosis',
|
||||
timestamp: new Date().toISOString()
|
||||
});
|
||||
} catch (retryError) {
|
||||
task.execution.skill_results.push({
|
||||
skill: skillName,
|
||||
status: 'failed',
|
||||
error: String(retryError).substring(0, 200),
|
||||
timestamp: new Date().toISOString()
|
||||
});
|
||||
|
||||
if (autoYes) {
|
||||
taskFailed = true;
|
||||
break;
|
||||
}
|
||||
|
||||
const answer = AskUserQuestion({
|
||||
questions: [{
|
||||
question: `${skillName} failed after CLI diagnosis + retry: ${String(retryError).substring(0, 100)}`,
|
||||
header: 'Error',
|
||||
multiSelect: false,
|
||||
options: [
|
||||
{ label: 'Skip task', description: 'Mark as failed, continue' },
|
||||
{ label: 'Abort', description: 'Stop run' }
|
||||
]
|
||||
}]
|
||||
});
|
||||
|
||||
if (answer.answers?.Error === 'Abort') {
|
||||
task.status = 'failed';
|
||||
task.execution.error = String(retryError).substring(0, 200);
|
||||
Write(`.workflow/.idaw/tasks/${task.id}.json`, JSON.stringify(task, null, 2));
|
||||
session.failed.push(task.id);
|
||||
session.status = 'failed';
|
||||
session.updated_at = new Date().toISOString();
|
||||
Write(`${sessionDir}/session.json`, JSON.stringify(session, null, 2));
|
||||
return;
|
||||
}
|
||||
taskFailed = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Phase 5: Checkpoint
|
||||
if (taskFailed) {
|
||||
task.status = 'failed';
|
||||
task.execution.error = 'Skill chain failed after retry';
|
||||
task.execution.completed_at = new Date().toISOString();
|
||||
session.failed.push(task.id);
|
||||
} else {
|
||||
// Git commit
|
||||
const commitMsg = `feat(idaw): ${task.title} [${task.id}]`;
|
||||
const diffCheck = Bash('git diff --stat HEAD 2>/dev/null || echo ""');
|
||||
const untrackedCheck = Bash('git ls-files --others --exclude-standard 2>/dev/null || echo ""');
|
||||
|
||||
if (diffCheck?.trim() || untrackedCheck?.trim()) {
|
||||
Bash('git add -A');
|
||||
Bash(`git commit -m "$(cat <<'EOF'\n${commitMsg}\nEOF\n)"`);
|
||||
const commitHash = Bash('git rev-parse --short HEAD 2>/dev/null')?.trim();
|
||||
task.execution.git_commit = commitHash;
|
||||
} else {
|
||||
task.execution.git_commit = 'no-commit';
|
||||
}
|
||||
|
||||
task.status = 'completed';
|
||||
task.execution.completed_at = new Date().toISOString();
|
||||
session.completed.push(task.id);
|
||||
}
|
||||
|
||||
task.updated_at = new Date().toISOString();
|
||||
Write(`.workflow/.idaw/tasks/${task.id}.json`, JSON.stringify(task, null, 2));
|
||||
session.updated_at = new Date().toISOString();
|
||||
Write(`${sessionDir}/session.json`, JSON.stringify(session, null, 2));
|
||||
|
||||
// Append progress
|
||||
const chain_str = chain.join(' → ');
|
||||
const progressEntry = `## ${task.id} — ${task.title}\n- Status: ${task.status}\n- Chain: ${chain_str}\n- Commit: ${task.execution.git_commit || '-'}\n\n`;
|
||||
const currentProgress = Read(`${sessionDir}/progress.md`);
|
||||
Write(`${sessionDir}/progress.md`, currentProgress + progressEntry);
|
||||
}
|
||||
|
||||
// Phase 6: Report
|
||||
session.status = session.failed.length > 0 && session.completed.length === 0 ? 'failed' : 'completed';
|
||||
session.current_task = null;
|
||||
session.updated_at = new Date().toISOString();
|
||||
Write(`${sessionDir}/session.json`, JSON.stringify(session, null, 2));
|
||||
|
||||
const summary = `\n---\n## Summary (Resumed)\n- Completed: ${session.completed.length}\n- Failed: ${session.failed.length}\n- Skipped: ${session.skipped.length}\n`;
|
||||
const finalProgress = Read(`${sessionDir}/progress.md`);
|
||||
Write(`${sessionDir}/progress.md`, finalProgress + summary);
|
||||
|
||||
console.log('\n=== IDAW Resume Complete ===');
|
||||
console.log(`Session: ${session.session_id}`);
|
||||
console.log(`Completed: ${session.completed.length} | Failed: ${session.failed.length} | Skipped: ${session.skipped.length}`);
|
||||
```
|
||||
|
||||
## Helper Functions
|
||||
|
||||
### assembleSkillArgs
|
||||
|
||||
```javascript
|
||||
function assembleSkillArgs(skillName, task, previousResult, autoYes, isFirst) {
|
||||
let args = '';
|
||||
|
||||
if (isFirst) {
|
||||
// Sanitize for shell safety
|
||||
const goal = `${task.title}\n${task.description}`
|
||||
.replace(/\\/g, '\\\\')
|
||||
.replace(/"/g, '\\"')
|
||||
.replace(/\$/g, '\\$')
|
||||
.replace(/`/g, '\\`');
|
||||
args = `"${goal}"`;
|
||||
if (task.task_type === 'bugfix-hotfix') args += ' --hotfix';
|
||||
} else if (previousResult?.session_id) {
|
||||
args = `--session="${previousResult.session_id}"`;
|
||||
}
|
||||
|
||||
if (autoYes && !args.includes('-y') && !args.includes('--yes')) {
|
||||
args = args ? `${args} -y` : '-y';
|
||||
}
|
||||
|
||||
return args;
|
||||
}
|
||||
```
|
||||
|
||||
## Examples
|
||||
|
||||
```bash
|
||||
# Resume most recent running session (interactive)
|
||||
/idaw:resume
|
||||
|
||||
# Resume specific session
|
||||
/idaw:resume IDA-auth-fix-20260301
|
||||
|
||||
# Resume with auto mode (skip interrupted, continue)
|
||||
/idaw:resume -y
|
||||
|
||||
# Resume specific session with auto mode
|
||||
/idaw:resume -y IDA-auth-fix-20260301
|
||||
```
|
||||
648
.claude/commands/idaw/run-coordinate.md
Normal file
648
.claude/commands/idaw/run-coordinate.md
Normal file
@@ -0,0 +1,648 @@
|
||||
---
|
||||
name: run-coordinate
|
||||
description: IDAW coordinator - execute task skill chains via external CLI with hook callbacks and git checkpoints
|
||||
argument-hint: "[-y|--yes] [--task <id>[,<id>,...]] [--dry-run] [--tool <tool>]"
|
||||
allowed-tools: Agent(*), AskUserQuestion(*), Read(*), Write(*), Bash(*), Glob(*), Grep(*)
|
||||
---
|
||||
|
||||
# IDAW Run Coordinate Command (/idaw:run-coordinate)
|
||||
|
||||
Coordinator variant of `/idaw:run`: external CLI execution with background tasks and hook callbacks.
|
||||
|
||||
**Execution Model**: `ccw cli -p "..." --tool <tool> --mode write` in background → hook callback → next step.
|
||||
|
||||
**vs `/idaw:run`**: Direct `Skill()` calls (blocking, main process) vs `ccw cli` (background, external process).
|
||||
|
||||
## When to Use
|
||||
|
||||
| Scenario | Use |
|
||||
|----------|-----|
|
||||
| Standard IDAW execution (main process) | `/idaw:run` |
|
||||
| External CLI execution (background, hook-driven) | `/idaw:run-coordinate` |
|
||||
| Need `claude` or `gemini` as execution tool | `/idaw:run-coordinate --tool claude` |
|
||||
| Long-running tasks, avoid context window pressure | `/idaw:run-coordinate` |
|
||||
|
||||
## Skill Chain Mapping
|
||||
|
||||
```javascript
|
||||
const SKILL_CHAIN_MAP = {
|
||||
'bugfix': ['workflow-lite-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-plan']
|
||||
};
|
||||
```
|
||||
|
||||
## Task Type Inference
|
||||
|
||||
```javascript
|
||||
function inferTaskType(title, description) {
|
||||
const text = `${title} ${description}`.toLowerCase();
|
||||
if (/urgent|production|critical/.test(text) && /fix|bug/.test(text)) return 'bugfix-hotfix';
|
||||
if (/refactor|重构|tech.*debt/.test(text)) return 'refactor';
|
||||
if (/tdd|test-driven|test first/.test(text)) return 'tdd';
|
||||
if (/test fail|fix test|failing test/.test(text)) return 'test-fix';
|
||||
if (/generate test|写测试|add test/.test(text)) return 'test';
|
||||
if (/review|code review/.test(text)) return 'review';
|
||||
if (/docs|documentation|readme/.test(text)) return 'docs';
|
||||
if (/fix|bug|error|crash|fail/.test(text)) return 'bugfix';
|
||||
if (/complex|multi-module|architecture/.test(text)) return 'feature-complex';
|
||||
return 'feature';
|
||||
}
|
||||
```
|
||||
|
||||
## 6-Phase Execution (Coordinator Model)
|
||||
|
||||
### Phase 1: Load Tasks
|
||||
|
||||
```javascript
|
||||
const args = $ARGUMENTS;
|
||||
const autoYes = /(-y|--yes)/.test(args);
|
||||
const dryRun = /--dry-run/.test(args);
|
||||
const taskFilter = args.match(/--task\s+([\w,-]+)/)?.[1]?.split(',') || null;
|
||||
const cliTool = args.match(/--tool\s+(\w+)/)?.[1] || 'claude';
|
||||
|
||||
// Load task files
|
||||
const taskFiles = Glob('.workflow/.idaw/tasks/IDAW-*.json') || [];
|
||||
|
||||
if (taskFiles.length === 0) {
|
||||
console.log('No IDAW tasks found. Use /idaw:add to create tasks.');
|
||||
return;
|
||||
}
|
||||
|
||||
// Parse and filter
|
||||
let tasks = taskFiles.map(f => JSON.parse(Read(f)));
|
||||
|
||||
if (taskFilter) {
|
||||
tasks = tasks.filter(t => taskFilter.includes(t.id));
|
||||
} else {
|
||||
tasks = tasks.filter(t => t.status === 'pending');
|
||||
}
|
||||
|
||||
if (tasks.length === 0) {
|
||||
console.log('No pending tasks to execute. Use /idaw:add to add tasks or --task to specify IDs.');
|
||||
return;
|
||||
}
|
||||
|
||||
// Sort: priority ASC (1=critical first), then ID ASC
|
||||
tasks.sort((a, b) => {
|
||||
if (a.priority !== b.priority) return a.priority - b.priority;
|
||||
return a.id.localeCompare(b.id);
|
||||
});
|
||||
```
|
||||
|
||||
### Phase 2: Session Setup
|
||||
|
||||
```javascript
|
||||
// Generate session ID: IDA-{slug}-YYYYMMDD
|
||||
const slug = tasks[0].title
|
||||
.toLowerCase()
|
||||
.replace(/[^a-z0-9]+/g, '-')
|
||||
.substring(0, 20)
|
||||
.replace(/-$/, '');
|
||||
const dateStr = new Date().toISOString().slice(0, 10).replace(/-/g, '');
|
||||
let sessionId = `IDA-${slug}-${dateStr}`;
|
||||
|
||||
// Check collision
|
||||
const existingSession = Glob(`.workflow/.idaw/sessions/${sessionId}/session.json`);
|
||||
if (existingSession?.length > 0) {
|
||||
sessionId = `${sessionId}-2`;
|
||||
}
|
||||
|
||||
const sessionDir = `.workflow/.idaw/sessions/${sessionId}`;
|
||||
Bash(`mkdir -p "${sessionDir}"`);
|
||||
|
||||
const session = {
|
||||
session_id: sessionId,
|
||||
mode: 'coordinate', // ★ Marks this as coordinator-mode session
|
||||
cli_tool: cliTool,
|
||||
status: 'running',
|
||||
created_at: new Date().toISOString(),
|
||||
updated_at: new Date().toISOString(),
|
||||
tasks: tasks.map(t => t.id),
|
||||
current_task: null,
|
||||
current_skill_index: 0,
|
||||
completed: [],
|
||||
failed: [],
|
||||
skipped: [],
|
||||
prompts_used: []
|
||||
};
|
||||
|
||||
Write(`${sessionDir}/session.json`, JSON.stringify(session, null, 2));
|
||||
|
||||
// Initialize progress.md
|
||||
const progressHeader = `# IDAW Progress — ${sessionId} (coordinate mode)\nStarted: ${session.created_at}\nCLI Tool: ${cliTool}\n\n`;
|
||||
Write(`${sessionDir}/progress.md`, progressHeader);
|
||||
```
|
||||
|
||||
### Phase 3: Startup Protocol
|
||||
|
||||
```javascript
|
||||
// Check for existing running sessions
|
||||
const runningSessions = Glob('.workflow/.idaw/sessions/IDA-*/session.json')
|
||||
?.map(f => { try { return JSON.parse(Read(f)); } catch { return null; } })
|
||||
.filter(s => s && s.status === 'running' && s.session_id !== sessionId) || [];
|
||||
|
||||
if (runningSessions.length > 0 && !autoYes) {
|
||||
const answer = AskUserQuestion({
|
||||
questions: [{
|
||||
question: `Found running session: ${runningSessions[0].session_id}. How to proceed?`,
|
||||
header: 'Conflict',
|
||||
multiSelect: false,
|
||||
options: [
|
||||
{ label: 'Resume existing', description: 'Use /idaw:resume instead' },
|
||||
{ label: 'Start fresh', description: 'Continue with new session' },
|
||||
{ label: 'Abort', description: 'Cancel this run' }
|
||||
]
|
||||
}]
|
||||
});
|
||||
if (answer.answers?.Conflict === 'Resume existing') {
|
||||
console.log(`Use: /idaw:resume ${runningSessions[0].session_id}`);
|
||||
return;
|
||||
}
|
||||
if (answer.answers?.Conflict === 'Abort') return;
|
||||
}
|
||||
|
||||
// Check git status
|
||||
const gitStatus = Bash('git status --porcelain 2>/dev/null');
|
||||
if (gitStatus?.trim() && !autoYes) {
|
||||
const answer = AskUserQuestion({
|
||||
questions: [{
|
||||
question: 'Working tree has uncommitted changes. How to proceed?',
|
||||
header: 'Git',
|
||||
multiSelect: false,
|
||||
options: [
|
||||
{ label: 'Continue', description: 'Proceed with dirty tree' },
|
||||
{ label: 'Stash', description: 'git stash before running' },
|
||||
{ label: 'Abort', description: 'Stop and handle manually' }
|
||||
]
|
||||
}]
|
||||
});
|
||||
if (answer.answers?.Git === 'Stash') Bash('git stash push -m "idaw-pre-run"');
|
||||
if (answer.answers?.Git === 'Abort') return;
|
||||
}
|
||||
|
||||
// Dry run
|
||||
if (dryRun) {
|
||||
console.log(`# Dry Run — ${sessionId} (coordinate mode, tool: ${cliTool})\n`);
|
||||
for (const task of tasks) {
|
||||
const taskType = task.task_type || inferTaskType(task.title, task.description);
|
||||
const chain = task.skill_chain || SKILL_CHAIN_MAP[taskType] || SKILL_CHAIN_MAP['feature'];
|
||||
console.log(`## ${task.id}: ${task.title}`);
|
||||
console.log(` Type: ${taskType} | Priority: ${task.priority}`);
|
||||
console.log(` Chain: ${chain.join(' → ')}`);
|
||||
console.log(` CLI: ccw cli --tool ${cliTool} --mode write\n`);
|
||||
}
|
||||
console.log(`Total: ${tasks.length} tasks`);
|
||||
return;
|
||||
}
|
||||
```
|
||||
|
||||
### Phase 4: Launch First Task (then wait for hook)
|
||||
|
||||
```javascript
|
||||
// Start with the first task, first skill
|
||||
const firstTask = tasks[0];
|
||||
const resolvedType = firstTask.task_type || inferTaskType(firstTask.title, firstTask.description);
|
||||
const chain = firstTask.skill_chain || SKILL_CHAIN_MAP[resolvedType] || SKILL_CHAIN_MAP['feature'];
|
||||
|
||||
// Update task → in_progress
|
||||
firstTask.status = 'in_progress';
|
||||
firstTask.task_type = resolvedType;
|
||||
firstTask.execution.started_at = new Date().toISOString();
|
||||
Write(`.workflow/.idaw/tasks/${firstTask.id}.json`, JSON.stringify(firstAgent, null, 2));
|
||||
|
||||
// Update session
|
||||
session.current_task = firstTask.id;
|
||||
session.current_skill_index = 0;
|
||||
session.updated_at = new Date().toISOString();
|
||||
Write(`${sessionDir}/session.json`, JSON.stringify(session, null, 2));
|
||||
|
||||
// ━━━ Pre-Task CLI Context Analysis (for complex/bugfix tasks) ━━━
|
||||
if (['bugfix', 'bugfix-hotfix', 'feature-complex'].includes(resolvedType)) {
|
||||
console.log(`Pre-analysis: gathering context for ${resolvedType} task...`);
|
||||
const affectedFiles = (firstTask.context?.affected_files || []).join(', ');
|
||||
const preAnalysisPrompt = `PURPOSE: Pre-analyze codebase context for IDAW task.
|
||||
TASK: • Understand current state of: ${affectedFiles || 'files related to: ' + firstTask.title} • Identify dependencies and risk areas
|
||||
MODE: analysis
|
||||
CONTEXT: @**/*
|
||||
EXPECTED: Brief context summary in 3-5 bullet points
|
||||
CONSTRAINTS: Keep concise`;
|
||||
Bash(`ccw cli -p '${preAnalysisPrompt.replace(/'/g, "'\\''")}' --tool gemini --mode analysis 2>&1 || echo "Pre-analysis skipped"`);
|
||||
}
|
||||
|
||||
// Assemble prompt for first skill
|
||||
const skillName = chain[0];
|
||||
const prompt = assembleCliPrompt(skillName, firstAgent, null, autoYes);
|
||||
|
||||
session.prompts_used.push({
|
||||
task_id: firstTask.id,
|
||||
skill_index: 0,
|
||||
skill: skillName,
|
||||
prompt: prompt,
|
||||
timestamp: new Date().toISOString()
|
||||
});
|
||||
session.updated_at = new Date().toISOString();
|
||||
Write(`${sessionDir}/session.json`, JSON.stringify(session, null, 2));
|
||||
|
||||
// Launch via ccw cli in background
|
||||
console.log(`[1/${tasks.length}] ${firstTask.id}: ${firstTask.title}`);
|
||||
console.log(` Chain: ${chain.join(' → ')}`);
|
||||
console.log(` Launching: ${skillName} via ccw cli --tool ${cliTool}`);
|
||||
|
||||
Bash(
|
||||
`ccw cli -p "${escapeForShell(prompt)}" --tool ${cliTool} --mode write`,
|
||||
{ run_in_background: true }
|
||||
);
|
||||
|
||||
// ★ STOP HERE — wait for hook callback
|
||||
// Hook callback will trigger handleStepCompletion() below
|
||||
```
|
||||
|
||||
### Phase 5: Hook Callback Handler (per-step completion)
|
||||
|
||||
```javascript
|
||||
// Called by hook when background CLI completes
|
||||
async function handleStepCompletion(sessionId, cliOutput) {
|
||||
const sessionDir = `.workflow/.idaw/sessions/${sessionId}`;
|
||||
const session = JSON.parse(Read(`${sessionDir}/session.json`));
|
||||
|
||||
const taskId = session.current_task;
|
||||
const task = JSON.parse(Read(`.workflow/.idaw/tasks/${taskId}.json`));
|
||||
|
||||
const resolvedType = task.task_type || inferTaskType(task.title, task.description);
|
||||
const chain = task.skill_chain || SKILL_CHAIN_MAP[resolvedType] || SKILL_CHAIN_MAP['feature'];
|
||||
const skillIdx = session.current_skill_index;
|
||||
const skillName = chain[skillIdx];
|
||||
|
||||
// Parse CLI output for session ID
|
||||
const parsedOutput = parseCliOutput(cliOutput);
|
||||
|
||||
// Record skill result
|
||||
task.execution.skill_results.push({
|
||||
skill: skillName,
|
||||
status: parsedOutput.success ? 'completed' : 'failed',
|
||||
session_id: parsedOutput.sessionId,
|
||||
timestamp: new Date().toISOString()
|
||||
});
|
||||
|
||||
// ━━━ Handle failure with CLI diagnosis ━━━
|
||||
if (!parsedOutput.success) {
|
||||
console.log(` ${skillName} failed. Running CLI diagnosis...`);
|
||||
const diagnosisPrompt = `PURPOSE: Diagnose why skill "${skillName}" failed during IDAW task.
|
||||
TASK: • Analyze error output • Check affected files: ${(task.context?.affected_files || []).join(', ') || 'unknown'}
|
||||
MODE: analysis
|
||||
CONTEXT: @**/* | Memory: IDAW task ${task.id}: ${task.title}
|
||||
EXPECTED: Root cause + fix recommendation
|
||||
CONSTRAINTS: Actionable diagnosis`;
|
||||
Bash(`ccw cli -p '${diagnosisPrompt.replace(/'/g, "'\\''")}' --tool gemini --mode analysis --rule analysis-diagnose-bug-root-cause 2>&1 || true`);
|
||||
|
||||
task.execution.skill_results.push({
|
||||
skill: `cli-diagnosis:${skillName}`,
|
||||
status: 'completed',
|
||||
timestamp: new Date().toISOString()
|
||||
});
|
||||
|
||||
// Retry once
|
||||
console.log(` Retrying: ${skillName}`);
|
||||
const retryPrompt = assembleCliPrompt(skillName, task, parsedOutput, true);
|
||||
session.prompts_used.push({
|
||||
task_id: taskId,
|
||||
skill_index: skillIdx,
|
||||
skill: `${skillName}-retry`,
|
||||
prompt: retryPrompt,
|
||||
timestamp: new Date().toISOString()
|
||||
});
|
||||
Write(`${sessionDir}/session.json`, JSON.stringify(session, null, 2));
|
||||
Write(`.workflow/.idaw/tasks/${taskId}.json`, JSON.stringify(task, null, 2));
|
||||
|
||||
Bash(
|
||||
`ccw cli -p "${escapeForShell(retryPrompt)}" --tool ${session.cli_tool} --mode write`,
|
||||
{ run_in_background: true }
|
||||
);
|
||||
return; // Wait for retry hook
|
||||
}
|
||||
|
||||
// ━━━ Skill succeeded — advance ━━━
|
||||
const nextSkillIdx = skillIdx + 1;
|
||||
|
||||
if (nextSkillIdx < chain.length) {
|
||||
// More skills in this task's chain → launch next skill
|
||||
session.current_skill_index = nextSkillIdx;
|
||||
session.updated_at = new Date().toISOString();
|
||||
|
||||
const nextSkill = chain[nextSkillIdx];
|
||||
const nextPrompt = assembleCliPrompt(nextSkill, task, parsedOutput, true);
|
||||
|
||||
session.prompts_used.push({
|
||||
task_id: taskId,
|
||||
skill_index: nextSkillIdx,
|
||||
skill: nextSkill,
|
||||
prompt: nextPrompt,
|
||||
timestamp: new Date().toISOString()
|
||||
});
|
||||
Write(`${sessionDir}/session.json`, JSON.stringify(session, null, 2));
|
||||
Write(`.workflow/.idaw/tasks/${taskId}.json`, JSON.stringify(task, null, 2));
|
||||
|
||||
console.log(` Next skill: ${nextSkill}`);
|
||||
Bash(
|
||||
`ccw cli -p "${escapeForShell(nextPrompt)}" --tool ${session.cli_tool} --mode write`,
|
||||
{ run_in_background: true }
|
||||
);
|
||||
return; // Wait for next hook
|
||||
}
|
||||
|
||||
// ━━━ Task chain complete — git checkpoint ━━━
|
||||
const commitMsg = `feat(idaw): ${task.title} [${task.id}]`;
|
||||
const diffCheck = Bash('git diff --stat HEAD 2>/dev/null || echo ""');
|
||||
const untrackedCheck = Bash('git ls-files --others --exclude-standard 2>/dev/null || echo ""');
|
||||
|
||||
if (diffCheck?.trim() || untrackedCheck?.trim()) {
|
||||
Bash('git add -A');
|
||||
Bash(`git commit -m "$(cat <<'EOF'\n${commitMsg}\nEOF\n)"`);
|
||||
const commitHash = Bash('git rev-parse --short HEAD 2>/dev/null')?.trim();
|
||||
task.execution.git_commit = commitHash;
|
||||
} else {
|
||||
task.execution.git_commit = 'no-commit';
|
||||
}
|
||||
|
||||
task.status = 'completed';
|
||||
task.execution.completed_at = new Date().toISOString();
|
||||
task.updated_at = new Date().toISOString();
|
||||
Write(`.workflow/.idaw/tasks/${taskId}.json`, JSON.stringify(task, null, 2));
|
||||
|
||||
session.completed.push(taskId);
|
||||
|
||||
// Append progress
|
||||
const progressEntry = `## ${task.id} — ${task.title}\n` +
|
||||
`- Status: completed\n` +
|
||||
`- Type: ${task.task_type}\n` +
|
||||
`- Chain: ${chain.join(' → ')}\n` +
|
||||
`- Commit: ${task.execution.git_commit || '-'}\n` +
|
||||
`- Mode: coordinate (${session.cli_tool})\n\n`;
|
||||
const currentProgress = Read(`${sessionDir}/progress.md`);
|
||||
Write(`${sessionDir}/progress.md`, currentProgress + progressEntry);
|
||||
|
||||
// ━━━ Advance to next task ━━━
|
||||
const allTaskIds = session.tasks;
|
||||
const completedSet = new Set([...session.completed, ...session.failed, ...session.skipped]);
|
||||
const nextTaskId = allTaskIds.find(id => !completedSet.has(id));
|
||||
|
||||
if (nextTaskId) {
|
||||
// Load next task
|
||||
const nextTask = JSON.parse(Read(`.workflow/.idaw/tasks/${nextTaskId}.json`));
|
||||
const nextType = nextTask.task_type || inferTaskType(nextTask.title, nextTask.description);
|
||||
const nextChain = nextTask.skill_chain || SKILL_CHAIN_MAP[nextType] || SKILL_CHAIN_MAP['feature'];
|
||||
|
||||
nextTask.status = 'in_progress';
|
||||
nextTask.task_type = nextType;
|
||||
nextTask.execution.started_at = new Date().toISOString();
|
||||
Write(`.workflow/.idaw/tasks/${nextTaskId}.json`, JSON.stringify(nextAgent, null, 2));
|
||||
|
||||
session.current_task = nextTaskId;
|
||||
session.current_skill_index = 0;
|
||||
session.updated_at = new Date().toISOString();
|
||||
Write(`${sessionDir}/session.json`, JSON.stringify(session, null, 2));
|
||||
|
||||
// Pre-analysis for complex tasks
|
||||
if (['bugfix', 'bugfix-hotfix', 'feature-complex'].includes(nextType)) {
|
||||
const affectedFiles = (nextTask.context?.affected_files || []).join(', ');
|
||||
Bash(`ccw cli -p 'PURPOSE: Pre-analyze context for ${nextTask.title}. TASK: Check ${affectedFiles || "related files"}. MODE: analysis. EXPECTED: 3-5 bullet points.' --tool gemini --mode analysis 2>&1 || true`);
|
||||
}
|
||||
|
||||
const nextSkillName = nextChain[0];
|
||||
const nextPrompt = assembleCliPrompt(nextSkillName, nextAgent, null, true);
|
||||
|
||||
session.prompts_used.push({
|
||||
task_id: nextTaskId,
|
||||
skill_index: 0,
|
||||
skill: nextSkillName,
|
||||
prompt: nextPrompt,
|
||||
timestamp: new Date().toISOString()
|
||||
});
|
||||
Write(`${sessionDir}/session.json`, JSON.stringify(session, null, 2));
|
||||
|
||||
const taskNum = session.completed.length + 1;
|
||||
const totalTasks = session.tasks.length;
|
||||
console.log(`\n[${taskNum}/${totalTasks}] ${nextTaskId}: ${nextTask.title}`);
|
||||
console.log(` Chain: ${nextChain.join(' → ')}`);
|
||||
|
||||
Bash(
|
||||
`ccw cli -p "${escapeForShell(nextPrompt)}" --tool ${session.cli_tool} --mode write`,
|
||||
{ run_in_background: true }
|
||||
);
|
||||
return; // Wait for hook
|
||||
}
|
||||
|
||||
// ━━━ All tasks complete — Phase 6: Report ━━━
|
||||
session.status = session.failed.length > 0 && session.completed.length === 0 ? 'failed' : 'completed';
|
||||
session.current_task = null;
|
||||
session.updated_at = new Date().toISOString();
|
||||
Write(`${sessionDir}/session.json`, JSON.stringify(session, null, 2));
|
||||
|
||||
const summary = `\n---\n## Summary (coordinate mode)\n` +
|
||||
`- CLI Tool: ${session.cli_tool}\n` +
|
||||
`- Completed: ${session.completed.length}\n` +
|
||||
`- Failed: ${session.failed.length}\n` +
|
||||
`- Skipped: ${session.skipped.length}\n` +
|
||||
`- Total: ${session.tasks.length}\n`;
|
||||
const finalProgress = Read(`${sessionDir}/progress.md`);
|
||||
Write(`${sessionDir}/progress.md`, finalProgress + summary);
|
||||
|
||||
console.log('\n=== IDAW Coordinate Complete ===');
|
||||
console.log(`Session: ${sessionId}`);
|
||||
console.log(`Completed: ${session.completed.length}/${session.tasks.length}`);
|
||||
if (session.failed.length > 0) console.log(`Failed: ${session.failed.join(', ')}`);
|
||||
}
|
||||
```
|
||||
|
||||
## Helper Functions
|
||||
|
||||
### assembleCliPrompt
|
||||
|
||||
```javascript
|
||||
function assembleCliPrompt(skillName, task, previousResult, autoYes) {
|
||||
let prompt = '';
|
||||
const yFlag = autoYes ? ' -y' : '';
|
||||
|
||||
// Map skill to command invocation
|
||||
if (skillName === 'workflow-lite-plan') {
|
||||
const goal = sanitize(`${task.title}\n${task.description}`);
|
||||
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)}"`;
|
||||
|
||||
} else if (skillName === 'workflow-execute') {
|
||||
if (previousResult?.sessionId) {
|
||||
prompt = `/workflow-execute${yFlag} --resume-session="${previousResult.sessionId}"`;
|
||||
} else {
|
||||
prompt = `/workflow-execute${yFlag}`;
|
||||
}
|
||||
|
||||
} else if (skillName === 'workflow-test-fix') {
|
||||
if (previousResult?.sessionId) {
|
||||
prompt = `/workflow-test-fix${yFlag} "${previousResult.sessionId}"`;
|
||||
} else {
|
||||
prompt = `/workflow-test-fix${yFlag} "${sanitize(task.title)}"`;
|
||||
}
|
||||
|
||||
} else if (skillName === 'workflow-tdd-plan') {
|
||||
prompt = `/workflow-tdd-plan${yFlag} "${sanitize(task.title)}"`;
|
||||
|
||||
} else if (skillName === 'workflow:refactor-cycle') {
|
||||
prompt = `/workflow:refactor-cycle${yFlag} "${sanitize(task.title)}"`;
|
||||
|
||||
} else if (skillName === 'review-cycle') {
|
||||
if (previousResult?.sessionId) {
|
||||
prompt = `/review-cycle${yFlag} --session="${previousResult.sessionId}"`;
|
||||
} else {
|
||||
prompt = `/review-cycle${yFlag}`;
|
||||
}
|
||||
|
||||
} else {
|
||||
// Generic fallback
|
||||
prompt = `/${skillName}${yFlag} "${sanitize(task.title)}"`;
|
||||
}
|
||||
|
||||
// Append task context
|
||||
prompt += `\n\nTask: ${task.title}\nDescription: ${task.description}`;
|
||||
if (task.context?.affected_files?.length > 0) {
|
||||
prompt += `\nAffected files: ${task.context.affected_files.join(', ')}`;
|
||||
}
|
||||
if (task.context?.acceptance_criteria?.length > 0) {
|
||||
prompt += `\nAcceptance criteria: ${task.context.acceptance_criteria.join('; ')}`;
|
||||
}
|
||||
|
||||
return prompt;
|
||||
}
|
||||
```
|
||||
|
||||
### sanitize & escapeForShell
|
||||
|
||||
```javascript
|
||||
function sanitize(text) {
|
||||
return text
|
||||
.replace(/\\/g, '\\\\')
|
||||
.replace(/"/g, '\\"')
|
||||
.replace(/\$/g, '\\$')
|
||||
.replace(/`/g, '\\`');
|
||||
}
|
||||
|
||||
function escapeForShell(prompt) {
|
||||
return prompt.replace(/'/g, "'\\''");
|
||||
}
|
||||
```
|
||||
|
||||
### parseCliOutput
|
||||
|
||||
```javascript
|
||||
function parseCliOutput(output) {
|
||||
// Extract session ID from CLI output (e.g., WFS-xxx, session-xxx)
|
||||
const sessionMatch = output.match(/(?:session|WFS|Session ID)[:\s]*([\w-]+)/i);
|
||||
const success = !/(?:error|failed|fatal)/i.test(output) || /completed|success/i.test(output);
|
||||
|
||||
return {
|
||||
success,
|
||||
sessionId: sessionMatch?.[1] || null,
|
||||
raw: output?.substring(0, 500)
|
||||
};
|
||||
}
|
||||
```
|
||||
|
||||
## CLI-Assisted Analysis
|
||||
|
||||
Same as `/idaw:run` — integrated at two points:
|
||||
|
||||
### Pre-Task Context Analysis
|
||||
For `bugfix`, `bugfix-hotfix`, `feature-complex` tasks: auto-invoke `ccw cli --tool gemini --mode analysis` before launching skill chain.
|
||||
|
||||
### Error Recovery with CLI Diagnosis
|
||||
When a skill's CLI execution fails: invoke diagnosis → retry once → if still fails, mark failed and advance.
|
||||
|
||||
```
|
||||
Skill CLI fails → CLI diagnosis (gemini) → Retry CLI → Still fails → mark failed → next task
|
||||
```
|
||||
|
||||
## State Flow
|
||||
|
||||
```
|
||||
Phase 4: Launch first skill
|
||||
↓
|
||||
ccw cli --tool claude --mode write (background)
|
||||
↓
|
||||
★ STOP — wait for hook callback
|
||||
↓
|
||||
Phase 5: handleStepCompletion()
|
||||
├─ Skill succeeded + more in chain → launch next skill → STOP
|
||||
├─ Skill succeeded + chain complete → git checkpoint → next task → STOP
|
||||
├─ Skill failed → CLI diagnosis → retry → STOP
|
||||
└─ All tasks done → Phase 6: Report
|
||||
```
|
||||
|
||||
## Session State (session.json)
|
||||
|
||||
```json
|
||||
{
|
||||
"session_id": "IDA-fix-login-20260301",
|
||||
"mode": "coordinate",
|
||||
"cli_tool": "claude",
|
||||
"status": "running|waiting|completed|failed",
|
||||
"created_at": "ISO",
|
||||
"updated_at": "ISO",
|
||||
"tasks": ["IDAW-001", "IDAW-002"],
|
||||
"current_task": "IDAW-001",
|
||||
"current_skill_index": 0,
|
||||
"completed": [],
|
||||
"failed": [],
|
||||
"skipped": [],
|
||||
"prompts_used": [
|
||||
{
|
||||
"task_id": "IDAW-001",
|
||||
"skill_index": 0,
|
||||
"skill": "workflow-lite-plan",
|
||||
"prompt": "/workflow-lite-plan -y \"Fix login timeout\"",
|
||||
"timestamp": "ISO"
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
## Differences from /idaw:run
|
||||
|
||||
| Aspect | /idaw:run | /idaw:run-coordinate |
|
||||
|--------|-----------|---------------------|
|
||||
| Execution | `Skill()` blocking in main process | `ccw cli` background + hook callback |
|
||||
| Context window | Shared (each skill uses main context) | Isolated (each CLI gets fresh context) |
|
||||
| Concurrency | Sequential blocking | Sequential non-blocking (hook-driven) |
|
||||
| State tracking | session.json + task.json | session.json + task.json + prompts_used |
|
||||
| Tool selection | N/A (Skill native) | `--tool claude\|gemini\|qwen` |
|
||||
| Resume | Via `/idaw:resume` (same) | Via `/idaw:resume` (same, detects mode) |
|
||||
| Best for | Short chains, interactive | Long chains, autonomous, context-heavy |
|
||||
|
||||
## Examples
|
||||
|
||||
```bash
|
||||
# Execute all pending tasks via claude CLI
|
||||
/idaw:run-coordinate -y
|
||||
|
||||
# Use specific CLI tool
|
||||
/idaw:run-coordinate -y --tool gemini
|
||||
|
||||
# Execute specific tasks
|
||||
/idaw:run-coordinate --task IDAW-001,IDAW-003 --tool claude
|
||||
|
||||
# Dry run (show plan without executing)
|
||||
/idaw:run-coordinate --dry-run
|
||||
|
||||
# Interactive mode
|
||||
/idaw:run-coordinate
|
||||
```
|
||||
539
.claude/commands/idaw/run.md
Normal file
539
.claude/commands/idaw/run.md
Normal file
@@ -0,0 +1,539 @@
|
||||
---
|
||||
name: run
|
||||
description: IDAW orchestrator - execute task skill chains serially with git checkpoints
|
||||
argument-hint: "[-y|--yes] [--task <id>[,<id>,...]] [--dry-run]"
|
||||
allowed-tools: Skill(*), TodoWrite(*), AskUserQuestion(*), Read(*), Write(*), Bash(*), Glob(*)
|
||||
---
|
||||
|
||||
# IDAW Run Command (/idaw:run)
|
||||
|
||||
## Auto Mode
|
||||
|
||||
When `--yes` or `-y`: Skip all confirmations, auto-skip on failure, proceed with dirty git.
|
||||
|
||||
## Skill Chain Mapping
|
||||
|
||||
```javascript
|
||||
const SKILL_CHAIN_MAP = {
|
||||
'bugfix': ['workflow-lite-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-plan']
|
||||
};
|
||||
```
|
||||
|
||||
## Task Type Inference
|
||||
|
||||
```javascript
|
||||
function inferTaskType(title, description) {
|
||||
const text = `${title} ${description}`.toLowerCase();
|
||||
if (/urgent|production|critical/.test(text) && /fix|bug/.test(text)) return 'bugfix-hotfix';
|
||||
if (/refactor|重构|tech.*debt/.test(text)) return 'refactor';
|
||||
if (/tdd|test-driven|test first/.test(text)) return 'tdd';
|
||||
if (/test fail|fix test|failing test/.test(text)) return 'test-fix';
|
||||
if (/generate test|写测试|add test/.test(text)) return 'test';
|
||||
if (/review|code review/.test(text)) return 'review';
|
||||
if (/docs|documentation|readme/.test(text)) return 'docs';
|
||||
if (/fix|bug|error|crash|fail/.test(text)) return 'bugfix';
|
||||
if (/complex|multi-module|architecture/.test(text)) return 'feature-complex';
|
||||
return 'feature';
|
||||
}
|
||||
```
|
||||
|
||||
## 6-Phase Execution
|
||||
|
||||
### Phase 1: Load Tasks
|
||||
|
||||
```javascript
|
||||
const args = $ARGUMENTS;
|
||||
const autoYes = /(-y|--yes)/.test(args);
|
||||
const dryRun = /--dry-run/.test(args);
|
||||
const taskFilter = args.match(/--task\s+([\w,-]+)/)?.[1]?.split(',') || null;
|
||||
|
||||
// Load task files
|
||||
const taskFiles = Glob('.workflow/.idaw/tasks/IDAW-*.json') || [];
|
||||
|
||||
if (taskFiles.length === 0) {
|
||||
console.log('No IDAW tasks found. Use /idaw:add to create tasks.');
|
||||
return;
|
||||
}
|
||||
|
||||
// Parse and filter
|
||||
let tasks = taskFiles.map(f => JSON.parse(Read(f)));
|
||||
|
||||
if (taskFilter) {
|
||||
tasks = tasks.filter(t => taskFilter.includes(t.id));
|
||||
} else {
|
||||
tasks = tasks.filter(t => t.status === 'pending');
|
||||
}
|
||||
|
||||
if (tasks.length === 0) {
|
||||
console.log('No pending tasks to execute. Use /idaw:add to add tasks or --task to specify IDs.');
|
||||
return;
|
||||
}
|
||||
|
||||
// Sort: priority ASC (1=critical first), then ID ASC
|
||||
tasks.sort((a, b) => {
|
||||
if (a.priority !== b.priority) return a.priority - b.priority;
|
||||
return a.id.localeCompare(b.id);
|
||||
});
|
||||
```
|
||||
|
||||
### Phase 2: Session Setup
|
||||
|
||||
```javascript
|
||||
// Generate session ID: IDA-{slug}-YYYYMMDD
|
||||
const slug = tasks[0].title
|
||||
.toLowerCase()
|
||||
.replace(/[^a-z0-9]+/g, '-')
|
||||
.substring(0, 20)
|
||||
.replace(/-$/, '');
|
||||
const dateStr = new Date().toISOString().slice(0, 10).replace(/-/g, '');
|
||||
let sessionId = `IDA-${slug}-${dateStr}`;
|
||||
|
||||
// Check collision
|
||||
const existingSession = Glob(`.workflow/.idaw/sessions/${sessionId}/session.json`);
|
||||
if (existingSession?.length > 0) {
|
||||
sessionId = `${sessionId}-2`;
|
||||
}
|
||||
|
||||
const sessionDir = `.workflow/.idaw/sessions/${sessionId}`;
|
||||
Bash(`mkdir -p "${sessionDir}"`);
|
||||
|
||||
const session = {
|
||||
session_id: sessionId,
|
||||
status: 'running',
|
||||
created_at: new Date().toISOString(),
|
||||
updated_at: new Date().toISOString(),
|
||||
tasks: tasks.map(t => t.id),
|
||||
current_task: null,
|
||||
completed: [],
|
||||
failed: [],
|
||||
skipped: []
|
||||
};
|
||||
|
||||
Write(`${sessionDir}/session.json`, JSON.stringify(session, null, 2));
|
||||
|
||||
// Initialize progress.md
|
||||
const progressHeader = `# IDAW Progress — ${sessionId}\nStarted: ${session.created_at}\n\n`;
|
||||
Write(`${sessionDir}/progress.md`, progressHeader);
|
||||
|
||||
// TodoWrite
|
||||
TodoWrite({
|
||||
todos: tasks.map((t, i) => ({
|
||||
content: `IDAW:[${i + 1}/${tasks.length}] ${t.title}`,
|
||||
status: i === 0 ? 'in_progress' : 'pending',
|
||||
activeForm: `Executing ${t.title}`
|
||||
}))
|
||||
});
|
||||
```
|
||||
|
||||
### Phase 3: Startup Protocol
|
||||
|
||||
```javascript
|
||||
// Check for existing running sessions
|
||||
const runningSessions = Glob('.workflow/.idaw/sessions/IDA-*/session.json')
|
||||
?.map(f => JSON.parse(Read(f)))
|
||||
.filter(s => s.status === 'running' && s.session_id !== sessionId) || [];
|
||||
|
||||
if (runningSessions.length > 0) {
|
||||
if (!autoYes) {
|
||||
const answer = AskUserQuestion({
|
||||
questions: [{
|
||||
question: `Found running session: ${runningSessions[0].session_id}. How to proceed?`,
|
||||
header: 'Conflict',
|
||||
multiSelect: false,
|
||||
options: [
|
||||
{ label: 'Resume existing', description: 'Use /idaw:resume instead' },
|
||||
{ label: 'Start fresh', description: 'Continue with new session' },
|
||||
{ label: 'Abort', description: 'Cancel this run' }
|
||||
]
|
||||
}]
|
||||
});
|
||||
if (answer.answers?.Conflict === 'Resume existing') {
|
||||
console.log(`Use: /idaw:resume ${runningSessions[0].session_id}`);
|
||||
return;
|
||||
}
|
||||
if (answer.answers?.Conflict === 'Abort') return;
|
||||
}
|
||||
// autoYes or "Start fresh": proceed
|
||||
}
|
||||
|
||||
// Check git status
|
||||
const gitStatus = Bash('git status --porcelain 2>/dev/null');
|
||||
if (gitStatus?.trim()) {
|
||||
if (!autoYes) {
|
||||
const answer = AskUserQuestion({
|
||||
questions: [{
|
||||
question: 'Working tree has uncommitted changes. How to proceed?',
|
||||
header: 'Git',
|
||||
multiSelect: false,
|
||||
options: [
|
||||
{ label: 'Continue', description: 'Proceed with dirty tree' },
|
||||
{ label: 'Stash', description: 'git stash before running' },
|
||||
{ label: 'Abort', description: 'Stop and handle manually' }
|
||||
]
|
||||
}]
|
||||
});
|
||||
if (answer.answers?.Git === 'Stash') {
|
||||
Bash('git stash push -m "idaw-pre-run"');
|
||||
}
|
||||
if (answer.answers?.Git === 'Abort') return;
|
||||
}
|
||||
// autoYes: proceed silently
|
||||
}
|
||||
|
||||
// Dry run: show plan and exit
|
||||
if (dryRun) {
|
||||
console.log(`# Dry Run — ${sessionId}\n`);
|
||||
for (const task of tasks) {
|
||||
const taskType = task.task_type || inferTaskType(task.title, task.description);
|
||||
const chain = task.skill_chain || SKILL_CHAIN_MAP[taskType] || SKILL_CHAIN_MAP['feature'];
|
||||
console.log(`## ${task.id}: ${task.title}`);
|
||||
console.log(` Type: ${taskType} | Priority: ${task.priority}`);
|
||||
console.log(` Chain: ${chain.join(' → ')}\n`);
|
||||
}
|
||||
console.log(`Total: ${tasks.length} tasks`);
|
||||
return;
|
||||
}
|
||||
```
|
||||
|
||||
### Phase 4: Main Loop (serial, one task at a time)
|
||||
|
||||
```javascript
|
||||
for (let taskIdx = 0; taskIdx < tasks.length; taskIdx++) {
|
||||
const task = tasks[taskIdx];
|
||||
|
||||
// Skip completed/failed/skipped
|
||||
if (['completed', 'failed', 'skipped'].includes(task.status)) continue;
|
||||
|
||||
// Resolve skill chain
|
||||
const resolvedType = task.task_type || inferTaskType(task.title, task.description);
|
||||
const chain = task.skill_chain || SKILL_CHAIN_MAP[resolvedType] || SKILL_CHAIN_MAP['feature'];
|
||||
|
||||
// Update task status → in_progress
|
||||
task.status = 'in_progress';
|
||||
task.task_type = resolvedType; // persist inferred type
|
||||
task.execution.started_at = new Date().toISOString();
|
||||
Write(`.workflow/.idaw/tasks/${task.id}.json`, JSON.stringify(task, null, 2));
|
||||
|
||||
// Update session
|
||||
session.current_task = task.id;
|
||||
session.updated_at = new Date().toISOString();
|
||||
Write(`${sessionDir}/session.json`, JSON.stringify(session, null, 2));
|
||||
|
||||
console.log(`\n--- [${taskIdx + 1}/${tasks.length}] ${task.id}: ${task.title} ---`);
|
||||
console.log(`Chain: ${chain.join(' → ')}`);
|
||||
|
||||
// ━━━ Pre-Task CLI Context Analysis (for complex/bugfix tasks) ━━━
|
||||
if (['bugfix', 'bugfix-hotfix', 'feature-complex'].includes(resolvedType)) {
|
||||
console.log(` Pre-analysis: gathering context for ${resolvedType} task...`);
|
||||
const affectedFiles = (task.context?.affected_files || []).join(', ');
|
||||
const preAnalysisPrompt = `PURPOSE: Pre-analyze codebase context for IDAW task before execution.
|
||||
TASK: • Understand current state of: ${affectedFiles || 'files related to: ' + task.title} • Identify dependencies and risk areas • Note existing patterns to follow
|
||||
MODE: analysis
|
||||
CONTEXT: @**/*
|
||||
EXPECTED: Brief context summary (affected modules, dependencies, risk areas) in 3-5 bullet points
|
||||
CONSTRAINTS: Keep concise | Focus on execution-relevant context`;
|
||||
const preAnalysis = Bash(`ccw cli -p '${preAnalysisPrompt.replace(/'/g, "'\\''")}' --tool gemini --mode analysis 2>&1 || echo "Pre-analysis skipped"`);
|
||||
task.execution.skill_results.push({
|
||||
skill: 'cli-pre-analysis',
|
||||
status: 'completed',
|
||||
context_summary: preAnalysis?.substring(0, 500),
|
||||
timestamp: new Date().toISOString()
|
||||
});
|
||||
}
|
||||
|
||||
// Execute each skill in chain
|
||||
let previousResult = null;
|
||||
let taskFailed = false;
|
||||
|
||||
for (let skillIdx = 0; skillIdx < chain.length; skillIdx++) {
|
||||
const skillName = chain[skillIdx];
|
||||
const skillArgs = assembleSkillArgs(skillName, task, previousResult, autoYes, skillIdx === 0);
|
||||
|
||||
console.log(` [${skillIdx + 1}/${chain.length}] ${skillName}`);
|
||||
|
||||
try {
|
||||
const result = Skill({ skill: skillName, args: skillArgs });
|
||||
previousResult = result;
|
||||
task.execution.skill_results.push({
|
||||
skill: skillName,
|
||||
status: 'completed',
|
||||
timestamp: new Date().toISOString()
|
||||
});
|
||||
} catch (error) {
|
||||
// ━━━ CLI-Assisted Error Recovery ━━━
|
||||
// Step 1: Invoke CLI diagnosis (auto-invoke trigger: self-repair fails)
|
||||
console.log(` Diagnosing failure: ${skillName}...`);
|
||||
const diagnosisPrompt = `PURPOSE: Diagnose why skill "${skillName}" failed during IDAW task execution.
|
||||
TASK: • Analyze error: ${String(error).substring(0, 300)} • Check affected files: ${(task.context?.affected_files || []).join(', ') || 'unknown'} • Identify root cause • Suggest fix strategy
|
||||
MODE: analysis
|
||||
CONTEXT: @**/* | Memory: IDAW task ${task.id}: ${task.title}
|
||||
EXPECTED: Root cause + actionable fix recommendation (1-2 sentences)
|
||||
CONSTRAINTS: Focus on actionable diagnosis`;
|
||||
const diagnosisResult = Bash(`ccw cli -p '${diagnosisPrompt.replace(/'/g, "'\\''")}' --tool gemini --mode analysis --rule analysis-diagnose-bug-root-cause 2>&1 || echo "CLI diagnosis unavailable"`);
|
||||
|
||||
task.execution.skill_results.push({
|
||||
skill: `cli-diagnosis:${skillName}`,
|
||||
status: 'completed',
|
||||
diagnosis: diagnosisResult?.substring(0, 500),
|
||||
timestamp: new Date().toISOString()
|
||||
});
|
||||
|
||||
// Step 2: Retry with diagnosis context
|
||||
console.log(` Retry with diagnosis: ${skillName}`);
|
||||
try {
|
||||
const retryResult = Skill({ skill: skillName, args: skillArgs });
|
||||
previousResult = retryResult;
|
||||
task.execution.skill_results.push({
|
||||
skill: skillName,
|
||||
status: 'completed-retry-with-diagnosis',
|
||||
timestamp: new Date().toISOString()
|
||||
});
|
||||
} catch (retryError) {
|
||||
// Step 3: Failed after CLI-assisted retry
|
||||
task.execution.skill_results.push({
|
||||
skill: skillName,
|
||||
status: 'failed',
|
||||
error: String(retryError).substring(0, 200),
|
||||
timestamp: new Date().toISOString()
|
||||
});
|
||||
|
||||
if (autoYes) {
|
||||
taskFailed = true;
|
||||
break;
|
||||
} else {
|
||||
const answer = AskUserQuestion({
|
||||
questions: [{
|
||||
question: `${skillName} failed after CLI diagnosis + retry: ${String(retryError).substring(0, 100)}. How to proceed?`,
|
||||
header: 'Error',
|
||||
multiSelect: false,
|
||||
options: [
|
||||
{ label: 'Skip task', description: 'Mark task as failed, continue to next' },
|
||||
{ label: 'Abort', description: 'Stop entire run' }
|
||||
]
|
||||
}]
|
||||
});
|
||||
if (answer.answers?.Error === 'Abort') {
|
||||
task.status = 'failed';
|
||||
task.execution.error = String(retryError).substring(0, 200);
|
||||
Write(`.workflow/.idaw/tasks/${task.id}.json`, JSON.stringify(task, null, 2));
|
||||
session.failed.push(task.id);
|
||||
session.status = 'failed';
|
||||
session.updated_at = new Date().toISOString();
|
||||
Write(`${sessionDir}/session.json`, JSON.stringify(session, null, 2));
|
||||
return;
|
||||
}
|
||||
taskFailed = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Phase 5: Checkpoint (per task) — inline
|
||||
if (taskFailed) {
|
||||
task.status = 'failed';
|
||||
task.execution.error = 'Skill chain failed after retry';
|
||||
task.execution.completed_at = new Date().toISOString();
|
||||
session.failed.push(task.id);
|
||||
} else {
|
||||
// Git commit checkpoint
|
||||
const commitMsg = `feat(idaw): ${task.title} [${task.id}]`;
|
||||
const diffCheck = Bash('git diff --stat HEAD 2>/dev/null || echo ""');
|
||||
const untrackedCheck = Bash('git ls-files --others --exclude-standard 2>/dev/null || echo ""');
|
||||
|
||||
if (diffCheck?.trim() || untrackedCheck?.trim()) {
|
||||
Bash('git add -A');
|
||||
const commitResult = Bash(`git commit -m "$(cat <<'EOF'\n${commitMsg}\nEOF\n)"`);
|
||||
const commitHash = Bash('git rev-parse --short HEAD 2>/dev/null')?.trim();
|
||||
task.execution.git_commit = commitHash;
|
||||
} else {
|
||||
task.execution.git_commit = 'no-commit';
|
||||
}
|
||||
|
||||
task.status = 'completed';
|
||||
task.execution.completed_at = new Date().toISOString();
|
||||
session.completed.push(task.id);
|
||||
}
|
||||
|
||||
// Write task + session state
|
||||
task.updated_at = new Date().toISOString();
|
||||
Write(`.workflow/.idaw/tasks/${task.id}.json`, JSON.stringify(task, null, 2));
|
||||
|
||||
session.updated_at = new Date().toISOString();
|
||||
Write(`${sessionDir}/session.json`, JSON.stringify(session, null, 2));
|
||||
|
||||
// Append to progress.md
|
||||
const duration = task.execution.started_at && task.execution.completed_at
|
||||
? formatDuration(new Date(task.execution.completed_at) - new Date(task.execution.started_at))
|
||||
: 'unknown';
|
||||
|
||||
const progressEntry = `## ${task.id} — ${task.title}\n` +
|
||||
`- Status: ${task.status}\n` +
|
||||
`- Type: ${task.task_type}\n` +
|
||||
`- Chain: ${chain.join(' → ')}\n` +
|
||||
`- Commit: ${task.execution.git_commit || '-'}\n` +
|
||||
`- Duration: ${duration}\n\n`;
|
||||
|
||||
const currentProgress = Read(`${sessionDir}/progress.md`);
|
||||
Write(`${sessionDir}/progress.md`, currentProgress + progressEntry);
|
||||
|
||||
// Update TodoWrite
|
||||
if (taskIdx + 1 < tasks.length) {
|
||||
TodoWrite({
|
||||
todos: tasks.map((t, i) => ({
|
||||
content: `IDAW:[${i + 1}/${tasks.length}] ${t.title}`,
|
||||
status: i < taskIdx + 1 ? 'completed' : (i === taskIdx + 1 ? 'in_progress' : 'pending'),
|
||||
activeForm: `Executing ${t.title}`
|
||||
}))
|
||||
});
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Phase 6: Report
|
||||
|
||||
```javascript
|
||||
session.status = session.failed.length > 0 && session.completed.length === 0 ? 'failed' : 'completed';
|
||||
session.current_task = null;
|
||||
session.updated_at = new Date().toISOString();
|
||||
Write(`${sessionDir}/session.json`, JSON.stringify(session, null, 2));
|
||||
|
||||
// Final progress summary
|
||||
const summary = `\n---\n## Summary\n` +
|
||||
`- Completed: ${session.completed.length}\n` +
|
||||
`- Failed: ${session.failed.length}\n` +
|
||||
`- Skipped: ${session.skipped.length}\n` +
|
||||
`- Total: ${tasks.length}\n`;
|
||||
|
||||
const finalProgress = Read(`${sessionDir}/progress.md`);
|
||||
Write(`${sessionDir}/progress.md`, finalProgress + summary);
|
||||
|
||||
// Display report
|
||||
console.log('\n=== IDAW Run Complete ===');
|
||||
console.log(`Session: ${sessionId}`);
|
||||
console.log(`Completed: ${session.completed.length}/${tasks.length}`);
|
||||
if (session.failed.length > 0) console.log(`Failed: ${session.failed.join(', ')}`);
|
||||
if (session.skipped.length > 0) console.log(`Skipped: ${session.skipped.join(', ')}`);
|
||||
|
||||
// List git commits
|
||||
for (const taskId of session.completed) {
|
||||
const t = JSON.parse(Read(`.workflow/.idaw/tasks/${taskId}.json`));
|
||||
if (t.execution.git_commit && t.execution.git_commit !== 'no-commit') {
|
||||
console.log(` ${t.execution.git_commit} ${t.title}`);
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## Helper Functions
|
||||
|
||||
### assembleSkillArgs
|
||||
|
||||
```javascript
|
||||
function assembleSkillArgs(skillName, task, previousResult, autoYes, isFirst) {
|
||||
let args = '';
|
||||
|
||||
if (isFirst) {
|
||||
// First skill: pass task goal — sanitize for shell safety
|
||||
const goal = `${task.title}\n${task.description}`
|
||||
.replace(/\\/g, '\\\\')
|
||||
.replace(/"/g, '\\"')
|
||||
.replace(/\$/g, '\\$')
|
||||
.replace(/`/g, '\\`');
|
||||
args = `"${goal}"`;
|
||||
|
||||
// bugfix-hotfix: add --hotfix
|
||||
if (task.task_type === 'bugfix-hotfix') {
|
||||
args += ' --hotfix';
|
||||
}
|
||||
} else if (previousResult?.session_id) {
|
||||
// Subsequent skills: chain session
|
||||
args = `--session="${previousResult.session_id}"`;
|
||||
}
|
||||
|
||||
// Propagate -y
|
||||
if (autoYes && !args.includes('-y') && !args.includes('--yes')) {
|
||||
args = args ? `${args} -y` : '-y';
|
||||
}
|
||||
|
||||
return args;
|
||||
}
|
||||
```
|
||||
|
||||
### formatDuration
|
||||
|
||||
```javascript
|
||||
function formatDuration(ms) {
|
||||
const seconds = Math.floor(ms / 1000);
|
||||
const minutes = Math.floor(seconds / 60);
|
||||
const remainingSeconds = seconds % 60;
|
||||
if (minutes > 0) return `${minutes}m ${remainingSeconds}s`;
|
||||
return `${seconds}s`;
|
||||
}
|
||||
```
|
||||
|
||||
## CLI-Assisted Analysis
|
||||
|
||||
IDAW integrates `ccw cli` (Gemini) for intelligent analysis at two key points:
|
||||
|
||||
### Pre-Task Context Analysis
|
||||
|
||||
For `bugfix`, `bugfix-hotfix`, and `feature-complex` tasks, IDAW automatically invokes CLI analysis **before** executing the skill chain to gather codebase context:
|
||||
|
||||
```
|
||||
Task starts → CLI pre-analysis (gemini) → Context gathered → Skill chain executes
|
||||
```
|
||||
|
||||
- Identifies dependencies and risk areas
|
||||
- Notes existing patterns to follow
|
||||
- Results stored in `task.execution.skill_results` as `cli-pre-analysis`
|
||||
|
||||
### Error Recovery with CLI Diagnosis
|
||||
|
||||
When a skill fails, instead of blind retry, IDAW uses CLI-assisted diagnosis:
|
||||
|
||||
```
|
||||
Skill fails → CLI diagnosis (gemini, analysis-diagnose-bug-root-cause)
|
||||
→ Root cause identified → Retry with diagnosis context
|
||||
→ Still fails → Skip (autoYes) or Ask user (interactive)
|
||||
```
|
||||
|
||||
- Uses `--rule analysis-diagnose-bug-root-cause` template
|
||||
- Diagnosis results stored in `task.execution.skill_results` as `cli-diagnosis:{skill}`
|
||||
- Follows CLAUDE.md auto-invoke trigger pattern: "self-repair fails → invoke CLI analysis"
|
||||
|
||||
### Execution Flow (with CLI analysis)
|
||||
|
||||
```
|
||||
Phase 4 Main Loop (per task):
|
||||
├─ [bugfix/complex only] CLI pre-analysis → context summary
|
||||
├─ Skill 1: execute
|
||||
│ ├─ Success → next skill
|
||||
│ └─ Failure → CLI diagnosis → retry → success/fail
|
||||
├─ Skill 2: execute ...
|
||||
└─ Phase 5: git checkpoint
|
||||
```
|
||||
|
||||
## Examples
|
||||
|
||||
```bash
|
||||
# Execute all pending tasks
|
||||
/idaw:run -y
|
||||
|
||||
# Execute specific tasks
|
||||
/idaw:run --task IDAW-001,IDAW-003
|
||||
|
||||
# Dry run (show plan without executing)
|
||||
/idaw:run --dry-run
|
||||
|
||||
# Interactive mode (confirm at each step)
|
||||
/idaw:run
|
||||
```
|
||||
182
.claude/commands/idaw/status.md
Normal file
182
.claude/commands/idaw/status.md
Normal file
@@ -0,0 +1,182 @@
|
||||
---
|
||||
name: status
|
||||
description: View IDAW task and session progress
|
||||
argument-hint: "[session-id]"
|
||||
allowed-tools: Read(*), Glob(*), Bash(*)
|
||||
---
|
||||
|
||||
# IDAW Status Command (/idaw:status)
|
||||
|
||||
## Overview
|
||||
|
||||
Read-only command to view IDAW task queue and execution session progress.
|
||||
|
||||
## Implementation
|
||||
|
||||
### Phase 1: Determine View Mode
|
||||
|
||||
```javascript
|
||||
const sessionId = $ARGUMENTS?.trim();
|
||||
|
||||
if (sessionId) {
|
||||
// Specific session view
|
||||
showSession(sessionId);
|
||||
} else {
|
||||
// Overview: pending tasks + latest session
|
||||
showOverview();
|
||||
}
|
||||
```
|
||||
|
||||
### Phase 2: Show Overview
|
||||
|
||||
```javascript
|
||||
function showOverview() {
|
||||
// 1. Load all tasks
|
||||
const taskFiles = Glob('.workflow/.idaw/tasks/IDAW-*.json') || [];
|
||||
|
||||
if (taskFiles.length === 0) {
|
||||
console.log('No IDAW tasks found. Use /idaw:add to create tasks.');
|
||||
return;
|
||||
}
|
||||
|
||||
const tasks = taskFiles.map(f => JSON.parse(Read(f)));
|
||||
|
||||
// 2. Group by status
|
||||
const byStatus = {
|
||||
pending: tasks.filter(t => t.status === 'pending'),
|
||||
in_progress: tasks.filter(t => t.status === 'in_progress'),
|
||||
completed: tasks.filter(t => t.status === 'completed'),
|
||||
failed: tasks.filter(t => t.status === 'failed'),
|
||||
skipped: tasks.filter(t => t.status === 'skipped')
|
||||
};
|
||||
|
||||
// 3. Display task summary table
|
||||
console.log('# IDAW Tasks\n');
|
||||
console.log('| ID | Title | Type | Priority | Status |');
|
||||
console.log('|----|-------|------|----------|--------|');
|
||||
|
||||
// Sort: priority ASC, then ID ASC
|
||||
const sorted = [...tasks].sort((a, b) => {
|
||||
if (a.priority !== b.priority) return a.priority - b.priority;
|
||||
return a.id.localeCompare(b.id);
|
||||
});
|
||||
|
||||
for (const t of sorted) {
|
||||
const type = t.task_type || '(infer)';
|
||||
console.log(`| ${t.id} | ${t.title.substring(0, 40)} | ${type} | ${t.priority} | ${t.status} |`);
|
||||
}
|
||||
|
||||
console.log(`\nTotal: ${tasks.length} | Pending: ${byStatus.pending.length} | Completed: ${byStatus.completed.length} | Failed: ${byStatus.failed.length}`);
|
||||
|
||||
// 4. Show latest session (if any)
|
||||
const sessionDirs = Glob('.workflow/.idaw/sessions/IDA-*/session.json') || [];
|
||||
if (sessionDirs.length > 0) {
|
||||
// Sort by modification time (newest first) — Glob returns sorted by mtime
|
||||
const latestSessionFile = sessionDirs[0];
|
||||
const session = JSON.parse(Read(latestSessionFile));
|
||||
console.log(`\n## Latest Session: ${session.session_id}`);
|
||||
console.log(`Status: ${session.status} | Tasks: ${session.tasks?.length || 0}`);
|
||||
console.log(`Completed: ${session.completed?.length || 0} | Failed: ${session.failed?.length || 0} | Skipped: ${session.skipped?.length || 0}`);
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Phase 3: Show Specific Session
|
||||
|
||||
```javascript
|
||||
function showSession(sessionId) {
|
||||
const sessionFile = `.workflow/.idaw/sessions/${sessionId}/session.json`;
|
||||
const progressFile = `.workflow/.idaw/sessions/${sessionId}/progress.md`;
|
||||
|
||||
// Try reading session
|
||||
try {
|
||||
const session = JSON.parse(Read(sessionFile));
|
||||
|
||||
console.log(`# IDAW Session: ${session.session_id}\n`);
|
||||
console.log(`Status: ${session.status}`);
|
||||
console.log(`Created: ${session.created_at}`);
|
||||
console.log(`Updated: ${session.updated_at}`);
|
||||
console.log(`Current Task: ${session.current_task || 'none'}\n`);
|
||||
|
||||
// Task detail table
|
||||
console.log('| ID | Title | Status | Commit |');
|
||||
console.log('|----|-------|--------|--------|');
|
||||
|
||||
for (const taskId of session.tasks) {
|
||||
const taskFile = `.workflow/.idaw/tasks/${taskId}.json`;
|
||||
try {
|
||||
const task = JSON.parse(Read(taskFile));
|
||||
const commit = task.execution?.git_commit?.substring(0, 7) || '-';
|
||||
console.log(`| ${task.id} | ${task.title.substring(0, 40)} | ${task.status} | ${commit} |`);
|
||||
} catch {
|
||||
console.log(`| ${taskId} | (file not found) | unknown | - |`);
|
||||
}
|
||||
}
|
||||
|
||||
console.log(`\nCompleted: ${session.completed?.length || 0} | Failed: ${session.failed?.length || 0} | Skipped: ${session.skipped?.length || 0}`);
|
||||
|
||||
// Show progress.md if exists
|
||||
try {
|
||||
const progress = Read(progressFile);
|
||||
console.log('\n---\n');
|
||||
console.log(progress);
|
||||
} catch {
|
||||
// No progress file yet
|
||||
}
|
||||
|
||||
} catch {
|
||||
// Session not found — try listing all sessions
|
||||
console.log(`Session "${sessionId}" not found.\n`);
|
||||
listSessions();
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Phase 4: List All Sessions
|
||||
|
||||
```javascript
|
||||
function listSessions() {
|
||||
const sessionFiles = Glob('.workflow/.idaw/sessions/IDA-*/session.json') || [];
|
||||
|
||||
if (sessionFiles.length === 0) {
|
||||
console.log('No IDAW sessions found. Use /idaw:run to start execution.');
|
||||
return;
|
||||
}
|
||||
|
||||
console.log('# IDAW Sessions\n');
|
||||
console.log('| Session ID | Status | Tasks | Completed | Failed |');
|
||||
console.log('|------------|--------|-------|-----------|--------|');
|
||||
|
||||
for (const f of sessionFiles) {
|
||||
try {
|
||||
const session = JSON.parse(Read(f));
|
||||
console.log(`| ${session.session_id} | ${session.status} | ${session.tasks?.length || 0} | ${session.completed?.length || 0} | ${session.failed?.length || 0} |`);
|
||||
} catch {
|
||||
// Skip malformed
|
||||
}
|
||||
}
|
||||
|
||||
console.log('\nUse /idaw:status <session-id> for details.');
|
||||
}
|
||||
```
|
||||
|
||||
## Examples
|
||||
|
||||
```bash
|
||||
# Show overview (pending tasks + latest session)
|
||||
/idaw:status
|
||||
|
||||
# Show specific session details
|
||||
/idaw:status IDA-auth-fix-20260301
|
||||
|
||||
# Output example:
|
||||
# IDAW Tasks
|
||||
#
|
||||
# | ID | Title | Type | Priority | Status |
|
||||
# |----------|------------------------------------|--------|----------|-----------|
|
||||
# | IDAW-001 | Fix auth token refresh | bugfix | 1 | completed |
|
||||
# | IDAW-002 | Add rate limiting | feature| 2 | pending |
|
||||
# | IDAW-003 | Refactor payment module | refact | 3 | pending |
|
||||
#
|
||||
# Total: 3 | Pending: 2 | Completed: 1 | Failed: 0
|
||||
```
|
||||
@@ -2,7 +2,7 @@
|
||||
name: issue:discover-by-prompt
|
||||
description: Discover issues from user prompt with Gemini-planned iterative multi-agent exploration. Uses ACE semantic search for context gathering and supports cross-module comparison (e.g., frontend vs backend API contracts).
|
||||
argument-hint: "[-y|--yes] <prompt> [--scope=src/**] [--depth=standard|deep] [--max-iterations=5]"
|
||||
allowed-tools: Skill(*), TodoWrite(*), Read(*), Bash(*), Task(*), AskUserQuestion(*), Glob(*), Grep(*), mcp__ace-tool__search_context(*), mcp__exa__search(*)
|
||||
allowed-tools: Skill(*), TodoWrite(*), Read(*), Bash(*), Agent(*), AskUserQuestion(*), Glob(*), Grep(*), mcp__ace-tool__search_context(*), mcp__exa__search(*)
|
||||
---
|
||||
|
||||
## Auto Mode
|
||||
@@ -404,7 +404,7 @@ while (shouldContinue && iteration < maxIterations) {
|
||||
|
||||
// Step 3: Launch dimension agents with ACE context
|
||||
const agentPromises = iterationPlan.dimensions.map(dimension =>
|
||||
Task({
|
||||
Agent({
|
||||
subagent_type: "cli-explore-agent",
|
||||
run_in_background: false,
|
||||
description: `Explore ${dimension.name} (iteration ${iteration})`,
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
name: issue:discover
|
||||
description: Discover potential issues from multiple perspectives (bug, UX, test, quality, security, performance, maintainability, best-practices) using CLI explore. Supports Exa external research for security and best-practices perspectives.
|
||||
argument-hint: "[-y|--yes] <path-pattern> [--perspectives=bug,ux,...] [--external]"
|
||||
allowed-tools: Skill(*), TodoWrite(*), Read(*), Bash(*), Task(*), AskUserQuestion(*), Glob(*), Grep(*)
|
||||
allowed-tools: Skill(*), TodoWrite(*), Read(*), Bash(*), Agent(*), AskUserQuestion(*), Glob(*), Grep(*)
|
||||
---
|
||||
|
||||
## Auto Mode
|
||||
@@ -185,7 +185,7 @@ Launch N agents in parallel (one per selected perspective):
|
||||
```javascript
|
||||
// Launch agents in parallel - agents write JSON and return summary
|
||||
const agentPromises = selectedPerspectives.map(perspective =>
|
||||
Task({
|
||||
Agent({
|
||||
subagent_type: "cli-explore-agent",
|
||||
run_in_background: false,
|
||||
description: `Discover ${perspective} issues`,
|
||||
@@ -252,6 +252,17 @@ await updateDiscoveryState(outputDir, {
|
||||
const hasHighPriority = issues.some(i => i.priority === 'critical' || i.priority === 'high');
|
||||
const hasMediumFindings = prioritizedFindings.some(f => f.priority === 'medium');
|
||||
|
||||
// Auto mode: auto-select recommended action
|
||||
if (autoYes) {
|
||||
if (hasHighPriority) {
|
||||
await appendJsonl('.workflow/issues/issues.jsonl', issues);
|
||||
console.log(`Exported ${issues.length} issues. Run /issue:plan to continue.`);
|
||||
} else {
|
||||
console.log('Discovery complete. No significant issues found.');
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
await AskUserQuestion({
|
||||
questions: [{
|
||||
question: `Discovery complete: ${issues.length} issues generated, ${prioritizedFindings.length} total findings. What would you like to do next?`,
|
||||
@@ -311,7 +322,7 @@ if (response === "Export to Issues") {
|
||||
**Perspective Analysis Agent**:
|
||||
|
||||
```javascript
|
||||
Task({
|
||||
Agent({
|
||||
subagent_type: "cli-explore-agent",
|
||||
run_in_background: false,
|
||||
description: `Discover ${perspective} issues`,
|
||||
@@ -357,7 +368,7 @@ Task({
|
||||
**Exa Research Agent** (for security and best-practices):
|
||||
|
||||
```javascript
|
||||
Task({
|
||||
Agent({
|
||||
subagent_type: "cli-explore-agent",
|
||||
run_in_background: false,
|
||||
description: `External research for ${perspective} via Exa`,
|
||||
|
||||
@@ -152,6 +152,12 @@ if (!QUEUE_ID) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Auto mode: auto-select if exactly one active queue
|
||||
if (autoYes && activeQueues.length === 1) {
|
||||
QUEUE_ID = activeQueues[0].id;
|
||||
console.log(`Auto-selected queue: ${QUEUE_ID}`);
|
||||
} else {
|
||||
|
||||
// Display and prompt user
|
||||
console.log('\nAvailable Queues:');
|
||||
console.log('ID'.padEnd(22) + 'Status'.padEnd(12) + 'Progress'.padEnd(12) + 'Issues');
|
||||
@@ -176,6 +182,7 @@ if (!QUEUE_ID) {
|
||||
});
|
||||
|
||||
QUEUE_ID = answer['Queue'];
|
||||
} // end else (multi-queue prompt)
|
||||
}
|
||||
|
||||
console.log(`\n## Executing Queue: ${QUEUE_ID}\n`);
|
||||
@@ -203,6 +210,13 @@ console.log(`
|
||||
- Parallel in batch 1: ${dag.parallel_batches[0]?.length || 0}
|
||||
`);
|
||||
|
||||
// Auto mode: use recommended defaults (Codex + Execute + Worktree)
|
||||
if (autoYes) {
|
||||
var executor = 'codex';
|
||||
var isDryRun = false;
|
||||
var useWorktree = true;
|
||||
} else {
|
||||
|
||||
// Interactive selection via AskUserQuestion
|
||||
const answer = AskUserQuestion({
|
||||
questions: [
|
||||
@@ -237,9 +251,10 @@ const answer = AskUserQuestion({
|
||||
]
|
||||
});
|
||||
|
||||
const executor = answer['Executor'].toLowerCase().split(' ')[0]; // codex|gemini|agent
|
||||
const isDryRun = answer['Mode'].includes('Dry-run');
|
||||
const useWorktree = answer['Worktree'].includes('Yes');
|
||||
var executor = answer['Executor'].toLowerCase().split(' ')[0]; // codex|gemini|agent
|
||||
var isDryRun = answer['Mode'].includes('Dry-run');
|
||||
var useWorktree = answer['Worktree'].includes('Yes');
|
||||
} // end else (interactive selection)
|
||||
|
||||
// Dry run mode
|
||||
if (isDryRun) {
|
||||
@@ -414,7 +429,7 @@ On failure, run:
|
||||
{ timeout: 3600000, run_in_background: true }
|
||||
);
|
||||
} else {
|
||||
return Task({
|
||||
return Agent({
|
||||
subagent_type: 'code-developer',
|
||||
run_in_background: false,
|
||||
description: `Execute solution ${solutionId}`,
|
||||
@@ -451,27 +466,33 @@ if (refreshedDag.ready_count > 0) {
|
||||
if (useWorktree && refreshedDag.ready_count === 0 && refreshedDag.completed_count === refreshedDag.total) {
|
||||
console.log('\n## All Solutions Completed - Worktree Cleanup');
|
||||
|
||||
const answer = AskUserQuestion({
|
||||
questions: [{
|
||||
question: `Queue complete. What to do with worktree branch "${worktreeBranch}"?`,
|
||||
header: 'Merge',
|
||||
multiSelect: false,
|
||||
options: [
|
||||
{ label: 'Create PR (Recommended)', description: 'Push branch and create pull request' },
|
||||
{ label: 'Merge to main', description: 'Merge all commits and cleanup worktree' },
|
||||
{ label: 'Keep branch', description: 'Cleanup worktree, keep branch for manual handling' }
|
||||
]
|
||||
}]
|
||||
});
|
||||
// Auto mode: Create PR (recommended)
|
||||
if (autoYes) {
|
||||
var mergeAction = 'Create PR';
|
||||
} else {
|
||||
const answer = AskUserQuestion({
|
||||
questions: [{
|
||||
question: `Queue complete. What to do with worktree branch "${worktreeBranch}"?`,
|
||||
header: 'Merge',
|
||||
multiSelect: false,
|
||||
options: [
|
||||
{ label: 'Create PR (Recommended)', description: 'Push branch and create pull request' },
|
||||
{ label: 'Merge to main', description: 'Merge all commits and cleanup worktree' },
|
||||
{ label: 'Keep branch', description: 'Cleanup worktree, keep branch for manual handling' }
|
||||
]
|
||||
}]
|
||||
});
|
||||
var mergeAction = answer['Merge'];
|
||||
}
|
||||
|
||||
const repoRoot = Bash('git rev-parse --show-toplevel').trim();
|
||||
|
||||
if (answer['Merge'].includes('Create PR')) {
|
||||
if (mergeAction.includes('Create PR')) {
|
||||
Bash(`git -C "${worktreePath}" push -u origin "${worktreeBranch}"`);
|
||||
Bash(`gh pr create --title "Queue ${dag.queue_id}" --body "Issue queue execution - all solutions completed" --head "${worktreeBranch}"`);
|
||||
Bash(`git worktree remove "${worktreePath}"`);
|
||||
console.log(`PR created for branch: ${worktreeBranch}`);
|
||||
} else if (answer['Merge'].includes('Merge to main')) {
|
||||
} else if (mergeAction.includes('Merge to main')) {
|
||||
// Check main is clean
|
||||
const mainDirty = Bash('git status --porcelain').trim();
|
||||
if (mainDirty) {
|
||||
|
||||
@@ -154,8 +154,8 @@ Phase 6: Bind Solution
|
||||
├─ Update issue status to 'planned'
|
||||
└─ Returns: SOL-{issue-id}-{uid}
|
||||
|
||||
Phase 7: Next Steps
|
||||
└─ Offer: Form queue | Convert another idea | View details | Done
|
||||
Phase 7: Next Steps (skip in auto mode)
|
||||
└─ Auto mode: complete directly | Interactive: Form queue | Convert another | Done
|
||||
```
|
||||
|
||||
## Context Enrichment Logic
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
name: plan
|
||||
description: Batch plan issue resolution using issue-plan-agent (explore + plan closed-loop)
|
||||
argument-hint: "[-y|--yes] --all-pending <issue-id>[,<issue-id>,...] [--batch-size 3]"
|
||||
allowed-tools: TodoWrite(*), Task(*), Skill(*), AskUserQuestion(*), Bash(*), Read(*), Write(*)
|
||||
allowed-tools: TodoWrite(*), Agent(*), Skill(*), AskUserQuestion(*), Bash(*), Read(*), Write(*)
|
||||
---
|
||||
|
||||
## Auto Mode
|
||||
@@ -160,7 +160,7 @@ ${issueList}
|
||||
|
||||
### Project Context (MANDATORY)
|
||||
1. Read: .workflow/project-tech.json (technology stack, architecture)
|
||||
2. Read: .workflow/project-guidelines.json (constraints and conventions)
|
||||
2. Read: .workflow/specs/*.md (constraints and conventions)
|
||||
|
||||
### Workflow
|
||||
1. Fetch issue details: ccw issue status <id> --json
|
||||
@@ -222,7 +222,7 @@ for (let i = 0; i < agentTasks.length; i += MAX_PARALLEL) {
|
||||
|
||||
// Collect results from this chunk
|
||||
for (const { taskId, batchIndex } of taskIds) {
|
||||
const result = TaskOutput(task_id=taskId, block=true);
|
||||
const result = TaskOutput({ task_id: taskId, block: true });
|
||||
|
||||
// Extract JSON from potential markdown code blocks (agent may wrap in ```json...```)
|
||||
const jsonText = extractJsonFromMarkdown(result);
|
||||
@@ -263,6 +263,14 @@ for (let i = 0; i < agentTasks.length; i += MAX_PARALLEL) {
|
||||
for (const pending of pendingSelections) {
|
||||
if (pending.solutions.length === 0) continue;
|
||||
|
||||
// Auto mode: auto-bind first (highest-ranked) solution
|
||||
if (autoYes) {
|
||||
const solId = pending.solutions[0].id;
|
||||
Bash(`ccw issue bind ${pending.issue_id} ${solId}`);
|
||||
console.log(`✓ ${pending.issue_id}: ${solId} bound (auto)`);
|
||||
continue;
|
||||
}
|
||||
|
||||
const options = pending.solutions.slice(0, 4).map(sol => ({
|
||||
label: `${sol.id} (${sol.task_count} tasks)`,
|
||||
description: sol.description || sol.approach || 'No description'
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
name: queue
|
||||
description: Form execution queue from bound solutions using issue-queue-agent (solution-level)
|
||||
argument-hint: "[-y|--yes] [--queues <n>] [--issue <id>]"
|
||||
allowed-tools: TodoWrite(*), Task(*), Bash(*), Read(*), Write(*)
|
||||
allowed-tools: TodoWrite(*), Agent(*), Bash(*), Read(*), Write(*)
|
||||
---
|
||||
|
||||
## Auto Mode
|
||||
@@ -247,7 +247,7 @@ if (numQueues === 1) {
|
||||
description=`Queue ${i + 1}/${numQueues}: ${group.length} solutions`
|
||||
)
|
||||
);
|
||||
// All agents launched in parallel via single message with multiple Task tool calls
|
||||
// All agents launched in parallel via single message with multiple Agent tool calls
|
||||
}
|
||||
```
|
||||
|
||||
@@ -273,6 +273,17 @@ const allClarifications = results.flatMap((r, i) =>
|
||||
```javascript
|
||||
if (allClarifications.length > 0) {
|
||||
for (const clarification of allClarifications) {
|
||||
// Auto mode: use recommended resolution (first option)
|
||||
if (autoYes) {
|
||||
const autoAnswer = clarification.options[0]?.label || 'skip';
|
||||
Task(
|
||||
subagent_type="issue-queue-agent",
|
||||
resume=clarification.agent_id,
|
||||
prompt=`Conflict ${clarification.conflict_id} resolved: ${autoAnswer}`
|
||||
);
|
||||
continue;
|
||||
}
|
||||
|
||||
// Present to user via AskUserQuestion
|
||||
const answer = AskUserQuestion({
|
||||
questions: [{
|
||||
@@ -345,6 +356,14 @@ ccw issue queue list --brief
|
||||
|
||||
**AskUserQuestion:**
|
||||
```javascript
|
||||
// Auto mode: merge into existing queue
|
||||
if (autoYes) {
|
||||
Bash(`ccw issue queue merge ${newQueueId} --queue ${activeQueueId}`);
|
||||
Bash(`ccw issue queue delete ${newQueueId}`);
|
||||
console.log(`Auto-merged new queue into ${activeQueueId}`);
|
||||
return;
|
||||
}
|
||||
|
||||
AskUserQuestion({
|
||||
questions: [{
|
||||
question: "Active queue exists. How would you like to proceed?",
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
name: prepare
|
||||
description: Delegate to universal-executor agent to analyze project via Gemini/Qwen CLI and return JSON core content package for task context
|
||||
argument-hint: "[--tool gemini|qwen] \"task context description\""
|
||||
allowed-tools: Task(*), Bash(*)
|
||||
allowed-tools: Agent(*), Bash(*)
|
||||
examples:
|
||||
- /memory:prepare "在当前前端基础上开发用户认证功能"
|
||||
- /memory:prepare --tool qwen "重构支付模块API"
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
name: analyze-with-file
|
||||
description: Interactive collaborative analysis with documented discussions, CLI-assisted exploration, and evolving understanding
|
||||
argument-hint: "[-y|--yes] [-c|--continue] \"topic or question\""
|
||||
allowed-tools: TodoWrite(*), Task(*), AskUserQuestion(*), Read(*), Grep(*), Glob(*), Bash(*), Edit(*), Write(*)
|
||||
allowed-tools: TodoWrite(*), Agent(*), AskUserQuestion(*), Read(*), Grep(*), Glob(*), Bash(*), Edit(*), Write(*)
|
||||
---
|
||||
|
||||
## Auto Mode
|
||||
@@ -11,222 +11,120 @@ When `--yes` or `-y`: Auto-confirm exploration decisions, use recommended analys
|
||||
|
||||
# Workflow Analyze Command
|
||||
|
||||
## Quick Start
|
||||
|
||||
```bash
|
||||
# Basic usage
|
||||
/workflow:analyze-with-file "如何优化这个项目的认证架构"
|
||||
|
||||
# With options
|
||||
/workflow:analyze-with-file --continue "认证架构" # Continue existing session
|
||||
/workflow:analyze-with-file -y "性能瓶颈分析" # Auto mode
|
||||
```
|
||||
|
||||
**Context Source**: cli-explore-agent + Gemini/Codex analysis
|
||||
**Output Directory**: `.workflow/.analysis/{session-id}/`
|
||||
**Core Innovation**: Documented discussion timeline with evolving understanding
|
||||
|
||||
## Output Artifacts
|
||||
|
||||
### Phase 1: Topic Understanding
|
||||
|
||||
| Artifact | Description |
|
||||
|----------|-------------|
|
||||
| `discussion.md` | Evolution of understanding & discussions (initialized) |
|
||||
| Session variables | Dimensions, focus areas, analysis depth |
|
||||
|
||||
### Phase 2: CLI Exploration
|
||||
|
||||
| Artifact | Description |
|
||||
|----------|-------------|
|
||||
| `exploration-codebase.json` | Single codebase context from cli-explore-agent |
|
||||
| `explorations/*.json` | Multi-perspective codebase explorations (parallel, up to 4) |
|
||||
| `explorations.json` | Single perspective aggregated findings |
|
||||
| `perspectives.json` | Multi-perspective findings (up to 4 perspectives) with synthesis |
|
||||
| Updated `discussion.md` | Round 1 with exploration results |
|
||||
|
||||
### Phase 3: Interactive Discussion
|
||||
|
||||
| Artifact | Description |
|
||||
|----------|-------------|
|
||||
| Updated `discussion.md` | Round 2-N with user feedback and insights |
|
||||
| Corrected assumptions | Tracked in discussion timeline |
|
||||
|
||||
### Phase 4: Synthesis & Conclusion
|
||||
|
||||
| Artifact | Description |
|
||||
|----------|-------------|
|
||||
| `conclusions.json` | Final synthesis with recommendations |
|
||||
| Final `discussion.md` | ⭐ Complete analysis with conclusions |
|
||||
|
||||
## Overview
|
||||
|
||||
Interactive collaborative analysis workflow with **documented discussion process**. Records understanding evolution, facilitates multi-round Q&A, and uses CLI tools for deep exploration.
|
||||
|
||||
**Core workflow**: Topic → Explore → Discuss → Document → Refine → Conclude
|
||||
| Phase | Artifact | Description |
|
||||
|-------|----------|-------------|
|
||||
| 1 | `discussion.md` | Initialized with TOC, Current Understanding block, timeline, metadata |
|
||||
| 1 | Session variables | Dimensions, focus areas, analysis depth |
|
||||
| 2 | `exploration-codebase.json` | Single codebase context from cli-explore-agent |
|
||||
| 2 | `explorations/*.json` | Multi-perspective codebase explorations (parallel, up to 4) |
|
||||
| 2 | `explorations.json` | Single perspective aggregated findings |
|
||||
| 2 | `perspectives.json` | Multi-perspective findings (up to 4) with synthesis |
|
||||
| 2 | Updated `discussion.md` | Round 1 + Initial Intent Coverage Check + Current Understanding replaced |
|
||||
| 3 | Updated `discussion.md` | Round 2-N: feedback, insights, narrative synthesis; TOC + Current Understanding updated each round |
|
||||
| 4 | `conclusions.json` | Final synthesis with recommendations (incl. steps[] + review_status) |
|
||||
| 4 | Final `discussion.md` | Complete analysis with conclusions, recommendation review summary, intent coverage matrix |
|
||||
|
||||
### Decision Recording Protocol
|
||||
|
||||
**⚠️ CRITICAL**: During analysis, the following situations **MUST** trigger immediate recording to discussion.md:
|
||||
**CRITICAL**: Record immediately when any of these occur:
|
||||
|
||||
| Trigger | What to Record | Target Section |
|
||||
|---------|---------------|----------------|
|
||||
| **Direction choice** | What was chosen, why, what alternatives were discarded | `#### Decision Log` |
|
||||
| **Key finding** | Finding content, impact scope, confidence level | `#### Key Findings` |
|
||||
| **Assumption change** | Old assumption → new understanding, reason for change, impact | `#### Corrected Assumptions` |
|
||||
| **User feedback** | User's original input, rationale for adoption/adjustment | `#### User Input` |
|
||||
| **Disagreement & trade-off** | Conflicting viewpoints, trade-off basis, final choice | `#### Decision Log` |
|
||||
| **Scope adjustment** | Before/after scope, trigger reason for adjustment | `#### Decision Log` |
|
||||
| **Direction choice** | What chosen, why, alternatives discarded | `#### Decision Log` |
|
||||
| **Key finding** | Content, impact scope, confidence level, hypothesis impact | `#### Key Findings` |
|
||||
| **Assumption change** | Old → new understanding, reason, impact | `#### Corrected Assumptions` |
|
||||
| **User feedback** | Input, rationale for adoption/adjustment | `#### User Input` |
|
||||
| **Disagreement & trade-off** | Conflicting views, trade-off basis, final choice | `#### Decision Log` |
|
||||
| **Scope adjustment** | Before/after scope, trigger reason | `#### Decision Log` |
|
||||
|
||||
**Decision Record Format**:
|
||||
```markdown
|
||||
> **Decision**: [Description of the decision]
|
||||
> - **Context**: [What triggered this decision]
|
||||
> - **Options considered**: [Alternatives evaluated]
|
||||
> - **Chosen**: [Selected approach] — **Reason**: [Rationale]
|
||||
> - **Impact**: [Effect on analysis direction/conclusions]
|
||||
> **Decision**: [Description]
|
||||
> - **Context**: [Trigger]
|
||||
> - **Options considered**: [Alternatives]
|
||||
> - **Chosen**: [Approach] — **Reason**: [Rationale]
|
||||
> - **Rejected**: [Why other options were discarded]
|
||||
> - **Impact**: [Effect on analysis]
|
||||
```
|
||||
|
||||
**Recording Principles**:
|
||||
- **Immediacy**: Record decisions as they happen, not at the end of a phase
|
||||
- **Completeness**: Capture context, options, chosen approach, and reason
|
||||
- **Traceability**: Later phases must be able to trace back why a decision was made
|
||||
|
||||
```
|
||||
┌─────────────────────────────────────────────────────────────────────────┐
|
||||
│ INTERACTIVE ANALYSIS WORKFLOW │
|
||||
├─────────────────────────────────────────────────────────────────────────┤
|
||||
│ │
|
||||
│ Phase 1: Topic Understanding │
|
||||
│ ├─ Parse topic/question │
|
||||
│ ├─ Identify analysis dimensions (architecture, performance, etc.) │
|
||||
│ ├─ Initial scoping with user │
|
||||
│ └─ Initialize discussion.md │
|
||||
│ │
|
||||
│ Phase 2: CLI Exploration │
|
||||
│ ├─ Codebase Exploration (cli-explore-agent, supports parallel ≤4) │
|
||||
│ ├─ Multi-Perspective Analysis (AFTER exploration) │
|
||||
│ │ ├─ Single: Comprehensive analysis │
|
||||
│ │ └─ Multi (≤4): Parallel perspectives with synthesis │
|
||||
│ ├─ Aggregate findings │
|
||||
│ └─ Update discussion.md with Round 1 │
|
||||
│ │
|
||||
│ Phase 3: Interactive Discussion (Multi-Round) │
|
||||
│ ├─ Present exploration findings │
|
||||
│ ├─ Facilitate Q&A with user │
|
||||
│ ├─ Capture user insights and corrections │
|
||||
│ ├─ Actions: Deepen | Adjust direction | Answer questions │
|
||||
│ ├─ Update discussion.md with each round │
|
||||
│ └─ Repeat until clarity achieved (max 5 rounds) │
|
||||
│ │
|
||||
│ Phase 4: Synthesis & Conclusion │
|
||||
│ ├─ Consolidate all insights │
|
||||
│ ├─ Generate conclusions with recommendations │
|
||||
│ ├─ Update discussion.md with final synthesis │
|
||||
│ └─ Offer follow-up options (issue/task/report) │
|
||||
│ │
|
||||
└─────────────────────────────────────────────────────────────────────────┘
|
||||
**Key Finding Record Format**:
|
||||
```markdown
|
||||
> **Finding**: [Content]
|
||||
> - **Confidence**: [High/Medium/Low] — **Why**: [Evidence basis]
|
||||
> - **Hypothesis Impact**: [Confirms/Refutes/Modifies] hypothesis "[name]"
|
||||
> - **Scope**: [What areas this affects]
|
||||
```
|
||||
|
||||
## Output Structure
|
||||
|
||||
```
|
||||
.workflow/.analysis/ANL-{slug}-{date}/
|
||||
├── discussion.md # ⭐ Evolution of understanding & discussions
|
||||
├── exploration-codebase.json # Phase 2: Single codebase context
|
||||
├── explorations/ # Phase 2: Multi-perspective codebase explorations (if selected)
|
||||
│ ├── technical.json
|
||||
│ └── architectural.json
|
||||
├── explorations.json # Phase 2: Single perspective findings
|
||||
├── perspectives.json # Phase 2: Multi-perspective findings (if selected)
|
||||
└── conclusions.json # Phase 4: Final synthesis
|
||||
```
|
||||
**Principles**: Immediacy (record as-it-happens), Completeness (context+options+chosen+reason+rejected), Traceability (later phases trace back), Depth (capture reasoning, not just outcomes)
|
||||
|
||||
## Implementation
|
||||
|
||||
### AskUserQuestion Constraints
|
||||
|
||||
All `AskUserQuestion` calls MUST comply:
|
||||
- **questions**: 1-4 questions per call
|
||||
- **options**: 2-4 per question (system auto-adds "Other" for free-text input)
|
||||
- **header**: max 12 characters
|
||||
- **label**: 1-5 words per option
|
||||
|
||||
### Session Initialization
|
||||
|
||||
**Objective**: Create session context and directory structure for analysis.
|
||||
|
||||
**Required Actions**:
|
||||
1. Extract topic/question from `$ARGUMENTS`
|
||||
2. Generate session ID: `ANL-{slug}-{date}`
|
||||
- slug: lowercase, alphanumeric + Chinese, max 40 chars
|
||||
- date: YYYY-MM-DD (UTC+8)
|
||||
2. Generate session ID: `ANL-{slug}-{date}` (slug: lowercase alphanumeric+Chinese, max 40 chars; date: YYYY-MM-DD UTC+8)
|
||||
3. Define session folder: `.workflow/.analysis/{session-id}`
|
||||
4. Parse command options:
|
||||
- `-c` or `--continue` for session continuation
|
||||
- `-y` or `--yes` for auto-approval mode
|
||||
5. Auto-detect mode: If session folder + discussion.md exist → continue mode
|
||||
6. Create directory structure: `{session-folder}/`
|
||||
4. Parse options: `-c`/`--continue` for continuation, `-y`/`--yes` for auto-approval
|
||||
5. Auto-detect: If session folder + discussion.md exist → continue mode
|
||||
6. Create directory structure
|
||||
7. **Create Progress Tracking** (TodoWrite — MANDATORY):
|
||||
```
|
||||
TodoWrite([
|
||||
{ id: "phase-1", title: "Phase 1: Topic Understanding", status: "in_progress" },
|
||||
{ id: "phase-2", title: "Phase 2: CLI Exploration", status: "pending" },
|
||||
{ id: "phase-3", title: "Phase 3: Interactive Discussion", status: "pending" },
|
||||
{ id: "phase-4", title: "Phase 4: Synthesis & Conclusion", 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`: Unique session identifier
|
||||
- `sessionFolder`: Base directory for all artifacts
|
||||
- `autoMode`: Boolean for auto-confirmation
|
||||
- `mode`: new | continue
|
||||
**Session Variables**: `sessionId`, `sessionFolder`, `autoMode` (boolean), `mode` (new|continue)
|
||||
|
||||
### Phase 1: Topic Understanding
|
||||
|
||||
**Objective**: Analyze topic, identify dimensions, gather user input, initialize discussion.md.
|
||||
1. **Parse Topic & Identify Dimensions** — Match keywords against Analysis Dimensions table
|
||||
2. **Initial Scoping** (if new session + not auto mode) — use **single AskUserQuestion call with up to 3 questions**:
|
||||
- Q1 **Focus** (multiSelect: true, header: "分析方向"): Top 3-4 directions from Dimension-Direction Mapping (options max 4)
|
||||
- Q2 **Perspectives** (multiSelect: true, header: "分析视角"): Up to 4 from Analysis Perspectives table (options max 4), default: single comprehensive
|
||||
- Q3 **Depth** (multiSelect: false, header: "分析深度"): Quick Overview / Standard / Deep Dive (3 options)
|
||||
3. **Initialize discussion.md** — Structure includes:
|
||||
- **Dynamic TOC** (top of file, updated after each round/phase): `## Table of Contents` with links to major sections
|
||||
- **Current Understanding** (replaceable block, overwritten each round — NOT appended): `## Current Understanding` initialized as "To be populated after exploration"
|
||||
- Session metadata, user context, initial questions, empty discussion timeline, initial dimension selection rationale
|
||||
4. **Record Phase 1 Decisions** — Dimension selection reasoning, depth rationale, any user adjustments
|
||||
|
||||
**Prerequisites**:
|
||||
- Session initialized with valid sessionId and sessionFolder
|
||||
- Topic/question available from $ARGUMENTS
|
||||
|
||||
**Workflow Steps**:
|
||||
|
||||
1. **Parse Topic & Identify Dimensions**
|
||||
- Match topic keywords against ANALYSIS_DIMENSIONS
|
||||
- Identify relevant dimensions: architecture, implementation, performance, security, concept, comparison, decision
|
||||
- Default to "general" if no match
|
||||
|
||||
2. **Initial Scoping** (if new session + not auto mode)
|
||||
- **Focus**: Multi-select from directions generated by detected dimensions (see Dimension-Direction Mapping)
|
||||
- **Perspectives**: Multi-select up to 4 analysis perspectives (see Analysis Perspectives), default: single comprehensive view
|
||||
- **Depth**: Single-select from Quick Overview (10-15min) / Standard Analysis (30-60min) / Deep Dive (1-2hr)
|
||||
|
||||
3. **Initialize discussion.md**
|
||||
- Create discussion.md with session metadata
|
||||
- Add user context: focus areas, analysis depth
|
||||
- Add initial understanding: dimensions, scope, key questions
|
||||
- Create empty sections for discussion timeline
|
||||
- **📌 Record initial decisions**: Document dimension selection rationale, excluded dimensions with reasons, intent behind user preferences
|
||||
|
||||
4. **📌 Record Phase 1 Decisions**
|
||||
- Record why these dimensions were selected (keyword match + user confirmation)
|
||||
- Record the rationale behind analysis depth selection
|
||||
- If user adjusted recommended focus, record the adjustment reason
|
||||
|
||||
**Success Criteria**:
|
||||
- Session folder created with discussion.md initialized
|
||||
- Analysis dimensions identified
|
||||
- User preferences captured (focus, depth)
|
||||
- **Phase 1 decisions recorded** with context and rationale
|
||||
**Success**: Session folder + discussion.md created, dimensions identified, preferences captured, decisions recorded
|
||||
**TodoWrite**: Update `phase-1` → `"completed"`, `phase-2` → `"in_progress"`
|
||||
|
||||
### Phase 2: CLI Exploration
|
||||
|
||||
**Objective**: Gather codebase context, then execute deep analysis via CLI tools.
|
||||
Codebase exploration FIRST, then CLI analysis.
|
||||
|
||||
**Prerequisites**:
|
||||
- Phase 1 completed successfully
|
||||
- discussion.md initialized
|
||||
- Dimensions identified
|
||||
**Step 1: Codebase Exploration** (cli-explore-agent, parallel up to 6)
|
||||
|
||||
**Workflow Steps** (⚠️ Codebase exploration FIRST):
|
||||
- **Single**: General codebase analysis → `{sessionFolder}/exploration-codebase.json`
|
||||
- **Multi-perspective**: Parallel per-perspective → `{sessionFolder}/explorations/{perspective}.json`
|
||||
- **Common tasks**: `ccw tool exec get_modules_by_depth '{}'`, keyword searches, read `.workflow/project-tech.json`
|
||||
|
||||
1. **Codebase Exploration via cli-explore-agent** (supports parallel up to 4)
|
||||
- Agent type: `cli-explore-agent`
|
||||
- Execution mode: parallel if multi-perspective selected, otherwise single (run_in_background: false for sequential, true for parallel)
|
||||
- **Single exploration**: General codebase analysis
|
||||
- **Multi-perspective**: Parallel explorations per perspective focus (max 4, each with specific angle)
|
||||
- **Common tasks**: Run `ccw tool exec get_modules_by_depth '{}'`, execute searches based on topic keywords, read `.workflow/project-tech.json`
|
||||
- **Output**: `{sessionFolder}/exploration-codebase.json` (single) or `{sessionFolder}/explorations/{perspective}.json` (multi)
|
||||
- **Purpose**: Enrich CLI prompts with codebase context for each perspective
|
||||
|
||||
**Single Exploration Example**:
|
||||
```javascript
|
||||
Task({
|
||||
// Template for cli-explore-agent (single or per-perspective)
|
||||
Agent({
|
||||
subagent_type: "cli-explore-agent",
|
||||
run_in_background: false,
|
||||
description: `Explore codebase: ${topicSlug}`,
|
||||
@@ -234,340 +132,298 @@ Task({
|
||||
## Analysis Context
|
||||
Topic: ${topic_or_question}
|
||||
Dimensions: ${dimensions.join(', ')}
|
||||
// For multi-perspective, add: Perspective: ${perspective.name} - ${perspective.focus}
|
||||
Session: ${sessionFolder}
|
||||
|
||||
## MANDATORY FIRST STEPS
|
||||
1. Run: ccw tool exec get_modules_by_depth '{}'
|
||||
2. Execute relevant searches based on topic keywords
|
||||
3. Read: .workflow/project-tech.json (if exists)
|
||||
2. Read: .workflow/project-tech.json (if exists)
|
||||
|
||||
## Exploration Focus
|
||||
${dimensions.map(d => `- ${d}: Identify relevant code patterns and structures`).join('\n')}
|
||||
## Layered Exploration (MUST follow all 3 layers)
|
||||
|
||||
### Layer 1 — Module Discovery (Breadth)
|
||||
- Search by topic keywords, identify ALL relevant files
|
||||
- Map module boundaries and entry points → relevant_files[] with annotations
|
||||
|
||||
### Layer 2 — Structure Tracing (Depth)
|
||||
- Top 3-5 key files: trace call chains 2-3 levels deep
|
||||
- Identify data flow paths and dependencies → call_chains[], data_flows[]
|
||||
|
||||
### Layer 3 — Code Anchor Extraction (Detail)
|
||||
- Each key finding: extract code snippet (20-50 lines) with file:line
|
||||
- Annotate WHY this matters → code_anchors[]
|
||||
|
||||
## Output
|
||||
Write findings to: ${sessionFolder}/exploration-codebase.json
|
||||
Write to: ${sessionFolder}/exploration-codebase.json
|
||||
// Multi-perspective: ${sessionFolder}/explorations/${perspective.name}.json
|
||||
|
||||
Schema: {relevant_files, patterns, key_findings, questions_for_user, _metadata}
|
||||
Schema: {relevant_files, patterns, key_findings, code_anchors: [{file, lines, snippet, significance}], call_chains: [{entry, chain, files}], questions_for_user, _metadata}
|
||||
`
|
||||
})
|
||||
```
|
||||
|
||||
**Multi-Perspective Parallel Example** (up to 4 agents):
|
||||
**Step 2: CLI Analysis** (AFTER exploration)
|
||||
|
||||
- **Single**: Comprehensive CLI analysis with exploration context
|
||||
- **Multi (up to 4)**: Parallel CLI calls per perspective
|
||||
- Execution: `Bash` with `run_in_background: true`
|
||||
|
||||
```javascript
|
||||
// Launch parallel explorations for each selected perspective
|
||||
selectedPerspectives.forEach(perspective => {
|
||||
Task({
|
||||
subagent_type: "cli-explore-agent",
|
||||
run_in_background: false, // Sequential execution, wait for each
|
||||
description: `Explore ${perspective.name}: ${topicSlug}`,
|
||||
prompt: `
|
||||
## Analysis Context
|
||||
Topic: ${topic_or_question}
|
||||
Perspective: ${perspective.name} - ${perspective.focus}
|
||||
Session: ${sessionFolder}
|
||||
|
||||
## MANDATORY FIRST STEPS
|
||||
1. Run: ccw tool exec get_modules_by_depth '{}'
|
||||
2. Execute searches focused on ${perspective.focus}
|
||||
3. Read: .workflow/project-tech.json (if exists)
|
||||
|
||||
## Exploration Focus (${perspective.name} angle)
|
||||
${perspective.exploration_tasks.map(t => `- ${t}`).join('\n')}
|
||||
|
||||
## Output
|
||||
Write findings to: ${sessionFolder}/explorations/${perspective.name}.json
|
||||
|
||||
Schema: {relevant_files, patterns, key_findings, perspective_insights, _metadata}
|
||||
`
|
||||
})
|
||||
})
|
||||
```
|
||||
|
||||
2. **Multi-Perspective CLI Analysis** (⚠️ AFTER exploration)
|
||||
- If user selected multiple perspectives (≤4): Launch CLI calls in parallel
|
||||
- If single/default perspective: Launch single comprehensive CLI analysis
|
||||
- **Shared context**: Include exploration-codebase.json findings in all prompts
|
||||
- **Execution**: Bash with run_in_background: true, wait for all results
|
||||
- **Output**: perspectives.json with analysis from each perspective
|
||||
|
||||
**Single Perspective Example**:
|
||||
```javascript
|
||||
Bash({
|
||||
command: `ccw cli -p "
|
||||
PURPOSE: Analyze topic '${topic_or_question}' from ${dimensions.join(', ')} perspectives
|
||||
Success: Actionable insights with clear reasoning
|
||||
|
||||
PRIOR EXPLORATION CONTEXT:
|
||||
- Key files: ${explorationResults.relevant_files.slice(0,5).map(f => f.path).join(', ')}
|
||||
- Patterns found: ${explorationResults.patterns.slice(0,3).join(', ')}
|
||||
- Key findings: ${explorationResults.key_findings.slice(0,3).join(', ')}
|
||||
|
||||
TASK:
|
||||
• Build on exploration findings above
|
||||
• Analyze common patterns and anti-patterns
|
||||
• Highlight potential issues or opportunities
|
||||
• Generate discussion points for user clarification
|
||||
|
||||
MODE: analysis
|
||||
CONTEXT: @**/* | Topic: ${topic_or_question}
|
||||
EXPECTED: Structured analysis with clear sections, specific insights tied to evidence, questions to deepen understanding, recommendations with rationale
|
||||
CONSTRAINTS: Focus on ${dimensions.join(', ')}
|
||||
" --tool gemini --mode analysis`,
|
||||
run_in_background: true
|
||||
})
|
||||
```
|
||||
|
||||
**Multi-Perspective Example** (parallel, up to 4):
|
||||
```javascript
|
||||
// Build shared context once
|
||||
// Build shared exploration context for CLI prompts
|
||||
const explorationContext = `
|
||||
PRIOR EXPLORATION CONTEXT:
|
||||
- Key files: ${explorationResults.relevant_files.slice(0,5).map(f => f.path).join(', ')}
|
||||
- Patterns found: ${explorationResults.patterns.slice(0,3).join(', ')}
|
||||
- Key findings: ${explorationResults.key_findings.slice(0,3).join(', ')}`
|
||||
- Patterns: ${explorationResults.patterns.slice(0,3).join(', ')}
|
||||
- Findings: ${explorationResults.key_findings.slice(0,3).join(', ')}
|
||||
- Code anchors:
|
||||
${(explorationResults.code_anchors || []).slice(0,5).map(a => ` [${a.file}:${a.lines}] ${a.significance}\n \`\`\`\n ${a.snippet}\n \`\`\``).join('\n')}
|
||||
- Call chains: ${(explorationResults.call_chains || []).slice(0,3).map(c => `${c.entry} → ${c.chain.join(' → ')}`).join('; ')}`
|
||||
|
||||
// Launch parallel CLI calls based on selected perspectives (max 4)
|
||||
selectedPerspectives.forEach(perspective => {
|
||||
Bash({
|
||||
command: `ccw cli -p "
|
||||
PURPOSE: ${perspective.purpose} for '${topic_or_question}'
|
||||
Success: ${perspective.success_criteria}
|
||||
// Single perspective (for multi: loop selectedPerspectives with perspective.purpose/tasks/constraints)
|
||||
Bash({
|
||||
command: `ccw cli -p "
|
||||
PURPOSE: Analyze '${topic_or_question}' from ${dimensions.join(', ')} perspectives
|
||||
Success: Actionable insights with clear reasoning
|
||||
|
||||
${explorationContext}
|
||||
|
||||
TASK:
|
||||
${perspective.tasks.map(t => `• ${t}`).join('\n')}
|
||||
• Build on exploration findings — reference specific code anchors
|
||||
• Analyze common patterns and anti-patterns with code evidence
|
||||
• Highlight potential issues/opportunities with file:line references
|
||||
• Generate discussion points for user clarification
|
||||
|
||||
MODE: analysis
|
||||
CONTEXT: @**/* | Topic: ${topic_or_question}
|
||||
EXPECTED: ${perspective.expected_output}
|
||||
CONSTRAINTS: ${perspective.constraints}
|
||||
" --tool ${perspective.tool} --mode analysis`,
|
||||
run_in_background: true
|
||||
})
|
||||
EXPECTED: Structured analysis with sections, insights tied to evidence, questions, recommendations
|
||||
CONSTRAINTS: Focus on ${dimensions.join(', ')}
|
||||
" --tool gemini --mode analysis`,
|
||||
run_in_background: true
|
||||
})
|
||||
|
||||
// ⚠️ STOP POINT: Wait for hook callback to receive all results before continuing
|
||||
// STOP: Wait for hook callback before continuing
|
||||
// Multi-perspective: Same pattern per perspective with perspective.purpose/tasks/constraints/tool
|
||||
```
|
||||
|
||||
3. **Aggregate Findings**
|
||||
- Consolidate all codebase explorations (exploration-codebase.json or explorations/*.json) and CLI perspective findings
|
||||
- If multi-perspective: Extract synthesis from both explorations and analyses (convergent themes, conflicting views, unique contributions)
|
||||
- Extract aggregated findings, discussion points, open questions across all sources
|
||||
- Write to explorations.json (single) or perspectives.json (multi)
|
||||
**Step 3: Aggregate Findings**
|
||||
- Consolidate explorations + CLI results
|
||||
- Multi: Extract synthesis (convergent themes, conflicting views, unique contributions)
|
||||
- Write to `explorations.json` (single) or `perspectives.json` (multi)
|
||||
|
||||
4. **Update discussion.md**
|
||||
- Append Round 1 section with exploration results
|
||||
- Single perspective: Include sources analyzed, key findings, discussion points, open questions
|
||||
- Multi-perspective: Include per-perspective findings + synthesis section
|
||||
**Step 4: Update discussion.md** — Append Round 1 with sources, key findings, discussion points, open questions
|
||||
|
||||
**explorations.json Schema** (single perspective):
|
||||
- `session_id`: Session identifier
|
||||
- `timestamp`: Exploration completion time
|
||||
- `topic`: Original topic/question
|
||||
- `dimensions[]`: Analysis dimensions
|
||||
**Step 5: Initial Intent Coverage Check** (FIRST check, before entering Phase 3):
|
||||
- Re-read original "User Intent" / "Analysis Context" from discussion.md header
|
||||
- Check each intent item against Round 1 findings: ✅ addressed / 🔄 in-progress / ❌ not yet touched
|
||||
- Append initial Intent Coverage Check to discussion.md
|
||||
- Present to user at beginning of Phase 3: "初始探索完成后,以下意图的覆盖情况:[list]。接下来的讨论将重点关注未覆盖的部分。"
|
||||
- Purpose: Early course correction — catch drift before spending multiple interactive rounds
|
||||
|
||||
**explorations.json Schema** (single):
|
||||
- `session_id`, `timestamp`, `topic`, `dimensions[]`
|
||||
- `sources[]`: {type, file/summary}
|
||||
- `key_findings[]`: Main insights
|
||||
- `discussion_points[]`: Questions for user
|
||||
- `open_questions[]`: Unresolved questions
|
||||
- `key_findings[]`, `code_anchors[]`: {file, lines, snippet, significance}
|
||||
- `call_chains[]`: {entry, chain, files}
|
||||
- `discussion_points[]`, `open_questions[]`
|
||||
|
||||
**perspectives.json Schema** (multi-perspective):
|
||||
- `session_id`: Session identifier
|
||||
- `timestamp`: Exploration completion time
|
||||
- `topic`: Original topic/question
|
||||
- `dimensions[]`: Analysis dimensions
|
||||
**perspectives.json Schema** (multi — extends explorations.json):
|
||||
- `perspectives[]`: [{name, tool, findings, insights, questions}]
|
||||
- `synthesis`: {convergent_themes, conflicting_views, unique_contributions}
|
||||
- `aggregated_findings[]`: Main insights across perspectives
|
||||
- `discussion_points[]`: Questions for user
|
||||
- `open_questions[]`: Unresolved questions
|
||||
- code_anchors/call_chains include `perspective` field
|
||||
|
||||
**Success Criteria**:
|
||||
- exploration-codebase.json (single) or explorations/*.json (multi) created with codebase context
|
||||
- explorations.json (single) or perspectives.json (multi) created with findings
|
||||
- discussion.md updated with Round 1 results
|
||||
- All agents and CLI calls completed successfully
|
||||
- **📌 Key findings recorded** with evidence references and confidence levels
|
||||
- **📌 Exploration decisions recorded** (why chose certain perspectives, tool selection rationale)
|
||||
**Success**: Exploration + CLI artifacts created, discussion.md Round 1, key findings and exploration decisions recorded
|
||||
**TodoWrite**: Update `phase-2` → `"completed"`, `phase-3` → `"in_progress"`
|
||||
|
||||
### Phase 3: Interactive Discussion
|
||||
|
||||
**Objective**: Iteratively refine understanding through user-guided discussion cycles.
|
||||
**Guideline**: Delegate complex tasks to agents (cli-explore-agent) or CLI calls. Avoid direct analysis in main process.
|
||||
|
||||
**Prerequisites**:
|
||||
- Phase 2 completed successfully
|
||||
- explorations.json contains initial findings
|
||||
- discussion.md has Round 1 results
|
||||
**Loop** (max 5 rounds):
|
||||
|
||||
**Guideline**: For complex tasks (code analysis, implementation, refactoring), delegate to agents via Task tool (cli-explore-agent, code-developer, universal-executor) or CLI calls (ccw cli). Avoid direct analysis/execution in main process.
|
||||
1. **Current Understanding Summary** (Round >= 2, BEFORE presenting new findings):
|
||||
- Generate 1-2 sentence recap: "到目前为止,我们已确认 [established facts]。上一轮 [key action/direction]。现在,这是新一轮的发现:"
|
||||
- Purpose: Reset context, prevent cognitive overload, make incremental progress visible
|
||||
|
||||
**Workflow Steps**:
|
||||
2. **Present Findings** from explorations.json
|
||||
|
||||
1. **Present Findings**
|
||||
- Display current findings from explorations.json
|
||||
- Show key points for user input
|
||||
3. **Gather Feedback** (AskUserQuestion, single-select, header: "分析反馈"):
|
||||
- **继续深入**: Direction correct — deepen automatically or user specifies direction (combines agree+deepen and agree+suggest)
|
||||
- **调整方向**: Different focus or specific questions to address
|
||||
- **补充信息**: User has additional context, constraints, or corrections to provide
|
||||
- **分析完成**: Sufficient → exit to Phase 4
|
||||
|
||||
2. **Gather User Feedback** (AskUserQuestion)
|
||||
- **Question**: Feedback on current analysis
|
||||
- **Options** (single-select):
|
||||
- **同意,继续深入**: Analysis direction correct, deepen exploration
|
||||
- **需要调整方向**: Different understanding or focus
|
||||
- **分析完成**: Sufficient information obtained
|
||||
- **有具体问题**: Specific questions to ask
|
||||
4. **Process Response** (always record user choice + impact to discussion.md):
|
||||
|
||||
3. **Process User Response**
|
||||
**继续深入** → Sub-question to choose direction (AskUserQuestion, single-select, header: "深入方向"):
|
||||
- Dynamically generate **max 3** context-driven options from: unresolved questions, low-confidence findings, unexplored dimensions, user-highlighted areas
|
||||
- Add **1** heuristic option that breaks current frame (e.g., "compare with best practices", "review from security perspective", "explore simpler alternatives")
|
||||
- Total: **max 4 options**. Each specifies: label, description, tool (cli-explore-agent for code-level / Gemini CLI for pattern-level), scope
|
||||
- **"Other" is auto-provided** by AskUserQuestion — covers user-specified custom direction (no need for separate "suggest next step" option)
|
||||
- Execute selected direction → merge new code_anchors/call_chains → record confirmed assumptions + deepen angle
|
||||
|
||||
**📌 Recording Checkpoint**: Regardless of which option the user selects, the following MUST be recorded to discussion.md:
|
||||
- User's original choice and expression
|
||||
- Impact of this choice on analysis direction
|
||||
- If direction changed, record a full Decision Record
|
||||
**调整方向** → AskUserQuestion (header: "新方向", user selects or provides custom via "Other") → new CLI exploration → Record Decision (old vs new direction, reason, impact)
|
||||
|
||||
**Agree, Deepen**:
|
||||
- Continue analysis in current direction
|
||||
- Use CLI for deeper exploration
|
||||
- **📌 Record**: Which assumptions were confirmed, specific angles for deeper exploration
|
||||
**补充信息** → Capture user input, integrate into context, answer questions via CLI/analysis if needed → Record corrections/additions + updated understanding
|
||||
|
||||
**Adjust Direction**:
|
||||
- AskUserQuestion for adjusted focus (code details / architecture / best practices)
|
||||
- Launch new CLI exploration with adjusted scope
|
||||
- **📌 Record Decision**: Trigger reason for direction adjustment, old vs new direction comparison, expected impact
|
||||
**分析完成** → Exit loop → Record why concluding
|
||||
|
||||
**Specific Questions**:
|
||||
- Capture user questions
|
||||
- Use CLI or direct analysis to answer
|
||||
- Document Q&A in discussion.md
|
||||
- **📌 Record**: Knowledge gaps revealed by the question, new understanding gained from the answer
|
||||
5. **Update discussion.md**:
|
||||
- **Append** Round N: user input, direction adjustment, Q&A, corrections, new insights
|
||||
- **Replace** `## Current Understanding` block with latest consolidated understanding (follow Consolidation Rules: promote confirmed, track corrections, focus on NOW)
|
||||
- **Update** `## Table of Contents` with links to new Round N sections
|
||||
|
||||
**Complete**:
|
||||
- Exit discussion loop, proceed to Phase 4
|
||||
- **📌 Record**: Why concluding at this round (sufficient information / scope fully focused / user satisfied)
|
||||
6. **Round Narrative Synthesis** (append to discussion.md after each round update):
|
||||
```markdown
|
||||
### Round N: Narrative Synthesis
|
||||
**起点**: 基于上一轮的 [conclusions/questions],本轮从 [starting point] 切入。
|
||||
**关键进展**: [New findings] [confirmed/refuted/modified] 了之前关于 [hypothesis] 的理解。
|
||||
**决策影响**: 用户选择 [feedback type],导致分析方向 [adjusted/deepened/maintained]。
|
||||
**当前理解**: 经过本轮,核心认知更新为 [updated understanding]。
|
||||
**遗留问题**: [remaining questions driving next round]
|
||||
```
|
||||
|
||||
4. **Update discussion.md**
|
||||
- Append Round N section with:
|
||||
- User input summary
|
||||
- Direction adjustment (if any)
|
||||
- User questions & answers (if any)
|
||||
- Updated understanding
|
||||
- Corrected assumptions
|
||||
- New insights
|
||||
7. **Intent Drift Check** (every round >= 2):
|
||||
- Re-read original "User Intent" from discussion.md header
|
||||
- Check each item: addressed / in-progress / implicitly absorbed / not yet discussed
|
||||
```markdown
|
||||
#### Intent Coverage Check
|
||||
- ✅ Intent 1: [addressed in Round N]
|
||||
- 🔄 Intent 2: [in-progress]
|
||||
- ⚠️ Intent 3: [implicitly absorbed by X — needs confirmation]
|
||||
- ❌ Intent 4: [not yet discussed]
|
||||
```
|
||||
- If ❌ or ⚠️ items exist → **proactively surface** to user at start of next round: "以下原始意图尚未充分覆盖:[list]。是否需要调整优先级?"
|
||||
|
||||
5. **Repeat or Converge**
|
||||
- Continue loop (max 5 rounds) or exit to Phase 4
|
||||
|
||||
**Discussion Actions**:
|
||||
|
||||
| User Choice | Action | Tool | Description |
|
||||
|-------------|--------|------|-------------|
|
||||
| Deepen | Continue current direction | Gemini CLI | Deeper analysis in same focus |
|
||||
| Adjust | Change analysis angle | Selected CLI | New exploration with adjusted scope |
|
||||
| Questions | Answer specific questions | CLI or analysis | Address user inquiries |
|
||||
| Complete | Exit discussion loop | - | Proceed to synthesis |
|
||||
|
||||
**Success Criteria**:
|
||||
- User feedback processed for each round
|
||||
- discussion.md updated with all discussion rounds
|
||||
- Assumptions corrected and documented
|
||||
- Exit condition reached (user selects "完成" or max rounds)
|
||||
- **📌 All decision points recorded** with Decision Record format
|
||||
- **📌 Direction changes documented** with before/after comparison and rationale
|
||||
**Success**: All rounds documented with narrative synthesis, assumptions corrected, all decisions recorded with rejection reasoning, direction changes with before/after
|
||||
**TodoWrite**: Update `phase-3` → `"completed"`, `phase-4` → `"in_progress"`
|
||||
|
||||
### Phase 4: Synthesis & Conclusion
|
||||
|
||||
**Objective**: Consolidate insights, generate conclusions, offer next steps.
|
||||
1. **Intent Coverage Verification** (MANDATORY before synthesis):
|
||||
- Check each original intent: ✅ Addressed / 🔀 Transformed / ⚠️ Absorbed / ❌ Missed
|
||||
```markdown
|
||||
### Intent Coverage Matrix
|
||||
| # | Original Intent | Status | Where Addressed | Notes |
|
||||
|---|----------------|--------|-----------------|-------|
|
||||
| 1 | [intent] | ✅ Addressed | Round N, Conclusion #M | |
|
||||
| 2 | [intent] | 🔀 Transformed | Round N → M | Original: X → Final: Y |
|
||||
| 3 | [intent] | ❌ Missed | — | Reason |
|
||||
```
|
||||
- **Gate**: ❌ Missed items must be either (a) addressed in additional round or (b) confirmed deferred by user
|
||||
- Add `intent_coverage[]` to conclusions.json
|
||||
|
||||
**Prerequisites**:
|
||||
- Phase 3 completed successfully
|
||||
- Multiple rounds of discussion documented
|
||||
- User ready to conclude
|
||||
|
||||
**Workflow Steps**:
|
||||
|
||||
1. **Consolidate Insights**
|
||||
- Extract all findings from discussion timeline
|
||||
- **📌 Compile Decision Trail**: Aggregate all Decision Records from Phases 1-3 into a consolidated decision log
|
||||
- **Key conclusions**: Main points with evidence and confidence levels (high/medium/low)
|
||||
- **Recommendations**: Action items with rationale and priority (high/medium/low)
|
||||
- **Open questions**: Remaining unresolved questions
|
||||
- **Follow-up suggestions**: Issue/task creation suggestions
|
||||
- **📌 Decision summary**: How key decisions shaped the final conclusions (link conclusions back to decisions)
|
||||
2. **Consolidate Insights**:
|
||||
- Compile Decision Trail from all phases
|
||||
- Key conclusions with evidence + confidence (high/medium/low)
|
||||
- Recommendations with rationale + priority (high/medium/low)
|
||||
- Open questions, follow-up suggestions
|
||||
- Decision summary linking conclusions back to decisions
|
||||
- Write to conclusions.json
|
||||
|
||||
2. **Final discussion.md Update**
|
||||
- Append conclusions section:
|
||||
- **Summary**: High-level overview
|
||||
- **Key Conclusions**: Ranked with evidence and confidence
|
||||
- **Recommendations**: Prioritized action items
|
||||
- **Remaining Questions**: Unresolved items
|
||||
- Update "Current Understanding (Final)":
|
||||
- **What We Established**: Confirmed points
|
||||
- **What Was Clarified/Corrected**: Important corrections
|
||||
- **Key Insights**: Valuable learnings
|
||||
- **📌 Add "Decision Trail" section**:
|
||||
- **Critical Decisions**: List of pivotal decisions that shaped the analysis outcome
|
||||
- **Direction Changes**: Timeline of scope/focus adjustments with rationale
|
||||
- **Trade-offs Made**: Key trade-offs and why certain paths were chosen over others
|
||||
- Add session statistics: rounds, duration, sources, artifacts, **decision count**
|
||||
3. **Final discussion.md Update**:
|
||||
- **Conclusions**: Summary, ranked key conclusions, prioritized recommendations, remaining questions
|
||||
- **Current Understanding (Final)**: What established, what clarified/corrected, key insights
|
||||
- **Decision Trail**: Critical decisions, direction changes timeline, trade-offs
|
||||
- Session statistics: rounds, duration, sources, artifacts, decision count
|
||||
|
||||
3. **Post-Completion Options** (AskUserQuestion)
|
||||
- **创建Issue**: Launch issue-discover with conclusions
|
||||
- **生成任务**: Launch workflow-lite-plan for implementation
|
||||
- **导出报告**: Generate standalone analysis report
|
||||
- **完成**: No further action
|
||||
4. **Display Conclusions Summary** — Present to user:
|
||||
- **Analysis Report**: summary, key conclusions (numbered, with confidence), recommendations (numbered, with priority + rationale + steps)
|
||||
- Open questions if any
|
||||
- Link to full report: `{sessionFolder}/discussion.md`
|
||||
|
||||
5. **Interactive Recommendation Review** (skip in auto mode):
|
||||
|
||||
Walk through each recommendation one-by-one for user confirmation:
|
||||
|
||||
```
|
||||
For each recommendation (ordered by priority high→medium→low):
|
||||
1. Present: action, rationale, priority, steps[] (numbered sub-steps)
|
||||
2. AskUserQuestion (single-select, header: "建议#N"):
|
||||
- **确认** (label: "确认", desc: "Accept as-is") → review_status = "accepted"
|
||||
- **修改** (label: "修改", desc: "Adjust scope/steps") → record modification → review_status = "modified"
|
||||
- **删除** (label: "删除", desc: "Not needed") → record reason → review_status = "rejected"
|
||||
- **跳过审议** (label: "跳过审议", desc: "Accept all remaining") → break loop
|
||||
3. Record review decision to discussion.md Decision Log
|
||||
4. Update conclusions.json recommendation.review_status
|
||||
```
|
||||
|
||||
**After review loop**: Display summary of reviewed recommendations:
|
||||
- Accepted: N items | Modified: N items | Rejected: N items
|
||||
- Only accepted/modified recommendations proceed to next step
|
||||
|
||||
6. **MANDATORY GATE: Next Step Selection** — workflow MUST NOT end without executing this step.
|
||||
|
||||
**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 conclusions (step 4) and recommendation review (step 5), you MUST immediately proceed here.
|
||||
|
||||
Call AskUserQuestion (single-select, header: "Next Step"):
|
||||
- **执行任务** (Recommended if high/medium priority recs exist): "基于分析结论启动 workflow-lite-plan 制定执行计划"
|
||||
- **产出Issue**: "将建议转化为 issue 进行跟踪管理"
|
||||
- **完成**: "分析已足够,无需进一步操作"
|
||||
|
||||
**Handle user selection**:
|
||||
|
||||
**"执行任务"** → MUST invoke Skill tool (do NOT just display a summary and stop):
|
||||
1. Build `taskDescription` from high/medium priority recommendations (fallback: summary)
|
||||
2. Assemble context: `## Prior Analysis ({sessionId})` + summary + key files (up to 8) + key findings (up to 5) from exploration-codebase.json
|
||||
3. **Invoke Skill tool immediately**:
|
||||
```javascript
|
||||
Skill({ skill: "workflow-lite-plan", args: `${taskDescription}\n\n${contextLines}` })
|
||||
```
|
||||
If Skill invocation is omitted, the workflow is BROKEN.
|
||||
4. After Skill invocation, analyze-with-file is complete — do not output any additional content
|
||||
|
||||
**"产出Issue"** → Convert recommendations to issues:
|
||||
1. For each recommendation in conclusions.recommendations (priority high/medium):
|
||||
- Build issue JSON: `{title, context: rec.action + rec.rationale, priority: rec.priority == 'high' ? 2 : 3, source: 'discovery', labels: dimensions}`
|
||||
- Create via pipe: `echo '<issue-json>' | ccw issue create`
|
||||
2. Display created issue IDs with next step hint: `/issue:plan <id>`
|
||||
|
||||
**"完成"** → No further action needed.
|
||||
|
||||
**TodoWrite**: Update `next-step` → `"completed"` after user selection is handled
|
||||
|
||||
**conclusions.json Schema**:
|
||||
- `session_id`: Session identifier
|
||||
- `topic`: Original topic/question
|
||||
- `completed`: Completion timestamp
|
||||
- `total_rounds`: Number of discussion rounds
|
||||
- `summary`: Executive summary
|
||||
- `key_conclusions[]`: {point, evidence, confidence}
|
||||
- `recommendations[]`: {action, rationale, priority}
|
||||
- `open_questions[]`: Unresolved questions
|
||||
- `follow_up_suggestions[]`: {type, summary}
|
||||
- `decision_trail[]`: {round, decision, context, options_considered, chosen, reason, impact}
|
||||
- `session_id`, `topic`, `completed`, `total_rounds`, `summary`
|
||||
- `key_conclusions[]`: {point, evidence, confidence, code_anchor_refs[]}
|
||||
- `code_anchors[]`: {file, lines, snippet, significance}
|
||||
- `recommendations[]`: {action, rationale, priority, steps[]: {description, target, verification}, review_status: accepted|modified|rejected|pending}
|
||||
- `open_questions[]`, `follow_up_suggestions[]`: {type, summary}
|
||||
- `decision_trail[]`: {round, decision, context, options_considered, chosen, rejected_reasons, reason, impact}
|
||||
- `narrative_trail[]`: {round, starting_point, key_progress, hypothesis_impact, updated_understanding, remaining_questions}
|
||||
- `intent_coverage[]`: {intent, status, where_addressed, notes}
|
||||
|
||||
**Success Criteria**:
|
||||
- conclusions.json created with final synthesis
|
||||
- discussion.md finalized with conclusions and decision trail
|
||||
- User offered next step options
|
||||
- Session complete
|
||||
- **📌 Complete decision trail** documented and traceable from initial scoping to final conclusions
|
||||
**Success**: conclusions.json created, discussion.md finalized, Intent Coverage Matrix verified, complete decision trail documented, `next-step` gate completed
|
||||
|
||||
## Configuration
|
||||
|
||||
### Analysis Perspectives
|
||||
|
||||
Optional multi-perspective parallel exploration (single perspective is default, max 4):
|
||||
|
||||
| Perspective | Tool | Focus | Best For |
|
||||
|------------|------|-------|----------|
|
||||
| **Technical** | Gemini | Implementation, code patterns, technical feasibility | Understanding how and technical details |
|
||||
| **Architectural** | Claude | System design, scalability, component interactions | Understanding structure and organization |
|
||||
| **Business** | Codex | Value, ROI, stakeholder impact, strategy | Understanding business implications |
|
||||
| **Domain Expert** | Gemini | Domain-specific patterns, best practices, standards | Industry-specific knowledge and practices |
|
||||
| **Technical** | Gemini | Implementation, code patterns, feasibility | How + technical details |
|
||||
| **Architectural** | Claude | System design, scalability, interactions | Structure + organization |
|
||||
| **Business** | Codex | Value, ROI, stakeholder impact | Business implications |
|
||||
| **Domain Expert** | Gemini | Domain patterns, best practices, standards | Industry knowledge |
|
||||
|
||||
**Selection**: User can multi-select up to 4 perspectives in Phase 1, or default to single comprehensive view
|
||||
User multi-selects up to 4 in Phase 1, default: single comprehensive view.
|
||||
|
||||
### Dimension-Direction Mapping
|
||||
|
||||
When user selects focus areas, generate directions dynamically from detected dimensions (don't use static options):
|
||||
|
||||
| Dimension | Possible Directions |
|
||||
|-----------|-------------------|
|
||||
| architecture | System Design, Component Interactions, Technology Choices, Integration Points, Design Patterns, Scalability Strategy |
|
||||
| implementation | Code Structure, Implementation Details, Code Patterns, Error Handling, Testing Approach, Algorithm Analysis |
|
||||
| performance | Performance Bottlenecks, Optimization Opportunities, Resource Utilization, Caching Strategy, Concurrency Issues |
|
||||
| security | Security Vulnerabilities, Authentication/Authorization, Access Control, Data Protection, Input Validation |
|
||||
| concept | Conceptual Foundation, Core Mechanisms, Fundamental Patterns, Theory & Principles, Trade-offs & Reasoning |
|
||||
| comparison | Solution Comparison, Pros & Cons Analysis, Technology Evaluation, Approach Differences |
|
||||
| decision | Decision Criteria, Trade-off Analysis, Risk Assessment, Impact Analysis, Implementation Implications |
|
||||
| architecture | System Design, Component Interactions, Technology Choices, Integration Points, Design Patterns, Scalability |
|
||||
| implementation | Code Structure, Details, Patterns, Error Handling, Testing, Algorithm Analysis |
|
||||
| performance | Bottlenecks, Optimization, Resource Utilization, Caching, Concurrency |
|
||||
| security | Vulnerabilities, Auth, Access Control, Data Protection, Input Validation |
|
||||
| concept | Foundation, Core Mechanisms, Patterns, Theory, Trade-offs |
|
||||
| comparison | Solution Comparison, Pros/Cons, Technology Evaluation, Approach Differences |
|
||||
| decision | Criteria, Trade-off Analysis, Risk Assessment, Impact, Implementation Implications |
|
||||
|
||||
**Implementation**: Present 2-3 top dimension-related directions, allow user to multi-select and add custom directions.
|
||||
Present 2-3 top directions per dimension, allow multi-select + custom.
|
||||
|
||||
### Analysis Dimensions
|
||||
|
||||
Dimensions matched against topic keywords to identify focus areas:
|
||||
|
||||
| Dimension | Keywords |
|
||||
|-----------|----------|
|
||||
| architecture | 架构, architecture, design, structure, 设计 |
|
||||
@@ -580,8 +436,6 @@ Dimensions matched against topic keywords to identify focus areas:
|
||||
|
||||
### Consolidation Rules
|
||||
|
||||
When updating "Current Understanding":
|
||||
|
||||
| Rule | Description |
|
||||
|------|-------------|
|
||||
| Promote confirmed insights | Move validated findings to "What We Established" |
|
||||
@@ -590,106 +444,19 @@ When updating "Current Understanding":
|
||||
| Avoid timeline repetition | Don't copy discussion details |
|
||||
| Preserve key learnings | Keep insights valuable for future reference |
|
||||
|
||||
**Example**:
|
||||
|
||||
❌ **Bad (cluttered)**:
|
||||
```markdown
|
||||
## Current Understanding
|
||||
In round 1 we discussed X, then in round 2 user said Y...
|
||||
```
|
||||
|
||||
✅ **Good (consolidated)**:
|
||||
```markdown
|
||||
## Current Understanding
|
||||
|
||||
### What We Established
|
||||
- The authentication flow uses JWT with refresh tokens
|
||||
- Rate limiting is implemented at API gateway level
|
||||
|
||||
### What Was Clarified
|
||||
- ~~Assumed Redis for sessions~~ → Actually uses database-backed sessions
|
||||
|
||||
### Key Insights
|
||||
- Current architecture supports horizontal scaling
|
||||
```
|
||||
|
||||
## Error Handling
|
||||
|
||||
| Error | Resolution |
|
||||
|-------|------------|
|
||||
| cli-explore-agent fails | Continue with available context, note limitation |
|
||||
| CLI timeout | Retry with shorter prompt, or skip perspective |
|
||||
| User timeout in discussion | Save state, show resume command |
|
||||
| Max rounds reached | Force synthesis, offer continuation option |
|
||||
| User timeout | Save state, show resume command |
|
||||
| Max rounds reached | Force synthesis, offer continuation |
|
||||
| No relevant findings | Broaden search, ask user for clarification |
|
||||
| Session folder conflict | Append timestamp suffix |
|
||||
| Gemini unavailable | Fallback to Codex or manual analysis |
|
||||
|
||||
## Best Practices
|
||||
|
||||
1. **Clear Topic Definition**: Detailed topics lead to better dimension identification
|
||||
2. **Agent-First for Complex Tasks**: For code analysis, implementation, or refactoring tasks during discussion, delegate to agents via Task tool (cli-explore-agent, code-developer, universal-executor) or CLI calls (ccw cli). Avoid direct analysis/execution in main process
|
||||
3. **Review discussion.md**: Check understanding evolution before conclusions
|
||||
4. **Embrace Corrections**: Track wrong-to-right transformations as learnings
|
||||
5. **Document Evolution**: discussion.md captures full thinking process
|
||||
6. **Use Continue Mode**: Resume sessions to build on previous analysis
|
||||
7. **Record Decisions Immediately**: Never defer recording - capture decisions as they happen using the Decision Record format. A decision not recorded in-the-moment is a decision lost
|
||||
8. **Link Decisions to Outcomes**: When writing conclusions, explicitly reference which decisions led to which outcomes. This creates an auditable trail from initial scoping to final recommendations
|
||||
|
||||
## Templates
|
||||
|
||||
### Discussion Document Structure
|
||||
|
||||
**discussion.md** contains:
|
||||
- **Header**: Session metadata (ID, topic, started, dimensions)
|
||||
- **User Context**: Focus areas, analysis depth
|
||||
- **Discussion Timeline**: Round-by-round findings
|
||||
- Round 1: Initial Understanding + Exploration Results + **Initial Decision Log**
|
||||
- Round 2-N: User feedback, adjusted understanding, corrections, new insights, **Decision Log per round**
|
||||
- **Decision Trail**: Consolidated critical decisions across all rounds
|
||||
- **Conclusions**: Summary, key conclusions, recommendations
|
||||
- **Current Understanding (Final)**: Consolidated insights
|
||||
- **Session Statistics**: Rounds, duration, sources, artifacts, decision count
|
||||
|
||||
Example sections:
|
||||
|
||||
```markdown
|
||||
### Round 2 - Discussion (timestamp)
|
||||
|
||||
#### User Input
|
||||
User agrees with current direction, wants deeper code analysis
|
||||
|
||||
#### Decision Log
|
||||
> **Decision**: Shift focus from high-level architecture to implementation-level code analysis
|
||||
> - **Context**: User confirmed architectural understanding is sufficient
|
||||
> - **Options considered**: Continue architecture analysis / Deep-dive into code patterns / Focus on testing gaps
|
||||
> - **Chosen**: Deep-dive into code patterns — **Reason**: User explicitly requested code-level analysis
|
||||
> - **Impact**: Subsequent exploration will target specific modules rather than system overview
|
||||
|
||||
#### Updated Understanding
|
||||
- Identified session management uses database-backed approach
|
||||
- Rate limiting applied at gateway, not application level
|
||||
|
||||
#### Corrected Assumptions
|
||||
- ~~Assumed Redis for sessions~~ → Database-backed sessions
|
||||
- Reason: User clarified architecture decision
|
||||
|
||||
#### New Insights
|
||||
- Current design allows horizontal scaling without session affinity
|
||||
```
|
||||
|
||||
## Usage Recommendations(Requires User Confirmation)
|
||||
|
||||
**When to Execute Directly :**
|
||||
- Short, focused analysis tasks (single module/component)
|
||||
- Clear, well-defined topics with limited scope
|
||||
- Quick information gathering without multi-round iteration
|
||||
- Follow-up analysis building on existing session
|
||||
|
||||
**Use `Skill(skill="workflow-lite-plan", args="\"task description\"")` when:**
|
||||
- Ready to implement (past analysis phase)
|
||||
- Need simple task breakdown
|
||||
- Focus on quick execution planning
|
||||
> **Lite-plan handoff**: Phase 4「执行任务」assembles analysis context as inline `## Prior Analysis` block, allowing lite-plan to skip redundant exploration.
|
||||
|
||||
---
|
||||
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
name: brainstorm-with-file
|
||||
description: Interactive brainstorming with multi-CLI collaboration, idea expansion, and documented thought evolution
|
||||
argument-hint: "[-y|--yes] [-c|--continue] [-m|--mode creative|structured] \"idea or topic\""
|
||||
allowed-tools: TodoWrite(*), Task(*), AskUserQuestion(*), Read(*), Grep(*), Glob(*), Bash(*), Edit(*), Write(*)
|
||||
allowed-tools: TodoWrite(*), Agent(*), AskUserQuestion(*), Read(*), Grep(*), Glob(*), Bash(*), Edit(*), Write(*)
|
||||
---
|
||||
|
||||
## Auto Mode
|
||||
@@ -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,47 +164,16 @@ 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
|
||||
Task({
|
||||
Agent({
|
||||
subagent_type: "cli-explore-agent",
|
||||
run_in_background: false,
|
||||
description: `Explore codebase for brainstorm: ${topicSlug}`,
|
||||
@@ -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 Task 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 Task 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-plan", 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
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
name: clean
|
||||
description: Intelligent code cleanup with mainline detection, stale artifact discovery, and safe execution
|
||||
argument-hint: "[-y|--yes] [--dry-run] [\"focus area\"]"
|
||||
allowed-tools: TodoWrite(*), Task(*), AskUserQuestion(*), Read(*), Glob(*), Bash(*), Write(*)
|
||||
allowed-tools: TodoWrite(*), Agent(*), AskUserQuestion(*), Read(*), Glob(*), Bash(*), Write(*)
|
||||
---
|
||||
|
||||
# Clean Command (/workflow:clean)
|
||||
@@ -475,21 +475,43 @@ if (selectedCategories.includes('Sessions')) {
|
||||
}
|
||||
}
|
||||
|
||||
// Update project-tech.json if features referenced deleted sessions
|
||||
// Update project-tech.json: remove development_index entries referencing deleted sessions
|
||||
const projectPath = '.workflow/project-tech.json'
|
||||
if (fileExists(projectPath)) {
|
||||
const project = JSON.parse(Read(projectPath))
|
||||
const deletedPaths = new Set(results.deleted)
|
||||
const deletedSessionIds = results.deleted
|
||||
.filter(p => p.match(/WFS-|lite-plan/))
|
||||
.map(p => p.split('/').pop())
|
||||
|
||||
project.features = project.features.filter(f =>
|
||||
!deletedPaths.has(f.traceability?.archive_path)
|
||||
)
|
||||
|
||||
project.statistics.total_features = project.features.length
|
||||
project.statistics.last_updated = getUtc8ISOString()
|
||||
if (project.development_index) {
|
||||
for (const category of Object.keys(project.development_index)) {
|
||||
project.development_index[category] = project.development_index[category].filter(entry =>
|
||||
!deletedSessionIds.includes(entry.session_id)
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
project._metadata.last_updated = getUtc8ISOString()
|
||||
Write(projectPath, JSON.stringify(project, null, 2))
|
||||
}
|
||||
|
||||
// Update specs/*.md: remove learnings referencing deleted sessions
|
||||
const guidelinesPath = '.ccw/specs/*.md'
|
||||
if (fileExists(guidelinesPath)) {
|
||||
const guidelines = JSON.parse(Read(guidelinesPath))
|
||||
const deletedSessionIds = results.deleted
|
||||
.filter(p => p.match(/WFS-|lite-plan/))
|
||||
.map(p => p.split('/').pop())
|
||||
|
||||
if (guidelines.learnings) {
|
||||
guidelines.learnings = guidelines.learnings.filter(l =>
|
||||
!deletedSessionIds.includes(l.session_id)
|
||||
)
|
||||
}
|
||||
|
||||
guidelines._metadata.updated_at = getUtc8ISOString()
|
||||
Write(guidelinesPath, JSON.stringify(guidelines, null, 2))
|
||||
}
|
||||
```
|
||||
|
||||
**Step 4.4: Report Results**
|
||||
@@ -541,8 +563,10 @@ Cleanup manifest archived to: ${sessionFolder}/cleanup-manifest.json
|
||||
| Manifest parse error | Regenerate from filesystem scan |
|
||||
| Empty discovery | Report "codebase is clean" |
|
||||
|
||||
|
||||
## Related Commands
|
||||
|
||||
- `/workflow:session:sync` - Sync session work to specs/*.md + project-tech (正向写入)
|
||||
- `/workflow:session:complete` - Properly archive active sessions
|
||||
- `memory-capture` skill - Save session memory before cleanup
|
||||
- `workflow-execute` skill - View current workflow state
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
name: workflow:collaborative-plan-with-file
|
||||
description: Collaborative planning with Plan Note - Understanding agent creates shared plan-note.md template, parallel agents fill pre-allocated sections, conflict detection without merge. Outputs executable plan-note.md.
|
||||
argument-hint: "[-y|--yes] <task description> [--max-agents=5]"
|
||||
allowed-tools: TodoWrite(*), Task(*), AskUserQuestion(*), Read(*), Bash(*), Write(*), Glob(*), Grep(*), mcp__ace-tool__search_context(*)
|
||||
allowed-tools: TodoWrite(*), Agent(*), AskUserQuestion(*), Read(*), Bash(*), Write(*), Glob(*), Grep(*), mcp__ace-tool__search_context(*)
|
||||
---
|
||||
|
||||
## Auto Mode
|
||||
@@ -205,6 +205,11 @@ Task(
|
||||
1. **Prioritize Latest Documentation**: Search for and reference latest README, design docs, architecture guides when available
|
||||
2. **Handle Ambiguities**: When requirement ambiguities exist, ask user for clarification (use AskUserQuestion) instead of assuming interpretations
|
||||
|
||||
### Project Context (MANDATORY)
|
||||
Read and incorporate:
|
||||
- \`.workflow/project-tech.json\` (if exists): Technology stack, architecture
|
||||
- \`.ccw/specs/*.md\` (if exists): Constraints, conventions -- apply as HARD CONSTRAINTS on sub-domain splitting and plan structure
|
||||
|
||||
### Input Requirements
|
||||
${taskDescription}
|
||||
|
||||
@@ -349,21 +354,19 @@ subDomains.map(sub =>
|
||||
**TASK ID Range**: ${sub.task_id_range[0]}-${sub.task_id_range[1]}
|
||||
**Session**: ${sessionId}
|
||||
|
||||
### Project Context (MANDATORY)
|
||||
Read and incorporate:
|
||||
- \`.workflow/project-tech.json\` (if exists): Technology stack, architecture
|
||||
- \`.ccw/specs/*.md\` (if exists): Constraints, conventions -- apply as HARD CONSTRAINTS
|
||||
|
||||
## Dual Output Tasks
|
||||
|
||||
### Task 1: Generate Two-Layer Plan Output
|
||||
Output: ${sessionFolder}/agents/${sub.focus_area}/plan.json (overview with task_ids[])
|
||||
Output: ${sessionFolder}/agents/${sub.focus_area}/.task/TASK-*.json (independent task files)
|
||||
Output: ${sessionFolder}/agents/${sub.focus_area}/plan.json
|
||||
Output: ${sessionFolder}/agents/${sub.focus_area}/.task/TASK-*.json
|
||||
Schema (plan): ~/.ccw/workflows/cli-templates/schemas/plan-overview-base-schema.json
|
||||
Schema (tasks): ~/.ccw/workflows/cli-templates/schemas/task-schema.json
|
||||
|
||||
**Two-Layer Output Format**:
|
||||
- plan.json: Overview with task_ids[] referencing .task/ files (NO tasks[] array)
|
||||
- .task/TASK-*.json: Independent task files following task-schema.json
|
||||
- plan.json required: summary, approach, task_ids, task_count, _metadata (with plan_type)
|
||||
- Task files required: id, title, description, depends_on, convergence (with criteria[])
|
||||
- Task fields: files[].change (not modification_points), convergence.criteria (not acceptance), test (not verification)
|
||||
|
||||
### Task 2: Sync Summary to plan-note.md
|
||||
|
||||
**Locate Your Sections**:
|
||||
@@ -584,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**:
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
name: debug-with-file
|
||||
description: Interactive hypothesis-driven debugging with documented exploration, understanding evolution, and Gemini-assisted correction
|
||||
argument-hint: "[-y|--yes] \"bug description or error message\""
|
||||
allowed-tools: TodoWrite(*), Task(*), AskUserQuestion(*), Read(*), Grep(*), Glob(*), Bash(*), Edit(*), Write(*)
|
||||
allowed-tools: TodoWrite(*), Agent(*), AskUserQuestion(*), Read(*), Grep(*), Glob(*), Bash(*), Edit(*), Write(*)
|
||||
---
|
||||
|
||||
## Auto Mode
|
||||
@@ -630,6 +630,16 @@ Why is config value None during update?
|
||||
|
||||
## Post-Completion Expansion
|
||||
|
||||
**Auto-sync**: 执行 `/workflow:session:sync -y "{summary}"` 更新 specs/*.md + project-tech。
|
||||
|
||||
```javascript
|
||||
// Auto mode: skip expansion question, complete session directly
|
||||
if (autoYes) {
|
||||
console.log('Debug session complete. Auto mode: skipping expansion.');
|
||||
return;
|
||||
}
|
||||
```
|
||||
|
||||
完成后询问用户是否扩展为issue(test/enhance/refactor/doc),选中项调用 `/issue:new "{summary} - {dimension}"`
|
||||
|
||||
---
|
||||
|
||||
@@ -1,408 +0,0 @@
|
||||
---
|
||||
name: init-guidelines
|
||||
description: Interactive wizard to fill project-guidelines.json based on project analysis
|
||||
argument-hint: "[--reset]"
|
||||
examples:
|
||||
- /workflow:init-guidelines
|
||||
- /workflow:init-guidelines --reset
|
||||
---
|
||||
|
||||
# Workflow Init Guidelines Command (/workflow:init-guidelines)
|
||||
|
||||
## Overview
|
||||
|
||||
Interactive multi-round wizard that analyzes the current project (via `project-tech.json`) and asks targeted questions to populate `.workflow/project-guidelines.json` with coding conventions, constraints, and quality rules.
|
||||
|
||||
**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.
|
||||
|
||||
## Usage
|
||||
```bash
|
||||
/workflow:init-guidelines # Fill guidelines interactively (skip if already populated)
|
||||
/workflow:init-guidelines --reset # Reset and re-fill guidelines from scratch
|
||||
```
|
||||
|
||||
## Execution Process
|
||||
|
||||
```
|
||||
Input Parsing:
|
||||
└─ Parse --reset flag → reset = true | false
|
||||
|
||||
Step 1: Check Prerequisites
|
||||
├─ project-tech.json must exist (run /workflow:init first)
|
||||
├─ project-guidelines.json: check if populated or scaffold-only
|
||||
└─ If populated + no --reset → Ask: "Guidelines already exist. Overwrite or append?"
|
||||
|
||||
Step 2: Load Project Context
|
||||
└─ Read project-tech.json → extract tech stack, architecture, patterns
|
||||
|
||||
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 project-guidelines.json
|
||||
|
||||
Step 5: Display Summary
|
||||
```
|
||||
|
||||
## Implementation
|
||||
|
||||
### Step 1: Check Prerequisites
|
||||
|
||||
```bash
|
||||
bash(test -f .workflow/project-tech.json && echo "TECH_EXISTS" || echo "TECH_NOT_FOUND")
|
||||
bash(test -f .workflow/project-guidelines.json && echo "GUIDELINES_EXISTS" || echo "GUIDELINES_NOT_FOUND")
|
||||
```
|
||||
|
||||
**If TECH_NOT_FOUND**: Exit with message
|
||||
```
|
||||
Project tech analysis not found. Run /workflow:init first.
|
||||
```
|
||||
|
||||
**Parse --reset flag**:
|
||||
```javascript
|
||||
const reset = $ARGUMENTS.includes('--reset')
|
||||
```
|
||||
|
||||
**If GUIDELINES_EXISTS and not --reset**: Check if guidelines are populated (not just scaffold)
|
||||
|
||||
```javascript
|
||||
const guidelines = JSON.parse(Read('.workflow/project-guidelines.json'))
|
||||
const isPopulated =
|
||||
guidelines.conventions.coding_style.length > 0 ||
|
||||
guidelines.conventions.naming_patterns.length > 0 ||
|
||||
guidelines.constraints.architecture.length > 0 ||
|
||||
guidelines.constraints.tech_stack.length > 0
|
||||
|
||||
if (isPopulated) {
|
||||
AskUserQuestion({
|
||||
questions: [{
|
||||
question: "Project guidelines already contain entries. How would you like to proceed?",
|
||||
header: "Mode",
|
||||
multiSelect: false,
|
||||
options: [
|
||||
{ label: "Append", description: "Keep existing entries and add new ones from the wizard" },
|
||||
{ label: "Reset", description: "Clear all existing entries and start fresh" },
|
||||
{ label: "Cancel", description: "Exit without changes" }
|
||||
]
|
||||
}]
|
||||
})
|
||||
// If Cancel → exit
|
||||
// If Reset → clear all arrays before proceeding
|
||||
// If Append → keep existing, wizard adds to them
|
||||
}
|
||||
```
|
||||
|
||||
### Step 2: Load Project Context
|
||||
|
||||
```javascript
|
||||
const projectTech = JSON.parse(Read('.workflow/project-tech.json'))
|
||||
|
||||
// Extract key info for generating smart questions
|
||||
const languages = projectTech.technology_analysis?.technology_stack?.languages
|
||||
|| projectTech.overview?.technology_stack?.languages || []
|
||||
const primaryLang = languages.find(l => l.primary)?.name || languages[0]?.name || 'Unknown'
|
||||
const frameworks = projectTech.technology_analysis?.technology_stack?.frameworks
|
||||
|| projectTech.overview?.technology_stack?.frameworks || []
|
||||
const testFrameworks = projectTech.technology_analysis?.technology_stack?.test_frameworks
|
||||
|| projectTech.overview?.technology_stack?.test_frameworks || []
|
||||
const archStyle = projectTech.technology_analysis?.architecture?.style
|
||||
|| projectTech.overview?.architecture?.style || 'Unknown'
|
||||
const archPatterns = projectTech.technology_analysis?.architecture?.patterns
|
||||
|| projectTech.overview?.architecture?.patterns || []
|
||||
const buildTools = projectTech.technology_analysis?.technology_stack?.build_tools
|
||||
|| projectTech.overview?.technology_stack?.build_tools || []
|
||||
```
|
||||
|
||||
### Step 3: Multi-Round Interactive 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.
|
||||
|
||||
---
|
||||
|
||||
#### Round 1: Coding Conventions
|
||||
|
||||
Generate options dynamically based on detected language/framework:
|
||||
|
||||
```javascript
|
||||
// Build language-specific coding style options
|
||||
const codingStyleOptions = []
|
||||
|
||||
if (['TypeScript', 'JavaScript'].includes(primaryLang)) {
|
||||
codingStyleOptions.push(
|
||||
{ label: "Strict TypeScript", description: "Use strict mode, no 'any' type, explicit return types for public APIs" },
|
||||
{ label: "Functional style", description: "Prefer pure functions, immutability, avoid class-based patterns where possible" },
|
||||
{ label: "Const over let", description: "Always use const; only use let when reassignment is truly needed" }
|
||||
)
|
||||
} else if (primaryLang === 'Python') {
|
||||
codingStyleOptions.push(
|
||||
{ label: "Type hints", description: "Use type hints for all function signatures and class attributes" },
|
||||
{ label: "Functional style", description: "Prefer pure functions, list comprehensions, avoid mutable state" },
|
||||
{ label: "PEP 8 strict", description: "Strict PEP 8 compliance with max line length 88 (Black formatter)" }
|
||||
)
|
||||
} else if (primaryLang === 'Go') {
|
||||
codingStyleOptions.push(
|
||||
{ label: "Error wrapping", description: "Always wrap errors with context using fmt.Errorf with %w" },
|
||||
{ label: "Interface first", description: "Define interfaces at the consumer side, not the provider" },
|
||||
{ label: "Table-driven tests", description: "Use table-driven test pattern for all unit tests" }
|
||||
)
|
||||
}
|
||||
// Add universal options
|
||||
codingStyleOptions.push(
|
||||
{ label: "Early returns", description: "Prefer early returns / guard clauses over deep nesting" }
|
||||
)
|
||||
|
||||
AskUserQuestion({
|
||||
questions: [
|
||||
{
|
||||
question: `Your project uses ${primaryLang}. Which coding style conventions do you follow?`,
|
||||
header: "Coding Style",
|
||||
multiSelect: true,
|
||||
options: codingStyleOptions.slice(0, 4) // Max 4 options
|
||||
},
|
||||
{
|
||||
question: `What naming conventions does your ${primaryLang} project use?`,
|
||||
header: "Naming",
|
||||
multiSelect: true,
|
||||
options: [
|
||||
{ label: "camelCase variables", description: "Variables and functions use camelCase (e.g., getUserName)" },
|
||||
{ label: "PascalCase types", description: "Classes, interfaces, type aliases use PascalCase (e.g., UserService)" },
|
||||
{ label: "UPPER_SNAKE constants", description: "Constants use UPPER_SNAKE_CASE (e.g., MAX_RETRIES)" },
|
||||
{ label: "Prefix interfaces", description: "Prefix interfaces with 'I' (e.g., IUserService)" }
|
||||
]
|
||||
}
|
||||
]
|
||||
})
|
||||
```
|
||||
|
||||
**Process Round 1 answers** → add to `conventions.coding_style` and `conventions.naming_patterns` arrays.
|
||||
|
||||
---
|
||||
|
||||
#### Round 2: File Structure & Documentation
|
||||
|
||||
```javascript
|
||||
AskUserQuestion({
|
||||
questions: [
|
||||
{
|
||||
question: `Your project has a ${archStyle} architecture. What file organization rules apply?`,
|
||||
header: "File Structure",
|
||||
multiSelect: true,
|
||||
options: [
|
||||
{ label: "Co-located tests", description: "Test files live next to source files (e.g., foo.ts + foo.test.ts)" },
|
||||
{ label: "Separate test dir", description: "Tests in a dedicated __tests__ or tests/ directory" },
|
||||
{ label: "One export per file", description: "Each file exports a single main component/class/function" },
|
||||
{ label: "Index barrels", description: "Use index.ts barrel files for clean imports from directories" }
|
||||
]
|
||||
},
|
||||
{
|
||||
question: "What documentation standards does your project follow?",
|
||||
header: "Documentation",
|
||||
multiSelect: true,
|
||||
options: [
|
||||
{ label: "JSDoc/docstring public APIs", description: "All public functions and classes must have JSDoc/docstrings" },
|
||||
{ label: "README per module", description: "Each major module/package has its own README" },
|
||||
{ label: "Inline comments for why", description: "Comments explain 'why', not 'what' — code should be self-documenting" },
|
||||
{ label: "No comment requirement", description: "Code should be self-explanatory; comments only for non-obvious logic" }
|
||||
]
|
||||
}
|
||||
]
|
||||
})
|
||||
```
|
||||
|
||||
**Process Round 2 answers** → add to `conventions.file_structure` and `conventions.documentation`.
|
||||
|
||||
---
|
||||
|
||||
#### Round 3: Architecture & Tech Stack Constraints
|
||||
|
||||
```javascript
|
||||
// Build architecture-specific options
|
||||
const archOptions = []
|
||||
|
||||
if (archStyle.toLowerCase().includes('monolith')) {
|
||||
archOptions.push(
|
||||
{ label: "No circular deps", description: "Modules must not have circular dependencies" },
|
||||
{ label: "Layer boundaries", description: "Strict layer separation: UI → Service → Data (no skipping layers)" }
|
||||
)
|
||||
} else if (archStyle.toLowerCase().includes('microservice')) {
|
||||
archOptions.push(
|
||||
{ label: "Service isolation", description: "Services must not share databases or internal state" },
|
||||
{ label: "API contracts", description: "All inter-service communication through versioned API contracts" }
|
||||
)
|
||||
}
|
||||
archOptions.push(
|
||||
{ label: "Stateless services", description: "Service/business logic must be stateless (state in DB/cache only)" },
|
||||
{ label: "Dependency injection", description: "Use dependency injection for testability, no hardcoded dependencies" }
|
||||
)
|
||||
|
||||
AskUserQuestion({
|
||||
questions: [
|
||||
{
|
||||
question: `Your ${archStyle} architecture uses ${archPatterns.join(', ') || 'various'} patterns. What architecture constraints apply?`,
|
||||
header: "Architecture",
|
||||
multiSelect: true,
|
||||
options: archOptions.slice(0, 4)
|
||||
},
|
||||
{
|
||||
question: `Tech stack: ${frameworks.join(', ')}. What technology constraints apply?`,
|
||||
header: "Tech Stack",
|
||||
multiSelect: true,
|
||||
options: [
|
||||
{ label: "No new deps without review", description: "Adding new dependencies requires explicit justification and review" },
|
||||
{ label: "Pin dependency versions", description: "All dependencies must use exact versions, not ranges" },
|
||||
{ label: "Prefer native APIs", description: "Use built-in/native APIs over third-party libraries when possible" },
|
||||
{ label: "Framework conventions", description: `Follow official ${frameworks[0] || 'framework'} conventions and best practices` }
|
||||
]
|
||||
}
|
||||
]
|
||||
})
|
||||
```
|
||||
|
||||
**Process Round 3 answers** → add to `constraints.architecture` and `constraints.tech_stack`.
|
||||
|
||||
---
|
||||
|
||||
#### Round 4: Performance & Security Constraints
|
||||
|
||||
```javascript
|
||||
AskUserQuestion({
|
||||
questions: [
|
||||
{
|
||||
question: "What performance requirements does your project have?",
|
||||
header: "Performance",
|
||||
multiSelect: true,
|
||||
options: [
|
||||
{ label: "API response time", description: "API endpoints must respond within 200ms (p95)" },
|
||||
{ label: "Bundle size limit", description: "Frontend bundle size must stay under 500KB gzipped" },
|
||||
{ label: "Lazy loading", description: "Large modules/routes must use lazy loading / code splitting" },
|
||||
{ label: "No N+1 queries", description: "Database access must avoid N+1 query patterns" }
|
||||
]
|
||||
},
|
||||
{
|
||||
question: "What security requirements does your project enforce?",
|
||||
header: "Security",
|
||||
multiSelect: true,
|
||||
options: [
|
||||
{ label: "Input sanitization", description: "All user input must be validated and sanitized before use" },
|
||||
{ label: "No secrets in code", description: "No API keys, passwords, or tokens in source code — use env vars" },
|
||||
{ label: "Auth on all endpoints", description: "All API endpoints require authentication unless explicitly public" },
|
||||
{ label: "Parameterized queries", description: "All database queries must use parameterized/prepared statements" }
|
||||
]
|
||||
}
|
||||
]
|
||||
})
|
||||
```
|
||||
|
||||
**Process Round 4 answers** → add to `constraints.performance` and `constraints.security`.
|
||||
|
||||
---
|
||||
|
||||
#### Round 5: Quality Rules
|
||||
|
||||
```javascript
|
||||
AskUserQuestion({
|
||||
questions: [
|
||||
{
|
||||
question: `Testing with ${testFrameworks.join(', ') || 'your test framework'}. What quality rules apply?`,
|
||||
header: "Quality",
|
||||
multiSelect: true,
|
||||
options: [
|
||||
{ label: "Min test coverage", description: "Minimum 80% code coverage for new code; no merging below threshold" },
|
||||
{ label: "No skipped tests", description: "Tests must not be skipped (.skip/.only) in committed code" },
|
||||
{ label: "Lint must pass", description: "All code must pass linter checks before commit (enforced by pre-commit)" },
|
||||
{ label: "Type check must pass", description: "Full type checking (tsc --noEmit) must pass with zero errors" }
|
||||
]
|
||||
}
|
||||
]
|
||||
})
|
||||
```
|
||||
|
||||
**Process Round 5 answers** → add to `quality_rules` array as `{ rule, scope, enforced_by }` objects.
|
||||
|
||||
### Step 4: Write project-guidelines.json
|
||||
|
||||
```javascript
|
||||
// Build the final guidelines object
|
||||
const finalGuidelines = {
|
||||
conventions: {
|
||||
coding_style: existingCodingStyle.concat(newCodingStyle),
|
||||
naming_patterns: existingNamingPatterns.concat(newNamingPatterns),
|
||||
file_structure: existingFileStructure.concat(newFileStructure),
|
||||
documentation: existingDocumentation.concat(newDocumentation)
|
||||
},
|
||||
constraints: {
|
||||
architecture: existingArchitecture.concat(newArchitecture),
|
||||
tech_stack: existingTechStack.concat(newTechStack),
|
||||
performance: existingPerformance.concat(newPerformance),
|
||||
security: existingSecurity.concat(newSecurity)
|
||||
},
|
||||
quality_rules: existingQualityRules.concat(newQualityRules),
|
||||
learnings: existingLearnings, // Preserve existing learnings
|
||||
_metadata: {
|
||||
created_at: existingMetadata?.created_at || new Date().toISOString(),
|
||||
version: "1.0.0",
|
||||
last_updated: new Date().toISOString(),
|
||||
updated_by: "workflow:init-guidelines"
|
||||
}
|
||||
}
|
||||
|
||||
Write('.workflow/project-guidelines.json', JSON.stringify(finalGuidelines, null, 2))
|
||||
```
|
||||
|
||||
### Step 5: Display Summary
|
||||
|
||||
```javascript
|
||||
const countConventions = finalGuidelines.conventions.coding_style.length
|
||||
+ finalGuidelines.conventions.naming_patterns.length
|
||||
+ finalGuidelines.conventions.file_structure.length
|
||||
+ finalGuidelines.conventions.documentation.length
|
||||
|
||||
const countConstraints = finalGuidelines.constraints.architecture.length
|
||||
+ finalGuidelines.constraints.tech_stack.length
|
||||
+ finalGuidelines.constraints.performance.length
|
||||
+ finalGuidelines.constraints.security.length
|
||||
|
||||
const countQuality = finalGuidelines.quality_rules.length
|
||||
|
||||
console.log(`
|
||||
✓ Project guidelines configured
|
||||
|
||||
## Summary
|
||||
- Conventions: ${countConventions} rules (coding: ${cs}, naming: ${np}, files: ${fs}, docs: ${doc})
|
||||
- Constraints: ${countConstraints} rules (arch: ${ar}, tech: ${ts}, perf: ${pf}, security: ${sc})
|
||||
- Quality rules: ${countQuality}
|
||||
|
||||
File: .workflow/project-guidelines.json
|
||||
|
||||
Next steps:
|
||||
- Use /workflow:session:solidify to add individual rules later
|
||||
- Guidelines will be auto-loaded by /workflow:plan for task generation
|
||||
`)
|
||||
```
|
||||
|
||||
## 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
|
||||
|
||||
## Related Commands
|
||||
|
||||
- `/workflow:init` - Creates scaffold; optionally calls this command
|
||||
- `/workflow:session:solidify` - Add individual rules one at a time
|
||||
@@ -1,288 +0,0 @@
|
||||
---
|
||||
name: init
|
||||
description: Initialize project-level state with intelligent project analysis using cli-explore-agent
|
||||
argument-hint: "[--regenerate]"
|
||||
examples:
|
||||
- /workflow:init
|
||||
- /workflow:init --regenerate
|
||||
---
|
||||
|
||||
# Workflow Init Command (/workflow:init)
|
||||
|
||||
## Overview
|
||||
Initialize `.workflow/project-tech.json` and `.workflow/project-guidelines.json` with comprehensive project understanding by delegating analysis to **cli-explore-agent**.
|
||||
|
||||
**Dual File System**:
|
||||
- `project-tech.json`: Auto-generated technical analysis (stack, architecture, components)
|
||||
- `project-guidelines.json`: 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
|
||||
```
|
||||
|
||||
## Execution Process
|
||||
|
||||
```
|
||||
Input Parsing:
|
||||
└─ Parse --regenerate flag → regenerate = 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
|
||||
├─ Create guidelines scaffold (if not exists)
|
||||
│ └─ Write .workflow/project-guidelines.json (empty structure)
|
||||
├─ Display summary
|
||||
└─ Ask about guidelines configuration
|
||||
├─ If guidelines empty → Ask user: "Configure now?" or "Skip"
|
||||
│ ├─ Configure now → Skill(skill="workflow:init-guidelines")
|
||||
│ └─ Skip → Show next steps
|
||||
└─ If guidelines populated → Show next steps only
|
||||
|
||||
Output:
|
||||
├─ .workflow/project-tech.json (+ .backup if regenerate)
|
||||
└─ .workflow/project-guidelines.json (scaffold or configured)
|
||||
```
|
||||
|
||||
## Implementation
|
||||
|
||||
### Step 1: Parse Input and Check Existing State
|
||||
|
||||
**Parse --regenerate flag**:
|
||||
```javascript
|
||||
const regenerate = $ARGUMENTS.includes('--regenerate')
|
||||
```
|
||||
|
||||
**Check existing state**:
|
||||
|
||||
```bash
|
||||
bash(test -f .workflow/project-tech.json && echo "TECH_EXISTS" || echo "TECH_NOT_FOUND")
|
||||
bash(test -f .workflow/project-guidelines.json && echo "GUIDELINES_EXISTS" || echo "GUIDELINES_NOT_FOUND")
|
||||
```
|
||||
|
||||
**If BOTH_EXIST and no --regenerate**: Exit early
|
||||
```
|
||||
Project already initialized:
|
||||
- Tech analysis: .workflow/project-tech.json
|
||||
- Guidelines: .workflow/project-guidelines.json
|
||||
|
||||
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: Create Guidelines Scaffold (if not exists)
|
||||
|
||||
```javascript
|
||||
// Only create if not exists (never overwrite user guidelines)
|
||||
if (!file_exists('.workflow/project-guidelines.json')) {
|
||||
const guidelinesScaffold = {
|
||||
conventions: {
|
||||
coding_style: [],
|
||||
naming_patterns: [],
|
||||
file_structure: [],
|
||||
documentation: []
|
||||
},
|
||||
constraints: {
|
||||
architecture: [],
|
||||
tech_stack: [],
|
||||
performance: [],
|
||||
security: []
|
||||
},
|
||||
quality_rules: [],
|
||||
learnings: [],
|
||||
_metadata: {
|
||||
created_at: new Date().toISOString(),
|
||||
version: "1.0.0"
|
||||
}
|
||||
};
|
||||
|
||||
Write('.workflow/project-guidelines.json', JSON.stringify(guidelinesScaffold, null, 2));
|
||||
}
|
||||
```
|
||||
|
||||
### Step 4: Display Summary
|
||||
|
||||
```javascript
|
||||
const projectTech = JSON.parse(Read('.workflow/project-tech.json'));
|
||||
const guidelinesExists = file_exists('.workflow/project-guidelines.json');
|
||||
|
||||
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
|
||||
- Guidelines: .workflow/project-guidelines.json ${guidelinesExists ? '(scaffold)' : ''}
|
||||
${regenerate ? '- Backup: .workflow/project-tech.json.backup' : ''}
|
||||
`);
|
||||
```
|
||||
|
||||
### Step 5: Ask About Guidelines Configuration
|
||||
|
||||
After displaying the summary, ask the user if they want to configure project guidelines interactively.
|
||||
|
||||
```javascript
|
||||
// Check if guidelines are just a scaffold (empty) or already populated
|
||||
const guidelines = JSON.parse(Read('.workflow/project-guidelines.json'));
|
||||
const isGuidelinesPopulated =
|
||||
guidelines.conventions.coding_style.length > 0 ||
|
||||
guidelines.conventions.naming_patterns.length > 0 ||
|
||||
guidelines.constraints.architecture.length > 0 ||
|
||||
guidelines.constraints.security.length > 0;
|
||||
|
||||
// Only ask if guidelines are not yet populated
|
||||
if (!isGuidelinesPopulated) {
|
||||
const userChoice = AskUserQuestion({
|
||||
questions: [{
|
||||
question: "Would you like to configure project guidelines now? The wizard will ask targeted questions based on your tech stack.",
|
||||
header: "Guidelines",
|
||||
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 /workflow:session:solidify to add rules individually"
|
||||
}
|
||||
]
|
||||
}]
|
||||
});
|
||||
|
||||
if (userChoice.answers["Guidelines"] === "Configure now (Recommended)") {
|
||||
console.log("\n🔧 Starting guidelines configuration wizard...\n");
|
||||
Skill(skill="workflow:init-guidelines");
|
||||
} else {
|
||||
console.log(`
|
||||
Next steps:
|
||||
- Use /workflow:init-guidelines to configure guidelines interactively
|
||||
- Use /workflow:session:solidify to add individual rules
|
||||
- Use /workflow:plan to start planning
|
||||
`);
|
||||
}
|
||||
} else {
|
||||
console.log(`
|
||||
Guidelines already configured (${guidelines.conventions.coding_style.length + guidelines.constraints.architecture.length}+ rules).
|
||||
|
||||
Next steps:
|
||||
- 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-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
|
||||
@@ -2,7 +2,7 @@
|
||||
name: integration-test-cycle
|
||||
description: Self-iterating integration test workflow with codebase exploration, test development, autonomous test-fix cycles, and reflection-driven strategy adjustment
|
||||
argument-hint: "[-y|--yes] [-c|--continue] [--max-iterations=N] \"module or feature description\""
|
||||
allowed-tools: TodoWrite(*), Task(*), AskUserQuestion(*), Read(*), Grep(*), Glob(*), Bash(*), Edit(*), Write(*), Skill(*)
|
||||
allowed-tools: TodoWrite(*), Agent(*), AskUserQuestion(*), Read(*), Grep(*), Glob(*), Bash(*), Edit(*), Write(*), Skill(*)
|
||||
---
|
||||
|
||||
## Auto Mode
|
||||
@@ -209,7 +209,7 @@ Unified integration test workflow: **Explore → Design → Develop → Test →
|
||||
1. **Codebase Exploration via cli-explore-agent**
|
||||
|
||||
```javascript
|
||||
Task({
|
||||
Agent({
|
||||
subagent_type: "cli-explore-agent",
|
||||
run_in_background: false,
|
||||
description: `Explore integration points: ${topicSlug}`,
|
||||
@@ -391,7 +391,7 @@ Also set `state.json.phase` to `"designed"`.
|
||||
1. **Generate Integration Tests via @code-developer**
|
||||
|
||||
```javascript
|
||||
Task({
|
||||
Agent({
|
||||
subagent_type: "code-developer",
|
||||
run_in_background: false,
|
||||
description: `Generate integration tests: ${topicSlug}`,
|
||||
@@ -435,7 +435,7 @@ Also set state.json "phase" to "developed".
|
||||
2. **Code Validation Gate via @test-fix-agent**
|
||||
|
||||
```javascript
|
||||
Task({
|
||||
Agent({
|
||||
subagent_type: "test-fix-agent",
|
||||
run_in_background: false,
|
||||
description: `Validate generated tests: ${topicSlug}`,
|
||||
@@ -605,7 +605,7 @@ After each iteration, update the `## Cumulative Learnings` section in reflection
|
||||
|
||||
**@test-fix-agent** (test execution):
|
||||
```javascript
|
||||
Task({
|
||||
Agent({
|
||||
subagent_type: "test-fix-agent",
|
||||
run_in_background: false,
|
||||
description: `Execute integration tests: iteration ${N}`,
|
||||
@@ -637,7 +637,7 @@ For each failure, assign:
|
||||
|
||||
**@cli-planning-agent** (failure analysis with reflection):
|
||||
```javascript
|
||||
Task({
|
||||
Agent({
|
||||
subagent_type: "cli-planning-agent",
|
||||
run_in_background: false,
|
||||
description: `Analyze failures: iteration ${N} - ${strategy}`,
|
||||
@@ -676,7 +676,7 @@ Analyze test failures using reflection context and generate fix strategy.
|
||||
|
||||
**@test-fix-agent** (apply fixes):
|
||||
```javascript
|
||||
Task({
|
||||
Agent({
|
||||
subagent_type: "test-fix-agent",
|
||||
run_in_background: false,
|
||||
description: `Apply fixes: iteration ${N} - ${strategy}`,
|
||||
@@ -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
|
||||
@@ -923,7 +927,7 @@ Single evolving state file — each phase writes its section:
|
||||
- Already have a completed implementation session (WFS-*)
|
||||
- Only need unit/component level tests
|
||||
|
||||
**Use `workflow-tdd` skill when:**
|
||||
**Use `workflow-tdd-plan` skill when:**
|
||||
- Building new features with test-first approach
|
||||
- Red-Green-Refactor cycle
|
||||
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
name: refactor-cycle
|
||||
description: Tech debt discovery and self-iterating refactoring with multi-dimensional analysis, prioritized execution, regression validation, and reflection-driven adjustment
|
||||
argument-hint: "[-y|--yes] [-c|--continue] [--scope=module|project] \"module or refactoring goal\""
|
||||
allowed-tools: TodoWrite(*), Task(*), AskUserQuestion(*), Read(*), Grep(*), Glob(*), Bash(*), Edit(*), Write(*)
|
||||
allowed-tools: TodoWrite(*), Agent(*), AskUserQuestion(*), Read(*), Grep(*), Glob(*), Bash(*), Edit(*), Write(*)
|
||||
---
|
||||
|
||||
## Auto Mode
|
||||
@@ -39,7 +39,7 @@ Closed-loop tech debt lifecycle: **Discover → Assess → Plan → Refactor →
|
||||
|
||||
**vs Existing Commands**:
|
||||
- **workflow:lite-fix**: Single bug fix, no systematic debt analysis
|
||||
- **workflow:plan + execute**: Generic implementation, no debt-aware prioritization or regression validation
|
||||
- **workflow-plan + execute**: Generic implementation, no debt-aware prioritization or regression validation
|
||||
- **This command**: Full debt lifecycle — discovery through multi-dimensional scan, prioritized execution with per-item regression validation
|
||||
|
||||
### Value Proposition
|
||||
@@ -200,7 +200,7 @@ Closed-loop tech debt lifecycle: **Discover → Assess → Plan → Refactor →
|
||||
1. **Codebase Exploration via cli-explore-agent**
|
||||
|
||||
```javascript
|
||||
Task({
|
||||
Agent({
|
||||
subagent_type: "cli-explore-agent",
|
||||
run_in_background: false,
|
||||
description: `Explore codebase for debt: ${topicSlug}`,
|
||||
@@ -465,7 +465,7 @@ Set `state.json.current_item` to item ID.
|
||||
#### Step 4.2: Execute Refactoring
|
||||
|
||||
```javascript
|
||||
Task({
|
||||
Agent({
|
||||
subagent_type: "code-developer",
|
||||
run_in_background: false,
|
||||
description: `Refactor ${item.id}: ${item.title}`,
|
||||
@@ -499,7 +499,7 @@ ${JSON.stringify(item.refactor_plan, null, 2)}
|
||||
|
||||
```javascript
|
||||
// 1. Run tests
|
||||
Task({
|
||||
Agent({
|
||||
subagent_type: "test-fix-agent",
|
||||
run_in_background: false,
|
||||
description: `Validate refactoring: ${item.id}`,
|
||||
@@ -843,6 +843,8 @@ AskUserQuestion({
|
||||
|
||||
## Post-Completion Expansion
|
||||
|
||||
**Auto-sync**: 执行 `/workflow:session:sync -y "{summary}"` 更新 specs/*.md + project-tech。
|
||||
|
||||
完成后询问用户是否扩展为issue(test/enhance/refactor/doc),选中项调用 `/issue:new "{summary} - {dimension}"`
|
||||
|
||||
---
|
||||
|
||||
@@ -1,620 +0,0 @@
|
||||
---
|
||||
name: req-plan-with-file
|
||||
description: Requirement-level progressive roadmap planning with issue creation. Decomposes requirements into convergent layers or task sequences, creates issues via ccw issue create, and generates roadmap.md for human review. Issues stored in .workflow/issues/issues.jsonl (single source of truth).
|
||||
argument-hint: "[-y|--yes] [-c|--continue] [-m|--mode progressive|direct|auto] \"requirement description\""
|
||||
allowed-tools: TodoWrite(*), Task(*), AskUserQuestion(*), Read(*), Grep(*), Glob(*), Bash(*), Edit(*), Write(*)
|
||||
---
|
||||
|
||||
## Auto Mode
|
||||
|
||||
When `--yes` or `-y`: Auto-confirm strategy selection, use recommended mode, skip interactive validation rounds.
|
||||
|
||||
# Workflow Req-Plan Command (/workflow:req-plan-with-file)
|
||||
|
||||
## Quick Start
|
||||
|
||||
```bash
|
||||
# Basic usage
|
||||
/workflow:req-plan-with-file "Implement user authentication system with OAuth and 2FA"
|
||||
|
||||
# With mode selection
|
||||
/workflow:req-plan-with-file -m progressive "Build real-time notification system" # Layered MVP→iterations
|
||||
/workflow:req-plan-with-file -m direct "Refactor payment module" # Topologically-sorted task sequence
|
||||
/workflow:req-plan-with-file -m auto "Add data export feature" # Auto-select strategy
|
||||
|
||||
# Continue existing session
|
||||
/workflow:req-plan-with-file --continue "user authentication system"
|
||||
|
||||
# Auto mode
|
||||
/workflow:req-plan-with-file -y "Implement caching layer"
|
||||
```
|
||||
|
||||
**Context Source**: cli-explore-agent (optional) + requirement analysis
|
||||
**Output Directory**: `.workflow/.req-plan/{session-id}/`
|
||||
**Core Innovation**: Requirement decomposition → issue creation via `ccw issue create`. Issues stored in `.workflow/issues/issues.jsonl` (single source of truth). Wave/dependency info embedded in issue tags (`wave-N`) and `extended_context.notes.depends_on_issues`. team-planex consumes issues directly by ID or tag query.
|
||||
|
||||
## Overview
|
||||
|
||||
Requirement-level layered roadmap planning command. Decomposes a requirement into **convergent layers or task sequences**, creates issues via `ccw issue create`. Issues are the single source of truth in `.workflow/issues/issues.jsonl`; wave and dependency info is embedded in issue tags and `extended_context.notes`.
|
||||
|
||||
**Dual Modes**:
|
||||
- **Progressive**: Layered MVP→iterations, suitable for high-uncertainty requirements (validate first, then refine)
|
||||
- **Direct**: Topologically-sorted task sequence, suitable for low-uncertainty requirements (clear tasks, directly ordered)
|
||||
- **Auto**: Automatically selects based on uncertainty level
|
||||
|
||||
**Core Workflow**: Requirement Understanding → Strategy Selection → Context Collection (optional) → Decomposition + Issue Creation → Validation → team-planex Handoff
|
||||
|
||||
```
|
||||
┌─────────────────────────────────────────────────────────────────────────┐
|
||||
│ REQ-PLAN ROADMAP WORKFLOW │
|
||||
├─────────────────────────────────────────────────────────────────────────┤
|
||||
│ │
|
||||
│ Phase 1: Requirement Understanding & Strategy Selection │
|
||||
│ ├─ Parse requirement: goal / constraints / stakeholders │
|
||||
│ ├─ Assess uncertainty level │
|
||||
│ │ ├─ High uncertainty → recommend progressive │
|
||||
│ │ └─ Low uncertainty → recommend direct │
|
||||
│ ├─ User confirms strategy (-m skips, -y auto-selects recommended) │
|
||||
│ └─ Initialize strategy-assessment.json + roadmap.md skeleton │
|
||||
│ │
|
||||
│ Phase 2: Context Collection (Optional) │
|
||||
│ ├─ Detect codebase: package.json / go.mod / src / ... │
|
||||
│ ├─ Has codebase → cli-explore-agent explores relevant modules │
|
||||
│ └─ No codebase → skip, pure requirement decomposition │
|
||||
│ │
|
||||
│ Phase 3: Decomposition & Issue Creation (cli-roadmap-plan-agent) │
|
||||
│ ├─ Progressive: define 2-4 layers, each with full convergence │
|
||||
│ ├─ Direct: vertical slicing + topological sort, each with convergence│
|
||||
│ ├─ Create issues via ccw issue create (ISS-xxx IDs) │
|
||||
│ └─ Generate roadmap.md (with issue ID references) │
|
||||
│ │
|
||||
│ Phase 4: Validation & team-planex Handoff │
|
||||
│ ├─ Display decomposition results (tabular + convergence criteria) │
|
||||
│ ├─ User feedback loop (up to 5 rounds) │
|
||||
│ └─ Next steps: team-planex full execution / wave-by-wave / view │
|
||||
│ │
|
||||
└─────────────────────────────────────────────────────────────────────────┘
|
||||
```
|
||||
|
||||
## Output
|
||||
|
||||
```
|
||||
.workflow/.req-plan/RPLAN-{slug}-{YYYY-MM-DD}/
|
||||
├── roadmap.md # Human-readable roadmap with issue ID references
|
||||
├── strategy-assessment.json # Strategy assessment result
|
||||
└── exploration-codebase.json # Codebase context (optional)
|
||||
```
|
||||
|
||||
| File | Phase | Description |
|
||||
|------|-------|-------------|
|
||||
| `strategy-assessment.json` | 1 | Uncertainty analysis + mode recommendation + extracted goal/constraints/stakeholders |
|
||||
| `roadmap.md` (skeleton) | 1 | Initial skeleton with placeholders, finalized in Phase 3 |
|
||||
| `exploration-codebase.json` | 2 | Codebase context: relevant modules, patterns, integration points (only when codebase exists) |
|
||||
| `roadmap.md` (final) | 3 | Human-readable roadmap with issue ID references, convergence details, team-planex execution guide |
|
||||
|
||||
**roadmap.md template**:
|
||||
|
||||
```markdown
|
||||
# Requirement Roadmap
|
||||
|
||||
**Session**: RPLAN-{slug}-{date}
|
||||
**Requirement**: {requirement}
|
||||
**Strategy**: {progressive|direct}
|
||||
**Generated**: {timestamp}
|
||||
|
||||
## Strategy Assessment
|
||||
- Uncertainty level: {high|medium|low}
|
||||
- Decomposition mode: {progressive|direct}
|
||||
- Assessment basis: {factors summary}
|
||||
|
||||
## Roadmap
|
||||
{Tabular display of layers/tasks}
|
||||
|
||||
## Convergence Criteria Details
|
||||
{Expanded convergence for each layer/task}
|
||||
|
||||
## Risks
|
||||
{Aggregated risks}
|
||||
|
||||
## Next Steps
|
||||
{Execution guidance}
|
||||
```
|
||||
|
||||
## Configuration
|
||||
|
||||
| Flag | Default | Description |
|
||||
|------|---------|-------------|
|
||||
| `-y, --yes` | false | Auto-confirm all decisions |
|
||||
| `-c, --continue` | false | Continue existing session |
|
||||
| `-m, --mode` | auto | Decomposition strategy: progressive / direct / auto |
|
||||
|
||||
**Session ID format**: `RPLAN-{slug}-{YYYY-MM-DD}`
|
||||
- slug: lowercase, alphanumeric + CJK characters, max 40 chars
|
||||
- date: YYYY-MM-DD (UTC+8)
|
||||
- Auto-detect continue: session folder + roadmap.md exists → continue mode
|
||||
|
||||
## JSONL Schema Design
|
||||
|
||||
### Issue Format
|
||||
|
||||
Each line in `issues.jsonl` follows the standard `issues-jsonl-schema.json` (see `.ccw/workflows/cli-templates/schemas/issues-jsonl-schema.json`).
|
||||
|
||||
**Key fields per issue**:
|
||||
|
||||
| Field | Source | Description |
|
||||
|-------|--------|-------------|
|
||||
| `id` | `ccw issue create` | Formal ISS-YYYYMMDD-NNN ID |
|
||||
| `title` | Layer/task mapping | `[LayerName] goal` or `[TaskType] title` |
|
||||
| `context` | Convergence fields | Markdown with goal, scope, convergence criteria, verification, DoD |
|
||||
| `priority` | Effort mapping | small→4, medium→3, large→2 |
|
||||
| `source` | Fixed | `"text"` |
|
||||
| `tags` | Auto-generated | `["req-plan", mode, name/type, "wave-N"]` |
|
||||
| `extended_context.notes` | Metadata JSON | session, strategy, original_id, wave, depends_on_issues |
|
||||
| `lifecycle_requirements` | Fixed | test_strategy, regression_scope, acceptance_type, commit_strategy |
|
||||
|
||||
### Convergence Criteria (in issue context)
|
||||
|
||||
Each issue's `context` field contains convergence information:
|
||||
|
||||
| Section | Purpose | Requirement |
|
||||
|---------|---------|-------------|
|
||||
| `## Convergence Criteria` | List of checkable specific conditions | **Testable** (can be written as assertions or manual steps) |
|
||||
| `## Verification` | How to verify these conditions | **Executable** (command, script, or explicit steps) |
|
||||
| `## Definition of Done` | One-sentence completion definition | **Business language** (non-technical person can judge) |
|
||||
|
||||
## Implementation
|
||||
|
||||
### Session Initialization
|
||||
|
||||
**Objective**: Create session context and directory structure.
|
||||
|
||||
```javascript
|
||||
const getUtc8ISOString = () => new Date(Date.now() + 8 * 60 * 60 * 1000).toISOString()
|
||||
|
||||
// Parse flags
|
||||
const autoYes = $ARGUMENTS.includes('--yes') || $ARGUMENTS.includes('-y')
|
||||
const continueMode = $ARGUMENTS.includes('--continue') || $ARGUMENTS.includes('-c')
|
||||
const modeMatch = $ARGUMENTS.match(/(?:--mode|-m)\s+(progressive|direct|auto)/)
|
||||
const requestedMode = modeMatch ? modeMatch[1] : 'auto'
|
||||
|
||||
// Clean requirement text (remove flags)
|
||||
const requirement = $ARGUMENTS
|
||||
.replace(/--yes|-y|--continue|-c|--mode\s+\w+|-m\s+\w+/g, '')
|
||||
.trim()
|
||||
|
||||
const slug = requirement.toLowerCase()
|
||||
.replace(/[^a-z0-9\u4e00-\u9fa5]+/g, '-')
|
||||
.substring(0, 40)
|
||||
const dateStr = getUtc8ISOString().substring(0, 10)
|
||||
const sessionId = `RPLAN-${slug}-${dateStr}`
|
||||
const sessionFolder = `.workflow/.req-plan/${sessionId}`
|
||||
|
||||
// Auto-detect continue: session folder + roadmap.md exists → continue mode
|
||||
Bash(`mkdir -p ${sessionFolder}`)
|
||||
```
|
||||
|
||||
### Phase 1: Requirement Understanding & Strategy Selection
|
||||
|
||||
**Objective**: Parse requirement, assess uncertainty, select decomposition strategy.
|
||||
|
||||
**Prerequisites**: Session initialized, requirement description available.
|
||||
|
||||
**Steps**:
|
||||
|
||||
1. **Parse Requirement**
|
||||
- Extract core goal (what to achieve)
|
||||
- Identify constraints (tech stack, timeline, compatibility, etc.)
|
||||
- Identify stakeholders (users, admins, developers, etc.)
|
||||
- Identify keywords to determine domain
|
||||
|
||||
2. **Assess Uncertainty Level**
|
||||
|
||||
```javascript
|
||||
const uncertaintyFactors = {
|
||||
scope_clarity: 'low|medium|high',
|
||||
technical_risk: 'low|medium|high',
|
||||
dependency_unknown: 'low|medium|high',
|
||||
domain_familiarity: 'low|medium|high',
|
||||
requirement_stability: 'low|medium|high'
|
||||
}
|
||||
// high uncertainty (>=3 high) → progressive
|
||||
// low uncertainty (>=3 low) → direct
|
||||
// otherwise → ask user preference
|
||||
```
|
||||
|
||||
3. **Strategy Selection** (skip if `-m` already specified)
|
||||
|
||||
```javascript
|
||||
if (requestedMode !== 'auto') {
|
||||
selectedMode = requestedMode
|
||||
} else if (autoYes) {
|
||||
selectedMode = recommendedMode
|
||||
} else {
|
||||
AskUserQuestion({
|
||||
questions: [{
|
||||
question: `Decomposition strategy selection:\n\nUncertainty assessment: ${uncertaintyLevel}\nRecommended strategy: ${recommendedMode}\n\nSelect decomposition strategy:`,
|
||||
header: "Strategy",
|
||||
multiSelect: false,
|
||||
options: [
|
||||
{
|
||||
label: recommendedMode === 'progressive' ? "Progressive (Recommended)" : "Progressive",
|
||||
description: "Layered MVP→iterations, validate core first then refine progressively. Suitable for high-uncertainty requirements needing quick validation"
|
||||
},
|
||||
{
|
||||
label: recommendedMode === 'direct' ? "Direct (Recommended)" : "Direct",
|
||||
description: "Topologically-sorted task sequence with explicit dependencies. Suitable for clear requirements with confirmed technical approach"
|
||||
}
|
||||
]
|
||||
}]
|
||||
})
|
||||
}
|
||||
```
|
||||
|
||||
4. **Generate strategy-assessment.json**
|
||||
|
||||
```javascript
|
||||
const strategyAssessment = {
|
||||
session_id: sessionId,
|
||||
requirement: requirement,
|
||||
timestamp: getUtc8ISOString(),
|
||||
uncertainty_factors: uncertaintyFactors,
|
||||
uncertainty_level: uncertaintyLevel, // 'high' | 'medium' | 'low'
|
||||
recommended_mode: recommendedMode,
|
||||
selected_mode: selectedMode,
|
||||
goal: extractedGoal,
|
||||
constraints: extractedConstraints,
|
||||
stakeholders: extractedStakeholders,
|
||||
domain_keywords: extractedKeywords
|
||||
}
|
||||
Write(`${sessionFolder}/strategy-assessment.json`, JSON.stringify(strategyAssessment, null, 2))
|
||||
```
|
||||
|
||||
5. **Initialize roadmap.md skeleton** (placeholder sections, finalized in Phase 4)
|
||||
|
||||
```javascript
|
||||
const roadmapMdSkeleton = `# Requirement Roadmap
|
||||
|
||||
**Session**: ${sessionId}
|
||||
**Requirement**: ${requirement}
|
||||
**Strategy**: ${selectedMode}
|
||||
**Status**: Planning
|
||||
**Created**: ${getUtc8ISOString()}
|
||||
|
||||
## Strategy Assessment
|
||||
- Uncertainty level: ${uncertaintyLevel}
|
||||
- Decomposition mode: ${selectedMode}
|
||||
|
||||
## Roadmap
|
||||
> To be populated after Phase 3 decomposition
|
||||
|
||||
## Convergence Criteria Details
|
||||
> To be populated after Phase 3 decomposition
|
||||
|
||||
## Risk Items
|
||||
> To be populated after Phase 3 decomposition
|
||||
|
||||
## Next Steps
|
||||
> To be populated after Phase 4 validation
|
||||
`
|
||||
Write(`${sessionFolder}/roadmap.md`, roadmapMdSkeleton)
|
||||
```
|
||||
|
||||
**Success Criteria**:
|
||||
- Requirement goal, constraints, stakeholders identified
|
||||
- Uncertainty level assessed
|
||||
- Strategy selected (progressive or direct)
|
||||
- strategy-assessment.json generated
|
||||
- roadmap.md skeleton initialized
|
||||
|
||||
### Phase 2: Context Collection (Optional)
|
||||
|
||||
**Objective**: If a codebase exists, collect relevant context to enhance decomposition quality.
|
||||
|
||||
**Prerequisites**: Phase 1 complete.
|
||||
|
||||
**Steps**:
|
||||
|
||||
1. **Detect Codebase**
|
||||
|
||||
```javascript
|
||||
const hasCodebase = Bash(`
|
||||
test -f package.json && echo "nodejs" ||
|
||||
test -f go.mod && echo "golang" ||
|
||||
test -f Cargo.toml && echo "rust" ||
|
||||
test -f pyproject.toml && echo "python" ||
|
||||
test -f pom.xml && echo "java" ||
|
||||
test -d src && echo "generic" ||
|
||||
echo "none"
|
||||
`).trim()
|
||||
```
|
||||
|
||||
2. **Codebase Exploration** (only when hasCodebase !== 'none')
|
||||
|
||||
```javascript
|
||||
if (hasCodebase !== 'none') {
|
||||
Task({
|
||||
subagent_type: "cli-explore-agent",
|
||||
run_in_background: false,
|
||||
description: `Explore codebase: ${slug}`,
|
||||
prompt: `
|
||||
## Exploration Context
|
||||
Requirement: ${requirement}
|
||||
Strategy: ${selectedMode}
|
||||
Project Type: ${hasCodebase}
|
||||
Session: ${sessionFolder}
|
||||
|
||||
## MANDATORY FIRST STEPS
|
||||
1. Run: ccw tool exec get_modules_by_depth '{}'
|
||||
2. Execute relevant searches based on requirement keywords
|
||||
3. Read: .workflow/project-tech.json (if exists)
|
||||
4. Read: .workflow/project-guidelines.json (if exists)
|
||||
|
||||
## Exploration Focus
|
||||
- Identify modules/components related to the requirement
|
||||
- Find existing patterns that should be followed
|
||||
- Locate integration points for new functionality
|
||||
- Assess current architecture constraints
|
||||
|
||||
## Output
|
||||
Write findings to: ${sessionFolder}/exploration-codebase.json
|
||||
|
||||
Schema: {
|
||||
project_type: "${hasCodebase}",
|
||||
relevant_modules: [{name, path, relevance}],
|
||||
existing_patterns: [{pattern, files, description}],
|
||||
integration_points: [{location, description, risk}],
|
||||
architecture_constraints: [string],
|
||||
tech_stack: {languages, frameworks, tools},
|
||||
_metadata: {timestamp, exploration_scope}
|
||||
}
|
||||
`
|
||||
})
|
||||
}
|
||||
// No codebase → skip, proceed directly to Phase 3
|
||||
```
|
||||
|
||||
**Success Criteria**:
|
||||
- Codebase detection complete
|
||||
- When codebase exists, exploration-codebase.json generated
|
||||
- When no codebase, skipped and logged
|
||||
|
||||
### Phase 3: Decomposition & Issue Creation
|
||||
|
||||
**Objective**: Execute requirement decomposition via `cli-roadmap-plan-agent`, creating issues and generating roadmap.md.
|
||||
|
||||
**Prerequisites**: Phase 1, Phase 2 complete. Strategy selected. Context collected (if applicable).
|
||||
|
||||
**Agent**: `cli-roadmap-plan-agent` (dedicated requirement roadmap planning agent, supports CLI-assisted decomposition + issue creation + built-in quality checks)
|
||||
|
||||
**Steps**:
|
||||
|
||||
1. **Prepare Context**
|
||||
|
||||
```javascript
|
||||
const strategy = JSON.parse(Read(`${sessionFolder}/strategy-assessment.json`))
|
||||
let explorationContext = null
|
||||
if (file_exists(`${sessionFolder}/exploration-codebase.json`)) {
|
||||
explorationContext = JSON.parse(Read(`${sessionFolder}/exploration-codebase.json`))
|
||||
}
|
||||
```
|
||||
|
||||
2. **Invoke cli-roadmap-plan-agent**
|
||||
|
||||
The agent internally executes a 5-phase flow:
|
||||
- Phase 1: Context loading + requirement analysis
|
||||
- Phase 2: CLI-assisted decomposition (Gemini → Qwen → manual fallback)
|
||||
- Phase 3: Record enhancement + validation (schema compliance, dependency checks, convergence quality)
|
||||
- Phase 4: Issue creation + roadmap generation (ccw issue create → roadmap.md)
|
||||
- Phase 5: CLI decomposition quality check (**MANDATORY** - requirement coverage, convergence criteria quality, dependency correctness)
|
||||
|
||||
```javascript
|
||||
Task({
|
||||
subagent_type: "cli-roadmap-plan-agent",
|
||||
run_in_background: false,
|
||||
description: `Roadmap decomposition: ${slug}`,
|
||||
prompt: `
|
||||
## Roadmap Decomposition Task
|
||||
|
||||
### Input Context
|
||||
- **Requirement**: ${requirement}
|
||||
- **Selected Mode**: ${selectedMode}
|
||||
- **Session ID**: ${sessionId}
|
||||
- **Session Folder**: ${sessionFolder}
|
||||
|
||||
### Strategy Assessment
|
||||
${JSON.stringify(strategy, null, 2)}
|
||||
|
||||
### Codebase Context
|
||||
${explorationContext
|
||||
? `File: ${sessionFolder}/exploration-codebase.json\n${JSON.stringify(explorationContext, null, 2)}`
|
||||
: 'No codebase detected - pure requirement decomposition'}
|
||||
|
||||
### Issue Creation
|
||||
- Use \`ccw issue create\` for each decomposed item
|
||||
- Issue format: issues-jsonl-schema (id, title, status, priority, context, source, tags, extended_context)
|
||||
- Update \`roadmap.md\` with issue ID references
|
||||
|
||||
### CLI Configuration
|
||||
- Primary tool: gemini
|
||||
- Fallback: qwen
|
||||
- Timeout: 60000ms
|
||||
|
||||
### Expected Output
|
||||
1. **${sessionFolder}/roadmap.md** - Human-readable roadmap with issue references
|
||||
2. Issues created in \`.workflow/issues/issues.jsonl\` via ccw issue create
|
||||
|
||||
### Mode-Specific Requirements
|
||||
|
||||
${selectedMode === 'progressive' ? `**Progressive Mode**:
|
||||
- 2-4 layers from MVP to full implementation
|
||||
- Each layer: id (L0-L3), name, goal, scope, excludes, convergence, risks, effort, depends_on
|
||||
- L0 (MVP) must be a self-contained closed loop with no dependencies
|
||||
- Scope: each feature belongs to exactly ONE layer (no overlap)
|
||||
- Layer names: MVP / Usable / Refined / Optimized` :
|
||||
|
||||
`**Direct Mode**:
|
||||
- Topologically-sorted task sequence
|
||||
- Each task: id (T1-Tn), title, type, scope, inputs, outputs, convergence, depends_on, parallel_group
|
||||
- Inputs must come from preceding task outputs or existing resources
|
||||
- Tasks in same parallel_group must be truly independent`}
|
||||
|
||||
### Convergence Quality Requirements
|
||||
- criteria[]: MUST be testable (can write assertions or manual verification steps)
|
||||
- verification: MUST be executable (command, script, or explicit steps)
|
||||
- definition_of_done: MUST use business language (non-technical person can judge)
|
||||
|
||||
### Execution
|
||||
1. Analyze requirement and build decomposition context
|
||||
2. Execute CLI-assisted decomposition (Gemini, fallback Qwen)
|
||||
3. Parse output, validate records, enhance convergence quality
|
||||
4. Create issues via ccw issue create, generate roadmap.md
|
||||
5. Execute mandatory quality check (Phase 5)
|
||||
6. Return brief completion summary
|
||||
`
|
||||
})
|
||||
```
|
||||
|
||||
**Success Criteria**:
|
||||
- Issues created via `ccw issue create`, each with formal ISS-xxx ID
|
||||
- roadmap.md generated with issue ID references
|
||||
- Agent's internal quality check passed
|
||||
- No circular dependencies
|
||||
- Progressive: 2-4 layers, no scope overlap
|
||||
- Direct: tasks have explicit inputs/outputs, parallel_group assigned
|
||||
|
||||
### Phase 4: Validation & team-planex Handoff
|
||||
|
||||
**Objective**: Display decomposition results, collect user feedback, provide team-planex execution options.
|
||||
|
||||
**Prerequisites**: Phase 3 complete, issues created, roadmap.md generated.
|
||||
|
||||
**Steps**:
|
||||
|
||||
1. **Display Decomposition Results** (tabular format)
|
||||
|
||||
```javascript
|
||||
// Use issueIdMap from Phase 3 for display
|
||||
const issueIds = Object.values(issueIdMap)
|
||||
```
|
||||
|
||||
**Progressive Mode**:
|
||||
```markdown
|
||||
## Roadmap Overview
|
||||
|
||||
| Wave | Issue ID | Name | Goal | Priority |
|
||||
|------|----------|------|------|----------|
|
||||
| 1 | ISS-xxx | MVP | ... | 2 |
|
||||
| 2 | ISS-yyy | Usable | ... | 3 |
|
||||
|
||||
### Convergence Criteria
|
||||
**Wave 1 - MVP (ISS-xxx)**:
|
||||
- Criteria: [criteria list]
|
||||
- Verification: [verification]
|
||||
- Definition of Done: [definition_of_done]
|
||||
```
|
||||
|
||||
**Direct Mode**:
|
||||
```markdown
|
||||
## Task Sequence
|
||||
|
||||
| Wave | Issue ID | Title | Type | Dependencies |
|
||||
|------|----------|-------|------|--------------|
|
||||
| 1 | ISS-xxx | ... | infrastructure | - |
|
||||
| 2 | ISS-yyy | ... | feature | ISS-xxx |
|
||||
|
||||
### Convergence Criteria
|
||||
**Wave 1 - ISS-xxx**:
|
||||
- Criteria: [criteria list]
|
||||
- Verification: [verification]
|
||||
- Definition of Done: [definition_of_done]
|
||||
```
|
||||
|
||||
2. **User Feedback Loop** (up to 5 rounds, skipped when autoYes)
|
||||
|
||||
```javascript
|
||||
if (!autoYes) {
|
||||
let round = 0
|
||||
let continueLoop = true
|
||||
|
||||
while (continueLoop && round < 5) {
|
||||
round++
|
||||
const feedback = AskUserQuestion({
|
||||
questions: [{
|
||||
question: `Roadmap validation (round ${round}):\nAny feedback on the current decomposition?`,
|
||||
header: "Feedback",
|
||||
multiSelect: false,
|
||||
options: [
|
||||
{ label: "Approve", description: "Decomposition is reasonable, proceed to next steps" },
|
||||
{ label: "Adjust Scope", description: "Some issue scopes need adjustment" },
|
||||
{ label: "Modify Convergence", description: "Convergence criteria are not specific or testable enough" },
|
||||
{ label: "Re-decompose", description: "Overall strategy or layering approach needs change" }
|
||||
]
|
||||
}]
|
||||
})
|
||||
|
||||
if (feedback === 'Approve') {
|
||||
continueLoop = false
|
||||
} else {
|
||||
// Handle adjustment based on feedback type
|
||||
// After adjustment, re-display and return to loop top
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
3. **Post-Completion Options**
|
||||
|
||||
```javascript
|
||||
if (!autoYes) {
|
||||
AskUserQuestion({
|
||||
questions: [{
|
||||
question: `路线图已生成,${issueIds.length} 个 issues 已创建。下一步:`,
|
||||
header: "Next Step",
|
||||
multiSelect: false,
|
||||
options: [
|
||||
{ label: "Execute with team-planex", description: `启动 team-planex 执行全部 ${issueIds.length} 个 issues` },
|
||||
{ label: "Execute first wave", description: "仅执行 Wave 1(按 wave-1 tag 筛选)" },
|
||||
{ label: "View issues", description: "查看已创建的 issue 详情" },
|
||||
{ label: "Done", description: "保存路线图,稍后执行" }
|
||||
]
|
||||
}]
|
||||
})
|
||||
}
|
||||
```
|
||||
|
||||
| Selection | Action |
|
||||
|-----------|--------|
|
||||
| Execute with team-planex | `Skill(skill="team-planex", args="${issueIds.join(' ')}")` |
|
||||
| Execute first wave | Filter issues by `wave-1` tag, pass to team-planex |
|
||||
| View issues | Display issues summary from `.workflow/issues/issues.jsonl` |
|
||||
| Done | Display file paths, end |
|
||||
|
||||
**Success Criteria**:
|
||||
- User feedback processed (or skipped via autoYes)
|
||||
- Post-completion options provided
|
||||
- team-planex handoff available via issue IDs
|
||||
|
||||
## Error Handling
|
||||
|
||||
| Error | Resolution |
|
||||
|-------|------------|
|
||||
| cli-explore-agent failure | Skip code exploration, proceed with pure requirement decomposition |
|
||||
| No codebase | Normal flow, skip Phase 2 |
|
||||
| Circular dependency detected | Prompt user to adjust dependencies, re-decompose |
|
||||
| User feedback timeout | Save current state, display `--continue` recovery command |
|
||||
| Max feedback rounds reached | Use current version to generate final artifacts |
|
||||
| Session folder conflict | Append timestamp suffix |
|
||||
|
||||
## Best Practices
|
||||
|
||||
1. **Clear requirement description**: Detailed description → more accurate uncertainty assessment and decomposition
|
||||
2. **Validate MVP first**: In progressive mode, L0 should be the minimum verifiable closed loop
|
||||
3. **Testable convergence**: criteria must be writable as assertions or manual steps; definition_of_done should be judgeable by non-technical stakeholders (see Convergence Criteria in JSONL Schema Design)
|
||||
4. **Agent-First for Exploration**: Delegate codebase exploration to cli-explore-agent, do not analyze directly in main flow
|
||||
5. **Incremental validation**: Use `--continue` to iterate on existing roadmaps
|
||||
6. **team-planex integration**: Issues created follow standard issues-jsonl-schema, directly consumable by team-planex via issue IDs and tags
|
||||
|
||||
|
||||
---
|
||||
|
||||
**Now execute req-plan-with-file for**: $ARGUMENTS
|
||||
544
.claude/commands/workflow/roadmap-with-file.md
Normal file
544
.claude/commands/workflow/roadmap-with-file.md
Normal file
@@ -0,0 +1,544 @@
|
||||
---
|
||||
name: roadmap-with-file
|
||||
description: Strategic requirement roadmap with iterative decomposition and issue creation. Outputs roadmap.md (human-readable, single source) + issues.jsonl (machine-executable). Handoff to team-planex.
|
||||
argument-hint: "[-y|--yes] [-c|--continue] [-m progressive|direct|auto] \"requirement description\""
|
||||
allowed-tools: TodoWrite(*), Agent(*), AskUserQuestion(*), Read(*), Grep(*), Glob(*), Bash(*), Edit(*), Write(*)
|
||||
---
|
||||
|
||||
## Auto Mode
|
||||
|
||||
When `--yes` or `-y`: Auto-confirm strategy selection, use recommended mode, skip interactive rounds.
|
||||
|
||||
# Workflow Roadmap Command (/workflow:roadmap-with-file)
|
||||
|
||||
## Quick Start
|
||||
|
||||
```bash
|
||||
# Basic usage
|
||||
/workflow:roadmap-with-file "Implement user authentication system with OAuth and 2FA"
|
||||
|
||||
# With mode selection
|
||||
/workflow:roadmap-with-file -m progressive "Build real-time notification system" # MVP→iterations
|
||||
/workflow:roadmap-with-file -m direct "Refactor payment module" # Topological sequence
|
||||
/workflow:roadmap-with-file -m auto "Add data export feature" # Auto-select
|
||||
|
||||
# Continue existing session
|
||||
/workflow:roadmap-with-file --continue "auth system"
|
||||
|
||||
# Auto mode
|
||||
/workflow:roadmap-with-file -y "Implement caching layer"
|
||||
```
|
||||
|
||||
**Context Source**: cli-explore-agent (optional) + requirement analysis
|
||||
**Output Directory**: `.workflow/.roadmap/{session-id}/`
|
||||
**Core Output**: `roadmap.md` (single source, human-readable) + `issues.jsonl` (global, machine-executable)
|
||||
|
||||
## Output Artifacts
|
||||
|
||||
### Single Source of Truth
|
||||
|
||||
| Artifact | Purpose | Consumer |
|
||||
|----------|---------|----------|
|
||||
| `roadmap.md` | ⭐ Human-readable strategic roadmap with all context | Human review, team-planex handoff |
|
||||
| `.workflow/issues/issues.jsonl` | Global issue store (appended) | team-planex, issue commands |
|
||||
|
||||
### Why No Separate JSON Files?
|
||||
|
||||
| Original File | Why Removed | Where Content Goes |
|
||||
|---------------|-------------|-------------------|
|
||||
| `strategy-assessment.json` | Duplicates roadmap.md content | Embedded in `roadmap.md` Strategy Assessment section |
|
||||
| `exploration-codebase.json` | Single-use intermediate | Embedded in `roadmap.md` Codebase Context appendix |
|
||||
|
||||
## Overview
|
||||
|
||||
Strategic requirement roadmap with **iterative decomposition**. Creates a single `roadmap.md` that evolves through discussion, with issues persisted to global `issues.jsonl` for execution.
|
||||
|
||||
**Core workflow**: Understand → Decompose → Iterate → Validate → Handoff
|
||||
|
||||
```
|
||||
┌─────────────────────────────────────────────────────────────────────────┐
|
||||
│ ROADMAP ITERATIVE WORKFLOW │
|
||||
├─────────────────────────────────────────────────────────────────────────┤
|
||||
│ │
|
||||
│ Phase 1: Requirement Understanding & Strategy │
|
||||
│ ├─ Parse requirement: goal / constraints / stakeholders │
|
||||
│ ├─ Assess uncertainty level → recommend mode │
|
||||
│ ├─ User confirms strategy (-m skips, -y auto-selects) │
|
||||
│ └─ Initialize roadmap.md with Strategy Assessment │
|
||||
│ │
|
||||
│ Phase 2: Decomposition & Issue Creation │
|
||||
│ ├─ cli-roadmap-plan-agent executes decomposition │
|
||||
│ ├─ Progressive: 2-4 layers (MVP→Optimized) with convergence │
|
||||
│ ├─ Direct: Topological task sequence with convergence │
|
||||
│ ├─ Create issues via ccw issue create → issues.jsonl │
|
||||
│ └─ Update roadmap.md with Roadmap table + Issue references │
|
||||
│ │
|
||||
│ Phase 3: Iterative Refinement (Multi-Round) │
|
||||
│ ├─ Present roadmap to user │
|
||||
│ ├─ Feedback: Approve | Adjust Scope | Modify Convergence | Replan │
|
||||
│ ├─ Update roadmap.md with each round │
|
||||
│ └─ Repeat until approved (max 5 rounds) │
|
||||
│ │
|
||||
│ Phase 4: Handoff │
|
||||
│ ├─ Final roadmap.md with Issue ID references │
|
||||
│ ├─ Options: team-planex | first wave | view issues | done │
|
||||
│ └─ Issues ready in .workflow/issues/issues.jsonl │
|
||||
│ │
|
||||
└─────────────────────────────────────────────────────────────────────────┘
|
||||
```
|
||||
|
||||
## Dual Modes
|
||||
|
||||
| Mode | Strategy | Best For | Decomposition |
|
||||
|------|----------|----------|---------------|
|
||||
| **Progressive** | MVP → Usable → Refined → Optimized | High uncertainty, need validation | 2-4 layers, each with full convergence |
|
||||
| **Direct** | Topological task sequence | Clear requirements, confirmed tech | Tasks with explicit inputs/outputs |
|
||||
|
||||
**Auto-selection logic**:
|
||||
- ≥3 high uncertainty factors → Progressive
|
||||
- ≥3 low uncertainty factors → Direct
|
||||
- Otherwise → Ask user preference
|
||||
|
||||
## Output Structure
|
||||
|
||||
```
|
||||
.workflow/.roadmap/RMAP-{slug}-{date}/
|
||||
└── roadmap.md # ⭐ Single source of truth
|
||||
# - Strategy Assessment (embedded)
|
||||
# - Roadmap Table
|
||||
# - Convergence Criteria per Issue
|
||||
# - Codebase Context (appendix, if applicable)
|
||||
# - Iteration History
|
||||
|
||||
.workflow/issues/issues.jsonl # Global issue store (appended)
|
||||
# - One JSON object per line
|
||||
# - Consumed by team-planex, issue commands
|
||||
```
|
||||
|
||||
## roadmap.md Template
|
||||
|
||||
```markdown
|
||||
# Requirement Roadmap
|
||||
|
||||
**Session**: RMAP-{slug}-{date}
|
||||
**Requirement**: {requirement}
|
||||
**Strategy**: {progressive|direct}
|
||||
**Status**: {Planning|Refining|Ready}
|
||||
**Created**: {timestamp}
|
||||
|
||||
---
|
||||
|
||||
## Strategy Assessment
|
||||
|
||||
- **Uncertainty Level**: {high|medium|low}
|
||||
- **Decomposition Mode**: {progressive|direct}
|
||||
- **Assessment Basis**: {factors summary}
|
||||
- **Goal**: {extracted goal}
|
||||
- **Constraints**: {extracted constraints}
|
||||
- **Stakeholders**: {extracted stakeholders}
|
||||
|
||||
---
|
||||
|
||||
## Roadmap
|
||||
|
||||
### Progressive Mode
|
||||
| Wave | Issue ID | Layer | Goal | Priority | Dependencies |
|
||||
|------|----------|-------|------|----------|--------------|
|
||||
| 1 | ISS-xxx | MVP | ... | 2 | - |
|
||||
| 2 | ISS-yyy | Usable | ... | 3 | ISS-xxx |
|
||||
|
||||
### Direct Mode
|
||||
| Wave | Issue ID | Title | Type | Dependencies |
|
||||
|------|----------|-------|------|--------------|
|
||||
| 1 | ISS-xxx | ... | infrastructure | - |
|
||||
| 2 | ISS-yyy | ... | feature | ISS-xxx |
|
||||
|
||||
---
|
||||
|
||||
## Convergence Criteria
|
||||
|
||||
### ISS-xxx: {Issue Title}
|
||||
- **Criteria**: [testable conditions]
|
||||
- **Verification**: [executable steps/commands]
|
||||
- **Definition of Done**: [business language, non-technical]
|
||||
|
||||
### ISS-yyy: {Issue Title}
|
||||
...
|
||||
|
||||
---
|
||||
|
||||
## Risks
|
||||
|
||||
| Risk | Severity | Mitigation |
|
||||
|------|----------|------------|
|
||||
| ... | ... | ... |
|
||||
|
||||
---
|
||||
|
||||
## Iteration History
|
||||
|
||||
### Round 1 - {timestamp}
|
||||
**User Feedback**: {feedback summary}
|
||||
**Changes Made**: {adjustments}
|
||||
**Status**: {approved|continue iteration}
|
||||
|
||||
---
|
||||
|
||||
## Codebase Context (Optional)
|
||||
|
||||
*Included when codebase exploration was performed*
|
||||
|
||||
- **Relevant Modules**: [...]
|
||||
- **Existing Patterns**: [...]
|
||||
- **Integration Points**: [...]
|
||||
```
|
||||
|
||||
## Issues JSONL Specification
|
||||
|
||||
### Location & Format
|
||||
|
||||
```
|
||||
Path: .workflow/issues/issues.jsonl
|
||||
Format: JSONL (one complete JSON object per line)
|
||||
Encoding: UTF-8
|
||||
Mode: Append-only (new issues appended to end)
|
||||
```
|
||||
|
||||
### Record Schema
|
||||
|
||||
```json
|
||||
{
|
||||
"id": "ISS-YYYYMMDD-NNN",
|
||||
"title": "[LayerName] goal or [TaskType] title",
|
||||
"status": "pending",
|
||||
"priority": 2,
|
||||
"context": "Markdown with goal, scope, convergence, verification, DoD",
|
||||
"source": "text",
|
||||
"tags": ["roadmap", "progressive|direct", "wave-N", "layer-name"],
|
||||
"extended_context": {
|
||||
"notes": {
|
||||
"session": "RMAP-{slug}-{date}",
|
||||
"strategy": "progressive|direct",
|
||||
"wave": 1,
|
||||
"depends_on_issues": []
|
||||
}
|
||||
},
|
||||
"lifecycle_requirements": {
|
||||
"test_strategy": "unit",
|
||||
"regression_scope": "affected",
|
||||
"acceptance_type": "automated",
|
||||
"commit_strategy": "per-issue"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Query Interface
|
||||
|
||||
```bash
|
||||
# By ID (detail view)
|
||||
ccw issue list ISS-20260227-001
|
||||
|
||||
# List all with status filter
|
||||
ccw issue list --status planned,queued
|
||||
ccw issue list --brief # JSON minimal output
|
||||
|
||||
# Queue operations (wave-based execution)
|
||||
ccw issue queue list # List all queues
|
||||
ccw issue queue dag # Get dependency graph (JSON)
|
||||
ccw issue next --queue <queue-id> # Get next task
|
||||
|
||||
# Execute
|
||||
ccw issue queue add <issue-id> # Add to active queue
|
||||
ccw issue done <item-id> # Mark completed
|
||||
```
|
||||
|
||||
> **Note**: Issues are tagged with `wave-N` in `tags[]` field for filtering. Use `--brief` for programmatic parsing.
|
||||
|
||||
### Consumers
|
||||
|
||||
| Consumer | Usage |
|
||||
|----------|-------|
|
||||
| `team-planex` | Load by ID or tag, execute in wave order |
|
||||
| `issue-manage` | CRUD operations on issues |
|
||||
| `issue:execute` | DAG-based parallel execution |
|
||||
| `issue:queue` | Form execution queue from solutions |
|
||||
|
||||
## Implementation
|
||||
|
||||
### Session Initialization
|
||||
|
||||
```javascript
|
||||
const getUtc8ISOString = () => new Date(Date.now() + 8 * 60 * 60 * 1000).toISOString()
|
||||
|
||||
// Parse flags
|
||||
const autoYes = $ARGUMENTS.includes('--yes') || $ARGUMENTS.includes('-y')
|
||||
const continueMode = $ARGUMENTS.includes('--continue') || $ARGUMENTS.includes('-c')
|
||||
const modeMatch = $ARGUMENTS.match(/(?:--mode|-m)\s+(progressive|direct|auto)/)
|
||||
const requestedMode = modeMatch ? modeMatch[1] : 'auto'
|
||||
|
||||
// Clean requirement text
|
||||
const requirement = $ARGUMENTS
|
||||
.replace(/--yes|-y|--continue|-c|--mode\s+\w+|-m\s+\w+/g, '')
|
||||
.trim()
|
||||
|
||||
const slug = requirement.toLowerCase()
|
||||
.replace(/[^a-z0-9\u4e00-\u9fa5]+/g, '-')
|
||||
.substring(0, 40)
|
||||
const dateStr = getUtc8ISOString().substring(0, 10)
|
||||
const sessionId = `RMAP-${slug}-${dateStr}`
|
||||
const sessionFolder = `.workflow/.roadmap/${sessionId}`
|
||||
|
||||
// Auto-detect continue
|
||||
if (continueMode || file_exists(`${sessionFolder}/roadmap.md`)) {
|
||||
// Resume existing session
|
||||
}
|
||||
Bash(`mkdir -p ${sessionFolder}`)
|
||||
```
|
||||
|
||||
### Phase 1: Requirement Understanding & Strategy
|
||||
|
||||
**Objective**: Parse requirement, assess uncertainty, select decomposition strategy, initialize roadmap.md.
|
||||
|
||||
**Steps**:
|
||||
|
||||
1. **Parse Requirement**
|
||||
- Extract: goal, constraints, stakeholders, keywords
|
||||
|
||||
2. **Assess Uncertainty**
|
||||
```javascript
|
||||
const uncertaintyFactors = {
|
||||
scope_clarity: 'low|medium|high',
|
||||
technical_risk: 'low|medium|high',
|
||||
dependency_unknown: 'low|medium|high',
|
||||
domain_familiarity: 'low|medium|high',
|
||||
requirement_stability: 'low|medium|high'
|
||||
}
|
||||
// ≥3 high → progressive, ≥3 low → direct, else → ask
|
||||
```
|
||||
|
||||
3. **Strategy Selection** (skip if `-m` specified or autoYes)
|
||||
```javascript
|
||||
AskUserQuestion({
|
||||
questions: [{
|
||||
question: `Decomposition strategy:\nUncertainty: ${uncertaintyLevel}\nRecommended: ${recommendedMode}`,
|
||||
header: "Strategy",
|
||||
multiSelect: false,
|
||||
options: [
|
||||
{ label: recommendedMode === 'progressive' ? "Progressive (Recommended)" : "Progressive",
|
||||
description: "MVP→iterations, validate core first" },
|
||||
{ label: recommendedMode === 'direct' ? "Direct (Recommended)" : "Direct",
|
||||
description: "Topological task sequence, clear dependencies" }
|
||||
]
|
||||
}]
|
||||
})
|
||||
```
|
||||
|
||||
4. **Initialize roadmap.md** with Strategy Assessment section
|
||||
|
||||
**Success Criteria**:
|
||||
- roadmap.md created with Strategy Assessment
|
||||
- Strategy selected (progressive or direct)
|
||||
- Uncertainty factors documented
|
||||
|
||||
### Phase 2: Decomposition & Issue Creation
|
||||
|
||||
**Objective**: Execute decomposition via `cli-roadmap-plan-agent`, create issues, update roadmap.md.
|
||||
|
||||
**Agent**: `cli-roadmap-plan-agent`
|
||||
|
||||
**Agent Tasks**:
|
||||
1. Analyze requirement with strategy context
|
||||
2. Execute CLI-assisted decomposition (Gemini → Qwen fallback)
|
||||
3. Create issues via `ccw issue create`
|
||||
4. Generate roadmap table with Issue ID references
|
||||
5. Update roadmap.md
|
||||
|
||||
**Agent Prompt Template**:
|
||||
```javascript
|
||||
Agent({
|
||||
subagent_type: "cli-roadmap-plan-agent",
|
||||
run_in_background: false,
|
||||
description: `Roadmap decomposition: ${slug}`,
|
||||
prompt: `
|
||||
## Roadmap Decomposition Agent
|
||||
|
||||
### Input Context
|
||||
- **Requirement**: ${requirement}
|
||||
- **Strategy**: ${selectedMode}
|
||||
- **Session**: ${sessionId}
|
||||
- **Folder**: ${sessionFolder}
|
||||
|
||||
### Mode-Specific Requirements
|
||||
|
||||
${selectedMode === 'progressive' ? `**Progressive Mode**:
|
||||
- 2-4 layers: MVP / Usable / Refined / Optimized
|
||||
- Each layer: goal, scope, excludes, convergence, risks, effort
|
||||
- L0 (MVP) must be self-contained, no dependencies
|
||||
- Scope: each feature in exactly ONE layer (no overlap)` :
|
||||
|
||||
`**Direct Mode**:
|
||||
- Topologically-sorted task sequence
|
||||
- Each task: title, type, scope, inputs, outputs, convergence, depends_on
|
||||
- Inputs from preceding outputs or existing resources
|
||||
- parallel_group for truly independent tasks`}
|
||||
|
||||
### Convergence Quality Requirements
|
||||
- criteria[]: MUST be testable
|
||||
- verification: MUST be executable
|
||||
- definition_of_done: MUST use business language
|
||||
|
||||
### Output
|
||||
1. **${sessionFolder}/roadmap.md** - Update with Roadmap table + Convergence sections
|
||||
2. **Append to .workflow/issues/issues.jsonl** via ccw issue create
|
||||
|
||||
### CLI Configuration
|
||||
- Primary: gemini, Fallback: qwen, Timeout: 60000ms
|
||||
`
|
||||
})
|
||||
```
|
||||
|
||||
**Success Criteria**:
|
||||
- Issues created in `.workflow/issues/issues.jsonl`
|
||||
- roadmap.md updated with Issue references
|
||||
- No circular dependencies
|
||||
- Convergence criteria testable
|
||||
|
||||
### Phase 3: Iterative Refinement
|
||||
|
||||
**Objective**: Multi-round user feedback to refine roadmap.
|
||||
|
||||
**Workflow Steps**:
|
||||
|
||||
1. **Present Roadmap**
|
||||
- Display Roadmap table + key Convergence criteria
|
||||
- Show issue count and wave breakdown
|
||||
|
||||
2. **Gather Feedback** (skip if autoYes)
|
||||
```javascript
|
||||
const feedback = AskUserQuestion({
|
||||
questions: [{
|
||||
question: `Roadmap validation (round ${round}):\n${issueCount} issues across ${waveCount} waves. Feedback?`,
|
||||
header: "Feedback",
|
||||
multiSelect: false,
|
||||
options: [
|
||||
{ label: "Approve", description: "Proceed to handoff" },
|
||||
{ label: "Adjust Scope", description: "Modify issue scopes" },
|
||||
{ label: "Modify Convergence", description: "Refine criteria/verification" },
|
||||
{ label: "Re-decompose", description: "Change strategy/layering" }
|
||||
]
|
||||
}]
|
||||
})
|
||||
```
|
||||
|
||||
3. **Process Feedback**
|
||||
- **Approve**: Exit loop, proceed to Phase 4
|
||||
- **Adjust Scope**: Modify issue context, update roadmap.md
|
||||
- **Modify Convergence**: Refine criteria/verification, update roadmap.md
|
||||
- **Re-decompose**: Return to Phase 2 with new strategy
|
||||
|
||||
4. **Update roadmap.md**
|
||||
- Append to Iteration History section
|
||||
- Update Roadmap table if changed
|
||||
- Increment round counter
|
||||
|
||||
5. **Loop** (max 5 rounds, then force proceed)
|
||||
|
||||
**Success Criteria**:
|
||||
- User approved OR max rounds reached
|
||||
- All changes recorded in Iteration History
|
||||
- roadmap.md reflects final state
|
||||
|
||||
### Phase 4: Handoff
|
||||
|
||||
**Objective**: Present final roadmap, offer execution options.
|
||||
|
||||
**Steps**:
|
||||
|
||||
1. **Display Summary**
|
||||
```markdown
|
||||
## Roadmap Complete
|
||||
|
||||
- **Session**: RMAP-{slug}-{date}
|
||||
- **Strategy**: {progressive|direct}
|
||||
- **Issues Created**: {count} across {waves} waves
|
||||
- **Roadmap**: .workflow/.roadmap/RMAP-{slug}-{date}/roadmap.md
|
||||
|
||||
| Wave | Issue Count | Layer/Type |
|
||||
|------|-------------|------------|
|
||||
| 1 | 2 | MVP / infrastructure |
|
||||
| 2 | 3 | Usable / feature |
|
||||
```
|
||||
|
||||
2. **Offer Options** (skip if autoYes)
|
||||
```javascript
|
||||
AskUserQuestion({
|
||||
questions: [{
|
||||
question: `${issueIds.length} issues ready. Next step:`,
|
||||
header: "Next Step",
|
||||
multiSelect: false,
|
||||
options: [
|
||||
{ label: "Execute with team-planex (Recommended)",
|
||||
description: `Run all ${issueIds.length} issues via team-planex` },
|
||||
{ label: "Execute first wave",
|
||||
description: "Run wave-1 issues only" },
|
||||
{ label: "View issues",
|
||||
description: "Display issue details from issues.jsonl" },
|
||||
{ label: "Done",
|
||||
description: "Save and exit, execute later" }
|
||||
]
|
||||
}]
|
||||
})
|
||||
```
|
||||
|
||||
3. **Execute Selection**
|
||||
| Selection | Action |
|
||||
|-----------|--------|
|
||||
| Execute with team-planex | `Skill(skill="team-planex", args="${issueIds.join(' ')}")` |
|
||||
| Execute first wave | Filter by `wave-1` tag, pass to team-planex |
|
||||
| View issues | Display from `.workflow/issues/issues.jsonl` |
|
||||
| Done | Output paths, end |
|
||||
|
||||
## Configuration
|
||||
|
||||
| Flag | Default | Description |
|
||||
|------|---------|-------------|
|
||||
| `-y, --yes` | false | Auto-confirm all decisions |
|
||||
| `-c, --continue` | false | Continue existing session |
|
||||
| `-m, --mode` | auto | Strategy: progressive / direct / auto |
|
||||
|
||||
**Session ID format**: `RMAP-{slug}-{YYYY-MM-DD}`
|
||||
|
||||
## Error Handling
|
||||
|
||||
| Error | Resolution |
|
||||
|-------|------------|
|
||||
| cli-roadmap-plan-agent fails | Retry once, fallback to manual decomposition |
|
||||
| No codebase | Skip exploration, pure requirement decomposition |
|
||||
| Circular dependency detected | Prompt user, re-decompose |
|
||||
| User feedback timeout | Save roadmap.md, show `--continue` command |
|
||||
| Max rounds reached | Force proceed with current roadmap |
|
||||
| Session folder conflict | Append timestamp suffix |
|
||||
|
||||
## Best Practices
|
||||
|
||||
1. **Clear Requirements**: Detailed description → better decomposition
|
||||
2. **Iterate on Roadmap**: Use feedback rounds to refine convergence criteria
|
||||
3. **Testable Convergence**: criteria = assertions, DoD = business language
|
||||
4. **Use Continue Mode**: Resume to iterate on existing roadmap
|
||||
5. **Wave Execution**: Start with wave-1 (MVP) to validate before full execution
|
||||
|
||||
## Usage Recommendations
|
||||
|
||||
**When to Use Roadmap vs Other Commands:**
|
||||
|
||||
| Scenario | Recommended Command |
|
||||
|----------|-------------------|
|
||||
| Strategic planning, need issue tracking | `/workflow:roadmap-with-file` |
|
||||
| Quick task breakdown, immediate execution | `/workflow-lite-plan` |
|
||||
| Collaborative multi-agent planning | `/workflow:collaborative-plan-with-file` |
|
||||
| Full specification documents | `spec-generator` skill |
|
||||
| Code implementation from existing plan | `/workflow-lite-plan` (Phase 1: plan → Phase 2: execute) |
|
||||
|
||||
---
|
||||
|
||||
**Now execute roadmap-with-file for**: $ARGUMENTS
|
||||
@@ -109,79 +109,16 @@ rm -f .workflow/archives/$SESSION_ID/.archiving
|
||||
Manifest: Updated with N total sessions
|
||||
```
|
||||
|
||||
### Phase 4: Update project-tech.json (Optional)
|
||||
### Phase 4: Auto-Sync Project State
|
||||
|
||||
**Skip if**: `.workflow/project-tech.json` doesn't exist
|
||||
Execute `/workflow:session:sync -y "{description}"` to update both `specs/*.md` and `project-tech.json` from session context.
|
||||
|
||||
```bash
|
||||
# Check
|
||||
test -f .workflow/project-tech.json || echo "SKIP"
|
||||
```
|
||||
|
||||
**If exists**, add feature entry:
|
||||
|
||||
```json
|
||||
{
|
||||
"id": "<slugified title>",
|
||||
"title": "<from IMPL_PLAN.md>",
|
||||
"status": "completed",
|
||||
"tags": ["<from Phase 2>"],
|
||||
"timeline": { "implemented_at": "<date>" },
|
||||
"traceability": { "session_id": "<SESSION_ID>", "archive_path": "<path>" }
|
||||
}
|
||||
```
|
||||
|
||||
**Output**:
|
||||
```
|
||||
✓ Feature added to project registry
|
||||
```
|
||||
|
||||
### Phase 5: Ask About Solidify (Always)
|
||||
|
||||
After successful archival, prompt user to capture learnings:
|
||||
|
||||
```javascript
|
||||
// Parse --yes flag
|
||||
const autoYes = $ARGUMENTS.includes('--yes') || $ARGUMENTS.includes('-y')
|
||||
|
||||
if (autoYes) {
|
||||
// Auto mode: Skip solidify
|
||||
console.log(`[--yes] Auto-selecting: Skip solidify`)
|
||||
console.log(`Session archived successfully.`)
|
||||
// Done - no solidify
|
||||
} else {
|
||||
// Interactive mode: Ask user
|
||||
AskUserQuestion({
|
||||
questions: [{
|
||||
question: "Would you like to solidify learnings from this session into project guidelines?",
|
||||
header: "Solidify",
|
||||
options: [
|
||||
{ label: "Yes, solidify now", description: "Extract learnings and update project-guidelines.json" },
|
||||
{ label: "Skip", description: "Archive complete, no learnings to capture" }
|
||||
],
|
||||
multiSelect: false
|
||||
}]
|
||||
})
|
||||
|
||||
// **If "Yes, solidify now"**: Execute `/workflow:session:solidify` with the archived session ID.
|
||||
}
|
||||
```
|
||||
Description 取自 Phase 2 的 `workflow-session.json` description 字段。
|
||||
|
||||
## Auto Mode Defaults
|
||||
|
||||
When `--yes` or `-y` flag is used:
|
||||
- **Solidify Learnings**: Auto-selected "Skip" (archive only, no solidify)
|
||||
|
||||
**Flag Parsing**:
|
||||
```javascript
|
||||
const autoYes = $ARGUMENTS.includes('--yes') || $ARGUMENTS.includes('-y')
|
||||
```
|
||||
|
||||
**Output**:
|
||||
```
|
||||
Session archived successfully.
|
||||
→ Run /workflow:session:solidify to capture learnings (recommended)
|
||||
```
|
||||
- **Sync**: Auto-executed with `-y` (no confirmation)
|
||||
|
||||
## Error Recovery
|
||||
|
||||
@@ -198,6 +135,5 @@ Session archived successfully.
|
||||
Phase 1: find session → create .archiving marker
|
||||
Phase 2: read key files → build manifest entry (no writes)
|
||||
Phase 3: mkdir → mv → update manifest.json → rm marker
|
||||
Phase 4: update project-tech.json features array (optional)
|
||||
Phase 5: ask user → solidify learnings (optional)
|
||||
Phase 4: /workflow:session:sync -y → update specs/*.md + project-tech
|
||||
```
|
||||
|
||||
@@ -57,5 +57,5 @@ Session WFS-user-auth resumed
|
||||
- Status: active
|
||||
- Paused at: 2025-09-15T14:30:00Z
|
||||
- Resumed at: 2025-09-15T15:45:00Z
|
||||
- Ready for: /workflow:execute
|
||||
- Ready for: /workflow-execute
|
||||
```
|
||||
@@ -1,465 +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 `.workflow/project-guidelines.json`. 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
|
||||
|
||||
```bash
|
||||
bash(test -f .workflow/project-guidelines.json && echo "EXISTS" || echo "NOT_FOUND")
|
||||
```
|
||||
|
||||
**If NOT_FOUND**, create scaffold:
|
||||
|
||||
```javascript
|
||||
const scaffold = {
|
||||
conventions: {
|
||||
coding_style: [],
|
||||
naming_patterns: [],
|
||||
file_structure: [],
|
||||
documentation: []
|
||||
},
|
||||
constraints: {
|
||||
architecture: [],
|
||||
tech_stack: [],
|
||||
performance: [],
|
||||
security: []
|
||||
},
|
||||
quality_rules: [],
|
||||
learnings: [],
|
||||
_metadata: {
|
||||
created_at: new Date().toISOString(),
|
||||
version: "1.0.0"
|
||||
}
|
||||
};
|
||||
|
||||
Write('.workflow/project-guidelines.json', JSON.stringify(scaffold, null, 2));
|
||||
```
|
||||
|
||||
### 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 Guidelines File
|
||||
|
||||
```javascript
|
||||
const guidelines = JSON.parse(Read('.workflow/project-guidelines.json'));
|
||||
|
||||
if (type === 'convention') {
|
||||
if (!guidelines.conventions[category]) {
|
||||
guidelines.conventions[category] = [];
|
||||
}
|
||||
if (!guidelines.conventions[category].includes(rule)) {
|
||||
guidelines.conventions[category].push(rule);
|
||||
}
|
||||
} else if (type === 'constraint') {
|
||||
if (!guidelines.constraints[category]) {
|
||||
guidelines.constraints[category] = [];
|
||||
}
|
||||
if (!guidelines.constraints[category].includes(rule)) {
|
||||
guidelines.constraints[category].push(rule);
|
||||
}
|
||||
} else if (type === 'learning') {
|
||||
guidelines.learnings.push(buildEntry(rule, type, category, sessionId));
|
||||
}
|
||||
|
||||
guidelines._metadata.updated_at = new Date().toISOString();
|
||||
guidelines._metadata.last_solidified_by = sessionId;
|
||||
|
||||
Write('.workflow/project-guidelines.json', JSON.stringify(guidelines, null, 2));
|
||||
```
|
||||
|
||||
### Step 5: Display Confirmation
|
||||
|
||||
```
|
||||
Guideline solidified
|
||||
|
||||
Type: ${type}
|
||||
Category: ${category}
|
||||
Rule: "${rule}"
|
||||
|
||||
Location: .workflow/project-guidelines.json -> ${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 `project-guidelines.json`:
|
||||
```json
|
||||
{
|
||||
"conventions": {
|
||||
"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:
|
||||
```json
|
||||
{
|
||||
"constraints": {
|
||||
"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:
|
||||
```json
|
||||
{
|
||||
"learnings": [
|
||||
{
|
||||
"date": "2024-12-28",
|
||||
"session_id": "WFS-auth-feature",
|
||||
"insight": "Cache invalidation requires event sourcing for consistency",
|
||||
"category": "architecture"
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
### 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 `project-guidelines.json` 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 project-guidelines.json scaffold if missing
|
||||
@@ -27,7 +27,7 @@ The `--type` parameter classifies sessions for CCW dashboard organization:
|
||||
|------|-------------|-------------|
|
||||
| `workflow` | Standard implementation (default) | `workflow-plan` skill |
|
||||
| `review` | Code review sessions | `review-cycle` skill |
|
||||
| `tdd` | TDD-based development | `workflow-tdd` skill |
|
||||
| `tdd` | TDD-based development | `workflow-tdd-plan` skill |
|
||||
| `test` | Test generation/fix sessions | `workflow-test-fix` skill |
|
||||
| `docs` | Documentation sessions | `memory-manage` skill |
|
||||
|
||||
@@ -38,31 +38,31 @@ 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
|
||||
# Check if project state exists (both files required)
|
||||
bash(test -f .workflow/project-tech.json && echo "TECH_EXISTS" || echo "TECH_NOT_FOUND")
|
||||
bash(test -f .workflow/project-guidelines.json && echo "GUIDELINES_EXISTS" || echo "GUIDELINES_NOT_FOUND")
|
||||
bash(test -f .ccw/specs/*.md && echo "GUIDELINES_EXISTS" || echo "GUIDELINES_NOT_FOUND")
|
||||
```
|
||||
|
||||
**If either NOT_FOUND**, delegate to `/workflow:init`:
|
||||
**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 project-guidelines.json will be created
|
||||
// project-tech.json and specs/*.md will be created
|
||||
```
|
||||
|
||||
**Output**:
|
||||
- If BOTH_EXIST: `PROJECT_STATE: initialized`
|
||||
- If NOT_FOUND: Calls `/workflow:init` → creates:
|
||||
- If NOT_FOUND: Calls `/workflow:spec:setup` → creates:
|
||||
- `.workflow/project-tech.json` with full technical analysis
|
||||
- `.workflow/project-guidelines.json` with empty scaffold
|
||||
- `.ccw/specs/*.md` with empty scaffold
|
||||
|
||||
**Note**: `/workflow:init` uses cli-explore-agent to build comprehensive project understanding (technology stack, architecture, key components). This step runs once per project. Subsequent executions skip initialization.
|
||||
**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)
|
||||
|
||||
|
||||
201
.claude/commands/workflow/session/sync.md
Normal file
201
.claude/commands/workflow/session/sync.md
Normal file
@@ -0,0 +1,201 @@
|
||||
---
|
||||
name: sync
|
||||
description: Quick-sync session work to specs/*.md and project-tech
|
||||
argument-hint: "[-y|--yes] [\"what was done\"]"
|
||||
allowed-tools: Bash(*), Read(*), Write(*), Edit(*)
|
||||
---
|
||||
|
||||
# Session Sync (/workflow:session:sync)
|
||||
|
||||
One-shot update `specs/*.md` + `project-tech.json` from current session context.
|
||||
|
||||
**Design**: Scan context → extract → write. No interactive wizards.
|
||||
|
||||
## Auto Mode
|
||||
|
||||
`--yes` or `-y`: Skip confirmation, auto-write both files.
|
||||
|
||||
## Process
|
||||
|
||||
```
|
||||
Step 1: Gather Context
|
||||
├─ git diff --stat HEAD~3..HEAD (recent changes)
|
||||
├─ Active session folder (.workflow/.lite-plan/*) if exists
|
||||
└─ User summary ($ARGUMENTS or auto-generate from git log)
|
||||
|
||||
Step 2: Extract Updates
|
||||
├─ Guidelines: conventions / constraints / learnings
|
||||
└─ Tech: development_index entry
|
||||
|
||||
Step 3: Preview & Confirm (skip if --yes)
|
||||
|
||||
Step 4: Write both files
|
||||
|
||||
Step 5: One-line confirmation
|
||||
```
|
||||
|
||||
## Step 1: Gather Context
|
||||
|
||||
```javascript
|
||||
const autoYes = $ARGUMENTS.includes('--yes') || $ARGUMENTS.includes('-y')
|
||||
const userSummary = $ARGUMENTS.replace(/--yes|-y/g, '').trim()
|
||||
|
||||
// Recent changes
|
||||
const gitStat = Bash('git diff --stat HEAD~3..HEAD 2>/dev/null || git diff --stat HEAD 2>/dev/null')
|
||||
const gitLog = Bash('git log --oneline -5')
|
||||
|
||||
// Active session (optional)
|
||||
const sessionFolders = Glob('.workflow/.lite-plan/*/plan.json')
|
||||
let sessionContext = null
|
||||
if (sessionFolders.length > 0) {
|
||||
const latest = sessionFolders[sessionFolders.length - 1]
|
||||
sessionContext = JSON.parse(Read(latest))
|
||||
}
|
||||
|
||||
// Build summary
|
||||
const summary = userSummary
|
||||
|| sessionContext?.summary
|
||||
|| gitLog.split('\n')[0].replace(/^[a-f0-9]+ /, '')
|
||||
```
|
||||
|
||||
## Step 2: Extract Updates
|
||||
|
||||
Analyze context and produce two update payloads. Use LLM reasoning (current agent) — no CLI calls.
|
||||
|
||||
```javascript
|
||||
// ── Guidelines extraction ──
|
||||
// Scan git diff + session for:
|
||||
// - New patterns adopted → convention
|
||||
// - Restrictions discovered → constraint
|
||||
// - Surprises / gotchas → learning
|
||||
//
|
||||
// Output: array of { type, category, text }
|
||||
// RULE: Only extract genuinely reusable insights. Skip trivial/obvious items.
|
||||
// RULE: Deduplicate against existing guidelines before adding.
|
||||
|
||||
// Load existing specs via ccw spec load
|
||||
const existingSpecs = Bash('ccw spec load --dimension specs 2>/dev/null || echo ""')
|
||||
const guidelineUpdates = [] // populated by agent analysis
|
||||
|
||||
// ── Tech extraction ──
|
||||
// Build one development_index entry from session work
|
||||
|
||||
function detectCategory(text) {
|
||||
text = text.toLowerCase()
|
||||
if (/\b(fix|bug|error|crash)\b/.test(text)) return 'bugfix'
|
||||
if (/\b(refactor|cleanup|reorganize)\b/.test(text)) return 'refactor'
|
||||
if (/\b(doc|readme|comment)\b/.test(text)) return 'docs'
|
||||
if (/\b(add|new|create|implement)\b/.test(text)) return 'feature'
|
||||
return 'enhancement'
|
||||
}
|
||||
|
||||
function detectSubFeature(gitStat) {
|
||||
// Most-changed directory from git diff --stat
|
||||
const dirs = gitStat.match(/\S+\//g) || []
|
||||
const counts = {}
|
||||
dirs.forEach(d => {
|
||||
const seg = d.split('/').filter(Boolean).slice(-2, -1)[0] || 'general'
|
||||
counts[seg] = (counts[seg] || 0) + 1
|
||||
})
|
||||
return Object.entries(counts).sort((a, b) => b[1] - a[1])[0]?.[0] || 'general'
|
||||
}
|
||||
|
||||
const techEntry = {
|
||||
title: summary.slice(0, 60),
|
||||
sub_feature: detectSubFeature(gitStat),
|
||||
date: new Date().toISOString().split('T')[0],
|
||||
description: summary.slice(0, 100),
|
||||
status: 'completed',
|
||||
session_id: sessionContext ? sessionFolders[sessionFolders.length - 1].match(/lite-plan\/([^/]+)/)?.[1] : null
|
||||
}
|
||||
```
|
||||
|
||||
## Step 3: Preview & Confirm
|
||||
|
||||
```javascript
|
||||
// Show preview
|
||||
console.log(`
|
||||
── Sync Preview ──
|
||||
|
||||
Guidelines (${guidelineUpdates.length} items):
|
||||
${guidelineUpdates.map(g => ` [${g.type}/${g.category}] ${g.text}`).join('\n') || ' (none)'}
|
||||
|
||||
Tech [${detectCategory(summary)}]:
|
||||
${techEntry.title}
|
||||
|
||||
Target files:
|
||||
.ccw/specs/*.md
|
||||
.workflow/project-tech.json
|
||||
`)
|
||||
|
||||
if (!autoYes) {
|
||||
const confirm = AskUserQuestion("Apply these updates? (modify/skip items if needed)")
|
||||
// User can say "skip guidelines" or "change category to bugfix" etc.
|
||||
}
|
||||
```
|
||||
|
||||
## Step 4: Write
|
||||
|
||||
```javascript
|
||||
// ── Update specs/*.md ──
|
||||
// Uses .ccw/specs/ directory (same as frontend/backend spec-index-builder)
|
||||
if (guidelineUpdates.length > 0) {
|
||||
// Map guideline types to spec files
|
||||
const specFileMap = {
|
||||
convention: '.ccw/specs/coding-conventions.md',
|
||||
constraint: '.ccw/specs/architecture-constraints.md',
|
||||
learning: '.ccw/specs/coding-conventions.md' // learnings appended to conventions
|
||||
}
|
||||
|
||||
for (const g of guidelineUpdates) {
|
||||
const targetFile = specFileMap[g.type]
|
||||
const existing = Read(targetFile)
|
||||
const ruleText = g.type === 'learning'
|
||||
? `- [${g.category}] ${g.text} (learned: ${new Date().toISOString().split('T')[0]})`
|
||||
: `- [${g.category}] ${g.text}`
|
||||
|
||||
// Deduplicate: skip if text already in file
|
||||
if (!existing.includes(g.text)) {
|
||||
const newContent = existing.trimEnd() + '\n' + ruleText + '\n'
|
||||
Write(targetFile, newContent)
|
||||
}
|
||||
}
|
||||
|
||||
// Rebuild spec index after writing
|
||||
Bash('ccw spec rebuild')
|
||||
}
|
||||
|
||||
// ── Update project-tech.json ──
|
||||
const techPath = '.workflow/project-tech.json'
|
||||
const tech = JSON.parse(Read(techPath))
|
||||
|
||||
if (!tech.development_index) {
|
||||
tech.development_index = { feature: [], enhancement: [], bugfix: [], refactor: [], docs: [] }
|
||||
}
|
||||
|
||||
const category = detectCategory(summary)
|
||||
tech.development_index[category].push(techEntry)
|
||||
tech._metadata.last_updated = new Date().toISOString()
|
||||
|
||||
Write(techPath, JSON.stringify(tech, null, 2))
|
||||
```
|
||||
|
||||
## Step 5: Confirm
|
||||
|
||||
```
|
||||
✓ Synced: ${guidelineUpdates.length} guidelines + 1 tech entry [${category}]
|
||||
```
|
||||
|
||||
## Error Handling
|
||||
|
||||
| Error | Resolution |
|
||||
|-------|------------|
|
||||
| File missing | Create scaffold (same as 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:spec:setup` - Initialize project with specs scaffold
|
||||
- `/workflow:spec:add` - Interactive wizard to create individual specs with scope selection
|
||||
644
.claude/commands/workflow/spec/add.md
Normal file
644
.claude/commands/workflow/spec/add.md
Normal 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
|
||||
650
.claude/commands/workflow/spec/setup.md
Normal file
650
.claude/commands/workflow/spec/setup.md
Normal file
@@ -0,0 +1,650 @@
|
||||
---
|
||||
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:spec:setup
|
||||
- /workflow:spec:setup --regenerate
|
||||
- /workflow:spec:setup --skip-specs
|
||||
- /workflow:spec:setup --reset
|
||||
---
|
||||
|
||||
# Workflow Spec Setup Command (/workflow:spec:setup)
|
||||
|
||||
## Overview
|
||||
|
||||
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 other workflow commands. Upon completion, return immediately to continue the calling workflow without interrupting the task flow.
|
||||
|
||||
## Usage
|
||||
```bash
|
||||
/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
|
||||
|
||||
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
|
||||
|
||||
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
|
||||
|
||||
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')
|
||||
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 BOTH_EXIST and no --regenerate and no --reset**: Exit early
|
||||
```
|
||||
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
|
||||
```
|
||||
|
||||
### 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 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
|
||||
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 && !reset) {
|
||||
AskUserQuestion({
|
||||
questions: [{
|
||||
question: "Project guidelines already contain entries. How would you like to proceed?",
|
||||
header: "Mode",
|
||||
multiSelect: false,
|
||||
options: [
|
||||
{ label: "Append", description: "Keep existing entries and add new ones from the wizard" },
|
||||
{ label: "Reset", description: "Clear all existing entries and start fresh" },
|
||||
{ label: "Cancel", description: "Exit without changes" }
|
||||
]
|
||||
}]
|
||||
})
|
||||
// If Cancel → exit
|
||||
// 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 5.1: Load Project Context
|
||||
|
||||
```javascript
|
||||
// Load project context via ccw spec load for planning context
|
||||
const projectContext = Bash('ccw spec load --category planning 2>/dev/null || echo "{}"')
|
||||
const specData = JSON.parse(projectContext)
|
||||
|
||||
// Extract key info from loaded specs for generating smart questions
|
||||
const languages = specData.overview?.technology_stack?.languages || []
|
||||
const primaryLang = languages.find(l => l.primary)?.name || languages[0]?.name || 'Unknown'
|
||||
const frameworks = specData.overview?.technology_stack?.frameworks || []
|
||||
const testFrameworks = specData.overview?.technology_stack?.test_frameworks || []
|
||||
const archStyle = specData.overview?.architecture?.style || 'Unknown'
|
||||
const archPatterns = specData.overview?.architecture?.patterns || []
|
||||
const buildTools = specData.overview?.technology_stack?.build_tools || []
|
||||
```
|
||||
|
||||
#### Step 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.
|
||||
|
||||
---
|
||||
|
||||
##### Round 1: Coding Conventions
|
||||
|
||||
Generate options dynamically based on detected language/framework:
|
||||
|
||||
```javascript
|
||||
// Build language-specific coding style options
|
||||
const codingStyleOptions = []
|
||||
|
||||
if (['TypeScript', 'JavaScript'].includes(primaryLang)) {
|
||||
codingStyleOptions.push(
|
||||
{ label: "Strict TypeScript", description: "Use strict mode, no 'any' type, explicit return types for public APIs" },
|
||||
{ label: "Functional style", description: "Prefer pure functions, immutability, avoid class-based patterns where possible" },
|
||||
{ label: "Const over let", description: "Always use const; only use let when reassignment is truly needed" }
|
||||
)
|
||||
} else if (primaryLang === 'Python') {
|
||||
codingStyleOptions.push(
|
||||
{ label: "Type hints", description: "Use type hints for all function signatures and class attributes" },
|
||||
{ label: "Functional style", description: "Prefer pure functions, list comprehensions, avoid mutable state" },
|
||||
{ label: "PEP 8 strict", description: "Strict PEP 8 compliance with max line length 88 (Black formatter)" }
|
||||
)
|
||||
} else if (primaryLang === 'Go') {
|
||||
codingStyleOptions.push(
|
||||
{ label: "Error wrapping", description: "Always wrap errors with context using fmt.Errorf with %w" },
|
||||
{ label: "Interface first", description: "Define interfaces at the consumer side, not the provider" },
|
||||
{ label: "Table-driven tests", description: "Use table-driven test pattern for all unit tests" }
|
||||
)
|
||||
}
|
||||
// Add universal options
|
||||
codingStyleOptions.push(
|
||||
{ label: "Early returns", description: "Prefer early returns / guard clauses over deep nesting" }
|
||||
)
|
||||
|
||||
AskUserQuestion({
|
||||
questions: [
|
||||
{
|
||||
question: `Your project uses ${primaryLang}. Which coding style conventions do you follow?`,
|
||||
header: "Coding Style",
|
||||
multiSelect: true,
|
||||
options: codingStyleOptions.slice(0, 4) // Max 4 options
|
||||
},
|
||||
{
|
||||
question: `What naming conventions does your ${primaryLang} project use?`,
|
||||
header: "Naming",
|
||||
multiSelect: true,
|
||||
options: [
|
||||
{ label: "camelCase variables", description: "Variables and functions use camelCase (e.g., getUserName)" },
|
||||
{ label: "PascalCase types", description: "Classes, interfaces, type aliases use PascalCase (e.g., UserService)" },
|
||||
{ label: "UPPER_SNAKE constants", description: "Constants use UPPER_SNAKE_CASE (e.g., MAX_RETRIES)" },
|
||||
{ label: "Prefix interfaces", description: "Prefix interfaces with 'I' (e.g., IUserService)" }
|
||||
]
|
||||
}
|
||||
]
|
||||
})
|
||||
```
|
||||
|
||||
**Process Round 1 answers** -> add to `conventions.coding_style` and `conventions.naming_patterns` arrays.
|
||||
|
||||
---
|
||||
|
||||
##### Round 2: File Structure & Documentation
|
||||
|
||||
```javascript
|
||||
AskUserQuestion({
|
||||
questions: [
|
||||
{
|
||||
question: `Your project has a ${archStyle} architecture. What file organization rules apply?`,
|
||||
header: "File Structure",
|
||||
multiSelect: true,
|
||||
options: [
|
||||
{ label: "Co-located tests", description: "Test files live next to source files (e.g., foo.ts + foo.test.ts)" },
|
||||
{ label: "Separate test dir", description: "Tests in a dedicated __tests__ or tests/ directory" },
|
||||
{ label: "One export per file", description: "Each file exports a single main component/class/function" },
|
||||
{ label: "Index barrels", description: "Use index.ts barrel files for clean imports from directories" }
|
||||
]
|
||||
},
|
||||
{
|
||||
question: "What documentation standards does your project follow?",
|
||||
header: "Documentation",
|
||||
multiSelect: true,
|
||||
options: [
|
||||
{ label: "JSDoc/docstring public APIs", description: "All public functions and classes must have JSDoc/docstrings" },
|
||||
{ label: "README per module", description: "Each major module/package has its own README" },
|
||||
{ label: "Inline comments for why", description: "Comments explain 'why', not 'what' — code should be self-documenting" },
|
||||
{ label: "No comment requirement", description: "Code should be self-explanatory; comments only for non-obvious logic" }
|
||||
]
|
||||
}
|
||||
]
|
||||
})
|
||||
```
|
||||
|
||||
**Process Round 2 answers** -> add to `conventions.file_structure` and `conventions.documentation`.
|
||||
|
||||
---
|
||||
|
||||
##### Round 3: Architecture & Tech Stack Constraints
|
||||
|
||||
```javascript
|
||||
// Build architecture-specific options
|
||||
const archOptions = []
|
||||
|
||||
if (archStyle.toLowerCase().includes('monolith')) {
|
||||
archOptions.push(
|
||||
{ label: "No circular deps", description: "Modules must not have circular dependencies" },
|
||||
{ label: "Layer boundaries", description: "Strict layer separation: UI → Service → Data (no skipping layers)" }
|
||||
)
|
||||
} else if (archStyle.toLowerCase().includes('microservice')) {
|
||||
archOptions.push(
|
||||
{ label: "Service isolation", description: "Services must not share databases or internal state" },
|
||||
{ label: "API contracts", description: "All inter-service communication through versioned API contracts" }
|
||||
)
|
||||
}
|
||||
archOptions.push(
|
||||
{ label: "Stateless services", description: "Service/business logic must be stateless (state in DB/cache only)" },
|
||||
{ label: "Dependency injection", description: "Use dependency injection for testability, no hardcoded dependencies" }
|
||||
)
|
||||
|
||||
AskUserQuestion({
|
||||
questions: [
|
||||
{
|
||||
question: `Your ${archStyle} architecture uses ${archPatterns.join(', ') || 'various'} patterns. What architecture constraints apply?`,
|
||||
header: "Architecture",
|
||||
multiSelect: true,
|
||||
options: archOptions.slice(0, 4)
|
||||
},
|
||||
{
|
||||
question: `Tech stack: ${frameworks.join(', ')}. What technology constraints apply?`,
|
||||
header: "Tech Stack",
|
||||
multiSelect: true,
|
||||
options: [
|
||||
{ label: "No new deps without review", description: "Adding new dependencies requires explicit justification and review" },
|
||||
{ label: "Pin dependency versions", description: "All dependencies must use exact versions, not ranges" },
|
||||
{ label: "Prefer native APIs", description: "Use built-in/native APIs over third-party libraries when possible" },
|
||||
{ label: "Framework conventions", description: `Follow official ${frameworks[0] || 'framework'} conventions and best practices` }
|
||||
]
|
||||
}
|
||||
]
|
||||
})
|
||||
```
|
||||
|
||||
**Process Round 3 answers** -> add to `constraints.architecture` and `constraints.tech_stack`.
|
||||
|
||||
---
|
||||
|
||||
##### Round 4: Performance & Security Constraints
|
||||
|
||||
```javascript
|
||||
AskUserQuestion({
|
||||
questions: [
|
||||
{
|
||||
question: "What performance requirements does your project have?",
|
||||
header: "Performance",
|
||||
multiSelect: true,
|
||||
options: [
|
||||
{ label: "API response time", description: "API endpoints must respond within 200ms (p95)" },
|
||||
{ label: "Bundle size limit", description: "Frontend bundle size must stay under 500KB gzipped" },
|
||||
{ label: "Lazy loading", description: "Large modules/routes must use lazy loading / code splitting" },
|
||||
{ label: "No N+1 queries", description: "Database access must avoid N+1 query patterns" }
|
||||
]
|
||||
},
|
||||
{
|
||||
question: "What security requirements does your project enforce?",
|
||||
header: "Security",
|
||||
multiSelect: true,
|
||||
options: [
|
||||
{ label: "Input sanitization", description: "All user input must be validated and sanitized before use" },
|
||||
{ label: "No secrets in code", description: "No API keys, passwords, or tokens in source code — use env vars" },
|
||||
{ label: "Auth on all endpoints", description: "All API endpoints require authentication unless explicitly public" },
|
||||
{ label: "Parameterized queries", description: "All database queries must use parameterized/prepared statements" }
|
||||
]
|
||||
}
|
||||
]
|
||||
})
|
||||
```
|
||||
|
||||
**Process Round 4 answers** -> add to `constraints.performance` and `constraints.security`.
|
||||
|
||||
---
|
||||
|
||||
##### Round 5: Quality Rules
|
||||
|
||||
```javascript
|
||||
AskUserQuestion({
|
||||
questions: [
|
||||
{
|
||||
question: `Testing with ${testFrameworks.join(', ') || 'your test framework'}. What quality rules apply?`,
|
||||
header: "Quality",
|
||||
multiSelect: true,
|
||||
options: [
|
||||
{ label: "Min test coverage", description: "Minimum 80% code coverage for new code; no merging below threshold" },
|
||||
{ label: "No skipped tests", description: "Tests must not be skipped (.skip/.only) in committed code" },
|
||||
{ label: "Lint must pass", description: "All code must pass linter checks before commit (enforced by pre-commit)" },
|
||||
{ label: "Type check must pass", description: "Full type checking (tsc --noEmit) must pass with zero errors" }
|
||||
]
|
||||
}
|
||||
]
|
||||
})
|
||||
```
|
||||
|
||||
**Process Round 5 answers** -> add to `quality_rules` array as `{ rule, scope, enforced_by }` objects.
|
||||
|
||||
### 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`.
|
||||
|
||||
**Category Assignment**: Based on the round and question type:
|
||||
- Round 1-2 (conventions): `category: general` (applies to all stages)
|
||||
- Round 3 (architecture/tech): `category: planning` (planning phase)
|
||||
- Round 4 (performance/security): `category: execution` (implementation phase)
|
||||
- Round 5 (quality): `category: execution` (testing phase)
|
||||
|
||||
```javascript
|
||||
// Helper: append rules to a spec MD file with category support
|
||||
// Uses .ccw/specs/ directory (same as frontend/backend spec-index-builder)
|
||||
function appendRulesToSpecFile(filePath, rules, defaultCategory = 'general') {
|
||||
if (rules.length === 0) return
|
||||
|
||||
// Ensure .ccw/specs/ directory exists
|
||||
const specDir = path.dirname(filePath)
|
||||
if (!fs.existsSync(specDir)) {
|
||||
fs.mkdirSync(specDir, { recursive: true })
|
||||
}
|
||||
|
||||
// Check if file exists
|
||||
if (!file_exists(filePath)) {
|
||||
// Create file with frontmatter including category
|
||||
const frontmatter = `---
|
||||
title: ${filePath.includes('conventions') ? 'Coding Conventions' : filePath.includes('constraints') ? 'Architecture Constraints' : 'Quality Rules'}
|
||||
readMode: optional
|
||||
priority: medium
|
||||
category: ${defaultCategory}
|
||||
scope: project
|
||||
dimension: specs
|
||||
keywords: [${defaultCategory}, ${filePath.includes('conventions') ? 'convention' : filePath.includes('constraints') ? 'constraint' : 'quality'}]
|
||||
---
|
||||
|
||||
# ${filePath.includes('conventions') ? 'Coding Conventions' : filePath.includes('constraints') ? 'Architecture Constraints' : 'Quality Rules'}
|
||||
|
||||
`
|
||||
Write(filePath, frontmatter)
|
||||
}
|
||||
|
||||
const existing = Read(filePath)
|
||||
// Append new rules as markdown list items after existing content
|
||||
const newContent = existing.trimEnd() + '\n' + rules.map(r => `- ${r}`).join('\n') + '\n'
|
||||
Write(filePath, newContent)
|
||||
}
|
||||
|
||||
// Write conventions (general category) - use .ccw/specs/ (same as frontend/backend)
|
||||
appendRulesToSpecFile('.ccw/specs/coding-conventions.md',
|
||||
[...newCodingStyle, ...newNamingPatterns, ...newFileStructure, ...newDocumentation],
|
||||
'general')
|
||||
|
||||
// Write constraints (planning category)
|
||||
appendRulesToSpecFile('.ccw/specs/architecture-constraints.md',
|
||||
[...newArchitecture, ...newTechStack, ...newPerformance, ...newSecurity],
|
||||
'planning')
|
||||
|
||||
// Write quality rules (execution category)
|
||||
if (newQualityRules.length > 0) {
|
||||
const qualityPath = '.ccw/specs/quality-rules.md'
|
||||
if (!file_exists(qualityPath)) {
|
||||
Write(qualityPath, `---
|
||||
title: Quality Rules
|
||||
readMode: required
|
||||
priority: high
|
||||
category: execution
|
||||
scope: project
|
||||
dimension: specs
|
||||
keywords: [execution, quality, testing, coverage, lint]
|
||||
---
|
||||
|
||||
# Quality Rules
|
||||
|
||||
`)
|
||||
}
|
||||
appendRulesToSpecFile(qualityPath,
|
||||
newQualityRules.map(q => `${q.rule} (scope: ${q.scope}, enforced by: ${q.enforced_by})`),
|
||||
'execution')
|
||||
}
|
||||
|
||||
// Rebuild spec index after writing
|
||||
Bash('ccw spec rebuild')
|
||||
```
|
||||
|
||||
#### 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 projectTech = JSON.parse(Read('.workflow/project-tech.json'));
|
||||
|
||||
if (skipSpecs) {
|
||||
// Minimal summary for --skip-specs mode
|
||||
console.log(`
|
||||
Project initialized successfully (tech analysis only)
|
||||
|
||||
## 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
|
||||
- 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:spec:add to add individual rules later
|
||||
- Specs are auto-loaded via hook on each prompt
|
||||
- Use workflow-plan skill 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
|
||||
**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: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
|
||||
@@ -2,7 +2,7 @@
|
||||
name: animation-extract
|
||||
description: Extract animation and transition patterns from prompt inference and image references for design system documentation
|
||||
argument-hint: "[-y|--yes] [--design-id <id>] [--session <id>] [--images "<glob>"] [--focus "<types>"] [--interactive] [--refine]"
|
||||
allowed-tools: TodoWrite(*), Read(*), Write(*), Glob(*), Bash(*), AskUserQuestion(*), Task(ui-design-agent)
|
||||
allowed-tools: TodoWrite(*), Read(*), Write(*), Glob(*), Bash(*), AskUserQuestion(*), Agent(ui-design-agent)
|
||||
---
|
||||
|
||||
## Auto Mode
|
||||
@@ -207,14 +207,14 @@ IF has_images:
|
||||
|
||||
### Step 2: Generate Animation Specification Options (Agent Task 1)
|
||||
|
||||
**Executor**: `Task(ui-design-agent)`
|
||||
**Executor**: `Agent(ui-design-agent)`
|
||||
|
||||
**Conditional Logic**: Branch based on `refine_mode` flag
|
||||
|
||||
```javascript
|
||||
IF NOT refine_mode:
|
||||
// EXPLORATION MODE (default)
|
||||
Task(ui-design-agent): `
|
||||
Agent(ui-design-agent): `
|
||||
[ANIMATION_SPECIFICATION_GENERATION_TASK]
|
||||
Generate context-aware animation specification questions
|
||||
|
||||
@@ -308,7 +308,7 @@ IF NOT refine_mode:
|
||||
|
||||
ELSE:
|
||||
// REFINEMENT MODE
|
||||
Task(ui-design-agent): `
|
||||
Agent(ui-design-agent): `
|
||||
[ANIMATION_REFINEMENT_OPTIONS_TASK]
|
||||
Generate refinement options for existing animation system
|
||||
|
||||
@@ -656,7 +656,7 @@ ELSE:
|
||||
|
||||
## Phase 2: Animation System Generation (Agent Task 2)
|
||||
|
||||
**Executor**: `Task(ui-design-agent)` for animation token generation
|
||||
**Executor**: `Agent(ui-design-agent)` for animation token generation
|
||||
|
||||
### Step 1: Load User Selection or Use Defaults
|
||||
|
||||
@@ -706,14 +706,14 @@ IF has_images:
|
||||
bash(mkdir -p {base_path}/animation-extraction)
|
||||
```
|
||||
|
||||
### Step 3: Launch Animation Generation Task
|
||||
### Step 3: Launch Animation Generation Agent
|
||||
|
||||
**Conditional Task**: Branch based on `refine_mode` flag
|
||||
|
||||
```javascript
|
||||
IF NOT refine_mode:
|
||||
// EXPLORATION MODE
|
||||
Task(ui-design-agent): `
|
||||
Agent(ui-design-agent): `
|
||||
[ANIMATION_SYSTEM_GENERATION_TASK]
|
||||
Generate production-ready animation system based on user preferences and CSS extraction
|
||||
|
||||
@@ -871,7 +871,7 @@ IF NOT refine_mode:
|
||||
|
||||
ELSE:
|
||||
// REFINEMENT MODE
|
||||
Task(ui-design-agent): `
|
||||
Agent(ui-design-agent): `
|
||||
[ANIMATION_SYSTEM_REFINEMENT_TASK]
|
||||
Apply selected refinements to existing animation system
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
---
|
||||
name: design-sync
|
||||
description: Synchronize finalized design system references to brainstorming artifacts, preparing them for /workflow:plan consumption
|
||||
description: Synchronize finalized design system references to brainstorming artifacts, preparing them for /workflow-plan consumption
|
||||
argument-hint: --session <session_id> [--selected-prototypes "<list>"]
|
||||
allowed-tools: Read(*), Write(*), Edit(*), TodoWrite(*), Glob(*), Bash(*)
|
||||
---
|
||||
@@ -351,10 +351,10 @@ Updated artifacts:
|
||||
✓ {role_count} role analysis.md files - Design system references
|
||||
✓ ui-designer/design-system-reference.md - Design system reference guide
|
||||
|
||||
Design system assets ready for /workflow:plan:
|
||||
Design system assets ready for /workflow-plan:
|
||||
- design-tokens.json | style-guide.md | {prototype_count} reference prototypes
|
||||
|
||||
Next: /workflow:plan [--agent] "<task description>"
|
||||
Next: /workflow-plan [--agent] "<task description>"
|
||||
The plan phase will automatically discover and utilize the design system.
|
||||
```
|
||||
|
||||
@@ -394,7 +394,7 @@ Next: /workflow:plan [--agent] "<task description>"
|
||||
@../../{design_id}/prototypes/{prototype}.html
|
||||
```
|
||||
|
||||
## Integration with /workflow:plan
|
||||
## Integration with /workflow-plan
|
||||
|
||||
After this update, `workflow-plan` skill will discover design assets through:
|
||||
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
name: explore-auto
|
||||
description: Interactive exploratory UI design workflow with style-centric batch generation, creates design variants from prompts/images with parallel execution and user selection
|
||||
argument-hint: "[--input "<value>"] [--targets "<list>"] [--target-type "page|component"] [--session <id>] [--style-variants <count>] [--layout-variants <count>]"
|
||||
allowed-tools: Skill(*), TodoWrite(*), Read(*), Bash(*), Glob(*), Write(*), Task(conceptual-planning-agent)
|
||||
allowed-tools: Skill(*), TodoWrite(*), Read(*), Bash(*), Glob(*), Write(*), Agent(conceptual-planning-agent)
|
||||
---
|
||||
|
||||
# UI Design Auto Workflow Command
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
name: generate
|
||||
description: Assemble UI prototypes by combining layout templates with design tokens (default animation support), pure assembler without new content generation
|
||||
argument-hint: [--design-id <id>] [--session <id>]
|
||||
allowed-tools: TodoWrite(*), Read(*), Write(*), Task(ui-design-agent), Bash(*)
|
||||
allowed-tools: TodoWrite(*), Read(*), Write(*), Agent(ui-design-agent), Bash(*)
|
||||
---
|
||||
|
||||
# Generate UI Prototypes (/workflow:ui-design:generate)
|
||||
@@ -129,7 +129,7 @@ ELSE:
|
||||
|
||||
## Phase 2: Assembly (Agent)
|
||||
|
||||
**Executor**: `Task(ui-design-agent)` grouped by `target × style` (max 10 layouts per agent, max 6 concurrent agents)
|
||||
**Executor**: `Agent(ui-design-agent)` grouped by `target × style` (max 10 layouts per agent, max 6 concurrent agents)
|
||||
|
||||
**⚠️ Core Principle**: **Each agent processes ONLY ONE style** (but can process multiple layouts for that style)
|
||||
|
||||
@@ -204,7 +204,7 @@ TodoWrite({todos: [
|
||||
For each batch (up to 6 parallel agents per batch):
|
||||
For each agent group `{target, style_id, layout_ids[]}` in current batch:
|
||||
```javascript
|
||||
Task(ui-design-agent): `
|
||||
Agent(ui-design-agent): `
|
||||
[LAYOUT_STYLE_ASSEMBLY]
|
||||
🎯 {target} × Style-{style_id} × Layouts-{layout_ids}
|
||||
⚠️ CONSTRAINT: Use ONLY style-{style_id}/design-tokens.json (never mix styles)
|
||||
|
||||
@@ -606,7 +606,7 @@ Total workflow time: ~{estimate_total_time()} minutes
|
||||
|
||||
{IF session_id:
|
||||
2. Create implementation tasks:
|
||||
/workflow:plan --session {session_id}
|
||||
/workflow-plan --session {session_id}
|
||||
|
||||
3. Generate tests (if needed):
|
||||
/workflow:test-gen {session_id}
|
||||
@@ -741,5 +741,5 @@ Design Quality:
|
||||
- Design token driven
|
||||
- {generated_count} assembled prototypes
|
||||
|
||||
Next: [/workflow:execute] OR [Open compare.html → /workflow:plan]
|
||||
Next: [/workflow-execute] OR [Open compare.html → /workflow-plan]
|
||||
```
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
name: workflow:ui-design:import-from-code
|
||||
description: Import design system from code files (CSS/JS/HTML/SCSS) with automatic file discovery and parallel agent analysis
|
||||
argument-hint: "[--design-id <id>] [--session <id>] [--source <path>]"
|
||||
allowed-tools: Read,Write,Bash,Glob,Grep,Task,TodoWrite
|
||||
allowed-tools: Read,Write,Bash,Glob,Grep,Agent,TodoWrite
|
||||
auto-continue: true
|
||||
---
|
||||
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
name: layout-extract
|
||||
description: Extract structural layout information from reference images or text prompts using Claude analysis with variant generation or refinement mode
|
||||
argument-hint: "[-y|--yes] [--design-id <id>] [--session <id>] [--images "<glob>"] [--prompt "<desc>"] [--targets "<list>"] [--variants <count>] [--device-type <desktop|mobile|tablet|responsive>] [--interactive] [--refine]"
|
||||
allowed-tools: TodoWrite(*), Read(*), Write(*), Glob(*), Bash(*), AskUserQuestion(*), Task(ui-design-agent), mcp__exa__web_search_exa(*)
|
||||
allowed-tools: TodoWrite(*), Read(*), Write(*), Glob(*), Bash(*), AskUserQuestion(*), Agent(ui-design-agent), mcp__exa__web_search_exa(*)
|
||||
---
|
||||
|
||||
## Auto Mode
|
||||
@@ -162,7 +162,7 @@ IF refine_mode:
|
||||
```
|
||||
|
||||
### Step 1: Generate Options (Agent Task 1 - Mode-Specific)
|
||||
**Executor**: `Task(ui-design-agent)`
|
||||
**Executor**: `Agent(ui-design-agent)`
|
||||
|
||||
**Exploration Mode** (default): Generate contrasting layout concepts
|
||||
**Refinement Mode** (`--refine`): Generate refinement options for existing layouts
|
||||
@@ -171,7 +171,7 @@ IF refine_mode:
|
||||
// Conditional agent task based on refine_mode
|
||||
IF NOT refine_mode:
|
||||
// EXPLORATION MODE
|
||||
Task(ui-design-agent): `
|
||||
Agent(ui-design-agent): `
|
||||
[LAYOUT_CONCEPT_GENERATION_TASK]
|
||||
Generate {variants_count} structurally distinct layout concepts for each target
|
||||
|
||||
@@ -217,7 +217,7 @@ IF NOT refine_mode:
|
||||
`
|
||||
ELSE:
|
||||
// REFINEMENT MODE
|
||||
Task(ui-design-agent): `
|
||||
Agent(ui-design-agent): `
|
||||
[LAYOUT_REFINEMENT_OPTIONS_TASK]
|
||||
Generate refinement options for existing layout(s)
|
||||
|
||||
@@ -461,7 +461,7 @@ Proceeding to generate {total_selections} detailed layout template(s)...
|
||||
|
||||
## Phase 2: Layout Template Generation (Agent Task 2)
|
||||
|
||||
**Executor**: `Task(ui-design-agent)` × `Total_Selected_Templates` in **parallel**
|
||||
**Executor**: `Agent(ui-design-agent)` × `Total_Selected_Templates` in **parallel**
|
||||
|
||||
### Step 1: Load User Selections or Default to All
|
||||
```bash
|
||||
@@ -512,7 +512,7 @@ REPORT: "Generating {total_tasks} layout templates across {targets.length} targe
|
||||
Generate layout templates for ALL selected concepts in parallel:
|
||||
```javascript
|
||||
FOR each task in task_list:
|
||||
Task(ui-design-agent): `
|
||||
Agent(ui-design-agent): `
|
||||
[LAYOUT_TEMPLATE_GENERATION_TASK #{task.variant_id} for {task.target}]
|
||||
Generate detailed layout template based on user-selected concept.
|
||||
Focus ONLY on structure and layout. DO NOT concern with visual style (colors, fonts, etc.).
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
name: workflow:ui-design:reference-page-generator
|
||||
description: Generate multi-component reference pages and documentation from design run extraction
|
||||
argument-hint: "[--design-run <path>] [--package-name <name>] [--output-dir <path>]"
|
||||
allowed-tools: Read,Write,Bash,Task,TodoWrite
|
||||
allowed-tools: Read,Write,Bash,Agent,TodoWrite
|
||||
auto-continue: true
|
||||
---
|
||||
|
||||
@@ -198,7 +198,7 @@ echo "[Phase 1] Component data preparation complete"
|
||||
**Agent Task**:
|
||||
|
||||
```javascript
|
||||
Task(ui-design-agent): `
|
||||
Agent(ui-design-agent): `
|
||||
[PREVIEW_SHOWCASE_GENERATION]
|
||||
Generate interactive multi-component showcase panel for reference package
|
||||
|
||||
@@ -210,7 +210,7 @@ Task(ui-design-agent): `
|
||||
2. ${package_dir}/design-tokens.json (design tokens - REQUIRED)
|
||||
3. ${package_dir}/animation-tokens.json (optional, if exists)
|
||||
|
||||
## Generation Task
|
||||
## Generation Agent
|
||||
|
||||
Create interactive showcase with these sections:
|
||||
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
name: unified-execute-with-file
|
||||
description: Universal execution engine for consuming any planning/brainstorm/analysis output with minimal progress tracking, multi-agent coordination, and incremental execution
|
||||
argument-hint: "[-y|--yes] [<path>[,<path2>] | -p|--plan <path>[,<path2>]] [--auto-commit] [--commit-prefix \"prefix\"] [\"execution context or task name\"]"
|
||||
allowed-tools: TodoWrite(*), Task(*), AskUserQuestion(*), Read(*), Grep(*), Glob(*), Bash(*), Edit(*), Write(*)
|
||||
allowed-tools: TodoWrite(*), Agent(*), AskUserQuestion(*), Read(*), Grep(*), Glob(*), Bash(*), Edit(*), Write(*)
|
||||
---
|
||||
|
||||
## Auto Mode
|
||||
@@ -34,7 +34,7 @@ When `--yes` or `-y`: Auto-confirm execution decisions, follow plan's DAG depend
|
||||
```
|
||||
|
||||
**Execution Methods**:
|
||||
- **Agent**: Task tool with code-developer (recommended for standard tasks)
|
||||
- **Agent**: Agent tool with code-developer (recommended for standard tasks)
|
||||
- **CLI-Codex**: `ccw cli --tool codex` (complex tasks, git-aware)
|
||||
- **CLI-Gemini**: `ccw cli --tool gemini` (analysis-heavy tasks)
|
||||
- **Auto**: Select based on task complexity (default in `-y` mode)
|
||||
@@ -99,7 +99,7 @@ Universal execution engine consuming **any** planning output and executing it wi
|
||||
│ Phase 5: Per-Task Execution (Agent OR CLI) │
|
||||
│ ├─ Extract relevant notes from previous tasks │
|
||||
│ ├─ Inject notes into execution context │
|
||||
│ ├─ Route to Agent (Task tool) OR CLI (ccw cli command) │
|
||||
│ ├─ Route to Agent (Agent tool) OR CLI (ccw cli command) │
|
||||
│ ├─ Generate structured notes for next task │
|
||||
│ ├─ Auto-commit if enabled (conventional commit format) │
|
||||
│ └─ Append event to unified log │
|
||||
@@ -471,11 +471,26 @@ ${recommendations.map(r => \`- ${r}\`).join('\\n')}
|
||||
|
||||
2. **Build Execution Context**
|
||||
|
||||
**Load Project Context** (from init.md products):
|
||||
```javascript
|
||||
// Read project-tech.json (if exists)
|
||||
const projectTech = file_exists('.workflow/project-tech.json')
|
||||
? JSON.parse(Read('.workflow/project-tech.json')) : null
|
||||
// Read specs/*.md (if exists)
|
||||
const projectGuidelines = file_exists('.ccw/specs/*.md')
|
||||
? JSON.parse(Read('.ccw/specs/*.md')) : null
|
||||
```
|
||||
|
||||
```javascript
|
||||
const executionContext = `
|
||||
⚠️ Execution Notes from Previous Tasks
|
||||
${relevantNotes} // Categorized notes with severity
|
||||
|
||||
📋 Project Context (from init.md)
|
||||
- Tech Stack: ${projectTech?.technology_analysis?.technology_stack || 'N/A'}
|
||||
- Architecture: ${projectTech?.technology_analysis?.architecture?.style || 'N/A'}
|
||||
- Constraints: ${projectGuidelines?.constraints || 'None defined'}
|
||||
|
||||
Current Task: ${task.id}
|
||||
- Original ID: ${task.original_id}
|
||||
- Source Plan: ${task.source_plan}
|
||||
@@ -492,10 +507,10 @@ ${recommendations.map(r => \`- ${r}\`).join('\\n')}
|
||||
|
||||
When: `executionMethod === "Agent"` or `Auto + Low Complexity`
|
||||
|
||||
Execute task via Task tool with code-developer agent:
|
||||
Execute task via Agent tool with code-developer agent:
|
||||
|
||||
```javascript
|
||||
Task({
|
||||
Agent({
|
||||
subagent_type: "code-developer", // or other agent types
|
||||
run_in_background: false,
|
||||
description: task.title,
|
||||
@@ -643,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
|
||||
|
||||
---
|
||||
|
||||
@@ -43,19 +43,19 @@ function getExistingCommandSources() {
|
||||
// These commands were migrated to skills but references were never updated
|
||||
const COMMAND_TO_SKILL_MAP = {
|
||||
// workflow commands → skills
|
||||
'/workflow:plan': 'workflow-plan',
|
||||
'/workflow:execute': 'workflow-execute',
|
||||
'/workflow:lite-plan': 'workflow-lite-plan',
|
||||
'/workflow-plan': 'workflow-plan',
|
||||
'/workflow-execute': 'workflow-execute',
|
||||
'/workflow-lite-plan': 'workflow-lite-plan',
|
||||
'/workflow:lite-execute': 'workflow-lite-plan', // lite-execute is part of lite-plan skill
|
||||
'/workflow:lite-fix': 'workflow-lite-plan', // lite-fix is part of lite-plan skill
|
||||
'/workflow:multi-cli-plan': 'workflow-multi-cli-plan',
|
||||
'/workflow:plan-verify': 'workflow-plan', // plan-verify is a phase of workflow-plan
|
||||
'/workflow-multi-cli-plan': 'workflow-multi-cli-plan',
|
||||
'/workflow-plan-verify': 'workflow-plan', // plan-verify is a phase of workflow-plan
|
||||
'/workflow:replan': 'workflow-plan', // replan is a phase of workflow-plan
|
||||
'/workflow:tdd-plan': 'workflow-tdd',
|
||||
'/workflow:tdd-verify': 'workflow-tdd', // tdd-verify is a phase of workflow-tdd
|
||||
'/workflow:test-fix-gen': 'workflow-test-fix',
|
||||
'/workflow-tdd-plan': 'workflow-tdd-plan',
|
||||
'/workflow-tdd-verify': 'workflow-tdd-plan', // tdd-verify is a phase of workflow-tdd-plan
|
||||
'/workflow-test-fix': 'workflow-test-fix',
|
||||
'/workflow:test-gen': 'workflow-test-fix',
|
||||
'/workflow:test-cycle-execute': 'workflow-test-fix',
|
||||
'/workflow-test-fix': 'workflow-test-fix',
|
||||
'/workflow:review': 'review-cycle',
|
||||
'/workflow:review-session-cycle': 'review-cycle',
|
||||
'/workflow:review-module-cycle': 'review-cycle',
|
||||
@@ -70,8 +70,8 @@ const COMMAND_TO_SKILL_MAP = {
|
||||
'/workflow:tools:context-gather': 'workflow-plan',
|
||||
'/workflow:tools:conflict-resolution': 'workflow-plan',
|
||||
'/workflow:tools:task-generate-agent': 'workflow-plan',
|
||||
'/workflow:tools:task-generate-tdd': 'workflow-tdd',
|
||||
'/workflow:tools:tdd-coverage-analysis': 'workflow-tdd',
|
||||
'/workflow:tools:task-generate-tdd': 'workflow-tdd-plan',
|
||||
'/workflow:tools:tdd-coverage-analysis': 'workflow-tdd-plan',
|
||||
'/workflow:tools:test-concept-enhanced': 'workflow-test-fix',
|
||||
'/workflow:tools:test-context-gather': 'workflow-test-fix',
|
||||
'/workflow:tools:test-task-generate': 'workflow-test-fix',
|
||||
@@ -319,17 +319,17 @@ function fixBrokenReferences() {
|
||||
// Pattern: `/ command:name` references that point to non-existent commands
|
||||
// These are documentation references - update to point to skill names
|
||||
const proseRefFixes = {
|
||||
'`/workflow:plan`': '`workflow-plan` skill',
|
||||
'`/workflow:execute`': '`workflow-execute` skill',
|
||||
'`/workflow-plan`': '`workflow-plan` skill',
|
||||
'`/workflow-execute`': '`workflow-execute` skill',
|
||||
'`/workflow:lite-execute`': '`workflow-lite-plan` skill',
|
||||
'`/workflow:lite-fix`': '`workflow-lite-plan` skill',
|
||||
'`/workflow:plan-verify`': '`workflow-plan` skill (plan-verify phase)',
|
||||
'`/workflow-plan-verify`': '`workflow-plan` skill (plan-verify phase)',
|
||||
'`/workflow:replan`': '`workflow-plan` skill (replan phase)',
|
||||
'`/workflow:tdd-plan`': '`workflow-tdd` skill',
|
||||
'`/workflow:tdd-verify`': '`workflow-tdd` skill (tdd-verify phase)',
|
||||
'`/workflow:test-fix-gen`': '`workflow-test-fix` skill',
|
||||
'`/workflow-tdd-plan`': '`workflow-tdd-plan` skill',
|
||||
'`/workflow-tdd-verify`': '`workflow-tdd-plan` skill (tdd-verify phase)',
|
||||
'`/workflow-test-fix`': '`workflow-test-fix` skill',
|
||||
'`/workflow:test-gen`': '`workflow-test-fix` skill',
|
||||
'`/workflow:test-cycle-execute`': '`workflow-test-fix` skill',
|
||||
'`/workflow-test-fix`': '`workflow-test-fix` skill',
|
||||
'`/workflow:review`': '`review-cycle` skill',
|
||||
'`/workflow:review-session-cycle`': '`review-cycle` skill',
|
||||
'`/workflow:review-module-cycle`': '`review-cycle` skill',
|
||||
@@ -346,8 +346,8 @@ function fixBrokenReferences() {
|
||||
'`/workflow:tools:task-generate`': '`workflow-plan` skill (task-generate phase)',
|
||||
'`/workflow:ui-design:auto`': '`/workflow:ui-design:explore-auto`',
|
||||
'`/workflow:ui-design:update`': '`/workflow:ui-design:generate`',
|
||||
'`/workflow:multi-cli-plan`': '`workflow-multi-cli-plan` skill',
|
||||
'`/workflow:lite-plan`': '`workflow-lite-plan` skill',
|
||||
'`/workflow-multi-cli-plan`': '`workflow-multi-cli-plan` skill',
|
||||
'`/workflow-lite-plan`': '`workflow-lite-plan` skill',
|
||||
'`/cli:plan`': '`workflow-lite-plan` skill',
|
||||
'`/test-cycle-execute`': '`workflow-test-fix` skill',
|
||||
};
|
||||
|
||||
@@ -83,7 +83,7 @@
|
||||
| 内容类型 | 保留要求 | 示例 |
|
||||
|---------|---------|------|
|
||||
| **Bash命令** | 完整命令,包含所有参数、管道、重定向 | `find . -name "*.json" \| head -1` |
|
||||
| **Agent Prompt** | 全文保留,包含OBJECTIVE、TASK、EXPECTED等所有节 | 完整的Task({prompt: "..."}) |
|
||||
| **Agent Prompt** | 全文保留,包含OBJECTIVE、TASK、EXPECTED等所有节 | 完整的Agent({prompt: "..."}) |
|
||||
| **代码函数** | 完整函数体,所有if/else分支 | `analyzeTaskComplexity()` 全部代码 |
|
||||
| **参数表格** | 所有行列,不省略任何参数 | Session Types表格 |
|
||||
| **JSON Schema** | 所有字段、类型、required定义 | context-package.json schema |
|
||||
@@ -95,7 +95,7 @@
|
||||
|
||||
1. **将代码替换为描述**
|
||||
- ❌ 错误:`Execute context gathering agent`
|
||||
- ✅ 正确:完整的 `Task({ subagent_type: "context-search-agent", prompt: "...[完整200行prompt]..." })`
|
||||
- ✅ 正确:完整的 `Agent({ subagent_type: "context-search-agent", prompt: "...[完整200行prompt]..." })`
|
||||
|
||||
2. **省略Prompt内容**
|
||||
- ❌ 错误:`Agent prompt for context gathering (see original file)`
|
||||
@@ -123,7 +123,7 @@
|
||||
| **命令调用语法** | 转换为 Phase 文件的相对路径 | `/workflow:session:start` → `phases/01-session-discovery.md` |
|
||||
| **命令路径引用** | 转换为 Skill 目录内路径 | `commands/workflow/tools/` → `phases/` |
|
||||
| **跨命令引用** | 转换为 Phase 间文件引用 | `workflow-plan` skill (context-gather phase) → `phases/02-context-gathering.md` |
|
||||
| **命令参数说明** | 移除或转为 Phase Prerequisites | `usage: /workflow:plan [session-id]` → Phase Prerequisites 中说明 |
|
||||
| **命令参数说明** | 移除或转为 Phase Prerequisites | `usage: /workflow-plan [session-id]` → Phase Prerequisites 中说明 |
|
||||
|
||||
**转换示例**:
|
||||
|
||||
@@ -277,7 +277,7 @@ commands/ skills/
|
||||
---
|
||||
name: {skill-name}
|
||||
description: {简短描述}. Triggers on "{trigger-phrase}".
|
||||
allowed-tools: Task, AskUserQuestion, TodoWrite, Read, Write, Edit, Bash, Glob, Grep
|
||||
allowed-tools: Agent, AskUserQuestion, TodoWrite, Read, Write, Edit, Bash, Glob, Grep
|
||||
---
|
||||
```
|
||||
|
||||
@@ -440,7 +440,7 @@ Complete: IMPL_PLAN.md + Task JSONs
|
||||
|--------|---------|---------|
|
||||
| **代码块数量** | 计数 ` ```bash ` 和 ` ```javascript ` | 与原文件相等 |
|
||||
| **表格数量** | 计数 ` \| ` 开头的行 | 与原文件相等 |
|
||||
| **Agent Prompt** | 搜索 `Task({` | 完整的prompt参数内容 |
|
||||
| **Agent Prompt** | 搜索 `Agent({` | 完整的prompt参数内容 |
|
||||
| **步骤编号** | 检查 `### Step` | 编号序列与原文件一致 |
|
||||
| **文件行数** | `wc -l` | ±20%以内 |
|
||||
| **关键函数** | 搜索函数名 | 所有函数完整保留 |
|
||||
@@ -492,10 +492,10 @@ Execute the context-search-agent to gather project context.
|
||||
### Step 2: Run context gathering
|
||||
|
||||
```javascript
|
||||
Task({
|
||||
Agent({
|
||||
subagent_type: "context-search-agent",
|
||||
prompt: `
|
||||
## Context Search Task
|
||||
## Context Search Agent
|
||||
|
||||
### OBJECTIVE
|
||||
Gather comprehensive context for planning session ${sessionId}
|
||||
@@ -535,7 +535,7 @@ Gather comprehensive context for planning session ${sessionId}
|
||||
│ └─→ 数量应相等 │
|
||||
│ │
|
||||
│ Step 3: 关键内容抽查 │
|
||||
│ - 搜索 Task({ → Agent Prompt 完整性 │
|
||||
│ - 搜索 Agent({ → Agent Prompt 完整性 │
|
||||
│ - 搜索函数名 → 函数体完整性 │
|
||||
│ - 搜索表格标记 → 表格完整性 │
|
||||
│ │
|
||||
@@ -562,8 +562,8 @@ grep -c '^|' commands/workflow/tools/context-gather.md
|
||||
grep -c '^|' skills/workflow-plan/phases/02-context-gathering.md
|
||||
|
||||
# 4. Agent Prompt检查
|
||||
grep -c 'Task({' commands/workflow/tools/context-gather.md
|
||||
grep -c 'Task({' skills/workflow-plan/phases/02-context-gathering.md
|
||||
grep -c 'Agent({' commands/workflow/tools/context-gather.md
|
||||
grep -c 'Agent({' skills/workflow-plan/phases/02-context-gathering.md
|
||||
|
||||
# 5. 函数定义检查
|
||||
grep -E '^(function|const.*=.*=>|async function)' commands/workflow/tools/context-gather.md
|
||||
|
||||
@@ -140,7 +140,7 @@ graph TD
|
||||
---
|
||||
name: {skill-name}
|
||||
description: {一句话描述}. {触发关键词}. Triggers on "{关键词1}", "{关键词2}".
|
||||
allowed-tools: Task, AskUserQuestion, Read, Bash, Glob, Grep, Write, {其他MCP工具}
|
||||
allowed-tools: Agent, AskUserQuestion, Read, Bash, Glob, Grep, Write, {其他MCP工具}
|
||||
---
|
||||
|
||||
# {Skill 标题}
|
||||
@@ -192,7 +192,7 @@ description: | # 必需:描述 + 触发词
|
||||
Generate XXX documents.
|
||||
Triggers on "keyword1", "keyword2".
|
||||
allowed-tools: | # 必需:允许使用的工具
|
||||
Task, AskUserQuestion, Read, Bash,
|
||||
Agent, AskUserQuestion, Read, Bash,
|
||||
Glob, Grep, Write, mcp__chrome__*
|
||||
---
|
||||
```
|
||||
@@ -641,7 +641,7 @@ touch my-skill/templates/agent-base.md
|
||||
---
|
||||
name: my-skill
|
||||
description: Generate XXX. Triggers on "keyword1", "keyword2".
|
||||
allowed-tools: Task, AskUserQuestion, Read, Bash, Glob, Grep, Write
|
||||
allowed-tools: Agent, AskUserQuestion, Read, Bash, Glob, Grep, Write
|
||||
---
|
||||
|
||||
# My Skill
|
||||
@@ -680,7 +680,7 @@ Generate XXX through multi-phase analysis.
|
||||
|
||||
| 工具 | 用途 | 适用 Skill |
|
||||
|------|------|------------|
|
||||
| `Task` | 启动子 Agent | 所有 |
|
||||
| `Agent` | 启动子 Agent | 所有 |
|
||||
| `AskUserQuestion` | 用户交互 | 所有 |
|
||||
| `Read/Write/Glob/Grep` | 文件操作 | 所有 |
|
||||
| `Bash` | 脚本执行 | 需要自动化 |
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
```
|
||||
177
.claude/skills/brainstorm/README.md
Normal file
177
.claude/skills/brainstorm/README.md
Normal 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`
|
||||
@@ -1,7 +1,7 @@
|
||||
---
|
||||
name: brainstorm
|
||||
description: Unified brainstorming skill with dual-mode operation - auto pipeline and single role analysis. Triggers on "brainstorm", "头脑风暴".
|
||||
allowed-tools: Skill(*), Task(conceptual-planning-agent, context-search-agent), AskUserQuestion(*), TodoWrite(*), Read(*), Write(*), Edit(*), Glob(*), Bash(*)
|
||||
allowed-tools: Skill(*), Agent(conceptual-planning-agent, context-search-agent), AskUserQuestion(*), TodoWrite(*), Read(*), Write(*), Edit(*), Glob(*), Bash(*)
|
||||
---
|
||||
|
||||
# Brainstorm
|
||||
@@ -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
|
||||
@@ -373,7 +399,7 @@ Initial → Phase 1 Mode Routing (completed)
|
||||
- `/workflow:session:start` - Start a new workflow session (optional, brainstorm creates its own)
|
||||
|
||||
**Follow-ups** (after brainstorm completes):
|
||||
- `/workflow:plan --session {sessionId}` - Generate implementation plan
|
||||
- `/workflow-plan --session {sessionId}` - Generate implementation plan
|
||||
- `/workflow:brainstorm:synthesis --session {sessionId}` - Run synthesis standalone (if skipped)
|
||||
|
||||
## Reference Information
|
||||
|
||||
@@ -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]
|
||||
|
||||
@@ -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 ? `
|
||||
@@ -469,7 +499,7 @@ ${selected_roles.length > 1 ? `
|
||||
- Run synthesis: /brainstorm --session ${session_id} (auto mode)
|
||||
` : `
|
||||
- Clarify insights: /brainstorm --session ${session_id} (auto mode)
|
||||
- Generate plan: /workflow:plan --session ${session_id}
|
||||
- Generate plan: /workflow-plan --session ${session_id}
|
||||
`}
|
||||
```
|
||||
|
||||
|
||||
@@ -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)
|
||||
@@ -744,7 +754,7 @@ Write(context_pkg_path, JSON.stringify(context_pkg))
|
||||
**Changelog**: .brainstorming/synthesis-changelog.md
|
||||
|
||||
### Next Steps
|
||||
PROCEED: `/workflow:plan --session {session-id}`
|
||||
PROCEED: `/workflow-plan --session {session-id}`
|
||||
```
|
||||
|
||||
## Output
|
||||
|
||||
22
.claude/skills/brainstorm/specs/terminology-template.json
Normal file
22
.claude/skills/brainstorm/specs/terminology-template.json
Normal 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
|
||||
}
|
||||
}
|
||||
@@ -1,18 +1,18 @@
|
||||
---
|
||||
name: ccw-help
|
||||
description: CCW command help system. Search, browse, recommend commands. Triggers "ccw-help", "ccw-issue".
|
||||
description: CCW command help system. Search, browse, recommend commands, skills, teams. Triggers "ccw-help", "ccw-issue".
|
||||
allowed-tools: Read, Grep, Glob, AskUserQuestion
|
||||
version: 7.0.0
|
||||
version: 8.0.0
|
||||
---
|
||||
|
||||
# CCW-Help Skill
|
||||
|
||||
CCW 命令帮助系统,提供命令搜索、推荐、文档查看功能。
|
||||
CCW 命令帮助系统,提供命令搜索、推荐、文档查看、Skill/Team 浏览功能。
|
||||
|
||||
## Trigger Conditions
|
||||
|
||||
- 关键词: "ccw-help", "ccw-issue", "帮助", "命令", "怎么用", "ccw 怎么用", "工作流"
|
||||
- 场景: 询问命令用法、搜索命令、请求下一步建议、询问任务应该用哪个工作流
|
||||
- 关键词: "ccw-help", "ccw-issue", "帮助", "命令", "怎么用", "ccw 怎么用", "工作流", "skill", "team"
|
||||
- 场景: 询问命令用法、搜索命令、请求下一步建议、询问任务应该用哪个工作流、浏览 Skill/Team 目录
|
||||
|
||||
## Operation Modes
|
||||
|
||||
@@ -61,7 +61,7 @@ CCW 命令帮助系统,提供命令搜索、推荐、文档查看功能。
|
||||
4. Get user confirmation
|
||||
5. Execute chain with TODO tracking
|
||||
|
||||
**Supported Workflows**:
|
||||
**Supported Workflows** (参考 [ccw.md](../../commands/ccw.md)):
|
||||
- **Level 1** (Lite-Lite-Lite): Ultra-simple quick tasks
|
||||
- **Level 2** (Rapid/Hotfix): Bug fixes, simple features, documentation
|
||||
- **Level 2.5** (Rapid-to-Issue): Bridge from quick planning to issue workflow
|
||||
@@ -71,12 +71,17 @@ CCW 命令帮助系统,提供命令搜索、推荐、文档查看功能。
|
||||
- Test-fix workflows (debug failing tests)
|
||||
- Review workflows (code review and fixes)
|
||||
- UI design workflows
|
||||
- Multi-CLI collaborative workflows
|
||||
- Cycle workflows (integration-test, refactor)
|
||||
- **Level 4** (Full): Exploratory tasks with brainstorming
|
||||
- **With-File Workflows**: Documented exploration with multi-CLI collaboration
|
||||
- `brainstorm-with-file`: Multi-perspective ideation
|
||||
- `debug-with-file`: Hypothesis-driven debugging
|
||||
- `analyze-with-file`: Collaborative analysis
|
||||
- `brainstorm-with-file`: Multi-perspective ideation → workflow-plan → workflow-execute
|
||||
- `debug-with-file`: Hypothesis-driven debugging (standalone)
|
||||
- `analyze-with-file`: Collaborative analysis → workflow-lite-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
|
||||
- **Team Workflow**: team-planex wave pipeline for parallel execution
|
||||
|
||||
### Mode 6: Issue Reporting
|
||||
|
||||
@@ -86,6 +91,16 @@ CCW 命令帮助系统,提供命令搜索、推荐、文档查看功能。
|
||||
1. Use AskUserQuestion to gather context
|
||||
2. Generate structured issue template
|
||||
|
||||
### Mode 7: Skill & Team Browsing
|
||||
|
||||
**Triggers**: "skill", "team", "技能", "团队", "有哪些 skill", "team 怎么用"
|
||||
|
||||
**Process**:
|
||||
1. Query `command.json` skills array
|
||||
2. Filter by category: workflow / team / review / meta / utility / standalone
|
||||
3. Present categorized skill list with descriptions
|
||||
4. For team skills, explain team architecture and usage patterns
|
||||
|
||||
## Data Source
|
||||
|
||||
Single source of truth: **[command.json](command.json)**
|
||||
@@ -94,8 +109,9 @@ Single source of truth: **[command.json](command.json)**
|
||||
|-------|---------|
|
||||
| `commands[]` | Flat command list with metadata |
|
||||
| `commands[].flow` | Relationships (next_steps, prerequisites) |
|
||||
| `commands[].essential` | Essential flag for onboarding |
|
||||
| `agents[]` | Agent directory |
|
||||
| `skills[]` | Skill directory with categories |
|
||||
| `skills[].is_team` | Whether skill uses team architecture |
|
||||
| `essential_commands[]` | Core commands list |
|
||||
|
||||
### Source Path Format
|
||||
@@ -109,6 +125,77 @@ Single source of truth: **[command.json](command.json)**
|
||||
}
|
||||
```
|
||||
|
||||
## Skill Catalog
|
||||
|
||||
### Workflow Skills (核心工作流)
|
||||
|
||||
| Skill | 内部流水线 | 触发词 |
|
||||
|-------|-----------|--------|
|
||||
| `workflow-lite-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 开发 |
|
||||
| `workflow-test-fix` | session → context → analysis → gen → cycle | "test-fix", 测试修复 |
|
||||
| `workflow-multi-cli-plan` | ACE context → CLI discussion → plan → execute | "multi-cli", 多CLI协作 |
|
||||
| `workflow-skill-designer` | Meta-skill for designing workflow skills | "skill-designer" |
|
||||
|
||||
### Team Skills (团队协作)
|
||||
|
||||
Team Skills 使用 `team-worker` agent 架构,Coordinator 编排流水线,Workers 是加载了 role-spec 的 `team-worker` agents。
|
||||
|
||||
| Skill | 用途 | 架构 |
|
||||
|-------|------|------|
|
||||
| `team-planex` | 规划+执行 wave pipeline | planner + executor, 适合清晰 issue/roadmap |
|
||||
| `team-lifecycle` | 完整生命周期 (spec/impl/test) | team-worker agents with role-specs |
|
||||
| `team-lifecycle-v4` | 优化版生命周期 | Optimized pipeline |
|
||||
| `team-lifecycle-v3` | 基础版生命周期 | All roles invoke unified skill |
|
||||
| `team-coordinate` | 通用动态团队协调 | 运行时动态生成 role-specs |
|
||||
| `team-coordinate` | 通用团队协调 v1 | Dynamic role generation |
|
||||
| `team-brainstorm` | 团队头脑风暴 | Multi-perspective analysis |
|
||||
| `team-frontend` | 前端开发团队 | Frontend specialists |
|
||||
| `team-issue` | Issue 解决团队 | Issue resolution pipeline |
|
||||
| `team-iterdev` | 迭代开发团队 | Iterative development |
|
||||
| `team-review` | 代码扫描/漏洞审查 | Scanning + vulnerability review |
|
||||
| `team-roadmap-dev` | Roadmap 驱动开发 | Requirement → implementation |
|
||||
| `team-tech-debt` | 技术债务清理 | Debt identification + cleanup |
|
||||
| `team-testing` | 测试团队 | Test planning + execution |
|
||||
| `team-quality-assurance` | QA 团队 | Quality assurance pipeline |
|
||||
| `team-uidesign` | UI 设计团队 | Design system + prototyping |
|
||||
| `team-ultra-analyze` | 深度协作分析 | Deep collaborative analysis |
|
||||
| `team-executor` | 轻量执行 (恢复会话) | Resume existing sessions |
|
||||
| `team-executor` | 轻量执行 v2 | Improved session resumption |
|
||||
|
||||
### Standalone Skills (独立技能)
|
||||
|
||||
| Skill | 用途 |
|
||||
|-------|------|
|
||||
| `brainstorm` | 双模头脑风暴 (auto pipeline / single role) |
|
||||
| `review-code` | 多维度代码审查 |
|
||||
| `review-cycle` | 审查+自动修复编排 |
|
||||
| `spec-generator` | 6阶段规格文档链 (product-brief → PRD → architecture → epics) |
|
||||
| `issue-manage` | 交互式 Issue 管理 (CRUD) |
|
||||
| `memory-capture` | 统一记忆捕获 (session compact / quick tip) |
|
||||
| `memory-manage` | 统一记忆管理 (CLAUDE.md + documentation) |
|
||||
| `command-generator` | 命令文件生成器 |
|
||||
| `skill-generator` | Meta-skill: 创建新 Skill |
|
||||
| `skill-tuning` | Skill 诊断与优化 |
|
||||
|
||||
## Workflow Mapping (CCW Auto-Route)
|
||||
|
||||
CCW 根据任务意图自动选择工作流级别(参考 [ccw.md](../../commands/ccw.md)):
|
||||
|
||||
| 输入示例 | 类型 | 级别 | 流水线 |
|
||||
|---------|------|------|--------|
|
||||
| "Add API endpoint" | feature (low) | 2 | workflow-lite-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 |
|
||||
| "roadmap: OAuth + 2FA" | roadmap | 4 | roadmap-with-file → team-planex |
|
||||
| "specification: 用户系统" | spec-driven | 4 | spec-generator → workflow-plan → workflow-execute |
|
||||
| "team planex: 用户系统" | team-planex | Team | team-planex |
|
||||
|
||||
## Slash Commands
|
||||
|
||||
```bash
|
||||
@@ -116,6 +203,8 @@ Single source of truth: **[command.json](command.json)**
|
||||
/ccw-help # General help entry
|
||||
/ccw-help search <keyword> # Search commands
|
||||
/ccw-help next <command> # Get next step suggestions
|
||||
/ccw-help skills # Browse skill catalog
|
||||
/ccw-help teams # Browse team skills
|
||||
/ccw-issue # Issue reporting
|
||||
```
|
||||
|
||||
@@ -128,6 +217,9 @@ Single source of truth: **[command.json](command.json)**
|
||||
/ccw "头脑风暴: 用户通知系统" # → detect brainstorm, use brainstorm-with-file
|
||||
/ccw "深度调试: 系统随机崩溃" # → detect debug-file, use debug-with-file
|
||||
/ccw "协作分析: 认证架构设计" # → detect analyze-file, use analyze-with-file
|
||||
/ccw "roadmap: OAuth + 2FA 路线图" # → roadmap-with-file → team-planex
|
||||
/ccw "集成测试: 支付流程" # → integration-test-cycle
|
||||
/ccw "重构 auth 模块" # → refactor-cycle
|
||||
```
|
||||
|
||||
## Maintenance
|
||||
@@ -135,6 +227,7 @@ Single source of truth: **[command.json](command.json)**
|
||||
### Update Mechanism
|
||||
|
||||
CCW-Help skill supports manual updates through user confirmation dialog.
|
||||
Script scans `commands/`, `agents/`, and `skills/` directories to regenerate all indexes.
|
||||
|
||||
#### How to Update
|
||||
|
||||
@@ -153,18 +246,33 @@ cd D:/Claude_dms3/.claude/skills/ccw-help
|
||||
python scripts/auto-update.py
|
||||
```
|
||||
|
||||
This runs `analyze_commands.py` to scan commands/ and agents/ directories and regenerate `command.json`.
|
||||
This runs `analyze_commands.py` to scan commands/, agents/, and skills/ directories and regenerate `command.json` + all index files.
|
||||
|
||||
#### Update Scripts
|
||||
|
||||
- **`auto-update.py`**: Simple wrapper that runs analyze_commands.py
|
||||
- **`analyze_commands.py`**: Scans directories and generates command index
|
||||
- **`analyze_commands.py`**: Scans directories and generates command/agent/skill indexes
|
||||
|
||||
#### Generated Index Files
|
||||
|
||||
| File | Content |
|
||||
|------|---------|
|
||||
| `command.json` | Master index: commands + agents + skills |
|
||||
| `index/all-commands.json` | Flat command list |
|
||||
| `index/all-agents.json` | Agent directory |
|
||||
| `index/all-skills.json` | Skill directory with metadata |
|
||||
| `index/skills-by-category.json` | Skills grouped by category |
|
||||
| `index/by-category.json` | Commands by category |
|
||||
| `index/by-use-case.json` | Commands by usage scenario |
|
||||
| `index/essential-commands.json` | Core commands for onboarding |
|
||||
| `index/command-relationships.json` | Command flow relationships |
|
||||
|
||||
## Statistics
|
||||
|
||||
- **Commands**: 50+
|
||||
- **Agents**: 16
|
||||
- **Workflows**: 6 main levels + 3 with-file variants
|
||||
- **Agents**: 22
|
||||
- **Skills**: 36+ (7 workflow, 19 team, 10+ standalone/utility)
|
||||
- **Workflows**: 6 main levels + 5 with-file variants + 2 cycle variants
|
||||
- **Essential**: 10 core commands
|
||||
|
||||
## Core Principle
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -29,6 +29,11 @@
|
||||
"description": "|",
|
||||
"source": "../../../agents/cli-planning-agent.md"
|
||||
},
|
||||
{
|
||||
"name": "cli-roadmap-plan-agent",
|
||||
"description": "|",
|
||||
"source": "../../../agents/cli-roadmap-plan-agent.md"
|
||||
},
|
||||
{
|
||||
"name": "code-developer",
|
||||
"description": "|",
|
||||
@@ -74,6 +79,16 @@
|
||||
"description": "|",
|
||||
"source": "../../../agents/tdd-developer.md"
|
||||
},
|
||||
{
|
||||
"name": "team-worker",
|
||||
"description": "|",
|
||||
"source": "../../../agents/team-worker.md"
|
||||
},
|
||||
{
|
||||
"name": "test-action-planning-agent",
|
||||
"description": "|",
|
||||
"source": "../../../agents/test-action-planning-agent.md"
|
||||
},
|
||||
{
|
||||
"name": "test-context-search-agent",
|
||||
"description": "|",
|
||||
|
||||
@@ -43,6 +43,72 @@
|
||||
"difficulty": "Intermediate",
|
||||
"source": "../../../commands/cli/codex-review.md"
|
||||
},
|
||||
{
|
||||
"name": "flow-create",
|
||||
"command": "/flow-create",
|
||||
"description": "Flow Template Generator - Generate workflow templates for meta-skill/flow-coordinator with interactive 3-phase workflow",
|
||||
"arguments": "[template-name] [--output <path>]",
|
||||
"category": "general",
|
||||
"subcategory": null,
|
||||
"usage_scenario": "implementation",
|
||||
"difficulty": "Intermediate",
|
||||
"source": "../../../commands/flow-create.md"
|
||||
},
|
||||
{
|
||||
"name": "add",
|
||||
"command": "/idaw:add",
|
||||
"description": "Add IDAW tasks - manual creation or import from ccw issue",
|
||||
"arguments": "[-y|--yes] [--from-issue <id>[,<id>,...]] \\\"description\\\" [--type <task_type>] [--priority <1-5>]",
|
||||
"category": "idaw",
|
||||
"subcategory": null,
|
||||
"usage_scenario": "general",
|
||||
"difficulty": "Intermediate",
|
||||
"source": "../../../commands/idaw/add.md"
|
||||
},
|
||||
{
|
||||
"name": "resume",
|
||||
"command": "/idaw:resume",
|
||||
"description": "Resume interrupted IDAW session from last checkpoint",
|
||||
"arguments": "[-y|--yes] [session-id]",
|
||||
"category": "idaw",
|
||||
"subcategory": null,
|
||||
"usage_scenario": "session-management",
|
||||
"difficulty": "Intermediate",
|
||||
"source": "../../../commands/idaw/resume.md"
|
||||
},
|
||||
{
|
||||
"name": "run-coordinate",
|
||||
"command": "/idaw:run-coordinate",
|
||||
"description": "IDAW coordinator - execute task skill chains via external CLI with hook callbacks and git checkpoints",
|
||||
"arguments": "[-y|--yes] [--task <id>[,<id>,...]] [--dry-run] [--tool <tool>]",
|
||||
"category": "idaw",
|
||||
"subcategory": null,
|
||||
"usage_scenario": "general",
|
||||
"difficulty": "Intermediate",
|
||||
"source": "../../../commands/idaw/run-coordinate.md"
|
||||
},
|
||||
{
|
||||
"name": "run",
|
||||
"command": "/idaw:run",
|
||||
"description": "IDAW orchestrator - execute task skill chains serially with git checkpoints",
|
||||
"arguments": "[-y|--yes] [--task <id>[,<id>,...]] [--dry-run]",
|
||||
"category": "idaw",
|
||||
"subcategory": null,
|
||||
"usage_scenario": "general",
|
||||
"difficulty": "Intermediate",
|
||||
"source": "../../../commands/idaw/run.md"
|
||||
},
|
||||
{
|
||||
"name": "status",
|
||||
"command": "/idaw:status",
|
||||
"description": "View IDAW task and session progress",
|
||||
"arguments": "[session-id]",
|
||||
"category": "idaw",
|
||||
"subcategory": null,
|
||||
"usage_scenario": "session-management",
|
||||
"difficulty": "Beginner",
|
||||
"source": "../../../commands/idaw/status.md"
|
||||
},
|
||||
{
|
||||
"name": "convert-to-plan",
|
||||
"command": "/issue:convert-to-plan",
|
||||
@@ -131,6 +197,17 @@
|
||||
"difficulty": "Intermediate",
|
||||
"source": "../../../commands/issue/queue.md"
|
||||
},
|
||||
{
|
||||
"name": "prepare",
|
||||
"command": "/memory:prepare",
|
||||
"description": "Delegate to universal-executor agent to analyze project via Gemini/Qwen CLI and return JSON core content package for task context",
|
||||
"arguments": "[--tool gemini|qwen] \\\"task context description\\",
|
||||
"category": "memory",
|
||||
"subcategory": null,
|
||||
"usage_scenario": "general",
|
||||
"difficulty": "Intermediate",
|
||||
"source": "../../../commands/memory/prepare.md"
|
||||
},
|
||||
{
|
||||
"name": "style-skill-memory",
|
||||
"command": "/memory:style-skill-memory",
|
||||
@@ -175,6 +252,17 @@
|
||||
"difficulty": "Intermediate",
|
||||
"source": "../../../commands/workflow/clean.md"
|
||||
},
|
||||
{
|
||||
"name": "workflow:collaborative-plan-with-file",
|
||||
"command": "/workflow:collaborative-plan-with-file",
|
||||
"description": "Collaborative planning with Plan Note - Understanding agent creates shared plan-note.md template, parallel agents fill pre-allocated sections, conflict detection without merge. Outputs executable plan-note.md.",
|
||||
"arguments": "[-y|--yes] <task description> [--max-agents=5]",
|
||||
"category": "workflow",
|
||||
"subcategory": null,
|
||||
"usage_scenario": "planning",
|
||||
"difficulty": "Intermediate",
|
||||
"source": "../../../commands/workflow/collaborative-plan-with-file.md"
|
||||
},
|
||||
{
|
||||
"name": "debug-with-file",
|
||||
"command": "/workflow:debug-with-file",
|
||||
@@ -186,17 +274,72 @@
|
||||
"difficulty": "Intermediate",
|
||||
"source": "../../../commands/workflow/debug-with-file.md"
|
||||
},
|
||||
{
|
||||
"name": "init-guidelines",
|
||||
"command": "/workflow:init-guidelines",
|
||||
"description": "Interactive wizard to fill specs/*.md based on project analysis",
|
||||
"arguments": "[--reset]",
|
||||
"category": "workflow",
|
||||
"subcategory": null,
|
||||
"usage_scenario": "general",
|
||||
"difficulty": "Intermediate",
|
||||
"source": "../../../commands/workflow/init-guidelines.md"
|
||||
},
|
||||
{
|
||||
"name": "init-specs",
|
||||
"command": "/workflow:init-specs",
|
||||
"description": "Interactive wizard to create individual specs or personal constraints with scope selection",
|
||||
"arguments": "[--scope <global|project>] [--dimension <specs|personal>] [--category <general|exploration|planning|execution>]",
|
||||
"category": "workflow",
|
||||
"subcategory": null,
|
||||
"usage_scenario": "general",
|
||||
"difficulty": "Intermediate",
|
||||
"source": "../../../commands/workflow/init-specs.md"
|
||||
},
|
||||
{
|
||||
"name": "init",
|
||||
"command": "/workflow:init",
|
||||
"description": "Initialize project-level state with intelligent project analysis using cli-explore-agent",
|
||||
"arguments": "[--regenerate]",
|
||||
"arguments": "[--regenerate] [--skip-specs]",
|
||||
"category": "workflow",
|
||||
"subcategory": null,
|
||||
"usage_scenario": "general",
|
||||
"difficulty": "Intermediate",
|
||||
"source": "../../../commands/workflow/init.md"
|
||||
},
|
||||
{
|
||||
"name": "integration-test-cycle",
|
||||
"command": "/workflow:integration-test-cycle",
|
||||
"description": "Self-iterating integration test workflow with codebase exploration, test development, autonomous test-fix cycles, and reflection-driven strategy adjustment",
|
||||
"arguments": "[-y|--yes] [-c|--continue] [--max-iterations=N] \\\"module or feature description\\",
|
||||
"category": "workflow",
|
||||
"subcategory": null,
|
||||
"usage_scenario": "testing",
|
||||
"difficulty": "Intermediate",
|
||||
"source": "../../../commands/workflow/integration-test-cycle.md"
|
||||
},
|
||||
{
|
||||
"name": "refactor-cycle",
|
||||
"command": "/workflow:refactor-cycle",
|
||||
"description": "Tech debt discovery and self-iterating refactoring with multi-dimensional analysis, prioritized execution, regression validation, and reflection-driven adjustment",
|
||||
"arguments": "[-y|--yes] [-c|--continue] [--scope=module|project] \\\"module or refactoring goal\\",
|
||||
"category": "workflow",
|
||||
"subcategory": null,
|
||||
"usage_scenario": "general",
|
||||
"difficulty": "Intermediate",
|
||||
"source": "../../../commands/workflow/refactor-cycle.md"
|
||||
},
|
||||
{
|
||||
"name": "roadmap-with-file",
|
||||
"command": "/workflow:roadmap-with-file",
|
||||
"description": "Strategic requirement roadmap with iterative decomposition and issue creation. Outputs roadmap.md (human-readable, single source) + issues.jsonl (machine-executable). Handoff to team-planex.",
|
||||
"arguments": "[-y|--yes] [-c|--continue] [-m progressive|direct|auto] \\\"requirement description\\",
|
||||
"category": "workflow",
|
||||
"subcategory": null,
|
||||
"usage_scenario": "general",
|
||||
"difficulty": "Intermediate",
|
||||
"source": "../../../commands/workflow/roadmap-with-file.md"
|
||||
},
|
||||
{
|
||||
"name": "complete",
|
||||
"command": "/workflow:session:complete",
|
||||
@@ -233,8 +376,8 @@
|
||||
{
|
||||
"name": "solidify",
|
||||
"command": "/workflow:session:solidify",
|
||||
"description": "Crystallize session learnings and user-defined constraints into permanent project guidelines",
|
||||
"arguments": "[-y|--yes] [--type <convention|constraint|learning>] [--category <category>] \\\"rule or insight\\",
|
||||
"description": "Crystallize session learnings and user-defined constraints into permanent project guidelines, or compress recent memories",
|
||||
"arguments": "[-y|--yes] [--type <convention|constraint|learning|compress>] [--category <category>] [--limit <N>] \\\"rule or insight\\",
|
||||
"category": "workflow",
|
||||
"subcategory": "session",
|
||||
"usage_scenario": "general",
|
||||
@@ -252,6 +395,17 @@
|
||||
"difficulty": "Intermediate",
|
||||
"source": "../../../commands/workflow/session/start.md"
|
||||
},
|
||||
{
|
||||
"name": "sync",
|
||||
"command": "/workflow:session:sync",
|
||||
"description": "Quick-sync session work to specs/*.md and project-tech",
|
||||
"arguments": "[-y|--yes] [\\\"what was done\\\"]",
|
||||
"category": "workflow",
|
||||
"subcategory": "session",
|
||||
"usage_scenario": "general",
|
||||
"difficulty": "Intermediate",
|
||||
"source": "../../../commands/workflow/session/sync.md"
|
||||
},
|
||||
{
|
||||
"name": "animation-extract",
|
||||
"command": "/workflow:ui-design:animation-extract",
|
||||
@@ -277,7 +431,7 @@
|
||||
{
|
||||
"name": "design-sync",
|
||||
"command": "/workflow:ui-design:design-sync",
|
||||
"description": "Synchronize finalized design system references to brainstorming artifacts, preparing them for /workflow:plan consumption",
|
||||
"description": "Synchronize finalized design system references to brainstorming artifacts, preparing them for /workflow-plan consumption",
|
||||
"arguments": "--session <session_id> [--selected-prototypes \"<list>\"]",
|
||||
"category": "workflow",
|
||||
"subcategory": "ui-design",
|
||||
@@ -366,11 +520,11 @@
|
||||
"name": "unified-execute-with-file",
|
||||
"command": "/workflow:unified-execute-with-file",
|
||||
"description": "Universal execution engine for consuming any planning/brainstorm/analysis output with minimal progress tracking, multi-agent coordination, and incremental execution",
|
||||
"arguments": "[-y|--yes] [-p|--plan <path>] [-m|--mode sequential|parallel] [\\\"execution context or task name\\\"]",
|
||||
"arguments": "[-y|--yes] [<path>[,<path2>] | -p|--plan <path>[,<path2>]] [--auto-commit] [--commit-prefix \\\"prefix\\\"] [\\\"execution context or task name\\\"]",
|
||||
"category": "workflow",
|
||||
"subcategory": null,
|
||||
"usage_scenario": "implementation",
|
||||
"difficulty": "Intermediate",
|
||||
"source": "../../../commands/workflow/unified-execute-with-file.md"
|
||||
}
|
||||
]
|
||||
]
|
||||
352
.claude/skills/ccw-help/index/all-skills.json
Normal file
352
.claude/skills/ccw-help/index/all-skills.json
Normal file
@@ -0,0 +1,352 @@
|
||||
[
|
||||
{
|
||||
"name": "brainstorm",
|
||||
"description": "Unified brainstorming skill with dual-mode operation - auto pipeline and single role analysis. Triggers on \"brainstorm\", \"头脑风暴\".",
|
||||
"category": "standalone",
|
||||
"is_team": false,
|
||||
"has_phases": true,
|
||||
"has_role_specs": false,
|
||||
"version": "",
|
||||
"source": "../../../skills/brainstorm/SKILL.md"
|
||||
},
|
||||
{
|
||||
"name": "ccw-help",
|
||||
"description": "CCW command help system. Search, browse, recommend commands, skills, teams. Triggers \"ccw-help\", \"ccw-issue\".",
|
||||
"category": "utility",
|
||||
"is_team": false,
|
||||
"has_phases": false,
|
||||
"has_role_specs": false,
|
||||
"version": "8.0.0",
|
||||
"source": "../../../skills/ccw-help/SKILL.md"
|
||||
},
|
||||
{
|
||||
"name": "command-generator",
|
||||
"description": "Command file generator - 5 phase workflow for creating Claude Code command files with YAML frontmatter. Generates .md command files for project or user scope. Triggers on \"create command\", \"new command\", \"command generator\".",
|
||||
"category": "meta",
|
||||
"is_team": false,
|
||||
"has_phases": true,
|
||||
"has_role_specs": false,
|
||||
"version": "",
|
||||
"source": "../../../skills/command-generator/SKILL.md"
|
||||
},
|
||||
{
|
||||
"name": "issue-manage",
|
||||
"description": "Interactive issue management with menu-driven CRUD operations. Use when managing issues, viewing issue status, editing issue fields, performing bulk operations, or viewing issue history. Triggers on \"manage issue\", \"list issues\", \"edit issue\", \"delete issue\", \"bulk update\", \"issue dashboard\", \"issue history\", \"completed issues\".",
|
||||
"category": "utility",
|
||||
"is_team": false,
|
||||
"has_phases": false,
|
||||
"has_role_specs": false,
|
||||
"version": "",
|
||||
"source": "../../../skills/issue-manage/SKILL.md"
|
||||
},
|
||||
{
|
||||
"name": "memory-capture",
|
||||
"description": "Unified memory capture with routing - session compact or quick tips. Triggers on \"memory capture\", \"compact session\", \"save session\", \"quick tip\", \"memory tips\", \"记录\", \"压缩会话\".",
|
||||
"category": "utility",
|
||||
"is_team": false,
|
||||
"has_phases": true,
|
||||
"has_role_specs": false,
|
||||
"version": "",
|
||||
"source": "../../../skills/memory-capture/SKILL.md"
|
||||
},
|
||||
{
|
||||
"name": "memory-manage",
|
||||
"description": "Unified memory management - CLAUDE.md updates and documentation generation with interactive routing. Triggers on \"memory manage\", \"update claude\", \"update memory\", \"generate docs\", \"更新记忆\", \"生成文档\".",
|
||||
"category": "utility",
|
||||
"is_team": false,
|
||||
"has_phases": true,
|
||||
"has_role_specs": false,
|
||||
"version": "",
|
||||
"source": "../../../skills/memory-manage/SKILL.md"
|
||||
},
|
||||
{
|
||||
"name": "review-code",
|
||||
"description": "Multi-dimensional code review with structured reports. Analyzes correctness, readability, performance, security, testing, and architecture. Triggers on \"review code\", \"code review\", \"审查代码\", \"代码审查\".",
|
||||
"category": "review",
|
||||
"is_team": false,
|
||||
"has_phases": true,
|
||||
"has_role_specs": false,
|
||||
"version": "",
|
||||
"source": "../../../skills/review-code/SKILL.md"
|
||||
},
|
||||
{
|
||||
"name": "review-cycle",
|
||||
"description": "Unified multi-dimensional code review with automated fix orchestration. Routes to session-based (git changes), module-based (path patterns), or fix mode. Triggers on \"workflow:review-cycle\", \"workflow:review-session-cycle\", \"workflow:review-module-cycle\", \"workflow:review-cycle-fix\".",
|
||||
"category": "review",
|
||||
"is_team": false,
|
||||
"has_phases": true,
|
||||
"has_role_specs": false,
|
||||
"version": "",
|
||||
"source": "../../../skills/review-cycle/SKILL.md"
|
||||
},
|
||||
{
|
||||
"name": "skill-generator",
|
||||
"description": "Meta-skill for creating new Claude Code skills with configurable execution modes. Supports sequential (fixed order) and autonomous (stateless) phase patterns. Use for skill scaffolding, skill creation, or building new workflows. Triggers on \"create skill\", \"new skill\", \"skill generator\".",
|
||||
"category": "meta",
|
||||
"is_team": false,
|
||||
"has_phases": true,
|
||||
"has_role_specs": false,
|
||||
"version": "",
|
||||
"source": "../../../skills/skill-generator/SKILL.md"
|
||||
},
|
||||
{
|
||||
"name": "skill-tuning",
|
||||
"description": "Universal skill diagnosis and optimization tool. Detect and fix skill execution issues including context explosion, long-tail forgetting, data flow disruption, and agent coordination failures. Supports Gemini CLI for deep analysis. Triggers on \"skill tuning\", \"tune skill\", \"skill diagnosis\", \"optimize skill\", \"skill debug\".",
|
||||
"category": "meta",
|
||||
"is_team": false,
|
||||
"has_phases": true,
|
||||
"has_role_specs": false,
|
||||
"version": "",
|
||||
"source": "../../../skills/skill-tuning/SKILL.md"
|
||||
},
|
||||
{
|
||||
"name": "spec-generator",
|
||||
"description": "Specification generator - 6 phase document chain producing product brief, PRD, architecture, and epics. Triggers on \"generate spec\", \"create specification\", \"spec generator\", \"workflow:spec\".",
|
||||
"category": "meta",
|
||||
"is_team": false,
|
||||
"has_phases": true,
|
||||
"has_role_specs": false,
|
||||
"version": "",
|
||||
"source": "../../../skills/spec-generator/SKILL.md"
|
||||
},
|
||||
{
|
||||
"name": "team-arch-opt",
|
||||
"description": "Unified team skill for architecture optimization. Uses team-worker agent architecture with role-spec files for domain logic. Coordinator orchestrates pipeline, workers are team-worker agents. Triggers on \"team arch-opt\".",
|
||||
"category": "team",
|
||||
"is_team": true,
|
||||
"has_phases": false,
|
||||
"has_role_specs": true,
|
||||
"version": "",
|
||||
"source": "../../../skills/team-arch-opt/SKILL.md"
|
||||
},
|
||||
{
|
||||
"name": "team-brainstorm",
|
||||
"description": "Unified team skill for brainstorming team. All roles invoke this skill with --role arg for role-specific execution. Triggers on \"team brainstorm\".",
|
||||
"category": "team",
|
||||
"is_team": true,
|
||||
"has_phases": false,
|
||||
"has_role_specs": false,
|
||||
"version": "",
|
||||
"source": "../../../skills/team-brainstorm/SKILL.md"
|
||||
},
|
||||
{
|
||||
"name": "team-coordinate",
|
||||
"description": "Universal team coordination skill with dynamic role generation. Uses team-worker agent architecture with role-spec files. Only coordinator is built-in -- all worker roles are generated at runtime as role-specs and spawned via team-worker agent. Beat/cadence model for orchestration. Triggers on \"Team Coordinate \".",
|
||||
"category": "team",
|
||||
"is_team": true,
|
||||
"has_phases": false,
|
||||
"has_role_specs": false,
|
||||
"version": "",
|
||||
"source": "../../../skills/team-coordinate/SKILL.md"
|
||||
},
|
||||
{
|
||||
"name": "team-executor",
|
||||
"description": "Lightweight session execution skill. Resumes existing team-coordinate sessions for pure execution via team-worker agents. No analysis, no role generation -- only loads and executes. Session path required. Triggers on \"Team Executor\".",
|
||||
"category": "team",
|
||||
"is_team": true,
|
||||
"has_phases": false,
|
||||
"has_role_specs": false,
|
||||
"version": "",
|
||||
"source": "../../../skills/team-executor/SKILL.md"
|
||||
},
|
||||
{
|
||||
"name": "team-frontend",
|
||||
"description": "Unified team skill for frontend development team. All roles invoke this skill with --role arg. Built-in ui-ux-pro-max design intelligence. Triggers on \"team frontend\".",
|
||||
"category": "team",
|
||||
"is_team": true,
|
||||
"has_phases": false,
|
||||
"has_role_specs": false,
|
||||
"version": "",
|
||||
"source": "../../../skills/team-frontend/SKILL.md"
|
||||
},
|
||||
{
|
||||
"name": "team-issue",
|
||||
"description": "Unified team skill for issue resolution. All roles invoke this skill with --role arg for role-specific execution. Triggers on \"team issue\".",
|
||||
"category": "team",
|
||||
"is_team": true,
|
||||
"has_phases": false,
|
||||
"has_role_specs": false,
|
||||
"version": "",
|
||||
"source": "../../../skills/team-issue/SKILL.md"
|
||||
},
|
||||
{
|
||||
"name": "team-iterdev",
|
||||
"description": "Unified team skill for iterative development team. All roles invoke this skill with --role arg for role-specific execution. Triggers on \"team iterdev\".",
|
||||
"category": "team",
|
||||
"is_team": true,
|
||||
"has_phases": false,
|
||||
"has_role_specs": false,
|
||||
"version": "",
|
||||
"source": "../../../skills/team-iterdev/SKILL.md"
|
||||
},
|
||||
{
|
||||
"name": "team-lifecycle",
|
||||
"description": "Unified team skill for full lifecycle - spec/impl/test. Uses team-worker agent architecture with role-spec files for domain logic. Coordinator orchestrates pipeline, workers are team-worker agents loaded with role-specific Phase 2-4 specs. Triggers on \"team lifecycle\".",
|
||||
"category": "team",
|
||||
"is_team": true,
|
||||
"has_phases": false,
|
||||
"has_role_specs": true,
|
||||
"version": "",
|
||||
"source": "../../../skills/team-lifecycle/SKILL.md"
|
||||
},
|
||||
{
|
||||
"name": "team-perf-opt",
|
||||
"description": "Unified team skill for performance optimization. Uses team-worker agent architecture with role-spec files for domain logic. Coordinator orchestrates pipeline, workers are team-worker agents. Triggers on \"team perf-opt\".",
|
||||
"category": "team",
|
||||
"is_team": true,
|
||||
"has_phases": false,
|
||||
"has_role_specs": true,
|
||||
"version": "",
|
||||
"source": "../../../skills/team-perf-opt/SKILL.md"
|
||||
},
|
||||
{
|
||||
"name": "team-planex",
|
||||
"description": "Unified team skill for plan-and-execute pipeline. Uses team-worker agent architecture with role-spec files for domain logic. Coordinator orchestrates pipeline, workers are team-worker agents. Triggers on \"team planex\".",
|
||||
"category": "team",
|
||||
"is_team": true,
|
||||
"has_phases": false,
|
||||
"has_role_specs": true,
|
||||
"version": "",
|
||||
"source": "../../../skills/team-planex/SKILL.md"
|
||||
},
|
||||
{
|
||||
"name": "team-quality-assurance",
|
||||
"description": "Unified team skill for quality assurance team. All roles invoke this skill with --role arg for role-specific execution. Triggers on \"team quality-assurance\", \"team qa\".",
|
||||
"category": "team",
|
||||
"is_team": true,
|
||||
"has_phases": false,
|
||||
"has_role_specs": false,
|
||||
"version": "",
|
||||
"source": "../../../skills/team-quality-assurance/SKILL.md"
|
||||
},
|
||||
{
|
||||
"name": "team-review",
|
||||
"description": "Unified team skill for code scanning, vulnerability review, optimization suggestions, and automated fix. 4-role team: coordinator, scanner, reviewer, fixer. Triggers on team-review.",
|
||||
"category": "team",
|
||||
"is_team": false,
|
||||
"has_phases": false,
|
||||
"has_role_specs": false,
|
||||
"version": "",
|
||||
"source": "../../../skills/team-review/SKILL.md"
|
||||
},
|
||||
{
|
||||
"name": "team-roadmap-dev",
|
||||
"description": "Unified team skill for roadmap-driven development workflow. Coordinator discusses roadmap with user, then dispatches phased execution pipeline (plan -> execute -> verify). All roles invoke this skill with --role arg. Triggers on \"team roadmap-dev\".",
|
||||
"category": "team",
|
||||
"is_team": true,
|
||||
"has_phases": false,
|
||||
"has_role_specs": false,
|
||||
"version": "",
|
||||
"source": "../../../skills/team-roadmap-dev/SKILL.md"
|
||||
},
|
||||
{
|
||||
"name": "team-tech-debt",
|
||||
"description": "Unified team skill for tech debt identification and cleanup. All roles invoke this skill with --role arg for role-specific execution. Triggers on \"team tech-debt\", \"tech debt cleanup\", \"技术债务\".",
|
||||
"category": "team",
|
||||
"is_team": true,
|
||||
"has_phases": false,
|
||||
"has_role_specs": false,
|
||||
"version": "",
|
||||
"source": "../../../skills/team-tech-debt/SKILL.md"
|
||||
},
|
||||
{
|
||||
"name": "team-testing",
|
||||
"description": "Unified team skill for testing team. All roles invoke this skill with --role arg for role-specific execution. Triggers on \"team testing\".",
|
||||
"category": "team",
|
||||
"is_team": true,
|
||||
"has_phases": false,
|
||||
"has_role_specs": false,
|
||||
"version": "",
|
||||
"source": "../../../skills/team-testing/SKILL.md"
|
||||
},
|
||||
{
|
||||
"name": "team-uidesign",
|
||||
"description": "Unified team skill for UI design team. All roles invoke this skill with --role arg for role-specific execution. CP-9 Dual-Track design+implementation.",
|
||||
"category": "team",
|
||||
"is_team": true,
|
||||
"has_phases": false,
|
||||
"has_role_specs": false,
|
||||
"version": "",
|
||||
"source": "../../../skills/team-uidesign/SKILL.md"
|
||||
},
|
||||
{
|
||||
"name": "team-ultra-analyze",
|
||||
"description": "Unified team skill for deep collaborative analysis. All roles invoke this skill with --role arg for role-specific execution. Triggers on \"team ultra-analyze\", \"team analyze\".",
|
||||
"category": "team",
|
||||
"is_team": true,
|
||||
"has_phases": false,
|
||||
"has_role_specs": false,
|
||||
"version": "",
|
||||
"source": "../../../skills/team-ultra-analyze/SKILL.md"
|
||||
},
|
||||
{
|
||||
"name": "workflow-execute",
|
||||
"description": "Coordinate agent execution for workflow tasks with automatic session discovery, parallel task processing, and status tracking. Triggers on \"workflow-execute\".",
|
||||
"category": "workflow",
|
||||
"is_team": false,
|
||||
"has_phases": true,
|
||||
"has_role_specs": false,
|
||||
"version": "",
|
||||
"source": "../../../skills/workflow-execute/SKILL.md"
|
||||
},
|
||||
{
|
||||
"name": "workflow-lite-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-plan/SKILL.md"
|
||||
},
|
||||
{
|
||||
"name": "workflow-multi-cli-plan",
|
||||
"description": "Multi-CLI collaborative planning and execution skill with integrated execution phase. Triggers on \"workflow-multi-cli-plan\".",
|
||||
"category": "workflow",
|
||||
"is_team": false,
|
||||
"has_phases": true,
|
||||
"has_role_specs": false,
|
||||
"version": "",
|
||||
"source": "../../../skills/workflow-multi-cli-plan/SKILL.md"
|
||||
},
|
||||
{
|
||||
"name": "workflow-plan",
|
||||
"description": "Unified planning skill - 4-phase planning workflow, plan verification, and interactive replanning. Triggers on \"workflow-plan\", \"workflow-plan-verify\", \"workflow:replan\".",
|
||||
"category": "workflow",
|
||||
"is_team": false,
|
||||
"has_phases": true,
|
||||
"has_role_specs": false,
|
||||
"version": "",
|
||||
"source": "../../../skills/workflow-plan/SKILL.md"
|
||||
},
|
||||
{
|
||||
"name": "workflow-skill-designer",
|
||||
"description": "Meta-skill for designing orchestrator+phases structured workflow skills. Creates SKILL.md coordinator with progressive phase loading, TodoWrite patterns, and data flow. Triggers on \"design workflow skill\", \"create workflow skill\", \"workflow skill designer\".",
|
||||
"category": "workflow",
|
||||
"is_team": false,
|
||||
"has_phases": true,
|
||||
"has_role_specs": false,
|
||||
"version": "",
|
||||
"source": "../../../skills/workflow-skill-designer/SKILL.md"
|
||||
},
|
||||
{
|
||||
"name": "workflow-tdd-plan",
|
||||
"description": "Unified TDD workflow skill combining 6-phase TDD planning with Red-Green-Refactor task chain generation, and 4-phase TDD verification with compliance reporting. Triggers on \"workflow-tdd-plan\", \"workflow-tdd-verify\".",
|
||||
"category": "workflow",
|
||||
"is_team": false,
|
||||
"has_phases": true,
|
||||
"has_role_specs": false,
|
||||
"version": "",
|
||||
"source": "../../../skills/workflow-tdd-plan/SKILL.md"
|
||||
},
|
||||
{
|
||||
"name": "workflow-test-fix",
|
||||
"description": "Unified test-fix pipeline combining test generation (session, context, analysis, task gen) with iterative test-cycle execution (adaptive strategy, progressive testing, CLI fallback). Triggers on \"workflow-test-fix\", \"workflow-test-fix\", \"test fix workflow\".",
|
||||
"category": "workflow",
|
||||
"is_team": false,
|
||||
"has_phases": true,
|
||||
"has_role_specs": false,
|
||||
"version": "",
|
||||
"source": "../../../skills/workflow-test-fix/SKILL.md"
|
||||
}
|
||||
]
|
||||
@@ -22,6 +22,17 @@
|
||||
"usage_scenario": "general",
|
||||
"difficulty": "Intermediate",
|
||||
"source": "../../../commands/ccw.md"
|
||||
},
|
||||
{
|
||||
"name": "flow-create",
|
||||
"command": "/flow-create",
|
||||
"description": "",
|
||||
"arguments": "",
|
||||
"category": "general",
|
||||
"subcategory": null,
|
||||
"usage_scenario": "implementation",
|
||||
"difficulty": "Intermediate",
|
||||
"source": "../../../commands/flow-create.md"
|
||||
}
|
||||
]
|
||||
},
|
||||
@@ -51,6 +62,65 @@
|
||||
}
|
||||
]
|
||||
},
|
||||
"idaw": {
|
||||
"_root": [
|
||||
{
|
||||
"name": "add",
|
||||
"command": "/idaw:add",
|
||||
"description": "Add IDAW tasks - manual creation or import from ccw issue",
|
||||
"arguments": "[-y|--yes] [--from-issue <id>[,<id>,...]] \\\"description\\\" [--type <task_type>] [--priority <1-5>]",
|
||||
"category": "idaw",
|
||||
"subcategory": null,
|
||||
"usage_scenario": "general",
|
||||
"difficulty": "Intermediate",
|
||||
"source": "../../../commands/idaw/add.md"
|
||||
},
|
||||
{
|
||||
"name": "resume",
|
||||
"command": "/idaw:resume",
|
||||
"description": "Resume interrupted IDAW session from last checkpoint",
|
||||
"arguments": "[-y|--yes] [session-id]",
|
||||
"category": "idaw",
|
||||
"subcategory": null,
|
||||
"usage_scenario": "session-management",
|
||||
"difficulty": "Intermediate",
|
||||
"source": "../../../commands/idaw/resume.md"
|
||||
},
|
||||
{
|
||||
"name": "run-coordinate",
|
||||
"command": "/idaw:run-coordinate",
|
||||
"description": "IDAW coordinator - execute task skill chains via external CLI with hook callbacks and git checkpoints",
|
||||
"arguments": "[-y|--yes] [--task <id>[,<id>,...]] [--dry-run] [--tool <tool>]",
|
||||
"category": "idaw",
|
||||
"subcategory": null,
|
||||
"usage_scenario": "general",
|
||||
"difficulty": "Intermediate",
|
||||
"source": "../../../commands/idaw/run-coordinate.md"
|
||||
},
|
||||
{
|
||||
"name": "run",
|
||||
"command": "/idaw:run",
|
||||
"description": "IDAW orchestrator - execute task skill chains serially with git checkpoints",
|
||||
"arguments": "[-y|--yes] [--task <id>[,<id>,...]] [--dry-run]",
|
||||
"category": "idaw",
|
||||
"subcategory": null,
|
||||
"usage_scenario": "general",
|
||||
"difficulty": "Intermediate",
|
||||
"source": "../../../commands/idaw/run.md"
|
||||
},
|
||||
{
|
||||
"name": "status",
|
||||
"command": "/idaw:status",
|
||||
"description": "View IDAW task and session progress",
|
||||
"arguments": "[session-id]",
|
||||
"category": "idaw",
|
||||
"subcategory": null,
|
||||
"usage_scenario": "session-management",
|
||||
"difficulty": "Beginner",
|
||||
"source": "../../../commands/idaw/status.md"
|
||||
}
|
||||
]
|
||||
},
|
||||
"issue": {
|
||||
"_root": [
|
||||
{
|
||||
@@ -145,6 +215,17 @@
|
||||
},
|
||||
"memory": {
|
||||
"_root": [
|
||||
{
|
||||
"name": "prepare",
|
||||
"command": "/memory:prepare",
|
||||
"description": "Delegate to universal-executor agent to analyze project via Gemini/Qwen CLI and return JSON core content package for task context",
|
||||
"arguments": "[--tool gemini|qwen] \\\"task context description\\",
|
||||
"category": "memory",
|
||||
"subcategory": null,
|
||||
"usage_scenario": "general",
|
||||
"difficulty": "Intermediate",
|
||||
"source": "../../../commands/memory/prepare.md"
|
||||
},
|
||||
{
|
||||
"name": "style-skill-memory",
|
||||
"command": "/memory:style-skill-memory",
|
||||
@@ -193,6 +274,17 @@
|
||||
"difficulty": "Intermediate",
|
||||
"source": "../../../commands/workflow/clean.md"
|
||||
},
|
||||
{
|
||||
"name": "workflow:collaborative-plan-with-file",
|
||||
"command": "/workflow:collaborative-plan-with-file",
|
||||
"description": "Collaborative planning with Plan Note - Understanding agent creates shared plan-note.md template, parallel agents fill pre-allocated sections, conflict detection without merge. Outputs executable plan-note.md.",
|
||||
"arguments": "[-y|--yes] <task description> [--max-agents=5]",
|
||||
"category": "workflow",
|
||||
"subcategory": null,
|
||||
"usage_scenario": "planning",
|
||||
"difficulty": "Intermediate",
|
||||
"source": "../../../commands/workflow/collaborative-plan-with-file.md"
|
||||
},
|
||||
{
|
||||
"name": "debug-with-file",
|
||||
"command": "/workflow:debug-with-file",
|
||||
@@ -204,22 +296,77 @@
|
||||
"difficulty": "Intermediate",
|
||||
"source": "../../../commands/workflow/debug-with-file.md"
|
||||
},
|
||||
{
|
||||
"name": "init-guidelines",
|
||||
"command": "/workflow:init-guidelines",
|
||||
"description": "Interactive wizard to fill specs/*.md based on project analysis",
|
||||
"arguments": "[--reset]",
|
||||
"category": "workflow",
|
||||
"subcategory": null,
|
||||
"usage_scenario": "general",
|
||||
"difficulty": "Intermediate",
|
||||
"source": "../../../commands/workflow/init-guidelines.md"
|
||||
},
|
||||
{
|
||||
"name": "init-specs",
|
||||
"command": "/workflow:init-specs",
|
||||
"description": "Interactive wizard to create individual specs or personal constraints with scope selection",
|
||||
"arguments": "[--scope <global|project>] [--dimension <specs|personal>] [--category <general|exploration|planning|execution>]",
|
||||
"category": "workflow",
|
||||
"subcategory": null,
|
||||
"usage_scenario": "general",
|
||||
"difficulty": "Intermediate",
|
||||
"source": "../../../commands/workflow/init-specs.md"
|
||||
},
|
||||
{
|
||||
"name": "init",
|
||||
"command": "/workflow:init",
|
||||
"description": "Initialize project-level state with intelligent project analysis using cli-explore-agent",
|
||||
"arguments": "[--regenerate]",
|
||||
"arguments": "[--regenerate] [--skip-specs]",
|
||||
"category": "workflow",
|
||||
"subcategory": null,
|
||||
"usage_scenario": "general",
|
||||
"difficulty": "Intermediate",
|
||||
"source": "../../../commands/workflow/init.md"
|
||||
},
|
||||
{
|
||||
"name": "integration-test-cycle",
|
||||
"command": "/workflow:integration-test-cycle",
|
||||
"description": "Self-iterating integration test workflow with codebase exploration, test development, autonomous test-fix cycles, and reflection-driven strategy adjustment",
|
||||
"arguments": "[-y|--yes] [-c|--continue] [--max-iterations=N] \\\"module or feature description\\",
|
||||
"category": "workflow",
|
||||
"subcategory": null,
|
||||
"usage_scenario": "testing",
|
||||
"difficulty": "Intermediate",
|
||||
"source": "../../../commands/workflow/integration-test-cycle.md"
|
||||
},
|
||||
{
|
||||
"name": "refactor-cycle",
|
||||
"command": "/workflow:refactor-cycle",
|
||||
"description": "Tech debt discovery and self-iterating refactoring with multi-dimensional analysis, prioritized execution, regression validation, and reflection-driven adjustment",
|
||||
"arguments": "[-y|--yes] [-c|--continue] [--scope=module|project] \\\"module or refactoring goal\\",
|
||||
"category": "workflow",
|
||||
"subcategory": null,
|
||||
"usage_scenario": "general",
|
||||
"difficulty": "Intermediate",
|
||||
"source": "../../../commands/workflow/refactor-cycle.md"
|
||||
},
|
||||
{
|
||||
"name": "roadmap-with-file",
|
||||
"command": "/workflow:roadmap-with-file",
|
||||
"description": "Strategic requirement roadmap with iterative decomposition and issue creation. Outputs roadmap.md (human-readable, single source) + issues.jsonl (machine-executable). Handoff to team-planex.",
|
||||
"arguments": "[-y|--yes] [-c|--continue] [-m progressive|direct|auto] \\\"requirement description\\",
|
||||
"category": "workflow",
|
||||
"subcategory": null,
|
||||
"usage_scenario": "general",
|
||||
"difficulty": "Intermediate",
|
||||
"source": "../../../commands/workflow/roadmap-with-file.md"
|
||||
},
|
||||
{
|
||||
"name": "unified-execute-with-file",
|
||||
"command": "/workflow:unified-execute-with-file",
|
||||
"description": "Universal execution engine for consuming any planning/brainstorm/analysis output with minimal progress tracking, multi-agent coordination, and incremental execution",
|
||||
"arguments": "[-y|--yes] [-p|--plan <path>] [-m|--mode sequential|parallel] [\\\"execution context or task name\\\"]",
|
||||
"arguments": "[-y|--yes] [<path>[,<path2>] | -p|--plan <path>[,<path2>]] [--auto-commit] [--commit-prefix \\\"prefix\\\"] [\\\"execution context or task name\\\"]",
|
||||
"category": "workflow",
|
||||
"subcategory": null,
|
||||
"usage_scenario": "implementation",
|
||||
@@ -264,8 +411,8 @@
|
||||
{
|
||||
"name": "solidify",
|
||||
"command": "/workflow:session:solidify",
|
||||
"description": "Crystallize session learnings and user-defined constraints into permanent project guidelines",
|
||||
"arguments": "[-y|--yes] [--type <convention|constraint|learning>] [--category <category>] \\\"rule or insight\\",
|
||||
"description": "Crystallize session learnings and user-defined constraints into permanent project guidelines, or compress recent memories",
|
||||
"arguments": "[-y|--yes] [--type <convention|constraint|learning|compress>] [--category <category>] [--limit <N>] \\\"rule or insight\\",
|
||||
"category": "workflow",
|
||||
"subcategory": "session",
|
||||
"usage_scenario": "general",
|
||||
@@ -282,6 +429,17 @@
|
||||
"usage_scenario": "general",
|
||||
"difficulty": "Intermediate",
|
||||
"source": "../../../commands/workflow/session/start.md"
|
||||
},
|
||||
{
|
||||
"name": "sync",
|
||||
"command": "/workflow:session:sync",
|
||||
"description": "Quick-sync session work to specs/*.md and project-tech",
|
||||
"arguments": "[-y|--yes] [\\\"what was done\\\"]",
|
||||
"category": "workflow",
|
||||
"subcategory": "session",
|
||||
"usage_scenario": "general",
|
||||
"difficulty": "Intermediate",
|
||||
"source": "../../../commands/workflow/session/sync.md"
|
||||
}
|
||||
],
|
||||
"ui-design": [
|
||||
@@ -310,7 +468,7 @@
|
||||
{
|
||||
"name": "design-sync",
|
||||
"command": "/workflow:ui-design:design-sync",
|
||||
"description": "Synchronize finalized design system references to brainstorming artifacts, preparing them for /workflow:plan consumption",
|
||||
"description": "Synchronize finalized design system references to brainstorming artifacts, preparing them for /workflow-plan consumption",
|
||||
"arguments": "--session <session_id> [--selected-prototypes \"<list>\"]",
|
||||
"category": "workflow",
|
||||
"subcategory": "ui-design",
|
||||
@@ -397,4 +555,4 @@
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -33,6 +33,39 @@
|
||||
"difficulty": "Intermediate",
|
||||
"source": "../../../commands/cli/cli-init.md"
|
||||
},
|
||||
{
|
||||
"name": "add",
|
||||
"command": "/idaw:add",
|
||||
"description": "Add IDAW tasks - manual creation or import from ccw issue",
|
||||
"arguments": "[-y|--yes] [--from-issue <id>[,<id>,...]] \\\"description\\\" [--type <task_type>] [--priority <1-5>]",
|
||||
"category": "idaw",
|
||||
"subcategory": null,
|
||||
"usage_scenario": "general",
|
||||
"difficulty": "Intermediate",
|
||||
"source": "../../../commands/idaw/add.md"
|
||||
},
|
||||
{
|
||||
"name": "run-coordinate",
|
||||
"command": "/idaw:run-coordinate",
|
||||
"description": "IDAW coordinator - execute task skill chains via external CLI with hook callbacks and git checkpoints",
|
||||
"arguments": "[-y|--yes] [--task <id>[,<id>,...]] [--dry-run] [--tool <tool>]",
|
||||
"category": "idaw",
|
||||
"subcategory": null,
|
||||
"usage_scenario": "general",
|
||||
"difficulty": "Intermediate",
|
||||
"source": "../../../commands/idaw/run-coordinate.md"
|
||||
},
|
||||
{
|
||||
"name": "run",
|
||||
"command": "/idaw:run",
|
||||
"description": "IDAW orchestrator - execute task skill chains serially with git checkpoints",
|
||||
"arguments": "[-y|--yes] [--task <id>[,<id>,...]] [--dry-run]",
|
||||
"category": "idaw",
|
||||
"subcategory": null,
|
||||
"usage_scenario": "general",
|
||||
"difficulty": "Intermediate",
|
||||
"source": "../../../commands/idaw/run.md"
|
||||
},
|
||||
{
|
||||
"name": "issue:discover-by-prompt",
|
||||
"command": "/issue:discover-by-prompt",
|
||||
@@ -77,6 +110,17 @@
|
||||
"difficulty": "Intermediate",
|
||||
"source": "../../../commands/issue/queue.md"
|
||||
},
|
||||
{
|
||||
"name": "prepare",
|
||||
"command": "/memory:prepare",
|
||||
"description": "Delegate to universal-executor agent to analyze project via Gemini/Qwen CLI and return JSON core content package for task context",
|
||||
"arguments": "[--tool gemini|qwen] \\\"task context description\\",
|
||||
"category": "memory",
|
||||
"subcategory": null,
|
||||
"usage_scenario": "general",
|
||||
"difficulty": "Intermediate",
|
||||
"source": "../../../commands/memory/prepare.md"
|
||||
},
|
||||
{
|
||||
"name": "clean",
|
||||
"command": "/workflow:clean",
|
||||
@@ -99,17 +143,61 @@
|
||||
"difficulty": "Intermediate",
|
||||
"source": "../../../commands/workflow/debug-with-file.md"
|
||||
},
|
||||
{
|
||||
"name": "init-guidelines",
|
||||
"command": "/workflow:init-guidelines",
|
||||
"description": "Interactive wizard to fill specs/*.md based on project analysis",
|
||||
"arguments": "[--reset]",
|
||||
"category": "workflow",
|
||||
"subcategory": null,
|
||||
"usage_scenario": "general",
|
||||
"difficulty": "Intermediate",
|
||||
"source": "../../../commands/workflow/init-guidelines.md"
|
||||
},
|
||||
{
|
||||
"name": "init-specs",
|
||||
"command": "/workflow:init-specs",
|
||||
"description": "Interactive wizard to create individual specs or personal constraints with scope selection",
|
||||
"arguments": "[--scope <global|project>] [--dimension <specs|personal>] [--category <general|exploration|planning|execution>]",
|
||||
"category": "workflow",
|
||||
"subcategory": null,
|
||||
"usage_scenario": "general",
|
||||
"difficulty": "Intermediate",
|
||||
"source": "../../../commands/workflow/init-specs.md"
|
||||
},
|
||||
{
|
||||
"name": "init",
|
||||
"command": "/workflow:init",
|
||||
"description": "Initialize project-level state with intelligent project analysis using cli-explore-agent",
|
||||
"arguments": "[--regenerate]",
|
||||
"arguments": "[--regenerate] [--skip-specs]",
|
||||
"category": "workflow",
|
||||
"subcategory": null,
|
||||
"usage_scenario": "general",
|
||||
"difficulty": "Intermediate",
|
||||
"source": "../../../commands/workflow/init.md"
|
||||
},
|
||||
{
|
||||
"name": "refactor-cycle",
|
||||
"command": "/workflow:refactor-cycle",
|
||||
"description": "Tech debt discovery and self-iterating refactoring with multi-dimensional analysis, prioritized execution, regression validation, and reflection-driven adjustment",
|
||||
"arguments": "[-y|--yes] [-c|--continue] [--scope=module|project] \\\"module or refactoring goal\\",
|
||||
"category": "workflow",
|
||||
"subcategory": null,
|
||||
"usage_scenario": "general",
|
||||
"difficulty": "Intermediate",
|
||||
"source": "../../../commands/workflow/refactor-cycle.md"
|
||||
},
|
||||
{
|
||||
"name": "roadmap-with-file",
|
||||
"command": "/workflow:roadmap-with-file",
|
||||
"description": "Strategic requirement roadmap with iterative decomposition and issue creation. Outputs roadmap.md (human-readable, single source) + issues.jsonl (machine-executable). Handoff to team-planex.",
|
||||
"arguments": "[-y|--yes] [-c|--continue] [-m progressive|direct|auto] \\\"requirement description\\",
|
||||
"category": "workflow",
|
||||
"subcategory": null,
|
||||
"usage_scenario": "general",
|
||||
"difficulty": "Intermediate",
|
||||
"source": "../../../commands/workflow/roadmap-with-file.md"
|
||||
},
|
||||
{
|
||||
"name": "list",
|
||||
"command": "/workflow:session:list",
|
||||
@@ -124,8 +212,8 @@
|
||||
{
|
||||
"name": "solidify",
|
||||
"command": "/workflow:session:solidify",
|
||||
"description": "Crystallize session learnings and user-defined constraints into permanent project guidelines",
|
||||
"arguments": "[-y|--yes] [--type <convention|constraint|learning>] [--category <category>] \\\"rule or insight\\",
|
||||
"description": "Crystallize session learnings and user-defined constraints into permanent project guidelines, or compress recent memories",
|
||||
"arguments": "[-y|--yes] [--type <convention|constraint|learning|compress>] [--category <category>] [--limit <N>] \\\"rule or insight\\",
|
||||
"category": "workflow",
|
||||
"subcategory": "session",
|
||||
"usage_scenario": "general",
|
||||
@@ -143,6 +231,17 @@
|
||||
"difficulty": "Intermediate",
|
||||
"source": "../../../commands/workflow/session/start.md"
|
||||
},
|
||||
{
|
||||
"name": "sync",
|
||||
"command": "/workflow:session:sync",
|
||||
"description": "Quick-sync session work to specs/*.md and project-tech",
|
||||
"arguments": "[-y|--yes] [\\\"what was done\\\"]",
|
||||
"category": "workflow",
|
||||
"subcategory": "session",
|
||||
"usage_scenario": "general",
|
||||
"difficulty": "Intermediate",
|
||||
"source": "../../../commands/workflow/session/sync.md"
|
||||
},
|
||||
{
|
||||
"name": "animation-extract",
|
||||
"command": "/workflow:ui-design:animation-extract",
|
||||
@@ -223,6 +322,98 @@
|
||||
"source": "../../../commands/workflow/analyze-with-file.md"
|
||||
}
|
||||
],
|
||||
"implementation": [
|
||||
{
|
||||
"name": "flow-create",
|
||||
"command": "/flow-create",
|
||||
"description": "",
|
||||
"arguments": "",
|
||||
"category": "general",
|
||||
"subcategory": null,
|
||||
"usage_scenario": "implementation",
|
||||
"difficulty": "Intermediate",
|
||||
"source": "../../../commands/flow-create.md"
|
||||
},
|
||||
{
|
||||
"name": "execute",
|
||||
"command": "/issue:execute",
|
||||
"description": "Execute queue with DAG-based parallel orchestration (one commit per solution)",
|
||||
"arguments": "[-y|--yes] --queue <queue-id> [--worktree [<existing-path>]]",
|
||||
"category": "issue",
|
||||
"subcategory": null,
|
||||
"usage_scenario": "implementation",
|
||||
"difficulty": "Intermediate",
|
||||
"source": "../../../commands/issue/execute.md"
|
||||
},
|
||||
{
|
||||
"name": "generate",
|
||||
"command": "/workflow:ui-design:generate",
|
||||
"description": "Assemble UI prototypes by combining layout templates with design tokens (default animation support), pure assembler without new content generation",
|
||||
"arguments": "[--design-id <id>] [--session <id>]",
|
||||
"category": "workflow",
|
||||
"subcategory": "ui-design",
|
||||
"usage_scenario": "implementation",
|
||||
"difficulty": "Intermediate",
|
||||
"source": "../../../commands/workflow/ui-design/generate.md"
|
||||
},
|
||||
{
|
||||
"name": "unified-execute-with-file",
|
||||
"command": "/workflow:unified-execute-with-file",
|
||||
"description": "Universal execution engine for consuming any planning/brainstorm/analysis output with minimal progress tracking, multi-agent coordination, and incremental execution",
|
||||
"arguments": "[-y|--yes] [<path>[,<path2>] | -p|--plan <path>[,<path2>]] [--auto-commit] [--commit-prefix \\\"prefix\\\"] [\\\"execution context or task name\\\"]",
|
||||
"category": "workflow",
|
||||
"subcategory": null,
|
||||
"usage_scenario": "implementation",
|
||||
"difficulty": "Intermediate",
|
||||
"source": "../../../commands/workflow/unified-execute-with-file.md"
|
||||
}
|
||||
],
|
||||
"session-management": [
|
||||
{
|
||||
"name": "resume",
|
||||
"command": "/idaw:resume",
|
||||
"description": "Resume interrupted IDAW session from last checkpoint",
|
||||
"arguments": "[-y|--yes] [session-id]",
|
||||
"category": "idaw",
|
||||
"subcategory": null,
|
||||
"usage_scenario": "session-management",
|
||||
"difficulty": "Intermediate",
|
||||
"source": "../../../commands/idaw/resume.md"
|
||||
},
|
||||
{
|
||||
"name": "status",
|
||||
"command": "/idaw:status",
|
||||
"description": "View IDAW task and session progress",
|
||||
"arguments": "[session-id]",
|
||||
"category": "idaw",
|
||||
"subcategory": null,
|
||||
"usage_scenario": "session-management",
|
||||
"difficulty": "Beginner",
|
||||
"source": "../../../commands/idaw/status.md"
|
||||
},
|
||||
{
|
||||
"name": "complete",
|
||||
"command": "/workflow:session:complete",
|
||||
"description": "Mark active workflow session as complete, archive with lessons learned, update manifest, remove active flag",
|
||||
"arguments": "[-y|--yes] [--detailed]",
|
||||
"category": "workflow",
|
||||
"subcategory": "session",
|
||||
"usage_scenario": "session-management",
|
||||
"difficulty": "Intermediate",
|
||||
"source": "../../../commands/workflow/session/complete.md"
|
||||
},
|
||||
{
|
||||
"name": "resume",
|
||||
"command": "/workflow:session:resume",
|
||||
"description": "Resume the most recently paused workflow session with automatic session discovery and status update",
|
||||
"arguments": "",
|
||||
"category": "workflow",
|
||||
"subcategory": "session",
|
||||
"usage_scenario": "session-management",
|
||||
"difficulty": "Intermediate",
|
||||
"source": "../../../commands/workflow/session/resume.md"
|
||||
}
|
||||
],
|
||||
"planning": [
|
||||
{
|
||||
"name": "convert-to-plan",
|
||||
@@ -268,6 +459,17 @@
|
||||
"difficulty": "Intermediate",
|
||||
"source": "../../../commands/workflow/brainstorm-with-file.md"
|
||||
},
|
||||
{
|
||||
"name": "workflow:collaborative-plan-with-file",
|
||||
"command": "/workflow:collaborative-plan-with-file",
|
||||
"description": "Collaborative planning with Plan Note - Understanding agent creates shared plan-note.md template, parallel agents fill pre-allocated sections, conflict detection without merge. Outputs executable plan-note.md.",
|
||||
"arguments": "[-y|--yes] <task description> [--max-agents=5]",
|
||||
"category": "workflow",
|
||||
"subcategory": null,
|
||||
"usage_scenario": "planning",
|
||||
"difficulty": "Intermediate",
|
||||
"source": "../../../commands/workflow/collaborative-plan-with-file.md"
|
||||
},
|
||||
{
|
||||
"name": "workflow:ui-design:codify-style",
|
||||
"command": "/workflow:ui-design:codify-style",
|
||||
@@ -282,7 +484,7 @@
|
||||
{
|
||||
"name": "design-sync",
|
||||
"command": "/workflow:ui-design:design-sync",
|
||||
"description": "Synchronize finalized design system references to brainstorming artifacts, preparing them for /workflow:plan consumption",
|
||||
"description": "Synchronize finalized design system references to brainstorming artifacts, preparing them for /workflow-plan consumption",
|
||||
"arguments": "--session <session_id> [--selected-prototypes \"<list>\"]",
|
||||
"category": "workflow",
|
||||
"subcategory": "ui-design",
|
||||
@@ -313,41 +515,6 @@
|
||||
"source": "../../../commands/workflow/ui-design/reference-page-generator.md"
|
||||
}
|
||||
],
|
||||
"implementation": [
|
||||
{
|
||||
"name": "execute",
|
||||
"command": "/issue:execute",
|
||||
"description": "Execute queue with DAG-based parallel orchestration (one commit per solution)",
|
||||
"arguments": "[-y|--yes] --queue <queue-id> [--worktree [<existing-path>]]",
|
||||
"category": "issue",
|
||||
"subcategory": null,
|
||||
"usage_scenario": "implementation",
|
||||
"difficulty": "Intermediate",
|
||||
"source": "../../../commands/issue/execute.md"
|
||||
},
|
||||
{
|
||||
"name": "generate",
|
||||
"command": "/workflow:ui-design:generate",
|
||||
"description": "Assemble UI prototypes by combining layout templates with design tokens (default animation support), pure assembler without new content generation",
|
||||
"arguments": "[--design-id <id>] [--session <id>]",
|
||||
"category": "workflow",
|
||||
"subcategory": "ui-design",
|
||||
"usage_scenario": "implementation",
|
||||
"difficulty": "Intermediate",
|
||||
"source": "../../../commands/workflow/ui-design/generate.md"
|
||||
},
|
||||
{
|
||||
"name": "unified-execute-with-file",
|
||||
"command": "/workflow:unified-execute-with-file",
|
||||
"description": "Universal execution engine for consuming any planning/brainstorm/analysis output with minimal progress tracking, multi-agent coordination, and incremental execution",
|
||||
"arguments": "[-y|--yes] [-p|--plan <path>] [-m|--mode sequential|parallel] [\\\"execution context or task name\\\"]",
|
||||
"category": "workflow",
|
||||
"subcategory": null,
|
||||
"usage_scenario": "implementation",
|
||||
"difficulty": "Intermediate",
|
||||
"source": "../../../commands/workflow/unified-execute-with-file.md"
|
||||
}
|
||||
],
|
||||
"documentation": [
|
||||
{
|
||||
"name": "style-skill-memory",
|
||||
@@ -361,28 +528,17 @@
|
||||
"source": "../../../commands/memory/style-skill-memory.md"
|
||||
}
|
||||
],
|
||||
"session-management": [
|
||||
"testing": [
|
||||
{
|
||||
"name": "complete",
|
||||
"command": "/workflow:session:complete",
|
||||
"description": "Mark active workflow session as complete, archive with lessons learned, update manifest, remove active flag",
|
||||
"arguments": "[-y|--yes] [--detailed]",
|
||||
"name": "integration-test-cycle",
|
||||
"command": "/workflow:integration-test-cycle",
|
||||
"description": "Self-iterating integration test workflow with codebase exploration, test development, autonomous test-fix cycles, and reflection-driven strategy adjustment",
|
||||
"arguments": "[-y|--yes] [-c|--continue] [--max-iterations=N] \\\"module or feature description\\",
|
||||
"category": "workflow",
|
||||
"subcategory": "session",
|
||||
"usage_scenario": "session-management",
|
||||
"subcategory": null,
|
||||
"usage_scenario": "testing",
|
||||
"difficulty": "Intermediate",
|
||||
"source": "../../../commands/workflow/session/complete.md"
|
||||
},
|
||||
{
|
||||
"name": "resume",
|
||||
"command": "/workflow:session:resume",
|
||||
"description": "Resume the most recently paused workflow session with automatic session discovery and status update",
|
||||
"arguments": "",
|
||||
"category": "workflow",
|
||||
"subcategory": "session",
|
||||
"usage_scenario": "session-management",
|
||||
"difficulty": "Intermediate",
|
||||
"source": "../../../commands/workflow/session/resume.md"
|
||||
"source": "../../../commands/workflow/integration-test-cycle.md"
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,64 @@
|
||||
{
|
||||
"workflow-plan": {
|
||||
"calls_internally": [
|
||||
"workflow:session:start"
|
||||
],
|
||||
"next_steps": [
|
||||
"workflow-plan-verify",
|
||||
"workflow:session:list",
|
||||
"workflow:unified-execute-with-file"
|
||||
],
|
||||
"alternatives": [],
|
||||
"prerequisites": []
|
||||
},
|
||||
"workflow-tdd-plan": {
|
||||
"calls_internally": [
|
||||
"workflow:session:start"
|
||||
],
|
||||
"next_steps": [
|
||||
"workflow-tdd-verify",
|
||||
"workflow:session:list",
|
||||
"workflow:unified-execute-with-file"
|
||||
],
|
||||
"alternatives": [],
|
||||
"prerequisites": []
|
||||
},
|
||||
"workflow:unified-execute-with-file": {
|
||||
"prerequisites": [
|
||||
"workflow-plan",
|
||||
"workflow-tdd-plan"
|
||||
],
|
||||
"related": [
|
||||
"workflow:session:list",
|
||||
"workflow:session:resume"
|
||||
],
|
||||
"next_steps": [
|
||||
"review-cycle",
|
||||
"workflow-test-fix"
|
||||
]
|
||||
},
|
||||
"workflow-plan-verify": {
|
||||
"prerequisites": [
|
||||
"workflow-plan"
|
||||
],
|
||||
"next_steps": [
|
||||
"workflow:unified-execute-with-file"
|
||||
],
|
||||
"related": [
|
||||
"workflow:session:list"
|
||||
]
|
||||
},
|
||||
"workflow-tdd-verify": {
|
||||
"prerequisites": [
|
||||
"workflow:unified-execute-with-file"
|
||||
],
|
||||
"related": []
|
||||
},
|
||||
"workflow:session:start": {
|
||||
"next_steps": [],
|
||||
"next_steps": [
|
||||
"workflow-plan",
|
||||
"workflow:unified-execute-with-file"
|
||||
],
|
||||
"related": [
|
||||
"workflow:session:list",
|
||||
"workflow:session:resume"
|
||||
@@ -11,5 +69,23 @@
|
||||
"related": [
|
||||
"workflow:session:list"
|
||||
]
|
||||
},
|
||||
"workflow-lite-plan": {
|
||||
"calls_internally": [],
|
||||
"next_steps": [
|
||||
"workflow:session:list"
|
||||
],
|
||||
"alternatives": [
|
||||
"workflow-plan"
|
||||
],
|
||||
"prerequisites": []
|
||||
},
|
||||
"review-cycle": {
|
||||
"prerequisites": [
|
||||
"workflow:unified-execute-with-file"
|
||||
],
|
||||
"related": [
|
||||
"workflow-test-fix"
|
||||
]
|
||||
}
|
||||
}
|
||||
|
||||
@@ -10,4 +10,4 @@
|
||||
"difficulty": "Intermediate",
|
||||
"source": "../../../commands/workflow/session/start.md"
|
||||
}
|
||||
]
|
||||
]
|
||||
364
.claude/skills/ccw-help/index/skills-by-category.json
Normal file
364
.claude/skills/ccw-help/index/skills-by-category.json
Normal file
@@ -0,0 +1,364 @@
|
||||
{
|
||||
"standalone": [
|
||||
{
|
||||
"name": "brainstorm",
|
||||
"description": "Unified brainstorming skill with dual-mode operation - auto pipeline and single role analysis. Triggers on \"brainstorm\", \"头脑风暴\".",
|
||||
"category": "standalone",
|
||||
"is_team": false,
|
||||
"has_phases": true,
|
||||
"has_role_specs": false,
|
||||
"version": "",
|
||||
"source": "../../../skills/brainstorm/SKILL.md"
|
||||
}
|
||||
],
|
||||
"meta": [
|
||||
{
|
||||
"name": "command-generator",
|
||||
"description": "Command file generator - 5 phase workflow for creating Claude Code command files with YAML frontmatter. Generates .md command files for project or user scope. Triggers on \"create command\", \"new command\", \"command generator\".",
|
||||
"category": "meta",
|
||||
"is_team": false,
|
||||
"has_phases": true,
|
||||
"has_role_specs": false,
|
||||
"version": "",
|
||||
"source": "../../../skills/command-generator/SKILL.md"
|
||||
},
|
||||
{
|
||||
"name": "skill-generator",
|
||||
"description": "Meta-skill for creating new Claude Code skills with configurable execution modes. Supports sequential (fixed order) and autonomous (stateless) phase patterns. Use for skill scaffolding, skill creation, or building new workflows. Triggers on \"create skill\", \"new skill\", \"skill generator\".",
|
||||
"category": "meta",
|
||||
"is_team": false,
|
||||
"has_phases": true,
|
||||
"has_role_specs": false,
|
||||
"version": "",
|
||||
"source": "../../../skills/skill-generator/SKILL.md"
|
||||
},
|
||||
{
|
||||
"name": "skill-tuning",
|
||||
"description": "Universal skill diagnosis and optimization tool. Detect and fix skill execution issues including context explosion, long-tail forgetting, data flow disruption, and agent coordination failures. Supports Gemini CLI for deep analysis. Triggers on \"skill tuning\", \"tune skill\", \"skill diagnosis\", \"optimize skill\", \"skill debug\".",
|
||||
"category": "meta",
|
||||
"is_team": false,
|
||||
"has_phases": true,
|
||||
"has_role_specs": false,
|
||||
"version": "",
|
||||
"source": "../../../skills/skill-tuning/SKILL.md"
|
||||
},
|
||||
{
|
||||
"name": "spec-generator",
|
||||
"description": "Specification generator - 6 phase document chain producing product brief, PRD, architecture, and epics. Triggers on \"generate spec\", \"create specification\", \"spec generator\", \"workflow:spec\".",
|
||||
"category": "meta",
|
||||
"is_team": false,
|
||||
"has_phases": true,
|
||||
"has_role_specs": false,
|
||||
"version": "",
|
||||
"source": "../../../skills/spec-generator/SKILL.md"
|
||||
}
|
||||
],
|
||||
"utility": [
|
||||
{
|
||||
"name": "ccw-help",
|
||||
"description": "CCW command help system. Search, browse, recommend commands, skills, teams. Triggers \"ccw-help\", \"ccw-issue\".",
|
||||
"category": "utility",
|
||||
"is_team": false,
|
||||
"has_phases": false,
|
||||
"has_role_specs": false,
|
||||
"version": "8.0.0",
|
||||
"source": "../../../skills/ccw-help/SKILL.md"
|
||||
},
|
||||
{
|
||||
"name": "issue-manage",
|
||||
"description": "Interactive issue management with menu-driven CRUD operations. Use when managing issues, viewing issue status, editing issue fields, performing bulk operations, or viewing issue history. Triggers on \"manage issue\", \"list issues\", \"edit issue\", \"delete issue\", \"bulk update\", \"issue dashboard\", \"issue history\", \"completed issues\".",
|
||||
"category": "utility",
|
||||
"is_team": false,
|
||||
"has_phases": false,
|
||||
"has_role_specs": false,
|
||||
"version": "",
|
||||
"source": "../../../skills/issue-manage/SKILL.md"
|
||||
},
|
||||
{
|
||||
"name": "memory-capture",
|
||||
"description": "Unified memory capture with routing - session compact or quick tips. Triggers on \"memory capture\", \"compact session\", \"save session\", \"quick tip\", \"memory tips\", \"记录\", \"压缩会话\".",
|
||||
"category": "utility",
|
||||
"is_team": false,
|
||||
"has_phases": true,
|
||||
"has_role_specs": false,
|
||||
"version": "",
|
||||
"source": "../../../skills/memory-capture/SKILL.md"
|
||||
},
|
||||
{
|
||||
"name": "memory-manage",
|
||||
"description": "Unified memory management - CLAUDE.md updates and documentation generation with interactive routing. Triggers on \"memory manage\", \"update claude\", \"update memory\", \"generate docs\", \"更新记忆\", \"生成文档\".",
|
||||
"category": "utility",
|
||||
"is_team": false,
|
||||
"has_phases": true,
|
||||
"has_role_specs": false,
|
||||
"version": "",
|
||||
"source": "../../../skills/memory-manage/SKILL.md"
|
||||
}
|
||||
],
|
||||
"review": [
|
||||
{
|
||||
"name": "review-code",
|
||||
"description": "Multi-dimensional code review with structured reports. Analyzes correctness, readability, performance, security, testing, and architecture. Triggers on \"review code\", \"code review\", \"审查代码\", \"代码审查\".",
|
||||
"category": "review",
|
||||
"is_team": false,
|
||||
"has_phases": true,
|
||||
"has_role_specs": false,
|
||||
"version": "",
|
||||
"source": "../../../skills/review-code/SKILL.md"
|
||||
},
|
||||
{
|
||||
"name": "review-cycle",
|
||||
"description": "Unified multi-dimensional code review with automated fix orchestration. Routes to session-based (git changes), module-based (path patterns), or fix mode. Triggers on \"workflow:review-cycle\", \"workflow:review-session-cycle\", \"workflow:review-module-cycle\", \"workflow:review-cycle-fix\".",
|
||||
"category": "review",
|
||||
"is_team": false,
|
||||
"has_phases": true,
|
||||
"has_role_specs": false,
|
||||
"version": "",
|
||||
"source": "../../../skills/review-cycle/SKILL.md"
|
||||
}
|
||||
],
|
||||
"team": [
|
||||
{
|
||||
"name": "team-arch-opt",
|
||||
"description": "Unified team skill for architecture optimization. Uses team-worker agent architecture with role-spec files for domain logic. Coordinator orchestrates pipeline, workers are team-worker agents. Triggers on \"team arch-opt\".",
|
||||
"category": "team",
|
||||
"is_team": true,
|
||||
"has_phases": false,
|
||||
"has_role_specs": true,
|
||||
"version": "",
|
||||
"source": "../../../skills/team-arch-opt/SKILL.md"
|
||||
},
|
||||
{
|
||||
"name": "team-brainstorm",
|
||||
"description": "Unified team skill for brainstorming team. All roles invoke this skill with --role arg for role-specific execution. Triggers on \"team brainstorm\".",
|
||||
"category": "team",
|
||||
"is_team": true,
|
||||
"has_phases": false,
|
||||
"has_role_specs": false,
|
||||
"version": "",
|
||||
"source": "../../../skills/team-brainstorm/SKILL.md"
|
||||
},
|
||||
{
|
||||
"name": "team-coordinate",
|
||||
"description": "Universal team coordination skill with dynamic role generation. Uses team-worker agent architecture with role-spec files. Only coordinator is built-in -- all worker roles are generated at runtime as role-specs and spawned via team-worker agent. Beat/cadence model for orchestration. Triggers on \"Team Coordinate \".",
|
||||
"category": "team",
|
||||
"is_team": true,
|
||||
"has_phases": false,
|
||||
"has_role_specs": false,
|
||||
"version": "",
|
||||
"source": "../../../skills/team-coordinate/SKILL.md"
|
||||
},
|
||||
{
|
||||
"name": "team-executor",
|
||||
"description": "Lightweight session execution skill. Resumes existing team-coordinate sessions for pure execution via team-worker agents. No analysis, no role generation -- only loads and executes. Session path required. Triggers on \"Team Executor\".",
|
||||
"category": "team",
|
||||
"is_team": true,
|
||||
"has_phases": false,
|
||||
"has_role_specs": false,
|
||||
"version": "",
|
||||
"source": "../../../skills/team-executor/SKILL.md"
|
||||
},
|
||||
{
|
||||
"name": "team-frontend",
|
||||
"description": "Unified team skill for frontend development team. All roles invoke this skill with --role arg. Built-in ui-ux-pro-max design intelligence. Triggers on \"team frontend\".",
|
||||
"category": "team",
|
||||
"is_team": true,
|
||||
"has_phases": false,
|
||||
"has_role_specs": false,
|
||||
"version": "",
|
||||
"source": "../../../skills/team-frontend/SKILL.md"
|
||||
},
|
||||
{
|
||||
"name": "team-issue",
|
||||
"description": "Unified team skill for issue resolution. All roles invoke this skill with --role arg for role-specific execution. Triggers on \"team issue\".",
|
||||
"category": "team",
|
||||
"is_team": true,
|
||||
"has_phases": false,
|
||||
"has_role_specs": false,
|
||||
"version": "",
|
||||
"source": "../../../skills/team-issue/SKILL.md"
|
||||
},
|
||||
{
|
||||
"name": "team-iterdev",
|
||||
"description": "Unified team skill for iterative development team. All roles invoke this skill with --role arg for role-specific execution. Triggers on \"team iterdev\".",
|
||||
"category": "team",
|
||||
"is_team": true,
|
||||
"has_phases": false,
|
||||
"has_role_specs": false,
|
||||
"version": "",
|
||||
"source": "../../../skills/team-iterdev/SKILL.md"
|
||||
},
|
||||
{
|
||||
"name": "team-lifecycle",
|
||||
"description": "Unified team skill for full lifecycle - spec/impl/test. Uses team-worker agent architecture with role-spec files for domain logic. Coordinator orchestrates pipeline, workers are team-worker agents loaded with role-specific Phase 2-4 specs. Triggers on \"team lifecycle\".",
|
||||
"category": "team",
|
||||
"is_team": true,
|
||||
"has_phases": false,
|
||||
"has_role_specs": true,
|
||||
"version": "",
|
||||
"source": "../../../skills/team-lifecycle/SKILL.md"
|
||||
},
|
||||
{
|
||||
"name": "team-perf-opt",
|
||||
"description": "Unified team skill for performance optimization. Uses team-worker agent architecture with role-spec files for domain logic. Coordinator orchestrates pipeline, workers are team-worker agents. Triggers on \"team perf-opt\".",
|
||||
"category": "team",
|
||||
"is_team": true,
|
||||
"has_phases": false,
|
||||
"has_role_specs": true,
|
||||
"version": "",
|
||||
"source": "../../../skills/team-perf-opt/SKILL.md"
|
||||
},
|
||||
{
|
||||
"name": "team-planex",
|
||||
"description": "Unified team skill for plan-and-execute pipeline. Uses team-worker agent architecture with role-spec files for domain logic. Coordinator orchestrates pipeline, workers are team-worker agents. Triggers on \"team planex\".",
|
||||
"category": "team",
|
||||
"is_team": true,
|
||||
"has_phases": false,
|
||||
"has_role_specs": true,
|
||||
"version": "",
|
||||
"source": "../../../skills/team-planex/SKILL.md"
|
||||
},
|
||||
{
|
||||
"name": "team-quality-assurance",
|
||||
"description": "Unified team skill for quality assurance team. All roles invoke this skill with --role arg for role-specific execution. Triggers on \"team quality-assurance\", \"team qa\".",
|
||||
"category": "team",
|
||||
"is_team": true,
|
||||
"has_phases": false,
|
||||
"has_role_specs": false,
|
||||
"version": "",
|
||||
"source": "../../../skills/team-quality-assurance/SKILL.md"
|
||||
},
|
||||
{
|
||||
"name": "team-review",
|
||||
"description": "Unified team skill for code scanning, vulnerability review, optimization suggestions, and automated fix. 4-role team: coordinator, scanner, reviewer, fixer. Triggers on team-review.",
|
||||
"category": "team",
|
||||
"is_team": false,
|
||||
"has_phases": false,
|
||||
"has_role_specs": false,
|
||||
"version": "",
|
||||
"source": "../../../skills/team-review/SKILL.md"
|
||||
},
|
||||
{
|
||||
"name": "team-roadmap-dev",
|
||||
"description": "Unified team skill for roadmap-driven development workflow. Coordinator discusses roadmap with user, then dispatches phased execution pipeline (plan -> execute -> verify). All roles invoke this skill with --role arg. Triggers on \"team roadmap-dev\".",
|
||||
"category": "team",
|
||||
"is_team": true,
|
||||
"has_phases": false,
|
||||
"has_role_specs": false,
|
||||
"version": "",
|
||||
"source": "../../../skills/team-roadmap-dev/SKILL.md"
|
||||
},
|
||||
{
|
||||
"name": "team-tech-debt",
|
||||
"description": "Unified team skill for tech debt identification and cleanup. All roles invoke this skill with --role arg for role-specific execution. Triggers on \"team tech-debt\", \"tech debt cleanup\", \"技术债务\".",
|
||||
"category": "team",
|
||||
"is_team": true,
|
||||
"has_phases": false,
|
||||
"has_role_specs": false,
|
||||
"version": "",
|
||||
"source": "../../../skills/team-tech-debt/SKILL.md"
|
||||
},
|
||||
{
|
||||
"name": "team-testing",
|
||||
"description": "Unified team skill for testing team. All roles invoke this skill with --role arg for role-specific execution. Triggers on \"team testing\".",
|
||||
"category": "team",
|
||||
"is_team": true,
|
||||
"has_phases": false,
|
||||
"has_role_specs": false,
|
||||
"version": "",
|
||||
"source": "../../../skills/team-testing/SKILL.md"
|
||||
},
|
||||
{
|
||||
"name": "team-uidesign",
|
||||
"description": "Unified team skill for UI design team. All roles invoke this skill with --role arg for role-specific execution. CP-9 Dual-Track design+implementation.",
|
||||
"category": "team",
|
||||
"is_team": true,
|
||||
"has_phases": false,
|
||||
"has_role_specs": false,
|
||||
"version": "",
|
||||
"source": "../../../skills/team-uidesign/SKILL.md"
|
||||
},
|
||||
{
|
||||
"name": "team-ultra-analyze",
|
||||
"description": "Unified team skill for deep collaborative analysis. All roles invoke this skill with --role arg for role-specific execution. Triggers on \"team ultra-analyze\", \"team analyze\".",
|
||||
"category": "team",
|
||||
"is_team": true,
|
||||
"has_phases": false,
|
||||
"has_role_specs": false,
|
||||
"version": "",
|
||||
"source": "../../../skills/team-ultra-analyze/SKILL.md"
|
||||
}
|
||||
],
|
||||
"workflow": [
|
||||
{
|
||||
"name": "workflow-execute",
|
||||
"description": "Coordinate agent execution for workflow tasks with automatic session discovery, parallel task processing, and status tracking. Triggers on \"workflow-execute\".",
|
||||
"category": "workflow",
|
||||
"is_team": false,
|
||||
"has_phases": true,
|
||||
"has_role_specs": false,
|
||||
"version": "",
|
||||
"source": "../../../skills/workflow-execute/SKILL.md"
|
||||
},
|
||||
{
|
||||
"name": "workflow-lite-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-plan/SKILL.md"
|
||||
},
|
||||
{
|
||||
"name": "workflow-multi-cli-plan",
|
||||
"description": "Multi-CLI collaborative planning and execution skill with integrated execution phase. Triggers on \"workflow-multi-cli-plan\".",
|
||||
"category": "workflow",
|
||||
"is_team": false,
|
||||
"has_phases": true,
|
||||
"has_role_specs": false,
|
||||
"version": "",
|
||||
"source": "../../../skills/workflow-multi-cli-plan/SKILL.md"
|
||||
},
|
||||
{
|
||||
"name": "workflow-plan",
|
||||
"description": "Unified planning skill - 4-phase planning workflow, plan verification, and interactive replanning. Triggers on \"workflow-plan\", \"workflow-plan-verify\", \"workflow:replan\".",
|
||||
"category": "workflow",
|
||||
"is_team": false,
|
||||
"has_phases": true,
|
||||
"has_role_specs": false,
|
||||
"version": "",
|
||||
"source": "../../../skills/workflow-plan/SKILL.md"
|
||||
},
|
||||
{
|
||||
"name": "workflow-skill-designer",
|
||||
"description": "Meta-skill for designing orchestrator+phases structured workflow skills. Creates SKILL.md coordinator with progressive phase loading, TodoWrite patterns, and data flow. Triggers on \"design workflow skill\", \"create workflow skill\", \"workflow skill designer\".",
|
||||
"category": "workflow",
|
||||
"is_team": false,
|
||||
"has_phases": true,
|
||||
"has_role_specs": false,
|
||||
"version": "",
|
||||
"source": "../../../skills/workflow-skill-designer/SKILL.md"
|
||||
},
|
||||
{
|
||||
"name": "workflow-tdd-plan",
|
||||
"description": "Unified TDD workflow skill combining 6-phase TDD planning with Red-Green-Refactor task chain generation, and 4-phase TDD verification with compliance reporting. Triggers on \"workflow-tdd-plan\", \"workflow-tdd-verify\".",
|
||||
"category": "workflow",
|
||||
"is_team": false,
|
||||
"has_phases": true,
|
||||
"has_role_specs": false,
|
||||
"version": "",
|
||||
"source": "../../../skills/workflow-tdd-plan/SKILL.md"
|
||||
},
|
||||
{
|
||||
"name": "workflow-test-fix",
|
||||
"description": "Unified test-fix pipeline combining test generation (session, context, analysis, task gen) with iterative test-cycle execution (adaptive strategy, progressive testing, CLI fallback). Triggers on \"workflow-test-fix\", \"workflow-test-fix\", \"test fix workflow\".",
|
||||
"category": "workflow",
|
||||
"is_team": false,
|
||||
"has_phases": true,
|
||||
"has_role_specs": false,
|
||||
"version": "",
|
||||
"source": "../../../skills/workflow-test-fix/SKILL.md"
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -1,11 +1,10 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
Analyze all command/agent files and generate index files for ccw-help skill.
|
||||
Analyze all command/agent/skill files and generate index files for ccw-help skill.
|
||||
Outputs relative paths pointing to source files (no reference folder duplication).
|
||||
"""
|
||||
|
||||
import os
|
||||
import re
|
||||
import json
|
||||
from pathlib import Path
|
||||
from collections import defaultdict
|
||||
@@ -15,9 +14,13 @@ from typing import Dict, List, Any
|
||||
BASE_DIR = Path("D:/Claude_dms3/.claude")
|
||||
COMMANDS_DIR = BASE_DIR / "commands"
|
||||
AGENTS_DIR = BASE_DIR / "agents"
|
||||
SKILLS_DIR = BASE_DIR / "skills"
|
||||
SKILL_DIR = BASE_DIR / "skills" / "ccw-help"
|
||||
INDEX_DIR = SKILL_DIR / "index"
|
||||
|
||||
# Skills to skip (internal/shared, not user-facing)
|
||||
SKIP_SKILLS = {"_shared", "ccw-help"}
|
||||
|
||||
def parse_frontmatter(content: str) -> Dict[str, Any]:
|
||||
"""Extract YAML frontmatter from markdown content."""
|
||||
frontmatter = {}
|
||||
@@ -139,73 +142,129 @@ def analyze_agent_file(file_path: Path) -> Dict[str, Any]:
|
||||
"source": rel_path # Relative from index/ dir (e.g., "../../../agents/...")
|
||||
}
|
||||
|
||||
def categorize_skill(name: str, description: str) -> str:
|
||||
"""Determine skill category from name and description."""
|
||||
if name.startswith('team-'):
|
||||
return "team"
|
||||
if name.startswith('workflow-'):
|
||||
return "workflow"
|
||||
if name.startswith('review-'):
|
||||
return "review"
|
||||
if name.startswith('spec-') or name.startswith('command-') or name.startswith('skill-'):
|
||||
return "meta"
|
||||
if name.startswith('memory-') or name.startswith('issue-'):
|
||||
return "utility"
|
||||
return "standalone"
|
||||
|
||||
|
||||
def analyze_skill_dir(skill_path: Path) -> Dict[str, Any] | None:
|
||||
"""Analyze a skill directory and extract metadata from SKILL.md."""
|
||||
skill_md = skill_path / "SKILL.md"
|
||||
if not skill_md.exists():
|
||||
return None
|
||||
|
||||
with open(skill_md, 'r', encoding='utf-8') as f:
|
||||
content = f.read()
|
||||
|
||||
frontmatter = parse_frontmatter(content)
|
||||
|
||||
name = frontmatter.get('name', skill_path.name)
|
||||
description = frontmatter.get('description', '')
|
||||
allowed_tools = frontmatter.get('allowed-tools', '')
|
||||
version = frontmatter.get('version', '')
|
||||
|
||||
category = categorize_skill(name, description)
|
||||
|
||||
# Detect if it's a team skill (uses TeamCreate + SendMessage together)
|
||||
is_team = 'TeamCreate' in allowed_tools and 'SendMessage' in allowed_tools
|
||||
|
||||
# Detect if it has phases
|
||||
phases_dir = skill_path / "phases"
|
||||
has_phases = phases_dir.exists() and any(phases_dir.iterdir()) if phases_dir.exists() else False
|
||||
|
||||
# Detect if it has role-specs
|
||||
role_specs_dir = skill_path / "role-specs"
|
||||
has_role_specs = role_specs_dir.exists() and any(role_specs_dir.iterdir()) if role_specs_dir.exists() else False
|
||||
|
||||
# Build relative path from INDEX_DIR
|
||||
rel_from_base = skill_path.relative_to(BASE_DIR)
|
||||
rel_path = "../../../" + str(rel_from_base).replace('\\', '/') + "/SKILL.md"
|
||||
|
||||
return {
|
||||
"name": name,
|
||||
"description": description,
|
||||
"category": category,
|
||||
"is_team": is_team,
|
||||
"has_phases": has_phases,
|
||||
"has_role_specs": has_role_specs,
|
||||
"version": version,
|
||||
"source": rel_path
|
||||
}
|
||||
|
||||
|
||||
def build_command_relationships() -> Dict[str, Any]:
|
||||
"""Build command relationship mappings."""
|
||||
return {
|
||||
"workflow:plan": {
|
||||
"workflow-plan": {
|
||||
"calls_internally": ["workflow:session:start", "workflow:tools:context-gather", "workflow:tools:conflict-resolution", "workflow:tools:task-generate-agent"],
|
||||
"next_steps": ["workflow:plan-verify", "workflow:status", "workflow:execute"],
|
||||
"alternatives": ["workflow:tdd-plan"],
|
||||
"next_steps": ["workflow-plan-verify", "workflow:status", "workflow-execute"],
|
||||
"alternatives": ["workflow-tdd-plan"],
|
||||
"prerequisites": []
|
||||
},
|
||||
"workflow:tdd-plan": {
|
||||
"workflow-tdd-plan": {
|
||||
"calls_internally": ["workflow:session:start", "workflow:tools:context-gather", "workflow:tools:task-generate-tdd"],
|
||||
"next_steps": ["workflow:tdd-verify", "workflow:status", "workflow:execute"],
|
||||
"alternatives": ["workflow:plan"],
|
||||
"next_steps": ["workflow-tdd-verify", "workflow:status", "workflow-execute"],
|
||||
"alternatives": ["workflow-plan"],
|
||||
"prerequisites": []
|
||||
},
|
||||
"workflow:execute": {
|
||||
"prerequisites": ["workflow:plan", "workflow:tdd-plan"],
|
||||
"workflow-execute": {
|
||||
"prerequisites": ["workflow-plan", "workflow-tdd-plan"],
|
||||
"related": ["workflow:status", "workflow:resume"],
|
||||
"next_steps": ["workflow:review", "workflow:tdd-verify"]
|
||||
"next_steps": ["workflow:review", "workflow-tdd-verify"]
|
||||
},
|
||||
"workflow:plan-verify": {
|
||||
"prerequisites": ["workflow:plan"],
|
||||
"next_steps": ["workflow:execute"],
|
||||
"workflow-plan-verify": {
|
||||
"prerequisites": ["workflow-plan"],
|
||||
"next_steps": ["workflow-execute"],
|
||||
"related": ["workflow:status"]
|
||||
},
|
||||
"workflow:tdd-verify": {
|
||||
"prerequisites": ["workflow:execute"],
|
||||
"workflow-tdd-verify": {
|
||||
"prerequisites": ["workflow-execute"],
|
||||
"related": ["workflow:tools:tdd-coverage-analysis"]
|
||||
},
|
||||
"workflow:session:start": {
|
||||
"next_steps": ["workflow:plan", "workflow:execute"],
|
||||
"next_steps": ["workflow-plan", "workflow-execute"],
|
||||
"related": ["workflow:session:list", "workflow:session:resume"]
|
||||
},
|
||||
"workflow:session:resume": {
|
||||
"alternatives": ["workflow:resume"],
|
||||
"related": ["workflow:session:list", "workflow:status"]
|
||||
},
|
||||
"workflow:lite-plan": {
|
||||
"calls_internally": ["workflow:lite-execute"],
|
||||
"next_steps": ["workflow:lite-execute", "workflow:status"],
|
||||
"alternatives": ["workflow:plan"],
|
||||
"workflow-lite-plan": {
|
||||
"calls_internally": [],
|
||||
"next_steps": ["workflow:status"],
|
||||
"alternatives": ["workflow-plan"],
|
||||
"prerequisites": []
|
||||
},
|
||||
"workflow:lite-fix": {
|
||||
"next_steps": ["workflow:lite-execute", "workflow:status"],
|
||||
"alternatives": ["workflow:lite-plan"],
|
||||
"related": ["workflow:test-cycle-execute"]
|
||||
},
|
||||
"workflow:lite-execute": {
|
||||
"prerequisites": ["workflow:lite-plan", "workflow:lite-fix"],
|
||||
"related": ["workflow:execute", "workflow:status"]
|
||||
"next_steps": ["workflow:status"],
|
||||
"alternatives": ["workflow-lite-plan"],
|
||||
"related": ["workflow-test-fix"]
|
||||
},
|
||||
"workflow:review-session-cycle": {
|
||||
"prerequisites": ["workflow:execute"],
|
||||
"prerequisites": ["workflow-execute"],
|
||||
"next_steps": ["workflow:review-fix"],
|
||||
"related": ["workflow:review-module-cycle"]
|
||||
},
|
||||
"workflow:review-fix": {
|
||||
"prerequisites": ["workflow:review-module-cycle", "workflow:review-session-cycle"],
|
||||
"related": ["workflow:test-cycle-execute"]
|
||||
"related": ["workflow-test-fix"]
|
||||
},
|
||||
"memory:docs": {
|
||||
"calls_internally": ["workflow:session:start", "workflow:tools:context-gather"],
|
||||
"next_steps": ["workflow:execute"]
|
||||
"next_steps": ["workflow-execute"]
|
||||
},
|
||||
"memory:skill-memory": {
|
||||
"next_steps": ["workflow:plan", "cli:analyze"],
|
||||
"next_steps": ["workflow-plan", "cli:analyze"],
|
||||
"related": ["memory:load-skill-memory"]
|
||||
}
|
||||
}
|
||||
@@ -213,11 +272,11 @@ def build_command_relationships() -> Dict[str, Any]:
|
||||
def identify_essential_commands(all_commands: List[Dict]) -> List[Dict]:
|
||||
"""Identify the most essential commands for beginners."""
|
||||
essential_names = [
|
||||
"workflow:lite-plan", "workflow:lite-fix", "workflow:plan",
|
||||
"workflow:execute", "workflow:status", "workflow:session:start",
|
||||
"workflow-lite-plan", "workflow:lite-fix", "workflow-plan",
|
||||
"workflow-execute", "workflow:status", "workflow:session:start",
|
||||
"workflow:review-session-cycle", "cli:analyze", "cli:chat",
|
||||
"memory:docs", "workflow:brainstorm:artifacts",
|
||||
"workflow:plan-verify", "workflow:resume", "version"
|
||||
"workflow-plan-verify", "workflow:resume", "version"
|
||||
]
|
||||
|
||||
essential = []
|
||||
@@ -267,7 +326,24 @@ def main():
|
||||
except Exception as e:
|
||||
print(f" ERROR analyzing {agent_file}: {e}")
|
||||
|
||||
print(f"\nAnalyzed {len(all_commands)} commands, {len(all_agents)} agents")
|
||||
# Analyze skill directories
|
||||
print("\n=== Analyzing Skill Files ===")
|
||||
skill_dirs = [d for d in SKILLS_DIR.iterdir() if d.is_dir() and d.name not in SKIP_SKILLS]
|
||||
print(f"Found {len(skill_dirs)} skill directories")
|
||||
|
||||
all_skills = []
|
||||
for skill_dir in sorted(skill_dirs):
|
||||
try:
|
||||
metadata = analyze_skill_dir(skill_dir)
|
||||
if metadata:
|
||||
all_skills.append(metadata)
|
||||
print(f" OK {metadata['name']} [{metadata['category']}]")
|
||||
else:
|
||||
print(f" SKIP {skill_dir.name} (no SKILL.md)")
|
||||
except Exception as e:
|
||||
print(f" ERROR analyzing {skill_dir}: {e}")
|
||||
|
||||
print(f"\nAnalyzed {len(all_commands)} commands, {len(all_agents)} agents, {len(all_skills)} skills")
|
||||
|
||||
# Generate index files
|
||||
INDEX_DIR.mkdir(parents=True, exist_ok=True)
|
||||
@@ -320,15 +396,62 @@ def main():
|
||||
json.dump(relationships, f, indent=2, ensure_ascii=False)
|
||||
print(f"OK Generated {relationships_path.name} ({os.path.getsize(relationships_path)} bytes)")
|
||||
|
||||
# 7. all-skills.json
|
||||
all_skills_path = INDEX_DIR / "all-skills.json"
|
||||
with open(all_skills_path, 'w', encoding='utf-8') as f:
|
||||
json.dump(all_skills, f, indent=2, ensure_ascii=False)
|
||||
print(f"OK Generated {all_skills_path.name} ({os.path.getsize(all_skills_path)} bytes)")
|
||||
|
||||
# 8. skills-by-category.json
|
||||
skills_by_cat = defaultdict(list)
|
||||
for skill in all_skills:
|
||||
skills_by_cat[skill['category']].append(skill)
|
||||
|
||||
skills_by_cat_path = INDEX_DIR / "skills-by-category.json"
|
||||
with open(skills_by_cat_path, 'w', encoding='utf-8') as f:
|
||||
json.dump(dict(skills_by_cat), f, indent=2, ensure_ascii=False)
|
||||
print(f"OK Generated {skills_by_cat_path.name} ({os.path.getsize(skills_by_cat_path)} bytes)")
|
||||
|
||||
# Generate master command.json (includes commands, agents, skills)
|
||||
master = {
|
||||
"_metadata": {
|
||||
"version": "4.0.0",
|
||||
"total_commands": len(all_commands),
|
||||
"total_agents": len(all_agents),
|
||||
"total_skills": len(all_skills),
|
||||
"description": "Auto-generated CCW-Help command index from analyze_commands.py",
|
||||
"generated": "Auto-updated - all commands, agents, skills synced from file system",
|
||||
"last_sync": "command.json now stays in sync with CLI definitions"
|
||||
},
|
||||
"essential_commands": [cmd['name'] for cmd in essential],
|
||||
"commands": all_commands,
|
||||
"agents": all_agents,
|
||||
"skills": all_skills,
|
||||
"categories": sorted(set(cmd['category'] for cmd in all_commands)),
|
||||
"skill_categories": sorted(skills_by_cat.keys())
|
||||
}
|
||||
|
||||
master_path = SKILL_DIR / "command.json"
|
||||
with open(master_path, 'w', encoding='utf-8') as f:
|
||||
json.dump(master, f, indent=2, ensure_ascii=False)
|
||||
print(f"\nOK Generated command.json ({os.path.getsize(master_path)} bytes)")
|
||||
|
||||
# Print summary
|
||||
print("\n=== Summary ===")
|
||||
print(f"Commands: {len(all_commands)}")
|
||||
print(f"Agents: {len(all_agents)}")
|
||||
print(f"Skills: {len(all_skills)}")
|
||||
print(f"Essential: {len(essential)}")
|
||||
print(f"\nBy category:")
|
||||
print(f"\nCommands by category:")
|
||||
for cat in sorted(by_category.keys()):
|
||||
total = sum(len(cmds) for cmds in by_category[cat].values())
|
||||
print(f" {cat}: {total}")
|
||||
print(f"\nSkills by category:")
|
||||
for cat in sorted(skills_by_cat.keys()):
|
||||
print(f" {cat}: {len(skills_by_cat[cat])}")
|
||||
for skill in skills_by_cat[cat]:
|
||||
team_tag = " [team]" if skill['is_team'] else ""
|
||||
print(f" - {skill['name']}{team_tag}")
|
||||
|
||||
print(f"\nIndex: {INDEX_DIR}")
|
||||
print("=== Complete ===")
|
||||
|
||||
190
.claude/skills/command-generator/SKILL.md
Normal file
190
.claude/skills/command-generator/SKILL.md
Normal file
@@ -0,0 +1,190 @@
|
||||
---
|
||||
name: command-generator
|
||||
description: Command file generator - 5 phase workflow for creating Claude Code command files with YAML frontmatter. Generates .md command files for project or user scope. Triggers on "create command", "new command", "command generator".
|
||||
allowed-tools: Read, Write, Edit, Bash, Glob
|
||||
---
|
||||
|
||||
# Command Generator
|
||||
|
||||
CLI-based command file generator producing Claude Code command .md files through a structured 5-phase workflow. Supports both project-level (`.claude/commands/`) and user-level (`~/.claude/commands/`) command locations.
|
||||
|
||||
## Architecture Overview
|
||||
|
||||
```
|
||||
+-----------------------------------------------------------+
|
||||
| Command Generator |
|
||||
| |
|
||||
| Input: skillName, description, location, [group], [hint] |
|
||||
| | |
|
||||
| +-------------------------------------------------+ |
|
||||
| | Phase 1-5: Sequential Pipeline | |
|
||||
| | | |
|
||||
| | [P1] --> [P2] --> [P3] --> [P4] --> [P5] | |
|
||||
| | Param Target Template Content File | |
|
||||
| | Valid Path Loading Format Gen | |
|
||||
| +-------------------------------------------------+ |
|
||||
| | |
|
||||
| Output: {scope}/.claude/commands/{group}/{name}.md |
|
||||
| |
|
||||
+-----------------------------------------------------------+
|
||||
```
|
||||
|
||||
## Key Design Principles
|
||||
|
||||
1. **Single Responsibility**: Generates one command file per invocation
|
||||
2. **Scope Awareness**: Supports project and user-level command locations
|
||||
3. **Template-Driven**: Uses consistent template for all generated commands
|
||||
4. **Validation First**: Validates all required parameters before file operations
|
||||
5. **Non-Destructive**: Warns if command file already exists
|
||||
|
||||
---
|
||||
|
||||
## Execution Flow
|
||||
|
||||
```
|
||||
Phase 1: Parameter Validation
|
||||
- Ref: phases/01-parameter-validation.md
|
||||
- Validate: skillName (required), description (required), location (required)
|
||||
- Optional: group, argumentHint
|
||||
- Output: validated params object
|
||||
|
||||
Phase 2: Target Path Resolution
|
||||
- Ref: phases/02-target-path-resolution.md
|
||||
- Resolve: location -> target commands directory
|
||||
- Support: project (.claude/commands/) vs user (~/.claude/commands/)
|
||||
- Handle: group subdirectory if provided
|
||||
- Output: targetPath string
|
||||
|
||||
Phase 3: Template Loading
|
||||
- Ref: phases/03-template-loading.md
|
||||
- Load: templates/command-md.md
|
||||
- Template contains YAML frontmatter with placeholders
|
||||
- Output: templateContent string
|
||||
|
||||
Phase 4: Content Formatting
|
||||
- Ref: phases/04-content-formatting.md
|
||||
- Substitute: {{name}}, {{description}}, {{group}}, {{argumentHint}}
|
||||
- Handle: optional fields (group, argumentHint)
|
||||
- Output: formattedContent string
|
||||
|
||||
Phase 5: File Generation
|
||||
- Ref: phases/05-file-generation.md
|
||||
- Check: file existence (warn if exists)
|
||||
- Write: formatted content to target path
|
||||
- Output: success confirmation with file path
|
||||
```
|
||||
|
||||
## Usage Examples
|
||||
|
||||
### Basic Command (Project Scope)
|
||||
```javascript
|
||||
Skill(skill="command-generator", args={
|
||||
skillName: "deploy",
|
||||
description: "Deploy application to production environment",
|
||||
location: "project"
|
||||
})
|
||||
// Output: .claude/commands/deploy.md
|
||||
```
|
||||
|
||||
### Grouped Command with Argument Hint
|
||||
```javascript
|
||||
Skill(skill="command-generator", args={
|
||||
skillName: "create",
|
||||
description: "Create new issue from GitHub URL or text",
|
||||
location: "project",
|
||||
group: "issue",
|
||||
argumentHint: "[-y|--yes] <github-url | text-description> [--priority 1-5]"
|
||||
})
|
||||
// Output: .claude/commands/issue/create.md
|
||||
```
|
||||
|
||||
### User-Level Command
|
||||
```javascript
|
||||
Skill(skill="command-generator", args={
|
||||
skillName: "global-status",
|
||||
description: "Show global Claude Code status",
|
||||
location: "user"
|
||||
})
|
||||
// Output: ~/.claude/commands/global-status.md
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Reference Documents by Phase
|
||||
|
||||
### Phase 1: Parameter Validation
|
||||
| Document | Purpose | When to Use |
|
||||
|----------|---------|-------------|
|
||||
| [phases/01-parameter-validation.md](phases/01-parameter-validation.md) | Validate required parameters | Phase 1 execution |
|
||||
|
||||
### Phase 2: Target Path Resolution
|
||||
| Document | Purpose | When to Use |
|
||||
|----------|---------|-------------|
|
||||
| [phases/02-target-path-resolution.md](phases/02-target-path-resolution.md) | Resolve target directory | Phase 2 execution |
|
||||
|
||||
### Phase 3: Template Loading
|
||||
| Document | Purpose | When to Use |
|
||||
|----------|---------|-------------|
|
||||
| [phases/03-template-loading.md](phases/03-template-loading.md) | Load command template | Phase 3 execution |
|
||||
| [templates/command-md.md](templates/command-md.md) | Command file template | Template reference |
|
||||
|
||||
### Phase 4: Content Formatting
|
||||
| Document | Purpose | When to Use |
|
||||
|----------|---------|-------------|
|
||||
| [phases/04-content-formatting.md](phases/04-content-formatting.md) | Format content with params | Phase 4 execution |
|
||||
|
||||
### Phase 5: File Generation
|
||||
| Document | Purpose | When to Use |
|
||||
|----------|---------|-------------|
|
||||
| [phases/05-file-generation.md](phases/05-file-generation.md) | Write final file | Phase 5 execution |
|
||||
|
||||
### Design Specifications
|
||||
| Document | Purpose | When to Use |
|
||||
|----------|---------|-------------|
|
||||
| [specs/command-design-spec.md](specs/command-design-spec.md) | Command design guidelines | Understanding best practices |
|
||||
|
||||
---
|
||||
|
||||
## Output Structure
|
||||
|
||||
### Generated Command File
|
||||
|
||||
```markdown
|
||||
---
|
||||
name: {skillName}
|
||||
description: {description}
|
||||
{group} {argumentHint}
|
||||
---
|
||||
|
||||
# {skillName} Command
|
||||
|
||||
## Overview
|
||||
{Auto-generated placeholder for command overview}
|
||||
|
||||
## Usage
|
||||
{Auto-generated placeholder for usage examples}
|
||||
|
||||
## Execution Flow
|
||||
{Auto-generated placeholder for execution steps}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Error Handling
|
||||
|
||||
| Error | Stage | Action |
|
||||
|-------|-------|--------|
|
||||
| Missing skillName | Phase 1 | Error: "skillName is required" |
|
||||
| Missing description | Phase 1 | Error: "description is required" |
|
||||
| Missing location | Phase 1 | Error: "location is required (project or user)" |
|
||||
| Invalid location | Phase 2 | Error: "location must be 'project' or 'user'" |
|
||||
| Template not found | Phase 3 | Error: "Command template not found" |
|
||||
| File exists | Phase 5 | Warning: "Command file already exists, will overwrite" |
|
||||
| Write failure | Phase 5 | Error: "Failed to write command file" |
|
||||
|
||||
---
|
||||
|
||||
## Related Skills
|
||||
|
||||
- **skill-generator**: Create complete skills with phases, templates, and specs
|
||||
- **flow-coordinator**: Orchestrate multi-step command workflows
|
||||
@@ -0,0 +1,174 @@
|
||||
# Phase 1: Parameter Validation
|
||||
|
||||
Validate all required parameters for command generation.
|
||||
|
||||
## Objective
|
||||
|
||||
Ensure all required parameters are provided before proceeding with command generation:
|
||||
- **skillName**: Command identifier (required)
|
||||
- **description**: Command description (required)
|
||||
- **location**: Target scope - "project" or "user" (required)
|
||||
- **group**: Optional grouping subdirectory
|
||||
- **argumentHint**: Optional argument hint string
|
||||
|
||||
## Input
|
||||
|
||||
Parameters received from skill invocation:
|
||||
- `skillName`: string (required)
|
||||
- `description`: string (required)
|
||||
- `location`: "project" | "user" (required)
|
||||
- `group`: string (optional)
|
||||
- `argumentHint`: string (optional)
|
||||
|
||||
## Validation Rules
|
||||
|
||||
### Required Parameters
|
||||
|
||||
```javascript
|
||||
const requiredParams = {
|
||||
skillName: {
|
||||
type: 'string',
|
||||
minLength: 1,
|
||||
pattern: /^[a-z][a-z0-9-]*$/, // lowercase, alphanumeric, hyphens
|
||||
error: 'skillName must be lowercase alphanumeric with hyphens, starting with a letter'
|
||||
},
|
||||
description: {
|
||||
type: 'string',
|
||||
minLength: 10,
|
||||
error: 'description must be at least 10 characters'
|
||||
},
|
||||
location: {
|
||||
type: 'string',
|
||||
enum: ['project', 'user'],
|
||||
error: 'location must be "project" or "user"'
|
||||
}
|
||||
};
|
||||
```
|
||||
|
||||
### Optional Parameters
|
||||
|
||||
```javascript
|
||||
const optionalParams = {
|
||||
group: {
|
||||
type: 'string',
|
||||
pattern: /^[a-z][a-z0-9-]*$/,
|
||||
default: null,
|
||||
error: 'group must be lowercase alphanumeric with hyphens'
|
||||
},
|
||||
argumentHint: {
|
||||
type: 'string',
|
||||
default: '',
|
||||
error: 'argumentHint must be a string'
|
||||
}
|
||||
};
|
||||
```
|
||||
|
||||
## Execution Steps
|
||||
|
||||
### Step 1: Extract Parameters
|
||||
|
||||
```javascript
|
||||
// Extract from skill args
|
||||
const params = {
|
||||
skillName: args.skillName,
|
||||
description: args.description,
|
||||
location: args.location,
|
||||
group: args.group || null,
|
||||
argumentHint: args.argumentHint || ''
|
||||
};
|
||||
```
|
||||
|
||||
### Step 2: Validate Required Parameters
|
||||
|
||||
```javascript
|
||||
function validateRequired(params, rules) {
|
||||
const errors = [];
|
||||
|
||||
for (const [key, rule] of Object.entries(rules)) {
|
||||
const value = params[key];
|
||||
|
||||
// Check existence
|
||||
if (value === undefined || value === null || value === '') {
|
||||
errors.push(`${key} is required`);
|
||||
continue;
|
||||
}
|
||||
|
||||
// Check type
|
||||
if (typeof value !== rule.type) {
|
||||
errors.push(`${key} must be a ${rule.type}`);
|
||||
continue;
|
||||
}
|
||||
|
||||
// Check minLength
|
||||
if (rule.minLength && value.length < rule.minLength) {
|
||||
errors.push(`${key} must be at least ${rule.minLength} characters`);
|
||||
}
|
||||
|
||||
// Check pattern
|
||||
if (rule.pattern && !rule.pattern.test(value)) {
|
||||
errors.push(rule.error);
|
||||
}
|
||||
|
||||
// Check enum
|
||||
if (rule.enum && !rule.enum.includes(value)) {
|
||||
errors.push(`${key} must be one of: ${rule.enum.join(', ')}`);
|
||||
}
|
||||
}
|
||||
|
||||
return errors;
|
||||
}
|
||||
|
||||
const requiredErrors = validateRequired(params, requiredParams);
|
||||
if (requiredErrors.length > 0) {
|
||||
throw new Error(`Validation failed:\n${requiredErrors.join('\n')}`);
|
||||
}
|
||||
```
|
||||
|
||||
### Step 3: Validate Optional Parameters
|
||||
|
||||
```javascript
|
||||
function validateOptional(params, rules) {
|
||||
const warnings = [];
|
||||
|
||||
for (const [key, rule] of Object.entries(rules)) {
|
||||
const value = params[key];
|
||||
|
||||
if (value !== null && value !== undefined && value !== '') {
|
||||
if (rule.pattern && !rule.pattern.test(value)) {
|
||||
warnings.push(`${key}: ${rule.error}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return warnings;
|
||||
}
|
||||
|
||||
const optionalWarnings = validateOptional(params, optionalParams);
|
||||
// Log warnings but continue
|
||||
```
|
||||
|
||||
### Step 4: Normalize Parameters
|
||||
|
||||
```javascript
|
||||
const validatedParams = {
|
||||
skillName: params.skillName.trim().toLowerCase(),
|
||||
description: params.description.trim(),
|
||||
location: params.location.trim().toLowerCase(),
|
||||
group: params.group ? params.group.trim().toLowerCase() : null,
|
||||
argumentHint: params.argumentHint ? params.argumentHint.trim() : ''
|
||||
};
|
||||
```
|
||||
|
||||
## Output
|
||||
|
||||
```javascript
|
||||
{
|
||||
status: 'validated',
|
||||
params: validatedParams,
|
||||
warnings: optionalWarnings
|
||||
}
|
||||
```
|
||||
|
||||
## Next Phase
|
||||
|
||||
Proceed to [Phase 2: Target Path Resolution](02-target-path-resolution.md) with `validatedParams`.
|
||||
@@ -0,0 +1,171 @@
|
||||
# Phase 2: Target Path Resolution
|
||||
|
||||
Resolve the target commands directory based on location parameter.
|
||||
|
||||
## Objective
|
||||
|
||||
Determine the correct target path for the command file based on:
|
||||
- **location**: "project" or "user" scope
|
||||
- **group**: Optional subdirectory for command organization
|
||||
- **skillName**: Command filename (with .md extension)
|
||||
|
||||
## Input
|
||||
|
||||
From Phase 1 validation:
|
||||
```javascript
|
||||
{
|
||||
skillName: string, // e.g., "create"
|
||||
description: string,
|
||||
location: "project" | "user",
|
||||
group: string | null, // e.g., "issue"
|
||||
argumentHint: string
|
||||
}
|
||||
```
|
||||
|
||||
## Path Resolution Rules
|
||||
|
||||
### Location Mapping
|
||||
|
||||
```javascript
|
||||
const locationMap = {
|
||||
project: '.claude/commands',
|
||||
user: '~/.claude/commands' // Expands to user home directory
|
||||
};
|
||||
```
|
||||
|
||||
### Path Construction
|
||||
|
||||
```javascript
|
||||
function resolveTargetPath(params) {
|
||||
const baseDir = locationMap[params.location];
|
||||
|
||||
if (!baseDir) {
|
||||
throw new Error(`Invalid location: ${params.location}. Must be "project" or "user".`);
|
||||
}
|
||||
|
||||
// Expand ~ to user home if present
|
||||
const expandedBase = baseDir.startsWith('~')
|
||||
? path.join(os.homedir(), baseDir.slice(1))
|
||||
: baseDir;
|
||||
|
||||
// Build full path
|
||||
let targetPath;
|
||||
if (params.group) {
|
||||
// Grouped command: .claude/commands/{group}/{skillName}.md
|
||||
targetPath = path.join(expandedBase, params.group, `${params.skillName}.md`);
|
||||
} else {
|
||||
// Top-level command: .claude/commands/{skillName}.md
|
||||
targetPath = path.join(expandedBase, `${params.skillName}.md`);
|
||||
}
|
||||
|
||||
return targetPath;
|
||||
}
|
||||
```
|
||||
|
||||
## Execution Steps
|
||||
|
||||
### Step 1: Get Base Directory
|
||||
|
||||
```javascript
|
||||
const location = validatedParams.location;
|
||||
const baseDir = locationMap[location];
|
||||
|
||||
if (!baseDir) {
|
||||
throw new Error(`Invalid location: ${location}. Must be "project" or "user".`);
|
||||
}
|
||||
```
|
||||
|
||||
### Step 2: Expand User Path (if applicable)
|
||||
|
||||
```javascript
|
||||
const os = require('os');
|
||||
const path = require('path');
|
||||
|
||||
let expandedBase = baseDir;
|
||||
if (baseDir.startsWith('~')) {
|
||||
expandedBase = path.join(os.homedir(), baseDir.slice(1));
|
||||
}
|
||||
```
|
||||
|
||||
### Step 3: Construct Full Path
|
||||
|
||||
```javascript
|
||||
let targetPath;
|
||||
let targetDir;
|
||||
|
||||
if (validatedParams.group) {
|
||||
// Command with group subdirectory
|
||||
targetDir = path.join(expandedBase, validatedParams.group);
|
||||
targetPath = path.join(targetDir, `${validatedParams.skillName}.md`);
|
||||
} else {
|
||||
// Top-level command
|
||||
targetDir = expandedBase;
|
||||
targetPath = path.join(targetDir, `${validatedParams.skillName}.md`);
|
||||
}
|
||||
```
|
||||
|
||||
### Step 4: Ensure Target Directory Exists
|
||||
|
||||
```javascript
|
||||
// Check and create directory if needed
|
||||
Bash(`mkdir -p "${targetDir}"`);
|
||||
```
|
||||
|
||||
### Step 5: Check File Existence
|
||||
|
||||
```javascript
|
||||
const fileExists = Bash(`test -f "${targetPath}" && echo "EXISTS" || echo "NOT_FOUND"`);
|
||||
|
||||
if (fileExists.includes('EXISTS')) {
|
||||
console.warn(`Warning: Command file already exists at ${targetPath}. Will overwrite.`);
|
||||
}
|
||||
```
|
||||
|
||||
## Output
|
||||
|
||||
```javascript
|
||||
{
|
||||
status: 'resolved',
|
||||
targetPath: targetPath, // Full path to command file
|
||||
targetDir: targetDir, // Directory containing command
|
||||
fileName: `${skillName}.md`,
|
||||
fileExists: fileExists.includes('EXISTS'),
|
||||
params: validatedParams // Pass through to next phase
|
||||
}
|
||||
```
|
||||
|
||||
## Path Examples
|
||||
|
||||
### Project Scope (No Group)
|
||||
```
|
||||
location: "project"
|
||||
skillName: "deploy"
|
||||
-> .claude/commands/deploy.md
|
||||
```
|
||||
|
||||
### Project Scope (With Group)
|
||||
```
|
||||
location: "project"
|
||||
skillName: "create"
|
||||
group: "issue"
|
||||
-> .claude/commands/issue/create.md
|
||||
```
|
||||
|
||||
### User Scope (No Group)
|
||||
```
|
||||
location: "user"
|
||||
skillName: "global-status"
|
||||
-> ~/.claude/commands/global-status.md
|
||||
```
|
||||
|
||||
### User Scope (With Group)
|
||||
```
|
||||
location: "user"
|
||||
skillName: "sync"
|
||||
group: "session"
|
||||
-> ~/.claude/commands/session/sync.md
|
||||
```
|
||||
|
||||
## Next Phase
|
||||
|
||||
Proceed to [Phase 3: Template Loading](03-template-loading.md) with `targetPath` and `params`.
|
||||
123
.claude/skills/command-generator/phases/03-template-loading.md
Normal file
123
.claude/skills/command-generator/phases/03-template-loading.md
Normal file
@@ -0,0 +1,123 @@
|
||||
# Phase 3: Template Loading
|
||||
|
||||
Load the command template file for content generation.
|
||||
|
||||
## Objective
|
||||
|
||||
Load the command template from the skill's templates directory. The template provides:
|
||||
- YAML frontmatter structure
|
||||
- Placeholder variables for substitution
|
||||
- Standard command file sections
|
||||
|
||||
## Input
|
||||
|
||||
From Phase 2:
|
||||
```javascript
|
||||
{
|
||||
targetPath: string,
|
||||
targetDir: string,
|
||||
fileName: string,
|
||||
fileExists: boolean,
|
||||
params: {
|
||||
skillName: string,
|
||||
description: string,
|
||||
location: string,
|
||||
group: string | null,
|
||||
argumentHint: string
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## Template Location
|
||||
|
||||
```
|
||||
.claude/skills/command-generator/templates/command-md.md
|
||||
```
|
||||
|
||||
## Execution Steps
|
||||
|
||||
### Step 1: Locate Template File
|
||||
|
||||
```javascript
|
||||
// Template is located in the skill's templates directory
|
||||
const skillDir = '.claude/skills/command-generator';
|
||||
const templatePath = `${skillDir}/templates/command-md.md`;
|
||||
```
|
||||
|
||||
### Step 2: Read Template Content
|
||||
|
||||
```javascript
|
||||
const templateContent = Read(templatePath);
|
||||
|
||||
if (!templateContent) {
|
||||
throw new Error(`Command template not found at ${templatePath}`);
|
||||
}
|
||||
```
|
||||
|
||||
### Step 3: Validate Template Structure
|
||||
|
||||
```javascript
|
||||
// Verify template contains expected placeholders
|
||||
const requiredPlaceholders = ['{{name}}', '{{description}}'];
|
||||
const optionalPlaceholders = ['{{group}}', '{{argumentHint}}'];
|
||||
|
||||
for (const placeholder of requiredPlaceholders) {
|
||||
if (!templateContent.includes(placeholder)) {
|
||||
throw new Error(`Template missing required placeholder: ${placeholder}`);
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Step 4: Store Template for Next Phase
|
||||
|
||||
```javascript
|
||||
const template = {
|
||||
content: templateContent,
|
||||
requiredPlaceholders: requiredPlaceholders,
|
||||
optionalPlaceholders: optionalPlaceholders
|
||||
};
|
||||
```
|
||||
|
||||
## Template Format Reference
|
||||
|
||||
The template should follow this structure:
|
||||
|
||||
```markdown
|
||||
---
|
||||
name: {{name}}
|
||||
description: {{description}}
|
||||
{{#if group}}group: {{group}}{{/if}}
|
||||
{{#if argumentHint}}argument-hint: {{argumentHint}}{{/if}}
|
||||
---
|
||||
|
||||
# {{name}} Command
|
||||
|
||||
[Template content with placeholders]
|
||||
```
|
||||
|
||||
## Output
|
||||
|
||||
```javascript
|
||||
{
|
||||
status: 'loaded',
|
||||
template: {
|
||||
content: templateContent,
|
||||
requiredPlaceholders: requiredPlaceholders,
|
||||
optionalPlaceholders: optionalPlaceholders
|
||||
},
|
||||
targetPath: targetPath,
|
||||
params: params
|
||||
}
|
||||
```
|
||||
|
||||
## Error Handling
|
||||
|
||||
| Error | Action |
|
||||
|-------|--------|
|
||||
| Template file not found | Throw error with path |
|
||||
| Missing required placeholder | Throw error with missing placeholder name |
|
||||
| Empty template | Throw error |
|
||||
|
||||
## Next Phase
|
||||
|
||||
Proceed to [Phase 4: Content Formatting](04-content-formatting.md) with `template`, `targetPath`, and `params`.
|
||||
184
.claude/skills/command-generator/phases/04-content-formatting.md
Normal file
184
.claude/skills/command-generator/phases/04-content-formatting.md
Normal file
@@ -0,0 +1,184 @@
|
||||
# Phase 4: Content Formatting
|
||||
|
||||
Format template content by substituting placeholders with parameter values.
|
||||
|
||||
## Objective
|
||||
|
||||
Replace all placeholder variables in the template with validated parameter values:
|
||||
- `{{name}}` -> skillName
|
||||
- `{{description}}` -> description
|
||||
- `{{group}}` -> group (if provided)
|
||||
- `{{argumentHint}}` -> argumentHint (if provided)
|
||||
|
||||
## Input
|
||||
|
||||
From Phase 3:
|
||||
```javascript
|
||||
{
|
||||
template: {
|
||||
content: string,
|
||||
requiredPlaceholders: string[],
|
||||
optionalPlaceholders: string[]
|
||||
},
|
||||
targetPath: string,
|
||||
params: {
|
||||
skillName: string,
|
||||
description: string,
|
||||
location: string,
|
||||
group: string | null,
|
||||
argumentHint: string
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## Placeholder Mapping
|
||||
|
||||
```javascript
|
||||
const placeholderMap = {
|
||||
'{{name}}': params.skillName,
|
||||
'{{description}}': params.description,
|
||||
'{{group}}': params.group || '',
|
||||
'{{argumentHint}}': params.argumentHint || ''
|
||||
};
|
||||
```
|
||||
|
||||
## Execution Steps
|
||||
|
||||
### Step 1: Initialize Content
|
||||
|
||||
```javascript
|
||||
let formattedContent = template.content;
|
||||
```
|
||||
|
||||
### Step 2: Substitute Required Placeholders
|
||||
|
||||
```javascript
|
||||
// These must always be replaced
|
||||
formattedContent = formattedContent.replace(/\{\{name\}\}/g, params.skillName);
|
||||
formattedContent = formattedContent.replace(/\{\{description\}\}/g, params.description);
|
||||
```
|
||||
|
||||
### Step 3: Handle Optional Placeholders
|
||||
|
||||
```javascript
|
||||
// Group placeholder
|
||||
if (params.group) {
|
||||
formattedContent = formattedContent.replace(/\{\{group\}\}/g, params.group);
|
||||
} else {
|
||||
// Remove group line if not provided
|
||||
formattedContent = formattedContent.replace(/^group: \{\{group\}\}\n?/gm, '');
|
||||
formattedContent = formattedContent.replace(/\{\{group\}\}/g, '');
|
||||
}
|
||||
|
||||
// Argument hint placeholder
|
||||
if (params.argumentHint) {
|
||||
formattedContent = formattedContent.replace(/\{\{argumentHint\}\}/g, params.argumentHint);
|
||||
} else {
|
||||
// Remove argument-hint line if not provided
|
||||
formattedContent = formattedContent.replace(/^argument-hint: \{\{argumentHint\}\}\n?/gm, '');
|
||||
formattedContent = formattedContent.replace(/\{\{argumentHint\}\}/g, '');
|
||||
}
|
||||
```
|
||||
|
||||
### Step 4: Handle Conditional Sections
|
||||
|
||||
```javascript
|
||||
// Remove empty frontmatter lines (caused by missing optional fields)
|
||||
formattedContent = formattedContent.replace(/\n{3,}/g, '\n\n');
|
||||
|
||||
// Handle {{#if group}} style conditionals
|
||||
if (formattedContent.includes('{{#if')) {
|
||||
// Process group conditional
|
||||
if (params.group) {
|
||||
formattedContent = formattedContent.replace(/\{\{#if group\}\}([\s\S]*?)\{\{\/if\}\}/g, '$1');
|
||||
} else {
|
||||
formattedContent = formattedContent.replace(/\{\{#if group\}\}[\s\S]*?\{\{\/if\}\}/g, '');
|
||||
}
|
||||
|
||||
// Process argumentHint conditional
|
||||
if (params.argumentHint) {
|
||||
formattedContent = formattedContent.replace(/\{\{#if argumentHint\}\}([\s\S]*?)\{\{\/if\}\}/g, '$1');
|
||||
} else {
|
||||
formattedContent = formattedContent.replace(/\{\{#if argumentHint\}\}[\s\S]*?\{\{\/if\}\}/g, '');
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Step 5: Validate Final Content
|
||||
|
||||
```javascript
|
||||
// Ensure no unresolved placeholders remain
|
||||
const unresolvedPlaceholders = formattedContent.match(/\{\{[^}]+\}\}/g);
|
||||
if (unresolvedPlaceholders) {
|
||||
console.warn(`Warning: Unresolved placeholders found: ${unresolvedPlaceholders.join(', ')}`);
|
||||
}
|
||||
|
||||
// Ensure frontmatter is valid
|
||||
const frontmatterMatch = formattedContent.match(/^---\n([\s\S]*?)\n---/);
|
||||
if (!frontmatterMatch) {
|
||||
throw new Error('Generated content has invalid frontmatter structure');
|
||||
}
|
||||
```
|
||||
|
||||
### Step 6: Generate Summary
|
||||
|
||||
```javascript
|
||||
const summary = {
|
||||
name: params.skillName,
|
||||
description: params.description.substring(0, 50) + (params.description.length > 50 ? '...' : ''),
|
||||
location: params.location,
|
||||
group: params.group,
|
||||
hasArgumentHint: !!params.argumentHint
|
||||
};
|
||||
```
|
||||
|
||||
## Output
|
||||
|
||||
```javascript
|
||||
{
|
||||
status: 'formatted',
|
||||
content: formattedContent,
|
||||
targetPath: targetPath,
|
||||
summary: summary
|
||||
}
|
||||
```
|
||||
|
||||
## Content Example
|
||||
|
||||
### Input Template
|
||||
```markdown
|
||||
---
|
||||
name: {{name}}
|
||||
description: {{description}}
|
||||
{{#if group}}group: {{group}}{{/if}}
|
||||
{{#if argumentHint}}argument-hint: {{argumentHint}}{{/if}}
|
||||
---
|
||||
|
||||
# {{name}} Command
|
||||
```
|
||||
|
||||
### Output (with all fields)
|
||||
```markdown
|
||||
---
|
||||
name: create
|
||||
description: Create structured issue from GitHub URL or text description
|
||||
group: issue
|
||||
argument-hint: [-y|--yes] <github-url | text-description> [--priority 1-5]
|
||||
---
|
||||
|
||||
# create Command
|
||||
```
|
||||
|
||||
### Output (minimal fields)
|
||||
```markdown
|
||||
---
|
||||
name: deploy
|
||||
description: Deploy application to production environment
|
||||
---
|
||||
|
||||
# deploy Command
|
||||
```
|
||||
|
||||
## Next Phase
|
||||
|
||||
Proceed to [Phase 5: File Generation](05-file-generation.md) with `content` and `targetPath`.
|
||||
185
.claude/skills/command-generator/phases/05-file-generation.md
Normal file
185
.claude/skills/command-generator/phases/05-file-generation.md
Normal file
@@ -0,0 +1,185 @@
|
||||
# Phase 5: File Generation
|
||||
|
||||
Write the formatted content to the target command file.
|
||||
|
||||
## Objective
|
||||
|
||||
Generate the final command file by:
|
||||
1. Checking for existing file (warn if present)
|
||||
2. Writing formatted content to target path
|
||||
3. Confirming successful generation
|
||||
|
||||
## Input
|
||||
|
||||
From Phase 4:
|
||||
```javascript
|
||||
{
|
||||
status: 'formatted',
|
||||
content: string,
|
||||
targetPath: string,
|
||||
summary: {
|
||||
name: string,
|
||||
description: string,
|
||||
location: string,
|
||||
group: string | null,
|
||||
hasArgumentHint: boolean
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## Execution Steps
|
||||
|
||||
### Step 1: Pre-Write Check
|
||||
|
||||
```javascript
|
||||
// Check if file already exists
|
||||
const fileExists = Bash(`test -f "${targetPath}" && echo "EXISTS" || echo "NOT_FOUND"`);
|
||||
|
||||
if (fileExists.includes('EXISTS')) {
|
||||
console.warn(`
|
||||
WARNING: Command file already exists at: ${targetPath}
|
||||
The file will be overwritten with new content.
|
||||
`);
|
||||
}
|
||||
```
|
||||
|
||||
### Step 2: Ensure Directory Exists
|
||||
|
||||
```javascript
|
||||
// Get directory from target path
|
||||
const targetDir = path.dirname(targetPath);
|
||||
|
||||
// Create directory if it doesn't exist
|
||||
Bash(`mkdir -p "${targetDir}"`);
|
||||
```
|
||||
|
||||
### Step 3: Write File
|
||||
|
||||
```javascript
|
||||
// Write the formatted content
|
||||
Write(targetPath, content);
|
||||
```
|
||||
|
||||
### Step 4: Verify Write
|
||||
|
||||
```javascript
|
||||
// Confirm file was created
|
||||
const verifyExists = Bash(`test -f "${targetPath}" && echo "SUCCESS" || echo "FAILED"`);
|
||||
|
||||
if (!verifyExists.includes('SUCCESS')) {
|
||||
throw new Error(`Failed to create command file at ${targetPath}`);
|
||||
}
|
||||
|
||||
// Verify content was written
|
||||
const writtenContent = Read(targetPath);
|
||||
if (!writtenContent || writtenContent.length === 0) {
|
||||
throw new Error(`Command file created but appears to be empty`);
|
||||
}
|
||||
```
|
||||
|
||||
### Step 5: Generate Success Report
|
||||
|
||||
```javascript
|
||||
const report = {
|
||||
status: 'completed',
|
||||
file: {
|
||||
path: targetPath,
|
||||
name: summary.name,
|
||||
location: summary.location,
|
||||
group: summary.group,
|
||||
size: writtenContent.length,
|
||||
created: new Date().toISOString()
|
||||
},
|
||||
command: {
|
||||
name: summary.name,
|
||||
description: summary.description,
|
||||
hasArgumentHint: summary.hasArgumentHint
|
||||
},
|
||||
nextSteps: [
|
||||
`Edit ${targetPath} to add implementation details`,
|
||||
'Add usage examples and execution flow',
|
||||
'Test the command with Claude Code'
|
||||
]
|
||||
};
|
||||
```
|
||||
|
||||
## Output
|
||||
|
||||
### Success Output
|
||||
|
||||
```javascript
|
||||
{
|
||||
status: 'completed',
|
||||
file: {
|
||||
path: '.claude/commands/issue/create.md',
|
||||
name: 'create',
|
||||
location: 'project',
|
||||
group: 'issue',
|
||||
size: 1234,
|
||||
created: '2026-02-27T12:00:00.000Z'
|
||||
},
|
||||
command: {
|
||||
name: 'create',
|
||||
description: 'Create structured issue from GitHub URL...',
|
||||
hasArgumentHint: true
|
||||
},
|
||||
nextSteps: [
|
||||
'Edit .claude/commands/issue/create.md to add implementation details',
|
||||
'Add usage examples and execution flow',
|
||||
'Test the command with Claude Code'
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
### Console Output
|
||||
|
||||
```
|
||||
Command generated successfully!
|
||||
|
||||
File: .claude/commands/issue/create.md
|
||||
Name: create
|
||||
Description: Create structured issue from GitHub URL...
|
||||
Location: project
|
||||
Group: issue
|
||||
|
||||
Next Steps:
|
||||
1. Edit .claude/commands/issue/create.md to add implementation details
|
||||
2. Add usage examples and execution flow
|
||||
3. Test the command with Claude Code
|
||||
```
|
||||
|
||||
## Error Handling
|
||||
|
||||
| Error | Action |
|
||||
|-------|--------|
|
||||
| Directory creation failed | Throw error with directory path |
|
||||
| File write failed | Throw error with target path |
|
||||
| Empty file detected | Throw error and attempt cleanup |
|
||||
| Permission denied | Throw error with permission hint |
|
||||
|
||||
## Cleanup on Failure
|
||||
|
||||
```javascript
|
||||
// If any step fails, attempt to clean up partial artifacts
|
||||
function cleanup(targetPath) {
|
||||
try {
|
||||
Bash(`rm -f "${targetPath}"`);
|
||||
} catch (e) {
|
||||
// Ignore cleanup errors
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## Completion
|
||||
|
||||
The command file has been successfully generated. The skill execution is complete.
|
||||
|
||||
### Usage Example
|
||||
|
||||
```bash
|
||||
# Use the generated command
|
||||
/issue:create https://github.com/owner/repo/issues/123
|
||||
|
||||
# Or with the group prefix
|
||||
/issue:create "Login fails with special chars"
|
||||
```
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user