Compare commits

..

52 Commits

Author SHA1 Message Date
catlog22
12034c8be5 release: version v3.4.2 - CLI documentation refactoring
Updated documentation for v3.4.2 release focusing on CLI command
documentation refactoring and single source of truth pattern.

## Changes

**CHANGELOG.md**:
- Added comprehensive v3.4.2 release notes
- Documented 681 lines reduction across 7 CLI command files
- Detailed removed duplicate sections and preserved unique content
- Explained single source of truth pattern with intelligent-tools-strategy.md

**README.md & README_CN.md**:
- Updated version badge from v3.4.0 to v3.4.2
- Updated "What's New" section with v3.4.2 highlights
- Documented CLI documentation refactoring benefits

## Release Summary

v3.4.2 focuses on documentation quality and maintenance optimization:
- Eliminated redundant documentation content
- Established implicit reference pattern to strategy guide
- Preserved all unique command-specific capabilities
- Reduced maintenance overhead for future updates

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

Co-Authored-By: Claude <noreply@anthropic.com>
2025-10-05 10:39:53 +08:00
catlog22
467963eee2 docs: refactor CLI command docs to eliminate redundancy
Streamlined 7 CLI command documentation files by removing duplicate
content that's already comprehensively covered in intelligent-tools-strategy.md
(loaded in memory). Established single source of truth (SSOT) pattern.

Changes:
- Removed duplicate command templates (→ strategy lines 51-118)
- Removed file pattern reference lists (→ strategy lines 324-329)
- Removed complex pattern discovery steps (→ strategy lines 331-355)
- Removed MODE field definitions (→ strategy lines 128-143)
- Removed tool feature descriptions (→ strategy lines 283-322)

Files streamlined:
- analyze.md: 117→61 lines (48% reduction)
- chat.md: 118→62 lines (47% reduction)
- execute.md: 180→100 lines (44% reduction)
- codex-execute.md: 481→473 lines (2% - preserved unique content)
- mode/bug-index.md: 144→75 lines (48% reduction)
- mode/code-analysis.md: 188→76 lines (60% reduction)
- mode/plan.md: 100→76 lines (24% reduction)

Total reduction: 681 lines removed across all files

Each doc now contains only:
- Unique purpose and parameters
- Command-specific execution flow
- Practical examples
- Brief reference to intelligent-tools-strategy.md

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

Co-Authored-By: Claude <noreply@anthropic.com>
2025-10-05 10:35:27 +08:00
catlog22
a9d6de228e feat: 增加文件模式参考和复杂模式发现的示例,增强 CLI 命令的文档 2025-10-05 10:26:08 +08:00
catlog22
7d9adf5a55 chore: 删除 intelligent-tools-strategy.md 中的参考链接以简化文档 2025-10-05 09:08:33 +08:00
catlog22
3bf15ced59 chore: 删除 intelligent-tools-strategy.md 文件并重新创建以更新策略框架 2025-10-05 08:56:39 +08:00
catlog22
dc228411d6 chore: 删除 intelligent-tools-strategy.md 文件并更新 .gitignore 以包含 version.json 2025-10-05 08:55:22 +08:00
catlog22
7dd83f150a fix: Use commit SHA as version for development builds instead of 'latest'
**Problem**:
- version.json showed "version": "latest" for dev builds
- Non-descriptive and not useful for version tracking

**Solution**:
- Use "dev-{commit_sha}" format for development builds
- Stable releases: "3.4.1" (from tag)
- Development builds: "dev-4ec1a17" (from commit SHA)
- API failure fallback: "dev-unknown"

**Version Format Examples**:
```json
// Stable release
{"version": "3.4.1", "commit_sha": "4ec1a17"}

// Development build
{"version": "dev-4ec1a17", "commit_sha": "4ec1a17"}
```

**Benefits**:
- Clear distinction between stable and dev versions
- version field always contains meaningful information
- No more "latest" placeholder values

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

Co-Authored-By: Claude <noreply@anthropic.com>
2025-10-04 23:58:47 +08:00
catlog22
4ec1a17ef4 feat: Add commit SHA tracking to version.json for precise version identification
**Version Tracking Enhancement**:
- Add commit_sha field to version.json for distinguishing development versions
- Auto-detect commit SHA from downloaded repository using git rev-parse
- Fallback to GitHub API if git is unavailable
- Update both PowerShell and Bash installers

**version.json Structure**:
```json
{
  "version": "3.4.1",
  "commit_sha": "9a49a86",
  "installation_mode": "Global",
  "installation_path": "...",
  "installation_date_utc": "...",
  "source_branch": "main",
  "installer_version": "2.2.0"
}
```

**Benefits**:
- /version command can precisely identify installed version
- Distinguish between stable releases and development builds
- Track exact commit for debugging and support

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

Co-Authored-By: Claude <noreply@anthropic.com>
2025-10-04 23:54:00 +08:00
catlog22
9a49a86221 feat: Implement dynamic version detection and passing system
**Installation System Updates**:
- install-remote.ps1: Auto-detect version from GitHub API and pass to installer
- Install-Claude.ps1: Accept dynamic version via -SourceVersion parameter
- install-remote.sh: Synchronize version detection logic with PowerShell version
- Add installer_version field to version.json for tracking

**Codex Agent Optimization** (.codex/AGENTS.md):
- Add system optimization requirements for direct binary execution
- Prioritize apply_patch tool over Python scripts for file editing
- Add Windows UTF-8 encoding configuration for Chinese character support

**Version Flow**:
1. install-remote.* detects version from GitHub API (latest release tag)
2. Passes version to Install-Claude.* via -SourceVersion/-SourceBranch
3. Installer writes accurate version to version.json

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

Co-Authored-By: Claude <noreply@anthropic.com>
2025-10-04 23:49:52 +08:00
catlog22
25a453d8f8 chore: Remove obsolete version.json file 2025-10-04 23:42:50 +08:00
catlog22
f574c0da47 feat: Add Codex CLI optimization requirements to AGENTS.md
Add system optimization section with performance and compatibility improvements:
- Direct binary execution to avoid shell wrapper overhead
- apply_patch tool priority for efficient text editing
- Windows UTF-8 encoding configuration for Chinese character support

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

Co-Authored-By: Claude <noreply@anthropic.com>
2025-10-04 23:40:34 +08:00
catlog22
5b38a63129 refactor: Remove model specification from CLI command files
Remove hardcoded model: sonnet from CLI command frontmatter to allow dynamic model selection.

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

Co-Authored-By: Claude <noreply@anthropic.com>
2025-10-04 23:26:42 +08:00
catlog22
813a307c3d feat: Optimize memory-gemini-bridge agent with tool parameter support and structured context
- Add tool parameter support (gemini/qwen/codex) to memory-gemini-bridge agent
- Implement TodoWrite task tracking for all depth levels
- Simplify agent instructions with direct bash commands
- Add structured context templates for both full and related update modes
- Ensure complete module path processing with no skipping
- Improve instruction adherence with clear execution requirements

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

Co-Authored-By: Claude <noreply@anthropic.com>
2025-10-04 21:16:00 +08:00
catlog22
f1ffe9503c feat: Add .qwen directory installation support to Install-Claude.ps1
Add .qwen directory to installation script for Qwen agent support,
ensuring complete multi-tool environment setup.

Changes:
- Add .qwen directory prerequisite check
- Add .qwen source and destination paths for Global mode
- Add .qwen source and destination paths for Path mode
- Include .qwen in backup folder detection
- Merge .qwen directory contents in both Global and Path modes
- Update installation summary to include .qwen
- Update Next steps documentation to include .qwen/QWEN.md

Installation modes:
- Global: Installs .qwen to ~/.qwen
- Path: Installs .qwen to local directory

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

Co-Authored-By: Claude <noreply@anthropic.com>
2025-10-04 20:47:56 +08:00
catlog22
437897faff feat: Add multi-tool support for CLAUDE.md documentation generation (v3.4.1)
Add flexible tool selection (gemini/qwen/codex) for documentation updates,
allowing users to choose the best tool for their analysis needs.

Changes:
- Add --tool parameter to /update-memory-full and /update-memory-related
- Enhance update_module_claude.sh with tool routing (gemini|qwen|codex)
- Update command documentation with tool selection examples
- Add CHANGELOG entry for v3.4.1

Tool features:
- Gemini (default): Documentation generation, pattern recognition
- Qwen: Architecture analysis, system design (direct command, no wrapper)
- Codex: Implementation validation, code quality analysis

Backward compatible: Commands default to gemini without --tool parameter

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

Co-Authored-By: Claude <noreply@anthropic.com>
2025-10-04 20:44:10 +08:00
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
catlog22
2efd45b0ed feat: Redesign test-gen workflow with independent session and cross-session context
Major redesign of test-gen workflow based on simplified architecture:

Core Changes:
- Creates independent test session (WFS-test-[source]) instead of modifying existing session
- Implements 4-phase execution with concept-enhanced analysis integration
- Reuses IMPL-*.json format with meta.type="test-fix" (no new task type)
- Auto-detects cross-session context via workflow-session.json metadata

4-Phase Workflow:
1. Phase 1: Create test session with workflow_type and source_session_id metadata
2. Phase 2: Auto-detect and gather cross-session context (summaries, git changes, tests)
3. Phase 3: Analyze implementation with concept-enhanced (parallel Gemini + Codex)
4. Phase 4: Generate IMPL-001.json task with test strategy from ANALYSIS_RESULTS.md

Key Features:
- Session isolation: Test session separate from implementation session
- Parameter simplification: context-gather auto-detects via metadata (no --source-session param)
- Format reuse: IMPL-*.json with meta.type field (zero changes to execute/status tools)
- Analysis integration: concept-enhanced provides comprehensive test strategy and code targets
- Automatic cross-session: Collects source session artifacts automatically

Tool Modifications Required:
- session-start: Support test session metadata (workflow_type, source_session_id)
- context-gather: Auto-detect test session and gather from source session
- task-generate: Extract test strategy from ANALYSIS_RESULTS.md
- concept-enhanced: No changes (already supports analysis)
- execute: No changes (already dispatches by meta.agent)

Data Flow:
User → session-start (creates test session) → context-gather (auto cross-session)
→ concept-enhanced (analyzes + generates strategy) → task-generate (creates task)
→ Returns summary → User triggers /workflow:execute separately

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

Co-Authored-By: Claude <noreply@anthropic.com>
2025-10-03 12:04:00 +08:00
catlog22
ae77e698db docs: Add prerequisites section with required tools installation guide
Added comprehensive prerequisites section to both English and Chinese README files:
- Core CLI tools: Gemini CLI, Codex CLI, Qwen Code with GitHub links
- System utilities: ripgrep, jq with download links
- Platform-specific quick install commands (macOS, Ubuntu/Debian, Windows)

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

Co-Authored-By: Claude <noreply@anthropic.com>
2025-10-03 09:36:47 +08:00
catlog22
b945e2de55 docs: Enhance target_files documentation and fix cross-platform command compatibility
## Target Files Enhancement
- Add support for new file creation in target_files format
- Update task-generate.md with comprehensive target_files generation guide
- Update concept-enhanced.md to output code modification targets
- Add examples showing both modification (file:function:lines) and creation (file) formats

## Cross-Platform Command Fixes
- Replace ls with find commands for better Windows Git Bash compatibility
- Update workflow commands: execute.md, status.md, review.md
- Update session commands: list.md, complete.md
- Add Bash environment guidelines to context-search-strategy.md
- Document forbidden Windows commands (findstr, dir, where, etc.)

## Files Updated
- Core workflows: workflow-architecture.md, task-core.md
- Command docs: 9 workflow command files
- Agent docs: action-planning-agent.md, task-generate-agent.md
- Strategy docs: context-search-strategy.md

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

Co-Authored-By: Claude <noreply@anthropic.com>
2025-10-02 22:40:37 +08:00
catlog22
661cb5be1c chore: Bump version to v3.2.1
- Update version badges in README.md, README_CN.md, PROJECT_INTRODUCTION.md
- Add RELEASE_NOTES_v3.2.1.md with detailed documentation fix changelog
- Document workflow-session.json path corrections

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

Co-Authored-By: Claude <noreply@anthropic.com>
2025-10-02 22:10:01 +08:00
catlog22
94a2150836 fix: Correct workflow-session.json path references in brainstorming docs
- Fix incorrect path: .brainstorming/workflow-session.json → /workflow-session.json
- Update 8 role files: data-architect, product-manager, product-owner, scrum-master,
  subject-matter-expert, ui-designer, ux-expert, auto-parallel
- Update artifacts.md to clarify correct session file location
- Align all paths with workflow-architecture.md standard structure

Fixes session file path confusion issue. workflow-session.json should be at
session root (.workflow/WFS-{session}/), not in .brainstorming/ subdirectory.

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

Co-Authored-By: Claude <noreply@anthropic.com>
2025-10-02 22:08:56 +08:00
catlog22
3067b8bda6 feat: Add .codex and .gemini agent configuration support
- Add .codex/Agent.md: Codex agent execution protocol
- Add .gemini/CLAUDE.md: Gemini agent execution protocol
- Update Install-Claude.ps1: Install .codex/.gemini to user profile (global) or target dir (path mode)
- Update Install-Claude.sh: Same installation support for bash
- Update intelligent-tools-strategy.md: Add MODE field definitions for Gemini/Qwen/Codex
- Update README.md: Add installation notes and workflow selection guide
- Update README_CN.md: Add Chinese version of installation notes and workflow guide

Installation behavior:
- Global mode: .codex and .gemini install to ~/.codex and ~/.gemini
- Path mode: .codex and .gemini install to <target-dir>/.codex and <target-dir>/.gemini
- Automatic backup of existing files before installation

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

Co-Authored-By: Claude <noreply@anthropic.com>
2025-10-02 15:24:33 +08:00
catlog22
47973718d6 docs: Update version badges and highlights to v3.2.0
Updated version information across README files:

Version Badge Updates:
- Changed version badge from v3.1.0 to v3.2.0
- Updated both English and Chinese README files

Highlights Section Refresh:
- Updated "Latest" section to highlight v3.2.0 features
- Replaced TDD workflow announcement with agent architecture simplification
- Added "What's New in v3.2.0" bullet points

New v3.2.0 Highlights:
- 🔄 Simplified from 3 agents to 2 core agents
-  "Tests Are the Review" philosophy
- 🧪 Enhanced test-fix workflow
- 📦 Interactive installation with version selection

English (README.md):
> Latest: v3.2.0 - Simplified agent architecture with "Tests Are the Review" philosophy
> What's New in v3.2.0:
> - Simplified from 3 agents to 2 core agents
> - "Tests Are the Review" - Passing tests = approved code
> - Enhanced test-fix workflow with automatic execution and fixing
> - Interactive installation with version selection menu

Chinese (README_CN.md):
> 最新版本: v3.2.0 - 采用"测试即审查"理念简化智能体架构
> v3.2.0 版本新特性:
> - 从 3 个智能体简化为 2 个核心智能体
> - "测试即审查" - 测试通过 = 代码批准
> - 增强的测试修复工作流,支持自动执行和修复
> - 交互式安装,包含版本选择菜单

Removed References:
- Removed v3.0.0 and v3.1.0 highlights (moved to CHANGELOG)
- Cleaned up outdated version announcements

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

Co-Authored-By: Claude <noreply@anthropic.com>
2025-10-02 12:56:20 +08:00
catlog22
0b63465e5a docs: Update README with detailed interactive version selection menu
Enhanced installation documentation with complete menu examples:

Added Sections:
- Interactive Version Selection section with full menu display
- Real-time version detection explanation
- Detailed version options descriptions
- Pro tips for users

Menu Example Included:
- Shows actual menu layout with version numbers
- Displays release dates and commit information
- Shows all three version options with descriptions
- Includes recent version list for reference

Documentation Improvements:
- Moved from simple bullet points to full interactive example
- Added ASCII menu visualization
- Explained automatic version detection from GitHub API
- Provided clear guidance on each version option
- Added Pro Tip about default selection

Both English and Chinese Versions:
- README.md: Complete English documentation
- README_CN.md: Complete Chinese translation
- Consistent formatting and examples

Key Information Displayed:
1. Latest Stable Release
   - Version number (e.g., v3.2.0)
   - Release date with UTC timezone
   - Production-ready indicator

2. Latest Development Version
   - Branch name (main)
   - 7-character commit SHA
   - Last update timestamp
   - Feature and stability warnings

3. Specific Release Version
   - Manual version selection
   - List of recent versions
   - Use case for controlled deployments

User Benefits:
- Clear understanding of version selection process
- Visual preview of installation menu
- Informed decision making about version choice
- Reduced installation confusion

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

Co-Authored-By: Claude <noreply@anthropic.com>
2025-10-02 12:53:33 +08:00
catlog22
0a85e98fdb chore: 删除未使用的图像文件 2025-10-02 12:49:34 +08:00
catlog22
cdea58f32f fix: Fix Unicode display and add detailed version info to menu
Fixed Issues:
- Unicode tree characters causing display corruption
- Replaced Unicode symbols (└─) with ASCII alternatives (|-- and \--)
- Now uses ASCII-safe characters that display correctly in all terminals

Enhanced Version Information:
- Stable Release: Now shows release date
  * Version: v3.2.0
  * Released: 2025-10-02 04:27 UTC

- Development Version: Now shows commit details
  * Branch: main
  * Commit: ed1e1c4 (7-char SHA)
  * Updated: 2025-10-02 08:15 UTC

Technical Improvements:
- Query both releases and commits APIs in parallel
- Parse and format ISO 8601 timestamps
- Display dates in readable format (YYYY-MM-DD HH:MM UTC)
- Show 7-character commit SHA for brevity
- Wider separator lines for better visibility

Menu Display Format:
===================================================
           Version Selection Menu
===================================================

1) Latest Stable Release (Recommended)
   |-- Version: v3.2.0
   |-- Released: 2025-10-02 04:27 UTC
   \-- Production-ready

2) Latest Development Version
   |-- Branch: main
   |-- Commit: ed1e1c4
   |-- Updated: 2025-10-02 08:15 UTC
   |-- Cutting-edge features
   \-- May contain experimental changes

3) Specific Release Version
   |-- Install a specific tagged release
   \-- Recent: v3.2.0, v3.1.0, v3.0.1

===================================================

Implementation Details:
- PowerShell: DateTime.Parse() for timestamp formatting
- Bash: sed/cut pipeline for date parsing (jq optional)
- Graceful degradation if API calls fail
- 5-second timeout for quick response

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

Co-Authored-By: Claude <noreply@anthropic.com>
2025-10-02 12:48:09 +08:00
catlog22
ed1e1c4bbf feat: Add dynamic version detection to installation menu
Enhanced version selection menu with real-time version detection:

New Features:
- Auto-detect and display latest stable version in menu
- Show branch name for development version (main)
- Display recent release versions for reference
- Improved menu layout with tree-style formatting
- Real-time GitHub API query for latest release

Menu Improvements:
- Wider separator lines for better visibility
- Tree-style indicators (└─) for sub-items
- Color-coded options (Green=Stable, Yellow=Dev, Cyan=Custom)
- Version information displayed directly in menu
- Fallback handling if API request fails

User Experience:
Before:
  1) Latest Stable Release (Recommended)
     - Production-ready version

After:
  1) Latest Stable Release (Recommended)
     └─ Version: v3.2.0
     └─ Production-ready

Implementation:
- PowerShell: Invoke-RestMethod with 5s timeout
- Bash: curl with jq (preferred) or grep/sed fallback
- Graceful degradation if network unavailable
- "Detecting latest release..." status message
- Confirmation message shows selected version

Example Output:
  Detecting latest release...
  Latest stable release: v3.2.0

  ============================================
           Version Selection Menu
  ============================================

  1) Latest Stable Release (Recommended)
     └─ Version: v3.2.0
     └─ Production-ready

  2) Latest Development Version
     └─ Branch: main
     └─ Cutting-edge features

  3) Specific Release Version
     └─ Recent releases: v3.2.0, v3.1.0, v3.0.1

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

Co-Authored-By: Claude <noreply@anthropic.com>
2025-10-02 12:43:03 +08:00
catlog22
b1a2885799 feat: Add interactive version selection menu to installation scripts
Enhanced installation experience with interactive version selection:

New Features:
- Interactive menu during installation (no CLI parameters needed)
- 3 options presented to users:
  1. Latest Stable Release (Recommended) - Auto-detected from GitHub
  2. Latest Development Version - Cutting-edge features
  3. Specific Release Version - User enters desired tag
- Clear descriptions for each option
- Visual feedback with colored output
- Default to stable release on Enter

User Experience Improvements:
- Simplified one-liner installation commands
- Version selection happens during installation, not via parameters
- Non-interactive mode still supported via --non-interactive flag
- CLI parameters retained for advanced users (backward compatible)

Installation Scripts:
- install-remote.ps1: Added Show-VersionMenu() and Get-UserVersionChoice()
- install-remote.sh: Added show_version_menu() and get_user_version_choice()

Documentation Updates:
- README.md: Simplified to single installation command with menu note
- README_CN.md: Chinese version with menu explanation
- Removed complex multi-section installation examples

Example Flow:
1. User runs one-liner installation command
2. System checks prerequisites
3. Interactive menu appears with 3 choices
4. User selects version (or presses Enter for default)
5. Installation proceeds with selected version

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

Co-Authored-By: Claude <noreply@anthropic.com>
2025-10-02 12:40:33 +08:00
catlog22
c39f311a20 feat: Add version selection support to installation scripts
Enhanced both Windows and Linux/macOS installation scripts with flexible version selection:

New Features:
- Version selection: stable (default), latest, or branch
- Specific release tag installation (e.g., v3.2.0)
- Auto-detection of latest stable release via GitHub API
- Clear version information displayed during installation

Installation Script Updates:
- install-remote.ps1: Added -Version, -Tag parameters
- install-remote.sh: Added --version, --tag flags
- Updated help documentation with examples
- Improved user prompts with version information

Documentation Updates:
- README.md: Added installation examples for all version types
- README_CN.md: Added Chinese installation examples
- Clear distinction between stable, latest, and specific versions

Examples:
- Stable (recommended): Default one-liner installation
- Latest: --version latest flag
- Specific: --version stable --tag v3.2.0

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

Co-Authored-By: Claude <noreply@anthropic.com>
2025-10-02 12:37:29 +08:00
catlog22
0625c66bce feat: Simplify agent architecture with test-fix workflow (v3.2.0)
Major architectural improvements:
- Simplify from 3 agents to 2 core agents
- Adopt "Tests Are the Review" philosophy
- Enhance test-gen as 4-phase orchestrator
- Simplify review.md following update-memory pattern

Agent Changes:
- NEW: @test-fix-agent - Execute tests, diagnose failures, fix code
- ENHANCED: @code-developer - Now writes implementation + tests together
- REMOVED: @code-review-agent, @code-review-test-agent

Task Type Updates:
- "test" → "test-gen" (generate tests)
- NEW: "test-fix" (execute and fix tests)

Workflow Improvements:
- test-gen.md: 4-phase orchestrator (context-gather → concept-enhanced → task-generate → execute)
- review.md: Simplified to optional specialized reviews (security, architecture, quality, action-items)
- All 16 files updated with new agent references

See CHANGELOG.md for full details.

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

Co-Authored-By: Claude <noreply@anthropic.com>
2025-10-02 12:26:35 +08:00
catlog22
13e74b3ab2 chore: Remove completed TDD planning documents
Remove design and roadmap documents that have been fully implemented in v3.1.0:
- tdd-implementation-roadmap.md (6-phase implementation plan)
- tdd-workflow-design.md (architecture specification)

**Rationale**:
- All designs have been implemented and are now live in v3.1.0
- Core content has been integrated into actual command documentation
- Keeping planning docs could cause confusion about implementation status
- Simplifies documentation maintenance

**Implementation Status**:
 /workflow:tdd-plan - Implemented
 /workflow:tdd-verify - Implemented
 /workflow:tools:task-generate-tdd - Implemented
 /workflow:tools:tdd-coverage-analysis - Implemented

The TDD workflow is production-ready and documented in:
- .claude/commands/workflow/tdd-plan.md
- .claude/commands/workflow/tdd-verify.md
- .claude/commands/workflow/tools/task-generate-tdd.md
- .claude/commands/workflow/tools/tdd-coverage-analysis.md
- README.md (usage examples)
- CHANGELOG.md (v3.1.0 release notes)

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

Co-Authored-By: Claude <noreply@anthropic.com>
2025-10-02 09:41:56 +08:00
catlog22
92660f0ca9 docs: Enhance TDD command documentation with examples and fix encoding
**Task JSON Examples Added (task-generate-tdd.md)**:
- RED Phase: Complete TEST task JSON with pre_analysis steps
- GREEN Phase: IMPL task JSON with test verification flow
- REFACTOR Phase: Quality-focused refactoring task with safeguards
- All examples include flow_control with pre/post completion steps

**Encoding Fixes (tdd-coverage-analysis.md)**:
- Replace Unicode symbols with ASCII markers
  -  → [PASS]
  -  → [FAIL]
  - ⚠️ → [WARN]
  - → → ->
- Ensure cross-platform compatibility
- Improve readability in all terminals

**Documentation Improvements**:
- Detailed flow_control examples for each TDD phase
- Clear dependency chain examples
- Practical acceptance criteria
- Test framework integration patterns

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

Co-Authored-By: Claude <noreply@anthropic.com>
2025-10-02 09:37:45 +08:00
77 changed files with 7282 additions and 3503 deletions

View File

