feat: Add TDD workflow support (v3.1.0)

🧪 TDD Workflow Commands:
- /workflow:tdd-plan: 5-phase TDD planning with Red-Green-Refactor chains
- /workflow:tdd-verify: 4-phase TDD compliance verification
- /workflow:tools:task-generate-tdd: TDD task chain generator
- /workflow:tools:tdd-coverage-analysis: Test coverage and cycle analysis

📋 Task Architecture:
- Task ID format: TEST-N.M → IMPL-N.M → REFACTOR-N.M
- Dependency enforcement: IMPL depends_on TEST, REFACTOR depends_on IMPL
- Meta fields: tdd_phase (red/green/refactor), agent assignments

📊 Compliance Scoring:
- Base score: 100 points with deductions for missing tasks
- Comprehensive validation: chain structure, dependencies, cycle execution
- Detailed reporting: TDD_COMPLIANCE_REPORT.md with recommendations

📚 Documentation:
- Updated README.md and README_CN.md with TDD workflow examples
- Added "How It Works" section explaining context-first architecture
- Enhanced Getting Started with complete 4-phase workflow
- Updated CHANGELOG.md with comprehensive v3.1.0 details

🎯 Design Philosophy:
- Context-first architecture eliminates execution uncertainty
- Pre-defined context gathering via context-package.json
- JSON-first task model with pre_analysis steps
- Multi-model orchestration (Gemini/Qwen/Codex)

