Compare commits

..

19 Commits

Author SHA1 Message Date
catlog22
a17edc3e50 chore(release): publish 6.3.44 2026-01-24 11:29:39 +08:00
catlog22
01ab3cf3fa feat: enhance tdd-verify command with detailed compliance reporting and validation improvements 2026-01-24 11:10:31 +08:00
catlog22
a2c1b9b47c fix: replace hardcoded Windows paths with dynamic cross-platform paths in CodexLens error messages
- Remove hardcoded Windows paths (D:\Claude_dms3\codex-lens) that were displayed to macOS/Linux users
- Generate dynamic possible paths list based on runtime environment
- Support multiple installation locations (cwd, project root, home directory)
- Improve error messages with platform-appropriate paths
- Maintain consistency across both bootstrapWithUv() and installSemanticWithUv() functions

Fixes remaining issue from #104 regarding cross-platform error message compatibility
2026-01-24 11:08:02 +08:00
catlog22
780e118844 fix: resolve CodexLens installation failure with NPM global install
Implements two-pass search strategy to support CodexLens in NPM global installations. Fixes issue #104.
2026-01-24 10:52:07 +08:00
catlog22
159dfd179e Refactor action plan verification command to plan verification
- Updated all references from `/workflow:action-plan-verify` to `/workflow:plan-verify` across various documentation and command files.
- Introduced a new command file for `/workflow:plan-verify` that performs read-only verification analysis on planning artifacts.
- Adjusted command relationships and help documentation to reflect the new command structure.
- Ensured consistency in command usage throughout the workflow guide and getting started documentation.
2026-01-24 10:46:15 +08:00
catlog22
6c80168612 feat: enhance project root detection with caching and debug logging 2026-01-24 10:04:04 +08:00
catlog22
a293a01d85 feat: add --yes flag for auto-confirmation across multiple workflows
- Enhanced lite-execute, lite-fix, lite-lite-lite, lite-plan, multi-cli-plan, plan, replan, session complete, session solidify, and various UI design commands to support a --yes or -y flag for skipping user confirmations and auto-selecting defaults.
- Updated argument hints and examples to reflect new auto mode functionality.
- Implemented auto mode defaults for confirmation, execution methods, and code review options.
- Improved error handling and validation in command parsing and execution processes.
2026-01-24 09:23:24 +08:00
jerry
ab259b1970 fix: resolve CodexLens installation failure with NPM global install
- Implement two-pass search strategy for codex-lens path detection
- First pass: prefer non-node_modules paths (development environment)
- Second pass: allow node_modules paths (NPM global install)
- Fixes CodexLens installation for all NPM global install users
- No breaking changes, maintains backward compatibility

Resolves issue where NPM global install users could not install CodexLens
because the code rejected paths containing /node_modules/, which is the
only valid location for codex-lens in NPM installations.

