Compare commits

...

21 Commits

Author SHA1 Message Date
catlog22
7f920cb33d docs: Release v3.4.0 with TDD workflow optimization and test-gen enhancements
Version Update:
- Bump version from v3.3.0 to v3.4.0

Documentation Updates (README.md & README_CN.md):
- Updated version badges to v3.4.0
- Revised What's New section highlighting:
  * TDD workflow streamlining (33% file reduction)
  * Test coverage analysis (Phase 3 integration)
  * Iterative Green Phase with test-fix-cycle
  * Manual-first fixes with optional --use-codex
  * Test-gen workflow enhancements (3 new tool commands)
  * Dynamic timeout allocation (20-120min)

Command Reference Updates:
- Updated /workflow:tdd-plan description (6 phases)
- Enhanced /workflow:test-gen with [--use-codex] flag
- Added 3 new tool commands:
  * /workflow:tools:test-context-gather
  * /workflow:tools:test-concept-enhanced
  * /workflow:tools:test-task-generate

Version Files:
- Updated .claude/version.json to 3.4.0
- Updated .claude/commands/version.md examples

Key Features in v3.4.0:
- Eliminated TDD_PLAN.md and TDD_TASK_BREAKDOWN.md (unified IMPL_PLAN.md)
- TDD workflow upgraded from 5 to 6 phases
- Built-in test-fix-cycle in IMPL tasks
- Gemini diagnosis using bug-fix.md template
- Test-gen workflow with comprehensive test generation support

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

Co-Authored-By: Claude <noreply@anthropic.com>
2025-10-04 20:18:23 +08:00
catlog22
d33c69cf4d fix: Remove timeout parameters from command examples in intelligent-tools-strategy.md 2025-10-04 20:11:44 +08:00
catlog22
7047cae356 feat: Optimize TDD workflow with streamlined file structure and test-gen integration
## TDD Workflow Enhancements

### File Structure Optimization
- **Eliminated**: TDD_PLAN.md (merged into unified IMPL_PLAN.md)
- **Eliminated**: .process/TDD_TASK_BREAKDOWN.md (enhanced ANALYSIS_RESULTS.md instead)
- **Unified**: Single IMPL_PLAN.md with TDD Task Chains section
- **Result**: Reduced 2 files per TDD session (-33% file count)

### Test-Gen Integration
- Added test coverage analysis phase (Phase 3: test-context-gather)
- Integrated iterative test-fix-cycle into Green phase (IMPL tasks)
- Gemini diagnosis with bug-fix template for test failures
- Auto-revert safety mechanism (max_iterations protection)
- Manual fix by default, optional Codex automation (--use-codex flag)

### Workflow Improvements
- 6-phase TDD planning (added test coverage analysis)
- ANALYSIS_RESULTS.md enhanced with TDD breakdown structure
- IMPL tasks include test-fix-cycle configuration
- Unified IMPL_PLAN.md structure: frontmatter + TDD Task Chains + standard sections

### Configuration
- meta.max_iterations: 3 (TDD) vs 5 (test-gen)
- meta.use_codex: false (default manual fixes)
- workflow_type: "tdd" in IMPL_PLAN.md frontmatter

### Benefits
- Eliminated redundancy (2 fewer files, 1 less Gemini call)
- Context-aware TDD (not greenfield-only)
- Faster feedback (test-fix-cycle in Green phase)
- Autonomous recovery (auto-diagnose and fix)
- Backward compatible (no breaking changes)

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

Co-Authored-By: Claude <noreply@anthropic.com>
2025-10-04 20:11:12 +08:00
catlog22
73bd0b2832 feat: Implement dynamic timeout allocation for CLI tools (20-120min)
- Add task complexity-based timeout allocation
- Simple tasks: 20-40min, Medium: 40-60min, Complex: 60-120min
- Codex commands use 1.5x multiplier for longer operations
- Auto-detect timeout from PURPOSE and TASK fields

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

Co-Authored-By: Claude <noreply@anthropic.com>
2025-10-04 19:37:36 +08:00
catlog22
f59b5b8102 feat: Enhance test-gen workflow with comprehensive test generation and fix cycle
- Create test-context-gather.md for MCP-based coverage analysis
  - Analyze test coverage gaps using MCP code-index tools
  - Identify files requiring tests
  - Detect test framework and conventions
  - Generate test-context-package.json with coverage data

- Create test-concept-enhanced.md for Gemini-powered test analysis
  - Analyze coverage gaps and implementation context
  - Study existing test patterns and conventions
  - Generate comprehensive test requirements
  - Design test generation strategy
  - Output TEST_ANALYSIS_RESULTS.md with test specifications

- Update test-task-generate.md to generate two tasks
  - IMPL-001: Test generation task calling @code-developer
  - IMPL-002: Test execution and fix cycle task calling @test-fix-agent
  - Use TEST_ANALYSIS_RESULTS.md for test generation requirements
  - Configure Gemini diagnosis and Codex resume mechanism for fixes

- Update test-gen.md to 5-phase workflow
  - Phase 1: Create test session
  - Phase 2: Gather test context (test-context-gather)
  - Phase 3: Analyze test requirements (test-concept-enhanced)
  - Phase 4: Generate test tasks (test-task-generate)
  - Phase 5: Return summary
  - Simplify documentation by removing redundant content
  - Maintain all original intent while improving clarity

Complete workflow: Coverage analysis → Gemini analysis → Test generation → Test execution → Fix cycle

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

Co-Authored-By: Claude <noreply@anthropic.com>
2025-10-04 19:33:28 +08:00
catlog22
7f4dfe51fd refactor: Enhance synthesis.md with comprehensive improvements
Major improvements to brainstorm synthesis specification:

1. Output Definition Unification (Critical)
   - Remove synthesis-report.md references
   - Unify to synthesis-specification.md as single output
   - Update all metadata and descriptions

2. Execution Model Clarification (High)
   - Change "Direct Execution Only" to "Direct Execution by Main Claude"
   - Clarify: Main Claude + Read/Write/Glob + cognitive analysis
   - Emphasize avoiding context transmission loss