🤖 Generated with Claude Code (https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
catlog22
2025-10-02 09:18:08 +08:00
parent c27ed8c900
commit de63ad5797
9 changed files with 2465 additions and 48 deletions

View File

@@ -0,0 +1,133 @@
---
name: tdd-plan
description: Orchestrate TDD workflow planning with Red-Green-Refactor task chains
usage: /workflow:tdd-plan [--agent] <input>
argument-hint: "[--agent] \"feature description\"|file.md|ISS-001"
examples:
- /workflow:tdd-plan "Implement user authentication"
- /workflow:tdd-plan --agent requirements.md
- /workflow:tdd-plan ISS-001
allowed-tools: SlashCommand(*), TodoWrite(*), Read(*), Bash(*)
---
# TDD Workflow Plan Command (/workflow:tdd-plan)
## Coordinator Role
**This command is a pure orchestrator**: Execute 5 slash commands in sequence, parse outputs, pass context, and ensure complete TDD workflow creation.
**Execution Modes**:
- **Manual Mode** (default): Use `/workflow:tools:task-generate-tdd`
- **Agent Mode** (`--agent`): Use `/workflow:tools:task-generate-tdd --agent`
## Core Rules
1. **Start Immediately**: First action is TodoWrite initialization, second action is Phase 1 execution
2. **No Preliminary Analysis**: Do not read files before Phase 1
3. **Parse Every Output**: Extract required data for next phase
4. **Sequential Execution**: Each phase depends on previous output
5. **Complete All Phases**: Do not return until Phase 5 completes
6. **TDD Context**: All descriptions include "TDD:" prefix
## 5-Phase Execution
### Phase 1: Session Discovery
**Command**: `/workflow:session:start --auto "TDD: [structured-description]"`
**TDD Structured Format**:
```
TDD: [Feature Name]
GOAL: [Objective]
SCOPE: [Included/excluded]
CONTEXT: [Background]
TEST_FOCUS: [Test scenarios]
```
**Parse**: Extract sessionId
### Phase 2: Context Gathering
**Command**: `/workflow:tools:context-gather --session [sessionId] "TDD: [structured-description]"`
**Parse**: Extract contextPath
### Phase 3: TDD Analysis
**Command**: `/workflow:tools:concept-enhanced --session [sessionId] --context [contextPath]`
**Parse**: Verify ANALYSIS_RESULTS.md
### Phase 4: TDD Task Generation
**Command**:
- Manual: `/workflow:tools:task-generate-tdd --session [sessionId]`
- Agent: `/workflow:tools:task-generate-tdd --session [sessionId] --agent`
**Parse**: Extract feature count, chain count, task count
**Validate**:
- TDD_PLAN.md exists
- IMPL_PLAN.md exists
- TEST-*.json, IMPL-*.json, REFACTOR-*.json exist
- TODO_LIST.md exists
### Phase 5: TDD Structure Validation
**Internal validation (no command)**
**Validate**:
1. Each feature has TEST → IMPL → REFACTOR chain
2. Dependencies: IMPL depends_on TEST, REFACTOR depends_on IMPL
3. Meta fields: tdd_phase correct ("red"/"green"/"refactor")
4. Agents: TEST uses @code-review-test-agent, IMPL/REFACTOR use @code-developer
**Return Summary**:
```
TDD Planning complete for session: [sessionId]
Features analyzed: [N]
TDD chains generated: [N]
Total tasks: [3N]
Structure:
- Feature 1: TEST-1.1 → IMPL-1.1 → REFACTOR-1.1
[...]
Plans:
- TDD Structure: .workflow/[sessionId]/TDD_PLAN.md
- Implementation: .workflow/[sessionId]/IMPL_PLAN.md
Next: /workflow:execute or /workflow:tdd-verify
```
## TodoWrite Pattern
```javascript
// Initialize
[
{content: "Execute session discovery", status: "in_progress", activeForm: "..."},
{content: "Execute context gathering", status: "pending", activeForm: "..."},
{content: "Execute TDD analysis", status: "pending", activeForm: "..."},
{content: "Execute TDD task generation", status: "pending", activeForm: "..."},
{content: "Validate TDD structure", status: "pending", activeForm: "..."}
]
// Update after each phase: mark current "completed", next "in_progress"
```
## Input Processing
Convert user input to TDD-structured format:
**Simple text** → Add TDD context
**Detailed text** → Extract components with TEST_FOCUS
**File/Issue** → Read and structure with TDD
## Error Handling
- **Parsing failure**: Retry once, then report
- **Validation failure**: Report missing/invalid data
- **Command failure**: Keep phase in_progress, report error
- **TDD validation failure**: Report incomplete chains or wrong dependencies
## Related Commands
- `/workflow:plan` - Standard (non-TDD) planning
- `/workflow:execute` - Execute TDD tasks
- `/workflow:tdd-verify` - Verify TDD compliance
- `/workflow:status` - View progress

View File

@@ -0,0 +1,361 @@
---
name: tdd-verify
description: Verify TDD workflow compliance and generate quality report
usage: /workflow:tdd-verify [session-id]
argument-hint: "[WFS-session-id]"
examples:
- /workflow:tdd-verify
- /workflow:tdd-verify WFS-auth
allowed-tools: SlashCommand(*), TodoWrite(*), Read(*), Bash(gemini-wrapper:*)
---
# TDD Verification Command (/workflow:tdd-verify)
## 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
## 4-Phase Execution
### Phase 1: Session Discovery
**Auto-detect or use provided session**
```bash
# If session-id provided
sessionId = argument
# Else auto-detect active session
find .workflow/ -name '.active-*' | head -1 | sed 's/.*active-//'
```
**Extract**: sessionId
**Validation**: Session directory exists
**TodoWrite**: Mark phase 1 completed, phase 2 in_progress
---
### Phase 2: Task Chain Validation
**Validate TDD structure using bash commands**
```bash
# Load all task JSONs
find .workflow/{sessionId}/.task/ -name '*.json'
# Extract task IDs
find .workflow/{sessionId}/.task/ -name '*.json' -exec jq -r '.id' {} \;
# Check dependencies
find .workflow/{sessionId}/.task/ -name 'IMPL-*.json' -exec jq -r '.context.depends_on[]?' {} \;
find .workflow/{sessionId}/.task/ -name 'REFACTOR-*.json' -exec jq -r '.context.depends_on[]?' {} \;
# Check meta fields
find .workflow/{sessionId}/.task/ -name '*.json' -exec jq -r '.meta.tdd_phase' {} \;
find .workflow/{sessionId}/.task/ -name '*.json' -exec jq -r '.meta.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"
**Extract**: Chain validation report
**TodoWrite**: Mark phase 2 completed, phase 3 in_progress
---
### Phase 3: Test Execution Analysis
**Command**: `SlashCommand(command="/workflow:tools:tdd-coverage-analysis --session [sessionId]")`
**Input**: sessionId from Phase 1
**Parse Output**:
- Coverage metrics (line, branch, function percentages)
- TDD cycle verification results
- Compliance score
**Validation**:
- `.workflow/{sessionId}/.process/test-results.json` exists
- `.workflow/{sessionId}/.process/coverage-report.json` exists
- `.workflow/{sessionId}/.process/tdd-cycle-report.md` exists
**TodoWrite**: Mark phase 3 completed, phase 4 in_progress
---
### Phase 4: Compliance Report Generation
**Gemini analysis for comprehensive TDD compliance report**
```bash
cd project-root && ~/.claude/scripts/gemini-wrapper -p "
PURPOSE: Generate TDD compliance report
TASK: Analyze TDD workflow execution and generate quality report
CONTEXT: @{.workflow/{sessionId}/.task/*.json,.workflow/{sessionId}/.summaries/*,.workflow/{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.
" > .workflow/{sessionId}/TDD_COMPLIANCE_REPORT.md
```
**Output**: TDD_COMPLIANCE_REPORT.md
**TodoWrite**: Mark phase 4 completed
**Return to User**:
```
TDD Verification Report - Session: {sessionId}
## Chain Validation
✅ Feature 1: TEST-1.1 → IMPL-1.1 → REFACTOR-1.1 (Complete)
✅ Feature 2: TEST-2.1 → IMPL-2.1 → REFACTOR-2.1 (Complete)
⚠️ 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/{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
```
## TodoWrite Pattern
```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...
```
## Validation Logic
### Chain Validation Algorithm
```
1. Load all task JSONs from .workflow/{sessionId}/.task/
2. Extract task IDs and group by feature number
3. For each feature:
- Check TEST-N.M exists
- Check IMPL-N.M exists
- Check REFACTOR-N.M exists (optional but recommended)
- Verify IMPL-N.M depends_on TEST-N.M
- Verify REFACTOR-N.M depends_on IMPL-N.M
- Verify meta.tdd_phase values
- Verify meta.agent assignments
4. Calculate chain completeness score
5. Report incomplete or invalid chains
```
### Compliance Scoring
```
Base Score: 100 points
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
Final Score: Max(0, Base Score - Deductions)
```
## Output Files
```
.workflow/{session-id}/
├── TDD_COMPLIANCE_REPORT.md # Comprehensive compliance report ⭐
└── .process/
├── test-results.json # From tdd-coverage-analysis
├── coverage-report.json # From tdd-coverage-analysis
└── tdd-cycle-report.md # From tdd-coverage-analysis
```
## Error Handling
### Session Discovery Errors
| Error | Cause | Resolution |
|-------|-------|------------|
| No active session | No .active-* file | Provide session-id explicitly |
| Multiple active sessions | Multiple .active-* files | Provide session-id explicitly |
| Session not found | Invalid session-id | Check available sessions |
### Validation Errors
| Error | Cause | Resolution |
|-------|-------|------------|
| Task files missing | Incomplete planning | Run tdd-plan first |
| Invalid JSON | Corrupted task files | Regenerate tasks |
| Missing summaries | Tasks not executed | Execute tasks before verify |
### Analysis Errors
| Error | Cause | Resolution |
|-------|-------|------------|
| 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 |
## Integration & Usage
### Command Chain
- **Called After**: `/workflow:execute` (when TDD tasks completed)
- **Calls**: `/workflow:tools:tdd-coverage-analysis`, Gemini wrapper
- **Related**: `/workflow:tdd-plan`, `/workflow:status`
### Basic Usage
```bash
# Auto-detect active session
/workflow:tdd-verify
# Specify session
/workflow:tdd-verify WFS-auth
```
### When to Use
- After completing all TDD tasks in a workflow
- Before merging TDD workflow branch
- For TDD process quality assessment
- To identify missing TDD steps
## TDD Compliance Report Structure
```markdown
# TDD Compliance Report - {Session ID}
**Generated**: {timestamp}
**Session**: {sessionId}
**Workflow Type**: TDD
## Executive Summary
Overall Compliance Score: {score}/100
Status: {EXCELLENT | GOOD | NEEDS IMPROVEMENT | FAILED}
## Chain Analysis
### Feature 1: {Feature Name}
**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
### Feature 2: {Feature Name}
**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
**Issues**:
- REFACTOR-2.1 task not completed
- IMPL-2.1 implementation exceeded minimal scope
[Repeat for all features]
## Test Coverage Analysis
### Coverage Metrics
- Line Coverage: {percentage}% {status}
- Branch Coverage: {percentage}% {status}
- Function Coverage: {percentage}% {status}
### Coverage Gaps
- {file}:{lines} - Uncovered error handling
- {file}:{lines} - Uncovered edge case
## TDD Cycle Validation
### Red Phase (Write Failing Test)
- ✅ {N}/{total} features had failing tests initially
- ⚠️ Feature 3: No evidence of initial test failure
### Green Phase (Make Test Pass)
- ✅ {N}/{total} implementations made tests pass
- ✅ All implementations minimal and focused
### Refactor Phase (Improve Quality)
- ⚠️ {N}/{total} features completed refactoring
- ❌ Feature 2, 4: Refactoring step skipped
## Best Practices Assessment
### Strengths
- Clear test descriptions
- Good test coverage
- Consistent naming conventions
- Well-structured code
### Areas for Improvement
- Some implementations over-engineered in Green phase
- Missing refactoring steps
- Test failure messages could be more descriptive
## Recommendations
### High Priority
1. Complete missing REFACTOR tasks (Features 2, 4)
2. Verify initial test failures for Feature 3
3. Simplify over-engineered implementations
### Medium Priority
1. Add edge case tests for Features 1, 3
2. Improve test failure message clarity
3. Increase branch coverage to >85%
### Low Priority
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}
```
## Related Commands
- `/workflow:tdd-plan` - Creates TDD workflow
- `/workflow:execute` - Executes TDD tasks
- `/workflow:tools:tdd-coverage-analysis` - Analyzes test coverage
- `/workflow:status` - Views workflow progress

View File

@@ -0,0 +1,215 @@
---
name: task-generate-tdd
description: Generate TDD task chains with Red-Green-Refactor dependencies
usage: /workflow:tools:task-generate-tdd --session <session_id> [--agent]
argument-hint: "--session WFS-session-id [--agent]"
examples:
- /workflow:tools:task-generate-tdd --session WFS-auth
- /workflow:tools:task-generate-tdd --session WFS-auth --agent
allowed-tools: Read(*), Write(*), Bash(gemini-wrapper:*), TodoWrite(*)
---
# TDD Task Generation Command
## Overview
Generate TDD-specific task chains from analysis results with enforced Red-Green-Refactor structure and dependencies.
## Core Philosophy
- **TDD-First**: Every feature starts with a failing test
- **Chain-Enforced**: Dependencies ensure proper TDD cycle
- **Phase-Explicit**: Each task marked with Red/Green/Refactor phase
- **Artifact-Aware**: Integrates brainstorming outputs
- **Memory-First**: Reuse loaded documents from memory
## Core Responsibilities
- Parse analysis results and identify testable features
- Generate Red-Green-Refactor task chains for each feature
- Enforce proper dependencies (TEST → IMPL → REFACTOR)
- Create TDD_PLAN.md and enhanced IMPL_PLAN.md
- Generate TODO_LIST.md with TDD phase indicators
- Update session state for TDD execution
## Execution Lifecycle
### Phase 1: Input Validation & Discovery
**⚡ Memory-First Rule**: Skip file loading if documents already in conversation memory
1. **Session Validation**
- If session metadata in memory → Skip loading
- Else: Load `.workflow/{session_id}/workflow-session.json`
2. **Analysis Results Loading**
- If ANALYSIS_RESULTS.md in memory → Skip loading
- Else: Read `.workflow/{session_id}/.process/ANALYSIS_RESULTS.md`
3. **Artifact Discovery**
- If artifact inventory in memory → Skip scanning
- Else: Scan `.workflow/{session_id}/.brainstorming/` directory
- Detect: synthesis-specification.md, topic-framework.md, role analyses
### Phase 2: TDD Task Analysis
#### Gemini TDD Breakdown
```bash
cd project-root && ~/.claude/scripts/gemini-wrapper -p "
PURPOSE: Generate TDD task breakdown with Red-Green-Refactor chains
TASK: Analyze ANALYSIS_RESULTS.md and create TDD-structured task breakdown
CONTEXT: @{.workflow/{session_id}/ANALYSIS_RESULTS.md,.workflow/{session_id}/.brainstorming/*}
EXPECTED:
- Feature list with testable requirements (identify 3-8 features)
- Test cases for each feature (Red phase) - specific test scenarios
- Implementation requirements (Green phase) - minimal code to pass
- Refactoring opportunities (Refactor phase) - quality improvements
- Task dependencies and execution order
- Focus paths for each phase
RULES:
- Each feature must have TEST → IMPL → REFACTOR chain
- Tests must define clear failure conditions
- Implementation must be minimal to pass tests
- Refactoring must maintain green tests
- Output structured markdown for task generation
- Maximum 10 features (30 total tasks)
" > .workflow/{session_id}/.process/TDD_TASK_BREAKDOWN.md
```
### Phase 3: TDD Task JSON Generation
#### Task Chain Structure
For each feature, generate 3 tasks with ID format:
- **TEST-N.M** (Red phase)
- **IMPL-N.M** (Green phase)
- **REFACTOR-N.M** (Refactor phase)
#### Chain Dependency Rules
- **IMPL depends_on TEST**: Cannot implement before test exists
- **REFACTOR depends_on IMPL**: Cannot refactor before implementation
- **Cross-feature dependencies**: If Feature 2 needs Feature 1, then `IMPL-2.1 depends_on ["REFACTOR-1.1"]`
#### Agent Assignment
- **TEST tasks** → `@code-review-test-agent`
- **IMPL tasks** → `@code-developer`
- **REFACTOR tasks** → `@code-developer`
#### Meta Fields
- `meta.type`: "test" | "feature" | "refactor"
- `meta.agent`: Agent for task execution
- `meta.tdd_phase`: "red" | "green" | "refactor"
### Phase 4: TDD_PLAN.md Generation
Generate TDD-specific plan with:
- Feature breakdown
- Red-Green-Refactor chains
- Execution order
- TDD compliance checkpoints
### Phase 5: Enhanced IMPL_PLAN.md Generation
Generate standard IMPL_PLAN.md with TDD context reference.
### Phase 6: TODO_LIST.md Generation
Generate task list with TDD phase indicators:
```markdown
## Feature 1: {Feature Name}
- [ ] **TEST-1.1**: Write failing test (🔴 RED) → [📋](./.task/TEST-1.1.json)
- [ ] **IMPL-1.1**: Implement to pass tests (🟢 GREEN) [depends: TEST-1.1] → [📋](./.task/IMPL-1.1.json)
- [ ] **REFACTOR-1.1**: Refactor implementation (🔵 REFACTOR) [depends: IMPL-1.1] → [📋](./.task/REFACTOR-1.1.json)
```
### Phase 7: Session State Update
Update workflow-session.json with TDD metadata:
```json
{
"workflow_type": "tdd",
"feature_count": 10,
"task_count": 30,
"tdd_chains": 10
}
```
## Output Files Structure
```
.workflow/{session-id}/
├── IMPL_PLAN.md # Standard implementation plan
├── TDD_PLAN.md # TDD-specific plan ⭐ NEW
├── TODO_LIST.md # Progress tracking with TDD phases
├── .task/
│ ├── TEST-1.1.json # Red phase task
│ ├── IMPL-1.1.json # Green phase task
│ ├── REFACTOR-1.1.json # Refactor phase task
│ └── ...
└── .process/
├── ANALYSIS_RESULTS.md # Input from concept-enhanced
├── TDD_TASK_BREAKDOWN.md # Gemini TDD breakdown ⭐ NEW
└── context-package.json # Input from context-gather
```
## Validation Rules
### Chain Completeness
- Every TEST-N.M must have corresponding IMPL-N.M and REFACTOR-N.M
### Dependency Enforcement
- IMPL-N.M must have `depends_on: ["TEST-N.M"]`
- REFACTOR-N.M must have `depends_on: ["IMPL-N.M"]`
### Task Limits
- Maximum 10 features (30 tasks total)
- Flat hierarchy only
## Error Handling
### Input Validation Errors
| Error | Cause | Resolution |
|-------|-------|------------|
| Session not found | Invalid session ID | Verify session exists |
| Analysis missing | Incomplete planning | Run concept-enhanced first |
### TDD Generation Errors
| Error | Cause | Resolution |
|-------|-------|------------|
| Feature count exceeds 10 | Too many features | Re-scope requirements |
| Missing test framework | No test config | Configure testing first |
| Invalid chain structure | Parsing error | Fix TDD breakdown |
## Integration & Usage
### Command Chain
- **Called By**: `/workflow:tdd-plan` (Phase 4)
- **Calls**: Gemini wrapper for TDD breakdown
- **Followed By**: `/workflow:execute`, `/workflow:tdd-verify`
### Basic Usage
```bash
# Manual mode (default)
/workflow:tools:task-generate-tdd --session WFS-auth
# Agent mode (autonomous task generation)
/workflow:tools:task-generate-tdd --session WFS-auth --agent
```
### Expected Output
```
TDD task generation complete for session: WFS-auth
Features analyzed: 5
TDD chains generated: 5
Total tasks: 15 (5 TEST + 5 IMPL + 5 REFACTOR)
Structure:
- Feature 1: TEST-1.1 → IMPL-1.1 → REFACTOR-1.1
- Feature 2: TEST-2.1 → IMPL-2.1 → REFACTOR-2.1
Plans generated:
- TDD Plan: .workflow/WFS-auth/TDD_PLAN.md
- Implementation Plan: .workflow/WFS-auth/IMPL_PLAN.md
Next: /workflow:execute or /workflow:tdd-verify
```
## Related Commands
- `/workflow:tdd-plan` - Orchestrates TDD workflow planning
- `/workflow:execute` - Executes TDD tasks in order
- `/workflow:tdd-verify` - Verifies TDD compliance

View File

@@ -0,0 +1,580 @@
# TDD Workflow Implementation Roadmap
## Overview
This roadmap outlines the implementation steps for the TDD workflow system, organized by priority and dependencies.
## Phase 1: Core TDD Task Generation (Foundation)
### Priority: HIGH
### Dependencies: None
### Estimated Effort: Medium
#### 1.1 Create task-generate-tdd Command
**File**: `.claude/commands/workflow/tools/task-generate-tdd.md`
**Implementation Steps**:
1. Copy structure from `task-generate.md`
2. Add TDD-specific Gemini prompt for task breakdown
3. Implement Red-Green-Refactor task chain generation logic
4. Add `meta.tdd_phase` field to task JSONs
5. Implement dependency enforcement (TEST → IMPL → REFACTOR)
6. Generate TDD_PLAN.md alongside IMPL_PLAN.md
**Key Features**:
- Gemini-based TDD task analysis
- Automatic chain creation for each feature
- Validation of TDD structure
- Support for both manual and agent modes
**Testing**:
- Test with single feature
- Test with multiple features
- Verify dependency chains
- Validate JSON schema compliance
---
## Phase 2: TDD Planning Orchestrator
### Priority: HIGH
### Dependencies: Phase 1
### Estimated Effort: Medium
#### 2.1 Create tdd-plan Command
**File**: `.claude/commands/workflow/tdd-plan.md`
**Implementation Steps**:
1. Copy orchestrator pattern from `plan.md`
2. Modify Phase 4 to call `task-generate-tdd` instead of `task-generate`
3. Add Phase 5 for TDD structure validation
4. Update structured input format to include TEST_FOCUS
5. Customize TodoWrite pattern for TDD phases
6. Design TDD-specific output summary
**Key Features**:
- 5-phase orchestration (adds validation phase)
- Reuses existing session:start, context-gather, concept-enhanced
- TDD-specific task generation in Phase 4
- Structure validation in Phase 5
- Clear TDD chain summary in output
**Testing**:
- End-to-end TDD workflow creation
- Verify all phases execute correctly
- Validate generated task structure
- Test with different input formats
---
## Phase 3: TDD Coverage Analysis Tool
### Priority: MEDIUM
### Dependencies: Phase 1
### Estimated Effort: Small
#### 3.1 Create tdd-coverage-analysis Command
**File**: `.claude/commands/workflow/tools/tdd-coverage-analysis.md`
**Implementation Steps**:
1. Create command specification
2. Implement test task extraction logic
3. Add test execution wrapper
4. Implement coverage data parsing
5. Add TDD cycle verification logic
6. Generate analysis report
**Key Features**:
- Extract test files from TEST tasks
- Run test suite with coverage
- Verify Red-Green-Refactor cycle
- Generate coverage metrics
- Identify gaps in TDD process
**Testing**:
- Test with completed TDD workflow
- Verify coverage data accuracy
- Test cycle verification logic
- Validate report generation
---
## Phase 4: TDD Verification Orchestrator
### Priority: MEDIUM
### Dependencies: Phase 1, Phase 3
### Estimated Effort: Medium
#### 4.1 Create tdd-verify Command
**File**: `.claude/commands/workflow/tdd-verify.md`
**Implementation Steps**:
1. Create 4-phase orchestrator structure
2. Implement session discovery logic
3. Add task chain validation
4. Integrate tdd-coverage-analysis
5. Add Gemini compliance report generation
6. Design verification output summary
**Key Features**:
- Automatic session detection
- Task chain structure validation
- Test execution analysis
- Compliance scoring
- Detailed quality recommendations
- Clear verification summary
**Testing**:
- Test with complete TDD workflow
- Test with incomplete workflow
- Verify compliance scoring
- Test report generation
---
## Phase 5: TDD Templates and Documentation
### Priority: MEDIUM
### Dependencies: Phases 1-4
### Estimated Effort: Small
#### 5.1 Create TDD Prompt Templates
**Files**:
- `.claude/workflows/cli-templates/prompts/development/tdd-test.txt`
- `.claude/workflows/cli-templates/prompts/development/tdd-impl.txt`
- `.claude/workflows/cli-templates/prompts/development/tdd-refactor.txt`
**Implementation Steps**:
1. Design test-writing template (Red phase)
2. Design implementation template (Green phase)
3. Design refactoring template (Refactor phase)
4. Include TDD best practices
5. Add specific acceptance criteria
**Key Features**:
- Phase-specific guidance
- TDD best practices embedded
- Clear acceptance criteria
- Agent-friendly format
#### 5.2 Update Core Documentation
**Files to Update**:
- `.claude/workflows/workflow-architecture.md`
- `.claude/workflows/task-core.md`
- `README.md`
**Updates Required**:
1. Add TDD workflow section to architecture
2. Document `meta.tdd_phase` field in task-core
3. Add TDD usage examples to README
4. Create TDD workflow diagram
5. Add troubleshooting guide
---
## Phase 6: Integration and Polish
### Priority: LOW
### Dependencies: Phases 1-5
### Estimated Effort: Small
#### 6.1 Command Registry Updates
**Files**:
- `.claude/commands.json` (if exists)
- Slash command documentation
**Updates**:
1. Register new commands
2. Update command help text
3. Add command shortcuts
4. Update command examples
#### 6.2 Testing and Validation
**Activities**:
1. End-to-end integration testing
2. Performance testing
3. Error handling validation
4. Documentation review
5. User acceptance testing
---
## Implementation Priority Matrix
```
Priority | Phase | Component | Effort | Dependencies
---------|-------|------------------------------|--------|-------------
HIGH | 1 | task-generate-tdd | Medium | None
HIGH | 2 | tdd-plan | Medium | Phase 1
MEDIUM | 3 | tdd-coverage-analysis | Small | Phase 1
MEDIUM | 4 | tdd-verify | Medium | Phase 1, 3
MEDIUM | 5 | Templates & Documentation | Small | Phase 1-4
LOW | 6 | Integration & Polish | Small | Phase 1-5
```
---
## Detailed Component Specifications
### Component 1: task-generate-tdd
**Inputs**:
- `--session <sessionId>`: Required session identifier
- `--agent`: Optional flag for agent mode
- ANALYSIS_RESULTS.md from session
**Outputs**:
- `TDD_PLAN.md`: TDD-specific implementation plan
- `IMPL_PLAN.md`: Standard implementation plan
- `TODO_LIST.md`: Task list with TDD phases
- `.task/TEST-*.json`: Test task files
- `.task/IMPL-*.json`: Implementation task files
- `.task/REFACTOR-*.json`: Refactoring task files
**Core Logic**:
```
1. Load ANALYSIS_RESULTS.md
2. Call Gemini to identify features and create TDD breakdown
3. For each feature:
a. Create TEST task (Red phase)
b. Create IMPL task with depends_on TEST (Green phase)
c. Create REFACTOR task with depends_on IMPL (Refactor phase)
4. Validate chain structure
5. Generate TDD_PLAN.md
6. Generate IMPL_PLAN.md
7. Generate TODO_LIST.md
8. Return task count and chain summary
```
**Gemini Prompt Structure**:
```
PURPOSE: Generate TDD task breakdown with Red-Green-Refactor chains
TASK: Analyze ANALYSIS_RESULTS.md and create TDD-structured task breakdown
CONTEXT: @{.workflow/[sessionId]/ANALYSIS_RESULTS.md}
EXPECTED:
- Feature list with testable requirements
- Test cases for each feature (Red phase)
- Implementation requirements (Green phase)
- Refactoring opportunities (Refactor phase)
- Task dependencies and execution order
RULES: Each feature must have TEST → IMPL → REFACTOR chain. Output structured markdown.
```
**Validation Rules**:
- Each TEST task must have ID format `TEST-N.M`
- Each IMPL task must have `depends_on: ["TEST-N.M"]`
- Each REFACTOR task must have `depends_on: ["IMPL-N.M"]`
- All tasks must have `meta.tdd_phase` field
- Agent must be appropriate for phase
---
### Component 2: tdd-plan
**Inputs**:
- `<input>`: Feature description, file path, or issue ID
- `--agent`: Optional flag for agent mode
**Outputs**:
- Session summary with TDD chain information
- All standard workflow outputs
- TDD_PLAN.md
**Phase Breakdown**:
**Phase 1: Session Discovery** (Reused)
- Command: `/workflow:session:start --auto "TDD: ..."`
- Extract: sessionId
**Phase 2: Context Gathering** (Reused)
- Command: `/workflow:tools:context-gather --session sessionId ...`
- Extract: contextPath
**Phase 3: TDD Analysis** (Reused)
- Command: `/workflow:tools:concept-enhanced --session sessionId --context contextPath`
- Extract: ANALYSIS_RESULTS.md
**Phase 4: TDD Task Generation** (New)
- Command: `/workflow:tools:task-generate-tdd --session sessionId [--agent]`
- Extract: Task count, chain count
**Phase 5: Structure Validation** (New)
- Internal validation
- Verify chain completeness
- Verify dependencies
- Extract: Validation status
**TodoWrite Pattern**:
```javascript
// Initialize
[
{content: "Execute session discovery", status: "in_progress", activeForm: "Executing session discovery"},
{content: "Execute context gathering", status: "pending", activeForm: "Executing context gathering"},
{content: "Execute TDD analysis", status: "pending", activeForm: "Executing TDD analysis"},
{content: "Execute TDD task generation", status: "pending", activeForm: "Executing TDD task generation"},
{content: "Validate TDD structure", status: "pending", activeForm: "Validating TDD structure"}
]
// After each phase, update one to "completed", next to "in_progress"
```
**Output Template**:
```
TDD Planning complete for session: {sessionId}
Features analyzed: {count}
TDD chains generated: {count}
Total tasks: {count}
Structure:
- {Feature 1}: TEST-1.1 → IMPL-1.1 → REFACTOR-1.1
- {Feature 2}: TEST-2.1 → IMPL-2.1 → REFACTOR-2.1
Plans:
- Implementation: .workflow/{sessionId}/IMPL_PLAN.md
- TDD Structure: .workflow/{sessionId}/TDD_PLAN.md
Next: /workflow:execute or /workflow:tdd-verify
```
---
### Component 3: tdd-coverage-analysis
**Inputs**:
- `--session <sessionId>`: Required session identifier
**Outputs**:
- `.process/test-results.json`: Test execution results
- `.process/coverage-report.json`: Coverage metrics
- `.process/tdd-cycle-report.md`: TDD cycle verification
**Core Logic**:
```
1. Extract all TEST tasks from session
2. Identify test files from focus_paths
3. Run test suite with coverage
4. Parse coverage data
5. For each TDD chain:
a. Verify TEST task created tests
b. Verify IMPL task made tests pass
c. Verify REFACTOR task maintained green tests
6. Generate cycle verification report
7. Return coverage metrics and cycle status
```
**Test Execution**:
```bash
npm test -- --coverage --json > .process/test-results.json
# or
pytest --cov --json-report > .process/test-results.json
```
**Cycle Verification Algorithm**:
```
For each chain (TEST-N.M, IMPL-N.M, REFACTOR-N.M):
1. Read TEST-N.M-summary.md
- Check: Tests were created
- Check: Tests failed initially
2. Read IMPL-N.M-summary.md
- Check: Implementation was completed
- Check: Tests now pass
3. Read REFACTOR-N.M-summary.md
- Check: Refactoring was completed
- Check: Tests still pass
If all checks pass: Chain is valid
Else: Report missing steps
```
---
### Component 4: tdd-verify
**Inputs**:
- `[session-id]`: Optional session ID (auto-detect if not provided)
**Outputs**:
- Verification summary
- TDD_COMPLIANCE_REPORT.md
**Phase Breakdown**:
**Phase 1: Session Discovery**
```bash
# If session-id provided
sessionId = argument
# Else auto-detect
sessionId = $(find .workflow/ -name '.active-*' | head -1 | sed 's/.*active-//')
```
**Phase 2: Task Chain Validation**
```bash
# Load all task JSONs
tasks=$(find .workflow/${sessionId}/.task/ -name '*.json')
# For each TDD chain
for feature in features:
verify_chain_exists(TEST-N.M, IMPL-N.M, REFACTOR-N.M)
verify_dependencies(IMPL depends_on TEST, REFACTOR depends_on IMPL)
verify_meta_fields(tdd_phase, agent)
```
**Phase 3: Test Execution Analysis**
```bash
/workflow:tools:tdd-coverage-analysis --session ${sessionId}
```
**Phase 4: Compliance Report**
```bash
cd project-root && ~/.claude/scripts/gemini-wrapper -p "
PURPOSE: Generate TDD compliance report
TASK: Analyze TDD workflow execution and generate quality report
CONTEXT: @{.workflow/${sessionId}/.task/*.json,.workflow/${sessionId}/.summaries/*}
EXPECTED:
- TDD compliance score
- Chain completeness verification
- Test coverage analysis
- Quality recommendations
- Red-Green-Refactor cycle validation
RULES: Focus on TDD best practices and workflow adherence
" > .workflow/${sessionId}/TDD_COMPLIANCE_REPORT.md
```
**Output Template**:
```
TDD Verification Report - Session: {sessionId}
## Chain Validation
{status} Feature 1: TEST-1.1 → IMPL-1.1 → REFACTOR-1.1 ({status})
{status} Feature 2: TEST-2.1 → IMPL-2.1 → REFACTOR-2.1 ({status})
## Test Execution
{status} All TEST tasks produced failing tests
{status} All IMPL tasks made tests pass
{status} All REFACTOR tasks maintained green tests
## Compliance Score: {score}/100
Detailed report: .workflow/{sessionId}/TDD_COMPLIANCE_REPORT.md
Recommendations:
{recommendations}
```
---
## File Structure Reference
```
.workflow/
└── WFS-{session-id}/
├── ANALYSIS_RESULTS.md # From concept-enhanced
├── IMPL_PLAN.md # Standard plan
├── TDD_PLAN.md # TDD-specific plan ⭐ NEW
├── TODO_LIST.md # With TDD phase markers
├── TDD_COMPLIANCE_REPORT.md # From tdd-verify ⭐ NEW
├── .task/
│ ├── TEST-1.1.json # Red phase ⭐ NEW
│ ├── IMPL-1.1.json # Green phase (enhanced)
│ ├── REFACTOR-1.1.json # Refactor phase ⭐ NEW
│ └── ...
├── .summaries/
│ ├── TEST-1.1-summary.md # Test task summary
│ ├── IMPL-1.1-summary.md # Implementation summary
│ ├── REFACTOR-1.1-summary.md # Refactor summary
│ └── ...
└── .process/
├── TDD_TASK_BREAKDOWN.md # Gemini breakdown ⭐ NEW
├── test-results.json # Test execution ⭐ NEW
├── coverage-report.json # Coverage data ⭐ NEW
└── tdd-cycle-report.md # Cycle verification ⭐ NEW
```
---
## Implementation Order
### Week 1: Foundation
1. Create `task-generate-tdd.md` specification
2. Implement Gemini TDD breakdown logic
3. Implement task JSON generation with TDD chains
4. Test with simple single-feature workflow
### Week 2: Orchestration
1. Create `tdd-plan.md` specification
2. Implement 5-phase orchestrator
3. Integrate with task-generate-tdd
4. End-to-end testing
### Week 3: Verification
1. Create `tdd-coverage-analysis.md` specification
2. Implement test execution and cycle verification
3. Create `tdd-verify.md` specification
4. Implement verification orchestrator
5. Integration testing
### Week 4: Polish
1. Create TDD prompt templates
2. Update documentation
3. Create usage examples
4. Final integration testing
5. User acceptance testing
---
## Success Criteria
### Functional Requirements
- [ ] TDD workflows can be created from feature descriptions
- [ ] Task chains enforce Red-Green-Refactor order
- [ ] Dependencies prevent out-of-order execution
- [ ] Verification detects non-compliance
- [ ] Coverage analysis integrates with test tools
- [ ] Reports provide actionable insights
### Quality Requirements
- [ ] Commands follow existing architectural patterns
- [ ] Error handling is robust
- [ ] Documentation is complete
- [ ] Examples demonstrate common use cases
- [ ] Integration with existing workflow is seamless
### Performance Requirements
- [ ] TDD planning completes within 2 minutes
- [ ] Verification completes within 1 minute
- [ ] Gemini analysis stays within token limits
- [ ] Test execution doesn't timeout
---
## Risk Mitigation
### Risk 1: Test Framework Integration
**Mitigation**: Support multiple test frameworks (npm test, pytest, etc.) with configurable commands
### Risk 2: Gemini Token Limits
**Mitigation**: Use focused context in prompts, paginate large analysis
### Risk 3: Complex Dependencies
**Mitigation**: Thorough validation logic, clear error messages
### Risk 4: User Adoption
**Mitigation**: Clear documentation, simple examples, gradual rollout
---
## Next Steps
1. **Review Design**: Get feedback on architecture and specifications
2. **Create Prototype**: Implement Phase 1 (task-generate-tdd) as proof of concept
3. **Test Prototype**: Validate with real-world TDD workflow
4. **Iterate**: Refine based on testing feedback
5. **Full Implementation**: Complete remaining phases
6. **Documentation**: Create user guides and examples
7. **Release**: Roll out to users with migration guide

View File

@@ -0,0 +1,617 @@
# TDD Workflow Design Specification
## Architecture Overview
The TDD workflow introduces a specialized planning and verification system that enforces Test-Driven Development principles through the existing workflow architecture. It follows the same orchestrator pattern as `/workflow:plan` but generates TDD-specific task chains.
## Command Structure
### Primary Commands (Orchestrators)
- `/workflow:tdd-plan` - TDD workflow planning orchestrator
- `/workflow:tdd-verify` - TDD compliance verification orchestrator
### Tool Commands (Executors)
- `/workflow:tools:task-generate-tdd` - TDD-specific task generator
- `/workflow:tools:tdd-coverage-analysis` - Test coverage analyzer
---
## 1. /workflow:tdd-plan Command
### Purpose
Orchestrate TDD-specific workflow planning that generates Red-Green-Refactor task chains with enforced dependencies.
### Command Specification
```yaml
name: tdd-plan
description: Orchestrate TDD workflow planning with Red-Green-Refactor task chains
usage: /workflow:tdd-plan [--agent] <input>
argument-hint: "[--agent] \"feature description\"|file.md|ISS-001"
examples:
- /workflow:tdd-plan "Implement user authentication"
- /workflow:tdd-plan --agent requirements.md
- /workflow:tdd-plan ISS-001
allowed-tools: SlashCommand(*), TodoWrite(*), Read(*), Bash(*)
```
### Execution Flow (5 Phases)
**Phase 1: Session Discovery**
```bash
/workflow:session:start --auto "TDD: [structured-description]"
```
- Extract: `sessionId` (WFS-xxx)
- Validation: Session directory created
**Phase 2: Context Gathering**
```bash
/workflow:tools:context-gather --session [sessionId] "TDD: [structured-description]"
```
- Extract: `contextPath` (context-package.json)
- Validation: Context package exists
**Phase 3: TDD Analysis**
```bash
/workflow:tools:concept-enhanced --session [sessionId] --context [contextPath]
```
- Extract: ANALYSIS_RESULTS.md
- Validation: Contains TDD-specific recommendations
**Phase 4: TDD Task Generation**
```bash
# Manual mode (default)
/workflow:tools:task-generate-tdd --session [sessionId]
# Agent mode
/workflow:tools:task-generate-tdd --session [sessionId] --agent
```
- Extract: Task count, TDD chain count
- Validation:
- IMPL_PLAN.md exists
- TDD_PLAN.md exists (TDD-specific plan)
- Task JSONs follow Red-Green-Refactor pattern
- Dependencies correctly enforced
**Phase 5: TDD Structure Validation**
```bash
# Internal validation step (no separate command call)
# Verify task chain structure:
# - Each feature has TEST → IMPL → REFACTOR sequence
# - Dependencies are correctly set
# - Meta.type fields are appropriate
```
- Extract: Validation report
- Validation: All TDD chains valid
### Structured Input Format
```
TDD: [feature-name]
GOAL: [Clear objective]
SCOPE: [What to test and implement]
CONTEXT: [Relevant background]
TEST_FOCUS: [Critical test scenarios]
```
### TDD-Specific TodoWrite Pattern
```javascript
TodoWrite({todos: [
{"content": "Execute session discovery", "status": "in_progress", "activeForm": "Executing session discovery"},
{"content": "Execute context gathering", "status": "pending", "activeForm": "Executing context gathering"},
{"content": "Execute TDD analysis", "status": "pending", "activeForm": "Executing TDD analysis"},
{"content": "Execute TDD task generation", "status": "pending", "activeForm": "Executing TDD task generation"},
{"content": "Validate TDD structure", "status": "pending", "activeForm": "Validating TDD structure"}
]})
```
### Output Structure
```
TDD Planning complete for session: [sessionId]
Features analyzed: [count]
TDD chains generated: [count]
Total tasks: [count]
Structure:
- [Feature 1]: TEST-1 → IMPL-1 → REFACTOR-1
- [Feature 2]: TEST-2 → IMPL-2 → REFACTOR-2
Plans:
- Implementation: .workflow/[sessionId]/IMPL_PLAN.md
- TDD Structure: .workflow/[sessionId]/TDD_PLAN.md
Next: /workflow:execute or /workflow:tdd-verify
```
---
## 2. /workflow:tools:task-generate-tdd Command
### Purpose
Generate TDD-specific task chains from ANALYSIS_RESULTS.md with enforced Red-Green-Refactor structure.
### Command Specification
```yaml
name: task-generate-tdd
description: Generate TDD task chains with Red-Green-Refactor dependencies
usage: /workflow:tools:task-generate-tdd --session <session-id> [--agent]
argument-hint: "--session WFS-xxx [--agent]"
examples:
- /workflow:tools:task-generate-tdd --session WFS-auth
- /workflow:tools:task-generate-tdd --session WFS-auth --agent
allowed-tools: Read(*), Write(*), Bash(gemini-wrapper:*)
```
### Implementation Flow
**Step 1: Load Analysis**
```bash
cat .workflow/[sessionId]/ANALYSIS_RESULTS.md
```
**Step 2: Gemini TDD Task Planning**
```bash
cd project-root && ~/.claude/scripts/gemini-wrapper -p "
PURPOSE: Generate TDD task breakdown with Red-Green-Refactor chains
TASK: Analyze ANALYSIS_RESULTS.md and create TDD-structured task breakdown
CONTEXT: @{.workflow/[sessionId]/ANALYSIS_RESULTS.md}
EXPECTED:
- Feature list with testable requirements
- Test cases for each feature (Red phase)
- Implementation requirements (Green phase)
- Refactoring opportunities (Refactor phase)
- Task dependencies and execution order
RULES: Each feature must have TEST → IMPL → REFACTOR chain. Output structured markdown for task generation.
" > .workflow/[sessionId]/.process/TDD_TASK_BREAKDOWN.md
```
**Step 3: Generate Task JSONs**
For each feature identified:
```json
// TEST Phase (Red)
{
"id": "TEST-1.1",
"title": "Write failing test for [feature]",
"status": "pending",
"meta": {
"type": "test",
"agent": "@code-review-test-agent",
"tdd_phase": "red"
},
"context": {
"requirements": ["Write test case that fails", "Test should define expected behavior"],
"focus_paths": ["tests/[feature]"],
"acceptance": ["Test written and fails with clear error message"],
"depends_on": []
}
}
// IMPL Phase (Green)
{
"id": "IMPL-1.1",
"title": "Implement [feature] to pass tests",
"status": "pending",
"meta": {
"type": "feature",
"agent": "@code-developer",
"tdd_phase": "green"
},
"context": {
"requirements": ["Implement minimal code to pass TEST-1.1"],
"focus_paths": ["src/[feature]", "tests/[feature]"],
"acceptance": ["All tests in TEST-1.1 pass"],
"depends_on": ["TEST-1.1"]
},
"flow_control": {
"pre_analysis": [
{
"step": "load_test_requirements",
"action": "Read test specifications from TEST phase",
"command": "bash(cat .workflow/[sessionId]/.summaries/TEST-1.1-summary.md)",
"output_to": "test_requirements",
"on_error": "fail"
}
]
}
}
// REFACTOR Phase
{
"id": "REFACTOR-1.1",
"title": "Refactor [feature] implementation",
"status": "pending",
"meta": {
"type": "refactor",
"agent": "@code-developer",
"tdd_phase": "refactor"
},
"context": {
"requirements": ["Improve code quality while keeping tests green", "Remove duplication", "Improve readability"],
"focus_paths": ["src/[feature]", "tests/[feature]"],
"acceptance": ["Code improved", "All tests still pass"],
"depends_on": ["IMPL-1.1"]
},
"flow_control": {
"pre_analysis": [
{
"step": "verify_tests_passing",
"action": "Run tests to confirm green state before refactoring",
"command": "bash(npm test -- tests/[feature])",
"output_to": "test_status",
"on_error": "fail"
}
]
}
}
```
**Step 4: Generate TDD_PLAN.md**
```markdown
# TDD Implementation Plan - [Session ID]
## Features and Test Chains
### Feature 1: [Feature Name]
**TDD Chain**: TEST-1.1 → IMPL-1.1 → REFACTOR-1.1
**Red Phase (TEST-1.1)**
- Write failing test for [specific behavior]
- Test assertions: [list]
**Green Phase (IMPL-1.1)**
- Implement minimal solution
- Dependencies: TEST-1.1 must fail first
**Refactor Phase (REFACTOR-1.1)**
- Improve: [specific improvements]
- Constraint: All tests must remain green
[Repeat for each feature]
## Execution Order
1. TEST-1.1 → IMPL-1.1 → REFACTOR-1.1
2. TEST-2.1 → IMPL-2.1 → REFACTOR-2.1
...
## TDD Compliance Checkpoints
- [ ] Each feature starts with failing test
- [ ] Implementation passes all tests
- [ ] Refactoring maintains green tests
- [ ] No implementation before tests
```
**Step 5: Generate TODO_LIST.md**
Standard todo list with TDD phase indicators:
```markdown
## Pending Tasks
- [ ] TEST-1.1: Write failing test for [feature] (RED)
- [ ] IMPL-1.1: Implement [feature] to pass tests (GREEN) [depends: TEST-1.1]
- [ ] REFACTOR-1.1: Refactor [feature] implementation (REFACTOR) [depends: IMPL-1.1]
```
### Validation Rules
1. **Chain Completeness**: Every TEST task must have corresponding IMPL and REFACTOR tasks
2. **Dependency Enforcement**:
- IMPL depends_on TEST
- REFACTOR depends_on IMPL
3. **Agent Assignment**:
- TEST tasks → `@code-review-test-agent`
- IMPL/REFACTOR tasks → `@code-developer`
4. **Meta Fields**:
- `meta.tdd_phase` must be "red", "green", or "refactor"
- `meta.type` must align with phase
---
## 3. /workflow:tdd-verify Command
### Purpose
Verify TDD workflow compliance, test coverage, and Red-Green-Refactor cycle execution.
### Command Specification
```yaml
name: tdd-verify
description: Verify TDD workflow compliance and generate quality report
usage: /workflow:tdd-verify [session-id]
argument-hint: "[WFS-session-id]"
examples:
- /workflow:tdd-verify
- /workflow:tdd-verify WFS-auth
allowed-tools: SlashCommand(*), TodoWrite(*), Read(*), Bash(*)
```
### Execution Flow (4 Phases)
**Phase 1: Session Discovery**
```bash
# Auto-detect or use provided session
find .workflow/ -name '.active-*' | head -1 | sed 's/.*active-//'
```
- Extract: `sessionId`
**Phase 2: Task Chain Validation**
```bash
# Bash script to validate TDD structure
find .workflow/[sessionId]/.task/ -name '*.json' -exec jq -r '.meta.tdd_phase' {} \;
```
- Verify: TEST → IMPL → REFACTOR chains exist
- Verify: Dependencies are correct
- Extract: Chain validation report
**Phase 3: Test Execution Analysis**
```bash
/workflow:tools:tdd-coverage-analysis --session [sessionId]
```
- Run tests from TEST tasks
- Verify IMPL tasks made tests pass
- Check REFACTOR tasks maintained green tests
- Extract: Test execution report
**Phase 4: Compliance Report Generation**
```bash
# Gemini analysis
cd project-root && ~/.claude/scripts/gemini-wrapper -p "
PURPOSE: Generate TDD compliance report
TASK: Analyze TDD workflow execution and generate quality report
CONTEXT: @{.workflow/[sessionId]/.task/*.json,.workflow/[sessionId]/.summaries/*}
EXPECTED:
- TDD compliance score
- Chain completeness verification
- Test coverage analysis
- Quality recommendations
- Red-Green-Refactor cycle validation
RULES: Focus on TDD best practices and workflow adherence
" > .workflow/[sessionId]/TDD_COMPLIANCE_REPORT.md
```
### TodoWrite Pattern
```javascript
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"}
]})
```
### Output Structure
```
TDD Verification Report - Session: [sessionId]
## Chain Validation
✅ Feature 1: TEST-1.1 → IMPL-1.1 → REFACTOR-1.1 (Complete)
✅ Feature 2: TEST-2.1 → IMPL-2.1 → REFACTOR-2.1 (Complete)
⚠️ 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
## Compliance Score: 95/100
Detailed report: .workflow/[sessionId]/TDD_COMPLIANCE_REPORT.md
Recommendations:
- Complete missing REFACTOR-3.1 task
- Consider additional edge case tests for Feature 2
```
---
## 4. /workflow:tools:tdd-coverage-analysis Command
### Purpose
Analyze test coverage and execution results for TDD workflow validation.
### Command Specification
```yaml
name: tdd-coverage-analysis
description: Analyze test coverage and TDD cycle execution
usage: /workflow:tools:tdd-coverage-analysis --session <session-id>
argument-hint: "--session WFS-xxx"
examples:
- /workflow:tools:tdd-coverage-analysis --session WFS-auth
allowed-tools: Read(*), Write(*), Bash(*)
```
### Implementation Flow
**Step 1: Extract Test Tasks**
```bash
find .workflow/[sessionId]/.task/ -name 'TEST-*.json' -exec jq -r '.context.focus_paths[]' {} \;
```
**Step 2: Run Test Suite**
```bash
npm test -- --coverage --json > .workflow/[sessionId]/.process/test-results.json
```
**Step 3: Analyze Coverage**
```bash
jq '.coverage' .workflow/[sessionId]/.process/test-results.json > .workflow/[sessionId]/.process/coverage-report.json
```
**Step 4: Verify TDD Cycle**
For each chain:
- Check TEST task created test files
- Check IMPL task made tests pass
- Check REFACTOR task didn't break tests
**Step 5: Generate Analysis Report**
```markdown
# Test Coverage Analysis
## Coverage Metrics
- Line Coverage: X%
- Branch Coverage: Y%
- Function Coverage: Z%
## TDD Cycle Verification
- Red Phase: X tests written and failed initially
- Green Phase: Y implementations made tests pass
- Refactor Phase: Z refactorings maintained green tests
## Gaps Identified
- [List any missing test coverage]
- [List any incomplete TDD cycles]
```
---
## Integration with Existing System
### Data Flow Diagram
```
User Input
/workflow:tdd-plan "feature description"
Phase 1: /workflow:session:start --auto "TDD: ..."
↓ sessionId
Phase 2: /workflow:tools:context-gather --session sessionId
↓ contextPath
Phase 3: /workflow:tools:concept-enhanced --session sessionId --context contextPath
↓ ANALYSIS_RESULTS.md
Phase 4: /workflow:tools:task-generate-tdd --session sessionId
↓ TEST-*.json, IMPL-*.json, REFACTOR-*.json
↓ TDD_PLAN.md, IMPL_PLAN.md, TODO_LIST.md
Phase 5: Internal validation
Return summary
/workflow:execute (user executes tasks)
/workflow:tdd-verify (user verifies compliance)
Phase 1: Session discovery
↓ sessionId
Phase 2: Task chain validation
↓ validation report
Phase 3: /workflow:tools:tdd-coverage-analysis
↓ coverage report
Phase 4: Gemini compliance report
↓ TDD_COMPLIANCE_REPORT.md
Return verification summary
```
### File Structure
```
.workflow/
└── WFS-[session-id]/
├── ANALYSIS_RESULTS.md # From concept-enhanced
├── IMPL_PLAN.md # Standard implementation plan
├── TDD_PLAN.md # TDD-specific plan (new)
├── TODO_LIST.md # Task list with TDD phases
├── TDD_COMPLIANCE_REPORT.md # Verification report (new)
├── .task/
│ ├── TEST-1.1.json
│ ├── IMPL-1.1.json
│ ├── REFACTOR-1.1.json
│ └── ...
├── .summaries/
│ ├── TEST-1.1-summary.md
│ ├── IMPL-1.1-summary.md
│ └── ...
└── .process/
├── TDD_TASK_BREAKDOWN.md # Gemini TDD breakdown
├── test-results.json # Test execution results
└── coverage-report.json # Coverage data
```
### Relationship with Existing Commands
- **Reuses**: `/workflow:session:start`, `/workflow:tools:context-gather`, `/workflow:tools:concept-enhanced`
- **Extends**: Adds TDD-specific task generation and verification
- **Compatible with**: `/workflow:execute`, `/workflow:status`, `/workflow:resume`
- **Complements**: `/workflow:test-gen` (TDD is proactive, test-gen is reactive)
---
## Implementation Checklist
### Command Files to Create
- [ ] `.claude/commands/workflow/tdd-plan.md`
- [ ] `.claude/commands/workflow/tdd-verify.md`
- [ ] `.claude/commands/workflow/tools/task-generate-tdd.md`
- [ ] `.claude/commands/workflow/tools/tdd-coverage-analysis.md`
### Template Files to Create
- [ ] `.claude/workflows/cli-templates/prompts/development/tdd-test.txt`
- [ ] `.claude/workflows/cli-templates/prompts/development/tdd-impl.txt`
- [ ] `.claude/workflows/cli-templates/prompts/development/tdd-refactor.txt`
### Documentation to Update
- [ ] `.claude/workflows/workflow-architecture.md` - Add TDD workflow section
- [ ] `.claude/workflows/task-core.md` - Document `meta.tdd_phase` field
- [ ] `README.md` - Add TDD workflow usage examples
### Testing Requirements
- [ ] Test tdd-plan with simple feature
- [ ] Verify task chain dependencies
- [ ] Test tdd-verify compliance checking
- [ ] Validate integration with workflow:execute
- [ ] Test error handling and validation
---
## Usage Examples
### Example 1: Create TDD Workflow
```bash
# Plan TDD workflow
/workflow:tdd-plan "Implement user registration with email validation"
# Execute tasks in order
/workflow:execute
# Verify TDD compliance
/workflow:tdd-verify
```
### Example 2: Agent Mode
```bash
# Use agent for autonomous TDD planning
/workflow:tdd-plan --agent requirements.md
# Execute with automatic task execution
/workflow:execute
```
### Example 3: Issue-Based TDD
```bash
# Create TDD workflow from issue
/workflow:tdd-plan ISS-042
# Execute and verify
/workflow:execute
/workflow:tdd-verify WFS-issue-042
```
---
## Benefits
1. **Enforced TDD Discipline**: Dependencies ensure tests come before implementation
2. **Clear Structure**: Red-Green-Refactor phases are explicit
3. **Quality Verification**: Built-in compliance checking
4. **Existing Architecture**: Reuses proven workflow patterns
5. **Agent Support**: Can be fully automated or manually controlled
6. **Comprehensive Reporting**: Clear visibility into TDD adherence
7. **Flexible**: Works with existing workflow commands

View File

@@ -5,6 +5,103 @@ All notable changes to Claude Code Workflow (CCW) will be documented in this fil
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
## [3.1.0] - 2025-10-02
### 🧪 TDD Workflow Support
This release introduces comprehensive Test-Driven Development (TDD) workflow support with Red-Green-Refactor cycle enforcement.
#### Added
**TDD Workflow Commands**:
- **`/workflow:tdd-plan`**: 5-phase TDD planning orchestrator
- Creates structured TDD workflow with TEST → IMPL → REFACTOR task chains
- Enforces Red-Green-Refactor methodology through task dependencies
- Supports both manual and agent modes (`--agent` flag)
- Validates TDD structure (chains, dependencies, meta fields)
- Outputs: `TDD_PLAN.md`, `IMPL_PLAN.md`, `TODO_LIST.md`
- **`/workflow:tdd-verify`**: 4-phase TDD compliance verification
- Validates task chain structure (TEST-N.M → IMPL-N.M → REFACTOR-N.M)
- Analyzes test coverage metrics (line, branch, function coverage)
- Verifies Red-Green-Refactor cycle execution
- Generates comprehensive compliance report with scoring (0-100)
- Outputs: `TDD_COMPLIANCE_REPORT.md`
**TDD Tool Commands**:
- **`/workflow:tools:task-generate-tdd`**: TDD task chain generator
- Uses Gemini AI to analyze requirements and create TDD breakdowns
- Generates TEST, IMPL, REFACTOR tasks with proper dependencies
- Creates task JSONs with `meta.tdd_phase` field ("red"/"green"/"refactor")
- Assigns specialized agents (`@code-review-test-agent`, `@code-developer`)
- Maximum 10 features (30 total tasks) per workflow
- **`/workflow:tools:tdd-coverage-analysis`**: Test coverage and cycle analysis
- Extracts test files from TEST tasks
- Runs test suite with coverage (supports npm, pytest, cargo, go test)
- Parses coverage metrics (line, branch, function)
- Verifies TDD cycle execution through task summaries
- Outputs: `test-results.json`, `coverage-report.json`, `tdd-cycle-report.md`
**TDD Architecture**:
- **Task ID Format**: `TEST-N.M`, `IMPL-N.M`, `REFACTOR-N.M`
- N = feature number (1-10)
- M = sub-task number (1-N)
- **Dependency System**:
- `IMPL-N.M` depends on `TEST-N.M`
- `REFACTOR-N.M` depends on `IMPL-N.M`
- Enforces execution order: Red → Green → Refactor
- **Meta Fields**:
- `meta.tdd_phase`: "red" | "green" | "refactor"
- `meta.agent`: "@code-review-test-agent" | "@code-developer"
**Compliance Scoring**:
```
Base Score: 100 points
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
```
#### Changed
**Documentation Updates**:
- Updated README.md with TDD workflow section
- Added TDD Quick Start guide
- Updated command reference with TDD commands
- Version badge updated to v3.1.0
**Integration**:
- TDD commands work alongside standard workflow commands
- Compatible with `/workflow:execute`, `/workflow:status`, `/workflow:resume`
- Uses same session management and artifact system
#### Benefits
**TDD Best Practices**:
- ✅ Enforced test-first development through task dependencies
- ✅ Automated Red-Green-Refactor cycle verification
- ✅ Comprehensive test coverage analysis
- ✅ Quality scoring and compliance reporting
- ✅ AI-powered task breakdown with TDD focus
**Developer Experience**:
- 🚀 Quick TDD workflow creation with single command
- 📊 Detailed compliance reports with actionable recommendations
- 🔄 Seamless integration with existing workflow system
- 🧪 Multi-framework test support (Jest, Pytest, Cargo, Go)
---
## [3.0.1] - 2025-10-01
### 🔧 Command Updates

255
README.md
View File

@@ -2,7 +2,7 @@
<div align="center">
[![Version](https://img.shields.io/badge/version-v3.0.1-blue.svg)](https://github.com/catlog22/Claude-Code-Workflow/releases)
[![Version](https://img.shields.io/badge/version-v3.1.0-blue.svg)](https://github.com/catlog22/Claude-Code-Workflow/releases)
[![License](https://img.shields.io/badge/license-MIT-green.svg)](LICENSE)
[![Platform](https://img.shields.io/badge/platform-Windows%20%7C%20Linux%20%7C%20macOS-lightgrey.svg)]()
[![MCP Tools](https://img.shields.io/badge/🔧_MCP_Tools-Experimental-orange.svg)](https://github.com/modelcontextprotocol)
@@ -15,7 +15,7 @@
**Claude Code Workflow (CCW)** is a next-generation multi-agent automation framework that orchestrates complex software development tasks through intelligent workflow management and autonomous execution.
> **🎉 Latest: v3.0.1** - Documentation optimization and brainstorming role updates. See [CHANGELOG.md](CHANGELOG.md) for details.
> **🎉 Latest: v3.1.0** - TDD Workflow Support with Red-Green-Refactor cycle enforcement. See [CHANGELOG.md](CHANGELOG.md) for details.
>
> **v3.0.0**: Introduced **unified CLI command structure**. The `/cli:*` commands consolidate all tool interactions (Gemini, Qwen, Codex) using a `--tool` flag for selection.
@@ -23,13 +23,15 @@
## ✨ Key Features
- **🤖 Multi-Agent System**: Specialized agents for planning, coding, testing, and reviewing.
- **🔄 End-to-End Workflow Automation**: From brainstorming (`/workflow:brainstorm`) to deployment.
- **🎯 JSON-First Architecture**: Uses JSON as the single source of truth for tasks, ensuring consistency.
- **🧪 Automated Test Generation**: Creates comprehensive test suites based on implementation analysis.
- **🎯 Context-First Architecture**: Pre-defined context gathering eliminates execution uncertainty and error accumulation.
- **🤖 Multi-Agent System**: Specialized agents (`@code-developer`, `@code-review-test-agent`) with tech-stack awareness.
- **🔄 End-to-End Workflow Automation**: From brainstorming to deployment with multi-phase orchestration.
- **📋 JSON-First Task Model**: Structured task definitions with `pre_analysis` steps for deterministic execution.
- **🧪 TDD Workflow Support**: Complete Test-Driven Development with Red-Green-Refactor cycle enforcement.
- **🧠 Multi-Model Orchestration**: Leverages Gemini (analysis), Qwen (architecture), and Codex (implementation) strengths.
- **✅ Pre-execution Verification**: Validates plans with both strategic (Gemini) and technical (Codex) analysis.
- **🔧 Unified CLI**: A single, powerful `/cli:*` command set for interacting with various AI tools.
- **🧠 Smart Context Management**: Automatically manages and updates project documentation (`CLAUDE.md`).
- **📦 Smart Context Package**: `context-package.json` links tasks to relevant codebase files and external examples.
---
@@ -55,27 +57,74 @@ After installation, run the following command to ensure CCW is working:
---
## 🚀 Getting Started: A Simple Workflow
## 🚀 Getting Started
1. **Start a new workflow session:**
```bash
/workflow:session:start "Create a new user authentication feature"
```
### Complete Development Workflow
2. **Generate an implementation plan:**
```bash
/workflow:plan "Implement JWT-based user authentication"
```
**Phase 1: Brainstorming & Conceptual Planning**
```bash
# Multi-perspective brainstorming with role-based agents
/workflow:brainstorm:auto-parallel "Build a user authentication system"
3. **Execute the plan with AI agents:**
```bash
/workflow:execute
```
# Review and refine specific aspects (optional)
/workflow:brainstorm:ui-designer "authentication flows"
/workflow:brainstorm:synthesis # Generate consolidated specification
```
4. **Check the status:**
```bash
/workflow:status
```
**Phase 2: Action Planning**
```bash
# Create executable implementation plan
/workflow:plan "Implement JWT-based authentication system"
# OR for TDD approach
/workflow:tdd-plan "Implement authentication with test-first development"
```
**Phase 3: Execution**
```bash
# Execute tasks with AI agents
/workflow:execute
# Monitor progress
/workflow:status
```
**Phase 4: Testing & Quality Assurance**
```bash
# Generate comprehensive test suite (standard workflow)
/workflow:test-gen
/workflow:execute
# OR verify TDD compliance (TDD workflow)
/workflow:tdd-verify
# Final quality review
/workflow:review
```
### Quick Start for Simple Tasks
**Feature Development:**
```bash
/workflow:session:start "Add password reset feature"
/workflow:plan "Email-based password reset with token expiry"
/workflow:execute
```
**Bug Fixing:**
```bash
# Interactive analysis with CLI tools
/cli:mode:bug-index --tool gemini "Login timeout on mobile devices"
# Execute the suggested fix
/workflow:execute
```
**Code Analysis:**
```bash
# Deep codebase analysis
/cli:mode:code-analysis --tool qwen "Analyze authentication module architecture"
```
---
@@ -101,9 +150,11 @@ After installation, run the following command to ensure CCW is working:
| `/workflow:session:*` | Manage development sessions (`start`, `pause`, `resume`, `list`, `switch`, `complete`). |
| `/workflow:brainstorm:*` | Use role-based agents for multi-perspective planning. |
| `/workflow:plan` | Create a detailed, executable plan from a description. |
| `/workflow:tdd-plan` | Create a Test-Driven Development workflow with Red-Green-Refactor cycles. |
| `/workflow:execute` | Execute the current workflow plan autonomously. |
| `/workflow:status` | Display the current status of the workflow. |
| `/workflow:test-gen` | Automatically generate a test plan from the implementation. |
| `/workflow:tdd-verify` | Verify TDD compliance and generate quality report. |
| `/workflow:review` | Initiate a quality assurance review of the completed work. |
### **Task & Memory Commands**
@@ -167,6 +218,162 @@ MCP (Model Context Protocol) tools provide advanced codebase analysis. **Complet
---
## 🧩 How It Works: Design Philosophy
### The Core Problem
Traditional AI coding workflows face a fundamental challenge: **execution uncertainty leads to error accumulation**.
**Example:**
```bash
# Prompt 1: "Develop XX feature"
# Prompt 2: "Review XX architecture in file Y, then develop XX feature"
```
While Prompt 1 might succeed for simple tasks, in complex workflows:
- The AI may examine different files each time
- Small deviations compound across multiple steps
- Final output drifts from the intended goal
> **CCW's Mission**: Solve the "1-to-N" problem — building upon existing codebases with precision, not just "0-to-1" greenfield development.
---
### The CCW Solution: Context-First Architecture
#### 1. **Pre-defined Context Gathering**
Instead of letting agents randomly explore, CCW uses structured context packages:
**`context-package.json`** created during planning:
```json
{
"metadata": {
"task_description": "...",
"tech_stack": {"frontend": [...], "backend": [...]},
"complexity": "high"
},
"assets": [
{
"path": "synthesis-specification.md",
"priority": "critical",
"sections": ["Backend Module Structure"]
}
],
"implementation_guidance": {
"start_with": ["Step 1", "Step 2"],
"critical_security_items": [...]
}
}
```
#### 2. **JSON-First Task Model**
Each task includes a `flow_control.pre_analysis` section:
```json
{
"id": "IMPL-1",
"flow_control": {
"pre_analysis": [
{
"step": "load_architecture",
"commands": ["Read(architecture.md)", "grep 'auth' src/"],
"output_to": "arch_context",
"on_error": "fail"
}
],
"implementation_approach": {
"modification_points": ["..."],
"logic_flow": ["..."]
},
"target_files": ["src/auth/index.ts"]
}
}
```
**Key Innovation**: The `pre_analysis` steps are **executed before implementation**, ensuring agents always have the correct context.
#### 3. **Multi-Phase Orchestration**
CCW workflows are orchestrators that coordinate slash commands:
**Planning Phase** (`/workflow:plan`):
```
Phase 1: session:start → Create session
Phase 2: context-gather → Build context-package.json
Phase 3: concept-enhanced → CLI analysis (Gemini/Qwen)
Phase 4: task-generate → Generate task JSONs with pre_analysis
```
**Execution Phase** (`/workflow:execute`):
```
For each task:
1. Execute pre_analysis steps → Load context
2. Apply implementation_approach → Make changes
3. Validate acceptance criteria → Verify success
4. Generate summary → Track progress
```
#### 4. **Multi-Model Orchestration**
Each AI model serves its strength:
| Model | Role | Use Cases |
|-------|------|-----------|
| **Gemini** | Analysis & Understanding | Long-context analysis, architecture review, bug investigation |
| **Qwen** | Architecture & Design | System design, code generation, architectural planning |
| **Codex** | Implementation | Feature development, testing, autonomous execution |
**Example:**
```bash
# Gemini analyzes the problem space
/cli:mode:code-analysis --tool gemini "Analyze auth module"
# Qwen designs the solution
/cli:analyze --tool qwen "Design scalable auth architecture"
# Codex implements the code
/workflow:execute # Uses @code-developer with Codex
```
---
### From 0-to-1 vs 1-to-N Development
| Scenario | Traditional Workflow | CCW Approach |
|----------|---------------------|--------------|
| **Greenfield (0→1)** | ✅ Works well | ✅ Adds structured planning |
| **Feature Addition (1→2)** | ⚠️ Context uncertainty | ✅ Context-package links to existing code |
| **Bug Fixing (N→N+1)** | ⚠️ May miss related code | ✅ Pre-analysis finds dependencies |
| **Refactoring** | ⚠️ Unpredictable scope | ✅ CLI analysis + structured tasks |
---
### Key Workflows
#### **Complete Development (Brainstorm → Deploy)**
```
Brainstorm (8 roles) → Synthesis → Plan (4 phases) → Execute → Test → Review
```
#### **Quick Feature Development**
```
session:start → plan → execute → test-gen → execute
```
#### **TDD Workflow**
```
tdd-plan (TEST→IMPL→REFACTOR chains) → execute → tdd-verify
```
#### **Bug Fixing**
```
cli:mode:bug-index (analyze) → execute (fix) → test-gen (verify)
```
---
## 🤝 Contributing & Support
- **Repository**: [GitHub - Claude-Code-Workflow](https://github.com/catlog22/Claude-Code-Workflow)

View File

@@ -2,7 +2,7 @@
<div align="center">
[![Version](https://img.shields.io/badge/version-v3.0.1-blue.svg)](https://github.com/catlog22/Claude-Code-Workflow/releases)
[![Version](https://img.shields.io/badge/version-v3.1.0-blue.svg)](https://github.com/catlog22/Claude-Code-Workflow/releases)
[![License](https://img.shields.io/badge/license-MIT-green.svg)](LICENSE)
[![Platform](https://img.shields.io/badge/platform-Windows%20%7C%20Linux%20%7C%20macOS-lightgrey.svg)]()
[![MCP工具](https://img.shields.io/badge/🔧_MCP工具-实验性-orange.svg)](https://github.com/modelcontextprotocol)
@@ -15,7 +15,7 @@
**Claude Code Workflow (CCW)** 是一个新一代的多智能体自动化开发框架,通过智能工作流管理和自主执行来协调复杂的软件开发任务。
> **🎉 最新版本: v3.0.1** - 文档优化和头脑风暴角色更新。详见 [CHANGELOG.md](CHANGELOG.md)。
> **🎉 最新版本: v3.1.0** - TDD 工作流支持,包含 Red-Green-Refactor 循环强制执行。详见 [CHANGELOG.md](CHANGELOG.md)。
>
> **v3.0.0 版本**: 引入了**统一的 CLI 命令结构**。`/cli:*` 命令通过 `--tool` 标志整合了所有工具Gemini, Qwen, Codex的交互。
@@ -23,13 +23,15 @@
## ✨ 核心特性
- **🤖 多智能体系统**: 用于规划、编码、测试和审查的专用智能体
- **🔄 端到端工作流自动化**: 从头脑风暴 (`/workflow:brainstorm`) 到部署的完整流程
- **🎯 JSON 优先架构**: 使用 JSON 作为任务的唯一真实数据源,确保一致性
- **🧪 自动测试生成**: 基于实现分析创建全面的测试套件
- **🎯 上下文优先架构**: 预定义上下文收集消除执行不确定性和误差累积
- **🤖 多智能体系统**: 专用智能体(`@code-developer``@code-review-test-agent`)具备技术栈感知能力
- **🔄 端到端工作流自动化**: 从头脑风暴到部署的多阶段编排
- **📋 JSON 优先任务模型**: 结构化任务定义,包含 `pre_analysis` 步骤实现确定性执行
- **🧪 TDD 工作流支持**: 完整的测试驱动开发,包含 Red-Green-Refactor 循环强制执行。
- **🧠 多模型编排**: 发挥 Gemini分析、Qwen架构和 Codex实现各自优势。
- **✅ 执行前验证**: 通过战略Gemini和技术Codex双重分析验证计划。
- **🔧 统一 CLI**: 一个强大、统一的 `/cli:*` 命令集,用于与各种 AI 工具交互。
- **🧠 智能上下文管理**: 自动管理和更新项目文档 (`CLAUDE.md`)
- **📦 智能上下文**: `context-package.json` 将任务链接到相关代码库文件和外部示例
---
@@ -55,27 +57,74 @@ bash <(curl -fsSL https://raw.githubusercontent.com/catlog22/Claude-Code-Workflo
---
## 🚀 快速入门:一个简单的工作流
## 🚀 快速入门
1. **启动一个新的工作流会话:**
```bash
/workflow:session:start "创建一个新的用户认证功能"
```
### 完整开发工作流
2. **生成一个实现计划:**
```bash
/workflow:plan "实现基于JWT的用户认证"
```
**阶段 1头脑风暴与概念规划**
```bash
# 多视角头脑风暴,使用基于角色的智能体
/workflow:brainstorm:auto-parallel "构建用户认证系统"
3. **使用 AI 智能体执行计划:**
```bash
/workflow:execute
```
# 审查和优化特定方面(可选)
/workflow:brainstorm:ui-designer "认证流程"
/workflow:brainstorm:synthesis # 生成综合规范
```
4. **检查状态:**
```bash
/workflow:status
```
**阶段 2行动规划**
```bash
# 创建可执行的实现计划
/workflow:plan "实现基于 JWT 的认证系统"
# 或使用 TDD 方法
/workflow:tdd-plan "使用测试优先开发实现认证"
```
**阶段 3执行**
```bash
# 使用 AI 智能体执行任务
/workflow:execute
# 监控进度
/workflow:status
```
**阶段 4测试与质量保证**
```bash
# 生成全面测试套件(标准工作流)
/workflow:test-gen
/workflow:execute
# 或验证 TDD 合规性TDD 工作流)
/workflow:tdd-verify
# 最终质量审查
/workflow:review
```
### 简单任务快速入门
**功能开发:**
```bash
/workflow:session:start "添加密码重置功能"
/workflow:plan "基于邮件的密码重置,带令牌过期"
/workflow:execute
```
**Bug 修复:**
```bash
# 使用 CLI 工具进行交互式分析
/cli:mode:bug-index --tool gemini "移动设备上登录超时"
# 执行建议的修复
/workflow:execute
```
**代码分析:**
```bash
# 深度代码库分析
/cli:mode:code-analysis --tool qwen "分析认证模块架构"
```
---
@@ -101,9 +150,11 @@ bash <(curl -fsSL https://raw.githubusercontent.com/catlog22/Claude-Code-Workflo
| `/workflow:session:*` | 管理开发会话(`start`, `pause`, `resume`, `list`, `switch`, `complete`)。 |
| `/workflow:brainstorm:*` | 使用基于角色的智能体进行多视角规划。 |
| `/workflow:plan` | 从描述创建详细、可执行的计划。 |
| `/workflow:tdd-plan` | 创建测试驱动开发工作流,包含 Red-Green-Refactor 循环。 |
| `/workflow:execute` | 自主执行当前的工作流计划。 |
| `/workflow:status` | 显示工作流的当前状态。 |
| `/workflow:test-gen` | 从实现中自动生成测试计划。 |
| `/workflow:tdd-verify` | 验证 TDD 合规性并生成质量报告。 |
| `/workflow:review` | 对已完成的工作启动质量保证审查。 |
### **任务与内存命令**
@@ -167,6 +218,162 @@ MCP (模型上下文协议) 工具提供高级代码库分析。**完全可选**
---
## 🧩 工作原理:设计理念
### 核心问题
传统的 AI 编码工作流面临一个根本性挑战:**执行不确定性导致误差累积**。
**示例:**
```bash
# 提示词1"开发XX功能"
# 提示词2"查看XX文件中架构设计开发XX功能"
```
虽然提示词1对简单任务可能成功但在复杂工作流中
- AI 每次可能检查不同的文件
- 小偏差在多个步骤中累积
- 最终输出偏离预期目标
> **CCW 的使命**:解决"1到N"的问题 — 精确地在现有代码库基础上开发,而不仅仅是"0到1"的全新项目开发。
---
### CCW 解决方案:上下文优先架构
#### 1. **预定义上下文收集**
CCW 使用结构化上下文包,而不是让智能体随机探索:
**规划阶段创建的 `context-package.json`**
```json
{
"metadata": {
"task_description": "...",
"tech_stack": {"frontend": [...], "backend": [...]},
"complexity": "high"
},
"assets": [
{
"path": "synthesis-specification.md",
"priority": "critical",
"sections": ["后端模块结构"]
}
],
"implementation_guidance": {
"start_with": ["步骤1", "步骤2"],
"critical_security_items": [...]
}
}
```
#### 2. **JSON 优先任务模型**
每个任务包含 `flow_control.pre_analysis` 部分:
```json
{
"id": "IMPL-1",
"flow_control": {
"pre_analysis": [
{
"step": "load_architecture",
"commands": ["Read(architecture.md)", "grep 'auth' src/"],
"output_to": "arch_context",
"on_error": "fail"
}
],
"implementation_approach": {
"modification_points": ["..."],
"logic_flow": ["..."]
},
"target_files": ["src/auth/index.ts"]
}
}
```
**核心创新**`pre_analysis` 步骤在实现**之前执行**,确保智能体始终拥有正确的上下文。
#### 3. **多阶段编排**
CCW 工作流是协调斜杠命令的编排器:
**规划阶段** (`/workflow:plan`)
```
阶段1: session:start → 创建会话
阶段2: context-gather → 构建 context-package.json
阶段3: concept-enhanced → CLI 分析Gemini/Qwen
阶段4: task-generate → 生成带 pre_analysis 的任务 JSON
```
**执行阶段** (`/workflow:execute`)
```
对于每个任务:
1. 执行 pre_analysis 步骤 → 加载上下文
2. 应用 implementation_approach → 进行更改
3. 验证验收标准 → 验证成功
4. 生成摘要 → 跟踪进度
```
#### 4. **多模型编排**
每个 AI 模型发挥各自优势:
| 模型 | 角色 | 使用场景 |
|------|------|----------|
| **Gemini** | 分析与理解 | 长上下文分析、架构审查、bug 调查 |
| **Qwen** | 架构与设计 | 系统设计、代码生成、架构规划 |
| **Codex** | 实现 | 功能开发、测试、自主执行 |
**示例:**
```bash
# Gemini 分析问题空间
/cli:mode:code-analysis --tool gemini "分析认证模块"
# Qwen 设计解决方案
/cli:analyze --tool qwen "设计可扩展的认证架构"
# Codex 实现代码
/workflow:execute # 使用带 Codex 的 @code-developer
```
---
### 0到1 vs 1到N 开发
| 场景 | 传统工作流 | CCW 方法 |
|------|-----------|----------|
| **全新项目0→1** | ✅ 效果良好 | ✅ 增加结构化规划 |
| **功能添加1→2** | ⚠️ 上下文不确定 | ✅ context-package 链接现有代码 |
| **Bug 修复N→N+1** | ⚠️ 可能遗漏相关代码 | ✅ pre_analysis 查找依赖 |
| **重构** | ⚠️ 范围不可预测 | ✅ CLI 分析 + 结构化任务 |
---
### 核心工作流
#### **完整开发(头脑风暴 → 部署)**
```
头脑风暴8个角色→ 综合 → 规划4阶段→ 执行 → 测试 → 审查
```
#### **快速功能开发**
```
session:start → plan → execute → test-gen → execute
```
#### **TDD 工作流**
```
tdd-plan (TEST→IMPL→REFACTOR 链) → execute → tdd-verify
```
#### **Bug 修复**
```
cli:mode:bug-index分析→ execute修复→ test-gen验证
```
---
## 🤝 贡献与支持
- **仓库**: [GitHub - Claude-Code-Workflow](https://github.com/catlog22/Claude-Code-Workflow)