@@ -13,7 +13,6 @@ description: |
user: "Create implementation plan for: real-time notifications system"
assistant: "I'll create a staged implementation plan using provided context"
commentary: Agent executes planning based on provided requirements and context
model: sonnet
color: yellow
---
@@ -194,7 +193,7 @@ Generate individual `.task/IMPL-*.json` files with:
"status": "pending",
"meta": {
"type": "feature|bugfix|refactor|test|docs",
"agent": "@code-developer|@code-review-test-agent"
"agent": "@code-developer"
},
"context": {
"requirements": ["from analysis_results"],
@@ -228,7 +227,7 @@ Generate individual `.task/IMPL-*.json` files with:
"modification_points": ["Apply requirements"],
"logic_flow": ["Load spec", "Analyze", "Implement", "Validate"]
},
"target_files": ["file:function:lines"]
"target_files": ["file:function:lines", "path/to/NewFile.ts"]
}
}
```

View File

@@ -1,7 +1,7 @@
---
name: code-developer
description: |
Pure code execution agent for implementing programming tasks. Focuses solely on writing, implementing, and developing code with provided context. Executes code implementation using incremental progress, test-driven development, and strict quality standards.
Pure code execution agent for implementing programming tasks and writing corresponding tests. Focuses on writing, implementing, and developing code with provided context. Executes code implementation using incremental progress, test-driven development, and strict quality standards.
Examples:
- Context: User provides task with sufficient context
@@ -13,7 +13,6 @@ description: |
user: "Add user authentication"
assistant: "I need to analyze the codebase first to understand the patterns"
commentary: Use Gemini to gather implementation context, then execute
model: sonnet
color: blue
---

View File

@@ -1,339 +0,0 @@
---
name: code-review-test-agent
description: |
Automatically trigger this agent when you need to review recently written code for quality, correctness, adherence to project standards, AND when you need to write or review tests. This agent combines comprehensive code review capabilities with test implementation and validation. Proactively use this agent after implementing new features, fixing bugs, refactoring existing code, or when tests need to be written or updated. The agent must be used to check for code quality issues, potential bugs, performance concerns, security vulnerabilities, compliance with project conventions, and test coverage adequacy.
Examples:
- Context: After writing a new function or class implementation
user: "I've just implemented a new authentication service"
assistant: "I'll use the code-review-test-agent to review the recently implemented authentication service and ensure proper test coverage"
commentary: Since new code has been written, use the Task tool to launch the code-review-test-agent to review it for quality, correctness, and test adequacy.
- Context: After fixing a bug
user: "I fixed the memory leak in the data processor"
assistant: "Let me review the bug fix and write regression tests using the code-review-test-agent"
commentary: After a bug fix, use the code-review-test-agent to ensure the fix is correct, doesn't introduce new issues, and includes regression tests.
- Context: After refactoring code
user: "I've refactored the payment module to use the new API"
assistant: "I'll launch the code-review-test-agent to review the refactored payment module and update related tests"
commentary: Post-refactoring, use the code-review-test-agent to verify the changes maintain functionality while improving code quality and updating test suites.
- Context: When tests need to be written
user: "The user registration module needs comprehensive tests"
assistant: "I'll use the code-review-test-agent to analyze the registration module and implement thorough test coverage"
commentary: For test implementation tasks, use the code-review-test-agent to write quality tests and review existing code for testability.
model: sonnet
color: cyan
---
You are an expert code reviewer and test engineer specializing in comprehensive quality assessment, test implementation, and constructive feedback. Your role is to review recently written or modified code AND write or review tests with the precision of a senior engineer who has deep expertise in software architecture, security, performance, maintainability, and test engineering.
## Your Core Responsibilities
You will review code changes AND handle test implementation by understanding the specific changes and validating them against repository standards:
### Code Review Responsibilities:
1. **Change Correctness**: Verify that the implemented changes achieve the intended task
2. **Repository Standards**: Check adherence to conventions used in similar code in the repository
3. **Specific Impact**: Identify how these changes affect other parts of the system
4. **Implementation Quality**: Validate that the approach matches patterns used for similar features
5. **Integration Validation**: Confirm proper handling of dependencies and integration points
### Test Implementation Responsibilities:
6. **Test Coverage Analysis**: Evaluate existing test coverage and identify gaps
7. **Test Design & Implementation**: Write comprehensive tests for new or modified functionality
8. **Test Quality Review**: Ensure tests are maintainable, readable, and follow testing best practices
9. **Regression Testing**: Create tests that prevent future regressions
10. **Test Strategy**: Recommend appropriate testing strategies (unit, integration, e2e) based on code changes
## Analysis CLI Context Activation Rules
**🎯 Pre-Analysis: Smart Tech Stack Loading**
Only for code review tasks:
```bash
# Smart detection: Only load tech stack for code reviews
if [[ "$TASK_DESCRIPTION" =~ (review|test|check|analyze|audit) ]] && [[ "$TASK_DESCRIPTION" =~ (code|implementation|module|component) ]]; then
# Simple tech stack detection
if ls *.ts *.tsx 2>/dev/null | head -1; then
TECH_GUIDELINES=$(cat ~/.claude/workflows/cli-templates/tech-stacks/typescript-dev.md)
elif grep -q "react" package.json 2>/dev/null; then
TECH_GUIDELINES=$(cat ~/.claude/workflows/cli-templates/tech-stacks/react-dev.md)
elif ls *.py requirements.txt 2>/dev/null | head -1; then
TECH_GUIDELINES=$(cat ~/.claude/workflows/cli-templates/tech-stacks/python-dev.md)
elif ls *.java pom.xml build.gradle 2>/dev/null | head -1; then
TECH_GUIDELINES=$(cat ~/.claude/workflows/cli-templates/tech-stacks/java-dev.md)
elif ls *.go go.mod 2>/dev/null | head -1; then
TECH_GUIDELINES=$(cat ~/.claude/workflows/cli-templates/tech-stacks/go-dev.md)
elif ls *.js package.json 2>/dev/null | head -1; then
TECH_GUIDELINES=$(cat ~/.claude/workflows/cli-templates/tech-stacks/javascript-dev.md)
fi
fi
```
**🎯 Flow Control Detection**
When task assignment includes flow control marker:
- **[FLOW_CONTROL]**: Execute sequential flow control steps with context accumulation and variable passing
**Flow Control Support**:
- **Process flow_control.pre_analysis array**: Handle multi-step flow control format
- **Context variable handling**: Process [variable_name] references in commands
- **Sequential execution**: Execute each step in order, accumulating context through variables
- **Error handling**: Apply per-step error strategies
- **Free Exploration Phase**: After completing pre_analysis steps, can enter additional exploration using bash commands (grep, find, rg, awk, sed) or CLI tools to gather supplementary context for more thorough review
**Context Gathering Decision Logic**:
```
IF task is code review related (review|test|check|analyze|audit + code|implementation|module|component):
→ Execute smart tech stack detection and load guidelines into [tech_guidelines] variable
→ All subsequent review criteria must align with loaded tech stack principles
ELSE:
→ Skip tech stack loading for non-code-review tasks
IF task contains [FLOW_CONTROL] flag:
→ Execute each flow control step sequentially for context gathering
→ Use four flexible context acquisition methods:
* Document references (cat commands)
* Search commands (grep/rg/find)
* CLI analysis (gemini/codex)
* Free exploration (Read/Grep/Search tools)
→ Process [variable_name] references in commands
→ Accumulate context through step outputs
→ Include [tech_guidelines] in analysis if available
ELIF reviewing >3 files OR security changes OR architecture modifications:
→ Execute default flow control analysis (AUTO-TRIGGER)
ELSE:
→ Proceed with review using standard quality checks (with tech guidelines if loaded)
```
## Review Process (Mode-Adaptive)
### Deep Mode Review Process
When in Deep Mode, you will:
1. **Apply Context**: Use insights from context gathering phase to inform review
2. **Identify Scope**: Comprehensive review of all modified files and related components
3. **Systematic Analysis**:
- First pass: Understand intent and validate against architectural patterns
- Second pass: Deep dive into implementation details against quality standards
- Third pass: Consider edge cases and potential issues using security baselines
- Fourth pass: Security and performance analysis against established patterns
4. **Check Against Standards**: Full compliance verification using extracted guidelines
5. **Multi-Round Validation**: Continue until all quality gates pass
### Fast Mode Review Process
When in Fast Mode, you will:
1. **Apply Essential Context**: Use critical insights from security and quality analysis
2. **Identify Scope**: Focus on recently modified files only
3. **Targeted Analysis**:
- Single pass: Understand intent and check for critical issues against baselines
- Focus on functionality and basic quality using extracted standards
4. **Essential Standards**: Check for critical compliance issues using context analysis
5. **Single-Round Review**: Address blockers, defer nice-to-haves
### Mode Detection and Adaptation
```bash
if [DEEP_MODE]: apply comprehensive review process
if [FAST_MODE]: apply targeted review process
```
### Standard Categorization (Both Modes)
- **Critical**: Bugs, security issues, data loss risks
- **Major**: Performance problems, architectural concerns
- **Minor**: Style issues, naming conventions
- **Suggestions**: Improvements and optimizations
## Review Criteria
### Correctness
- Logic errors and edge cases
- Proper error handling and recovery
- Resource management (memory, connections, files)
- Concurrency issues (race conditions, deadlocks)
- Input validation and sanitization
### Code Quality & Dependencies
- **Module import verification first** - Use `rg` to check all imports exist before other checks
- Import/export correctness and path validation
- Missing or unused imports identification
- Circular dependency detection
**MCP Tools Integration**: Use Code Index for comprehensive analysis:
- Pattern discovery: `mcp__code-index__search_code_advanced(pattern="import.*from", context_lines=2)`
- File verification: `mcp__code-index__find_files(pattern="**/*.test.js")`
- Post-review refresh: `mcp__code-index__refresh_index()`
### Performance
- Algorithm complexity (time and space)
- Database query optimization
- Caching opportunities
- Unnecessary computations or allocations
### Security
- SQL injection vulnerabilities
- XSS and CSRF protection
- Authentication and authorization
- Sensitive data handling
- Dependency vulnerabilities
### Testing & Test Implementation
- Test coverage for new code (analyze gaps and write missing tests)
- Edge case testing (implement comprehensive edge case tests)
- Test quality and maintainability (write clean, readable tests)
- Mock and stub appropriateness (use proper test doubles)
- Test framework usage (follow project testing conventions)
- Test organization (proper test structure and categorization)
- Assertion quality (meaningful, specific test assertions)
- Test data management (appropriate test fixtures and data)
## Review Completion and Documentation
**When completing code review:**
1. **Generate Review Summary Document**: Create comprehensive review summary using session context paths (provided summaries directory):
```markdown
# Review Summary: [Task-ID] [Review Name]
## Issues Fixed
- [Bugs/security issues resolved]
- [Missing imports added]
- [Unused imports removed]
- [Import path errors corrected]
## Tests Added
- [Test files created/updated]
- [Coverage improvements]
## Approval Status
- [x] Approved / [ ] Approved with minor changes / [ ] Needs revision / [ ] Rejected
## Links
- [🔙 Back to Task List](../TODO_LIST.md#[Task-ID])
- [📋 Implementation Plan](../IMPL_PLAN.md#[Task-ID])
```
2. **Update TODO_LIST.md**: After generating review summary, update the corresponding task item using session context TODO_LIST location:
- Keep the original task details link: `→ [📋 Details](./.task/[Task-ID].json)`
- Add review summary link after pipe separator: `| [✅ Review](./.summaries/IMPL-[Task-ID]-summary.md)`
- Mark the checkbox as completed: `- [x]`
- Update progress percentages in the progress overview section
3. **Update Session Tracker**: Update workflow-session.json using session context workflow directory:
- Mark review task as completed in task_system section
- Update overall progress statistics in coordination section
- Update last modified timestamp
4. **Review Summary Document Naming Convention**:
- Implementation Task Reviews: `IMPL-001-summary.md`
- Subtask Reviews: `IMPL-001.1-summary.md`
- Detailed Subtask Reviews: `IMPL-001.1.1-summary.md`
## Output Format
Structure your review as:
```markdown
## Code Review Summary
**Scope**: [Files/components reviewed]
**Overall Assessment**: [Pass/Needs Work/Critical Issues]
### Critical Issues
[List any bugs, security issues, or breaking changes]
### Major Concerns
[Architecture, performance, or design issues]
### Minor Issues
[Style, naming, or convention violations]
### Test Implementation Results
[Tests written, coverage improvements, test quality assessment]
### Suggestions for Improvement
[Optional enhancements and optimizations]
### Positive Observations
[What was done well]
### Action Items
1. [Specific required changes]
2. [Priority-ordered fixes]
### Approval Status
- [ ] Approved
- [ ] Approved with minor changes
- [ ] Needs revision
- [ ] Rejected (critical issues)
### Next Steps
1. Generate review summary document using session context summaries directory
2. Update TODO_LIST.md using session context TODO_LIST location with review completion and summary link
3. Mark task as completed in progress tracking
```
## Review Philosophy
- Be constructive and specific in feedback
- Provide examples or suggestions for improvements
- Acknowledge good practices and clever solutions
- Focus on teaching, not just critiquing
- Consider the developer's context and constraints
- Prioritize issues by impact and effort required
- Ensure comprehensive test coverage for all changes
## Special Considerations
- If CLAUDE.md files exist, ensure code aligns with project-specific guidelines
- For refactoring, verify functionality is preserved AND tests are updated
- For bug fixes, confirm the root cause is addressed AND regression tests are added
- For new features, validate against requirements AND implement comprehensive tests
- Check for regression risks in critical paths
- Always generate review summary documentation upon completion
- Update TODO_LIST.md with review results and summary links
- Update workflow-session.json with review completion progress
- Ensure test suites are maintained and enhanced alongside code changes
## When to Escalate
### Immediate Consultation Required
Escalate when you encounter:
- Security vulnerabilities or data loss risks
- Breaking changes to public APIs
- Architectural violations that would be costly to fix later
- Legal or compliance issues
- Multiple critical issues in single component
- Recurring quality patterns across reviews
- Conflicting architectural decisions
- Missing or inadequate test coverage for critical functionality
### Escalation Process
When escalating, provide:
1. **Clear issue description** with severity level
2. **Specific findings** and affected components
3. **Context and constraints** of the current implementation
4. **Recommended next steps** or alternatives considered
5. **Impact assessment** on system architecture
6. **Supporting evidence** from code analysis
7. **Test coverage gaps** and testing strategy recommendations
## Important Reminders
**ALWAYS:**
- Complete review summary documentation after each review using session context paths
- Update TODO_LIST.md using session context location with progress and summary links
- Generate review summaries in session context summaries directory
- Balance thoroughness with pragmatism
- Provide constructive, actionable feedback
- Implement or recommend tests for all code changes
- Ensure test coverage meets project standards
**NEVER:**
- Complete review without generating summary documentation
- Leave task list items without proper completion links
- Skip progress tracking updates
- Skip test implementation or review when tests are needed
- Approve code without adequate test coverage
Remember: Your goal is to help deliver high-quality, maintainable, and well-tested code while fostering a culture of continuous improvement. Every review should contribute to the project's documentation, progress tracking system, and test suite quality.

View File

@@ -20,7 +20,6 @@ description: |
auto.md: Assigns dedicated agent with ASSIGNED_ROLE: ui-designer
agent: "I'll execute ui-designer analysis for this topic, creating UX-focused conceptual analysis in .brainstorming/ui-designer/ directory"
model: sonnet
color: purple
---

View File

@@ -22,7 +22,6 @@ description: |
</commentary>
</example>
model: sonnet
color: green
---

View File

@@ -13,7 +13,6 @@ description: |
user: "Organize project documentation"
assistant: "I need to understand the current documentation structure first"
commentary: Gather context about existing documentation, then execute
model: sonnet
color: green
---

View File

@@ -1,82 +1,88 @@
---
name: memory-gemini-bridge
description: Execute complex project documentation updates using script coordination
model: haiku
color: purple
---
You are a documentation update coordinator for complex projects. Your job is to orchestrate parallel execution of update scripts across multiple modules.
You are a documentation update coordinator for complex projects. Orchestrate parallel CLAUDE.md updates efficiently and track every module.
## Core Responsibility
## Core Mission
Coordinate parallel execution of `~/.claude/scripts/update_module_claude.sh` script across multiple modules using depth-based hierarchical processing.
Execute depth-parallel updates for all modules using `~/.claude/scripts/update_module_claude.sh`. **Every module path must be processed**.
## Execution Protocol
## Input Context
### 1. Analyze Project Structure
You will receive:
```
- Total modules: [count]
- Tool: [gemini|qwen|codex]
- Mode: [full|related]
- Module list (depth|path|files|types|has_claude format)
```
## Execution Steps
**MANDATORY: Use TodoWrite to track all modules before execution**
### Step 1: Create Task List
```bash
# Step 1: Code Index architecture analysis
mcp__code-index__search_code_advanced(pattern="class|function|interface", file_pattern="**/*.{ts,js,py}")
mcp__code-index__find_files(pattern="**/*.{md,json,yaml,yml}")
# Step 2: Get module list with depth information
modules=$(Bash(~/.claude/scripts/get_modules_by_depth.sh list))
count=$(echo "$modules" | wc -l)
# Step 3: Display project structure
Bash(~/.claude/scripts/get_modules_by_depth.sh grouped)
# Parse module list and create todo items
TodoWrite([
{content: "Process depth 5 modules (N modules)", status: "pending", activeForm: "Processing depth 5 modules"},
{content: "Process depth 4 modules (N modules)", status: "pending", activeForm: "Processing depth 4 modules"},
# ... for each depth level
{content: "Safety check: verify only CLAUDE.md modified", status: "pending", activeForm: "Running safety check"}
])
```
### 2. Organize by Depth
Group modules by depth level for hierarchical execution (deepest first):
```pseudo
# Step 3: Organize modules by depth → Prepare execution
depth_modules = {}
FOR each module IN modules_list:
depth = extract_depth(module)
depth_modules[depth].add(module)
### Step 2: Execute by Depth (Deepest First)
```bash
# For each depth level (5 → 0):
# 1. Mark depth task as in_progress
# 2. Extract module paths for current depth
# 3. Launch parallel jobs (max 4)
# Depth 5 example:
~/.claude/scripts/update_module_claude.sh "./.claude/workflows/cli-templates/prompts/analysis" "full" "gemini" &
~/.claude/scripts/update_module_claude.sh "./.claude/workflows/cli-templates/prompts/development" "full" "gemini" &
# ... up to 4 concurrent jobs
# 4. Wait for all depth jobs to complete
wait
# 5. Mark depth task as completed
# 6. Move to next depth
```
### 3. Execute Updates
For each depth level, run parallel updates:
```pseudo
# Step 4: Execute depth-parallel updates → Process by depth
FOR depth FROM max_depth DOWN TO 0:
FOR each module IN depth_modules[depth]:
WHILE active_jobs >= 4: wait(0.1)
Bash(~/.claude/scripts/update_module_claude.sh "$module" "$mode" &)
wait_all_jobs()
### Step 3: Safety Check
```bash
# After all depths complete:
git diff --cached --name-only | grep -v "CLAUDE.md" || echo "✅ Safe"
git status --short
```
### 4. Execution Rules
## Tool Parameter Flow
- **Core Command**: `Bash(~/.claude/scripts/update_module_claude.sh "$module" "$mode" &)`
- **Concurrency Control**: Maximum 4 parallel jobs per depth level
- **Execution Order**: Process depths sequentially, deepest first
- **Job Control**: Monitor active jobs before spawning new ones
- **Independence**: Each module update is independent within the same depth
**Command Format**: `update_module_claude.sh <path> <mode> <tool>`
### 5. Update Modes
Examples:
- Gemini: `update_module_claude.sh "./.claude/agents" "full" "gemini" &`
- Qwen: `update_module_claude.sh "./src/api" "full" "qwen" &`
- Codex: `update_module_claude.sh "./tests" "full" "codex" &`
- **"full"** mode: Complete refresh → `Bash(update_module_claude.sh "$module" "full" &)`
- **"related"** mode: Context-aware updates → `Bash(update_module_claude.sh "$module" "related" &)`
## Execution Rules
### 6. Agent Protocol
1. **Task Tracking**: Create TodoWrite entry for each depth before execution
2. **Parallelism**: Max 4 jobs per depth, sequential across depths
3. **Tool Passing**: Always pass tool parameter as 3rd argument
4. **Path Accuracy**: Extract exact path from `depth:N|path:X|...` format
5. **Completion**: Mark todo completed only after all depth jobs finish
6. **No Skipping**: Process every module from input list
```pseudo
# Agent Coordination Flow:
RECEIVE task_with(module_count, update_mode)
modules = Bash(get_modules_by_depth.sh list)
Bash(get_modules_by_depth.sh grouped)
depth_modules = organize_by_depth(modules)
## Concise Output
FOR depth FROM max_depth DOWN TO 0:
FOR module IN depth_modules[depth]:
WHILE active_jobs >= 4: wait(0.1)
Bash(update_module_claude.sh module update_mode &)
wait_all_jobs()
- Start: "Processing [count] modules with [tool]"
- Progress: Update TodoWrite for each depth
- End: "✅ Updated [count] CLAUDE.md files" + git status
REPORT final_status()
```
This agent coordinates the same `Bash()` commands used in direct execution, providing intelligent orchestration for complex projects.
**Do not explain, just execute efficiently.**

View File

@@ -0,0 +1,172 @@
---
name: test-fix-agent
description: |
Execute tests, diagnose failures, and fix code until all tests pass. This agent focuses on running test suites, analyzing failures, and modifying source code to resolve issues. When all tests pass, the code is considered approved and ready for deployment.
Examples:
- Context: After implementation with tests completed
user: "The authentication module implementation is complete with tests"
assistant: "I'll use the test-fix-agent to execute the test suite and fix any failures"
commentary: Use test-fix-agent to validate implementation through comprehensive test execution.
- Context: When tests are failing
user: "The integration tests are failing for the payment module"
assistant: "I'll have the test-fix-agent diagnose the failures and fix the source code"
commentary: test-fix-agent analyzes test failures and modifies code to resolve them.
- Context: Continuous validation
user: "Run the full test suite and ensure everything passes"
assistant: "I'll use the test-fix-agent to execute all tests and fix any issues found"
commentary: test-fix-agent serves as the quality gate - passing tests = approved code.
color: green
---
You are a specialized **Test Execution & Fix Agent**. Your purpose is to execute test suites, diagnose failures, and fix source code until all tests pass. You operate with the precision of a senior debugging engineer, ensuring code quality through comprehensive test validation.
## Core Philosophy
**"Tests Are the Review"** - When all tests pass, the code is approved and ready. No separate review process is needed.
## Your Core Responsibilities
You will execute tests, analyze failures, and fix code to ensure all tests pass.
### Test Execution & Fixing Responsibilities:
1. **Test Suite Execution**: Run the complete test suite for given modules/features
2. **Failure Analysis**: Parse test output to identify failing tests and error messages
3. **Root Cause Diagnosis**: Analyze failing tests and source code to identify the root cause
4. **Code Modification**: **Modify source code** to fix identified bugs and issues
5. **Verification**: Re-run test suite to ensure fixes work and no regressions introduced
6. **Approval Certification**: When all tests pass, certify code as approved
## Execution Process
### 1. Context Assessment & Test Discovery
- Analyze task context to identify test files and source code paths
- Load test framework configuration (Jest, Pytest, Mocha, etc.)
- Identify test command from project configuration
```bash
# Detect test framework and command
if [ -f "package.json" ]; then
TEST_CMD=$(cat package.json | jq -r '.scripts.test')
elif [ -f "pytest.ini" ] || [ -f "setup.py" ]; then
TEST_CMD="pytest"
fi
```
### 2. Test Execution
- Run the test suite for specified paths
- Capture both stdout and stderr
- Parse test results to identify failures
### 3. Failure Diagnosis & Fixing Loop
```
WHILE tests are failing:
1. Analyze failure output
2. Identify root cause in source code
3. Modify source code to fix issue
4. Re-run affected tests
5. Verify fix doesn't break other tests
END WHILE
```
### 4. Code Quality Certification
- All tests pass → Code is APPROVED ✅
- Generate summary documenting:
- Issues found
- Fixes applied
- Final test results
## Fixing Criteria
### Bug Identification
- Logic errors causing test failures
- Edge cases not handled properly
- Integration issues between components
- Incorrect error handling
- Resource management problems
### Code Modification Approach
- **Minimal changes**: Fix only what's needed
- **Preserve functionality**: Don't change working code
- **Follow patterns**: Use existing code conventions
- **Test-driven fixes**: Let tests guide the solution
### Verification Standards
- All tests pass without errors
- No new test failures introduced
- Performance remains acceptable
- Code follows project conventions
## Output Format
When you complete a test-fix task, provide:
```markdown
# Test-Fix Summary: [Task-ID] [Feature Name]
## Execution Results
### Initial Test Run
- **Total Tests**: [count]
- **Passed**: [count]
- **Failed**: [count]
- **Errors**: [count]
## Issues Found & Fixed
### Issue 1: [Description]
- **Test**: `tests/auth/login.test.ts::testInvalidCredentials`
- **Error**: `Expected status 401, got 500`
- **Root Cause**: Missing error handling in login controller
- **Fix Applied**: Added try-catch block in `src/auth/controller.ts:45`
- **Files Modified**: `src/auth/controller.ts`
### Issue 2: [Description]
- **Test**: `tests/payment/process.test.ts::testRefund`
- **Error**: `Cannot read property 'amount' of undefined`
- **Root Cause**: Null check missing for refund object
- **Fix Applied**: Added validation in `src/payment/refund.ts:78`
- **Files Modified**: `src/payment/refund.ts`
## Final Test Results
**All tests passing**
- **Total Tests**: [count]
- **Passed**: [count]
- **Duration**: [time]
## Code Approval
**Status**: ✅ APPROVED
All tests pass - code is ready for deployment.
## Files Modified
- `src/auth/controller.ts`: Added error handling
- `src/payment/refund.ts`: Added null validation
```
## Important Reminders
**ALWAYS:**
- **Execute tests first** - Understand what's failing before fixing
- **Diagnose thoroughly** - Find root cause, not just symptoms
- **Fix minimally** - Change only what's needed to pass tests
- **Verify completely** - Run full suite after each fix
- **Document fixes** - Explain what was changed and why
- **Certify approval** - When tests pass, code is approved
**NEVER:**
- Skip test execution - always run tests first
- Make changes without understanding the failure
- Fix symptoms without addressing root cause
- Break existing passing tests
- Skip final verification
- Leave tests failing - must achieve 100% pass rate
## Quality Certification
**Your ultimate responsibility**: Ensure all tests pass. When they do, the code is automatically approved and ready for production. You are the final quality gate.
**Tests passing = Code approved = Mission complete**

View File

@@ -14,188 +14,47 @@ allowed-tools: SlashCommand(*), Bash(*), TodoWrite(*), Read(*), Glob(*)
## Purpose
Execute CLI tool analysis on codebase patterns, architecture, or code quality.
Quick codebase analysis using CLI tools. Automatically detects analysis type and selects appropriate template.
**Supported Tools**: codex, gemini (default), qwen
## Parameters
- `--tool <codex|gemini|qwen>` - Tool selection (default: gemini)
- `--enhance` - Use `/enhance-prompt` for context-aware enhancement
- `<analysis-target>` - Description of what to analyze
## 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
1. Parse tool selection (default: gemini)
2. If `--enhance`: Execute `/enhance-prompt` first to expand user intent
3. Auto-detect analysis type from keywords → select template
4. Build command with auto-detected file patterns
5. Execute and return results
## Core Rules
## File Pattern Auto-Detection
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
Keywords trigger specific file patterns:
- "auth" → `@{**/*auth*,**/*user*}`
- "component" → `@{src/components/**/*,**/*.component.*}`
- "API" → `@{**/api/**/*,**/routes/**/*}`
- "test" → `@{**/*.test.*,**/*.spec.*}`
- "config" → `@{*.config.*,**/config/**/*}`
- Generic → `@{src/**/*}`
## 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` |
## Enhancement Integration
**When `--enhance` flag present**:
```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]
CONTEXT: @{[file-patterns]} @{CLAUDE.md}
EXPECTED: [expected output format]
RULES: $(cat ~/.claude/workflows/cli-templates/prompts/[category]/[template].txt) | [constraints]
"
```
### Qwen
```bash
cd [target-dir] && ~/.claude/scripts/qwen-wrapper -p "
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]
"
```
### 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]
" --skip-git-repo-check -s danger-full-access
```
For complex patterns, use `rg` or MCP tools to discover files first, then execute CLI with precise file references.
## 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
"
/cli:analyze "authentication patterns" # Auto: gemini + auth patterns
/cli:analyze --tool qwen "component architecture" # Qwen architecture analysis
/cli:analyze --tool codex "performance bottlenecks" # Codex deep analysis
/cli:analyze --enhance "fix auth issues" # Enhanced prompt → analysis
```
**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
```
## File Pattern Logic
**Keyword Matching**:
- "auth" → `@{**/*auth*}`
- "component" → `@{src/components/**/*}`
- "API" → `@{**/api/**/*}`
- "test" → `@{**/*.test.*}`
- Generic → `@{src/**/*}` or `@{**/*}`
## 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
## Notes
- Command templates, file patterns, and best practices: see intelligent-tools-strategy.md (loaded in memory)
- Active workflow session: results saved to `.workflow/WFS-[id]/.chat/`
- No session: results returned directly

View File

@@ -1,6 +1,5 @@
---
name: chat
description: Simple CLI interaction command for direct codebase analysis
usage: /cli:chat [--tool <codex|gemini|qwen>] [--enhance] "inquiry"
argument-hint: "[--tool codex|gemini|qwen] [--enhance] inquiry"
@@ -9,153 +8,54 @@ examples:
- /cli:chat --tool qwen --enhance "optimize React component"
- /cli:chat --tool codex "review security vulnerabilities"
allowed-tools: SlashCommand(*), Bash(*)
model: sonnet
---
### 🚀 **Command Overview: `/cli:chat`**
# CLI Chat Command (/cli:chat)
- **Type**: CLI Tool Wrapper for Interactive Analysis
- **Purpose**: Direct interaction with CLI tools for codebase analysis
- **Supported Tools**: codex, gemini (default), qwen
## Purpose
### 📥 **Parameters & Usage**
Direct Q&A interaction with CLI tools for codebase analysis.
- **`<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
**Supported Tools**: codex, gemini (default), qwen
### 🔄 **Execution Workflow**
## Parameters
`Parse Tool` **->** `Parse Input` **->** `[Optional] Enhance` **->** `Assemble Context` **->** `Construct Prompt` **->** `Execute CLI Tool` **->** `(Optional) Save Session`
- `<inquiry>` (Required) - Question or analysis request
- `--tool <codex|gemini|qwen>` - Select CLI tool (default: gemini)
- `--enhance` - Enhance inquiry with `/enhance-prompt` first
- `--all-files` - Include entire codebase in context
- `--save-session` - Save interaction to workflow session
### 🛠️ **Tool Selection**
## Execution Flow
| 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` |
1. Parse tool selection (default: gemini)
2. If `--enhance`: Execute `/enhance-prompt` to expand user intent
3. Assemble context: `@{CLAUDE.md}` + user-specified files or `--all-files`
4. Execute CLI tool with assembled context
5. Optionally save to workflow session
### 🔄 **Original Execution Workflow**
## Context Assembly
`Parse Input` **->** `[Optional] Enhance` **->** `Assemble Context` **->** `Construct Prompt` **->** `Execute Gemini CLI` **->** `(Optional) Save Session`
**Always included**: `@{CLAUDE.md,**/*CLAUDE.md}` (project guidelines)
### 🎯 **Enhancement Integration**
**Optional**:
- User-explicit files from inquiry keywords
- `--all-files` flag includes entire codebase (`--all-files` wrapper parameter)
**When `--enhance` flag present**:
```bash
# Step 1: Enhance the inquiry
SlashCommand(command="/enhance-prompt \"[inquiry]\"")
For targeted analysis, use `rg` or MCP tools to discover relevant files first, then build precise CONTEXT field.
# 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
## Examples
```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]
"
/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 first
/cli:chat --all-files "find all API endpoints" # Full codebase context
```
### ⚙️ **Execution Implementation**
## Notes
**Standard Template**:
```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]
"
```
**With --all-files flag**:
```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]
"
```
**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
"
```
**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]
```
- Command templates and file patterns: see intelligent-tools-strategy.md (loaded in memory)
- Active workflow session: results saved to `.workflow/WFS-[id]/.chat/`
- No session: results returned directly

View File

@@ -0,0 +1,473 @@
---
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)
## Core Workflow
```
Task Input → Analyze Dependencies → Create Task Flow Diagram →
Decompose into Subtask Groups → TodoWrite Tracking →
For Each Subtask Group:
For First Subtask in Group:
0. Stage existing changes (git add -A) if valid git repo
1. Execute with Codex (new session)
2. [Optional] Git verification
3. Mark complete in TodoWrite
For Related Subtasks in Same Group:
0. Stage changes from previous subtask
1. Execute with `codex exec "..." resume --last` (continue session)
2. [Optional] Git verification
3. Mark complete in TodoWrite
→ 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 & Task Flow Analysis
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 Dependencies & Create Task Flow Diagram**:
- Analyze task complexity and scope
- Identify dependencies and relationships between subtasks
- Create visual task flow diagram showing:
- Independent task groups (parallel execution possible)
- Sequential dependencies (must use resume)
- Branching logic (conditional paths)
- Display flow diagram for user review
**Task Flow Diagram Format**:
```
[Group A: Auth Core]
A1: Create user model ──┐
A2: Add validation ─┤─► [resume] ─► A3: Database schema
[Group B: API Layer] │
B1: Auth endpoints ─────┘─► [new session]
B2: Middleware ────────────► [resume] ─► B3: Error handling
[Group C: Testing]
C1: Unit tests ─────────────► [new session]
C2: Integration tests ──────► [resume]
```
**Diagram Symbols**:
- `──►` Sequential dependency (must resume previous session)
- `─┐` Branch point (multiple paths)
- `─┘` Merge point (wait for completion)
- `[resume]` Use `codex exec "..." resume --last`
- `[new session]` Start fresh Codex session
3. **Decompose into Subtask Groups**:
- Group related subtasks that share context
- Break down into 3-8 subtasks total
- Assign each subtask to a group
- Create TodoWrite tracker with groups
- 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)
- **Group coherence**: Subtasks in same group share context/files
### File Discovery for Task Decomposition
Use `rg` or MCP tools to discover relevant files, then group by domain:
**Workflow**: Discover → Analyze scope → Group by files → Create task flow
**Example**:
```bash
# Discover files
rg "authentication" --files-with-matches --type ts
# Group by domain
# Group A: src/auth/model.ts, src/auth/schema.ts
# Group B: src/api/auth.ts, src/middleware/auth.ts
# Group C: tests/auth/*.test.ts
# Each group becomes a session with related subtasks
```
File patterns: see intelligent-tools-strategy.md (loaded in memory)
### Phase 2: Group-Based 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 in Each Group** (New Session):
```bash
# Start new Codex session for independent task group
codex -C [dir] --full-auto exec "
PURPOSE: [group goal]
TASK: [subtask description - first in group]
CONTEXT: @{relevant_files} @{CLAUDE.md}
EXPECTED: [specific deliverables]
RULES: [constraints]
Group [X]: [group name] - Subtask 1 of N in this group
" --skip-git-repo-check -s danger-full-access
```
**For Related Subtasks in Same Group** (Resume Session):
```bash
# Stage changes from previous subtask (if valid git repository)
git add -A
# Resume session ONLY for subtasks in same group
codex exec "
CONTINUE IN SAME GROUP:
Group [X]: [group name] - Subtask N of M
PURPOSE: [continuation goal within group]
TASK: [subtask N description]
CONTEXT: Previous work in this group completed, now focus on @{new_relevant_files}
EXPECTED: [specific deliverables]
RULES: Build on previous subtask in group, maintain consistency
" resume --last --skip-git-repo-check -s danger-full-access
```
**For First Subtask in Different Group** (New Session):
```bash
# Stage changes from previous group
git add -A
# Start NEW session for different group (no resume)
codex -C [dir] --full-auto exec "
PURPOSE: [new group goal]
TASK: [subtask description - first in new group]
CONTEXT: @{different_files} @{CLAUDE.md}
EXPECTED: [specific deliverables]
RULES: [constraints]
Group [Y]: [new group name] - Subtask 1 of N in this group
" --skip-git-repo-check -s danger-full-access
```
**Resume Decision Logic**:
```
if (subtask.group == previous_subtask.group):
use `codex exec "..." resume --last` # Continue session
else:
use `codex -C [dir] exec "..."` # New session
```
### 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 with Groups
**Initial Setup with Task Flow**:
```javascript
TodoWrite({
todos: [
// Display task flow diagram first
{ content: "Task Flow Analysis Complete - See diagram above", status: "completed", activeForm: "Analyzing task flow" },
// Group A subtasks (will use resume within group)
{ content: "[Group A] Subtask 1: [description]", status: "in_progress", activeForm: "Executing Group A subtask 1" },
{ content: "[Group A] Subtask 2: [description] [resume]", status: "pending", activeForm: "Executing Group A subtask 2" },
// Group B subtasks (new session, then resume within group)
{ content: "[Group B] Subtask 1: [description] [new session]", status: "pending", activeForm: "Executing Group B subtask 1" },
{ content: "[Group B] Subtask 2: [description] [resume]", status: "pending", activeForm: "Executing Group B subtask 2" },
// Group C subtasks (new session)
{ content: "[Group C] Subtask 1: [description] [new session]", status: "pending", activeForm: "Executing Group C subtask 1" },
{ content: "Final verification and summary", status: "pending", activeForm: "Verifying and summarizing" }
]
})
```
**After Each Subtask**:
```javascript
TodoWrite({
todos: [
{ content: "Task Flow Analysis Complete - See diagram above", status: "completed", activeForm: "Analyzing task flow" },
{ content: "[Group A] Subtask 1: [description]", status: "completed", activeForm: "Executing Group A subtask 1" },
{ content: "[Group A] Subtask 2: [description] [resume]", status: "in_progress", activeForm: "Executing Group A subtask 2" },
// ... update status
]
})
```
## Codex Resume Mechanism
**Why Group-Based Resume?**
- **Within Group**: Maintains conversation context for related subtasks
- Codex remembers previous decisions and patterns
- Reduces context repetition
- Ensures consistency in implementation style
- **Between Groups**: Fresh session for independent tasks
- Avoids context pollution from unrelated work
- Prevents confusion when switching domains
- Maintains focused attention on current group
**How It Works**:
1. **First subtask in Group A**: Creates new Codex session
2. **Subsequent subtasks in Group A**: Use `codex resume --last` to continue session
3. **First subtask in Group B**: Creates NEW Codex session (no resume)
4. **Subsequent subtasks in Group B**: Use `codex resume --last` within Group B
5. Each group builds on its own context, isolated from other groups
**When to Resume vs New Session**:
```
✅ RESUME (same group):
- Subtasks share files/modules
- Logical continuation of previous work
- Same architectural domain
❌ NEW SESSION (different group):
- Independent task area
- Different files/modules
- Switching architectural domains
- Testing after implementation
```
**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 Flow Diagram:
[Group A: Auth Core]
A1: Create user model ──┐
A2: Add validation ─┤─► [resume] ─► A3: Database schema
[Group B: API Layer] │
B1: Auth endpoints ─────┘─► [new session]
B2: Middleware ────────────► [resume] ─► B3: Error handling
[Group C: Testing]
C1: Unit tests ─────────────► [new session]
C2: Integration tests ──────► [resume]
📋 Task Decomposition:
[Group A] 1. Create user model
[Group A] 2. Add validation logic [resume]
[Group A] 3. Implement database schema [resume]
[Group B] 4. Create auth endpoints [new session]
[Group B] 5. Add middleware [resume]
[Group B] 6. Error handling [resume]
[Group C] 7. Unit tests [new session]
[Group C] 8. Integration tests [resume]
▶️ [Group A] Executing Subtask 1/8: Create user model
Starting new Codex session for Group A...
[Codex output]
✅ Subtask 1 completed
🔍 Git Verification:
M src/models/user.ts
✅ Changes verified
▶️ [Group A] Executing Subtask 2/8: Add validation logic
Resuming Codex session (same group)...
[Codex output]
✅ Subtask 2 completed
▶️ [Group B] Executing Subtask 4/8: Create auth endpoints
Starting NEW Codex session for Group B...
[Codex output]
✅ Subtask 4 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 with Groups**
```bash
/cli:codex-execute "implement user authentication system"
# Task Flow Diagram:
# [Group A: Data Layer]
# A1: Create user model ──► [resume] ──► A2: Database schema
#
# [Group B: Auth Logic]
# B1: JWT token generation ──► [new session]
# B2: Authentication middleware ──► [resume]
#
# [Group C: API Endpoints]
# C1: Login/logout endpoints ──► [new session]
#
# [Group D: Testing]
# D1: Unit tests ──► [new session]
# D2: Integration tests ──► [resume]
# Execution:
# Group A: A1 (new) → A2 (resume)
# Group B: B1 (new) → B2 (resume)
# Group C: C1 (new)
# Group D: D1 (new) → D2 (resume)
```
**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. **Task Flow First**: Always create visual flow diagram before execution
2. **Group Related Work**: Cluster subtasks by domain/files for efficient resume
3. **Subtask Granularity**: Keep subtasks small and focused (5-15 min each)
4. **Clear Boundaries**: Each subtask should have well-defined input/output
5. **Git Hygiene**: Use `--verify-git` for critical refactoring
6. **Pre-Execution Staging**: Stage changes before each subtask to clearly see codex modifications
7. **Smart Resume**: Use `resume --last` ONLY within same group
8. **Fresh Sessions**: Start new session when switching to different group/domain
9. **Recovery Points**: TodoWrite with group labels provides clear progress tracking
10. **Image References**: Attach design files for UI tasks (first subtask in group)
## 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

@@ -9,227 +9,91 @@ examples:
- /cli:execute --tool codex IMPL-001
- /cli:execute --enhance "fix API performance issues"
allowed-tools: SlashCommand(*), Bash(*)
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
**Key Feature**: Automatic context inference and file pattern detection
**Core Guidelines**: @~/.claude/workflows/intelligent-tools-strategy.md
## Core Concepts
## 🚨 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
### Execution Modes
## 🎯 Enhancement Integration
**1. Description Mode** (supports `--enhance`):
- Input: Natural language description
- Process: [Optional: Enhance] → Keyword analysis → Pattern inference → Execute
**When `--enhance` flag present** (for Description Mode only):
**2. Task ID Mode** (no `--enhance`):
- Input: Workflow task identifier (e.g., `IMPL-001`)
- Process: Task JSON parsing → Scope analysis → Execute
### Context Inference
Auto-selects files based on keywords and technology:
- "auth" → `@{**/*auth*,**/*user*}`
- "React" → `@{src/**/*.{jsx,tsx}}`
- "api" → `@{**/api/**/*,**/routes/**/*}`
- Always includes: `@{CLAUDE.md,**/*CLAUDE.md}`
For precise file targeting, use `rg` or MCP tools to discover files first.
### Codex Session Continuity
**Resume Pattern** for related tasks:
```bash
# Step 1: Enhance the description
SlashCommand(command="/enhance-prompt \"[description]\"")
# First task - establish session
codex -C [dir] --full-auto exec "[task]" --skip-git-repo-check -s danger-full-access
# 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
# Related task - continue session
codex --full-auto exec "[related-task]" resume --last --skip-git-repo-check -s danger-full-access
```
**Example**:
```bash
# User: /gemini:execute --enhance "fix login"
Use `resume --last` when current task extends/relates to previous execution. See intelligent-tools-strategy.md for auto-resume rules.
# 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
## Parameters
# 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.
## 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
### 2. Task ID Mode (no --enhance)
**Input**: Workflow task identifier
```bash
/gemini:execute IMPL-001
```
**Process**: Task JSON parsing → Scope analysis → Context integration → Execution
## Context Inference Logic
**Auto-selects relevant files based on:**
- **Keywords**: "auth" → `@{**/*auth*,**/*user*}`
- **Technology**: "React" → `@{src/**/*.{jsx,tsx}}`
- **Task Type**: "api" → `@{**/api/**/*,**/routes/**/*}`
- **Always includes**: `@{CLAUDE.md,**/*CLAUDE.md}`
## Command Options
| Option | Purpose |
|--------|---------|
| `--debug` | Verbose execution logging |
| `--save-session` | Save complete execution session to workflow |
- `--tool <codex|gemini|qwen>` - Select CLI tool (default: gemini)
- `--enhance` - Enhance input with `/enhance-prompt` first (Description Mode only)
- `<description|task-id>` - Natural language description or task identifier
- `--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 session: Save to `.workflow/WFS-[id]/.chat/execute-[timestamp].md`
- No session: 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
## Examples
### Task Integration
```bash
# Execute specific workflow task
/gemini:execute IMPL-001
# Description mode with auto-detection
/cli:execute "implement JWT authentication with middleware"
# Loads from: .task/IMPL-001.json
# Uses: task context, brainstorming refs, scope definitions
# Updates: workflow status, generates summary
# Enhanced prompt
/cli:execute --enhance "implement JWT authentication"
# Task ID mode
/cli:execute IMPL-001
# Codex execution
/cli:execute --tool codex "optimize database queries"
# Qwen with enhancement
/cli:execute --tool qwen --enhance "refactor auth module"
```
## 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]
"
```
**Example**:
```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
"
```
### 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]
"
```
**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
"
```
## Auto-Generated Outputs
### 1. Implementation Summary
**Location**: `.summaries/[TASK-ID]-summary.md` or auto-generated ID
```markdown
# Task Summary: [Task-ID] [Description]
## 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.
## Notes
- Command templates, YOLO mode details, and session management: see intelligent-tools-strategy.md (loaded in memory)
- Auto-generated outputs: `.summaries/[TASK-ID]-summary.md`, `.chat/execute-[timestamp].md`

View File

@@ -8,107 +8,67 @@ examples:
- /cli:mode:bug-index --tool qwen --enhance "login not working"
- /cli:mode:bug-index --tool codex --cd "src/auth" "token validation fails"
allowed-tools: SlashCommand(*), Bash(*)
model: sonnet
---
# CLI Mode: Bug Index (/cli:mode:bug-index)
## Purpose
Execute systematic bug analysis and fix suggestions using CLI tools with diagnostic template.
Systematic bug analysis with diagnostic template (`~/.claude/prompt-templates/bug-fix.md`).
**Supported Tools**: codex, gemini (default), qwen
**Key Feature**: `--cd` flag for directory-scoped analysis
## Parameters
- `--tool <codex|gemini|qwen>` - Tool selection (default: gemini)
- `--enhance` - Enhance bug description with `/enhance-prompt` first
- `--cd "path"` - Target directory for focused analysis
- `<bug-description>` (Required) - Bug description or error message
## Execution Flow
1. **Parse tool selection**: Extract `--tool` flag (default: gemini)
2. **If `--enhance` flag present**: Execute `/enhance-prompt "[bug-description]"` first
3. Parse bug description (original or enhanced)
4. Detect target directory (from `--cd` or auto-infer)
5. Build command for selected tool with bug-fix template
6. Execute analysis
7. Save to session (if active)
1. Parse tool and directory options
2. If `--enhance`: Execute `/enhance-prompt` to expand bug context
3. Use bug-fix template: `~/.claude/prompt-templates/bug-fix.md`
4. Execute with `--all-files` in target directory
5. Save to `.workflow/WFS-[id]/.chat/bug-index-[timestamp].md`
## Core Rules
## Analysis Focus (via Template)
1. **Enhance First (if flagged)**: Execute `/enhance-prompt` before analysis
2. **Directory Context**: Use `cd` when `--cd` provided or auto-detected
3. **Template Required**: Always use bug-fix template
4. **Session Output**: Save to `.workflow/WFS-[id]/.chat/bug-index-[timestamp].md`
## Command Template
**Core Guidelines**: @~/.claude/workflows/intelligent-tools-strategy.md
```bash
cd [directory] && ~/.claude/scripts/gemini-wrapper --all-files -p "
PURPOSE: [bug analysis goal]
TASK: Systematic bug analysis and fix recommendations
CONTEXT: @{CLAUDE.md,**/*CLAUDE.md} [entire codebase in directory]
EXPECTED: Root cause analysis, code path tracing, targeted fixes
RULES: $(cat ~/.claude/prompt-templates/bug-fix.md) | Bug: [description]
"
```
- Root cause investigation
- Code path tracing
- Targeted minimal fixes
- Impact assessment
## Examples
**Basic Bug Analysis**:
```bash
cd . && ~/.claude/scripts/gemini-wrapper --all-files -p "
PURPOSE: Debug authentication null pointer error
TASK: Identify root cause and provide fix
CONTEXT: @{CLAUDE.md,**/*CLAUDE.md}
EXPECTED: Root cause, code path, minimal fix, impact assessment
RULES: $(cat ~/.claude/prompt-templates/bug-fix.md) | Bug: null pointer in login flow
"
# Basic bug analysis
/cli:mode:bug-index "null pointer in authentication"
# Directory-specific
/cli:mode:bug-index --cd "src/auth" "token validation fails"
# Enhanced description
/cli:mode:bug-index --enhance "login broken"
# Qwen for architecture-related bugs
/cli:mode:bug-index --tool qwen "circular dependency in modules"
```
**Directory-Specific**:
## Bug Investigation Workflow
```bash
cd src/auth && ~/.claude/scripts/gemini-wrapper --all-files -p "
PURPOSE: Fix token validation failure
TASK: Analyze token validation bug in auth module
CONTEXT: @{CLAUDE.md,**/*CLAUDE.md}
EXPECTED: Validation logic analysis, fix recommendation
RULES: $(cat ~/.claude/prompt-templates/bug-fix.md) | Bug: token validation fails intermittently
"
# 1. Find bug-related files
rg "error_keyword" --files-with-matches
# 2. Execute bug analysis with focused context
/cli:mode:bug-index --cd "src/module" "specific error description"
```
**With Enhancement**:
```bash
# User: /gemini:mode:bug-index --enhance "login broken"
## Notes
# Step 1: Enhance
/enhance-prompt "login broken"
# Returns:
# INTENT: Debug login authentication failure
# CONTEXT: Known session state issue
# ACTION: Check session management → verify token → test flow
# Step 2: Analyze with enhanced context
cd . && ~/.claude/scripts/gemini-wrapper --all-files -p "
PURPOSE: Debug login authentication failure
TASK: Analyze session management, token handling, auth flow
CONTEXT: @{CLAUDE.md,**/*CLAUDE.md} Known: session state issue
EXPECTED: Root cause in session/token, targeted fix
RULES: $(cat ~/.claude/prompt-templates/bug-fix.md) | Focus on session management
"
```
## Analysis Focus
**Template provides**:
- **Root Cause Analysis**: Systematic investigation
- **Code Path Tracing**: Execution flow analysis
- **Targeted Solutions**: Minimal, specific fixes
- **Impact Assessment**: Side effect evaluation
## Session Output
**Location**: `.workflow/WFS-[topic]/.chat/bug-index-[timestamp].md`
**Includes**:
- Bug description
- Template used
- Analysis results
- Recommended actions
- Command templates and file patterns: see intelligent-tools-strategy.md (loaded in memory)
- Template path: `~/.claude/prompt-templates/bug-fix.md`
- Always uses `--all-files` for comprehensive codebase context

View File

@@ -8,197 +8,68 @@ examples:
- /cli:mode:code-analysis --tool qwen --enhance "explain data transformation pipeline"
- /cli:mode:code-analysis --tool codex --cd "src/core" "trace execution path for user registration"
allowed-tools: SlashCommand(*), Bash(*)
model: sonnet
---
# CLI Mode: Code Analysis (/cli:mode:code-analysis)
## Purpose
Execute systematic code analysis and debugging using CLI tools with specialized code analysis template.
Systematic code analysis with execution path tracing template (`~/.claude/prompt-templates/code-analysis.md`).
**Supported Tools**: codex, gemini (default), qwen
**Key Feature**: `--cd` flag for directory-scoped analysis
## Parameters
- `--tool <codex|gemini|qwen>` - Tool selection (default: gemini)
- `--enhance` - Enhance analysis target with `/enhance-prompt` first
- `--cd "path"` - Target directory for focused analysis
- `<analysis-target>` (Required) - Code analysis target or question
## Execution Flow
1. **Parse tool selection**: Extract `--tool` flag (default: gemini)
2. **If `--enhance` flag present**: Execute `/enhance-prompt "[analysis-target]"` first
3. Parse analysis target (original or enhanced)
4. Detect target directory (from `--cd` or auto-infer)
5. Build command for selected tool with code-analysis template
6. Execute deep analysis
7. Save to session (if active)
1. Parse tool and directory options
2. If `--enhance`: Execute `/enhance-prompt` to expand analysis intent
3. Use code-analysis template: `~/.claude/prompt-templates/code-analysis.md`
4. Execute with `--all-files` in target directory
5. Save to `.workflow/WFS-[id]/.chat/code-analysis-[timestamp].md`
## Core Rules
## Analysis Capabilities (via Template)
1. **Tool Selection**: Use `--tool` value or default to gemini
2. **Enhance First (if flagged)**: Execute `/enhance-prompt` before analysis
3. **Directory Context**: Use `cd` when `--cd` provided or auto-detected
4. **Template Required**: Always use code-analysis template
5. **Session Output**: Save to `.workflow/WFS-[id]/.chat/code-analysis-[timestamp].md`
## Analysis Capabilities
The code-analysis template provides:
- **Systematic Code Analysis**: Break down complex code into manageable parts
- **Execution Path Tracing**: Track variable states and call stacks
- **Control & Data Flow**: Understand code logic and data transformations
- **Call Flow Visualization**: Diagram function calling sequences
- **Logical Reasoning**: Explain "why" behind code behavior
- **Debugging Insights**: Identify potential bugs or inefficiencies
## Command Templates
**Core Guidelines**: @~/.claude/workflows/intelligent-tools-strategy.md
### Gemini (Default)
```bash
cd [directory] && ~/.claude/scripts/gemini-wrapper --all-files -p "
PURPOSE: [analysis goal from target]
TASK: Deep code analysis with execution path tracing
CONTEXT: @{CLAUDE.md,**/*CLAUDE.md} [entire codebase in directory]
EXPECTED: Systematic analysis, call flow diagram, data transformations, logical explanation
RULES: $(cat ~/.claude/prompt-templates/code-analysis.md) | Focus on [specific aspect]
"
```
### Qwen
```bash
cd [directory] && ~/.claude/scripts/qwen-wrapper --all-files -p "
PURPOSE: [analysis goal from target]
TASK: Architecture-level code analysis and pattern recognition
CONTEXT: @{CLAUDE.md,**/*CLAUDE.md} [entire codebase in directory]
EXPECTED: Architectural insights, design patterns, code structure analysis
RULES: $(cat ~/.claude/prompt-templates/code-analysis.md) | Focus on [specific aspect]
"
```
### Codex
```bash
codex -C [directory] --full-auto exec "
PURPOSE: [analysis goal from target]
TASK: Deep code inspection with debugging insights
CONTEXT: @{CLAUDE.md,**/*CLAUDE.md} [entire codebase in directory]
EXPECTED: Execution trace, bug identification, optimization opportunities
RULES: $(cat ~/.claude/prompt-templates/code-analysis.md) | Focus on [specific aspect]
" --skip-git-repo-check -s danger-full-access
```
- Execution path tracing with variable states
- Call flow visualization and diagrams
- Control & data flow analysis
- Logical reasoning ("why" behind code behavior)
- Debugging insights and inefficiency detection
## Examples
**Basic Code Analysis (Gemini)**:
```bash
cd . && ~/.claude/scripts/gemini-wrapper --all-files -p "
PURPOSE: Analyze authentication flow logic
TASK: Trace authentication execution path and identify key functions
CONTEXT: @{CLAUDE.md,**/*CLAUDE.md}
EXPECTED: Step-by-step flow, call diagram, data passing between functions
RULES: $(cat ~/.claude/prompt-templates/code-analysis.md) | Focus on control flow and security
"
# Basic code analysis
/cli:mode:code-analysis "trace authentication flow"
# Directory-specific with enhancement
/cli:mode:code-analysis --cd "src/auth" --enhance "how does JWT work"
# Qwen for architecture analysis
/cli:mode:code-analysis --tool qwen "explain microservices communication"
# Codex for deep tracing
/cli:mode:code-analysis --tool codex --cd "src/api" "trace request lifecycle"
```
**Architecture Analysis (Qwen)**:
```bash
# User: /cli:mode:code-analysis --tool qwen "explain data transformation pipeline"
## Code Tracing Workflow
cd . && ~/.claude/scripts/qwen-wrapper --all-files -p "
PURPOSE: Explain data transformation pipeline architecture
TASK: Analyze data flow and transformation patterns
CONTEXT: @{CLAUDE.md,**/*CLAUDE.md}
EXPECTED: Pipeline structure, transformation stages, data format changes
RULES: $(cat ~/.claude/prompt-templates/code-analysis.md) | Focus on data flow and patterns
"
```bash
# 1. Find entry points
rg "function.*main|export.*handler" --files-with-matches
# 2. Execute deep analysis
/cli:mode:code-analysis --cd "src" "trace execution from entry point"
```
**Deep Debugging (Codex)**:
```bash
# User: /cli:mode:code-analysis --tool codex --cd "src/core" "trace execution path for user registration"
## Notes
codex -C src/core --full-auto exec "
PURPOSE: Trace execution path for user registration
TASK: Deep analysis of registration flow with debugging insights
CONTEXT: @{CLAUDE.md,**/*CLAUDE.md}
EXPECTED: Complete execution trace, variable states, potential issues
RULES: $(cat ~/.claude/prompt-templates/code-analysis.md) | Focus on edge cases and error handling
" --skip-git-repo-check -s danger-full-access
```
**With Enhancement**:
```bash
# User: /cli:mode:code-analysis --enhance "why is login slow"
# Step 1: Enhance
/enhance-prompt "why is login slow"
# Returns:
# INTENT: Identify performance bottlenecks in login flow
# CONTEXT: Authentication module, database queries
# ACTION: Trace execution path → identify slow operations → suggest optimizations
# Step 2: Analyze with enhanced context
cd . && ~/.claude/scripts/gemini-wrapper --all-files -p "
PURPOSE: Identify performance bottlenecks in login flow
TASK: Trace login execution path and measure operation costs
CONTEXT: @{CLAUDE.md,**/*CLAUDE.md} @{**/*auth*,**/*login*}
EXPECTED: Performance analysis, bottleneck identification, optimization recommendations
RULES: $(cat ~/.claude/prompt-templates/code-analysis.md) | Focus on performance and database queries
"
```
## Analysis Output Structure
Based on code-analysis.md template, output includes:
### 1. 思考过程 (Thinking Process)
- Analysis strategy and approach
- Key assumptions about code behavior
### 2. 对问题的理解 (Understanding)
- Restate analysis target
- Confirm understanding of requirements
### 3. 核心解答 (Core Answer)
- Direct, concise answer to analysis question
### 4. 详细分析与调用逻辑 (Detailed Analysis)
- **代码段识别**: Relevant code sections
- **执行流程**: Step-by-step execution flow
- **调用图**: Visual call flow diagram with symbols:
- `───►` Function call
- `◄───` Return
- `│` Continuation
- `├─` Intermediate step
- `└─` Last step in block
- **数据传递**: Data passing and state changes
- **逻辑解释**: Why code behaves this way
### 5. 总结 (Summary)
- Key findings and recommendations
## Session Output
**Location**: `.workflow/WFS-[topic]/.chat/code-analysis-[timestamp].md`
**Includes**:
- Analysis target
- Template used
- Complete structured analysis
- Call flow diagrams
- Debugging insights
- Recommendations
## Use Cases
| Use Case | Best Tool | Focus |
|----------|-----------|-------|
| **Understand execution flow** | gemini | Call sequences, data flow |
| **Architectural patterns** | qwen | Design patterns, structure |
| **Performance debugging** | codex | Bottlenecks, optimizations |
| **Bug investigation** | codex | Error paths, edge cases |
| **Code review** | gemini | Logic correctness, clarity |
| **Refactoring planning** | qwen | Structure improvements |
## Tool Selection Guide
- **Gemini**: Best for general code understanding and tracing
- **Qwen**: Best for architectural analysis and pattern recognition
- **Codex**: Best for deep debugging and performance analysis
- Command templates and file patterns: see intelligent-tools-strategy.md (loaded in memory)
- Template path: `~/.claude/prompt-templates/code-analysis.md`
- Always uses `--all-files` for comprehensive code context

View File

@@ -8,97 +8,68 @@ examples:
- /cli:mode:plan --tool qwen --enhance "plan microservices migration"
- /cli:mode:plan --tool codex --cd "src/auth" "authentication system"
allowed-tools: SlashCommand(*), Bash(*)
model: sonnet
---
# CLI Mode: Plan (/cli:mode:plan)
## Purpose
Execute planning and architecture analysis using CLI tools with specialized template.
Comprehensive planning and architecture analysis with strategic planning template (`~/.claude/prompt-templates/plan.md`).
**Supported Tools**: codex, gemini (default), qwen
**Key Feature**: `--cd` flag for directory-scoped planning
## Parameters
- `--tool <codex|gemini|qwen>` - Tool selection (default: gemini)
- `--enhance` - Enhance topic with `/enhance-prompt` first
- `--cd "path"` - Target directory for focused planning
- `<topic>` (Required) - Planning topic or architectural question
## Execution Flow
1. **Parse tool selection**: Extract `--tool` flag (default: gemini)
2. **If `--enhance` flag present**: Execute `/enhance-prompt "[topic]"` first
3. Parse topic (original or enhanced)
4. Detect target directory (from `--cd` or auto-infer)
5. Build command for selected tool with planning template
6. Execute analysis
7. Save to session (if active)
1. Parse tool and directory options
2. If `--enhance`: Execute `/enhance-prompt` to expand planning context
3. Use planning template: `~/.claude/prompt-templates/plan.md`
4. Execute with `--all-files` in target directory
5. Save to `.workflow/WFS-[id]/.chat/plan-[timestamp].md`
## Core Rules
## Planning Capabilities (via Template)
1. **Enhance First (if flagged)**: Execute `/enhance-prompt` before planning
2. **Directory Context**: Use `cd` when `--cd` provided or auto-detected
3. **Template Required**: Always use planning template
4. **Session Output**: Save to `.workflow/WFS-[id]/.chat/plan-[timestamp].md`
## Command Template
**Core Guidelines**: @~/.claude/workflows/intelligent-tools-strategy.md
```bash
cd [directory] && ~/.claude/scripts/gemini-wrapper --all-files -p "
PURPOSE: [planning goal from topic]
TASK: Comprehensive planning and architecture analysis
CONTEXT: @{CLAUDE.md,**/*CLAUDE.md} [entire codebase in directory]
EXPECTED: Strategic insights, implementation roadmap, key decisions
RULES: $(cat ~/.claude/prompt-templates/plan.md) | Focus on [topic area]
"
```
- Strategic architecture insights
- Implementation roadmaps
- Key technical decisions
- Risk assessment
- Resource planning
## Examples
**Basic Planning**:
```bash
cd . && ~/.claude/scripts/gemini-wrapper --all-files -p "
PURPOSE: Design user dashboard feature architecture
TASK: Comprehensive architecture planning for dashboard
CONTEXT: @{CLAUDE.md,**/*CLAUDE.md}
EXPECTED: Architecture design, component structure, implementation roadmap
RULES: $(cat ~/.claude/prompt-templates/plan.md) | Focus on scalability and UX
"
# Basic planning
/cli:mode:plan "design user dashboard"
# Enhanced with directory scope
/cli:mode:plan --cd "src/api" --enhance "plan API refactoring"
# Qwen for architecture planning
/cli:mode:plan --tool qwen "plan microservices migration"
# Codex for technical planning
/cli:mode:plan --tool codex "plan testing strategy"
```
**Directory-Specific**:
## Planning Workflow
```bash
cd src/auth && ~/.claude/scripts/gemini-wrapper --all-files -p "
PURPOSE: Plan authentication system redesign
TASK: Analyze current auth and plan improvements
CONTEXT: @{CLAUDE.md,**/*CLAUDE.md}
EXPECTED: Migration strategy, security improvements, timeline
RULES: $(cat ~/.claude/prompt-templates/plan.md) | Focus on security and backward compatibility
"
# 1. Gather existing architecture info
rg "architecture|design" --files-with-matches
# 2. Execute planning analysis
/cli:mode:plan "topic for strategic planning"
```
**With Enhancement**:
```bash
# User: /gemini:mode:plan --enhance "fix auth issues"
## Notes
# Step 1: Enhance
/enhance-prompt "fix auth issues"
# Returns structured planning context
# Step 2: Plan with enhanced input
cd . && ~/.claude/scripts/gemini-wrapper --all-files -p "
PURPOSE: [enhanced goal]
TASK: [enhanced task description]
CONTEXT: @{CLAUDE.md,**/*CLAUDE.md} [enhanced context]
EXPECTED: Strategic plan with enhanced requirements
RULES: $(cat ~/.claude/prompt-templates/plan.md) | [enhanced constraints]
"
```
## Session Output
**Location**: `.workflow/WFS-[topic]/.chat/plan-[timestamp].md`
**Includes**:
- Planning topic
- Template used
- Analysis results
- Implementation roadmap
- Key decisions
- Command templates and file patterns: see intelligent-tools-strategy.md (loaded in memory)
- Template path: `~/.claude/prompt-templates/plan.md`
- Always uses `--all-files` for comprehensive project context

View File

@@ -88,8 +88,9 @@ Files updated: .task/IMPL-1.json + 2 subtask files + TODO_LIST.md
### Agent Assignment
- **Design/Planning** → `@planning-agent`
- **Implementation** → `@code-developer`
- **Testing** → `@code-review-test-agent`
- **Review** → `@review-agent`
- **Testing** → `@code-developer` (type: "test-gen")
- **Test Validation** → `@test-fix-agent` (type: "test-fix")
- **Review** → `@general-purpose` (optional)
### Context Inheritance
- Subtasks inherit parent requirements
@@ -161,8 +162,8 @@ See @~/.claude/workflows/workflow-architecture.md for:
▸ impl-1: Build authentication (container)
├── impl-1.1: Design schema → @planning-agent
├── impl-1.2: Implement logic → @code-developer
└── impl-1.3: Write tests → @code-review-test-agent
├── impl-1.2: Implement logic + tests → @code-developer
└── impl-1.3: Execute & fix tests → @test-fix-agent
```
## Error Handling

View File

@@ -107,8 +107,9 @@ Tasks inherit from:
Based on task type and title keywords:
- **Build/Implement** → @code-developer
- **Design/Plan** → @planning-agent
- **Test/Validate** → @code-review-test-agent
- **Review/Audit** → @review-agent`
- **Test Generation** → @code-developer (type: "test-gen")
- **Test Execution/Fix** → @test-fix-agent (type: "test-fix")
- **Review/Audit** → @general-purpose (optional, only when explicitly requested)
## Validation Rules

View File

@@ -24,8 +24,8 @@ examples:
- Executes step-by-step, requiring user confirmation at each checkpoint.
- Allows for dynamic adjustments and manual review during the process.
- **review**
- Executes under the supervision of a `@review-agent`.
- Performs quality checks and provides detailed feedback at each step.
- Optional manual review using `@general-purpose`.
- Used only when explicitly requested by user.
### 🤖 **Agent Selection Logic**
@@ -45,10 +45,12 @@ FUNCTION select_agent(task, agent_override):
RETURN "@code-developer"
WHEN CONTAINS "Design schema", "Plan":
RETURN "@planning-agent"
WHEN CONTAINS "Write tests":
RETURN "@code-review-test-agent"
WHEN CONTAINS "Write tests", "Generate tests":
RETURN "@code-developer" // type: test-gen
WHEN CONTAINS "Execute tests", "Fix tests", "Validate":
RETURN "@test-fix-agent" // type: test-fix
WHEN CONTAINS "Review code":
RETURN "@review-agent"
RETURN "@general-purpose" // Optional manual review
DEFAULT:
RETURN "@code-developer" // Default agent
END CASE
@@ -232,13 +234,15 @@ Different agents receive context tailored to their function, including implement
- Implementation risks and mitigation strategies
- Architecture implications from implementation.context_notes
**`@code-review-test-agent`**:
- Files to test from implementation.files[].path
- Logic flows to validate from implementation.modifications.logic_flow
- Error conditions to test from implementation.context_notes.error_handling
- Performance benchmarks from implementation.context_notes.performance_considerations
**`@test-fix-agent`**:
- Test files to execute from task.context.focus_paths
- Source files to fix from implementation.files[].path
- Expected behaviors from implementation.modifications.logic_flow
- Error conditions to validate from implementation.context_notes.error_handling
- Performance requirements from implementation.context_notes.performance_considerations
**`@review-agent`**:
**`@general-purpose`**:
- Used for optional manual reviews when explicitly requested
- Code quality standards and implementation patterns
- Security considerations from implementation.context_notes.risks
- Dependency validation from implementation.context_notes.dependencies

View File

@@ -1,33 +1,46 @@
---
name: update-memory-full
description: Complete project-wide CLAUDE.md documentation update
usage: /update-memory-full
usage: /update-memory-full [--tool <gemini|qwen|codex>]
argument-hint: "[--tool gemini|qwen|codex]"
examples:
- /update-memory-full # Full project documentation update
- /update-memory-full # Full project documentation update (gemini default)
- /update-memory-full --tool qwen # Use Qwen for architecture analysis
- /update-memory-full --tool codex # Use Codex for implementation validation
---
### 🚀 Command Overview: `/update-memory-full`
Complete project-wide documentation update using depth-parallel execution.
**Tool Selection**:
- **Gemini (default)**: Documentation generation, pattern recognition, architecture review
- **Qwen**: Architecture analysis, system design documentation
- **Codex**: Implementation validation, code quality analysis
### 📝 Execution Template
```bash
#!/bin/bash
# Complete project-wide CLAUDE.md documentation update
# Step 1: Code Index architecture analysis
# Step 1: Parse tool selection (default: gemini)
tool="gemini"
[[ "$*" == *"--tool qwen"* ]] && tool="qwen"
[[ "$*" == *"--tool codex"* ]] && tool="codex"
# Step 2: Code Index architecture analysis
mcp__code-index__search_code_advanced(pattern="class|function|interface", file_pattern="**/*.{ts,js,py}")
mcp__code-index__find_files(pattern="**/*.{md,json,yaml,yml}")
# Step 2: Cache git changes
# Step 3: Cache git changes
Bash(git add -A 2>/dev/null || true)
# Step 3: Get and display project structure
# Step 4: Get and display project structure
modules=$(Bash(~/.claude/scripts/get_modules_by_depth.sh list))
count=$(echo "$modules" | wc -l)
# Step 3: Analysis handover → Model takes control
# Step 5: Analysis handover → Model takes control
# BASH_EXECUTION_STOPS → MODEL_ANALYSIS_BEGINS
# Pseudocode flow:
@@ -35,6 +48,8 @@ count=$(echo "$modules" | wc -l)
# → Task "Complex project full update" subagent_type: "memory-gemini-bridge"
# ELSE:
# → Present plan and WAIT FOR USER APPROVAL before execution
#
# Pass tool parameter to update_module_claude.sh: "$tool"
```
### 🧠 Model Analysis Phase
@@ -43,7 +58,7 @@ After the bash script completes the initial analysis, the model takes control to
1. **Analyze Complexity**: Review module count and project context
2. **Parse CLAUDE.md Status**: Extract which modules have/need CLAUDE.md files
3. **Choose Strategy**:
3. **Choose Strategy**:
- Simple projects: Present execution plan with CLAUDE.md paths to user
- Complex projects: Delegate to memory-gemini-bridge agent
4. **Present Detailed Plan**: Show user exactly which CLAUDE.md files will be created/updated
@@ -56,17 +71,19 @@ After the bash script completes the initial analysis, the model takes control to
Model will present detailed plan:
```
📋 Update Plan:
Tool: [gemini|qwen|codex] (from --tool parameter)
NEW CLAUDE.md files (X):
- ./src/components/CLAUDE.md
- ./src/services/CLAUDE.md
UPDATE existing CLAUDE.md files (Y):
- ./CLAUDE.md
- ./src/CLAUDE.md
- ./tests/CLAUDE.md
Total: N CLAUDE.md files will be processed
⚠️ Confirm execution? (y/n)
```
@@ -84,7 +101,7 @@ depth_modules = organize_by_depth(modules)
FOR depth FROM max_depth DOWN TO 0:
FOR each module IN depth_modules[depth]:
WHILE active_jobs >= 4: wait(0.1)
Bash(~/.claude/scripts/update_module_claude.sh "$module" "full" &)
Bash(~/.claude/scripts/update_module_claude.sh "$module" "full" "$tool" &)
wait_all_jobs()
# Step 6: Safety check and restore staging state
@@ -102,13 +119,43 @@ Bash(git status --short)
```
**For Complex Projects (>20 modules):**
The model will delegate to the memory-gemini-bridge agent using the Task tool:
```
The model will delegate to the memory-gemini-bridge agent with structured context:
```javascript
Task "Complex project full update"
prompt: "Execute full documentation update for [count] modules using depth-parallel execution"
subagent_type: "memory-gemini-bridge"
prompt: `
CONTEXT:
- Total modules: ${module_count}
- Tool: ${tool} // from --tool parameter, default: gemini
- Mode: full
- Existing CLAUDE.md: ${existing_count}
- New CLAUDE.md needed: ${new_count}
MODULE LIST:
${modules_output} // Full output from get_modules_by_depth.sh list
REQUIREMENTS:
1. Use TodoWrite to track each depth level before execution
2. Process depths 5→0 sequentially, max 4 parallel jobs per depth
3. Command format: update_module_claude.sh "<path>" "full" "${tool}" &
4. Extract exact path from "depth:N|path:<PATH>|..." format
5. Verify all ${module_count} modules are processed
6. Run safety check after completion
7. Display git status
Execute depth-parallel updates for all modules.
`
```
**Agent receives complete context:**
- Module count and tool selection
- Full structured module list
- Clear execution requirements
- Path extraction format
- Success criteria
### 📚 Usage Examples

View File

@@ -1,15 +1,23 @@
---
name: update-memory-related
description: Context-aware CLAUDE.md documentation updates based on recent changes
usage: /update-memory-related
usage: /update-memory-related [--tool <gemini|qwen|codex>]
argument-hint: "[--tool gemini|qwen|codex]"
examples:
- /update-memory-related # Update documentation based on recent changes
- /update-memory-related # Update documentation based on recent changes (gemini default)
- /update-memory-related --tool qwen # Use Qwen for architecture analysis
- /update-memory-related --tool codex # Use Codex for implementation validation
---
### 🚀 Command Overview: `/update-memory-related`
Context-aware documentation update for modules affected by recent changes.
**Tool Selection**:
- **Gemini (default)**: Documentation generation, pattern recognition, architecture review
- **Qwen**: Architecture analysis, system design documentation
- **Codex**: Implementation validation, code quality analysis
### 📝 Execution Template
@@ -17,23 +25,28 @@ Context-aware documentation update for modules affected by recent changes.
#!/bin/bash
# Context-aware CLAUDE.md documentation update
# Step 1: Code Index refresh and architecture analysis
# Step 1: Parse tool selection (default: gemini)
tool="gemini"
[[ "$*" == *"--tool qwen"* ]] && tool="qwen"
[[ "$*" == *"--tool codex"* ]] && tool="codex"
# Step 2: Code Index refresh and architecture analysis
mcp__code-index__refresh_index()
mcp__code-index__search_code_advanced(pattern="class|function|interface", file_pattern="**/*.{ts,js,py}")
# Step 2: Detect changed modules (before staging)
# Step 3: Detect changed modules (before staging)
changed=$(Bash(~/.claude/scripts/detect_changed_modules.sh list))
# Step 3: Cache git changes (protect current state)
# Step 4: Cache git changes (protect current state)
Bash(git add -A 2>/dev/null || true)
# Step 3: Use detected changes or fallback
# Step 5: Use detected changes or fallback
if [ -z "$changed" ]; then
changed=$(Bash(~/.claude/scripts/get_modules_by_depth.sh list | head -10))
fi
count=$(echo "$changed" | wc -l)
# Step 4: Analysis handover → Model takes control
# Step 6: Analysis handover → Model takes control
# BASH_EXECUTION_STOPS → MODEL_ANALYSIS_BEGINS
# Pseudocode flow:
@@ -41,6 +54,8 @@ count=$(echo "$changed" | wc -l)
# → Task "Complex project related update" subagent_type: "memory-gemini-bridge"
# ELSE:
# → Present plan and WAIT FOR USER APPROVAL before execution
#
# Pass tool parameter to update_module_claude.sh: "$tool"
```
### 🧠 Model Analysis Phase
@@ -62,18 +77,20 @@ After the bash script completes change detection, the model takes control to:
Model will present detailed plan for affected modules:
```
📋 Related Update Plan:
Tool: [gemini|qwen|codex] (from --tool parameter)
CHANGED modules affecting CLAUDE.md:
NEW CLAUDE.md files (X):
- ./src/api/auth/CLAUDE.md [new module]
- ./src/utils/helpers/CLAUDE.md [new module]
UPDATE existing CLAUDE.md files (Y):
- ./src/api/CLAUDE.md [parent of changed auth/]
- ./src/CLAUDE.md [root level]
Total: N CLAUDE.md files will be processed for recent changes
⚠️ Confirm execution? (y/n)
```
@@ -91,7 +108,7 @@ depth_modules = organize_by_depth(changed_modules)
FOR depth FROM max_depth DOWN TO 0:
FOR each module IN depth_modules[depth]:
WHILE active_jobs >= 4: wait(0.1)
Bash(~/.claude/scripts/update_module_claude.sh "$module" "related" &)
Bash(~/.claude/scripts/update_module_claude.sh "$module" "related" "$tool" &)
wait_all_jobs()
# Step 6: Safety check and restore staging state
@@ -109,13 +126,44 @@ Bash(git diff --stat)
```
**For Complex Changes (>15 modules):**
The model will delegate to the memory-gemini-bridge agent using the Task tool:
```
The model will delegate to the memory-gemini-bridge agent with structured context:
```javascript
Task "Complex project related update"
prompt: "Execute context-aware update for [count] changed modules using depth-parallel execution"
subagent_type: "memory-gemini-bridge"
prompt: `
CONTEXT:
- Total modules: ${change_count}
- Tool: ${tool} // from --tool parameter, default: gemini
- Mode: related
- Changed modules detected via: detect_changed_modules.sh
- Existing CLAUDE.md: ${existing_count}
- New CLAUDE.md needed: ${new_count}
MODULE LIST:
${changed_modules_output} // Full output from detect_changed_modules.sh list
REQUIREMENTS:
1. Use TodoWrite to track each depth level before execution
2. Process depths sequentially (deepest→shallowest), max 4 parallel jobs per depth
3. Command format: update_module_claude.sh "<path>" "related" "${tool}" &
4. Extract exact path from "depth:N|path:<PATH>|..." format
5. Verify all ${change_count} modules are processed
6. Run safety check after completion
7. Display git diff --stat
Execute depth-parallel updates for changed modules only.
`
```
**Agent receives complete context:**
- Changed module count and tool selection
- Full structured module list (changed only)
- Clear execution requirements with "related" mode
- Path extraction format
- Success criteria
### 📚 Usage Examples

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

@@ -91,10 +91,11 @@ allowed-tools: TodoWrite(*), Read(*), Write(*), Bash(*), Glob(*)
**Document Structure**:
```
.workflow/WFS-[topic]/.brainstorming/
── topic-framework.md # ★ STRUCTURED FRAMEWORK DOCUMENT
└── workflow-session.json # Framework metadata and role assignments
── topic-framework.md # ★ STRUCTURED FRAMEWORK DOCUMENT
```
**Note**: `workflow-session.json` is located at `.workflow/WFS-[topic]/workflow-session.json` (session root), not inside `.brainstorming/`.
## Framework Template Structures
### Dynamic Role-Based Framework

View File

@@ -149,7 +149,7 @@ Task(subagent_type="conceptual-planning-agent",
3. **load_session_metadata**
- Action: Load session metadata and topic description
- Command: bash(cat .workflow/WFS-{topic}/.brainstorming/workflow-session.json 2>/dev/null || echo '{}')
- Command: bash(cat .workflow/WFS-{topic}/workflow-session.json 2>/dev/null || echo '{}')
- Output: session_metadata
### Implementation Context
@@ -162,7 +162,7 @@ Task(subagent_type="conceptual-planning-agent",
### Session Context
**Workflow Directory**: .workflow/WFS-{topic}/.brainstorming/
**Output Directory**: .workflow/WFS-{topic}/.brainstorming/{role}/
**Session JSON**: .workflow/WFS-{topic}/.brainstorming/workflow-session.json
**Session JSON**: .workflow/WFS-{topic}/workflow-session.json
### Dependencies & Context
**Topic**: {user-provided-topic}

View File

@@ -88,7 +88,7 @@ ANALYSIS_MODE: {framework_mode ? "framework_based" : "standalone"}
3. **load_session_metadata**
- Action: Load session metadata and existing context
- Command: Read(.workflow/WFS-{session}/.brainstorming/session.json)
- Command: Read(.workflow/WFS-{session}/workflow-session.json)
- Output: session_context
## Analysis Requirements
@@ -136,7 +136,7 @@ TodoWrite({
activeForm: "Generating structured data-architect analysis"
},
{
content: "Update session.json with data-architect completion status",
content: "Update workflow-session.json with data-architect completion status",
status: "pending",
activeForm: "Updating session metadata"
}

View File

@@ -88,7 +88,7 @@ ANALYSIS_MODE: {framework_mode ? "framework_based" : "standalone"}
3. **load_session_metadata**
- Action: Load session metadata and existing context
- Command: Read(.workflow/WFS-{session}/.brainstorming/session.json)
- Command: Read(.workflow/WFS-{session}/workflow-session.json)
- Output: session_context
## Analysis Requirements
@@ -136,7 +136,7 @@ TodoWrite({
activeForm: "Generating structured product-manager analysis"
},
{
content: "Update session.json with product-manager completion status",
content: "Update workflow-session.json with product-manager completion status",
status: "pending",
activeForm: "Updating session metadata"
}

View File

@@ -88,7 +88,7 @@ ANALYSIS_MODE: {framework_mode ? "framework_based" : "standalone"}
3. **load_session_metadata**
- Action: Load session metadata and existing context
- Command: Read(.workflow/WFS-{session}/.brainstorming/session.json)
- Command: Read(.workflow/WFS-{session}/workflow-session.json)
- Output: session_context
## Analysis Requirements
@@ -136,7 +136,7 @@ TodoWrite({
activeForm: "Generating structured product-owner analysis"
},
{
content: "Update session.json with product-owner completion status",
content: "Update workflow-session.json with product-owner completion status",
status: "pending",
activeForm: "Updating session metadata"
}

View File

@@ -88,7 +88,7 @@ ANALYSIS_MODE: {framework_mode ? "framework_based" : "standalone"}
3. **load_session_metadata**
- Action: Load session metadata and existing context
- Command: Read(.workflow/WFS-{session}/.brainstorming/session.json)
- Command: Read(.workflow/WFS-{session}/workflow-session.json)
- Output: session_context
## Analysis Requirements
@@ -136,7 +136,7 @@ TodoWrite({
activeForm: "Generating structured scrum-master analysis"
},
{
content: "Update session.json with scrum-master completion status",
content: "Update workflow-session.json with scrum-master completion status",
status: "pending",
activeForm: "Updating session metadata"
}

View File

@@ -88,7 +88,7 @@ ANALYSIS_MODE: {framework_mode ? "framework_based" : "standalone"}
3. **load_session_metadata**
- Action: Load session metadata and existing context
- Command: Read(.workflow/WFS-{session}/.brainstorming/session.json)
- Command: Read(.workflow/WFS-{session}/workflow-session.json)
- Output: session_context
## Analysis Requirements
@@ -136,7 +136,7 @@ TodoWrite({
activeForm: "Generating structured subject-matter-expert analysis"
},
{
content: "Update session.json with subject-matter-expert completion status",
content: "Update workflow-session.json with subject-matter-expert completion status",
status: "pending",
activeForm: "Updating session metadata"
}

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

@@ -88,7 +88,7 @@ ANALYSIS_MODE: {framework_mode ? "framework_based" : "standalone"}
3. **load_session_metadata**
- Action: Load session metadata and existing context
- Command: Read(.workflow/WFS-{session}/.brainstorming/session.json)
- Command: Read(.workflow/WFS-{session}/workflow-session.json)
- Output: session_context
## Analysis Requirements
@@ -136,7 +136,7 @@ TodoWrite({
activeForm: "Generating structured ui-designer analysis"
},
{
content: "Update session.json with ui-designer completion status",
content: "Update workflow-session.json with ui-designer completion status",
status: "pending",
activeForm: "Updating session metadata"
}

View File

@@ -88,7 +88,7 @@ ANALYSIS_MODE: {framework_mode ? "framework_based" : "standalone"}
3. **load_session_metadata**
- Action: Load session metadata and existing context
- Command: Read(.workflow/WFS-{session}/.brainstorming/session.json)
- Command: Read(.workflow/WFS-{session}/workflow-session.json)
- Output: session_context
## Analysis Requirements
@@ -136,7 +136,7 @@ TodoWrite({
activeForm: "Generating structured ux-expert analysis"
},
{
content: "Update session.json with ux-expert completion status",
content: "Update workflow-session.json with ux-expert completion status",
status: "pending",
activeForm: "Updating session metadata"
}

View File

@@ -185,9 +185,9 @@ TodoWrite({
activeForm: "Executing IMPL-1.2: Implement auth logic"
},
{
content: "Execute IMPL-2: Review implementations [code-review-agent]",
content: "Execute TEST-FIX-1: Validate implementation tests [test-fix-agent]",
status: "pending",
activeForm: "Executing IMPL-2: Review implementations"
activeForm: "Executing TEST-FIX-1: Validate implementation tests"
}
]
});
@@ -356,8 +356,8 @@ Task(subagent_type="{meta.agent}",
**WORKFLOW COMPLETION CHECK**:
After updating task status, check if workflow is complete:
total_tasks=\$(ls .workflow/*/\.task/*.json | wc -l)
completed_tasks=\$(ls .workflow/*/\.summaries/*.md 2>/dev/null | wc -l)
total_tasks=\$(find .workflow/*/\.task/ -name "*.json" -type f 2>/dev/null | wc -l)
completed_tasks=\$(find .workflow/*/\.summaries/ -name "*.md" -type f 2>/dev/null | wc -l)
if [ \$total_tasks -eq \$completed_tasks ]; then
SlashCommand(command=\"/workflow:session:complete\")
fi"),
@@ -384,8 +384,8 @@ Task(subagent_type="{meta.agent}",
"title": "Task title",
"status": "pending|active|completed|blocked",
"meta": {
"type": "feature|bugfix|refactor|test|docs",
"agent": "@code-developer|@planning-agent|@code-review-test-agent"
"type": "feature|bugfix|refactor|test-gen|test-fix|docs",
"agent": "@code-developer|@test-fix-agent|@general-purpose"
},
"context": {
"requirements": ["req1", "req2"],
@@ -433,7 +433,7 @@ Task(subagent_type="{meta.agent}",
"task_description": "Implement following consolidated synthesis specification...",
"modification_points": ["Apply synthesis specification requirements..."]
},
"target_files": ["file:function:lines"]
"target_files": ["file:function:lines", "path/to/NewFile.ts"]
}
}
```
@@ -451,8 +451,9 @@ Task(subagent_type="{meta.agent}",
meta.agent specified → Use specified agent
meta.agent missing → Infer from meta.type:
- "feature" → @code-developer
- "test" → @code-review-test-agent
- "review" → @code-review-agent
- "test-gen" → @code-developer
- "test-fix" → @test-fix-agent
- "review" → @general-purpose
- "docs" → @doc-generator
```

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

@@ -1,85 +1,272 @@
---
name: review
description: Execute review phase for quality validation
usage: /workflow:review
argument-hint: none
description: Optional specialized review (security, architecture, docs) for completed implementation
usage: /workflow:review [--type=<type>] [session-id]
argument-hint: "[--type=security|architecture|action-items|quality] [session-id]"
examples:
- /workflow:review
- /workflow:review # Quality review of active session
- /workflow:review --type=security # Security audit of active session
- /workflow:review --type=architecture WFS-user-auth # Architecture review of specific session
- /workflow:review --type=action-items # Pre-deployment verification
---
# Workflow Review Command (/workflow:review)
### 🚀 Command Overview: `/workflow:review`
## Overview
Final phase for quality validation, testing, and completion.
**Optional specialized review** for completed implementations. In the standard workflow, **passing tests = approved code**. Use this command only when specialized review is required (security, architecture, compliance, docs).
## Core Principles
**Session Management:** @~/.claude/workflows/workflow-architecture.md
## Philosophy: "Tests Are the Review"
## Review Process
-**Default**: All tests pass → Code approved
- 🔍 **Optional**: Specialized reviews for:
- 🔒 Security audits (vulnerabilities, auth/authz)
- 🏗️ Architecture compliance (patterns, technical debt)
- 📋 Action items verification (requirements met, acceptance criteria)
1. **Validation Checks**
- All tasks completed
- Tests passing
- Code quality metrics
- Documentation complete
## Review Types
2. **Generate Review Report**
| Type | Focus | Use Case |
|------|-------|----------|
| `quality` | Code quality, best practices, maintainability | Default general review |
| `security` | Security vulnerabilities, data handling, access control | Security audits |
| `architecture` | Architectural patterns, technical debt, design decisions | Architecture compliance |
| `action-items` | Requirements met, acceptance criteria verified, action items completed | Pre-deployment verification |
**Notes**:
- For documentation generation, use `/workflow:tools:docs`
- For CLAUDE.md updates, use `/update-memory-related`
## Execution Template
```bash
#!/bin/bash
# Optional specialized review for completed implementation
# Step 1: Session ID resolution
if [ -n "$SESSION_ARG" ]; then
sessionId="$SESSION_ARG"
else
sessionId=$(find .workflow/ -name '.active-*' | head -1 | sed 's/.*active-//')
fi
# Step 2: Validation
if [ ! -d ".workflow/${sessionId}" ]; then
echo "❌ Session ${sessionId} not found"
exit 1
fi
# Check for completed tasks
if [ ! -d ".workflow/${sessionId}/.summaries" ] || [ -z "$(find .workflow/${sessionId}/.summaries/ -name "IMPL-*.md" -type f 2>/dev/null)" ]; then
echo "❌ No completed implementation found. Complete implementation first"
exit 1
fi
# Step 3: Determine review type (default: quality)
review_type="${TYPE_ARG:-quality}"
# Redirect docs review to specialized command
if [ "$review_type" = "docs" ]; then
echo "💡 For documentation generation, please use:"
echo " /workflow:tools:docs"
echo ""
echo "The docs command provides:"
echo " - Hierarchical architecture documentation"
echo " - API documentation generation"
echo " - Documentation structure analysis"
exit 0
fi
# Step 4: Analysis handover → Model takes control
# BASH_EXECUTION_STOPS → MODEL_ANALYSIS_BEGINS
```
### 🧠 Model Analysis Phase
After bash validation, the model takes control to:
1. **Load Context**: Read completed task summaries and changed files
```bash
# Load implementation summaries
cat .workflow/${sessionId}/.summaries/IMPL-*.md
# Load test results (if available)
cat .workflow/${sessionId}/.summaries/TEST-FIX-*.md 2>/dev/null
# Get changed files
git log --since="$(cat .workflow/${sessionId}/workflow-session.json | jq -r .created_at)" --name-only --pretty=format: | sort -u
```
2. **Perform Specialized Review**: Based on `review_type`
**Security Review** (`--type=security`):
- Use MCP code search for security patterns:
```bash
mcp__code-index__search_code_advanced(pattern="password|token|secret|auth", file_pattern="*.{ts,js,py}")
mcp__code-index__search_code_advanced(pattern="eval|exec|innerHTML|dangerouslySetInnerHTML", file_pattern="*.{ts,js,tsx}")
```
- Use Gemini for security analysis:
```bash
cd .workflow/${sessionId} && ~/.claude/scripts/gemini-wrapper -p "
PURPOSE: Security audit of completed implementation
TASK: Review code for security vulnerabilities, insecure patterns, auth/authz issues
CONTEXT: @{.summaries/IMPL-*.md,../..,../../CLAUDE.md}
EXPECTED: Security findings report with severity levels
RULES: Focus on OWASP Top 10, authentication, authorization, data validation, injection risks
" --approval-mode yolo
```
**Architecture Review** (`--type=architecture`):
- Use Qwen for architecture analysis:
```bash
cd .workflow/${sessionId} && ~/.claude/scripts/qwen-wrapper -p "
PURPOSE: Architecture compliance review
TASK: Evaluate adherence to architectural patterns, identify technical debt, review design decisions
CONTEXT: @{.summaries/IMPL-*.md,../..,../../CLAUDE.md}
EXPECTED: Architecture assessment with recommendations
RULES: Check for patterns, separation of concerns, modularity, scalability
" --approval-mode yolo
```
**Quality Review** (`--type=quality`):
- Use Gemini for code quality:
```bash
cd .workflow/${sessionId} && ~/.claude/scripts/gemini-wrapper -p "
PURPOSE: Code quality and best practices review
TASK: Assess code readability, maintainability, adherence to best practices
CONTEXT: @{.summaries/IMPL-*.md,../..,../../CLAUDE.md}
EXPECTED: Quality assessment with improvement suggestions
RULES: Check for code smells, duplication, complexity, naming conventions
" --approval-mode yolo
```
**Action Items Review** (`--type=action-items`):
- Verify all requirements and acceptance criteria met:
```bash
# Load task requirements and acceptance criteria
find .workflow/${sessionId}/.task -name "IMPL-*.json" -exec jq -r '
"Task: " + .id + "\n" +
"Requirements: " + (.context.requirements | join(", ")) + "\n" +
"Acceptance: " + (.context.acceptance | join(", "))
' {} \;
# Check implementation summaries against requirements
cd .workflow/${sessionId} && ~/.claude/scripts/gemini-wrapper -p "
PURPOSE: Verify all requirements and acceptance criteria are met
TASK: Cross-check implementation summaries against original requirements
CONTEXT: @{.task/IMPL-*.json,.summaries/IMPL-*.md,../..,../../CLAUDE.md}
EXPECTED:
- Requirements coverage matrix
- Acceptance criteria verification
- Missing/incomplete action items
- Pre-deployment readiness assessment
RULES:
- Check each requirement has corresponding implementation
- Verify all acceptance criteria are met
- Flag any incomplete or missing action items
- Assess deployment readiness
" --approval-mode yolo
```
3. **Generate Review Report**: Create structured report
```markdown
# Review Report
## Task Completion
- Total: 10
- Completed: 10
- Success Rate: 100%
## Quality Metrics
- Test Coverage: 85%
- Code Quality: A
- Documentation: Complete
## Issues Found
- Minor: 2
- Major: 0
- Critical: 0
# Review Report: ${review_type}
**Session**: ${sessionId}
**Date**: $(date)
**Type**: ${review_type}
## Summary
- Tasks Reviewed: [count IMPL tasks]
- Files Changed: [count files]
- Severity: [High/Medium/Low]
## Findings
### Critical Issues
- [Issue 1 with file:line reference]
- [Issue 2 with file:line reference]
### Recommendations
- [Recommendation 1]
- [Recommendation 2]
### Positive Observations
- [Good pattern observed]
## Action Items
- [ ] [Action 1]
- [ ] [Action 2]
```
3. **Update Session**
```json
{
"current_phase": "REVIEW",
"phases": {
"REVIEW": {
"status": "completed",
"output": "REVIEW.md",
"test_results": {
"passed": 45,
"failed": 0,
"coverage": 85
}
}
}
}
4. **Output Files**:
```bash
# Save review report
Write(.workflow/${sessionId}/REVIEW-${review_type}.md)
# Update session metadata
# (optional) Update workflow-session.json with review status
```
## Auto-fix (Default)
Auto-fix is enabled by default:
- Automatically fixes minor issues
- Runs formatters and linters
- Updates documentation
- Re-runs tests
5. **Optional: Update Memory** (if docs review or significant findings):
```bash
# If architecture or quality issues found, suggest memory update
if [ "$review_type" = "architecture" ] || [ "$review_type" = "quality" ]; then
echo "💡 Consider updating project documentation:"
echo " /update-memory-related"
fi
```
## Completion Criteria
- All tasks marked complete
- Tests passing (configurable threshold)
- No critical issues
- Documentation updated
## Usage Examples
## Output Files
- `REVIEW.md` - Review report
- `workflow-session.json` - Updated with results
- `test-results.json` - Detailed test output
```bash
# General quality review after implementation
/workflow:review
# Security audit before deployment
/workflow:review --type=security
# Architecture review for specific session
/workflow:review --type=architecture WFS-payment-integration
# Documentation review
/workflow:review --type=docs
```
## ✨ Features
- **Simple Validation**: Check session exists and has completed tasks
- **No Complex Orchestration**: Direct analysis, no multi-phase pipeline
- **Specialized Reviews**: Different prompts and tools for different review types
- **MCP Integration**: Fast code search for security and architecture patterns
- **CLI Tool Integration**: Gemini for analysis, Qwen for architecture
- **Structured Output**: Markdown reports with severity levels and action items
- **Optional Memory Update**: Suggests documentation updates for significant findings
## Integration with Workflow
```
Standard Workflow:
plan → execute → test-gen → execute ✅
Optional Review (when needed):
plan → execute → test-gen → execute → review (security/architecture/docs)
```
**When to Use**:
- Before production deployment (security review + action-items review)
- After major feature (architecture review)
- Before code freeze (quality review)
- Pre-deployment verification (action-items review)
**When NOT to Use**:
- Regular development (tests are sufficient)
- Simple bug fixes (test-fix-agent handles it)
- Minor changes (update-memory-related is enough)
## Related Commands
- `/workflow:execute` - Must complete first
- `/task:status` - Check task completion
- `/workflow:status` - View overall status
- `/workflow:execute` - Must complete implementation first
- `/workflow:test-gen` - Primary quality gate (tests)
- `/workflow:tools:docs` - Generate hierarchical documentation (use instead of `--type=docs`)
- `/update-memory-related` - Update CLAUDE.md docs after architecture findings
- `/workflow:status` - Check session status

View File

@@ -44,8 +44,8 @@ mv temp.json .workflow/WFS-session/workflow-session.json
### Step 5: Count Final Statistics
```bash
ls .workflow/WFS-session/.task/*.json 2>/dev/null | wc -l
ls .workflow/WFS-session/.summaries/*.md 2>/dev/null | wc -l
find .workflow/WFS-session/.task/ -name "*.json" -type f 2>/dev/null | wc -l
find .workflow/WFS-session/.summaries/ -name "*.md" -type f 2>/dev/null | wc -l
```
### Step 6: Remove Active Marker
@@ -56,12 +56,12 @@ rm .workflow/.active-WFS-session-name
## Simple Bash Commands
### Basic Operations
- **Find active session**: `ls .workflow/.active-*`
- **Find active session**: `find .workflow/ -name ".active-*" -type f`
- **Get session name**: `basename marker | sed 's/^\.active-//'`
- **Update status**: `jq '.status = "completed"' session.json > temp.json`
- **Add timestamp**: `jq '.completed_at = "'$(date -u +%Y-%m-%dT%H:%M:%SZ)'"'`
- **Count tasks**: `ls .task/*.json | wc -l`
- **Count completed**: `ls .summaries/*.md | wc -l`
- **Count tasks**: `find .task/ -name "*.json" -type f | wc -l`
- **Count completed**: `find .summaries/ -name "*.md" -type f 2>/dev/null | wc -l`
- **Remove marker**: `rm .workflow/.active-session`
### Completion Result
@@ -92,11 +92,11 @@ Session Completion Summary:
### Error Handling
```bash
# No active session
ls .workflow/.active-* 2>/dev/null || echo "No active session found"
find .workflow/ -name ".active-*" -type f 2>/dev/null || echo "No active session found"
# Incomplete tasks
task_count=$(ls .task/*.json | wc -l)
summary_count=$(ls .summaries/*.md 2>/dev/null | wc -l)
task_count=$(find .task/ -name "*.json" -type f | wc -l)
summary_count=$(find .summaries/ -name "*.md" -type f 2>/dev/null | wc -l)
test $task_count -eq $summary_count || echo "Warning: Not all tasks completed"
```

View File

@@ -35,8 +35,8 @@ jq -r '.session_id, .status, .project' .workflow/WFS-session/workflow-session.js
### Step 4: Count Task Progress
```bash
ls .workflow/WFS-session/.task/*.json 2>/dev/null | wc -l
ls .workflow/WFS-session/.summaries/*.md 2>/dev/null | wc -l
find .workflow/WFS-session/.task/ -name "*.json" -type f 2>/dev/null | wc -l
find .workflow/WFS-session/.summaries/ -name "*.md" -type f 2>/dev/null | wc -l
```
### Step 5: Get Creation Time
@@ -47,11 +47,11 @@ jq -r '.created_at // "unknown"' .workflow/WFS-session/workflow-session.json
## Simple Bash Commands
### Basic Operations
- **List sessions**: `ls .workflow/WFS-*`
- **Find active**: `ls .workflow/.active-*`
- **List sessions**: `find .workflow/ -maxdepth 1 -type d -name "WFS-*"`
- **Find active**: `find .workflow/ -name ".active-*" -type f`
- **Read session data**: `jq -r '.session_id, .status' session.json`
- **Count tasks**: `ls .task/*.json | wc -l`
- **Count completed**: `ls .summaries/*.md | wc -l`
- **Count tasks**: `find .task/ -name "*.json" -type f | wc -l`
- **Count completed**: `find .summaries/ -name "*.md" -type f 2>/dev/null | wc -l`
- **Get timestamp**: `jq -r '.created_at' session.json`
## Simple Output Format

View File

@@ -25,7 +25,7 @@ Generates on-demand views from JSON task data. No synchronization needed - all v
### Step 1: Find Active Session
```bash
ls .workflow/.active-* 2>/dev/null | head -1
find .workflow/ -name ".active-*" -type f 2>/dev/null | head -1
```
### Step 2: Load Session Data
@@ -35,7 +35,7 @@ cat .workflow/WFS-session/workflow-session.json
### Step 3: Scan Task Files
```bash
ls .workflow/WFS-session/.task/*.json 2>/dev/null
find .workflow/WFS-session/.task/ -name "*.json" -type f 2>/dev/null
```
### Step 4: Generate Task Status
@@ -45,8 +45,8 @@ cat .workflow/WFS-session/.task/impl-1.json | jq -r '.status'
### Step 5: Count Task Progress
```bash
ls .workflow/WFS-session/.task/*.json | wc -l
ls .workflow/WFS-session/.summaries/*.md 2>/dev/null | wc -l
find .workflow/WFS-session/.task/ -name "*.json" -type f | wc -l
find .workflow/WFS-session/.summaries/ -name "*.md" -type f 2>/dev/null | wc -l
```
### Step 6: Display Overview
@@ -66,11 +66,11 @@ ls .workflow/WFS-session/.summaries/*.md 2>/dev/null | wc -l
## Simple Bash Commands
### Basic Operations
- **Find active session**: `ls .workflow/.active-*`
- **Find active session**: `find .workflow/ -name ".active-*" -type f`
- **Read session info**: `cat .workflow/session/workflow-session.json`
- **List tasks**: `ls .workflow/session/.task/*.json`
- **List tasks**: `find .workflow/session/.task/ -name "*.json" -type f`
- **Check task status**: `cat task.json | jq -r '.status'`
- **Count completed**: `ls .summaries/*.md | wc -l`
- **Count completed**: `find .summaries/ -name "*.md" -type f | wc -l`
### Task Status Check
- **pending**: Not started yet
@@ -87,8 +87,8 @@ test -f .workflow/.active-* && echo "Session active"
for f in .workflow/session/.task/*.json; do jq empty "$f" && echo "Valid: $f"; done
# Check summaries match
ls .task/*.json | wc -l
ls .summaries/*.md | wc -l
find .task/ -name "*.json" -type f | wc -l
find .summaries/ -name "*.md" -type f 2>/dev/null | wc -l
```
## Simple Output Format

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,145 +1,304 @@
---
name: test-gen
description: Generate comprehensive test workflow based on completed implementation tasks
usage: /workflow:test-gen [session-id]
argument-hint: "WFS-session-id"
description: Create independent test-fix workflow session by analyzing completed implementation
usage: /workflow:test-gen [--use-codex] <source-session-id>
argument-hint: "[--use-codex] <source-session-id>"
examples:
- /workflow:test-gen
- /workflow:test-gen WFS-user-auth
- /workflow:test-gen --use-codex WFS-api-refactor
allowed-tools: SlashCommand(*), TodoWrite(*), Read(*), Bash(*)
---
# Workflow Test Generation Command
# Workflow Test Generation Command (/workflow:test-gen)
## Overview
Analyzes completed implementation sessions and generates comprehensive test requirements, then calls workflow:plan to create test workflow.
## Coordinator Role
## Usage
```bash
/workflow:test-gen # Auto-detect active session
/workflow:test-gen WFS-session-id # Analyze specific session
**This command is a pure orchestrator**: Creates an independent test-fix workflow session for validating a completed implementation. It reuses the standard planning toolchain with automatic cross-session context gathering.
**Core Principles**:
- **Session Isolation**: Creates new `WFS-test-[source]` session to keep verification separate from implementation
- **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
2. Gather cross-session context (automatic) → Parse context path
3. Analyze implementation with concept-enhanced → Parse ANALYSIS_RESULTS.md
4. Generate test task from analysis → Return summary
## Core Rules
1. **Start Immediately**: First action is TodoWrite initialization, second action is Phase 1 test session creation
2. **No Preliminary Analysis**: Do not read files or analyze before Phase 1
3. **Parse Every Output**: Extract required data from each phase 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 (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)
## 5-Phase Execution
### Phase 1: Create Test Session
**Command**: `SlashCommand(command="/workflow:session:start --new \"Test validation for [sourceSessionId]\"")`
**Input**: `sourceSessionId` from user argument (e.g., `WFS-user-auth`)
**Expected Behavior**:
- Creates new session with pattern `WFS-test-[source-slug]` (e.g., `WFS-test-user-auth`)
- Writes metadata to `workflow-session.json`:
- `workflow_type: "test_session"`
- `source_session_id: "[sourceSessionId]"`
- Returns new session ID for subsequent phases
**Parse Output**:
- Extract: new test session ID (store as `testSessionId`)
- Pattern: `WFS-test-[slug]`
**Validation**:
- Source session `.workflow/[sourceSessionId]/` exists
- Source session has completed IMPL tasks (`.summaries/IMPL-*-summary.md`)
- New test session directory created
- Metadata includes `workflow_type` and `source_session_id`
**TodoWrite**: Mark phase 1 completed, phase 2 in_progress
---
### 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`)
**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: test context package path (store as `testContextPath`)
- Pattern: `.workflow/[testSessionId]/.process/test-context-package.json`
**Validation**:
- 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: Test Generation Analysis
**Command**: `SlashCommand(command="/workflow:tools:test-concept-enhanced --session [testSessionId] --context [testContextPath]")`
**Input**:
- `testSessionId` from Phase 1
- `testContextPath` from Phase 2
**Expected Behavior**:
- 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/TEST_ANALYSIS_RESULTS.md` created
- Contains test requirements and generation strategy
- Lists test files to create with specifications
**Validation**:
- 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 Tasks
**Command**: `SlashCommand(command="/workflow:tools:test-task-generate [--use-codex] --session [testSessionId]")`
**Input**:
- `testSessionId` from Phase 1
- `--use-codex` flag (if present in original command)
**Expected Behavior**:
- 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 (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 - 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
**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**:
```
Independent test-fix workflow created successfully!
Source Session: [sourceSessionId]
Test Session: [testSessionId]
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 workflow: /workflow:execute
3. Monitor progress: /workflow:status
```
## Dynamic Session ID Resolution
**TodoWrite**: Mark phase 5 completed
The `${SESSION_ID}` variable is dynamically resolved based on:
---
1. **Command argument**: If session-id provided as argument, use it directly
2. **Auto-detection**: If no argument, detect from active session markers
3. **Format**: Always in format `WFS-session-name`
## TodoWrite Pattern
```bash
# Example resolution logic:
# If argument provided: SESSION_ID = "WFS-user-auth"
# If no argument: SESSION_ID = $(find .workflow/ -name '.active-*' | head -1 | sed 's/.*active-//')
Track progress through 5 phases:
```javascript
TodoWrite({todos: [
{"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"}
]})
```
## Implementation Flow
Update status to `in_progress` when starting each phase, mark `completed` when done.
### Step 1: Identify Target Session
```bash
# Auto-detect active session (if no session-id provided)
find .workflow/ -name '.active-*' | head -1 | sed 's/.*active-//'
## Data Flow
# Use provided session-id or detected session-id
# SESSION_ID = provided argument OR detected active session
```
/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)
```
### Step 2: Get Session Start Time
```bash
cat .workflow/WFS-${SESSION_ID}/workflow-session.json | jq -r .created_at
```
## Session Metadata
### Step 3: Git Change Analysis (using session start time)
```bash
git log --since="$(cat .workflow/WFS-${SESSION_ID}/workflow-session.json | jq -r .created_at)" --name-only --pretty=format: | sort -u | grep -v '^$'
```
Test session includes `workflow_type: "test_session"` and `source_session_id` for automatic context gathering.
### Step 4: Filter Code Files
```bash
git log --since="$(cat .workflow/WFS-${SESSION_ID}/workflow-session.json | jq -r .created_at)" --name-only --pretty=format: | sort -u | grep -E '\.(js|ts|jsx|tsx|py|java|go|rs)$'
```
## Task Output
### Step 5: Load Session Context
```bash
cat .workflow/WFS-${SESSION_ID}/.summaries/IMPL-*-summary.md 2>/dev/null
```
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)
### Step 6: Extract Focus Paths
```bash
find .workflow/WFS-${SESSION_ID}/.task/ -name '*.json' -exec jq -r '.context.focus_paths[]?' {} \;
```
See `/workflow:tools:test-task-generate` for complete task JSON schemas.
### Step 7: Gemini Analysis and Planning Document Generation
```bash
cd project-root && ~/.claude/scripts/gemini-wrapper -p "
PURPOSE: Analyze implementation and generate comprehensive test planning document
TASK: Review changed files and implementation context to create detailed test planning document
CONTEXT: Changed files: [changed_files], Implementation summaries: [impl_summaries], Focus paths: [focus_paths]
EXPECTED: Complete test planning document including:
- Test strategy analysis
- Critical test scenarios identification
- Edge cases and error conditions
- Test priority matrix
- Resource requirements
- Implementation approach recommendations
- Specific test cases with acceptance criteria
RULES: Generate structured markdown document suitable for workflow planning. Focus on actionable test requirements based on actual implementation changes.
" > .workflow/WFS-${SESSION_ID}/.process/GEMINI_TEST_PLAN.md
```
## Error Handling
### Step 8: Generate Combined Test Requirements Document
```bash
mkdir -p .workflow/WFS-${SESSION_ID}/.process
```
| 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 |
```bash
cat > .workflow/WFS-${SESSION_ID}/.process/TEST_REQUIREMENTS.md << 'EOF'
# Test Requirements Summary for WFS-${SESSION_ID}
## Output Files
## Analysis Data Sources
- Git change analysis results
- Implementation summaries and context
- Gemini-generated test planning document
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
## Reference Documents
- Detailed test plan: GEMINI_TEST_PLAN.md
- Implementation context: IMPL-*-summary.md files
## Agent Execution
## Integration Note
This document combines analysis data with Gemini-generated planning document for comprehensive test workflow generation.
EOF
```
**IMPL-001** (@code-developer):
- Generates test files based on TEST_ANALYSIS_RESULTS.md
- Follows existing test patterns and conventions
### Step 9: Call Workflow Plan with Gemini Planning Document
```bash
/workflow:plan .workflow/WFS-${SESSION_ID}/.process/GEMINI_TEST_PLAN.md
```
**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
## Simple Bash Commands
See `/workflow:tools:test-task-generate` for detailed specifications.
### Basic Operations
- **Find active session**: `find .workflow/ -name '.active-*'`
- **Get git changes**: `git log --since='date' --name-only`
- **Filter code files**: `grep -E '\.(js|ts|py)$'`
- **Load summaries**: `cat .workflow/WFS-*/summaries/*.md`
- **Extract JSON data**: `jq -r '.context.focus_paths[]'`
- **Create directory**: `mkdir -p .workflow/session/.process`
- **Write file**: `cat > file << 'EOF'`
## Best Practices
### Gemini CLI Integration
- **Planning command**: `~/.claude/scripts/gemini-wrapper -p "prompt" > GEMINI_TEST_PLAN.md`
- **Context loading**: Include changed files and implementation context
- **Document generation**: Creates comprehensive test planning document
- **Direct handoff**: Pass Gemini planning document to workflow:plan
## No Complex Logic
- No variables or functions
- No conditional statements
- No loops or complex pipes
- Direct bash commands only
- Gemini CLI for intelligent analysis
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` - Called to generate test workflow
- `/workflow:execute` - Executes generated test tasks
- `/workflow:status` - Shows test workflow progress
- `/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
@@ -141,6 +150,9 @@ Advanced solution design and feasibility analysis engine with parallel CLI execu
RULES:
- Focus on SOLUTION IMPROVEMENTS and KEY DESIGN DECISIONS, NOT task planning
- Provide architectural rationale, evaluate alternatives, assess tradeoffs
- **CRITICAL**: Identify code targets - existing files as "file:function:lines", new files as "file"
- For modifications: specify exact files/functions/line ranges
- For new files: specify file path only (no function or lines)
- Do NOT create task lists, implementation steps, or code examples
- Do NOT generate any code snippets or implementation details
- **MUST write output to .workflow/{session_id}/.process/gemini-solution-design.md**
@@ -172,6 +184,8 @@ Advanced solution design and feasibility analysis engine with parallel CLI execu
RULES:
- Focus on TECHNICAL FEASIBILITY and RISK ASSESSMENT, NOT implementation planning
- Validate architectural decisions, identify potential issues, recommend optimizations
- **CRITICAL**: Verify code targets - existing files "file:function:lines", new files "file"
- Confirm exact locations for modifications, identify additional new files if needed
- Do NOT create task breakdowns, step-by-step guides, or code examples
- Do NOT generate any code snippets or implementation details
- **MUST write output to .workflow/{session_id}/.process/codex-feasibility-validation.md**
@@ -301,6 +315,39 @@ Generated ANALYSIS_RESULTS.md focuses on **solution improvements, key design dec
- **Module Dependencies**: {dependency_graph_and_order}
- **Quality Assurance**: {qa_approach_and_validation}
### Code Modification Targets
**Purpose**: Specific code locations for modification AND new files to create
**Format**:
- Existing files: `file:function:lines` (with line numbers)
- New files: `file` (no function or lines)
**Identified Targets**:
1. **Target**: `src/auth/AuthService.ts:login:45-52`
- **Type**: Modify existing
- **Modification**: Enhance error handling
- **Rationale**: Current logic lacks validation for edge cases
2. **Target**: `src/auth/PasswordReset.ts`
- **Type**: Create new file
- **Purpose**: Password reset functionality
- **Rationale**: New feature requirement
3. **Target**: `src/middleware/auth.ts:validateToken:30-45`
- **Type**: Modify existing
- **Modification**: Add token expiry check
- **Rationale**: Security requirement for JWT validation
4. **Target**: `tests/auth/PasswordReset.test.ts`
- **Type**: Create new file
- **Purpose**: Test coverage for password reset
- **Rationale**: Test requirement for new feature
**Note**:
- For new files, only specify the file path (no function or lines)
- For existing files without line numbers, use `file:function:*` format
- Task generation will refine these during the `analyze_task_patterns` step
### Feasibility Assessment
- **Technical Complexity**: {complexity_rating_and_analysis}
- **Performance Impact**: {expected_performance_characteristics}

View File

@@ -158,7 +158,7 @@ Task(
"status": "pending",
"meta": {
"type": "feature|bugfix|refactor|test|docs",
"agent": "@code-developer|@code-review-test-agent"
"agent": "@code-developer|@test-fix-agent|@general-purpose"
},
"context": {
"requirements": ["extracted from analysis"],
@@ -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,16 +217,17 @@ 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"
]
},
"target_files": ["file:function:lines"]
"target_files": ["file:function:lines", "path/to/NewFile.ts"]
}
}
\`\`\`

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:
@@ -95,19 +84,250 @@ For each feature, generate 3 tasks with ID format:
- `meta.agent`: Agent for task execution
- `meta.tdd_phase`: "red" | "green" | "refactor"
### Phase 4: TDD_PLAN.md Generation
#### Task JSON Examples
Generate TDD-specific plan with:
- Feature breakdown
- Red-Green-Refactor chains
- Execution order
- TDD compliance checkpoints
**RED Phase - Test Task (TEST-1.1.json)**
```json
{
"id": "TEST-1.1",
"title": "Write failing test for user authentication",
"status": "pending",
"meta": {
"type": "test",
"agent": "@code-review-test-agent",
"tdd_phase": "red"
},
"context": {
"requirements": [
"Write test case for login with valid credentials",
"Test should fail with 'AuthService not implemented' error",
"Include tests for invalid credentials and edge cases"
],
"focus_paths": ["tests/auth/login.test.ts"],
"acceptance": [
"Test file created with at least 3 test cases",
"Test runs and fails with clear error message",
"Test assertions define expected behavior"
],
"depends_on": []
},
"flow_control": {
"pre_analysis": [
{
"step": "check_test_framework",
"action": "Verify test framework is configured",
"command": "bash(npm list jest || npm list vitest)",
"output_to": "test_framework_info",
"on_error": "warn"
}
]
}
}
```
### Phase 5: Enhanced IMPL_PLAN.md Generation
**GREEN Phase - Implementation Task (IMPL-1.1.json)**
```json
{
"id": "IMPL-1.1",
"title": "Implement user authentication to pass tests",
"status": "pending",
"meta": {
"type": "feature",
"agent": "@code-developer",
"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",
"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",
"Test failures resolved within iteration limit"
],
"depends_on": ["TEST-1.1"]
},
"flow_control": {
"pre_analysis": [
{
"step": "load_test_requirements",
"action": "Read test specifications from TEST phase",
"command": "bash(cat .workflow/WFS-xxx/.summaries/TEST-1.1-summary.md)",
"output_to": "test_requirements",
"on_error": "fail"
},
{
"step": "verify_tests_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 (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"
}
}
}
}
```
Generate standard IMPL_PLAN.md with TDD context reference.
**REFACTOR Phase - Refactoring Task (REFACTOR-1.1.json)**
```json
{
"id": "REFACTOR-1.1",
"title": "Refactor authentication implementation",
"status": "pending",
"meta": {
"type": "refactor",
"agent": "@code-developer",
"tdd_phase": "refactor"
},
"context": {
"requirements": [
"Improve code quality while keeping tests green",
"Remove duplication in credential validation",
"Improve error handling and logging",
"Enhance code readability and maintainability"
],
"focus_paths": ["src/auth/AuthService.ts", "tests/auth/login.test.ts"],
"acceptance": [
"Code quality improved (complexity, readability)",
"All tests still pass after refactoring",
"No new functionality added",
"Duplication eliminated"
],
"depends_on": ["IMPL-1.1"]
},
"flow_control": {
"pre_analysis": [
{
"step": "verify_tests_passing",
"action": "Run tests to confirm green state before refactoring",
"command": "bash(npm test -- tests/auth/login.test.ts)",
"output_to": "test_status",
"on_error": "fail"
},
{
"step": "analyze_code_quality",
"action": "Run linter and complexity analysis",
"command": "bash(npm run lint src/auth/AuthService.ts)",
"output_to": "quality_metrics",
"on_error": "warn"
}
],
"post_completion": [
{
"step": "verify_tests_still_passing",
"action": "Confirm tests remain green after refactoring",
"command": "bash(npm test -- tests/auth/login.test.ts)",
"output_to": "final_test_status",
"on_error": "fail"
}
]
}
}
```
### Phase 6: TODO_LIST.md Generation
### Phase 4: Unified IMPL_PLAN.md Generation
Generate single comprehensive IMPL_PLAN.md with:
**Frontmatter**:
```yaml
---
identifier: WFS-{session-id}
workflow_type: "tdd"
feature_count: N
task_count: 3N
tdd_chains: N
---
```
**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 5: TODO_LIST.md Generation
Generate task list with TDD phase indicators:
```markdown
@@ -117,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
@@ -132,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
@@ -203,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

@@ -67,8 +67,8 @@ Generate task JSON files and IMPL_PLAN.md from analysis results with automatic a
"title": "Descriptive task name",
"status": "pending|active|completed|blocked|container",
"meta": {
"type": "feature|bugfix|refactor|test|docs",
"agent": "@code-developer|@planning-agent|@code-review-test-agent"
"type": "feature|bugfix|refactor|test-gen|test-fix|docs",
"agent": "@code-developer|@test-fix-agent|@general-purpose"
},
"context": {
"requirements": ["Clear requirement from analysis"],
@@ -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"
},
{
@@ -142,20 +145,21 @@ Generate task JSON files and IMPL_PLAN.md from analysis results with automatic a
},
{
"step": "analyze_task_patterns",
"action": "Analyze existing code patterns",
"action": "Analyze existing code patterns and identify modification targets",
"commands": [
"bash(cd \"[focus_paths]\")",
"bash(~/.claude/scripts/gemini-wrapper -p \"PURPOSE: Analyze patterns TASK: Review '[title]' CONTEXT: [synthesis_specification] [individual_artifacts] EXPECTED: Pattern analysis RULES: Prioritize synthesis-specification.md\")"
"bash(~/.claude/scripts/gemini-wrapper -p \"PURPOSE: Identify modification targets TASK: Analyze '[title]' and locate specific files/functions/lines to modify CONTEXT: [synthesis_specification] [individual_artifacts] EXPECTED: Code locations in format 'file:function:lines' RULES: Prioritize synthesis-specification.md, identify exact modification points\")"
],
"output_to": "task_context",
"output_to": "task_context_with_targets",
"on_error": "fail"
}
],
"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"
]
},
@@ -175,8 +180,40 @@ Generate task JSON files and IMPL_PLAN.md from analysis results with automatic a
1. Parse analysis results and extract task definitions
2. Detect brainstorming artifacts with priority scoring
3. Generate task context (requirements, focus_paths, acceptance)
4. Build flow_control with artifact loading steps
5. Create individual task JSON files in `.task/`
4. **Determine modification targets**: Extract specific code locations from analysis
5. Build flow_control with artifact loading steps and target_files
6. Create individual task JSON files in `.task/`
#### Target Files Generation (Critical)
**Purpose**: Identify specific code locations for modification AND new files to create
**Source Data Priority**:
1. **ANALYSIS_RESULTS.md** - Should contain identified code locations
2. **Gemini/MCP Analysis** - From `analyze_task_patterns` step
3. **Context Package** - File references from `focus_paths`
**Format**: `["file:function:lines"]` or `["file"]` (for new files)
- `file`: Relative path from project root (e.g., `src/auth/AuthService.ts`)
- `function`: Function/method name to modify (e.g., `login`, `validateToken`) - **omit for new files**
- `lines`: Approximate line range (e.g., `45-52`, `120-135`) - **omit for new files**
**Examples**:
```json
"target_files": [
"src/auth/AuthService.ts:login:45-52",
"src/middleware/auth.ts:validateToken:30-45",
"src/auth/PasswordReset.ts",
"tests/auth/PasswordReset.test.ts",
"tests/auth.test.ts:testLogin:15-20"
]
```
**Generation Strategy**:
- **New files to create** → Use `["path/to/NewFile.ts"]` (no function or lines)
- **Existing files with specific locations** → Use `["file:function:lines"]`
- **Existing files with function only** → Search lines using MCP/grep `["file:function:*"]`
- **Existing files (explore entire)** → Mark as `["file.ts:*:*"]`
- **No specific targets** → Leave empty `[]` (agent explores focus_paths)
### Phase 3: Artifact Detection & Integration

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

View File

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

View File

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

View File

@@ -1,13 +1,15 @@
#!/bin/bash
# Update CLAUDE.md for a specific module with automatic layer detection
# Usage: update_module_claude.sh <module_path> [update_type]
# Usage: update_module_claude.sh <module_path> [update_type] [tool]
# module_path: Path to the module directory
# update_type: full|related (default: full)
# tool: gemini|qwen|codex (default: gemini)
# Script automatically detects layer depth and selects appropriate template
update_module_claude() {
local module_path="$1"
local update_type="${2:-full}"
local tool="${3:-gemini}"
# Validate parameters
if [ -z "$module_path" ]; then
@@ -40,30 +42,30 @@ 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
# Prepare logging info
local module_name=$(basename "$module_path")
echo "⚡ Updating: $module_path"
echo " Layer: $layer | Type: $update_type | Files: $file_count"
echo " Layer: $layer | Type: $update_type | Tool: $tool | Files: $file_count"
echo " Template: $(basename "$template_path") | Strategy: $analysis_strategy"
# Generate prompt with template injection
@@ -106,31 +108,50 @@ update_module_claude() {
# Execute update
local start_time=$(date +%s)
echo " 🔄 Starting update..."
if cd "$module_path" 2>/dev/null; then
# Execute gemini command with layer-specific analysis strategy
local gemini_result=0
if [ "$analysis_strategy" = "--all-files" ]; then
gemini --all-files --yolo -p "$base_prompt
local tool_result=0
local final_prompt="$base_prompt
Module Information:
- Name: $module_name
- Path: $module_path
- Layer: $layer
- Analysis Strategy: $analysis_strategy" 2>&1
gemini_result=$?
else
gemini --yolo -p "$analysis_strategy $base_prompt
- Tool: $tool
- Analysis Strategy: $analysis_strategy"
Module Information:
- Name: $module_name
- Path: $module_path
- Layer: $layer
- Analysis Strategy: $analysis_strategy" 2>&1
gemini_result=$?
fi
if [ $gemini_result -eq 0 ]; then
# Execute with selected tool
case "$tool" in
qwen)
if [ "$analysis_strategy" = "--all-files" ]; then
qwen --all-files --yolo -p "$final_prompt" 2>&1
tool_result=$?
else
qwen --yolo -p "$analysis_strategy $final_prompt" 2>&1
tool_result=$?
fi
;;
codex)
if [ "$analysis_strategy" = "--all-files" ]; then
codex --full-auto exec "$final_prompt" --skip-git-repo-check -s danger-full-access 2>&1
tool_result=$?
else
codex --full-auto exec "$final_prompt CONTEXT: $analysis_strategy" --skip-git-repo-check -s danger-full-access 2>&1
tool_result=$?
fi
;;
gemini|*)
if [ "$analysis_strategy" = "--all-files" ]; then
gemini --all-files --yolo -p "$final_prompt" 2>&1
tool_result=$?
else
gemini --yolo -p "$analysis_strategy $final_prompt" 2>&1
tool_result=$?
fi
;;
esac
if [ $tool_result -eq 0 ]; then
local end_time=$(date +%s)
local duration=$((end_time - start_time))
echo " ✅ Completed in ${duration}s"

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

@@ -6,6 +6,12 @@ type: search-guideline
# Context Search Strategy
## ⚡ Execution Environment
**CRITICAL**: All commands execute in **Bash environment** (Git Bash on Windows, Bash on Linux/macOS)
**❌ Forbidden**: Windows-specific commands (`findstr`, `dir`, `where`, `type`, `copy`, `del`) - Use Bash equivalents (`grep`, `find`, `which`, `cat`, `cp`, `rm`)
## ⚡ Core Search Tools
**rg (ripgrep)**: Fast content search with regex support
@@ -18,6 +24,7 @@ type: search-guideline
- **Use find for files** - Locate files/directories by name
- **Use grep sparingly** - Only when rg unavailable
- **Use get_modules_by_depth.sh first** - MANDATORY for program architecture analysis before planning
- **Always use Bash commands** - NEVER use Windows cmd/PowerShell commands
### Quick Command Reference
```bash

View File

@@ -6,11 +6,22 @@ type: strategic-guideline
# Intelligent Tools Selection Strategy
## 📋 Table of Contents
1. [Core Framework](#-core-framework)
2. [Tool Specifications](#-tool-specifications)
3. [Command Templates](#-command-templates)
4. [Tool Selection Guide](#-tool-selection-guide)
5. [Usage Patterns](#-usage-patterns)
6. [Best Practices](#-best-practices)
---
## ⚡ Core Framework
**Gemini**: Analysis, understanding, exploration & documentation
**Qwen**: Architecture analysis, code generation & implementation
**Codex**: Development, implementation & automation
### Tool Overview
- **Gemini**: Analysis, understanding, exploration & documentation
- **Qwen**: Architecture analysis, code generation & implementation
- **Codex**: Development, implementation & automation
### Decision Principles
- **Use tools early and often** - Tools are faster, more thorough, and reliable than manual approaches
@@ -18,6 +29,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
@@ -26,57 +38,165 @@ type: strategic-guideline
4. **Not sure?** → Use multiple tools in parallel
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
---
### 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
## 🎯 Tool Specifications
## 🎯 Universal Command Template
### Gemini
- **Command**: `~/.claude/scripts/gemini-wrapper`
- **Strengths**: Large context window, pattern recognition
- **Best For**: Analysis, documentation generation, code exploration
- **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
### Standard Format (REQUIRED)
#### MODE Options
- `analysis` (default) - Read-only analysis and documentation generation
- `write` - ⚠️ Create/modify codebase files (requires explicit specification, auto-enables --approval-mode yolo)
### Qwen
- **Command**: `~/.claude/scripts/qwen-wrapper`
- **Strengths**: Architecture analysis, pattern recognition
- **Best For**: System design analysis, architectural review
- **Permissions**: Architecture analysis only, no automatic code generation
- **Default MODE**: `analysis` (read-only)
- **⚠️ Write Trigger**: Explicitly prohibited from auto-calling write mode
#### MODE Options
- `analysis` (default) - Architecture analysis only, no code generation/modification (read-only)
- `write` - ⚠️ Code generation (requires explicit specification, disabled by default)
### Codex
- **Command**: `codex --full-auto exec`
- **Strengths**: Autonomous development, mathematical reasoning
- **Best For**: Implementation, testing, automation
- **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
#### MODE Options
- `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
#### 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
- **Parameter Position**: `resume --last` must be placed AFTER the prompt string at command END
- **Example**:
```bash
# First task - establish session
codex -C project --full-auto exec "Implement auth module" --skip-git-repo-check -s danger-full-access
# Subsequent tasks - continue same session
codex --full-auto exec "Add JWT validation" resume --last --skip-git-repo-check -s danger-full-access
codex --full-auto exec "Write auth tests" resume --last --skip-git-repo-check -s danger-full-access
```
#### Auto-Resume Decision Rules
**When to use `resume --last`**:
- Current task is related to/extends previous Codex task in conversation memory
- Current task requires context from previous implementation
- Current task is part of multi-step workflow (e.g., implement → enhance → test)
- Session memory indicates recent Codex execution on same module/feature
**When NOT to use `resume --last`**:
- First Codex task in conversation
- New independent task unrelated to previous work
- Switching to different module/feature area
- No recent Codex task in conversation memory
---
## 🎯 Command Templates
### Universal Template Structure
Every command MUST follow this structure:
- [ ] **PURPOSE** - Clear goal and intent
- [ ] **TASK** - Specific execution task
- [ ] **MODE** - Execution mode and permission level
- [ ] **CONTEXT** - File references and memory context from previous sessions
- [ ] **EXPECTED** - Clear expected results
- [ ] **RULES** - Template reference and constraints
### Standard Command Formats
#### Gemini Commands
```bash
# Gemini Analysis
# Gemini Analysis (read-only, default)
cd [directory] && ~/.claude/scripts/gemini-wrapper -p "
PURPOSE: [clear analysis goal]
TASK: [specific analysis task]
MODE: analysis
CONTEXT: [file references and memory context]
EXPECTED: [expected output]
RULES: [template reference and constraints]
"
# Qwen Architecture & Code Generation
# Gemini Write Mode (requires explicit MODE=write)
# NOTE: --approval-mode yolo must be placed AFTER wrapper command, BEFORE -p
cd [directory] && ~/.claude/scripts/gemini-wrapper --approval-mode yolo -p "
PURPOSE: [clear goal]
TASK: [specific task]
MODE: write
CONTEXT: [file references and memory context]
EXPECTED: [expected output]
RULES: [template reference and constraints]
"
```
#### Qwen Commands
```bash
# Qwen Architecture Analysis (read-only, default)
cd [directory] && ~/.claude/scripts/qwen-wrapper -p "
PURPOSE: [clear architecture/code goal]
TASK: [specific architecture/code task]
PURPOSE: [clear architecture goal]
TASK: [specific analysis task]
MODE: analysis
CONTEXT: [file references and memory context]
EXPECTED: [expected deliverables]
RULES: [template reference and constraints]
"
# Codex Development
# Qwen Write Mode (requires explicit MODE=write)
# NOTE: --approval-mode yolo must be placed AFTER wrapper command, BEFORE -p
cd [directory] && ~/.claude/scripts/qwen-wrapper --approval-mode yolo -p "
PURPOSE: [clear goal]
TASK: [specific task]
MODE: write
CONTEXT: [file references and memory context]
EXPECTED: [expected deliverables]
RULES: [template reference and constraints]
"
```
#### Codex Commands
```bash
# Codex Development (requires explicit MODE=auto)
# NOTE: --skip-git-repo-check and -s danger-full-access must be placed at command END
codex -C [directory] --full-auto exec "
PURPOSE: [clear development goal]
TASK: [specific development task]
MODE: auto
CONTEXT: [file references and memory context]
EXPECTED: [expected deliverables]
RULES: [template reference and constraints]
" --skip-git-repo-check -s danger-full-access
# Codex Test/Write Mode (requires explicit MODE=write)
# NOTE: --skip-git-repo-check and -s danger-full-access must be placed at command END
codex -C [directory] --full-auto exec "
PURPOSE: [clear goal]
TASK: [specific task]
MODE: write
CONTEXT: [file references and memory context]
EXPECTED: [expected deliverables]
RULES: [template reference and constraints]
" --skip-git-repo-check -s danger-full-access
```
### Template Structure
- [ ] **PURPOSE** - Clear goal and intent
- [ ] **TASK** - Specific execution task
- [ ] **CONTEXT** - File references and memory context from previous sessions
- [ ] **EXPECTED** - Clear expected results
- [ ] **RULES** - Template reference and constraints
### Directory Context
### Directory Context Configuration
Tools execute in current working directory:
- **Gemini**: `cd path/to/project && ~/.claude/scripts/gemini-wrapper -p "prompt"`
- **Qwen**: `cd path/to/project && ~/.claude/scripts/qwen-wrapper -p "prompt"`
@@ -84,7 +204,7 @@ Tools execute in current working directory:
- **Path types**: Supports both relative (`../project`) and absolute (`/full/path`) paths
- **Token analysis**: For gemini-wrapper and qwen-wrapper, token counting happens in current directory
### Rules Field Format
### RULES Field Format
```bash
RULES: $(cat "~/.claude/workflows/cli-templates/prompts/[category]/[template].txt") | [constraints]
```
@@ -95,7 +215,44 @@ RULES: $(cat "~/.claude/workflows/cli-templates/prompts/[category]/[template].tx
- No template: `Focus on security patterns, include dependency analysis`
- File patterns: `@{src/**/*.ts,CLAUDE.md} - Stay within scope`
## 📊 Tool Selection Matrix
### File Pattern Reference
- All files: `@{**/*}`
- Source files: `@{src/**/*}`
- TypeScript: `@{*.ts,*.tsx}`
- With docs: `@{CLAUDE.md,**/*CLAUDE.md}`
- Tests: `@{src/**/*.test.*}`
**Complex Pattern Discovery**:
For complex file pattern requirements, use semantic discovery tools BEFORE CLI execution:
- **rg (ripgrep)**: Content-based file discovery with regex patterns
- **Code Index MCP**: Semantic file search based on task requirements
- **Workflow**: Discover → Extract precise paths → Build CONTEXT field
**Example**:
```bash
# Step 1: Discover files semantically
rg "export.*Component" --files-with-matches --type ts # Find component files
mcp__code-index__search_code_advanced(pattern="interface.*Props", file_pattern="*.tsx") # Find interface files
# Step 2: Build precise CONTEXT from discovery results
CONTEXT: @{src/components/Auth.tsx,src/types/auth.d.ts,src/hooks/useAuth.ts}
# Step 3: Execute CLI with precise file references
cd src && ~/.claude/scripts/gemini-wrapper -p "
PURPOSE: Analyze authentication components
TASK: Review auth component patterns and props interfaces
MODE: analysis
CONTEXT: @{components/Auth.tsx,types/auth.d.ts,hooks/useAuth.ts}
EXPECTED: Pattern analysis and improvement suggestions
RULES: Focus on type safety and component composition
"
```
---
## 📊 Tool Selection Guide
### Selection Matrix
| Task Type | Tool | Use Case | Template |
|-----------|------|----------|-----------|
@@ -108,11 +265,11 @@ RULES: $(cat "~/.claude/workflows/cli-templates/prompts/[category]/[template].tx
| **Security** | Codex | Vulnerability assessment, fixes | `analysis/security.txt` |
| **Refactoring** | Multiple | Gemini for analysis, Qwen/Codex for execution | `development/refactor.txt` |
## 📁 Template System
### Template System
**Base Structure**: `~/.claude/workflows/cli-templates/`
### Available Templates
#### Available Templates
```
prompts/
├── analysis/
@@ -138,6 +295,8 @@ tech-stacks/
└── react-dev.md - React architecture
```
---
## 🚀 Usage Patterns
### Workflow Integration (REQUIRED)
@@ -149,95 +308,95 @@ When planning any coding task, **ALWAYS** integrate CLI tools:
4. **Quality Phase**: Use Codex for testing and validation
### Common Scenarios
#### Code Analysis
```bash
# Project Analysis (in current directory)
~/.claude/scripts/gemini-wrapper -p "
PURPOSE: Understand codebase architecture
TASK: Analyze project structure and identify patterns
MODE: analysis
CONTEXT: @{src/**/*.ts,CLAUDE.md} Previous analysis of auth system
EXPECTED: Architecture overview and integration points
RULES: $(cat "~/.claude/workflows/cli-templates/prompts/analysis/architecture.txt") | Focus on integration points
"
# Project Analysis (in different directory)
cd ../other-project && ~/.claude/scripts/gemini-wrapper -p "
PURPOSE: Compare authentication patterns
TASK: Analyze auth implementation in related project
CONTEXT: @{src/auth/**/*} Current project context from session memory
EXPECTED: Pattern comparison and recommendations
RULES: $(cat "~/.claude/workflows/cli-templates/prompts/analysis/pattern.txt") | Focus on architectural differences
"
# Architecture Design (with Qwen)
cd src/auth && ~/.claude/scripts/qwen-wrapper -p "
PURPOSE: Design authentication system architecture
TASK: Create modular JWT-based auth system design
CONTEXT: @{src/auth/**/*} Existing patterns and requirements
EXPECTED: Complete architecture with code scaffolding
RULES: $(cat "~/.claude/workflows/cli-templates/prompts/analysis/architecture.txt") | Focus on modularity and security
"
# Feature Development (in target directory)
codex -C path/to/project --full-auto exec "
PURPOSE: Implement user authentication
TASK: Create JWT-based authentication system
CONTEXT: @{src/auth/**/*} Database schema from session memory
EXPECTED: Complete auth module with tests
RULES: $(cat "~/.claude/workflows/cli-templates/prompts/development/feature.txt") | Follow security best practices
" --skip-git-repo-check -s danger-full-access
# Code Review Preparation
~/.claude/scripts/gemini-wrapper -p "
PURPOSE: Prepare comprehensive code review
TASK: Analyze code changes and identify potential issues
CONTEXT: @{**/*.modified} Recent changes discussed in last session
EXPECTED: Review checklist and improvement suggestions
RULES: $(cat "~/.claude/workflows/cli-templates/prompts/analysis/quality.txt") | Focus on maintainability
RULES: $(cat '~/.claude/workflows/cli-templates/prompts/analysis/architecture.txt') | Focus on integration points
"
```
## 📋 Planning Checklist
#### Documentation Generation
```bash
~/.claude/scripts/gemini-wrapper -p "
PURPOSE: Generate API documentation
TASK: Create comprehensive API reference from code
MODE: write
CONTEXT: @{src/api/**/*}
EXPECTED: API.md with all endpoints documented
RULES: Follow project documentation standards
"
```
For every development task:
- [ ] **Purpose defined** - Clear goal and intent
- [ ] **Context gathered** - File references and session memory documented
- [ ] **Gemini analysis** completed for understanding
- [ ] **Template selected** - Appropriate template chosen
- [ ] **Constraints specified** - File patterns, scope, requirements
- [ ] **Implementation approach** - Tool selection and workflow
- [ ] **Quality measures** - Testing and validation plan
#### Architecture Analysis
```bash
cd src/auth && ~/.claude/scripts/qwen-wrapper -p "
PURPOSE: Analyze authentication system architecture
TASK: Review JWT-based auth system design
MODE: analysis
CONTEXT: @{src/auth/**/*} Existing patterns and requirements
EXPECTED: Architecture analysis report with recommendations
RULES: $(cat '~/.claude/workflows/cli-templates/prompts/analysis/architecture.txt') | Focus on security
"
```
## 🎯 Key Features
#### Feature Development (Multi-task with Resume)
```bash
# First task - establish session
codex -C path/to/project --full-auto exec "
PURPOSE: Implement user authentication
TASK: Create JWT-based authentication system
MODE: auto
CONTEXT: @{src/auth/**/*} Database schema from session memory
EXPECTED: Complete auth module with tests
RULES: $(cat '~/.claude/workflows/cli-templates/prompts/development/feature.txt') | Follow security best practices
" --skip-git-repo-check -s danger-full-access
### Gemini
- **Command**: `~/.claude/scripts/gemini-wrapper`
- **Strengths**: Large context window, pattern recognition
- **Best For**: Analysis, architecture review, code exploration
# Continue in same session - Add JWT validation
codex --full-auto exec "
PURPOSE: Enhance authentication security
TASK: Add JWT token validation and refresh logic
MODE: auto
CONTEXT: Previous auth implementation from current session
EXPECTED: JWT validation middleware and token refresh endpoints
RULES: Follow JWT best practices, maintain session context
" resume --last --skip-git-repo-check -s danger-full-access
### Qwen
- **Command**: `~/.claude/scripts/qwen-wrapper`
- **Strengths**: Architecture analysis, code generation, implementation patterns
- **Best For**: System design, code scaffolding, architectural planning
# Continue in same session - Add tests
codex --full-auto exec "
PURPOSE: Increase test coverage
TASK: Generate comprehensive tests for auth module
MODE: write
CONTEXT: Auth implementation from current session
EXPECTED: Complete test suite with 80%+ coverage
RULES: Use Jest, follow existing patterns
" resume --last --skip-git-repo-check -s danger-full-access
```
### 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
#### Interactive Session Resume
```bash
# Resume previous session with picker
codex resume
### File Patterns
- All files: `@{**/*}`
- Source files: `@{src/**/*}`
- TypeScript: `@{*.ts,*.tsx}`
- With docs: `@{CLAUDE.md,**/*CLAUDE.md}`
- Tests: `@{src/**/*.test.*}`
# Or resume most recent session directly
codex resume --last
```
---
## 🔧 Best Practices
### General Guidelines
- **Start with templates** - Use predefined templates for consistency
- **Be specific** - Clear PURPOSE, TASK, and EXPECTED fields
- **Include constraints** - File patterns, scope, requirements in RULES
- **Test patterns first** - Validate file patterns with `ls`
- **Discover patterns first** - Use rg/MCP for complex file discovery before CLI execution
- **Build precise CONTEXT** - Convert discovery results to explicit file references
- **Document context** - Always reference CLAUDE.md for context
### Context Optimization Strategy
@@ -250,15 +409,71 @@ For every development task:
**Example**:
```bash
# Focused analysis (preferred)
cd src/auth && ~/.claude/scripts/gemini-wrapper -p "analyze auth patterns"
# Gemini - Focused analysis
cd src/auth && ~/.claude/scripts/gemini-wrapper -p "
PURPOSE: Understand authentication patterns
TASK: Analyze auth implementation
MODE: analysis
CONTEXT: @{**/*.ts}
EXPECTED: Pattern documentation
RULES: Focus on security best practices
"
# Focused architecture (Qwen)
cd src/auth && ~/.claude/scripts/qwen-wrapper -p "design auth architecture"
# Qwen - Architecture analysis
cd src/auth && ~/.claude/scripts/qwen-wrapper -p "
PURPOSE: Analyze auth architecture
TASK: Review auth system design and patterns
MODE: analysis
CONTEXT: @{**/*}
EXPECTED: Architecture analysis report
RULES: Focus on modularity and security
"
# Focused implementation (Codex)
codex -C src/auth --full-auto exec "analyze auth implementation" --skip-git-repo-check
# Codex - Implementation
codex -C src/auth --full-auto exec "
PURPOSE: Improve auth implementation
TASK: Review and enhance auth code
MODE: auto
CONTEXT: @{**/*.ts}
EXPECTED: Code improvements and fixes
RULES: Maintain backward compatibility
" --skip-git-repo-check -s danger-full-access
```
# Multi-scope (stay in root)
~/.claude/scripts/gemini-wrapper -p "CONTEXT: @{src/auth/**/*,src/api/**/*}"
```
### Planning Checklist
For every development task:
- [ ] **Purpose defined** - Clear goal and intent
- [ ] **Mode selected** - Execution mode and permission level determined
- [ ] **Context gathered** - File references and session memory documented
- [ ] **Gemini analysis** completed for understanding
- [ ] **Template selected** - Appropriate template chosen
- [ ] **Constraints specified** - File patterns, scope, requirements
- [ ] **Implementation approach** - Tool selection and workflow
- [ ] **Quality measures** - Testing and validation plan
- [ ] **Tool configuration** - Review `.gemini/CLAUDE.md` or `.codex/Agent.md` if needed
---
## ⚙️ Execution Configuration
### Core Execution Rules
- **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
- **⚠️ 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
- **Parameter Position**: Place AFTER the wrapper command: `gemini-wrapper --approval-mode yolo -p "..."`
- **Codex Write Access**: Use `-s danger-full-access` and `--skip-git-repo-check` ONLY when MODE=auto explicitly specified
- **Parameter Position**: Place AFTER the prompt string at command END: `codex ... exec "..." --skip-git-repo-check -s danger-full-access`
- **Default Behavior**: All tools default to analysis/read-only mode without explicit write permission

View File

@@ -13,8 +13,8 @@ All task files use this simplified 5-field schema (aligned with workflow-archite
"status": "pending|active|completed|blocked|container",
"meta": {
"type": "feature|bugfix|refactor|test|docs",
"agent": "@code-developer|@planning-agent|@code-review-test-agent"
"type": "feature|bugfix|refactor|test-gen|test-fix|docs",
"agent": "@code-developer|@action-planning-agent|@test-fix-agent|@general-purpose"
},
"context": {
@@ -49,7 +49,8 @@ All task files use this simplified 5-field schema (aligned with workflow-archite
},
"target_files": [
"src/auth/login.ts:handleLogin:75-120",
"src/middleware/auth.ts:validateToken"
"src/middleware/auth.ts:validateToken",
"src/auth/PasswordReset.ts"
]
}
}
@@ -81,7 +82,7 @@ All task files use this simplified 5-field schema (aligned with workflow-archite
**Components**:
- **pre_analysis**: Array of sequential process steps
- **implementation_approach**: Task execution strategy
- **target_files**: Specific files to modify in "file:function:lines" format
- **target_files**: Files to modify/create - existing files in `file:function:lines` format, new files as `file` only
**Step Structure**:
```json
@@ -145,17 +146,17 @@ Tasks inherit from:
## Agent Mapping
### Automatic Agent Selection
- **@code-developer**: Implementation tasks, coding
- **@planning-agent**: Design, architecture planning
- **@code-review-test-agent**: Testing, validation
- **@review-agent**: Code review, quality checks
- **@code-developer**: Implementation tasks, coding, test writing
- **@action-planning-agent**: Design, architecture planning
- **@test-fix-agent**: Test execution, failure diagnosis, code fixing
- **@general-purpose**: Optional manual review (only when explicitly requested)
### Agent Context Filtering
Each agent receives tailored context:
- **@code-developer**: Complete implementation details
- **@planning-agent**: High-level requirements, risks
- **@test-agent**: Files to test, logic flows to validate
- **@review-agent**: Quality standards, security considerations
- **@code-developer**: Complete implementation details, test requirements
- **@action-planning-agent**: High-level requirements, risks, architecture
- **@test-fix-agent**: Test execution, failure diagnosis, code fixing
- **@general-purpose**: Quality standards, security considerations (when requested)
## Deprecated Fields

View File

@@ -113,8 +113,8 @@ All task files use this unified 5-field schema with optional artifacts enhanceme
"status": "pending|active|completed|blocked|container",
"meta": {
"type": "feature|bugfix|refactor|test|docs",
"agent": "code-developer|planning-agent|code-review-test-agent"
"type": "feature|bugfix|refactor|test-gen|test-fix|docs",
"agent": "@code-developer|@action-planning-agent|@test-fix-agent|@general-purpose"
},
"context": {
@@ -175,7 +175,8 @@ All task files use this unified 5-field schema with optional artifacts enhanceme
},
"target_files": [
"src/auth/login.ts:handleLogin:75-120",
"src/middleware/auth.ts:validateToken"
"src/middleware/auth.ts:validateToken",
"src/auth/PasswordReset.ts"
]
}
}
@@ -219,7 +220,7 @@ The **flow_control** field manages task execution with two main components:
- **task_description**: Comprehensive implementation description
- **modification_points**: Specific code modification targets
- **logic_flow**: Business logic execution sequence
- **target_files**: Target file list in `file:function:lines` format
- **target_files**: Target file list - existing files in `file:function:lines` format, new files as `file` only
#### Tool Reference
**Command Types Available**:
@@ -420,10 +421,10 @@ fi
### Agent Assignment
Based on task type and title keywords:
- **Planning tasks** → @planning-agent
- **Implementation** → @code-developer
- **Testing** → @code-review-test-agent
- **Review** → @review-agent
- **Planning tasks** → @action-planning-agent
- **Implementation** → @code-developer (code + tests)
- **Test execution/fixing** → @test-fix-agent
- **Review** → @general-purpose (optional, only when explicitly requested)
### Execution Context
Agents receive complete task JSON plus workflow context:

371
.codex/AGENTS.md Normal file
View File

@@ -0,0 +1,371 @@
# Codex Agent Execution Protocol
## Overview
**Role**: Codex - autonomous development, implementation, and testing
## Prompt Structure
### Single-Task Format
**Receive prompts in this format**:
```
PURPOSE: [development goal]
TASK: [specific implementation task]
MODE: [auto|write]
CONTEXT: [file patterns]
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
### System Optimization
**Hard Requirement**: Call binaries directly in `functions.shell`, always set `workdir`, and avoid shell wrappers such as `bash -lc`, `sh -lc`, `zsh -lc`, `cmd /c`, `pwsh.exe -NoLogo -NoProfile -Command`, and `powershell.exe -NoLogo -NoProfile -Command`.
**Text Editing Priority**: Use the `apply_patch` tool for all routine text edits; fall back to `sed` for single-line substitutions only if `apply_patch` is unavailable, and avoid `python` editing scripts unless both options fail.
**`apply_patch` Usage**: Invoke `apply_patch` with the patch payload as the second element in the command array (no shell-style flags). Provide `workdir` and, when helpful, a short `justification` alongside the command.
**Example invocation**:
```json
{
"command": ["apply_patch", "*** Begin Patch\n*** Update File: path/to/file\n@@\n- old\n+ new\n*** End Patch\n"],
"workdir": "<workdir>",
"justification": "Brief reason for the change"
}
```
**Windows UTF-8 Encoding**: Before executing commands on Windows systems, ensure proper UTF-8 encoding by running:
```powershell
[Console]::InputEncoding = [Text.UTF8Encoding]::new($false)
[Console]::OutputEncoding = [Text.UTF8Encoding]::new($false)
chcp 65001 > $null
```
### ALWAYS
- **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
- **Test continuously** - Run tests after every change
- **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
- **Use direct binary calls** - Avoid shell wrappers for efficiency
- **Prefer apply_patch** - Use for text edits over Python scripts
- **Configure Windows encoding** - Set UTF-8 for Chinese character support
### NEVER
- **Make assumptions** - Verify with existing code
- **Ignore existing patterns** - Study before implementing
- **Skip tests** - Tests are mandatory
- **Use clever tricks** - Choose boring, obvious solutions
- **Over-engineer** - Simple solutions over complex architectures
- **Break existing code** - Ensure backward compatibility
- **Exceed 3 attempts** - Stop and reassess if blocked 3 times
## MODE Behavior
### MODE: auto (default)
**Permissions**:
- Full file operations (create/modify/delete)
- Run tests and builds
- Commit code incrementally
**Execute (Single Task)**:
1. Parse PURPOSE and TASK
2. Analyze CONTEXT files - find 3+ similar patterns
3. Plan implementation approach
4. Generate code following RULES and project patterns
5. Write tests alongside code
6. Run tests continuously
7. Commit working code incrementally
8. Validate all EXPECTED deliverables
9. Report results
**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
**Permissions**:
- Focused file operations
- Create/modify specific files
- Run tests for validation
**Execute**:
1. Analyze CONTEXT files
2. Make targeted changes
3. Validate tests pass
4. Report file changes
**Use For**: Test generation, documentation updates, targeted fixes
## RULES Processing
- **Parse the RULES field** to identify template content and additional constraints
- **Recognize `|` as separator** between template and additional constraints
- **ALWAYS apply all template guidelines** provided in the prompt
- **ALWAYS apply all additional constraints** specified after `|`
- **Treat all rules as mandatory** - both template and constraints must be followed
- **Failure to follow any rule** constitutes task failure
## Error Handling
### Three-Attempt Rule
**On 3rd failed attempt**:
1. **Stop execution**
2. **Report status**: What was attempted, what failed, root cause
3. **Request guidance**: Ask for clarification, suggest alternatives
### Recovery Strategies
**Syntax/Type Errors**:
1. Review and fix errors
2. Re-run tests
3. Validate build succeeds
**Runtime Errors**:
1. Analyze stack trace
2. Add error handling
3. Add tests for error cases
**Test Failures**:
1. Debug in isolation
2. Review test setup
3. Fix implementation or test
**Build Failures**:
1. Check error messages
2. Fix incrementally
3. Validate each fix
## Progress Reporting
### During Execution (Single Task)
```
[1/5] Analyzing existing code patterns...
[2/5] Planning implementation approach...
[3/5] Generating code...
[4/5] Writing tests...
[5/5] Running validation...
```
### 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
Changes:
- Created: [files with line counts]
- Modified: [files with changes]
Validation:
✅ Tests: [count] passing
✅ Coverage: [percentage]
✅ Build: Success
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
```
⚠️ Task partially completed
Completed: [what worked]
Blocked: [what failed and why]
Required: [what's needed]
Recommendation: [next steps]
```
## Quality Standards
### Code Quality
- Follow project's existing patterns
- Match import style and naming conventions
- Single responsibility per function/class
- DRY (Don't Repeat Yourself)
- YAGNI (You Aren't Gonna Need It)
### Testing
- Test all public functions
- Test edge cases and error conditions
- Mock external dependencies
- Target 80%+ coverage
### Error Handling
- Proper try-catch blocks
- Clear error messages
- 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
- **Learning from existing code** - Study 3+ patterns before implementing
- **Pragmatic over dogmatic** - Adapt to project reality
- **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
### Before Implementation
- [ ] Understand PURPOSE and TASK clearly
- [ ] Review all CONTEXT files
- [ ] Find 3+ similar patterns in codebase
- [ ] Check RULES templates and constraints
- [ ] Plan implementation approach
### During Implementation
- [ ] Follow existing patterns exactly
- [ ] Write tests alongside code
- [ ] Run tests after every change
- [ ] Commit working code incrementally
- [ ] Handle errors properly
### After Implementation
- [ ] Run full test suite - all pass
- [ ] Check coverage - meets target
- [ ] Run build - succeeds
- [ ] Review EXPECTED - all deliverables met
---
**Version**: 2.2.0
**Last Updated**: 2025-10-04
**Changes**:
- Added system optimization requirements for direct binary calls
- Added apply_patch tool priority for text editing
- Added Windows UTF-8 encoding configuration for Chinese character support
- Previous: Multi-step task execution support with resume mechanism

143
.gemini/GEMINI.md Normal file
View File

@@ -0,0 +1,143 @@
# Gemini Execution Protocol
## Overview
**Role**: Gemini - code analysis and documentation generation
## Prompt Structure
**Receive prompts in this format**:
```
PURPOSE: [goal statement]
TASK: [specific task]
MODE: [analysis|write]
CONTEXT: [file patterns]
EXPECTED: [deliverables]
RULES: [constraints and templates]
```
## Execution Requirements
### ALWAYS
- **Parse all six fields** - Understand PURPOSE, TASK, MODE, CONTEXT, EXPECTED, RULES
- **Follow MODE strictly** - Respect permission boundaries
- **Analyze CONTEXT files** - Read all matching patterns thoroughly
- **Apply RULES** - Follow templates and constraints exactly
- **Provide evidence** - Quote code with file:line references
- **Match EXPECTED** - Deliver exactly what's requested
### NEVER
- **Assume behavior** - Verify with actual code
- **Ignore CONTEXT** - Stay within specified file patterns
- **Skip RULES** - Templates are mandatory when provided
- **Make unsubstantiated claims** - Always back with code references
- **Deviate from MODE** - Respect read/write boundaries
## MODE Behavior
### MODE: analysis (default)
**Permissions**:
- Read all CONTEXT files
- Create/modify documentation files
**Execute**:
1. Read and analyze CONTEXT files
2. Identify patterns and issues
3. Generate insights and recommendations
4. Create documentation if needed
5. Output structured analysis
**Constraint**: Do NOT modify source code files
### MODE: write
**Permissions**:
- Full file operations
- Create/modify any files
**Execute**:
1. Read CONTEXT files
2. Perform requested file operations
3. Create/modify files as specified
4. Validate changes
5. Report file changes
## Output Format
### Standard Analysis Structure
```markdown
# Analysis: [TASK Title]
## Summary
[2-3 sentence overview]
## Key Findings
1. [Finding] - path/to/file:123
2. [Finding] - path/to/file:456
## Detailed Analysis
[Evidence-based analysis with code quotes]
## Recommendations
1. [Actionable recommendation]
2. [Actionable recommendation]
```
### Code References
Always use format: `path/to/file:line_number`
Example: "Authentication logic at `src/auth/jwt.ts:45` uses deprecated algorithm"
## RULES Processing
- **Parse the RULES field** to identify template content and additional constraints
- **Recognize `|` as separator** between template and additional constraints
- **ALWAYS apply all template guidelines** provided in the prompt
- **ALWAYS apply all additional constraints** specified after `|`
- **Treat all rules as mandatory** - both template and constraints must be followed
- **Failure to follow any rule** constitutes task failure
## Error Handling
**File Not Found**:
- Report missing files
- Continue with available files
- Note in output
**Invalid CONTEXT Pattern**:
- Report invalid pattern
- Request correction
- Do not guess
## Quality Standards
### Thoroughness
- Analyze ALL files in CONTEXT
- Check cross-file patterns
- Identify edge cases
- Quantify when possible
### Evidence-Based
- Quote relevant code
- Provide file:line references
- Link related patterns
### Actionable
- Clear recommendations
- Prioritized by impact
- Specific, not vague
## Philosophy
- **Incremental over big bangs** - Suggest small, testable changes
- **Learn from existing code** - Reference project patterns
- **Pragmatic over dogmatic** - Adapt to project reality
- **Clear over clever** - Prefer obvious solutions
- **Simple over complex** - Avoid over-engineering

4
.gitignore vendored
View File

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

143
.qwen/QWEN.md Normal file
View File

@@ -0,0 +1,143 @@
# QWEN Execution Protocol
## Overview
**Role**: QWEN - code analysis and documentation generation
## Prompt Structure
**Receive prompts in this format**:
```
PURPOSE: [goal statement]
TASK: [specific task]
MODE: [analysis|write]
CONTEXT: [file patterns]
EXPECTED: [deliverables]
RULES: [constraints and templates]
```
## Execution Requirements
### ALWAYS
- **Parse all six fields** - Understand PURPOSE, TASK, MODE, CONTEXT, EXPECTED, RULES
- **Follow MODE strictly** - Respect permission boundaries
- **Analyze CONTEXT files** - Read all matching patterns thoroughly
- **Apply RULES** - Follow templates and constraints exactly
- **Provide evidence** - Quote code with file:line references
- **Match EXPECTED** - Deliver exactly what's requested
### NEVER
- **Assume behavior** - Verify with actual code
- **Ignore CONTEXT** - Stay within specified file patterns
- **Skip RULES** - Templates are mandatory when provided
- **Make unsubstantiated claims** - Always back with code references
- **Deviate from MODE** - Respect read/write boundaries
## MODE Behavior
### MODE: analysis (default)
**Permissions**:
- Read all CONTEXT files
- Create/modify documentation files
**Execute**:
1. Read and analyze CONTEXT files
2. Identify patterns and issues
3. Generate insights and recommendations
4. Create documentation if needed
5. Output structured analysis
**Constraint**: Do NOT modify source code files
### MODE: write
**Permissions**:
- Full file operations
- Create/modify any files
**Execute**:
1. Read CONTEXT files
2. Perform requested file operations
3. Create/modify files as specified
4. Validate changes
5. Report file changes
## Output Format
### Standard Analysis Structure
```markdown
# Analysis: [TASK Title]
## Summary
[2-3 sentence overview]
## Key Findings
1. [Finding] - path/to/file:123
2. [Finding] - path/to/file:456
## Detailed Analysis
[Evidence-based analysis with code quotes]
## Recommendations
1. [Actionable recommendation]
2. [Actionable recommendation]
```
### Code References
Always use format: `path/to/file:line_number`
Example: "Authentication logic at `src/auth/jwt.ts:45` uses deprecated algorithm"
## RULES Processing
- **Parse the RULES field** to identify template content and additional constraints
- **Recognize `|` as separator** between template and additional constraints
- **ALWAYS apply all template guidelines** provided in the prompt
- **ALWAYS apply all additional constraints** specified after `|`
- **Treat all rules as mandatory** - both template and constraints must be followed
- **Failure to follow any rule** constitutes task failure
## Error Handling
**File Not Found**:
- Report missing files
- Continue with available files
- Note in output
**Invalid CONTEXT Pattern**:
- Report invalid pattern
- Request correction
- Do not guess
## Quality Standards
### Thoroughness
- Analyze ALL files in CONTEXT
- Check cross-file patterns
- Identify edge cases
- Quantify when possible
### Evidence-Based
- Quote relevant code
- Provide file:line references
- Link related patterns
### Actionable
- Clear recommendations
- Prioritized by impact
- Specific, not vague
## Philosophy
- **Incremental over big bangs** - Suggest small, testable changes
- **Learn from existing code** - Reference project patterns
- **Pragmatic over dogmatic** - Adapt to project reality
- **Clear over clever** - Prefer obvious solutions
- **Simple over complex** - Avoid over-engineering

View File

@@ -5,6 +5,417 @@ 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.4.2] - 2025-10-05
### 📚 CLI Documentation Refactoring
This release focuses on eliminating redundant documentation by establishing a single source of truth (SSOT) pattern for CLI command references.
#### Changed
**CLI Command Documentation Refactoring**:
- Refactored 7 CLI command documentation files to eliminate redundancy
- Removed **681 total lines** of duplicate content across all files
- Established implicit reference pattern to `intelligent-tools-strategy.md` (loaded in memory)
- Preserved all unique command-specific content and capabilities
**Specific File Reductions**:
- `analyze.md`: 117→61 lines (48% reduction)
- `chat.md`: 118→62 lines (47% reduction)
- `execute.md`: 180→100 lines (44% reduction)
- `codex-execute.md`: 481→473 lines (2% - preserved unique workflow content)
- `mode/bug-index.md`: 144→75 lines (48% reduction)
- `mode/code-analysis.md`: 188→76 lines (60% reduction)
- `mode/plan.md`: 100→76 lines (24% reduction)
**Removed Duplicate Sections**:
- Universal Command Template (now only in `intelligent-tools-strategy.md`)
- File Pattern Reference (centralized in strategy guide)
- Complex Pattern Discovery (centralized in strategy guide)
- MODE Field Definition (centralized in strategy guide)
- Enhancement Integration details (referenced implicitly)
- Session Persistence details (referenced implicitly)
**Preserved Unique Content**:
- Command-specific purpose and parameters
- Unique execution flows and capabilities
- Specialized features (YOLO permissions, task decomposition, resume patterns)
- Command-specific examples and workflows
- File pattern auto-detection logic for analyze command
- Group-based execution workflow for codex-execute command
#### Added
**Documentation Enhancement** (prior to refactoring):
- Enhanced file pattern examples and complex pattern discovery documentation
- Added semantic discovery workflow integration examples
#### Technical Details
**Single Source of Truth Pattern**:
All CLI commands now reference `intelligent-tools-strategy.md` for:
- Universal command template structure
- File pattern syntax and examples
- Complex pattern discovery workflows
- MODE field definitions and permissions
- Tool-specific features and capabilities
**Reference Pattern**:
```markdown
## Notes
- Command templates and file patterns: see intelligent-tools-strategy.md (loaded in memory)
```
This approach reduces maintenance overhead while ensuring documentation consistency across all CLI commands.
## [3.4.1] - 2025-10-04
### 🎯 Multi-Tool Support for Documentation Updates
This release adds flexible tool selection for CLAUDE.md documentation generation, allowing users to choose between Gemini, Qwen, or Codex based on their analysis needs.
#### Added
**Multi-Tool Support**:
- **`/update-memory-full --tool <gemini|qwen|codex>`**: Choose tool for full project documentation update
- **`/update-memory-related --tool <gemini|qwen|codex>`**: Choose tool for context-aware documentation update
- **Default**: Gemini (documentation generation, pattern recognition)
- **Qwen**: Architecture analysis, system design documentation
- **Codex**: Implementation validation, code quality analysis
**Script Enhancement** (`update_module_claude.sh`):
- Added third parameter for tool selection: `<module_path> [update_type] [tool]`
- Support for three tools with consistent parameter syntax:
- `gemini --all-files --yolo -p` (default)
- `qwen --all-files --yolo -p` (direct command, no wrapper)
- `codex --full-auto exec` (with danger-full-access)
- Automatic tool routing via case statement
- Improved logging with tool information display
#### Changed
**Command Documentation**:
- Updated `/update-memory-full.md` with tool selection usage and examples
- Updated `/update-memory-related.md` with tool selection usage and examples
- Added tool selection strategy and rationale documentation
#### Technical Details
**Tool Execution Patterns**:
```bash
# Gemini (default)
gemini --all-files --yolo -p "$prompt"
# Qwen (architecture analysis)
qwen --all-files --yolo -p "$prompt"
# Codex (implementation validation)
codex --full-auto exec "$prompt" --skip-git-repo-check -s danger-full-access
```
**Backward Compatibility**:
- ✅ Existing commands without `--tool` parameter default to Gemini
- ✅ All three tools support Layer 1-4 template system
- ✅ No breaking changes to existing workflows
## [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
This release simplifies the agent architecture and introduces an automated test-fix workflow based on the principle "Tests Are the Review".
#### Added
**New Agent: test-fix-agent**:
- **Purpose**: Execute tests, diagnose failures, and fix code until all tests pass
- **Philosophy**: When all tests pass, code is automatically approved (no separate review needed)
- **Responsibilities**:
- Execute complete test suite for implemented modules
- Parse test output and identify failures
- Diagnose root cause of test failures
- Modify source code to fix issues
- Re-run tests to verify fixes
- Certify code approval when all tests pass
**Enhanced test-gen Command**:
- Transforms from planning tool to workflow orchestrator
- Auto-generates TEST-FIX tasks for test-fix-agent
- Automatically executes test validation via `/workflow:execute`
- Eliminates manual planning document generation
**New Task Types**:
- `test-gen`: Test generation tasks (handled by @code-developer)
- `test-fix`: Test execution and fixing tasks (handled by @test-fix-agent)
#### Changed
**Agent Architecture Simplification**:
- **Removed**: `@code-review-agent` and `@code-review-test-agent`
- Testing now serves as the quality gate
- Passing tests = approved code
- **Enhanced**: `@code-developer` now writes implementation + tests together
- Unified generative work (code + tests)
- Maintains context continuity
- **Added**: `@general-purpose` for optional manual reviews
- Used only when explicitly requested
- Handles special cases and edge scenarios
**Task Type Updates**:
- `"test"` → `"test-gen"` (clearer distinction from test-fix)
- Agent mapping updated across all commands:
- `feature|bugfix|refactor|test-gen` → `@code-developer`
- `test-fix` → `@test-fix-agent`
- `review` → `@general-purpose` (optional)
**Workflow Changes**:
```
Old: code-developer → test-agent → code-review-agent
New: code-developer (code+tests) → test-fix-agent (execute+fix) → ✅ approved
```
#### Removed
- `@code-review-agent` - Testing serves as quality gate
- `@code-review-test-agent` - Functionality split between code-developer and test-fix-agent
- Separate review step - Tests passing = code approved
---
## [3.1.0] - 2025-10-02
### 🧪 TDD Workflow Support

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,13 @@ param(
[switch]$BackupAll,
[switch]$NoBackup
[switch]$NoBackup,
[string]$SourceVersion = "",
[string]$SourceBranch = "",
[string]$SourceCommit = ""
)
# Set encoding for proper Unicode support
@@ -74,7 +80,10 @@ if ($PSVersionTable.PSVersion.Major -ge 6) {
# Script metadata
$ScriptName = "Claude Code Workflow System Installer"
$Version = "2.1.0"
$ScriptVersion = "2.2.0" # Installer script version
# Default version (will be overridden by -SourceVersion from install-remote.ps1)
$DefaultVersion = "unknown"
# Initialize backup behavior - backup is enabled by default unless NoBackup is specified
if (-not $BackupAll -and -not $NoBackup) {
@@ -137,8 +146,15 @@ function Show-Banner {
}
function Show-Header {
param(
[string]$InstallVersion = $DefaultVersion
)
Show-Banner
Write-ColorOutput " $ScriptName v$Version" $ColorInfo
Write-ColorOutput " $ScriptName v$ScriptVersion" $ColorInfo
if ($InstallVersion -ne "unknown") {
Write-ColorOutput " Installing Claude Code Workflow v$InstallVersion" $ColorInfo
}
Write-ColorOutput " Unified workflow system with comprehensive coordination" $ColorInfo
Write-ColorOutput "========================================================================" $ColorInfo
if ($NoBackup) {
@@ -156,22 +172,40 @@ function Test-Prerequisites {
Write-ColorOutput "Current version: $($PSVersionTable.PSVersion)" $ColorError
return $false
}
# Test source files exist
$sourceDir = $PSScriptRoot
$claudeDir = Join-Path $sourceDir ".claude"
$claudeMd = Join-Path $sourceDir "CLAUDE.md"
$codexDir = Join-Path $sourceDir ".codex"
$geminiDir = Join-Path $sourceDir ".gemini"
$qwenDir = Join-Path $sourceDir ".qwen"
if (-not (Test-Path $claudeDir)) {
Write-ColorOutput "ERROR: .claude directory not found in $sourceDir" $ColorError
return $false
}
if (-not (Test-Path $claudeMd)) {
Write-ColorOutput "ERROR: CLAUDE.md file not found in $sourceDir" $ColorError
return $false
}
if (-not (Test-Path $codexDir)) {
Write-ColorOutput "ERROR: .codex directory not found in $sourceDir" $ColorError
return $false
}
if (-not (Test-Path $geminiDir)) {
Write-ColorOutput "ERROR: .gemini directory not found in $sourceDir" $ColorError
return $false
}
if (-not (Test-Path $qwenDir)) {
Write-ColorOutput "ERROR: .qwen directory not found in $sourceDir" $ColorError
return $false
}
Write-ColorOutput "Prerequisites check passed" $ColorSuccess
return $true
}
@@ -610,6 +644,40 @@ function Merge-DirectoryContents {
return $true
}
function Create-VersionJson {
param(
[string]$TargetClaudeDir,
[string]$InstallationMode
)
# Determine version from source parameter (passed from install-remote.ps1)
$versionNumber = if ($SourceVersion) { $SourceVersion } else { $DefaultVersion }
$sourceBranch = if ($SourceBranch) { $SourceBranch } else { "unknown" }
$commitSha = if ($SourceCommit) { $SourceCommit } else { "unknown" }
# Create version.json content
$versionInfo = @{
version = $versionNumber
commit_sha = $commitSha
installation_mode = $InstallationMode
installation_path = $TargetClaudeDir
installation_date_utc = (Get-Date).ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ssZ")
source_branch = $sourceBranch
installer_version = $ScriptVersion
}
$versionJsonPath = Join-Path $TargetClaudeDir "version.json"
try {
$versionInfo | ConvertTo-Json | Out-File -FilePath $versionJsonPath -Encoding utf8 -Force
Write-ColorOutput "Created version.json: $versionNumber ($commitSha) - $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
@@ -617,6 +685,9 @@ function Install-Global {
$userProfile = [Environment]::GetFolderPath("UserProfile")
$globalClaudeDir = Join-Path $userProfile ".claude"
$globalClaudeMd = Join-Path $globalClaudeDir "CLAUDE.md"
$globalCodexDir = Join-Path $userProfile ".codex"
$globalGeminiDir = Join-Path $userProfile ".gemini"
$globalQwenDir = Join-Path $userProfile ".qwen"
Write-ColorOutput "Global installation path: $userProfile" $ColorInfo
@@ -624,12 +695,27 @@ function Install-Global {
$sourceDir = $PSScriptRoot
$sourceClaudeDir = Join-Path $sourceDir ".claude"
$sourceClaudeMd = Join-Path $sourceDir "CLAUDE.md"
$sourceCodexDir = Join-Path $sourceDir ".codex"
$sourceGeminiDir = Join-Path $sourceDir ".gemini"
$sourceQwenDir = Join-Path $sourceDir ".qwen"
# Create backup folder if needed (default behavior unless NoBackup is specified)
$backupFolder = $null
if (-not $NoBackup) {
if (Test-Path $globalClaudeDir) {
$existingFiles = Get-ChildItem $globalClaudeDir -Recurse -File -ErrorAction SilentlyContinue
if ((Test-Path $globalClaudeDir) -or (Test-Path $globalCodexDir) -or (Test-Path $globalGeminiDir) -or (Test-Path $globalQwenDir)) {
$existingFiles = @()
if (Test-Path $globalClaudeDir) {
$existingFiles += Get-ChildItem $globalClaudeDir -Recurse -File -ErrorAction SilentlyContinue
}
if (Test-Path $globalCodexDir) {
$existingFiles += Get-ChildItem $globalCodexDir -Recurse -File -ErrorAction SilentlyContinue
}
if (Test-Path $globalGeminiDir) {
$existingFiles += Get-ChildItem $globalGeminiDir -Recurse -File -ErrorAction SilentlyContinue
}
if (Test-Path $globalQwenDir) {
$existingFiles += Get-ChildItem $globalQwenDir -Recurse -File -ErrorAction SilentlyContinue
}
if (($existingFiles -and ($existingFiles | Measure-Object).Count -gt 0)) {
$backupFolder = Get-BackupDirectory -TargetDirectory $userProfile
Write-ColorOutput "Backup folder created: $backupFolder" $ColorInfo
@@ -649,6 +735,22 @@ function Install-Global {
Write-ColorOutput "Installing CLAUDE.md to global .claude directory..." $ColorInfo
$claudeMdInstalled = Copy-FileToDestination -Source $sourceClaudeMd -Destination $globalClaudeMd -Description "CLAUDE.md" -BackupFolder $backupFolder
# Merge .codex directory contents
Write-ColorOutput "Merging .codex directory contents..." $ColorInfo
$codexMerged = Merge-DirectoryContents -Source $sourceCodexDir -Destination $globalCodexDir -Description ".codex directory contents" -BackupFolder $backupFolder
# Merge .gemini directory contents
Write-ColorOutput "Merging .gemini directory contents..." $ColorInfo
$geminiMerged = Merge-DirectoryContents -Source $sourceGeminiDir -Destination $globalGeminiDir -Description ".gemini directory contents" -BackupFolder $backupFolder
# Merge .qwen directory contents
Write-ColorOutput "Merging .qwen directory contents..." $ColorInfo
$qwenMerged = Merge-DirectoryContents -Source $sourceQwenDir -Destination $globalQwenDir -Description ".qwen 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) {
@@ -679,14 +781,20 @@ function Install-Path {
$sourceDir = $PSScriptRoot
$sourceClaudeDir = Join-Path $sourceDir ".claude"
$sourceClaudeMd = Join-Path $sourceDir "CLAUDE.md"
$sourceCodexDir = Join-Path $sourceDir ".codex"
$sourceGeminiDir = Join-Path $sourceDir ".gemini"
$sourceQwenDir = Join-Path $sourceDir ".qwen"
# Local paths - only for agents, commands, output-styles
# Local paths - for agents, commands, output-styles, .codex, .gemini, .qwen
$localClaudeDir = Join-Path $TargetDirectory ".claude"
$localCodexDir = Join-Path $TargetDirectory ".codex"
$localGeminiDir = Join-Path $TargetDirectory ".gemini"
$localQwenDir = Join-Path $TargetDirectory ".qwen"
# Create backup folder if needed
$backupFolder = $null
if (-not $NoBackup) {
if ((Test-Path $localClaudeDir) -or (Test-Path $globalClaudeDir)) {
if ((Test-Path $localClaudeDir) -or (Test-Path $localCodexDir) -or (Test-Path $localGeminiDir) -or (Test-Path $localQwenDir) -or (Test-Path $globalClaudeDir)) {
$backupFolder = Get-BackupDirectory -TargetDirectory $TargetDirectory
Write-ColorOutput "Backup folder created: $backupFolder" $ColorInfo
}
@@ -774,6 +882,26 @@ function Install-Path {
Write-ColorOutput "Installing CLAUDE.md to global .claude directory..." $ColorInfo
Copy-FileToDestination -Source $sourceClaudeMd -Destination $globalClaudeMd -Description "CLAUDE.md" -BackupFolder $backupFolder
# Merge .codex directory contents to local location
Write-ColorOutput "Merging .codex directory contents to local location..." $ColorInfo
$codexMerged = Merge-DirectoryContents -Source $sourceCodexDir -Destination $localCodexDir -Description ".codex directory contents" -BackupFolder $backupFolder
# Merge .gemini directory contents to local location
Write-ColorOutput "Merging .gemini directory contents to local location..." $ColorInfo
$geminiMerged = Merge-DirectoryContents -Source $sourceGeminiDir -Destination $localGeminiDir -Description ".gemini directory contents" -BackupFolder $backupFolder
# Merge .qwen directory contents to local location
Write-ColorOutput "Merging .qwen directory contents to local location..." $ColorInfo
$qwenMerged = Merge-DirectoryContents -Source $sourceQwenDir -Destination $localQwenDir -Description ".qwen 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) {
@@ -879,10 +1007,11 @@ function Show-Summary {
if ($Mode -eq "Path") {
Write-Host " Local Path: $Path"
Write-Host " Global Path: $([Environment]::GetFolderPath('UserProfile'))"
Write-Host " Local Components: agents, commands, output-styles"
Write-Host " Local Components: agents, commands, output-styles, .codex, .gemini, .qwen"
Write-Host " Global Components: workflows, scripts, python_script, etc."
} else {
Write-Host " Path: $Path"
Write-Host " Global Components: .claude, .codex, .gemini, .qwen"
}
if ($NoBackup) {
@@ -896,10 +1025,13 @@ function Show-Summary {
Write-Host ""
Write-ColorOutput "Next steps:" $ColorInfo
Write-Host "1. Review CLAUDE.md - Customize guidelines for your project"
Write-Host "2. Configure settings - Edit .claude/settings.local.json as needed"
Write-Host "3. Start using Claude Code with Agent workflow coordination!"
Write-Host "4. Use /workflow commands for task execution"
Write-Host "5. Use /update-memory commands for memory system management"
Write-Host "2. Review .codex/Agent.md - Codex agent execution protocol"
Write-Host "3. Review .gemini/CLAUDE.md - Gemini agent execution protocol"
Write-Host "4. Review .qwen/QWEN.md - Qwen agent execution protocol"
Write-Host "5. Configure settings - Edit .claude/settings.local.json as needed"
Write-Host "6. Start using Claude Code with Agent workflow coordination!"
Write-Host "7. Use /workflow commands for task execution"
Write-Host "8. Use /update-memory commands for memory system management"
Write-Host ""
Write-ColorOutput "Documentation: https://github.com/catlog22/Claude-CCW" $ColorInfo
@@ -907,7 +1039,10 @@ function Show-Summary {
}
function Main {
Show-Header
# Use SourceVersion parameter if provided, otherwise use default
$installVersion = if ($SourceVersion) { $SourceVersion } else { $DefaultVersion }
Show-Header -InstallVersion $installVersion
# Test prerequisites
Write-ColorOutput "Checking system requirements..." $ColorInfo

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
@@ -97,6 +97,8 @@ function test_prerequisites() {
local script_dir="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
local claude_dir="$script_dir/.claude"
local claude_md="$script_dir/CLAUDE.md"
local codex_dir="$script_dir/.codex"
local gemini_dir="$script_dir/.gemini"
if [ ! -d "$claude_dir" ]; then
write_color "ERROR: .claude directory not found in $script_dir" "$COLOR_ERROR"
@@ -108,6 +110,16 @@ function test_prerequisites() {
return 1
fi
if [ ! -d "$codex_dir" ]; then
write_color "ERROR: .codex directory not found in $script_dir" "$COLOR_ERROR"
return 1
fi
if [ ! -d "$gemini_dir" ]; then
write_color "ERROR: .gemini directory not found in $script_dir" "$COLOR_ERROR"
return 1
fi
write_color "✓ Prerequisites check passed" "$COLOR_SUCCESS"
return 0
}
@@ -389,6 +401,8 @@ function install_global() {
local user_home="$HOME"
local global_claude_dir="${user_home}/.claude"
local global_claude_md="${global_claude_dir}/CLAUDE.md"
local global_codex_dir="${user_home}/.codex"
local global_gemini_dir="${user_home}/.gemini"
write_color "Global installation path: $user_home" "$COLOR_INFO"
@@ -396,14 +410,25 @@ function install_global() {
local script_dir="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
local source_claude_dir="${script_dir}/.claude"
local source_claude_md="${script_dir}/CLAUDE.md"
local source_codex_dir="${script_dir}/.codex"
local source_gemini_dir="${script_dir}/.gemini"
# Create backup folder if needed
local backup_folder=""
if [ "$NO_BACKUP" = false ]; then
local has_existing_files=false
if [ -d "$global_claude_dir" ] && [ "$(ls -A "$global_claude_dir" 2>/dev/null)" ]; then
backup_folder=$(get_backup_directory "$user_home")
write_color "Backup folder created: $backup_folder" "$COLOR_INFO"
has_existing_files=true
elif [ -d "$global_codex_dir" ] && [ "$(ls -A "$global_codex_dir" 2>/dev/null)" ]; then
has_existing_files=true
elif [ -d "$global_gemini_dir" ] && [ "$(ls -A "$global_gemini_dir" 2>/dev/null)" ]; then
has_existing_files=true
elif [ -f "$global_claude_md" ]; then
has_existing_files=true
fi
if [ "$has_existing_files" = true ]; then
backup_folder=$(get_backup_directory "$user_home")
write_color "Backup folder created: $backup_folder" "$COLOR_INFO"
fi
@@ -417,6 +442,14 @@ function install_global() {
write_color "Installing CLAUDE.md to global .claude directory..." "$COLOR_INFO"
copy_file_to_destination "$source_claude_md" "$global_claude_md" "CLAUDE.md" "$backup_folder"
# Merge .codex directory contents
write_color "Merging .codex directory contents..." "$COLOR_INFO"
merge_directory_contents "$source_codex_dir" "$global_codex_dir" ".codex directory contents" "$backup_folder"
# Merge .gemini directory contents
write_color "Merging .gemini directory contents..." "$COLOR_INFO"
merge_directory_contents "$source_gemini_dir" "$global_gemini_dir" ".gemini directory contents" "$backup_folder"
# Remove empty backup folder
if [ -n "$backup_folder" ] && [ -d "$backup_folder" ]; then
if [ -z "$(ls -A "$backup_folder" 2>/dev/null)" ]; then
@@ -442,14 +475,18 @@ function install_path() {
local script_dir="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
local source_claude_dir="${script_dir}/.claude"
local source_claude_md="${script_dir}/CLAUDE.md"
local source_codex_dir="${script_dir}/.codex"
local source_gemini_dir="${script_dir}/.gemini"
# Local paths
local local_claude_dir="${target_dir}/.claude"
local local_codex_dir="${target_dir}/.codex"
local local_gemini_dir="${target_dir}/.gemini"
# Create backup folder if needed
local backup_folder=""
if [ "$NO_BACKUP" = false ]; then
if [ -d "$local_claude_dir" ] || [ -d "$global_claude_dir" ]; then
if [ -d "$local_claude_dir" ] || [ -d "$local_codex_dir" ] || [ -d "$local_gemini_dir" ] || [ -d "$global_claude_dir" ]; then
backup_folder=$(get_backup_directory "$target_dir")
write_color "Backup folder created: $backup_folder" "$COLOR_INFO"
fi
@@ -530,6 +567,14 @@ function install_path() {
write_color "Installing CLAUDE.md to global .claude directory..." "$COLOR_INFO"
copy_file_to_destination "$source_claude_md" "$global_claude_md" "CLAUDE.md" "$backup_folder"
# Merge .codex directory contents to local location
write_color "Merging .codex directory contents to local location..." "$COLOR_INFO"
merge_directory_contents "$source_codex_dir" "$local_codex_dir" ".codex directory contents" "$backup_folder"
# Merge .gemini directory contents to local location
write_color "Merging .gemini directory contents to local location..." "$COLOR_INFO"
merge_directory_contents "$source_gemini_dir" "$local_gemini_dir" ".gemini directory contents" "$backup_folder"
# Remove empty backup folder
if [ -n "$backup_folder" ] && [ -d "$backup_folder" ]; then
if [ -z "$(ls -A "$backup_folder" 2>/dev/null)" ]; then
@@ -631,10 +676,11 @@ function show_summary() {
if [ "$mode" = "Path" ]; then
echo " Local Path: $path"
echo " Global Path: $HOME"
echo " Local Components: agents, commands, output-styles"
echo " Local Components: agents, commands, output-styles, .codex, .gemini"
echo " Global Components: workflows, scripts, python_script, etc."
else
echo " Path: $path"
echo " Global Components: .claude, .codex, .gemini"
fi
if [ "$NO_BACKUP" = true ]; then
@@ -648,10 +694,12 @@ function show_summary() {
echo ""
write_color "Next steps:" "$COLOR_INFO"
echo "1. Review CLAUDE.md - Customize guidelines for your project"
echo "2. Configure settings - Edit .claude/settings.local.json as needed"
echo "3. Start using Claude Code with Agent workflow coordination!"
echo "4. Use /workflow commands for task execution"
echo "5. Use /update-memory commands for memory system management"
echo "2. Review .codex/Agent.md - Codex agent execution protocol"
echo "3. Review .gemini/CLAUDE.md - Gemini agent execution protocol"
echo "4. Configure settings - Edit .claude/settings.local.json as needed"
echo "5. Start using Claude Code with Agent workflow coordination!"
echo "6. Use /workflow commands for task execution"
echo "7. Use /update-memory commands for memory system management"
echo ""
write_color "Documentation: https://github.com/catlog22/Claude-Code-Workflow" "$COLOR_INFO"

View File

@@ -1,6 +1,6 @@
# 🚀 Claude Code Workflow (CCW): 下一代多智能体软件开发自动化框架
[![Version](https://img.shields.io/badge/version-v2.1.0--experimental-blue.svg)](https://github.com/catlog22/Claude-Code-Workflow/releases)
[![Version](https://img.shields.io/badge/version-v3.2.1-blue.svg)](https://github.com/catlog22/Claude-Code-Workflow/releases)
[![MCP工具](https://img.shields.io/badge/🔧_MCP工具-实验性-orange.svg)](https://github.com/modelcontextprotocol)
[![License](https://img.shields.io/badge/license-MIT-green.svg)](LICENSE)

273
README.md
View File

@@ -2,7 +2,7 @@
<div align="center">
[![Version](https://img.shields.io/badge/version-v3.1.0-blue.svg)](https://github.com/catlog22/Claude-Code-Workflow/releases)
[![Version](https://img.shields.io/badge/version-v3.4.2-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,16 +15,22 @@
**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.1.0** - TDD Workflow Support with Red-Green-Refactor cycle enforcement. See [CHANGELOG.md](CHANGELOG.md) for details.
> **🎉 Latest: v3.4.2** - CLI documentation refactoring & single source of truth. See [CHANGELOG.md](CHANGELOG.md) for details.
>
> **v3.0.0**: Introduced **unified CLI command structure**. The `/cli:*` commands consolidate all tool interactions (Gemini, Qwen, Codex) using a `--tool` flag for selection.
> **What's New in v3.4.2**:
> - 📚 **CLI Documentation Refactoring**: Eliminated 681 lines of duplicate content across 7 command files
> - 🎯 **Single Source of Truth**: Established implicit reference pattern to `intelligent-tools-strategy.md`
> - 🔍 **Documentation Consistency**: All CLI commands now reference centralized strategy guide
> - 💡 **Maintenance Optimization**: Reduced maintenance overhead while preserving unique command features
> - ✨ **Enhanced Clarity**: Streamlined documentation focuses on command-specific capabilities
> - 📖 **Better Organization**: File patterns, templates, and MODE definitions centralized
---
## ✨ Key Features
- **🎯 Context-First Architecture**: Pre-defined context gathering eliminates execution uncertainty and error accumulation.
- **🤖 Multi-Agent System**: Specialized agents (`@code-developer`, `@code-review-test-agent`) with tech-stack awareness.
- **🤖 Multi-Agent System**: Specialized agents (`@code-developer`, `@test-fix-agent`) with tech-stack awareness and automated test validation.
- **🔄 End-to-End Workflow Automation**: From brainstorming to deployment with multi-phase orchestration.
- **📋 JSON-First Task Model**: Structured task definitions with `pre_analysis` steps for deterministic execution.
- **🧪 TDD Workflow Support**: Complete Test-Driven Development with Red-Green-Refactor cycle enforcement.
@@ -49,12 +55,185 @@ Invoke-Expression (Invoke-WebRequest -Uri "https://raw.githubusercontent.com/cat
bash <(curl -fsSL https://raw.githubusercontent.com/catlog22/Claude-Code-Workflow/main/install-remote.sh)
```
### **📋 Interactive Version Selection**
After running the installation command, you'll see an interactive menu with real-time version information:
```
Detecting latest release and commits...
Latest stable: v3.2.0 (2025-10-02 04:27 UTC)
Latest commit: cdea58f (2025-10-02 08:15 UTC)
====================================================
Version Selection Menu
====================================================
1) Latest Stable Release (Recommended)
|-- Version: v3.2.0
|-- Released: 2025-10-02 04:27 UTC
\-- Production-ready
2) Latest Development Version
|-- Branch: main
|-- Commit: cdea58f
|-- Updated: 2025-10-02 08:15 UTC
|-- Cutting-edge features
\-- May contain experimental changes
3) Specific Release Version
|-- Install a specific tagged release
\-- Recent: v3.2.0, v3.1.0, v3.0.1
====================================================
Select version to install (1-3, default: 1):
```
**Version Options:**
- **Option 1 (Recommended)**: Latest stable release with verified production quality
- **Option 2**: Latest development version from main branch with newest features
- **Option 3**: Specific version tag for controlled deployments
> 💡 **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
```
> **📝 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`)
> - **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
---
## 🚀 Getting Started
@@ -91,15 +270,12 @@ 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
# Final quality review
/workflow:review
```
### Quick Start for Simple Tasks
@@ -120,6 +296,22 @@ After installation, run the following command to ensure CCW is working:
/workflow:execute
```
> **💡 When to Use Which Approach?**
>
> **Use `/workflow:plan` + `/workflow:execute` for:**
> - Complex features requiring multiple modules (>3 modules)
> - Tasks with multiple subtasks (>5 subtasks)
> - Cross-cutting changes affecting architecture
> - Features requiring coordination between components
> - When you need structured planning and progress tracking
>
> **Use Claude Code directly for:**
> - Simple, focused changes (single file or module)
> - Quick bug fixes with clear solutions
> - Documentation updates
> - Code refactoring within one component
> - Straightforward feature additions
**Code Analysis:**
```bash
# Deep codebase analysis
@@ -150,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` | Initiate a quality assurance review of the completed work. |
| `/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**
@@ -164,57 +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
### **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.1.0-blue.svg)](https://github.com/catlog22/Claude-Code-Workflow/releases)
[![Version](https://img.shields.io/badge/version-v3.4.2-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,9 +15,15 @@
**Claude Code Workflow (CCW)** 是一个新一代的多智能体自动化开发框架,通过智能工作流管理和自主执行来协调复杂的软件开发任务。
> **🎉 最新版本: v3.1.0** - TDD 工作流支持,包含 Red-Green-Refactor 循环强制执行。详见 [CHANGELOG.md](CHANGELOG.md)。
> **🎉 最新版本: v3.4.2** - CLI 文档重构与单一信息源。详见 [CHANGELOG.md](CHANGELOG.md)。
>
> **v3.0.0 版本**: 引入了**统一的 CLI 命令结构**。`/cli:*` 命令通过 `--tool` 标志整合了所有工具Gemini, Qwen, Codex的交互。
> **v3.4.2 版本新特性**:
> - 📚 **CLI 文档重构**: 消除 7 个命令文件中的 681 行重复内容
> - 🎯 **单一信息源**: 建立对 `intelligent-tools-strategy.md` 的隐式引用模式
> - 🔍 **文档一致性**: 所有 CLI 命令现在引用集中的策略指南
> - 💡 **维护优化**: 降低维护开销,同时保留独特的命令功能
> - ✨ **增强清晰度**: 精简的文档专注于命令特定功能
> - 📖 **更好的组织**: 文件模式、模板和 MODE 定义集中化
---
@@ -49,12 +55,185 @@ Invoke-Expression (Invoke-WebRequest -Uri "https://raw.githubusercontent.com/cat
bash <(curl -fsSL https://raw.githubusercontent.com/catlog22/Claude-Code-Workflow/main/install-remote.sh)
```
### **📋 交互式版本选择**
运行安装命令后,您将看到包含实时版本信息的交互式菜单:
```
正在检测最新版本和提交...
最新稳定版: v3.2.0 (2025-10-02 04:27 UTC)
最新提交: cdea58f (2025-10-02 08:15 UTC)
====================================================
版本选择菜单
====================================================
1) 最新稳定版(推荐)
|-- 版本: v3.2.0
|-- 发布时间: 2025-10-02 04:27 UTC
\-- 生产就绪
2) 最新开发版
|-- 分支: main
|-- 提交: cdea58f
|-- 更新时间: 2025-10-02 08:15 UTC
|-- 最新功能
\-- 可能包含实验性更改
3) 指定版本
|-- 安装特定标签版本
\-- 最近版本: v3.2.0, v3.1.0, v3.0.1
====================================================
选择要安装的版本 (1-3, 默认: 1):
```
**版本选项:**
- **选项 1推荐**:经过验证的最新稳定版本,生产环境可用
- **选项 2**:来自 main 分支的最新开发版本,包含最新功能
- **选项 3**:指定版本标签,用于受控部署
> 💡 **提示**:安装程序会自动从 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 工具可用。如果没有安装,您可能会遇到:
- 代码分析和搜索操作速度较慢
- 某些场景下上下文质量降低
- 回退到效率较低的传统工具
- 高级工作流中可能出现意外行为
---
## 🚀 快速入门
@@ -91,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
```
### 简单任务快速入门
@@ -120,6 +296,22 @@ bash <(curl -fsSL https://raw.githubusercontent.com/catlog22/Claude-Code-Workflo
/workflow:execute
```
> **💡 何时使用哪种方式?**
>
> **使用 `/workflow:plan` + `/workflow:execute` 适用于:**
> - 需要多个模块的复杂功能(>3 个模块)
> - 包含多个子任务的任务(>5 个子任务)
> - 影响架构的横切变更
> - 需要组件间协调的功能
> - 需要结构化规划和进度跟踪时
>
> **直接使用 Claude Code 适用于:**
> - 简单、聚焦的变更(单个文件或模块)
> - 解决方案明确的快速 bug 修复
> - 文档更新
> - 单个组件内的代码重构
> - 简单直接的功能添加
**代码分析:**
```bash
# 深度代码库分析
@@ -150,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:review` | **可选** 手动审查(仅在明确需要时使用,测试通过即代表代码已批准)。 |
| `/workflow:tools:test-context-gather` | 分析测试覆盖率,识别缺失的测试文件。 |
| `/workflow:tools:test-concept-enhanced` | 使用 Gemini 生成测试策略和需求分析。 |
| `/workflow:tools:test-task-generate` | 生成测试任务 JSON包含 test-fix-cycle 规范。 |
### **任务与内存命令**
@@ -164,57 +359,7 @@ bash <(curl -fsSL https://raw.githubusercontent.com/catlog22/Claude-Code-Workflo
| `/task:*` | 管理单个任务(`create`, `breakdown`, `execute`, `replan`)。 |
| `/update-memory-full` | 重新索引整个项目文档。 |
| `/update-memory-related` | 更新与最近更改相关的文档。 |
---
## ⚙️ 配置
### **必需: 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)

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

@@ -1,16 +1,88 @@
#!/usr/bin/env pwsh
# Claude Code Workflow (CCW) - Remote Installation Script
# One-liner remote installation for Claude Code Workflow system
<#
.SYNOPSIS
Claude Code Workflow (CCW) - Remote Installation Script
.DESCRIPTION
One-liner remote installation for Claude Code Workflow system.
Downloads and installs CCW from GitHub with flexible version selection.
.PARAMETER Version
Installation version type:
- "stable" (default): Latest stable release tag
- "latest": Latest main branch (development version)
- "branch": Install from specific branch
.PARAMETER Tag
Specific release tag to install (e.g., "v3.2.0")
Only used when Version is "stable"
.PARAMETER Branch
Branch name to install from (default: "main")
Only used when Version is "branch"
.PARAMETER Global
Install to global user directory (~/.claude)
.PARAMETER Directory
Install to custom directory
.PARAMETER Force
Skip confirmation prompts
.PARAMETER NoBackup
Skip backup of existing installation
.PARAMETER NonInteractive
Run in non-interactive mode
.PARAMETER BackupAll
Backup all files including git-ignored files
.EXAMPLE
# Install latest stable release (recommended)
.\install-remote.ps1
.EXAMPLE
# Install specific stable version
.\install-remote.ps1 -Version stable -Tag "v3.2.0"
.EXAMPLE
# Install latest development version
.\install-remote.ps1 -Version latest
.EXAMPLE
# Install from specific branch
.\install-remote.ps1 -Version branch -Branch "feature/new-feature"
.EXAMPLE
# Install to global directory without prompts
.\install-remote.ps1 -Global -Force
.LINK
https://github.com/catlog22/Claude-Code-Workflow
#>
[CmdletBinding()]
param(
[ValidateSet("stable", "latest", "branch")]
[string]$Version = "stable",
[string]$Tag = "",
[string]$Branch = "main",
[switch]$Global,
[string]$Directory = "",
[switch]$Force,
[switch]$NoBackup,
[switch]$NonInteractive,
[switch]$BackupAll,
[string]$Branch = "main"
[switch]$BackupAll
)
# Set encoding for proper Unicode support
@@ -26,7 +98,7 @@ if ($PSVersionTable.PSVersion.Major -ge 6) {
# Script metadata
$ScriptName = "Claude Code Workflow (CCW) Remote Installer"
$Version = "2.1.1"
$InstallerVersion = "2.2.0"
# Colors for output
$ColorSuccess = "Green"
@@ -43,7 +115,7 @@ function Write-ColorOutput {
}
function Show-Header {
Write-ColorOutput "==== $ScriptName v$Version ====" $ColorInfo
Write-ColorOutput "==== $ScriptName v$InstallerVersion ====" $ColorInfo
Write-ColorOutput "========================================================" $ColorInfo
Write-Host ""
}
@@ -78,29 +150,70 @@ function Get-TempDirectory {
return $tempDir
}
function Get-LatestRelease {
try {
$apiUrl = "https://api.github.com/repos/catlog22/Claude-Code-Workflow/releases/latest"
$response = Invoke-RestMethod -Uri $apiUrl -UseBasicParsing
return $response.tag_name
} catch {
Write-ColorOutput "WARNING: Failed to fetch latest release, using 'main' branch" $ColorWarning
return $null
}
}
function Download-Repository {
param(
[string]$TempDir,
[string]$Branch = "main"
[string]$Version = "stable",
[string]$Branch = "main",
[string]$Tag = ""
)
$repoUrl = "https://github.com/catlog22/Claude-Code-Workflow"
$zipUrl = "$repoUrl/archive/refs/heads/$Branch.zip"
# Determine download URL based on version type
if ($Version -eq "stable") {
# Download latest stable release
if ([string]::IsNullOrEmpty($Tag)) {
$latestTag = Get-LatestRelease
if ($latestTag) {
$Tag = $latestTag
} else {
# Fallback to main branch if API fails
$zipUrl = "$repoUrl/archive/refs/heads/main.zip"
$downloadType = "main branch (fallback)"
}
}
if (-not [string]::IsNullOrEmpty($Tag)) {
$zipUrl = "$repoUrl/archive/refs/tags/$Tag.zip"
$downloadType = "stable release $Tag"
}
} elseif ($Version -eq "latest") {
# Download latest main branch
$zipUrl = "$repoUrl/archive/refs/heads/main.zip"
$downloadType = "latest main branch"
} else {
# Download specific branch
$zipUrl = "$repoUrl/archive/refs/heads/$Branch.zip"
$downloadType = "branch $Branch"
}
$zipPath = Join-Path $TempDir "repo.zip"
Write-ColorOutput "Downloading from GitHub..." $ColorInfo
Write-ColorOutput "Source: $repoUrl" $ColorInfo
Write-ColorOutput "Branch: $Branch" $ColorInfo
Write-ColorOutput "Type: $downloadType" $ColorInfo
try {
# Download with progress
$progressPreference = $ProgressPreference
$ProgressPreference = 'SilentlyContinue'
Invoke-WebRequest -Uri $zipUrl -OutFile $zipPath -UseBasicParsing
$ProgressPreference = $progressPreference
if (Test-Path $zipPath) {
$fileSize = (Get-Item $zipPath).Length
Write-ColorOutput "Download complete ($([math]::Round($fileSize/1024/1024, 2)) MB)" $ColorSuccess
@@ -145,23 +258,26 @@ function Extract-Repository {
function Invoke-LocalInstaller {
param(
[string]$RepoDir
[string]$RepoDir,
[string]$VersionInfo = "",
[string]$BranchInfo = "",
[string]$CommitSha = ""
)
$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
}
@@ -169,11 +285,16 @@ function Invoke-LocalInstaller {
if ($NoBackup) { $params["NoBackup"] = $NoBackup }
if ($NonInteractive) { $params["NonInteractive"] = $NonInteractive }
if ($BackupAll) { $params["BackupAll"] = $BackupAll }
# Pass version, branch, and commit information
if ($VersionInfo) { $params["SourceVersion"] = $VersionInfo }
if ($BranchInfo) { $params["SourceBranch"] = $BranchInfo }
if ($CommitSha) { $params["SourceCommit"] = $CommitSha }
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
@@ -182,7 +303,7 @@ function Invoke-LocalInstaller {
Write-ColorOutput "Executing: & `"$installerPath`"" $ColorInfo
& $installerPath
}
Pop-Location
return $true
} catch {
@@ -225,29 +346,200 @@ function Wait-ForUserConfirmation {
}
}
function Show-VersionMenu {
param(
[string]$LatestStableVersion = "Detecting...",
[string]$LatestStableDate = "",
[string]$LatestCommitId = "",
[string]$LatestCommitDate = ""
)
Write-Host ""
Write-ColorOutput "====================================================" $ColorInfo
Write-ColorOutput " Version Selection Menu" $ColorInfo
Write-ColorOutput "====================================================" $ColorInfo
Write-Host ""
# Option 1: Latest Stable
Write-ColorOutput "1) Latest Stable Release (Recommended)" $ColorSuccess
if ($LatestStableVersion -ne "Detecting..." -and $LatestStableVersion -ne "Unknown") {
Write-Host " |-- Version: $LatestStableVersion"
if ($LatestStableDate) {
Write-Host " |-- Released: $LatestStableDate"
}
Write-Host " \-- Production-ready"
} else {
Write-Host " |-- Version: Auto-detected from GitHub"
Write-Host " \-- Production-ready"
}
Write-Host ""
# Option 2: Latest Development
Write-ColorOutput "2) Latest Development Version" $ColorWarning
Write-Host " |-- Branch: main"
if ($LatestCommitId -and $LatestCommitDate) {
Write-Host " |-- Commit: $LatestCommitId"
Write-Host " |-- Updated: $LatestCommitDate"
}
Write-Host " |-- Cutting-edge features"
Write-Host " \-- May contain experimental changes"
Write-Host ""
# Option 3: Specific Version
Write-ColorOutput "3) Specific Release Version" $ColorInfo
Write-Host " |-- Install a specific tagged release"
Write-Host " \-- Recent: v3.2.0, v3.1.0, v3.0.1"
Write-Host ""
Write-ColorOutput "====================================================" $ColorInfo
Write-Host ""
}
function Get-UserVersionChoice {
if ($NonInteractive -or $Force) {
# Non-interactive mode: use default stable version
return @{
Type = "stable"
Tag = $Tag
Branch = $Branch
}
}
# Detect latest stable version and commit info
Write-ColorOutput "Detecting latest release and commits..." $ColorInfo
$latestVersion = "Unknown"
$latestStableDate = ""
$latestCommitId = ""
$latestCommitDate = ""
try {
# Get latest release info
$apiUrl = "https://api.github.com/repos/catlog22/Claude-Code-Workflow/releases/latest"
$response = Invoke-RestMethod -Uri $apiUrl -UseBasicParsing -TimeoutSec 5
$latestVersion = $response.tag_name
# Parse and format release date to local time
if ($response.published_at) {
$publishDate = [DateTime]::Parse($response.published_at).ToLocalTime()
$latestStableDate = $publishDate.ToString("yyyy-MM-dd HH:mm")
}
Write-ColorOutput "Latest stable: $latestVersion ($latestStableDate)" $ColorSuccess
} catch {
Write-ColorOutput "Could not detect latest release" $ColorWarning
}
try {
# Get latest commit info from main branch
$commitUrl = "https://api.github.com/repos/catlog22/Claude-Code-Workflow/commits/main"
$commitResponse = Invoke-RestMethod -Uri $commitUrl -UseBasicParsing -TimeoutSec 5
$latestCommitId = $commitResponse.sha.Substring(0, 7)
# Parse and format commit date to local time
if ($commitResponse.commit.committer.date) {
$commitDate = [DateTime]::Parse($commitResponse.commit.committer.date).ToLocalTime()
$latestCommitDate = $commitDate.ToString("yyyy-MM-dd HH:mm")
}
Write-ColorOutput "Latest commit: $latestCommitId ($latestCommitDate)" $ColorSuccess
} catch {
Write-ColorOutput "Could not detect latest commit" $ColorWarning
}
Show-VersionMenu -LatestStableVersion $latestVersion -LatestStableDate $latestStableDate -LatestCommitId $latestCommitId -LatestCommitDate $latestCommitDate
$choice = Read-Host "Select version to install (1-3, default: 1)"
switch ($choice) {
"2" {
Write-Host ""
Write-ColorOutput "✓ Selected: Latest Development Version (main branch)" $ColorSuccess
return @{
Type = "latest"
Tag = ""
Branch = "main"
}
}
"3" {
Write-Host ""
Write-ColorOutput "Available recent releases:" $ColorInfo
Write-Host " v3.2.0, v3.1.0, v3.0.1, v3.0.0"
Write-Host ""
$tagInput = Read-Host "Enter version tag (e.g., v3.2.0)"
if ([string]::IsNullOrWhiteSpace($tagInput)) {
Write-ColorOutput "No tag specified, using latest stable" $ColorWarning
return @{
Type = "stable"
Tag = ""
Branch = "main"
}
}
Write-ColorOutput "✓ Selected: Specific Version $tagInput" $ColorSuccess
return @{
Type = "stable"
Tag = $tagInput
Branch = "main"
}
}
default {
Write-Host ""
if ($latestVersion -ne "Unknown") {
Write-ColorOutput "✓ Selected: Latest Stable Release ($latestVersion)" $ColorSuccess
} else {
Write-ColorOutput "✓ Selected: Latest Stable Release (auto-detect)" $ColorSuccess
}
return @{
Type = "stable"
Tag = ""
Branch = "main"
}
}
}
}
function Main {
Show-Header
Write-ColorOutput "This will download and install Claude Code Workflow System from GitHub." $ColorInfo
Write-Host ""
# Test prerequisites
Write-ColorOutput "Checking system requirements..." $ColorInfo
if (-not (Test-Prerequisites)) {
Wait-ForUserConfirmation "System check failed! Press any key to exit..." -ExitAfter
}
# Get version choice from user (interactive menu)
$versionChoice = Get-UserVersionChoice
$script:Version = $versionChoice.Type
$script:Tag = $versionChoice.Tag
$script:Branch = $versionChoice.Branch
# Determine version information for display
$versionInfo = switch ($Version) {
"stable" {
if ($Tag) { "Stable release: $Tag" }
else { "Latest stable release (auto-detected)" }
}
"latest" { "Latest main branch (development)" }
"branch" { "Custom branch: $Branch" }
}
# Confirm installation
if (-not $NonInteractive -and -not $Force) {
Write-Host ""
Write-ColorOutput "SECURITY NOTE:" $ColorWarning
Write-Host "- This script will download and execute Claude Code Workflow from GitHub"
Write-Host "- Repository: https://github.com/catlog22/Claude-Code-Workflow"
Write-Host "- Branch: $Branch (latest stable version)"
Write-ColorOutput "INSTALLATION DETAILS:" $ColorInfo
Write-Host "- Repository: https://github.com/catlog22/Claude-Code-Workflow"
Write-Host "- Version: $versionInfo"
Write-Host "- Features: Intelligent workflow orchestration with multi-agent coordination"
Write-Host ""
Write-ColorOutput "SECURITY NOTE:" $ColorWarning
Write-Host "- This script will download and execute code from GitHub"
Write-Host "- Please ensure you trust this source"
Write-Host ""
$choice = Read-Host "Continue with installation? (y/N)"
if ($choice -notmatch '^[Yy]') {
Write-ColorOutput "Installation cancelled" $ColorWarning
@@ -258,26 +550,69 @@ function Main {
# Create temp directory
$tempDir = Get-TempDirectory
Write-ColorOutput "Temporary directory: $tempDir" $ColorInfo
try {
# Download repository
$zipPath = Download-Repository $tempDir $Branch
$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
# Get commit SHA from the downloaded repository first
$commitSha = ""
try {
Push-Location $repoDir
$commitSha = (git rev-parse --short HEAD 2>$null)
if (-not $commitSha) {
# Fallback: try to get from GitHub API
$commitUrl = "https://api.github.com/repos/catlog22/Claude-Code-Workflow/commits/$Branch"
$commitResponse = Invoke-RestMethod -Uri $commitUrl -UseBasicParsing -TimeoutSec 5 -ErrorAction SilentlyContinue
if ($commitResponse.sha) {
$commitSha = $commitResponse.sha.Substring(0, 7)
}
}
Pop-Location
} catch {
Pop-Location
$commitSha = "unknown"
}
# Determine version and branch information to pass
$versionToPass = ""
if ($Tag) {
# Specific tag version
$versionToPass = $Tag -replace '^v', '' # Remove 'v' prefix
} elseif ($Version -eq "stable") {
# Auto-detected latest stable
$latestTag = Get-LatestRelease
if ($latestTag) {
$versionToPass = $latestTag -replace '^v', ''
} else {
# Fallback: use commit SHA as version
$versionToPass = "dev-$commitSha"
}
} else {
# Latest development or branch - use commit SHA as version
$versionToPass = "dev-$commitSha"
}
$branchToPass = if ($Version -eq "branch") { $Branch } elseif ($Version -eq "latest") { "main" } elseif ($Tag) { $Tag } else { "main" }
Write-ColorOutput "Version info: $versionToPass (branch: $branchToPass, commit: $commitSha)" $ColorInfo
# Run local installer with version information
$success = Invoke-LocalInstaller -RepoDir $repoDir -VersionInfo $versionToPass -BranchInfo $branchToPass -CommitSha $commitSha
if (-not $success) {
throw "Installation script failed"
}
Write-Host ""
Write-ColorOutput "Remote installation completed successfully!" $ColorSuccess

View File

@@ -6,9 +6,13 @@ set -e # Exit on error
# Script metadata
SCRIPT_NAME="Claude Code Workflow (CCW) Remote Installer"
VERSION="2.1.1"
INSTALLER_VERSION="2.2.0"
BRANCH="${BRANCH:-main}"
# Version control
VERSION_TYPE="${VERSION_TYPE:-stable}" # stable, latest, branch
TAG_VERSION=""
# Colors for output
COLOR_RESET='\033[0m'
COLOR_SUCCESS='\033[0;32m'
@@ -32,15 +36,15 @@ function write_color() {
}
function show_header() {
write_color "==== $SCRIPT_NAME v$VERSION ====" "$COLOR_INFO"
write_color "==== $SCRIPT_NAME v$INSTALLER_VERSION ====" "$COLOR_INFO"
write_color "========================================================" "$COLOR_INFO"
echo ""
}
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
@@ -72,17 +76,80 @@ function get_temp_directory() {
echo "$temp_dir"
}
function get_latest_release() {
local api_url="https://api.github.com/repos/catlog22/Claude-Code-Workflow/releases/latest"
if command -v jq &> /dev/null; then
# Use jq if available
local tag
tag=$(curl -fsSL "$api_url" 2>/dev/null | jq -r '.tag_name' 2>/dev/null)
if [ -n "$tag" ] && [ "$tag" != "null" ]; then
echo "$tag"
return 0
fi
else
# Fallback: parse JSON with grep/sed
local tag
tag=$(curl -fsSL "$api_url" 2>/dev/null | grep -o '"tag_name":\s*"[^"]*"' | sed 's/"tag_name":\s*"\([^"]*\)"/\1/')
if [ -n "$tag" ]; then
echo "$tag"
return 0
fi
fi
write_color "WARNING: Failed to fetch latest release, using 'main' branch" "$COLOR_WARNING" >&2
return 1
}
function download_repository() {
local temp_dir="$1"
local branch="${2:-main}"
local version_type="${2:-stable}"
local branch="${3:-main}"
local tag="${4:-}"
local repo_url="https://github.com/catlog22/Claude-Code-Workflow"
local zip_url="${repo_url}/archive/refs/heads/${branch}.zip"
local zip_url=""
local download_type=""
# Determine download URL based on version type
case "$version_type" in
stable)
# Download latest stable release
if [ -z "$tag" ]; then
tag=$(get_latest_release)
if [ -z "$tag" ]; then
# Fallback to main branch if API fails
zip_url="${repo_url}/archive/refs/heads/main.zip"
download_type="main branch (fallback)"
else
zip_url="${repo_url}/archive/refs/tags/${tag}.zip"
download_type="stable release $tag"
fi
else
zip_url="${repo_url}/archive/refs/tags/${tag}.zip"
download_type="stable release $tag"
fi
;;
latest)
# Download latest main branch
zip_url="${repo_url}/archive/refs/heads/main.zip"
download_type="latest main branch"
;;
branch)
# Download specific branch
zip_url="${repo_url}/archive/refs/heads/${branch}.zip"
download_type="branch $branch"
;;
*)
write_color "ERROR: Invalid version type: $version_type" "$COLOR_ERROR" >&2
return 1
;;
esac
local zip_path="${temp_dir}/repo.zip"
write_color "Downloading from GitHub..." "$COLOR_INFO" >&2
write_color "Source: $repo_url" "$COLOR_INFO" >&2
write_color "Branch: $branch" "$COLOR_INFO" >&2
write_color "URL: $zip_url" "$COLOR_INFO" >&2
write_color "Type: $download_type" "$COLOR_INFO" >&2
# Download with curl
if curl -fsSL -o "$zip_path" "$zip_url" 2>&1 >&2; then
@@ -142,6 +209,9 @@ function extract_repository() {
function invoke_local_installer() {
local repo_dir="$1"
local version_info="$2"
local branch_info="$3"
local commit_sha="$4"
local installer_path="${repo_dir}/Install-Claude.sh"
# Make installer executable
@@ -182,6 +252,19 @@ function invoke_local_installer() {
params+=("-BackupAll")
fi
# Pass version, branch, and commit information
if [ -n "$version_info" ]; then
params+=("-SourceVersion" "$version_info")
fi
if [ -n "$branch_info" ]; then
params+=("-SourceBranch" "$branch_info")
fi
if [ -n "$commit_sha" ]; then
params+=("-SourceCommit" "$commit_sha")
fi
# Execute installer
if (cd "$repo_dir" && "$installer_path" "${params[@]}"); then
return 0
@@ -217,6 +300,23 @@ function wait_for_user() {
function parse_arguments() {
while [[ $# -gt 0 ]]; do
case "$1" in
--version)
VERSION_TYPE="$2"
if [[ ! "$VERSION_TYPE" =~ ^(stable|latest|branch)$ ]]; then
write_color "ERROR: Invalid version type: $VERSION_TYPE" "$COLOR_ERROR"
write_color "Valid options: stable, latest, branch" "$COLOR_ERROR"
exit 1
fi
shift 2
;;
--tag)
TAG_VERSION="$2"
shift 2
;;
--branch)
BRANCH="$2"
shift 2
;;
--global)
INSTALL_GLOBAL=true
shift
@@ -241,10 +341,6 @@ function parse_arguments() {
BACKUP_ALL=true
shift
;;
--branch)
BRANCH="$2"
shift 2
;;
--help)
show_help
exit 0
@@ -260,33 +356,219 @@ function parse_arguments() {
function show_help() {
cat << EOF
$SCRIPT_NAME v$VERSION
$SCRIPT_NAME v$INSTALLER_VERSION
Usage: $0 [OPTIONS]
Options:
Version Options:
--version TYPE Version type: stable (default), latest, or branch
--tag TAG Specific release tag (e.g., v3.2.0) - for stable version
--branch BRANCH Branch name (default: main) - for branch version
Installation Options:
--global Install to global user directory (~/.claude)
--directory DIR Install to custom directory
--force Force installation without prompts
--no-backup Skip backup creation
--non-interactive Non-interactive mode (no prompts)
--backup-all Backup all files before installation
--branch BRANCH Specify GitHub branch (default: main)
--help Show this help message
Examples:
# Interactive installation
# Install latest stable release (recommended)
$0
# Install specific stable version
$0 --version stable --tag v3.2.0
# Install latest development version
$0 --version latest
# Install from specific branch
$0 --version branch --branch feature/new-feature
# Global installation without prompts
$0 --global --non-interactive
# Custom directory installation
$0 --directory /opt/claude-code-workflow
Repository: https://github.com/catlog22/Claude-Code-Workflow
EOF
}
function show_version_menu() {
local latest_version="$1"
local latest_date="$2"
local commit_id="$3"
local commit_date="$4"
echo ""
write_color "====================================================" "$COLOR_INFO"
write_color " Version Selection Menu" "$COLOR_INFO"
write_color "====================================================" "$COLOR_INFO"
echo ""
# Option 1: Latest Stable
write_color "1) Latest Stable Release (Recommended)" "$COLOR_SUCCESS"
if [ -n "$latest_version" ] && [ "$latest_version" != "Unknown" ]; then
echo " |-- Version: $latest_version"
if [ -n "$latest_date" ]; then
echo " |-- Released: $latest_date"
fi
echo " \-- Production-ready"
else
echo " |-- Version: Auto-detected from GitHub"
echo " \-- Production-ready"
fi
echo ""
# Option 2: Latest Development
write_color "2) Latest Development Version" "$COLOR_WARNING"
echo " |-- Branch: main"
if [ -n "$commit_id" ] && [ -n "$commit_date" ]; then
echo " |-- Commit: $commit_id"
echo " |-- Updated: $commit_date"
fi
echo " |-- Cutting-edge features"
echo " \-- May contain experimental changes"
echo ""
# Option 3: Specific Version
write_color "3) Specific Release Version" "$COLOR_INFO"
echo " |-- Install a specific tagged release"
echo " \-- Recent: v3.2.0, v3.1.0, v3.0.1"
echo ""
write_color "====================================================" "$COLOR_INFO"
echo ""
}
function get_user_version_choice() {
if [ "$NON_INTERACTIVE" = true ] || [ "$FORCE" = true ]; then
# Non-interactive mode: use default stable version
echo "stable"
return 0
fi
# Detect latest stable version and commit info
write_color "Detecting latest release and commits..." "$COLOR_INFO"
local latest_version="Unknown"
local latest_date=""
local commit_id=""
local commit_date=""
# Get latest release info
local release_data
release_data=$(curl -fsSL --connect-timeout 5 "https://api.github.com/repos/catlog22/Claude-Code-Workflow/releases/latest" 2>/dev/null)
if [ -n "$release_data" ]; then
if command -v jq &> /dev/null; then
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
# 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
# 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
if [ -n "$latest_version" ] && [ "$latest_version" != "null" ] && [ "$latest_version" != "Unknown" ]; then
write_color "Latest stable: $latest_version ($latest_date)" "$COLOR_SUCCESS"
else
latest_version="Unknown"
write_color "Could not detect latest release" "$COLOR_WARNING"
fi
# Get latest commit info
local commit_data
commit_data=$(curl -fsSL --connect-timeout 5 "https://api.github.com/repos/catlog22/Claude-Code-Workflow/commits/main" 2>/dev/null)
if [ -n "$commit_data" ]; then
if command -v jq &> /dev/null; then
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
# 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
# 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
if [ -n "$commit_id" ] && [ -n "$commit_date" ]; then
write_color "Latest commit: $commit_id ($commit_date)" "$COLOR_SUCCESS"
else
write_color "Could not detect latest commit" "$COLOR_WARNING"
fi
show_version_menu "$latest_version" "$latest_date" "$commit_id" "$commit_date"
read -p "Select version to install (1-3, default: 1): " choice
case "$choice" in
2)
echo ""
write_color "✓ Selected: Latest Development Version (main branch)" "$COLOR_SUCCESS"
VERSION_TYPE="latest"
TAG_VERSION=""
BRANCH="main"
;;
3)
echo ""
write_color "Available recent releases:" "$COLOR_INFO"
echo " v3.2.0, v3.1.0, v3.0.1, v3.0.0"
echo ""
read -p "Enter version tag (e.g., v3.2.0): " tag_input
if [ -z "$tag_input" ]; then
write_color "⚠ No tag specified, using latest stable" "$COLOR_WARNING"
VERSION_TYPE="stable"
TAG_VERSION=""
else
echo ""
write_color "✓ Selected: Specific Version $tag_input" "$COLOR_SUCCESS"
VERSION_TYPE="stable"
TAG_VERSION="$tag_input"
fi
BRANCH="main"
;;
*)
echo ""
if [ "$latest_version" != "Unknown" ]; then
write_color "✓ Selected: Latest Stable Release ($latest_version)" "$COLOR_SUCCESS"
else
write_color "✓ Selected: Latest Stable Release (auto-detect)" "$COLOR_SUCCESS"
fi
VERSION_TYPE="stable"
TAG_VERSION=""
BRANCH="main"
;;
esac
}
function main() {
show_header
@@ -300,14 +582,37 @@ function main() {
exit 1
fi
# Get version choice from user (interactive menu)
get_user_version_choice
# Determine version information for display
local version_info=""
case "$VERSION_TYPE" in
stable)
if [ -n "$TAG_VERSION" ]; then
version_info="Stable release: $TAG_VERSION"
else
version_info="Latest stable release (auto-detected)"
fi
;;
latest)
version_info="Latest main branch (development)"
;;
branch)
version_info="Custom branch: $BRANCH"
;;
esac
# Confirm installation
if [ "$NON_INTERACTIVE" != true ] && [ "$FORCE" != true ]; then
echo ""
write_color "SECURITY NOTE:" "$COLOR_WARNING"
echo "- This script will download and execute Claude Code Workflow from GitHub"
write_color "INSTALLATION DETAILS:" "$COLOR_INFO"
echo "- Repository: https://github.com/catlog22/Claude-Code-Workflow"
echo "- Branch: $BRANCH (latest stable version)"
echo "- Version: $version_info"
echo "- Features: Intelligent workflow orchestration with multi-agent coordination"
echo ""
write_color "SECURITY NOTE:" "$COLOR_WARNING"
echo "- This script will download and execute code from GitHub"
echo "- Please ensure you trust this source"
echo ""
@@ -328,7 +633,7 @@ function main() {
# Download repository
local zip_path
write_color "Starting download process..." "$COLOR_INFO"
zip_path=$(download_repository "$temp_dir" "$BRANCH")
zip_path=$(download_repository "$temp_dir" "$VERSION_TYPE" "$BRANCH" "$TAG_VERSION")
local download_status=$?
if [ $download_status -eq 0 ] && [ -n "$zip_path" ] && [ -f "$zip_path" ]; then
@@ -343,8 +648,54 @@ function main() {
if [ $extract_status -eq 0 ] && [ -n "$repo_dir" ] && [ -d "$repo_dir" ]; then
write_color "Extraction successful: $repo_dir" "$COLOR_SUCCESS"
# Run local installer
if invoke_local_installer "$repo_dir"; then
# Get commit SHA from the downloaded repository first
local commit_sha=""
if command -v git &> /dev/null && [ -d "$repo_dir/.git" ]; then
commit_sha=$(cd "$repo_dir" && git rev-parse --short HEAD 2>/dev/null || echo "unknown")
else
# Fallback: try to get from GitHub API
local temp_branch="main"
[ "$VERSION_TYPE" = "branch" ] && temp_branch="$BRANCH"
commit_sha=$(curl -fsSL "https://api.github.com/repos/catlog22/Claude-Code-Workflow/commits/$temp_branch" 2>/dev/null | grep -o '"sha": *"[^"]*"' | head -1 | cut -d'"' -f4 | cut -c1-7)
[ -z "$commit_sha" ] && commit_sha="unknown"
fi
# Determine version and branch information to pass
local version_to_pass=""
local branch_to_pass=""
if [ -n "$TAG_VERSION" ]; then
# Specific tag version - remove 'v' prefix
version_to_pass="${TAG_VERSION#v}"
elif [ "$VERSION_TYPE" = "stable" ]; then
# Auto-detected latest stable
local latest_tag
latest_tag=$(get_latest_release)
if [ -n "$latest_tag" ]; then
version_to_pass="${latest_tag#v}"
else
# Fallback: use commit SHA as version
version_to_pass="dev-$commit_sha"
fi
else
# Latest development or branch - use commit SHA as version
version_to_pass="dev-$commit_sha"
fi
if [ "$VERSION_TYPE" = "branch" ]; then
branch_to_pass="$BRANCH"
elif [ "$VERSION_TYPE" = "latest" ]; then
branch_to_pass="main"
elif [ -n "$TAG_VERSION" ]; then
branch_to_pass="$TAG_VERSION"
else
branch_to_pass="main"
fi
write_color "Version info: $version_to_pass (branch: $branch_to_pass, commit: $commit_sha)" "$COLOR_INFO"
# Run local installer with version information
if invoke_local_installer "$repo_dir" "$version_to_pass" "$branch_to_pass" "$commit_sha"; then
success=true
echo ""
write_color "✓ Remote installation completed successfully!" "$COLOR_SUCCESS"