3. Dynamic Role Discovery (High)
   - Replace hardcoded 9-role list with runtime discovery
   - Scan .brainstorming/* directories for actual analysis.md files
   - Support flexible participation (1 to 9+ roles)
   - Update metadata to reflect dynamic role counts

4. Enhanced Document Structure (Critical)
   - Add "Key Designs & Decisions" section
     * Core architecture diagrams (Mermaid)
     * User journey maps (images)
     * Data model overview (ERD)
     * Architecture Decision Records (ADRs)

   - Add "Controversial Points & Alternatives" section
     * Document disagreements and rejected alternatives
     * Preserve decision context and rationale
     * Track dissenting roles

   - Add "Process & Collaboration Concerns" section
     * Team capability assessment
     * Process risks and mitigation
     * Collaboration patterns
     * Timeline constraints

5. Requirements Table Enhancement (Medium)
   - Add "Rationale Summary" column to all requirement tables
   - Reduce over-reliance on @ references
   - Provide immediate context for better readability

6. Responsibility Clarification
   - synthesis-specification.md: Defines "WHAT" (requirements, design)
   - IMPL_PLAN.md: Defines "HOW" (executable tasks)
   - Clear handoff between brainstorm and planning phases

7. Updated Quality Assurance Standards
   - Visual Clarity: Diagrams required
   - Decision Transparency: Alternatives documented
   - No Role Marginalization: Process roles equally visible
   - Context-Rich: Rationale included
   - Decision Traceability: @ references maintained

Related: plan.md improvements for auto-continue clarity and synthesis integration

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

Co-Authored-By: Claude <noreply@anthropic.com>
2025-10-04 16:40:06 +08:00
catlog22
9a28866837 fix: Update synthesis and plan documentation for consistency in output file naming 2025-10-04 14:36:25 +08:00
catlog22
e90c9baa13 refactor: Optimize document passing strategy in workflow
- **concept-enhanced**: Add explicit priority for source documents
  - PRIMARY: role analysis.md files (complete technical details, ADRs)
  - SECONDARY: synthesis-specification.md (integrated requirements)
  - Framework: topic-framework.md (discussion context)

- **task-generate**: Enhanced artifacts array with usage guidance
  - Add 'usage' field for each artifact type
  - Support dynamic role discovery
  - Reorder priority: synthesis (highest) → role_analysis (high) → framework (low)

- **pre_analysis**: Add explicit artifact loading instructions
  - Note when to consult role analysis (API schemas, caching configs, design tokens)
  - Load system-architect, ui-designer, product-manager analyses

- **implementation_approach**: Add clear priority instructions
  - Primary: Use synthesis-specification.md for requirements
  - Secondary: Refer to artifacts[] for technical details
  - Update logic_flow to include "Consult artifacts when needed"

- **gitignore**: Add .workflow directory to ignore list

🎯 Result: Balanced strategy - 100% fidelity in analysis phase, 78% token efficiency in planning phase, hybrid approach in execution phase

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

Co-Authored-By: Claude <noreply@anthropic.com>
2025-10-04 12:44:07 +08:00
catlog22
237a2867fb docs: Move Configuration section below Installation in README files
- Reorganize README.md and README_CN.md structure
- Move Configuration section directly after Installation for better flow
- Update MCP Tools section to "Recommended" with warning notes in both languages
- Improve user experience by placing setup instructions together

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

Co-Authored-By: Claude <noreply@anthropic.com>
2025-10-04 11:39:51 +08:00
catlog22
c8f0352ffb fix: Display timestamps in user's local timezone in installation scripts
- Convert UTC timestamps to local timezone in install-remote.ps1
- Convert UTC timestamps to local timezone in install-remote.sh
- Support cross-platform date conversion (GNU date and BSD date)
- Remove 'UTC' suffix from timestamp displays

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

Co-Authored-By: Claude <noreply@anthropic.com>
2025-10-04 09:57:46 +08:00
catlog22
48c6fa9a40 docs: Update documentation for git staging and MCP recommendations
- Add pre-execution git staging to codex-execute workflow for clear change visibility
- Update README to recommend MCP tools installation (not optional)
- Add core principle: no unsolicited reports without user permission

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

Co-Authored-By: Claude <noreply@anthropic.com>
2025-10-04 09:55:00 +08:00
catlog22
3a78dac919 release: v3.3.0 - CLI Tool Enhancements & Codex Multi-Step Execution
 Features:
- New /cli:codex-execute command for automated multi-step task execution
- Codex resume mechanism (codex exec "..." resume --last) for context continuity
- TodoWrite progress tracking for subtask execution
- Optional Git verification after each subtask (--verify-git flag)
- Automatic task JSON detection and loading
- Enhanced Codex agent configuration (.codex/AGENTS.md v2.1.0)

📚 Documentation:
- Streamlined CLI documentation (60% reduction in redundancy)
- Updated /cli:analyze, /cli:chat, /cli:execute commands
- Enhanced intelligent-tools-strategy.md with Codex resume patterns
- Unified command templates for Gemini/Qwen vs Codex
- Added Codex -i parameter documentation for image attachment

🔧 Technical:
- Multi-task prompt format (Single-Task & Multi-Task)
- Subtask coordination guidelines and best practices
- Enhanced MODE: auto with subtask execution flow
- Progress reporting for multi-step workflows

📦 Updates:
- Version bumped to 3.3.0 in README.md, README_CN.md
- Created .claude/version.json for version tracking
- Comprehensive CHANGELOG.md entry with all changes

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

Co-Authored-By: Claude <noreply@anthropic.com>
2025-10-04 00:51:34 +08:00
catlog22
4b578285ea refactor: Enhance tool write protection and lower Bash requirement
- Add explicit write operation protection in intelligent-tools-strategy
  - Require MODE=write or MODE=auto for local codebase modifications
  - Default all tools to read-only analysis mode
  - Convert all Chinese text to English for consistency
- Lower Bash version requirement from 4.0 to 2.0 in Install-Claude.sh
  - Align with install-remote.sh requirements
  - Improve compatibility with older systems

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

Co-Authored-By: Claude <noreply@anthropic.com>
2025-10-04 00:09:17 +08:00
catlog22
5c66e268ec fix: Clarify auto-continue workflow execution model in plan command
- Replace sequential execution model with explicit auto-continue pattern
- Document that each phase returns to user before auto-continuing
- Use TodoList state for progress tracking (no external state files)
- Store parsed data (sessionId, contextPath) in memory between phases
- Clarify error handling keeps phase in_progress without proceeding

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

Co-Authored-By: Claude <noreply@anthropic.com>
2025-10-03 23:56:09 +08:00
catlog22
de4914f046 fix: Lower Bash version requirement from 4.0 to 2.0
Based on Gemini analysis, all script features (double brackets, local keyword,
BASH_VERSINFO array) are supported in Bash 2.0+. This change improves
compatibility with older systems while maintaining full functionality.

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

Co-Authored-By: Claude <noreply@anthropic.com>
2025-10-03 21:23:23 +08:00
catlog22
00d1be60cb refactor: Rename DMS directory to memory and update references
- Renamed .claude/workflows/cli-templates/prompts/dms/ to memory/
- Updated all path references in update_module_claude.sh
- Updated terminology in INSTALL.md and INSTALL_CN.md
- Changed DMS system references to memory system

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

Co-Authored-By: Claude <noreply@anthropic.com>
2025-10-03 13:46:44 +08:00
catlog22
f549dfcc9b release: v3.2.3 - Version Management System
Add comprehensive version management and upgrade notification system:

New Features:
- Add /version command for checking installed versions
- GitHub API integration for latest release detection
- Automatic upgrade notifications and recommendations
- Version tracking in both local and global installations
- Quick version check with comprehensive status display

Documentation Updates:
- Update CHANGELOG.md with v3.2.3 release notes
- Update README.md version badge to v3.2.3
- Update README_CN.md with Chinese version documentation
- Add RELEASE_NOTES_v3.2.3.md with detailed release information
- Add /version command to command reference tables

Cleanup:
- Remove old release notes (RELEASE_NOTES_v2.0.md, RELEASE_NOTES_v3.2.1.md)

Version Files:
- Update ~/.claude/version.json to v3.2.3

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

Co-Authored-By: Claude <noreply@anthropic.com>
2025-10-03 13:09:37 +08:00
catlog22
c5c36a23ea fix: Optimize version command API calls and data extraction
- Change API endpoint from /branches/main to /commits/main for reliable commit info
- Add 30-second timeout to all network calls for slow connections
- Extract release name and published date from latest release
- Extract commit message (first line only) using improved parsing
- Add commit date extraction from main branch
- Update documentation with API endpoints and timeout configuration
- Fix commit message extraction to handle JSON escape sequences

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

Co-Authored-By: Claude <noreply@anthropic.com>
2025-10-03 13:00:06 +08:00
catlog22
a03415bfeb feat: Add version tracking and upgrade check system
- Add /version command to check installed and latest versions
- Create version.json metadata file during installation
- Pass version and branch info from install-remote.ps1 to Install-Claude.ps1
- Support version comparison and upgrade recommendations
- Track installation mode (Global/Path) and source branch

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

Co-Authored-By: Claude <noreply@anthropic.com>
2025-10-03 12:46:44 +08:00
catlog22
06772c675e docs: Enhance core coding principles with engineering best practices
Integrated five fundamental engineering principles at the start of Core Beliefs:
- Good taste: eliminate edge cases for elegant logic
- Extreme simplicity: complexity as root cause of issues
- Pragmatism: solve real problems, not hypothetical ones
- Data structures first: prioritize data design over code
- Backward compatibility: preserve existing functionality

These principles complement existing guidelines while emphasizing foundational software engineering wisdom.

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

Co-Authored-By: Claude <noreply@anthropic.com>
2025-10-03 12:24:29 +08:00
catlog22
8c062f3611 docs: Update README files for v3.2.2 release
Update both English and Chinese README files to reflect v3.2.2 changes:

Version Updates:
- Bump version badge from v3.2.1 to v3.2.2
- Update "What's New" section with v3.2.2 features

Key Documentation Changes:
- Independent test session architecture (WFS-test-[source])
- Automatic cross-session context gathering via metadata
- Integrated concept-enhanced analysis (Gemini + Codex parallel)
- Reuses IMPL-*.json format with meta.type="test-fix"
- 4-phase workflow: session → context → analysis → task generation

Command Reference Updates:
- Updated /workflow:test-gen description to reflect independent workflow creation
- Updated Phase 4 examples to show new usage: /workflow:test-gen WFS-auth

Changes in Both Files:
- README.md: English version updated
- README_CN.md: Chinese version updated with matching content

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

Co-Authored-By: Claude <noreply@anthropic.com>
2025-10-03 12:07:35 +08:00
40 changed files with 3982 additions and 1651 deletions

View File

@@ -17,185 +17,68 @@ allowed-tools: SlashCommand(*), Bash(*), TodoWrite(*), Read(*), Glob(*)
Execute CLI tool analysis on codebase patterns, architecture, or code quality.
**Supported Tools**: codex, gemini (default), qwen
**Reference**: @~/.claude/workflows/intelligent-tools-strategy.md for complete tool details
## Execution Flow
1. **Parse tool selection**: Extract `--tool` flag (default: gemini)
2. **If `--enhance` flag present**: Execute `/enhance-prompt "[analysis-target]"` and use enhanced output
3. Parse analysis target (original or enhanced)
4. Detect analysis type (pattern/architecture/security/quality)
5. Build command for selected tool with template
6. Execute analysis
7. Return results
## Core Rules
1. **Tool Selection**: Use `--tool` value or default to gemini
2. **Enhance First (if flagged)**: Execute `/enhance-prompt` before analysis when `--enhance` present
3. **Execute Immediately**: Build and run command without preliminary analysis
4. **Template Selection**: Auto-select template based on keywords
5. **Context Inclusion**: Always include CLAUDE.md in context
6. **Direct Output**: Return tool output directly to user
## Tool Selection
| Tool | Wrapper | Best For | Permissions |
|------|---------|----------|-------------|
| **gemini** (default) | `~/.claude/scripts/gemini-wrapper` | Analysis, exploration, documentation | Read-only |
| **qwen** | `~/.claude/scripts/qwen-wrapper` | Architecture, code generation | Read-only for analyze |
| **codex** | `codex --full-auto exec` | Development analysis, deep inspection | `-s danger-full-access --skip-git-repo-check` |
1. Parse tool selection (default: gemini)
2. If `--enhance`: Execute `/enhance-prompt` first
3. Detect analysis type and select template
4. Build and execute command
5. Return results
## Enhancement Integration
**When `--enhance` flag present**:
**When `--enhance` flag present**: Execute `/enhance-prompt "[analysis-target]"` first, then use enhanced output (INTENT/CONTEXT/ACTION) to build the analysis command.
## Command Template
**Gemini/Qwen**:
```bash
# Step 1: Enhance the prompt
SlashCommand(command="/enhance-prompt \"[analysis-target]\"")
# Step 2: Use enhanced output as analysis target
# Enhanced output provides:
# - INTENT: Clear technical goal
# - CONTEXT: Session memory + patterns
# - ACTION: Implementation steps
# - ATTENTION: Critical constraints
```
**Example**:
```bash
# User: /gemini:analyze --enhance "fix auth issues"
# Step 1: Enhance
/enhance-prompt "fix auth issues"
# Returns:
# INTENT: Debug authentication failures
# CONTEXT: JWT implementation in src/auth/, known token expiry issue
# ACTION: Analyze token lifecycle → verify refresh flow → check middleware
# ATTENTION: Preserve existing session management
# Step 2: Analyze with enhanced context
cd . && ~/.claude/scripts/gemini-wrapper -p "
PURPOSE: Debug authentication failures (from enhanced: JWT token lifecycle)
TASK: Analyze token lifecycle, refresh flow, and middleware integration
CONTEXT: @{src/auth/**/*} @{CLAUDE.md} Session context: known token expiry issue
EXPECTED: Root cause analysis with file references
RULES: $(cat ~/.claude/workflows/cli-templates/prompts/analysis/security.txt) | Focus on JWT token handling
"
```
## Analysis Types
| Type | Keywords | Template | Context |
|------|----------|----------|---------|
| **pattern** | pattern, hooks, usage | analysis/pattern.txt | Matched files + CLAUDE.md |
| **architecture** | architecture, structure, design | analysis/architecture.txt | Full codebase + CLAUDE.md |
| **security** | security, vulnerability, auth | analysis/security.txt | Matched files + CLAUDE.md |
| **quality** | quality, test, coverage | analysis/quality.txt | Source + test files + CLAUDE.md |
## Command Templates
### Gemini (Default)
```bash
cd [target-dir] && ~/.claude/scripts/gemini-wrapper -p "
PURPOSE: [analysis goal from user input]
TASK: [specific analysis task]
cd [dir] && ~/.claude/scripts/[gemini|qwen]-wrapper -p "
PURPOSE: [analysis goal]
TASK: [specific task]
CONTEXT: @{[file-patterns]} @{CLAUDE.md}
EXPECTED: [expected output format]
EXPECTED: [output format]
RULES: $(cat ~/.claude/workflows/cli-templates/prompts/[category]/[template].txt) | [constraints]
"
```
### Qwen
**Codex**:
```bash
cd [target-dir] && ~/.claude/scripts/qwen-wrapper -p "
PURPOSE: [analysis goal from user input]
TASK: [specific analysis task]
codex -C [dir] --full-auto exec "
PURPOSE: [analysis goal]
TASK: [specific task]
CONTEXT: @{[file-patterns]} @{CLAUDE.md}
EXPECTED: [expected output format]
RULES: $(cat ~/.claude/workflows/cli-templates/prompts/[category]/[template].txt) | [constraints]
"
```
### Codex
```bash
codex -C [target-dir] --full-auto exec "
PURPOSE: [analysis goal from user input]
TASK: [specific analysis task]
CONTEXT: @{[file-patterns]} @{CLAUDE.md}
EXPECTED: [expected output format]
RULES: $(cat ~/.claude/workflows/cli-templates/prompts/[category]/[template].txt) | [constraints]
EXPECTED: [output format]
RULES: [constraints]
" --skip-git-repo-check -s danger-full-access
# With image attachment (e.g., UI screenshots, diagrams)
codex -C [dir] -i screenshot.png --full-auto exec "..." --skip-git-repo-check -s danger-full-access
```
## Examples
**Pattern Analysis (Gemini - default)**:
```bash
cd . && ~/.claude/scripts/gemini-wrapper -p "
PURPOSE: Analyze authentication patterns
TASK: Identify auth implementation patterns and conventions
CONTEXT: @{**/*auth*} @{CLAUDE.md}
EXPECTED: Pattern summary with file references
RULES: $(cat ~/.claude/workflows/cli-templates/prompts/analysis/pattern.txt) | Focus on security
"
```
**Architecture Review (Qwen)**:
```bash
# User: /cli:analyze --tool qwen "component architecture"
cd . && ~/.claude/scripts/qwen-wrapper -p "
PURPOSE: Review component architecture
TASK: Analyze component structure and dependencies
CONTEXT: @{src/**/*} @{CLAUDE.md}
EXPECTED: Architecture diagram and integration points
RULES: $(cat ~/.claude/workflows/cli-templates/prompts/analysis/architecture.txt) | Focus on modularity
"
```
**Deep Inspection (Codex)**:
```bash
# User: /cli:analyze --tool codex "performance bottlenecks"
codex -C . --full-auto exec "
PURPOSE: Identify performance bottlenecks
TASK: Deep analysis of performance issues
CONTEXT: @{src/**/*} @{CLAUDE.md}
EXPECTED: Performance metrics and optimization recommendations
RULES: Focus on computational complexity and memory usage
" --skip-git-repo-check -s danger-full-access
/cli:analyze "authentication patterns" # Gemini (default)
/cli:analyze --tool qwen "component architecture" # Qwen architecture
/cli:analyze --tool codex "performance bottlenecks" # Codex deep analysis
/cli:analyze --enhance "fix auth issues" # Enhanced prompt first
```
## File Pattern Logic
**Keyword Matching**:
Auto-detect file patterns from keywords:
- "auth" → `@{**/*auth*}`
- "component" → `@{src/components/**/*}`
- "API" → `@{**/api/**/*}`
- "test" → `@{**/*.test.*}`
- Generic → `@{src/**/*}` or `@{**/*}`
- Generic → `@{src/**/*}`
## Session Integration
**Detect Active Session**: Check for `.workflow/.active-*` marker file
**If Session Active**:
- Save results to `.workflow/WFS-[id]/.chat/analysis-[timestamp].md`
- Include session context in analysis
**If No Session**:
- Return results directly to user
## Output Format
Return Gemini's output directly, which includes:
- File references (file:line format)
- Code snippets
- Pattern analysis
- Recommendations
## Error Handling
- **Missing Template**: Use generic analysis prompt
- **No Context**: Use `@{**/*}` as fallback
- **Command Failure**: Report error and suggest manual command
- **Active Session**: Save results to `.workflow/WFS-[id]/.chat/analysis-[timestamp].md`
- **No Session**: Return results directly to user

View File

@@ -12,150 +12,81 @@ allowed-tools: SlashCommand(*), Bash(*)
model: sonnet
---
### 🚀 **Command Overview: `/cli:chat`**
## Purpose
- **Type**: CLI Tool Wrapper for Interactive Analysis
- **Purpose**: Direct interaction with CLI tools for codebase analysis
- **Supported Tools**: codex, gemini (default), qwen
Direct interaction with CLI tools for codebase analysis and Q&A.
### 📥 **Parameters & Usage**
**Supported Tools**: codex, gemini (default), qwen
**Reference**: @~/.claude/workflows/intelligent-tools-strategy.md for complete tool details
- **`<inquiry>` (Required)**: Your question or analysis request
- **`--tool <codex|gemini|qwen>` (Optional)**: Select CLI tool (default: gemini)
- **`--enhance` (Optional)**: Enhance inquiry with `/enhance-prompt` before execution
- **`--all-files` (Optional)**: Includes the entire codebase in the analysis context
- **`--save-session` (Optional)**: Saves the interaction to current workflow session directory
- **File References**: Specify files or patterns using `@{path/to/file}` syntax
## Parameters
### 🔄 **Execution Workflow**
- `<inquiry>` (Required): Question or analysis request
- `--tool <codex|gemini|qwen>` (Optional): Select CLI tool (default: gemini)
- `--enhance` (Optional): Enhance inquiry with `/enhance-prompt` first
- `--all-files` (Optional): Include entire codebase in context
- `--save-session` (Optional): Save interaction to workflow session
`Parse Tool` **->** `Parse Input` **->** `[Optional] Enhance` **->** `Assemble Context` **->** `Construct Prompt` **->** `Execute CLI Tool` **->** `(Optional) Save Session`
## Execution Flow
### 🛠️ **Tool Selection**
1. Parse tool selection (default: gemini)
2. If `--enhance`: Execute `/enhance-prompt` first
3. Assemble context (files + CLAUDE.md)
4. Execute CLI tool
5. Optional: Save to session
| Tool | Best For | Wrapper |
|------|----------|---------|
| **gemini** (default) | General analysis, exploration | `~/.claude/scripts/gemini-wrapper` |
| **qwen** | Architecture, design patterns | `~/.claude/scripts/qwen-wrapper` |
| **codex** | Development queries, deep analysis | `codex --full-auto exec` |
## Enhancement Integration
### 🔄 **Original Execution Workflow**
**When `--enhance` flag present**: Execute `/enhance-prompt "[inquiry]"` first, then use enhanced output (INTENT/CONTEXT/ACTION) to build the chat command.
`Parse Input` **->** `[Optional] Enhance` **->** `Assemble Context` **->** `Construct Prompt` **->** `Execute Gemini CLI` **->** `(Optional) Save Session`
## Context Assembly
### 🎯 **Enhancement Integration**
Context gathered from:
1. **Project Guidelines**: `@{CLAUDE.md,**/*CLAUDE.md}` (always)
2. **User-Explicit Files**: Files specified by user
3. **All Files Flag**: `--all-files` includes entire codebase
**When `--enhance` flag present**:
## Command Template
**Gemini/Qwen**:
```bash
# Step 1: Enhance the inquiry
SlashCommand(command="/enhance-prompt \"[inquiry]\"")
# Step 2: Use enhanced output for chat
# Enhanced output provides enriched context and structured intent
```
**Example**:
```bash
# User: /gemini:chat --enhance "fix the login"
# Step 1: Enhance
/enhance-prompt "fix the login"
# Returns:
# INTENT: Debug login authentication failure
# CONTEXT: JWT auth in src/auth/, session state issue
# ACTION: Check token validation → verify middleware → test flow
# Step 2: Chat with enhanced context
gemini -p "Debug login authentication failure. Focus on JWT token validation
in src/auth/, verify middleware integration, and test authentication flow.
Known issue: session state management"
```
### 📚 **Context Assembly**
Context is gathered from:
1. **Project Guidelines**: Always includes `@{CLAUDE.md,**/*CLAUDE.md}`
2. **User-Explicit Files**: Files specified by the user (e.g., `@{src/auth/*.js}`)
3. **All Files Flag**: The `--all-files` flag includes the entire codebase
### 📝 **Prompt Format**
**Core Guidelines**: @~/.claude/workflows/intelligent-tools-strategy.md
```bash
cd [directory] && ~/.claude/scripts/gemini-wrapper -p "
PURPOSE: [clear analysis/inquiry goal]
TASK: [specific analysis or question]
CONTEXT: @{CLAUDE.md,**/*CLAUDE.md} @{target_files}
EXPECTED: [expected response format]
RULES: [constraints or focus areas]
cd [dir] && ~/.claude/scripts/[gemini|qwen]-wrapper -p "
PURPOSE: [inquiry goal]
TASK: [specific question]
CONTEXT: @{CLAUDE.md} @{target_files}
EXPECTED: [response format]
RULES: [constraints]
"
# With --all-files
cd [dir] && ~/.claude/scripts/[gemini|qwen]-wrapper --all-files -p "..."
```
### ⚙️ **Execution Implementation**
**Standard Template**:
**Codex**:
```bash
cd . && ~/.claude/scripts/gemini-wrapper -p "
PURPOSE: [user inquiry goal]
TASK: [specific question or analysis]
CONTEXT: @{CLAUDE.md,**/*CLAUDE.md} @{inferred_or_specified_files}
EXPECTED: Analysis with file references and code examples
RULES: [focus areas based on inquiry]
"
codex -C [dir] --full-auto exec "
PURPOSE: [inquiry goal]
TASK: [specific question]
CONTEXT: @{CLAUDE.md} @{target_files}
EXPECTED: [response format]
RULES: [constraints]
" --skip-git-repo-check -s danger-full-access
# With image attachment
codex -C [dir] -i screenshot.png --full-auto exec "..." --skip-git-repo-check -s danger-full-access
```
**With --all-files flag**:
## Examples
```bash
cd . && ~/.claude/scripts/gemini-wrapper --all-files -p "
PURPOSE: [user inquiry goal]
TASK: [specific question or analysis]
CONTEXT: @{CLAUDE.md,**/*CLAUDE.md} [entire codebase]
EXPECTED: Comprehensive analysis across all files
RULES: [focus areas based on inquiry]
"
/cli:chat "analyze the authentication flow" # Gemini (default)
/cli:chat --tool qwen "optimize React component" # Qwen
/cli:chat --tool codex "review security vulnerabilities" # Codex
/cli:chat --enhance "fix the login" # Enhanced prompt
/cli:chat --all-files "find all API endpoints" # Full codebase
```
**Example - Authentication Analysis**:
```bash
cd . && ~/.claude/scripts/gemini-wrapper -p "
PURPOSE: Understand authentication flow implementation
TASK: Analyze authentication flow and identify patterns
CONTEXT: @{**/*auth*,**/*login*} @{CLAUDE.md}
EXPECTED: Flow diagram, security assessment, integration points
RULES: Focus on security patterns and JWT handling
"
```
## Session Persistence
**Example - Performance Optimization**:
```bash
cd src/components && ~/.claude/scripts/gemini-wrapper -p "
PURPOSE: Optimize React component performance
TASK: Identify performance bottlenecks in component rendering
CONTEXT: @{**/*.{jsx,tsx}} @{CLAUDE.md}
EXPECTED: Specific optimization recommendations with file:line references
RULES: Focus on re-render patterns and memoization opportunities
"
```
### 💾 **Session Persistence**
When `--save-session` flag is used:
- Check for existing active session (`.workflow/.active-*` markers)
- Save to existing session's `.chat/` directory or create new session
- File format: `chat-YYYYMMDD-HHMMSS.md`
- Include query, context, and response in saved file
**Session Template:**
```markdown
# Chat Session: [Timestamp]
## Query
[Original user inquiry]
## Context
[Files and patterns included in analysis]
## Gemini Response
[Complete response from Gemini CLI]
```
- **Active Session**: Save to `.workflow/WFS-[id]/.chat/chat-[timestamp].md`
- **No Session**: Return results directly

View File

@@ -0,0 +1,322 @@
---
name: codex-execute
description: Automated task decomposition and execution with Codex using resume mechanism
usage: /cli:codex-execute [--verify-git] <task-description|task-id>
argument-hint: "[--verify-git] task description or task-id"
examples:
- /cli:codex-execute "implement user authentication system"
- /cli:codex-execute --verify-git "refactor API layer"
- /cli:codex-execute IMPL-001
allowed-tools: SlashCommand(*), Bash(*), TodoWrite(*), Read(*), Glob(*)
---
# CLI Codex Execute Command (/cli:codex-execute)
## Purpose
Automated task decomposition and sequential execution with Codex, using `codex exec "..." resume --last` mechanism for continuity between subtasks.
**Input**: User description or task ID (automatically loads from `.task/[ID].json` if applicable)
**Reference**: @~/.claude/workflows/intelligent-tools-strategy.md for Codex details
## Core Workflow
```
Task Input → Decompose into Subtasks → TodoWrite Tracking →
For Each Subtask:
0. Stage existing changes (git add -A) if valid git repo
1. Execute with Codex
2. [Optional] Git verification
3. Mark complete in TodoWrite
4. Resume next subtask with `codex resume --last`
→ Final Summary
```
## Parameters
- `<input>` (Required): Task description or task ID (e.g., "implement auth" or "IMPL-001")
- If input matches task ID format, loads from `.task/[ID].json`
- Otherwise, uses input as task description
- `--verify-git` (Optional): Verify git status after each subtask completion
## Execution Flow
### Phase 1: Input Processing & Decomposition
1. **Parse Input**:
- Check if input matches task ID pattern (e.g., `IMPL-001`, `TASK-123`)
- If yes: Load from `.task/[ID].json` and extract requirements
- If no: Use input as task description directly
2. **Analyze & Decompose**:
- Analyze task complexity and scope
- Break down into 3-8 subtasks
- Create TodoWrite tracker with all subtasks
- Display decomposition for user review
**Decomposition Criteria**:
- Each subtask: 5-15 minutes completable
- Clear, testable outcomes
- Explicit dependencies
- Focused file scope (1-5 files per subtask)
### Phase 2: Sequential Execution
**Pre-Execution Git Staging** (if valid git repository):
```bash
# Stage all current changes before codex execution
# This makes codex changes clearly visible in git diff
git add -A
git status --short
```
**For First Subtask**:
```bash
# Initial execution (no resume needed)
codex -C [dir] --full-auto exec "
PURPOSE: [task goal]
TASK: [subtask 1 description]
CONTEXT: @{relevant_files} @{CLAUDE.md}
EXPECTED: [specific deliverables]
RULES: [constraints]
Subtask 1 of N: [subtask title]
" --skip-git-repo-check -s danger-full-access
```
**For Subsequent Subtasks** (using resume --last):
```bash
# Stage changes from previous subtask (if valid git repository)
git add -A
# Resume previous session for context continuity
codex exec "
CONTINUE TO NEXT SUBTASK:
Subtask N of M: [subtask title]
PURPOSE: [continuation goal]
TASK: [subtask N description]
CONTEXT: Previous work completed, now focus on @{new_relevant_files}
EXPECTED: [specific deliverables]
RULES: Build on previous subtask, maintain consistency
" resume --last --skip-git-repo-check -s danger-full-access
```
### Phase 3: Verification (if --verify-git enabled)
After each subtask completion:
```bash
# Check git status
git status --short
# Verify expected changes
git diff --stat
# Optional: Check for untracked files that should be committed
git ls-files --others --exclude-standard
```
**Verification Checks**:
- Files modified match subtask scope
- No unexpected changes in unrelated files
- No merge conflicts or errors
- Code compiles/runs (if applicable)
### Phase 4: TodoWrite Tracking
**Initial Setup**:
```javascript
TodoWrite({
todos: [
{ content: "Subtask 1: [description]", status: "in_progress", activeForm: "Executing subtask 1" },
{ content: "Subtask 2: [description]", status: "pending", activeForm: "Executing subtask 2" },
{ content: "Subtask 3: [description]", status: "pending", activeForm: "Executing subtask 3" },
// ... more subtasks
{ content: "Final verification and summary", status: "pending", activeForm: "Verifying and summarizing" }
]
})
```
**After Each Subtask**:
```javascript
TodoWrite({
todos: [
{ content: "Subtask 1: [description]", status: "completed", activeForm: "Executing subtask 1" },
{ content: "Subtask 2: [description]", status: "in_progress", activeForm: "Executing subtask 2" },
// ... update status
]
})
```
## Codex Resume Mechanism
**Why `codex resume --last`?**
- Maintains conversation context across subtasks
- Codex remembers previous decisions and patterns
- Reduces context repetition
- Ensures consistency in implementation style
**How It Works**:
1. First subtask creates new Codex session
2. After completion, session is saved
3. Subsequent subtasks use `codex resume --last` to continue
4. Each subtask builds on previous context
5. Final subtask completes full task
**Image Support**:
```bash
# First subtask with design reference
codex -C [dir] -i design.png --full-auto exec "..." --skip-git-repo-check -s danger-full-access
# Resume for next subtask (image context preserved)
codex exec "CONTINUE TO NEXT SUBTASK: ..." resume --last --skip-git-repo-check -s danger-full-access
```
## Error Handling
**Subtask Failure**:
1. Mark subtask as blocked in TodoWrite
2. Report error details to user
3. Pause execution for manual intervention
4. User can choose to:
- Retry current subtask
- Continue to next subtask
- Abort entire task
**Git Verification Failure** (if --verify-git):
1. Show unexpected changes
2. Pause execution
3. Request user decision:
- Continue anyway
- Rollback and retry
- Manual fix
**Codex Session Lost**:
1. Detect if `codex exec "..." resume --last` fails
2. Attempt retry with fresh session
3. Report to user if manual intervention needed
## Output Format
**During Execution**:
```
📋 Task Decomposition:
1. [Subtask 1 description]
2. [Subtask 2 description]
...
▶️ Executing Subtask 1/N: [title]
Codex session started...
[Codex output]
✅ Subtask 1 completed
🔍 Git Verification:
M src/file1.ts
A src/file2.ts
✅ Changes verified
▶️ Executing Subtask 2/N: [title]
Resuming Codex session...
[Codex output]
✅ Subtask 2 completed
...
✅ All Subtasks Completed
📊 Summary: [file references, changes, next steps]
```
**Final Summary**:
```markdown
# Task Execution Summary: [Task Description]
## Subtasks Completed
1. ✅ [Subtask 1]: [files modified]
2. ✅ [Subtask 2]: [files modified]
...
## Files Modified
- src/file1.ts:10-50 - [changes]
- src/file2.ts - [changes]
## Git Status
- N files modified
- M files added
- No conflicts
## Next Steps
- [Suggested follow-up actions]
```
## Examples
**Example 1: Simple Task**
```bash
/cli:codex-execute "implement user authentication system"
# Decomposes into:
# 1. Create user model and database schema
# 2. Implement JWT token generation
# 3. Create authentication middleware
# 4. Add login/logout endpoints
# 5. Write tests for auth flow
```
**Example 2: With Git Verification**
```bash
/cli:codex-execute --verify-git "refactor API layer to use dependency injection"
# After each subtask, verifies:
# - Only expected files modified
# - No breaking changes in unrelated code
# - Tests still pass
```
**Example 3: With Task ID**
```bash
/cli:codex-execute IMPL-001
# Loads task from .task/IMPL-001.json
# Decomposes based on task requirements
```
## Best Practices
1. **Subtask Granularity**: Keep subtasks small and focused
2. **Clear Boundaries**: Each subtask should have well-defined input/output
3. **Git Hygiene**: Use `--verify-git` for critical refactoring
4. **Pre-Execution Staging**: Stage changes before each subtask to clearly see codex modifications
5. **Context Continuity**: Let `codex resume --last` maintain context
6. **Recovery Points**: TodoWrite provides clear progress tracking
7. **Image References**: Attach design files for UI tasks
## Input Processing
**Automatic Detection**:
- Input matches task ID pattern → Load from `.task/[ID].json`
- Otherwise → Use as task description
**Task JSON Structure** (when loading from file):
```json
{
"task_id": "IMPL-001",
"title": "Implement user authentication",
"description": "Create JWT-based auth system",
"acceptance_criteria": [...],
"scope": {...},
"brainstorming_refs": [...]
}
```
**Save Results**:
- Execution log: `.chat/codex-execute-[timestamp].md` (if workflow active)
- Summary: `.summaries/[TASK-ID]-summary.md` (if task ID provided)
- TodoWrite tracking embedded in session
## Notes
**vs. `/cli:execute`**:
- `/cli:execute`: Single-shot execution with Gemini/Qwen/Codex
- `/cli:codex-execute`: Multi-stage Codex execution with automatic task decomposition and resume mechanism
**Input Flexibility**: Accepts both freeform descriptions and task IDs (auto-detects and loads JSON)
**Context Window**: `codex exec "..." resume --last` maintains conversation history, ensuring consistency across subtasks without redundant context injection.

View File

@@ -14,222 +14,98 @@ model: sonnet
# CLI Execute Command (/cli:execute)
## Overview
## Purpose
**⚡ YOLO-enabled execution**: Auto-approves all confirmations for streamlined implementation workflow.
**Purpose**: Execute implementation tasks using intelligent context inference and CLI tools with full permissions.
Execute implementation tasks with YOLO permissions (auto-approves all confirmations).
**Supported Tools**: codex, gemini (default), qwen
**Reference**: @~/.claude/workflows/intelligent-tools-strategy.md for complete tool details
**Core Guidelines**: @~/.claude/workflows/intelligent-tools-strategy.md
## YOLO Permissions
## 🚨 YOLO Permissions
Auto-approves: file pattern inference, execution, file modifications, summary generation
**All confirmations auto-approved by default:**
- ✅ File pattern inference confirmation
- ✅ Gemini execution confirmation
- ✅ File modification confirmation
- ✅ Implementation summary generation
## Enhancement Integration
## 🎯 Enhancement Integration
**When `--enhance` flag present** (Description Mode only): Execute `/enhance-prompt "[description]"` first, then use enhanced output (INTENT/CONTEXT/ACTION) for execution.
**When `--enhance` flag present** (for Description Mode only):
```bash
# Step 1: Enhance the description
SlashCommand(command="/enhance-prompt \"[description]\"")
# Step 2: Use enhanced output for execution
# Enhanced output provides:
# - INTENT: Clear technical goal
# - CONTEXT: Session memory + codebase patterns
# - ACTION: Specific implementation steps
# - ATTENTION: Critical constraints
```
**Example**:
```bash
# User: /gemini:execute --enhance "fix login"
# Step 1: Enhance
/enhance-prompt "fix login"
# Returns:
# INTENT: Debug authentication failure in login flow
# CONTEXT: JWT auth in src/auth/, known token expiry issue
# ACTION: Fix token validation → update refresh logic → test flow
# ATTENTION: Preserve existing session management
# Step 2: Execute with enhanced context
gemini --all-files -p "@{src/auth/**/*} @{CLAUDE.md}
Implementation: Debug authentication failure in login flow
Focus: Token validation, refresh logic, test flow
Constraints: Preserve existing session management"
```
**Note**: `--enhance` only applies to Description Mode. Task ID Mode uses task JSON directly.
**Note**: Task ID Mode uses task JSON directly (no enhancement).
## Execution Modes
### 1. Description Mode (supports --enhance)
**Input**: Natural language description
```bash
/gemini:execute "implement JWT authentication with middleware"
/gemini:execute --enhance "implement JWT authentication with middleware"
```
**Process**: [Optional: Enhance] → Keyword analysis → Pattern inference → Context collection → Execution
**1. Description Mode** (supports `--enhance`):
- Input: Natural language description
- Process: [Optional: Enhance] → Keyword analysis → Pattern inference → Execute
### 2. Task ID Mode (no --enhance)
**Input**: Workflow task identifier
```bash
/gemini:execute IMPL-001
```
**Process**: Task JSON parsing → Scope analysis → Context integration → Execution
**2. Task ID Mode** (no `--enhance`):
- Input: Workflow task identifier (e.g., `IMPL-001`)
- Process: Task JSON parsing → Scope analysis → Execute
## Context Inference Logic
## Context Inference
**Auto-selects relevant files based on:**
Auto-selects files based on:
- **Keywords**: "auth" → `@{**/*auth*,**/*user*}`
- **Technology**: "React" → `@{src/**/*.{jsx,tsx}}`
- **Task Type**: "api" → `@{**/api/**/*,**/routes/**/*}`
- **Always includes**: `@{CLAUDE.md,**/*CLAUDE.md}`
- **Always**: `@{CLAUDE.md,**/*CLAUDE.md}`
## Command Options
## Options
| Option | Purpose |
|--------|---------|
| `--debug` | Verbose execution logging |
| `--save-session` | Save complete execution session to workflow |
- `--debug`: Verbose logging
- `--save-session`: Save execution to workflow session
## Workflow Integration
### Session Management
⚠️ **Auto-detects active session**: Checks `.workflow/.active-*` marker file
**Session Management**: Auto-detects `.workflow/.active-*` marker
- **Active**: Save to `.workflow/WFS-[id]/.chat/execute-[timestamp].md`
- **None**: Create new session
**Session storage:**
- **Active session exists**: Saves to `.workflow/WFS-[topic]/.chat/execute-[timestamp].md`
- **No active session**: Creates new session directory
**Task Integration**: Load from `.task/[TASK-ID].json`, update status, generate summary
### Task Integration
## Command Template
**Gemini/Qwen** (with YOLO approval):
```bash
# Execute specific workflow task
/gemini:execute IMPL-001
# Loads from: .task/IMPL-001.json
# Uses: task context, brainstorming refs, scope definitions
# Updates: workflow status, generates summary
```
## Execution Templates
**Core Guidelines**: @~/.claude/workflows/intelligent-tools-strategy.md
### Permission Requirements
**Gemini Write Access** (when file modifications needed):
- Add `--approval-mode yolo` flag for auto-approval
- Required for: file creation, modification, deletion
### User Description Template
```bash
cd [target-directory] && ~/.claude/scripts/gemini-wrapper --approval-mode yolo -p "
PURPOSE: [clear implementation goal from description]
TASK: [specific implementation task]
CONTEXT: @{inferred_patterns} @{CLAUDE.md,**/*CLAUDE.md}
EXPECTED: Implementation code with file:line locations, test cases, integration guidance
RULES: [template reference if applicable] | [constraints]
cd [dir] && ~/.claude/scripts/[gemini|qwen]-wrapper --approval-mode yolo -p "
PURPOSE: [implementation goal]
TASK: [specific task]
MODE: write
CONTEXT: @{inferred_patterns} @{CLAUDE.md}
EXPECTED: Implementation with file:line references
RULES: $(cat ~/.claude/workflows/cli-templates/prompts/[category]/[template].txt) | [constraints]
"
```
**Example**:
**Codex**:
```bash
cd . && ~/.claude/scripts/gemini-wrapper --approval-mode yolo -p "
PURPOSE: Implement JWT authentication with middleware
TASK: Create authentication system with token validation
CONTEXT: @{**/*auth*,**/*middleware*} @{CLAUDE.md}
EXPECTED: Auth service, middleware, tests with file modifications
RULES: Follow existing auth patterns | Security best practices
"
codex -C [dir] --full-auto exec "
PURPOSE: [implementation goal]
TASK: [specific task]
MODE: auto
CONTEXT: @{inferred_patterns} @{CLAUDE.md}
EXPECTED: Implementation with file:line references
RULES: [constraints]
" --skip-git-repo-check -s danger-full-access
# With image attachment
codex -C [dir] -i design.png --full-auto exec "..." --skip-git-repo-check -s danger-full-access
```
### Task ID Template
```bash
cd [task-directory] && ~/.claude/scripts/gemini-wrapper --approval-mode yolo -p "
PURPOSE: [task_title]
TASK: Execute [task-id] implementation
CONTEXT: @{task_files} @{brainstorming_refs} @{CLAUDE.md,**/*CLAUDE.md}
EXPECTED: Complete implementation following acceptance criteria
RULES: $(cat [task_template]) | Task type: [task_type], Scope: [task_scope]
"
```
## Examples
**Example**:
```bash
cd .workflow/WFS-123 && ~/.claude/scripts/gemini-wrapper --approval-mode yolo -p "
PURPOSE: Implement user profile editing
TASK: Execute IMPL-001 implementation
CONTEXT: @{src/user/**/*} @{.brainstorming/product-owner/analysis.md} @{CLAUDE.md}
EXPECTED: Profile edit API, UI components, validation, tests
RULES: $(cat ~/.claude/workflows/cli-templates/prompts/development/feature.txt) | Type: feature, Scope: user module
"
/cli:execute "implement JWT authentication with middleware" # Description mode
/cli:execute --enhance "implement JWT authentication" # Enhanced
/cli:execute IMPL-001 # Task ID mode
/cli:execute --tool codex "optimize database queries" # Codex execution
```
## Auto-Generated Outputs
### 1. Implementation Summary
**Location**: `.summaries/[TASK-ID]-summary.md` or auto-generated ID
- **Summary**: `.summaries/[TASK-ID]-summary.md`
- **Session**: `.chat/execute-[timestamp].md`
```markdown
# Task Summary: [Task-ID] [Description]
## Notes
## Implementation
- **Files Modified**: [file:line references]
- **Features Added**: [specific functionality]
- **Context Used**: [inferred patterns]
## Integration
- [Links to workflow documents]
```
### 2. Execution Session
**Location**: `.chat/execute-[timestamp].md`
```markdown
# Execution Session: [Timestamp]
## Input
[User description or Task ID]
## Context Inference
[File patterns used with rationale]
## Implementation Results
[Generated code and modifications]
## Status Updates
[Workflow integration updates]
```
## Error Handling
- **Task ID not found**: Lists available tasks
- **Pattern inference failure**: Uses generic `src/**/*` pattern
- **Execution failure**: Attempts fallback with simplified context
- **File modification errors**: Reports specific file/permission issues
## Performance Features
- **Smart caching**: Frequently used pattern mappings
- **Progressive inference**: Precise → broad pattern fallback
- **Parallel execution**: When multiple contexts needed
- **Directory optimization**: Switches to optimal execution path
## Integration Workflow
**Typical sequence:**
1. `workflow:plan` → Creates tasks
2. `/gemini:execute IMPL-001` → Executes with YOLO permissions
3. Auto-updates workflow status and generates summaries
4. `workflow:review` → Final validation
**vs. `/gemini:analyze`**: Execute performs analysis **and implementation**, analyze is read-only.
**vs. `/cli:analyze`**: Execute performs implementation, analyze is read-only.

261
.claude/commands/version.md Normal file
View File

@@ -0,0 +1,261 @@
---
name: version
description: Display version information and check for updates
usage: /version
examples:
- /version
allowed-tools: Bash(*)
---
# Version Command (/version)
## Purpose
Display local and global installation versions, check for the latest updates from GitHub, and provide upgrade recommendations.
## Execution Flow
1. **Local Version Check**: Read version information from `./.claude/version.json` if it exists.
2. **Global Version Check**: Read version information from `~/.claude/version.json` if it exists.
3. **Fetch Remote Versions**: Use GitHub API to get the latest stable release tag and the latest commit hash from the main branch.
4. **Compare & Suggest**: Compare installed versions with the latest remote versions and provide upgrade suggestions if applicable.
## Step 1: Check Local Version
### Check if local version.json exists
```bash
bash(test -f ./.claude/version.json && echo "found" || echo "not_found")
```
### Read local version (if exists)
```bash
bash(cat ./.claude/version.json)
```
### Extract version with jq (preferred)
```bash
bash(cat ./.claude/version.json | grep -o '"version": *"[^"]*"' | cut -d'"' -f4)
```
### Extract installation date
```bash
bash(cat ./.claude/version.json | grep -o '"installation_date_utc": *"[^"]*"' | cut -d'"' -f4)
```
**Output Format**:
```
Local Version: 3.2.1
Installed: 2025-10-03T12:00:00Z
```
## Step 2: Check Global Version
### Check if global version.json exists
```bash
bash(test -f ~/.claude/version.json && echo "found" || echo "not_found")
```
### Read global version
```bash
bash(cat ~/.claude/version.json)
```
### Extract version
```bash
bash(cat ~/.claude/version.json | grep -o '"version": *"[^"]*"' | cut -d'"' -f4)
```
### Extract installation date
```bash
bash(cat ~/.claude/version.json | grep -o '"installation_date_utc": *"[^"]*"' | cut -d'"' -f4)
```
**Output Format**:
```
Global Version: 3.2.1
Installed: 2025-10-03T12:00:00Z
```
## Step 3: Fetch Latest Stable Release
### Call GitHub API for latest release (with timeout)
```bash
bash(curl -fsSL "https://api.github.com/repos/catlog22/Claude-Code-Workflow/releases/latest" 2>/dev/null, timeout: 30000)
```
### Extract tag name (version)
```bash
bash(curl -fsSL "https://api.github.com/repos/catlog22/Claude-Code-Workflow/releases/latest" 2>/dev/null | grep -o '"tag_name": *"[^"]*"' | head -1 | cut -d'"' -f4, timeout: 30000)
```
### Extract release name
```bash
bash(curl -fsSL "https://api.github.com/repos/catlog22/Claude-Code-Workflow/releases/latest" 2>/dev/null | grep -o '"name": *"[^"]*"' | head -1 | cut -d'"' -f4, timeout: 30000)
```
### Extract published date
```bash
bash(curl -fsSL "https://api.github.com/repos/catlog22/Claude-Code-Workflow/releases/latest" 2>/dev/null | grep -o '"published_at": *"[^"]*"' | cut -d'"' -f4, timeout: 30000)
```
**Output Format**:
```
Latest Stable: v3.2.2
Release: v3.2.2: Independent Test-Gen Workflow with Cross-Session Context
Published: 2025-10-03T04:10:08Z
```
## Step 4: Fetch Latest Main Branch
### Call GitHub API for latest commit on main (with timeout)
```bash
bash(curl -fsSL "https://api.github.com/repos/catlog22/Claude-Code-Workflow/commits/main" 2>/dev/null, timeout: 30000)
```
### Extract commit SHA (short)
```bash
bash(curl -fsSL "https://api.github.com/repos/catlog22/Claude-Code-Workflow/commits/main" 2>/dev/null | grep -o '"sha": *"[^"]*"' | head -1 | cut -d'"' -f4 | cut -c1-7, timeout: 30000)
```
### Extract commit message (first line only)
```bash
bash(curl -fsSL "https://api.github.com/repos/catlog22/Claude-Code-Workflow/commits/main" 2>/dev/null | grep '"message":' | cut -d'"' -f4 | cut -d'\' -f1, timeout: 30000)
```
### Extract commit date
```bash
bash(curl -fsSL "https://api.github.com/repos/catlog22/Claude-Code-Workflow/commits/main" 2>/dev/null | grep -o '"date": *"[^"]*"' | head -1 | cut -d'"' -f4, timeout: 30000)
```
**Output Format**:
```
Latest Dev: a03415b
Message: feat: Add version tracking and upgrade check system
Date: 2025-10-03T04:46:44Z
```
## Step 5: Compare Versions and Suggest Upgrade
### Normalize versions (remove 'v' prefix)
```bash
bash(echo "v3.2.1" | sed 's/^v//')
```
### Compare two versions
```bash
bash(printf "%s\n%s" "3.2.1" "3.2.2" | sort -V | tail -n 1)
```
### Check if versions are equal
```bash
# If equal: Up to date
# If remote newer: Upgrade available
# If local newer: Development version
```
**Output Scenarios**:
**Scenario 1: Up to date**
```
✅ You are on the latest stable version (3.2.1)
```
**Scenario 2: Upgrade available**
```
⬆️ A newer stable version is available: v3.2.2
Your version: 3.2.1
To upgrade:
PowerShell: iex (iwr -useb https://raw.githubusercontent.com/catlog22/Claude-Code-Workflow/main/install-remote.ps1)
Bash: bash <(curl -fsSL https://raw.githubusercontent.com/catlog22/Claude-Code-Workflow/main/install-remote.sh)
```
**Scenario 3: Development version**
```
✨ You are running a development version (3.4.0-dev)
This is newer than the latest stable release (v3.3.0)
```
## Simple Bash Commands
### Basic Operations
```bash
# Check local version file
bash(test -f ./.claude/version.json && cat ./.claude/version.json)
# Check global version file
bash(test -f ~/.claude/version.json && cat ~/.claude/version.json)
# Extract version from JSON
bash(cat version.json | grep -o '"version": *"[^"]*"' | cut -d'"' -f4)
# Extract date from JSON
bash(cat version.json | grep -o '"installation_date_utc": *"[^"]*"' | cut -d'"' -f4)
# Fetch latest release (with timeout)
bash(curl -fsSL "https://api.github.com/repos/catlog22/Claude-Code-Workflow/releases/latest" 2>/dev/null, timeout: 30000)
# Extract tag name
bash(curl -fsSL "https://api.github.com/repos/catlog22/Claude-Code-Workflow/releases/latest" 2>/dev/null | grep -o '"tag_name": *"[^"]*"' | cut -d'"' -f4, timeout: 30000)
# Extract release name
bash(curl -fsSL "https://api.github.com/repos/catlog22/Claude-Code-Workflow/releases/latest" 2>/dev/null | grep -o '"name": *"[^"]*"' | head -1 | cut -d'"' -f4, timeout: 30000)
# Fetch latest commit (with timeout)
bash(curl -fsSL "https://api.github.com/repos/catlog22/Claude-Code-Workflow/commits/main" 2>/dev/null, timeout: 30000)
# Extract commit SHA
bash(curl -fsSL "https://api.github.com/repos/catlog22/Claude-Code-Workflow/commits/main" 2>/dev/null | grep -o '"sha": *"[^"]*"' | head -1 | cut -d'"' -f4 | cut -c1-7, timeout: 30000)
# Extract commit message (first line)
bash(curl -fsSL "https://api.github.com/repos/catlog22/Claude-Code-Workflow/commits/main" 2>/dev/null | grep '"message":' | cut -d'"' -f4 | cut -d'\' -f1, timeout: 30000)
# Compare versions
bash(printf "%s\n%s" "3.2.1" "3.2.2" | sort -V | tail -n 1)
# Remove 'v' prefix
bash(echo "v3.2.1" | sed 's/^v//')
```
## Error Handling
### No installation found
```
WARNING: Claude Code Workflow not installed
Install using:
PowerShell: iex (iwr -useb https://raw.githubusercontent.com/catlog22/Claude-Code-Workflow/main/install-remote.ps1)
```
### Network error
```
ERROR: Could not fetch latest version from GitHub
Check your network connection
```
### Invalid version.json
```
ERROR: version.json is invalid or corrupted
```
## Design Notes
- Uses simple, direct bash commands instead of complex functions
- Each step is independent and can be executed separately
- Fallback to grep/sed for JSON parsing (no jq dependency required)
- Network calls use curl with error suppression and 30-second timeout
- Version comparison uses `sort -V` for accurate semantic versioning
- Use `/commits/main` API instead of `/branches/main` for more reliable commit info
- Extract first line of commit message using `cut -d'\' -f1` to handle JSON escape sequences
## API Endpoints
### GitHub API Used
- **Latest Release**: `https://api.github.com/repos/catlog22/Claude-Code-Workflow/releases/latest`
- Fields: `tag_name`, `name`, `published_at`
- **Latest Commit**: `https://api.github.com/repos/catlog22/Claude-Code-Workflow/commits/main`
- Fields: `sha`, `commit.message`, `commit.author.date`
### Timeout Configuration
All network calls should use `timeout: 30000` (30 seconds) to handle slow connections.
## Related Commands
- `/cli:cli-init` - Initialize CLI configurations
- `/workflow:session:list` - List workflow sessions

View File

@@ -1,6 +1,6 @@
---
name: synthesis
description: Generate synthesis-report.md from topic-framework and role analyses with @ references
description: Generate synthesis-specification.md from topic-framework and role analyses with @ references
usage: /workflow:brainstorm:synthesis
argument-hint: "no arguments required - synthesizes existing framework and role analyses"
examples:
@@ -11,25 +11,36 @@ allowed-tools: Read(*), Write(*), TodoWrite(*), Glob(*)
## 🧩 **Synthesis Document Generator**
### Core Function
**Specialized command for generating synthesis-report.md** that integrates topic-framework.md and all role analysis.md files using @ reference system. Creates comprehensive strategic analysis with cross-role insights.
**Specialized command for generating synthesis-specification.md** that integrates topic-framework.md and all role analysis.md files using @ reference system. Creates comprehensive implementation specification with cross-role insights.
**Dynamic Role Discovery**: Automatically detects which roles participated in brainstorming by scanning for `*/analysis.md` files. Synthesizes only actual participating roles, not predefined lists.
### Primary Capabilities
- **Framework Integration**: Reference topic-framework.md discussion points across all roles
- **Role Analysis Integration**: Consolidate all role/analysis.md files using @ references
- **Cross-Framework Comparison**: Compare how each role addressed framework discussion points
- **Dynamic Role Discovery**: Automatically identifies participating roles at runtime
- **Framework Integration**: Reference topic-framework.md discussion points across all discovered roles
- **Role Analysis Integration**: Consolidate all discovered role/analysis.md files using @ references
- **Cross-Framework Comparison**: Compare how each participating role addressed framework discussion points
- **@ Reference System**: Create structured references to source documents
- **Update Detection**: Smart updates when new role analyses are added
- **Flexible Participation**: Supports any subset of available roles (1 to 9+)
### Document Integration Model
**Three-Document Reference System**:
1. **topic-framework.md** → Structured discussion framework (input)
2. **[role]/analysis.md** → Role-specific analyses addressing framework (input)
3. **synthesis-report.md**Integrated synthesis with @ references (output)
3. **synthesis-specification.md**Complete integrated specification (output)
## ⚙️ **Execution Protocol**
### ⚠️ Direct Execution Only
**DO NOT use Task tool or delegate to any agent** - This is a document synthesis task using only Read/Write/Glob tools for aggregating existing analyses.
### ⚠️ Direct Execution by Main Claude
**Execution Model**: Main Claude directly executes this command without delegating to sub-agents.
**Rationale**:
- **Full Context Access**: Avoids context transmission loss that occurs with Task tool delegation
- **Complex Cognitive Analysis**: Leverages main Claude's complete reasoning capabilities for cross-role synthesis
- **Tool Usage**: Combines Read/Write/Glob tools with main Claude's analytical intelligence
**DO NOT use Task tool** - Main Claude performs intelligent analysis directly while reading/writing files, ensuring no information loss from context passing.
### Phase 1: Document Discovery & Validation
```bash
@@ -51,22 +62,39 @@ IF NOT EXISTS:
### Phase 2: Role Analysis Discovery
```bash
# Discover available role analyses
# Dynamically discover available role analyses
SCAN_DIRECTORY: .workflow/WFS-{session}/.brainstorming/
FIND_ANALYSES: [
*/analysis.md files in role directories
Scan all subdirectories for */analysis.md files
Extract role names from directory names
]
# Available roles (for reference, actual participation is dynamic):
# - product-manager
# - product-owner
# - scrum-master
# - system-architect
# - ui-designer
# - ux-expert
# - data-architect
# - subject-matter-expert
# - test-strategist
LOAD_DOCUMENTS: {
"topic_framework": topic-framework.md,
"role_analyses": [discovered analysis.md files],
"existing_synthesis": synthesis-report.md (if exists)
"role_analyses": [dynamically discovered analysis.md files],
"participating_roles": [extract role names from discovered directories],
"existing_synthesis": synthesis-specification.md (if exists)
}
# Note: Not all roles participate in every brainstorming session
# Only synthesize roles that actually produced analysis.md files
```
### Phase 3: Update Mechanism Check
```bash
# Check for existing synthesis
IF synthesis-report.md EXISTS:
IF synthesis-specification.md EXISTS:
SHOW current synthesis summary to user
ASK: "Synthesis exists. Do you want to:"
OPTIONS:
@@ -84,42 +112,60 @@ Initialize synthesis task tracking:
{"content": "Validate topic-framework.md and role analyses availability", "status": "in_progress", "activeForm": "Validating source documents"},
{"content": "Load topic framework discussion points structure", "status": "pending", "activeForm": "Loading framework structure"},
{"content": "Cross-analyze role responses to each framework point", "status": "pending", "activeForm": "Cross-analyzing framework responses"},
{"content": "Generate synthesis-report.md with @ references", "status": "pending", "activeForm": "Generating synthesis with references"},
{"content": "Generate synthesis-specification.md with @ references", "status": "pending", "activeForm": "Generating synthesis with references"},
{"content": "Update session metadata with synthesis completion", "status": "pending", "activeForm": "Updating session metadata"}
]
```
### Phase 4: Cross-Role Analysis Execution
### Phase 5: Cross-Role Analysis Execution
#### 4.1 Data Collection and Preprocessing
**Dynamic Role Processing**: The number and types of roles are determined at runtime based on actual analysis.md files discovered in Phase 2.
#### 5.1 Data Collection and Preprocessing
```pseudo
FOR each role_directory in brainstorming_roles:
IF role_directory exists:
role_analysis = Read(role_directory + "/analysis.md")
role_recommendations = Read(role_directory + "/recommendations.md") IF EXISTS
role_insights[role] = extract_key_insights(role_analysis)
role_recommendations[role] = extract_recommendations(role_analysis)
role_concerns[role] = extract_concerns_risks(role_analysis)
# Iterate over dynamically discovered role analyses
FOR each discovered_role IN participating_roles:
role_directory = brainstorm_dir + "/" + discovered_role
# Load role analysis (required)
role_analysis = Read(role_directory + "/analysis.md")
# Load optional artifacts if present
IF EXISTS(role_directory + "/recommendations.md"):
role_recommendations[discovered_role] = Read(role_directory + "/recommendations.md")
END IF
# Extract insights from analysis
role_insights[discovered_role] = extract_key_insights(role_analysis)
role_recommendations[discovered_role] = extract_recommendations(role_analysis)
role_concerns[discovered_role] = extract_concerns_risks(role_analysis)
role_diagrams[discovered_role] = identify_diagrams_and_visuals(role_analysis)
END FOR
# Log participating roles for metadata
participating_role_count = COUNT(participating_roles)
participating_role_names = participating_roles
```
#### 4.2 Cross-Role Insight Analysis
#### 5.2 Cross-Role Insight Analysis
```pseudo
# Consensus identification
# Consensus identification (across all participating roles)
consensus_areas = identify_common_themes(role_insights)
agreement_matrix = create_agreement_matrix(role_recommendations)
# Disagreement analysis
# Disagreement analysis (track which specific roles disagree)
disagreement_areas = identify_conflicting_views(role_insights)
tension_points = analyze_role_conflicts(role_recommendations)
FOR each conflict IN disagreement_areas:
conflict.dissenting_roles = identify_dissenting_roles(conflict)
END FOR
# Innovation opportunity extraction
innovation_opportunities = extract_breakthrough_ideas(role_insights)
synergy_opportunities = identify_cross_role_synergies(role_insights)
```
#### 4.3 Priority and Decision Matrix Generation
#### 5.3 Priority and Decision Matrix Generation
```pseudo
# Create comprehensive evaluation matrix
FOR each recommendation:
@@ -137,16 +183,6 @@ SORT recommendations BY priority_score DESC
## 📊 **Output Specification**
### Output Location
```
.workflow/WFS-{topic-slug}/.brainstorming/
├── topic-framework.md # Input: Framework structure
├── [role]/analysis.md # Input: Role analyses (multiple)
└── synthesis-report.md # ★ OUTPUT: Integrated synthesis with @ references
```
### Streamlined Single-Document Output ⚠️ SIMPLIFIED STRUCTURE
#### Output Document - Single Comprehensive Synthesis
The synthesis process creates **one consolidated document** that integrates all role perspectives:
```
@@ -157,30 +193,74 @@ The synthesis process creates **one consolidated document** that integrates all
```
#### synthesis-specification.md Structure (Complete Specification)
**Document Purpose**: Defines **"WHAT"** to build - comprehensive requirements and design blueprint.
**Scope**: High-level features, requirements, and design specifications. Does NOT include executable task breakdown (that's IMPL_PLAN.md's responsibility).
```markdown
# [Topic] - Integrated Implementation Specification
**Framework Reference**: @topic-framework.md | **Generated**: [timestamp] | **Session**: WFS-[topic-slug]
**Source Integration**: All brainstorming role perspectives consolidated
**Document Type**: Requirements & Design Specification (WHAT to build)
## Executive Summary
Strategic overview with key insights, breakthrough opportunities, and implementation priorities.
## Key Designs & Decisions
### Core Architecture Diagram
```mermaid
graph TD
A[Component A] --> B[Component B]
B --> C[Component C]
```
*Reference: @system-architect/analysis.md#architecture-diagram*
### User Journey Map
![User Journey](./assets/user-journey.png)
*Reference: @ux-expert/analysis.md#user-journey*
### Data Model Overview
```mermaid
erDiagram
USER ||--o{ ORDER : places
ORDER ||--|{ LINE-ITEM : contains
```
*Reference: @data-architect/analysis.md#data-model*
### Architecture Decision Records (ADRs)
**ADR-01: [Decision Title]**
- **Context**: Background and problem statement
- **Decision**: Chosen approach
- **Rationale**: Why this approach was selected
- **Reference**: @system-architect/analysis.md#adr-01
## Controversial Points & Alternatives
| Point | Adopted Solution | Alternative Solution(s) | Decision Rationale | Dissenting Roles |
|-------|------------------|-------------------------|--------------------| -----------------|
| Authentication | JWT Token (@security-expert) | Session-Cookie (@system-architect) | Stateless API support for multi-platform | System Architect noted session performance benefits |
| UI Framework | React (@ui-designer) | Vue.js (@subject-matter-expert) | Team expertise and ecosystem maturity | Subject Matter Expert preferred Vue for learning curve |
*This section preserves decision context and rejected alternatives for future reference.*
## Requirements & Acceptance Criteria
### Functional Requirements
| ID | Description | Source | Priority | Acceptance | Dependencies |
|----|-------------|--------|----------|------------|--------------|
| FR-01 | Core feature | @role/analysis.md | High | Criteria | None |
| ID | Description | Rationale Summary | Source | Priority | Acceptance | Dependencies |
|----|-------------|-------------------|--------|----------|------------|--------------|
| FR-01 | User authentication | Enable secure multi-platform access | @product-manager/analysis.md | High | User can login via email/password | None |
| FR-02 | Data export | User-requested analytics feature | @product-owner/analysis.md | Medium | Export to CSV/JSON | FR-01 |
### Non-Functional Requirements
| ID | Description | Target | Validation |
|----|-------------|--------|------------|
| NFR-01 | Performance | <200ms | Testing |
| ID | Description | Rationale Summary | Target | Validation | Source |
|----|-------------|-------------------|--------|------------|--------|
| NFR-01 | Response time | UX research shows <200ms critical | <200ms | Load testing | @ux-expert/analysis.md |
| NFR-02 | Data encryption | Compliance requirement | AES-256 | Security audit | @security-expert/analysis.md |
### Business Requirements
| ID | Description | Value | Success Metric |
|----|-------------|-------|----------------|
| BR-01 | User engagement | High | 80% retention |
| ID | Description | Rationale Summary | Value | Success Metric | Source |
|----|-------------|-------------------|-------|----------------|--------|
| BR-01 | User retention | Market analysis shows engagement gap | High | 80% 30-day retention | @product-manager/analysis.md |
| BR-02 | Revenue growth | Business case justification | High | 25% MRR increase | @product-owner/analysis.md |
## Design Specifications
### UI/UX Guidelines
@@ -201,7 +281,34 @@ Strategic overview with key insights, breakthrough opportunities, and implementa
- Compliance requirements and regulations
- Technical quality and domain-specific patterns
## Implementation Roadmap
## Process & Collaboration Concerns
**Consolidated from**: @scrum-master/analysis.md, @product-owner/analysis.md
### Team Capability Assessment
| Required Skill | Current Level | Gap Analysis | Mitigation Strategy | Reference |
|----------------|---------------|--------------|---------------------|-----------|
| Kubernetes | Intermediate | Need advanced knowledge | Training + external consultant | @scrum-master/analysis.md |
| React Hooks | Advanced | Team ready | None | @scrum-master/analysis.md |
### Process Risks
| Risk | Impact | Probability | Mitigation | Owner |
|------|--------|-------------|------------|-------|
| Cross-team API dependency | High | Medium | Early API contract definition | @scrum-master/analysis.md |
| UX-Dev alignment gap | Medium | High | Weekly design sync meetings | @ux-expert/analysis.md |
### Collaboration Patterns
- **Design-Dev Pairing**: UI Designer and Frontend Dev pair programming for complex interactions
- **Architecture Reviews**: Weekly arch review for system-level decisions
- **User Testing Cadence**: Bi-weekly UX testing sessions with real users
- **Reference**: @scrum-master/analysis.md#collaboration
### Timeline Constraints
- **Blocking Dependencies**: Project-X API must complete before Phase 2
- **Resource Constraints**: Only 2 backend developers available in Q1
- **External Dependencies**: Third-party OAuth provider integration timeline
- **Reference**: @scrum-master/analysis.md#constraints
## Implementation Roadmap (High-Level)
### Development Phases
**Phase 1** (0-3 months): Foundation and core features
**Phase 2** (3-6 months): Advanced features and integrations
@@ -212,10 +319,12 @@ Strategic overview with key insights, breakthrough opportunities, and implementa
- Testing strategy and quality assurance
- Deployment and monitoring approach
### Task Breakdown
- Epic and feature mapping aligned with requirements
- Sprint planning guidance with dependency management
- Resource allocation and timeline recommendations
### Feature Grouping (Epic-Level)
- High-level feature grouping and prioritization
- Epic-level dependencies and sequencing
- Strategic milestones and release planning
**Note**: Detailed task breakdown into executable work items is handled by `/workflow:plan``IMPL_PLAN.md`
## Risk Assessment & Mitigation
### Critical Risks Identified
@@ -235,6 +344,9 @@ Strategic overview with key insights, breakthrough opportunities, and implementa
### Streamlined Status Synchronization
Upon completion, update `workflow-session.json`:
**Dynamic Role Participation**: The `participating_roles` and `roles_synthesized` values are determined at runtime based on actual analysis.md files discovered.
```json
{
"phases": {
@@ -242,22 +354,47 @@ Upon completion, update `workflow-session.json`:
"status": "completed",
"synthesis_completed": true,
"completed_at": "timestamp",
"participating_roles": ["product-manager", "product-owner", "scrum-master", "system-architect", "ui-designer", "ux-expert", "data-architect", "subject-matter-expert", "test-strategist"],
"participating_roles": ["<dynamically-discovered-role-1>", "<dynamically-discovered-role-2>", "..."],
"available_roles": ["product-manager", "product-owner", "scrum-master", "system-architect", "ui-designer", "ux-expert", "data-architect", "subject-matter-expert", "test-strategist"],
"consolidated_output": {
"synthesis_specification": ".workflow/WFS-{topic}/.brainstorming/synthesis-specification.md"
},
"synthesis_quality": {
"role_integration": "complete",
"requirement_coverage": "comprehensive",
"decision_transparency": "alternatives_documented",
"process_risks_identified": true,
"implementation_readiness": "ready"
},
"content_metrics": {
"roles_synthesized": 9,
"functional_requirements": 25,
"non_functional_requirements": 12,
"business_requirements": 8,
"implementation_phases": 3,
"risk_factors_identified": 8
"roles_synthesized": "<COUNT(participating_roles)>",
"functional_requirements": "<dynamic-count>",
"non_functional_requirements": "<dynamic-count>",
"business_requirements": "<dynamic-count>",
"architecture_decisions": "<dynamic-count>",
"controversial_points": "<dynamic-count>",
"diagrams_included": "<dynamic-count>",
"process_risks": "<dynamic-count>",
"team_skill_gaps": "<dynamic-count>",
"implementation_phases": "<dynamic-count>",
"risk_factors_identified": "<dynamic-count>"
}
}
}
}
```
**Example with actual values**:
```json
{
"phases": {
"BRAINSTORM": {
"status": "completed",
"participating_roles": ["product-manager", "system-architect", "ui-designer", "ux-expert", "scrum-master"],
"content_metrics": {
"roles_synthesized": 5,
"functional_requirements": 18,
"controversial_points": 2
}
}
}
@@ -268,28 +405,35 @@ Upon completion, update `workflow-session.json`:
### Required Synthesis Elements
- [ ] Integration of all available role analyses with comprehensive coverage
- [ ] Clear identification of consensus areas and disagreement points
- [ ] **Key Designs & Decisions**: Architecture diagrams, user journey maps, ADRs documented
- [ ] **Controversial Points**: Disagreement points, alternatives, and decision rationale captured
- [ ] **Process Concerns**: Team capability gaps, process risks, collaboration patterns identified
- [ ] Quantified priority recommendation matrix with evaluation criteria
- [ ] Actionable implementation plan with phased approach
- [ ] Comprehensive risk assessment with mitigation strategies
### Synthesis Analysis Quality Standards
- [ ] **Completeness**: Integrates all available role analyses without gaps
- [ ] **Visual Clarity**: Key diagrams (architecture, data model, user journey) included via Mermaid or images
- [ ] **Decision Transparency**: Documents not just decisions, but alternatives and why they were rejected
- [ ] **Insight Generation**: Identifies cross-role patterns and deep insights
- [ ] **Actionability**: Provides specific, executable recommendations and next steps
- [ ] **Balance**: Considers all role perspectives and addresses concerns
- [ ] **Actionability**: Provides specific, executable recommendations with rationale
- [ ] **Balance**: Considers all role perspectives, including process-oriented roles (Scrum Master)
- [ ] **Forward-Looking**: Includes long-term strategic and innovation considerations
### Output Validation Criteria
- [ ] **Priority-Based**: Recommendations prioritized using multi-dimensional evaluation
- [ ] **Resource-Aware**: Implementation plans consider resource and time constraints
- [ ] **Risk-Managed**: Comprehensive risk assessment with mitigation strategies
- [ ] **Context-Rich**: Each requirement includes rationale summary for immediate understanding
- [ ] **Resource-Aware**: Team skill gaps and constraints explicitly documented
- [ ] **Risk-Managed**: Both technical and process risks captured with mitigation strategies
- [ ] **Measurable Success**: Clear success metrics and monitoring frameworks
- [ ] **Clear Actions**: Specific next steps with assigned responsibilities and timelines
### Integration Excellence Standards
- [ ] **Cross-Role Synthesis**: Successfully identifies and resolves role perspective conflicts
- [ ] **Cross-Role Synthesis**: Successfully identifies and documents role perspective conflicts
- [ ] **No Role Marginalization**: Process, UX, and compliance concerns equally visible as functional requirements
- [ ] **Strategic Coherence**: Recommendations form coherent strategic direction
- [ ] **Implementation Readiness**: Plans are detailed enough for immediate execution
- [ ] **Implementation Readiness**: Plans detailed enough for immediate execution, with clear handoff to IMPL_PLAN.md
- [ ] **Stakeholder Alignment**: Addresses needs and concerns of all key stakeholders
- [ ] **Decision Traceability**: Every major decision traceable to source role analysis via @ references
- [ ] **Continuous Improvement**: Establishes framework for ongoing optimization and learning

View File

@@ -15,13 +15,23 @@ allowed-tools: SlashCommand(*), TodoWrite(*), Read(*), Bash(*)
## Coordinator Role
**This command is a pure orchestrator**: Execute 4 slash commands in sequence, parse their outputs, pass context between them, and ensure complete execution.
**This command is a pure orchestrator**: Execute 4 slash commands in sequence, parse their outputs, pass context between them, and ensure complete execution through **automatic continuation**.
**Execution Flow**:
1. Initialize TodoWrite → Execute Phase 1 → Parse output → Update TodoWrite
2. Execute Phase 2 with Phase 1 data → Parse output → Update TodoWrite
3. Execute Phase 3 with Phase 2 data → Parse output → Update TodoWrite
4. Execute Phase 4 with Phase 3 validation → Update TodoWrite → Return summary
**Execution Model - Auto-Continue Workflow**:
This workflow runs **fully autonomously** once triggered. Each phase completes, reports its output to you, then **immediately and automatically** proceeds to the next phase without requiring any user intervention.
1. **User triggers**: `/workflow:plan "task"`
2. **Phase 1 executes** → Reports output to user → Auto-continues
3. **Phase 2 executes** → Reports output to user → Auto-continues
4. **Phase 3 executes** → Reports output to user → Auto-continues
5. **Phase 4 executes** → Reports final summary
**Auto-Continue Mechanism**:
- TodoList tracks current phase status
- After each phase completion, automatically executes next pending phase
- **No user action required** - workflow runs end-to-end autonomously
- Progress updates shown at each phase for visibility
**Execution Modes**:
- **Manual Mode** (default): Use `/workflow:tools:task-generate`
@@ -32,9 +42,8 @@ allowed-tools: SlashCommand(*), TodoWrite(*), Read(*), Bash(*)
1. **Start Immediately**: First action is TodoWrite initialization, second action is Phase 1 command execution
2. **No Preliminary Analysis**: Do not read files, analyze structure, or gather context before Phase 1
3. **Parse Every Output**: Extract required data from each command's output for next phase
4. **Sequential Execution**: Each phase depends on previous phase's output
5. **Complete All Phases**: Do not return to user until Phase 4 completes
6. **Track Progress**: Update TodoWrite after every phase completion
4. **Auto-Continue via TodoList**: Check TodoList status to execute next pending phase automatically
5. **Track Progress**: Update TodoWrite after every phase completion
## 4-Phase Execution
@@ -64,6 +73,8 @@ CONTEXT: Existing user database schema, REST API endpoints
**TodoWrite**: Mark phase 1 completed, phase 2 in_progress
**After Phase 1**: Return to user showing Phase 1 results, then auto-continue to Phase 2
---
### Phase 2: Context Gathering
@@ -83,6 +94,8 @@ CONTEXT: Existing user database schema, REST API endpoints
**TodoWrite**: Mark phase 2 completed, phase 3 in_progress
**After Phase 2**: Return to user showing Phase 2 results, then auto-continue to Phase 3
---
### Phase 3: Intelligent Analysis
@@ -99,9 +112,18 @@ CONTEXT: Existing user database schema, REST API endpoints
**TodoWrite**: Mark phase 3 completed, phase 4 in_progress
**After Phase 3**: Return to user showing Phase 3 results, then auto-continue to Phase 4
---
### Phase 4: Task Generation
**Relationship with Brainstorm Phase**:
- If brainstorm synthesis exists (synthesis-specification.md), Phase 3 analysis incorporates it as input
- **synthesis-specification.md defines "WHAT"**: Requirements, design specs, high-level features
- **IMPL_PLAN.md defines "HOW"**: Executable task breakdown, dependencies, implementation sequence
- Task generation translates high-level specifications into concrete, actionable work items
**Command**:
- Manual: `SlashCommand(command="/workflow:tools:task-generate --session [sessionId]")`
- Agent: `SlashCommand(command="/workflow:tools:task-generate-agent --session [sessionId]")`
@@ -227,23 +249,23 @@ Return summary to user
- **Parsing Failure**: If output parsing fails, retry command once, then report error
- **Validation Failure**: If validation fails, report which file/data is missing
- **Command Failure**: Keep phase `in_progress`, report error to user, do not proceed
- **Command Failure**: Keep phase `in_progress`, report error to user, do not proceed to next phase
## Coordinator Checklist
✅ **Pre-Phase**: Convert user input to structured format (GOAL/SCOPE/CONTEXT)
✅ Initialize TodoWrite before any command
✅ Execute Phase 1 immediately with structured description
✅ Parse session ID from Phase 1 output
✅ Parse session ID from Phase 1 output, store in memory
✅ Pass session ID and structured description to Phase 2 command
✅ Parse context path from Phase 2 output
✅ Parse context path from Phase 2 output, store in memory
✅ Pass session ID and context path to Phase 3 command
✅ Verify ANALYSIS_RESULTS.md after Phase 3
✅ Select correct Phase 4 command based on --agent flag
✅ Pass session ID to Phase 4 command
✅ Verify all Phase 4 outputs
✅ Update TodoWrite after each phase
Return summary only after Phase 4 completes
After each phase, automatically continue to next phase based on TodoList status
## Structure Template Reference

View File

@@ -29,7 +29,7 @@ allowed-tools: SlashCommand(*), TodoWrite(*), Read(*), Bash(*)
5. **Complete All Phases**: Do not return until Phase 5 completes
6. **TDD Context**: All descriptions include "TDD:" prefix
## 5-Phase Execution
## 6-Phase Execution
### Phase 1: Session Discovery
**Command**: `/workflow:session:start --auto "TDD: [structured-description]"`
@@ -50,12 +50,36 @@ TEST_FOCUS: [Test scenarios]
**Parse**: Extract contextPath
### Phase 3: TDD Analysis
### Phase 3: Test Coverage Analysis
**Command**: `/workflow:tools:test-context-gather --session [sessionId]`
**Purpose**: Analyze existing codebase for:
- Existing test patterns and conventions
- Current test coverage
- Related components and integration points
- Test framework detection
**Parse**: Extract testContextPath (`.workflow/[sessionId]/.process/test-context-package.json`)
**Benefits**:
- Makes TDD aware of existing environment
- Identifies reusable test patterns
- Prevents duplicate test creation
- Enables integration with existing tests
### Phase 4: TDD Analysis
**Command**: `/workflow:tools:concept-enhanced --session [sessionId] --context [contextPath]`
**Parse**: Verify ANALYSIS_RESULTS.md
**Note**: Generates ANALYSIS_RESULTS.md with TDD-specific structure:
- Feature list with testable requirements
- Test cases for Red phase
- Implementation requirements for Green phase
- Refactoring opportunities
- Task dependencies and execution order
### Phase 4: TDD Task Generation
**Parse**: Verify ANALYSIS_RESULTS.md contains TDD breakdown sections
### Phase 5: TDD Task Generation
**Command**:
- Manual: `/workflow:tools:task-generate-tdd --session [sessionId]`
- Agent: `/workflow:tools:task-generate-tdd --session [sessionId] --agent`
@@ -63,12 +87,13 @@ TEST_FOCUS: [Test scenarios]
**Parse**: Extract feature count, chain count, task count
**Validate**:
- TDD_PLAN.md exists
- IMPL_PLAN.md exists
- IMPL_PLAN.md exists (unified plan with TDD Task Chains section)
- TEST-*.json, IMPL-*.json, REFACTOR-*.json exist
- TODO_LIST.md exists
- IMPL tasks include test-fix-cycle configuration
- IMPL_PLAN.md contains workflow_type: "tdd" in frontmatter
### Phase 5: TDD Structure Validation
### Phase 6: TDD Structure Validation
**Internal validation (no command)**
**Validate**:
@@ -76,6 +101,7 @@ TEST_FOCUS: [Test scenarios]
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
5. IMPL tasks contain test-fix-cycle in flow_control for iterative Green phase
**Return Summary**:
```
@@ -89,9 +115,9 @@ 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
Plan:
- Unified Implementation Plan: .workflow/[sessionId]/IMPL_PLAN.md
(includes TDD Task Chains section)
Next: /workflow:execute or /workflow:tdd-verify
```
@@ -99,13 +125,14 @@ Next: /workflow:execute or /workflow:tdd-verify
## TodoWrite Pattern
```javascript
// Initialize
// Initialize (6 phases now)
[
{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: "..."}
{content: "Execute session discovery", status: "in_progress", activeForm: "Executing session discovery"},
{content: "Execute context gathering", status: "pending", activeForm: "Executing context gathering"},
{content: "Execute test coverage analysis", status: "pending", activeForm: "Executing test coverage analysis"},
{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"}
]
// Update after each phase: mark current "completed", next "in_progress"
@@ -131,3 +158,96 @@ Convert user input to TDD-structured format:
- `/workflow:execute` - Execute TDD tasks
- `/workflow:tdd-verify` - Verify TDD compliance
- `/workflow:status` - View progress
## TDD Workflow Enhancements
### Overview
The TDD workflow has been significantly enhanced by integrating best practices from both traditional `plan --agent` and `test-gen` workflows, creating a hybrid approach that bridges the gap between idealized TDD and real-world development complexity.
### Key Improvements
#### 1. Test Coverage Analysis (Phase 3)
**Adopted from test-gen workflow**
Before planning TDD tasks, the workflow now analyzes the existing codebase:
- Detects existing test patterns and conventions
- Identifies current test coverage
- Discovers related components and integration points
- Detects test framework automatically
**Benefits**:
- Context-aware TDD planning
- Avoids duplicate test creation
- Enables integration with existing tests
- No longer assumes greenfield scenarios
#### 2. Iterative Green Phase with Test-Fix Cycle
**Adopted from test-gen workflow**
IMPL (Green phase) tasks now include automatic test-fix cycle for resilient implementation:
**Enhanced IMPL Task Flow**:
```
1. Write minimal implementation code
2. Execute test suite
3. IF tests pass → Complete task ✅
4. IF tests fail → Enter fix cycle:
a. Gemini diagnoses with bug-fix template
b. Apply fix (manual or Codex)
c. Retest
d. Repeat (max 3 iterations)
5. IF max iterations → Auto-revert changes 🔄
```
**Benefits**:
- ✅ Faster feedback within Green phase
- ✅ Autonomous recovery from implementation errors
- ✅ Systematic debugging with Gemini
- ✅ Safe rollback prevents broken state
#### 3. Agent-Driven Planning
**From plan --agent workflow**
Supports action-planning-agent for more autonomous TDD planning with:
- MCP tool integration (code-index, exa)
- Memory-first principles
- Brainstorming artifact integration
- Task merging over decomposition
### Workflow Comparison
| Aspect | Previous | Current |
|--------|----------|---------|
| **Phases** | 5 | 6 (test coverage analysis) |
| **Context** | Greenfield assumption | Existing codebase aware |
| **Green Phase** | Single implementation | Iterative with fix cycle |
| **Failure Handling** | Manual intervention | Auto-diagnose + fix + revert |
| **Test Analysis** | None | Deep coverage analysis |
| **Feedback Loop** | Post-execution | During Green phase |
### Migration Notes
**Backward Compatibility**: ✅ Fully compatible
- Existing TDD workflows continue to work
- New features are additive, not breaking
- Phase 3 can be skipped if test-context-gather not available
**Session Structure**:
```
.workflow/WFS-xxx/
├── IMPL_PLAN.md (unified plan with TDD Task Chains section)
├── TODO_LIST.md
├── .process/
│ ├── context-package.json
│ ├── test-context-package.json
│ ├── ANALYSIS_RESULTS.md (enhanced with TDD breakdown)
│ └── green-fix-iteration-*.md (fix logs)
└── .task/
├── TEST-*.json (Red phase)
├── IMPL-*.json (Green phase with test-fix-cycle)
└── REFACTOR-*.json (Refactor phase)
```
**Configuration Options** (in IMPL tasks):
- `meta.max_iterations`: Fix attempts (default: 3)
- `meta.use_codex`: Auto-fix mode (default: false)

View File

@@ -1,11 +1,11 @@
---
name: test-gen
description: Create independent test-fix workflow session by analyzing completed implementation
usage: /workflow:test-gen <source-session-id>
argument-hint: "<source-session-id>"
usage: /workflow:test-gen [--use-codex] <source-session-id>
argument-hint: "[--use-codex] <source-session-id>"
examples:
- /workflow:test-gen WFS-user-auth
- /workflow:test-gen WFS-api-refactor
- /workflow:test-gen --use-codex WFS-api-refactor
allowed-tools: SlashCommand(*), TodoWrite(*), Read(*), Bash(*)
---
@@ -20,6 +20,7 @@ allowed-tools: SlashCommand(*), TodoWrite(*), Read(*), Bash(*)
- **Context-First**: Prioritizes gathering code changes and summaries from source session
- **Format Reuse**: Creates standard `IMPL-*.json` task, using `meta.type: "test-fix"` for agent assignment
- **Parameter Simplification**: Tools auto-detect test session type via metadata, no manual cross-session parameters needed
- **Manual First**: Default to manual fixes, use `--use-codex` flag for automated Codex fix application
**Execution Flow**:
1. Initialize TodoWrite → Create test session → Parse session ID
@@ -36,8 +37,9 @@ allowed-tools: SlashCommand(*), TodoWrite(*), Read(*), Bash(*)
5. **Complete All Phases**: Do not return to user until Phase 4 completes (execution triggered separately)
6. **Track Progress**: Update TodoWrite after every phase completion
7. **Automatic Detection**: context-gather auto-detects test session and gathers source session context
8. **Parse --use-codex Flag**: Extract flag from arguments and pass to Phase 4 (test-task-generate)
## 4-Phase Execution
## 5-Phase Execution
### Phase 1: Create Test Session
**Command**: `SlashCommand(command="/workflow:session:start --new \"Test validation for [sourceSessionId]\"")`
@@ -65,107 +67,117 @@ allowed-tools: SlashCommand(*), TodoWrite(*), Read(*), Bash(*)
---
### Phase 2: Gather Cross-Session Context
**Command**: `SlashCommand(command="/workflow:tools:context-gather --session [testSessionId]")`
### Phase 2: Gather Test Context
**Command**: `SlashCommand(command="/workflow:tools:test-context-gather --session [testSessionId]")`
**Input**: `testSessionId` from Phase 1 (e.g., `WFS-test-user-auth`)
**Automatic Detection**:
- context-gather reads `.workflow/[testSessionId]/workflow-session.json`
- Detects `workflow_type: "test_session"`
- Automatically uses `source_session_id` to gather source session context
- No need for manual `--source-session` parameter
**Cross-Session Context Collection** (Automatic):
- Implementation summaries: `.workflow/[sourceSessionId]/.summaries/IMPL-*-summary.md`
- Code changes: `git log --since=[source_session_created_at]` for changed files
- Original plan: `.workflow/[sourceSessionId]/IMPL_PLAN.md`
- Test files: Discovered via MCP code-index tools
**Expected Behavior**:
- Load source session implementation context and summaries
- Analyze test coverage using MCP tools (find existing tests)
- Identify files requiring tests (coverage gaps)
- Detect test framework and conventions
- Generate `test-context-package.json`
**Parse Output**:
- Extract: context package path (store as `contextPath`)
- Pattern: `.workflow/[testSessionId]/.process/context-package.json`
- Extract: test context package path (store as `testContextPath`)
- Pattern: `.workflow/[testSessionId]/.process/test-context-package.json`
**Validation**:
- Context package created in test session directory
- Contains source session artifacts (summaries, changed files)
- Includes test file inventory
- Test context package created
- Contains source session summaries
- Includes coverage gap analysis
- Test framework detected
- Test conventions documented
**TodoWrite**: Mark phase 2 completed, phase 3 in_progress
---
### Phase 3: Implementation Analysis
**Command**: `SlashCommand(command="/workflow:tools:concept-enhanced --session [testSessionId] --context [contextPath]")`
### Phase 3: Test Generation Analysis
**Command**: `SlashCommand(command="/workflow:tools:test-concept-enhanced --session [testSessionId] --context [testContextPath]")`
**Input**:
- `testSessionId` from Phase 1 (e.g., `WFS-test-user-auth`)
- `contextPath` from Phase 2 (e.g., `.workflow/WFS-test-user-auth/.process/context-package.json`)
**Analysis Focus**:
- Review implementation summaries from source session
- Identify test files and coverage gaps
- Assess test execution strategy (unit, integration, e2e)
- Determine failure diagnosis approach
- Recommend code quality improvements
- `testSessionId` from Phase 1
- `testContextPath` from Phase 2
**Expected Behavior**:
- Reads context-package.json with cross-session artifacts
- Executes parallel analysis (Gemini for test strategy, optional Codex for validation)
- Generates comprehensive test execution strategy
- Identifies code modification targets for test fixes
- Provides feasibility assessment for test validation
- Use Gemini to analyze coverage gaps and implementation context
- Study existing test patterns and conventions
- Generate test requirements for each missing test file
- Design test generation strategy
- Generate `TEST_ANALYSIS_RESULTS.md`
**Parse Output**:
- Verify `.workflow/[testSessionId]/.process/ANALYSIS_RESULTS.md` created
- Contains test strategy and execution plan
- Lists code modification targets (format: `file:function:lines` or `file`)
- Includes risk assessment and optimization recommendations
- Verify `.workflow/[testSessionId]/.process/TEST_ANALYSIS_RESULTS.md` created
- Contains test requirements and generation strategy
- Lists test files to create with specifications
**Validation**:
- File `.workflow/[testSessionId]/.process/ANALYSIS_RESULTS.md` exists
- Contains complete analysis sections:
- Current State Analysis (test coverage, existing tests)
- Proposed Solution Design (test execution strategy)
- Implementation Strategy (code targets, feasibility)
- Solution Optimization (performance, quality)
- Critical Success Factors (acceptance criteria)
- TEST_ANALYSIS_RESULTS.md exists with complete sections:
- Coverage Assessment
- Test Framework & Conventions
- Test Requirements by File
- Test Generation Strategy
- Implementation Targets (test files to create)
- Success Criteria
**TodoWrite**: Mark phase 3 completed, phase 4 in_progress
---
### Phase 4: Generate Test Task
**Command**: `SlashCommand(command="/workflow:tools:task-generate --session [testSessionId]")`
### Phase 4: Generate Test Tasks
**Command**: `SlashCommand(command="/workflow:tools:test-task-generate [--use-codex] --session [testSessionId]")`
**Input**: `testSessionId` from Phase 1
**Input**:
- `testSessionId` from Phase 1
- `--use-codex` flag (if present in original command)
**Expected Behavior**:
- Reads ANALYSIS_RESULTS.md from Phase 3
- Extracts test strategy and code modification targets
- Generates `IMPL-001.json` (reusing standard format) with:
- `meta.type: "test-fix"` (enables @test-fix-agent assignment)
- `meta.agent: "@test-fix-agent"`
- `context.requirements`: Test execution requirements from analysis
- `context.focus_paths`: Test files and source files from analysis
- `context.acceptance`: All tests pass criteria
- `flow_control.pre_analysis`: Load source session summaries
- `flow_control.implementation_approach`: Test execution strategy from ANALYSIS_RESULTS.md
- `flow_control.target_files`: Code modification targets from analysis
- Parse TEST_ANALYSIS_RESULTS.md from Phase 3
- Extract test requirements and generation strategy
- Generate **TWO task JSON files**:
- **IMPL-001.json**: Test Generation task (calls @code-developer)
- **IMPL-002.json**: Test Execution and Fix Cycle task (calls @test-fix-agent)
- Generate IMPL_PLAN.md with test generation and execution strategy
- Generate TODO_LIST.md with both tasks
**Parse Output**:
- Verify `.workflow/[testSessionId]/.task/IMPL-001.json` exists
- Verify `.workflow/[testSessionId]/.task/IMPL-001.json` exists (test generation)
- Verify `.workflow/[testSessionId]/.task/IMPL-002.json` exists (test execution & fix)
- Verify `.workflow/[testSessionId]/IMPL_PLAN.md` created
- Verify `.workflow/[testSessionId]/TODO_LIST.md` created
**Validation**:
- Task JSON has `id: "IMPL-001"` and `meta.type: "test-fix"`
- IMPL_PLAN.md contains test validation strategy from ANALYSIS_RESULTS.md
- TODO_LIST.md shows IMPL-001 task
- flow_control includes code targets and test strategy
- Task is ready for /workflow:execute
**Validation - IMPL-001.json (Test Generation)**:
- Task ID: `IMPL-001`
- `meta.type: "test-gen"`
- `meta.agent: "@code-developer"`
- `context.requirements`: Generate tests based on TEST_ANALYSIS_RESULTS.md
- `flow_control.pre_analysis`: Load TEST_ANALYSIS_RESULTS.md and test context
- `flow_control.implementation_approach`: Test generation steps
- `flow_control.target_files`: Test files to create from analysis section 5
**TodoWrite**: Mark phase 4 completed
**Validation - IMPL-002.json (Test Execution & Fix)**:
- Task ID: `IMPL-002`
- `meta.type: "test-fix"`
- `meta.agent: "@test-fix-agent"`
- `meta.use_codex: true|false` (based on --use-codex flag)
- `context.depends_on: ["IMPL-001"]`
- `context.requirements`: Execute and fix tests
- `flow_control.implementation_approach.test_fix_cycle`: Complete cycle specification
- **Cycle pattern**: test → gemini_diagnose → manual_fix (or codex if --use-codex) → retest
- **Tools configuration**: Gemini for analysis with bug-fix template, manual or Codex for fixes
- **Exit conditions**: Success (all pass) or failure (max iterations)
- `flow_control.implementation_approach.modification_points`: 3-phase execution flow
- Phase 1: Initial test execution
- Phase 2: Iterative Gemini diagnosis + manual/Codex fixes (based on flag)
- Phase 3: Final validation and certification
**TodoWrite**: Mark phase 4 completed, phase 5 in_progress
---
### Phase 5: Return Summary to User
**Return to User**:
```
@@ -173,315 +185,120 @@ Independent test-fix workflow created successfully!
Source Session: [sourceSessionId]
Test Session: [testSessionId]
Task Created: IMPL-001 (test-fix)
Tasks Created:
- IMPL-001: Test Generation (@code-developer)
- IMPL-002: Test Execution & Fix Cycle (@test-fix-agent)
Test Framework: [detected framework]
Test Files to Generate: [count]
Max Fix Iterations: 5
Fix Mode: [Manual|Codex Automated] (based on --use-codex flag)
Next Steps:
1. Review test plan: .workflow/[testSessionId]/IMPL_PLAN.md
2. Execute validation: /workflow:execute
2. Execute workflow: /workflow:execute
3. Monitor progress: /workflow:status
The @test-fix-agent will:
- Execute all tests
- Diagnose any failures
- Fix code until tests pass
```
**TodoWrite**: Mark phase 5 completed
---
## TodoWrite Pattern
Track progress through 5 phases:
```javascript
// Initialize (before Phase 1)
TodoWrite({todos: [
{"content": "Create independent test session", "status": "in_progress", "activeForm": "Creating test session"},
{"content": "Gather cross-session context", "status": "pending", "activeForm": "Gathering cross-session context"},
{"content": "Analyze implementation for test strategy", "status": "pending", "activeForm": "Analyzing implementation"},
{"content": "Generate test validation task", "status": "pending", "activeForm": "Generating test validation task"}
]})
// After Phase 1
TodoWrite({todos: [
{"content": "Create independent test session", "status": "completed", "activeForm": "Creating test session"},
{"content": "Gather cross-session context", "status": "in_progress", "activeForm": "Gathering cross-session context"},
{"content": "Analyze implementation for test strategy", "status": "pending", "activeForm": "Analyzing implementation"},
{"content": "Generate test validation task", "status": "pending", "activeForm": "Generating test validation task"}
]})
// After Phase 2
TodoWrite({todos: [
{"content": "Create independent test session", "status": "completed", "activeForm": "Creating test session"},
{"content": "Gather cross-session context", "status": "completed", "activeForm": "Gathering cross-session context"},
{"content": "Analyze implementation for test strategy", "status": "in_progress", "activeForm": "Analyzing implementation"},
{"content": "Generate test validation task", "status": "pending", "activeForm": "Generating test validation task"}
]})
// After Phase 3
TodoWrite({todos: [
{"content": "Create independent test session", "status": "completed", "activeForm": "Creating test session"},
{"content": "Gather cross-session context", "status": "completed", "activeForm": "Gathering cross-session context"},
{"content": "Analyze implementation for test strategy", "status": "completed", "activeForm": "Analyzing implementation"},
{"content": "Generate test validation task", "status": "in_progress", "activeForm": "Generating test validation task"}
]})
// After Phase 4
TodoWrite({todos: [
{"content": "Create independent test session", "status": "completed", "activeForm": "Creating test session"},
{"content": "Gather cross-session context", "status": "completed", "activeForm": "Gathering cross-session context"},
{"content": "Analyze implementation for test strategy", "status": "completed", "activeForm": "Analyzing implementation"},
{"content": "Generate test validation task", "status": "completed", "activeForm": "Generating test validation task"}
{"content": "Create independent test session", "status": "in_progress|completed", "activeForm": "Creating test session"},
{"content": "Gather test coverage context", "status": "pending|in_progress|completed", "activeForm": "Gathering test coverage context"},
{"content": "Analyze test requirements with Gemini", "status": "pending|in_progress|completed", "activeForm": "Analyzing test requirements"},
{"content": "Generate test generation and execution tasks", "status": "pending|in_progress|completed", "activeForm": "Generating test tasks"},
{"content": "Return workflow summary", "status": "pending|in_progress|completed", "activeForm": "Returning workflow summary"}
]})
```
Update status to `in_progress` when starting each phase, mark `completed` when done.
## Data Flow
```
User: /workflow:test-gen WFS-user-auth
Phase 1: session-start --new "Test validation for WFS-user-auth"
Creates: WFS-test-user-auth session
↓ Writes: workflow-session.json with workflow_type="test_session", source_session_id="WFS-user-auth"
Output: testSessionId = "WFS-test-user-auth"
Phase 2: context-gather --session WFS-test-user-auth
↓ Auto-detects: test session type from workflow-session.json
Auto-reads: source_session_id = "WFS-user-auth"
↓ Gathers: Cross-session context (summaries, code changes, tests)
Output: .workflow/WFS-test-user-auth/.process/context-package.json
Phase 3: concept-enhanced --session WFS-test-user-auth --context context-package.json
↓ Reads: context-package.json with cross-session artifacts
↓ Executes: Parallel analysis (Gemini test strategy + optional Codex validation)
↓ Analyzes: Test coverage, execution strategy, code targets
↓ Output: .workflow/WFS-test-user-auth/.process/ANALYSIS_RESULTS.md
Phase 4: task-generate --session WFS-test-user-auth
↓ Reads: ANALYSIS_RESULTS.md with test strategy and code targets
↓ Generates: IMPL-001.json with meta.type="test-fix"
↓ Output: Task, plan, and todo files in test session
Return: Summary with next steps (user triggers /workflow:execute separately)
/workflow:test-gen WFS-user-auth
Phase 1: session-start → WFS-test-user-auth
Phase 2: test-context-gather → test-context-package.json
Phase 3: test-concept-enhanced → TEST_ANALYSIS_RESULTS.md
Phase 4: test-task-generate → IMPL-001.json + IMPL-002.json
Phase 5: Return summary
/workflow:execute → IMPL-001 (@code-developer) → IMPL-002 (@test-fix-agent)
```
## Session Metadata Design
## Session Metadata
**Test Session (`WFS-test-user-auth/workflow-session.json`)**:
```json
{
"session_id": "WFS-test-user-auth",
"project": "Test validation for user authentication implementation",
"status": "planning",
"created_at": "2025-10-03T12:00:00Z",
"workflow_type": "test_session",
"source_session_id": "WFS-user-auth"
}
```
Test session includes `workflow_type: "test_session"` and `source_session_id` for automatic context gathering.
## Automatic Cross-Session Context Collection
## Task Output
When `context-gather` detects `workflow_type: "test_session"`:
Generates two tasks:
- **IMPL-001** (@code-developer): Test generation from TEST_ANALYSIS_RESULTS.md
- **IMPL-002** (@test-fix-agent): Test execution with iterative fix cycle (max 5 iterations)
**Collected from Source Session** (`.workflow/WFS-user-auth/`):
- Implementation summaries: `.summaries/IMPL-*-summary.md`
- Code changes: `git log --since=[source_created_at] --name-only`
- Original plan: `IMPL_PLAN.md`
- Task definitions: `.task/IMPL-*.json`
**Collected from Current Project**:
- Test files: `mcp__code-index__find_files(pattern="*.test.*")`
- Test configuration: `package.json`, `jest.config.js`, etc.
- Source files: Based on changed files from git log
## Task Generation Output
task-generate creates `IMPL-001.json` (reusing standard format) with:
```json
{
"id": "IMPL-001",
"title": "Execute and validate tests for [sourceSessionId]",
"status": "pending",
"meta": {
"type": "test-fix",
"agent": "@test-fix-agent"
},
"context": {
"requirements": [
"Execute complete test suite for all implemented modules",
"Diagnose and fix any test failures",
"Ensure all tests pass before completion"
],
"focus_paths": ["src/**/*.test.ts", "src/**/implementation.ts"],
"acceptance": [
"All tests pass successfully",
"No test failures or errors",
"Code is approved and ready for deployment"
],
"depends_on": [],
"artifacts": []
},
"flow_control": {
"pre_analysis": [
{
"step": "load_source_session_summaries",
"action": "Load implementation summaries from source session",
"commands": [
"bash(find .workflow/[sourceSessionId]/.summaries/ -name 'IMPL-*-summary.md' 2>/dev/null)",
"Read(.workflow/[sourceSessionId]/.summaries/IMPL-001-summary.md)"
],
"output_to": "implementation_context",
"on_error": "skip_optional"
},
{
"step": "analyze_test_files",
"action": "Identify test files and coverage",
"commands": [
"mcp__code-index__find_files(pattern=\"*.test.*\")",
"mcp__code-index__search_code_advanced(pattern=\"test|describe|it\", file_pattern=\"*.test.*\")"
],
"output_to": "test_inventory",
"on_error": "fail"
}
],
"implementation_approach": {
"task_description": "Execute tests and fix failures until all pass",
"modification_points": [
"Run test suite using detected framework",
"Parse test output to identify failures",
"Diagnose root cause of failures",
"Modify source code to fix issues",
"Re-run tests to verify fixes"
],
"logic_flow": [
"Load implementation context",
"Identify test framework and configuration",
"Execute complete test suite",
"If failures: analyze error messages",
"Fix source code based on diagnosis",
"Re-run tests",
"Repeat until all tests pass"
]
},
"target_files": ["src/**/*.test.ts", "src/**/implementation.ts"]
}
}
```
See `/workflow:tools:test-task-generate` for complete task JSON schemas.
## Error Handling
### Phase 1 Failures
- **Source session not found**: Return error "Source session [sourceSessionId] not found in .workflow/"
- **Invalid source session**: Return error "Source session [sourceSessionId] has no completed IMPL tasks"
- **Session creation failed**: Return error "Could not create test session. Check /workflow:session:start"
| Phase | Error | Action |
|-------|-------|--------|
| 1 | Source session not found | Return error with source session ID |
| 1 | No completed IMPL tasks | Return error, source incomplete |
| 2 | Context gathering failed | Return error, check source artifacts |
| 3 | Analysis failed | Return error, check context package |
| 4 | Task generation failed | Retry once, then error with details |
### Phase 2 Failures
- **Context gathering failed**: Return error "Could not gather cross-session context. Check source session artifacts"
- **No source artifacts**: Return error "Source session has no implementation summaries or git history"
## Output Files
### Phase 3 Failures
- **Analysis failed**: Return error "Implementation analysis failed. Check context package and ANALYSIS_RESULTS.md"
- **No test strategy**: Return error "Could not determine test execution strategy from analysis"
- **Missing code targets**: Warning only, proceed with general test task
### Phase 4 Failures
- **Task generation failed**: Retry once, then return error with details
- **Invalid task structure**: Return error with JSON validation details
## Workflow Integration
### Complete Flow Example
```
1. Implementation Phase (prior to test-gen)
/workflow:plan "Build auth system"
→ Creates WFS-auth session
→ @code-developer implements + writes tests
→ Creates IMPL-001-summary.md in WFS-auth
2. Test Generation Phase (test-gen)
/workflow:test-gen WFS-auth
Phase 1: session-start → Creates WFS-test-auth session
Phase 2: context-gather → Gathers from WFS-auth, creates context-package.json
Phase 3: concept-enhanced → Analyzes implementation, creates ANALYSIS_RESULTS.md
Phase 4: task-generate → Creates IMPL-001.json with meta.type="test-fix"
Returns: Summary with next steps
3. Test Execution Phase (user-triggered)
/workflow:execute
→ Detects active session: WFS-test-auth
→ @test-fix-agent picks up IMPL-001 (test-fix type)
→ Runs test suite
→ Diagnoses failures (if any)
→ Fixes source code
→ Re-runs tests
→ All pass → Code approved ✅
```
### Output Files Created
**In Test Session** (`.workflow/WFS-test-auth/`):
- `workflow-session.json` - Contains workflow_type and source_session_id
- `.process/context-package.json` - Cross-session context from WFS-auth
- `.process/ANALYSIS_RESULTS.md` - Test strategy and code targets from concept-enhanced
- `.task/IMPL-001.json` - Test-fix task definition
- `IMPL_PLAN.md` - Test validation plan (from ANALYSIS_RESULTS.md)
Created in `.workflow/WFS-test-[session]/`:
- `workflow-session.json` - Session metadata
- `.process/test-context-package.json` - Coverage analysis
- `.process/TEST_ANALYSIS_RESULTS.md` - Test requirements
- `.task/IMPL-001.json` - Test generation task
- `.task/IMPL-002.json` - Test execution & fix task
- `IMPL_PLAN.md` - Test plan
- `TODO_LIST.md` - Task checklist
- `.summaries/IMPL-001-summary.md` - Created by @test-fix-agent after completion
## Agent Execution
**IMPL-001** (@code-developer):
- Generates test files based on TEST_ANALYSIS_RESULTS.md
- Follows existing test patterns and conventions
**IMPL-002** (@test-fix-agent):
1. Run test suite
2. Iterative fix cycle (max 5):
- Gemini diagnosis with bug-fix template → surgical fix suggestions
- Manual fix application (default) OR Codex applies fixes if --use-codex flag (resume mechanism)
- Retest and check regressions
3. Final validation and certification
See `/workflow:tools:test-task-generate` for detailed specifications.
## Best Practices
1. **Run after implementation complete**: Ensure source session has completed IMPL tasks and summaries
2. **Check git commits**: Implementation changes should be committed for accurate git log analysis
3. **Verify test files exist**: Source implementation should include test files
4. **Independent sessions**: Test session is separate from implementation session for clean separation
5. **Monitor execution**: Use `/workflow:status` to track test-fix progress after /workflow:execute
## Coordinator Checklist
✅ Initialize TodoWrite before any command (4 phases)
✅ Phase 1: Create test session with source session ID
✅ Parse new test session ID from Phase 1 output
✅ Phase 2: Run context-gather (auto-detects test session, no extra params)
✅ Verify context-package.json contains cross-session artifacts
✅ Phase 3: Run concept-enhanced with session and context path
✅ Verify ANALYSIS_RESULTS.md contains test strategy and code targets
✅ Phase 4: Run task-generate to create IMPL-001.json
✅ Verify task has meta.type="test-fix" and meta.agent="@test-fix-agent"
✅ Verify flow_control includes analysis insights and code targets
✅ Update TodoWrite after each phase
✅ Return summary after Phase 4 (execution is separate user action)
## Required Tool Modifications
### `/workflow:session:start`
- Support `--new` flag for test session creation
- Auto-detect test session pattern from task description
- Write `workflow_type: "test_session"` and `source_session_id` to metadata
### `/workflow:tools:context-gather`
- Read session metadata to detect `workflow_type: "test_session"`
- Auto-extract `source_session_id` from metadata
- Gather cross-session context from source session artifacts
- Include git log analysis from source session creation time
### `/workflow:tools:concept-enhanced`
- No changes required (already supports cross-session context analysis)
- Will automatically analyze test strategy based on context-package.json
- Generates ANALYSIS_RESULTS.md with code targets and test execution plan
### `/workflow:tools:task-generate`
- Recognize test session context and generate appropriate task
- Create `IMPL-001.json` with `meta.type: "test-fix"`
- Extract test strategy from ANALYSIS_RESULTS.md
- Include code targets and cross-session references in flow_control
### `/workflow:execute`
- No changes required (already dispatches by meta.agent)
1. Run after implementation complete (ensure source session has summaries)
2. Commit implementation changes before test-gen
3. Monitor execution with `/workflow:status`
4. Review iteration logs in `.process/fix-iteration-*`
## Related Commands
- `/workflow:plan` - Create implementation workflow (run before test-gen)
- `/workflow:session:start` - Phase 1 tool for test session creation
- `/workflow:tools:context-gather` - Phase 2 tool for cross-session context collection
- `/workflow:tools:concept-enhanced` - Phase 3 tool for implementation analysis and test strategy
- `/workflow:tools:task-generate` - Phase 4 tool for test task creation
- `/workflow:execute` - Execute test-fix workflow (user-triggered after test-gen)
- `/workflow:status` - Check workflow progress
- `@test-fix-agent` - Agent that executes and fixes tests
- `/workflow:tools:test-context-gather` - Phase 2 (coverage analysis)
- `/workflow:tools:test-concept-enhanced` - Phase 3 (Gemini test analysis)
- `/workflow:tools:test-task-generate` - Phase 4 (task generation)
- `/workflow:execute` - Execute workflow
- `/workflow:status` - Check progress

View File

@@ -130,6 +130,15 @@ Advanced solution design and feasibility analysis engine with parallel CLI execu
- Tech stack from tech_stack section
- Project structure from statistics section
**ANALYSIS PRIORITY - Use ALL source documents from context-package assets[]**:
1. PRIMARY SOURCES (Highest Priority): Individual role analysis.md files (system-architect, ui-designer, product-manager, etc.)
- These contain complete technical details, design rationale, ADRs, and decision context
- Extract: Technical specs, API schemas, design tokens, caching configs, performance metrics
2. SYNTHESIS REFERENCE (Medium Priority): synthesis-specification.md
- Use for integrated requirements and cross-role alignment
- Validate decisions and identify integration points
3. TOPIC FRAMEWORK (Low Priority): topic-framework.md for discussion context
EXPECTED:
1. CURRENT STATE ANALYSIS: Existing patterns, code structure, integration points, technical debt
2. SOLUTION DESIGN: Core architecture principles, system design, key design decisions with rationale

View File

@@ -169,7 +169,21 @@ Task(
{
"type": "synthesis_specification",
"path": "{synthesis_spec_path}",
"priority": "highest"
"priority": "highest",
"usage": "Primary requirement source - use for consolidated requirements and cross-role alignment"
},
{
"type": "role_analysis",
"path": "{role_analysis_path}",
"priority": "high",
"usage": "Technical/design/business details from specific roles. Common roles: system-architect (ADRs, APIs, caching), ui-designer (design tokens, layouts), product-manager (user stories, metrics)",
"note": "Dynamically discovered - multiple role analysis files included based on brainstorming results"
},
{
"type": "topic_framework",
"path": "{topic_framework_path}",
"priority": "low",
"usage": "Discussion context and framework structure"
}
]
},
@@ -203,12 +217,13 @@ Task(
}
],
"implementation_approach": {
"task_description": "Implement '[title]' following synthesis specification",
"task_description": "Implement '[title]' following synthesis specification. PRIORITY: Use synthesis-specification.md as primary requirement source. When implementation needs technical details (e.g., API schemas, caching configs, design tokens), refer to artifacts[] for detailed specifications from original role analyses.",
"modification_points": ["Apply requirements from synthesis"],
"logic_flow": [
"Load synthesis specification",
"Analyze existing patterns",
"Implement following specification",
"Consult artifacts for technical details when needed",
"Validate against acceptance criteria"
]
},

View File

@@ -20,6 +20,9 @@ Generate TDD-specific task chains from analysis results with enforced Red-Green-
- **Phase-Explicit**: Each task marked with Red/Green/Refactor phase
- **Artifact-Aware**: Integrates brainstorming outputs
- **Memory-First**: Reuse loaded documents from memory
- **Context-Aware**: Analyzes existing codebase and test patterns
- **Iterative Green Phase**: Auto-diagnose and fix test failures with Gemini + optional Codex
- **Safety-First**: Auto-revert on max iterations to prevent broken state
## Core Responsibilities
- Parse analysis results and identify testable features
@@ -47,32 +50,18 @@ Generate TDD-specific task chains from analysis results with enforced Red-Green-
- Else: Scan `.workflow/{session_id}/.brainstorming/` directory
- Detect: synthesis-specification.md, topic-framework.md, role analyses
### Phase 2: TDD Task Analysis
### Phase 2: TDD Task JSON Generation
#### 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
**Input**: Use `.process/ANALYSIS_RESULTS.md` directly (enhanced with TDD structure from concept-enhanced phase)
**Note**: The ANALYSIS_RESULTS.md now includes TDD-specific breakdown:
- Feature list with testable requirements
- Test cases for Red phase
- Implementation requirements for Green phase
- Refactoring opportunities
- 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
### Phase 3: Enhanced IMPL_PLAN.md Generation
#### Task Chain Structure
For each feature, generate 3 tasks with ID format:
@@ -145,19 +134,23 @@ For each feature, generate 3 tasks with ID format:
"meta": {
"type": "feature",
"agent": "@code-developer",
"tdd_phase": "green"
"tdd_phase": "green",
"max_iterations": 3,
"use_codex": false
},
"context": {
"requirements": [
"Implement minimal AuthService to pass TEST-1.1",
"Handle valid and invalid credentials",
"Return appropriate success/error responses"
"Return appropriate success/error responses",
"If tests fail after implementation, diagnose and fix iteratively"
],
"focus_paths": ["src/auth/AuthService.ts", "tests/auth/login.test.ts"],
"acceptance": [
"All tests in TEST-1.1 pass",
"Implementation is minimal and focused",
"No over-engineering or premature optimization"
"No over-engineering or premature optimization",
"Test failures resolved within iteration limit"
],
"depends_on": ["TEST-1.1"]
},
@@ -172,21 +165,83 @@ For each feature, generate 3 tasks with ID format:
},
{
"step": "verify_tests_failing",
"action": "Confirm tests are currently failing",
"action": "Confirm tests are currently failing (Red phase validation)",
"command": "bash(npm test -- tests/auth/login.test.ts || echo 'Tests failing as expected')",
"output_to": "initial_test_status",
"on_error": "warn"
},
{
"step": "load_test_context",
"action": "Load test patterns and framework info",
"command": "bash(cat .workflow/WFS-xxx/.process/test-context-package.json 2>/dev/null || echo '{}')",
"output_to": "test_context",
"on_error": "skip_optional"
}
],
"implementation_approach": {
"task_description": "Write minimal code to pass tests, then enter iterative fix cycle if they still fail",
"initial_implementation": [
"Write minimal code based on test requirements",
"Execute test suite: bash(npm test -- tests/auth/login.test.ts)",
"If tests pass → Complete task",
"If tests fail → Capture failure logs and proceed to test-fix cycle"
],
"test_fix_cycle": {
"max_iterations": 3,
"cycle_pattern": "gemini_diagnose → manual_fix (or codex if meta.use_codex=true) → retest",
"tools": {
"diagnosis": "gemini-wrapper (MODE: analysis, uses bug-fix template)",
"fix_application": "manual (default) or codex if meta.use_codex=true",
"verification": "bash(npm test -- tests/auth/login.test.ts)"
},
"exit_conditions": {
"success": "all_tests_pass",
"failure": "max_iterations_reached"
},
"steps": [
"ITERATION LOOP (max 3):",
" 1. Gemini Diagnosis:",
" bash(cd .workflow/WFS-xxx/.process && ~/.claude/scripts/gemini-wrapper --all-files -p \"",
" PURPOSE: Diagnose TDD Green phase test failure iteration [N]",
" TASK: Systematic bug analysis and fix recommendations",
" MODE: analysis",
" CONTEXT: @{CLAUDE.md,**/*CLAUDE.md}",
" Test output: [test_failures]",
" Test requirements: [test_requirements]",
" Implementation: [focus_paths]",
" EXPECTED: Root cause analysis, code path tracing, targeted fixes",
" RULES: $(cat ~/.claude/prompt-templates/bug-fix.md) | Bug: [test_failure_description]",
" Minimal surgical fixes only - stay in Green phase",
" \" > green-fix-iteration-[N]-diagnosis.md)",
" 2. Apply Fix (check meta.use_codex):",
" IF meta.use_codex=false (default): Present diagnosis to user for manual fix",
" IF meta.use_codex=true: Codex applies fix automatically",
" 3. Retest: bash(npm test -- tests/auth/login.test.ts)",
" 4. If pass → Exit loop, complete task",
" If fail → Continue to next iteration",
"IF max_iterations reached: Revert changes, report failure"
]
}
},
"post_completion": [
{
"step": "verify_tests_passing",
"action": "Confirm all tests now pass",
"action": "Confirm all tests now pass (Green phase achieved)",
"command": "bash(npm test -- tests/auth/login.test.ts)",
"output_to": "final_test_status",
"on_error": "fail"
}
]
],
"error_handling": {
"max_iterations_reached": {
"action": "revert_all_changes",
"commands": [
"bash(git reset --hard HEAD)",
"bash(echo 'TDD Green phase failed: Unable to pass tests within 3 iterations' > .workflow/WFS-xxx/.process/green-phase-failure.md)"
],
"report": "Generate failure report in .summaries/IMPL-1.1-failure-report.md"
}
}
}
}
```
@@ -248,19 +303,31 @@ For each feature, generate 3 tasks with ID format:
}
```
### Phase 4: TDD_PLAN.md Generation
### Phase 4: Unified IMPL_PLAN.md Generation
Generate TDD-specific plan with:
- Feature breakdown
- Red-Green-Refactor chains
- Execution order
- TDD compliance checkpoints
Generate single comprehensive IMPL_PLAN.md with:
### Phase 5: Enhanced IMPL_PLAN.md Generation
**Frontmatter**:
```yaml
---
identifier: WFS-{session-id}
workflow_type: "tdd"
feature_count: N
task_count: 3N
tdd_chains: N
---
```
Generate standard IMPL_PLAN.md with TDD context reference.
**Structure**:
1. **Summary**: Project overview
2. **TDD Task Chains** (TDD-specific section):
- Visual representation of TEST → IMPL → REFACTOR chains
- Feature-by-feature breakdown with phase indicators
3. **Task Breakdown**: Standard task listing
4. **Implementation Strategy**: Execution approach
5. **Success Criteria**: Acceptance conditions
### Phase 6: TODO_LIST.md Generation
### Phase 5: TODO_LIST.md Generation
Generate task list with TDD phase indicators:
```markdown
@@ -270,7 +337,7 @@ Generate task list with TDD phase indicators:
- [ ] **REFACTOR-1.1**: Refactor implementation (🔵 REFACTOR) [depends: IMPL-1.1] → [📋](./.task/REFACTOR-1.1.json)
```
### Phase 7: Session State Update
### Phase 6: Session State Update
Update workflow-session.json with TDD metadata:
```json
@@ -285,18 +352,18 @@ Update workflow-session.json with TDD metadata:
## Output Files Structure
```
.workflow/{session-id}/
├── IMPL_PLAN.md # Standard implementation plan
├── TDD_PLAN.md # TDD-specific plan ⭐ NEW
├── IMPL_PLAN.md # Unified plan with TDD Task Chains section
├── TODO_LIST.md # Progress tracking with TDD phases
├── .task/
│ ├── TEST-1.1.json # Red phase task
│ ├── IMPL-1.1.json # Green phase task
│ ├── IMPL-1.1.json # Green phase task (with test-fix-cycle)
│ ├── 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
├── ANALYSIS_RESULTS.md # Enhanced with TDD breakdown from concept-enhanced
├── test-context-package.json # Test coverage analysis
── context-package.json # Input from context-gather
└── green-fix-iteration-*.md # Fix logs from Green phase
```
## Validation Rules
@@ -356,13 +423,49 @@ Structure:
- 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
- Unified Plan: .workflow/WFS-auth/IMPL_PLAN.md (includes TDD Task Chains section)
Next: /workflow:execute or /workflow:tdd-verify
```
## Test Coverage Analysis Integration
The TDD workflow includes test coverage analysis (via `/workflow:tools:test-context-gather`) to:
- Detect existing test patterns and conventions
- Identify current test coverage gaps
- Discover test framework and configuration
- Enable integration with existing tests
This makes TDD workflow context-aware instead of assuming greenfield scenarios.
## Iterative Green Phase with Test-Fix Cycle
IMPL (Green phase) tasks include automatic test-fix cycle:
**Process Flow**:
1. **Initial Implementation**: Write minimal code to pass tests
2. **Test Execution**: Run test suite
3. **Success Path**: Tests pass → Complete task
4. **Failure Path**: Tests fail → Enter iterative fix cycle:
- **Gemini Diagnosis**: Analyze failures with bug-fix template
- **Fix Application**: Manual (default) or Codex (if meta.use_codex=true)
- **Retest**: Verify fix resolves failures
- **Repeat**: Up to max_iterations (default: 3)
5. **Safety Net**: Auto-revert all changes if max iterations reached
**Key Benefits**:
- ✅ Faster feedback loop within Green phase
- ✅ Autonomous recovery from initial implementation errors
- ✅ Systematic debugging with Gemini's bug-fix template
- ✅ Safe rollback prevents broken TDD state
## Configuration Options
- **meta.max_iterations**: Number of fix attempts (default: 3 for TDD, 5 for test-gen)
- **meta.use_codex**: Enable Codex automated fixes (default: false, manual)
## Related Commands
- `/workflow:tdd-plan` - Orchestrates TDD workflow planning
- `/workflow:tdd-plan` - Orchestrates TDD workflow planning (6 phases)
- `/workflow:tools:test-context-gather` - Analyzes test coverage
- `/workflow:execute` - Executes TDD tasks in order
- `/workflow:tdd-verify` - Verifies TDD compliance
- `/workflow:test-gen` - Post-implementation test generation

View File

@@ -84,21 +84,22 @@ Generate task JSON files and IMPL_PLAN.md from analysis results with automatic a
"source": "brainstorm_synthesis",
"path": ".workflow/WFS-[session]/.brainstorming/synthesis-specification.md",
"priority": "highest",
"contains": "complete_integrated_specification"
"usage": "Primary requirement source - use for consolidated requirements and cross-role alignment"
},
{
"type": "role_analysis",
"source": "brainstorm_roles",
"path": ".workflow/WFS-[session]/.brainstorming/[role-name]/analysis.md",
"priority": "high",
"usage": "Technical/design/business details from specific roles. Common roles: system-architect (ADRs, APIs, caching), ui-designer (design tokens, layouts), product-manager (user stories, metrics)",
"note": "Dynamically discovered - multiple role analysis files may be included based on brainstorming results"
},
{
"type": "topic_framework",
"source": "brainstorm_framework",
"path": ".workflow/WFS-[session]/.brainstorming/topic-framework.md",
"priority": "medium",
"contains": "discussion_framework_structure"
},
{
"type": "individual_role_analysis",
"source": "brainstorm_roles",
"path": ".workflow/WFS-[session]/.brainstorming/[role]/analysis.md",
"priority": "low",
"contains": "role_specific_analysis_fallback"
"usage": "Discussion context and framework structure"
}
]
},
@@ -115,14 +116,16 @@ Generate task JSON files and IMPL_PLAN.md from analysis results with automatic a
"on_error": "skip_optional"
},
{
"step": "load_individual_role_artifacts",
"action": "Load individual role analyses as fallback",
"step": "load_role_analysis_artifacts",
"action": "Load role-specific analysis documents for technical details",
"note": "These artifacts contain implementation details not in synthesis. Consult when needing: API schemas, caching configs, design tokens, ADRs, performance metrics.",
"commands": [
"bash(find .workflow/WFS-[session]/.brainstorming/ -name 'analysis.md' 2>/dev/null | head -8)",
"Read(.workflow/WFS-[session]/.brainstorming/system-architect/analysis.md)",
"Read(.workflow/WFS-[session]/.brainstorming/ui-designer/analysis.md)",
"Read(.workflow/WFS-[session]/.brainstorming/system-architect/analysis.md)"
"Read(.workflow/WFS-[session]/.brainstorming/product-manager/analysis.md)"
],
"output_to": "individual_artifacts",
"output_to": "role_analysis_artifacts",
"on_error": "skip_optional"
},
{
@@ -152,10 +155,11 @@ Generate task JSON files and IMPL_PLAN.md from analysis results with automatic a
}
],
"implementation_approach": {
"task_description": "Implement '[title]' following synthesis specification",
"task_description": "Implement '[title]' following synthesis specification. PRIORITY: Use synthesis-specification.md as primary requirement source. When implementation needs technical details (e.g., API schemas, caching configs, design tokens), refer to artifacts[] for detailed specifications from original role analyses.",
"modification_points": [
"Apply consolidated requirements from synthesis-specification.md",
"Follow technical guidelines from synthesis",
"Consult artifacts for implementation details when needed",
"Integrate with existing patterns"
],
"logic_flow": [
@@ -163,6 +167,7 @@ Generate task JSON files and IMPL_PLAN.md from analysis results with automatic a
"Extract requirements and design",
"Analyze existing patterns",
"Implement following specification",
"Consult artifacts for technical details when needed",
"Validate against acceptance criteria"
]
},

View File

@@ -0,0 +1,468 @@
---
name: test-concept-enhanced
description: Analyze test requirements and generate test generation strategy using Gemini
usage: /workflow:tools:test-concept-enhanced --session <test_session_id> --context <test_context_package_path>
argument-hint: "--session WFS-test-session-id --context path/to/test-context-package.json"
examples:
- /workflow:tools:test-concept-enhanced --session WFS-test-auth --context .workflow/WFS-test-auth/.process/test-context-package.json
---
# Test Concept Enhanced Command
## Overview
Specialized analysis tool for test generation workflows that uses Gemini to analyze test coverage gaps, implementation context, and generate comprehensive test generation strategies.
## Core Philosophy
- **Coverage-Driven**: Focus on identified test gaps from context analysis
- **Pattern-Based**: Learn from existing tests and project conventions
- **Gemini-Powered**: Use Gemini for test requirement analysis and strategy design
- **Single-Round Analysis**: Comprehensive test analysis in one execution
- **No Code Generation**: Strategy and planning only, actual test generation happens in task execution
## Core Responsibilities
- Parse test-context-package.json from test-context-gather
- Analyze implementation summaries and coverage gaps
- Study existing test patterns and conventions
- Generate test generation strategy using Gemini
- Produce TEST_ANALYSIS_RESULTS.md for task generation
## Execution Lifecycle
### Phase 1: Validation & Preparation
1. **Session Validation**
- Load `.workflow/{test_session_id}/workflow-session.json`
- Verify test session type is "test-gen"
- Extract source session reference
2. **Context Package Validation**
- Read `test-context-package.json`
- Validate required sections: metadata, source_context, test_coverage, test_framework
- Extract coverage gaps and framework details
3. **Strategy Determination**
- **Simple Test Generation** (1-3 files): Single Gemini analysis
- **Medium Test Generation** (4-6 files): Gemini comprehensive analysis
- **Complex Test Generation** (>6 files): Gemini analysis with modular approach
### Phase 2: Gemini Test Analysis
**Tool Configuration**:
```bash
cd .workflow/{test_session_id}/.process && ~/.claude/scripts/gemini-wrapper -p "
PURPOSE: Analyze test coverage gaps and design comprehensive test generation strategy
TASK: Study implementation context, existing tests, and generate test requirements for missing coverage
MODE: analysis
CONTEXT: @{.workflow/{test_session_id}/.process/test-context-package.json}
**MANDATORY FIRST STEP**: Read and analyze test-context-package.json to understand:
- Test coverage gaps from test_coverage.missing_tests[]
- Implementation context from source_context.implementation_summaries[]
- Existing test patterns from test_framework.conventions
- Changed files requiring tests from source_context.implementation_summaries[].changed_files
**ANALYSIS REQUIREMENTS**:
1. **Implementation Understanding**
- Load all implementation summaries from source session
- Understand implemented features, APIs, and business logic
- Extract key functions, classes, and modules
- Identify integration points and dependencies
2. **Existing Test Pattern Analysis**
- Study existing test files for patterns and conventions
- Identify test structure (describe/it, test suites, fixtures)
- Analyze assertion patterns and mocking strategies
- Extract test setup/teardown patterns
3. **Coverage Gap Assessment**
- For each file in missing_tests[], analyze:
- File purpose and functionality
- Public APIs requiring test coverage
- Critical paths and edge cases
- Integration points requiring tests
- Prioritize tests: high (core logic), medium (utilities), low (helpers)
4. **Test Requirements Specification**
- For each missing test file, specify:
- **Test scope**: What needs to be tested
- **Test scenarios**: Happy path, error cases, edge cases, integration
- **Test data**: Required fixtures, mocks, test data
- **Dependencies**: External services, databases, APIs to mock
- **Coverage targets**: Functions/methods requiring tests
5. **Test Generation Strategy**
- Determine test generation approach for each file
- Identify reusable test patterns from existing tests
- Plan test data and fixture requirements
- Define mocking strategy for dependencies
- Specify expected test file structure
EXPECTED OUTPUT - Write to gemini-test-analysis.md:
# Test Generation Analysis
## 1. Implementation Context Summary
- **Source Session**: {source_session_id}
- **Implemented Features**: {feature_summary}
- **Changed Files**: {list_of_implementation_files}
- **Tech Stack**: {technologies_used}
## 2. Test Coverage Assessment
- **Existing Tests**: {count} files
- **Missing Tests**: {count} files
- **Coverage Percentage**: {percentage}%
- **Priority Breakdown**:
- High Priority: {count} files (core business logic)
- Medium Priority: {count} files (utilities, helpers)
- Low Priority: {count} files (configuration, constants)
## 3. Existing Test Pattern Analysis
- **Test Framework**: {framework_name_and_version}
- **File Naming Convention**: {pattern}
- **Test Structure**: {describe_it_or_other}
- **Assertion Style**: {expect_assert_should}
- **Mocking Strategy**: {mocking_framework_and_patterns}
- **Setup/Teardown**: {beforeEach_afterEach_patterns}
- **Test Data**: {fixtures_factories_builders}
## 4. Test Requirements by File
### File: {implementation_file_path}
**Test File**: {suggested_test_file_path}
**Priority**: {high|medium|low}
#### Scope
- {description_of_what_needs_testing}
#### Test Scenarios
1. **Happy Path Tests**
- {scenario_1}
- {scenario_2}
2. **Error Handling Tests**
- {error_scenario_1}
- {error_scenario_2}
3. **Edge Case Tests**
- {edge_case_1}
- {edge_case_2}
4. **Integration Tests** (if applicable)
- {integration_scenario_1}
- {integration_scenario_2}
#### Test Data & Fixtures
- {required_test_data}
- {required_mocks}
- {required_fixtures}
#### Dependencies to Mock
- {external_service_1}
- {external_service_2}
#### Coverage Targets
- Function: {function_name} - {test_requirements}
- Function: {function_name} - {test_requirements}
---
[Repeat for each missing test file]
---
## 5. Test Generation Strategy
### Overall Approach
- {strategy_description}
### Test Generation Order
1. {file_1} - {rationale}
2. {file_2} - {rationale}
3. {file_3} - {rationale}
### Reusable Patterns
- {pattern_1_from_existing_tests}
- {pattern_2_from_existing_tests}
### Test Data Strategy
- {approach_to_test_data_and_fixtures}
### Mocking Strategy
- {approach_to_mocking_dependencies}
### Quality Criteria
- Code coverage target: {percentage}%
- Test scenarios per function: {count}
- Integration test coverage: {approach}
## 6. Implementation Targets
**Purpose**: Identify new test files to create
**Format**: New test files only (no existing files to modify)
**Test Files to Create**:
1. **Target**: `tests/auth/TokenValidator.test.ts`
- **Type**: Create new test file
- **Purpose**: Test TokenValidator class
- **Scenarios**: 15 test cases covering validation logic, error handling, edge cases
- **Dependencies**: Mock JWT library, test fixtures for tokens
2. **Target**: `tests/middleware/errorHandler.test.ts`
- **Type**: Create new test file
- **Purpose**: Test error handling middleware
- **Scenarios**: 8 test cases for different error types and response formats
- **Dependencies**: Mock Express req/res/next, error fixtures
[List all test files to create]
## 7. Success Metrics
- **Test Coverage Goal**: {target_percentage}%
- **Test Quality**: All scenarios covered (happy, error, edge, integration)
- **Convention Compliance**: Follow existing test patterns
- **Maintainability**: Clear test descriptions, reusable fixtures
RULES:
- Focus on TEST REQUIREMENTS and GENERATION STRATEGY, NOT code generation
- Study existing test patterns thoroughly for consistency
- Prioritize critical business logic tests
- Specify clear test scenarios and coverage targets
- Identify all dependencies requiring mocks
- **MUST write output to .workflow/{test_session_id}/.process/gemini-test-analysis.md**
- Do NOT generate actual test code or implementation
- Output ONLY test analysis and generation strategy
" --approval-mode yolo
```
**Output Location**: `.workflow/{test_session_id}/.process/gemini-test-analysis.md`
### Phase 3: Results Synthesis
1. **Output Validation**
- Verify `gemini-test-analysis.md` exists and is complete
- Validate all required sections present
- Check test requirements are actionable
2. **Quality Assessment**
- Test scenarios cover happy path, errors, edge cases
- Dependencies and mocks clearly identified
- Test generation strategy is practical
- Coverage targets are reasonable
### Phase 4: TEST_ANALYSIS_RESULTS.md Generation
Synthesize Gemini analysis into standardized format:
```markdown
# Test Generation Analysis Results
## Executive Summary
- **Test Session**: {test_session_id}
- **Source Session**: {source_session_id}
- **Analysis Timestamp**: {timestamp}
- **Coverage Gap**: {missing_test_count} files require tests
- **Test Framework**: {framework}
- **Overall Strategy**: {high_level_approach}
---
## 1. Coverage Assessment
### Current Coverage
- **Existing Tests**: {count} files
- **Implementation Files**: {count} files
- **Coverage Percentage**: {percentage}%
### Missing Tests (Priority Order)
1. **High Priority** ({count} files)
- {file_1} - {reason}
- {file_2} - {reason}
2. **Medium Priority** ({count} files)
- {file_1} - {reason}
3. **Low Priority** ({count} files)
- {file_1} - {reason}
---
## 2. Test Framework & Conventions
### Framework Configuration
- **Framework**: {framework_name}
- **Version**: {version}
- **Test Pattern**: {file_pattern}
- **Test Directory**: {directory_structure}
### Conventions
- **File Naming**: {convention}
- **Test Structure**: {describe_it_blocks}
- **Assertions**: {assertion_library}
- **Mocking**: {mocking_framework}
- **Setup/Teardown**: {beforeEach_afterEach}
### Example Pattern (from existing tests)
```
{example_test_structure_from_analysis}
```
---
## 3. Test Requirements by File
[For each missing test, include:]
### Test File: {test_file_path}
**Implementation**: {implementation_file}
**Priority**: {high|medium|low}
**Estimated Test Count**: {count}
#### Test Scenarios
1. **Happy Path**: {scenarios}
2. **Error Handling**: {scenarios}
3. **Edge Cases**: {scenarios}
4. **Integration**: {scenarios}
#### Dependencies & Mocks
- {dependency_1_to_mock}
- {dependency_2_to_mock}
#### Test Data Requirements
- {fixture_1}
- {fixture_2}
---
## 4. Test Generation Strategy
### Generation Approach
{overall_strategy_description}
### Generation Order
1. {test_file_1} - {rationale}
2. {test_file_2} - {rationale}
3. {test_file_3} - {rationale}
### Reusable Components
- **Test Fixtures**: {common_fixtures}
- **Mock Patterns**: {common_mocks}
- **Helper Functions**: {test_helpers}
### Quality Targets
- **Coverage Goal**: {percentage}%
- **Scenarios per Function**: {min_count}
- **Integration Coverage**: {approach}
---
## 5. Implementation Targets
**Purpose**: New test files to create (code-developer will generate these)
**Test Files to Create**:
1. **Target**: `tests/auth/TokenValidator.test.ts`
- **Implementation Source**: `src/auth/TokenValidator.ts`
- **Test Scenarios**: 15 (validation, error handling, edge cases)
- **Dependencies**: Mock JWT library, token fixtures
- **Priority**: High
2. **Target**: `tests/middleware/errorHandler.test.ts`
- **Implementation Source**: `src/middleware/errorHandler.ts`
- **Test Scenarios**: 8 (error types, response formats)
- **Dependencies**: Mock Express, error fixtures
- **Priority**: High
[List all test files with full specifications]
---
## 6. Success Criteria
### Coverage Metrics
- Achieve {target_percentage}% code coverage
- All public APIs have tests
- Critical paths fully covered
### Quality Standards
- All test scenarios covered (happy, error, edge, integration)
- Follow existing test conventions
- Clear test descriptions and assertions
- Maintainable test structure
### Validation Approach
- Run full test suite after generation
- Verify coverage with coverage tool
- Manual review of test quality
- Integration test validation
---
## 7. Reference Information
### Source Context
- **Implementation Summaries**: {paths}
- **Existing Tests**: {example_tests}
- **Documentation**: {relevant_docs}
### Analysis Tools
- **Gemini Analysis**: gemini-test-analysis.md
- **Coverage Tools**: {coverage_tool_if_detected}
```
**Output Location**: `.workflow/{test_session_id}/.process/TEST_ANALYSIS_RESULTS.md`
## Error Handling
### Validation Errors
| Error | Cause | Resolution |
|-------|-------|------------|
| Missing context package | test-context-gather not run | Run test-context-gather first |
| No coverage gaps | All files have tests | Skip test generation, proceed to test execution |
| No test framework detected | Missing test dependencies | Request user to configure test framework |
| Invalid source session | Source session incomplete | Complete implementation first |
### Gemini Execution Errors
| Error | Cause | Recovery |
|-------|-------|----------|
| Timeout | Large project analysis | Reduce scope, analyze by module |
| Output incomplete | Token limit exceeded | Retry with focused analysis |
| No output file | Write permission error | Check directory permissions |
### Fallback Strategy
- If Gemini fails, generate basic TEST_ANALYSIS_RESULTS.md from context package
- Use coverage gaps and framework info to create minimal requirements
- Provide guidance for manual test planning
## Performance Optimization
- **Focused Analysis**: Only analyze files with missing tests
- **Pattern Reuse**: Study existing tests for quick pattern extraction
- **Parallel Operations**: Load implementation summaries in parallel
- **Timeout Management**: 20-minute limit for Gemini analysis
## Integration
### Called By
- `/workflow:test-gen` (Phase 4: Analysis)
### Requires
- `/workflow:tools:test-context-gather` output (test-context-package.json)
### Followed By
- `/workflow:tools:test-task-generate` - Generates test task JSON with code-developer invocation
## Success Criteria
- ✅ Valid TEST_ANALYSIS_RESULTS.md generated
- ✅ All missing tests documented with requirements
- ✅ Test scenarios cover happy path, errors, edge cases
- ✅ Dependencies and mocks identified
- ✅ Test generation strategy is actionable
- ✅ Execution time < 20 minutes
- ✅ Output follows existing test conventions
## Related Commands
- `/workflow:tools:test-context-gather` - Provides input context
- `/workflow:tools:test-task-generate` - Consumes analysis results
- `/workflow:test-gen` - Main test generation workflow

View File

@@ -0,0 +1,310 @@
---
name: test-context-gather
description: Collect test coverage context and identify files requiring test generation
usage: /workflow:tools:test-context-gather --session <test_session_id>
argument-hint: "--session WFS-test-session-id"
examples:
- /workflow:tools:test-context-gather --session WFS-test-auth
- /workflow:tools:test-context-gather --session WFS-test-payment
---
# Test Context Gather Command
## Overview
Specialized context collector for test generation workflows that analyzes test coverage, identifies missing tests, and packages implementation context from source sessions.
## Core Philosophy
- **Coverage-First**: Analyze existing test coverage before planning
- **Gap Identification**: Locate implementation files without corresponding tests
- **Source Context Loading**: Import implementation summaries from source session
- **Framework Detection**: Auto-detect test framework and patterns
- **MCP-Powered**: Leverage code-index tools for precise analysis
## Core Responsibilities
- Load source session implementation context
- Analyze current test coverage using MCP tools
- Identify files requiring test generation
- Detect test framework and conventions
- Package test context for analysis phase
## Execution Lifecycle
### Phase 1: Session Validation & Source Loading
1. **Test Session Validation**
- Load `.workflow/{test_session_id}/workflow-session.json`
- Extract `meta.source_session` reference
- Validate test session type is "test-gen"
2. **Source Session Context Loading**
- Read `.workflow/{source_session_id}/workflow-session.json`
- Load implementation summaries from `.workflow/{source_session_id}/.summaries/`
- Extract changed files and implementation scope
- Identify implementation patterns and tech stack
### Phase 2: Test Coverage Analysis (MCP Tools)
1. **Existing Test Discovery**
```bash
# Find all test files
mcp__code-index__find_files(pattern="*.test.*")
mcp__code-index__find_files(pattern="*.spec.*")
mcp__code-index__find_files(pattern="*test_*.py")
# Search for test patterns
mcp__code-index__search_code_advanced(
pattern="describe|it|test|@Test",
file_pattern="*.test.*",
context_lines=0
)
```
2. **Coverage Gap Analysis**
```bash
# For each implementation file from source session
# Check if corresponding test file exists
# Example: src/auth/AuthService.ts -> tests/auth/AuthService.test.ts
# src/utils/validator.py -> tests/test_validator.py
# Output: List of files without tests
```
3. **Test Statistics**
- Count total test files
- Count implementation files from source session
- Calculate coverage percentage
- Identify coverage gaps by module
### Phase 3: Test Framework Detection
1. **Framework Identification**
```bash
# Check package.json or requirements.txt
mcp__code-index__search_code_advanced(
pattern="jest|mocha|jasmine|pytest|unittest|rspec",
file_pattern="package.json|requirements.txt|Gemfile",
context_lines=2
)
# Analyze existing test patterns
mcp__code-index__search_code_advanced(
pattern="describe\\(|it\\(|test\\(|def test_",
file_pattern="*.test.*",
context_lines=3
)
```
2. **Convention Analysis**
- Test file naming patterns (*.test.ts vs *.spec.ts)
- Test directory structure (tests/ vs __tests__ vs src/**/*.test.*)
- Assertion library (expect, assert, should)
- Mocking framework (jest.fn, sinon, unittest.mock)
### Phase 4: Context Packaging
Generate `test-context-package.json`:
```json
{
"metadata": {
"test_session_id": "WFS-test-auth",
"source_session_id": "WFS-auth",
"timestamp": "2025-10-04T10:30:00Z",
"task_type": "test-generation",
"complexity": "medium"
},
"source_context": {
"implementation_summaries": [
{
"task_id": "IMPL-001",
"summary_path": ".workflow/WFS-auth/.summaries/IMPL-001-summary.md",
"changed_files": [
"src/auth/AuthService.ts",
"src/auth/TokenValidator.ts",
"src/middleware/auth.ts"
],
"implementation_type": "feature"
}
],
"tech_stack": ["typescript", "express", "jsonwebtoken"],
"project_patterns": {
"architecture": "layered",
"error_handling": "try-catch with custom errors",
"async_pattern": "async/await"
}
},
"test_coverage": {
"existing_tests": [
"tests/auth/AuthService.test.ts",
"tests/middleware/auth.test.ts"
],
"missing_tests": [
{
"implementation_file": "src/auth/TokenValidator.ts",
"suggested_test_file": "tests/auth/TokenValidator.test.ts",
"priority": "high",
"reason": "New implementation without tests"
}
],
"coverage_stats": {
"total_implementation_files": 3,
"files_with_tests": 2,
"files_without_tests": 1,
"coverage_percentage": 66.7
}
},
"test_framework": {
"framework": "jest",
"version": "^29.0.0",
"test_pattern": "**/*.test.ts",
"test_directory": "tests/",
"assertion_library": "expect",
"mocking_framework": "jest",
"conventions": {
"file_naming": "*.test.ts",
"test_structure": "describe/it blocks",
"setup_teardown": "beforeEach/afterEach"
}
},
"assets": [
{
"type": "implementation_summary",
"path": ".workflow/WFS-auth/.summaries/IMPL-001-summary.md",
"relevance": "Source implementation context",
"priority": "highest"
},
{
"type": "existing_test",
"path": "tests/auth/AuthService.test.ts",
"relevance": "Test pattern reference",
"priority": "high"
},
{
"type": "source_code",
"path": "src/auth/TokenValidator.ts",
"relevance": "Implementation requiring tests",
"priority": "high"
},
{
"type": "documentation",
"path": "CLAUDE.md",
"relevance": "Project conventions",
"priority": "medium"
}
],
"focus_areas": [
"Generate comprehensive tests for TokenValidator",
"Follow existing Jest patterns from AuthService tests",
"Cover happy path, error cases, and edge cases",
"Include integration tests for middleware"
]
}
```
## Output Location
```
.workflow/{test_session_id}/.process/test-context-package.json
```
## MCP Tools Usage
### File Discovery
```bash
# Test files
mcp__code-index__find_files(pattern="*.test.*")
mcp__code-index__find_files(pattern="*.spec.*")
# Implementation files
mcp__code-index__find_files(pattern="*.ts")
mcp__code-index__find_files(pattern="*.js")
```
### Content Search
```bash
# Test framework detection
mcp__code-index__search_code_advanced(
pattern="jest|mocha|pytest",
file_pattern="package.json|requirements.txt"
)
# Test pattern analysis
mcp__code-index__search_code_advanced(
pattern="describe|it|test",
file_pattern="*.test.*",
context_lines=2
)
```
### Coverage Analysis
```bash
# For each implementation file
# Check if test exists
implementation_file="src/auth/AuthService.ts"
test_file_patterns=(
"tests/auth/AuthService.test.ts"
"src/auth/AuthService.test.ts"
"src/auth/__tests__/AuthService.test.ts"
)
# Search for test file
for pattern in "${test_file_patterns[@]}"; do
if mcp__code-index__find_files(pattern="$pattern") | grep -q .; then
echo "✅ Test exists: $pattern"
break
fi
done
```
## Error Handling
| Error | Cause | Resolution |
|-------|-------|------------|
| Source session not found | Invalid source_session reference | Verify test session metadata |
| No implementation summaries | Source session incomplete | Complete source session first |
| MCP tools unavailable | MCP not configured | Fallback to bash find/grep |
| No test framework detected | Missing test dependencies | Request user to specify framework |
## Fallback Strategy (No MCP)
```bash
# File discovery
find . -name "*.test.*" -o -name "*.spec.*" | grep -v node_modules
# Framework detection
grep -r "jest\|mocha\|pytest" package.json requirements.txt 2>/dev/null
# Coverage analysis
for impl_file in $(cat changed_files.txt); do
test_file=$(echo $impl_file | sed 's/src/tests/' | sed 's/\(.*\)\.\(ts\|js\|py\)$/\1.test.\2/')
[ ! -f "$test_file" ] && echo "$impl_file → MISSING TEST"
done
```
## Integration
### Called By
- `/workflow:test-gen` (Phase 3: Context Gathering)
### Calls
- MCP code-index tools for analysis
- Bash file operations for fallback
### Followed By
- `/workflow:tools:test-concept-enhanced` - Analyzes context and plans test generation
## Success Criteria
- ✅ Source session context loaded successfully
- ✅ Test coverage gaps identified with MCP tools
- ✅ Test framework detected and documented
- ✅ Valid test-context-package.json generated
- ✅ All missing tests catalogued with priority
- ✅ Execution time < 20 seconds
## Related Commands
- `/workflow:test-gen` - Main test generation workflow
- `/workflow:tools:test-concept-enhanced` - Test generation analysis
- `/workflow:tools:test-task-generate` - Test task JSON generation

View File

@@ -0,0 +1,655 @@
---
name: test-task-generate
description: Generate test-fix task JSON with iterative test-fix-retest cycle specification
usage: /workflow:tools:test-task-generate [--use-codex] --session <test-session-id>
argument-hint: "[--use-codex] --session WFS-test-session-id"
examples:
- /workflow:tools:test-task-generate --session WFS-test-auth
- /workflow:tools:test-task-generate --use-codex --session WFS-test-auth
---
# Test Task Generation Command
## Overview
Generate specialized test-fix task JSON with comprehensive test-fix-retest cycle specification, including Gemini diagnosis (using bug-fix template) and manual fix workflow (Codex automation only when explicitly requested).
## Core Philosophy
- **Analysis-Driven Test Generation**: Use TEST_ANALYSIS_RESULTS.md from test-concept-enhanced
- **Agent-Based Test Creation**: Call @code-developer agent for comprehensive test generation
- **Coverage-First**: Generate all missing tests before execution
- **Test Execution**: Execute complete test suite after generation
- **Gemini Diagnosis**: Use Gemini for root cause analysis and fix suggestions (references bug-fix template)
- **Manual Fixes First**: Apply fixes manually by default, codex only when explicitly needed
- **Iterative Refinement**: Repeat test-analyze-fix-retest cycle until all tests pass
- **Surgical Fixes**: Minimal code changes, no refactoring during test fixes
- **Auto-Revert**: Rollback all changes if max iterations reached
## Core Responsibilities
- Parse TEST_ANALYSIS_RESULTS.md from test-concept-enhanced
- Extract test requirements and generation strategy
- Parse `--use-codex` flag to determine fix mode (manual vs automated)
- Generate test generation subtask calling @code-developer
- Generate test execution and fix cycle task JSON with appropriate fix mode
- Configure Gemini diagnosis workflow (bug-fix template) and manual/Codex fix application
- Create test-oriented IMPL_PLAN.md and TODO_LIST.md with test generation phase
## Execution Lifecycle
### Phase 1: Input Validation & Discovery
1. **Parameter Parsing**
- Parse `--use-codex` flag from command arguments
- Store flag value for IMPL-002.json generation
2. **Test Session Validation**
- Load `.workflow/{test-session-id}/workflow-session.json`
- Verify `workflow_type: "test_session"`
- Extract `source_session_id` from metadata
3. **Test Analysis Results Loading**
- **REQUIRED**: Load `.workflow/{test-session-id}/.process/TEST_ANALYSIS_RESULTS.md`
- Parse test requirements by file
- Extract test generation strategy
- Identify test files to create with specifications
4. **Test Context Package Loading**
- Load `.workflow/{test-session-id}/.process/test-context-package.json`
- Extract test framework configuration
- Extract coverage gaps and priorities
- Load source session implementation summaries
### Phase 2: Task JSON Generation
Generate **TWO task JSON files**:
1. **IMPL-001.json** - Test Generation (calls @code-developer)
2. **IMPL-002.json** - Test Execution and Fix Cycle (calls @test-fix-agent)
#### IMPL-001.json - Test Generation Task
```json
{
"id": "IMPL-001",
"title": "Generate comprehensive tests for [sourceSessionId]",
"status": "pending",
"meta": {
"type": "test-gen",
"agent": "@code-developer",
"source_session": "[sourceSessionId]",
"test_framework": "jest|pytest|cargo|detected"
},
"context": {
"requirements": [
"Generate comprehensive test files based on TEST_ANALYSIS_RESULTS.md",
"Follow existing test patterns and conventions from test framework",
"Create tests for all missing coverage identified in analysis",
"Include happy path, error handling, edge cases, and integration tests",
"Use test data and mocks as specified in analysis",
"Ensure tests follow project coding standards"
],
"focus_paths": [
"tests/**/*",
"src/**/*.test.*",
"{paths_from_analysis}"
],
"acceptance": [
"All test files from TEST_ANALYSIS_RESULTS.md section 5 are created",
"Tests follow existing test patterns and conventions",
"Test scenarios cover happy path, errors, edge cases, integration",
"All dependencies are properly mocked",
"Test files are syntactically valid and can be executed",
"Test coverage meets analysis requirements"
],
"depends_on": [],
"source_context": {
"session_id": "[sourceSessionId]",
"test_analysis": ".workflow/[testSessionId]/.process/TEST_ANALYSIS_RESULTS.md",
"test_context": ".workflow/[testSessionId]/.process/test-context-package.json",
"implementation_summaries": [
".workflow/[sourceSessionId]/.summaries/IMPL-001-summary.md"
]
}
},
"flow_control": {
"pre_analysis": [
{
"step": "load_test_analysis",
"action": "Load test generation requirements and strategy",
"commands": [
"Read(.workflow/[testSessionId]/.process/TEST_ANALYSIS_RESULTS.md)",
"Read(.workflow/[testSessionId]/.process/test-context-package.json)"
],
"output_to": "test_generation_requirements",
"on_error": "fail"
},
{
"step": "load_implementation_context",
"action": "Load source implementation for test generation context",
"commands": [
"bash(for f in .workflow/[sourceSessionId]/.summaries/IMPL-*-summary.md; do echo \"=== $(basename $f) ===\"&& cat \"$f\"; done)"
],
"output_to": "implementation_context",
"on_error": "skip_optional"
},
{
"step": "load_existing_test_patterns",
"action": "Study existing tests for pattern reference",
"commands": [
"mcp__code-index__find_files(pattern=\"*.test.*\")",
"bash(# Read first 2 existing test files as examples)",
"bash(test_files=$(mcp__code-index__find_files(pattern=\"*.test.*\") | head -2))",
"bash(for f in $test_files; do echo \"=== $f ===\"&& cat \"$f\"; done)"
],
"output_to": "existing_test_patterns",
"on_error": "skip_optional"
}
],
"implementation_approach": {
"task_description": "Generate comprehensive test suite based on TEST_ANALYSIS_RESULTS.md. Follow test generation strategy and create all test files listed in section 5 (Implementation Targets).",
"generation_steps": [
"Read TEST_ANALYSIS_RESULTS.md section 3 (Test Requirements by File)",
"Read TEST_ANALYSIS_RESULTS.md section 4 (Test Generation Strategy)",
"Study existing test patterns from test_context.test_framework.conventions",
"For each test file in section 5 (Implementation Targets):",
" - Create test file with specified scenarios",
" - Implement happy path tests",
" - Implement error handling tests",
" - Implement edge case tests",
" - Implement integration tests (if specified)",
" - Add required mocks and fixtures",
"Follow test framework conventions and project standards",
"Ensure all tests are executable and syntactically valid"
],
"quality_criteria": [
"All test scenarios from analysis are implemented",
"Test structure matches existing patterns",
"Clear test descriptions and assertions",
"Proper setup/teardown and fixtures",
"Dependencies properly mocked",
"Tests follow project coding standards"
]
},
"target_files": [
"{test_file_1 from TEST_ANALYSIS_RESULTS.md section 5}",
"{test_file_2 from TEST_ANALYSIS_RESULTS.md section 5}",
"{test_file_N from TEST_ANALYSIS_RESULTS.md section 5}"
]
}
}
```
#### IMPL-002.json - Test Execution & Fix Cycle Task
```json
{
"id": "IMPL-002",
"title": "Execute and fix tests for [sourceSessionId]",
"status": "pending",
"meta": {
"type": "test-fix",
"agent": "@test-fix-agent",
"source_session": "[sourceSessionId]",
"test_framework": "jest|pytest|cargo|detected",
"max_iterations": 5,
"use_codex": false // Set to true if --use-codex flag present
},
"context": {
"requirements": [
"Execute complete test suite (generated in IMPL-001)",
"Diagnose test failures using Gemini analysis with bug-fix template",
"Present fixes to user for manual application (default)",
"Use Codex ONLY if user explicitly requests automation",
"Iterate until all tests pass or max iterations reached",
"Revert changes if unable to fix within iteration limit"
],
"focus_paths": [
"tests/**/*",
"src/**/*.test.*",
"{implementation_files_from_source_session}"
],
"acceptance": [
"All tests pass successfully (100% pass rate)",
"No test failures or errors in final run",
"Code changes are minimal and surgical",
"All fixes are verified through retest",
"Iteration logs document fix progression"
],
"depends_on": ["IMPL-001"],
"source_context": {
"session_id": "[sourceSessionId]",
"test_generation_summary": ".workflow/[testSessionId]/.summaries/IMPL-001-summary.md",
"implementation_summaries": [
".workflow/[sourceSessionId]/.summaries/IMPL-001-summary.md"
]
}
},
"flow_control": {
"pre_analysis": [
{
"step": "load_source_session_summaries",
"action": "Load implementation context from source session",
"commands": [
"bash(find .workflow/[sourceSessionId]/.summaries/ -name 'IMPL-*-summary.md' 2>/dev/null)",
"bash(for f in .workflow/[sourceSessionId]/.summaries/IMPL-*-summary.md; do echo \"=== $(basename $f) ===\"&& cat \"$f\"; done)"
],
"output_to": "implementation_context",
"on_error": "skip_optional"
},
{
"step": "discover_test_framework",
"action": "Identify test framework and test command",
"commands": [
"bash(jq -r '.scripts.test // \"npm test\"' package.json 2>/dev/null || echo 'pytest' || echo 'cargo test')",
"bash([ -f 'package.json' ] && echo 'jest/npm' || [ -f 'pytest.ini' ] && echo 'pytest' || [ -f 'Cargo.toml' ] && echo 'cargo' || echo 'unknown')"
],
"output_to": "test_command",
"on_error": "fail"
},
{
"step": "analyze_test_coverage",
"action": "Analyze test coverage and identify missing tests",
"commands": [
"mcp__code-index__find_files(pattern=\"*.test.*\")",
"mcp__code-index__search_code_advanced(pattern=\"test|describe|it|def test_\", file_pattern=\"*.test.*\")",
"bash(# Count implementation files vs test files)",
"bash(impl_count=$(find [changed_files_dirs] -type f \\( -name '*.ts' -o -name '*.js' -o -name '*.py' \\) ! -name '*.test.*' 2>/dev/null | wc -l))",
"bash(test_count=$(mcp__code-index__find_files(pattern=\"*.test.*\") | wc -l))",
"bash(echo \"Implementation files: $impl_count, Test files: $test_count\")"
],
"output_to": "test_coverage_analysis",
"on_error": "skip_optional"
},
{
"step": "identify_files_without_tests",
"action": "List implementation files that lack corresponding test files",
"commands": [
"bash(# For each changed file from source session, check if test exists)",
"bash(for file in [changed_files]; do test_file=$(echo $file | sed 's/\\(.*\\)\\.\\(ts\\|js\\|py\\)$/\\1.test.\\2/'); [ ! -f \"$test_file\" ] && echo \"$file\"; done)"
],
"output_to": "files_without_tests",
"on_error": "skip_optional"
},
{
"step": "prepare_test_environment",
"action": "Ensure test environment is ready",
"commands": [
"bash([ -f 'package.json' ] && npm install 2>/dev/null || true)",
"bash([ -f 'requirements.txt' ] && pip install -q -r requirements.txt 2>/dev/null || true)"
],
"output_to": "environment_status",
"on_error": "skip_optional"
}
],
"implementation_approach": {
"task_description": "Execute iterative test-fix-retest cycle using Gemini diagnosis (bug-fix template) and manual fixes (Codex only if explicitly needed)",
"test_fix_cycle": {
"max_iterations": 5,
"cycle_pattern": "test → gemini_diagnose → manual_fix (or codex if needed) → retest",
"tools": {
"test_execution": "bash(test_command)",
"diagnosis": "gemini-wrapper (MODE: analysis, uses bug-fix template)",
"fix_application": "manual (default) or codex exec resume --last (if explicitly needed)",
"verification": "bash(test_command) + regression_check"
},
"exit_conditions": {
"success": "all_tests_pass",
"failure": "max_iterations_reached",
"error": "test_command_not_found"
}
},
"modification_points": [
"PHASE 1: Initial Test Execution",
" 1.1. Discover test command from framework detection",
" 1.2. Execute initial test run: bash([test_command])",
" 1.3. Parse test output and count failures",
" 1.4. If all pass → Skip to PHASE 3 (success)",
" 1.5. If failures → Store failure output, proceed to PHASE 2",
"",
"PHASE 2: Iterative Test-Fix-Retest Cycle (max 5 iterations)",
" Note: This phase handles test failures, NOT test generation failures",
" Initialize: max_iterations=5, current_iteration=0",
" ",
" WHILE (tests failing AND current_iteration < max_iterations):",
" current_iteration++",
" ",
" STEP 2.1: Gemini Diagnosis (using bug-fix template)",
" - Prepare diagnosis context:",
" * Test failure output from previous run",
" * Source files from focus_paths",
" * Implementation summaries from source session",
" - Execute Gemini analysis with bug-fix template:",
" bash(cd .workflow/WFS-test-[session]/.process && ~/.claude/scripts/gemini-wrapper --all-files -p \"",
" PURPOSE: Diagnose test failure iteration [N] and propose minimal fix",
" TASK: Systematic bug analysis and fix recommendations for test failure",
" MODE: analysis",
" CONTEXT: @{CLAUDE.md,**/*CLAUDE.md}",
" Test output: [test_failures]",
" Source files: [focus_paths]",
" Implementation: [implementation_context]",
" EXPECTED: Root cause analysis, code path tracing, targeted fixes",
" RULES: $(cat ~/.claude/prompt-templates/bug-fix.md) | Bug: [test_failure_description]",
" Minimal surgical fixes only - no refactoring",
" \" > fix-iteration-[N]-diagnosis.md)",
" - Parse diagnosis → extract fix_suggestion and target_files",
" - Present fix to user for manual application (default)",
" ",
" STEP 2.2: Apply Fix (Based on meta.use_codex Flag)",
" ",
" IF meta.use_codex = false (DEFAULT):",
" - Present Gemini diagnosis to user for manual fix",
" - User applies fix based on diagnosis recommendations",
" - Stage changes: bash(git add -A)",
" - Store fix log: .process/fix-iteration-[N]-changes.log",
" ",
" IF meta.use_codex = true (--use-codex flag present):",
" - Stage current changes (if valid git repo): bash(git add -A)",
" - First iteration: Start new Codex session",
" codex -C [project_root] --full-auto exec \"",
" PURPOSE: Fix test failure iteration 1",
" TASK: [fix_suggestion from Gemini]",
" MODE: write",
" CONTEXT: Diagnosis: .workflow/.process/fix-iteration-1-diagnosis.md",
" Target files: [target_files]",
" Implementation context: [implementation_context]",
" EXPECTED: Minimal code changes to resolve test failure",
" RULES: Apply ONLY suggested changes, no refactoring",
" Preserve existing code style",
" \" --skip-git-repo-check -s danger-full-access",
" - Subsequent iterations: Resume session for context continuity",
" codex exec \"",
" CONTINUE TO NEXT FIX:",
" Iteration [N] of 5: Fix test failure",
" ",
" PURPOSE: Fix remaining test failures",
" TASK: [fix_suggestion from Gemini iteration N]",
" CONTEXT: Previous fixes applied, diagnosis: .process/fix-iteration-[N]-diagnosis.md",
" EXPECTED: Surgical fix for current failure",
" RULES: Build on previous fixes, maintain consistency",
" \" resume --last --skip-git-repo-check -s danger-full-access",
" - Store fix log: .process/fix-iteration-[N]-changes.log",
" ",
" STEP 2.3: Retest and Verification",
" - Re-execute test suite: bash([test_command])",
" - Capture output: .process/fix-iteration-[N]-retest.log",
" - Count failures: bash(grep -c 'FAIL\\|ERROR' .process/fix-iteration-[N]-retest.log)",
" - Check for regression:",
" IF new_failures > previous_failures:",
" WARN: Regression detected",
" Include in next Gemini diagnosis context",
" - Analyze results:",
" IF all_tests_pass:",
" BREAK loop → Proceed to PHASE 3",
" ELSE:",
" Update test_failures context",
" CONTINUE loop",
" ",
" IF max_iterations reached AND tests still failing:",
" EXECUTE: git reset --hard HEAD (revert all changes)",
" MARK: Task status = blocked",
" GENERATE: Detailed failure report with iteration logs",
" EXIT: Require manual intervention",
"",
"PHASE 3: Final Validation and Certification",
" 3.1. Execute final confirmation test run",
" 3.2. Generate success summary:",
" - Iterations required: [current_iteration]",
" - Fixes applied: [summary from iteration logs]",
" - Test results: All passing ✅",
" 3.3. Mark task status: completed",
" 3.4. Update TODO_LIST.md: Mark as ✅",
" 3.5. Certify code: APPROVED for deployment"
],
"logic_flow": [
"Load source session implementation context",
"Discover test framework and command",
"PHASE 0: Test Coverage Check",
" Analyze existing test files",
" Identify files without tests",
" IF tests missing:",
" Report to user (no automatic generation)",
" Wait for user to generate tests or request automation",
" ELSE:",
" Skip to Phase 1",
"PHASE 1: Initial Test Execution",
" Execute test suite",
" IF all pass → Success (Phase 3)",
" ELSE → Store failures, proceed to Phase 2",
"PHASE 2: Iterative Fix Cycle (max 5 iterations)",
" LOOP (max 5 times):",
" 1. Gemini diagnoses failure with bug-fix template → fix suggestion",
" 2. Check meta.use_codex flag:",
" - IF false (default): Present fix to user for manual application",
" - IF true (--use-codex): Codex applies fix with resume for continuity",
" 3. Retest and check results",
" 4. IF pass → Exit loop to Phase 3",
" 5. ELSE → Continue with updated context",
" IF max iterations → Revert + report failure",
"PHASE 3: Final Validation",
" Confirm all tests pass",
" Generate summary (include test generation info)",
" Certify code APPROVED"
],
"error_handling": {
"max_iterations_reached": {
"action": "revert_all_changes",
"commands": [
"bash(git reset --hard HEAD)",
"bash(jq '.status = \"blocked\"' .workflow/[session]/.task/IMPL-001.json > temp.json && mv temp.json .workflow/[session]/.task/IMPL-001.json)"
],
"report": "Generate failure report with iteration logs in .summaries/IMPL-001-failure-report.md"
},
"test_command_fails": {
"action": "treat_as_test_failure",
"context": "Use stderr as failure context for Gemini diagnosis"
},
"codex_apply_fails": {
"action": "retry_once_then_skip",
"fallback": "Mark iteration as skipped, continue to next"
},
"gemini_diagnosis_fails": {
"action": "retry_with_simplified_context",
"fallback": "Use previous diagnosis, continue"
},
"regression_detected": {
"action": "log_warning_continue",
"context": "Include regression info in next Gemini diagnosis"
}
}
},
"target_files": [
"Auto-discovered from test failures",
"Extracted from Gemini diagnosis each iteration",
"Format: file:function:lines or file (for new files)"
],
"codex_session": {
"strategy": "resume_for_continuity",
"first_iteration": "codex exec \"fix iteration 1\" --full-auto",
"subsequent_iterations": "codex exec \"fix iteration N\" resume --last",
"benefits": [
"Maintains conversation context across fixes",
"Remembers previous decisions and patterns",
"Ensures consistency in fix approach",
"Reduces redundant context injection"
]
}
}
}
```
### Phase 3: IMPL_PLAN.md Generation
#### Document Structure
```markdown
---
identifier: WFS-test-[session-id]
source_session: WFS-[source-session-id]
workflow_type: test_session
test_framework: jest|pytest|cargo|detected
---
# Test Validation Plan: [Source Session Topic]
## Summary
Execute comprehensive test suite for implementation from session WFS-[source-session-id].
Diagnose and fix all test failures using iterative Gemini analysis and Codex execution.
## Source Session Context
- **Implementation Session**: WFS-[source-session-id]
- **Completed Tasks**: IMPL-001, IMPL-002, ...
- **Changed Files**: [list from git log]
- **Implementation Summaries**: [references to source session summaries]
## Test Framework
- **Detected Framework**: jest|pytest|cargo|other
- **Test Command**: npm test|pytest|cargo test
- **Test Files**: [discovered test files]
- **Coverage**: [estimated test coverage]
## Test-Fix-Retest Cycle
- **Max Iterations**: 5
- **Diagnosis Tool**: Gemini (analysis mode with bug-fix template from bug-index.md)
- **Fix Tool**: Manual (default, meta.use_codex=false) or Codex (if --use-codex flag, meta.use_codex=true)
- **Verification**: Bash test execution + regression check
### Cycle Workflow
1. **Initial Test**: Execute full suite, capture failures
2. **Iterative Fix Loop** (max 5 times):
- Gemini diagnoses failure using bug-fix template → surgical fix suggestion
- Check meta.use_codex flag:
- If false (default): Present fix to user for manual application
- If true (--use-codex): Codex applies fix with resume for context continuity
- Retest and verify (check for regressions)
- Continue until all pass or max iterations reached
3. **Final Validation**: Confirm all tests pass, certify code
### Error Recovery
- **Max iterations reached**: Revert all changes, report failure
- **Test command fails**: Treat as test failure, diagnose with Gemini
- **Codex fails**: Retry once, skip iteration if still failing
- **Regression detected**: Log warning, include in next diagnosis
## Task Breakdown
- **IMPL-001**: Execute and validate tests with iterative fix cycle
## Implementation Strategy
- **Phase 1**: Initial test execution and failure capture
- **Phase 2**: Iterative Gemini diagnosis + Codex fix + retest
- **Phase 3**: Final validation and code certification
## Success Criteria
- All tests pass (100% pass rate)
- No test failures or errors in final run
- Minimal, surgical code changes
- Iteration logs document fix progression
- Code certified APPROVED for deployment
```
### Phase 4: TODO_LIST.md Generation
```markdown
# Tasks: Test Validation for [Source Session]
## Task Progress
- [ ] **IMPL-001**: Execute and validate tests with iterative fix cycle → [📋](./.task/IMPL-001.json)
## Execution Details
- **Source Session**: WFS-[source-session-id]
- **Test Framework**: jest|pytest|cargo
- **Max Iterations**: 5
- **Tools**: Gemini diagnosis + Codex resume fixes
## Status Legend
- `- [ ]` = Pending
- `- [x]` = Completed
```
## Output Files Structure
```
.workflow/WFS-test-[session]/
├── workflow-session.json # Test session metadata
├── IMPL_PLAN.md # Test validation plan
├── TODO_LIST.md # Progress tracking
├── .task/
│ └── IMPL-001.json # Test-fix task with cycle spec
├── .process/
│ ├── ANALYSIS_RESULTS.md # From concept-enhanced (optional)
│ ├── context-package.json # From context-gather
│ ├── initial-test.log # Phase 1: Initial test results
│ ├── fix-iteration-1-diagnosis.md # Gemini diagnosis iteration 1
│ ├── fix-iteration-1-changes.log # Codex changes iteration 1
│ ├── fix-iteration-1-retest.log # Retest results iteration 1
│ ├── fix-iteration-N-*.md/log # Subsequent iterations
│ └── final-test.log # Phase 3: Final validation
└── .summaries/
└── IMPL-001-summary.md # Success report OR failure report
```
## Error Handling
### Input Validation Errors
| Error | Cause | Resolution |
|-------|-------|------------|
| Not a test session | Missing workflow_type: "test_session" | Verify session created by test-gen |
| Source session not found | Invalid source_session_id | Check source session exists |
| No implementation summaries | Source session incomplete | Ensure source session has completed tasks |
### Test Framework Discovery Errors
| Error | Cause | Resolution |
|-------|-------|------------|
| No test command found | Unknown framework | Manual test command specification |
| No test files found | Tests not written | Request user to write tests first |
| Test dependencies missing | Incomplete setup | Run dependency installation |
### Generation Errors
| Error | Cause | Resolution |
|-------|-------|------------|
| Invalid JSON structure | Template error | Fix task generation logic |
| Missing required fields | Incomplete metadata | Validate session metadata |
## Integration & Usage
### Command Chain
- **Called By**: `/workflow:test-gen` (Phase 4)
- **Calls**: None (terminal command)
- **Followed By**: `/workflow:execute` (user-triggered)
### Basic Usage
```bash
# Manual fix mode (default)
/workflow:tools:test-task-generate --session WFS-test-auth
# Automated Codex fix mode
/workflow:tools:test-task-generate --use-codex --session WFS-test-auth
```
### Flag Behavior
- **No flag**: `meta.use_codex=false`, manual fixes presented to user
- **--use-codex**: `meta.use_codex=true`, Codex automatically applies fixes with resume mechanism
## Related Commands
- `/workflow:test-gen` - Creates test session and calls this tool
- `/workflow:tools:context-gather` - Provides cross-session context
- `/workflow:tools:concept-enhanced` - Provides test strategy analysis
- `/workflow:execute` - Executes the generated test-fix task
- `@test-fix-agent` - Agent that executes the iterative test-fix cycle
## Agent Execution Notes
The `@test-fix-agent` will execute the task by following the `flow_control.implementation_approach` specification:
1. **Load task JSON**: Read complete test-fix task from `.task/IMPL-002.json`
2. **Check meta.use_codex**: Determine fix mode (manual or automated)
3. **Execute pre_analysis**: Load source context, discover framework, analyze tests
4. **Phase 1**: Run initial test suite
5. **Phase 2**: If failures, enter iterative loop:
- Use Gemini for diagnosis (analysis mode with bug-fix template)
- Check meta.use_codex flag:
- If false (default): Present fix suggestions to user for manual application
- If true (--use-codex): Use Codex resume for automated fixes (maintains context)
- Retest and check for regressions
- Repeat max 5 times
6. **Phase 3**: Generate summary and certify code
7. **Error Recovery**: Revert changes if max iterations reached
**Bug Diagnosis Template**: Uses bug-fix.md template as referenced in bug-index.md for systematic root cause analysis, code path tracing, and targeted fix recommendations.
**Codex Usage**: The agent uses `codex exec "..." resume --last` pattern ONLY when meta.use_codex=true (--use-codex flag present) to maintain conversation context across multiple fix iterations, ensuring consistency and learning from previous attempts.

View File

@@ -1,10 +1,3 @@
---
name: plan
description: 软件架构规划和技术实现计划分析模板
category: planning
keywords: [规划, 架构, 实现计划, 技术设计, 修改方案]
---
# 软件架构规划模板
# AI Persona & Core Mission

View File

@@ -40,22 +40,22 @@ update_module_claude() {
if [ "$module_path" = "." ]; then
# Root directory
layer="Layer 1 (Root)"
template_path="$HOME/.claude/workflows/cli-templates/prompts/dms/claude-layer1-root.txt"
template_path="$HOME/.claude/workflows/cli-templates/prompts/memory/claude-layer1-root.txt"
analysis_strategy="--all-files"
elif [[ "$clean_path" =~ ^[^/]+$ ]]; then
# Top-level directories (e.g., .claude, src, tests)
layer="Layer 2 (Domain)"
template_path="$HOME/.claude/workflows/cli-templates/prompts/dms/claude-layer2-domain.txt"
template_path="$HOME/.claude/workflows/cli-templates/prompts/memory/claude-layer2-domain.txt"
analysis_strategy="@{*/CLAUDE.md}"
elif [[ "$clean_path" =~ ^[^/]+/[^/]+$ ]]; then
# Second-level directories (e.g., .claude/scripts, src/components)
layer="Layer 3 (Module)"
template_path="$HOME/.claude/workflows/cli-templates/prompts/dms/claude-layer3-module.txt"
template_path="$HOME/.claude/workflows/cli-templates/prompts/memory/claude-layer3-module.txt"
analysis_strategy="@{*/CLAUDE.md}"
else
# Deeper directories (e.g., .claude/workflows/cli-templates/prompts)
layer="Layer 4 (Sub-Module)"
template_path="$HOME/.claude/workflows/cli-templates/prompts/dms/claude-layer4-submodule.txt"
template_path="$HOME/.claude/workflows/cli-templates/prompts/memory/claude-layer4-submodule.txt"
analysis_strategy="--all-files"
fi

7
.claude/version.json Normal file
View File

@@ -0,0 +1,7 @@
{
"version": "3.4.0",
"installation_mode": "Local",
"installation_path": "D:\\Claude_dms3\\.claude",
"source_branch": "main",
"installation_date_utc": "2025-10-04T00:00:00Z"
}

View File

@@ -1,4 +1,4 @@
Analyze project structure for DMS hierarchy optimization:
Analyze project structure for memory hierarchy optimization:
## Required Analysis:
1. Assess project complexity and file organization patterns

View File

@@ -18,6 +18,7 @@ type: strategic-guideline
- **Default to tools** - Use specialized tools for most coding tasks, no matter how small
- **Lower barriers** - Engage tools immediately when encountering any complexity
- **Context optimization** - Based on user intent, determine whether to use `-C [directory]` parameter for focused analysis to reduce irrelevant context import
- **⚠️ Write operation protection** - For local codebase write/modify operations, require EXPLICIT user confirmation unless user provides clear instructions containing MODE=write or MODE=auto
### Quick Decision Rules
1. **Exploring/Understanding?** → Start with Gemini
@@ -27,21 +28,29 @@ type: strategic-guideline
5. **Small task?** → Still use tools - they're faster than manual work
### Core Execution Rules
- **Default Timeout**: Bash commands default execution time = 20 minutes (1200000ms)
- **Apply to All Tools**: All bash() wrapped commands including Gemini, Qwen wrapper and Codex executions use this timeout
- **Command Examples**: `bash(cd target/directory && ~/.claude/scripts/gemini-wrapper -p "prompt")`, `bash(cd target/directory && ~/.claude/scripts/qwen-wrapper -p "prompt")`, `bash(codex -C directory --full-auto exec "task")`
- **Override When Needed**: Specify custom timeout for longer operations
- **Dynamic Timeout (20-120min)**: Allocate execution time based on task complexity
- Simple tasks (analysis, search): 20-40min (1200000-2400000ms)
- Medium tasks (refactoring, documentation): 40-60min (2400000-3600000ms)
- Complex tasks (implementation, migration): 60-120min (3600000-7200000ms)
- **Codex Multiplier**: Codex commands use 1.5x of allocated time
- **Apply to All Tools**: All bash() wrapped commands including Gemini, Qwen wrapper and Codex executions
- **Command Examples**: `bash(~/.claude/scripts/gemini-wrapper -p "prompt")`, `bash(codex -C directory --full-auto exec "task")`
- **Auto-detect**: Analyze PURPOSE and TASK fields to determine appropriate timeout
### Permission Framework
- **Gemini/Qwen Write Access**: Use `--approval-mode yolo` when tools need to create/modify files
- **Codex Write Access**: Always use `-s danger-full-access` and `--skip-git-repo-check` for development and file operations
- **Auto-approval Protocol**: Enable automatic tool approvals for autonomous workflow execution
- **⚠️ WRITE PROTECTION**: Local codebase write/modify requires EXPLICIT user confirmation
- **Analysis Mode (default)**: Read-only, safe for auto-execution
- **Write Mode**: Requires user explicitly states MODE=write or MODE=auto in prompt
- **Exception**: User provides clear instructions like "modify", "create", "implement"
- **Gemini/Qwen Write Access**: Use `--approval-mode yolo` ONLY when MODE=write explicitly specified
- **Codex Write Access**: Use `-s danger-full-access` and `--skip-git-repo-check` ONLY when MODE=auto explicitly specified
- **Default Behavior**: All tools default to analysis/read-only mode without explicit write permission
## 🎯 Universal Command Template
### Standard Format (REQUIRED)
```bash
# Gemini Analysis (全权限)
# Gemini Analysis (read/write capable)
cd [directory] && ~/.claude/scripts/gemini-wrapper -p "
PURPOSE: [clear analysis goal]
TASK: [specific analysis task]
@@ -51,7 +60,7 @@ EXPECTED: [expected output]
RULES: [template reference and constraints]
"
# Qwen Architecture Analysis (仅分析)
# Qwen Architecture Analysis (read-only analysis)
cd [directory] && ~/.claude/scripts/qwen-wrapper -p "
PURPOSE: [clear architecture goal]
TASK: [specific analysis task]
@@ -84,16 +93,18 @@ RULES: [template reference and constraints]
The MODE field controls execution behavior and file permissions:
**For Gemini** (全权限,可读写):
- `analysis` (default) - 分析 + 可生成文档
- `write` - 创建/修改文件(自动启用 --approval-mode yolo
**For Gemini**:
- `analysis` (default) - Read-only analysis and documentation generation
- `write` - ⚠️ Create/modify codebase files (requires explicit specification, auto-enables --approval-mode yolo)
**For Qwen** (仅分析):
- `analysis` (default) - 仅架构分析,不生成代码
**For Qwen**:
- `analysis` (default) - Architecture analysis only, no code generation/modification (read-only)
- `write` - ⚠️ Code generation (requires explicit specification, disabled by default)
**For Codex**:
- `auto` (default) - 自主开发,全文件操作
- `write` - 测试生成和文件修改
- `auto` - ⚠️ Autonomous development with full file operations (requires explicit specification, enables -s danger-full-access)
- `write` - ⚠️ Test generation and file modification (requires explicit specification)
- **Default**: No default mode, MODE must be explicitly specified
### Directory Context
Tools execute in current working directory:
@@ -235,26 +246,34 @@ For every development task:
## 🎯 Key Features
### Gemini (全权限)
### Gemini
- **Command**: `~/.claude/scripts/gemini-wrapper`
- **Strengths**: Large context window, pattern recognition
- **Best For**: Analysis, documentation generation, code exploration
- **Permissions**: 可读写MODE=write 时自动启用 --approval-mode yolo
- **Default MODE**: `analysis`
- **Permissions**: Default read-only analysis, MODE=write requires explicit specification (auto-enables --approval-mode yolo)
- **Default MODE**: `analysis` (read-only)
- **⚠️ Write Trigger**: Only when user explicitly requests "generate documentation", "modify code", or specifies MODE=write
### Qwen (仅分析)
### Qwen
- **Command**: `~/.claude/scripts/qwen-wrapper`
- **Strengths**: Architecture analysis, pattern recognition
- **Best For**: System design analysis, architectural review
- **Permissions**: 仅分析,不生成代码
- **Default MODE**: `analysis`
- **Permissions**: Architecture analysis only, no automatic code generation
- **Default MODE**: `analysis` (read-only)
- **⚠️ Write Trigger**: Explicitly prohibited from auto-calling write mode
### Codex
- **Command**: `codex --full-auto exec`
- **Strengths**: Autonomous development, mathematical reasoning
- **Best For**: Implementation, testing, automation
- **Required**: `-s danger-full-access` and `--skip-git-repo-check` for development
- **Default MODE**: `auto`
- **Permissions**: Requires explicit MODE=auto or MODE=write specification
- **Default MODE**: No default, must be explicitly specified
- **⚠️ Write Trigger**: Only when user explicitly requests "implement", "modify", "generate code" AND specifies MODE
- **Session Management**:
- `codex resume` - Resume previous interactive session (picker by default)
- `codex exec "task" resume --last` - Continue most recent session with new task (maintains context)
- `codex -i <image_file>` - Attach image(s) to initial prompt (useful for UI/design references)
- **Multi-task Pattern**: First task uses `exec`, subsequent tasks use `exec "..." resume --last` for context continuity
### File Patterns
- All files: `@{**/*}`

View File

@@ -6,6 +6,8 @@
## Prompt Structure
### Single-Task Format
**Receive prompts in this format**:
```
@@ -17,11 +19,37 @@ EXPECTED: [deliverables]
RULES: [constraints and templates]
```
### Multi-Task Format (Subtask Execution)
**First subtask** (creates new session):
```
PURPOSE: [overall goal]
TASK: [subtask 1 description]
MODE: auto
CONTEXT: [file patterns]
EXPECTED: [subtask deliverables]
RULES: [constraints]
Subtask 1 of N: [subtask title]
```
**Subsequent subtasks** (continues via `resume --last`):
```
CONTINUE TO NEXT SUBTASK:
Subtask N of M: [subtask title]
PURPOSE: [continuation goal]
TASK: [subtask N description]
CONTEXT: Previous work completed, now focus on [new files]
EXPECTED: [subtask deliverables]
RULES: Build on previous subtask, maintain consistency
```
## Execution Requirements
### ALWAYS
- **Parse all six fields** - Understand PURPOSE, TASK, MODE, CONTEXT, EXPECTED, RULES
- **Parse all fields** - Understand PURPOSE, TASK, MODE, CONTEXT, EXPECTED, RULES
- **Detect subtask format** - Check for "Subtask N of M" or "CONTINUE TO NEXT SUBTASK"
- **Follow MODE strictly** - Respect execution boundaries
- **Study CONTEXT files** - Find 3+ similar patterns before implementing
- **Apply RULES** - Follow templates and constraints exactly
@@ -29,6 +57,7 @@ RULES: [constraints and templates]
- **Commit incrementally** - Small, working commits
- **Match project style** - Follow existing patterns exactly
- **Validate EXPECTED** - Ensure all deliverables are met
- **Report context** (subtasks) - Summarize key info for next subtask
### NEVER
@@ -49,7 +78,7 @@ RULES: [constraints and templates]
- Run tests and builds
- Commit code incrementally
**Execute**:
**Execute (Single Task)**:
1. Parse PURPOSE and TASK
2. Analyze CONTEXT files - find 3+ similar patterns
3. Plan implementation approach
@@ -60,7 +89,17 @@ RULES: [constraints and templates]
8. Validate all EXPECTED deliverables
9. Report results
**Use For**: Feature implementation, bug fixes, refactoring
**Execute (Multi-Task/Subtask)**:
1. **First subtask**: Follow single-task flow above
2. **Subsequent subtasks** (via `resume --last`):
- Recall context from previous subtask(s)
- Build on previous work (don't repeat)
- Maintain consistency with previous decisions
- Focus on current subtask scope only
- Test integration with previous subtasks
- Report subtask completion status
**Use For**: Feature implementation, bug fixes, refactoring, multi-step tasks
### MODE: write
@@ -119,7 +158,7 @@ RULES: [constraints and templates]
## Progress Reporting
### During Execution
### During Execution (Single Task)
```
[1/5] Analyzing existing code patterns...
@@ -129,7 +168,17 @@ RULES: [constraints and templates]
[5/5] Running validation...
```
### On Success
### During Execution (Subtask)
```
[Subtask N/M: Subtask Title]
[1/4] Recalling context from previous subtasks...
[2/4] Implementing current subtask...
[3/4] Testing integration with previous work...
[4/4] Validating subtask completion...
```
### On Success (Single Task)
```
✅ Task completed
@@ -146,6 +195,26 @@ Validation:
Next Steps: [recommendations]
```
### On Success (Subtask)
```
✅ Subtask N/M completed
Changes:
- Created: [files]
- Modified: [files]
Integration:
✅ Compatible with previous subtasks
✅ Tests: [count] passing
✅ Build: Success
Context for next subtask:
- [Key decisions made]
- [Files created/modified]
- [Patterns established]
```
### On Partial Completion
```
@@ -178,6 +247,60 @@ Recommendation: [next steps]
- Graceful degradation
- Don't expose sensitive info
## Multi-Step Task Execution
### Context Continuity via Resume
When executing subtasks via `codex exec "..." resume --last`:
**Advantages**:
- Session memory preserves previous decisions
- Maintains implementation style consistency
- Avoids redundant context re-injection
- Enables incremental testing and validation
**Best Practices**:
1. **First subtask**: Establish patterns and architecture
2. **Subsequent subtasks**: Build on established patterns
3. **Test integration**: After each subtask, verify compatibility
4. **Report context**: Summarize key decisions for next subtask
5. **Maintain scope**: Focus only on current subtask goals
### Subtask Coordination
**DO**:
- Remember decisions from previous subtasks
- Reuse patterns established earlier
- Test integration with previous work
- Report what's ready for next subtask
**DON'T**:
- Re-implement what previous subtasks completed
- Change patterns established earlier (unless explicitly requested)
- Skip testing integration points
- Assume next subtask's requirements
### Example Flow
```
Subtask 1: Create data models
→ Establishes: Schema patterns, validation approach
→ Delivers: Models with tests
→ Context for next: Model structure, validation rules
Subtask 2: Implement API endpoints (resume --last)
→ Recalls: Model structure from subtask 1
→ Builds on: Uses established models
→ Delivers: API with integration tests
→ Context for next: API patterns, error handling
Subtask 3: Add authentication (resume --last)
→ Recalls: API patterns from subtask 2
→ Integrates: Auth middleware into existing endpoints
→ Delivers: Secured API
→ Final validation: Full integration test
```
## Philosophy
- **Incremental progress over big bangs** - Small, testable changes
@@ -186,6 +309,7 @@ Recommendation: [next steps]
- **Clear intent over clever code** - Boring, obvious solutions
- **Simple over complex** - Avoid over-engineering
- **Follow existing style** - Match project patterns exactly
- **Context continuity** - Leverage resume for multi-step consistency
## Execution Checklist
@@ -211,5 +335,6 @@ Recommendation: [next steps]
---
**Version**: 2.0.0
**Last Updated**: 2025-10-02
**Version**: 2.1.0
**Last Updated**: 2025-10-04
**Changes**: Added multi-step task execution support with resume mechanism

3
.gitignore vendored
View File

@@ -17,4 +17,5 @@ yarn-error.log*
Thumbs.db
.env
settings.local.json
settings.local.json
.workflow

View File

@@ -5,6 +5,241 @@ 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.3.0] - 2025-10-04
### 🚀 CLI Tool Enhancements & Codex Multi-Step Execution
This release streamlines CLI tool documentation and introduces automated multi-step task execution with Codex.
#### Added
**New Command: `/cli:codex-execute`**:
- **Purpose**: Automated task decomposition and sequential execution with Codex
- **Features**:
- Automatic task breakdown into 3-8 manageable subtasks
- Sequential execution using `codex exec "..." resume --last` mechanism
- TodoWrite progress tracking for each subtask
- Optional Git verification after each subtask (`--verify-git` flag)
- Supports both freeform descriptions and workflow task IDs
- Automatic detection and loading of task JSON files
- Context continuity across subtasks via resume mechanism
- Integration with workflow system (optional)
**Codex Resume Mechanism**:
- **First Subtask**: Creates new Codex session with `codex exec`
- **Subsequent Subtasks**: Continues with `codex exec "..." resume --last`
- **Benefits**:
- Session memory preserves previous decisions
- Maintains implementation style consistency
- Avoids redundant context re-injection
- Enables incremental testing and validation
**Enhanced Codex Agent Configuration** (`.codex/AGENTS.md`):
- Added multi-task prompt format (Single-Task & Multi-Task)
- Enhanced MODE: auto with subtask execution flow
- New "Multi-Step Task Execution" section with:
- Context continuity best practices
- Subtask coordination guidelines
- Example 3-subtask workflow demonstration
- Updated progress reporting for subtasks
- Version 2.1.0 with multi-step task execution support
#### Changed
**CLI Documentation Optimization**:
- **Streamlined Documentation**: Reduced redundancy by referencing `intelligent-tools-strategy.md`
- **Updated Commands**:
- `/cli:analyze` - Simplified from ~200 to ~78 lines
- `/cli:chat` - Simplified from ~161 to ~92 lines
- `/cli:execute` - Simplified from ~235 to ~111 lines
- **Unified Command Templates**:
- Separated Gemini/Qwen (uses `-p` parameter) from Codex (uses `exec` command)
- Added Codex `-i` parameter documentation for image attachment
- Consistent template structure across all CLI commands
**Intelligent Tools Strategy Updates**:
- Enhanced Codex session management documentation
- Added `codex exec "..." resume --last` syntax explanation
- Documented multi-task execution pattern
- Clarified image attachment workflow with resume
**Command Template Improvements**:
- **Gemini/Qwen**: `cd [dir] && ~/.claude/scripts/[tool]-wrapper -p "..."`
- **Codex**: `codex -C [dir] --full-auto exec "..." --skip-git-repo-check -s danger-full-access`
- **Codex with Resume**: `codex exec "..." resume --last --skip-git-repo-check -s danger-full-access`
- **Image Support**: `codex -C [dir] -i image.png --full-auto exec "..."`
#### Technical Details
**Multi-Step Execution Flow**:
```
Input → Parse (Description/Task ID) → Decompose into Subtasks → TodoWrite Tracking →
For Each Subtask:
1. Execute with Codex (first: exec, subsequent: exec resume --last)
2. [Optional] Git verification
3. Mark complete in TodoWrite
→ Final Summary
```
**Subtask Decomposition Criteria**:
- Each subtask: 5-15 minutes completable
- Clear, testable outcomes
- Explicit dependencies
- Focused file scope (1-5 files per subtask)
**Error Handling**:
- Subtask failure: Pause for user intervention
- Git verification failure: Request user decision
- Codex session lost: Attempt retry with fresh session
**Integration Features**:
- Automatic task ID detection (e.g., `IMPL-001`, `TASK-123`)
- JSON task loading from `.task/[ID].json`
- Execution logging to `.chat/codex-execute-[timestamp].md`
- Summary generation to `.summaries/[TASK-ID]-summary.md`
#### Benefits
**Developer Experience**:
- 🚀 Automated task breakdown reduces planning overhead
- 📊 Clear progress tracking with TodoWrite integration
- 🔄 Context continuity improves code consistency
- ✅ Optional Git verification ensures code quality
- 🎯 Focused subtask execution reduces complexity
**Code Quality**:
- 🧪 Incremental testing after each subtask
- 🔍 Git verification catches unexpected changes
- 📝 Comprehensive execution logs for audit trail
- 🎨 Image attachment support for UI/design tasks
**Documentation**:
- 📚 Reduced documentation redundancy by ~60%
- 🔗 Clear references to master documentation
- ✨ Consistent command structure across all CLI tools
- 📖 Better separation of concerns (strategy vs. command docs)
---
## [3.2.3] - 2025-10-03
### ✨ Version Management System
This release introduces a comprehensive version management and upgrade notification system.
#### Added
**New Command: `/version`**:
- **Purpose**: Display version information and check for updates from GitHub
- **Features**:
- Shows local and global installation versions
- Fetches latest stable release from GitHub API
- Displays latest development commit from main branch
- Compares installed versions with remote versions
- Provides upgrade recommendations with installation commands
- Supports both stable and development version tracking
**Version Information Display**:
- **Local Version**: Shows project-specific installation (if exists)
- **Global Version**: Shows `~/.claude` installation with tracking mode
- **Latest Stable**: Displays latest release tag, name, and publish date
- **Latest Dev**: Shows latest commit hash, message, and date
- **Status Assessment**: Automatic version comparison and upgrade suggestions
**Version Tracking Files**:
- **`.claude/version.json`**: Local project version tracking
- **`~/.claude/version.json`**: Global installation version tracking
- **Fields**:
- `version`: Version number or "latest" for main branch tracking
- `installation_mode`: "Local" or "Global"
- `installation_path`: Installation directory
- `source_branch`: Source branch (usually "main")
- `installation_date_utc`: ISO 8601 timestamp
**GitHub API Integration**:
- **Latest Release**: `https://api.github.com/repos/catlog22/Claude-Code-Workflow/releases/latest`
- Extracts: `tag_name`, `name`, `published_at`
- **Latest Commit**: `https://api.github.com/repos/catlog22/Claude-Code-Workflow/commits/main`
- Extracts: `sha`, `commit.message`, `commit.author.date`
- **Timeout**: 30-second timeout for slow connections
- **Error Handling**: Graceful fallback for network errors
**Command Output Scenarios**:
1. **Up to date**:
```
✅ You are on the latest stable version (3.2.3)
```
2. **Upgrade available**:
```
⬆️ A newer stable version is available: v3.2.3
Your version: 3.2.2
To upgrade:
PowerShell: iex (iwr -useb https://raw.githubusercontent.com/catlog22/Claude-Code-Workflow/main/install-remote.ps1)
Bash: bash <(curl -fsSL https://raw.githubusercontent.com/catlog22/Claude-Code-Workflow/main/install-remote.sh)
```
3. **Development version**:
```
✨ You are running a development version (3.3.0-dev)
This is newer than the latest stable release (v3.2.3)
```
#### Changed
**Documentation Updates**:
- Added `/version` command reference to README.md
- Added version management documentation to README_CN.md
- Created comprehensive `.claude/commands/version.md` implementation guide
- Updated command tables with version management examples
**Installation Scripts Enhancement**:
- Installation scripts now create `version.json` files automatically
- Track installation mode (local vs global)
- Record installation timestamp
- Support version tracking for both stable and development installations
#### Technical Details
**Implementation**:
- Uses simple bash commands (no jq dependency required)
- Fallback to grep/sed for JSON parsing
- Network calls with curl and error suppression
- Version comparison using `sort -V` for semantic versioning
- Cross-platform compatible (Windows Git Bash, Linux, macOS)
**Command Structure**:
```bash
/version # Display version and check for updates
```
**No parameters required** - command automatically:
1. Checks local version file (`./.claude/version.json`)
2. Checks global version file (`~/.claude/version.json`)
3. Fetches latest release from GitHub
4. Fetches latest commit from main branch
5. Compares versions and provides recommendations
#### Benefits
**User Experience**:
- 🔍 Quick version check with single command
- 📊 Comprehensive version information display
- 🔄 Automatic upgrade notifications
- 📈 Development version tracking support
- 🌐 GitHub API integration for latest updates
**DevOps**:
- 📁 Version tracking in both local and global installations
- 🕐 Installation timestamp for audit trails
- 🔀 Support for both stable and development branches
- ⚡ Fast execution with 30-second network timeout
- 🛡️ Graceful error handling for offline scenarios
---
## [3.2.0] - 2025-10-02
### 🔄 Test-Fix Workflow & Agent Architecture Simplification

View File

@@ -19,12 +19,16 @@ For all CLI tool usage, command syntax, and integration guidelines:
### Core Beliefs
- **Pursue good taste** - Eliminate edge cases to make code logic natural and elegant
- **Embrace extreme simplicity** - Complexity is the root of all evil
- **Be pragmatic** - Code must solve real-world problems, not hypothetical ones
- **Data structures first** - Bad programmers worry about code; good programmers worry about data structures
- **Never break backward compatibility** - Existing functionality is sacred and inviolable
- **Incremental progress over big bangs** - Small changes that compile and pass tests
- **Learning from existing code** - Study and plan before implementing
- **Pragmatic over dogmatic** - Adapt to project reality
- **Clear intent over clever code** - Be boring and obvious
- **Simple solutions over complex architectures** - Avoid over-engineering and premature optimization
- **Follow existing code style** - Match import patterns, naming conventions, and formatting of existing codebase
- **No unsolicited reports** - Task summaries can be performed internally, but NEVER generate additional reports, documentation files, or summary files without explicit user permission
### Simplicity Means
@@ -53,6 +57,7 @@ For all CLI tool usage, command syntax, and integration guidelines:
**NEVER**:
- Make assumptions - verify with existing code
- Generate reports, summaries, or documentation files without explicit user request
**ALWAYS**:
- Plan complex tasks thoroughly before implementation

View File

@@ -186,7 +186,7 @@ cd Dmsflow
.\Install-Claude.ps1 -Global
# 4. Start using Claude Code with Agent workflows!
# Use /workflow commands and DMS system for development
# Use /workflow commands and memory system for development
```
## Verification
@@ -207,7 +207,7 @@ After installation, verify:
- Check that global `.claude` directory is recognized
- Verify workflow commands and DMS commands are available
- Test `/workflow` commands for agent coordination
- Test `/dmsflow version` to check version information
- Test `/workflow version` to check version information
## Troubleshooting

View File

@@ -162,7 +162,7 @@ cd Dmsflow
.\Install-Claude.ps1 -Global
# 4. 开始使用 Claude Code Agent 工作流!
# 使用 /workflow 命令和 DMS 系统进行开发
# 使用 /workflow 命令和内存系统进行开发
```
## 验证
@@ -181,9 +181,9 @@ cd Dmsflow
2. **测试 Claude Code**
- 在项目中打开 Claude Code
- 检查全局 `.claude` 目录是否被识别
- 验证工作流命令和 DMS 命令是否可用
- 验证工作流命令和内存命令是否可用
- 测试 `/workflow` 命令的 Agent 协调功能
- 测试 `/dmsflow version` 检查版本信息
- 测试 `/workflow version` 检查版本信息
## 故障排除

View File

@@ -59,7 +59,11 @@ param(
[switch]$BackupAll,
[switch]$NoBackup
[switch]$NoBackup,
[string]$SourceVersion = "",
[string]$SourceBranch = ""
)
# Set encoding for proper Unicode support
@@ -622,6 +626,37 @@ function Merge-DirectoryContents {
return $true
}
function Create-VersionJson {
param(
[string]$TargetClaudeDir,
[string]$InstallationMode
)
# Determine version from source or default
$versionNumber = if ($SourceVersion) { $SourceVersion } else { $Version }
$sourceBranch = if ($SourceBranch) { $SourceBranch } else { "unknown" }
# Create version.json content
$versionInfo = @{
version = $versionNumber
installation_mode = $InstallationMode
installation_path = $TargetClaudeDir
installation_date_utc = (Get-Date).ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ssZ")
source_branch = $sourceBranch
}
$versionJsonPath = Join-Path $TargetClaudeDir "version.json"
try {
$versionInfo | ConvertTo-Json | Out-File -FilePath $versionJsonPath -Encoding utf8 -Force
Write-ColorOutput "Created version.json: $versionNumber ($InstallationMode)" $ColorSuccess
return $true
} catch {
Write-ColorOutput "WARNING: Failed to create version.json: $($_.Exception.Message)" $ColorWarning
return $false
}
}
function Install-Global {
Write-ColorOutput "Installing Claude Code Workflow System globally..." $ColorInfo
@@ -682,6 +717,10 @@ function Install-Global {
Write-ColorOutput "Merging .gemini directory contents..." $ColorInfo
$geminiMerged = Merge-DirectoryContents -Source $sourceGeminiDir -Destination $globalGeminiDir -Description ".gemini directory contents" -BackupFolder $backupFolder
# Create version.json in global .claude directory
Write-ColorOutput "Creating version.json..." $ColorInfo
Create-VersionJson -TargetClaudeDir $globalClaudeDir -InstallationMode "Global"
if ($backupFolder -and (Test-Path $backupFolder)) {
$backupFiles = Get-ChildItem $backupFolder -Recurse -File -ErrorAction SilentlyContinue
if (-not $backupFiles -or ($backupFiles | Measure-Object).Count -eq 0) {
@@ -819,6 +858,14 @@ function Install-Path {
Write-ColorOutput "Merging .gemini directory contents to local location..." $ColorInfo
$geminiMerged = Merge-DirectoryContents -Source $sourceGeminiDir -Destination $localGeminiDir -Description ".gemini directory contents" -BackupFolder $backupFolder
# Create version.json in local .claude directory
Write-ColorOutput "Creating version.json in local directory..." $ColorInfo
Create-VersionJson -TargetClaudeDir $localClaudeDir -InstallationMode "Path"
# Also create version.json in global .claude directory
Write-ColorOutput "Creating version.json in global directory..." $ColorInfo
Create-VersionJson -TargetClaudeDir $globalClaudeDir -InstallationMode "Global"
if ($backupFolder -and (Test-Path $backupFolder)) {
$backupFiles = Get-ChildItem $backupFolder -Recurse -File -ErrorAction SilentlyContinue
if (-not $backupFiles -or ($backupFiles | Measure-Object).Count -eq 0) {

View File

@@ -87,8 +87,8 @@ function show_header() {
function test_prerequisites() {
# Test bash version
if [ "${BASH_VERSINFO[0]}" -lt 4 ]; then
write_color "ERROR: Bash 4.0 or higher is required" "$COLOR_ERROR"
if [ "${BASH_VERSINFO[0]}" -lt 2 ]; then
write_color "ERROR: Bash 2.0 or higher is required" "$COLOR_ERROR"
write_color "Current version: ${BASH_VERSION}" "$COLOR_ERROR"
return 1
fi

246
README.md
View File

@@ -2,7 +2,7 @@
<div align="center">
[![Version](https://img.shields.io/badge/version-v3.2.1-blue.svg)](https://github.com/catlog22/Claude-Code-Workflow/releases)
[![Version](https://img.shields.io/badge/version-v3.4.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,13 +15,15 @@
**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.2.0** - Simplified agent architecture with "Tests Are the Review" philosophy. See [CHANGELOG.md](CHANGELOG.md) for details.
> **🎉 Latest: v3.4.0** - TDD workflow optimization & test generation enhancements. See [CHANGELOG.md](CHANGELOG.md) for details.
>
> **What's New in v3.2.0**:
> - 🔄 Simplified from 3 agents to 2 core agents (`@code-developer`, `@test-fix-agent`)
> - ✅ "Tests Are the Review" - Passing tests = approved code
> - 🧪 Enhanced test-fix workflow with automatic execution and fixing
> - 📦 Interactive installation with version selection menu
> **What's New in v3.4.0**:
> - 🧪 **TDD Workflow Streamlining**: Unified IMPL_PLAN.md structure, 33% reduction in redundant files
> - 🔄 **Test Coverage Analysis**: TDD workflow upgraded to 6 phases with Phase 3 test context gathering
> - 🔁 **Iterative Green Phase**: Built-in test-fix-cycle in IMPL tasks with Gemini auto-diagnosis
> - 🛠️ **Manual-First Fixes**: Gemini + bug-fix template diagnosis by default, optional `--use-codex` automation
> - ✅ **Test-Gen Workflow Enhancement**: Added 3 supporting tool commands for complete test generation flow
> - ⏱️ **Dynamic Timeout Allocation**: CLI tools default to 20-120min for large-scale analysis
---
@@ -94,17 +96,143 @@ Select version to install (1-3, default: 1):
> 💡 **Pro Tip**: The installer automatically detects and displays the latest version numbers and release dates from GitHub. Just press Enter to select the recommended stable release.
### **📦 Local Installation (Install-Claude.ps1)**
For local installation without network access, use the bundled PowerShell installer:
**Installation Modes:**
```powershell
# Interactive mode with prompts (recommended)
.\Install-Claude.ps1
# Quick install with automatic backup
.\Install-Claude.ps1 -Force -BackupAll
# Non-interactive install
.\Install-Claude.ps1 -NonInteractive -Force
```
**Installation Options:**
| Mode | Description | Installs To |
|------|-------------|-------------|
| **Global** | System-wide installation (default) | `~/.claude/`, `~/.codex/`, `~/.gemini/` |
| **Path** | Custom directory + global hybrid | Local: `agents/`, `commands/`<br>Global: `workflows/`, `scripts/` |
**Backup Behavior:**
- **Default**: Automatic backup enabled (`-BackupAll`)
- **Disable**: Use `-NoBackup` flag (⚠️ overwrites without backup)
- **Backup location**: `claude-backup-{timestamp}/` in installation directory
**⚠️ Important Warnings:**
- `-Force -BackupAll`: Silent file overwrite (with backup)
- `-NoBackup -Force`: Permanent file overwrite (no recovery)
- Global mode modifies user profile directories
### **✅ Verify Installation**
After installation, run the following command to ensure CCW is working:
```bash
/workflow:session:list
```
> **📝 Important Notes:**
> **📝 Installation Notes:**
> - The installer will automatically install/update `.codex/` and `.gemini/` directories
> - **Global mode**: Installs to `~/.codex` and `~/.gemini`
> - **Path mode**: Installs to your specified directory (e.g., `project/.codex`, `project/.gemini`)
> - Existing files will be backed up automatically before installation
> - **Backup**: Existing files are backed up by default to `claude-backup-{timestamp}/`
> - **Safety**: Use interactive mode for first-time installation to review changes
---
## ⚙️ Configuration
### **Prerequisites: Required Tools**
Before using CCW, install the following command-line tools:
#### **Core CLI Tools**
| Tool | Purpose | Installation |
|------|---------|--------------|
| **Gemini CLI** | AI analysis & documentation | `npm install -g @google/gemini-cli` ([GitHub](https://github.com/google-gemini/gemini-cli)) |
| **Codex CLI** | AI development & implementation | `npm install -g @openai/codex` ([GitHub](https://github.com/openai/codex)) |
| **Qwen Code** | AI architecture & code generation | `npm install -g @qwen-code/qwen-code` ([Docs](https://github.com/QwenLM/qwen-code)) |
#### **System Utilities**
| Tool | Purpose | Installation |
|------|---------|--------------|
| **ripgrep (rg)** | Fast code search | [Download](https://github.com/BurntSushi/ripgrep/releases) or `brew install ripgrep` (macOS), `apt install ripgrep` (Ubuntu) |
| **jq** | JSON processing | [Download](https://jqlang.github.io/jq/download/) or `brew install jq` (macOS), `apt install jq` (Ubuntu) |
**Quick Install (All Tools):**
```bash
# macOS
brew install ripgrep jq
npm install -g @google/gemini-cli @openai/codex @qwen-code/qwen-code
# Ubuntu/Debian
sudo apt install ripgrep jq
npm install -g @google/gemini-cli @openai/codex @qwen-code/qwen-code
# Windows (Chocolatey)
choco install ripgrep jq
npm install -g @google/gemini-cli @openai/codex @qwen-code/qwen-code
```
### **Essential: Gemini CLI Setup**
Configure Gemini CLI for optimal integration:
```json
// ~/.gemini/settings.json
{
"contextFileName": ["CLAUDE.md", "GEMINI.md"]
}
```
### **Recommended: .geminiignore**
Optimize performance by excluding unnecessary files:
```bash
# .geminiignore (in project root)
/dist/
/build/
/node_modules/
/.next/
*.tmp
*.log
/temp/
# Include important docs
!README.md
!**/CLAUDE.md
```
### **Recommended: MCP Tools** *(Enhanced Analysis)*
MCP (Model Context Protocol) tools provide advanced codebase analysis. **Recommended installation** - While CCW has fallback mechanisms, not installing MCP tools may lead to unexpected behavior or degraded performance in some workflows.
#### Available MCP Servers
| MCP Server | Purpose | Installation Guide |
|------------|---------|-------------------|
| **Exa MCP** | External API patterns & best practices | [Install Guide](https://smithery.ai/server/exa) |
| **Code Index MCP** | Advanced internal code search | [Install Guide](https://github.com/johnhuang316/code-index-mcp) |
#### Benefits When Enabled
- 📊 **Faster Analysis**: Direct codebase indexing vs manual searching
- 🌐 **External Context**: Real-world API patterns and examples
- 🔍 **Advanced Search**: Pattern matching and similarity detection
-**Better Reliability**: Primary tools for certain workflows
⚠️ **Note**: Some workflows expect MCP tools to be available. Without them, you may experience:
- Slower code analysis and search operations
- Reduced context quality in some scenarios
- Fallback to less efficient traditional tools
- Potential unexpected behavior in advanced workflows
---
@@ -142,9 +270,9 @@ After installation, run the following command to ensure CCW is working:
**Phase 4: Testing & Quality Assurance**
```bash
# Generate comprehensive test suite (standard workflow)
/workflow:test-gen
/workflow:execute
# Generate independent test-fix workflow (v3.2.2+)
/workflow:test-gen WFS-auth # Creates WFS-test-auth session
/workflow:execute # Runs test validation
# OR verify TDD compliance (TDD workflow)
/workflow:tdd-verify
@@ -214,12 +342,15 @@ 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:tdd-plan` | Create TDD workflow (6 phases) with test coverage analysis and 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:test-gen [--use-codex] <session>` | Create test generation workflow with auto-diagnosis and fix cycle for completed implementations. |
| `/workflow:tdd-verify` | Verify TDD compliance and generate quality report. |
| `/workflow:review` | **Optional** manual review (only use when explicitly needed - passing tests = approved code). |
| `/workflow:tools:test-context-gather` | Analyze test coverage and identify missing test files. |
| `/workflow:tools:test-concept-enhanced` | Generate test strategy and requirements analysis using Gemini. |
| `/workflow:tools:test-task-generate` | Generate test task JSON with test-fix-cycle specification. |
### **Task & Memory Commands**
@@ -228,92 +359,7 @@ After installation, run the following command to ensure CCW is working:
| `/task:*` | Manage individual tasks (`create`, `breakdown`, `execute`, `replan`). |
| `/update-memory-full` | Re-index the entire project documentation. |
| `/update-memory-related` | Update documentation related to recent changes. |
---
## ⚙️ Configuration
### **Prerequisites: Required Tools**
Before using CCW, install the following command-line tools:
#### **Core CLI Tools**
| Tool | Purpose | Installation |
|------|---------|--------------|
| **Gemini CLI** | AI analysis & documentation | `npm install -g @google/gemini-cli` ([GitHub](https://github.com/google-gemini/gemini-cli)) |
| **Codex CLI** | AI development & implementation | `npm install -g @openai/codex` ([GitHub](https://github.com/openai/codex)) |
| **Qwen Code** | AI architecture & code generation | `npm install -g @qwen-code/qwen-code` ([Docs](https://github.com/QwenLM/qwen-code)) |
#### **System Utilities**
| Tool | Purpose | Installation |
|------|---------|--------------|
| **ripgrep (rg)** | Fast code search | [Download](https://github.com/BurntSushi/ripgrep/releases) or `brew install ripgrep` (macOS), `apt install ripgrep` (Ubuntu) |
| **jq** | JSON processing | [Download](https://jqlang.github.io/jq/download/) or `brew install jq` (macOS), `apt install jq` (Ubuntu) |
**Quick Install (All Tools):**
```bash
# macOS
brew install ripgrep jq
npm install -g @google/gemini-cli @openai/codex @qwen-code/qwen-code
# Ubuntu/Debian
sudo apt install ripgrep jq
npm install -g @google/gemini-cli @openai/codex @qwen-code/qwen-code
# Windows (Chocolatey)
choco install ripgrep jq
npm install -g @google/gemini-cli @openai/codex @qwen-code/qwen-code
```
### **Essential: Gemini CLI Setup**
Configure Gemini CLI for optimal integration:
```json
// ~/.gemini/settings.json
{
"contextFileName": "CLAUDE.md"
}
```
### **Recommended: .geminiignore**
Optimize performance by excluding unnecessary files:
```bash
# .geminiignore (in project root)
/dist/
/build/
/node_modules/
/.next/
*.tmp
*.log
/temp/
# Include important docs
!README.md
!**/CLAUDE.md
```
### **Optional: MCP Tools** *(Enhanced Analysis)*
MCP (Model Context Protocol) tools provide advanced codebase analysis. **Completely optional** - CCW works perfectly without them.
#### Available MCP Servers
| MCP Server | Purpose | Installation Guide |
|------------|---------|-------------------|
| **Exa MCP** | External API patterns & best practices | [Install Guide](https://github.com/exa-labs/exa-mcp-server) |
| **Code Index MCP** | Advanced internal code search | [Install Guide](https://github.com/johnhuang316/code-index-mcp) |
#### Benefits When Enabled
- 📊 **Faster Analysis**: Direct codebase indexing vs manual searching
- 🌐 **External Context**: Real-world API patterns and examples
- 🔍 **Advanced Search**: Pattern matching and similarity detection
-**Automatic Fallback**: Uses traditional tools when MCP unavailable
| `/version` | Display version information and check for updates from GitHub. |
---

View File

@@ -2,7 +2,7 @@
<div align="center">
[![Version](https://img.shields.io/badge/version-v3.2.1-blue.svg)](https://github.com/catlog22/Claude-Code-Workflow/releases)
[![Version](https://img.shields.io/badge/version-v3.4.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,13 +15,15 @@
**Claude Code Workflow (CCW)** 是一个新一代的多智能体自动化开发框架,通过智能工作流管理和自主执行来协调复杂的软件开发任务。
> **🎉 最新版本: v3.2.0** - 采用"测试即审查"理念简化智能体架构。详见 [CHANGELOG.md](CHANGELOG.md)。
> **🎉 最新版本: v3.4.0** - TDD 工作流优化与测试生成增强。详见 [CHANGELOG.md](CHANGELOG.md)。
>
> **v3.2.0 版本新特性**:
> - 🔄 从 3 个智能体简化为 2 个核心智能体(`@code-developer`、`@test-fix-agent`
> - ✅ "测试即审查" - 测试通过 = 代码批准
> - 🧪 增强的测试修复工作流,支持自动执行和修复
> - 📦 交互式安装,包含版本选择菜单
> **v3.4.0 版本新特性**:
> - 🧪 **TDD 工作流优化**: 精简文件结构,统一使用 IMPL_PLAN.md减少 33% 冗余文件
> - 🔄 **测试覆盖分析**: TDD 工作流升级至 6 阶段,新增 Phase 3 测试上下文收集
> - 🔁 **迭代 Green Phase**: IMPL 任务内置 test-fix-cycle支持 Gemini 自动诊断和修复
> - 🛠️ **手动优先修复**: 默认使用 Gemini + bug-fix 模板诊断,可选 `--use-codex` 自动化
> - ✅ **test-gen 工作流增强**: 新增 3 个配套工具命令,完整测试生成和修复流程
> - ⏱️ **动态超时分配**: CLI 工具默认 20-120 分钟超时,适应大型项目分析
---
@@ -94,17 +96,143 @@ bash <(curl -fsSL https://raw.githubusercontent.com/catlog22/Claude-Code-Workflo
> 💡 **提示**:安装程序会自动从 GitHub 检测并显示最新的版本号和发布日期。只需按 Enter 键即可选择推荐的稳定版本。
### **📦 本地安装 (Install-Claude.ps1)**
无需网络访问时,使用内置的 PowerShell 安装脚本:
**安装模式:**
```powershell
# 交互式安装(推荐)
.\Install-Claude.ps1
# 快速安装(自动备份)
.\Install-Claude.ps1 -Force -BackupAll
# 非交互式安装
.\Install-Claude.ps1 -NonInteractive -Force
```
**安装选项:**
| 模式 | 描述 | 安装位置 |
|------|------|----------|
| **Global** | 系统级安装(默认) | `~/.claude/``~/.codex/``~/.gemini/` |
| **Path** | 自定义目录 + 全局混合 | 本地:`agents/``commands/`<br>全局:`workflows/``scripts/` |
**备份行为:**
- **默认**:自动备份启用(`-BackupAll`
- **禁用**:使用 `-NoBackup` 标志(⚠️ 无备份覆盖)
- **备份位置**:安装目录中的 `claude-backup-{timestamp}/`
**⚠️ 重要警告:**
- `-Force -BackupAll`:静默文件覆盖(带备份)
- `-NoBackup -Force`:永久文件覆盖(无法恢复)
- Global 模式会修改用户配置目录
### **✅ 验证安装**
安装后,运行以下命令以确保 CCW 正常工作:
```bash
/workflow:session:list
```
> **📝 重要说明:**
> **📝 安装说明:**
> - 安装程序将自动安装/更新 `.codex/` 和 `.gemini/` 目录
> - **全局模式**:安装到 `~/.codex` 和 `~/.gemini`
> - **路径模式**:安装到指定目录(例如 `project/.codex`、`project/.gemini`
> - 安装前会自动备份现有文件
> - **备份**:默认自动备份现有文件到 `claude-backup-{timestamp}/`
> - **安全**:首次安装建议使用交互式模式以审查更改
---
## ⚙️ 配置
### **前置要求:必需工具**
在使用 CCW 之前,请安装以下命令行工具:
#### **核心 CLI 工具**
| 工具 | 用途 | 安装方式 |
|------|------|----------|
| **Gemini CLI** | AI 分析与文档生成 | `npm install -g @google/gemini-cli` ([GitHub](https://github.com/google-gemini/gemini-cli)) |
| **Codex CLI** | AI 开发与实现 | `npm install -g @openai/codex` ([GitHub](https://github.com/openai/codex)) |
| **Qwen Code** | AI 架构与代码生成 | `npm install -g @qwen-code/qwen-code` ([文档](https://github.com/QwenLM/qwen-code)) |
#### **系统实用工具**
| 工具 | 用途 | 安装方式 |
|------|------|----------|
| **ripgrep (rg)** | 快速代码搜索 | [下载](https://github.com/BurntSushi/ripgrep/releases) 或 `brew install ripgrep` (macOS), `apt install ripgrep` (Ubuntu) |
| **jq** | JSON 处理 | [下载](https://jqlang.github.io/jq/download/) 或 `brew install jq` (macOS), `apt install jq` (Ubuntu) |
**快速安装(所有工具):**
```bash
# macOS
brew install ripgrep jq
npm install -g @google/gemini-cli @openai/codex @qwen-code/qwen-code
# Ubuntu/Debian
sudo apt install ripgrep jq
npm install -g @google/gemini-cli @openai/codex @qwen-code/qwen-code
# Windows (Chocolatey)
choco install ripgrep jq
npm install -g @google/gemini-cli @openai/codex @qwen-code/qwen-code
```
### **必需: Gemini CLI 设置**
配置 Gemini CLI 以实现最佳集成:
```json
// ~/.gemini/settings.json
{
"contextFileName": ["CLAUDE.md", "GEMINI.md"]
}
```
### **推荐: .geminiignore**
通过排除不必要的文件来优化性能:
```bash
# .geminiignore (在项目根目录)
/dist/
/build/
/node_modules/
/.next/
*.tmp
*.log
/temp/
# 包含重要文档
!README.md
!**/CLAUDE.md
```
### **推荐: MCP 工具** *(增强分析)*
MCP (模型上下文协议) 工具提供高级代码库分析。**推荐安装** - 虽然 CCW 具有回退机制,但不安装 MCP 工具可能会导致某些工作流出现意外行为或性能下降。
#### 可用的 MCP 服务器
| MCP 服务器 | 用途 | 安装指南 |
|------------|------|---------|
| **Exa MCP** | 外部 API 模式和最佳实践 | [安装指南](https://smithery.ai/server/exa) |
| **Code Index MCP** | 高级内部代码搜索 | [安装指南](https://github.com/johnhuang316/code-index-mcp) |
#### 启用后的好处
- 📊 **更快分析**: 直接代码库索引 vs 手动搜索
- 🌐 **外部上下文**: 真实世界的 API 模式和示例
- 🔍 **高级搜索**: 模式匹配和相似性检测
-**更好的可靠性**: 某些工作流的主要工具
⚠️ **注意**: 某些工作流期望 MCP 工具可用。如果没有安装,您可能会遇到:
- 代码分析和搜索操作速度较慢
- 某些场景下上下文质量降低
- 回退到效率较低的传统工具
- 高级工作流中可能出现意外行为
---
@@ -142,15 +270,12 @@ bash <(curl -fsSL https://raw.githubusercontent.com/catlog22/Claude-Code-Workflo
**阶段 4测试与质量保证**
```bash
# 生成全面测试套件(标准工作流
/workflow:test-gen
/workflow:execute
# 生成独立测试修复工作流v3.2.2+
/workflow:test-gen WFS-auth # 创建 WFS-test-auth 会话
/workflow:execute # 运行测试验证
# 或验证 TDD 合规性TDD 工作流)
/workflow:tdd-verify
# 可选:手动审查(仅在明确需要时使用)
# /workflow:review # 测试通过 = 代码已批准
```
### 简单任务快速入门
@@ -217,12 +342,15 @@ 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:tdd-plan` | 创建 TDD 工作流6 阶段),包含测试覆盖分析和 Red-Green-Refactor 循环。 |
| `/workflow:execute` | 自主执行当前的工作流计划。 |
| `/workflow:status` | 显示工作流的当前状态。 |
| `/workflow:test-gen` | 从实现中自动生成测试计划。 |
| `/workflow:test-gen [--use-codex] <session>` | 为已完成实现创建独立测试生成工作流,支持自动诊断和修复。 |
| `/workflow:tdd-verify` | 验证 TDD 合规性并生成质量报告。 |
| `/workflow:review` | **可选** 手动审查(仅在明确需要时使用,测试通过即代表代码已批准)。 |
| `/workflow:tools:test-context-gather` | 分析测试覆盖率,识别缺失的测试文件。 |
| `/workflow:tools:test-concept-enhanced` | 使用 Gemini 生成测试策略和需求分析。 |
| `/workflow:tools:test-task-generate` | 生成测试任务 JSON包含 test-fix-cycle 规范。 |
### **任务与内存命令**
@@ -231,92 +359,7 @@ bash <(curl -fsSL https://raw.githubusercontent.com/catlog22/Claude-Code-Workflo
| `/task:*` | 管理单个任务(`create`, `breakdown`, `execute`, `replan`)。 |
| `/update-memory-full` | 重新索引整个项目文档。 |
| `/update-memory-related` | 更新与最近更改相关的文档。 |
---
## ⚙️ 配置
### **前置要求:必需工具**
在使用 CCW 之前,请安装以下命令行工具:
#### **核心 CLI 工具**
| 工具 | 用途 | 安装方式 |
|------|------|----------|
| **Gemini CLI** | AI 分析与文档生成 | `npm install -g @google/gemini-cli` ([GitHub](https://github.com/google-gemini/gemini-cli)) |
| **Codex CLI** | AI 开发与实现 | `npm install -g @openai/codex` ([GitHub](https://github.com/openai/codex)) |
| **Qwen Code** | AI 架构与代码生成 | `npm install -g @qwen-code/qwen-code` ([文档](https://github.com/QwenLM/qwen-code)) |
#### **系统实用工具**
| 工具 | 用途 | 安装方式 |
|------|------|----------|
| **ripgrep (rg)** | 快速代码搜索 | [下载](https://github.com/BurntSushi/ripgrep/releases) 或 `brew install ripgrep` (macOS), `apt install ripgrep` (Ubuntu) |
| **jq** | JSON 处理 | [下载](https://jqlang.github.io/jq/download/) 或 `brew install jq` (macOS), `apt install jq` (Ubuntu) |
**快速安装(所有工具):**
```bash
# macOS
brew install ripgrep jq
npm install -g @google/gemini-cli @openai/codex @qwen-code/qwen-code
# Ubuntu/Debian
sudo apt install ripgrep jq
npm install -g @google/gemini-cli @openai/codex @qwen-code/qwen-code
# Windows (Chocolatey)
choco install ripgrep jq
npm install -g @google/gemini-cli @openai/codex @qwen-code/qwen-code
```
### **必需: Gemini CLI 设置**
配置 Gemini CLI 以实现最佳集成:
```json
// ~/.gemini/settings.json
{
"contextFileName": "CLAUDE.md"
}
```
### **推荐: .geminiignore**
通过排除不必要的文件来优化性能:
```bash
# .geminiignore (在项目根目录)
/dist/
/build/
/node_modules/
/.next/
*.tmp
*.log
/temp/
# 包含重要文档
!README.md
!**/CLAUDE.md
```
### **可选: MCP 工具** *(增强分析)*
MCP (模型上下文协议) 工具提供高级代码库分析。**完全可选** - CCW 在没有它们的情况下也能完美工作。
#### 可用的 MCP 服务器
| MCP 服务器 | 用途 | 安装指南 |
|------------|------|---------|
| **Exa MCP** | 外部 API 模式和最佳实践 | [安装指南](https://github.com/exa-labs/exa-mcp-server) |
| **Code Index MCP** | 高级内部代码搜索 | [安装指南](https://github.com/johnhuang316/code-index-mcp) |
#### 启用后的好处
- 📊 **更快分析**: 直接代码库索引 vs 手动搜索
- 🌐 **外部上下文**: 真实世界的 API 模式和示例
- 🔍 **高级搜索**: 模式匹配和相似性检测
-**自动回退**: MCP 不可用时使用传统工具
| `/version` | 显示版本信息并检查 GitHub 更新。 |
---

View File

@@ -1,264 +0,0 @@
# 🚀 Claude Code Workflow (CCW) v2.0.0 Release Notes
**Release Date**: September 28, 2025
**Release Type**: Major Version Release
**Repository**: https://github.com/catlog22/Claude-Code-Workflow
---
## 📋 Overview
Claude Code Workflow v2.0 represents a **major architectural evolution** with significant enhancements to the multi-agent automation framework. This release introduces a comprehensive four-layer architecture, enhanced workflow lifecycle management, and intelligent tech stack detection.
> **🎯 Upgrade Recommendation**: This is a **breaking change release** with significant architectural improvements. Review the breaking changes section before upgrading.
---
## 🌟 Major Features & Enhancements
### 🏗️ **Four-Layer Architecture (NEW)**
CCW now operates through four distinct architectural layers with defined responsibilities and data contracts:
| Layer | Components | Data Flow | Integration Points |
|-------|------------|-----------|-------------------|
| **🖥️ Interface Layer** | CLI Commands, Gemini/Codex/Qwen Wrappers | User input → Commands → Agents | External CLI tools, approval modes |
| **📋 Session Layer** | `.active-[session]` markers, `workflow-session.json` | Session state → Task discovery | Atomic session switching |
| **📊 Task/Data Layer** | `.task/impl-*.json`, hierarchy management | Task definitions → Agent execution | JSON-first model, generated views |
| **🤖 Orchestration Layer** | Multi-agent coordination, dependency resolution | Agent outputs → Task updates | Intelligent execution flow |
### 🔄 **Enhanced Workflow Lifecycle**
Complete development lifecycle with quality gates at each phase:
1. **💡 Brainstorm Phase** - Multi-perspective conceptual planning with role-based analysis
2. **📋 Plan Phase** - Structured implementation planning with task decomposition
3. **✅ Verify Phase** - Pre-execution validation using Gemini (strategic) + Codex (technical)
4. **⚡ Execute Phase** - Autonomous implementation with multi-agent orchestration
5. **🧪 Test Phase** - Automated test workflow generation with comprehensive coverage
6. **🔍 Review Phase** - Quality assurance and completion validation
### 🧪 **Automated Test Generation**
Comprehensive test workflow creation:
- **Implementation Analysis**: Scans completed IMPL-* tasks for test requirements
- **Multi-layered Testing**: Unit, Integration, E2E, Performance, Security tests
- **Agent Assignment**: Specialized test agents for different test types
- **Dependency Mapping**: Test execution follows implementation dependency chains
### ✅ **Plan Verification System**
Dual-engine validation before execution:
- **Gemini Strategic Analysis**: High-level feasibility and architectural soundness
- **Codex Technical Analysis**: Implementation details and technical feasibility
- **Cross-Validation**: Identifies conflicts between strategic vision and technical constraints
- **Improvement Suggestions**: Actionable recommendations before implementation begins
### 🧠 **Smart Tech Stack Detection**
Intelligent task-based loading of technology guidelines:
- **Automatic Detection**: Only loads tech stacks for development and code review tasks
- **Multi-Language Support**: TypeScript, React, Python, Java, Go, JavaScript
- **Performance Optimized**: Skips detection for non-relevant tasks
- **Context-Aware**: Applies appropriate tech stack principles to development work
### 🔮 **Qwen CLI Integration**
Full integration of Qwen CLI for architecture analysis and code generation:
- **Architecture Analysis**: System design patterns and code quality assessment
- **Code Generation**: Implementation scaffolding and component creation
- **Intelligent Modes**: Auto template selection and precise architectural planning
---
## 📊 New Commands & Capabilities
### **Issue Management Commands**
- ` /workflow:issue:create` - Create new project issues with priority and type
- `📋 /workflow:issue:list` - List and filter issues by status and assignment
- `📝 /workflow:issue:update` - Update existing issue status and assignments
- `✅ /workflow:issue:close` - Close completed issues with resolution reasons
### **Enhanced Workflow Commands**
- `✅ /workflow:plan-verify` - Pre-execution validation using dual analysis
- `🧪 /workflow:test-gen` - Generate comprehensive test workflows
- `🎨 /workflow:brainstorm:artifacts` - Generate structured planning documents
- `🔍 /workflow:plan-deep` - Deep technical planning with Gemini analysis
### **Qwen CLI Commands**
- `🔍 /qwen:analyze` - Architecture analysis and code quality assessment
- `💬 /qwen:chat` - Direct Qwen interaction for design discussions
- `⚡ /qwen:execute` - Intelligent implementation with YOLO permissions
- `🚀 /qwen:mode:auto` - Auto template selection and execution
- `🐛 /qwen:mode:bug-index` - Bug analysis and fix suggestions
- `📋 /qwen:mode:plan` - Architecture planning and analysis
---
## 🔧 Technical Improvements
### **Script & Tool Enhancements**
- **gemini-wrapper**: Improved token management and path handling
- **qwen-wrapper**: Streamlined execution and simplified interface
- **Cross-Platform**: Enhanced Windows path compatibility with proper quoting
- **Directory Navigation**: Intelligent context optimization for focused analysis
### **Agent Improvements**
- **Flow Control**: Enhanced sequential execution with context accumulation
- **Context Assessment**: Smart tech stack loading for relevant tasks only
- **Error Handling**: Improved per-step error strategies
- **Variable Passing**: Context transfer between execution steps
### **Documentation Overhaul**
- **Unified Structure**: Aligned English and Chinese documentation
- **Command Standardization**: Consistent syntax across all commands
- **Architecture Clarity**: Clear data flow and integration point descriptions
- **Version Synchronization**: Both language versions now reflect v2.0 features
---
## 📈 Performance & Compatibility
### **Performance Metrics**
| Metric | Performance | Details |
|--------|-------------|---------|
| 🔄 **Session Switching** | <10ms | Atomic marker file operations |
| 📊 **JSON Queries** | <1ms | Direct JSON access, no parsing overhead |
| 📝 **Doc Updates** | <30s | Medium projects, intelligent targeting |
| 🔍 **Context Loading** | <5s | Complex codebases with caching |
| ⚡ **Task Execution** | 10min timeout | Complex operations with error handling |
### **System Requirements**
- **🖥️ OS**: Windows 10+, Ubuntu 18.04+, macOS 10.15+
- **📦 Dependencies**: Git, Node.js (Gemini), Python 3.8+ (Codex)
- **💾 Storage**: ~50MB core + variable project data
- **🧠 Memory**: 512MB minimum, 2GB recommended
### **Integration Requirements**
- **🔍 Gemini CLI**: Required for analysis and strategic planning workflows
- **🤖 Codex CLI**: Required for autonomous development and bug fixing
- **🔮 Qwen CLI**: Required for architecture analysis and code generation
- **📂 Git Repository**: Required for change tracking and version control
---
## ⚠️ Breaking Changes
### **Removed Components**
- **Python CLI Backend**: All `pycli` references and related scripts removed
- **Deprecated Scripts**: `install_pycli.sh`, `pycli`, `pycli.conf`, `tech-stack-loader.sh`
- **Legacy Commands**: Old path reading scripts and unused Python tools
### **Command Syntax Changes**
- **Session Commands**: `/workflow:session list``/workflow:session:list`
- **File Naming**: Standardized to lowercase `.task/impl-*.json`
- **Session Markers**: Unified format `.active-[session]`
### **Architecture Changes**
- **Data Model**: Migrated to JSON-first architecture
- **Session Management**: Atomic marker-based system
- **Task Structure**: Standardized hierarchy and status management
### **Configuration Updates**
Required Gemini CLI configuration:
```json
{
"contextFileName": "CLAUDE.md"
}
```
---
## 🚀 Migration Guide
### **From v1.x to v2.0**
1. **Update Configuration**:
```bash
# Update Gemini CLI settings
echo '{"contextFileName": "CLAUDE.md"}' > ~/.gemini/settings.json
```
2. **Clean Legacy Files**:
```bash
# Remove old Python CLI references
rm -f .claude/scripts/pycli*
rm -f .claude/scripts/install_pycli.sh
```
3. **Update Command Usage**:
```bash
# Old syntax
/workflow:session list
# New syntax
/workflow:session:list
```
4. **Verify Installation**:
```bash
/workflow:session:list
```
---
## 📚 Documentation & Resources
### **Updated Documentation**
- **README.md**: Complete v2.0 feature documentation
- **README_CN.md**: Chinese documentation with v2.0 alignment
- **Architecture Guides**: Four-layer system documentation
- **Command Reference**: Comprehensive CLI command tables
### **Quick Start**
```bash
# Install CCW v2.0
Invoke-Expression (Invoke-WebRequest -Uri "https://raw.githubusercontent.com/catlog22/Claude-Code-Workflow/main/install-remote.ps1" -UseBasicParsing).Content
# Verify installation
/workflow:session:list
# Start first workflow
/workflow:session:start "My First Project"
```
---
## 🤝 Contributing & Support
### **Development**
- **GitHub**: https://github.com/catlog22/Claude-Code-Workflow
- **Issues**: https://github.com/catlog22/Claude-Code-Workflow/issues
- **Discussions**: https://github.com/catlog22/Claude-Code-Workflow/discussions
### **Community**
- **Documentation**: [Project Wiki](https://github.com/catlog22/Claude-Code-Workflow/wiki)
- **Changelog**: [Release History](CHANGELOG.md)
- **License**: MIT License
---
## 🙏 Acknowledgments
Special thanks to the community for feedback and contributions that made v2.0 possible. This release represents a significant step forward in automated development workflow capabilities.
---
**🚀 Claude Code Workflow v2.0**
*Professional software development workflow automation through intelligent multi-agent coordination and autonomous execution capabilities.*
---
## 📝 Commit History Summary
This release includes 15+ commits spanning major architectural improvements:
- **5d08c53**: Smart tech stack detection for agents
- **b956943**: Workflow architecture documentation updates
- **8baca52**: README v2.0 alignment and four-layer architecture
- **0756682**: Python CLI cleanup and modernization
- **be4db94**: Concept evaluation framework addition
- **817f51c**: Qwen CLI integration and task commands
For complete commit history, see: [GitHub Commits](https://github.com/catlog22/Claude-Code-Workflow/commits/main)

View File

@@ -1,142 +0,0 @@
# 🔧 Claude Code Workflow (CCW) v3.2.1 Release Notes
**Release Date**: October 2, 2025
**Release Type**: Patch Release - Documentation Fix
**Repository**: https://github.com/catlog22/Claude-Code-Workflow
---
## 📋 Overview
CCW v3.2.1 is a critical documentation fix release that corrects `workflow-session.json` path references throughout the brainstorming workflow documentation. This ensures consistency with the architecture specification defined in `workflow-architecture.md`.
---
## 🐛 Bug Fixes
### **Documentation Path Corrections**
**Issue**: Documentation incorrectly referenced `workflow-session.json` inside the `.brainstorming/` subdirectory
**Impact**:
- Confusing path references in 9 brainstorming role documentation files
- Inconsistency with architectural specifications
- Potential runtime errors when commands attempt to read session metadata
**Fixed Files** (9 total):
1.`data-architect.md`
2.`product-manager.md`
3.`product-owner.md`
4.`scrum-master.md`
5.`subject-matter-expert.md`
6.`ui-designer.md`
7.`ux-expert.md`
8.`auto-parallel.md`
9.`artifacts.md`
**Corrections Applied**:
-**Incorrect**: `.workflow/WFS-{session}/.brainstorming/workflow-session.json`
-**Correct**: `.workflow/WFS-{session}/workflow-session.json`
---
## 📐 Architecture Alignment
### Confirmed Standard Structure
```
.workflow/WFS-[topic-slug]/
├── workflow-session.json # ✅ Session metadata (root level)
├── .brainstorming/ # Brainstorming artifacts subdirectory
│ └── topic-framework.md
├── IMPL_PLAN.md
├── TODO_LIST.md
└── .task/
└── IMPL-*.json
```
### Key Points
- `workflow-session.json` is **always at session root level**
- `.brainstorming/` directory contains **only** framework and analysis files
- No session metadata files inside subdirectories
---
## 📊 Changes Summary
| Category | Files Changed | Lines Modified |
|----------|--------------|----------------|
| Documentation Fixes | 9 | 19 insertions, 18 deletions |
| Path Corrections | 8 role files | 2 corrections per file |
| Structure Clarifications | 1 artifacts file | Added architectural note |
---
## ✅ Verification
**Pre-Release Checks**:
- ✅ No incorrect `.brainstorming/workflow-session.json` references
- ✅ No legacy `session.json` references
- ✅ All brainstorming roles use correct paths
- ✅ Architecture consistency verified with Gemini analysis
---
## 🔄 Upgrade Instructions
### For Existing Users
**No action required** - This is a documentation-only fix.
1. Pull the latest changes:
```bash
git pull origin main
```
2. Review updated documentation:
- `.claude/commands/workflow/brainstorm/*.md`
### For New Users
Simply clone the repository with the correct documentation:
```bash
git clone https://github.com/catlog22/Claude-Code-Workflow.git
```
---
## 📚 Related Documentation
- **Architecture Reference**: `.claude/workflows/workflow-architecture.md`
- **Brainstorming Commands**: `.claude/commands/workflow/brainstorm/`
- **Session Management**: `.claude/commands/workflow/session/`
---
## 🙏 Acknowledgments
Special thanks to the analysis tools used in this fix:
- **Gemini CLI**: Path verification and consistency checking
- **Codex**: Initial codebase analysis
- **Claude Code**: Documentation review and corrections
---
## 🔗 Links
- **Full Changelog**: [v3.2.0...v3.2.1](https://github.com/catlog22/Claude-Code-Workflow/compare/v3.2.0...v3.2.1)
- **Issues Fixed**: Documentation consistency issue
- **Previous Release**: [v3.2.0 Release Notes](RELEASE_NOTES_v3.2.0.md)
---
## 📝 Notes
- This is a **non-breaking change** - existing workflows will continue to function
- Documentation now correctly reflects the implemented architecture
- No code changes were necessary - this was purely a documentation correction
---
**Contributors**: Claude Code Development Team
**License**: MIT
**Support**: [GitHub Issues](https://github.com/catlog22/Claude-Code-Workflow/issues)

252
RELEASE_NOTES_v3.2.3.md Normal file
View File

@@ -0,0 +1,252 @@
# v3.2.3 - Version Management System
## 🎉 Release Date
2025-10-03
## ✨ Overview
This release introduces a comprehensive version management and upgrade notification system, making it easy to track your Claude Code Workflow installation and stay up-to-date with the latest releases.
## 🆕 New Features
### `/version` Command
A powerful new command that provides complete version information and automatic update checking:
**Features:**
- 📊 **Version Display**: Shows both local and global installation versions
- 🌐 **GitHub Integration**: Fetches latest stable release and development commits
- 🔄 **Smart Comparison**: Automatically compares installed version with latest available
- 💡 **Upgrade Recommendations**: Provides installation commands for easy upgrading
-**Fast Execution**: 30-second timeout for network calls, graceful offline handling
**Usage:**
```bash
/version
```
**Example Output:**
```
Installation Status:
- Local: No project-specific installation
- Global: ✅ Installed at ~/.claude
- Version: v3.2.3
- Installed: 2025-10-03T05:01:34Z
Latest Releases:
- Stable: v3.2.3 (2025-10-03T04:10:08Z)
- v3.2.3: Version Management System
- Latest Commit: c5c36a2 (2025-10-03T05:00:06Z)
- fix: Optimize version command API calls and data extraction
Status: ✅ You are on the latest stable version (3.2.3)
```
### Version Tracking System
**Version Files:**
- `.claude/version.json` - Local project installation tracking
- `~/.claude/version.json` - Global installation tracking
**Tracked Information:**
```json
{
"version": "v3.2.3",
"installation_mode": "Global",
"installation_path": "C:\\Users\\username\\.claude",
"source_branch": "main",
"installation_date_utc": "2025-10-03T05:01:34Z"
}
```
### GitHub API Integration
**Endpoints Used:**
- **Latest Release**: `https://api.github.com/repos/catlog22/Claude-Code-Workflow/releases/latest`
- Extracts: tag_name, release name, published date
- **Latest Commit**: `https://api.github.com/repos/catlog22/Claude-Code-Workflow/commits/main`
- Extracts: commit SHA, message, author date
**Network Handling:**
- 30-second timeout for slow connections
- Graceful error handling for offline scenarios
- No external dependencies (uses curl and grep/sed)
## 🔄 What's Changed
### Documentation Updates
**Updated Files:**
-`CHANGELOG.md` - Added comprehensive v3.2.3 release notes
-`README.md` - Updated version badge to v3.2.3, added `/version` command
-`README_CN.md` - Updated version badge and command reference (Chinese)
-`.claude/commands/version.md` - Complete implementation guide
**Version References:**
- All version badges updated from v3.2.2 to v3.2.3
- "What's New" sections updated with v3.2.3 features
- Command reference tables include `/version` command
### Installation Scripts Enhancement
**Future Enhancement** (for next release):
- Installation scripts will automatically create `version.json` files
- Track installation mode (local vs global)
- Record installation timestamp
- Support version tracking for both stable and development installations
## 📋 Version Comparison Scenarios
### Scenario 1: Up to Date
```
✅ You are on the latest stable version (3.2.3)
```
### Scenario 2: Upgrade Available
```
⬆️ A newer stable version is available: v3.2.4
Your version: 3.2.3
To upgrade:
PowerShell: iex (iwr -useb https://raw.githubusercontent.com/catlog22/Claude-Code-Workflow/main/install-remote.ps1)
Bash: bash <(curl -fsSL https://raw.githubusercontent.com/catlog22/Claude-Code-Workflow/main/install-remote.sh)
```
### Scenario 3: Development Version
```
✨ You are running a development version (3.3.0-dev)
This is newer than the latest stable release (v3.2.3)
```
## 🛠️ Technical Details
### Implementation Highlights
**Simple Bash Commands:**
- No jq dependency required (uses grep/sed for JSON parsing)
- Cross-platform compatible (Windows Git Bash, Linux, macOS)
- Version comparison using `sort -V` for semantic versioning
- Direct API access using curl with error suppression
**Command Structure:**
```bash
# Check local version
test -f ./.claude/version.json && cat ./.claude/version.json
# Check global version
test -f ~/.claude/version.json && cat ~/.claude/version.json
# Fetch latest release (with timeout)
curl -fsSL "https://api.github.com/repos/catlog22/Claude-Code-Workflow/releases/latest" 2>/dev/null
# Extract version
grep -o '"tag_name": *"[^"]*"' | cut -d'"' -f4
# Compare versions
printf "%s\n%s" "3.2.2" "3.2.3" | sort -V | tail -n 1
```
## 📊 Benefits
### User Experience
- 🔍 **Quick version check** with single command
- 📊 **Comprehensive information** display (local, global, stable, dev)
- 🔄 **Automatic upgrade notifications** when new versions available
- 📈 **Development version tracking** for cutting-edge features
- 🌐 **GitHub integration** for latest updates
### DevOps
- 📁 **Version tracking** in both local and global installations
- 🕐 **Installation timestamp** for audit trails
- 🔀 **Support for both stable and development** branches
-**Fast execution** with 30-second network timeout
- 🛡️ **Graceful error handling** for offline scenarios
## 🔗 Related Commands
- `/cli:cli-init` - Initialize CLI tool configurations
- `/workflow:session:list` - List workflow sessions
- `/update-memory-full` - Update project documentation
## 📦 Installation
### Fresh Installation
**Windows (PowerShell):**
```powershell
iex (iwr -useb https://raw.githubusercontent.com/catlog22/Claude-Code-Workflow/main/install-remote.ps1)
```
**Linux/macOS (Bash):**
```bash
bash <(curl -fsSL https://raw.githubusercontent.com/catlog22/Claude-Code-Workflow/main/install-remote.sh)
```
### Upgrade from v3.2.2
Use the same installation commands above. The installer will automatically:
1. Detect your existing installation
2. Back up current files (if using `-BackupAll`)
3. Update to v3.2.3
4. Create/update `version.json` files
## 🐛 Bug Fixes
- Fixed commit message extraction to handle JSON escape sequences
- Improved API endpoint from `/branches/main` to `/commits/main` for reliable commit info
- Added 30-second timeout to all network calls for slow connections
- Enhanced release name and published date extraction
## 📚 Documentation
### New Documentation
- `.claude/commands/version.md` - Complete command implementation guide
- API endpoints and usage
- Timeout configuration
- Error handling scenarios
- Simple bash command examples
### Updated Documentation
- `CHANGELOG.md` - v3.2.3 release notes
- `README.md` - Version badge and command reference
- `README_CN.md` - Chinese version updates
## 🙏 Credits
This release includes contributions and improvements based on:
- GitHub API integration for version detection
- Cross-platform bash command compatibility
- User feedback on installation and upgrade processes
## 📝 Notes
- **Backward Compatible**: All existing commands and workflows continue to work
- **No Breaking Changes**: This is a minor release with new features only
- **Optional Feature**: `/version` command is entirely optional, existing workflows unaffected
## 🚀 What's Next
**Planned for v3.2.4:**
- Enhanced installation script to auto-create version.json
- Version tracking in all installation modes
- Automatic version detection during installation
**Future Enhancements:**
- Auto-update functionality (opt-in)
- Version comparison in workflow sessions
- Release notes display in CLI
---
**Full Changelog**: [v3.2.2...v3.2.3](https://github.com/catlog22/Claude-Code-Workflow/compare/v3.2.2...v3.2.3)
**Installation:**
```bash
# One-line install (recommended)
bash <(curl -fsSL https://raw.githubusercontent.com/catlog22/Claude-Code-Workflow/main/install-remote.sh)
# Or use specific version tag
git clone -b v3.2.3 https://github.com/catlog22/Claude-Code-Workflow.git
```
🤖 Generated with [Claude Code](https://claude.com/claude-code)

View File

@@ -258,23 +258,25 @@ function Extract-Repository {
function Invoke-LocalInstaller {
param(
[string]$RepoDir
[string]$RepoDir,
[string]$VersionInfo = "",
[string]$BranchInfo = ""
)
$installerPath = Join-Path $RepoDir "Install-Claude.ps1"
if (-not (Test-Path $installerPath)) {
Write-ColorOutput "ERROR: Install-Claude.ps1 not found" $ColorError
return $false
}
Write-ColorOutput "Running local installer..." $ColorInfo
Write-Host ""
# Build parameters for local installer
$params = @{}
if ($Global) { $params["InstallMode"] = "Global" }
if ($Directory) {
if ($Directory) {
$params["InstallMode"] = "Custom"
$params["TargetPath"] = $Directory
}
@@ -282,11 +284,15 @@ function Invoke-LocalInstaller {
if ($NoBackup) { $params["NoBackup"] = $NoBackup }
if ($NonInteractive) { $params["NonInteractive"] = $NonInteractive }
if ($BackupAll) { $params["BackupAll"] = $BackupAll }
# Pass version and branch information
if ($VersionInfo) { $params["SourceVersion"] = $VersionInfo }
if ($BranchInfo) { $params["SourceBranch"] = $BranchInfo }
try {
# Change to repo directory and run installer
Push-Location $RepoDir
if ($params.Count -gt 0) {
$paramList = ($params.GetEnumerator() | ForEach-Object { "-$($_.Key) $($_.Value)" }) -join " "
Write-ColorOutput "Executing: & `"$installerPath`" $paramList" $ColorInfo
@@ -295,7 +301,7 @@ function Invoke-LocalInstaller {
Write-ColorOutput "Executing: & `"$installerPath`"" $ColorInfo
& $installerPath
}
Pop-Location
return $true
} catch {
@@ -410,10 +416,10 @@ function Get-UserVersionChoice {
$response = Invoke-RestMethod -Uri $apiUrl -UseBasicParsing -TimeoutSec 5
$latestVersion = $response.tag_name
# Parse and format release date
# Parse and format release date to local time
if ($response.published_at) {
$publishDate = [DateTime]::Parse($response.published_at)
$latestStableDate = $publishDate.ToString("yyyy-MM-dd HH:mm UTC")
$publishDate = [DateTime]::Parse($response.published_at).ToLocalTime()
$latestStableDate = $publishDate.ToString("yyyy-MM-dd HH:mm")
}
Write-ColorOutput "Latest stable: $latestVersion ($latestStableDate)" $ColorSuccess
@@ -427,10 +433,10 @@ function Get-UserVersionChoice {
$commitResponse = Invoke-RestMethod -Uri $commitUrl -UseBasicParsing -TimeoutSec 5
$latestCommitId = $commitResponse.sha.Substring(0, 7)
# Parse and format commit date
# Parse and format commit date to local time
if ($commitResponse.commit.committer.date) {
$commitDate = [DateTime]::Parse($commitResponse.commit.committer.date)
$latestCommitDate = $commitDate.ToString("yyyy-MM-dd HH:mm UTC")
$commitDate = [DateTime]::Parse($commitResponse.commit.committer.date).ToLocalTime()
$latestCommitDate = $commitDate.ToString("yyyy-MM-dd HH:mm")
}
Write-ColorOutput "Latest commit: $latestCommitId ($latestCommitDate)" $ColorSuccess
@@ -542,26 +548,32 @@ function Main {
# Create temp directory
$tempDir = Get-TempDirectory
Write-ColorOutput "Temporary directory: $tempDir" $ColorInfo
try {
# Download repository
$zipPath = Download-Repository -TempDir $tempDir -Version $Version -Branch $Branch -Tag $Tag
if (-not $zipPath) {
throw "Download failed"
}
# Extract repository
$repoDir = Extract-Repository $zipPath $tempDir
if (-not $repoDir) {
throw "Extraction failed"
}
# Run local installer
$success = Invoke-LocalInstaller $repoDir
# Determine version and branch information to pass
$versionToPass = if ($Tag) { $Tag } else { "latest" }
$branchToPass = if ($Version -eq "branch") { $Branch } elseif ($Version -eq "latest") { "main" } elseif ($Tag) { $Tag } else { "main" }
Write-ColorOutput "Version info: $versionToPass (branch: $branchToPass)" $ColorInfo
# Run local installer with version information
$success = Invoke-LocalInstaller -RepoDir $repoDir -VersionInfo $versionToPass -BranchInfo $branchToPass
if (-not $success) {
throw "Installation script failed"
}
Write-Host ""
Write-ColorOutput "Remote installation completed successfully!" $ColorSuccess

View File

@@ -43,8 +43,8 @@ function show_header() {
function test_prerequisites() {
# Test bash version
if [ "${BASH_VERSINFO[0]}" -lt 4 ]; then
write_color "ERROR: Bash 4.0 or higher is required" "$COLOR_ERROR"
if [ "${BASH_VERSINFO[0]}" -lt 2 ]; then
write_color "ERROR: Bash 2.0 or higher is required" "$COLOR_ERROR"
write_color "Current version: ${BASH_VERSION}" "$COLOR_ERROR"
return 1
fi
@@ -452,14 +452,19 @@ function get_user_version_choice() {
latest_version=$(echo "$release_data" | jq -r '.tag_name' 2>/dev/null)
local published_at=$(echo "$release_data" | jq -r '.published_at' 2>/dev/null)
if [ -n "$published_at" ] && [ "$published_at" != "null" ]; then
# Format: 2025-10-02T04:27:21Z -> 2025-10-02 04:27 UTC
latest_date=$(echo "$published_at" | sed 's/T/ /' | sed 's/Z/ UTC/' | cut -d'.' -f1)
# Convert UTC to local time
if command -v date &> /dev/null; then
latest_date=$(date -d "$published_at" '+%Y-%m-%d %H:%M' 2>/dev/null || date -jf '%Y-%m-%dT%H:%M:%SZ' "$published_at" '+%Y-%m-%d %H:%M' 2>/dev/null)
fi
fi
else
latest_version=$(echo "$release_data" | grep -o '"tag_name":\s*"[^"]*"' | sed 's/"tag_name":\s*"\([^"]*\)"/\1/')
local published_at=$(echo "$release_data" | grep -o '"published_at":\s*"[^"]*"' | sed 's/"published_at":\s*"\([^"]*\)"/\1/')
if [ -n "$published_at" ]; then
latest_date=$(echo "$published_at" | sed 's/T/ /' | sed 's/Z/ UTC/' | cut -d'.' -f1)
# Convert UTC to local time
if command -v date &> /dev/null; then
latest_date=$(date -d "$published_at" '+%Y-%m-%d %H:%M' 2>/dev/null || date -jf '%Y-%m-%dT%H:%M:%SZ' "$published_at" '+%Y-%m-%d %H:%M' 2>/dev/null)
fi
fi
fi
fi
@@ -480,13 +485,19 @@ function get_user_version_choice() {
commit_id=$(echo "$commit_data" | jq -r '.sha' 2>/dev/null | cut -c1-7)
local committer_date=$(echo "$commit_data" | jq -r '.commit.committer.date' 2>/dev/null)
if [ -n "$committer_date" ] && [ "$committer_date" != "null" ]; then
commit_date=$(echo "$committer_date" | sed 's/T/ /' | sed 's/Z/ UTC/' | cut -d'.' -f1)
# Convert UTC to local time
if command -v date &> /dev/null; then
commit_date=$(date -d "$committer_date" '+%Y-%m-%d %H:%M' 2>/dev/null || date -jf '%Y-%m-%dT%H:%M:%SZ' "$committer_date" '+%Y-%m-%d %H:%M' 2>/dev/null)
fi
fi
else
commit_id=$(echo "$commit_data" | grep -o '"sha":\s*"[^"]*"' | head -1 | sed 's/"sha":\s*"\([^"]*\)"/\1/' | cut -c1-7)
local committer_date=$(echo "$commit_data" | grep -o '"date":\s*"[^"]*"' | head -1 | sed 's/"date":\s*"\([^"]*\)"/\1/')
if [ -n "$committer_date" ]; then
commit_date=$(echo "$committer_date" | sed 's/T/ /' | sed 's/Z/ UTC/' | cut -d'.' -f1)
# Convert UTC to local time
if command -v date &> /dev/null; then
commit_date=$(date -d "$committer_date" '+%Y-%m-%d %H:%M' 2>/dev/null || date -jf '%Y-%m-%dT%H:%M:%SZ' "$committer_date" '+%Y-%m-%d %H:%M' 2>/dev/null)
fi
fi
fi
fi