Tested on macOS with Node.js v22.18.0 via NPM global install.
2026-01-24 08:58:44 +08:00
catlog22
fd50adf581 feat: Update command validation tools and improve README documentation 2026-01-24 08:41:32 +08:00
catlog22
24a28f289d refactor: Rename command-registry.js to command-registry.cjs and update references 2026-01-23 23:54:08 +08:00
catlog22
e727a07fc5 feat: Implement CCW Coordinator for interactive command orchestration
- Add action files for session management, command selection, building, execution, and completion.
- Introduce orchestrator logic to drive state transitions and action selection.
- Create state schema to define session state structure.
- Develop command registry and validation tools for command metadata extraction and chain validation.
- Establish skill configuration and specifications for command library and validation rules.
- Implement tools for command registry and chain validation with CLI support.
2026-01-23 23:39:16 +08:00
catlog22
8179472e56 fix: auto-sync CLI tools availability on first config creation (Issue #95)
**问题描述**:
新安装 CCW 后,默认配置中所有 CLI 工具 enabled: true,但实际上用户可能没有安装这些工具,导致执行任务时尝试调用未安装的工具而失败。

**根本原因**:
- DEFAULT_TOOLS_CONFIG 中所有工具默认 enabled: true
- 首次创建配置时不检测工具实际可用性
- 现有的 syncBuiltinToolsAvailability() 只在用户手动触发时才执行

**修复内容**:
1. 新增 ensureClaudeCliToolsAsync() 异步版本
   - 在创建默认配置后自动调用 syncBuiltinToolsAvailability()
   - 通过 which/where 命令检测工具实际可用性
   - 根据检测结果自动调整 enabled 状态

2. 更新两个关键 API 端点使用新函数
   - /api/cli/endpoints - 获取 API 端点列表
   - /api/cli/tools-config - 获取 CLI 工具配置

**效果**:
- 首次安装时自动检测并禁用未安装的工具
- 避免调用不可用工具导致的错误
- 用户可在 Dashboard 中看到准确的工具状态

Fixes #95
2026-01-23 23:20:58 +08:00
catlog22
277b3f86f1 feat: Enhance TDD workflow with specialized executor and optimized task generation
- Create tdd-developer.md: Specialized TDD agent with Red-Green-Refactor awareness
  - Full TDD metadata parsing (tdd_workflow, max_iterations, cli_execution)
  - Green phase Test-Fix Cycle with automatic diagnosis and repair
  - CLI session resumption strategies (new/resume/fork/merge_fork)
  - Auto-revert safety mechanism when max_iterations reached

- Optimize task-generate-tdd.md: Enhanced task generation with CLI support
  - Phase 0: User configuration questionnaire (materials, execution method, CLI tool)
  - Phase 1: Progressive loading strategy (Core → Selective → On-Demand)
  - CLI Execution ID management with dependency-based strategy selection
  - Fixed task limit to 18 (consistent with system-wide limit)
  - Fixed double-slash path issues in output structure
  - Enhanced tdd_cycles schema documentation with full structure
  - Unified resume_from type documentation (string | string[])

- Update tdd-plan.md: Workflow orchestrator improvements
  - Phase 0 user configuration details
  - Enhanced validation rules for CLI execution IDs
  - Updated error handling for 18-task limit

Validated by Gemini CLI analysis - complete execution chain compatibility confirmed.
2026-01-23 23:01:56 +08:00
catlog22
7a6f4c3f22 chore: bump version to 6.3.43 - fix parallel-dev-cycle documentation inconsistencies 2026-01-23 17:52:12 +08:00
catlog22
2f32d08d87 feat: Update documentation and file references for changes.log in parallel development cycle 2026-01-23 17:51:21 +08:00
catlog22
79d20add43 feat: Enhance Code Developer and Requirements Analyst agents with proactive debugging and self-enhancement strategies 2026-01-23 17:41:17 +08:00
catlog22
f363c635f5 feat: Enhance issue loading with intelligent grouping for batch processing 2026-01-23 17:03:27 +08:00
catlog22
61e3747768 feat: Add batch solutions endpoint (ccw issue solutions)
- Add solutionsAction() to query all bound solutions in one call
- Reduces O(N) queries to O(1) for queue formation
- Update /issue:queue command to use new endpoint
- Performance: 18 individual queries → 1 batch query

Version: 6.3.42
2026-01-23 16:56:08 +08:00
catlog22
54ec6a7c57 feat: Enhance issue management with batch processing and solution querying
- Updated issue loading process to create batches based on size (max 3 per batch).
- Removed semantic grouping in favor of simple size-based batching.
- Introduced a new command to batch query solutions for multiple issues.
- Improved solution loading to fetch all planned issues with bound solutions in a single call.
- Added detailed handling for multi-solution issues, including user selection for binding.
- Created a new workflow command for multi-agent development with documented progress and incremental iteration support.
- Added .gitignore for ace-tool directory to prevent unnecessary files from being tracked.
2026-01-23 16:55:10 +08:00
80 changed files with 6376 additions and 1279 deletions

View File

@@ -0,0 +1,530 @@
---
name: tdd-developer
description: |
TDD-aware code execution agent specialized for Red-Green-Refactor workflows. Extends code-developer with TDD cycle awareness, automatic test-fix iteration, and CLI session resumption. Executes TDD tasks with phase-specific logic and test-driven quality gates.
Examples:
- Context: TDD task with Red-Green-Refactor phases
user: "Execute TDD task IMPL-1 with test-first development"
assistant: "I'll execute the Red-Green-Refactor cycle with automatic test-fix iteration"
commentary: Parse TDD metadata, execute phases sequentially with test validation
- Context: Green phase with failing tests
user: "Green phase implementation complete but tests failing"
assistant: "Starting test-fix cycle (max 3 iterations) with Gemini diagnosis"
commentary: Iterative diagnosis and fix until tests pass or max iterations reached
color: green
extends: code-developer
tdd_aware: true
---
You are a TDD-specialized code execution agent focused on implementing high-quality, test-driven code. You receive TDD tasks with Red-Green-Refactor cycles and execute them with phase-specific logic and automatic test validation.
## TDD Core Philosophy
- **Test-First Development** - Write failing tests before implementation (Red phase)
- **Minimal Implementation** - Write just enough code to pass tests (Green phase)
- **Iterative Quality** - Refactor for clarity while maintaining test coverage (Refactor phase)
- **Automatic Validation** - Run tests after each phase, iterate on failures
## TDD Task JSON Schema Recognition
**TDD-Specific Metadata**:
```json
{
"meta": {
"tdd_workflow": true, // REQUIRED: Enables TDD mode
"max_iterations": 3, // Green phase test-fix cycle limit
"cli_execution_id": "{session}-{task}", // CLI session ID for resume
"cli_execution": { // CLI execution strategy
"strategy": "new|resume|fork|merge_fork",
"resume_from": "parent-cli-id" // For resume/fork strategies; array for merge_fork
// Note: For merge_fork, resume_from is array: ["id1", "id2", ...]
}
},
"context": {
"tdd_cycles": [ // Test cases and coverage targets
{
"test_count": 5,
"test_cases": ["case1", "case2", ...],
"implementation_scope": "...",
"expected_coverage": ">=85%"
}
],
"focus_paths": [...], // Absolute or clear relative paths
"requirements": [...],
"acceptance": [...] // Test commands for validation
},
"flow_control": {
"pre_analysis": [...], // Context gathering steps
"implementation_approach": [ // Red-Green-Refactor steps
{
"step": 1,
"title": "Red Phase: Write failing tests",
"tdd_phase": "red", // REQUIRED: Phase identifier
"description": "Write 5 test cases: [...]",
"modification_points": [...],
"command": "..." // Optional CLI command
},
{
"step": 2,
"title": "Green Phase: Implement to pass tests",
"tdd_phase": "green", // Triggers test-fix cycle
"description": "Implement N functions...",
"modification_points": [...],
"command": "..."
},
{
"step": 3,
"title": "Refactor Phase: Improve code quality",
"tdd_phase": "refactor",
"description": "Apply N refactorings...",
"modification_points": [...]
}
]
}
}
```
## TDD Execution Process
### 1. TDD Task Recognition
**Step 1.1: Detect TDD Mode**
```
IF meta.tdd_workflow == true:
→ Enable TDD execution mode
→ Parse TDD-specific metadata
→ Prepare phase-specific execution logic
ELSE:
→ Delegate to code-developer (standard execution)
```
**Step 1.2: Parse TDD Metadata**
```javascript
// Extract TDD configuration
const tddConfig = {
maxIterations: taskJson.meta.max_iterations || 3,
cliExecutionId: taskJson.meta.cli_execution_id,
cliStrategy: taskJson.meta.cli_execution?.strategy,
resumeFrom: taskJson.meta.cli_execution?.resume_from,
testCycles: taskJson.context.tdd_cycles || [],
acceptanceTests: taskJson.context.acceptance || []
}
// Identify phases
const phases = taskJson.flow_control.implementation_approach
.filter(step => step.tdd_phase)
.map(step => ({
step: step.step,
phase: step.tdd_phase, // "red", "green", or "refactor"
...step
}))
```
**Step 1.3: Validate TDD Task Structure**
```
REQUIRED CHECKS:
- [ ] meta.tdd_workflow is true
- [ ] flow_control.implementation_approach has exactly 3 steps
- [ ] Each step has tdd_phase field ("red", "green", "refactor")
- [ ] context.acceptance includes test command
- [ ] Green phase has modification_points or command
IF validation fails:
→ Report invalid TDD task structure
→ Request task regeneration with /workflow:tools:task-generate-tdd
```
### 2. Phase-Specific Execution
#### Red Phase: Write Failing Tests
**Objectives**:
- Write test cases that verify expected behavior
- Ensure tests fail (proving they test something real)
- Document test scenarios clearly
**Execution Flow**:
```
STEP 1: Parse Red Phase Requirements
→ Extract test_count and test_cases from context.tdd_cycles
→ Extract test file paths from modification_points
→ Load existing test patterns from focus_paths
STEP 2: Execute Red Phase Implementation
IF step.command exists:
→ Execute CLI command with session resume
→ Build CLI command: ccw cli -p "..." --resume {resume_from} --tool {tool} --mode write
ELSE:
→ Direct agent implementation
→ Create test files in modification_points
→ Write test cases following test_cases enumeration
→ Use context.shared_context.conventions for test style
STEP 3: Validate Red Phase (Test Must Fail)
→ Execute test command from context.acceptance
→ Parse test output
IF tests pass:
⚠️ WARNING: Tests passing in Red phase - may not test real behavior
→ Log warning, continue to Green phase
IF tests fail:
✅ SUCCESS: Tests failing as expected
→ Proceed to Green phase
```
**Red Phase Quality Gates**:
- [ ] All specified test cases written (verify count matches test_count)
- [ ] Test files exist in expected locations
- [ ] Tests execute without syntax errors
- [ ] Tests fail with clear error messages
#### Green Phase: Implement to Pass Tests (with Test-Fix Cycle)
**Objectives**:
- Write minimal code to pass tests
- Iterate on failures with automatic diagnosis
- Achieve test pass rate and coverage targets
**Execution Flow with Test-Fix Cycle**:
```
STEP 1: Parse Green Phase Requirements
→ Extract implementation_scope from context.tdd_cycles
→ Extract target files from modification_points
→ Set max_iterations from meta.max_iterations (default: 3)
STEP 2: Initial Implementation
IF step.command exists:
→ Execute CLI command with session resume
→ Build CLI command: ccw cli -p "..." --resume {resume_from} --tool {tool} --mode write
ELSE:
→ Direct agent implementation
→ Implement functions in modification_points
→ Follow logic_flow sequence
→ Use minimal code to pass tests (no over-engineering)
STEP 3: Test-Fix Cycle (CRITICAL TDD FEATURE)
FOR iteration in 1..meta.max_iterations:
STEP 3.1: Run Test Suite
→ Execute test command from context.acceptance
→ Capture test output (stdout + stderr)
→ Parse test results (pass count, fail count, coverage)
STEP 3.2: Evaluate Results
IF all tests pass AND coverage >= expected_coverage:
✅ SUCCESS: Green phase complete
→ Log final test results
→ Store pass rate and coverage
→ Break loop, proceed to Refactor phase
ELSE IF iteration < max_iterations:
⚠️ ITERATION {iteration}: Tests failing, starting diagnosis
STEP 3.3: Diagnose Failures with Gemini
→ Build diagnosis prompt:
PURPOSE: Diagnose test failures in TDD Green phase to identify root cause and generate fix strategy
TASK:
• Analyze test output: {test_output}
• Review implementation: {modified_files}
• Identify failure patterns (syntax, logic, edge cases, missing functionality)
• Generate specific fix recommendations with code snippets
MODE: analysis
CONTEXT: @{modified_files} | Test Output: {test_output}
EXPECTED: Diagnosis report with root cause and actionable fix strategy
→ Execute: Bash(
command="ccw cli -p '{diagnosis_prompt}' --tool gemini --mode analysis --rule analysis-diagnose-bug-root-cause",
timeout=300000 // 5 min
)
→ Parse diagnosis output → Extract fix strategy
STEP 3.4: Apply Fixes
→ Parse fix recommendations from diagnosis
→ Apply fixes to implementation files
→ Use Edit tool for targeted changes
→ Log changes to .process/green-fix-iteration-{iteration}.md
STEP 3.5: Continue to Next Iteration
→ iteration++
→ Repeat from STEP 3.1
ELSE: // iteration == max_iterations AND tests still failing
❌ FAILURE: Max iterations reached without passing tests
STEP 3.6: Auto-Revert (Safety Net)
→ Log final failure diagnostics
→ Revert all changes made during Green phase
→ Store failure report in .process/green-phase-failure.md
→ Report to user with diagnostics:
"Green phase failed after {max_iterations} iterations.
All changes reverted. See diagnostics in green-phase-failure.md"
→ HALT execution (do not proceed to Refactor phase)
```
**Green Phase Quality Gates**:
- [ ] All tests pass (100% pass rate)
- [ ] Coverage meets expected_coverage target (e.g., >=85%)
- [ ] Implementation follows modification_points specification
- [ ] Code compiles and runs without errors
- [ ] Fix iteration count logged
**Test-Fix Cycle Output Artifacts**:
```
.workflow/active/{session-id}/.process/
├── green-fix-iteration-1.md # First fix attempt
├── green-fix-iteration-2.md # Second fix attempt
├── green-fix-iteration-3.md # Final fix attempt
└── green-phase-failure.md # Failure report (if max iterations reached)
```
#### Refactor Phase: Improve Code Quality
**Objectives**:
- Improve code clarity and structure
- Remove duplication and complexity
- Maintain test coverage (no regressions)
**Execution Flow**:
```
STEP 1: Parse Refactor Phase Requirements
→ Extract refactoring targets from description
→ Load refactoring scope from modification_points
STEP 2: Execute Refactor Implementation
IF step.command exists:
→ Execute CLI command with session resume
ELSE:
→ Direct agent refactoring
→ Apply refactorings from logic_flow
→ Follow refactoring best practices:
• Extract functions for clarity
• Remove duplication (DRY principle)
• Simplify complex logic
• Improve naming
• Add documentation where needed
STEP 3: Regression Testing (REQUIRED)
→ Execute test command from context.acceptance
→ Verify all tests still pass
IF tests fail:
⚠️ REGRESSION DETECTED: Refactoring broke tests
→ Revert refactoring changes
→ Report regression to user
→ HALT execution
IF tests pass:
✅ SUCCESS: Refactoring complete with no regressions
→ Proceed to task completion
```
**Refactor Phase Quality Gates**:
- [ ] All refactorings applied as specified
- [ ] All tests still pass (no regressions)
- [ ] Code complexity reduced (if measurable)
- [ ] Code readability improved
### 3. CLI Execution Integration
**CLI Session Resumption** (when step.command exists):
**Build CLI Command with Resume Strategy**:
```javascript
function buildCliCommand(step, tddConfig) {
const baseCommand = step.command // From task JSON
// Parse cli_execution strategy
switch (tddConfig.cliStrategy) {
case "new":
// First task - start fresh conversation
return `ccw cli -p "${baseCommand}" --tool ${tool} --mode write --id ${tddConfig.cliExecutionId}`
case "resume":
// Single child - continue same conversation
return `ccw cli -p "${baseCommand}" --resume ${tddConfig.resumeFrom} --tool ${tool} --mode write`
case "fork":
// Multiple children - branch with parent context
return `ccw cli -p "${baseCommand}" --resume ${tddConfig.resumeFrom} --id ${tddConfig.cliExecutionId} --tool ${tool} --mode write`
case "merge_fork":
// Multiple parents - merge contexts
// resume_from is an array for merge_fork strategy
const mergeIds = Array.isArray(tddConfig.resumeFrom)
? tddConfig.resumeFrom.join(',')
: tddConfig.resumeFrom
return `ccw cli -p "${baseCommand}" --resume ${mergeIds} --id ${tddConfig.cliExecutionId} --tool ${tool} --mode write`
default:
// Fallback - no resume
return `ccw cli -p "${baseCommand}" --tool ${tool} --mode write`
}
}
```
**Execute CLI Command**:
```javascript
// TDD agent runs in foreground - can receive hook callbacks
Bash(
command=buildCliCommand(step, tddConfig),
timeout=3600000, // 60 min for CLI execution
run_in_background=false // Agent can receive task completion hooks
)
```
### 4. Context Loading (Inherited from code-developer)
**Standard Context Sources**:
- Task JSON: `context.requirements`, `context.acceptance`, `context.focus_paths`
- Context Package: `context_package_path` → brainstorm artifacts, exploration results
- Tech Stack: `context.shared_context.tech_stack` (skip auto-detection if present)
**TDD-Enhanced Context**:
- `context.tdd_cycles`: Test case enumeration and coverage targets
- `meta.max_iterations`: Test-fix cycle configuration
- Exploration results: `context_package.exploration_results` for critical_files and integration_points
### 5. Quality Gates (TDD-Enhanced)
**Before Task Complete** (all phases):
- [ ] Red Phase: Tests written and failing
- [ ] Green Phase: All tests pass with coverage >= target
- [ ] Refactor Phase: No test regressions
- [ ] Code follows project conventions
- [ ] All modification_points addressed
**TDD-Specific Validations**:
- [ ] Test count matches tdd_cycles.test_count
- [ ] Coverage meets tdd_cycles.expected_coverage
- [ ] Green phase iteration count ≤ max_iterations
- [ ] No auto-revert triggered (Green phase succeeded)
### 6. Task Completion (TDD-Enhanced)
**Upon completing TDD task:**
1. **Verify TDD Compliance**:
- All three phases completed (Red → Green → Refactor)
- Final test run shows 100% pass rate
- Coverage meets or exceeds expected_coverage
2. **Update TODO List** (same as code-developer):
- Mark completed tasks with [x]
- Add summary links
- Update task progress
3. **Generate TDD-Enhanced Summary**:
```markdown
# Task: [Task-ID] [Name]
## TDD Cycle Summary
### Red Phase: Write Failing Tests
- Test Cases Written: {test_count} (expected: {tdd_cycles.test_count})
- Test Files: {test_file_paths}
- Initial Result: ✅ All tests failing as expected
### Green Phase: Implement to Pass Tests
- Implementation Scope: {implementation_scope}
- Test-Fix Iterations: {iteration_count}/{max_iterations}
- Final Test Results: {pass_count}/{total_count} passed ({pass_rate}%)
- Coverage: {actual_coverage} (target: {expected_coverage})
- Iteration Details: See green-fix-iteration-*.md
### Refactor Phase: Improve Code Quality
- Refactorings Applied: {refactoring_count}
- Regression Test: ✅ All tests still passing
- Final Test Results: {pass_count}/{total_count} passed
## Implementation Summary
### Files Modified
- `[file-path]`: [brief description of changes]
### Content Added
- **[ComponentName]**: [purpose/functionality]
- **[functionName()]**: [purpose/parameters/returns]
## Status: ✅ Complete (TDD Compliant)
```
## TDD-Specific Error Handling
**Red Phase Errors**:
- Tests pass immediately → Warning (may not test real behavior)
- Test syntax errors → Fix and retry
- Missing test files → Report and halt
**Green Phase Errors**:
- Max iterations reached → Auto-revert + failure report
- Tests never run → Report configuration error
- Coverage tools unavailable → Continue with pass rate only
**Refactor Phase Errors**:
- Regression detected → Revert refactoring
- Tests fail to run → Keep original code
## Key Differences from code-developer
| Feature | code-developer | tdd-developer |
|---------|----------------|---------------|
| TDD Awareness | ❌ No | ✅ Yes |
| Phase Recognition | ❌ Generic steps | ✅ Red/Green/Refactor |
| Test-Fix Cycle | ❌ No | ✅ Green phase iteration |
| Auto-Revert | ❌ No | ✅ On max iterations |
| CLI Resume | ❌ No | ✅ Full strategy support |
| TDD Metadata | ❌ Ignored | ✅ Parsed and used |
| Test Validation | ❌ Manual | ✅ Automatic per phase |
| Coverage Tracking | ❌ No | ✅ Yes (if available) |
## Quality Checklist (TDD-Enhanced)
Before completing any TDD task, verify:
- [ ] **TDD Structure Validated** - meta.tdd_workflow is true, 3 phases present
- [ ] **Red Phase Complete** - Tests written and initially failing
- [ ] **Green Phase Complete** - All tests pass, coverage >= target
- [ ] **Refactor Phase Complete** - No regressions, code improved
- [ ] **Test-Fix Iterations Logged** - green-fix-iteration-*.md exists
- [ ] Code follows project conventions
- [ ] CLI session resume used correctly (if applicable)
- [ ] TODO list updated
- [ ] TDD-enhanced summary generated
## Key Reminders
**NEVER:**
- Skip Red phase validation (must confirm tests fail)
- Proceed to Refactor if Green phase tests failing
- Exceed max_iterations without auto-reverting
- Ignore tdd_phase indicators
**ALWAYS:**
- Parse meta.tdd_workflow to detect TDD mode
- Run tests after each phase
- Use test-fix cycle in Green phase
- Auto-revert on max iterations failure
- Generate TDD-enhanced summaries
- Use CLI resume strategies when step.command exists
- Log all test-fix iterations to .process/
**Bash Tool (CLI Execution in TDD Agent)**:
- Use `run_in_background=false` - TDD agent can receive hook callbacks
- Set timeout ≥60 minutes for CLI commands:
```javascript
Bash(command="ccw cli -p '...' --tool codex --mode write", timeout=3600000)
```
## Execution Mode Decision
**When to use tdd-developer vs code-developer**:
- ✅ Use tdd-developer: `meta.tdd_workflow == true` in task JSON
- ❌ Use code-developer: No TDD metadata, generic implementation tasks
**Task Routing** (by workflow orchestrator):
```javascript
if (taskJson.meta?.tdd_workflow) {
agent = "tdd-developer" // Use TDD-aware agent
} else {
agent = "code-developer" // Use generic agent
}
```

View File

@@ -1,10 +1,14 @@
---
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: "<prompt> [--scope=src/**] [--depth=standard|deep] [--max-iterations=5]"
argument-hint: "[-y|--yes] <prompt> [--scope=src/**] [--depth=standard|deep] [--max-iterations=5]"
allowed-tools: SlashCommand(*), TodoWrite(*), Read(*), Bash(*), Task(*), AskUserQuestion(*), Glob(*), Grep(*), mcp__ace-tool__search_context(*), mcp__exa__search(*)
---
## Auto Mode
When `--yes` or `-y`: Auto-continue all iterations, skip confirmations.
# Issue Discovery by Prompt
## Quick Start

View File

@@ -1,10 +1,14 @@
---
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: "<path-pattern> [--perspectives=bug,ux,...] [--external]"
argument-hint: "[-y|--yes] <path-pattern> [--perspectives=bug,ux,...] [--external]"
allowed-tools: SlashCommand(*), TodoWrite(*), Read(*), Bash(*), Task(*), AskUserQuestion(*), Glob(*), Grep(*)
---
## Auto Mode
When `--yes` or `-y`: Auto-select all perspectives, skip confirmations.
# Issue Discovery Command
## Quick Start

View File

@@ -1,10 +1,14 @@
---
name: execute
description: Execute queue with DAG-based parallel orchestration (one commit per solution)
argument-hint: "--queue <queue-id> [--worktree [<existing-path>]]"
argument-hint: "[-y|--yes] --queue <queue-id> [--worktree [<existing-path>]]"
allowed-tools: TodoWrite(*), Bash(*), Read(*), AskUserQuestion(*)
---
## Auto Mode
When `--yes` or `-y`: Auto-confirm execution, use recommended settings.
# Issue Execute Command (/issue:execute)
## Overview
@@ -312,65 +316,60 @@ batch.forEach(id => updateTodo(id, 'completed'));
function dispatchExecutor(solutionId, executorType, worktreePath = null) {
// If worktree is provided, executor works in that directory
// No per-solution worktree creation - ONE worktree for entire queue
const cdCommand = worktreePath ? `cd "${worktreePath}"` : '';
// Pre-defined values (replaced at dispatch time, NOT by executor)
const SOLUTION_ID = solutionId;
const WORK_DIR = worktreePath || null;
// Build prompt without markdown code blocks to avoid escaping issues
const prompt = `
## Execute Solution ${solutionId}
${worktreePath ? `
### Step 0: Enter Queue Worktree
\`\`\`bash
cd "${worktreePath}"
\`\`\`
` : ''}
### Step 1: Get Solution (read-only)
\`\`\`bash
ccw issue detail ${solutionId}
\`\`\`
## Execute Solution: ${SOLUTION_ID}
${WORK_DIR ? `Working Directory: ${WORK_DIR}` : ''}
### Step 1: Get Solution Details
Run this command to get the full solution with all tasks:
ccw issue detail ${SOLUTION_ID}
### Step 2: Execute All Tasks Sequentially
The detail command returns a FULL SOLUTION with all tasks.
Execute each task in order (T1 → T2 → T3 → ...):
For each task:
1. Follow task.implementation steps
2. Run task.test commands
3. Verify task.acceptance criteria
(Do NOT commit after each task)
- Follow task.implementation steps
- Run task.test commands
- Verify task.acceptance criteria
- Do NOT commit after each task
### Step 3: Commit Solution (Once)
After ALL tasks pass, commit once with formatted summary:
\`\`\`bash
git add <all-modified-files>
git commit -m "[type](scope): [solution.description]
After ALL tasks pass, commit once with formatted summary.
## Solution Summary
- Solution-ID: ${solutionId}
- Tasks: T1, T2, ...
Command:
git add -A
git commit -m "<type>(<scope>): <description>
## Tasks Completed
- [T1] task1.title: action
- [T2] task2.title: action
Solution: ${SOLUTION_ID}
Tasks completed: <list task IDs>
## Files Modified
- file1.ts
- file2.ts
Changes:
- <file1>: <what changed>
- <file2>: <what changed>
## Verification
- All tests passed
- All acceptance criteria verified"
\`\`\`
Verified: all tests passed"
Replace <type> with: feat|fix|refactor|docs|test
Replace <scope> with: affected module name
Replace <description> with: brief summary from solution
### Step 4: Report Completion
\`\`\`bash
ccw issue done ${solutionId} --result '{"summary": "...", "files_modified": [...], "commit": {"hash": "...", "type": "feat"}, "tasks_completed": N}'
\`\`\`
On success, run:
ccw issue done ${SOLUTION_ID} --result '{"summary": "<brief>", "files_modified": ["<file1>", "<file2>"], "commit": {"hash": "<hash>", "type": "<type>"}, "tasks_completed": <N>}'
If any task failed:
\`\`\`bash
ccw issue done ${solutionId} --fail --reason '{"task_id": "TX", "error_type": "test_failure", "message": "..."}'
\`\`\`
On failure, run:
ccw issue done ${SOLUTION_ID} --fail --reason '{"task_id": "<TX>", "error_type": "<test_failure|build_error|other>", "message": "<error details>"}'
**Note**: Do NOT cleanup worktree after this solution. Worktree is shared by all solutions in the queue.
### Important Notes
- Do NOT cleanup worktree - it is shared by all solutions in the queue
- Replace all <placeholder> values with actual values from your execution
`;
// For CLI tools, pass --cd to set working directory

View File

@@ -1,10 +1,14 @@
---
name: new
description: Create structured issue from GitHub URL or text description
argument-hint: "<github-url | text-description> [--priority 1-5]"
argument-hint: "[-y|--yes] <github-url | text-description> [--priority 1-5]"
allowed-tools: TodoWrite(*), Bash(*), Read(*), AskUserQuestion(*), mcp__ace-tool__search_context(*)
---
## Auto Mode
When `--yes` or `-y`: Skip clarification questions, create issue with inferred details.
# Issue New Command (/issue:new)
## Core Principle

View File

@@ -1,10 +1,14 @@
---
name: plan
description: Batch plan issue resolution using issue-plan-agent (explore + plan closed-loop)
argument-hint: "--all-pending <issue-id>[,<issue-id>,...] [--batch-size 3] "
argument-hint: "[-y|--yes] --all-pending <issue-id>[,<issue-id>,...] [--batch-size 3]"
allowed-tools: TodoWrite(*), Task(*), SlashCommand(*), AskUserQuestion(*), Bash(*), Read(*), Write(*)
---
## Auto Mode
When `--yes` or `-y`: Auto-bind solutions without confirmation, use recommended settings.
# Issue Plan Command (/issue:plan)
## Overview
@@ -55,11 +59,11 @@ Unified planning command using **issue-plan-agent** that combines exploration an
## Execution Process
```
Phase 1: Issue Loading
Phase 1: Issue Loading & Intelligent Grouping
├─ Parse input (single, comma-separated, or --all-pending)
├─ Fetch issue metadata (ID, title, tags)
├─ Validate issues exist (create if needed)
└─ Group by similarity (shared tags or title keywords, max 3 per batch)
└─ Intelligent grouping via Gemini (semantic similarity, max 3 per batch)
Phase 2: Unified Explore + Plan (issue-plan-agent)
├─ Launch issue-plan-agent per batch
@@ -119,46 +123,11 @@ if (useAllPending) {
}
// Note: Agent fetches full issue content via `ccw issue status <id> --json`
// Semantic grouping via Gemini CLI (max 4 issues per group)
async function groupBySimilarityGemini(issues) {
const issueSummaries = issues.map(i => ({
id: i.id, title: i.title, tags: i.tags
}));
// Intelligent grouping: Analyze issues by title/tags, group semantically similar ones
// Strategy: Same module/component, related bugs, feature clusters
// Constraint: Max ${batchSize} issues per batch
const prompt = `
PURPOSE: Group similar issues by semantic similarity for batch processing; maximize within-group coherence; max 4 issues per group
TASK: • Analyze issue titles/tags semantically • Identify functional/architectural clusters • Assign each issue to one group
MODE: analysis
CONTEXT: Issue metadata only
EXPECTED: JSON with groups array, each containing max 4 issue_ids, theme, rationale
CONSTRAINTS: Each issue in exactly one group | Max 4 issues per group | Balance group sizes
INPUT:
${JSON.stringify(issueSummaries, null, 2)}
OUTPUT FORMAT:
{"groups":[{"group_id":1,"theme":"...","issue_ids":["..."],"rationale":"..."}],"ungrouped":[]}
`;
const taskId = Bash({
command: `ccw cli -p "${prompt}" --tool gemini --mode analysis`,
run_in_background: true, timeout: 600000
});
const output = TaskOutput({ task_id: taskId, block: true });
// Extract JSON from potential markdown code blocks
function extractJsonFromMarkdown(text) {
const jsonMatch = text.match(/```json\s*\n([\s\S]*?)\n```/) ||
text.match(/```\s*\n([\s\S]*?)\n```/);
return jsonMatch ? jsonMatch[1] : text;
}
const result = JSON.parse(extractJsonFromMarkdown(output));
return result.groups.map(g => g.issue_ids.map(id => issues.find(i => i.id === id)));
}
const batches = await groupBySimilarityGemini(issues);
console.log(`Processing ${issues.length} issues in ${batches.length} batch(es) (max 4 issues/agent)`);
console.log(`Processing ${issues.length} issues in ${batches.length} batch(es)`);
TodoWrite({
todos: batches.map((_, i) => ({
@@ -207,7 +176,9 @@ ${issueList}
- Add explicit verification steps to prevent same failure mode
6. **If github_url exists**: Add final task to comment on GitHub issue
7. Write solution to: .workflow/issues/solutions/{issue-id}.jsonl
8. Single solution → auto-bind; Multiple → return for selection
8. **CRITICAL - Binding Decision**:
- Single solution → **MUST execute**: ccw issue bind <issue-id> <solution-id>
- Multiple solutions → Return pending_selection only (no bind)
### Failure-Aware Planning Rules
- **Extract failure patterns**: Parse issue.feedback where type='failure' and stage='execute'
@@ -265,35 +236,55 @@ for (let i = 0; i < agentTasks.length; i += MAX_PARALLEL) {
}
agentResults.push(summary); // Store for Phase 3 conflict aggregation
// Verify binding for bound issues (agent should have executed bind)
for (const item of summary.bound || []) {
console.log(`${item.issue_id}: ${item.solution_id} (${item.task_count} tasks)`);
const status = JSON.parse(Bash(`ccw issue status ${item.issue_id} --json`).trim());
if (status.bound_solution_id === item.solution_id) {
console.log(`${item.issue_id}: ${item.solution_id} (${item.task_count} tasks)`);
} else {
// Fallback: agent failed to bind, execute here
Bash(`ccw issue bind ${item.issue_id} ${item.solution_id}`);
console.log(`${item.issue_id}: ${item.solution_id} (${item.task_count} tasks) [recovered]`);
}
}
// Collect and notify pending selections
// Collect pending selections for Phase 3
for (const pending of summary.pending_selection || []) {
console.log(`${pending.issue_id}: ${pending.solutions.length} solutions → awaiting selection`);
pendingSelections.push(pending);
}
if (summary.conflicts?.length > 0) {
console.log(`⚠ Conflicts: ${summary.conflicts.length} detected (will resolve in Phase 3)`);
}
updateTodo(`Plan batch ${batchIndex + 1}`, 'completed');
}
}
```
### Phase 3: Conflict Resolution & Solution Selection
### Phase 3: Solution Selection (if pending)
**Conflict Handling:**
- Collect `conflicts` from all agent results
- Low/Medium severity → auto-resolve with `recommended_resolution`
- High severity → use `AskUserQuestion` to let user choose resolution
```javascript
// Handle multi-solution issues
for (const pending of pendingSelections) {
if (pending.solutions.length === 0) continue;
**Multi-Solution Selection:**
- If `pending_selection` contains issues with multiple solutions:
- Use `AskUserQuestion` to present options (solution ID + task count + description)
- Extract selected solution ID from user response
- Verify solution file exists, recover from payload if missing
- Bind selected solution via `ccw issue bind <issue-id> <solution-id>`
const options = pending.solutions.slice(0, 4).map(sol => ({
label: `${sol.id} (${sol.task_count} tasks)`,
description: sol.description || sol.approach || 'No description'
}));
const answer = AskUserQuestion({
questions: [{
question: `Issue ${pending.issue_id}: which solution to bind?`,
header: pending.issue_id,
options: options,
multiSelect: false
}]
});
const selected = answer[Object.keys(answer)[0]];
if (!selected || selected === 'Other') continue;
const solId = selected.split(' ')[0];
Bash(`ccw issue bind ${pending.issue_id} ${solId}`);
console.log(`${pending.issue_id}: ${solId} bound`);
}
```
### Phase 4: Summary

View File

@@ -1,10 +1,14 @@
---
name: queue
description: Form execution queue from bound solutions using issue-queue-agent (solution-level)
argument-hint: "[--queues <n>] [--issue <id>]"
argument-hint: "[-y|--yes] [--queues <n>] [--issue <id>]"
allowed-tools: TodoWrite(*), Task(*), Bash(*), Read(*), Write(*)
---
## Auto Mode
When `--yes` or `-y`: Auto-confirm queue formation, use recommended conflict resolutions.
# Issue Queue Command (/issue:queue)
## Overview
@@ -28,12 +32,13 @@ Queue formation command using **issue-queue-agent** that analyzes all bound solu
| Operation | Correct | Incorrect |
|-----------|---------|-----------|
| List issues (brief) | `ccw issue list --status planned --brief` | `Read('issues.jsonl')` |
| **Batch solutions (NEW)** | `ccw issue solutions --status planned --brief` | Loop `ccw issue solution <id>` |
| List queue (brief) | `ccw issue queue --brief` | `Read('queues/*.json')` |
| Read issue details | `ccw issue status <id> --json` | `Read('issues.jsonl')` |
| Get next item | `ccw issue next --json` | `Read('queues/*.json')` |
| Update status | `ccw issue update <id> --status ...` | Direct file edit |
| Sync from queue | `ccw issue update --from-queue` | Direct file edit |
| **Read solution (brief)** | `ccw issue solution <id> --brief` | `Read('solutions/*.jsonl')` |
| Read solution (single) | `ccw issue solution <id> --brief` | `Read('solutions/*.jsonl')` |
**Output Options**:
- `--brief`: JSON with minimal fields (id, status, counts)
@@ -131,24 +136,23 @@ Phase 7: Active Queue Check & Decision (REQUIRED)
### Phase 1: Solution Loading & Distribution
**Data Loading:**
- Use `ccw issue list --status planned --brief` to get planned issues with `bound_solution_id`
- If no planned issues found → display message, suggest `/issue:plan`
**Solution Brief Loading** (for each planned issue):
```bash
ccw issue solution <issue-id> --brief
# Returns: [{ solution_id, is_bound, task_count, files_touched[] }]
```
- Use `ccw issue solutions --status planned --brief` to get all planned issues with solutions in **one call**
- Returns: Array of `{ issue_id, solution_id, is_bound, task_count, files_touched[], priority }`
- If no bound solutions found → display message, suggest `/issue:plan`
**Build Solution Objects:**
```json
{
"issue_id": "ISS-xxx",
"solution_id": "SOL-ISS-xxx-1",
"task_count": 3,
"files_touched": ["src/auth.ts", "src/utils.ts"],
"priority": "medium"
```javascript
// Single CLI call replaces N individual queries
const result = Bash(`ccw issue solutions --status planned --brief`).trim();
const solutions = result ? JSON.parse(result) : [];
if (solutions.length === 0) {
console.log('No bound solutions found. Run /issue:plan first.');
return;
}
// solutions already in correct format:
// { issue_id, solution_id, is_bound, task_count, files_touched[], priority }
```
**Multi-Queue Distribution** (if `--queues > 1`):

View File

@@ -1,9 +1,13 @@
---
name: breakdown
description: Decompose complex task into subtasks with dependency mapping, creates child task JSONs with parent references and execution order
argument-hint: "task-id"
argument-hint: "[-y|--yes] task-id"
---
## Auto Mode
When `--yes` or `-y`: Auto-confirm breakdown, use recommended subtask structure.
# Task Breakdown Command (/task:breakdown)
## Overview

View File

@@ -1,10 +1,14 @@
---
name: replan
description: Update task JSON with new requirements or batch-update multiple tasks from verification report, tracks changes in task-changes.json
argument-hint: "task-id [\"text\"|file.md] | --batch [verification-report.md]"
argument-hint: "[-y|--yes] task-id [\"text\"|file.md] | --batch [verification-report.md]"
allowed-tools: Read(*), Write(*), Edit(*), TodoWrite(*), Glob(*), Bash(*)
---
## Auto Mode
When `--yes` or `-y`: Auto-confirm updates, use recommended changes.
# Task Replan Command (/task:replan)
> **⚠️ DEPRECATION NOTICE**: This command is maintained for backward compatibility. For new workflows, use `/workflow:replan` which provides:
@@ -353,7 +357,7 @@ Review error details in summary report
# No replan recommendations found
Verification report contains no replan recommendations
Check report content or use /workflow:action-plan-verify first
Check report content or use /workflow:plan-verify first
```
## Batch Mode Integration

View File

@@ -1,8 +1,8 @@
---
name: action-plan-verify
description: Perform non-destructive cross-artifact consistency analysis between IMPL_PLAN.md and task JSONs with quality gate validation
name: plan-verify
description: Perform READ-ONLY verification analysis between IMPL_PLAN.md, task JSONs, and brainstorming artifacts. Generates structured report with quality gate recommendation. Does NOT modify any files.
argument-hint: "[optional: --session session-id]"
allowed-tools: Read(*), TodoWrite(*), Glob(*), Bash(*)
allowed-tools: Read(*), Write(*), Glob(*), Bash(*)
---
## User Input
@@ -15,13 +15,26 @@ You **MUST** consider the user input before proceeding (if not empty).
## Goal
Identify inconsistencies, duplications, ambiguities, and underspecified items between action planning artifacts (`IMPL_PLAN.md`, `task.json`) and brainstorming artifacts (`role analysis documents`) before implementation. This command MUST run only after `/workflow:plan` has successfully produced complete `IMPL_PLAN.md` and task JSON files.
Generate a comprehensive verification report that identifies inconsistencies, duplications, ambiguities, and underspecified items between action planning artifacts (`IMPL_PLAN.md`, `task.json`) and brainstorming artifacts (`role analysis documents`). This command MUST run only after `/workflow:plan` has successfully produced complete `IMPL_PLAN.md` and task JSON files.
**Output**: A structured Markdown report saved to `.workflow/active/WFS-{session}/.process/ACTION_PLAN_VERIFICATION.md` containing:
- Executive summary with quality gate recommendation
- Detailed findings by severity (CRITICAL/HIGH/MEDIUM/LOW)
- Requirements coverage analysis
- Dependency integrity check
- Synthesis alignment validation
- Actionable remediation recommendations
## Operating Constraints
**STRICTLY READ-ONLY**: Do **not** modify any files. Output a structured analysis report. Offer an optional remediation plan (user must explicitly approve before any follow-up editing commands).
**STRICTLY READ-ONLY FOR SOURCE ARTIFACTS**:
- **MUST NOT** modify `IMPL_PLAN.md`, any `task.json` files, or brainstorming artifacts
- **MUST NOT** create or delete task files
- **MUST ONLY** write the verification report to `.process/ACTION_PLAN_VERIFICATION.md`
**Synthesis Authority**: The `role analysis documents` is **authoritative** for requirements and design decisions. Any conflicts between IMPL_PLAN/tasks and synthesis are automatically CRITICAL and require adjustment of the plan/tasks—not reinterpretation of requirements.
**Synthesis Authority**: The `role analysis documents` are **authoritative** for requirements and design decisions. Any conflicts between IMPL_PLAN/tasks and synthesis are automatically CRITICAL and require adjustment of the plan/tasks—not reinterpretation of requirements.
**Quality Gate Authority**: The verification report provides a binding recommendation (BLOCK_EXECUTION / PROCEED_WITH_FIXES / PROCEED_WITH_CAUTION / PROCEED) based on objective severity criteria. User MUST review critical/high issues before proceeding with implementation.
## Execution Steps
@@ -47,6 +60,12 @@ ELSE:
session_dir = .workflow/active/WFS-{session}
brainstorm_dir = session_dir/.brainstorming
task_dir = session_dir/.task
process_dir = session_dir/.process
session_file = session_dir/workflow-session.json
# Create .process directory if not exists (report output location)
IF NOT EXISTS(process_dir):
bash(mkdir -p "{process_dir}")
# Validate required artifacts
# Note: "role analysis documents" refers to [role]/analysis.md files (e.g., product-manager/analysis.md)
@@ -54,7 +73,12 @@ SYNTHESIS_DIR = brainstorm_dir # Contains role analysis files: */analysis.md
IMPL_PLAN = session_dir/IMPL_PLAN.md
TASK_FILES = Glob(task_dir/*.json)
# Abort if missing
# Abort if missing - in order of dependency
SESSION_FILE_EXISTS = EXISTS(session_file)
IF NOT SESSION_FILE_EXISTS:
WARNING: "workflow-session.json not found. User intent alignment verification will be skipped."
# Continue execution - this is optional context, not blocking
SYNTHESIS_FILES = Glob(brainstorm_dir/*/analysis.md)
IF SYNTHESIS_FILES.count == 0:
ERROR: "No role analysis documents found in .brainstorming/*/analysis.md. Run /workflow:brainstorm:synthesis first"
@@ -73,12 +97,14 @@ IF TASK_FILES.count == 0:
Load only minimal necessary context from each artifact:
**From workflow-session.json** (NEW - PRIMARY REFERENCE):
**From workflow-session.json** (OPTIONAL - Primary Reference for User Intent):
- **ONLY IF EXISTS**: Load user intent context
- Original user prompt/intent (project or description field)
- User's stated goals and objectives
- User's scope definition
- **IF MISSING**: Set user_intent_analysis = "SKIPPED: workflow-session.json not found"
**From role analysis documents**:
**From role analysis documents** (AUTHORITATIVE SOURCE):
- Functional Requirements (IDs, descriptions, acceptance criteria)
- Non-Functional Requirements (IDs, targets)
- Business Requirements (IDs, success metrics)
@@ -126,9 +152,21 @@ Create internal representations (do not include raw artifacts in output):
### 4. Detection Passes (Token-Efficient Analysis)
Focus on high-signal findings. Limit to 50 findings total; aggregate remainder in overflow summary.
**Token Budget Strategy**:
- **Total Limit**: 50 findings maximum (aggregate remainder in overflow summary)
- **Priority Allocation**: CRITICAL (unlimited) → HIGH (15) → MEDIUM (20) → LOW (15)
- **Early Exit**: If CRITICAL findings > 0 in User Intent/Requirements Coverage, skip LOW/MEDIUM priority checks
#### A. User Intent Alignment (NEW - CRITICAL)
**Execution Order** (Process in sequence; skip if token budget exhausted):
1. **Tier 1 (CRITICAL Path)**: A, B, C - User intent, coverage, consistency (process fully)
2. **Tier 2 (HIGH Priority)**: D, E - Dependencies, synthesis alignment (limit 15 findings total)
3. **Tier 3 (MEDIUM Priority)**: F - Specification quality (limit 20 findings)
4. **Tier 4 (LOW Priority)**: G, H - Duplication, feasibility (limit 15 findings total)
---
#### A. User Intent Alignment (CRITICAL - Tier 1)
- **Goal Alignment**: IMPL_PLAN objectives match user's original intent
- **Scope Drift**: Plan covers user's stated scope without unauthorized expansion

View File

@@ -1,10 +1,14 @@
---
name: artifacts
description: Interactive clarification generating confirmed guidance specification through role-based analysis and synthesis
argument-hint: "topic or challenge description [--count N]"
argument-hint: "[-y|--yes] topic or challenge description [--count N]"
allowed-tools: TodoWrite(*), Read(*), Write(*), Glob(*), AskUserQuestion(*)
---
## Auto Mode
When `--yes` or `-y`: Auto-select recommended roles, skip all clarification questions, use default answers.
## Overview
Seven-phase workflow: **Context collection****Topic analysis****Role selection****Role questions****Conflict resolution****Final check****Generate specification**

View File

@@ -1,10 +1,14 @@
---
name: auto-parallel
description: Parallel brainstorming automation with dynamic role selection and concurrent execution across multiple perspectives
argument-hint: "topic or challenge description" [--count N]
argument-hint: "[-y|--yes] topic or challenge description [--count N]"
allowed-tools: SlashCommand(*), Task(*), TodoWrite(*), Read(*), Write(*), Bash(*), Glob(*)
---
## Auto Mode
When `--yes` or `-y`: Auto-select recommended roles, skip all clarification questions, use default answers.
# Workflow Brainstorm Parallel Auto Command
## Coordinator Role

View File

@@ -1,10 +1,14 @@
---
name: synthesis
description: Clarify and refine role analyses through intelligent Q&A and targeted updates with synthesis agent
argument-hint: "[optional: --session session-id]"
argument-hint: "[-y|--yes] [optional: --session session-id]"
allowed-tools: Task(conceptual-planning-agent), TodoWrite(*), Read(*), Write(*), Edit(*), Glob(*), AskUserQuestion(*)
---
## Auto Mode
When `--yes` or `-y`: Auto-select all enhancements, skip clarification questions, use default answers.
## Overview
Six-phase workflow to eliminate ambiguities and enhance conceptual depth in role analyses:

View File

@@ -1,7 +1,7 @@
---
name: clean
description: Intelligent code cleanup with mainline detection, stale artifact discovery, and safe execution
argument-hint: "[--dry-run] [\"focus area\"]"
argument-hint: "[-y|--yes] [--dry-run] [\"focus area\"]"
allowed-tools: TodoWrite(*), Task(*), AskUserQuestion(*), Read(*), Glob(*), Bash(*), Write(*)
---
@@ -21,8 +21,22 @@ Intelligent cleanup command that explores the codebase to identify the developme
```bash
/workflow:clean # Full intelligent cleanup (explore → analyze → confirm → execute)
/workflow:clean --yes # Auto mode (use safe defaults, no confirmation)
/workflow:clean --dry-run # Explore and analyze only, no execution
/workflow:clean "auth module" # Focus cleanup on specific area
/workflow:clean -y "auth module" # Auto mode with focus area
```
## Auto Mode Defaults
When `--yes` or `-y` flag is used:
- **Categories to Clean**: Auto-selects `["Sessions"]` only (safest - only workflow sessions)
- **Risk Level**: Auto-selects `"Low only"` (only low-risk items)
- All confirmations skipped, proceeds directly to execution
**Flag Parsing**:
```javascript
const autoYes = $ARGUMENTS.includes('--yes') || $ARGUMENTS.includes('-y')
const dryRun = $ARGUMENTS.includes('--dry-run')
```
## Execution Process
@@ -329,39 +343,57 @@ To execute cleanup: /workflow:clean
**Step 3.3: User Confirmation**
```javascript
AskUserQuestion({
questions: [
{
question: "Which categories to clean?",
header: "Categories",
multiSelect: true,
options: [
{
label: "Sessions",
description: `${manifest.summary.by_category.stale_sessions} stale workflow sessions`
},
{
label: "Documents",
description: `${manifest.summary.by_category.drifted_documents} drifted documents`
},
{
label: "Dead Code",
description: `${manifest.summary.by_category.dead_code} unused code files`
}
]
},
{
question: "Risk level to include?",
header: "Risk",
multiSelect: false,
options: [
{ label: "Low only", description: "Safest - only obviously stale items" },
{ label: "Low + Medium", description: "Recommended - includes likely unused items" },
{ label: "All", description: "Aggressive - includes high-risk items" }
]
}
]
})
// Parse --yes flag
const autoYes = $ARGUMENTS.includes('--yes') || $ARGUMENTS.includes('-y')
let userSelection
if (autoYes) {
// Auto mode: Use safe defaults
console.log(`[--yes] Auto-selecting safe cleanup defaults:`)
console.log(` - Categories: Sessions only`)
console.log(` - Risk level: Low only`)
userSelection = {
categories: ["Sessions"],
risk: "Low only"
}
} else {
// Interactive mode: Ask user
userSelection = AskUserQuestion({
questions: [
{
question: "Which categories to clean?",
header: "Categories",
multiSelect: true,
options: [
{
label: "Sessions",
description: `${manifest.summary.by_category.stale_sessions} stale workflow sessions`
},
{
label: "Documents",
description: `${manifest.summary.by_category.drifted_documents} drifted documents`
},
{
label: "Dead Code",
description: `${manifest.summary.by_category.dead_code} unused code files`
}
]
},
{
question: "Risk level to include?",
header: "Risk",
multiSelect: false,
options: [
{ label: "Low only", description: "Safest - only obviously stale items" },
{ label: "Low + Medium", description: "Recommended - includes likely unused items" },
{ label: "All", description: "Aggressive - includes high-risk items" }
]
}
]
})
}
```
---

View File

@@ -1,10 +1,14 @@
---
name: debug-with-file
description: Interactive hypothesis-driven debugging with documented exploration, understanding evolution, and Gemini-assisted correction
argument-hint: "\"bug description or error message\""
argument-hint: "[-y|--yes] \"bug description or error message\""
allowed-tools: TodoWrite(*), Task(*), AskUserQuestion(*), Read(*), Grep(*), Glob(*), Bash(*), Edit(*), Write(*)
---
## Auto Mode
When `--yes` or `-y`: Auto-confirm all decisions (hypotheses, fixes, iteration), use recommended settings.
# Workflow Debug-With-File Command (/workflow:debug-with-file)
## Overview

View File

@@ -1,10 +1,14 @@
---
name: debug
description: Interactive hypothesis-driven debugging with NDJSON logging, iterative until resolved
argument-hint: "\"bug description or error message\""
argument-hint: "[-y|--yes] \"bug description or error message\""
allowed-tools: TodoWrite(*), Task(*), AskUserQuestion(*), Read(*), Grep(*), Glob(*), Bash(*), Edit(*), Write(*)
---
## Auto Mode
When `--yes` or `-y`: Auto-confirm all decisions (hypotheses, fixes, iteration), use recommended settings.
# Workflow Debug Command (/workflow:debug)
## Overview

File diff suppressed because it is too large Load Diff

View File

@@ -1,7 +1,7 @@
---
name: execute
description: Coordinate agent execution for workflow tasks with automatic session discovery, parallel task processing, and status tracking
argument-hint: "[--resume-session=\"session-id\"]"
argument-hint: "[-y|--yes] [--resume-session=\"session-id\"]"
---
# Workflow Execute Command
@@ -11,6 +11,30 @@ Orchestrates autonomous workflow execution through systematic task discovery, ag
**Resume Mode**: When called with `--resume-session` flag, skips discovery phase and directly enters TodoWrite generation and agent execution for the specified session.
## Usage
```bash
# Interactive mode (with confirmations)
/workflow:execute
/workflow:execute --resume-session="WFS-auth"
# Auto mode (skip confirmations, use defaults)
/workflow:execute --yes
/workflow:execute -y
/workflow:execute -y --resume-session="WFS-auth"
```
## Auto Mode Defaults
When `--yes` or `-y` flag is used:
- **Session Selection**: Automatically selects the first (most recent) active session
- **Completion Choice**: Automatically completes session (runs `/workflow:session:complete --yes`)
**Flag Parsing**:
```javascript
const autoYes = $ARGUMENTS.includes('--yes') || $ARGUMENTS.includes('-y')
```
## Performance Optimization Strategy
**Lazy Loading**: Task JSONs read **on-demand** during execution, not upfront. TODO_LIST.md + IMPL_PLAN.md provide metadata for planning.
@@ -122,24 +146,38 @@ List sessions with metadata and prompt user selection:
bash(for dir in .workflow/active/WFS-*/; do [ -d "$dir" ] || continue; session=$(basename "$dir"); project=$(jq -r '.project // "Unknown"' "${dir}workflow-session.json" 2>/dev/null || echo "Unknown"); total=$(grep -c '^\- \[' "${dir}TODO_LIST.md" 2>/dev/null || echo 0); completed=$(grep -c '^\- \[x\]' "${dir}TODO_LIST.md" 2>/dev/null || echo 0); if [ "$total" -gt 0 ]; then progress=$((completed * 100 / total)); else progress=0; fi; echo "$session | $project | $completed/$total tasks ($progress%)"; done)
```
Use AskUserQuestion to present formatted options (max 4 options shown):
**Parse --yes flag**:
```javascript
// If more than 4 sessions, show most recent 4 with "Other" option for manual input
const sessions = getActiveSessions() // sorted by last modified
const displaySessions = sessions.slice(0, 4)
const autoYes = $ARGUMENTS.includes('--yes') || $ARGUMENTS.includes('-y')
```
AskUserQuestion({
questions: [{
question: "Multiple active sessions detected. Select one:",
header: "Session",
multiSelect: false,
options: displaySessions.map(s => ({
label: s.id,
description: `${s.project} | ${s.progress}`
}))
// Note: User can select "Other" to manually enter session ID
}]
})
**Conditional Selection**:
```javascript
if (autoYes) {
// Auto mode: Select first session (most recent)
const firstSession = sessions[0]
console.log(`[--yes] Auto-selecting session: ${firstSession.id}`)
selectedSessionId = firstSession.id
// Continue to Phase 2
} else {
// Interactive mode: Use AskUserQuestion to present formatted options (max 4 options shown)
// If more than 4 sessions, show most recent 4 with "Other" option for manual input
const sessions = getActiveSessions() // sorted by last modified
const displaySessions = sessions.slice(0, 4)
AskUserQuestion({
questions: [{
question: "Multiple active sessions detected. Select one:",
header: "Session",
multiSelect: false,
options: displaySessions.map(s => ({
label: s.id,
description: `${s.project} | ${s.progress}`
}))
// Note: User can select "Other" to manually enter session ID
}]
})
}
```
**Input Validation**:
@@ -252,23 +290,33 @@ while (TODO_LIST.md has pending tasks) {
6. **User Choice**: When all tasks finished, ask user to choose next step:
```javascript
AskUserQuestion({
questions: [{
question: "All tasks completed. What would you like to do next?",
header: "Next Step",
multiSelect: false,
options: [
{
label: "Enter Review",
description: "Run specialized review (security/architecture/quality/action-items)"
},
{
label: "Complete Session",
description: "Archive session and update manifest"
}
]
}]
})
// Parse --yes flag
const autoYes = $ARGUMENTS.includes('--yes') || $ARGUMENTS.includes('-y')
if (autoYes) {
// Auto mode: Complete session automatically
console.log(`[--yes] Auto-selecting: Complete Session`)
SlashCommand("/workflow:session:complete --yes")
} else {
// Interactive mode: Ask user
AskUserQuestion({
questions: [{
question: "All tasks completed. What would you like to do next?",
header: "Next Step",
multiSelect: false,
options: [
{
label: "Enter Review",
description: "Run specialized review (security/architecture/quality/action-items)"
},
{
label: "Complete Session",
description: "Archive session and update manifest"
}
]
}]
})
}
```
**Based on user selection**:

View File

@@ -1,7 +1,7 @@
---
name: lite-execute
description: Execute tasks based on in-memory plan, prompt description, or file content
argument-hint: "[--in-memory] [\"task description\"|file-path]"
argument-hint: "[-y|--yes] [--in-memory] [\"task description\"|file-path]"
allowed-tools: TodoWrite(*), Task(*), Bash(*)
---
@@ -62,31 +62,49 @@ Flexible task execution command supporting three input modes: in-memory plan (fr
**User Interaction**:
```javascript
AskUserQuestion({
questions: [
{
question: "Select execution method:",
header: "Execution",
multiSelect: false,
options: [
{ label: "Agent", description: "@code-developer agent" },
{ label: "Codex", description: "codex CLI tool" },
{ label: "Auto", description: "Auto-select based on complexity" }
]
},
{
question: "Enable code review after execution?",
header: "Code Review",
multiSelect: false,
options: [
{ label: "Skip", description: "No review" },
{ label: "Gemini Review", description: "Gemini CLI tool" },
{ label: "Codex Review", description: "Git-aware review (prompt OR --uncommitted)" },
{ label: "Agent Review", description: "Current agent review" }
]
}
]
})
// Parse --yes flag
const autoYes = $ARGUMENTS.includes('--yes') || $ARGUMENTS.includes('-y')
let userSelection
if (autoYes) {
// Auto mode: Use defaults
console.log(`[--yes] Auto-confirming execution:`)
console.log(` - Execution method: Auto`)
console.log(` - Code review: Skip`)
userSelection = {
execution_method: "Auto",
code_review_tool: "Skip"
}
} else {
// Interactive mode: Ask user
userSelection = AskUserQuestion({
questions: [
{
question: "Select execution method:",
header: "Execution",
multiSelect: false,
options: [
{ label: "Agent", description: "@code-developer agent" },
{ label: "Codex", description: "codex CLI tool" },
{ label: "Auto", description: "Auto-select based on complexity" }
]
},
{
question: "Enable code review after execution?",
header: "Code Review",
multiSelect: false,
options: [
{ label: "Skip", description: "No review" },
{ label: "Gemini Review", description: "Gemini CLI tool" },
{ label: "Codex Review", description: "Git-aware review (prompt OR --uncommitted)" },
{ label: "Agent Review", description: "Current agent review" }
]
}
]
})
}
```
### Mode 3: File Content

View File

@@ -1,7 +1,7 @@
---
name: lite-fix
description: Lightweight bug diagnosis and fix workflow with intelligent severity assessment and optional hotfix mode for production incidents
argument-hint: "[--hotfix] \"bug description or issue reference\""
argument-hint: "[-y|--yes] [--hotfix] \"bug description or issue reference\""
allowed-tools: TodoWrite(*), Task(*), SlashCommand(*), AskUserQuestion(*)
---
@@ -25,10 +25,32 @@ Intelligent lightweight bug fixing command with dynamic workflow adaptation base
/workflow:lite-fix [FLAGS] <BUG_DESCRIPTION>
# Flags
-y, --yes Skip all confirmations (auto mode)
--hotfix, -h Production hotfix mode (minimal diagnosis, fast fix)
# Arguments
<bug-description> Bug description, error message, or path to .md file (required)
# Examples
/workflow:lite-fix "用户登录失败" # Interactive mode
/workflow:lite-fix --yes "用户登录失败" # Auto mode (no confirmations)
/workflow:lite-fix -y --hotfix "生产环境数据库连接失败" # Auto + hotfix mode
```
## Auto Mode Defaults
When `--yes` or `-y` flag is used:
- **Clarification Questions**: Skipped (no clarification phase)
- **Fix Plan Confirmation**: Auto-selected "Allow"
- **Execution Method**: Auto-selected "Auto"
- **Code Review**: Auto-selected "Skip"
- **Severity**: Uses auto-detected severity (no manual override)
- **Hotfix Mode**: Respects --hotfix flag if present, otherwise normal mode
**Flag Parsing**:
```javascript
const autoYes = $ARGUMENTS.includes('--yes') || $ARGUMENTS.includes('-y')
const hotfixMode = $ARGUMENTS.includes('--hotfix') || $ARGUMENTS.includes('-h')
```
## Execution Process
@@ -332,9 +354,17 @@ function deduplicateClarifications(clarifications) {
const uniqueClarifications = deduplicateClarifications(allClarifications)
// Multi-round clarification: batch questions (max 4 per round)
// ⚠️ MUST execute ALL rounds until uniqueClarifications exhausted
if (uniqueClarifications.length > 0) {
// Parse --yes flag
const autoYes = $ARGUMENTS.includes('--yes') || $ARGUMENTS.includes('-y')
if (autoYes) {
// Auto mode: Skip clarification phase
console.log(`[--yes] Skipping ${uniqueClarifications.length} clarification questions`)
console.log(`Proceeding to fix planning with diagnosis results...`)
// Continue to Phase 3
} else if (uniqueClarifications.length > 0) {
// Interactive mode: Multi-round clarification
// ⚠️ MUST execute ALL rounds until uniqueClarifications exhausted
const BATCH_SIZE = 4
const totalRounds = Math.ceil(uniqueClarifications.length / BATCH_SIZE)
@@ -600,40 +630,60 @@ ${fixPlan.tasks.map((t, i) => `${i+1}. ${t.title} (${t.scope})`).join('\n')}
**Step 4.2: Collect Confirmation**
```javascript
AskUserQuestion({
questions: [
{
question: `Confirm fix plan? (${fixPlan.tasks.length} tasks, ${fixPlan.severity} severity)`,
header: "Confirm",
multiSelect: true,
options: [
{ label: "Allow", description: "Proceed as-is" },
{ label: "Modify", description: "Adjust before execution" },
{ label: "Cancel", description: "Abort workflow" }
]
},
{
question: "Execution method:",
header: "Execution",
multiSelect: false,
options: [
{ label: "Agent", description: "@code-developer agent" },
{ label: "Codex", description: "codex CLI tool" },
{ label: "Auto", description: `Auto: ${fixPlan.severity === 'Low' ? 'Agent' : 'Codex'}` }
]
},
{
question: "Code review after fix?",
header: "Review",
multiSelect: false,
options: [
{ label: "Gemini Review", description: "Gemini CLI" },
{ label: "Agent Review", description: "@code-reviewer" },
{ label: "Skip", description: "No review" }
]
}
]
})
// Parse --yes flag
const autoYes = $ARGUMENTS.includes('--yes') || $ARGUMENTS.includes('-y')
let userSelection
if (autoYes) {
// Auto mode: Use defaults
console.log(`[--yes] Auto-confirming fix plan:`)
console.log(` - Confirmation: Allow`)
console.log(` - Execution: Auto`)
console.log(` - Review: Skip`)
userSelection = {
confirmation: "Allow",
execution_method: "Auto",
code_review_tool: "Skip"
}
} else {
// Interactive mode: Ask user
userSelection = AskUserQuestion({
questions: [
{
question: `Confirm fix plan? (${fixPlan.tasks.length} tasks, ${fixPlan.severity} severity)`,
header: "Confirm",
multiSelect: false,
options: [
{ label: "Allow", description: "Proceed as-is" },
{ label: "Modify", description: "Adjust before execution" },
{ label: "Cancel", description: "Abort workflow" }
]
},
{
question: "Execution method:",
header: "Execution",
multiSelect: false,
options: [
{ label: "Agent", description: "@code-developer agent" },
{ label: "Codex", description: "codex CLI tool" },
{ label: "Auto", description: `Auto: ${fixPlan.severity === 'Low' ? 'Agent' : 'Codex'}` }
]
},
{
question: "Code review after fix?",
header: "Review",
multiSelect: false,
options: [
{ label: "Gemini Review", description: "Gemini CLI" },
{ label: "Agent Review", description: "@code-reviewer" },
{ label: "Skip", description: "No review" }
]
}
]
})
}
```
---

View File

@@ -1,10 +1,14 @@
---
name: workflow:lite-lite-lite
description: Ultra-lightweight multi-tool analysis and direct execution. No artifacts for simple tasks; auto-creates planning docs in .workflow/.scratchpad/ for complex tasks. Auto tool selection based on task analysis, user-driven iteration via AskUser.
argument-hint: "<task description>"
argument-hint: "[-y|--yes] <task description>"
allowed-tools: TodoWrite(*), Task(*), AskUserQuestion(*), Read(*), Bash(*), Write(*), mcp__ace-tool__search_context(*), mcp__ccw-tools__write_file(*)
---
## Auto Mode
When `--yes` or `-y`: Skip clarification questions, auto-select tools, execute directly with recommended settings.
# Ultra-Lite Multi-Tool Workflow
## Quick Start

View File

@@ -1,7 +1,7 @@
---
name: lite-plan
description: Lightweight interactive planning workflow with in-memory planning, code exploration, and execution execute to lite-execute after user confirmation
argument-hint: "[-e|--explore] \"task description\"|file.md"
argument-hint: "[-y|--yes] [-e|--explore] \"task description\"|file.md"
allowed-tools: TodoWrite(*), Task(*), SlashCommand(*), AskUserQuestion(*)
---
@@ -25,10 +25,30 @@ Intelligent lightweight planning command with dynamic workflow adaptation based
/workflow:lite-plan [FLAGS] <TASK_DESCRIPTION>
# Flags
-y, --yes Skip all confirmations (auto mode)
-e, --explore Force code exploration phase (overrides auto-detection)
# Arguments
<task-description> Task description or path to .md file (required)
# Examples
/workflow:lite-plan "实现JWT认证" # Interactive mode
/workflow:lite-plan --yes "实现JWT认证" # Auto mode (no confirmations)
/workflow:lite-plan -y -e "优化数据库查询性能" # Auto mode + force exploration
```
## Auto Mode Defaults
When `--yes` or `-y` flag is used:
- **Clarification Questions**: Skipped (no clarification phase)
- **Plan Confirmation**: Auto-selected "Allow"
- **Execution Method**: Auto-selected "Auto"
- **Code Review**: Auto-selected "Skip"
**Flag Parsing**:
```javascript
const autoYes = $ARGUMENTS.includes('--yes') || $ARGUMENTS.includes('-y')
const forceExplore = $ARGUMENTS.includes('--explore') || $ARGUMENTS.includes('-e')
```
## Execution Process
@@ -323,8 +343,16 @@ explorations.forEach(exp => {
// - Produce dedupedClarifications with unique intents only
const dedupedClarifications = intelligentMerge(allClarifications)
// Multi-round clarification: batch questions (max 4 per round)
if (dedupedClarifications.length > 0) {
// Parse --yes flag
const autoYes = $ARGUMENTS.includes('--yes') || $ARGUMENTS.includes('-y')
if (autoYes) {
// Auto mode: Skip clarification phase
console.log(`[--yes] Skipping ${dedupedClarifications.length} clarification questions`)
console.log(`Proceeding to planning with exploration results...`)
// Continue to Phase 3
} else if (dedupedClarifications.length > 0) {
// Interactive mode: Multi-round clarification
const BATCH_SIZE = 4
const totalRounds = Math.ceil(dedupedClarifications.length / BATCH_SIZE)
@@ -497,42 +525,62 @@ ${plan.tasks.map((t, i) => `${i+1}. ${t.title} (${t.file})`).join('\n')}
**Step 4.2: Collect Confirmation**
```javascript
// Note: Execution "Other" option allows specifying CLI tools from ~/.claude/cli-tools.json
AskUserQuestion({
questions: [
{
question: `Confirm plan? (${plan.tasks.length} tasks, ${plan.complexity})`,
header: "Confirm",
multiSelect: true,
options: [
{ label: "Allow", description: "Proceed as-is" },
{ label: "Modify", description: "Adjust before execution" },
{ label: "Cancel", description: "Abort workflow" }
]
},
{
question: "Execution method:",
header: "Execution",
multiSelect: false,
options: [
{ label: "Agent", description: "@code-developer agent" },
{ label: "Codex", description: "codex CLI tool" },
{ label: "Auto", description: `Auto: ${plan.complexity === 'Low' ? 'Agent' : 'Codex'}` }
]
},
{
question: "Code review after execution?",
header: "Review",
multiSelect: false,
options: [
{ label: "Gemini Review", description: "Gemini CLI review" },
{ label: "Codex Review", description: "Git-aware review (prompt OR --uncommitted)" },
{ label: "Agent Review", description: "@code-reviewer agent" },
{ label: "Skip", description: "No review" }
]
}
]
})
// Parse --yes flag
const autoYes = $ARGUMENTS.includes('--yes') || $ARGUMENTS.includes('-y')
let userSelection
if (autoYes) {
// Auto mode: Use defaults
console.log(`[--yes] Auto-confirming plan:`)
console.log(` - Confirmation: Allow`)
console.log(` - Execution: Auto`)
console.log(` - Review: Skip`)
userSelection = {
confirmation: "Allow",
execution_method: "Auto",
code_review_tool: "Skip"
}
} else {
// Interactive mode: Ask user
// Note: Execution "Other" option allows specifying CLI tools from ~/.claude/cli-tools.json
userSelection = AskUserQuestion({
questions: [
{
question: `Confirm plan? (${plan.tasks.length} tasks, ${plan.complexity})`,
header: "Confirm",
multiSelect: false,
options: [
{ label: "Allow", description: "Proceed as-is" },
{ label: "Modify", description: "Adjust before execution" },
{ label: "Cancel", description: "Abort workflow" }
]
},
{
question: "Execution method:",
header: "Execution",
multiSelect: false,
options: [
{ label: "Agent", description: "@code-developer agent" },
{ label: "Codex", description: "codex CLI tool" },
{ label: "Auto", description: `Auto: ${plan.complexity === 'Low' ? 'Agent' : 'Codex'}` }
]
},
{
question: "Code review after execution?",
header: "Review",
multiSelect: false,
options: [
{ label: "Gemini Review", description: "Gemini CLI review" },
{ label: "Codex Review", description: "Git-aware review (prompt OR --uncommitted)" },
{ label: "Agent Review", description: "@code-reviewer agent" },
{ label: "Skip", description: "No review" }
]
}
]
})
}
```
---

View File

@@ -1,10 +1,14 @@
---
name: workflow:multi-cli-plan
description: Multi-CLI collaborative planning workflow with ACE context gathering and iterative cross-verification. Uses cli-discuss-agent for Gemini+Codex+Claude analysis to converge on optimal execution plan.
argument-hint: "<task description> [--max-rounds=3] [--tools=gemini,codex] [--mode=parallel|serial]"
argument-hint: "[-y|--yes] <task description> [--max-rounds=3] [--tools=gemini,codex] [--mode=parallel|serial]"
allowed-tools: TodoWrite(*), Task(*), AskUserQuestion(*), Read(*), Bash(*), Write(*), mcp__ace-tool__search_context(*)
---
## Auto Mode
When `--yes` or `-y`: Auto-approve plan, use recommended solution and execution method (Agent, Skip review).
# Multi-CLI Collaborative Planning Command
## Quick Start

View File

@@ -0,0 +1,527 @@
---
name: plan-verify
description: Perform READ-ONLY verification analysis between IMPL_PLAN.md, task JSONs, and brainstorming artifacts. Generates structured report with quality gate recommendation. Does NOT modify any files.
argument-hint: "[optional: --session session-id]"
allowed-tools: Read(*), Write(*), Glob(*), Bash(*)
---
## User Input
```text
$ARGUMENTS
```
You **MUST** consider the user input before proceeding (if not empty).
## Goal
Generate a comprehensive verification report that identifies inconsistencies, duplications, ambiguities, and underspecified items between action planning artifacts (`IMPL_PLAN.md`, `task.json`) and brainstorming artifacts (`role analysis documents`). This command MUST run only after `/workflow:plan` has successfully produced complete `IMPL_PLAN.md` and task JSON files.
**Output**: A structured Markdown report saved to `.workflow/active/WFS-{session}/.process/PLAN_VERIFICATION.md` containing:
- Executive summary with quality gate recommendation
- Detailed findings by severity (CRITICAL/HIGH/MEDIUM/LOW)
- Requirements coverage analysis
- Dependency integrity check
- Synthesis alignment validation
- Actionable remediation recommendations
## Operating Constraints
**STRICTLY READ-ONLY FOR SOURCE ARTIFACTS**:
- **MUST NOT** modify `IMPL_PLAN.md`, any `task.json` files, or brainstorming artifacts
- **MUST NOT** create or delete task files
- **MUST ONLY** write the verification report to `.process/PLAN_VERIFICATION.md`
**Synthesis Authority**: The `role analysis documents` are **authoritative** for requirements and design decisions. Any conflicts between IMPL_PLAN/tasks and synthesis are automatically CRITICAL and require adjustment of the plan/tasks—not reinterpretation of requirements.
**Quality Gate Authority**: The verification report provides a binding recommendation (BLOCK_EXECUTION / PROCEED_WITH_FIXES / PROCEED_WITH_CAUTION / PROCEED) based on objective severity criteria. User MUST review critical/high issues before proceeding with implementation.
## Execution Steps
### 1. Initialize Analysis Context
```bash
# Detect active workflow session
IF --session parameter provided:
session_id = provided session
ELSE:
# Auto-detect active session
active_sessions = bash(find .workflow/active/ -name "WFS-*" -type d 2>/dev/null)
IF active_sessions is empty:
ERROR: "No active workflow session found. Use --session <session-id>"
EXIT
ELSE IF active_sessions has multiple entries:
# Use most recently modified session
session_id = bash(ls -td .workflow/active/WFS-*/ 2>/dev/null | head -1 | xargs basename)
ELSE:
session_id = basename(active_sessions[0])
# Derive absolute paths
session_dir = .workflow/active/WFS-{session}
brainstorm_dir = session_dir/.brainstorming
task_dir = session_dir/.task
process_dir = session_dir/.process
session_file = session_dir/workflow-session.json
# Create .process directory if not exists (report output location)
IF NOT EXISTS(process_dir):
bash(mkdir -p "{process_dir}")
# Validate required artifacts
# Note: "role analysis documents" refers to [role]/analysis.md files (e.g., product-manager/analysis.md)
SYNTHESIS_DIR = brainstorm_dir # Contains role analysis files: */analysis.md
IMPL_PLAN = session_dir/IMPL_PLAN.md
TASK_FILES = Glob(task_dir/*.json)
# Abort if missing - in order of dependency
SESSION_FILE_EXISTS = EXISTS(session_file)
IF NOT SESSION_FILE_EXISTS:
WARNING: "workflow-session.json not found. User intent alignment verification will be skipped."
# Continue execution - this is optional context, not blocking
SYNTHESIS_FILES = Glob(brainstorm_dir/*/analysis.md)
IF SYNTHESIS_FILES.count == 0:
ERROR: "No role analysis documents found in .brainstorming/*/analysis.md. Run /workflow:brainstorm:synthesis first"
EXIT
IF NOT EXISTS(IMPL_PLAN):
ERROR: "IMPL_PLAN.md not found. Run /workflow:plan first"
EXIT
IF TASK_FILES.count == 0:
ERROR: "No task JSON files found. Run /workflow:plan first"
EXIT
```
### 2. Load Artifacts (Progressive Disclosure)
Load only minimal necessary context from each artifact:
**From workflow-session.json** (OPTIONAL - Primary Reference for User Intent):
- **ONLY IF EXISTS**: Load user intent context
- Original user prompt/intent (project or description field)
- User's stated goals and objectives
- User's scope definition
- **IF MISSING**: Set user_intent_analysis = "SKIPPED: workflow-session.json not found"
**From role analysis documents** (AUTHORITATIVE SOURCE):
- Functional Requirements (IDs, descriptions, acceptance criteria)
- Non-Functional Requirements (IDs, targets)
- Business Requirements (IDs, success metrics)
- Key Architecture Decisions
- Risk factors and mitigation strategies
- Implementation Roadmap (high-level phases)
**From IMPL_PLAN.md**:
- Summary and objectives
- Context Analysis
- Implementation Strategy
- Task Breakdown Summary
- Success Criteria
- Brainstorming Artifacts References (if present)
**From task.json files**:
- Task IDs
- Titles and descriptions
- Status
- Dependencies (depends_on, blocks)
- Context (requirements, focus_paths, acceptance, artifacts)
- Flow control (pre_analysis, implementation_approach)
- Meta (complexity, priority)
### 3. Build Semantic Models
Create internal representations (do not include raw artifacts in output):
**Requirements inventory**:
- Each functional/non-functional/business requirement with stable ID
- Requirement text, acceptance criteria, priority
**Architecture decisions inventory**:
- ADRs from synthesis
- Technology choices
- Data model references
**Task coverage mapping**:
- Map each task to one or more requirements (by ID reference or keyword inference)
- Map each requirement to covering tasks
**Dependency graph**:
- Task-to-task dependencies (depends_on, blocks)
- Requirement-level dependencies (from synthesis)
### 4. Detection Passes (Token-Efficient Analysis)
**Token Budget Strategy**:
- **Total Limit**: 50 findings maximum (aggregate remainder in overflow summary)
- **Priority Allocation**: CRITICAL (unlimited) → HIGH (15) → MEDIUM (20) → LOW (15)
- **Early Exit**: If CRITICAL findings > 0 in User Intent/Requirements Coverage, skip LOW/MEDIUM priority checks
**Execution Order** (Process in sequence; skip if token budget exhausted):
1. **Tier 1 (CRITICAL Path)**: A, B, C - User intent, coverage, consistency (process fully)
2. **Tier 2 (HIGH Priority)**: D, E - Dependencies, synthesis alignment (limit 15 findings total)
3. **Tier 3 (MEDIUM Priority)**: F - Specification quality (limit 20 findings)
4. **Tier 4 (LOW Priority)**: G, H - Duplication, feasibility (limit 15 findings total)
---
#### A. User Intent Alignment (CRITICAL - Tier 1)
- **Goal Alignment**: IMPL_PLAN objectives match user's original intent
- **Scope Drift**: Plan covers user's stated scope without unauthorized expansion
- **Success Criteria Match**: Plan's success criteria reflect user's expectations
- **Intent Conflicts**: Tasks contradicting user's original objectives
#### B. Requirements Coverage Analysis
- **Orphaned Requirements**: Requirements in synthesis with zero associated tasks
- **Unmapped Tasks**: Tasks with no clear requirement linkage
- **NFR Coverage Gaps**: Non-functional requirements (performance, security, scalability) not reflected in tasks
#### C. Consistency Validation
- **Requirement Conflicts**: Tasks contradicting synthesis requirements
- **Architecture Drift**: IMPL_PLAN architecture not matching synthesis ADRs
- **Terminology Drift**: Same concept named differently across IMPL_PLAN and tasks
- **Data Model Inconsistency**: Tasks referencing entities/fields not in synthesis data model
#### D. Dependency Integrity
- **Circular Dependencies**: Task A depends on B, B depends on C, C depends on A
- **Missing Dependencies**: Task requires outputs from another task but no explicit dependency
- **Broken Dependencies**: Task depends on non-existent task ID
- **Logical Ordering Issues**: Implementation tasks before foundational setup without dependency note
#### E. Synthesis Alignment
- **Priority Conflicts**: High-priority synthesis requirements mapped to low-priority tasks
- **Success Criteria Mismatch**: IMPL_PLAN success criteria not covering synthesis acceptance criteria
- **Risk Mitigation Gaps**: Critical risks in synthesis without corresponding mitigation tasks
#### F. Task Specification Quality
- **Ambiguous Focus Paths**: Tasks with vague or missing focus_paths
- **Underspecified Acceptance**: Tasks without clear acceptance criteria
- **Missing Artifacts References**: Tasks not referencing relevant brainstorming artifacts in context.artifacts
- **Weak Flow Control**: Tasks without clear implementation_approach or pre_analysis steps
- **Missing Target Files**: Tasks without flow_control.target_files specification
#### G. Duplication Detection
- **Overlapping Task Scope**: Multiple tasks with nearly identical descriptions
- **Redundant Requirements Coverage**: Same requirement covered by multiple tasks without clear partitioning
#### H. Feasibility Assessment
- **Complexity Misalignment**: Task marked "simple" but requires multiple file modifications
- **Resource Conflicts**: Parallel tasks requiring same resources/files
- **Skill Gap Risks**: Tasks requiring skills not in team capability assessment (from synthesis)
### 5. Severity Assignment
Use this heuristic to prioritize findings:
- **CRITICAL**:
- Violates user's original intent (goal misalignment, scope drift)
- Violates synthesis authority (requirement conflict)
- Core requirement with zero coverage
- Circular dependencies
- Broken dependencies
- **HIGH**:
- NFR coverage gaps
- Priority conflicts
- Missing risk mitigation tasks
- Ambiguous acceptance criteria
- **MEDIUM**:
- Terminology drift
- Missing artifacts references
- Weak flow control
- Logical ordering issues
- **LOW**:
- Style/wording improvements
- Minor redundancy not affecting execution
### 6. Produce Compact Analysis Report
**Report Generation**: Generate report content and save to file.
Output a Markdown report with the following structure:
```markdown
# Plan Verification Report
**Session**: WFS-{session-id}
**Generated**: {timestamp}
**Artifacts Analyzed**: role analysis documents, IMPL_PLAN.md, {N} task files
**User Intent Analysis**: {user_intent_analysis or "SKIPPED: workflow-session.json not found"}
---
## Executive Summary
### Quality Gate Decision
| Metric | Value | Status |
|--------|-------|--------|
| Overall Risk Level | CRITICAL \| HIGH \| MEDIUM \| LOW | {status_emoji} |
| Critical Issues | {count} | 🔴 |
| High Issues | {count} | 🟠 |
| Medium Issues | {count} | 🟡 |
| Low Issues | {count} | 🟢 |
### Recommendation
**{RECOMMENDATION}**
**Decision Rationale**:
{brief explanation based on severity criteria}
**Quality Gate Criteria**:
- **BLOCK_EXECUTION**: Critical issues > 0 (must fix before proceeding)
- **PROCEED_WITH_FIXES**: Critical = 0, High > 0 (fix recommended before execution)
- **PROCEED_WITH_CAUTION**: Critical = 0, High = 0, Medium > 0 (proceed with awareness)
- **PROCEED**: Only Low issues or None (safe to execute)
---
## Findings Summary
| ID | Category | Severity | Location(s) | Summary | Recommendation |
|----|----------|----------|-------------|---------|----------------|
| C1 | Coverage | CRITICAL | synthesis:FR-03 | Requirement "User auth" has zero task coverage | Add authentication implementation task |
| H1 | Consistency | HIGH | IMPL-1.2 vs synthesis:ADR-02 | Task uses REST while synthesis specifies GraphQL | Align task with ADR-02 decision |
| M1 | Specification | MEDIUM | IMPL-2.1 | Missing context.artifacts reference | Add @synthesis reference |
| L1 | Duplication | LOW | IMPL-3.1, IMPL-3.2 | Similar scope | Consider merging |
(Generate stable IDs prefixed by severity initial: C/H/M/L + number)
---
## User Intent Alignment Analysis
{IF user_intent_analysis != "SKIPPED"}
### Goal Alignment
- **User Intent**: {user_original_intent}
- **IMPL_PLAN Objectives**: {plan_objectives}
- **Alignment Status**: {ALIGNED/MISALIGNED/PARTIAL}
- **Findings**: {specific alignment issues}
### Scope Verification
- **User Scope**: {user_defined_scope}
- **Plan Scope**: {plan_actual_scope}
- **Drift Detection**: {NONE/MINOR/MAJOR}
- **Findings**: {specific scope issues}
{ELSE}
> ⚠️ User intent alignment analysis was skipped because workflow-session.json was not found.
{END IF}
---
## Requirements Coverage Analysis
### Functional Requirements
| Requirement ID | Requirement Summary | Has Task? | Task IDs | Priority Match | Notes |
|----------------|---------------------|-----------|----------|----------------|-------|
| FR-01 | User authentication | Yes | IMPL-1.1, IMPL-1.2 | Match | Complete |
| FR-02 | Data export | Yes | IMPL-2.3 | Mismatch | High req → Med priority task |
| FR-03 | Profile management | No | - | - | **CRITICAL: Zero coverage** |
### Non-Functional Requirements
| Requirement ID | Requirement Summary | Has Task? | Task IDs | Notes |
|----------------|---------------------|-----------|----------|-------|
| NFR-01 | Response time <200ms | No | - | **HIGH: No performance tasks** |
| NFR-02 | Security compliance | Yes | IMPL-4.1 | Complete |
### Business Requirements
| Requirement ID | Requirement Summary | Has Task? | Task IDs | Notes |
|----------------|---------------------|-----------|----------|-------|
| BR-01 | Launch by Q2 | Yes | IMPL-1.* through IMPL-5.* | Timeline realistic |
### Coverage Metrics
| Requirement Type | Total | Covered | Coverage % |
|------------------|-------|---------|------------|
| Functional | {count} | {count} | {percent}% |
| Non-Functional | {count} | {count} | {percent}% |
| Business | {count} | {count} | {percent}% |
| **Overall** | **{total}** | **{covered}** | **{percent}%** |
---
## Dependency Integrity
### Dependency Graph Analysis
**Circular Dependencies**: {None or List}
**Broken Dependencies**:
- IMPL-2.3 depends on "IMPL-2.4" (non-existent)
**Missing Dependencies**:
- IMPL-5.1 (integration test) has no dependency on IMPL-1.* (implementation tasks)
**Logical Ordering Issues**:
{List or "None detected"}
---
## Synthesis Alignment Issues
| Issue Type | Synthesis Reference | IMPL_PLAN/Task | Impact | Recommendation |
|------------|---------------------|----------------|--------|----------------|
| Architecture Conflict | synthesis:ADR-01 (JWT auth) | IMPL_PLAN uses session cookies | HIGH | Update IMPL_PLAN to use JWT |
| Priority Mismatch | synthesis:FR-02 (High) | IMPL-2.3 (Medium) | MEDIUM | Elevate task priority |
| Missing Risk Mitigation | synthesis:Risk-03 (API rate limits) | No mitigation tasks | HIGH | Add rate limiting implementation task |
---
## Task Specification Quality
### Aggregate Statistics
| Quality Dimension | Tasks Affected | Percentage |
|-------------------|----------------|------------|
| Missing Artifacts References | {count} | {percent}% |
| Weak Flow Control | {count} | {percent}% |
| Missing Target Files | {count} | {percent}% |
| Ambiguous Focus Paths | {count} | {percent}% |
### Sample Issues
- **IMPL-1.2**: No context.artifacts reference to synthesis
- **IMPL-3.1**: Missing flow_control.target_files specification
- **IMPL-4.2**: Vague focus_paths ["src/"] - needs refinement
---
## Feasibility Concerns
| Concern | Tasks Affected | Issue | Recommendation |
|---------|----------------|-------|----------------|
| Skill Gap | IMPL-6.1, IMPL-6.2 | Requires Kubernetes expertise not in team | Add training task or external consultant |
| Resource Conflict | IMPL-3.1, IMPL-3.2 | Both modify src/auth/service.ts in parallel | Add dependency or serialize |
---
## Detailed Findings by Severity
### CRITICAL Issues ({count})
{Detailed breakdown of each critical issue with location, impact, and recommendation}
### HIGH Issues ({count})
{Detailed breakdown of each high issue with location, impact, and recommendation}
### MEDIUM Issues ({count})
{Detailed breakdown of each medium issue with location, impact, and recommendation}
### LOW Issues ({count})
{Detailed breakdown of each low issue with location, impact, and recommendation}
---
## Metrics Summary
| Metric | Value |
|--------|-------|
| Total Requirements | {count} ({functional} functional, {nonfunctional} non-functional, {business} business) |
| Total Tasks | {count} |
| Overall Coverage | {percent}% ({covered}/{total} requirements with ≥1 task) |
| Critical Issues | {count} |
| High Issues | {count} |
| Medium Issues | {count} |
| Low Issues | {count} |
| Total Findings | {total_findings} |
---
## Remediation Recommendations
### Priority Order
1. **CRITICAL** - Must fix before proceeding
2. **HIGH** - Fix before execution
3. **MEDIUM** - Fix during or after implementation
4. **LOW** - Optional improvements
### Next Steps
Based on the quality gate recommendation ({RECOMMENDATION}):
{IF BLOCK_EXECUTION}
**🛑 BLOCK EXECUTION**
You must resolve all CRITICAL issues before proceeding with implementation:
1. Review each critical issue in detail
2. Determine remediation approach (modify IMPL_PLAN.md, update task.json, or add new tasks)
3. Apply fixes systematically
4. Re-run verification to confirm resolution
{ELSE IF PROCEED_WITH_FIXES}
**⚠️ PROCEED WITH FIXES RECOMMENDED**
No critical issues detected, but HIGH issues exist. Recommended workflow:
1. Review high-priority issues
2. Apply fixes before execution for optimal results
3. Re-run verification (optional)
{ELSE IF PROCEED_WITH_CAUTION}
**✅ PROCEED WITH CAUTION**
Only MEDIUM issues detected. You may proceed with implementation:
- Address medium issues during or after implementation
- Maintain awareness of identified concerns
{ELSE}
**✅ PROCEED**
No significant issues detected. Safe to execute implementation workflow.
{END IF}
---
**Report End**
```
### 7. Save and Display Report
**Step 7.1: Save Report**:
```bash
report_path = ".workflow/active/WFS-{session}/.process/PLAN_VERIFICATION.md"
Write(report_path, full_report_content)
```
**Step 7.2: Display Summary to User**:
```bash
# Display executive summary in terminal
echo "=== Plan Verification Complete ==="
echo "Report saved to: {report_path}"
echo ""
echo "Quality Gate: {RECOMMENDATION}"
echo "Critical: {count} | High: {count} | Medium: {count} | Low: {count}"
echo ""
echo "Next: Review full report for detailed findings and recommendations"
```
**Step 7.3: Completion**:
- Report is saved to `.process/PLAN_VERIFICATION.md`
- User can review findings and decide on remediation approach
- No automatic modifications are made to source artifacts
- User can manually apply fixes or use separate remediation command (if available)

View File

@@ -1,10 +1,14 @@
---
name: plan
description: 5-phase planning workflow with action-planning-agent task generation, outputs IMPL_PLAN.md and task JSONs
argument-hint: "\"text description\"|file.md"
argument-hint: "[-y|--yes] \"text description\"|file.md"
allowed-tools: SlashCommand(*), TodoWrite(*), Read(*), Bash(*)
---
## Auto Mode
When `--yes` or `-y`: Auto-continue all phases (skip confirmations), use recommended conflict resolutions.
# Workflow Plan Command (/workflow:plan)
## Coordinator Role
@@ -318,11 +322,11 @@ Tasks generated: [count]
Plan: .workflow/active/[sessionId]/IMPL_PLAN.md
Recommended Next Steps:
1. /workflow:action-plan-verify --session [sessionId] # Verify plan quality before execution
1. /workflow:plan-verify --session [sessionId] # Verify plan quality before execution
2. /workflow:status # Review task breakdown
3. /workflow:execute # Start implementation (after verification)
Quality Gate: Consider running /workflow:action-plan-verify to catch issues early
Quality Gate: Consider running /workflow:plan-verify to catch issues early
```
## TodoWrite Pattern
@@ -546,6 +550,6 @@ CONSTRAINTS: [Limitations or boundaries]
- `/workflow:tools:task-generate-agent` - Phase 4: Generate task JSON files with agent-driven approach
**Follow-up Commands**:
- `/workflow:action-plan-verify` - Recommended: Verify plan quality and catch issues before execution
- `/workflow:plan-verify` - Recommended: Verify plan quality and catch issues before execution
- `/workflow:status` - Review task breakdown and current progress
- `/workflow:execute` - Begin implementation of generated tasks

View File

@@ -1,7 +1,7 @@
---
name: replan
description: Interactive workflow replanning with session-level artifact updates and boundary clarification through guided questioning
argument-hint: "[--session session-id] [task-id] \"requirements\"|file.md [--interactive]"
argument-hint: "[-y|--yes] [--session session-id] [task-id] \"requirements\"|file.md [--interactive]"
allowed-tools: Read(*), Write(*), Edit(*), TodoWrite(*), Glob(*), Bash(*)
---
@@ -117,10 +117,48 @@ const taskId = taskIdMatch?.[1]
---
### Auto Mode Support
When `--yes` or `-y` flag is used, the command skips interactive clarification and uses safe defaults:
```javascript
const autoYes = $ARGUMENTS.includes('--yes') || $ARGUMENTS.includes('-y')
```
**Auto Mode Defaults**:
- **Modification Scope**: `tasks_only` (safest - only update task details)
- **Affected Modules**: All modules related to the task
- **Task Changes**: `update_only` (no structural changes)
- **Dependency Changes**: `no` (preserve existing dependencies)
- **User Confirmation**: Auto-confirm execution
**Note**: `--interactive` flag overrides `--yes` flag (forces interactive mode).
---
### Phase 2: Interactive Requirement Clarification
**Purpose**: Define modification scope through guided questioning
**Auto Mode Check**:
```javascript
if (autoYes && !interactive) {
// Use defaults and skip to Phase 3
console.log(`[--yes] Using safe defaults for replan:`)
console.log(` - Scope: tasks_only`)
console.log(` - Changes: update_only`)
console.log(` - Dependencies: preserve existing`)
userSelections = {
scope: 'tasks_only',
modules: 'all_affected',
task_changes: 'update_only',
dependency_changes: false
}
// Proceed to Phase 3
}
```
#### Session Mode Questions
**Q1: Modification Scope**
@@ -228,10 +266,29 @@ interface ImpactAnalysis {
**Step 3.3: User Confirmation**
```javascript
Options:
- 确认执行: 开始应用所有修改
- 调整计划: 重新回答问题调整范围
- 取消操作: 放弃本次重规划
// Parse --yes flag
const autoYes = $ARGUMENTS.includes('--yes') || $ARGUMENTS.includes('-y')
if (autoYes) {
// Auto mode: Auto-confirm execution
console.log(`[--yes] Auto-confirming replan execution`)
userConfirmation = '确认执行'
// Proceed to Phase 4
} else {
// Interactive mode: Ask user
AskUserQuestion({
questions: [{
question: "修改计划已生成,请确认操作:",
header: "Confirm",
options: [
{ label: "确认执行", description: "开始应用所有修改" },
{ label: "调整计划", description: "重新回答问题调整范围" },
{ label: "取消操作", description: "放弃本次重规划" }
],
multiSelect: false
}]
})
}
```
**Output**: Modification plan confirmed or adjusted

View File

@@ -605,6 +605,4 @@ Use `ccw view` to open the workflow dashboard in browser:
```bash
ccw view
```
```

View File

@@ -1,8 +1,10 @@
---
name: complete
description: Mark active workflow session as complete, archive with lessons learned, update manifest, remove active flag
argument-hint: "[-y|--yes] [--detailed]"
examples:
- /workflow:session:complete
- /workflow:session:complete --yes
- /workflow:session:complete --detailed
---
@@ -139,20 +141,41 @@ test -f .workflow/project-tech.json || echo "SKIP"
After successful archival, prompt user to capture learnings:
```javascript
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
}]
})
// 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.
}
```
**If "Yes, solidify now"**: Execute `/workflow:session:solidify` with the archived session ID.
## 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**:
```

View File

@@ -1,14 +1,18 @@
---
name: solidify
description: Crystallize session learnings and user-defined constraints into permanent project guidelines
argument-hint: "[--type <convention|constraint|learning>] [--category <category>] \"rule or insight\""
argument-hint: "[-y|--yes] [--type <convention|constraint|learning>] [--category <category>] \"rule or insight\""
examples:
- /workflow:session:solidify "Use functional components for all React code" --type convention
- /workflow:session:solidify "No direct DB access from controllers" --type constraint --category architecture
- /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
---
## Auto Mode
When `--yes` or `-y`: Auto-categorize and add guideline without confirmation.
# Session Solidify Command (/workflow:session:solidify)
## Overview

View File

@@ -268,15 +268,19 @@ SlashCommand(command="/workflow:tools:conflict-resolution --session [sessionId]
### Phase 5: TDD Task Generation
**Step 5.1: Execute** - TDD task generation via action-planning-agent
**Step 5.1: Execute** - TDD task generation via action-planning-agent with Phase 0 user configuration
```javascript
SlashCommand(command="/workflow:tools:task-generate-tdd --session [sessionId]")
```
**Note**: CLI tool usage is determined semantically from user's task description.
**Note**: Phase 0 now includes:
- Supplementary materials collection (file paths or inline content)
- Execution method preference (Agent/Hybrid/CLI)
- CLI tool preference (Codex/Gemini/Qwen/Auto)
- These preferences are passed to agent for task generation
**Parse**: Extract feature count, task count (not chain count - tasks now contain internal TDD cycles)
**Parse**: Extract feature count, task count (not chain count - tasks now contain internal TDD cycles), CLI execution IDs assigned
**Validate**:
- IMPL_PLAN.md exists (unified plan with TDD Implementation Tasks section)
@@ -284,15 +288,24 @@ SlashCommand(command="/workflow:tools:task-generate-tdd --session [sessionId]")
- TODO_LIST.md exists with internal TDD phase indicators
- Each IMPL task includes:
- `meta.tdd_workflow: true`
- `flow_control.implementation_approach` with 3 steps (red/green/refactor)
- `meta.cli_execution_id: {session_id}-{task_id}`
- `meta.cli_execution: { "strategy": "new|resume|fork|merge_fork", ... }`
- `flow_control.implementation_approach` with exactly 3 steps (red/green/refactor)
- Green phase includes test-fix-cycle configuration
- `context.focus_paths`: absolute or clear relative paths (enhanced with exploration critical_files)
- `flow_control.pre_analysis`: includes exploration integration_points analysis
- IMPL_PLAN.md contains workflow_type: "tdd" in frontmatter
- Task count ≤10 (compliance with task limit)
- User configuration applied:
- If executionMethod == "cli" or "hybrid": command field added to steps
- CLI tool preference reflected in execution guidance
- Task count ≤18 (compliance with hard limit)
**Red Flag Detection** (Non-Blocking Warnings):
- Task count >10: `⚠️ High task count may indicate insufficient decomposition`
- Task count >18: `⚠️ Task count exceeds hard limit - request re-scope`
- Missing cli_execution_id: `⚠️ Task lacks CLI execution ID for resume support`
- Missing test-fix-cycle: `⚠️ Green phase lacks auto-revert configuration`
- Generic task names: `⚠️ Vague task names suggest unclear TDD cycles`
- Missing focus_paths: `⚠️ Task lacks clear file scope for implementation`
**Action**: Log warnings to `.workflow/active/[sessionId]/.process/tdd-warnings.log` (non-blocking)
@@ -338,14 +351,22 @@ SlashCommand(command="/workflow:tools:task-generate-tdd --session [sessionId]")
1. Each task contains complete TDD workflow (Red-Green-Refactor internally)
2. Task structure validation:
- `meta.tdd_workflow: true` in all IMPL tasks
- `meta.cli_execution_id` present (format: {session_id}-{task_id})
- `meta.cli_execution` strategy assigned (new/resume/fork/merge_fork)
- `flow_control.implementation_approach` has exactly 3 steps
- Each step has correct `tdd_phase`: "red", "green", "refactor"
- `context.focus_paths` are absolute or clear relative paths
- `flow_control.pre_analysis` includes exploration integration analysis
3. Dependency validation:
- Sequential features: IMPL-N depends_on ["IMPL-(N-1)"] if needed
- Complex features: IMPL-N.M depends_on ["IMPL-N.(M-1)"] for subtasks
- CLI execution strategies correctly assigned based on dependency graph
4. Agent assignment: All IMPL tasks use @code-developer
5. Test-fix cycle: Green phase step includes test-fix-cycle logic with max_iterations
6. Task count: Total tasks ≤10 (simple + subtasks)
6. Task count: Total tasks ≤18 (simple + subtasks hard limit)
7. User configuration:
- Execution method choice reflected in task structure
- CLI tool preference documented in implementation guidance (if CLI selected)
**Red Flag Checklist** (from TDD best practices):
- [ ] No tasks skip Red phase (`tdd_phase: "red"` exists in step 1)
@@ -371,7 +392,7 @@ ls -la .workflow/active/[sessionId]/.task/IMPL-*.json
echo "IMPL tasks: $(ls .workflow/active/[sessionId]/.task/IMPL-*.json 2>/dev/null | wc -l)"
# Sample task structure verification (first task)
jq '{id, tdd: .meta.tdd_workflow, phases: [.flow_control.implementation_approach[].tdd_phase]}' \
jq '{id, tdd: .meta.tdd_workflow, cli_id: .meta.cli_execution_id, phases: [.flow_control.implementation_approach[].tdd_phase]}' \
"$(ls .workflow/active/[sessionId]/.task/IMPL-*.json | head -1)"
```
@@ -379,8 +400,9 @@ jq '{id, tdd: .meta.tdd_workflow, phases: [.flow_control.implementation_approach
| Evidence Type | Verification Method | Pass Criteria |
|---------------|---------------------|---------------|
| File existence | `ls -la` artifacts | All files present |
| Task count | Count IMPL-*.json | Count matches claims |
| TDD structure | jq sample extraction | Shows red/green/refactor |
| Task count | Count IMPL-*.json | Count matches claims (≤18) |
| TDD structure | jq sample extraction | Shows red/green/refactor + cli_execution_id |
| CLI execution IDs | jq extraction | All tasks have cli_execution_id assigned |
| Warning log | Check tdd-warnings.log | Logged (may be empty) |
**Return Summary**:
@@ -393,7 +415,7 @@ Total tasks: [M] (1 task per simple feature + subtasks for complex features)
Task breakdown:
- Simple features: [K] tasks (IMPL-1 to IMPL-K)
- Complex features: [L] features with [P] subtasks
- Total task count: [M] (within 10-task limit)
- Total task count: [M] (within 18-task hard limit)
Structure:
- IMPL-1: {Feature 1 Name} (Internal: Red → Green → Refactor)
@@ -407,22 +429,31 @@ Plans generated:
- Unified Implementation Plan: .workflow/active/[sessionId]/IMPL_PLAN.md
(includes TDD Implementation Tasks section with workflow_type: "tdd")
- Task List: .workflow/active/[sessionId]/TODO_LIST.md
(with internal TDD phase indicators)
(with internal TDD phase indicators and CLI execution strategies)
- Task JSONs: .workflow/active/[sessionId]/.task/IMPL-*.json
(with cli_execution_id and execution strategies for resume support)
TDD Configuration:
- Each task contains complete Red-Green-Refactor cycle
- Green phase includes test-fix cycle (max 3 iterations)
- Auto-revert on max iterations reached
- CLI execution strategies: new/resume/fork/merge_fork based on dependency graph
User Configuration Applied:
- Execution Method: [agent|hybrid|cli]
- CLI Tool Preference: [codex|gemini|qwen|auto]
- Supplementary Materials: [included|none]
- Task generation follows cli-tools-usage.md guidelines
⚠️ ACTION REQUIRED: Before execution, ensure you understand WHY each Red phase test is expected to fail.
This is crucial for valid TDD - if you don't know why the test fails, you can't verify it tests the right thing.
Recommended Next Steps:
1. /workflow:action-plan-verify --session [sessionId] # Verify TDD plan quality and dependencies
2. /workflow:execute --session [sessionId] # Start TDD execution
1. /workflow:plan-verify --session [sessionId] # Verify TDD plan quality and dependencies
2. /workflow:execute --session [sessionId] # Start TDD execution with CLI strategies
3. /workflow:tdd-verify [sessionId] # Post-execution TDD compliance check
Quality Gate: Consider running /workflow:action-plan-verify to validate TDD task structure and dependencies
Quality Gate: Consider running /workflow:plan-verify to validate TDD task structure, dependencies, and CLI execution strategies
```
## TodoWrite Pattern
@@ -500,7 +531,7 @@ TDD Workflow Orchestrator
└─ Phase 6: TDD Structure Validation
└─ Internal validation + summary returned
└─ Recommend: /workflow:action-plan-verify
└─ Recommend: /workflow:plan-verify
Key Points:
• ← ATTACHED: SlashCommand attaches sub-tasks to orchestrator TodoWrite
@@ -547,9 +578,11 @@ Convert user input to TDD-structured format:
| Parsing failure | Empty/malformed output | Retry once, then report |
| Missing context-package | File read error | Re-run `/workflow:tools:context-gather` |
| Invalid task JSON | jq parse error | Report malformed file path |
| High task count (>10) | Count validation | Log warning, continue (non-blocking) |
| Task count exceeds 18 | Count validation ≥19 | Request re-scope, split into multiple sessions |
| Missing cli_execution_id | All tasks lack ID | Regenerate tasks with phase 0 user config |
| Test-context missing | File not found | Re-run `/workflow:tools:test-context-gather` |
| Phase timeout | No response | Retry phase, check CLI connectivity |
| CLI tool not available | Tool not in cli-tools.json | Fall back to alternative preferred tool |
## Related Commands
@@ -565,7 +598,7 @@ Convert user input to TDD-structured format:
- `/workflow:tools:task-generate-tdd` - Phase 5: Generate TDD tasks (CLI tool usage determined semantically)
**Follow-up Commands**:
- `/workflow:action-plan-verify` - Recommended: Verify TDD plan quality and structure before execution
- `/workflow:plan-verify` - Recommended: Verify TDD plan quality and structure before execution
- `/workflow:status` - Review TDD task breakdown
- `/workflow:execute` - Begin TDD implementation
- `/workflow:tdd-verify` - Post-execution: Verify TDD compliance and generate quality report
@@ -574,7 +607,7 @@ Convert user input to TDD-structured format:
| Situation | Recommended Command | Purpose |
|-----------|---------------------|---------|
| First time planning | `/workflow:action-plan-verify` | Validate task structure before execution |
| First time planning | `/workflow:plan-verify` | Validate task structure before execution |
| Warnings in tdd-warnings.log | Review log, refine tasks | Address Red Flags before proceeding |
| High task count warning | Consider `/workflow:session:start` | Split into focused sub-sessions |
| Ready to implement | `/workflow:execute` | Begin TDD Red-Green-Refactor cycles |
@@ -587,7 +620,7 @@ Convert user input to TDD-structured format:
```
/workflow:tdd-plan
[Planning Complete] ──→ /workflow:action-plan-verify (recommended)
[Planning Complete] ──→ /workflow:plan-verify (recommended)
[Verified/Ready] ─────→ /workflow:execute

View File

@@ -1,214 +1,301 @@
---
name: tdd-verify
description: Verify TDD workflow compliance against Red-Green-Refactor cycles, generate quality report with coverage analysis
argument-hint: "[optional: WFS-session-id]"
allowed-tools: SlashCommand(*), TodoWrite(*), Read(*), Bash(gemini:*)
description: Verify TDD workflow compliance against Red-Green-Refactor cycles. Generates quality report with coverage analysis and quality gate recommendation. Orchestrates sub-commands for comprehensive validation.
argument-hint: "[optional: --session WFS-session-id]"
allowed-tools: SlashCommand(*), TodoWrite(*), Read(*), Write(*), Bash(*), Glob(*)
---
# TDD Verification Command (/workflow:tdd-verify)
## Goal
Verify TDD workflow execution quality by validating Red-Green-Refactor cycle compliance, test coverage completeness, and task chain structure integrity. This command orchestrates multiple analysis phases and generates a comprehensive compliance report with quality gate recommendation.
**Output**: A structured Markdown report saved to `.workflow/active/WFS-{session}/TDD_COMPLIANCE_REPORT.md` containing:
- Executive summary with compliance score and quality gate recommendation
- Task chain validation (TEST → IMPL → REFACTOR structure)
- Test coverage metrics (line, branch, function)
- Red-Green-Refactor cycle verification
- Best practices adherence assessment
- Actionable improvement recommendations
## Operating Constraints
**ORCHESTRATOR MODE**:
- This command coordinates multiple sub-commands (`/workflow:tools:tdd-coverage-analysis`, `ccw cli`)
- MAY write output files: TDD_COMPLIANCE_REPORT.md (primary report), .process/*.json (intermediate artifacts)
- MUST NOT modify source task files or implementation code
- MUST NOT create or delete tasks in the workflow
**Quality Gate Authority**: The compliance report provides a binding recommendation (BLOCK_MERGE / REQUIRE_FIXES / PROCEED_WITH_CAVEATS / APPROVED) based on objective compliance criteria.
## Coordinator Role
**This command is a pure orchestrator**: Execute 4 phases to verify TDD workflow compliance, test coverage, and Red-Green-Refactor cycle execution.
## Core Responsibilities
- Verify TDD task chain structure
- Analyze test coverage
- Validate TDD cycle execution
- Generate compliance report
- Verify TDD task chain structure (TEST → IMPL → REFACTOR)
- Analyze test coverage metrics
- Validate TDD cycle execution quality
- Generate compliance report with quality gate recommendation
## Execution Process
```
Input Parsing:
└─ Decision (session argument):
├─ session-id provided → Use provided session
└─ No session-id → Auto-detect active session
├─ --session provided → Use provided session
└─ No session → Auto-detect active session
Phase 1: Session Discovery
├─ Validate session directory exists
TodoWrite: Mark phase 1 completed
Phase 1: Session Discovery & Validation
├─ Detect or validate session directory
Check required artifacts exist (.task/*.json, .summaries/*)
└─ ERROR if invalid or incomplete
Phase 2: Task Chain Validation
Phase 2: Task Chain Structure Validation
├─ Load all task JSONs from .task/
├─ Extract task IDs and group by feature
├─ Validate TDD structure:
│ ├─ TEST-N.M → IMPL-N.M → REFACTOR-N.M chain
│ ├─ Dependency verification
│ └─ Meta field validation (tdd_phase, agent)
└─ TodoWrite: Mark phase 2 completed
├─ Validate TDD structure: TEST-N.M → IMPL-N.M → REFACTOR-N.M
├─ Verify dependencies (depends_on)
├─ Validate meta fields (tdd_phase, agent)
└─ Extract chain validation data
Phase 3: Test Execution Analysis
└─ /workflow:tools:tdd-coverage-analysis
├─ Coverage metrics extraction
├─ TDD cycle verification
└─ Compliance score calculation
Phase 3: Coverage & Cycle Analysis
├─ Call: /workflow:tools:tdd-coverage-analysis
├─ Parse: test-results.json, coverage-report.json, tdd-cycle-report.md
└─ Extract coverage metrics and TDD cycle verification
Phase 4: Compliance Report Generation
├─ Gemini analysis for comprehensive report
├─ Aggregate findings from Phases 1-3
├─ Calculate compliance score (0-100)
├─ Determine quality gate recommendation
├─ Generate TDD_COMPLIANCE_REPORT.md
└─ Return summary to user
└─ Display summary to user
```
## 4-Phase Execution
### Phase 1: Session Discovery
**Auto-detect or use provided session**
### Phase 1: Session Discovery & Validation
**Step 1.1: Detect Session**
```bash
# If session-id provided
sessionId = argument
IF --session parameter provided:
session_id = provided session
ELSE:
# Auto-detect active session
active_sessions = bash(find .workflow/active/ -name "WFS-*" -type d 2>/dev/null)
IF active_sessions is empty:
ERROR: "No active workflow session found. Use --session <session-id>"
EXIT
ELSE IF active_sessions has multiple entries:
# Use most recently modified session
session_id = bash(ls -td .workflow/active/WFS-*/ 2>/dev/null | head -1 | xargs basename)
ELSE:
session_id = basename(active_sessions[0])
# Else auto-detect active session
find .workflow/active/ -name "WFS-*" -type d | head -1 | sed 's/.*\///'
# Derive paths
session_dir = .workflow/active/WFS-{session_id}
task_dir = session_dir/.task
summaries_dir = session_dir/.summaries
process_dir = session_dir/.process
```
**Extract**: sessionId
**Step 1.2: Validate Required Artifacts**
```bash
# Check task files exist
task_files = Glob(task_dir/*.json)
IF task_files.count == 0:
ERROR: "No task JSON files found. Run /workflow:tdd-plan first"
EXIT
**Validation**: Session directory exists
# Check summaries exist (optional but recommended for full analysis)
summaries_exist = EXISTS(summaries_dir)
IF NOT summaries_exist:
WARNING: "No .summaries/ directory found. Some analysis may be limited."
```
**TodoWrite**: Mark phase 1 completed, phase 2 in_progress
**Output**: session_id, session_dir, task_files list
---
### Phase 2: Task Chain Validation
**Validate TDD structure using bash commands**
### Phase 2: Task Chain Structure Validation
**Step 2.1: Load and Parse Task JSONs**
```bash
# Load all task JSONs
for task_file in .workflow/active/{sessionId}/.task/*.json; do
cat "$task_file"
done
# Single-pass JSON extraction using jq
validation_data = bash("""
# Load all tasks and extract structured data
cd '{session_dir}/.task'
# Extract task IDs
for task_file in .workflow/active/{sessionId}/.task/*.json; do
cat "$task_file" | jq -r '.id'
done
# Extract all task IDs
task_ids=$(jq -r '.id' *.json 2>/dev/null | sort)
# Check dependencies - read tasks and filter for IMPL/REFACTOR
for task_file in .workflow/active/{sessionId}/.task/IMPL-*.json; do
cat "$task_file" | jq -r '.context.depends_on[]?'
done
# Extract dependencies for IMPL tasks
impl_deps=$(jq -r 'select(.id | startswith("IMPL")) | .id + ":" + (.context.depends_on[]? // "none")' *.json 2>/dev/null)
for task_file in .workflow/active/{sessionId}/.task/REFACTOR-*.json; do
cat "$task_file" | jq -r '.context.depends_on[]?'
done
# Extract dependencies for REFACTOR tasks
refactor_deps=$(jq -r 'select(.id | startswith("REFACTOR")) | .id + ":" + (.context.depends_on[]? // "none")' *.json 2>/dev/null)
# Check meta fields
for task_file in .workflow/active/{sessionId}/.task/*.json; do
cat "$task_file" | jq -r '.meta.tdd_phase'
done
# Extract meta fields
meta_tdd=$(jq -r '.id + ":" + (.meta.tdd_phase // "missing")' *.json 2>/dev/null)
meta_agent=$(jq -r '.id + ":" + (.meta.agent // "missing")' *.json 2>/dev/null)
for task_file in .workflow/active/{sessionId}/.task/*.json; do
cat "$task_file" | jq -r '.meta.agent'
done
# Output as JSON
jq -n --arg ids "$task_ids" \\
--arg impl "$impl_deps" \\
--arg refactor "$refactor_deps" \\
--arg tdd "$meta_tdd" \\
--arg agent "$meta_agent" \\
'{ids: $ids, impl_deps: $impl, refactor_deps: $refactor, tdd: $tdd, agent: $agent}'
""")
```
**Validation**:
- For each feature N, verify TEST-N.M → IMPL-N.M → REFACTOR-N.M exists
- IMPL-N.M.context.depends_on includes TEST-N.M
- REFACTOR-N.M.context.depends_on includes IMPL-N.M
- TEST tasks have tdd_phase="red" and agent="@code-review-test-agent"
- IMPL/REFACTOR tasks have tdd_phase="green"/"refactor" and agent="@code-developer"
**Step 2.2: Validate TDD Chain Structure**
```
Parse validation_data JSON and validate:
**Extract**: Chain validation report
For each feature N (extracted from task IDs):
1. TEST-N.M exists?
2. IMPL-N.M exists?
3. REFACTOR-N.M exists? (optional but recommended)
4. IMPL-N.M.context.depends_on contains TEST-N.M?
5. REFACTOR-N.M.context.depends_on contains IMPL-N.M?
6. TEST-N.M.meta.tdd_phase == "red"?
7. TEST-N.M.meta.agent == "@code-review-test-agent"?
8. IMPL-N.M.meta.tdd_phase == "green"?
9. IMPL-N.M.meta.agent == "@code-developer"?
10. REFACTOR-N.M.meta.tdd_phase == "refactor"?
**TodoWrite**: Mark phase 2 completed, phase 3 in_progress
Calculate:
- chain_completeness_score = (complete_chains / total_chains) * 100
- dependency_accuracy = (correct_deps / total_deps) * 100
- meta_field_accuracy = (correct_meta / total_meta) * 100
```
**Output**: chain_validation_report (JSON structure with validation results)
---
### Phase 3: Test Execution Analysis
**Command**: `SlashCommand(command="/workflow:tools:tdd-coverage-analysis --session [sessionId]")`
### Phase 3: Coverage & Cycle Analysis
**Input**: sessionId from Phase 1
**Step 3.1: Call Coverage Analysis Sub-command**
```bash
SlashCommand(command="/workflow:tools:tdd-coverage-analysis --session {session_id}")
```
**Parse Output**:
- Coverage metrics (line, branch, function percentages)
- TDD cycle verification results
- Compliance score
**Step 3.2: Parse Output Files**
```bash
# Check required outputs exist
IF NOT EXISTS(process_dir/test-results.json):
WARNING: "test-results.json not found. Coverage analysis incomplete."
coverage_data = null
ELSE:
coverage_data = Read(process_dir/test-results.json)
**Validation**:
- `.workflow/active/{sessionId}/.process/test-results.json` exists
- `.workflow/active/{sessionId}/.process/coverage-report.json` exists
- `.workflow/active/{sessionId}/.process/tdd-cycle-report.md` exists
IF NOT EXISTS(process_dir/coverage-report.json):
WARNING: "coverage-report.json not found. Coverage metrics incomplete."
metrics = null
ELSE:
metrics = Read(process_dir/coverage-report.json)
**TodoWrite**: Mark phase 3 completed, phase 4 in_progress
IF NOT EXISTS(process_dir/tdd-cycle-report.md):
WARNING: "tdd-cycle-report.md not found. Cycle validation incomplete."
cycle_data = null
ELSE:
cycle_data = Read(process_dir/tdd-cycle-report.md)
```
**Step 3.3: Extract Coverage Metrics**
```
If coverage_data exists:
- line_coverage_percent
- branch_coverage_percent
- function_coverage_percent
- uncovered_files (list)
- uncovered_lines (map: file -> line ranges)
If cycle_data exists:
- red_phase_compliance (tests failed initially?)
- green_phase_compliance (tests pass after impl?)
- refactor_phase_compliance (tests stay green during refactor?)
- minimal_implementation_score (was impl minimal?)
```
**Output**: coverage_analysis, cycle_analysis
---
### Phase 4: Compliance Report Generation
**Gemini analysis for comprehensive TDD compliance report**
**Step 4.1: Calculate Compliance Score**
```
Base Score: 100 points
Deductions:
Chain Structure:
- Missing TEST task: -30 points per feature
- Missing IMPL task: -30 points per feature
- Missing REFACTOR task: -10 points per feature
- Wrong dependency: -15 points per error
- Wrong agent: -5 points per error
- Wrong tdd_phase: -5 points per error
TDD Cycle Compliance:
- Test didn't fail initially: -10 points per feature
- Tests didn't pass after IMPL: -20 points per feature
- Tests broke during REFACTOR: -15 points per feature
- Over-engineered IMPL: -10 points per feature
Coverage Quality:
- Line coverage < 80%: -5 points
- Branch coverage < 70%: -5 points
- Function coverage < 80%: -5 points
- Critical paths uncovered: -10 points
Final Score: Max(0, Base Score - Total Deductions)
```
**Step 4.2: Determine Quality Gate**
```
IF score >= 90 AND no_critical_violations:
recommendation = "APPROVED"
ELSE IF score >= 70 AND critical_violations == 0:
recommendation = "PROCEED_WITH_CAVEATS"
ELSE IF score >= 50:
recommendation = "REQUIRE_FIXES"
ELSE:
recommendation = "BLOCK_MERGE"
```
**Step 4.3: Generate Report**
```bash
ccw cli -p "
PURPOSE: Generate TDD compliance report
TASK: Analyze TDD workflow execution and generate quality report
CONTEXT: @{.workflow/active/{sessionId}/.task/*.json,.workflow/active/{sessionId}/.summaries/*,.workflow/active/{sessionId}/.process/tdd-cycle-report.md}
EXPECTED:
- TDD compliance score (0-100)
- Chain completeness verification
- Test coverage analysis summary
- Quality recommendations
- Red-Green-Refactor cycle validation
- Best practices adherence assessment
RULES: Focus on TDD best practices and workflow adherence. Be specific about violations and improvements.
" --tool gemini --mode analysis --cd project-root > .workflow/active/{sessionId}/TDD_COMPLIANCE_REPORT.md
report_content = Generate markdown report (see structure below)
report_path = "{session_dir}/TDD_COMPLIANCE_REPORT.md"
Write(report_path, report_content)
```
**Output**: TDD_COMPLIANCE_REPORT.md
**TodoWrite**: Mark phase 4 completed
**Return to User**:
```
TDD Verification Report - Session: {sessionId}
## Chain Validation
[COMPLETE] Feature 1: TEST-1.1 → IMPL-1.1 → REFACTOR-1.1 (Complete)
[COMPLETE] Feature 2: TEST-2.1 → IMPL-2.1 → REFACTOR-2.1 (Complete)
[INCOMPLETE] Feature 3: TEST-3.1 → IMPL-3.1 (Missing REFACTOR phase)
## Test Execution
All TEST tasks produced failing tests
All IMPL tasks made tests pass
All REFACTOR tasks maintained green tests
## Coverage Metrics
Line Coverage: {percentage}%
Branch Coverage: {percentage}%
Function Coverage: {percentage}%
## Compliance Score: {score}/100
Detailed report: .workflow/active/{sessionId}/TDD_COMPLIANCE_REPORT.md
Recommendations:
- Complete missing REFACTOR-3.1 task
- Consider additional edge case tests for Feature 2
- Improve test failure message clarity in Feature 1
**Step 4.4: Display Summary to User**
```bash
echo "=== TDD Verification Complete ==="
echo "Session: {session_id}"
echo "Report: {report_path}"
echo ""
echo "Quality Gate: {recommendation}"
echo "Compliance Score: {score}/100"
echo ""
echo "Chain Validation: {chain_completeness_score}%"
echo "Line Coverage: {line_coverage}%"
echo "Branch Coverage: {branch_coverage}%"
echo ""
echo "Next: Review full report for detailed findings"
```
## TodoWrite Pattern
## TodoWrite Pattern (Optional)
**Note**: As an orchestrator command, TodoWrite tracking is optional and primarily useful for long-running verification processes. For most cases, the 4-phase execution is fast enough that progress tracking adds noise without value.
```javascript
// Initialize (before Phase 1)
TodoWrite({todos: [
{"content": "Identify target session", "status": "in_progress", "activeForm": "Identifying target session"},
{"content": "Validate task chain structure", "status": "pending", "activeForm": "Validating task chain structure"},
{"content": "Analyze test execution", "status": "pending", "activeForm": "Analyzing test execution"},
{"content": "Generate compliance report", "status": "pending", "activeForm": "Generating compliance report"}
]})
// After Phase 1
TodoWrite({todos: [
{"content": "Identify target session", "status": "completed", "activeForm": "Identifying target session"},
{"content": "Validate task chain structure", "status": "in_progress", "activeForm": "Validating task chain structure"},
{"content": "Analyze test execution", "status": "pending", "activeForm": "Analyzing test execution"},
{"content": "Generate compliance report", "status": "pending", "activeForm": "Generating compliance report"}
]})
// Continue pattern for Phase 2, 3, 4...
// Only use TodoWrite for complex multi-session verification
// Skip for single-session verification
```
## Validation Logic
@@ -229,27 +316,24 @@ TodoWrite({todos: [
5. Report incomplete or invalid chains
```
### Compliance Scoring
```
Base Score: 100 points
### Quality Gate Criteria
Deductions:
- Missing TEST task: -30 points per feature
- Missing IMPL task: -30 points per feature
- Missing REFACTOR task: -10 points per feature
- Wrong dependency: -15 points per error
- Wrong agent: -5 points per error
- Wrong tdd_phase: -5 points per error
- Test didn't fail initially: -10 points per feature
- Tests didn't pass after IMPL: -20 points per feature
- Tests broke during REFACTOR: -15 points per feature
| Recommendation | Score Range | Critical Violations | Action |
|----------------|-------------|---------------------|--------|
| **APPROVED** | ≥90 | 0 | Safe to merge |
| **PROCEED_WITH_CAVEATS** | ≥70 | 0 | Can proceed, address minor issues |
| **REQUIRE_FIXES** | ≥50 | Any | Must fix before merge |
| **BLOCK_MERGE** | <50 | Any | Block merge until resolved |
Final Score: Max(0, Base Score - Deductions)
```
**Critical Violations**:
- Missing TEST or IMPL task for any feature
- Tests didn't fail initially (Red phase violation)
- Tests didn't pass after IMPL (Green phase violation)
- Tests broke during REFACTOR (Refactor phase violation)
## Output Files
```
.workflow/active/{session-id}/
.workflow/active/WFS-{session-id}/
├── TDD_COMPLIANCE_REPORT.md # Comprehensive compliance report ⭐
└── .process/
├── test-results.json # From tdd-coverage-analysis
@@ -262,14 +346,14 @@ Final Score: Max(0, Base Score - Deductions)
### Session Discovery Errors
| Error | Cause | Resolution |
|-------|-------|------------|
| No active session | No WFS-* directories | Provide session-id explicitly |
| Multiple active sessions | Multiple WFS-* directories | Provide session-id explicitly |
| No active session | No WFS-* directories | Provide --session explicitly |
| Multiple active sessions | Multiple WFS-* directories | Provide --session explicitly |
| Session not found | Invalid session-id | Check available sessions |
### Validation Errors
| Error | Cause | Resolution |
|-------|-------|------------|
| Task files missing | Incomplete planning | Run tdd-plan first |
| Task files missing | Incomplete planning | Run /workflow:tdd-plan first |
| Invalid JSON | Corrupted task files | Regenerate tasks |
| Missing summaries | Tasks not executed | Execute tasks before verify |
@@ -278,13 +362,13 @@ Final Score: Max(0, Base Score - Deductions)
|-------|-------|------------|
| Coverage tool missing | No test framework | Configure testing first |
| Tests fail to run | Code errors | Fix errors before verify |
| Gemini analysis fails | Token limit / API error | Retry or reduce context |
| Sub-command fails | tdd-coverage-analysis error | Check sub-command logs |
## Integration & Usage
### Command Chain
- **Called After**: `/workflow:execute` (when TDD tasks completed)
- **Calls**: `/workflow:tools:tdd-coverage-analysis`, Gemini CLI
- **Calls**: `/workflow:tools:tdd-coverage-analysis`
- **Related**: `/workflow:tdd-plan`, `/workflow:status`
### Basic Usage
@@ -293,7 +377,7 @@ Final Score: Max(0, Base Score - Deductions)
/workflow:tdd-verify
# Specify session
/workflow:tdd-verify WFS-auth
/workflow:tdd-verify --session WFS-auth
```
### When to Use
@@ -308,61 +392,125 @@ Final Score: Max(0, Base Score - Deductions)
# TDD Compliance Report - {Session ID}
**Generated**: {timestamp}
**Session**: {sessionId}
**Session**: WFS-{sessionId}
**Workflow Type**: TDD
---
## Executive Summary
Overall Compliance Score: {score}/100
Status: {EXCELLENT | GOOD | NEEDS IMPROVEMENT | FAILED}
### Quality Gate Decision
| Metric | Value | Status |
|--------|-------|--------|
| Compliance Score | {score}/100 | {status_emoji} |
| Chain Completeness | {percentage}% | {status} |
| Line Coverage | {percentage}% | {status} |
| Branch Coverage | {percentage}% | {status} |
| Function Coverage | {percentage}% | {status} |
### Recommendation
**{RECOMMENDATION}**
**Decision Rationale**:
{brief explanation based on score and violations}
**Quality Gate Criteria**:
- **APPROVED**: Score ≥90, no critical violations
- **PROCEED_WITH_CAVEATS**: Score ≥70, no critical violations
- **REQUIRE_FIXES**: Score ≥50 or critical violations exist
- **BLOCK_MERGE**: Score <50
---
## Chain Analysis
### Feature 1: {Feature Name}
**Status**: Complete
**Status**: Complete
**Chain**: TEST-1.1 → IMPL-1.1 → REFACTOR-1.1
- **Red Phase**: Test created and failed with clear message
- **Green Phase**: Minimal implementation made test pass
- **Refactor Phase**: Code improved, tests remained green
| Phase | Task | Status | Details |
|-------|------|--------|---------|
| Red | TEST-1.1 | ✅ Pass | Test created and failed with clear message |
| Green | IMPL-1.1 | ✅ Pass | Minimal implementation made test pass |
| Refactor | REFACTOR-1.1 | ✅ Pass | Code improved, tests remained green |
### Feature 2: {Feature Name}
**Status**: Incomplete
**Status**: ⚠️ Incomplete
**Chain**: TEST-2.1 → IMPL-2.1 (Missing REFACTOR-2.1)
- **Red Phase**: Test created and failed
- **Green Phase**: Implementation seems over-engineered
- **Refactor Phase**: Missing
| Phase | Task | Status | Details |
|-------|------|--------|---------|
| Red | TEST-2.1 | ✅ Pass | Test created and failed |
| Green | IMPL-2.1 | ⚠️ Warning | Implementation seems over-engineered |
| Refactor | REFACTOR-2.1 | ❌ Missing | Task not completed |
**Issues**:
- REFACTOR-2.1 task not completed
- IMPL-2.1 implementation exceeded minimal scope
- REFACTOR-2.1 task not completed (-10 points)
- IMPL-2.1 implementation exceeded minimal scope (-10 points)
[Repeat for all features]
### Chain Validation Summary
| Metric | Value |
|--------|-------|
| Total Features | {count} |
| Complete Chains | {count} ({percent}%) |
| Incomplete Chains | {count} |
| Missing TEST | {count} |
| Missing IMPL | {count} |
| Missing REFACTOR | {count} |
| Dependency Errors | {count} |
| Meta Field Errors | {count} |
---
## Test Coverage Analysis
### Coverage Metrics
- Line Coverage: {percentage}% {status}
- Branch Coverage: {percentage}% {status}
- Function Coverage: {percentage}% {status}
| Metric | Coverage | Target | Status |
|--------|----------|--------|--------|
| Line Coverage | {percentage}% | ≥80% | {status} |
| Branch Coverage | {percentage}% | ≥70% | {status} |
| Function Coverage | {percentage}% | ≥80% | {status} |
### Coverage Gaps
- {file}:{lines} - Uncovered error handling
- {file}:{lines} - Uncovered edge case
| File | Lines | Issue | Priority |
|------|-------|-------|----------|
| src/auth/service.ts | 45-52 | Uncovered error handling | HIGH |
| src/utils/parser.ts | 78-85 | Uncovered edge case | MEDIUM |
---
## TDD Cycle Validation
### Red Phase (Write Failing Test)
- {N}/{total} features had failing tests initially
- Feature 3: No evidence of initial test failure
- {N}/{total} features had failing tests initially ({percent}%)
- ✅ Compliant features: {list}
- ❌ Non-compliant features: {list}
**Violations**:
- Feature 3: No evidence of initial test failure (-10 points)
### Green Phase (Make Test Pass)
- {N}/{total} implementations made tests pass
- All implementations minimal and focused
- {N}/{total} implementations made tests pass ({percent}%)
- ✅ Compliant features: {list}
- ❌ Non-compliant features: {list}
**Violations**:
- Feature 2: Implementation over-engineered (-10 points)
### Refactor Phase (Improve Quality)
- {N}/{total} features completed refactoring
- Feature 2, 4: Refactoring step skipped
- {N}/{total} features completed refactoring ({percent}%)
- ✅ Compliant features: {list}
- ❌ Non-compliant features: {list}
**Violations**:
- Feature 2, 4: Refactoring step skipped (-20 points total)
---
## Best Practices Assessment
@@ -377,24 +525,61 @@ Status: {EXCELLENT | GOOD | NEEDS IMPROVEMENT | FAILED}
- Missing refactoring steps
- Test failure messages could be more descriptive
---
## Detailed Findings by Severity
### Critical Issues ({count})
{List of critical issues with impact and remediation}
### High Priority Issues ({count})
{List of high priority issues with impact and remediation}
### Medium Priority Issues ({count})
{List of medium priority issues with impact and remediation}
### Low Priority Issues ({count})
{List of low priority issues with impact and remediation}
---
## Recommendations
### High Priority
### Required Fixes (Before Merge)
1. Complete missing REFACTOR tasks (Features 2, 4)
2. Verify initial test failures for Feature 3
3. Simplify over-engineered implementations
3. Fix tests that broke during refactoring
### Medium Priority
1. Add edge case tests for Features 1, 3
2. Improve test failure message clarity
3. Increase branch coverage to >85%
### Recommended Improvements
1. Simplify over-engineered implementations
2. Add edge case tests for Features 1, 3
3. Improve test failure message clarity
4. Increase branch coverage to >85%
### Low Priority
### Optional Enhancements
1. Add more descriptive test names
2. Consider parameterized tests for similar scenarios
3. Document TDD process learnings
## Conclusion
{Summary of compliance status and next steps}
---
## Metrics Summary
| Metric | Value |
|--------|-------|
| Total Features | {count} |
| Complete Chains | {count} ({percent}%) |
| Compliance Score | {score}/100 |
| Critical Issues | {count} |
| High Issues | {count} |
| Medium Issues | {count} |
| Low Issues | {count} |
| Line Coverage | {percent}% |
| Branch Coverage | {percent}% |
| Function Coverage | {percent}% |
---
**Report End**
```

View File

@@ -1,12 +1,16 @@
---
name: conflict-resolution
description: Detect and resolve conflicts between plan and existing codebase using CLI-powered analysis with Gemini/Qwen
argument-hint: "--session WFS-session-id --context path/to/context-package.json"
argument-hint: "[-y|--yes] --session WFS-session-id --context path/to/context-package.json"
examples:
- /workflow:tools:conflict-resolution --session WFS-auth --context .workflow/active/WFS-auth/.process/context-package.json
- /workflow:tools:conflict-resolution --session WFS-payment --context .workflow/active/WFS-payment/.process/context-package.json
- /workflow:tools:conflict-resolution -y --session WFS-payment --context .workflow/active/WFS-payment/.process/context-package.json
---
## Auto Mode
When `--yes` or `-y`: Auto-select recommended strategy for each conflict, skip clarification questions.
# Conflict Resolution Command
## Purpose
@@ -209,6 +213,8 @@ Task(subagent_type="cli-execution-agent", run_in_background=false, prompt=`
### Phase 3: User Interaction Loop
```javascript
const autoYes = $ARGUMENTS.includes('--yes') || $ARGUMENTS.includes('-y')
FOR each conflict:
round = 0, clarified = false, userClarifications = []
@@ -216,8 +222,13 @@ FOR each conflict:
// 1. Display conflict info (text output for context)
displayConflictSummary(conflict) // id, brief, severity, overlap_analysis if ModuleOverlap
// 2. Strategy selection via AskUserQuestion
AskUserQuestion({
// 2. Strategy selection
if (autoYes) {
console.log(`[--yes] Auto-selecting recommended strategy`)
selectedStrategy = conflict.strategies[conflict.recommended || 0]
clarified = true // Skip clarification loop
} else {
AskUserQuestion({
questions: [{
question: formatStrategiesForDisplay(conflict.strategies),
header: "策略选择",
@@ -230,18 +241,19 @@ FOR each conflict:
{ label: "自定义修改", description: `建议: ${conflict.modification_suggestions?.slice(0,2).join('; ')}` }
]
}]
})
})
// 3. Handle selection
if (userChoice === "自定义修改") {
customConflicts.push({ id, brief, category, suggestions, overlap_analysis })
break
// 3. Handle selection
if (userChoice === "自定义修改") {
customConflicts.push({ id, brief, category, suggestions, overlap_analysis })
break
}
selectedStrategy = findStrategyByName(userChoice)
}
selectedStrategy = findStrategyByName(userChoice)
// 4. Clarification (if needed) - batched max 4 per call
if (selectedStrategy.clarification_needed?.length > 0) {
if (!autoYes && selectedStrategy.clarification_needed?.length > 0) {
for (batch of chunk(selectedStrategy.clarification_needed, 4)) {
AskUserQuestion({
questions: batch.map((q, i) => ({

View File

@@ -1,11 +1,16 @@
---
name: task-generate-agent
description: Generate implementation plan documents (IMPL_PLAN.md, task JSONs, TODO_LIST.md) using action-planning-agent - produces planning artifacts, does NOT execute code implementation
argument-hint: "--session WFS-session-id"
argument-hint: "[-y|--yes] --session WFS-session-id"
examples:
- /workflow:tools:task-generate-agent --session WFS-auth
- /workflow:tools:task-generate-agent -y --session WFS-auth
---
## Auto Mode
When `--yes` or `-y`: Skip user questions, use defaults (no materials, Agent executor, Codex CLI tool).
# Generate Implementation Plan Command
## Overview
@@ -67,9 +72,25 @@ Phase 3: Integration (+1 Coordinator, Multi-Module Only)
**Purpose**: Collect user preferences before task generation to ensure generated tasks match execution expectations.
**User Questions**:
**Auto Mode Check**:
```javascript
AskUserQuestion({
const autoYes = $ARGUMENTS.includes('--yes') || $ARGUMENTS.includes('-y')
if (autoYes) {
console.log(`[--yes] Using defaults: No materials, Agent executor, Codex CLI`)
userConfig = {
supplementaryMaterials: { type: "none", content: [] },
executionMethod: "agent",
preferredCliTool: "codex",
enableResume: true
}
// Skip to Phase 1
}
```
**User Questions** (skipped if autoYes):
```javascript
if (!autoYes) AskUserQuestion({
questions: [
{
question: "Do you have supplementary materials or guidelines to include?",
@@ -104,11 +125,10 @@ AskUserQuestion({
}
]
})
```
**Handle Materials Response**:
**Handle Materials Response** (skipped if autoYes):
```javascript
if (userConfig.materials === "Provide file paths") {
if (!autoYes && userConfig.materials === "Provide file paths") {
// Follow-up question for file paths
const pathsResponse = AskUserQuestion({
questions: [{

View File

@@ -1,11 +1,16 @@
---
name: task-generate-tdd
description: Autonomous TDD task generation using action-planning-agent with Red-Green-Refactor cycles, test-first structure, and cycle validation
argument-hint: "--session WFS-session-id"
argument-hint: "[-y|--yes] --session WFS-session-id"
examples:
- /workflow:tools:task-generate-tdd --session WFS-auth
- /workflow:tools:task-generate-tdd -y --session WFS-auth
---
## Auto Mode
When `--yes` or `-y`: Skip user questions, use defaults (no materials, Agent executor).
# Autonomous TDD Task Generation Command
## Overview
@@ -78,44 +83,176 @@ Phase 2: Agent Execution (Document Generation)
## Execution Lifecycle
### Phase 1: Discovery & Context Loading
### Phase 0: User Configuration (Interactive)
**Purpose**: Collect user preferences before TDD task generation to ensure generated tasks match execution expectations and provide necessary supplementary context.
**User Questions**:
```javascript
AskUserQuestion({
questions: [
{
question: "Do you have supplementary materials or guidelines to include?",
header: "Materials",
multiSelect: false,
options: [
{ label: "No additional materials", description: "Use existing context only" },
{ label: "Provide file paths", description: "I'll specify paths to include" },
{ label: "Provide inline content", description: "I'll paste content directly" }
]
},
{
question: "Select execution method for generated TDD tasks:",
header: "Execution",
multiSelect: false,
options: [
{ label: "Agent (Recommended)", description: "Claude agent executes Red-Green-Refactor cycles directly" },
{ label: "Hybrid", description: "Agent orchestrates, calls CLI for complex steps (Red/Green phases)" },
{ label: "CLI Only", description: "All TDD cycles via CLI tools (codex/gemini/qwen)" }
]
},
{
question: "If using CLI, which tool do you prefer?",
header: "CLI Tool",
multiSelect: false,
options: [
{ label: "Codex (Recommended)", description: "Best for TDD Red-Green-Refactor cycles" },
{ label: "Gemini", description: "Best for analysis and large context" },
{ label: "Qwen", description: "Alternative analysis tool" },
{ label: "Auto", description: "Let agent decide per-task" }
]
}
]
})
```
**Handle Materials Response**:
```javascript
if (userConfig.materials === "Provide file paths") {
// Follow-up question for file paths
const pathsResponse = AskUserQuestion({
questions: [{
question: "Enter file paths to include (comma-separated or one per line):",
header: "Paths",
multiSelect: false,
options: [
{ label: "Enter paths", description: "Provide paths in text input" }
]
}]
})
userConfig.supplementaryPaths = parseUserPaths(pathsResponse)
}
```
**Build userConfig**:
```javascript
const userConfig = {
supplementaryMaterials: {
type: "none|paths|inline",
content: [...], // Parsed paths or inline content
},
executionMethod: "agent|hybrid|cli",
preferredCliTool: "codex|gemini|qwen|auto",
enableResume: true // Always enable resume for CLI executions
}
```
**Pass to Agent**: Include `userConfig` in agent prompt for Phase 2.
---
### Phase 1: Context Preparation & Discovery
**Command Responsibility**: Command prepares session paths and metadata, provides to agent for autonomous context loading.
**⚡ Memory-First Rule**: Skip file loading if documents already in conversation memory
**Agent Context Package**:
**📊 Progressive Loading Strategy**: Load context incrementally due to large analysis.md file sizes:
- **Core**: session metadata + context-package.json (always load)
- **Selective**: synthesis_output OR (guidance + relevant role analyses) - NOT all role analyses
- **On-Demand**: conflict resolution (if conflict_risk >= medium), test context
**🛤️ Path Clarity Requirement**: All `focus_paths` prefer absolute paths (e.g., `D:\\project\\src\\module`), or clear relative paths from project root (e.g., `./src/module`)
**Session Path Structure** (Provided by Command to Agent):
```
.workflow/active/WFS-{session-id}/
├── workflow-session.json # Session metadata
├── .process/
│ ├── context-package.json # Context package with artifact catalog
│ ├── test-context-package.json # Test coverage analysis
│ └── conflict-resolution.json # Conflict resolution (if exists)
├── .task/ # Output: Task JSON files
│ ├── IMPL-1.json
│ ├── IMPL-2.json
│ └── ...
├── IMPL_PLAN.md # Output: TDD implementation plan
└── TODO_LIST.md # Output: TODO list with TDD phases
```
**Command Preparation**:
1. **Assemble Session Paths** for agent prompt:
- `session_metadata_path`: `.workflow/active/{session-id}/workflow-session.json`
- `context_package_path`: `.workflow/active/{session-id}/.process/context-package.json`
- `test_context_package_path`: `.workflow/active/{session-id}/.process/test-context-package.json`
- Output directory paths
2. **Provide Metadata** (simple values):
- `session_id`: WFS-{session-id}
- `workflow_type`: "tdd"
- `mcp_capabilities`: {exa_code, exa_web, code_index}
3. **Pass userConfig** from Phase 0
**Agent Context Package** (Agent loads autonomously):
```javascript
{
"session_id": "WFS-[session-id]",
"workflow_type": "tdd",
// Note: CLI tool usage is determined semantically by action-planning-agent based on user's task description
// Core (ALWAYS load)
"session_metadata": {
// If in memory: use cached content
// Else: Load from .workflow/active//{session-id}/workflow-session.json
// Else: Load from workflow-session.json
},
"context_package": {
// If in memory: use cached content
// Else: Load from context-package.json
},
// Selective (load based on progressive strategy)
"brainstorm_artifacts": {
// Loaded from context-package.json → brainstorm_artifacts section
"role_analyses": [
"synthesis_output": {"path": "...", "exists": true}, // Load if exists (highest priority)
"guidance_specification": {"path": "...", "exists": true}, // Load if no synthesis
"role_analyses": [ // Load SELECTIVELY based on task relevance
{
"role": "system-architect",
"files": [{"path": "...", "type": "primary|supplementary"}]
}
],
"guidance_specification": {"path": "...", "exists": true},
"synthesis_output": {"path": "...", "exists": true},
"conflict_resolution": {"path": "...", "exists": true} // if conflict_risk >= medium
]
},
"context_package_path": ".workflow/active//{session-id}/.process/context-package.json",
"context_package": {
// If in memory: use cached content
// Else: Load from .workflow/active//{session-id}/.process/context-package.json
},
"test_context_package_path": ".workflow/active//{session-id}/.process/test-context-package.json",
// On-Demand (load if exists)
"test_context_package": {
// Existing test patterns and coverage analysis
// Load from test-context-package.json
// Contains existing test patterns and coverage analysis
},
"conflict_resolution": {
// Load from conflict-resolution.json if conflict_risk >= medium
// Check context-package.conflict_detection.resolution_file
},
// Capabilities
"mcp_capabilities": {
"codex_lens": true,
"exa_code": true,
"exa_web": true
"exa_web": true,
"code_index": true
},
// User configuration from Phase 0
"user_config": {
// From Phase 0 AskUserQuestion
}
}
```
@@ -124,21 +261,21 @@ Phase 2: Agent Execution (Document Generation)
1. **Load Session Context** (if not in memory)
```javascript
if (!memory.has("workflow-session.json")) {
Read(.workflow/active//{session-id}/workflow-session.json)
Read(.workflow/active/{session-id}/workflow-session.json)
}
```
2. **Load Context Package** (if not in memory)
```javascript
if (!memory.has("context-package.json")) {
Read(.workflow/active//{session-id}/.process/context-package.json)
Read(.workflow/active/{session-id}/.process/context-package.json)
}
```
3. **Load Test Context Package** (if not in memory)
```javascript
if (!memory.has("test-context-package.json")) {
Read(.workflow/active//{session-id}/.process/test-context-package.json)
Read(.workflow/active/{session-id}/.process/test-context-package.json)
}
```
@@ -180,62 +317,81 @@ Phase 2: Agent Execution (Document Generation)
)
```
### Phase 2: Agent Execution (Document Generation)
### Phase 2: Agent Execution (TDD Document Generation)
**Pre-Agent Template Selection** (Command decides path before invoking agent):
```javascript
// Command checks flag and selects template PATH (not content)
const templatePath = hasCliExecuteFlag
? "~/.claude/workflows/cli-templates/prompts/workflow/task-json-cli-mode.txt"
: "~/.claude/workflows/cli-templates/prompts/workflow/task-json-agent-mode.txt";
```
**Purpose**: Generate TDD planning documents (IMPL_PLAN.md, task JSONs, TODO_LIST.md) - planning only, NOT code implementation.
**Agent Invocation**:
```javascript
Task(
subagent_type="action-planning-agent",
run_in_background=false,
description="Generate TDD task JSON and implementation plan",
description="Generate TDD planning documents (IMPL_PLAN.md, task JSONs, TODO_LIST.md)",
prompt=`
## Execution Context
## TASK OBJECTIVE
Generate TDD implementation planning documents (IMPL_PLAN.md, task JSONs, TODO_LIST.md) for workflow session
**Session ID**: WFS-{session-id}
**Workflow Type**: TDD
**Note**: CLI tool usage is determined semantically from user's task description
IMPORTANT: This is PLANNING ONLY - you are generating planning documents, NOT implementing code.
## Phase 1: Discovery Results (Provided Context)
CRITICAL: Follow the progressive loading strategy (load analysis.md files incrementally due to file size):
- **Core**: session metadata + context-package.json (always)
- **Selective**: synthesis_output OR (guidance + relevant role analyses) - NOT all
- **On-Demand**: conflict resolution (if conflict_risk >= medium), test context
### Session Metadata
{session_metadata_content}
## SESSION PATHS
Input:
- Session Metadata: .workflow/active/{session-id}/workflow-session.json
- Context Package: .workflow/active/{session-id}/.process/context-package.json
- Test Context: .workflow/active/{session-id}/.process/test-context-package.json
### Role Analyses (Enhanced by Synthesis)
{role_analyses_content}
- Includes requirements, design specs, enhancements, and clarifications from synthesis phase
Output:
- Task Dir: .workflow/active/{session-id}/.task/
- IMPL_PLAN: .workflow/active/{session-id}/IMPL_PLAN.md
- TODO_LIST: .workflow/active/{session-id}/TODO_LIST.md
### Artifacts Inventory
- **Guidance Specification**: {guidance_spec_path}
- **Role Analyses**: {role_analyses_list}
## CONTEXT METADATA
Session ID: {session-id}
Workflow Type: TDD
MCP Capabilities: {exa_code, exa_web, code_index}
### Context Package
{context_package_summary}
- Includes conflict_risk assessment
## USER CONFIGURATION (from Phase 0)
Execution Method: ${userConfig.executionMethod} // agent|hybrid|cli
Preferred CLI Tool: ${userConfig.preferredCliTool} // codex|gemini|qwen|auto
Supplementary Materials: ${userConfig.supplementaryMaterials}
### Test Context Package
{test_context_package_summary}
- Existing test patterns, framework config, coverage analysis
## CLI TOOL SELECTION
Based on userConfig.executionMethod:
- "agent": No command field in implementation_approach steps
- "hybrid": Add command field to complex steps only (Red/Green phases recommended for CLI)
- "cli": Add command field to ALL Red-Green-Refactor steps
### Conflict Resolution (Conditional)
If conflict_risk was medium/high, modifications have been applied to:
- **guidance-specification.md**: Design decisions updated to resolve conflicts
- **Role analyses (*.md)**: Recommendations adjusted for compatibility
- **context-package.json**: Marked as "resolved" with conflict IDs
- Conflict resolution results stored in conflict-resolution.json
CLI Resume Support (MANDATORY for all CLI commands):
- Use --resume parameter to continue from previous task execution
- Read previous task's cliExecutionId from session state
- Format: ccw cli -p "[prompt]" --resume [previousCliId] --tool [tool] --mode write
### MCP Analysis Results (Optional)
**Code Structure**: {mcp_code_index_results}
**External Research**: {mcp_exa_research_results}
## EXPLORATION CONTEXT (from context-package.exploration_results)
- Load exploration_results from context-package.json
- Use aggregated_insights.critical_files for focus_paths generation
- Apply aggregated_insights.constraints to acceptance criteria
- Reference aggregated_insights.all_patterns for implementation approach
- Use aggregated_insights.all_integration_points for precise modification locations
- Use conflict_indicators for risk-aware task sequencing
## Phase 2: TDD Document Generation Task
## CONFLICT RESOLUTION CONTEXT (if exists)
- Check context-package.conflict_detection.resolution_file for conflict-resolution.json path
- If exists, load .process/conflict-resolution.json:
- Apply planning_constraints as task constraints (for brainstorm-less workflows)
- Reference resolved_conflicts for implementation approach alignment
- Handle custom_conflicts with explicit task notes
## TEST CONTEXT INTEGRATION
- Load test-context-package.json for existing test patterns and coverage analysis
- Extract test framework configuration (Jest/Pytest/etc.)
- Identify existing test conventions and patterns
- Map coverage gaps to TDD Red phase test targets
## TDD DOCUMENT GENERATION TASK
**Agent Configuration Reference**: All TDD task generation rules, quantification requirements, Red-Green-Refactor cycle structure, quality standards, and execution details are defined in action-planning-agent.
@@ -256,31 +412,61 @@ If conflict_risk was medium/high, modifications have been applied to:
#### Required Outputs Summary
##### 1. TDD Task JSON Files (.task/IMPL-*.json)
- **Location**: `.workflow/active//{session-id}/.task/`
- **Schema**: 5-field structure with TDD-specific metadata
- **Location**: `.workflow/active/{session-id}/.task/`
- **Schema**: 6-field structure with TDD-specific metadata
- `id, title, status, context_package_path, meta, context, flow_control`
- `meta.tdd_workflow`: true (REQUIRED)
- `meta.max_iterations`: 3 (Green phase test-fix cycle limit)
- `meta.cli_execution_id`: Unique CLI execution ID (format: `{session_id}-{task_id}`)
- `meta.cli_execution`: Strategy object (new|resume|fork|merge_fork)
- `context.tdd_cycles`: Array with quantified test cases and coverage
- `context.focus_paths`: Absolute or clear relative paths (enhanced with exploration critical_files)
- `flow_control.implementation_approach`: Exactly 3 steps with `tdd_phase` field
1. Red Phase (`tdd_phase: "red"`): Write failing tests
2. Green Phase (`tdd_phase: "green"`): Implement to pass tests
3. Refactor Phase (`tdd_phase: "refactor"`): Improve code quality
- CLI tool usage determined semantically (add `command` field when user requests CLI execution)
- `flow_control.pre_analysis`: Include exploration integration_points analysis
- CLI tool usage based on userConfig (add `command` field per executionMethod)
- **Details**: See action-planning-agent.md § TDD Task JSON Generation
##### 2. IMPL_PLAN.md (TDD Variant)
- **Location**: `.workflow/active//{session-id}/IMPL_PLAN.md`
- **Location**: `.workflow/active/{session-id}/IMPL_PLAN.md`
- **Template**: `~/.claude/workflows/cli-templates/prompts/workflow/impl-plan-template.txt`
- **TDD-Specific Frontmatter**: workflow_type="tdd", tdd_workflow=true, feature_count, task_breakdown
- **TDD Implementation Tasks Section**: Feature-by-feature with internal Red-Green-Refactor cycles
- **Context Analysis**: Artifact references and exploration insights
- **Details**: See action-planning-agent.md § TDD Implementation Plan Creation
##### 3. TODO_LIST.md
- **Location**: `.workflow/active//{session-id}/TODO_LIST.md`
- **Location**: `.workflow/active/{session-id}/TODO_LIST.md`
- **Format**: Hierarchical task list with internal TDD phase indicators (Red → Green → Refactor)
- **Status**: ▸ (container), [ ] (pending), [x] (completed)
- **Links**: Task JSON references and summaries
- **Details**: See action-planning-agent.md § TODO List Generation
### CLI EXECUTION ID REQUIREMENTS (MANDATORY)
Each task JSON MUST include:
- **meta.cli_execution_id**: Unique ID for CLI execution (format: `{session_id}-{task_id}`)
- **meta.cli_execution**: Strategy object based on depends_on:
- No deps → `{ "strategy": "new" }`
- 1 dep (single child) → `{ "strategy": "resume", "resume_from": "parent-cli-id" }`
- 1 dep (multiple children) → `{ "strategy": "fork", "resume_from": "parent-cli-id" }`
- N deps → `{ "strategy": "merge_fork", "resume_from": ["id1", "id2", ...] }`
- **Type**: `resume_from: string | string[]` (string for resume/fork, array for merge_fork)
**CLI Execution Strategy Rules**:
1. **new**: Task has no dependencies - starts fresh CLI conversation
2. **resume**: Task has 1 parent AND that parent has only this child - continues same conversation
3. **fork**: Task has 1 parent BUT parent has multiple children - creates new branch with parent context
4. **merge_fork**: Task has multiple parents - merges all parent contexts into new conversation
**Execution Command Patterns**:
- new: `ccw cli -p "[prompt]" --tool [tool] --mode write --id [cli_execution_id]`
- resume: `ccw cli -p "[prompt]" --resume [resume_from] --tool [tool] --mode write`
- fork: `ccw cli -p "[prompt]" --resume [resume_from] --id [cli_execution_id] --tool [tool] --mode write`
- merge_fork: `ccw cli -p "[prompt]" --resume [resume_from.join(',')] --id [cli_execution_id] --tool [tool] --mode write` (resume_from is array)
### Quantification Requirements (MANDATORY)
**Core Rules**:
@@ -302,6 +488,7 @@ If conflict_risk was medium/high, modifications have been applied to:
- [ ] Every acceptance criterion includes measurable coverage percentage
- [ ] tdd_cycles array contains test_count and test_cases for each cycle
- [ ] No vague language ("comprehensive", "complete", "thorough")
- [ ] cli_execution_id and cli_execution strategy assigned to each task
### Agent Execution Summary
@@ -317,20 +504,34 @@ If conflict_risk was medium/high, modifications have been applied to:
- ✓ Quantification requirements enforced (explicit counts, measurable acceptance, exact targets)
- ✓ Task count ≤18 (hard limit)
- ✓ Each task has meta.tdd_workflow: true
- ✓ Each task has exactly 3 implementation steps with tdd_phase field
-Green phase includes test-fix cycle logic
-Artifact references mapped correctly
-MCP tool integration added
- ✓ Each task has exactly 3 implementation steps with tdd_phase field ("red", "green", "refactor")
-Each task has meta.cli_execution_id and meta.cli_execution strategy
-Green phase includes test-fix cycle logic with max_iterations
-focus_paths are absolute or clear relative paths (from exploration critical_files)
- ✓ Artifact references mapped correctly from context package
- ✓ Exploration context integrated (critical_files, constraints, patterns, integration_points)
- ✓ Conflict resolution context applied (if conflict_risk >= medium)
- ✓ Test context integrated (existing test patterns and coverage analysis)
- ✓ Documents follow TDD template structure
- ✓ CLI tool selection based on userConfig.executionMethod
## Output
## SUCCESS CRITERIA
- All planning documents generated successfully:
- Task JSONs valid and saved to .task/ directory with cli_execution_id
- IMPL_PLAN.md created with complete TDD structure
- TODO_LIST.md generated matching task JSONs
- CLI execution strategies assigned based on task dependencies
- Return completion status with document count and task breakdown summary
Generate all three documents and report completion status:
- TDD task JSON files created: N files (IMPL-*.json)
## OUTPUT SUMMARY
Generate all three documents and report:
- TDD task JSON files created: N files (IMPL-*.json) with cli_execution_id assigned
- TDD cycles configured: N cycles with quantified test cases
- Artifacts integrated: synthesis-spec, guidance-specification, N role analyses
- CLI execution strategies: new/resume/fork/merge_fork assigned per dependency graph
- Artifacts integrated: synthesis-spec/guidance-specification, relevant role analyses
- Exploration context: critical_files, constraints, patterns, integration_points
- Test context integrated: existing patterns and coverage
- MCP enhancements: CodexLens, exa-research
- Conflict resolution: applied (if conflict_risk >= medium)
- Session ready for TDD execution: /workflow:execute
`
)
@@ -338,50 +539,64 @@ Generate all three documents and report completion status:
### Agent Context Passing
**Memory-Aware Context Assembly**:
**Context Delegation Model**: Command provides paths and metadata, agent loads context autonomously using progressive loading strategy.
**Command Provides** (in agent prompt):
```javascript
// Assemble context package for agent
const agentContext = {
session_id: "WFS-[id]",
// Command assembles these simple values and paths for agent
const commandProvides = {
// Session paths
session_metadata_path: ".workflow/active/WFS-{id}/workflow-session.json",
context_package_path: ".workflow/active/WFS-{id}/.process/context-package.json",
test_context_package_path: ".workflow/active/WFS-{id}/.process/test-context-package.json",
output_task_dir: ".workflow/active/WFS-{id}/.task/",
output_impl_plan: ".workflow/active/WFS-{id}/IMPL_PLAN.md",
output_todo_list: ".workflow/active/WFS-{id}/TODO_LIST.md",
// Simple metadata
session_id: "WFS-{id}",
workflow_type: "tdd",
mcp_capabilities: { exa_code: true, exa_web: true, code_index: true },
// Use memory if available, else load
session_metadata: memory.has("workflow-session.json")
? memory.get("workflow-session.json")
: Read(.workflow/active/WFS-[id]/workflow-session.json),
context_package_path: ".workflow/active/WFS-[id]/.process/context-package.json",
context_package: memory.has("context-package.json")
? memory.get("context-package.json")
: Read(".workflow/active/WFS-[id]/.process/context-package.json"),
test_context_package_path: ".workflow/active/WFS-[id]/.process/test-context-package.json",
test_context_package: memory.has("test-context-package.json")
? memory.get("test-context-package.json")
: Read(".workflow/active/WFS-[id]/.process/test-context-package.json"),
// Extract brainstorm artifacts from context package
brainstorm_artifacts: extractBrainstormArtifacts(context_package),
// Load role analyses using paths from context package
role_analyses: brainstorm_artifacts.role_analyses
.flatMap(role => role.files)
.map(file => Read(file.path)),
// Load conflict resolution if exists (prefer new JSON format)
conflict_resolution: context_package.conflict_detection?.resolution_file
? Read(context_package.conflict_detection.resolution_file) // .process/conflict-resolution.json
: (brainstorm_artifacts?.conflict_resolution?.exists
? Read(brainstorm_artifacts.conflict_resolution.path)
: null),
// Optional MCP enhancements
mcp_analysis: executeMcpDiscovery()
// User configuration from Phase 0
user_config: {
supplementaryMaterials: { type: "...", content: [...] },
executionMethod: "agent|hybrid|cli",
preferredCliTool: "codex|gemini|qwen|auto",
enableResume: true
}
}
```
**Agent Loads Autonomously** (progressive loading):
```javascript
// Agent executes progressive loading based on memory state
const agentLoads = {
// Core (ALWAYS load if not in memory)
session_metadata: loadIfNotInMemory(session_metadata_path),
context_package: loadIfNotInMemory(context_package_path),
// Selective (based on progressive strategy)
// Priority: synthesis_output > guidance + relevant_role_analyses
brainstorm_content: loadSelectiveBrainstormArtifacts(context_package),
// On-Demand (load if exists and relevant)
test_context: loadIfExists(test_context_package_path),
conflict_resolution: loadConflictResolution(context_package),
// Optional (if MCP available)
exploration_results: extractExplorationResults(context_package),
external_research: executeMcpResearch() // If needed
}
```
**Progressive Loading Implementation** (agent responsibility):
1. **Check memory first** - skip if already loaded
2. **Load core files** - session metadata + context-package.json
3. **Smart selective loading** - synthesis_output OR (guidance + task-relevant role analyses)
4. **On-demand loading** - test context, conflict resolution (if conflict_risk >= medium)
5. **Extract references** - exploration results, artifact paths from context package
## TDD Task Structure Reference
This section provides quick reference for TDD task JSON structure. For complete implementation details, see the agent invocation prompt in Phase 2 above.
@@ -389,14 +604,31 @@ This section provides quick reference for TDD task JSON structure. For complete
**Quick Reference**:
- Each TDD task contains complete Red-Green-Refactor cycle
- Task ID format: `IMPL-N` (simple) or `IMPL-N.M` (complex subtasks)
- Required metadata: `meta.tdd_workflow: true`, `meta.max_iterations: 3`
- Flow control: Exactly 3 steps with `tdd_phase` field (red, green, refactor)
- Context: `tdd_cycles` array with quantified test cases and coverage
- Required metadata:
- `meta.tdd_workflow: true`
- `meta.max_iterations: 3`
- `meta.cli_execution_id: "{session_id}-{task_id}"`
- `meta.cli_execution: { "strategy": "new|resume|fork|merge_fork", ... }`
- Context: `tdd_cycles` array with quantified test cases and coverage:
```javascript
tdd_cycles: [
{
test_count: 5, // Number of test cases to write
test_cases: ["case1", "case2"], // Enumerated test scenarios
implementation_scope: "...", // Files and functions to implement
expected_coverage: ">=85%" // Coverage target
}
]
```
- Context: `focus_paths` use absolute or clear relative paths
- Flow control: Exactly 3 steps with `tdd_phase` field ("red", "green", "refactor")
- Flow control: `pre_analysis` includes exploration integration_points analysis
- Command field: Added per `userConfig.executionMethod` (agent/hybrid/cli)
- See Phase 2 agent prompt for full schema and requirements
## Output Files Structure
```
.workflow/active//{session-id}/
.workflow/active/{session-id}/
├── IMPL_PLAN.md # Unified plan with TDD Implementation Tasks section
├── TODO_LIST.md # Progress tracking with internal TDD phase indicators
├── .task/
@@ -432,9 +664,9 @@ This section provides quick reference for TDD task JSON structure. For complete
- No circular dependencies allowed
### Task Limits
- Maximum 10 total tasks (simple + subtasks)
- Flat hierarchy (≤5 tasks) or two-level (6-10 tasks with containers)
- Re-scope requirements if >10 tasks needed
- Maximum 18 total tasks (simple + subtasks) - hard limit for TDD workflows
- Flat hierarchy (≤5 tasks) or two-level (6-18 tasks with containers)
- Re-scope requirements if >18 tasks needed
### TDD Workflow Validation
- `meta.tdd_workflow` must be true
@@ -454,7 +686,7 @@ This section provides quick reference for TDD task JSON structure. For complete
### TDD Generation Errors
| Error | Cause | Resolution |
|-------|-------|------------|
| Task count exceeds 10 | Too many features or subtasks | Re-scope requirements or merge features |
| Task count exceeds 18 | Too many features or subtasks | Re-scope requirements or merge features into multiple TDD sessions |
| Missing test framework | No test config | Configure testing first |
| Invalid TDD workflow | Missing tdd_phase or incomplete flow_control | Fix TDD structure in ANALYSIS_RESULTS.md |
| Missing tdd_workflow flag | Task doesn't have meta.tdd_workflow: true | Add TDD workflow metadata |
@@ -512,6 +744,6 @@ IMPL (Green phase) tasks include automatic test-fix cycle:
## Configuration Options
- **meta.max_iterations**: Number of fix attempts (default: 3 for TDD, 5 for test-gen)
- **meta.max_iterations**: Number of fix attempts in Green phase (default: 3)
- **CLI tool usage**: Determined semantically from user's task description via `command` field in implementation_approach

View File

@@ -1,10 +1,14 @@
---
name: animation-extract
description: Extract animation and transition patterns from prompt inference and image references for design system documentation
argument-hint: "[--design-id <id>] [--session <id>] [--images "<glob>"] [--focus "<types>"] [--interactive] [--refine]"
argument-hint: "[-y|--yes] [--design-id <id>] [--session <id>] [--images "<glob>"] [--focus "<types>"] [--interactive] [--refine]"
allowed-tools: TodoWrite(*), Read(*), Write(*), Glob(*), Bash(*), AskUserQuestion(*), Task(ui-design-agent)
---
## Auto Mode
When `--yes` or `-y`: Skip all clarification questions, use AI-inferred animation decisions.
# Animation Extraction Command
## Overview

View File

@@ -1,10 +1,14 @@
---
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: [--design-id <id>] [--session <id>] [--images "<glob>"] [--prompt "<desc>"] [--targets "<list>"] [--variants <count>] [--device-type <desktop|mobile|tablet|responsive>] [--interactive] [--refine]
argument-hint: "[-y|--yes] [--design-id <id>] [--session <id>] [--images "<glob>"] [--prompt "<desc>"] [--targets "<list>"] [--variants <count>] [--device-type <desktop|mobile|tablet|responsive>] [--interactive] [--refine]"
allowed-tools: TodoWrite(*), Read(*), Write(*), Glob(*), Bash(*), AskUserQuestion(*), Task(ui-design-agent), mcp__exa__web_search_exa(*)
---
## Auto Mode
When `--yes` or `-y`: Skip all clarification questions, use AI-inferred layout decisions.
# Layout Extraction Command
## Overview

View File

@@ -1,10 +1,14 @@
---
name: style-extract
description: Extract design style from reference images or text prompts using Claude analysis with variant generation or refinement mode
argument-hint: "[--design-id <id>] [--session <id>] [--images "<glob>"] [--prompt "<desc>"] [--variants <count>] [--interactive] [--refine]"
argument-hint: "[-y|--yes] [--design-id <id>] [--session <id>] [--images "<glob>"] [--prompt "<desc>"] [--variants <count>] [--interactive] [--refine]"
allowed-tools: TodoWrite(*), Read(*), Write(*), Glob(*), AskUserQuestion(*)
---
## Auto Mode
When `--yes` or `-y`: Skip all clarification questions, use AI-inferred design decisions.
# Style Extraction Command
## Overview

View File

@@ -0,0 +1,45 @@
# CCW Coordinator
交互式命令编排工具
## 使用
```
/ccw-coordinator
/coordinator
```
## 流程
1. 用户描述任务
2. Claude推荐命令链
3. 用户确认或调整
4. 执行命令链
5. 生成报告
## 示例
**Bug修复**
```
任务: 修复登录bug
推荐: lite-fix → test-cycle-execute
```
**新功能**
```
任务: 实现注册功能
推荐: plan → execute → test-cycle-execute
```
## 文件说明
| 文件 | 用途 |
|------|------|
| SKILL.md | Skill入口 |
| phases/orchestrator.md | 编排逻辑 |
| phases/state-schema.md | 状态定义 |
| phases/actions/*.md | 动作实现 |
| specs/specs.md | 命令库、验证规则、注册表 |
| tools/chain-validate.cjs | 验证工具 |
| tools/command-registry.cjs | 命令注册表工具 |

View File

@@ -0,0 +1,320 @@
---
name: ccw-coordinator
description: Interactive command orchestration tool for building and executing Claude CLI command chains. Triggers on "coordinator", "ccw-coordinator", "命令编排", "command chain", "orchestrate commands", "编排CLI命令".
allowed-tools: Task, AskUserQuestion, Read, Write, Bash, Glob, Grep
---
# CCW Coordinator
交互式命令编排工具允许用户依次选择命令形成命令串然后依次调用claude cli执行整个命令串。
支持灵活的工作流组合,提供交互式界面用于命令选择、编排和执行管理。
## Architecture Overview
```
┌─────────────────────────────────────────────────────────────────┐
│ Orchestrator (状态驱动决策) │
│ 根据用户选择编排命令和执行流程 │
└───────────────┬─────────────────────────────────────────────────┘
┌───────────┼───────────┬───────────────┐
↓ ↓ ↓ ↓
┌─────────┐ ┌──────────────┐ ┌────────────┐ ┌──────────┐
│ Init │ │ Command │ │ Command │ │ Execute │
│ │ │ Selection │ │ Build │ │ │
│ │ │ │ │ │ │ │
│ 初始化 │ │ 选择命令 │ │ 编排调整 │ │ 执行链 │
└─────────┘ └──────────────┘ └────────────┘ └──────────┘
│ │ │ │
└───────────────┼──────────────┴────────────┘
┌──────────────┐
│ Complete │
│ 生成报告 │
└──────────────┘
```
## Key Design Principles
1. **智能推荐**: Claude 根据用户任务描述,自动推荐最优命令链
2. **交互式编排**: 用户通过交互式界面选择和编排命令,实时反馈
3. **无状态动作**: 每个动作独立执行,通过共享状态进行通信
4. **灵活的命令库**: 支持ccw workflow命令和标准claude cli命令
5. **执行透明性**: 展示执行进度、结果和可能的错误
6. **会话持久化**: 保存编排会话,支持中途暂停和恢复
7. **智能提示词生成**: 根据任务上下文和前序产物自动生成 ccw cli 提示词
8. **自动确认**: 所有命令自动添加 `-y` 参数,跳过交互式确认,实现无人值守执行
## Intelligent Prompt Generation
执行命令时,系统根据以下信息智能生成 `ccw cli -p` 提示词:
### 提示词构成
```javascript
// 集成命令注册表 (~/.claude/tools/command-registry.js)
const registry = new CommandRegistry();
registry.buildRegistry();
function generatePrompt(cmd, state) {
const cmdMeta = registry.getCommand(cmd.command);
let prompt = `任务: ${state.task_description}\n`;
if (state.execution_results.length > 0) {
const previousOutputs = state.execution_results
.filter(r => r.status === 'success')
.map(r => {
if (r.summary?.session) {
return `- ${r.command}: ${r.summary.session} (${r.summary.files?.join(', ')})`;
}
return `- ${r.command}: 已完成`;
})
.join('\n');
prompt += `\n前序完成:\n${previousOutputs}\n`;
}
// 从 YAML 头提取命令元数据
if (cmdMeta) {
prompt += `\n命令: ${cmd.command}`;
if (cmdMeta.argumentHint) {
prompt += ` ${cmdMeta.argumentHint}`;
}
}
return prompt;
}
```
### 产物追踪
每个命令执行后自动提取关键产物:
```javascript
{
command: "/workflow:lite-plan",
status: "success",
output: "...",
summary: {
session: "WFS-plan-20250123", // 会话ID
files: [".workflow/IMPL_PLAN.md"], // 产物文件
timestamp: "2025-01-23T10:30:00Z"
}
}
```
### 命令调用示例
```bash
# 自动生成的智能提示词
ccw cli -p "任务: 实现用户认证功能
前序完成:
- /workflow:lite-plan: WFS-plan-20250123 (.workflow/IMPL_PLAN.md)
命令: /workflow:lite-execute [--resume-session=\"session-id\"]" /workflow:lite-execute
```
### 命令注册表集成
- **位置**: `tools/command-registry.js` (skill 内置)
- **工作模式**: 按需提取(只提取用户任务链中的命令)
- **功能**: 自动查找全局 `.claude/commands/workflow` 目录,解析命令 YAML 头元数据
- **作用**: 确保提示词包含准确的命令参数和上下文
详见 `tools/README.md`
---
## Execution Flow
### Orchestrator Execution Loop
```javascript
1. 初始化会话
2. 循环执行直到完成
读取当前状态
选择下一个动作根据状态和用户意图
执行动作更新状态
检查终止条件
3. 生成最终报告
```
### Action Sequence (Typical)
```
action-init
↓ (status: pending → running)
action-command-selection (可重复)
↓ (添加命令到链)
action-command-build (可选)
↓ (调整命令顺序)
action-command-execute
↓ (依次执行所有命令)
action-complete
↓ (status: running → completed)
```
## State Management
### Initial State
```json
{
"status": "pending",
"task_description": "",
"command_chain": [],
"confirmed": false,
"error_count": 0,
"execution_results": [],
"current_command_index": 0,
"started_at": null
}
```
### State Transitions
```
pending → running (init) → running → completed (execute)
aborted (error or user exit)
```
## Directory Setup
```javascript
const timestamp = new Date().toISOString().slice(0,19).replace(/[-:T]/g, '');
const workDir = `.workflow/.ccw-coordinator/${timestamp}`;
Bash(`mkdir -p "${workDir}"`);
Bash(`mkdir -p "${workDir}/commands"`);
Bash(`mkdir -p "${workDir}/logs"`);
```
## Output Structure
```
.workflow/.ccw-coordinator/{timestamp}/
├── state.json # 当前会话状态
├── command-chain.json # 编排的完整命令链
├── execution-log.md # 执行日志
├── final-summary.md # 最终报告
├── commands/ # 各命令执行详情
│ ├── 01-command.log
│ ├── 02-command.log
│ └── ...
└── logs/ # 错误和警告日志
├── errors.log
└── warnings.log
```
## Reference Documents
| Document | Purpose |
|----------|---------|
| [phases/orchestrator.md](phases/orchestrator.md) | 编排器实现 |
| [phases/state-schema.md](phases/state-schema.md) | 状态结构定义 |
| [phases/actions/action-init.md](phases/actions/action-init.md) | 初始化动作 |
| [phases/actions/action-command-selection.md](phases/actions/action-command-selection.md) | 命令选择动作 |
| [phases/actions/action-command-build.md](phases/actions/action-command-build.md) | 命令编排动作 |
| [phases/actions/action-command-execute.md](phases/actions/action-command-execute.md) | 命令执行动作 |
| [phases/actions/action-complete.md](phases/actions/action-complete.md) | 完成动作 |
| [phases/actions/action-abort.md](phases/actions/action-abort.md) | 中止动作 |
| [specs/specs.md](specs/specs.md) | 命令库、验证规则、注册表 |
| [tools/chain-validate.cjs](tools/chain-validate.cjs) | 验证工具 |
| [tools/command-registry.cjs](tools/command-registry.cjs) | 命令注册表工具 |
---
## Usage Examples
### 快速命令链
用户想要执行:规划 → 执行 → 测试
```
1. 触发 /ccw-coordinator
2. 描述任务:"实现用户注册功能"
3. Claude推荐: plan → execute → test-cycle-execute
4. 用户确认
5. 执行命令链
```
### 复杂工作流
用户想要执行:规划 → 执行 → 审查 → 修复
```
1. 触发 /ccw-coordinator
2. 描述任务:"重构认证模块"
3. Claude推荐: plan → execute → review-session-cycle → review-fix
4. 用户可调整命令顺序
5. 确认执行
6. 实时查看执行进度
```
### 紧急修复
用户想要快速修复bug
```
1. 触发 /ccw-coordinator
2. 描述任务:"修复生产环境登录bug"
3. Claude推荐: lite-fix --hotfix → test-cycle-execute
4. 用户确认
5. 快速执行修复
```
## Constraints and Rules
### 1. 命令推荐约束
- **智能推荐优先**: 必须先基于用户任务描述进行智能推荐,而非直接展示命令库
- **不使用静态映射**: 禁止使用查表或硬编码的推荐逻辑(如 `if task=bug则推荐lite-fix`
- **推荐必须说明理由**: Claude 推荐命令链时必须解释为什么这样推荐
- **用户保留选择权**: 推荐后,用户可选择:使用推荐/调整/手动选择
### 2. 验证约束
- **执行前必须验证**: 使用 `chain-validate.js` 验证命令链合法性
- **不合法必须提示**: 如果验证失败,必须明确告知用户错误原因和修复方法
- **允许用户覆盖**: 验证失败时,询问用户是否仍要执行(警告模式)
### 3. 执行约束
- **顺序执行**: 命令必须严格按照 command_chain 中的 order 顺序执行
- **错误处理**: 单个命令失败时,询问用户:重试/跳过/中止
- **错误上限**: 连续 3 次错误自动中止会话
- **实时反馈**: 每个命令执行时显示进度(如 `[2/5] 执行: lite-execute`
### 4. 状态管理约束
- **状态持久化**: 每次状态更新必须立即写入磁盘
- **单一数据源**: 状态只保存在 `state.json`,禁止多个状态文件
- **原子操作**: 状态更新必须使用 read-modify-write 模式,避免并发冲突
### 5. 用户体验约束
- **最小交互**: 默认使用智能推荐 + 一次确认,避免多次询问
- **清晰输出**: 每个步骤输出必须包含:当前状态、可用选项、建议操作
- **可恢复性**: 会话中断后,用户可从上次状态恢复
### 6. 禁止行为
-**禁止跳过推荐步骤**: 不能直接进入手动选择,必须先尝试推荐
-**禁止静态推荐**: 不能使用 recommended-chains.json 查表
-**禁止无验证执行**: 不能跳过链条验证直接执行
-**禁止静默失败**: 错误必须明确报告,不能静默跳过
## Notes
- 编排器使用状态机模式,确保执行流程的可靠性
- 所有命令链和执行结果都被持久化保存,支持后续查询和调试
- 支持用户中途修改命令链(在执行前)
- 执行错误会自动记录,支持重试机制
- Claude 智能推荐基于任务分析,非查表静态推荐

View File

@@ -0,0 +1,9 @@
# action-abort
中止会话,保存状态
```javascript
updateState({ status: 'aborted' });
console.log(`会话已中止: ${workDir}`);
```

View File

@@ -0,0 +1,40 @@
# action-command-build
调整命令链顺序或删除命令
## 流程
1. 显示当前命令链
2. 让用户调整(重新排序、删除)
3. 确认执行
## 伪代码
```javascript
// 显示链
console.log('命令链:');
state.command_chain.forEach((cmd, i) => {
console.log(`${i+1}. ${cmd.command}`);
});
// 询问用户
const action = await AskUserQuestion({
options: [
'继续执行',
'删除命令',
'重新排序',
'返回选择'
]
});
// 处理用户操作
if (action === '继续执行') {
updateState({confirmed: true, status: 'executing'});
}
// ... 其他操作
```
## 状态更新
- command_chain (可能修改)
- confirmed = true 时状态转为 executing

View File

@@ -0,0 +1,124 @@
# action-command-execute
依次执行命令链,智能生成 ccw cli 提示词
## 命令注册表集成
```javascript
// 从 ./tools/command-registry.cjs 按需提取命令元数据
const CommandRegistry = require('./tools/command-registry.cjs');
const registry = new CommandRegistry();
// 只提取当前任务链中的命令
const commandNames = command_chain.map(cmd => cmd.command);
const commandMeta = registry.getCommands(commandNames);
```
## 提示词生成策略
```javascript
function generatePrompt(cmd, state, commandMeta) {
const { task_description, execution_results } = state;
// 获取命令元数据(从已提取的 commandMeta
const cmdInfo = commandMeta[cmd.command];
// 提取前序产物信息
const previousOutputs = execution_results
.filter(r => r.status === 'success')
.map(r => {
const summary = r.summary;
if (summary?.session) {
return `- ${r.command}: ${summary.session} (${summary.files?.join(', ') || '完成'})`;
}
return `- ${r.command}: 已完成`;
})
.join('\n');
// 根据命令类型构建提示词
let prompt = `任务: ${task_description}\n`;
if (previousOutputs) {
prompt += `\n前序完成:\n${previousOutputs}\n`;
}
// 添加命令元数据上下文
if (cmdInfo) {
prompt += `\n命令: ${cmd.command}`;
if (cmdInfo.argumentHint) {
prompt += ` ${cmdInfo.argumentHint}`;
}
}
return prompt;
}
```
## 执行逻辑
```javascript
for (let i = current_command_index; i < command_chain.length; i++) {
const cmd = command_chain[i];
console.log(`[${i+1}/${command_chain.length}] 执行: ${cmd.command}`);
// 生成智能提示词
const prompt = generatePrompt(cmd, state, commandMeta);
try {
// 使用 ccw cli 执行(添加 -y 参数跳过确认)
const result = Bash(`ccw cli -p "${prompt.replace(/"/g, '\\"')}" ${cmd.command} -y`, {
run_in_background: true
});
execution_results.push({
command: cmd.command,
status: result.exit_code === 0 ? 'success' : 'failed',
exit_code: result.exit_code,
output: result.stdout,
summary: extractSummary(result.stdout) // 提取关键产物
});
command_chain[i].status = 'completed';
current_command_index = i + 1;
} catch (error) {
error_count++;
command_chain[i].status = 'failed';
if (error_count >= 3) break;
const action = await AskUserQuestion({
options: ['重试', '跳过', '中止']
});
if (action === '重试') i--;
if (action === '中止') break;
}
updateState({ command_chain, execution_results, current_command_index, error_count });
}
```
## 产物提取
```javascript
function extractSummary(output) {
// 从输出提取关键产物信息
// 例如: 会话ID, 文件路径, 任务完成状态等
const sessionMatch = output.match(/WFS-\w+-\d+/);
const fileMatch = output.match(/\.workflow\/[^\s]+/g);
return {
session: sessionMatch?.[0],
files: fileMatch || [],
timestamp: new Date().toISOString()
};
}
```
## 状态更新
- execution_results (包含 summary 产物信息)
- command_chain[].status
- current_command_index

View File

@@ -0,0 +1,48 @@
# action-command-selection
## 流程
1. 问用户任务
2. Claude推荐命令链
3. 用户确认/手动选择
4. 添加到command_chain
## 伪代码
```javascript
// 1. 获取用户任务描述
const taskInput = await AskUserQuestion({
question: '请描述您的任务',
options: [
{ label: '手动选择命令', value: 'manual' }
]
});
// 保存任务描述到状态
updateState({ task_description: taskInput.text || taskInput.value });
// 2. 若用户描述任务Claude推荐
if (taskInput.text) {
console.log('推荐: ', recommendChain(taskInput.text));
const confirm = await AskUserQuestion({
question: '是否使用推荐链?',
options: ['使用推荐', '调整', '手动选择']
});
if (confirm === '使用推荐') {
addCommandsToChain(recommendedChain);
updateState({ confirmed: true });
return;
}
}
// 3. 手动选择
const commands = loadCommandLibrary();
const selected = await AskUserQuestion(commands);
addToChain(selected);
```
## 状态更新
- task_description = 用户任务描述
- command_chain.push(newCommand)
- 如果用户确认: confirmed = true

View File

@@ -0,0 +1,25 @@
# action-complete
生成执行报告
```javascript
const success = execution_results.filter(r => r.status === 'success').length;
const failed = execution_results.filter(r => r.status === 'failed').length;
const duration = Date.now() - new Date(started_at).getTime();
const report = `
# 执行报告
- 会话: ${session_id}
- 耗时: ${Math.round(duration/1000)}s
- 成功: ${success}
- 失败: ${failed}
## 命令详情
${command_chain.map((c, i) => `${i+1}. ${c.command} - ${c.status}`).join('\n')}
`;
Write(`${workDir}/final-report.md`, report);
updateState({ status: 'completed' });
```

View File

@@ -0,0 +1,26 @@
# action-init
初始化编排会话
```javascript
const timestamp = Date.now();
const workDir = `.workflow/.ccw-coordinator/${timestamp}`;
Bash(`mkdir -p "${workDir}"`);
const state = {
session_id: `coord-${timestamp}`,
status: 'running',
started_at: new Date().toISOString(),
task_description: '',
command_chain: [],
current_command_index: 0,
execution_results: [],
confirmed: false,
error_count: 0
};
Write(`${workDir}/state.json`, JSON.stringify(state, null, 2));
console.log(`会话已初始化: ${workDir}`);
```

View File

@@ -0,0 +1,59 @@
# Orchestrator
状态驱动编排:读状态 → 选动作 → 执行 → 更新状态
## 决策逻辑
```javascript
function selectNextAction(state) {
if (['completed', 'aborted'].includes(state.status)) return null;
if (state.error_count >= 3) return 'action-abort';
switch (state.status) {
case 'pending':
return 'action-init';
case 'running':
return state.confirmed && state.command_chain.length > 0
? 'action-command-execute'
: 'action-command-selection';
case 'executing':
const pending = state.command_chain.filter(c => c.status === 'pending');
return pending.length === 0 ? 'action-complete' : 'action-command-execute';
default:
return 'action-abort';
}
}
```
## 执行循环
```javascript
const timestamp = Date.now();
const workDir = `.workflow/.ccw-coordinator/${timestamp}`;
Bash(`mkdir -p "${workDir}"`);
const state = {
session_id: `coord-${timestamp}`,
status: 'pending',
started_at: new Date().toISOString(),
task_description: '', // 从 action-command-selection 获取
command_chain: [],
current_command_index: 0,
execution_results: [],
confirmed: false,
error_count: 0
};
Write(`${workDir}/state.json`, JSON.stringify(state, null, 2));
let iterations = 0;
while (iterations < 50) {
const state = JSON.parse(Read(`${workDir}/state.json`));
const nextAction = selectNextAction(state);
if (!nextAction) break;
console.log(`[${nextAction}]`);
// 执行 phases/actions/{nextAction}.md
iterations++;
}
```

View File

@@ -0,0 +1,66 @@
# State Schema
```typescript
interface State {
session_id: string;
status: 'pending' | 'running' | 'executing' | 'completed' | 'aborted';
started_at: string;
task_description: string; // 用户任务描述
command_chain: Command[];
current_command_index: number;
execution_results: ExecutionResult[];
confirmed: boolean;
error_count: number;
}
interface Command {
id: string;
order: number;
command: string;
status: 'pending' | 'running' | 'completed' | 'failed';
result?: ExecutionResult;
}
interface ExecutionResult {
command: string;
status: 'success' | 'failed';
exit_code: number;
output?: string;
summary?: { // 提取的关键产物
session?: string;
files?: string[];
timestamp: string;
};
}
```
## 状态转移
```
pending → running → executing → completed
↓ ↓
(abort) (error → abort)
```
## 初始化
```javascript
{
session_id: generateId(),
status: 'pending',
started_at: new Date().toISOString(),
task_description: '', // 从用户输入获取
command_chain: [],
current_command_index: 0,
execution_results: [],
confirmed: false,
error_count: 0
}
```
## 更新
- 添加命令: `command_chain.push(cmd)`
- 确认执行: `confirmed = true, status = 'executing'`
- 记录执行: `execution_results.push(...), current_command_index++`
- 错误计数: `error_count++`

View File

@@ -0,0 +1,66 @@
{
"skill_name": "ccw-coordinator",
"display_name": "CCW Coordinator",
"description": "Interactive command orchestration - select, build, and execute workflow command chains",
"execution_mode": "autonomous",
"version": "1.0.0",
"triggers": [
"coordinator",
"ccw-coordinator",
"命令编排",
"command chain"
],
"allowed_tools": [
"Task",
"AskUserQuestion",
"Read",
"Write",
"Bash"
],
"actions": [
{
"id": "action-init",
"name": "Init",
"description": "Initialize orchestration session"
},
{
"id": "action-command-selection",
"name": "Select Commands",
"description": "Interactive command selection from library"
},
{
"id": "action-command-build",
"name": "Build Chain",
"description": "Adjust and confirm command chain"
},
{
"id": "action-command-execute",
"name": "Execute",
"description": "Execute command chain sequentially"
},
{
"id": "action-complete",
"name": "Complete",
"description": "Generate final report"
},
{
"id": "action-abort",
"name": "Abort",
"description": "Abort session and save state"
}
],
"termination_conditions": [
"user_exit",
"task_completed",
"error"
],
"output": {
"location": ".workflow/.ccw-coordinator/{timestamp}",
"artifacts": [
"state.json",
"command-chain.json",
"execution-log.md",
"final-report.md"
]
}
}

View File

@@ -0,0 +1,169 @@
# Command Library
CCW Coordinator 支持的命令库。基于 CCW workflow 命令系统。
## Command Categories
### Planning Commands
| Command | Description | Level |
|---------|-------------|-------|
| `/workflow:lite-plan` | 轻量级规划 | L2 |
| `/workflow:plan` | 标准规划 | L3 |
| `/workflow:multi-cli-plan` | 多CLI协作规划 | L2 |
| `/workflow:brainstorm:auto-parallel` | 头脑风暴规划 | L4 |
| `/workflow:tdd-plan` | TDD规划 | L3 |
### Execution Commands
| Command | Description | Level |
|---------|-------------|-------|
| `/workflow:lite-execute` | 轻量级执行 | L2 |
| `/workflow:execute` | 标准执行 | L3 |
| `/workflow:test-cycle-execute` | 测试循环执行 | L3 |
### BugFix Commands
| Command | Description | Level |
|---------|-------------|-------|
| `/workflow:lite-fix` | 轻量级修复 | L2 |
| `/workflow:lite-fix --hotfix` | 紧急修复 | L2 |
### Testing Commands
| Command | Description | Level |
|---------|-------------|-------|
| `/workflow:test-gen` | 测试生成 | L3 |
| `/workflow:test-fix-gen` | 测试修复生成 | L3 |
| `/workflow:tdd-verify` | TDD验证 | L3 |
### Review Commands
| Command | Description | Level |
|---------|-------------|-------|
| `/workflow:review-session-cycle` | 会话审查 | L3 |
| `/workflow:review-module-cycle` | 模块审查 | L3 |
| `/workflow:review-fix` | 审查修复 | L3 |
| `/workflow:plan-verify` | 计划验证 | L3 |
### Documentation Commands
| Command | Description | Level |
|---------|-------------|-------|
| `/memory:docs` | 生成文档 | L2 |
| `/memory:update-related` | 更新相关文档 | L2 |
| `/memory:update-full` | 全面更新文档 | L2 |
### Issue Commands
| Command | Description | Level |
|---------|-------------|-------|
| `/issue:discover` | 发现Issue | Supplementary |
| `/issue:discover-by-prompt` | 基于提示发现Issue | Supplementary |
| `/issue:plan --all-pending` | 规划所有待处理Issue | Supplementary |
| `/issue:queue` | 排队Issue | Supplementary |
| `/issue:execute` | 执行Issue | Supplementary |
## Command Chains (Recommended)
### 标准开发流程
```
1. /workflow:lite-plan
2. /workflow:lite-execute
3. /workflow:test-cycle-execute
```
### 完整规划流程
```
1. /workflow:plan
2. /workflow:plan-verify
3. /workflow:execute
4. /workflow:review-session-cycle
```
### TDD 流程
```
1. /workflow:tdd-plan
2. /workflow:execute
3. /workflow:tdd-verify
```
### Issue 批处理流程
```
1. /issue:plan --all-pending
2. /issue:queue
3. /issue:execute
```
## JSON Format
```json
{
"workflow_commands": [
{
"category": "Planning",
"commands": [
{ "name": "/workflow:lite-plan", "description": "轻量级规划" },
{ "name": "/workflow:plan", "description": "标准规划" },
{ "name": "/workflow:multi-cli-plan", "description": "多CLI协作规划" },
{ "name": "/workflow:brainstorm:auto-parallel", "description": "头脑风暴" },
{ "name": "/workflow:tdd-plan", "description": "TDD规划" }
]
},
{
"category": "Execution",
"commands": [
{ "name": "/workflow:lite-execute", "description": "轻量级执行" },
{ "name": "/workflow:execute", "description": "标准执行" },
{ "name": "/workflow:test-cycle-execute", "description": "测试循环执行" }
]
},
{
"category": "BugFix",
"commands": [
{ "name": "/workflow:lite-fix", "description": "轻量级修复" },
{ "name": "/workflow:lite-fix --hotfix", "description": "紧急修复" }
]
},
{
"category": "Testing",
"commands": [
{ "name": "/workflow:test-gen", "description": "测试生成" },
{ "name": "/workflow:test-fix-gen", "description": "测试修复" },
{ "name": "/workflow:tdd-verify", "description": "TDD验证" }
]
},
{
"category": "Review",
"commands": [
{ "name": "/workflow:review-session-cycle", "description": "会话审查" },
{ "name": "/workflow:review-module-cycle", "description": "模块审查" },
{ "name": "/workflow:review-fix", "description": "审查修复" },
{ "name": "/workflow:plan-verify", "description": "计划验证" }
]
},
{
"category": "Documentation",
"commands": [
{ "name": "/memory:docs", "description": "生成文档" },
{ "name": "/memory:update-related", "description": "更新相关文档" },
{ "name": "/memory:update-full", "description": "全面更新文档" }
]
},
{
"category": "Issues",
"commands": [
{ "name": "/issue:discover", "description": "发现Issue" },
{ "name": "/issue:discover-by-prompt", "description": "基于提示发现Issue" },
{ "name": "/issue:plan --all-pending", "description": "规划所有待处理Issue" },
{ "name": "/issue:queue", "description": "排队Issue" },
{ "name": "/issue:execute", "description": "执行Issue" }
]
}
]
}
```

View File

@@ -0,0 +1,362 @@
# CCW Coordinator Specifications
命令库、验证规则和注册表一体化规范。
---
## 命令库
### Planning Commands
| Command | Description | Level |
|---------|-------------|-------|
| `/workflow:lite-plan` | 轻量级规划 | L2 |
| `/workflow:plan` | 标准规划 | L3 |
| `/workflow:multi-cli-plan` | 多CLI协作规划 | L2 |
| `/workflow:brainstorm:auto-parallel` | 头脑风暴规划 | L4 |
| `/workflow:tdd-plan` | TDD规划 | L3 |
### Execution Commands
| Command | Description | Level |
|---------|-------------|-------|
| `/workflow:lite-execute` | 轻量级执行 | L2 |
| `/workflow:execute` | 标准执行 | L3 |
| `/workflow:test-cycle-execute` | 测试循环执行 | L3 |
### BugFix Commands
| Command | Description | Level |
|---------|-------------|-------|
| `/workflow:lite-fix` | 轻量级修复 | L2 |
| `/workflow:lite-fix --hotfix` | 紧急修复 | L2 |
### Testing Commands
| Command | Description | Level |
|---------|-------------|-------|
| `/workflow:test-gen` | 测试生成 | L3 |
| `/workflow:test-fix-gen` | 测试修复生成 | L3 |
| `/workflow:tdd-verify` | TDD验证 | L3 |
### Review Commands
| Command | Description | Level |
|---------|-------------|-------|
| `/workflow:review-session-cycle` | 会话审查 | L3 |
| `/workflow:review-module-cycle` | 模块审查 | L3 |
| `/workflow:review-fix` | 审查修复 | L3 |
| `/workflow:plan-verify` | 计划验证 | L3 |
### Documentation Commands
| Command | Description | Level |
|---------|-------------|-------|
| `/memory:docs` | 生成文档 | L2 |
| `/memory:update-related` | 更新相关文档 | L2 |
| `/memory:update-full` | 全面更新文档 | L2 |
### Issue Commands
| Command | Description |
|---------|-------------|
| `/issue:discover` | 发现Issue |
| `/issue:discover-by-prompt` | 基于提示发现Issue |
| `/issue:plan --all-pending` | 规划所有待处理Issue |
| `/issue:queue` | 排队Issue |
| `/issue:execute` | 执行Issue |
---
## 命令链推荐
### 标准开发流程
```
1. /workflow:lite-plan
2. /workflow:lite-execute
3. /workflow:test-cycle-execute
```
### 完整规划流程
```
1. /workflow:plan
2. /workflow:plan-verify
3. /workflow:execute
4. /workflow:review-session-cycle
```
### TDD 流程
```
1. /workflow:tdd-plan
2. /workflow:execute
3. /workflow:tdd-verify
```
### Issue 批处理流程
```
1. /issue:plan --all-pending
2. /issue:queue
3. /issue:execute
```
---
## 验证规则
### Rule 1: Single Planning Command
每条链最多包含一个规划命令。
| 有效 | 无效 |
|------|------|
| `plan → execute` | `plan → lite-plan → execute` |
### Rule 2: Compatible Pairs
规划和执行命令必须兼容。
| Planning | Execution | 兼容 |
|----------|-----------|------|
| lite-plan | lite-execute | ✓ |
| lite-plan | execute | ✗ |
| multi-cli-plan | lite-execute | ✓ |
| multi-cli-plan | execute | ✓ |
| plan | execute | ✓ |
| plan | lite-execute | ✗ |
| tdd-plan | execute | ✓ |
| tdd-plan | lite-execute | ✗ |
### Rule 3: Testing After Execution
测试命令必须在执行命令之后。
| 有效 | 无效 |
|------|------|
| `execute → test-cycle-execute` | `test-cycle-execute → execute` |
### Rule 4: Review After Execution
审查命令必须在执行命令之后。
| 有效 | 无效 |
|------|------|
| `execute → review-session-cycle` | `review-session-cycle → execute` |
### Rule 5: BugFix Standalone
`lite-fix` 必须单独执行,不能与其他命令组合。
| 有效 | 无效 |
|------|------|
| `lite-fix` | `plan → lite-fix → execute` |
| `lite-fix --hotfix` | `lite-fix → test-cycle-execute` |
### Rule 6: Dependency Satisfaction
每个命令的依赖必须在前面执行。
```javascript
test-fix-gen test-cycle-execute
test-cycle-execute
```
### Rule 7: No Redundancy
链条中不能有重复的命令。
| 有效 | 无效 |
|------|------|
| `plan → execute → test` | `plan → plan → execute` |
### Rule 8: Command Exists
所有命令必须在此规范中定义。
---
## 反模式(避免)
### ❌ Pattern 1: Multiple Planning
```
plan → lite-plan → execute
```
**问题**: 重复分析,浪费时间
**修复**: 选一个规划命令
### ❌ Pattern 2: Test Without Context
```
test-cycle-execute (独立执行)
```
**问题**: 没有执行上下文,无法工作
**修复**: 先执行 `execute``test-fix-gen`
### ❌ Pattern 3: BugFix with Planning
```
plan → execute → lite-fix
```
**问题**: lite-fix 是独立命令,不应与规划混合
**修复**: 用 `lite-fix` 单独修复,或用 `plan → execute` 做大改
### ❌ Pattern 4: Review Without Changes
```
review-session-cycle (独立执行)
```
**问题**: 没有 git 改动可审查
**修复**: 先执行 `execute` 生成改动
### ❌ Pattern 5: TDD Misuse
```
tdd-plan → lite-execute
```
**问题**: lite-execute 无法处理 TDD 任务结构
**修复**: 用 `tdd-plan → execute → tdd-verify`
---
## 命令注册表
### 命令元数据结构
```json
{
"command_name": {
"category": "Planning|Execution|Testing|Review|BugFix|Maintenance",
"level": "L0|L1|L2|L3",
"description": "命令描述",
"inputs": ["input1", "input2"],
"outputs": ["output1", "output2"],
"dependencies": ["依赖命令"],
"parameters": [
{"name": "--flag", "type": "string|boolean|number", "default": "value"}
],
"chain_position": "start|middle|middle_or_end|end|standalone",
"next_recommended": ["推荐的下一个命令"]
}
}
```
### 命令分组
| Group | Commands |
|-------|----------|
| planning | lite-plan, multi-cli-plan, plan, tdd-plan |
| execution | lite-execute, execute, develop-with-file |
| testing | test-gen, test-fix-gen, test-cycle-execute, tdd-verify |
| review | review-session-cycle, review-module-cycle, review-fix |
| bugfix | lite-fix, debug, debug-with-file |
| maintenance | clean, replan |
| verification | plan-verify, tdd-verify |
### 兼容性矩阵
| 组合 | 状态 |
|------|------|
| lite-plan + lite-execute | ✓ compatible |
| lite-plan + execute | ✗ incompatible - use plan |
| multi-cli-plan + lite-execute | ✓ compatible |
| plan + execute | ✓ compatible |
| plan + lite-execute | ✗ incompatible - use lite-plan |
| tdd-plan + execute | ✓ compatible |
| execute + test-cycle-execute | ✓ compatible |
| lite-execute + test-cycle-execute | ✓ compatible |
| test-fix-gen + test-cycle-execute | ✓ required |
| review-session-cycle + review-fix | ✓ compatible |
| lite-fix + test-cycle-execute | ✗ incompatible - lite-fix standalone |
---
## 验证工具
### chain-validate.cjs
位置: `tools/chain-validate.cjs`
验证命令链合法性:
```bash
node tools/chain-validate.cjs plan execute test-cycle-execute
```
输出:
```
{
"valid": true,
"errors": [],
"warnings": []
}
```
## 命令注册表
### 工具位置
位置: `tools/command-registry.cjs` (skill 内置)
### 工作模式
**按需提取**: 只提取用户确定的任务链中的命令,不是全量扫描。
```javascript
// 用户任务链: [lite-plan, lite-execute]
const commandNames = command_chain.map(cmd => cmd.command);
const commandMeta = registry.getCommands(commandNames);
// 只提取这 2 个命令的元数据
```
### 功能
- 自动查找全局 `.claude/commands/workflow` 目录(相对路径 > 用户 home
- 按需提取指定命令的 YAML 头元数据
- 缓存机制避免重复读取
- 提供批量查询接口
### 集成方式
在 action-command-execute 中自动集成:
```javascript
const CommandRegistry = require('./tools/command-registry.cjs');
const registry = new CommandRegistry();
// 只提取任务链中的命令
const commandNames = command_chain.map(cmd => cmd.command);
const commandMeta = registry.getCommands(commandNames);
// 使用元数据生成提示词
const cmdInfo = commandMeta[cmd.command];
// {
// name: 'lite-plan',
// description: '轻量级规划...',
// argumentHint: '[-e|--explore] "task description"',
// allowedTools: [...],
// filePath: '...'
// }
```
### 提示词生成
智能提示词自动包含:
1. **任务上下文**: 用户任务描述
2. **前序产物**: 已完成命令的产物信息
3. **命令元数据**: 命令的参数提示和描述
```
任务: 实现用户注册功能
前序完成:
- /workflow:lite-plan: WFS-plan-001 (IMPL_PLAN.md)
命令: /workflow:lite-execute [--resume-session="session-id"]
```
详见 `tools/README.md`

View File

@@ -0,0 +1,95 @@
# CCW Coordinator Tools
## command-registry.cjs
命令注册表工具:获取和提取命令元数据。
### 功能
- **按需提取**: 只提取指定命令的完整信息name, description, argumentHint, allowedTools 等)
- **全量获取**: 获取所有命令的名称和描述(快速查询)
- **自动查找**: 从全局 `.claude/commands/workflow` 目录读取(项目相对路径 > 用户 home
- **缓存机制**: 避免重复读取文件
### 编程接口
```javascript
const CommandRegistry = require('./tools/command-registry.cjs');
const registry = new CommandRegistry();
// 1. 获取所有命令的名称和描述(快速)
const allCommands = registry.getAllCommandsSummary();
// {
// "/workflow:lite-plan": {
// name: 'lite-plan',
// description: '轻量级规划...'
// },
// "/workflow:lite-execute": { ... }
// }
// 2. 按需提取指定命令的完整信息
const commands = registry.getCommands([
'/workflow:lite-plan',
'/workflow:lite-execute'
]);
// {
// "/workflow:lite-plan": {
// name: 'lite-plan',
// description: '...',
// argumentHint: '[-e|--explore] "task description"',
// allowedTools: [...],
// filePath: '...'
// },
// ...
// }
```
### 命令行接口
```bash
# 获取所有命令的名称和描述
node .claude/skills/ccw-coordinator/tools/command-registry.cjs
node .claude/skills/ccw-coordinator/tools/command-registry.cjs --all
# 输出: 23 个命令的简明列表 (name + description)
```
```bash
# 按需提取指定命令的完整信息
node .claude/skills/ccw-coordinator/tools/command-registry.cjs lite-plan lite-execute
# 输出: 完整信息 (name, description, argumentHint, allowedTools, filePath)
```
### 集成用途
`action-command-execute` 中使用:
```javascript
// 1. 初始化时只提取任务链中的命令(完整信息)
const commandNames = command_chain.map(cmd => cmd.command);
const commandMeta = registry.getCommands(commandNames);
// 2. 生成提示词时使用
function generatePrompt(cmd, state, commandMeta) {
const cmdInfo = commandMeta[cmd.command];
let prompt = `任务: ${state.task_description}\n`;
if (cmdInfo?.argumentHint) {
prompt += `命令: ${cmd.command} ${cmdInfo.argumentHint}`;
}
return prompt;
}
```
确保 `ccw cli -p "..."` 提示词包含准确的命令参数提示。
### 目录查找逻辑
自动查找顺序:
1. `.claude/commands/workflow` (相对于当前工作目录)
2. `~/.claude/commands/workflow` (用户 home 目录)

View File

@@ -0,0 +1,320 @@
#!/usr/bin/env node
/**
* Chain Validation Tool
*
* Validates workflow command chains against defined rules.
*
* Usage:
* node chain-validate.js plan execute test-cycle-execute
* node chain-validate.js --json "plan,execute,test-cycle-execute"
* node chain-validate.js --file custom-chain.json
*/
const fs = require('fs');
const path = require('path');
// Optional registry loading - gracefully degrade if not found
let registry = null;
try {
const registryPath = path.join(__dirname, '..', 'specs', 'chain-registry.json');
if (fs.existsSync(registryPath)) {
registry = JSON.parse(fs.readFileSync(registryPath, 'utf8'));
}
} catch (error) {
// Registry not available - dependency validation will be skipped
}
class ChainValidator {
constructor(registry) {
this.registry = registry;
this.errors = [];
this.warnings = [];
}
validate(chain) {
this.errors = [];
this.warnings = [];
this.validateSinglePlanning(chain);
this.validateCompatiblePairs(chain);
this.validateTestingPosition(chain);
this.validateReviewPosition(chain);
this.validateBugfixStandalone(chain);
this.validateDependencies(chain);
this.validateNoRedundancy(chain);
this.validateCommandExistence(chain);
return {
valid: this.errors.length === 0,
errors: this.errors,
warnings: this.warnings
};
}
validateSinglePlanning(chain) {
const planningCommands = chain.filter(cmd =>
['plan', 'lite-plan', 'multi-cli-plan', 'tdd-plan'].includes(cmd)
);
if (planningCommands.length > 1) {
this.errors.push({
rule: 'Single Planning Command',
message: `Too many planning commands: ${planningCommands.join(', ')}`,
severity: 'error'
});
}
}
validateCompatiblePairs(chain) {
const compatibility = {
'lite-plan': ['lite-execute'],
'multi-cli-plan': ['lite-execute', 'execute'],
'plan': ['execute'],
'tdd-plan': ['execute']
};
const planningCmd = chain.find(cmd =>
['plan', 'lite-plan', 'multi-cli-plan', 'tdd-plan'].includes(cmd)
);
const executionCmd = chain.find(cmd =>
['execute', 'lite-execute'].includes(cmd)
);
if (planningCmd && executionCmd) {
const compatible = compatibility[planningCmd] || [];
if (!compatible.includes(executionCmd)) {
this.errors.push({
rule: 'Compatible Pairs',
message: `${planningCmd} incompatible with ${executionCmd}`,
fix: `Use ${planningCmd} with ${compatible.join(' or ')}`,
severity: 'error'
});
}
}
}
validateTestingPosition(chain) {
const executionIdx = chain.findIndex(cmd =>
['execute', 'lite-execute', 'develop-with-file'].includes(cmd)
);
const testingIdx = chain.findIndex(cmd =>
['test-cycle-execute', 'tdd-verify', 'test-gen', 'test-fix-gen'].includes(cmd)
);
if (testingIdx !== -1 && executionIdx !== -1 && executionIdx > testingIdx) {
this.errors.push({
rule: 'Testing After Execution',
message: 'Testing commands must come after execution',
severity: 'error'
});
}
if (testingIdx !== -1 && executionIdx === -1) {
const hasTestGen = chain.some(cmd => ['test-gen', 'test-fix-gen'].includes(cmd));
if (!hasTestGen) {
this.warnings.push({
rule: 'Testing After Execution',
message: 'test-cycle-execute without execution context - needs test-gen or execute first',
severity: 'warning'
});
}
}
}
validateReviewPosition(chain) {
const executionIdx = chain.findIndex(cmd =>
['execute', 'lite-execute'].includes(cmd)
);
const reviewIdx = chain.findIndex(cmd =>
cmd.includes('review')
);
if (reviewIdx !== -1 && executionIdx !== -1 && executionIdx > reviewIdx) {
this.errors.push({
rule: 'Review After Changes',
message: 'Review commands must come after execution',
severity: 'error'
});
}
if (reviewIdx !== -1 && executionIdx === -1) {
const isModuleReview = chain[reviewIdx] === 'review-module-cycle';
if (!isModuleReview) {
this.warnings.push({
rule: 'Review After Changes',
message: 'Review without execution - needs git changes to review',
severity: 'warning'
});
}
}
}
validateBugfixStandalone(chain) {
if (chain.includes('lite-fix')) {
const others = chain.filter(cmd => cmd !== 'lite-fix');
if (others.length > 0) {
this.errors.push({
rule: 'BugFix Standalone',
message: 'lite-fix must be standalone, cannot combine with other commands',
fix: 'Use lite-fix alone OR use plan + execute for larger changes',
severity: 'error'
});
}
}
}
validateDependencies(chain) {
// Skip if registry not available
if (!this.registry || !this.registry.commands) {
return;
}
for (let i = 0; i < chain.length; i++) {
const cmd = chain[i];
const cmdMeta = this.registry.commands[cmd];
if (!cmdMeta) continue;
const deps = cmdMeta.dependencies || [];
const depsOptional = cmdMeta.dependencies_optional || false;
if (deps.length > 0 && !depsOptional) {
const hasDependency = deps.some(dep => {
const depIdx = chain.indexOf(dep);
return depIdx !== -1 && depIdx < i;
});
if (!hasDependency) {
this.errors.push({
rule: 'Dependency Satisfaction',
message: `${cmd} requires ${deps.join(' or ')} before it`,
severity: 'error'
});
}
}
}
}
validateNoRedundancy(chain) {
const seen = new Set();
const duplicates = [];
for (const cmd of chain) {
if (seen.has(cmd)) {
duplicates.push(cmd);
}
seen.add(cmd);
}
if (duplicates.length > 0) {
this.errors.push({
rule: 'No Redundant Commands',
message: `Duplicate commands: ${duplicates.join(', ')}`,
severity: 'error'
});
}
}
validateCommandExistence(chain) {
// Skip if registry not available
if (!this.registry || !this.registry.commands) {
return;
}
for (const cmd of chain) {
if (!this.registry.commands[cmd]) {
this.errors.push({
rule: 'Command Existence',
message: `Unknown command: ${cmd}`,
severity: 'error'
});
}
}
}
}
function main() {
const args = process.argv.slice(2);
if (args.length === 0) {
console.log('Usage:');
console.log(' chain-validate.js <command1> <command2> ...');
console.log(' chain-validate.js --json "cmd1,cmd2,cmd3"');
console.log(' chain-validate.js --file chain.json');
process.exit(1);
}
let chain;
if (args[0] === '--json') {
chain = args[1].split(',').map(s => s.trim());
} else if (args[0] === '--file') {
const filePath = args[1];
// SEC-001: 路径遍历验证 - 只允许访问工作目录下的文件
const resolvedPath = path.resolve(filePath);
const workDir = path.resolve('.');
if (!resolvedPath.startsWith(workDir)) {
console.error('Error: File path must be within current working directory');
process.exit(1);
}
// CORR-001: JSON 解析错误处理
let fileContent;
try {
fileContent = JSON.parse(fs.readFileSync(resolvedPath, 'utf8'));
} catch (error) {
console.error(`Error: Failed to parse JSON file ${filePath}: ${error.message}`);
process.exit(1);
}
// CORR-002: 嵌套属性 null 检查
chain = fileContent.chain || fileContent.steps?.map(s => s.command) || [];
if (chain.length === 0) {
console.error('Error: No valid chain found in file (expected "chain" array or "steps" with "command" fields)');
process.exit(1);
}
} else {
chain = args;
}
const validator = new ChainValidator(registry);
const result = validator.validate(chain);
console.log('\n=== Chain Validation Report ===\n');
console.log('Chain:', chain.join(' → '));
console.log('');
if (result.valid) {
console.log('✓ Chain is valid!\n');
} else {
console.log('✗ Chain has errors:\n');
result.errors.forEach(err => {
console.log(` [${err.rule}] ${err.message}`);
if (err.fix) {
console.log(` Fix: ${err.fix}`);
}
});
console.log('');
}
if (result.warnings.length > 0) {
console.log('⚠ Warnings:\n');
result.warnings.forEach(warn => {
console.log(` [${warn.rule}] ${warn.message}`);
});
console.log('');
}
process.exit(result.valid ? 0 : 1);
}
if (require.main === module) {
main();
}
module.exports = { ChainValidator };

View File

@@ -0,0 +1,255 @@
#!/usr/bin/env node
/**
* Command Registry Tool
*
* 功能:
* 1. 根据命令名称查找并提取 YAML 头
* 2. 从全局 .claude/commands/workflow 目录读取
* 3. 支持按需提取(不是全量扫描)
*/
const fs = require('fs');
const path = require('path');
const os = require('os');
class CommandRegistry {
constructor(commandDir = null) {
// 优先使用传入的目录
if (commandDir) {
this.commandDir = commandDir;
} else {
// 自动查找 .claude/commands/workflow
this.commandDir = this.findCommandDir();
}
this.cache = {};
}
/**
* 自动查找 .claude/commands/workflow 目录
* 支持: 项目相对路径、用户 home 目录
*/
findCommandDir() {
// 1. 尝试相对于当前工作目录
const relativePath = path.join('.claude', 'commands', 'workflow');
if (fs.existsSync(relativePath)) {
return path.resolve(relativePath);
}
// 2. 尝试用户 home 目录
const homeDir = os.homedir();
const homeCommandDir = path.join(homeDir, '.claude', 'commands', 'workflow');
if (fs.existsSync(homeCommandDir)) {
return homeCommandDir;
}
// 未找到时返回 null后续操作会失败并提示
return null;
}
/**
* 解析 YAML 头 (简化版本)
*
* 限制:
* - 只支持简单的 key: value 对 (单行值)
* - 不支持多行值、嵌套对象、复杂列表
* - allowed-tools 字段支持逗号分隔的字符串,自动转为数组
*
* 示例:
* ---
* name: lite-plan
* description: "Lightweight planning workflow"
* allowed-tools: Read, Write, Bash
* ---
*/
parseYamlHeader(content) {
// 处理 Windows 行结尾 (\r\n)
const match = content.match(/^---[\r\n]+([\s\S]*?)[\r\n]+---/);
if (!match) return null;
const yamlContent = match[1];
const result = {};
try {
const lines = yamlContent.split(/[\r\n]+/);
for (const line of lines) {
const trimmed = line.trim();
if (!trimmed || trimmed.startsWith('#')) continue; // 跳过空行和注释
const colonIndex = trimmed.indexOf(':');
if (colonIndex === -1) continue;
const key = trimmed.substring(0, colonIndex).trim();
const value = trimmed.substring(colonIndex + 1).trim();
if (!key) continue; // 跳过无效行
// 去除引号 (单引号或双引号)
let cleanValue = value.replace(/^["']|["']$/g, '');
// allowed-tools 字段特殊处理:转为数组
// 支持格式: "Read, Write, Bash" 或 "Read,Write,Bash"
if (key === 'allowed-tools') {
cleanValue = Array.isArray(cleanValue)
? cleanValue
: cleanValue.split(',').map(t => t.trim()).filter(t => t);
}
result[key] = cleanValue;
}
} catch (error) {
console.error('YAML parsing error:', error.message);
return null;
}
return result;
}
/**
* 获取单个命令的元数据
* @param {string} commandName 命令名称 (e.g., "lite-plan" 或 "/workflow:lite-plan")
* @returns {object|null} 命令信息或 null
*/
getCommand(commandName) {
if (!this.commandDir) {
console.error('ERROR: .claude/commands/workflow 目录未找到');
return null;
}
// 标准化命令名称
const normalized = commandName.startsWith('/workflow:')
? commandName.substring('/workflow:'.length)
: commandName;
// 检查缓存
if (this.cache[normalized]) {
return this.cache[normalized];
}
// 读取命令文件
const filePath = path.join(this.commandDir, `${normalized}.md`);
if (!fs.existsSync(filePath)) {
return null;
}
try {
const content = fs.readFileSync(filePath, 'utf-8');
const header = this.parseYamlHeader(content);
if (header && header.name) {
const result = {
name: header.name,
command: `/workflow:${header.name}`,
description: header.description || '',
argumentHint: header['argument-hint'] || '',
allowedTools: Array.isArray(header['allowed-tools'])
? header['allowed-tools']
: (header['allowed-tools'] ? [header['allowed-tools']] : []),
filePath: filePath
};
// 缓存结果
this.cache[normalized] = result;
return result;
}
} catch (error) {
console.error(`读取命令失败 ${filePath}:`, error.message);
}
return null;
}
/**
* 批量获取多个命令的元数据
* @param {array} commandNames 命令名称数组
* @returns {object} 命令信息映射
*/
getCommands(commandNames) {
const result = {};
for (const name of commandNames) {
const cmd = this.getCommand(name);
if (cmd) {
result[cmd.command] = cmd;
}
}
return result;
}
/**
* 获取所有命令的名称和描述
* @returns {object} 命令名称和描述的映射
*/
getAllCommandsSummary() {
const result = {};
const commandDir = this.commandDir;
if (!commandDir) {
return result;
}
try {
const files = fs.readdirSync(commandDir);
for (const file of files) {
if (!file.endsWith('.md')) continue;
const filePath = path.join(commandDir, file);
const stat = fs.statSync(filePath);
if (stat.isDirectory()) continue;
try {
const content = fs.readFileSync(filePath, 'utf-8');
const header = this.parseYamlHeader(content);
if (header && header.name) {
const commandName = `/workflow:${header.name}`;
result[commandName] = {
name: header.name,
description: header.description || ''
};
}
} catch (error) {
// 跳过读取失败的文件
continue;
}
}
} catch (error) {
// 目录读取失败
return result;
}
return result;
}
/**
* 生成注册表 JSON
*/
toJSON(commands = null) {
const data = commands || this.cache;
return JSON.stringify(data, null, 2);
}
}
// CLI 模式
if (require.main === module) {
const args = process.argv.slice(2);
if (args.length === 0 || args[0] === '--all') {
// 获取所有命令的名称和描述
const registry = new CommandRegistry();
const commands = registry.getAllCommandsSummary();
console.log(JSON.stringify(commands, null, 2));
process.exit(0);
}
const registry = new CommandRegistry();
const commands = registry.getCommands(args);
console.log(JSON.stringify(commands, null, 2));
}
module.exports = CommandRegistry;

View File

@@ -15,7 +15,7 @@
"/workflow:review-session-cycle",
"/memory:docs",
"/workflow:brainstorm:artifacts",
"/workflow:action-plan-verify",
"/workflow:plan-verify",
"/version"
],
@@ -69,7 +69,7 @@
"difficulty": "Intermediate",
"essential": true,
"flow": {
"next_steps": ["/workflow:action-plan-verify", "/workflow:execute"],
"next_steps": ["/workflow:plan-verify", "/workflow:execute"],
"alternatives": ["/workflow:tdd-plan"]
},
"source": "../../../commands/workflow/plan.md"
@@ -89,8 +89,8 @@
"source": "../../../commands/workflow/execute.md"
},
{
"name": "action-plan-verify",
"command": "/workflow:action-plan-verify",
"name": "plan-verify",
"command": "/workflow:plan-verify",
"description": "Cross-artifact consistency analysis",
"arguments": "[--session session-id]",
"category": "workflow",
@@ -100,7 +100,7 @@
"prerequisites": ["/workflow:plan"],
"next_steps": ["/workflow:execute"]
},
"source": "../../../commands/workflow/action-plan-verify.md"
"source": "../../../commands/workflow/plan-verify.md"
},
{
"name": "init",

View File

@@ -144,7 +144,7 @@ def build_command_relationships() -> Dict[str, Any]:
return {
"workflow:plan": {
"calls_internally": ["workflow:session:start", "workflow:tools:context-gather", "workflow:tools:conflict-resolution", "workflow:tools:task-generate-agent"],
"next_steps": ["workflow:action-plan-verify", "workflow:status", "workflow:execute"],
"next_steps": ["workflow:plan-verify", "workflow:status", "workflow:execute"],
"alternatives": ["workflow:tdd-plan"],
"prerequisites": []
},
@@ -159,7 +159,7 @@ def build_command_relationships() -> Dict[str, Any]:
"related": ["workflow:status", "workflow:resume"],
"next_steps": ["workflow:review", "workflow:tdd-verify"]
},
"workflow:action-plan-verify": {
"workflow:plan-verify": {
"prerequisites": ["workflow:plan"],
"next_steps": ["workflow:execute"],
"related": ["workflow:status"]
@@ -217,7 +217,7 @@ def identify_essential_commands(all_commands: List[Dict]) -> List[Dict]:
"workflow:execute", "workflow:status", "workflow:session:start",
"workflow:review-session-cycle", "cli:analyze", "cli:chat",
"memory:docs", "workflow:brainstorm:artifacts",
"workflow:action-plan-verify", "workflow:resume", "version"
"workflow:plan-verify", "workflow:resume", "version"
]
essential = []

View File

@@ -22,7 +22,7 @@
},
"verify": {
"description": "Plan and quality verification",
"commands": ["/workflow:action-plan-verify", "/workflow:tdd-verify"]
"commands": ["/workflow:plan-verify", "/workflow:tdd-verify"]
},
"execute": {
"description": "Task execution and implementation",
@@ -152,7 +152,7 @@
"artifacts": ".workflow/active/{session}/",
"steps": [
{ "command": "/workflow:plan", "optional": false },
{ "command": "/workflow:action-plan-verify", "optional": false, "auto_continue": true },
{ "command": "/workflow:plan-verify", "optional": false, "auto_continue": true },
{ "command": "/workflow:execute", "optional": false },
{ "command": "/workflow:review", "optional": true }
],
@@ -171,7 +171,7 @@
"steps": [
{ "command": "/workflow:brainstorm:auto-parallel", "optional": false, "confirm_before": true },
{ "command": "/workflow:plan", "optional": false },
{ "command": "/workflow:action-plan-verify", "optional": true, "auto_continue": true },
{ "command": "/workflow:plan-verify", "optional": true, "auto_continue": true },
{ "command": "/workflow:execute", "optional": false }
],
"cli_hints": {
@@ -244,7 +244,7 @@
"artifacts": ".workflow/active/{session}/",
"steps": [
{ "command": "/workflow:tdd-plan", "optional": false },
{ "command": "/workflow:action-plan-verify", "optional": true, "auto_continue": true },
{ "command": "/workflow:plan-verify", "optional": true, "auto_continue": true },
{ "command": "/workflow:execute", "optional": false },
{ "command": "/workflow:tdd-verify", "optional": false }
],

View File

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

View File

@@ -7,7 +7,7 @@ Multi-agent parallel development cycle using Codex subagent pattern with continu
This skill implements a **single-file-per-agent** development workflow:
- **RA**: `requirements.md` (all requirements + edge cases + history)
- **EP**: `plan.md` (architecture + tasks + integration points)
- **EP**: `exploration.md`, `architecture.md`, `plan.json` (codebase exploration + architecture + structured tasks)
- **CD**: `implementation.md` (progress + files + decisions + testing)
- **VAS**: `summary.md` (validation + test results + recommendations)
@@ -49,7 +49,9 @@ Creates:
│ ├── requirements.md (v1.0.0)
│ └── changes.log (NDJSON)
├── ep/
│ ├── plan.md (v1.0.0)
│ ├── exploration.md (v1.0.0)
│ ├── architecture.md (v1.0.0)
│ ├── plan.json (v1.0.0)
│ └── changes.log (NDJSON)
├── cd/
│ ├── implementation.md (v1.0.0)
@@ -113,20 +115,19 @@ When iteration completes, next extends to v1.1.0:
```
Current State (v1.0.0)
├── requirements.md (v1.0.0)
├── plan.md (v1.0.0)
├── plan.json (v1.0.0)
├── implementation.md (v1.0.0)
└── summary.md (v1.0.0)
User: "Add GitHub provider"
Archive Old Write New
├── history/requirements-v1.0.0.md
├── history/plan-v1.0.0.md → requirements.md (v1.1.0) - REWRITTEN
├── history/impl-v1.0.0.md → plan.md (v1.1.0) - REWRITTEN
└── history/summary-v1.0.0.md → implementation.md (v1.1.0) - REWRITTEN
→ summary.md (v1.1.0) - REWRITTEN
Append to changes.log (NDJSON)
├── history/requirements-v1.0.0.md → requirements.md (v1.1.0) - REWRITTEN
├── history/plan-v1.0.0.json → plan.json (v1.1.0) - REWRITTEN
├── history/impl-v1.0.0.md → implementation.md (v1.1.0) - REWRITTEN
└── history/summary-v1.0.0.md → summary.md (v1.1.0) - REWRITTEN
Append to changes.log (NDJSON)
```
## Session Files
@@ -142,11 +143,13 @@ ra/ - Requirements Analyst
└── requirements-v1.1.0.md
ep/ - Exploration & Planning
├── plan.md # v1.2.0 (current)
├── exploration.md # v1.2.0 (codebase exploration)
├── architecture.md # v1.2.0 (architecture design)
├── plan.json # v1.2.0 (structured task list, current)
├── changes.log # NDJSON audit trail
└── history/
├── plan-v1.0.0.md
└── plan-v1.1.0.md
├── plan-v1.0.0.json
└── plan-v1.1.0.json
cd/ - Code Developer
├── implementation.md # v1.2.0 (current)
@@ -203,7 +206,7 @@ vas/ - Validation & Archival
| Agent | File | Contains | Size |
|-------|------|----------|------|
| **RA** | requirements.md | All FR, NFR, edge cases, history summary | ~2-5KB |
| **EP** | plan.md | Architecture, all tasks, critical path, history | ~3-8KB |
| **EP** | exploration.md + architecture.md + plan.json | Codebase exploration, architecture design, structured task list | ~5-10KB total |
| **CD** | implementation.md | Completed tasks, files changed, decisions, tests | ~4-10KB |
| **VAS** | summary.md | Test results, coverage, issues, recommendations | ~5-12KB |
@@ -362,14 +365,14 @@ Orchestrator (main coordinator)
All write to:
- requirements.md (v1.x.0)
- plan.md (v1.x.0)
- exploration.md, architecture.md, plan.json (v1.x.0)
- implementation.md (v1.x.0)
- summary.md (v1.x.0)
- changes.log (NDJSON append)
[Automatic archival]
- history/requirements-v1.{x-1}.0.md
- history/plan-v1.{x-1}.0.md
- history/plan-v1.{x-1}.0.json
- etc...
Orchestrator: Next iteration?

View File

@@ -1,25 +1,26 @@
---
name: Parallel Dev Cycle
description: Multi-agent parallel development cycle with requirement analysis, exploration planning, code development, and validation. Supports continuous iteration with markdown progress documentation.
argument-hint: TASK="<task description>" [--cycle-id=<id>] [--auto] [--parallel=<count>]
argument-hint: TASK="<task description>" | --cycle-id=<id> [--extend="<extension>"] [--auto] [--parallel=<count>]
---
# Parallel Dev Cycle - Multi-Agent Development Workflow
Multi-agent parallel development cycle using Codex subagent pattern with four specialized workers:
1. **Requirements Analysis & Extension** (RA) - 需求分析及扩展
2. **Exploration & Planning** (EP) - 探索规划
3. **Code Development** (CD) - 代码开发
4. **Validation & Archival Summary** (VAS) - 验证及归档总结
1. **Requirements Analysis & Extension** (RA) - Requirement analysis and self-enhancement
2. **Exploration & Planning** (EP) - Exploration and planning
3. **Code Development** (CD) - Code development with debug strategy support
4. **Validation & Archival Summary** (VAS) - Validation and archival summary
每个 agent **仅维护一个主文档文件**,支持版本化、自动归档、完整历史追溯。
Each agent **maintains one main document** (e.g., requirements.md, plan.json, implementation.md) that is completely rewritten per iteration, plus auxiliary logs (changes.log, debug-log.ndjson) that are append-only. Supports versioning, automatic archival, and complete history tracking.
## Arguments
| Arg | Required | Description |
|-----|----------|-------------|
| TASK | No | Task description (for new cycle, mutually exclusive with --cycle-id) |
| --cycle-id | No | Existing cycle ID to continue (from API or previous session) |
| TASK | One of TASK or --cycle-id | Task description (for new cycle, mutually exclusive with --cycle-id) |
| --cycle-id | One of TASK or --cycle-id | Existing cycle ID to continue (from API or previous session) |
| --extend | No | Extension description (only valid with --cycle-id) |
| --auto | No | Auto-cycle mode (run all phases sequentially) |
| --parallel | No | Number of parallel agents (default: 4, max: 4) |
@@ -61,12 +62,13 @@ Multi-agent parallel development cycle using Codex subagent pattern with four sp
## Key Design Principles
1. **Single File Per Agent**: 每个 agent 仅维护一个主文件(精简清晰)
2. **Version-Based Overwrite**: 每个版本完全重写主文件
3. **Automatic Archival**: 旧版本自动归档到 `history/` 目录
4. **Complete Audit Trail**: Changes.log (NDJSON) 保留所有变更历史
5. **Parallel Execution**: 四个 agent 同时工作,无需等待
6. **File References**: 使用简短文件路径而非内容传递
1. **Main Document + Auxiliary Logs**: Each agent maintains one main document (rewritten per iteration) and auxiliary logs (append-only)
2. **Version-Based Overwrite**: Main documents completely rewritten per version; logs append-only
3. **Automatic Archival**: Old main document versions automatically archived to `history/` directory
4. **Complete Audit Trail**: Changes.log (NDJSON) preserves all change history
5. **Parallel Coordination**: Four agents launched simultaneously; coordination via shared state and orchestrator
6. **File References**: Use short file paths instead of content passing
7. **Self-Enhancement**: RA agent proactively extends requirements based on context
## Session Structure
@@ -75,439 +77,118 @@ Multi-agent parallel development cycle using Codex subagent pattern with four sp
+-- {cycleId}.json # Master state file
+-- {cycleId}.progress/
+-- ra/
| +-- requirements.md # v1.2.0 (当前,完全重写)
| +-- changes.log # NDJSON 完整历史(append-only
| +-- requirements.md # Current version (complete rewrite)
| +-- changes.log # NDJSON complete history (append-only)
| └-- history/
| +-- requirements-v1.0.0.md # 归档快照
| +-- requirements-v1.1.0.md # 归档快照
| +-- requirements-v1.0.0.md # Archived snapshot
| +-- requirements-v1.1.0.md # Archived snapshot
+-- ep/
| +-- plan.md # v1.2.0 (当前)
| +-- changes.log # NDJSON 完整历史
| +-- exploration.md # Codebase exploration report
| +-- architecture.md # Architecture design
| +-- plan.json # Structured task list (current version)
| +-- changes.log # NDJSON complete history
| └-- history/
| +-- plan-v1.0.0.md
| +-- plan-v1.1.0.md
| +-- plan-v1.0.0.json
| +-- plan-v1.1.0.json
+-- cd/
| +-- implementation.md # v1.2.0 (当前)
| +-- changes.log # NDJSON 完整历史
| +-- implementation.md # Current version
| +-- debug-log.ndjson # Debug hypothesis tracking
| +-- changes.log # NDJSON complete history
| └-- history/
| +-- implementation-v1.0.0.md
| +-- implementation-v1.1.0.md
+-- vas/
| +-- summary.md # v1.2.0 (当前)
| +-- changes.log # NDJSON 完整历史
| +-- summary.md # Current version
| +-- changes.log # NDJSON complete history
| └-- history/
| +-- summary-v1.0.0.md
| +-- summary-v1.1.0.md
└-- coordination/
+-- timeline.md # 执行时间线
+-- decisions.log # 决策日志
+-- timeline.md # Execution timeline
+-- decisions.log # Decision log
```
## State Management
### Unified Cycle State
State schema is defined in [phases/state-schema.md](phases/state-schema.md). The master state file (`{cycleId}.json`) tracks:
```json
{
"cycle_id": "cycle-v1-20260122-abc123",
"title": "Task title",
"status": "running",
"current_iteration": 2,
"current_phase": "cd",
"agents": {
"ra": {
"status": "completed",
"version": "1.2.0",
"output_file": ".workflow/.cycle/cycle-v1-xxx.progress/ra/requirements.md",
"summary": { "requirements": 10, "edge_cases": 5 }
},
"ep": {
"status": "completed",
"version": "1.2.0",
"output_file": ".workflow/.cycle/cycle-v1-xxx.progress/ep/plan.md",
"summary": { "tasks": 8, "critical_path": 4 }
},
"cd": {
"status": "running",
"version": "1.1.0",
"output_file": ".workflow/.cycle/cycle-v1-xxx.progress/cd/implementation.md",
"summary": { "completed_tasks": 3, "files_modified": 5 }
},
"vas": {
"status": "idle",
"version": "0.0.0",
"output_file": null
}
}
}
```
## Agent Output Format
### RA: requirements.md (单文件完整输出)
```markdown
# Requirements Specification - v1.2.0
## Document Status
| Field | Value |
|-------|-------|
| **Version** | 1.2.0 |
| **Previous Version** | 1.1.0 (Added Google OAuth) |
| **This Version** | Added MFA support, GitHub provider |
| **Iteration** | 3 |
| **Updated** | 2026-01-23T10:00:00+08:00 |
---
## Functional Requirements
- FR-001: OAuth authentication via Google/GitHub (v1.0.0, enhanced v1.1.0-1.2.0)
- FR-002: Multi-provider support (v1.1.0)
- FR-003: MFA/TOTP support (NEW v1.2.0)
## Non-Functional Requirements
- NFR-001: Response time < 500ms
- NFR-002: Support 1000 concurrent users
## Edge Cases
- EC-001: OAuth timeout → Fallback retry
- EC-002: Invalid TOTP → Max 3 attempts (NEW v1.2.0)
## Success Criteria
- [ ] All FRs implemented
- [ ] NFRs validated
- [ ] Coverage > 80%
---
## History Summary
| Version | Date | Summary |
|---------|------|---------|
| 1.0.0 | 2026-01-22 | Initial OAuth |
| 1.1.0 | 2026-01-22 | + Google OAuth |
| 1.2.0 | 2026-01-23 | + GitHub, + MFA (current) |
For detailed history, see `history/` and `changes.log`
```
### EP: plan.md (单文件完整输出)
```markdown
# Implementation Plan - v1.2.0
## Plan Status
| Field | Value |
|-------|-------|
| **Version** | 1.2.0 |
| **Previous** | 1.1.0 (Added GitHub integration) |
| **This Version** | Added MFA tasks (current) |
| **Total Tasks** | 10 |
| **Estimated Hours** | 20 |
---
## Architecture Highlights
- OAuth: passport-oauth2 library
- Providers: Google, GitHub
- Providers: Store in User.oauth_id, oauth_provider
- MFA: TOTP-based (NEW v1.2.0)
---
## Implementation Tasks
### Phase 1: Foundation (TASK-001-003)
- TASK-001: Setup OAuth config (1h, small)
- TASK-002: Update User model (2h, medium)
- TASK-003: Google OAuth strategy (4h, large)
### Phase 2: Multi-Provider (TASK-004-005)
- TASK-004: GitHub OAuth strategy (3h, medium) [NEW v1.2.0]
- TASK-005: Provider selection UI (2h, medium)
### Phase 3: MFA (TASK-006-008) [NEW v1.2.0]
- TASK-006: TOTP setup endpoint (3h, medium)
- TASK-007: TOTP verification (2h, medium)
- TASK-008: Recovery codes (1h, small)
### Phase 4: Testing & Docs (TASK-009-010)
- TASK-009: Integration tests (4h, large)
- TASK-010: Documentation (2h, medium)
---
## Critical Path
1. TASK-001 → TASK-002 → TASK-003 → TASK-005
2. TASK-006 → TASK-007 → TASK-008 → TASK-009
---
## Integration Points
- Location: src/middleware/auth.ts
- Database: User table oauth_* columns
- Frontend: login.tsx OAuth buttons
---
## History Summary
| Version | Date | Summary |
|---------|------|---------|
| 1.0.0 | 2026-01-22 | Basic OAuth plan |
| 1.1.0 | 2026-01-22 | + GitHub task |
| 1.2.0 | 2026-01-23 | + MFA tasks (current) |
```
### CD: implementation.md (单文件完整输出)
```markdown
# Implementation Progress - v1.1.0
## Progress Status
| Field | Value |
|-------|-------|
| **Version** | 1.1.0 |
| **Previous** | 1.0.0 (Initial OAuth) |
| **This Version** | GitHub OAuth support (current) |
| **Iteration** | 2 |
| **Updated** | 2026-01-23T09:30:00+08:00 |
---
## Completed Tasks
- ✓ TASK-001: Setup OAuth config (1h)
- ✓ TASK-002: Update User model (2h)
- ✓ TASK-003: Google OAuth strategy (4h)
- ✓ TASK-004: GitHub OAuth strategy (3h) [NEW v1.1.0]
## In Progress
- 🔄 TASK-005: Provider selection UI (50% complete)
## Next Tasks
- ☐ TASK-006: TOTP setup (v1.2.0)
- ☐ Tests & documentation
---
## Files Modified
| File | Action | Description |
|------|--------|-------------|
| src/config/oauth.ts | create | OAuth config (45 lines) |
| src/strategies/oauth-google.ts | create | Google strategy (120 lines) |
| src/strategies/oauth-github.ts | create | GitHub strategy (100 lines) [NEW v1.1.0] |
| src/models/User.ts | modify | +oauth_id, oauth_provider (8 lines) |
| src/routes/auth.ts | modify | +/auth/google, /auth/github (+75 lines) |
---
## Key Decisions Made
1. **OAuth Library**: passport-oauth2 (mature, well-maintained)
2. **Token Storage**: Database (for refresh tokens)
3. **Provider Selection**: Buttons on login page
---
## Issues & Blockers
### Current
- None
### Resolved (v1.0.0 → v1.1.0)
- ✓ OAuth callback URL validation (fixed)
- ✓ CORS issues (headers updated)
---
## Testing Status
| Test Type | v1.0.0 | v1.1.0 |
|-----------|--------|--------|
| Unit | 20/20 ✓ | 25/25 ✓ |
| Integration | 8/10 ⚠ | 12/14 ⚠ |
| E2E | 3/5 ⚠ | 5/8 ⚠ |
---
## History Summary
| Version | Date | Summary |
|---------|------|---------|
| 1.0.0 | 2026-01-22 | Google OAuth implementation |
| 1.1.0 | 2026-01-23 | + GitHub OAuth (current) |
```
### VAS: summary.md (单文件完整输出)
```markdown
# Validation & Summary Report - v1.0.0
## Validation Status
| Metric | Value | Target | Status |
|--------|-------|--------|--------|
| **Test Pass Rate** | 92% | 90% | ✓ |
| **Code Coverage** | 87% | 80% | ✓ |
| **Requirements Met** | 3/3 | 100% | ✓ |
| **Critical Issues** | 0 | 0 | ✓ |
| **Production Ready** | YES | - | ✓ |
---
## Test Execution Results
- **Total Tests**: 50
- **Passed**: 46 (92%)
- **Failed**: 4 (8%)
- **Duration**: 2m 34s
### Failures
1. **oauth-refresh**: Expected token refresh, got error
- Severity: Medium
- Recommendation: Handle expired refresh tokens (v1.1.0 task)
2. **concurrent-login**: Race condition in session writes
- Severity: High
- Recommendation: Add mutex for session writes (v1.1.0 task)
3. **github-provider**: Timeout on provider response
- Severity: Medium
- Recommendation: Add retry logic with backoff
4. **totp-edge-case**: Invalid TOTP timing window
- Severity: Low
- Recommendation: Expand timing window by ±30s
---
## Code Coverage Analysis
- **Overall**: 87% (target: 80%) ✓
- **OAuth Module**: 95%
- **Routes**: 82%
- **User Model**: 78%
### Gaps
- Error recovery paths (15% uncovered)
- Concurrent request handling (20% uncovered)
---
## Requirements Verification
- ✓ FR-001: OAuth authentication (100% implemented)
- ✓ FR-002: Multi-provider support (Google: 100%, GitHub: 95%)
- ⚠ FR-003: MFA support (0% - planned v1.2.0)
- ✓ NFR-001: Response time < 500ms (avg 245ms)
- ✓ NFR-002: Handle 100 concurrent (sustained 120)
---
## Known Issues Summary
1. **MEDIUM**: OAuth refresh token edge case
- Impact: Users may need re-auth
- Status: Will fix in v1.1.0
2. **MEDIUM**: GitHub provider timeout
- Impact: Occasional login failures
- Status: Will fix in v1.1.0
---
## Deliverables Checklist
- ✓ Code implementation complete
- ✓ Unit tests written (20/20)
- ✓ Integration tests written (12/14)
- ✓ Documentation updated
- ✓ Security review: PASSED
- ✓ Performance benchmarks: MET
---
## Recommendations
1. **For v1.1.0**: Fix refresh token and concurrent login issues
2. **For v1.2.0**: Implement MFA/TOTP support
3. **For v1.3.0**: Add provider error recovery
4. **General**: Increase timeout tolerances
---
## Sign-Off
- **Status**: ✓ APPROVED FOR PRODUCTION
- **Validating Agent**: VAS-v1.0.0
- **Timestamp**: 2026-01-22T12:00:00+08:00
- **By**: Validation & Archival Specialist
---
## History Summary
| Version | Date | Summary |
|---------|------|---------|
| 1.0.0 | 2026-01-22 | Initial validation report (current) |
```
- Cycle metadata (id, title, status, iterations)
- Agent states (status, output files, version)
- Shared context (requirements, plan, changes, test results)
- Coordination data (feedback log, decisions, blockers)
## Versioning Workflow
### 初始版本 (v1.0.0)
### Initial Version (v1.0.0)
```bash
/parallel-dev-cycle TASK="Implement OAuth login"
```
生成:
Generates:
```
requirements.md (v1.0.0)
plan.md (v1.0.0)
implementation.md (v1.0.0) - 如适用
summary.md (v1.0.0) - 如适用
exploration.md (v1.0.0)
architecture.md (v1.0.0)
plan.json (v1.0.0)
implementation.md (v1.0.0) - if applicable
summary.md (v1.0.0) - if applicable
```
### 迭代版本 (v1.1.0, v1.2.0)
### Iteration Versions (v1.1.0, v1.2.0)
```bash
/parallel-dev-cycle --cycle-id=cycle-v1-xxx --extend="Add GitHub support"
```
**自动处理**
1. 读取当前 `requirements.md (v1.0.0)`
2. 自动归档到 `history/requirements-v1.0.0.md`
3. 重新创建 `requirements.md (v1.1.0)` - 完全覆盖
4. 追加变更到 `changes.log` (NDJSON)
**Automatic handling**:
1. Read current `requirements.md (v1.0.0)`
2. Auto-archive to `history/requirements-v1.0.0.md`
3. Recreate `requirements.md (v1.1.0)` - complete overwrite
4. Append changes to `changes.log` (NDJSON)
## Changes.log Format (NDJSON)
保留永久审计日志append-only永不删除
Permanent audit log (append-only, never deleted):
```jsonl
{"timestamp":"2026-01-22T10:00:00+08:00","version":"1.0.0","agent":"ra","action":"create","change":"Initial requirements","iteration":1}
{"timestamp":"2026-01-22T11:00:00+08:00","version":"1.1.0","agent":"ra","action":"update","change":"Added Google OAuth requirement","iteration":2}
{"timestamp":"2026-01-22T11:30:00+08:00","version":"1.0.0","agent":"ep","action":"create","change":"Initial implementation plan","iteration":1}
{"timestamp":"2026-01-22T12:00:00+08:00","version":"1.1.0","agent":"ep","action":"update","change":"Added GitHub OAuth tasks","iteration":2}
{"timestamp":"2026-01-22T13:00:00+08:00","version":"1.0.0","agent":"cd","action":"create","change":"Started OAuth implementation","iteration":1}
```
## Usage
```bash
# 启动新循环
# Start new cycle
/parallel-dev-cycle TASK="Implement real-time notifications"
# 继续循环
# Continue cycle
/parallel-dev-cycle --cycle-id=cycle-v1-20260122-abc123
# 带扩展需求的迭代
# Iteration with extension
/parallel-dev-cycle --cycle-id=cycle-v1-20260122-abc123 --extend="Also add email notifications"
# 自动模式
# Auto mode
/parallel-dev-cycle --auto TASK="Add OAuth authentication"
```
## Key Benefits
**简洁**: 每个 agent 只维护 1 个文件 + changes.log
**高效**: 版本重写无需复杂版本标记
**可查**: 完整历史在 `history/` `changes.log`
**快速**: Agent 读取当前版本快速(不需解析历史)
**审计**: NDJSON changes.log 完整追溯每个变更
- **Simple**: Each agent maintains only 1 file + changes.log
- **Efficient**: Version rewrite without complex version marking
- **Traceable**: Complete history in `history/` and `changes.log`
- **Fast**: Agent reads current version quickly (no history parsing needed)
- **Auditable**: NDJSON changes.log fully traces every change
- **Self-Enhancing**: RA agent proactively extends requirements
- **Debug-Ready**: CD agent supports hypothesis-driven debugging
## Reference Documents
| Document | Purpose |
|----------|---------|
| [phases/orchestrator.md](phases/orchestrator.md) | 协调器逻辑 |
| [phases/state-schema.md](phases/state-schema.md) | 状态结构 |
| [phases/agents/](phases/agents/) | 四个 agent 角色 |
| [specs/coordination-protocol.md](specs/coordination-protocol.md) | 通信协议 |
| [specs/versioning-strategy.md](specs/versioning-strategy.md) | 版本管理 |
| [phases/orchestrator.md](phases/orchestrator.md) | Orchestrator logic |
| [phases/state-schema.md](phases/state-schema.md) | State structure definition |
| [phases/agents/](phases/agents/) | Four agent role definitions |
| [specs/coordination-protocol.md](specs/coordination-protocol.md) | Communication protocol |
| [specs/versioning-strategy.md](specs/versioning-strategy.md) | Version management |

View File

@@ -28,7 +28,7 @@ The Code Developer is responsible for implementing features according to the pla
- Document all file modifications
- Log changes in NDJSON format
- Track which iteration introduced which changes
- Update code-changes.log
- Update changes.log
4. **Report Issues**
- Document development blockers
@@ -43,7 +43,7 @@ The Code Developer is responsible for implementing features according to the pla
- Test code before submitting
- Document code changes clearly
- Track blockers and issues
- Append to code-changes.log, never overwrite
- Append to changes.log, never overwrite
- Reference requirements in code comments
- Use meaningful commit messages in implementation notes
@@ -90,7 +90,7 @@ For each task in the plan:
- Reference requirements
3. **Track Changes**
- Log each file modification to code-changes.log
- Log each file modification to changes.log
- Format: `{timestamp, iteration, file, action, description}`
- Include reason for change
@@ -99,12 +99,96 @@ For each task in the plan:
- Verify integration
- Test error cases
- Check performance
- **If tests fail**: Initiate Debug Workflow (see Debug Workflow section)
5. **Report Progress**
- Update implementation.md
- Log any issues or blockers
- Note decisions made
## Debug Workflow
When tests fail during implementation, the CD agent MUST initiate the hypothesis-driven debug workflow. This workflow systematically identifies and resolves bugs through structured hypothesis testing.
### Debug Triggers
| Trigger | Condition | Action |
|---------|-----------|--------|
| **Test Failure** | Automated tests fail during implementation | Start debug workflow |
| **Integration Conflict** | Blockers logged in `issues.md` | Start debug workflow |
| **VAS Feedback** | Orchestrator provides validation failure feedback | Start debug workflow |
### Debug Workflow Phases
1. **Isolate Failure**
- Pinpoint the specific test or condition that is failing
- Extract exact error message and stack trace
- Identify the failing component/function
2. **Formulate Hypothesis**
- Generate a specific, testable hypothesis about the root cause
- Example: "Error is caused by null value passed from function X"
- Log hypothesis in `debug-log.ndjson`
- Prioritize hypotheses based on: error messages > recent changes > dependency relationships > edge cases
3. **Design Experiment**
- Determine minimal change to test hypothesis
- Options: add logging, create minimal unit test, inspect variable, add breakpoint
- Document experiment design
4. **Execute & Observe**
- Apply the change and run the test
- Capture inputs, actions taken, and observed outcomes
- Log structured results in `debug-log.ndjson`
5. **Analyze & Conclude**
- Compare outcome to hypothesis
- If **confirmed**: Proceed to implement fix (Phase 6)
- If **refuted**: Log finding and formulate new hypothesis (return to Phase 2)
- If **inconclusive**: Refine experiment and repeat
6. **Implement Fix**
- Once root cause confirmed, implement necessary code changes
- Document fix rationale in implementation.md
- Log fix in changes.log
7. **Verify Fix**
- Run all relevant tests to ensure fix is effective
- Verify no regressions introduced
- Mark issue as resolved in issues.md
### Debug Log Format (NDJSON)
File: `.workflow/.cycle/{cycleId}.progress/cd/debug-log.ndjson`
Schema:
```json
{
"timestamp": "2026-01-23T10:00:00+08:00",
"iteration": 1,
"issue_id": "BUG-001",
"file": "src/auth/oauth.ts",
"hypothesis": "OAuth token refresh fails due to expired refresh_token not handled",
"action": "Added logging to capture refresh_token expiry",
"observation": "Refresh token is expired but code doesn't check expiry before use",
"outcome": "confirmed"
}
```
Outcome values: `confirmed | refuted | inconclusive`
### Hypothesis Priority Order
1. **Direct Error Messages/Stack Traces**: Most reliable starting point
2. **Recent Changes**: Check `changes.log` for recent modifications
3. **Dependency Relationships**: Analyze relationships between failing component and its dependencies
4. **Edge Cases**: Review `edge-cases.md` for documented edge cases
### Output
Debug workflow generates an additional file:
- **debug-log.ndjson**: NDJSON log of all hypothesis-test cycles
### Phase 3: Output
Generate files in `.workflow/.cycle/{cycleId}.progress/cd/`:
@@ -150,7 +234,7 @@ Overview of what was implemented in this iteration.
- Code review and merge
```
**code-changes.log** (NDJSON):
**changes.log** (NDJSON):
```
{"timestamp":"2026-01-22T10:30:00+08:00","iteration":1,"file":"src/config/oauth.ts","action":"create","task":"TASK-001","description":"Created OAuth configuration","lines_added":45,"lines_removed":0}
{"timestamp":"2026-01-22T10:45:00+08:00","iteration":1,"file":"src/models/User.ts","action":"modify","task":"TASK-002","description":"Added oauth_id and oauth_provider fields","lines_added":8,"lines_removed":0}
@@ -190,11 +274,12 @@ Overview of what was implemented in this iteration.
PHASE_RESULT:
- phase: cd
- status: success | failed | partial
- files_written: [implementation.md, code-changes.log, issues.md]
- files_written: [implementation.md, changes.log, debug-log.ndjson (if debug executed), issues.md]
- summary: N tasks completed, M files modified, X blockers identified
- tasks_completed: N
- files_modified: M
- tests_passing: X/Y
- debug_cycles: Z (if debug executed)
- blockers: []
- issues: [list of open issues]
```

View File

@@ -59,13 +59,24 @@ The Requirements Analyst maintains **a single file** (`requirements.md`) contain
- Task description from state
- Project tech stack and guidelines
2. **Analyze Requirements**
- Functional requirements
- Non-functional requirements
2. **Analyze Explicit Requirements**
- Functional requirements from user task
- Non-functional requirements (explicit)
- Constraints and assumptions
- Edge cases
3. **Generate Single File**
3. **Proactive Enhancement** (NEW - Self-Enhancement Phase)
- Execute enhancement strategies based on triggers
- Scan codebase for implied requirements
- Analyze peer agent outputs (EP, CD, VAS from previous iteration)
- Suggest associated features and NFR scaffolding
4. **Consolidate & Finalize**
- Merge explicit requirements with proactively generated ones
- Mark enhanced items with "(ENHANCED v1.0.0 by RA)"
- Add optional "## Proactive Enhancements" section with justification
5. **Generate Single File**
- Write `requirements.md` v1.0.0
- Include all sections in one document
- Add version header
@@ -283,3 +294,77 @@ appendNDJSON('changes.log', {
5. **Audit Trail**: Changes.log tracks every modification
6. **Readability First**: File should be clear and concise
7. **Version Markers**: Mark new items with "(NEW v1.x.0)"
8. **Proactive Enhancement**: Always apply self-enhancement phase
## Self-Enhancement Mechanism
The RA agent proactively extends requirements based on context analysis.
### Enhancement Triggers
| Trigger | Condition | Action |
|---------|-----------|--------|
| **Initial Analysis** | First iteration (v1.0.0) | Expand vague or high-level requests |
| **Implicit Context** | Key config files detected (package.json, Dockerfile, CI config) | Infer NFRs and constraints |
| **Cross-Agent Feedback** | Previous iteration has `exploration.identified_risks`, `cd.blockers`, or `vas.test_results.failed_tests` | Cover uncovered requirements |
### Enhancement Strategies
1. **Codebase Analysis**
- Scan key project files (package.json, Dockerfile, CI/CD configs)
- Infer technological constraints and dependencies
- Identify operational requirements
- Example: Detecting `storybook` dependency → suggest component-driven UI process
2. **Peer Output Mining**
- Analyze EP agent's `exploration.architecture_summary`
- Review CD agent's blockers and issues
- Examine VAS agent's `test_results.failed_tests`
- Formalize insights as new requirements
3. **Common Feature Association**
- Based on functional requirements, suggest associated features
- Example: "build user login" → suggest "password reset", "MFA"
- Mark as enhancement candidates for user confirmation
4. **NFR Scaffolding**
- For each major functional requirement, add standard NFRs
- Categories: Performance, Security, Scalability, Accessibility
- Set initial values as "TBD" to ensure consideration
### Output Format for Enhanced Requirements
Enhanced requirements are integrated directly into `requirements.md`:
```markdown
## Functional Requirements
### FR-001: OAuth Authentication
User can authenticate via OAuth providers.
**Status**: Defined (v1.0.0)
**Priority**: High
### FR-002: Password Reset (ENHANCED v1.0.0 by RA)
Users can reset their password via email link.
**Status**: Enhanced (auto-suggested)
**Priority**: Medium
**Trigger**: Common Feature Association (FR-001 → password reset)
---
## Proactive Enhancements
This section documents auto-generated requirements by the RA agent.
| ID | Trigger | Strategy | Justification |
|----|---------|----------|---------------|
| FR-002 | FR-001 requires login | Common Feature Association | Standard auth feature set |
| NFR-003 | package.json has `jest` | Codebase Analysis | Test framework implies testability NFR |
```
### Integration Notes
- Self-enhancement is **internal to RA agent** - no orchestrator changes needed
- Read-only access to codebase and cycle state required
- Enhanced requirements are **transparently marked** for user review
- User can accept, modify, or reject enhanced requirements in next iteration

View File

@@ -456,7 +456,7 @@ Code Developer - Implement features based on plan and requirements.
Write files to ${progressDir}/cd/:
- implementation.md: Implementation progress and decisions
- code-changes.log: NDJSON format, each line: {file, action, timestamp}
- changes.log: NDJSON format, each line: {file, action, timestamp}
- issues.md: Development issues and blockers
## OUTPUT FORMAT
@@ -484,7 +484,7 @@ function spawnVASAgent(cycleId, state, progressDir) {
### MANDATORY FIRST STEPS (Agent Execute)
1. **Read role definition**: ~/.codex/agents/validation-archivist.md
2. Read: ${progressDir}/cd/code-changes.log
2. Read: ${progressDir}/cd/changes.log
---
@@ -638,7 +638,7 @@ function generateFinalSummary(cycleId, state) {
## Generated Files
- .workflow/.cycle/${cycleId}.progress/ra/requirements.md
- .workflow/.cycle/${cycleId}.progress/ep/plan.json
- .workflow/.cycle/${cycleId}.progress/cd/code-changes.log
- .workflow/.cycle/${cycleId}.progress/cd/changes.log
- .workflow/.cycle/${cycleId}.progress/vas/summary.md
## Continuation Instructions

View File

@@ -353,7 +353,7 @@ State changes trigger file writes:
|--------------|-----------|
| `requirements` updated | `.progress/ra/requirements.md` + version bump |
| `plan` updated | `.progress/ep/plan.json` + version bump |
| `changes` appended | `.progress/cd/code-changes.log` + iteration marker |
| `changes` appended | `.progress/cd/changes.log` + iteration marker |
| `test_results` updated | `.progress/vas/test-results.json` + version bump |
| Full iteration done | `.progress/coordination/timeline.md` appended |
@@ -413,7 +413,7 @@ function rebuildState(cycleId) {
// Read markdown files
const raMarkdown = Read(`${progressDir}/ra/requirements.md`)
const epMarkdown = Read(`${progressDir}/ep/plan.json`)
const cdChanges = Read(`${progressDir}/cd/code-changes.log`)
const cdChanges = Read(`${progressDir}/cd/changes.log`)
const vasResults = Read(`${progressDir}/vas/test-results.json`)
// Reconstruct state from files

View File

@@ -244,7 +244,7 @@ if (cdChangesPath && exists(cdChangesPath)) {
"version": "1.0.0",
"output_files": {
"progress": ".workflow/.cycle/cycle-v1-20260122-abc123.progress/cd/implementation.md",
"changes": ".workflow/.cycle/cycle-v1-20260122-abc123.progress/cd/code-changes.log",
"changes": ".workflow/.cycle/cycle-v1-20260122-abc123.progress/cd/changes.log",
"issues": ".workflow/.cycle/cycle-v1-20260122-abc123.progress/cd/issues.md"
},
"summary": {
@@ -313,7 +313,7 @@ Full Test Report: .workflow/.cycle/${cycleId}.progress/vas/test-results.json (v1
## Implementation Reference
- Current Code: .workflow/.cycle/${cycleId}.progress/cd/implementation.md (v1.0.0)
- Code Changes: .workflow/.cycle/${cycleId}.progress/cd/code-changes.log (v1.0.0)
- Code Changes: .workflow/.cycle/${cycleId}.progress/cd/changes.log (v1.0.0)
## Action Required
1. Review failing tests in referenced test results file

View File

@@ -12,19 +12,26 @@ The coordination protocol enables four parallel agents (RA, EP, CD, VAS) to comm
**Location**: `.workflow/.cycle/{cycleId}.json`
All agents read from and write to the unified state file:
**Access Pattern**:
- **Agents**: READ ONLY - check dependencies and status
- **Orchestrator**: READ-WRITE - updates state after each phase
```javascript
// Every agent: Read fresh state at action start
// Every agent: Read state to check dependencies
const state = JSON.parse(Read(`.workflow/.cycle/${cycleId}.json`))
const canProceed = checkDependencies(state)
// Every agent: Write updated state at action end
Write(`.workflow/.cycle/${cycleId}.json`, JSON.stringify(state, null, 2))
// Agent outputs PHASE_RESULT (reports to orchestrator, NOT writes directly)
console.log("PHASE_RESULT: ...")
// Only Orchestrator writes to state file after receiving PHASE_RESULT
// Write(`.workflow/.cycle/${cycleId}.json`, JSON.stringify(updatedState, null, 2))
```
**Protocol**:
- Read-Update-Write pattern (no lock needed, orchestrator serializes)
- Timestamp all updates with ISO8601 format
- Only orchestrator writes to state file (no concurrent writes, no lock needed)
- Agents read state to understand dependencies
- Timestamp all orchestrator updates with ISO8601 format
- Never delete existing data, only append
### 2. Progress Markdown Files (Async Log)
@@ -33,18 +40,18 @@ Write(`.workflow/.cycle/${cycleId}.json`, JSON.stringify(state, null, 2))
Each agent writes progress to dedicated markdown files:
| Agent | Files |
|-------|-------|
| RA | requirements.md, edge-cases.md, changes.log |
| EP | exploration.md, architecture.md, plan.json |
| CD | implementation.md, code-changes.log, issues.md |
| VAS | validation.md, test-results.json, coverage.md, summary.md |
| Agent | Main Documents (Rewrite) | Logs (Append-Only) |
|-------|--------------------------|-------------------|
| RA | requirements.md | changes.log |
| EP | exploration.md, architecture.md, plan.json | changes.log |
| CD | implementation.md, issues.md | changes.log, debug-log.ndjson |
| VAS | validation.md, summary.md, test-results.json | changes.log |
**Protocol**:
- Append-only pattern (no overwrites)
- Version each document independently
- **Main documents**: Complete rewrite per iteration, archived to `history/`
- **Log files**: Append-only (changes.log, debug-log.ndjson) - never delete
- **Version synchronization**: All main documents share same version (e.g., all v1.1.0 in iteration 2)
- Include timestamp on each update
- Maintain backward compatibility
### 3. Orchestrator send_input (Synchronous)
@@ -198,6 +205,8 @@ PHASE_DETAILS:
## Dependency Resolution
**Execution Model**: All four agents are spawned in parallel, but execution blocks based on dependencies. Orchestrator manages dependency resolution via shared state.
### Build Order (Default)
```
@@ -206,6 +215,12 @@ RA (Requirements) → EP (Planning) → CD (Development) → VAS (Validation)
Block EP Block CD Block VAS Block completion
```
**Explanation**:
- All agents spawned simultaneously
- Each agent checks dependencies in shared state before proceeding
- Blocked agents wait for dependency completion
- Orchestrator uses `send_input` to notify dependent agents when ready
### Parallel Opportunities
Some phases can run in parallel:
@@ -384,7 +399,7 @@ console.log(state.coordination.feedback_log)
tail .workflow/.cycle/cycle-xxx.progress/ra/changes.log
# Check CD changes
grep "TASK-001" .workflow/.cycle/cycle-xxx.progress/cd/code-changes.log
grep "TASK-001" .workflow/.cycle/cycle-xxx.progress/cd/changes.log
# Check coordination timeline
tail -50 .workflow/.cycle/cycle-xxx.progress/coordination/feedback.md

View File

@@ -1,50 +1,51 @@
# Document Versioning Strategy
文档版本管理策略:重新创建 vs 增量更新
Document version management strategy: Complete Rewrite + Archive History
## 推荐方案:重新创建 + 归档历史
## Recommended Approach: Complete Rewrite + Archive History
每次迭代,**完全重写**主文档,旧版本自动归档到 `history/` 目录。
For each iteration, **completely rewrite** the main document, and automatically archive the old version to the `history/` directory.
### 文件结构
### File Structure
```
.workflow/.cycle/cycle-v1-20260122-abc123.progress/
├── ra/
│ ├── requirements.md # v1.2.0 (当前版本,重新创建)
│ ├── edge-cases.md # v1.2.0 (当前版本,重新创建)
│ ├── changes.log # NDJSON 完整变更历史(append-only
│ ├── requirements.md # v1.2.0 (current version, complete rewrite)
│ ├── edge-cases.md # v1.2.0 (current version, complete rewrite)
│ ├── changes.log # NDJSON complete change history (append-only)
│ └── history/
│ ├── requirements-v1.0.0.md (归档)
│ ├── requirements-v1.1.0.md (归档)
│ ├── edge-cases-v1.0.0.md (归档)
│ └── edge-cases-v1.1.0.md (归档)
│ ├── requirements-v1.0.0.md (archived)
│ ├── requirements-v1.1.0.md (archived)
│ ├── edge-cases-v1.0.0.md (archived)
│ └── edge-cases-v1.1.0.md (archived)
├── ep/
│ ├── exploration.md # v1.2.0 (当前)
│ ├── architecture.md # v1.2.0 (当前)
│ ├── plan.json # v1.2.0 (当前)
│ ├── exploration.md # v1.2.0 (current)
│ ├── architecture.md # v1.2.0 (current)
│ ├── plan.json # v1.2.0 (current)
│ └── history/
│ ├── plan-v1.0.0.json
│ └── plan-v1.1.0.json
├── cd/
│ ├── implementation.md # v1.2.0 (当前)
│ ├── code-changes.log # NDJSON 完整历史
│ ├── issues.md # 当前未解决问题
│ ├── implementation.md # v1.2.0 (current)
│ ├── changes.log # NDJSON complete history
│ ├── debug-log.ndjson # Debug hypothesis tracking
│ ├── issues.md # Current unresolved issues
│ └── history/
│ ├── implementation-v1.0.0.md
│ └── implementation-v1.1.0.md
└── vas/
├── validation.md # v1.2.0 (当前)
├── test-results.json # v1.2.0 (当前)
├── summary.md # v1.2.0 (当前)
├── validation.md # v1.2.0 (current)
├── test-results.json # v1.2.0 (current)
├── summary.md # v1.2.0 (current)
└── history/
├── validation-v1.0.0.md
└── test-results-v1.0.0.json
```
## 文档模板优化
## Optimized Document Template
### Requirements.md (重新创建版本)
### Requirements.md (Complete Rewrite Version)
```markdown
# Requirements Specification - v1.2.0
@@ -162,7 +163,7 @@ Response time < 500ms for all OAuth flows.
**Detailed History**: See `history/` directory and `changes.log`
```
### Changes.log (NDJSON - 完整历史)
### Changes.log (NDJSON - Complete History)
```jsonl
{"timestamp":"2026-01-22T10:00:00+08:00","iteration":1,"version":"1.0.0","action":"create","type":"requirement","id":"FR-001","description":"Initial OAuth requirement"}
@@ -173,37 +174,37 @@ Response time < 500ms for all OAuth flows.
{"timestamp":"2026-01-23T10:05:00+08:00","iteration":3,"version":"1.2.0","action":"update","type":"requirement","id":"FR-002","description":"Added GitHub provider"}
```
## 实现流程
## Implementation Flow
### Agent 工作流RA 为例)
### Agent Workflow (RA Example)
```javascript
// ==================== RA Agent 迭代流程 ====================
// ==================== RA Agent Iteration Flow ====================
// 读取当前状态
// Read current state
const state = JSON.parse(Read(`.workflow/.cycle/${cycleId}.json`))
const currentVersion = state.requirements?.version || "0.0.0"
const iteration = state.current_iteration
// 如果是迭代(已有旧版本)
// If iteration (old version exists)
if (currentVersion !== "0.0.0") {
// 1. 归档旧版本
// 1. Archive old version
const oldFile = `.workflow/.cycle/${cycleId}.progress/ra/requirements.md`
const archiveFile = `.workflow/.cycle/${cycleId}.progress/ra/history/requirements-v${currentVersion}.md`
Copy(oldFile, archiveFile) // 归档
Copy(oldFile, archiveFile) // Archive
// 2. 读取旧版本(可选,用于理解上下文)
// 2. Read old version (optional, for context understanding)
const oldRequirements = Read(oldFile)
// 3. 读取变更历史
// 3. Read change history
const changesLog = readNDJSON(`.workflow/.cycle/${cycleId}.progress/ra/changes.log`)
}
// 4. 生成新版本号
// 4. Generate new version number
const newVersion = bumpVersion(currentVersion, 'minor') // 1.1.0 -> 1.2.0
// 5. 生成新文档(完全重写)
// 5. Generate new document (complete rewrite)
const newRequirements = generateRequirements({
version: newVersion,
previousVersion: currentVersion,
@@ -211,13 +212,13 @@ const newRequirements = generateRequirements({
currentChanges: "Added MFA and GitHub provider",
iteration: iteration,
taskDescription: state.description,
changesLog: changesLog // 用于理解历史
changesLog: changesLog // For understanding history
})
// 6. 写入新文档(覆盖旧的)
// 6. Write new document (overwrite old)
Write(`.workflow/.cycle/${cycleId}.progress/ra/requirements.md`, newRequirements)
// 7. 追加变更到 changes.log
// 7. Append change to changes.log
appendNDJSON(`.workflow/.cycle/${cycleId}.progress/ra/changes.log`, {
timestamp: getUtc8ISOString(),
iteration: iteration,
@@ -228,7 +229,7 @@ appendNDJSON(`.workflow/.cycle/${cycleId}.progress/ra/changes.log`, {
description: "Added MFA requirement"
})
// 8. 更新状态
// 8. Update state
state.requirements = {
version: newVersion,
output_file: `.workflow/.cycle/${cycleId}.progress/ra/requirements.md`,
@@ -242,25 +243,25 @@ state.requirements = {
Write(`.workflow/.cycle/${cycleId}.json`, JSON.stringify(state, null, 2))
```
## 优势对比
## Advantages Comparison
| 方面 | 增量更新 | 重新创建 + 归档 |
|------|----------|----------------|
| **文档简洁性** | ❌ 越来越长 | ✅ 始终简洁 |
| **Agent 解析** | ❌ 需要解析历史 | ✅ 只看当前版本 |
| **维护复杂度** | ❌ 高(版本标记) | ✅ 低(直接重写) |
| **文件大小** | ❌ 膨胀 | ✅ 固定 |
| **历史追溯** | ✅ 在主文档 | ✅ history/ + changes.log |
| **人类可读** | ❌ 需要跳过历史 | ✅ 直接看当前 |
| **Token 使用** | ❌ 多(读取完整历史) | ✅ 少(只读当前) |
| Aspect | Incremental Update | Complete Rewrite + Archive |
|--------|-------------------|---------------------------|
| **Document Conciseness** | ❌ Gets longer | ✅ Always concise |
| **Agent Parsing** | ❌ Must parse history | ✅ Only read current version |
| **Maintenance Complexity** | ❌ High (version marking) | ✅ Low (direct rewrite) |
| **File Size** | ❌ Bloats | ✅ Fixed |
| **History Tracking** | ✅ In main document | ✅ In history/ + changes.log |
| **Human Readability** | ❌ Must skip history | ✅ Direct current view |
| **Token Usage** | ❌ More (read complete history) | ✅ Less (only read current) |
## 归档策略
## Archive Strategy
### 自动归档触发时机
### Auto-Archive Trigger
```javascript
function shouldArchive(currentVersion, state) {
// 每次版本更新时归档
// Archive on each version update
return currentVersion !== state.requirements?.version
}
@@ -269,29 +270,29 @@ function archiveOldVersion(cycleId, agent, filename, currentVersion) {
const archiveDir = `.workflow/.cycle/${cycleId}.progress/${agent}/history`
const archiveFile = `${archiveDir}/${filename.replace('.', `-v${currentVersion}.`)}`
// 确保归档目录存在
// Ensure archive directory exists
mkdir -p ${archiveDir}
// 复制(不是移动,保持当前文件直到新版本写入)
// Copy (not move, keep current file until new version written)
Copy(currentFile, archiveFile)
console.log(`Archived ${filename} v${currentVersion} to history/`)
}
```
### 清理策略(可选)
### Cleanup Strategy (Optional)
保留最近 N 个版本,删除更老的归档:
Keep most recent N versions, delete older archives:
```javascript
function cleanupArchives(cycleId, agent, keepVersions = 3) {
const historyDir = `.workflow/.cycle/${cycleId}.progress/${agent}/history`
const archives = listFiles(historyDir)
// 按版本号排序
// Sort by version number
archives.sort((a, b) => compareVersions(extractVersion(a), extractVersion(b)))
// 删除最老的版本(保留最近 N 个)
// Delete oldest versions (keep most recent N)
if (archives.length > keepVersions) {
const toDelete = archives.slice(0, archives.length - keepVersions)
toDelete.forEach(file => Delete(`${historyDir}/${file}`))
@@ -299,32 +300,32 @@ function cleanupArchives(cycleId, agent, keepVersions = 3) {
}
```
## Changes.log 的重要性
## Importance of Changes.log
虽然主文档重新创建,但 **changes.log (NDJSON) 永久保留完整历史**
Although main document is completely rewritten, **changes.log (NDJSON) permanently preserves complete history**:
```bash
# 查看所有变更
# View all changes
cat .workflow/.cycle/cycle-xxx.progress/ra/changes.log | jq .
# 查看某个需求的历史
# View history of specific requirement
cat .workflow/.cycle/cycle-xxx.progress/ra/changes.log | jq 'select(.id=="FR-001")'
# 按迭代查看变更
# View changes by iteration
cat .workflow/.cycle/cycle-xxx.progress/ra/changes.log | jq 'select(.iteration==2)'
```
这样:
- **主文档**: 清晰简洁(当前状态)
- **Changes.log**: 完整追溯(所有历史)
- **History/**: 快照备份(按需查看)
This way:
- **Main Document**: Clear and concise (current state)
- **Changes.log**: Complete traceability (all history)
- **History/**: Snapshot backups (view on demand)
## 推荐实施
## Recommended Implementation
1.采用"重新创建"策略
2.主文档只保留"上一版本简要说明"
3.自动归档到 `history/` 目录
4. ✅ Changes.log (NDJSON) 保留完整历史
5.可选:保留最近 3-5 个历史版本
1.Adopt "Complete Rewrite" strategy
2.Main document only keeps "previous version summary"
3.Auto-archive to `history/` directory
4. ✅ Changes.log (NDJSON) preserves complete history
5.Optional: Keep most recent 3-5 historical versions
这样既保持了文档简洁Agent 友好),又保留了完整历史(审计友好)。
This approach keeps documents concise (agent-friendly) while preserving complete history (audit-friendly).

View File

@@ -60,7 +60,7 @@ These commands orchestrate complex, multi-phase development processes, from plan
| Command | Description |
|---|---|
| `/workflow:action-plan-verify`| Perform non-destructive cross-artifact consistency and quality analysis of IMPL_PLAN.md and task.json before execution. |
| `/workflow:plan-verify`| Perform non-destructive cross-artifact consistency and quality analysis of IMPL_PLAN.md and task.json before execution. |
### Code Review Cycle

2
FAQ.md
View File

@@ -665,7 +665,7 @@ CCW ensures dependencies are completed before dependent tasks execute.
2. **Run verification**:
```bash
/workflow:action-plan-verify
/workflow:plan-verify
```
3. **Automated reviews**:

View File

@@ -153,7 +153,7 @@ After planning, validate your implementation plan for consistency and completene
```bash
# After /workflow:plan completes, verify task quality
/workflow:action-plan-verify
/workflow:plan-verify
# The command will:
# 1. Check requirements coverage (all requirements have tasks)

View File

@@ -158,7 +158,7 @@
```bash
# /workflow:plan 完成后,验证任务质量
/workflow:action-plan-verify
/workflow:plan-verify
# 该命令将:
# 1. 检查需求覆盖率(所有需求都有任务)

View File

@@ -310,7 +310,7 @@ Return: Summary + Next Steps
```bash
/workflow:plan "task description" # Complete planning
/workflow:action-plan-verify # Verify plan (recommended)
/workflow:plan-verify # Verify plan (recommended)
/workflow:execute # Execute
/workflow:review # (optional) Review
```
@@ -354,7 +354,7 @@ Phase 6: TDD Structure Validation
```bash
/workflow:tdd-plan "feature description" # TDD planning
/workflow:action-plan-verify # Verify (recommended)
/workflow:plan-verify # Verify (recommended)
/workflow:execute # Execute (follow Red-Green-Refactor)
/workflow:tdd-verify # Verify TDD compliance
```
@@ -454,7 +454,7 @@ Phase 3: Synthesis Integration
```bash
/workflow:brainstorm:auto-parallel "topic" [--count N] [--style-skill package]
/workflow:plan --session {sessionId} # Plan based on brainstorm results
/workflow:action-plan-verify # Verify
/workflow:plan-verify # Verify
/workflow:execute # Execute
```

View File

@@ -309,7 +309,7 @@ Return: Summary + Next Steps
```bash
/workflow:plan "task description" # 完整规划
/workflow:action-plan-verify # 验证计划 (推荐)
/workflow:plan-verify # 验证计划 (推荐)
/workflow:execute # 执行
/workflow:review # (可选) 审查
```
@@ -353,7 +353,7 @@ Phase 6: TDD Structure Validation
```bash
/workflow:tdd-plan "feature description" # TDD 规划
/workflow:action-plan-verify # 验证 (推荐)
/workflow:plan-verify # 验证 (推荐)
/workflow:execute # 执行 (遵循 Red-Green-Refactor)
/workflow:tdd-verify # 验证 TDD 流程合规
```
@@ -453,7 +453,7 @@ Phase 3: Synthesis Integration
```bash
/workflow:brainstorm:auto-parallel "topic" [--count N] [--style-skill package]
/workflow:plan --session {sessionId} # 基于头脑风暴结果规划
/workflow:action-plan-verify # 验证
/workflow:plan-verify # 验证
/workflow:execute # 执行
```

View File

@@ -233,6 +233,28 @@ const ISSUES_DIR = '.workflow/issues';
// ============ Storage Layer (JSONL) ============
/**
* Cached project root to avoid repeated git command execution
*/
let cachedProjectRoot: string | null = null;
/**
* Clear cached project root (for testing)
*/
export function clearProjectRootCache(): void {
cachedProjectRoot = null;
}
/**
* Debug logging helper (enabled via CCW_DEBUG=true)
*/
const DEBUG = process.env.CCW_DEBUG === 'true';
function debugLog(msg: string): void {
if (DEBUG) {
console.log(`[ccw:worktree] ${msg}`);
}
}
/**
* Normalize path for comparison (handles Windows case sensitivity)
*/
@@ -271,7 +293,32 @@ function resolveMainRepoFromGitFile(gitFilePath: string): string | null {
* This ensures .workflow/issues/ is always accessed from the main repo.
*/
function getProjectRoot(): string {
// First, try to detect if we're in a git worktree using git commands
// Return cached result if available
if (cachedProjectRoot) {
debugLog(`Using cached project root: ${cachedProjectRoot}`);
return cachedProjectRoot;
}
debugLog(`Detecting project root from cwd: ${process.cwd()}`);
// Priority 1: Check CCW_MAIN_REPO environment variable
const envMainRepo = process.env.CCW_MAIN_REPO;
if (envMainRepo) {
debugLog(`Found CCW_MAIN_REPO env: ${envMainRepo}`);
const hasWorkflow = existsSync(join(envMainRepo, '.workflow'));
const hasGit = existsSync(join(envMainRepo, '.git'));
if (hasWorkflow || hasGit) {
debugLog(`CCW_MAIN_REPO validated (workflow=${hasWorkflow}, git=${hasGit})`);
cachedProjectRoot = envMainRepo;
return envMainRepo;
} else {
console.warn('[ccw] CCW_MAIN_REPO is set but path is invalid (no .workflow or .git)');
console.warn(`[ccw] Path: ${envMainRepo}`);
}
}
// Priority 2: Try to detect if we're in a git worktree using git commands
try {
// Get the common git directory (points to main repo's .git)
const gitCommonDir = execSync('git rev-parse --git-common-dir', {
@@ -287,6 +334,9 @@ function getProjectRoot(): string {
timeout: EXEC_TIMEOUTS.GIT_QUICK,
}).trim();
debugLog(`Git common dir: ${gitCommonDir}`);
debugLog(`Git dir: ${gitDir}`);
// Normalize paths for comparison (Windows case insensitive)
const normalizedCommon = normalizePath(gitCommonDir);
const normalizedGit = normalizePath(gitDir);
@@ -298,8 +348,12 @@ function getProjectRoot(): string {
// .git directory's parent is the repo root
const mainRepoRoot = resolve(absoluteCommonDir, '..');
debugLog(`Detected worktree, main repo: ${mainRepoRoot}`);
// Verify .workflow or .git exists in main repo
if (existsSync(join(mainRepoRoot, '.workflow')) || existsSync(join(mainRepoRoot, '.git'))) {
debugLog(`Main repo validated, returning: ${mainRepoRoot}`);
cachedProjectRoot = mainRepoRoot;
return mainRepoRoot;
}
}
@@ -307,10 +361,11 @@ function getProjectRoot(): string {
if (isExecTimeoutError(err)) {
console.warn(`[issue] git rev-parse timed out after ${EXEC_TIMEOUTS.GIT_QUICK}ms; falling back to filesystem detection`);
}
debugLog(`Git command failed, falling back to filesystem detection`);
// Git command failed - fall through to manual detection
}
// Standard detection with worktree file support: walk up to find .workflow or .git
// Priority 3: Standard detection with worktree file support: walk up to find .workflow or .git
let dir = process.cwd();
while (dir !== resolve(dir, '..')) {
const gitPath = join(dir, '.git');
@@ -322,22 +377,45 @@ function getProjectRoot(): string {
if (gitStat.isFile()) {
// .git is a file - this is a worktree, try to resolve main repo
const mainRepo = resolveMainRepoFromGitFile(gitPath);
if (mainRepo && existsSync(join(mainRepo, '.workflow'))) {
return mainRepo;
debugLog(`Parsed .git file, main repo: ${mainRepo}`);
if (mainRepo) {
// Verify main repo has .git directory (always true for main repo)
// Don't require .workflow - it may not exist yet in a new repo
const hasGit = existsSync(join(mainRepo, '.git'));
const hasWorkflow = existsSync(join(mainRepo, '.workflow'));
if (hasGit || hasWorkflow) {
if (!hasWorkflow) {
console.warn('[ccw] Worktree detected but main repo has no .workflow directory');
console.warn(`[ccw] Main repo: ${mainRepo}`);
console.warn('[ccw] Issue commands may fail until .workflow is created');
console.warn('[ccw] Set CCW_MAIN_REPO environment variable to override detection');
}
debugLog(`Main repo validated via .git file (git=${hasGit}, workflow=${hasWorkflow})`);
cachedProjectRoot = mainRepo;
return mainRepo;
}
}
// If main repo doesn't have .workflow, fall back to current worktree
}
} catch {
// stat failed, continue with normal logic
debugLog(`Failed to stat ${gitPath}, continuing`);
}
}
if (existsSync(join(dir, '.workflow')) || existsSync(gitPath)) {
debugLog(`Found project root at: ${dir}`);
cachedProjectRoot = dir;
return dir;
}
dir = resolve(dir, '..');
}
return process.cwd();
debugLog(`No project root found, using cwd: ${process.cwd()}`);
const fallback = process.cwd();
cachedProjectRoot = fallback;
return fallback;
}
function getIssuesDir(): string {
@@ -1220,6 +1298,81 @@ async function solutionAction(issueId: string | undefined, options: IssueOptions
}
}
/**
* solutions - Batch query solutions for multiple issues
* Usage: ccw issue solutions --status planned --brief
*/
async function solutionsAction(options: IssueOptions): Promise<void> {
// Get issues filtered by status
const issues = readIssues();
let targetIssues = issues;
if (options.status) {
const statuses = options.status.split(',').map((s: string) => s.trim());
targetIssues = issues.filter((i: Issue) => statuses.includes(i.status));
}
// Filter to only issues with bound_solution_id
const boundIssues = targetIssues.filter((i: Issue) => i.bound_solution_id);
if (boundIssues.length === 0) {
if (options.json || options.brief) {
console.log('[]');
} else {
console.log(chalk.yellow('No bound solutions found'));
}
return;
}
// Collect solutions for all bound issues
const allSolutions: Array<{
issue_id: string;
solution_id: string;
is_bound: boolean;
task_count: number;
files_touched: string[];
priority?: number;
}> = [];
for (const issue of boundIssues) {
const solutions = readSolutions(issue.id);
const boundSolution = solutions.find(s => s.id === issue.bound_solution_id);
if (boundSolution) {
const filesTouched = new Set<string>();
for (const task of boundSolution.tasks) {
if (task.modification_points) {
for (const mp of task.modification_points) {
if (mp.file) filesTouched.add(mp.file);
}
}
}
allSolutions.push({
issue_id: issue.id,
solution_id: boundSolution.id,
is_bound: true,
task_count: boundSolution.tasks.length,
files_touched: Array.from(filesTouched),
priority: issue.priority
});
}
}
// Brief mode: already minimal
if (options.brief || options.json) {
console.log(JSON.stringify(allSolutions, null, 2));
return;
}
// Human-readable output
console.log(chalk.bold.cyan(`\nBound Solutions (${allSolutions.length}):\n`));
for (const sol of allSolutions) {
console.log(`${chalk.green('◉')} ${sol.issue_id}${sol.solution_id}`);
console.log(chalk.gray(` Tasks: ${sol.task_count}, Files: ${sol.files_touched.length}`));
}
}
/**
* init - Initialize a new issue (manual ID)
*/
@@ -2832,6 +2985,9 @@ export async function issueCommand(
case 'solution':
await solutionAction(argsArray[0], options);
break;
case 'solutions':
await solutionsAction(options);
break;
case 'init':
await initAction(argsArray[0], options);
break;

1
ccw/src/core/routes/.gitignore vendored Normal file
View File

@@ -0,0 +1 @@
.ace-tool/

View File

@@ -35,6 +35,7 @@ import {
import {
loadClaudeCliTools,
ensureClaudeCliTools,
ensureClaudeCliToolsAsync,
saveClaudeCliTools,
loadClaudeCliSettings,
saveClaudeCliSettings,
@@ -329,16 +330,18 @@ export async function handleCliRoutes(ctx: RouteContext): Promise<boolean> {
// API: Get all API endpoints (for --tool custom --model <id>)
if (pathname === '/api/cli/endpoints' && req.method === 'GET') {
try {
// Use ensureClaudeCliTools to auto-create config if missing
const config = ensureClaudeCliTools(initialPath);
const endpoints = getApiEndpointsFromTools(config);
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ endpoints }));
} catch (err) {
res.writeHead(500, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ error: (err as Error).message }));
}
(async () => {
try {
// Use ensureClaudeCliToolsAsync to auto-create config with availability sync
const config = await ensureClaudeCliToolsAsync(initialPath);
const endpoints = getApiEndpointsFromTools(config);
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ endpoints }));
} catch (err) {
res.writeHead(500, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ error: (err as Error).message }));
}
})();
return true;
}
@@ -820,21 +823,23 @@ export async function handleCliRoutes(ctx: RouteContext): Promise<boolean> {
// API: Get CLI Tools Config from .claude/cli-tools.json (with fallback to global)
if (pathname === '/api/cli/tools-config' && req.method === 'GET') {
try {
// Use ensureClaudeCliTools to auto-create config if missing
const toolsConfig = ensureClaudeCliTools(initialPath);
const settingsConfig = loadClaudeCliSettings(initialPath);
const info = getClaudeCliToolsInfo(initialPath);
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({
tools: toolsConfig,
settings: settingsConfig,
_configInfo: info
}));
} catch (err) {
res.writeHead(500, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ error: (err as Error).message }));
}
(async () => {
try {
// Use ensureClaudeCliToolsAsync to auto-create config with availability sync
const toolsConfig = await ensureClaudeCliToolsAsync(initialPath);
const settingsConfig = loadClaudeCliSettings(initialPath);
const info = getClaudeCliToolsInfo(initialPath);
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({
tools: toolsConfig,
settings: settingsConfig,
_configInfo: info
}));
} catch (err) {
res.writeHead(500, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ error: (err as Error).message }));
}
})();
return true;
}

View File

@@ -726,7 +726,7 @@ function getWorkflowGraphData(workflow) {
{ data: { id: 'start', label: ht('help.workflows.planFull.start') } },
{ data: { id: 'cli-analyze', label: ht('help.workflows.planFull.cliAnalyze') } },
{ data: { id: 'plan', label: '/workflow:plan' } },
{ data: { id: 'verify', label: '/workflow:action-plan-verify' } },
{ data: { id: 'verify', label: '/workflow:plan-verify' } },
{ data: { id: 'execute', label: '/workflow:execute' } },
{ data: { id: 'test', label: '/workflow:test-gen' } },
{ data: { id: 'review', label: '/workflow:review' } },

View File

@@ -418,6 +418,56 @@ export function ensureClaudeCliTools(projectDir: string, createInProject: boolea
}
}
/**
* Async version of ensureClaudeCliTools with automatic availability sync
* Creates default config in global ~/.claude directory and syncs with actual tool availability
* @param projectDir - Project directory path (used for reading existing project config)
* @param createInProject - DEPRECATED: Always creates in global dir. Kept for backward compatibility.
* @returns The config that was created/exists
*/
export async function ensureClaudeCliToolsAsync(projectDir: string, createInProject: boolean = false): Promise<ClaudeCliToolsConfig & { _source?: string }> {
const resolved = resolveConfigPath(projectDir);
if (resolved.source !== 'default') {
// Config exists, load and return it
return loadClaudeCliTools(projectDir);
}
// Config doesn't exist - create in global directory only
debugLog('[claude-cli-tools] Config not found, creating default cli-tools.json in ~/.claude');
const defaultConfig: ClaudeCliToolsConfig = { ...DEFAULT_TOOLS_CONFIG };
// Always create in global directory (user-level config), respecting CCW_DATA_DIR
const claudeHome = process.env.CCW_DATA_DIR
? path.join(process.env.CCW_DATA_DIR, '.claude')
: path.join(os.homedir(), '.claude');
if (!fs.existsSync(claudeHome)) {
fs.mkdirSync(claudeHome, { recursive: true });
}
const globalPath = getGlobalConfigPath();
try {
fs.writeFileSync(globalPath, JSON.stringify(defaultConfig, null, 2), 'utf-8');
debugLog(`[claude-cli-tools] Created default config at: ${globalPath}`);
// Auto-sync with actual tool availability on first creation
try {
debugLog('[claude-cli-tools] Auto-syncing tool availability on first creation...');
const syncResult = await syncBuiltinToolsAvailability(projectDir);
debugLog(`[claude-cli-tools] Auto-sync completed: enabled=[${syncResult.changes.enabled.join(', ')}], disabled=[${syncResult.changes.disabled.join(', ')}]`);
return { ...syncResult.config, _source: 'global' };
} catch (syncErr) {
console.warn('[claude-cli-tools] Failed to auto-sync availability:', syncErr);
// Return default config if sync fails
return { ...defaultConfig, _source: 'global' };
}
} catch (err) {
console.error('[claude-cli-tools] Failed to create global config:', err);
return { ...defaultConfig, _source: 'default' };
}
}
/**
* Load CLI tools configuration from global ~/.claude/cli-tools.json
* Falls back to default config if not found.

View File

@@ -83,8 +83,8 @@ function findLocalPackagePath(packageName: string): string | null {
possiblePaths.push(join(cwdParent, packageName));
}
// First pass: prefer non-node_modules paths (development environment)
for (const localPath of possiblePaths) {
// Skip paths inside node_modules
if (isInsideNodeModules(localPath)) {
continue;
}
@@ -94,8 +94,12 @@ function findLocalPackagePath(packageName: string): string | null {
}
}
if (!isDevEnvironment()) {
console.log(`[CodexLens] Running from node_modules - will try PyPI for ${packageName}`);
// Second pass: allow node_modules paths (NPM global install)
for (const localPath of possiblePaths) {
if (existsSync(join(localPath, 'pyproject.toml'))) {
console.log(`[CodexLens] Found ${packageName} in node_modules at: ${localPath}`);
return localPath;
}
}
return null;
@@ -666,14 +670,26 @@ async function bootstrapWithUv(gpuMode: GpuMode = 'cpu'): Promise<BootstrapResul
if (!codexLensPath) {
// codex-lens is a local-only package, not published to PyPI
// Generate dynamic paths for error message (cross-platform)
const possiblePaths = [
join(process.cwd(), 'codex-lens'),
join(__dirname, '..', '..', '..', 'codex-lens'),
join(homedir(), 'codex-lens'),
];
const cwd = process.cwd();
const cwdParent = dirname(cwd);
if (cwdParent !== cwd) {
possiblePaths.push(join(cwdParent, 'codex-lens'));
}
const pathsList = possiblePaths.map(p => ` - ${p}`).join('\n');
const errorMsg = `Cannot find codex-lens directory for local installation.\n\n` +
`codex-lens is a local development package (not published to PyPI) and must be installed from local files.\n\n` +
`To fix this:\n` +
`1. Ensure the 'codex-lens' directory exists in your project root\n` +
` Expected location: D:\\Claude_dms3\\codex-lens\n` +
`2. Verify pyproject.toml exists: D:\\Claude_dms3\\codex-lens\\pyproject.toml\n` +
`3. Run ccw from the correct working directory (e.g., D:\\Claude_dms3)\n` +
`4. Or manually install: cd D:\\Claude_dms3\\codex-lens && pip install -e .[${extras.join(',')}]`;
`1. Ensure 'codex-lens' directory exists at one of these locations:\n${pathsList}\n` +
`2. Verify pyproject.toml exists in the codex-lens directory\n` +
`3. Run ccw from the correct working directory\n` +
`4. Or manually install: cd /path/to/codex-lens && pip install -e .[${extras.join(',')}]`;
return { success: false, error: errorMsg };
}
@@ -740,13 +756,26 @@ async function installSemanticWithUv(gpuMode: GpuMode = 'cpu'): Promise<Bootstra
// Install with extras - UV handles dependency conflicts automatically
if (!codexLensPath) {
// codex-lens is a local-only package, not published to PyPI
// Generate dynamic paths for error message (cross-platform)
const possiblePaths = [
join(process.cwd(), 'codex-lens'),
join(__dirname, '..', '..', '..', 'codex-lens'),
join(homedir(), 'codex-lens'),
];
const cwd = process.cwd();
const cwdParent = dirname(cwd);
if (cwdParent !== cwd) {
possiblePaths.push(join(cwdParent, 'codex-lens'));
}
const pathsList = possiblePaths.map(p => ` - ${p}`).join('\n');
const errorMsg = `Cannot find codex-lens directory for local installation.\n\n` +
`codex-lens is a local development package (not published to PyPI) and must be installed from local files.\n\n` +
`To fix this:\n` +
`1. Ensure the 'codex-lens' directory exists in your project root\n` +
`2. Verify pyproject.toml exists in codex-lens directory\n` +
`1. Ensure 'codex-lens' directory exists at one of these locations:\n${pathsList}\n` +
`2. Verify pyproject.toml exists in the codex-lens directory\n` +
`3. Run ccw from the correct working directory\n` +
`4. Or manually install: cd codex-lens && pip install -e .[${extras.join(',')}]`;
`4. Or manually install: cd /path/to/codex-lens && pip install -e .[${extras.join(',')}]`;
return { success: false, error: errorMsg };
}

4
package-lock.json generated
View File

@@ -1,12 +1,12 @@
{
"name": "claude-code-workflow",
"version": "6.3.41",
"version": "6.3.44",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "claude-code-workflow",
"version": "6.3.41",
"version": "6.3.44",
"license": "MIT",
"dependencies": {
"@modelcontextprotocol/sdk": "^1.0.4",

View File

@@ -1,6 +1,6 @@
{
"name": "claude-code-workflow",
"version": "6.3.41",
"version": "6.3.44",
"description": "JSON-driven multi-agent development framework with intelligent CLI orchestration (Gemini/Qwen/Codex), context-first architecture, and automated workflow execution",
"type": "module",
"main": "ccw/src/index.js",