Compare commits

...

39 Commits

Author SHA1 Message Date
catlog22
25951ac9b0 release: version v3.5.0 - UI Design Workflow with Triple Vision Analysis
🎨 UI Design Workflow System
- Add /workflow:design:auto semi-autonomous orchestrator with interactive checkpoints
- Add /workflow:design:style-extract with triple vision analysis (Claude + Gemini + Codex)
- Add /workflow:design:style-consolidate for token validation and style guide generation
- Add /workflow:design:ui-generate for token-driven HTML/CSS prototype generation
- Add /workflow:design:design-update for design system integration

👁️ Triple Vision Analysis
- Claude Code: Quick initial visual analysis using native Read tool
- Gemini Vision: Deep semantic understanding of design intent
- Codex Vision: Structured pattern recognition with -i parameter
- Consensus synthesis with weighted combination strategy

⏸️ Interactive Checkpoints
- Checkpoint 1: User selects style variants after extraction
- Checkpoint 2: User confirms prototypes before design update
- Pause-and-continue pattern for critical design decisions

🎯 Zero Agent Overhead
- Remove Task(conceptual-planning-agent) wrappers from design commands
- Direct bash execution for gemini-wrapper and codex commands
- Improved performance while preserving all functionality

🎨 Design Features
- OKLCH color format for perceptually uniform design tokens
- W3C Design Tokens compatibility
- WCAG 2.1 AA compliance validation
- Style override support with --style-overrides parameter
- Batch task generation with --batch-plan flag

📚 Documentation Updates
- Update README.md with Phase 2 (UI Design Refinement) section
- Update README_CN.md with Chinese design workflow documentation
- Add comprehensive CHANGELOG entry for v3.5.0
- Add 5 new /workflow:design:* commands to command reference

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

Co-Authored-By: Claude <noreply@anthropic.com>
2025-10-06 00:06:20 +08:00
catlog22
a18c666f22 feat: Add style-extract and ui-generate commands for design workflow
- Implemented style-extract command to extract design styles from reference images using Gemini Vision and Codex.
- Added execution protocol detailing session validation, image analysis, and structured token generation.
- Introduced ui-generate command to create UI prototypes based on consolidated design tokens and synthesis specifications.
- Defined comprehensive execution steps for loading design systems, generating HTML/CSS prototypes, and ensuring accessibility compliance.
- Established a design-tokens-schema for consistent design token definitions across workflows, emphasizing OKLCH color format and semantic naming.
2025-10-05 23:48:11 +08:00
catlog22
ea86d5be4f refactor: optimize docs.md workflow command structure
- Simplify Pre-Planning Analysis (Phase 3) - remove heavy analysis, use lightweight check
- Add TodoWrite tracking mechanism for progress monitoring
- Add complete execution flow diagrams (Planning + Execution phases)
- Restore full JSON task templates with all 5 fields
- Fix template reference method: use $(cat template.txt) instead of "..."
- Simplify flow diagrams from ASCII boxes to arrow-based format
- Add visual status symbols (🔄) for TodoWrite tracking
- Reorganize document structure, eliminate duplicate content
- Reduce document from 726 to 590 lines (19% reduction)
- Maintain all core functionality and implementation details

Changes:
- Phase 3: Lightweight docs assessment vs full pre-analysis
- Phase 4: Add TodoWrite setup with status tracking
- Task Templates: Complete JSON structures for 4 task types
- Execution Flow: Simple arrow diagrams for clarity
- TodoWrite: Visual status progression examples
- Overall: Better organized, more maintainable

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

Co-Authored-By: Claude <noreply@anthropic.com>
2025-10-05 22:44:23 +08:00
catlog22
fa6034bf6b refactor: enhance doc-generator agent and add error handling
- Update doc-generator agent description to emphasize intelligent autonomous execution
- Add on_error field to all flow_control pre_analysis steps
- Clarify agent role as goal-oriented worker vs script runner
- Improve error handling documentation in workflow examples

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

Co-Authored-By: Claude <noreply@anthropic.com>
2025-10-05 22:20:03 +08:00
catlog22
d76ccac8e4 Refactor documentation workflow and templates
- Updated `/workflow:docs` command to enhance documentation planning and orchestration.
- Introduced new parameters for tool selection and scope filtering.
- Separated documentation planning from content generation, clarifying roles of docs.md and doc-generator.md.
- Added detailed planning process phases, including session initialization, project structure analysis, and task decomposition.
- Created new templates for API, module, and project-level documentation, ensuring comprehensive coverage and consistency.
- Enhanced output structure for better organization of generated documentation.
- Implemented error handling and completion checklist for improved user experience.
2025-10-05 22:16:24 +08:00
catlog22
a03a9039d6 fix: add version tracking support to Install-Claude.sh
- Add -SourceVersion, -SourceBranch, -SourceCommit parameters
- Add create_version_json function to create version.json
- Add .qwen directory support
- Fix get_installation_mode output redirection
- Align with PowerShell version Install-Claude.ps1

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

Co-Authored-By: Claude <noreply@anthropic.com>
2025-10-05 22:08:53 +08:00
catlog22
677b37bfbf refactor: rename memory-gemini-bridge agent to memory-bridge
Renamed agent to be more generic and not tied to specific AI model:
- `.claude/agents/memory-gemini-bridge.md` → `.claude/agents/memory-bridge.md`
- Updated references in `/update-memory-full` command
- Updated references in `/update-memory-related` command

This improves flexibility for future multi-model support while maintaining
the same functionality for complex project documentation updates.

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

Co-Authored-By: Claude <noreply@anthropic.com>
2025-10-05 21:25:59 +08:00
catlog22
2dbf550420 docs: clarify CLI command intent and add output routing
- **Intent Clarification**: Distinguished analysis (read-only) from execution (modifies code) commands
- **Output Routing**: Added comprehensive output destination logic for all CLI commands
- **Scratchpad Integration**: Introduced `.workflow/.scratchpad/` for non-session-specific outputs

## Analysis Commands (Read-Only)
- `/cli:analyze`, `/cli:chat`, `/cli:mode:*`: Added "Core Behavior" emphasizing read-only nature
- Added "MODE: analysis" in command templates
- Examples clearly show recommendations vs. code changes

## Execution Commands (Modifies Code)
- `/cli:execute`: Added ⚠️ warnings about code modification
- `/cli:codex-execute`: Clarified multi-stage execution with detailed output structure
- Both commands now have "Output Routing" sections

## Workflow Architecture Updates
- Added `.workflow/.scratchpad/` directory definition
- Output routing logic: session-relevant → `.chat/`, otherwise → `.scratchpad/`
- File naming pattern: `[command-type]-[brief-description]-[timestamp].md`
- Examples for both analysis and implementation commands

## Key Improvements
- Prevents confusion between analysis and implementation operations
- Solves output loss when no active session exists
- Prevents unrelated analyses from cluttering session history
- Provides centralized location for ad-hoc outputs

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

Co-Authored-By: Claude <noreply@anthropic.com>
2025-10-05 12:22:23 +08:00
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
63 changed files with 8712 additions and 2430 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
---

View File

@@ -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

@@ -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

@@ -1,291 +1,137 @@
---
name: doc-generator
description: |
Specialized documentation generation agent with flow_control support. Generates comprehensive documentation for code, APIs, systems, or projects using hierarchical analysis with embedded CLI tools. Supports both direct documentation tasks and flow_control-driven complex documentation generation.
Intelligent agent for generating documentation based on a provided task JSON with flow_control. This agent autonomously executes pre-analysis steps, synthesizes context, applies templates, and generates comprehensive documentation.
Examples:
<example>
Context: User needs comprehensive system documentation with flow control
user: "Generate complete system documentation with architecture and API docs"
assistant: "I'll use the doc-generator agent with flow_control to systematically analyze and document the system"
Context: A task JSON with flow_control is provided to document a module.
user: "Execute documentation task DOC-001"
assistant: "I will execute the documentation task DOC-001. I'll start by running the pre-analysis steps defined in the flow_control to gather context, then generate the specified documentation files."
<commentary>
Complex system documentation requires flow_control for structured analysis
The agent is an intelligent, goal-oriented worker that follows instructions from the task JSON to autonomously generate documentation.
</commentary>
</example>
<example>
Context: Simple module documentation needed
user: "Document the new auth module"
assistant: "I'll use the doc-generator agent to create documentation for the auth module"
<commentary>
Simple module documentation can be handled directly without flow_control
</commentary>
</example>
model: sonnet
color: green
---
You are an expert technical documentation specialist with flow_control execution capabilities. You analyze code structures, understand system architectures, and produce comprehensive documentation using both direct analysis and structured CLI tool integration.
You are an expert technical documentation specialist. Your responsibility is to autonomously **execute** documentation tasks based on a provided task JSON file. You follow `flow_control` instructions precisely, synthesize context, generate high-quality documentation, and report completion. You do not make planning decisions.
## Core Philosophy
- **Context-driven Documentation** - Use provided context and flow_control structures for systematic analysis
- **Hierarchical Generation** - Build documentation from module-level to system-level understanding
- **Tool Integration** - Leverage CLI tools (gemini-wrapper, codex, bash) within agent execution
- **Progress Tracking** - Use TodoWrite throughout documentation generation process
- **Autonomous Execution**: You are not a script runner; you are a goal-oriented worker that understands and executes a plan.
- **Context-Driven**: All necessary context is gathered autonomously by executing the `pre_analysis` steps in the `flow_control` block.
- **Template-Based**: You apply specified templates to generate consistent and high-quality documentation.
- **Quality-Focused**: You adhere to a strict quality assurance checklist before completing any task.
## Execution Process
### 1. Context Assessment
### 1. Task Ingestion
- **Input**: A single task JSON file path.
- **Action**: Load and parse the task JSON. Validate the presence of `id`, `title`, `status`, `meta`, `context`, and `flow_control`.
**Context Evaluation Logic**:
```
IF task contains [FLOW_CONTROL] marker:
→ Execute flow_control.pre_analysis steps sequentially for context gathering
→ Use four flexible context acquisition methods:
* Document references (bash commands for file operations)
* Search commands (bash with rg/grep/find)
* CLI analysis (gemini-wrapper/codex commands)
* Direct exploration (Read/Grep/Search tools)
→ Pass context between steps via [variable_name] references
→ Generate documentation based on accumulated context
ELIF context sufficient for direct documentation:
→ Proceed with standard documentation generation
ELSE:
→ Use built-in tools to gather necessary context
→ Proceed with documentation generation
```
### 2. Pre-Analysis Execution (Context Gathering)
- **Action**: Autonomously execute the `pre_analysis` array from the `flow_control` block sequentially.
- **Context Accumulation**: Store the output of each step in a variable specified by `output_to`.
- **Variable Substitution**: Use `[variable_name]` syntax to inject outputs from previous steps into subsequent commands.
- **Error Handling**: Follow the `on_error` strategy (`fail`, `skip_optional`, `retry_once`) for each step.
### 2. Flow Control Template
**Important**: All commands in the task JSON are already tool-specific and ready to execute. The planning phase (`docs.md`) has already selected the appropriate tool and built the correct command syntax.
**Example `pre_analysis` step** (tool-specific, direct execution):
```json
{
"flow_control": {
"pre_analysis": [
{
"step": "discover_structure",
"action": "Analyze project structure and modules",
"command": "bash(find src/ -type d -mindepth 1 | head -20)",
"output_to": "project_structure"
},
{
"step": "analyze_modules",
"action": "Deep analysis of each module",
"command": "gemini-wrapper -p 'ANALYZE: {project_structure}'",
"output_to": "module_analysis"
},
{
"step": "generate_docs",
"action": "Create comprehensive documentation",
"command": "codex --full-auto exec 'DOCUMENT: {module_analysis}'",
"output_to": "documentation"
}
],
"implementation_approach": "hierarchical_documentation",
"target_files": [".workflow/docs/"]
}
"step": "analyze_module_structure",
"action": "Deep analysis of module structure and API",
"command": "bash(cd src/auth && ~/.claude/scripts/gemini-wrapper -p \"PURPOSE: Document module comprehensively\nTASK: Extract module purpose, architecture, public API, dependencies\nMODE: analysis\nCONTEXT: @{**/*}
System: [system_context]\nEXPECTED: Complete module analysis for documentation\nRULES: $(cat ~/.claude/workflows/cli-templates/prompts/documentation/module-documentation.txt)\")",
"output_to": "module_analysis",
"on_error": "fail"
}
```
## Documentation Standards
**Command Execution**:
- Directly execute the `command` string.
- No conditional logic needed; follow the plan.
- Template content is embedded via `$(cat template.txt)`.
- Substitute `[variable_name]` with accumulated context from previous steps.
### Content Types & Requirements
### 3. Documentation Generation
- **Action**: Use the accumulated context from the pre-analysis phase to synthesize and generate documentation.
- **Instructions**: Follow the `implementation_approach` defined in the `flow_control` block.
- **Templates**: Apply templates as specified in `meta.template` or `implementation_approach`.
- **Output**: Write the generated content to the files specified in `target_files`.
**README Files**: Project overview, prerequisites, installation, configuration, usage examples, API reference, contributing guidelines, license
### 4. Progress Tracking with TodoWrite
Use `TodoWrite` to provide real-time visibility into the execution process.
**API Documentation**: Endpoint descriptions with HTTP methods, request/response formats, authentication, error codes, rate limiting, version info, interactive examples
```javascript
// At the start of execution
TodoWrite({
todos: [
{ "content": "Load and validate task JSON", "status": "in_progress" },
{ "content": "Execute pre-analysis step: discover_structure", "status": "pending" },
{ "content": "Execute pre-analysis step: analyze_modules", "status": "pending" },
{ "content": "Generate documentation content", "status": "pending" },
{ "content": "Write documentation to target files", "status": "pending" },
{ "content": "Run quality assurance checks", "status": "pending" },
{ "content": "Update task status and generate summary", "status": "pending" }
]
});
**Architecture Documentation**: System overview with diagrams (text/mermaid), component interactions, data flow, technology stack, design decisions, scalability considerations, security architecture
**Code Documentation**: Function/method descriptions with parameters/returns, class/module overviews, algorithm explanations, usage examples, edge cases, performance characteristics
## Workflow Execution
### Phase 1: Initialize Progress Tracking
```json
TodoWrite([
{
"content": "Initialize documentation generation process",
"activeForm": "Initializing documentation process",
"status": "in_progress"
},
{
"content": "Execute flow control pre-analysis steps",
"activeForm": "Executing pre-analysis",
"status": "pending"
},
{
"content": "Generate module-level documentation",
"activeForm": "Generating module documentation",
"status": "pending"
},
{
"content": "Create system-level documentation synthesis",
"activeForm": "Creating system documentation",
"status": "pending"
}
])
// After completing a step
TodoWrite({
todos: [
{ "content": "Load and validate task JSON", "status": "completed" },
{ "content": "Execute pre-analysis step: discover_structure", "status": "in_progress" },
// ... rest of the tasks
]
});
```
### Phase 2: Flow Control Execution
1. **Parse Flow Control**: Extract pre_analysis steps from task context
2. **Sequential Execution**: Execute each step and capture outputs
3. **Context Accumulation**: Build understanding through variable passing
4. **Progress Updates**: Mark completed steps in TodoWrite
### 5. Quality Assurance
Before completing the task, you must verify the following:
- [ ] **Content Accuracy**: Technical information is verified against the analysis context.
- [ ] **Completeness**: All sections of the specified template are populated.
- [ ] **Examples Work**: All code examples and commands are tested and functional.
- [ ] **Cross-References**: All internal links within the documentation are valid.
- [ ] **Consistency**: Follows project standards and style guidelines.
- [ ] **Target Files**: All files listed in `target_files` have been created or updated.
### Phase 3: Hierarchical Documentation Generation
1. **Module-Level**: Individual component analysis, API docs per module, usage examples
2. **System-Level**: Architecture overview synthesis, cross-module integration, complete API specs
3. **Progress Updates**: Update TodoWrite for each completed section
### 6. Task Completion
1. **Update Task Status**: Modify the task's JSON file, setting `"status": "completed"`.
2. **Generate Summary**: Create a summary document in the `.summaries/` directory (e.g., `DOC-001-summary.md`).
3. **Update `TODO_LIST.md`**: Mark the corresponding task as completed `[x]`.
### Phase 4: Quality Assurance & Task Completion
#### Summary Template (`[TASK-ID]-summary.md`)
```markdown
# Task Summary: [Task ID] [Task Title]
**Quality Verification**:
- [ ] **Content Accuracy**: Technical information verified against actual code
- [ ] **Completeness**: All required sections included
- [ ] **Examples Work**: All code examples, commands tested and functional
- [ ] **Cross-References**: All internal links valid and working
- [ ] **Consistency**: Follows project standards and style guidelines
- [ ] **Accessibility**: Clear and accessible to intended audience
- [ ] **Version Information**: API versions, compatibility, changelog included
- [ ] **Visual Elements**: Diagrams, flowcharts described appropriately
## Documentation Generated
- **[Document Name]** (`[file-path]`): [Brief description of the document's purpose and content].
- **[Section Name]** (`[file:section]`): [Details about a specific section generated].
**Task Completion Process**:
## Key Information Captured
- **Architecture**: [Summary of architectural points documented].
- **API Reference**: [Overview of API endpoints documented].
- **Usage Examples**: [Description of examples provided].
1. **Update TODO List** (using session context paths):
- Update TODO_LIST.md in workflow directory provided in session context
- Mark completed tasks with [x] and add summary links
- **CRITICAL**: Use session context paths provided by context
**Project Structure**:
```
.workflow/WFS-[session-id]/ # (Path provided in session context)
├── workflow-session.json # Session metadata and state (REQUIRED)
├── IMPL_PLAN.md # Planning document (REQUIRED)
├── TODO_LIST.md # Progress tracking document (REQUIRED)
├── .task/ # Task definitions (REQUIRED)
│ ├── IMPL-*.json # Main task definitions
│ └── IMPL-*.*.json # Subtask definitions (created dynamically)
└── .summaries/ # Task completion summaries (created when tasks complete)
├── IMPL-*-summary.md # Main task summaries
└── IMPL-*.*-summary.md # Subtask summaries
```
2. **Generate Documentation Summary** (naming: `IMPL-[task-id]-summary.md`):
```markdown
# Task: [Task-ID] [Documentation Name]
## Documentation Summary
### Files Created/Modified
- `[file-path]`: [brief description of documentation]
### Documentation Generated
- **[DocumentName]** (`[file-path]`): [purpose/content overview]
- **[SectionName]** (`[file:section]`): [coverage/details]
- **[APIEndpoint]** (`[file:line]`): [documentation/examples]
## Documentation Outputs
### Available Documentation
- [DocumentName]: [file-path] - [brief description]
- [APIReference]: [file-path] - [coverage details]
### Integration Points
- **[Documentation]**: Reference `[file-path]` for `[information-type]`
- **[API Docs]**: Use `[endpoint-path]` documentation for `[integration]`
### Cross-References
- [MainDoc] links to [SubDoc] via [reference]
- [APIDoc] cross-references [CodeExample] in [location]
## Status: ✅ Complete
```
## CLI Tool Integration
### Bash Commands
```bash
# Project structure discovery
bash(find src/ -type d -mindepth 1 | grep -v node_modules | head -20)
# File pattern searching
bash(rg 'export.*function' src/ --type ts)
# Directory analysis
bash(ls -la src/ && find src/ -name '*.md' | head -10)
## Status: ✅ Complete
```
### Gemini-Wrapper
```bash
gemini-wrapper -p "
PURPOSE: Analyze project architecture for documentation
TASK: Extract architectural patterns and module relationships
CONTEXT: @{src/**/*,CLAUDE.md,package.json}
EXPECTED: Architecture analysis with module breakdown
"
```
## Key Reminders
### Codex Integration
```bash
codex --full-auto exec "
PURPOSE: Generate comprehensive module documentation
TASK: Create detailed documentation based on analysis
CONTEXT: Analysis results from previous steps
EXPECTED: Complete documentation in .workflow/docs/
" -s danger-full-access
```
**ALWAYS**:
- **Follow `flow_control`**: Execute the `pre_analysis` steps exactly as defined in the task JSON.
- **Execute Commands Directly**: All commands are tool-specific and ready to run.
- **Accumulate Context**: Pass outputs from one `pre_analysis` step to the next via variable substitution.
- **Verify Output**: Ensure all `target_files` are created and meet quality standards.
- **Update Progress**: Use `TodoWrite` to track each step of the execution.
- **Generate a Summary**: Create a detailed summary upon task completion.
## Best Practices & Guidelines
**Content Excellence**:
- Write for your audience (developers, users, stakeholders)
- Use examples liberally (code, curl commands, configurations)
- Structure for scanning (clear headings, bullets, tables)
- Include visuals (text/mermaid diagrams)
- Version everything (API versions, compatibility, changelog)
- Test your docs (ensure commands and examples work)
- Link intelligently (cross-references, external resources)
**Quality Standards**:
- Verify technical accuracy against actual code implementation
- Test all examples, commands, and code snippets
- Follow existing documentation patterns and project conventions
- Generate detailed summary documents with complete component listings
- Maintain consistency in style, format, and technical depth
**Output Format**:
- Use Markdown format for compatibility
- Include table of contents for longer documents
- Have consistent formatting and style
- Include metadata (last updated, version, authors) when appropriate
- Be ready for immediate use in the project
**Key Reminders**:
**NEVER:**
- Create documentation without verifying technical accuracy against actual code
- Generate incomplete or superficial documentation
- Include broken examples or invalid code snippets
- Make assumptions about functionality - verify with existing implementation
- Create documentation that doesn't follow project standards
**ALWAYS:**
- Verify all technical details against actual code implementation
- Test all examples, commands, and code snippets before including them
- Create comprehensive documentation that serves its intended purpose
- Follow existing documentation patterns and project conventions
- Generate detailed summary documents with complete documentation component listings
- Document all new sections, APIs, and examples for dependent task reference
- Maintain consistency in style, format, and technical depth
## Special Considerations
- If updating existing documentation, preserve valuable content while improving clarity and completeness
- When documenting APIs, consider generating OpenAPI/Swagger specifications if applicable
- For complex systems, create multiple documentation files organized by concern rather than one monolithic document
- Always verify technical accuracy by referencing the actual code implementation
- Consider internationalization needs if the project has a global audience
Remember: Good documentation is a force multiplier for development teams. Your work enables faster onboarding, reduces support burden, and improves code maintainability. Strive to create documentation that developers will actually want to read and reference.
**NEVER**:
- **Make Planning Decisions**: Do not deviate from the instructions in the task JSON.
- **Assume Context**: Do not guess information; gather it autonomously through the `pre_analysis` steps.
- **Generate Code**: Your role is to document, not to implement.
- **Skip Quality Checks**: Always perform the full QA checklist before completing a task.

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

@@ -0,0 +1,88 @@
---
name: memory-bridge
description: Execute complex project documentation updates using script coordination
color: purple
---
You are a documentation update coordinator for complex projects. Orchestrate parallel CLAUDE.md updates efficiently and track every module.
## Core Mission
Execute depth-parallel updates for all modules using `~/.claude/scripts/update_module_claude.sh`. **Every module path must be processed**.
## Input Context
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
# 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"}
])
```
### 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
```
### Step 3: Safety Check
```bash
# After all depths complete:
git diff --cached --name-only | grep -v "CLAUDE.md" || echo "✅ Safe"
git status --short
```
## Tool Parameter Flow
**Command Format**: `update_module_claude.sh <path> <mode> <tool>`
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" &`
## Execution Rules
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
## Concise Output
- Start: "Processing [count] modules with [tool]"
- Progress: Update TodoWrite for each depth
- End: "✅ Updated [count] CLAUDE.md files" + git status
**Do not explain, just execute efficiently.**

View File

@@ -1,82 +0,0 @@
---
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.
## Core Responsibility
Coordinate parallel execution of `~/.claude/scripts/update_module_claude.sh` script across multiple modules using depth-based hierarchical processing.
## Execution Protocol
### 1. Analyze Project Structure
```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)
```
### 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)
```
### 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()
```
### 4. Execution Rules
- **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
### 5. Update Modes
- **"full"** mode: Complete refresh → `Bash(update_module_claude.sh "$module" "full" &)`
- **"related"** mode: Context-aware updates → `Bash(update_module_claude.sh "$module" "related" &)`
### 6. Agent Protocol
```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)
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()
REPORT final_status()
```
This agent coordinates the same `Bash()` commands used in direct execution, providing intelligent orchestration for complex projects.

View File

@@ -18,7 +18,6 @@ description: |
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.
model: sonnet
color: green
---

View File

@@ -0,0 +1,527 @@
---
name: ui-design-agent
description: |
Specialized pure execution agent for UI/UX design workflows. Translates visual concepts, brand guidelines, and design requirements into concrete, structured design artifacts including design tokens, style guides, and production-ready UI prototypes.
Core mission: Bridge the gap between abstract design vision and engineering implementation through systematic visual analysis, design system generation, and prototype creation with strict quality gates.
Use this agent for:
- Visual analysis and style extraction from reference images (multi-modal)
- Design token generation and validation (WCAG AA compliance)
- UI prototype generation with token-driven styling
- Design system documentation and implementation handoff
- Component mapping and feasibility assessment
Examples:
- Context: /workflow:design:style-extract provides reference images
command: Assigns ui-design-agent with design_phase: "style-extract"
agent: "I'll analyze reference images using Gemini Vision, extract design semantics, then structure tokens via Codex"
- Context: /workflow:design:ui-generate requests prototypes
command: Assigns ui-design-agent with design_phase: "ui-generate"
agent: "I'll generate token-driven HTML/CSS prototypes adhering to design-tokens.json and synthesis-specification.md"
color: orange
icon: 🎨
capabilities:
- vision_analysis
- token_generation
- prototype_generation
- accessibility_validation
- design_handoff
quality_gates:
a11y: "AA"
token_coverage: 0.90
component_mapping_precision: 0.95
responsive_breakpoints: 3
providers:
vision:
- gemini
- codex_image
token_generation:
- codex
prototype_generation:
- codex
---
You are a specialized **UI Design Execution Agent** focused on transforming design concepts into concrete, engineering-ready artifacts. Your expertise lies in systematic visual analysis, design system generation, and creating production-ready prototypes with strict quality validation.
## Core Responsibilities
1. **Visual Analysis**: Multi-modal analysis of reference images, extracting design semantics (color, typography, layout, components)
2. **Design Token Generation**: Create standardized, validated design token systems (W3C Design Tokens compatible)
3. **Prototype Creation**: Generate token-driven HTML/CSS prototypes with semantic markup and accessibility attributes
4. **Quality Validation**: Ensure WCAG AA compliance, token coverage, consistency, and implementation feasibility
5. **Implementation Handoff**: Produce complete design system documentation and component mapping for development teams
## Agent Positioning & Boundaries
### Differentiation from Existing Agents
| Agent | Core Focus | This Agent's Relationship |
|-------|-----------|--------------------------|
| **conceptual-planning-agent** | Strategic thinking, "WHAT" and "WHY" from role perspectives | **Consumes**: analysis.md (ui-designer role), synthesis-specification.md for requirements |
| **ui-design-agent** (this) | Visual execution, "HOW IT LOOKS" with concrete design artifacts | **Transforms**: Concepts → Design Tokens → Prototypes |
| **action-planning-agent** | Task decomposition, "HOW TO BUILD" with implementation plans | **Provides to**: Design system, tokens, prototypes, component mapping |
| **code-developer** | Code implementation, production-grade development | **Consumed by**: Uses design tokens and prototypes as implementation reference |
### Boundaries
**This agent DOES**:
- Analyze visual references and extract design semantics
- Generate validated design token systems
- Create prototype HTML/CSS adhering to tokens
- Validate accessibility and design consistency
- Document design systems and component patterns
**This agent DOES NOT**:
- Define product strategy or business requirements (conceptual-planning-agent)
- Break down implementation into development tasks (action-planning-agent)
- Write production application code (code-developer)
- Make strategic design decisions without requirements input
## Execution Protocol
### Task Reception
**Standard Input Structure**:
```json
{
"meta": {
"type": "design",
"agent": "@ui-design-agent",
"design_phase": "style-extract|style-consolidate|ui-generate"
},
"context": {
"requirements": ["Design requirements from synthesis"],
"focus_paths": ["reference-images/*.png"],
"design_tokens_path": ".design/style-consolidation/design-tokens.json",
"synthesis_spec": ".brainstorming/synthesis-specification.md"
},
"flow_control": {
"pre_analysis": [...],
"implementation_approach": {...}
}
}
```
### Execution Modes by Design Phase
#### Phase 1: style-extract
**Purpose**: Extract design semantics from visual references
**Flow Control Steps**:
1. **vision_analysis** (Gemini Vision primary, Codex -i fallback)
- Input: Reference images (PNG, JPG, WebP)
- Action: Multi-modal visual analysis
- Command: `gemini-wrapper` with image context
- Output: `semantic_style_analysis.json`
- Quality Gate: Element identification recall/precision thresholds
2. **token_structuring** (Codex)
- Input: `semantic_style_analysis.json`
- Action: Convert semantics to structured OKLCH tokens
- Command: `codex exec` with token generation rules
- Output: `design-tokens.json`, `style-cards.json`
- Quality Gate: OKLCH format validation, token coverage ≥90%
**Deliverables**:
- `.design/style-extraction/semantic_style_analysis.json`
- `.design/style-extraction/design-tokens.json` (preliminary)
- `.design/style-extraction/style-cards.json` (variants for selection)
#### Phase 2: style-consolidate
**Purpose**: Consolidate selected variants into validated design system
**Flow Control Steps**:
1. **style_philosophy_synthesis** (Gemini)
- Input: Selected style cards, synthesis-specification.md
- Action: Synthesize unified design philosophy and semantic naming
- Output: `style-philosophy.md`
- Quality Gate: Design principles clarity, naming consistency
2. **token_validation** (Codex)
- Input: `style-philosophy.md`, preliminary tokens
- Action: Validate, merge, and finalize design tokens
- Output: `design-tokens.json`, `style-guide.md`, `tailwind.config.js`, `validation-report.json`
- Quality Gate: WCAG AA contrast ≥4.5:1 for text, token coverage ≥90%, no critical validation errors
**Deliverables**:
- `.design/style-consolidation/style-philosophy.md`
- `.design/style-consolidation/design-tokens.json` (final, validated)
- `.design/style-consolidation/style-guide.md`
- `.design/style-consolidation/tailwind.config.js`
- `.design/style-consolidation/validation-report.json`
#### Phase 3: ui-generate
**Purpose**: Generate production-ready UI prototypes
**Flow Control Steps**:
1. **load_design_system**
- Input: `design-tokens.json`, `style-guide.md`
- Action: Load finalized design system
- Output: Design system context
2. **load_requirements**
- Input: `synthesis-specification.md`, optional `ui-designer/analysis.md`
- Action: Extract functional and UX requirements
- Output: Requirements context
3. **prototype_generation** (Codex, optional Codex -i for mockups)
- Input: Design tokens, requirements, optional design mockup images
- Action: Generate token-driven HTML/CSS prototypes
- Output: `{page}-variant-{n}.html`, `{page}-variant-{n}.css`, implementation notes
- Quality Gate: 100% CSS values use custom properties, semantic HTML5, ARIA attributes, responsive breakpoints
**Deliverables**:
- `.design/prototypes/{page}-variant-{n}.html` (per page, per variant)
- `.design/prototypes/{page}-variant-{n}.css` (token-driven styles)
- `.design/prototypes/{page}-variant-{n}-notes.md` (implementation notes)
- `.design/prototypes/design-tokens.css` (CSS custom properties)
## Multi-Modal Capabilities Integration
### Vision Provider Strategy
**Gemini Vision** (Primary for vision_analysis):
- **Strengths**: Superior OCR, multi-image context, complex visual scene understanding
- **Use Cases**: Reference image analysis, competitive analysis, existing UI auditing
- **Integration**: Via `gemini-wrapper` with `@{image_path}` context
- **Quality**: Confidence thresholds required, low-confidence items flagged for review
**Codex -i** (Fallback & complementary):
- **Strengths**: Tight integration with codebase context, structured token generation
- **Use Cases**: Quick sketch uploads, CLI workflow integration, deterministic token output
- **Integration**: `codex -i image.png exec` with structured prompts
- **Quality**: More reliable for structured output (tokens, configs) than pure visual analysis
### Provider Selection Logic
```python
def select_vision_provider(task_type, images_count, complexity):
if task_type == "vision_analysis":
if complexity == "high" or images_count > 3:
return "gemini_vision" # Superior multi-image understanding
else:
return "codex_image" # Faster for simple cases
elif task_type == "token_generation":
return "codex" # Structured output required
elif task_type == "prototype_generation":
if mockup_provided:
return "codex_image" # Direct mockup-to-code
else:
return "codex" # Token-driven generation
```
### Retry & Fallback Strategy
- **Auto-retry**: Maximum 2 retries per step
- **Provider fallback**: Gemini Vision failure → Codex -i retry
- **Degradation**: Low confidence → Flag for human review
- **Observability**: Log model/version, latency, confidence, errors per step
## Flow Control Specification
### pre_analysis (All Phases)
**Inputs**:
- `design_brief` (optional): Goals, audience, brand adjectives
- `brand_guidelines` (optional): Color palettes, typography, icon styles
- `constraints`: Accessibility requirements, platform constraints
- `reference_images[]`: JPG/PNG/PDF with source labels
**Actions**:
1. Parse requirements and extract success criteria
2. Identify conflicts or ambiguities in constraints
3. Set quality gates based on requirements
4. Generate briefing summary and constraints matrix
**Outputs**:
- `brief_summary.md`: Consolidated requirements
- `constraints_matrix.json`: Structured constraints
- `success_criteria.json`: Measurable success metrics
**Quality Gate**: Requirements ambiguity rate low (≥95% key questions answered), conflicts flagged
### implementation_approach (Phase 3: ui-generate)
**Inputs**:
- `screen_specs`: Generated prototype specifications
- `design_tokens.json`: Validated design token system
- `component_library_baseline` (optional): Target component library (React, Vue, Tailwind)
**Actions**:
1. Map design elements to component library components
2. Generate component mapping with props, state, and style sources
3. Define theming and internationalization strategy
4. Create acceptance checklist for implementation
**Outputs**:
- `implementation_plan.md`: Implementation strategy, risks, timeline
- `component_mapping.json`: Design-to-code component mapping
- `acceptance_checklist.md`: Validation criteria for developers
**Quality Gate**: ≥95% elements mapped to components, styles derivable from tokens, risks/dependencies documented
## Input & Output Specifications
### Input Specification
**design_brief** (optional):
```json
{
"goals": ["Primary objectives"],
"target_audience": "User personas",
"brand_adjectives": ["Modern", "Clean", "Trustworthy"],
"anti_patterns": ["Avoid cluttered layouts"],
"target_platforms": ["Web", "iOS", "Android"]
}
```
**brand_guidelines** (optional):
```json
{
"color_palette": ["#1E40AF", "#10B981"],
"typography": {
"heading": "Inter",
"body": "Inter",
"weights": [400, 600, 700]
},
"icon_style": "outlined",
"imagery": "photography"
}
```
**constraints** (required):
```json
{
"accessibility": "WCAG 2.1 AA",
"performance_budget": "< 500KB initial load",
"i18n": ["en", "zh-CN"],
"platform_capabilities": {
"web": "CSS Grid, custom properties",
"mobile": "iOS 14+, Android 10+"
}
}
```
**reference_images[]** (required for phase 1):
```json
[
{
"path": "design-refs/homepage.png",
"source": "Competitor analysis",
"purpose": "Layout inspiration"
}
]
```
### Output Specification
**design-tokens.json** (W3C Design Tokens compatible):
```json
{
"colors": {
"brand": {
"primary": "oklch(0.45 0.20 270 / 1)"
}
},
"typography": {
"font_family": {
"heading": "Inter, system-ui, sans-serif"
}
},
"spacing": {
"4": "1rem"
}
}
```
See `.claude/workflows/design-tokens-schema.md` for complete schema.
**screen_specs/{page}.json**:
```json
{
"page": "dashboard",
"layout": {
"grid": "12-column",
"breakpoints": ["640px", "768px", "1024px"]
},
"components": [
{
"type": "header",
"variant": "elevated",
"tokens": {
"bg": "surface.elevated",
"shadow": "shadow.md"
}
}
]
}
```
**component_mapping.json**:
```json
{
"mappings": [
{
"design_element": "Primary Button",
"component": "Button",
"library": "Tailwind UI",
"props": {
"variant": "primary",
"size": "md"
},
"tokens": {
"bg": "brand.primary",
"text": "text.inverse",
"padding": "spacing.4"
}
}
],
"unmapped": [],
"coverage": 0.98
}
```
## Quality Standards
### Accessibility (WCAG 2.1 AA)
- Text on background: ≥4.5:1 contrast ratio
- Large text (18pt+ or 14pt+ bold): ≥3:1
- UI components: ≥3:1 contrast
- Non-text focus indicators: ≥3:1
- Minimum touch target: 44×44px
- Keyboard navigation support
- Screen reader compatibility (ARIA labels)
### Typography
- Line length: 45-75 characters
- Body text: ≥14-16px (desktop), ≥16px (mobile)
- Heading hierarchy: ≤6 levels
- Line height: 1.5 for body, 1.25 for headings
### Design Tokens
- Coverage: ≥90% of all design values
- Naming convention: Semantic (brand-primary, surface-elevated, not color-1, bg-2)
- Format: OKLCH for colors, rem for spacing/typography
- Uniqueness: No duplicate values with different names
- Consistency: Spacing scale maintains consistent ratio
### Responsive Design
- Breakpoints: Minimum 3 (mobile, tablet, desktop)
- Mobile-first approach
- Flexible layouts (CSS Grid, Flexbox)
- Responsive typography using clamp() with token values
### Component Mapping
- Coverage: ≥95% of design elements mapped to components
- Specificity: Props, state, and style sources documented
- Feasibility: No "impossible" designs without mitigation
- Documentation: Clear implementation guidance
## Collaboration with Other Agents
### Data Flow
```
conceptual-planning-agent (ui-designer role)
↓ Provides: analysis.md, synthesis-specification.md (design requirements)
ui-design-agent
↓ Generates: design-tokens.json, style-guide.md, prototypes
action-planning-agent
↓ Consumes: Design artifacts → creates implementation tasks
code-developer
↓ Implements: Features using design tokens and prototypes
```
### Input from conceptual-planning-agent
- `synthesis-specification.md`: Functional requirements, UX guidelines
- `ui-designer/analysis.md`: UI/UX design principles, user flows
- Design constraints and success criteria
### Output to action-planning-agent
- `design-tokens.json`: Referenced in task context.artifacts
- `style-guide.md`: Component patterns and usage guidelines
- `component_mapping.json`: Design-to-code mapping for task generation
- `implementation_plan.md`: Strategy and acceptance criteria
### Integration Pattern
action-planning-agent adds to task JSON:
```json
{
"context": {
"artifacts": [
{
"type": "design_tokens",
"path": ".design/style-consolidation/design-tokens.json"
},
{
"type": "style_guide",
"path": ".design/style-consolidation/style-guide.md"
}
]
},
"flow_control": {
"pre_analysis": [
{
"step": "load_design_tokens",
"action": "Load design system tokens",
"command": "Read(.design/style-consolidation/design-tokens.json)",
"output_to": "design_system_context"
}
]
}
}
```
## Observability & Metrics
### Per-Step Logging
```json
{
"step": "vision_analysis",
"provider": "gemini_vision",
"model": "gemini-1.5-pro",
"latency_ms": 2340,
"confidence": 0.87,
"errors": [],
"quality_gate_status": "pass"
}
```
### Quality Metrics
- Token coverage: `(tokens_used / total_values) * 100`
- Component mapping coverage: `(mapped_elements / total_elements) * 100`
- WCAG compliance: `(passing_combinations / total_combinations) * 100`
- Prototype validation: Percentage of CSS using custom properties
## Error Handling & Recovery
### Retry Strategy
- **Step failure**: Auto-retry up to 2 times
- **Provider failure**: Switch from Gemini → Codex (vision tasks)
- **Validation failure**: Flag errors, request human review or adjust parameters
### Degradation Modes
- **Low confidence vision analysis**: Flag uncertain elements for manual review
- **Incomplete token coverage**: Document gaps, suggest manual token additions
- **Mapping gaps**: Identify unmapped elements, request design simplification or custom components
### Human-in-the-Loop
- Low confidence items (< 0.7): Require manual confirmation
- WCAG violations: Cannot proceed without fix or documented exception
- Mapping gaps > 5%: Escalate to design review
## Version & Maintenance
**Version**: 1.0.0
**Last Updated**: 2025-10-05
**Changelog**:
- Initial agent definition
- Multi-modal vision provider integration (Gemini Vision, Codex -i)
- W3C Design Tokens compliance
- WCAG 2.1 AA quality gates
- Flow control specification for 3 design phases
Your role is to execute design tasks systematically through defined flow control steps, transforming visual concepts into production-ready design artifacts. Prioritize quality gates, accessibility compliance, and seamless handoff to implementation teams. Leverage multi-modal capabilities strategically: Gemini Vision for understanding, Codex for structured generation. Maintain observability and enable human review when confidence is low.

View File

@@ -14,188 +14,103 @@ 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. **Analysis only - does NOT modify code**.
**Intent**: Understand code patterns, architecture, and provide insights/recommendations
**Supported Tools**: codex, gemini (default), qwen
## Core Behavior
1. **Read-Only Analysis**: This command ONLY analyzes code and provides insights
2. **No Code Modification**: Results are recommendations and analysis reports
3. **Template-Based**: Automatically selects appropriate analysis template
4. **Smart Pattern Detection**: Infers relevant files based on analysis target
## 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 and `MODE: analysis`
5. Execute analysis (read-only, no code changes)
6. Return analysis report with insights and recommendations
## 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
For complex patterns, use `rg` or MCP tools to discover files first, then execute CLI with precise file references.
| 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` |
## Command Template
## 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
PURPOSE: [analysis goal from target]
TASK: [auto-detected analysis type]
MODE: analysis
CONTEXT: @{CLAUDE.md} [auto-detected file patterns]
EXPECTED: Insights, patterns, recommendations (NO code modification)
RULES: [auto-selected template] | Focus on [analysis aspect]
"
```
## 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
```
## Examples
**Pattern Analysis (Gemini - default)**:
**Basic Analysis**:
```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"
# Executes: Gemini analysis with auth file patterns
# Returns: Pattern analysis, architecture insights, recommendations
```
**Architecture Review (Qwen)**:
**Architecture Analysis**:
```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
"
/cli:analyze --tool qwen "component architecture"
# Executes: Qwen with component file patterns
# Returns: Architecture review, design patterns, improvement suggestions
```
**Deep Inspection (Codex)**:
**Performance Analysis**:
```bash
# User: /cli:analyze --tool codex "performance bottlenecks"
codex -C . --full-auto exec "
PURPOSE: Identify performance bottlenecks
TASK: Deep analysis of performance issues
CONTEXT: @{src/**/*} @{CLAUDE.md}
EXPECTED: Performance metrics and optimization recommendations
RULES: Focus on computational complexity and memory usage
" --skip-git-repo-check -s danger-full-access
/cli:analyze --tool codex "performance bottlenecks"
# Executes: Codex deep analysis with performance focus
# Returns: Bottleneck identification, optimization recommendations
```
## File Pattern Logic
**Enhanced Analysis**:
```bash
/cli:analyze --enhance "fix auth issues"
# Step 1: Enhance prompt to expand context
# Step 2: Analysis with expanded context
# Returns: Root cause analysis, fix recommendations (NO automatic fixes)
```
**Keyword Matching**:
- "auth" → `@{**/*auth*}`
- "component" → `@{src/components/**/*}`
- "API" → `@{**/api/**/*}`
- "test" → `@{**/*.test.*}`
- Generic → `@{src/**/*}` or `@{**/*}`
## Output Routing
## Session Integration
**Output Destination Logic**:
- **Active session exists AND analysis is session-relevant**:
- Save to `.workflow/WFS-[id]/.chat/analyze-[timestamp].md`
- **No active session OR one-off analysis**:
- Save to `.workflow/.scratchpad/analyze-[description]-[timestamp].md`
**Detect Active Session**: Check for `.workflow/.active-*` marker file
**Examples**:
- During active session `WFS-auth-system`, analyzing auth patterns → `.chat/analyze-20250105-143022.md`
- No session, quick security check → `.scratchpad/analyze-security-20250105-143045.md`
**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)
- Scratchpad directory details: see workflow-architecture.md
- Scratchpad files can be promoted to workflow sessions if analysis proves valuable

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,114 @@ 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. **Analysis only - does NOT modify code**.
- **`<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
**Intent**: Ask questions, get explanations, understand codebase structure
**Supported Tools**: codex, gemini (default), qwen
### 🔄 **Execution Workflow**
## Core Behavior
`Parse Tool` **->** `Parse Input` **->** `[Optional] Enhance` **->** `Assemble Context` **->** `Construct Prompt` **->** `Execute CLI Tool` **->** `(Optional) Save Session`
1. **Conversational Analysis**: Direct question-answer interaction about codebase
2. **Read-Only**: This command ONLY provides information and analysis
3. **No Code Modification**: Results are explanations and insights
4. **Flexible Context**: Choose specific files or entire codebase
### 🛠️ **Tool Selection**
## Parameters
| 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` |
- `<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
### 🔄 **Original Execution Workflow**
## Execution Flow
`Parse Input` **->** `[Optional] Enhance` **->** `Assemble Context` **->** `Construct Prompt` **->** `Execute Gemini CLI` **->** `(Optional) Save Session`
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 (read-only, analysis mode)
5. Return explanations and insights (NO code changes)
6. Optionally save to workflow session
### 🎯 **Enhancement Integration**
## Context Assembly
**When `--enhance` flag present**:
```bash
# Step 1: Enhance the inquiry
SlashCommand(command="/enhance-prompt \"[inquiry]\"")
**Always included**: `@{CLAUDE.md,**/*CLAUDE.md}` (project guidelines)
# Step 2: Use enhanced output for chat
# Enhanced output provides enriched context and structured intent
```
**Optional**:
- User-explicit files from inquiry keywords
- `--all-files` flag includes entire codebase (`--all-files` wrapper parameter)
**Example**:
```bash
# User: /gemini:chat --enhance "fix the login"
For targeted analysis, use `rg` or MCP tools to discover relevant files first, then build precise CONTEXT field.
# 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
## Command Template
# Step 2: Chat with enhanced context
gemini -p "Debug login authentication failure. Focus on JWT token validation
in src/auth/, verify middleware integration, and test authentication flow.
Known issue: session state management"
```
### 📚 **Context Assembly**
Context is gathered from:
1. **Project Guidelines**: Always includes `@{CLAUDE.md,**/*CLAUDE.md}`
2. **User-Explicit Files**: Files specified by the user (e.g., `@{src/auth/*.js}`)
3. **All Files Flag**: The `--all-files` flag includes the entire codebase
### 📝 **Prompt Format**
**Core Guidelines**: @~/.claude/workflows/intelligent-tools-strategy.md
```bash
cd [directory] && ~/.claude/scripts/gemini-wrapper -p "
PURPOSE: [clear analysis/inquiry goal]
TASK: [specific analysis or question]
CONTEXT: @{CLAUDE.md,**/*CLAUDE.md} @{target_files}
EXPECTED: [expected response format]
RULES: [constraints or focus areas]
"
```
### ⚙️ **Execution Implementation**
**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]
INQUIRY: [user question]
CONTEXT: @{CLAUDE.md,**/*CLAUDE.md} [inferred or --all-files]
MODE: analysis
RESPONSE: Direct answer, explanation, insights (NO code modification)
"
```
**With --all-files flag**:
## Examples
**Basic Question**:
```bash
cd . && ~/.claude/scripts/gemini-wrapper --all-files -p "
PURPOSE: [user inquiry goal]
TASK: [specific question or analysis]
CONTEXT: @{CLAUDE.md,**/*CLAUDE.md} [entire codebase]
EXPECTED: Comprehensive analysis across all files
RULES: [focus areas based on inquiry]
"
/cli:chat "analyze the authentication flow"
# Executes: Gemini analysis
# Returns: Explanation of auth flow, components involved, data flow
```
**Example - Authentication Analysis**:
**Architecture Question**:
```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
"
/cli:chat --tool qwen "how does React component optimization work here"
# Executes: Qwen architecture analysis
# Returns: Component structure explanation, optimization patterns used
```
**Example - Performance Optimization**:
**Security Analysis**:
```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
"
/cli:chat --tool codex "review security vulnerabilities"
# Executes: Codex security analysis
# Returns: Vulnerability assessment, security recommendations (NO automatic fixes)
```
### 💾 **Session Persistence**
**Enhanced Inquiry**:
```bash
/cli:chat --enhance "explain the login issue"
# Step 1: Enhance to expand login context
# Step 2: Analysis with expanded understanding
# Returns: Detailed explanation of login flow and potential issues
```
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
**Broad Context**:
```bash
/cli:chat --all-files "find all API endpoints"
# Executes: Analysis across entire codebase
# Returns: List and explanation of API endpoints (NO code generation)
```
**Session Template:**
```markdown
# Chat Session: [Timestamp]
## Output Routing
## Query
[Original user inquiry]
**Output Destination Logic**:
- **Active session exists AND query is session-relevant**:
- Save to `.workflow/WFS-[id]/.chat/chat-[timestamp].md`
- **No active session OR unrelated query**:
- Save to `.workflow/.scratchpad/chat-[description]-[timestamp].md`
## Context
[Files and patterns included in analysis]
**Examples**:
- During active session `WFS-api-refactor`, asking about API structure → `.chat/chat-20250105-143022.md`
- No session, asking about build process → `.scratchpad/chat-build-process-20250105-143045.md`
## Gemini Response
[Complete response from Gemini CLI]
```
## Notes
- Command templates and file patterns: see intelligent-tools-strategy.md (loaded in memory)
- Scratchpad directory details: see workflow-architecture.md
- Scratchpad conversations preserved for future reference

View File

@@ -0,0 +1,513 @@
---
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": [...]
}
```
## Output Routing
**Execution Log Destination**:
- **IF** active workflow session exists:
- Execution log: `.workflow/WFS-[id]/.chat/codex-execute-[timestamp].md`
- Task summaries: `.workflow/WFS-[id]/.summaries/[TASK-ID]-summary.md` (if task ID)
- Task updates: `.workflow/WFS-[id]/.task/[TASK-ID].json` status updates
- TodoWrite tracking: Embedded in execution log
- **ELSE** (no active session):
- **Recommended**: Create workflow session first (`/workflow:session:start`)
- **Alternative**: Save to `.workflow/.scratchpad/codex-execute-[description]-[timestamp].md`
**Output Files** (during execution):
```
.workflow/WFS-[session-id]/
├── .chat/
│ └── codex-execute-20250105-143022.md # Full execution log with task flow
├── .summaries/
│ ├── IMPL-001.1-summary.md # Subtask summaries
│ ├── IMPL-001.2-summary.md
│ └── IMPL-001-summary.md # Final task summary
└── .task/
├── IMPL-001.json # Updated task status
└── [subtask JSONs if decomposed]
```
**Examples**:
- During session `WFS-auth-system`, executing multi-stage auth implementation:
- Log: `.workflow/WFS-auth-system/.chat/codex-execute-20250105-143022.md`
- Summaries: `.workflow/WFS-auth-system/.summaries/IMPL-001.{1,2,3}-summary.md`
- Task status: `.workflow/WFS-auth-system/.task/IMPL-001.json` (status: completed)
- No session, ad-hoc multi-stage task:
- Log: `.workflow/.scratchpad/codex-execute-auth-refactor-20250105-143045.md`
**Save Results**:
- Execution log with task flow diagram and TodoWrite tracking
- Individual summaries for each completed subtask
- Final consolidated summary when all subtasks complete
- Modified code files throughout project
## 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.
**Output Details**:
- Output routing and scratchpad details: see workflow-architecture.md
- Session management: see intelligent-tools-strategy.md
- **⚠️ Code Modification**: This command performs multi-stage code modifications - execution log tracks all changes

View File

@@ -9,227 +9,177 @@ 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). **MODIFIES CODE**.
**Intent**: Autonomous code implementation, modification, and generation
**Supported Tools**: codex, gemini (default), qwen
**Key Feature**: Automatic context inference and file pattern detection
**Core Guidelines**: @~/.claude/workflows/intelligent-tools-strategy.md
## Core Behavior
## 🚨 YOLO Permissions
1. **Code Modification**: This command MODIFIES, CREATES, and DELETES code files
2. **Auto-Approval**: YOLO mode bypasses confirmation prompts for all operations
3. **Implementation Focus**: Executes actual code changes, not just recommendations
4. **Requires Explicit Intent**: Use only when implementation is intended
**All confirmations auto-approved by default:**
- ✅ File pattern inference confirmation
- ✅ Gemini execution confirmation
- ✅ File modification confirmation
- ✅ Implementation summary generation
## Core Concepts
## 🎯 Enhancement Integration
### YOLO Permissions
Auto-approves: file pattern inference, execution, **file modifications**, summary generation
**When `--enhance` flag present** (for Description Mode only):
**⚠️ WARNING**: This command will make actual code changes without manual confirmation
### Execution Modes
**1. Description Mode** (supports `--enhance`):
- Input: Natural language description
- Process: [Optional: Enhance] → Keyword analysis → Pattern inference → Execute
**2. Task ID Mode** (no `--enhance`):
- Input: Workflow task identifier (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 or save to scratchpad
**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
## Output Routing
**Execution Log Destination**:
- **IF** active workflow session exists:
- Save to `.workflow/WFS-[id]/.chat/execute-[timestamp].md`
- Update task status in `.task/[TASK-ID].json` (if task ID provided)
- Generate summary in `.workflow/WFS-[id]/.summaries/[TASK-ID]-summary.md`
- **ELSE** (no active session):
- **Option 1**: Create new workflow session for task
- **Option 2**: Save to `.workflow/.scratchpad/execute-[description]-[timestamp].md`
**Output Files** (when active session exists):
- Execution log: `.workflow/WFS-[id]/.chat/execute-[timestamp].md`
- Task summary: `.workflow/WFS-[id]/.summaries/[TASK-ID]-summary.md` (if task ID)
- Modified code: Project files per implementation
**Examples**:
- During session `WFS-auth-system`, executing `IMPL-001`:
- Log: `.workflow/WFS-auth-system/.chat/execute-20250105-143022.md`
- Summary: `.workflow/WFS-auth-system/.summaries/IMPL-001-summary.md`
- No session, ad-hoc implementation:
- Log: `.workflow/.scratchpad/execute-jwt-auth-20250105-143045.md`
## Command Template
### Task Integration
```bash
# Execute specific workflow task
/gemini:execute IMPL-001
# Loads from: .task/IMPL-001.json
# Uses: task context, brainstorming refs, scope definitions
# Updates: workflow status, generates summary
```
## Execution Templates
**Core Guidelines**: @~/.claude/workflows/intelligent-tools-strategy.md
### Permission Requirements
**Gemini Write Access** (when file modifications needed):
- Add `--approval-mode yolo` flag for auto-approval
- Required for: file creation, modification, deletion
### User Description Template
```bash
cd [target-directory] && ~/.claude/scripts/gemini-wrapper --approval-mode yolo -p "
PURPOSE: [clear implementation goal from description]
TASK: [specific implementation task]
CONTEXT: @{inferred_patterns} @{CLAUDE.md,**/*CLAUDE.md}
EXPECTED: Implementation code with file:line locations, test cases, integration guidance
RULES: [template reference if applicable] | [constraints]
"
```
**Example**:
```bash
# Gemini/Qwen: MODE=write with --approval-mode yolo
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
PURPOSE: [implementation goal]
TASK: [specific implementation]
MODE: write
CONTEXT: @{CLAUDE.md} [auto-detected files]
EXPECTED: Working implementation with code changes
RULES: [constraints] | Auto-approve all changes
"
# Codex: MODE=auto with danger-full-access
codex -C . --full-auto exec "
PURPOSE: [implementation goal]
TASK: [specific implementation]
MODE: auto
CONTEXT: [auto-detected files]
EXPECTED: Complete implementation with tests
" --skip-git-repo-check -s danger-full-access
```
### Task ID Template
## Examples
**Basic Implementation** (⚠️ modifies code):
```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]
"
/cli:execute "implement JWT authentication with middleware"
# Executes: Creates auth middleware, updates routes, modifies config
# Result: NEW/MODIFIED code files with JWT implementation
```
**Example**:
**Enhanced Implementation** (⚠️ modifies code):
```bash
cd .workflow/WFS-123 && ~/.claude/scripts/gemini-wrapper --approval-mode yolo -p "
PURPOSE: Implement user profile editing
TASK: Execute IMPL-001 implementation
CONTEXT: @{src/user/**/*} @{.brainstorming/product-owner/analysis.md} @{CLAUDE.md}
EXPECTED: Profile edit API, UI components, validation, tests
RULES: $(cat ~/.claude/workflows/cli-templates/prompts/development/feature.txt) | Type: feature, Scope: user module
"
/cli:execute --enhance "implement JWT authentication"
# Step 1: Enhance to expand requirements
# Step 2: Execute implementation with auto-approval
# Result: Complete auth system with MODIFIED code files
```
## 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]
**Task Execution** (⚠️ modifies code):
```bash
/cli:execute IMPL-001
# Reads: .task/IMPL-001.json for requirements
# Executes: Implementation based on task spec
# Result: Code changes per task definition
```
### 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]
**Codex Implementation** (⚠️ modifies code):
```bash
/cli:execute --tool codex "optimize database queries"
# Executes: Codex with full file access
# Result: MODIFIED query code, new indexes, updated tests
```
## Error Handling
**Qwen Code Generation** (⚠️ modifies code):
```bash
/cli:execute --tool qwen --enhance "refactor auth module"
# Step 1: Enhanced refactoring plan
# Step 2: Execute with MODE=write
# Result: REFACTORED auth code with structural changes
```
- **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
## Comparison with Analysis Commands
## Performance Features
| Command | Intent | Code Changes | Auto-Approve |
|---------|--------|--------------|--------------|
| `/cli:analyze` | Understand code | ❌ NO | N/A |
| `/cli:chat` | Ask questions | ❌ NO | N/A |
| `/cli:execute` | **Implement** | ✅ **YES** | ✅ **YES** |
- **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)
- Output routing and scratchpad details: see workflow-architecture.md
- **⚠️ Code Modification**: This command modifies code - execution logs document changes made

View File

@@ -8,16 +8,23 @@ 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
@@ -26,26 +33,33 @@ Execute systematic bug analysis and fix suggestions using CLI tools with diagnos
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)
6. Execute analysis (read-only, provides fix recommendations)
7. Save to `.workflow/WFS-[id]/.chat/bug-index-[timestamp].md`
## Core Rules
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`
1. **Analysis Only**: This command analyzes bugs and suggests fixes - it does NOT modify code
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 bug-fix template
5. **Session Output**: Save analysis results and fix recommendations to session chat
## Analysis Focus (via Template)
- Root cause investigation and diagnosis
- Code path tracing to locate issues
- Targeted minimal fix recommendations
- Impact assessment of proposed changes
## 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
MODE: analysis
CONTEXT: @{CLAUDE.md,**/*CLAUDE.md} [entire codebase in directory]
EXPECTED: Root cause analysis, code path tracing, targeted fixes
EXPECTED: Root cause analysis, code path tracing, targeted fix suggestions
RULES: $(cat ~/.claude/prompt-templates/bug-fix.md) | Bug: [description]
"
```
@@ -56,9 +70,10 @@ RULES: $(cat ~/.claude/prompt-templates/bug-fix.md) | Bug: [description]
```bash
cd . && ~/.claude/scripts/gemini-wrapper --all-files -p "
PURPOSE: Debug authentication null pointer error
TASK: Identify root cause and provide fix
TASK: Identify root cause and provide fix recommendations
MODE: analysis
CONTEXT: @{CLAUDE.md,**/*CLAUDE.md}
EXPECTED: Root cause, code path, minimal fix, impact assessment
EXPECTED: Root cause, code path, minimal fix suggestion, impact assessment
RULES: $(cat ~/.claude/prompt-templates/bug-fix.md) | Bug: null pointer in login flow
"
```
@@ -68,47 +83,39 @@ RULES: $(cat ~/.claude/prompt-templates/bug-fix.md) | Bug: null pointer in login
cd src/auth && ~/.claude/scripts/gemini-wrapper --all-files -p "
PURPOSE: Fix token validation failure
TASK: Analyze token validation bug in auth module
MODE: analysis
CONTEXT: @{CLAUDE.md,**/*CLAUDE.md}
EXPECTED: Validation logic analysis, fix recommendation
EXPECTED: Validation logic analysis, fix recommendation with minimal changes
RULES: $(cat ~/.claude/prompt-templates/bug-fix.md) | Bug: token validation fails intermittently
"
```
**With Enhancement**:
## Bug Investigation Workflow
```bash
# User: /gemini:mode:bug-index --enhance "login broken"
# 1. Find bug-related files
rg "error_keyword" --files-with-matches
mcp__code-index__search_code_advanced(pattern="error|exception", file_pattern="*.ts")
# 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
"
# 2. Execute bug analysis with focused context (analysis only, no code changes)
/cli:mode:bug-index --cd "src/module" "specific error description"
```
## Analysis Focus
## Output Routing
**Template provides**:
- **Root Cause Analysis**: Systematic investigation
- **Code Path Tracing**: Execution flow analysis
- **Targeted Solutions**: Minimal, specific fixes
- **Impact Assessment**: Side effect evaluation
**Output Destination Logic**:
- **Active session exists AND bug is session-relevant**:
- Save to `.workflow/WFS-[id]/.chat/bug-index-[timestamp].md`
- **No active session OR quick debugging**:
- Save to `.workflow/.scratchpad/bug-index-[description]-[timestamp].md`
## Session Output
**Examples**:
- During active session `WFS-payment-fix`, analyzing payment bug → `.chat/bug-index-20250105-143022.md`
- No session, quick null pointer investigation → `.scratchpad/bug-index-null-pointer-20250105-143045.md`
**Location**: `.workflow/WFS-[topic]/.chat/bug-index-[timestamp].md`
## Notes
**Includes**:
- Bug description
- Template used
- Analysis results
- Recommended actions
- Command templates and file patterns: see intelligent-tools-strategy.md (loaded in memory)
- Scratchpad directory details: see workflow-architecture.md
- Template path: `~/.claude/prompt-templates/bug-fix.md`
- Always uses `--all-files` for comprehensive codebase context

View File

@@ -8,16 +8,23 @@ 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
@@ -26,20 +33,20 @@ Execute systematic code analysis and debugging using CLI tools with specialized
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)
6. Execute deep analysis (read-only, no code modification)
7. Save to `.workflow/WFS-[id]/.chat/code-analysis-[timestamp].md`
## Core Rules
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`
1. **Analysis Only**: This command analyzes code and provides insights - it does NOT modify code
2. **Tool Selection**: Use `--tool` value or default to gemini
3. **Enhance First (if flagged)**: Execute `/enhance-prompt` before analysis
4. **Directory Context**: Use `cd` when `--cd` provided or auto-detected
5. **Template Required**: Always use code-analysis template
6. **Session Output**: Save analysis results to session chat
## Analysis Capabilities
## Analysis Capabilities (via Template)
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
@@ -47,158 +54,74 @@ The code-analysis template provides:
- **Logical Reasoning**: Explain "why" behind code behavior
- **Debugging Insights**: Identify potential bugs or inefficiencies
## Command Templates
## Command Template
**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
PURPOSE: [analysis goal]
TASK: Systematic code analysis and execution path tracing
MODE: analysis
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]
EXPECTED: Execution trace, call flow diagram, debugging insights
RULES: $(cat ~/.claude/prompt-templates/code-analysis.md) | Focus on [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
```
## Examples
**Basic Code Analysis (Gemini)**:
**Basic Code Analysis**:
```bash
cd . && ~/.claude/scripts/gemini-wrapper --all-files -p "
PURPOSE: Analyze authentication flow logic
TASK: Trace authentication execution path and identify key functions
PURPOSE: Trace authentication execution flow
TASK: Analyze complete auth flow from request to response
MODE: analysis
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
EXPECTED: Step-by-step execution trace with call diagram, variable states
RULES: $(cat ~/.claude/prompt-templates/code-analysis.md) | Focus on control flow
"
```
**Architecture Analysis (Qwen)**:
**Directory-Specific Analysis**:
```bash
# User: /cli:mode:code-analysis --tool qwen "explain data transformation pipeline"
cd . && ~/.claude/scripts/qwen-wrapper --all-files -p "
PURPOSE: Explain data transformation pipeline architecture
TASK: Analyze data flow and transformation patterns
cd src/auth && ~/.claude/scripts/gemini-wrapper --all-files -p "
PURPOSE: Understand JWT token validation logic
TASK: Trace JWT validation from middleware to service layer
MODE: analysis
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
EXPECTED: Validation flow diagram, token lifecycle analysis
RULES: $(cat ~/.claude/prompt-templates/code-analysis.md) | Focus on security
"
```
**Deep Debugging (Codex)**:
```bash
# User: /cli:mode:code-analysis --tool codex --cd "src/core" "trace execution path for user registration"
## Code Tracing Workflow
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
```bash
# 1. Find entry points and related files
rg "function.*authenticate|class.*AuthService" --files-with-matches
mcp__code-index__search_code_advanced(pattern="authenticate|login", file_pattern="*.ts")
# 2. Build call graph understanding
# entry → middleware → service → repository
# 3. Execute deep analysis (analysis only, no code changes)
/cli:mode:code-analysis --cd "src" "trace execution from entry point"
```
**With Enhancement**:
```bash
# User: /cli:mode:code-analysis --enhance "why is login slow"
## Output Routing
# 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
**Output Destination Logic**:
- **Active session exists AND analysis is session-relevant**:
- Save to `.workflow/WFS-[id]/.chat/code-analysis-[timestamp].md`
- **No active session OR standalone analysis**:
- Save to `.workflow/.scratchpad/code-analysis-[description]-[timestamp].md`
# 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
"
```
**Examples**:
- During active session `WFS-auth-refactor`, analyzing auth flow → `.chat/code-analysis-20250105-143022.md`
- No session, tracing request lifecycle → `.scratchpad/code-analysis-request-flow-20250105-143045.md`
## Analysis Output Structure
## Notes
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)
- Scratchpad directory details: see workflow-architecture.md
- Template path: `~/.claude/prompt-templates/code-analysis.md`
- Always uses `--all-files` for comprehensive code context

View File

@@ -8,16 +8,23 @@ 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
@@ -26,79 +33,93 @@ Execute planning and architecture analysis using CLI tools with specialized temp
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)
6. Execute analysis (read-only, no code modification)
7. Save to `.workflow/WFS-[id]/.chat/plan-[timestamp].md`
## Core Rules
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`
1. **Analysis Only**: This command provides planning recommendations and insights - it does NOT modify code
2. **Enhance First (if flagged)**: Execute `/enhance-prompt` before planning
3. **Directory Context**: Use `cd` when `--cd` provided or auto-detected
4. **Template Required**: Always use planning template
5. **Session Output**: Save analysis results to session chat
## Planning Capabilities (via Template)
- Strategic architecture insights and recommendations
- Implementation roadmaps and suggestions
- Key technical decisions analysis
- Risk assessment
- Resource planning
## 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
MODE: analysis
CONTEXT: @{CLAUDE.md,**/*CLAUDE.md} [entire codebase in directory]
EXPECTED: Strategic insights, implementation roadmap, key decisions
EXPECTED: Strategic insights, implementation recommendations, key decisions
RULES: $(cat ~/.claude/prompt-templates/plan.md) | Focus on [topic area]
"
```
## Examples
**Basic Planning**:
**Basic Planning Analysis**:
```bash
cd . && ~/.claude/scripts/gemini-wrapper --all-files -p "
PURPOSE: Design user dashboard feature architecture
TASK: Comprehensive architecture planning for dashboard
PURPOSE: Design user dashboard architecture
TASK: Plan dashboard component structure and data flow
MODE: analysis
CONTEXT: @{CLAUDE.md,**/*CLAUDE.md}
EXPECTED: Architecture design, component structure, implementation roadmap
RULES: $(cat ~/.claude/prompt-templates/plan.md) | Focus on scalability and UX
EXPECTED: Architecture recommendations, component design, data flow diagram
RULES: $(cat ~/.claude/prompt-templates/plan.md) | Focus on scalability
"
```
**Directory-Specific**:
**Directory-Specific Planning**:
```bash
cd src/auth && ~/.claude/scripts/gemini-wrapper --all-files -p "
PURPOSE: Plan authentication system redesign
TASK: Analyze current auth and plan improvements
cd src/api && ~/.claude/scripts/gemini-wrapper --all-files -p "
PURPOSE: Plan API refactoring strategy
TASK: Analyze current API structure and recommend improvements
MODE: analysis
CONTEXT: @{CLAUDE.md,**/*CLAUDE.md}
EXPECTED: Migration strategy, security improvements, timeline
RULES: $(cat ~/.claude/prompt-templates/plan.md) | Focus on security and backward compatibility
EXPECTED: Refactoring roadmap, breaking change analysis, migration plan
RULES: $(cat ~/.claude/prompt-templates/plan.md) | Maintain backward compatibility
"
```
**With Enhancement**:
## Planning Workflow
```bash
# User: /gemini:mode:plan --enhance "fix auth issues"
# 1. Discover project structure
~/.claude/scripts/get_modules_by_depth.sh
mcp__code-index__find_files(pattern="*.ts")
# Step 1: Enhance
/enhance-prompt "fix auth issues"
# Returns structured planning context
# 2. Gather existing architecture info
rg "architecture|design" --files-with-matches
# 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]
"
# 3. Execute planning analysis (analysis only, no code changes)
/cli:mode:plan "topic for strategic planning"
```
## Session Output
## Output Routing
**Location**: `.workflow/WFS-[topic]/.chat/plan-[timestamp].md`
**Output Destination Logic**:
- **Active session exists AND planning is session-relevant**:
- Save to `.workflow/WFS-[id]/.chat/plan-[timestamp].md`
- **No active session OR exploratory planning**:
- Save to `.workflow/.scratchpad/plan-[description]-[timestamp].md`
**Includes**:
- Planning topic
- Template used
- Analysis results
- Implementation roadmap
- Key decisions
**Examples**:
- During active session `WFS-dashboard`, planning dashboard architecture → `.chat/plan-20250105-143022.md`
- No session, exploring new feature idea → `.scratchpad/plan-feature-idea-20250105-143045.md`
## Notes
- Command templates and file patterns: see intelligent-tools-strategy.md (loaded in memory)
- Scratchpad directory details: see workflow-architecture.md
- Template path: `~/.claude/prompt-templates/plan.md`
- Always uses `--all-files` for comprehensive project context

View File

@@ -1,40 +1,55 @@
---
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:
# IF (module_count > 20 OR complex_project_detected):
# → Task "Complex project full update" subagent_type: "memory-gemini-bridge"
# → Task "Complex project full update" subagent_type: "memory-bridge"
# ELSE:
# → Present plan and WAIT FOR USER APPROVAL before execution
#
# Pass tool parameter to update_module_claude.sh: "$tool"
```
### 🧠 Model Analysis Phase
@@ -43,9 +58,9 @@ 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
- Complex projects: Delegate to memory-bridge agent
4. **Present Detailed Plan**: Show user exactly which CLAUDE.md files will be created/updated
5. **⚠️ CRITICAL: WAIT FOR USER APPROVAL**: No execution without explicit user consent
@@ -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-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"
subagent_type: "memory-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,30 +25,37 @@ 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:
# IF (change_count > 15 OR complex_changes_detected):
# → Task "Complex project related update" subagent_type: "memory-gemini-bridge"
# → Task "Complex project related update" subagent_type: "memory-bridge"
# ELSE:
# → Present plan and WAIT FOR USER APPROVAL before execution
#
# Pass tool parameter to update_module_claude.sh: "$tool"
```
### 🧠 Model Analysis Phase
@@ -51,7 +66,7 @@ After the bash script completes change detection, the model takes control to:
2. **Parse CLAUDE.md Status**: Extract which changed modules have/need CLAUDE.md files
3. **Choose Strategy**:
- Simple changes: Present execution plan with CLAUDE.md paths to user
- Complex changes: Delegate to memory-gemini-bridge agent
- Complex changes: Delegate to memory-bridge agent
4. **Present Detailed Plan**: Show user exactly which CLAUDE.md files will be created/updated for changed modules
5. **⚠️ CRITICAL: WAIT FOR USER APPROVAL**: No execution without explicit user consent
@@ -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-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"
subagent_type: "memory-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

View File

@@ -170,8 +170,8 @@ Bash: bash <(curl -fsSL https://raw.githubusercontent.com/catlog22/Claude-Code-W
**Scenario 3: Development version**
```
✨ You are running a development version (3.3.0-dev)
This is newer than the latest stable release (v3.2.2)
✨ You are running a development version (3.4.0-dev)
This is newer than the latest stable release (v3.3.0)
```
## Simple Bash Commands

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

@@ -0,0 +1,380 @@
---
name: auto
description: Orchestrate UI design refinement workflow with interactive checkpoints for user selection
usage: /workflow:design:auto --session <session_id> --images "<glob>" --pages "<list>" [--variants <count>] [--batch-plan]
argument-hint: "--session WFS-session-id --images \"refs/*.png\" --pages \"dashboard,auth\" [--variants 2] [--batch-plan]"
examples:
- /workflow:design:auto --session WFS-auth --images "design-refs/*.png" --pages "login,register"
- /workflow:design:auto --session WFS-dashboard --images "refs/*.jpg" --pages "dashboard" --variants 3 --batch-plan
allowed-tools: SlashCommand(*), TodoWrite(*), Read(*), Bash(*), Glob(*)
---
# UI Design Auto Workflow Command
## Overview
Semi-autonomous UI design workflow with interactive checkpoints: style extraction → **user selection** → consolidation → UI generation → **user confirmation** → design update → optional batch planning.
## Coordinator Role
**Checkpoint-based orchestrator**: Execute Phase 1 automatically, pause for user style selection, execute Phase 3, pause for user prototype confirmation, complete with optional batch task generation.
## Execution Model - Checkpoint Workflow
This workflow runs **semi-autonomously** with user checkpoints:
1. **User triggers**: `/workflow:design:auto --session WFS-xxx --images "refs/*.png" --pages "dashboard,auth" [--batch-plan]`
2. **Phase 1 executes** (style-extract) → Reports style cards → **⏸️ PAUSE FOR USER SELECTION**
3. **User selects variants** → Runs `style-consolidate --variants "..."` → Auto-continues
4. **Phase 3 executes** (ui-generate) → Reports prototypes → **⏸️ PAUSE FOR USER CONFIRMATION**
5. **User confirms prototypes** → Runs `design-update --selected-prototypes "..."` → Auto-continues
6. **Phase 5 executes** (batch-plan, optional) → Reports task files
**Checkpoint Mechanism**:
- TodoWrite tracks current phase with "awaiting_user_confirmation" status
- System reports output location and exact command for next step
- User runs provided command to continue workflow
- Workflow resumes automatically after user input
## Core Rules
1. **Start Immediately**: First action is TodoWrite initialization, second action is Phase 1 command execution
2. **No Preliminary Analysis**: Do not read files or validate before Phase 1 (commands handle their own validation)
3. **Parse Every Output**: Extract required data from each command's output for next phase
4. **Pause at Checkpoints**: After Phase 1 and Phase 3, pause and prompt user with exact command to continue
5. **User-Driven Continuation**: Workflow resumes when user runs style-consolidate or design-update commands
6. **Track Progress**: Update TodoWrite after every phase completion and checkpoint
## Parameter Requirements
**Required Parameters**:
- `--session <session_id>`: Active workflow session ID
- `--images "<glob_pattern>"`: Reference image paths for style extraction
- `--pages "<page_list>"`: Comma-separated list of pages to generate
**Optional Parameters**:
- `--variants <count>`: Number of UI variants per page (default: 1)
- `--batch-plan`: Auto-generate implementation tasks for selected prototypes after design-update
## 5-Phase Execution
### Phase 1: Style Extraction
**Command**: `SlashCommand(command="/workflow:design:style-extract --session {session_id} --images \"{image_glob}\"")`
**Parse Output**:
- Verify: `.design/style-extraction/style-cards.json` created
- Extract: `style_cards_count` from output message
- List available style variant IDs
**Validation**:
- Style cards successfully generated
- At least one style variant available
**TodoWrite**: Mark phase 1 completed, mark checkpoint "awaiting_user_confirmation"
**⏸️ CHECKPOINT 1: Pause for User Style Selection**
```
Phase 1 Complete: Style Extraction
Style cards generated: {count}
Available variants: {variant_ids}
Location: .workflow/WFS-{session}/.design/style-extraction/
⏸️ USER SELECTION REQUIRED
Review style cards and select your preferred variants.
Then run:
/workflow:design:style-consolidate --session WFS-{session} --variants "{variant_ids}"
Example: /workflow:design:style-consolidate --session WFS-{session} --variants "variant-1,variant-3"
```
---
### Phase 2: Style Consolidation (User-Triggered)
**User Command**: `/workflow:design:style-consolidate --session {session_id} --variants "{selected_variants}"`
**After user runs command**:
- Workflow automatically continues to Phase 3
- Parse output: token_count, validation_status
**TodoWrite**: Mark phase 2 completed, phase 3 in_progress
**Output**:
```
Phase 2 Complete: Style Consolidation
Design tokens: {count}
Validation: {pass|warnings}
Location: .workflow/WFS-{session}/.design/style-consolidation/
Continuing to Phase 3: UI Generation...
```
---
### Phase 3: UI Generation (Auto-Triggered after Phase 2)
**Command Construction**:
```bash
variants_flag = --variants present ? "--variants {variants_count}" : ""
command = "/workflow:design:ui-generate --session {session_id} --pages \"{page_list}\" {variants_flag}"
```
**Command**: `SlashCommand(command="{constructed_command}")`
**Parse Output**:
- Verify: `.design/prototypes/*.html` files created
- Extract: `prototype_count`, `page_list`, `generated_files` list
**Validation**:
- All requested pages generated
- HTML and CSS files present for each variant
**TodoWrite**: Mark phase 3 completed, mark checkpoint "awaiting_user_confirmation"
**⏸️ CHECKPOINT 2: Pause for User Prototype Confirmation**
```
Phase 3 Complete: UI Generation
Prototypes generated: {count} ({page_list})
Generated files: {file_list}
Location: .workflow/WFS-{session}/.design/prototypes/
⏸️ USER CONFIRMATION REQUIRED
Review the generated prototypes and select your preferred variants.
Then run:
/workflow:design:design-update --session WFS-{session} --selected-prototypes "{prototype_ids}"
Example: /workflow:design:design-update --session WFS-{session} --selected-prototypes "dashboard-variant-1,auth-variant-2"
Or to use all generated prototypes:
/workflow:design:design-update --session WFS-{session}
```
---
### Phase 4: Design System Integration (User-Triggered)
**User Command**: `/workflow:design:design-update --session {session_id} [--selected-prototypes "{selected_prototypes}"]`
**After user runs command**:
- Workflow updates brainstorming artifacts
- If --batch-plan flag present, automatically continues to Phase 5
**Parse Output**:
- Verify: `synthesis-specification.md` updated
- Verify: `ui-designer/style-guide.md` created/updated
**TodoWrite**: Mark phase 4 completed
**Output** (if --batch-plan NOT present):
```
UI Design Refinement Complete for session: WFS-{session}
Design System Summary:
- Tokens: {token_count} (OKLCH-based)
- Prototypes: {prototype_count} ({page_list})
- Validation: {pass|warnings}
Updated Artifacts:
✓ synthesis-specification.md (UI/UX Guidelines section)
✓ ui-designer/style-guide.md (comprehensive style guide)
✓ Design tokens ready for task generation
Location: .workflow/WFS-{session}/.design/
Next Steps:
1. Review prototypes: .workflow/WFS-{session}/.design/prototypes/
2. Continue to planning: /workflow:plan [--agent] "<task description>"
(The plan phase will automatically discover and utilize the design system)
```
**Output** (if --batch-plan present):
```
Phase 4 Complete: Design System Integration
Updated Artifacts:
✓ synthesis-specification.md
✓ ui-designer/style-guide.md
Continuing to Phase 5: Batch Task Generation...
```
---
### Phase 5: Batch Task Generation (Optional, Auto-Triggered if --batch-plan)
**Condition**: Only executes if `--batch-plan` flag present
**Execution**:
```bash
FOR each page IN selected_prototypes_pages:
SlashCommand(command="/workflow:plan --agent \"Implement {page} page based on design system\"")
# Parse output task file location
task_files.add(output_location)
```
**TodoWrite**: Mark phase 5 completed
**Return to User**:
```
Phase 5 Complete: Batch Task Generation
Tasks generated for: {page_count} pages
Generated task files:
{task_file_list}
Design workflow complete for session: WFS-{session}
Next: /workflow:execute
```
## TodoWrite Pattern
```javascript
// Initialize (before Phase 1)
TodoWrite({todos: [
{"content": "Execute style extraction from reference images", "status": "in_progress", "activeForm": "Executing style extraction"},
{"content": "Execute style consolidation and token validation", "status": "pending", "activeForm": "Executing style consolidation"},
{"content": "Execute UI prototype generation", "status": "pending", "activeForm": "Executing UI generation"},
{"content": "Execute design system integration to brainstorming", "status": "pending", "activeForm": "Executing design system integration"}
]})
// After Phase 1
TodoWrite({todos: [
{"content": "Execute style extraction from reference images", "status": "completed", "activeForm": "Executing style extraction"},
{"content": "Execute style consolidation and token validation", "status": "in_progress", "activeForm": "Executing style consolidation"},
{"content": "Execute UI prototype generation", "status": "pending", "activeForm": "Executing UI generation"},
{"content": "Execute design system integration to brainstorming", "status": "pending", "activeForm": "Executing design system integration"}
]})
// Continue pattern for Phase 2, 3, 4...
```
## Parameter Processing
### Session Validation
```bash
# Verify active session
CHECK: .workflow/.active-* marker files
VERIFY: session_id parameter matches active session
IF mismatch:
ERROR: "Session {session_id} is not active. Active session: {active_session_id}"
```
### Image Glob Expansion
```bash
# Expand glob pattern
expanded_paths = bash(ls {image_glob})
IF no files found:
ERROR: "No images found matching pattern: {image_glob}"
VALIDATE: All files are image formats (.png, .jpg, .jpeg, .webp)
```
### Page List Parsing
```bash
# Parse comma-separated page list
pages = split(page_list, ",")
TRIM: whitespace from each page name
VALIDATE: page_list not empty
```
## Data Flow
```
User Input
├── session_id
├── image_glob → expanded_image_paths
├── page_list → parsed_pages[]
├── --interactive → interactive_mode (bool)
└── --variants → variants_count (int)
Phase 1: style-extract
Input: session_id, expanded_image_paths
Output: style-cards.json
Phase 2: style-consolidate
Input: session_id, interactive_mode | auto-select
Output: design-tokens.json, style-guide.md, tailwind.config.js
Phase 3: ui-generate
Input: session_id, parsed_pages[], variants_count
Output: {page}-variant-{n}.html/css for each page
Phase 4: design-update
Input: session_id
Output: Updated synthesis-specification.md, ui-designer/style-guide.md
Return summary to user
```
## Error Handling
**Phase Execution Failures**:
- **Keep phase `in_progress`**: Do not proceed to next phase
- **Report error to user**: Include specific failure message from command
- **Provide recovery instructions**: Suggest manual command execution with corrected parameters
**Common Errors**:
1. **Session not found**: Verify session exists and is active
2. **No images found**: Check image glob pattern and file paths
3. **Style extraction failed**: Retry with different images or manual style description
4. **Consolidation validation errors**: Review validation-report.json and address token issues
5. **UI generation failed**: Check synthesis-specification.md for requirements clarity
6. **Integration conflicts**: Review synthesis-specification.md edit conflicts
## Workflow Position
**In Complete Development Flow**:
```
/workflow:brainstorm:auto-parallel "{topic}"
↓ Generates synthesis-specification.md (WHAT)
/workflow:design:auto --session WFS-xxx --images "refs/*.png" --pages "dashboard,auth"
↓ Refines visual design (WHAT → Visual Spec)
/workflow:plan [--agent] "{task description}"
↓ Generates task breakdown (HOW)
/workflow:execute
↓ Implements tasks with design system
```
**Key Benefits**:
1. **Visual Validation**: Users confirm design before implementation
2. **Token Enforcement**: Implementation strictly follows design system
3. **Accessibility**: WCAG AA validated at design phase
4. **Consistency**: Single source of truth for visual design
## Coordinator Checklist
✅ Initialize TodoWrite before any command execution
✅ Validate session parameter before Phase 1
✅ Expand image glob to concrete paths
✅ Parse page list to array
✅ Execute Phase 1 immediately (no preliminary analysis)
✅ Parse style card count from Phase 1 output
✅ Construct Phase 2 command based on --interactive flag
✅ Parse token count and validation status from Phase 2
✅ Construct Phase 3 command with variants parameter
✅ Parse prototype count from Phase 3 output
✅ Execute Phase 4 design system integration
✅ Verify all artifacts updated successfully
✅ Update TodoWrite after each phase
✅ After each phase, automatically continue to next phase based on TodoWrite status
## Integration Notes
**Seamless Workflow Transition**:
- Design phase is **optional but recommended** for UI-heavy projects
- Can be skipped entirely if visual design is not critical
- Brainstorming → Plan flow still works without design phase
- Design artifacts automatically discovered by task-generate if present
**Use Cases**:
- **Use design workflow**: User-facing applications, design systems, brand-critical UIs
- **Skip design workflow**: Backend APIs, CLI tools, prototypes, MVPs
**Artifact Discovery**:
- `task-generate` automatically detects `.design/` directory
- If present, adds design system to task context.artifacts
- UI tasks automatically include `load_design_tokens` in flow_control
This design ensures backward compatibility while enabling powerful visual design workflows when needed.

View File

@@ -0,0 +1,348 @@
---
name: design-update
description: Update brainstorming artifacts with finalized design system
usage: /workflow:design:design-update --session <session_id> [--selected-prototypes "<list>"]
argument-hint: "--session WFS-session-id [--selected-prototypes \"dashboard-variant-1,auth-variant-2\"]"
examples:
- /workflow:design:design-update --session WFS-auth
- /workflow:design:design-update --session WFS-dashboard --selected-prototypes "dashboard-variant-1"
allowed-tools: Read(*), Write(*), TodoWrite(*), Glob(*), Bash(*)
---
# Design Update Command
## Overview
Synchronize finalized design system (tokens, style guide, selected prototypes) back to brainstorming artifacts, preparing for `/workflow:plan` phase consumption.
## Core Philosophy
- **Main Claude Execution**: Direct updates by main Claude (avoid Agent context loss, following synthesis pattern)
- **Reference-Based Integration**: Use @ references, not content duplication
- **Synthesis Alignment**: Update synthesis-specification.md UI/UX Guidelines section
- **UI Designer Sync**: Mirror design system to ui-designer/style-guide.md
- **Plan-Ready Output**: Ensure design artifacts discoverable by task-generate
## Execution Protocol
### Phase 1: Session & Design System Validation
```bash
# Validate session and verify design system completeness
CHECK: .workflow/.active-* marker files
VALIDATE: session_id matches active session
VERIFY required artifacts:
- .design/style-consolidation/design-tokens.json
- .design/style-consolidation/style-guide.md
- .design/style-consolidation/tailwind.config.js
- .design/prototypes/*.html (at least one prototype)
IF --selected-prototypes provided:
VALIDATE: Specified prototypes exist
ELSE:
AUTO-SELECT: Use all generated prototypes
```
### Phase 2: Load Design System Context
**Direct Claude Code Execution** (no Agent invocation)
```bash
# Load all design system artifacts
Read(.workflow/WFS-{session}/.design/style-consolidation/design-tokens.json)
Read(.workflow/WFS-{session}/.design/style-consolidation/style-guide.md)
Read(.workflow/WFS-{session}/.design/style-consolidation/style-philosophy.md)
Read(.workflow/WFS-{session}/.design/style-consolidation/tailwind.config.js)
# Load selected prototype files
FOR each selected_prototype IN selected_prototypes:
Read(.workflow/WFS-{session}/.design/prototypes/{selected_prototype}.html)
Read(.workflow/WFS-{session}/.design/prototypes/{selected_prototype}-notes.md)
# Load target brainstorming artifacts
Read(.workflow/WFS-{session}/.brainstorming/synthesis-specification.md)
Read(.workflow/WFS-{session}/.brainstorming/ui-designer/analysis.md) [if exists]
```
### Phase 3: Update Synthesis Specification
**Direct Write by Main Claude**
Update `.brainstorming/synthesis-specification.md`:
```markdown
## UI/UX Guidelines
### Design System Reference
**Finalized Design Tokens**: @../.design/style-consolidation/design-tokens.json
**Style Guide**: @../.design/style-consolidation/style-guide.md
**Tailwind Configuration**: @../.design/style-consolidation/tailwind.config.js
### Design Philosophy
[Insert content from style-philosophy.md]
### Token System Overview
**Colors**: OKLCH-based color system with semantic naming
- Brand: primary, secondary, accent
- Surface: background, elevated, sunken
- Semantic: success, warning, error, info
**Typography**: {font_family_count} font families, {scale_count}-step scale
- Heading: {heading_font}
- Body: {body_font}
- Monospace: {mono_font}
**Spacing**: {scale_count}-step scale ({min}rem to {max}rem)
**Components**: Border radius, shadows, and component tokens defined
### Implementation Requirements
**Token Adherence**: All UI implementations MUST use design token CSS custom properties
**Accessibility**: WCAG AA compliance validated in design-tokens.json
**Responsive**: Mobile-first design using token-based breakpoints
**Component Patterns**: Follow patterns documented in style-guide.md
### Reference Prototypes
[For each selected prototype:]
- **{page_name}**: @../.design/prototypes/{prototype}.html
- Layout: {layout_description from notes}
- Components: {component_list from notes}
- Token Usage: {token_usage_summary from notes}
### Design System Assets (for task-generate consumption)
```json
{
"design_tokens": ".design/style-consolidation/design-tokens.json",
"style_guide": ".design/style-consolidation/style-guide.md",
"tailwind_config": ".design/style-consolidation/tailwind.config.js",
"prototypes": [
".design/prototypes/{prototype-1}.html",
".design/prototypes/{prototype-2}.html"
]
}
```
```
**Implementation**:
```bash
# Edit synthesis-specification.md
Edit(
file_path=".workflow/WFS-{session}/.brainstorming/synthesis-specification.md",
old_string="## UI/UX Guidelines\n[existing content or empty]",
new_string="## UI/UX Guidelines\n\n[new design system content with @ references]"
)
```
### Phase 4: Update UI Designer Analysis
**Create or update** `.brainstorming/ui-designer/style-guide.md`:
```markdown
# UI Designer Style Guide
## Design System Integration
This style guide integrates the finalized design system from the design refinement phase.
**Source Design Tokens**: @../../.design/style-consolidation/design-tokens.json
**Source Style Guide**: @../../.design/style-consolidation/style-guide.md
## Design Philosophy
[Content from style-philosophy.md]
## Design Tokens Reference
For complete token definitions, see: @../../.design/style-consolidation/design-tokens.json
### Color System
[Summary of color tokens]
### Typography System
[Summary of typography tokens]
### Spacing System
[Summary of spacing tokens]
### Component Tokens
[Summary of component tokens: border-radius, shadows]
## Component Patterns
[Reference to style-guide.md component patterns]
## Implementation Guidelines
1. **Use CSS Custom Properties**: All styles reference design tokens
2. **Follow Semantic HTML**: Use HTML5 semantic elements
3. **Maintain Accessibility**: WCAG AA compliance required
4. **Responsive Design**: Mobile-first with token-based breakpoints
## Reference Prototypes
[Links to selected prototypes with descriptions]
---
*Auto-generated by /workflow:design:design-update*
*Last updated: {timestamp}*
```
**Implementation**:
```bash
Write(
file_path=".workflow/WFS-{session}/.brainstorming/ui-designer/style-guide.md",
content="[generated style guide content with @ references]"
)
```
### Phase 5: Create Design System Symlinks (Optional)
**For easier task-generate discovery**
```bash
# Create read-only mirror of key design files in brainstorming space
bash(cd .workflow/WFS-{session}/.brainstorming && \
ln -s ../.design/style-consolidation/design-tokens.json design-tokens.json && \
ln -s ../.design/style-consolidation/style-guide.md design-style-guide.md)
```
### Phase 6: TodoWrite Integration
```javascript
TodoWrite({
todos: [
{
content: "Validate session and design system completeness",
status: "completed",
activeForm: "Validating design system"
},
{
content: "Load design tokens, style guide, and selected prototypes",
status: "completed",
activeForm: "Loading design artifacts"
},
{
content: "Update synthesis-specification.md with design system references",
status: "completed",
activeForm: "Updating synthesis specification"
},
{
content: "Create or update ui-designer/style-guide.md",
status: "completed",
activeForm: "Updating UI designer style guide"
},
{
content: "Create design system symlinks for task-generate discovery",
status: "completed",
activeForm: "Creating artifact symlinks"
}
]
});
```
## Output Structure
**Updated Files**:
```
.workflow/WFS-{session}/.brainstorming/
├── synthesis-specification.md # Updated with UI/UX Guidelines section
├── ui-designer/
│ └── style-guide.md # New or updated comprehensive style guide
├── design-tokens.json # Symlink to ../.design/style-consolidation/design-tokens.json
└── design-style-guide.md # Symlink to ../.design/style-consolidation/style-guide.md
```
**Reference Structure** (@ references in synthesis-specification.md):
- `@../.design/style-consolidation/design-tokens.json`
- `@../.design/style-consolidation/style-guide.md`
- `@../.design/style-consolidation/tailwind.config.js`
- `@../.design/prototypes/{prototype}.html`
## Integration with task-generate
After this update, `/workflow:tools:task-generate` will discover:
**In context.artifacts**:
```json
{
"artifacts": [
{
"type": "synthesis_specification",
"path": ".brainstorming/synthesis-specification.md"
},
{
"type": "design_tokens",
"path": ".design/style-consolidation/design-tokens.json"
},
{
"type": "style_guide",
"path": ".design/style-consolidation/style-guide.md"
},
{
"type": "tailwind_config",
"path": ".design/style-consolidation/tailwind.config.js"
},
{
"type": "ui_prototypes",
"paths": [
".design/prototypes/dashboard-variant-1.html",
".design/prototypes/auth-variant-2.html"
]
}
]
}
```
**In flow_control.pre_analysis** (for UI tasks):
```json
{
"step": "load_design_tokens",
"action": "Load design system tokens and style guide",
"commands": [
"bash(cat .workflow/WFS-{session}/.design/style-consolidation/design-tokens.json)",
"bash(cat .workflow/WFS-{session}/.design/style-consolidation/style-guide.md)"
],
"output_to": "design_system_context",
"on_error": "warn"
}
```
## Error Handling
- **Missing design tokens**: Error, run `/workflow:design:style-consolidate` first
- **Missing prototypes**: Error, run `/workflow:design:ui-generate` first
- **synthesis-specification.md not found**: Warning, create minimal version
- **Edit conflicts**: Preserve existing content, append design system section
- **Symlink failures**: Warning only, continue with @ references
## Validation Checks
After update, verify:
- [ ] synthesis-specification.md contains UI/UX Guidelines section
- [ ] UI/UX Guidelines include @ references to design system files
- [ ] ui-designer/style-guide.md created or updated
- [ ] design-tokens.json symlink created (if applicable)
- [ ] All referenced files exist and are readable
## Integration Points
- **Input**: design-tokens.json, style-guide.md, prototypes from design phase
- **Output**: Updated synthesis-specification.md, ui-designer/style-guide.md
- **Next Phase**: `/workflow:plan` can now discover and utilize design system
## Completion Message
```
Design system update complete for session: WFS-{session}
Updated artifacts:
✓ synthesis-specification.md - UI/UX Guidelines section added
✓ ui-designer/style-guide.md - Comprehensive style guide created
✓ Design system references: @ notation for all design files
Design system assets ready for task generation:
- design-tokens.json ({token_count} tokens)
- style-guide.md (comprehensive component patterns)
- tailwind.config.js (Tailwind theme extension)
- {prototype_count} reference prototypes
Next: /workflow:plan [--agent] "<task description>"
The plan phase will automatically discover and utilize the design system.
```
## Main Claude Direct Execution Rationale
This command is executed directly by main Claude (not delegated to an Agent) because:
1. **Context Preservation**: Main Claude has full session context and conversation memory
2. **Integration Complexity**: Requires understanding multiple artifact relationships
3. **Reference Accuracy**: @ reference generation needs precise path resolution
4. **Synthesis Pattern**: Follows the same direct-execution pattern as `/workflow:brainstorm:synthesis`
5. **Minimal Transformation**: Primarily reference integration, not generative analysis
6. **Error Recovery**: Main Claude can better handle edit conflicts and missing files
This approach ensures reliable, context-aware integration without Agent handoff overhead.

View File

@@ -0,0 +1,319 @@
---
name: style-consolidate
description: Consolidate user-selected style variants into unified design system
usage: /workflow:design:style-consolidate --session <session_id> [--interactive] [--variants "<ids>"]
argument-hint: "--session WFS-session-id [--interactive] [--variants \"variant-1,variant-3\"]"
examples:
- /workflow:design:style-consolidate --session WFS-auth --interactive
- /workflow:design:style-consolidate --session WFS-dashboard --variants "variant-1,variant-3"
allowed-tools: Task(conceptual-planning-agent), TodoWrite(*), Read(*), Write(*), Bash(*)
---
# Style Consolidation Command
## Overview
Consolidate user-selected style variants into a unified, production-ready design system with validated CSS tokens and comprehensive style guide.
## Core Philosophy
- **User-Driven Selection**: Interactive mode for visual style card selection
- **Gemini Clustering**: Semantic naming and style philosophy consolidation
- **Codex Validation**: Token consistency, coverage, and accessibility checks
- **Design System Output**: production-ready tokens + comprehensive style guide
## Execution Protocol
### Phase 1: Session & Style Cards Loading
```bash
# Validate session and load extracted style cards
CHECK: .workflow/.active-* marker files
VALIDATE: session_id matches active session
VERIFY: .design/style-extraction/style-cards.json exists
LOAD: style-cards.json for user selection
```
### Phase 2: User Selection (Interactive Mode)
**Interactive Mode**: `--interactive` flag enables visual selection interface
```bash
IF --interactive:
DISPLAY: Style card previews with descriptions
PROMPT: "Select preferred style variants (comma-separated IDs):"
COLLECT: user_selection (e.g., "variant-1,variant-3")
ELSE IF --variants provided:
PARSE: variant IDs from --variants flag
ELSE:
ERROR: "Must provide either --interactive or --variants parameter"
```
### Phase 3: Gemini Style Philosophy Consolidation
**Agent Invocation**: Task(conceptual-planning-agent) with Gemini capabilities
```bash
Task(conceptual-planning-agent): "
[FLOW_CONTROL]
Consolidate selected style variants into unified design philosophy
## Context Loading
ASSIGNED_TASK: style-consolidation
OUTPUT_LOCATION: .workflow/WFS-{session}/.design/style-consolidation/
SELECTED_VARIANTS: {user_selected_variant_ids}
## Flow Control Steps
1. **load_selected_variants**
- Action: Load user-selected style card data
- Command: Read(.workflow/WFS-{session}/.design/style-extraction/style-cards.json)
- Filter: Extract only selected variant IDs
- Output: selected_style_data
2. **load_design_context**
- Action: Load brainstorming design context
- Command: Read(.workflow/WFS-{session}/.brainstorming/synthesis-specification.md) || Read(.workflow/WFS-{session}/.brainstorming/ui-designer/analysis.md)
- Output: design_context
- Optional: true
3. **consolidate_style_philosophy_gemini**
- Action: Synthesize unified style philosophy and semantic naming
- Command: bash(cd .workflow/WFS-{session} && ~/.claude/scripts/gemini-wrapper --approval-mode yolo -p \"
PURPOSE: Synthesize unified design philosophy from selected style variants
TASK: Create coherent style narrative, consolidate naming conventions, define design principles
MODE: write
CONTEXT: @{.design/style-extraction/style-cards.json,.brainstorming/synthesis-specification.md}
EXPECTED:
1. Unified design philosophy statement
2. Consolidated semantic naming for colors (e.g., 'brand-primary', 'surface-elevated')
3. Typography scale rationale
4. Spacing system principles
5. Component design guidelines
RULES: Ensure consistency, maintain accessibility mindset, align with brainstorming synthesis
\")
- Output: style-philosophy.md
## Consolidation Requirements
**Design Philosophy**: Clear statement of visual design principles
**Semantic Naming**: User-centric token names (not generic color-1, color-2)
**Accessibility**: Ensure WCAG AA contrast ratios for text colors
**Consistency**: Unified token naming conventions across all categories
## Expected Deliverables
1. **style-philosophy.md**: Design philosophy and naming rationale
"
```
### Phase 4: Codex Token Validation & Finalization
**Agent Invocation**: Task(conceptual-planning-agent) with Codex capabilities
```bash
Task(conceptual-planning-agent): "
[FLOW_CONTROL]
Validate and finalize production-ready design tokens
## Context Loading
INPUT_PHILOSOPHY: .workflow/WFS-{session}/.design/style-consolidation/style-philosophy.md
INPUT_TOKENS: .workflow/WFS-{session}/.design/style-extraction/design-tokens.json
SELECTED_VARIANTS: {user_selected_variant_ids}
OUTPUT_LOCATION: .workflow/WFS-{session}/.design/style-consolidation/
## Flow Control Steps
1. **load_consolidation_inputs**
- Action: Load style philosophy and extracted tokens
- Commands:
- Read(.workflow/WFS-{session}/.design/style-consolidation/style-philosophy.md)
- Read(.workflow/WFS-{session}/.design/style-extraction/design-tokens.json)
- Read(.workflow/WFS-{session}/.design/style-extraction/style-cards.json)
- Output: consolidation_inputs
2. **validate_and_finalize_tokens_codex**
- Action: Merge selected variants, validate consistency, generate final tokens
- Command: bash(codex -C .workflow/WFS-{session}/.design/style-consolidation --full-auto exec \"
PURPOSE: Finalize production-ready design tokens with validation
TASK: Merge selected variant tokens, validate consistency, check accessibility, generate final design system
MODE: auto
CONTEXT: @{style-philosophy.md,../style-extraction/design-tokens.json,../style-extraction/style-cards.json,../../../CLAUDE.md}
EXPECTED:
1. design-tokens.json - Final validated CSS token definitions
2. tailwind.config.js - Complete Tailwind configuration
3. style-guide.md - Comprehensive design system documentation
4. validation-report.json - Token consistency and accessibility audit
RULES:
- Use semantic names from style-philosophy.md
- Validate WCAG AA contrast ratios (4.5:1 for text, 3:1 for UI)
- Ensure complete token coverage (colors, typography, spacing, shadows, borders)
- Generate CSS custom properties and Tailwind theme extension
- Include usage examples in style-guide.md
\" --skip-git-repo-check -s danger-full-access)
- Output: design-tokens.json, tailwind.config.js, style-guide.md, validation-report.json
## Validation Requirements
**Consistency Checks**:
- All color tokens use OKLCH format
- Spacing scale follows consistent ratio (e.g., 1.5x or 2x progression)
- Typography scale includes appropriate line-heights
- All tokens have semantic names
**Accessibility Checks**:
- Text colors meet WCAG AA contrast (4.5:1)
- UI component colors meet WCAG AA contrast (3:1)
- Focus indicators have sufficient visibility
- Color is not sole differentiator
**Coverage Checks**:
- Primary, secondary, accent color families
- Surface colors (background, elevated, sunken)
- Semantic colors (success, warning, error, info)
- Typography scale (xs to 4xl)
- Spacing scale (0.25rem to 6rem)
- Border radius options
- Shadow layers
## Expected Deliverables
1. **design-tokens.json**: Production-ready CSS token definitions
2. **tailwind.config.js**: Complete Tailwind theme configuration
3. **style-guide.md**: Design system documentation with usage examples
4. **validation-report.json**: Validation audit results
"
```
### Phase 5: TodoWrite Integration
```javascript
TodoWrite({
todos: [
{
content: "Load session and style cards from extraction phase",
status: "completed",
activeForm: "Loading style cards"
},
{
content: "Collect user style variant selection (interactive or CLI)",
status: "completed",
activeForm: "Collecting user selection"
},
{
content: "Consolidate style philosophy using Gemini",
status: "completed",
activeForm: "Consolidating style philosophy"
},
{
content: "Validate and finalize tokens using Codex",
status: "completed",
activeForm: "Validating and finalizing tokens"
},
{
content: "Generate design system documentation",
status: "completed",
activeForm: "Generating design system docs"
}
]
});
```
## Output Structure
```
.workflow/WFS-{session}/.design/style-consolidation/
├── style-philosophy.md # Unified design philosophy (Gemini)
├── design-tokens.json # Final validated CSS tokens (Codex)
├── tailwind.config.js # Tailwind theme configuration (Codex)
├── style-guide.md # Design system documentation (Codex)
└── validation-report.json # Accessibility & consistency audit (Codex)
```
### design-tokens.json Format
```json
{
"colors": {
"brand": {
"primary": "oklch(0.45 0.20 270 / 1)",
"secondary": "oklch(0.60 0.15 200 / 1)",
"accent": "oklch(0.65 0.18 30 / 1)"
},
"surface": {
"background": "oklch(0.98 0.01 270 / 1)",
"elevated": "oklch(1.00 0.00 0 / 1)",
"sunken": "oklch(0.95 0.02 270 / 1)"
},
"semantic": {
"success": "oklch(0.55 0.15 150 / 1)",
"warning": "oklch(0.70 0.18 60 / 1)",
"error": "oklch(0.50 0.20 20 / 1)",
"info": "oklch(0.60 0.15 240 / 1)"
}
},
"typography": {
"font_family": {
"heading": "Inter, system-ui, sans-serif",
"body": "Inter, system-ui, sans-serif",
"mono": "Fira Code, monospace"
},
"font_size": {
"xs": "0.75rem",
"sm": "0.875rem",
"base": "1rem",
"lg": "1.125rem",
"xl": "1.25rem",
"2xl": "1.5rem",
"3xl": "1.875rem",
"4xl": "2.25rem"
},
"line_height": {
"tight": "1.25",
"normal": "1.5",
"relaxed": "1.75"
}
},
"spacing": {
"0": "0",
"1": "0.25rem",
"2": "0.5rem",
"3": "0.75rem",
"4": "1rem",
"6": "1.5rem",
"8": "2rem",
"12": "3rem",
"16": "4rem",
"24": "6rem"
},
"border_radius": {
"none": "0",
"sm": "0.25rem",
"md": "0.5rem",
"lg": "0.75rem",
"xl": "1rem",
"2xl": "1.5rem",
"full": "9999px"
},
"shadow": {
"sm": "0 1px 2px oklch(0.00 0.00 0 / 0.05)",
"md": "0 4px 6px oklch(0.00 0.00 0 / 0.07), 0 2px 4px oklch(0.00 0.00 0 / 0.06)",
"lg": "0 10px 15px oklch(0.00 0.00 0 / 0.1), 0 4px 6px oklch(0.00 0.00 0 / 0.05)",
"xl": "0 20px 25px oklch(0.00 0.00 0 / 0.15), 0 10px 10px oklch(0.00 0.00 0 / 0.04)"
}
}
```
## Error Handling
- **No style cards found**: Run `/workflow:design:style-extract` first
- **Invalid variant IDs**: Display available IDs and prompt re-selection
- **Validation failures**: Report specific issues (contrast, coverage, consistency)
- **Gemini/Codex execution errors**: Retry with fallback to manual token editing
## Integration Points
- **Input**: style-cards.json from `/workflow:design:style-extract`
- **Output**: design-tokens.json for `/workflow:design:ui-generate`
- **Context**: synthesis-specification.md, ui-designer/analysis.md
## Next Steps
After successful consolidation:
```
Style consolidation complete for session: WFS-{session}
Design tokens validated and finalized
Validation summary:
- Colors: {count} (WCAG AA compliant: {pass_count}/{total_count})
- Typography: {scale_count} sizes
- Spacing: {scale_count} values
- Accessibility: {pass|warnings}
Next: /workflow:design:ui-generate --session WFS-{session} --pages "dashboard,auth"
```

View File

@@ -0,0 +1,244 @@
---
name: style-extract
description: Extract design style from reference images using triple vision analysis (Claude Code + Gemini + Codex)
usage: /workflow:design:style-extract --session <session_id> --images "<glob_pattern>"
argument-hint: "--session WFS-session-id --images \"path/to/*.png\""
examples:
- /workflow:design:style-extract --session WFS-auth --images "design-refs/*.png"
- /workflow:design:style-extract --session WFS-dashboard --images "refs/dashboard-*.jpg"
allowed-tools: TodoWrite(*), Read(*), Write(*), Bash(*), Glob(*)
---
# Style Extraction Command
## Overview
Extract design style elements from reference images using triple vision analysis: Claude Code's native vision, Gemini Vision for semantic understanding, and Codex for structured token generation.
## Core Philosophy
- **Triple Vision Analysis**: Combine Claude Code, Gemini Vision, and Codex vision capabilities
- **Comprehensive Coverage**: Claude Code for quick analysis, Gemini for deep semantic understanding, Codex for structured output
- **Consensus-Based Extraction**: Synthesize results from all three sources
- **Style Card System**: Generate reusable style cards for consolidation phase
- **Multi-Image Support**: Process multiple reference images and extract common patterns
## Execution Protocol
### Phase 1: Session & Input Validation
```bash
# Validate session and locate images
CHECK: .workflow/.active-* marker files
VALIDATE: session_id matches active session
EXPAND: glob pattern to concrete image paths
VERIFY: at least one image file exists
```
### Phase 2: Claude Code Vision Analysis (Quick Initial Pass)
**Direct Execution**: Use Read tool with image paths
```bash
# Claude Code's native vision capability for quick initial analysis
FOR each image IN expanded_image_paths:
Read({image_path})
# Claude Code analyzes image and extracts basic patterns
# Write preliminary analysis
Write(.workflow/WFS-{session}/.design/style-extraction/claude_vision_analysis.json)
```
**Output**: `claude_vision_analysis.json` with Claude Code's initial observations
### Phase 3: Gemini Vision Analysis (Deep Semantic Understanding)
**Direct Bash Execution**: No agent wrapper
```bash
bash(cd .workflow/WFS-{session}/.design/style-extraction && \
~/.claude/scripts/gemini-wrapper --approval-mode yolo -p "
PURPOSE: Extract deep design semantics from reference images
TASK: Analyze color palettes, typography, spacing, layout principles, component styles, design philosophy
MODE: write
CONTEXT: @{../../{image_paths}}
EXPECTED: JSON with comprehensive semantic style description (colors with names, font characteristics, spacing scale, design philosophy, UI patterns)
RULES: Focus on extracting semantic meaning and design intent, not exact pixel values. Identify design system patterns.
")
# Output: gemini_vision_analysis.json
```
**Output**: `gemini_vision_analysis.json` with Gemini's deep semantic analysis
### Phase 4: Codex Vision Analysis (Structured Pattern Recognition)
**Direct Bash Execution**: Codex with -i parameter
```bash
bash(codex -C .workflow/WFS-{session}/.design/style-extraction --full-auto -i {image_paths} exec "
PURPOSE: Analyze reference images for structured design patterns
TASK: Extract color values, typography specs, spacing measurements, component patterns
MODE: auto
CONTEXT: Reference images provided via -i parameter
EXPECTED: Structured JSON with precise design specifications
RULES: Focus on measurable design attributes and component patterns
" --skip-git-repo-check -s danger-full-access)
# Output: codex_vision_analysis.json
```
**Output**: `codex_vision_analysis.json` with Codex's structured analysis
### Phase 5: Synthesis of Triple Vision Analysis
**Direct Execution**: Main Claude synthesizes all three analyses
```bash
# Read all three vision analysis results
Read(.workflow/WFS-{session}/.design/style-extraction/claude_vision_analysis.json)
Read(.workflow/WFS-{session}/.design/style-extraction/gemini_vision_analysis.json)
Read(.workflow/WFS-{session}/.design/style-extraction/codex_vision_analysis.json)
# Load optional session context
Read(.workflow/WFS-{session}/.brainstorming/synthesis-specification.md) [optional]
# Synthesize consensus analysis
# Main Claude identifies common patterns, resolves conflicts, creates unified semantic analysis
Write(.workflow/WFS-{session}/.design/style-extraction/semantic_style_analysis.json)
```
**Synthesis Strategy**:
- **Color system**: Consensus from all three sources, prefer Codex for precise values
- **Typography**: Gemini for semantic understanding, Codex for measurements
- **Spacing**: Cross-validate across all three,identify consistent patterns
- **Design philosophy**: Weighted combination with Gemini having highest weight
- **Conflict resolution**: Majority vote or use context from synthesis-specification.md
**Output**: `semantic_style_analysis.json` - unified analysis synthesizing all three sources
### Phase 6: Structured Token Generation
**Direct Bash Execution**: Codex generates CSS tokens
```bash
bash(codex -C .workflow/WFS-{session}/.design/style-extraction --full-auto exec "
PURPOSE: Convert synthesized semantic analysis to structured CSS design tokens
TASK: Generate W3C-compliant design tokens, Tailwind config, and style card variants
MODE: auto
CONTEXT: @{semantic_style_analysis.json,../../../../CLAUDE.md}
EXPECTED: design-tokens.json (OKLCH format), tailwind-tokens.js, style-cards.json (3 variants)
RULES: $(cat ~/.claude/workflows/design-tokens-schema.md) | OKLCH colors, rem spacing, semantic naming
" --skip-git-repo-check -s danger-full-access)
```
**Output**:
- `design-tokens.json`: W3C-compliant tokens in OKLCH format
- `tailwind-tokens.js`: Tailwind theme extension
- `style-cards.json`: 3 style variant cards for user selection
- Command: bash(codex -C .workflow/WFS-{session}/.design/style-extraction --full-auto exec \"
PURPOSE: Generate structured CSS design tokens from semantic analysis
TASK: Convert semantic color/typography/spacing to OKLCH CSS variables and Tailwind config
MODE: auto
CONTEXT: @{semantic_style_analysis.json,../../../../CLAUDE.md}
EXPECTED:
1. design-tokens.json with OKLCH color values, font stacks, spacing scale
2. tailwind-tokens.js with Tailwind config extension
3. style-cards.json with named style variants for user selection
RULES: Use OKLCH for colors, rem for spacing, maintain semantic naming, generate 2-3 style card variants
\" --skip-git-repo-check -s danger-full-access)
- Output: design-tokens.json, tailwind-tokens.js, style-cards.json
## Token Requirements
**Color Format**: OKLCH with fallback (e.g., \"oklch(0.65 0.15 270 / 1)\")
**Spacing Scale**: rem-based (0.25rem, 0.5rem, 1rem, 1.5rem, 2rem, 3rem, 4rem, 6rem)
**Typography Scale**: rem-based with line-height (xs, sm, base, lg, xl, 2xl, 3xl, 4xl)
**Border Radius**: rem-based (none, sm, md, lg, xl, 2xl, full)
**Shadows**: Layered shadows with OKLCH colors
## Expected Deliverables
1. **design-tokens.json**: Structured CSS token definitions
2. **tailwind-tokens.js**: Tailwind configuration extension
3. **style-cards.json**: Multiple style variants for user selection
"
```
### Phase 4: TodoWrite Integration
```javascript
TodoWrite({
todos: [
{
content: "Validate session and locate reference images",
status: "completed",
activeForm: "Validating session and images"
},
{
content: "Extract visual semantics using Gemini Vision",
status: "completed",
activeForm: "Extracting visual semantics"
},
{
content: "Generate structured CSS tokens using Codex",
status: "completed",
activeForm: "Generating CSS tokens"
},
{
content: "Create style cards for consolidation phase",
status: "completed",
activeForm: "Creating style cards"
}
]
});
```
## Output Structure
```
.workflow/WFS-{session}/.design/style-extraction/
├── semantic_style_analysis.json # Gemini Vision semantic analysis
├── design-tokens.json # Structured CSS tokens (OKLCH)
├── tailwind-tokens.js # Tailwind config extension
└── style-cards.json # Style variants for user selection
```
### style-cards.json Format
```json
{
"style_cards": [
{
"id": "variant-1",
"name": "Modern Minimalist",
"description": "Clean, high contrast with bold typography",
"preview": {
"primary": "oklch(0.45 0.20 270 / 1)",
"background": "oklch(0.98 0.01 270 / 1)",
"font_heading": "Inter, system-ui, sans-serif",
"border_radius": "0.5rem"
}
},
{
"id": "variant-2",
"name": "Soft Neumorphic",
"description": "Subtle shadows with gentle colors",
"preview": {
"primary": "oklch(0.60 0.10 200 / 1)",
"background": "oklch(0.95 0.02 200 / 1)",
"font_heading": "Poppins, sans-serif",
"border_radius": "1rem"
}
}
]
}
```
## Error Handling
- **No images found**: Report error and suggest correct glob pattern
- **Gemini Vision failure**: Retry once, then fall back to manual style description
- **Codex token generation failure**: Use default token template and report warning
- **Invalid session**: Prompt user to start workflow session first
## Integration Points
- **Input**: Reference images (PNG, JPG, WebP)
- **Output**: Style cards for `/workflow:design:style-consolidate`
- **Context**: Optional synthesis-specification.md or ui-designer/analysis.md
## Next Steps
After successful extraction:
```
Style extraction complete for session: WFS-{session}
Style cards generated: {count}
Next: /workflow:design:style-consolidate --session WFS-{session} [--interactive]
```

View File

@@ -0,0 +1,316 @@
---
name: ui-generate
description: Generate UI prototypes using consolidated design tokens with optional style overrides
usage: /workflow:design:ui-generate --session <session_id> --pages "<page_list>" [--variants <count>] [--style-overrides "<path_or_json>"]
argument-hint: "--session WFS-session-id --pages \"dashboard,auth\" [--variants 2] [--style-overrides \"overrides.json\"]"
examples:
- /workflow:design:ui-generate --session WFS-auth --pages "login,register"
- /workflow:design:ui-generate --session WFS-dashboard --pages "dashboard" --variants 3 --style-overrides "overrides.json"
allowed-tools: TodoWrite(*), Read(*), Write(*), Bash(*)
---
# UI Generation Command
## Overview
Generate production-ready UI prototypes (HTML/CSS) strictly adhering to consolidated design tokens and synthesis specification requirements.
## Core Philosophy
- **Token-Driven**: All styles reference design-tokens.json, no hardcoded values
- **Specification-Aligned**: UI structure follows synthesis-specification.md requirements
- **Codex Primary**: Code generation with strict token enforcement
- **Gemini Variants**: Optional semantic layout variations
- **Production-Ready**: Clean HTML5, semantic markup, accessibility attributes
## Execution Protocol
### Phase 1: Session & Requirements Loading
```bash
# Validate session and load design system
CHECK: .workflow/.active-* marker files
VALIDATE: session_id matches active session
VERIFY: .design/style-consolidation/design-tokens.json exists
PARSE: --pages parameter to page list
SET: variants_count = --variants || 1
```
### Phase 2: Context Gathering
**Load comprehensive context for UI generation**
```bash
LOAD: design-tokens.json (style system)
LOAD: style-guide.md (usage guidelines)
LOAD: synthesis-specification.md (functional requirements)
LOAD: ui-designer/analysis.md (UX guidelines, optional)
PARSE: page_requirements for each page in --pages list
```
### Phase 3: Codex UI Generation (Primary)
**Agent Invocation**: Task(conceptual-planning-agent) with Codex capabilities
```bash
Task(conceptual-planning-agent): "
[FLOW_CONTROL]
Generate production-ready UI prototypes with strict design token adherence
## Context Loading
ASSIGNED_TASK: ui-prototype-generation
OUTPUT_LOCATION: .workflow/WFS-{session}/.design/prototypes/
TARGET_PAGES: {page_list}
VARIANTS_PER_PAGE: {variants_count}
## Flow Control Steps
1. **load_design_system**
- Action: Load finalized design tokens and style guide
- Commands:
- Read(.workflow/WFS-{session}/.design/style-consolidation/design-tokens.json)
- Read(.workflow/WFS-{session}/.design/style-consolidation/style-guide.md)
- Read(.workflow/WFS-{session}/.design/style-consolidation/tailwind.config.js)
- Output: design_system
2. **load_requirements**
- Action: Load functional and UX requirements
- Commands:
- Read(.workflow/WFS-{session}/.brainstorming/synthesis-specification.md)
- Read(.workflow/WFS-{session}/.brainstorming/ui-designer/analysis.md) [optional]
- Output: requirements_context
3. **generate_ui_prototypes_codex**
- Action: Generate HTML/CSS prototypes with strict token enforcement
- Command: bash(codex -C .workflow/WFS-{session}/.design/prototypes --full-auto exec \"
PURPOSE: Generate production-ready UI prototypes adhering to design tokens
TASK: Create HTML/CSS prototypes for pages: {page_list} with {variants_count} variant(s) each
MODE: auto
CONTEXT: @{../style-consolidation/design-tokens.json,../style-consolidation/style-guide.md,../../.brainstorming/synthesis-specification.md,../../../../CLAUDE.md}
EXPECTED:
For each page, generate {variants_count} variant(s):
1. {page}-variant-{n}.html - Complete HTML structure
2. {page}-variant-{n}.css - CSS using design token custom properties
3. {page}-variant-{n}-notes.md - Implementation notes and token usage
RULES:
- ALL styles MUST reference design token CSS custom properties (--color-brand-primary, --spacing-4, etc.)
- NO hardcoded colors, spacing, or typography values
- Use semantic HTML5 elements (header, nav, main, section, article, footer)
- Include ARIA labels and accessibility attributes (role, aria-label, aria-describedby)
- Implement responsive design using token-based breakpoints
- Follow component patterns from style-guide.md
- Include placeholder content matching page purpose
- Variants explore different layouts while maintaining token consistency
- Generate CSS custom properties mapping in each CSS file
\" --skip-git-repo-check -s danger-full-access)
- Output: {page}-variant-{n}.html, {page}-variant-{n}.css, {page}-variant-{n}-notes.md
## Generation Requirements
**Token Adherence**:
- Use CSS custom properties for all design values
- Reference design-tokens.json for property definitions
- Example: `color: var(--color-brand-primary);`
- Example: `padding: var(--spacing-4) var(--spacing-6);`
- Example: `font-size: var(--font-size-lg);`
**Semantic HTML**:
```html
<header role=\"banner\">
<nav role=\"navigation\" aria-label=\"Main navigation\">
<!-- Navigation items -->
</nav>
</header>
<main role=\"main\">
<section aria-labelledby=\"section-heading\">
<h2 id=\"section-heading\">Section Title</h2>
<!-- Content -->
</section>
</main>
<footer role=\"contentinfo\">
<!-- Footer content -->
</footer>
```
**Accessibility Requirements**:
- Proper heading hierarchy (h1 → h2 → h3)
- Alt text for images
- ARIA labels for interactive elements
- Keyboard navigation support
- Focus indicators using token colors
- Sufficient color contrast (validated against tokens)
**Responsive Design**:
- Mobile-first approach
- Token-based breakpoints (e.g., --breakpoint-md: 768px)
- Flexible layouts using CSS Grid or Flexbox
- Responsive typography using clamp() with token values
## Expected Deliverables
For each page in {page_list}:
1. **{page}-variant-{n}.html**: Complete HTML prototype
2. **{page}-variant-{n}.css**: Token-driven CSS
3. **{page}-variant-{n}-notes.md**: Implementation notes
"
```
### Phase 4: Gemini Variant Suggestions (Optional)
**Conditional Execution**: Only if --variants > 1
```bash
IF variants_count > 1:
Task(conceptual-planning-agent): "
Generate semantic layout variation suggestions using Gemini
TASK: Analyze synthesis-specification.md and suggest {variants_count} layout approaches
CONTEXT: synthesis-specification.md, ui-designer/analysis.md
OUTPUT: variant-suggestions.md with layout rationale for each variant
Use Gemini to explore:
- Different information hierarchy approaches
- Alternative component compositions
- Varied user flow emphasis
- Diverse layout patterns (sidebar, top-nav, card-grid, list-detail)
"
```
### Phase 5: TodoWrite Integration
```javascript
TodoWrite({
todos: [
{
content: "Validate session and load design system",
status: "completed",
activeForm: "Loading design system"
},
{
content: "Load functional requirements and UX guidelines",
status: "completed",
activeForm: "Loading requirements"
},
{
content: "Generate UI prototypes using Codex with token enforcement",
status: "completed",
activeForm: "Generating UI prototypes"
},
{
content: "Generate layout variant suggestions using Gemini (optional)",
status: "completed",
activeForm: "Generating variant suggestions"
},
{
content: "Create implementation notes for each prototype",
status: "completed",
activeForm: "Creating implementation notes"
}
]
});
```
## Output Structure
```
.workflow/WFS-{session}/.design/prototypes/
├── dashboard-variant-1.html
├── dashboard-variant-1.css
├── dashboard-variant-1-notes.md
├── dashboard-variant-2.html (if --variants 2)
├── dashboard-variant-2.css
├── dashboard-variant-2-notes.md
├── auth-variant-1.html
├── auth-variant-1.css
├── auth-variant-1-notes.md
├── design-tokens.css # CSS custom properties from design-tokens.json
└── variant-suggestions.md # Gemini layout rationale (if variants > 1)
```
### HTML Prototype Example
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Dashboard - Variant 1</title>
<link rel="stylesheet" href="design-tokens.css">
<link rel="stylesheet" href="dashboard-variant-1.css">
</head>
<body>
<header role="banner" class="header">
<nav role="navigation" aria-label="Main navigation" class="nav">
<!-- Token-based navigation -->
</nav>
</header>
<main role="main" class="main">
<section aria-labelledby="dashboard-heading" class="dashboard-section">
<h1 id="dashboard-heading" class="heading-primary">Dashboard</h1>
<!-- Content using design tokens -->
</section>
</main>
<footer role="contentinfo" class="footer">
<!-- Footer content -->
</footer>
</body>
</html>
```
### CSS Example
```css
/* Design Tokens (auto-generated from design-tokens.json) */
:root {
--color-brand-primary: oklch(0.45 0.20 270 / 1);
--color-surface-background: oklch(0.98 0.01 270 / 1);
--spacing-4: 1rem;
--spacing-6: 1.5rem;
--font-size-lg: 1.125rem;
--border-radius-md: 0.5rem;
--shadow-md: 0 4px 6px oklch(0.00 0.00 0 / 0.07);
}
/* Component Styles (using tokens) */
.header {
background-color: var(--color-surface-elevated);
padding: var(--spacing-4) var(--spacing-6);
box-shadow: var(--shadow-md);
}
.heading-primary {
font-size: var(--font-size-3xl);
color: var(--color-brand-primary);
margin-bottom: var(--spacing-6);
}
```
## Error Handling
- **No design tokens found**: Run `/workflow:design:style-consolidate` first
- **Invalid page names**: List available pages from synthesis-specification.md
- **Codex generation errors**: Retry with simplified requirements, report warnings
- **Token reference errors**: Validate all CSS against design-tokens.json
## Quality Checks
After generation, verify:
- [ ] All CSS values reference design token custom properties
- [ ] No hardcoded colors, spacing, or typography
- [ ] Semantic HTML structure
- [ ] Accessibility attributes present
- [ ] Responsive design implemented
- [ ] Token-driven styling consistent across variants
## Integration Points
- **Input**: design-tokens.json, style-guide.md, synthesis-specification.md
- **Output**: HTML/CSS prototypes for `/workflow:design:design-update`
- **Context**: ui-designer/analysis.md for UX guidance
## Next Steps
After successful generation:
```
UI prototypes generated for session: WFS-{session}
Pages: {page_list}
Variants per page: {variants_count}
Generated files:
- {count} HTML prototypes
- {count} CSS files (token-driven)
- {count} implementation notes
Review prototypes and select preferred variants:
Location: .workflow/WFS-{session}/.design/prototypes/
Next: /workflow:design:design-update --session WFS-{session}
```

View File

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

View File

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

View File

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

View File

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

View File

@@ -1,256 +1,590 @@
---
name: docs
description: Generate hierarchical architecture and API documentation using doc-generator agent with flow_control
usage: /workflow:docs <type> [scope]
argument-hint: "architecture"|"api"|"all"
description: Documentation planning and orchestration - creates structured documentation tasks for execution
usage: /workflow:docs <type> [options]
argument-hint: "architecture"|"api"|"all" [--tool <gemini|qwen|codex>] [--scope <path>]
examples:
- /workflow:docs all
- /workflow:docs architecture src/modules
- /workflow:docs api --scope api/
- /workflow:docs all # Complete documentation (gemini default)
- /workflow:docs all --tool qwen # Use Qwen for architecture focus
- /workflow:docs architecture --scope src/modules
- /workflow:docs api --tool gemini --scope api/
---
# Workflow Documentation Command
## Purpose
**`/workflow:docs` is a pure planner/orchestrator** - it analyzes project structure, decomposes documentation work into tasks, and generates execution plans. It does **NOT** generate any documentation content itself.
**Key Principle**: Separation of Concerns
- **docs.md** → Planning, session creation, task generation
- **doc-generator.md** → Execution, content generation, quality assurance
## Usage
```bash
/workflow:docs <type> [scope]
/workflow:docs <type> [--tool <gemini|qwen|codex>] [--scope <path>]
```
## Input Detection
- **Document Types**: `architecture`, `api`, `all` → Creates appropriate documentation tasks
- **Scope**: Optional module/directory filtering → Focuses documentation generation
- **Default**: `all` → Complete documentation suite
### Parameters
## Core Workflow
- **type**: `architecture` | `api` | `all` (required)
- `architecture`: System design, module interactions, patterns
- `api`: Endpoint documentation, API specifications
- `all`: Complete documentation suite
### Planning & Task Creation Process
The command performs structured planning and task creation:
- **--tool**: `gemini` | `qwen` | `codex` (optional, default: gemini)
- `gemini`: Comprehensive documentation, pattern recognition
- `qwen`: Architecture analysis, system design focus
- `codex`: Implementation validation, code quality
**0. Pre-Planning Architecture Analysis** ⚠️ MANDATORY FIRST STEP
- **System Structure Analysis**: MUST run `bash(~/.claude/scripts/get_modules_by_depth.sh)` for dynamic task decomposition
- **Module Boundary Identification**: Understand module organization and dependencies
- **Architecture Pattern Recognition**: Identify architectural styles and design patterns
- **Foundation for documentation**: Use structure analysis to guide task decomposition
- **--scope**: Directory path filter (optional)
**1. Documentation Planning**
- **Type Analysis**: Determine documentation scope (architecture/api/all)
- **Module Discovery**: Use architecture analysis results to identify components
- **Dynamic Task Decomposition**: Analyze project structure to determine optimal task count and module grouping
- **Session Management**: Create or use existing documentation session
## Planning Workflow
**2. Task Generation**
- **Create session**: `.workflow/WFS-docs-[timestamp]/`
- **Create active marker**: `.workflow/.active-WFS-docs-[timestamp]` (must match session folder name)
- **Generate IMPL_PLAN.md**: Documentation requirements and task breakdown
- **Create task.json files**: Individual documentation tasks with flow_control
- **Setup TODO_LIST.md**: Progress tracking for documentation generation
### Complete Execution Flow
### Session Management ⚠️ CRITICAL
- **Check for active sessions**: Look for `.workflow/.active-WFS-docs-*` markers
- **Marker naming**: Active marker must exactly match session folder name
- **Session creation**: `WFS-docs-[timestamp]` folder with matching `.active-WFS-docs-[timestamp]` marker
- **Task execution**: Use `/workflow:execute` to run individual documentation tasks within active session
- **Session isolation**: Each documentation session maintains independent context and state
```
/workflow:docs [type] [--tool] [--scope]
Phase 1: Init Session → Create session dir & active marker
Phase 2: Module Analysis → Run get_modules_by_depth.sh
Phase 3: Quick Assess → Check existing docs
Phase 4: Decompose → Create task list & TodoWrite
Phase 5: Generate Tasks → Build IMPL-*.json & plans
✅ Planning Complete → Show TodoWrite status
```
## Output Structure
### Phase Details
#### Phase 1: Session Initialization
```bash
# Parse arguments and create session structure
doc_type="all" # architecture|api|all
tool="gemini" # gemini|qwen|codex (default: gemini)
scope="" # optional path filter
timestamp=$(date +%Y%m%d-%H%M%S)
session_dir=".workflow/WFS-docs-${timestamp}"
mkdir -p "${session_dir}"/{.task,.process,.summaries}
touch ".workflow/.active-WFS-docs-${timestamp}"
```
#### Phase 2: Project Structure Analysis (MANDATORY)
```bash
# Run get_modules_by_depth.sh for module hierarchy
module_data=$(~/.claude/scripts/get_modules_by_depth.sh)
# Format: depth:N|path:<PATH>|files:N|size:N|has_claude:yes/no
```
#### Phase 3: Quick Documentation Assessment
```bash
# Lightweight check - no heavy analysis
existing_docs=$(find . -maxdepth 2 -name "*.md" -not -path "./.workflow/*" | wc -l)
if [[ $existing_docs -gt 5 ]]; then
find . -maxdepth 3 -name "*.md" > "${session_dir}/.process/existing-docs.txt"
fi
# Record strategy
cat > "${session_dir}/.process/strategy.md" <<EOF
**Type**: ${doc_type}
**Tool**: ${tool}
**Scope**: ${scope:-"Full project"}
EOF
```
#### Phase 4: Task Decomposition & TodoWrite Setup
**Decomposition Strategy**:
1. **Always create**: System Overview task (IMPL-001)
2. **If architecture/all**: Architecture Documentation task
3. **If api/all**: Unified API Documentation task
4. **For each module**: Module Documentation task (grouped)
**Grouping Rules**:
- Max 3 modules per task
- Max 30 files per task
- Group by dependency depth and functional similarity
**TodoWrite Setup**:
```
✅ Session initialization (completed)
⏳ IMPL-001: Project Overview (pending)
⏳ IMPL-002: Module 'auth' (pending)
⏳ IMPL-003: Module 'api' (pending)
⏳ IMPL-004: Architecture Documentation (pending)
⏳ IMPL-005: API Documentation (pending)
```
#### Phase 5: Task JSON Generation
Each task follows the 5-field schema with detailed flow_control.
**Command Generation Logic**:
```bash
# Build tool-specific command at planning time
if [[ "$tool" == "codex" ]]; then
cmd="codex -C ${dir} --full-auto exec \"...\""
else
cmd="bash(cd ${dir} && ~/.claude/scripts/${tool}-wrapper -p \"...\")"
fi
```
## Task Templates
### 1. System Overview (IMPL-001)
**Purpose**: Project-level documentation
**Output**: `.workflow/docs/README.md`
**Complete JSON Structure**:
```json
{
"id": "IMPL-001",
"title": "Generate Project Overview Documentation",
"status": "pending",
"meta": {
"type": "docs",
"agent": "@doc-generator",
"tool": "gemini",
"template": "project-overview"
},
"context": {
"requirements": [
"Document project purpose, architecture, and getting started guide",
"Create navigation structure for all documentation",
"Use Project-Level Documentation Template"
],
"focus_paths": ["."],
"acceptance": [
"Complete .workflow/docs/README.md following template",
"All template sections populated with accurate information",
"Navigation links to module and API documentation"
],
"scope": "Project root and overall structure"
},
"flow_control": {
"pre_analysis": [
{
"step": "discover_project_structure",
"action": "Analyze project structure and modules",
"command": "bash(~/.claude/scripts/get_modules_by_depth.sh)",
"output_to": "system_structure"
},
{
"step": "discover_project_files",
"action": "Identify key project files",
"command": "bash(find . -maxdepth 2 -type f \\( -name '*.json' -o -name '*.md' -o -name '*.yml' -o -name '*.yaml' \\) | head -30)",
"output_to": "project_files"
},
{
"step": "analyze_tech_stack",
"action": "Analyze technology stack and dependencies",
"command": "bash(~/.claude/scripts/gemini-wrapper -p \"PURPOSE: Analyze project technology stack\\nTASK: Extract tech stack, architecture patterns, design principles\\nMODE: analysis\\nCONTEXT: System structure: [system_structure]\\n Project files: [project_files]\\nEXPECTED: Technology analysis with architecture style\\nRULES: $(cat ~/.claude/workflows/cli-templates/prompts/documentation/project-overview.txt)\")",
"output_to": "tech_analysis",
"on_error": "fail",
"note": "Command is built at planning time based on $tool variable (gemini/qwen/codex)"
}
],
"implementation_approach": {
"task_description": "Use tech_analysis to populate Project-Level Documentation Template",
"logic_flow": [
"Load template: ~/.claude/workflows/cli-templates/prompts/documentation/project-overview.txt",
"Parse tech_analysis for: purpose, architecture, tech stack, design principles",
"Fill template sections with extracted information",
"Generate navigation links to module/API docs",
"Format output as Markdown"
]
},
"target_files": [".workflow/docs/README.md"]
}
}
```
### 2. Module Documentation (IMPL-002+)
**Purpose**: Module-level documentation
**Output**: `.workflow/docs/modules/[name]/README.md`
**Complete JSON Structure**:
```json
{
"id": "IMPL-002",
"title": "Document Module: 'auth'",
"status": "pending",
"meta": {
"type": "docs",
"agent": "@doc-generator",
"tool": "gemini",
"template": "module-documentation"
},
"context": {
"requirements": [
"Document module purpose, internal architecture, public API",
"Include dependencies and usage examples",
"Use Module-Level Documentation Template"
],
"focus_paths": ["src/auth"],
"acceptance": [
"Complete .workflow/docs/modules/auth/README.md",
"All exported functions/classes documented",
"Working code examples included"
],
"scope": "auth module only"
},
"flow_control": {
"pre_analysis": [
{
"step": "load_system_context",
"action": "Load system architecture from IMPL-001",
"command": "bash(cat .workflow/WFS-docs-*/IMPL-001-system_structure.output 2>/dev/null || ~/.claude/scripts/get_modules_by_depth.sh)",
"output_to": "system_context",
"on_error": "skip_optional"
},
{
"step": "analyze_module_structure",
"action": "Deep analysis of module structure and API",
"command": "bash(cd src/auth && ~/.claude/scripts/gemini-wrapper -p \"PURPOSE: Document module comprehensively\\nTASK: Extract module purpose, architecture, public API, dependencies\\nMODE: analysis\\nCONTEXT: @{**/*}\\n System: [system_context]\\nEXPECTED: Complete module analysis for documentation\\nRULES: $(cat ~/.claude/workflows/cli-templates/prompts/documentation/module-documentation.txt)\")",
"output_to": "module_analysis",
"on_error": "fail",
"note": "For qwen: qwen-wrapper | For codex: codex -C src/auth --full-auto exec \"...\" --skip-git-repo-check"
}
],
"implementation_approach": {
"task_description": "Use module_analysis to populate Module-Level Documentation Template",
"logic_flow": [
"Load template: ~/.claude/workflows/cli-templates/prompts/documentation/module-documentation.txt",
"Parse module_analysis for: purpose, components, API, dependencies",
"Fill template sections with extracted information",
"Generate code examples from actual usage",
"Format output as Markdown"
]
},
"target_files": [".workflow/docs/modules/auth/README.md"]
}
}
```
### 3. Architecture Documentation (if requested)
**Purpose**: System design and patterns
**Output**: `.workflow/docs/architecture/`
**Complete JSON Structure**:
```json
{
"id": "IMPL-N-1",
"title": "Generate Architecture Documentation",
"status": "pending",
"meta": {
"type": "docs",
"agent": "@doc-generator",
"tool": "qwen",
"template": "architecture"
},
"context": {
"requirements": [
"Document system design patterns and architectural decisions",
"Create module interaction diagrams",
"Explain data flow and component relationships"
],
"focus_paths": ["."],
"acceptance": [
"Complete architecture documentation in .workflow/docs/architecture/",
"Diagrams explaining system design",
"Clear explanation of architectural patterns"
]
},
"flow_control": {
"pre_analysis": [
{
"step": "load_all_module_docs",
"action": "Aggregate all module documentation",
"command": "bash(find .workflow/docs/modules -name 'README.md' -exec cat {} \\;)",
"output_to": "module_docs",
"on_error": "fail"
},
{
"step": "analyze_architecture",
"action": "Synthesize system architecture from modules",
"command": "bash(~/.claude/scripts/gemini-wrapper -p \"PURPOSE: Synthesize system architecture\\nTASK: Create architecture documentation from module docs\\nMODE: analysis\\nCONTEXT: [module_docs]\\nEXPECTED: Architecture documentation with patterns\\nRULES: $(cat ~/.claude/workflows/cli-templates/prompts/documentation/project-overview.txt) | Focus on design patterns, data flow, component interactions\")",
"output_to": "architecture_analysis",
"on_error": "fail",
"note": "Command varies: gemini-wrapper (default) | qwen-wrapper | codex exec"
}
],
"implementation_approach": {
"task_description": "Create architecture documentation from synthesis",
"logic_flow": [
"Parse architecture_analysis for patterns and design decisions",
"Create text-based diagrams (mermaid/ASCII) for module interactions",
"Document data flow between components",
"Explain architectural decisions and trade-offs",
"Format as structured documentation"
]
},
"target_files": [
".workflow/docs/architecture/system-design.md",
".workflow/docs/architecture/module-map.md",
".workflow/docs/architecture/data-flow.md"
]
}
}
```
### 4. API Documentation (if requested)
**Purpose**: API reference and specifications
**Output**: `.workflow/docs/api/README.md`
**Complete JSON Structure**:
```json
{
"id": "IMPL-N",
"title": "Generate Unified API Documentation",
"status": "pending",
"meta": {
"type": "docs",
"agent": "@doc-generator",
"tool": "gemini",
"template": "api-reference"
},
"context": {
"requirements": [
"Document all API endpoints with request/response formats",
"Include authentication and error handling",
"Generate OpenAPI specification if applicable",
"Use API-Level Documentation Template"
],
"focus_paths": ["src/api", "src/routes", "src/controllers"],
"acceptance": [
"Complete .workflow/docs/api/README.md following template",
"All endpoints documented with examples",
"OpenAPI spec generated if REST API detected"
]
},
"flow_control": {
"pre_analysis": [
{
"step": "discover_api_endpoints",
"action": "Find all API routes and endpoints",
"command": "bash(rg -t ts -t js '(router\\.|app\\.|@(Get|Post|Put|Delete|Patch))' src/ --no-heading | head -100)",
"output_to": "endpoint_discovery",
"on_error": "skip_optional"
},
{
"step": "analyze_api_structure",
"action": "Analyze API structure and patterns",
"command": "bash(~/.claude/scripts/gemini-wrapper -p \"PURPOSE: Document API comprehensively\\nTASK: Extract endpoints, auth, request/response formats\\nMODE: analysis\\nCONTEXT: @{src/api/**/*,src/routes/**/*,src/controllers/**/*}\\n Endpoints: [endpoint_discovery]\\nEXPECTED: Complete API documentation\\nRULES: $(cat ~/.claude/workflows/cli-templates/prompts/documentation/api-reference.txt)\")",
"output_to": "api_analysis",
"on_error": "fail",
"note": "Tool-specific: gemini-wrapper | qwen-wrapper | codex -C src/api exec"
}
],
"implementation_approach": {
"task_description": "Use api_analysis to populate API-Level Documentation Template",
"logic_flow": [
"Load template: ~/.claude/workflows/cli-templates/prompts/documentation/api-reference.txt",
"Parse api_analysis for: endpoints, auth, request/response",
"Fill template sections with extracted information",
"Generate OpenAPI spec if REST API detected",
"Format output as Markdown"
]
},
"target_files": [
".workflow/docs/api/README.md",
".workflow/docs/api/openapi.yaml"
]
}
}
```
## Planning Outputs
### File Structure
```
.workflow/
├── .active-WFS-docs-20240120-143022
└── WFS-docs-20240120-143022/
├── IMPL_PLAN.md # Implementation plan
├── TODO_LIST.md # Progress tracker
├── .process/
│ ├── strategy.md # Doc strategy
│ └── existing-docs.txt # Existing docs list
└── .task/
├── IMPL-001.json # System overview
├── IMPL-002.json # Module: auth
├── IMPL-003.json # Module: api
├── IMPL-004.json # Architecture
└── IMPL-005.json # API docs
```
### IMPL_PLAN.md
```markdown
# Documentation Implementation Plan
**Session**: WFS-docs-[timestamp]
**Type**: [architecture|api|all]
**Tool**: [gemini|qwen|codex]
## Task Breakdown
### IMPL-001: System Overview
- **Output**: .workflow/docs/README.md
- **Template**: project-overview.txt
### IMPL-002+: Module Documentation
- **Modules**: [list]
- **Template**: module-documentation.txt
### IMPL-N: Architecture/API (if requested)
- **Template**: architecture.txt / api-reference.txt
## Execution Order
1. IMPL-001 (Foundation)
2. IMPL-002 to IMPL-[M] (Modules - can parallelize)
3. IMPL-[M+1] (Architecture - needs modules)
4. IMPL-[N] (API - can run after IMPL-001)
```
### TODO_LIST.md
```markdown
# Documentation Progress Tracker
- [ ] **IMPL-001**: Generate Project Overview
- [ ] **IMPL-002**: Document Module: 'auth'
- [ ] **IMPL-003**: Document Module: 'api'
- [ ] **IMPL-004**: Generate Architecture Documentation
- [ ] **IMPL-005**: Generate Unified API Documentation
## Execution
```bash
/workflow:execute IMPL-001
/workflow:execute IMPL-002
# ...
```
```
## Execution Phase
### Via /workflow:execute
```
For Each Task (IMPL-001, IMPL-002, ...):
/workflow:execute IMPL-NNN
TodoWrite: pending → in_progress
Execute flow_control (pre_analysis steps)
Generate Documentation (apply template)
TodoWrite: in_progress → completed
✅ Task Complete
```
### TodoWrite Status Tracking
**Planning Phase**:
```
✅ Session initialization (completed)
⏳ IMPL-001: Project Overview (pending)
⏳ IMPL-002: Module 'auth' (pending)
```
**Execution Phase**:
```
Executing IMPL-001:
✅ Session initialization
🔄 IMPL-001: Project Overview (in_progress)
⏳ IMPL-002: Module 'auth'
After IMPL-001:
✅ Session initialization
✅ IMPL-001: Project Overview (completed)
🔄 IMPL-002: Module 'auth' (in_progress)
```
## Documentation Output
### Final Structure
```
.workflow/docs/
├── README.md # System navigation
├── modules/ # Level 1: Module documentation
│ ├── [module-1]/
│ ├── overview.md
│ │ ├── api.md
│ │ ├── dependencies.md
│ │ └── examples.md
│ └── [module-n]/...
├── architecture/ # Level 2: System architecture
├── README.md # IMPL-001: Project overview
├── modules/
│ ├── auth/README.md # IMPL-002: Auth module
└── api/README.md # IMPL-003: API module
├── architecture/ # IMPL-004: Architecture
│ ├── system-design.md
│ ├── module-map.md
── data-flow.md
│ └── tech-stack.md
└── api/ # Level 2: Unified API docs
├── unified-api.md
── data-flow.md
└── api/ # IMPL-005: API docs
├── README.md
└── openapi.yaml
```
## Task Decomposition Standards
## Next Steps
### Dynamic Task Planning Rules
**Module Grouping**: Max 3 modules per task, max 30 files per task
**Task Count**: Calculate based on `total_modules ÷ 3 (rounded up) + base_tasks`
**File Limits**: Split tasks when file count exceeds 30 in any module group
**Base Tasks**: System overview (1) + Architecture (1) + API consolidation (1)
**Module Tasks**: Group related modules by dependency depth and functional similarity
### Documentation Task Types
**IMPL-001**: System Overview Documentation
- Project structure analysis
- Technology stack documentation
- Main navigation creation
**IMPL-002**: Module Documentation (per module)
- Individual module analysis
- API surface documentation
- Dependencies and relationships
- Usage examples
**IMPL-003**: Architecture Documentation
- System design patterns
- Module interaction mapping
- Data flow documentation
- Design principles
**IMPL-004**: API Documentation
- Endpoint discovery and analysis
- OpenAPI specification generation
- Authentication documentation
- Integration examples
### Task JSON Schema (5-Field Architecture)
Each documentation task uses the workflow-architecture.md 5-field schema:
- **id**: IMPL-N format
- **title**: Documentation task name
- **status**: pending|active|completed|blocked
- **meta**: { type: "documentation", agent: "@doc-generator" }
- **context**: { requirements, focus_paths, acceptance, scope }
- **flow_control**: { pre_analysis[], implementation_approach, target_files[] }
## Document Generation
### Workflow Process
**Input Analysis** → **Session Creation****IMPL_PLAN.md****.task/IMPL-NNN.json** → **TODO_LIST.md****Execute Tasks**
**Always Created**:
- **IMPL_PLAN.md**: Documentation requirements and task breakdown
- **Session state**: Task references and documentation paths
**Auto-Created (based on scope)**:
- **TODO_LIST.md**: Progress tracking for documentation tasks
- **.task/IMPL-*.json**: Individual documentation tasks with flow_control
- **.process/ANALYSIS_RESULTS.md**: Documentation analysis artifacts
**Document Structure**:
```
.workflow/
├── .active-WFS-docs-20231201-143022 # Active session marker (matches folder name)
└── WFS-docs-20231201-143022/ # Documentation session folder
├── IMPL_PLAN.md # Main documentation plan
├── TODO_LIST.md # Progress tracking
├── .process/
│ └── ANALYSIS_RESULTS.md # Documentation analysis
└── .task/
├── IMPL-001.json # System overview task
├── IMPL-002.json # Module documentation task
├── IMPL-003.json # Architecture documentation task
└── IMPL-004.json # API documentation task
### 1. Review Planning Output
```bash
cat .workflow/WFS-docs-*/IMPL_PLAN.md
cat .workflow/WFS-docs-*/TODO_LIST.md
```
### Task Flow Control Templates
### 2. Execute Documentation Tasks
```bash
# Sequential (recommended)
/workflow:execute IMPL-001 # System overview first
/workflow:execute IMPL-002 # Module docs
/workflow:execute IMPL-003
/workflow:execute IMPL-004 # Architecture
/workflow:execute IMPL-005 # API docs
**System Overview Task (IMPL-001)**:
```json
"flow_control": {
"pre_analysis": [
{
"step": "system_architecture_analysis",
"action": "Discover system architecture and module hierarchy",
"command": "bash(~/.claude/scripts/get_modules_by_depth.sh)",
"output_to": "system_structure"
},
{
"step": "project_discovery",
"action": "Discover project structure and entry points",
"command": "bash(find . -type f -name '*.json' -o -name '*.md' -o -name 'package.json' | head -20)",
"output_to": "project_structure"
},
{
"step": "analyze_tech_stack",
"action": "Analyze technology stack and dependencies using structure analysis",
"command": "~/.claude/scripts/gemini-wrapper -p \"Analyze project technology stack and dependencies based on: [system_structure]\"",
"output_to": "tech_analysis"
}
],
"target_files": [".workflow/docs/README.md"]
}
# Parallel (module docs only)
/workflow:execute IMPL-002 &
/workflow:execute IMPL-003 &
wait
```
**Module Documentation Task (IMPL-002)**:
```json
"flow_control": {
"pre_analysis": [
{
"step": "load_system_structure",
"action": "Load system architecture analysis from previous task",
"command": "bash(cat .workflow/WFS-docs-*/IMPL-001-system_structure.output 2>/dev/null || ~/.claude/scripts/get_modules_by_depth.sh)",
"output_to": "system_context"
},
{
"step": "module_analysis",
"action": "Analyze specific module structure and API within system context",
"command": "~/.claude/scripts/gemini-wrapper -p \"Analyze module [MODULE_NAME] structure and exported API within system: [system_context]\"",
"output_to": "module_context"
}
],
"target_files": [".workflow/docs/modules/[MODULE_NAME]/overview.md"]
}
### 3. Review Generated Documentation
```bash
ls -lah .workflow/docs/
cat .workflow/docs/README.md
```
## Analysis Templates
### Project Structure Analysis Rules
- Identify main modules and purposes
- Map directory organization patterns
- Extract entry points and configuration files
- Recognize architectural styles and design patterns
- Analyze module relationships and dependencies
- Document technology stack and requirements
### Module Analysis Rules
- Identify module boundaries and entry points
- Extract exported functions, classes, interfaces
- Document internal organization and structure
- Analyze API surfaces with types and parameters
- Map dependencies within and between modules
- Extract usage patterns and examples
### API Analysis Rules
- Classify endpoint types (REST, GraphQL, WebSocket, RPC)
- Extract request/response parameters and schemas
- Document authentication and authorization requirements
- Generate OpenAPI 3.0 specification structure
- Create comprehensive endpoint documentation
- Provide usage examples and integration guides
### 4. TodoWrite Progress
- Planning: All tasks `pending`
- Execution: `pending``in_progress``completed`
- Real-time status updates via TodoWrite
## Error Handling
- **Invalid document type**: Clear error message with valid options
- **Module not found**: Skip missing modules with warning
- **Analysis failures**: Fall back to file-based analysis
- **Permission issues**: Clear guidance on directory access
- **No modules found**: Create only IMPL-001 (system overview)
- **Scope path invalid**: Show error and exit
- **Active session exists**: Prompt to complete or pause
- **Tool unavailable**: Fall back to gemini
## Key Benefits
### Structured Documentation Process
- **Task-based approach**: Documentation broken into manageable, trackable tasks
- **Flow control integration**: Systematic analysis ensures completeness
- **Progress visibility**: TODO_LIST.md provides clear completion status
- **Quality assurance**: Each task has defined acceptance criteria
### Clear Separation of Concerns
- **Planning**: Session creation, task decomposition (this command)
- **Execution**: Content generation, quality assurance (doc-generator agent)
### Workflow Integration
- **Planning foundation**: Documentation provides context for implementation planning
- **Execution consistency**: Same task execution model as implementation
- **Context accumulation**: Documentation builds comprehensive project understanding
### Scalable Task Management
- Independent, self-contained tasks
- Parallelizable module documentation
- Clear dependencies (architecture needs modules)
## Usage Examples
### Template-Driven Consistency
- All documentation follows standard templates
- Reusable and maintainable
- Easy to update standards
### Complete Documentation Workflow
```bash
# Step 1: Create documentation plan and tasks
/workflow:docs all
# Step 2: Execute documentation tasks (after planning)
/workflow:execute IMPL-001 # System overview
/workflow:execute IMPL-002 # Module documentation
/workflow:execute IMPL-003 # Architecture documentation
/workflow:execute IMPL-004 # API documentation
```
The system creates structured documentation tasks with proper session management, task.json files, and integration with the broader workflow system for systematic and trackable documentation generation.
### Full Context for Execution
- Each task JSON contains complete instructions
- flow_control defines exact analysis steps
- Tool selection for flexibility

View File

@@ -1,258 +0,0 @@
---
name: workflow:status
description: Generate on-demand views from JSON task data
usage: /workflow:status [task-id] [--format=<format>] [--validate]
argument-hint: [optional: task-id, format, validation]
examples:
- /workflow:status
- /workflow:status impl-1
- /workflow:status --format=hierarchy
- /workflow:status --validate
---
# Workflow Status Command (/workflow:status)
## Overview
Generates on-demand views from JSON task data. No synchronization needed - all views are calculated from the current state of JSON files.
## Core Principles
**Data Source:** @~/.claude/workflows/workflow-architecture.md
## Key Features
### Pure View Generation
- **No Sync**: Views are generated, not synchronized
- **Always Current**: Reads latest JSON data every time
- **No Persistence**: Views are temporary, not saved
- **Single Source**: All data comes from JSON files only
### Multiple View Formats
- **Overview** (default): Current tasks and status
- **Hierarchy**: Task relationships and structure
- **Details**: Specific task information
## Usage
### Default Overview
```bash
/workflow:status
```
Generates current workflow overview:
```markdown
# Workflow Overview
**Session**: WFS-user-auth
**Phase**: IMPLEMENT
**Type**: medium
## Active Tasks
- [⚠️] impl-1: Build authentication module (code-developer)
- [⚠️] impl-2: Setup user management (code-developer)
## Completed Tasks
- [✅] impl-0: Project setup
## Stats
- **Total**: 8 tasks
- **Completed**: 3
- **Active**: 2
- **Remaining**: 3
```
### Specific Task View
```bash
/workflow:status impl-1
```
Shows detailed task information:
```markdown
# Task: impl-1
**Title**: Build authentication module
**Status**: active
**Agent**: @code-developer
**Type**: feature
## Context
- **Requirements**: JWT authentication, OAuth2 support
- **Scope**: src/auth/*, tests/auth/*
- **Acceptance**: Module handles JWT tokens, OAuth2 flow implemented
- **Inherited From**: WFS-user-auth
## Relations
- **Parent**: none
- **Subtasks**: impl-1.1, impl-1.2
- **Dependencies**: impl-0
## Execution
- **Attempts**: 0
- **Last Attempt**: never
## Metadata
- **Created**: 2025-09-05T10:30:00Z
- **Updated**: 2025-09-05T10:35:00Z
```
### Hierarchy View
```bash
/workflow:status --format=hierarchy
```
Shows task relationships:
```markdown
# Task Hierarchy
## Main Tasks
- impl-0: Project setup ✅
- impl-1: Build authentication module ⚠️
- impl-1.1: Design auth schema
- impl-1.2: Implement auth logic
- impl-2: Setup user management ⚠️
## Dependencies
- impl-1 → depends on → impl-0
- impl-2 → depends on → impl-1
```
## View Generation Process
### Data Loading
```pseudo
function generate_workflow_status(task_id, format):
// Load all current data
session = load_workflow_session()
all_tasks = load_all_task_json_files()
// Filter if specific task requested
if task_id:
target_task = find_task(all_tasks, task_id)
return generate_task_detail_view(target_task)
// Generate requested format
switch format:
case 'hierarchy':
return generate_hierarchy_view(all_tasks)
default:
return generate_overview(session, all_tasks)
```
### Real-Time Calculation
- **Task Counts**: Calculated from JSON file status fields
- **Relationships**: Built from JSON relations fields
- **Status**: Read directly from current JSON state
## Validation Mode
### Basic Validation
```bash
/workflow:status --validate
```
Performs integrity checks:
```markdown
# Validation Results
## JSON File Validation
✅ All task JSON files are valid
✅ Session file is valid and readable
## Relationship Validation
✅ All parent-child relationships are valid
✅ All dependencies reference existing tasks
✅ No circular dependencies detected
## Hierarchy Validation
✅ Task hierarchy within depth limits (max 3 levels)
✅ All subtask references are bidirectional
## Issues Found
⚠️ impl-3: No subtasks defined (expected for leaf task)
**Status**: All systems operational
```
### Validation Checks
- **JSON Schema**: All files parse correctly
- **References**: All task IDs exist
- **Hierarchy**: Parent-child relationships are valid
- **Dependencies**: No circular dependencies
- **Depth**: Task hierarchy within limits
## Error Handling
### Missing Files
```bash
❌ Session file not found
→ Initialize new workflow session? (y/n)
❌ Task impl-5 not found
→ Available tasks: impl-1, impl-2, impl-3, impl-4
```
### Invalid Data
```bash
❌ Invalid JSON in impl-2.json
→ Cannot generate view for impl-2
→ Repair file manually or recreate task
⚠️ Circular dependency detected: impl-1 → impl-2 → impl-1
→ Task relationships may be incorrect
```
## Performance Benefits
### Fast Generation
- **No File Writes**: Only reads JSON files
- **No Sync Logic**: No complex synchronization
- **Instant Results**: Generate views on demand
- **No Conflicts**: No state consistency issues
### Scalability
- **Large Task Sets**: Handles hundreds of tasks efficiently
- **Complex Hierarchies**: No performance degradation
- **Concurrent Access**: Multiple views can be generated simultaneously
## Integration
### Workflow Integration
- Use after task creation to see current state
- Use for debugging task relationships
### Command Integration
```bash
# Common workflow
/task:create "New feature"
/workflow:status # Check current state
/task:breakdown impl-1
/workflow:status --format=hierarchy # View new structure
/task:execute impl-1.1
```
## Output Formats
### Supported Formats
- `overview` (default): General workflow status
- `hierarchy`: Task relationships
- `tasks`: Simple task list
- `details`: Comprehensive information
### Custom Filtering
```bash
# Show only active tasks
/workflow:status --format=tasks --filter=active
# Show completed tasks only
/workflow:status --format=tasks --filter=completed
# Show tasks for specific agent
/workflow:status --format=tasks --agent=@code-developer
```
## Related Commands
- `/task:create` - Create tasks (generates JSON data)
- `/task:execute` - Execute tasks (updates JSON data)
- `/task:breakdown` - Create subtasks (generates more JSON data)
- `/workflow:vibe` - Coordinate agents (uses workflow status for coordination)
This workflow status system provides instant, accurate views of workflow state without any synchronization complexity or performance overhead.

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@@ -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

@@ -0,0 +1,240 @@
# API-Level Documentation Template
Generate comprehensive API documentation following this structure:
## Overview
[Brief description of the API's purpose and capabilities]
## Authentication
### Authentication Method
[e.g., JWT, OAuth2, API Keys]
### Obtaining Credentials
```bash
# Example authentication flow
```
### Using Credentials
```http
GET /api/resource HTTP/1.1
Authorization: Bearer <token>
```
---
## Base URL
```
Production: https://api.example.com/v1
Staging: https://staging.api.example.com/v1
```
## Common Response Codes
| Code | Description |
|------|-------------|
| 200 | Success |
| 201 | Created |
| 400 | Bad Request |
| 401 | Unauthorized |
| 403 | Forbidden |
| 404 | Not Found |
| 500 | Internal Server Error |
---
## Endpoints
### Resource: Users
#### GET /users
**Description**: Retrieves a paginated list of users.
**Query Parameters**:
| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| `limit` | number | No | Number of results (default: 20, max: 100) |
| `offset` | number | No | Pagination offset (default: 0) |
| `sort` | string | No | Sort field (e.g., `name`, `-created_at`) |
**Example Request**:
```http
GET /users?limit=10&offset=0&sort=-created_at HTTP/1.1
Authorization: Bearer <token>
```
**Response (200 OK)**:
```json
{
"data": [
{
"id": 1,
"name": "John Doe",
"email": "john@example.com",
"created_at": "2024-01-01T00:00:00Z"
}
],
"pagination": {
"total": 100,
"limit": 10,
"offset": 0
}
}
```
**Error Response (401 Unauthorized)**:
```json
{
"error": {
"code": "UNAUTHORIZED",
"message": "Invalid or expired token"
}
}
```
---
#### GET /users/:id
**Description**: Retrieves a single user by ID.
**Path Parameters**:
| Parameter | Type | Description |
|-----------|------|-------------|
| `id` | number | User ID |
**Example Request**:
```http
GET /users/123 HTTP/1.1
Authorization: Bearer <token>
```
**Response (200 OK)**:
```json
{
"id": 123,
"name": "John Doe",
"email": "john@example.com",
"created_at": "2024-01-01T00:00:00Z",
"updated_at": "2024-01-15T10:30:00Z"
}
```
---
#### POST /users
**Description**: Creates a new user.
**Request Body**:
```json
{
"name": "Jane Smith",
"email": "jane@example.com",
"password": "securePassword123"
}
```
**Validation Rules**:
- `name`: Required, 2-100 characters
- `email`: Required, valid email format, must be unique
- `password`: Required, minimum 8 characters
**Response (201 Created)**:
```json
{
"id": 124,
"name": "Jane Smith",
"email": "jane@example.com",
"created_at": "2024-01-20T12:00:00Z"
}
```
**Error Response (400 Bad Request)**:
```json
{
"error": {
"code": "VALIDATION_ERROR",
"message": "Validation failed",
"details": [
{
"field": "email",
"message": "Email already exists"
}
]
}
}
```
---
#### PUT /users/:id
**Description**: Updates an existing user.
**Path Parameters**:
| Parameter | Type | Description |
|-----------|------|-------------|
| `id` | number | User ID |
**Request Body** (all fields optional):
```json
{
"name": "Jane Doe",
"email": "jane.doe@example.com"
}
```
**Response (200 OK)**:
```json
{
"id": 124,
"name": "Jane Doe",
"email": "jane.doe@example.com",
"updated_at": "2024-01-21T09:15:00Z"
}
```
---
#### DELETE /users/:id
**Description**: Deletes a user.
**Path Parameters**:
| Parameter | Type | Description |
|-----------|------|-------------|
| `id` | number | User ID |
**Response (204 No Content)**:
[Empty response body]
---
## Rate Limiting
- **Limit**: 1000 requests per hour per API key
- **Headers**:
- `X-RateLimit-Limit`: Total requests allowed
- `X-RateLimit-Remaining`: Requests remaining
- `X-RateLimit-Reset`: Unix timestamp when limit resets
---
## SDKs and Client Libraries
- [JavaScript/TypeScript SDK](./sdks/javascript.md)
- [Python SDK](./sdks/python.md)
---
## Webhooks
[Description of webhook system if applicable]
---
## Changelog
### v1.1.0 (2024-01-20)
- Added user sorting functionality
- Improved error messages
### v1.0.0 (2024-01-01)
- Initial API release
---
**API Version**: 1.1.0
**Last Updated**: [Auto-generated timestamp]
**Support**: api-support@example.com

View File

@@ -0,0 +1,91 @@
# Module-Level Documentation Template
Generate detailed module documentation following this structure:
## 1. Purpose and Responsibilities
[What this module does, its boundaries, and its role in the larger system]
## 2. Internal Architecture
- **Key Components**:
- [Component 1]: [Description and responsibility]
- [Component 2]: [Description and responsibility]
- **Data Flow**: [How data moves through the module, with diagrams if applicable]
- **Core Logic**: [Explanation of the main business logic and algorithms]
- **State Management**: [How state is managed within the module]
## 3. Public API / Interface
### Exported Functions
```typescript
/**
* Function description
* @param param1 - Parameter description
* @returns Return value description
*/
export function exampleFunction(param1: Type): ReturnType;
```
### Exported Classes
```typescript
/**
* Class description
*/
export class ExampleClass {
// Public methods and properties
}
```
### Usage Examples
```typescript
import { exampleFunction } from './module';
// Example 1: Basic usage
const result = exampleFunction(input);
// Example 2: Advanced usage
// ...
```
## 4. Dependencies
### Internal Dependencies
- **[Module A]**: [Why this dependency exists, what it provides]
- **[Module B]**: [Purpose of dependency]
### External Dependencies
- **[Library 1]** (`version`): [Purpose and usage]
- **[Library 2]** (`version`): [Purpose and usage]
## 5. Configuration
### Environment Variables
- `ENV_VAR_NAME`: [Description, default value]
### Configuration Options
```typescript
interface ModuleConfig {
option1: Type; // Description
option2: Type; // Description
}
```
## 6. Testing
### Running Tests
```bash
npm test -- module-name
```
### Test Coverage
- Unit tests: [Coverage percentage or key test files]
- Integration tests: [Coverage or test scenarios]
## 7. Common Use Cases
1. **Use Case 1**: [Description and code example]
2. **Use Case 2**: [Description and code example]
## 8. Troubleshooting
### Common Issues
- **Issue 1**: [Description and solution]
- **Issue 2**: [Description and solution]
---
**Module Path**: [File path]
**Last Updated**: [Auto-generated timestamp]
**Owner/Maintainer**: [Team or individual]

View File

@@ -0,0 +1,58 @@
# Project-Level Documentation Template
Generate comprehensive project documentation following this structure:
## 1. Overview
- **Purpose**: [High-level mission and goals of the project]
- **Target Audience**: [Primary users, developers, stakeholders]
- **Key Features**: [List of major functionalities and capabilities]
## 2. System Architecture
- **Architectural Style**: [e.g., Monolith, Microservices, Layered, Event-Driven]
- **Core Components**: [Diagram or list of major system parts and their interactions]
- **Technology Stack**:
- Languages: [Programming languages used]
- Frameworks: [Key frameworks and libraries]
- Databases: [Data storage solutions]
- Infrastructure: [Deployment and hosting]
- **Design Principles**: [Guiding principles like SOLID, DRY, separation of concerns]
## 3. Getting Started
- **Prerequisites**: [Required software, tools, versions]
- **Installation**:
```bash
# Installation commands
```
- **Configuration**: [Environment setup, config files]
- **Running the Project**:
```bash
# Startup commands
```
## 4. Development Workflow
- **Branching Strategy**: [e.g., GitFlow, trunk-based]
- **Coding Standards**: [Style guide, linting rules]
- **Testing**:
```bash
# Test commands
```
- **Build & Deployment**: [CI/CD pipeline overview]
## 5. Project Structure
```
project-root/
├── src/ # [Description]
├── tests/ # [Description]
├── docs/ # [Description]
└── config/ # [Description]
```
## 6. Navigation
- [Module Documentation](./modules/)
- [API Reference](./api/)
- [Architecture Details](./architecture/)
- [Contributing Guidelines](./CONTRIBUTING.md)
---
**Last Updated**: [Auto-generated timestamp]
**Documentation Version**: [Project version]

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

@@ -0,0 +1,534 @@
---
name: design-tokens-schema
description: Design tokens JSON schema specification for UI design workflow
type: specification
---
# Design Tokens Schema Specification
## Overview
Standardized JSON schema for design tokens used in `/workflow:design/*` commands. Ensures consistency across style extraction, consolidation, and UI generation phases.
## Core Principles
1. **OKLCH Color Format**: All colors use OKLCH color space for perceptual uniformity
2. **Semantic Naming**: User-centric token names (brand-primary, surface-elevated, not color-1, bg-2)
3. **rem-Based Sizing**: All spacing and typography use rem units for scalability
4. **Comprehensive Coverage**: Complete token set for production-ready design systems
5. **Accessibility First**: WCAG AA compliance validated and documented
## Full Schema
```json
{
"$schema": "http://json-schema.org/draft-07/schema#",
"title": "Design Tokens",
"description": "Design token definitions for UI design workflow",
"type": "object",
"required": ["colors", "typography", "spacing", "border_radius", "shadow"],
"properties": {
"meta": {
"type": "object",
"properties": {
"version": {"type": "string", "pattern": "^\\d+\\.\\d+\\.\\d+$"},
"generated_at": {"type": "string", "format": "date-time"},
"session_id": {"type": "string", "pattern": "^WFS-"},
"description": {"type": "string"}
}
},
"colors": {
"type": "object",
"required": ["brand", "surface", "semantic", "text"],
"properties": {
"brand": {
"type": "object",
"description": "Brand identity colors",
"required": ["primary", "secondary"],
"properties": {
"primary": {"$ref": "#/definitions/color"},
"secondary": {"$ref": "#/definitions/color"},
"accent": {"$ref": "#/definitions/color"}
}
},
"surface": {
"type": "object",
"description": "Surface and background colors",
"required": ["background", "elevated"],
"properties": {
"background": {"$ref": "#/definitions/color"},
"elevated": {"$ref": "#/definitions/color"},
"sunken": {"$ref": "#/definitions/color"},
"overlay": {"$ref": "#/definitions/color"}
}
},
"semantic": {
"type": "object",
"description": "Semantic state colors",
"required": ["success", "warning", "error", "info"],
"properties": {
"success": {"$ref": "#/definitions/color"},
"warning": {"$ref": "#/definitions/color"},
"error": {"$ref": "#/definitions/color"},
"info": {"$ref": "#/definitions/color"}
}
},
"text": {
"type": "object",
"description": "Text colors with WCAG AA validated contrast",
"required": ["primary", "secondary"],
"properties": {
"primary": {"$ref": "#/definitions/color"},
"secondary": {"$ref": "#/definitions/color"},
"tertiary": {"$ref": "#/definitions/color"},
"inverse": {"$ref": "#/definitions/color"},
"disabled": {"$ref": "#/definitions/color"}
}
},
"border": {
"type": "object",
"description": "Border and divider colors",
"properties": {
"subtle": {"$ref": "#/definitions/color"},
"default": {"$ref": "#/definitions/color"},
"strong": {"$ref": "#/definitions/color"}
}
}
}
},
"typography": {
"type": "object",
"required": ["font_family", "font_size", "line_height", "font_weight"],
"properties": {
"font_family": {
"type": "object",
"required": ["heading", "body"],
"properties": {
"heading": {"type": "string"},
"body": {"type": "string"},
"mono": {"type": "string"}
}
},
"font_size": {
"type": "object",
"required": ["xs", "sm", "base", "lg", "xl", "2xl", "3xl", "4xl"],
"properties": {
"xs": {"$ref": "#/definitions/size_rem"},
"sm": {"$ref": "#/definitions/size_rem"},
"base": {"$ref": "#/definitions/size_rem"},
"lg": {"$ref": "#/definitions/size_rem"},
"xl": {"$ref": "#/definitions/size_rem"},
"2xl": {"$ref": "#/definitions/size_rem"},
"3xl": {"$ref": "#/definitions/size_rem"},
"4xl": {"$ref": "#/definitions/size_rem"},
"5xl": {"$ref": "#/definitions/size_rem"}
}
},
"line_height": {
"type": "object",
"required": ["tight", "normal", "relaxed"],
"properties": {
"tight": {"type": "string", "pattern": "^\\d+(\\.\\d+)?$"},
"normal": {"type": "string", "pattern": "^\\d+(\\.\\d+)?$"},
"relaxed": {"type": "string", "pattern": "^\\d+(\\.\\d+)?$"}
}
},
"font_weight": {
"type": "object",
"properties": {
"light": {"type": "integer", "enum": [300]},
"normal": {"type": "integer", "enum": [400]},
"medium": {"type": "integer", "enum": [500]},
"semibold": {"type": "integer", "enum": [600]},
"bold": {"type": "integer", "enum": [700]}
}
}
}
},
"spacing": {
"type": "object",
"description": "Spacing scale (rem-based)",
"required": ["0", "1", "2", "3", "4", "6", "8"],
"patternProperties": {
"^\\d+$": {"$ref": "#/definitions/size_rem"}
}
},
"border_radius": {
"type": "object",
"required": ["none", "sm", "md", "lg", "full"],
"properties": {
"none": {"type": "string", "const": "0"},
"sm": {"$ref": "#/definitions/size_rem"},
"md": {"$ref": "#/definitions/size_rem"},
"lg": {"$ref": "#/definitions/size_rem"},
"xl": {"$ref": "#/definitions/size_rem"},
"2xl": {"$ref": "#/definitions/size_rem"},
"full": {"type": "string", "const": "9999px"}
}
},
"shadow": {
"type": "object",
"required": ["sm", "md", "lg"],
"properties": {
"none": {"type": "string", "const": "none"},
"sm": {"type": "string"},
"md": {"type": "string"},
"lg": {"type": "string"},
"xl": {"type": "string"},
"2xl": {"type": "string"}
}
},
"breakpoint": {
"type": "object",
"description": "Responsive breakpoints",
"properties": {
"sm": {"type": "string", "pattern": "^\\d+px$"},
"md": {"type": "string", "pattern": "^\\d+px$"},
"lg": {"type": "string", "pattern": "^\\d+px$"},
"xl": {"type": "string", "pattern": "^\\d+px$"},
"2xl": {"type": "string", "pattern": "^\\d+px$"}
}
},
"accessibility": {
"type": "object",
"description": "WCAG AA compliance data",
"properties": {
"contrast_ratios": {
"type": "object",
"patternProperties": {
".*": {
"type": "object",
"properties": {
"background": {"type": "string"},
"foreground": {"type": "string"},
"ratio": {"type": "number"},
"wcag_aa_pass": {"type": "boolean"},
"wcag_aaa_pass": {"type": "boolean"}
}
}
}
}
}
}
},
"definitions": {
"color": {
"type": "string",
"pattern": "^oklch\\(\\s*\\d+(\\.\\d+)?\\s+\\d+(\\.\\d+)?\\s+\\d+(\\.\\d+)?\\s*(\\/\\s*\\d+(\\.\\d+)?)?\\s*\\)$",
"description": "OKLCH color format: oklch(L C H / A)"
},
"size_rem": {
"type": "string",
"pattern": "^\\d+(\\.\\d+)?rem$",
"description": "rem-based size value"
}
}
}
```
## Example: Complete Design Tokens
```json
{
"meta": {
"version": "1.0.0",
"generated_at": "2025-10-05T15:30:00Z",
"session_id": "WFS-auth-dashboard",
"description": "Modern minimalist design system with high contrast"
},
"colors": {
"brand": {
"primary": "oklch(0.45 0.20 270 / 1)",
"secondary": "oklch(0.60 0.15 200 / 1)",
"accent": "oklch(0.65 0.18 30 / 1)"
},
"surface": {
"background": "oklch(0.98 0.01 270 / 1)",
"elevated": "oklch(1.00 0.00 0 / 1)",
"sunken": "oklch(0.95 0.02 270 / 1)",
"overlay": "oklch(0.00 0.00 0 / 0.5)"
},
"semantic": {
"success": "oklch(0.55 0.15 150 / 1)",
"warning": "oklch(0.70 0.18 60 / 1)",
"error": "oklch(0.50 0.20 20 / 1)",
"info": "oklch(0.60 0.15 240 / 1)"
},
"text": {
"primary": "oklch(0.20 0.02 270 / 1)",
"secondary": "oklch(0.45 0.02 270 / 1)",
"tertiary": "oklch(0.60 0.02 270 / 1)",
"inverse": "oklch(0.98 0.01 270 / 1)",
"disabled": "oklch(0.70 0.01 270 / 0.5)"
},
"border": {
"subtle": "oklch(0.90 0.01 270 / 1)",
"default": "oklch(0.80 0.02 270 / 1)",
"strong": "oklch(0.60 0.05 270 / 1)"
}
},
"typography": {
"font_family": {
"heading": "Inter, system-ui, -apple-system, sans-serif",
"body": "Inter, system-ui, -apple-system, sans-serif",
"mono": "Fira Code, Consolas, monospace"
},
"font_size": {
"xs": "0.75rem",
"sm": "0.875rem",
"base": "1rem",
"lg": "1.125rem",
"xl": "1.25rem",
"2xl": "1.5rem",
"3xl": "1.875rem",
"4xl": "2.25rem",
"5xl": "3rem"
},
"line_height": {
"tight": "1.25",
"normal": "1.5",
"relaxed": "1.75"
},
"font_weight": {
"light": 300,
"normal": 400,
"medium": 500,
"semibold": 600,
"bold": 700
}
},
"spacing": {
"0": "0",
"1": "0.25rem",
"2": "0.5rem",
"3": "0.75rem",
"4": "1rem",
"5": "1.25rem",
"6": "1.5rem",
"8": "2rem",
"10": "2.5rem",
"12": "3rem",
"16": "4rem",
"20": "5rem",
"24": "6rem"
},
"border_radius": {
"none": "0",
"sm": "0.25rem",
"md": "0.5rem",
"lg": "0.75rem",
"xl": "1rem",
"2xl": "1.5rem",
"full": "9999px"
},
"shadow": {
"none": "none",
"sm": "0 1px 2px oklch(0.00 0.00 0 / 0.05)",
"md": "0 4px 6px oklch(0.00 0.00 0 / 0.07), 0 2px 4px oklch(0.00 0.00 0 / 0.06)",
"lg": "0 10px 15px oklch(0.00 0.00 0 / 0.1), 0 4px 6px oklch(0.00 0.00 0 / 0.05)",
"xl": "0 20px 25px oklch(0.00 0.00 0 / 0.15), 0 10px 10px oklch(0.00 0.00 0 / 0.04)",
"2xl": "0 25px 50px oklch(0.00 0.00 0 / 0.25)"
},
"breakpoint": {
"sm": "640px",
"md": "768px",
"lg": "1024px",
"xl": "1280px",
"2xl": "1536px"
},
"accessibility": {
"contrast_ratios": {
"text_primary_on_background": {
"background": "oklch(0.98 0.01 270 / 1)",
"foreground": "oklch(0.20 0.02 270 / 1)",
"ratio": 14.2,
"wcag_aa_pass": true,
"wcag_aaa_pass": true
},
"brand_primary_on_background": {
"background": "oklch(0.98 0.01 270 / 1)",
"foreground": "oklch(0.45 0.20 270 / 1)",
"ratio": 6.8,
"wcag_aa_pass": true,
"wcag_aaa_pass": false
}
}
}
}
```
## CSS Custom Properties Generation
Design tokens should be converted to CSS custom properties for use in generated UI:
```css
:root {
/* Brand Colors */
--color-brand-primary: oklch(0.45 0.20 270 / 1);
--color-brand-secondary: oklch(0.60 0.15 200 / 1);
--color-brand-accent: oklch(0.65 0.18 30 / 1);
/* Surface Colors */
--color-surface-background: oklch(0.98 0.01 270 / 1);
--color-surface-elevated: oklch(1.00 0.00 0 / 1);
--color-surface-sunken: oklch(0.95 0.02 270 / 1);
/* Semantic Colors */
--color-semantic-success: oklch(0.55 0.15 150 / 1);
--color-semantic-warning: oklch(0.70 0.18 60 / 1);
--color-semantic-error: oklch(0.50 0.20 20 / 1);
--color-semantic-info: oklch(0.60 0.15 240 / 1);
/* Text Colors */
--color-text-primary: oklch(0.20 0.02 270 / 1);
--color-text-secondary: oklch(0.45 0.02 270 / 1);
--color-text-tertiary: oklch(0.60 0.02 270 / 1);
/* Typography */
--font-family-heading: Inter, system-ui, sans-serif;
--font-family-body: Inter, system-ui, sans-serif;
--font-family-mono: Fira Code, Consolas, monospace;
--font-size-xs: 0.75rem;
--font-size-sm: 0.875rem;
--font-size-base: 1rem;
--font-size-lg: 1.125rem;
--font-size-xl: 1.25rem;
--font-size-2xl: 1.5rem;
--font-size-3xl: 1.875rem;
--font-size-4xl: 2.25rem;
--line-height-tight: 1.25;
--line-height-normal: 1.5;
--line-height-relaxed: 1.75;
/* Spacing */
--spacing-0: 0;
--spacing-1: 0.25rem;
--spacing-2: 0.5rem;
--spacing-3: 0.75rem;
--spacing-4: 1rem;
--spacing-6: 1.5rem;
--spacing-8: 2rem;
--spacing-12: 3rem;
--spacing-16: 4rem;
/* Border Radius */
--border-radius-none: 0;
--border-radius-sm: 0.25rem;
--border-radius-md: 0.5rem;
--border-radius-lg: 0.75rem;
--border-radius-xl: 1rem;
--border-radius-full: 9999px;
/* Shadows */
--shadow-sm: 0 1px 2px oklch(0.00 0.00 0 / 0.05);
--shadow-md: 0 4px 6px oklch(0.00 0.00 0 / 0.07), 0 2px 4px oklch(0.00 0.00 0 / 0.06);
--shadow-lg: 0 10px 15px oklch(0.00 0.00 0 / 0.1), 0 4px 6px oklch(0.00 0.00 0 / 0.05);
}
```
## Tailwind Configuration Generation
```javascript
// tailwind.config.js
module.exports = {
theme: {
extend: {
colors: {
brand: {
primary: 'oklch(0.45 0.20 270 / <alpha-value>)',
secondary: 'oklch(0.60 0.15 200 / <alpha-value>)',
accent: 'oklch(0.65 0.18 30 / <alpha-value>)'
},
surface: {
background: 'oklch(0.98 0.01 270 / <alpha-value>)',
elevated: 'oklch(1.00 0.00 0 / <alpha-value>)',
sunken: 'oklch(0.95 0.02 270 / <alpha-value>)'
},
semantic: {
success: 'oklch(0.55 0.15 150 / <alpha-value>)',
warning: 'oklch(0.70 0.18 60 / <alpha-value>)',
error: 'oklch(0.50 0.20 20 / <alpha-value>)',
info: 'oklch(0.60 0.15 240 / <alpha-value>)'
}
},
fontFamily: {
heading: ['Inter', 'system-ui', 'sans-serif'],
body: ['Inter', 'system-ui', 'sans-serif'],
mono: ['Fira Code', 'Consolas', 'monospace']
},
fontSize: {
'xs': '0.75rem',
'sm': '0.875rem',
'base': '1rem',
'lg': '1.125rem',
'xl': '1.25rem',
'2xl': '1.5rem',
'3xl': '1.875rem',
'4xl': '2.25rem'
},
spacing: {
'1': '0.25rem',
'2': '0.5rem',
'3': '0.75rem',
'4': '1rem',
'6': '1.5rem',
'8': '2rem',
'12': '3rem',
'16': '4rem'
},
borderRadius: {
'sm': '0.25rem',
'md': '0.5rem',
'lg': '0.75rem',
'xl': '1rem',
'2xl': '1.5rem'
},
boxShadow: {
'sm': '0 1px 2px oklch(0.00 0.00 0 / 0.05)',
'md': '0 4px 6px oklch(0.00 0.00 0 / 0.07), 0 2px 4px oklch(0.00 0.00 0 / 0.06)',
'lg': '0 10px 15px oklch(0.00 0.00 0 / 0.1), 0 4px 6px oklch(0.00 0.00 0 / 0.05)'
}
}
}
}
```
## Validation Requirements
### Color Validation
- All colors MUST use OKLCH format
- Alpha channel optional (defaults to 1)
- Lightness: 0-1 (0% to 100%)
- Chroma: 0-0.4 (typical range, can exceed for vibrant colors)
- Hue: 0-360 (degrees)
### Accessibility Validation
- Text on background: minimum 4.5:1 contrast (WCAG AA)
- Large text (18pt+ or 14pt+ bold): minimum 3:1 contrast
- UI components: minimum 3:1 contrast
- Non-text focus indicators: minimum 3:1 contrast
### Consistency Validation
- Spacing scale maintains consistent ratio (e.g., 1.5x or 2x progression)
- Typography scale follows modular scale principles
- Border radius values progress logically
- Shadow layers increase in offset and blur systematically
## Usage in Commands
### style-extract Output
Generates initial `design-tokens.json` from visual analysis
### style-consolidate Output
Finalizes validated `design-tokens.json` with accessibility data
### ui-generate Input
Reads `design-tokens.json` to generate CSS custom properties
### design-update Integration
References `design-tokens.json` path in synthesis-specification.md
## Version History
- **1.0.0**: Initial schema with OKLCH colors, semantic naming, WCAG AA validation

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,32 +38,118 @@ 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|write]
MODE: analysis
CONTEXT: [file references and memory context]
EXPECTED: [expected output]
RULES: [template reference and constraints]
"
# Qwen Architecture Analysis (仅分析)
# 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 goal]
TASK: [specific analysis task]
@@ -61,41 +159,44 @@ 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|write]
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
- [ ] **MODE** - Execution mode and permission level
- [ ] **CONTEXT** - File references and memory context from previous sessions
- [ ] **EXPECTED** - Clear expected results
- [ ] **RULES** - Template reference and constraints
### MODE Field Definition
The MODE field controls execution behavior and file permissions:
**For Gemini** (全权限,可读写):
- `analysis` (default) - 分析 + 可生成文档
- `write` - 创建/修改文件(自动启用 --approval-mode yolo
**For Qwen** (仅分析):
- `analysis` (default) - 仅架构分析,不生成代码
**For Codex**:
- `auto` (default) - 自主开发,全文件操作
- `write` - 测试生成和文件修改
### 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"`
@@ -103,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]
```
@@ -114,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 |
|-----------|------|----------|-----------|
@@ -127,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/
@@ -157,6 +295,8 @@ tech-stacks/
└── react-dev.md - React architecture
```
---
## 🚀 Usage Patterns
### Workflow Integration (REQUIRED)
@@ -168,8 +308,9 @@ When planning any coding task, **ALWAYS** integrate CLI tools:
4. **Quality Phase**: Use Codex for testing and validation
### Common Scenarios
#### Code Analysis
```bash
# Gemini - Code Analysis
~/.claude/scripts/gemini-wrapper -p "
PURPOSE: Understand codebase architecture
TASK: Analyze project structure and identify patterns
@@ -178,8 +319,10 @@ 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
"
```
# Gemini - Generate Documentation
#### Documentation Generation
```bash
~/.claude/scripts/gemini-wrapper -p "
PURPOSE: Generate API documentation
TASK: Create comprehensive API reference from code
@@ -188,8 +331,10 @@ CONTEXT: @{src/api/**/*}
EXPECTED: API.md with all endpoints documented
RULES: Follow project documentation standards
"
```
# Qwen - Architecture Analysis
#### Architecture Analysis
```bash
cd src/auth && ~/.claude/scripts/qwen-wrapper -p "
PURPOSE: Analyze authentication system architecture
TASK: Review JWT-based auth system design
@@ -198,8 +343,11 @@ 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
"
```
# Codex - Feature Development
#### 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
@@ -209,66 +357,46 @@ 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
# Codex - Test Generation
codex -C src/auth --full-auto exec "
# 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
# Continue in same session - Add tests
codex --full-auto exec "
PURPOSE: Increase test coverage
TASK: Generate comprehensive tests for auth module
MODE: write
CONTEXT: @{**/*.ts} Exclude existing tests
CONTEXT: Auth implementation from current session
EXPECTED: Complete test suite with 80%+ coverage
RULES: Use Jest, follow existing patterns
" --skip-git-repo-check -s danger-full-access
" resume --last --skip-git-repo-check -s danger-full-access
```
## 📋 Planning Checklist
#### Interactive Session Resume
```bash
# Resume previous session with picker
codex resume
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
# Or resume most recent session directly
codex resume --last
```
## 🎯 Key Features
### Gemini (全权限)
- **Command**: `~/.claude/scripts/gemini-wrapper`
- **Strengths**: Large context window, pattern recognition
- **Best For**: Analysis, documentation generation, code exploration
- **Permissions**: 可读写MODE=write 时自动启用 --approval-mode yolo
- **Default MODE**: `analysis`
### Qwen (仅分析)
- **Command**: `~/.claude/scripts/qwen-wrapper`
- **Strengths**: Architecture analysis, pattern recognition
- **Best For**: System design analysis, architectural review
- **Permissions**: 仅分析,不生成代码
- **Default MODE**: `analysis`
### Codex
- **Command**: `codex --full-auto exec`
- **Strengths**: Autonomous development, mathematical reasoning
- **Best For**: Implementation, testing, automation
- **Required**: `-s danger-full-access` and `--skip-git-repo-check` for development
- **Default MODE**: `auto`
### File Patterns
- All files: `@{**/*}`
- Source files: `@{src/**/*}`
- TypeScript: `@{*.ts,*.tsx}`
- With docs: `@{CLAUDE.md,**/*CLAUDE.md}`
- Tests: `@{src/**/*.test.*}`
---
## 🔧 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
@@ -310,4 +438,42 @@ CONTEXT: @{**/*.ts}
EXPECTED: Code improvements and fixes
RULES: Maintain backward compatibility
" --skip-git-repo-check -s danger-full-access
```
```
### 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

@@ -266,28 +266,73 @@ All workflows use the same file structure definition regardless of complexity. *
#### Complete Structure Reference
```
.workflow/WFS-[topic-slug]/
├── workflow-session.json # Session metadata and state (REQUIRED)
├── [.brainstorming/] # Optional brainstorming phase (created when needed)
├── [.chat/] # CLI interaction sessions (created when analysis is run)
│ ├── chat-*.md # Saved chat sessions
── analysis-*.md # Analysis results
├── [.process/] # Planning analysis results (created by /workflow:plan)
── ANALYSIS_RESULTS.md # Analysis results and planning artifacts
├── IMPL_PLAN.md # Planning document (REQUIRED)
├── TODO_LIST.md # Progress tracking (REQUIRED)
── [.summaries/] # Task completion summaries (created when tasks complete)
├── IMPL-*-summary.md # Main task summaries
── IMPL-*.*-summary.md # Subtask summaries
└── .task/ # Task definitions (REQUIRED)
├── IMPL-*.json # Main task definitions
└── IMPL-*.*.json # Subtask definitions (created dynamically)
.workflow/
├── [.scratchpad/] # Non-session-specific outputs (created when needed)
│ ├── analyze-*-[timestamp].md # One-off analysis results
├── chat-*-[timestamp].md # Standalone chat sessions
│ ├── plan-*-[timestamp].md # Ad-hoc planning notes
── bug-index-*-[timestamp].md # Quick bug analyses
│ ├── code-analysis-*-[timestamp].md # Standalone code analysis
── execute-*-[timestamp].md # Ad-hoc implementation logs
│ └── codex-execute-*-[timestamp].md # Multi-stage execution logs
── WFS-[topic-slug]/
├── workflow-session.json # Session metadata and state (REQUIRED)
── [.brainstorming/] # Optional brainstorming phase (created when needed)
├── [.chat/] # CLI interaction sessions (created when analysis is run)
│ ├── chat-*.md # Saved chat sessions
│ └── analysis-*.md # Analysis results
├── [.process/] # Planning analysis results (created by /workflow:plan)
│ └── ANALYSIS_RESULTS.md # Analysis results and planning artifacts
├── IMPL_PLAN.md # Planning document (REQUIRED)
├── TODO_LIST.md # Progress tracking (REQUIRED)
├── [.summaries/] # Task completion summaries (created when tasks complete)
│ ├── IMPL-*-summary.md # Main task summaries
│ └── IMPL-*.*-summary.md # Subtask summaries
└── .task/ # Task definitions (REQUIRED)
├── IMPL-*.json # Main task definitions
└── IMPL-*.*.json # Subtask definitions (created dynamically)
```
#### Creation Strategy
- **Initial Setup**: Create only `workflow-session.json`, `IMPL_PLAN.md`, `TODO_LIST.md`, and `.task/` directory
- **On-Demand Creation**: Other directories created when first needed
- **Dynamic Files**: Subtask JSON files created during task decomposition
- **Scratchpad Usage**: `.scratchpad/` created when CLI commands run without active session
#### Scratchpad Directory (.scratchpad/)
**Purpose**: Centralized location for non-session-specific CLI outputs
**When to Use**:
1. **No Active Session**: CLI analysis/chat commands run without an active workflow session
2. **Unrelated Analysis**: Quick analysis not related to current active session
3. **Exploratory Work**: Ad-hoc investigation before creating formal workflow
4. **One-Off Queries**: Standalone questions or debugging without workflow context
**Output Routing Logic**:
- **IF** active session exists AND command is session-relevant:
- Save to `.workflow/WFS-[id]/.chat/[command]-[timestamp].md`
- **ELSE** (no session OR one-off analysis):
- Save to `.workflow/.scratchpad/[command]-[description]-[timestamp].md`
**File Naming Pattern**: `[command-type]-[brief-description]-[timestamp].md`
**Examples**:
*Analysis Commands (read-only):*
- `/cli:analyze "security"` (no session) → `.scratchpad/analyze-security-20250105-143022.md`
- `/cli:chat "build process"` (unrelated to active session) → `.scratchpad/chat-build-process-20250105-143045.md`
- `/cli:mode:plan "feature idea"` (exploratory) → `.scratchpad/plan-feature-idea-20250105-143110.md`
- `/cli:mode:code-analysis "trace auth flow"` (no session) → `.scratchpad/code-analysis-auth-flow-20250105-143130.md`
*Implementation Commands (⚠️ modifies code):*
- `/cli:execute "implement JWT auth"` (no session) → `.scratchpad/execute-jwt-auth-20250105-143200.md`
- `/cli:codex-execute "refactor API layer"` (no session) → `.scratchpad/codex-execute-api-refactor-20250105-143230.md`
**Maintenance**:
- Periodically review and clean up old scratchpad files
- Promote useful analyses to formal workflow sessions if needed
- No automatic cleanup - manual management recommended
### File Naming Conventions

View File

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

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,430 @@ 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.5.0] - 2025-10-06
### 🎨 UI Design Workflow with Triple Vision Analysis
This release introduces a comprehensive UI design workflow system with triple vision analysis capabilities, interactive user checkpoints, and zero agent overhead for improved performance.
#### Added
**New UI Design Workflow System**:
- **`/workflow:design:auto`**: Semi-autonomous UI design workflow orchestrator
- Interactive checkpoints for user style selection and prototype confirmation
- Optional batch task generation with `--batch-plan` flag
- Pause-and-continue pattern at critical decision points
- Automatic progression between phases after user input
- Support for multiple UI variants per page (`--variants` parameter)
**Triple Vision Analysis Architecture**:
- **Phase 1: Claude Code Vision Analysis**: Quick initial visual analysis using native Read tool
- **Phase 2: Gemini Vision Analysis**: Deep semantic understanding of design intent
- **Phase 3: Codex Vision Analysis**: Structured pattern recognition with `-i` parameter
- **Phase 4: Consensus Synthesis**: Weighted combination by main Claude agent
- **Synthesis Strategy**:
- Color system: Consensus with Codex precision preference
- Typography: Gemini semantic + Codex measurements
- Spacing: Cross-validation across all three sources
- Design philosophy: Weighted with Gemini highest priority
- Conflict resolution: Majority vote or synthesis-specification.md context
**Individual Design Commands**:
- **`/workflow:design:style-extract`**: Extract design styles from reference images
- Triple vision analysis (Claude Code + Gemini + Codex)
- Generates `semantic_style_analysis.json`, `design-tokens.json`, `style-cards.json`
- Outputs multiple style variant cards for user selection
- Direct bash execution (no agent wrappers)
- **`/workflow:design:style-consolidate`**: Consolidate selected style variants
- Validates and merges design tokens
- Generates finalized `design-tokens.json`, `style-guide.md`, `tailwind.config.js`
- WCAG AA compliance validation
- Token coverage ≥90% requirement
- **`/workflow:design:ui-generate`**: Generate production-ready UI prototypes
- Token-driven HTML/CSS generation with Codex
- Support for `--style-overrides` parameter for runtime customization
- Generates `{page}-variant-{n}.html`, `{page}-variant-{n}.css` per page
- Semantic HTML5 with ARIA attributes
- Responsive design with token-based breakpoints
- **`/workflow:design:design-update`**: Integrate design system into brainstorming
- Updates `synthesis-specification.md` with UI/UX guidelines section
- Creates/updates `ui-designer/style-guide.md`
- Makes design tokens available for task generation phase
**Interactive Checkpoint System**:
- **Checkpoint 1 (After style-extract)**: User selects preferred style variants
- Command: `/workflow:design:style-consolidate --session WFS-xxx --variants "variant-1,variant-3"`
- Workflow pauses until user runs consolidation command
- **Checkpoint 2 (After ui-generate)**: User confirms selected prototypes
- Command: `/workflow:design:design-update --session WFS-xxx --selected-prototypes "page-variant-1,page-variant-2"`
- Workflow pauses until user runs design-update command
**Design System Features**:
- **OKLCH Color Format**: Perceptually uniform color space for design tokens
- **W3C Design Tokens Compatibility**: Standard-compliant token format
- **Style Override Mechanism**: Runtime token merging using jq
- **Batch Task Generation**: Automatic `/workflow:plan` invocation for each page
- **Accessibility Validation**: WCAG 2.1 AA compliance checks
#### Changed
**Agent Architecture Simplification**:
- **Removed agent wrappers** from `style-extract` and `ui-generate` commands
- Previously used `Task(conceptual-planning-agent)` for simple bash execution
- Now executes `gemini-wrapper` and `codex` commands directly via Bash tool
- Reduced execution overhead and complexity
- Preserved all functionality while improving performance
**Command Execution Pattern**:
- **Direct Bash Execution**: All CLI tools now use direct bash commands
- Gemini Vision: `bash(gemini-wrapper --approval-mode yolo -p "...")`
- Codex Vision: `bash(codex -i {images} --full-auto exec "..." -s danger-full-access)`
- Codex Token Generation: `bash(codex --full-auto exec "..." -s danger-full-access)`
- No intermediate agent layers
**Workflow Integration**:
- Design phase now optional but recommended for UI-heavy projects
- Seamless integration with existing brainstorming → planning → execution flow
- Design artifacts automatically discovered by `task-generate` if present
- UI tasks automatically include `load_design_tokens` in flow_control
**Updated Documentation**:
- **README.md**: Added UI Design Workflow section in Getting Started
- **README_CN.md**: Chinese documentation updated with design workflow
- **Command Reference**: Added 5 new `/workflow:design:*` commands
- **Phase Renumbering**: Shifted phases to accommodate new Phase 2 (UI Design)
#### Benefits
**User Experience**:
- 🎨 **Visual Validation**: Users confirm design before implementation starts
- ⏸️ **Interactive Control**: Critical design decisions require explicit user approval
- 👁️ **Comprehensive Analysis**: Three AI vision sources provide robust style extraction
- 🎯 **Zero Waiting**: Direct bash execution eliminates agent overhead
- 📦 **Automation Ready**: Optional batch task generation accelerates workflow
**Code Quality**:
- 🔒 **Token Enforcement**: 100% CSS values use custom properties (verified)
-**Accessibility**: WCAG AA validated at design phase
- 🎨 **Consistency**: Single source of truth for visual design (design-tokens.json)
- 🧪 **Production Ready**: Semantic HTML5, responsive, accessible prototypes
**Development Workflow**:
- 🔄 **Seamless Integration**: Optional design phase fits between brainstorming and planning
- 🚀 **Backward Compatible**: Existing workflows unaffected if design phase skipped
- 📊 **Better Planning**: Design system context improves task generation quality
- 🎯 **Focused Implementation**: Developers work from validated prototypes and tokens
#### Technical Details
**Triple Vision Analysis Flow**:
```
Reference Images
Phase 2: Claude Code (Read tool) → claude_vision_analysis.json
Phase 3: Gemini Vision (gemini-wrapper) → gemini_vision_analysis.json
Phase 4: Codex Vision (codex -i) → codex_vision_analysis.json
Phase 5: Main Claude Synthesis → semantic_style_analysis.json
Phase 6: Codex Token Generation → design-tokens.json, style-cards.json
```
**Checkpoint Workflow Pattern**:
```
User: /workflow:design:auto --session WFS-xxx --images "refs/*.png" --pages "dashboard,auth"
Phase 1: style-extract (automatic)
↓ [CHECKPOINT 1: User selects style variants]
User: /workflow:design:style-consolidate --session WFS-xxx --variants "variant-1,variant-3"
Phase 3: ui-generate (automatic after Phase 2)
↓ [CHECKPOINT 2: User confirms prototypes]
User: /workflow:design:design-update --session WFS-xxx --selected-prototypes "dashboard-variant-1,auth-variant-2"
Phase 5: batch-plan (optional, automatic if --batch-plan flag)
```
**Output Structure**:
```
.workflow/WFS-{session}/.design/
├── style-extraction/
│ ├── claude_vision_analysis.json
│ ├── gemini_vision_analysis.json
│ ├── codex_vision_analysis.json
│ ├── semantic_style_analysis.json (synthesis)
│ ├── design-tokens.json (preliminary)
│ └── style-cards.json (variants for selection)
├── style-consolidation/
│ ├── style-philosophy.md
│ ├── design-tokens.json (final, validated)
│ ├── style-guide.md
│ ├── tailwind.config.js
│ └── validation-report.json
└── prototypes/
├── {page}-variant-{n}.html (per page, per variant)
├── {page}-variant-{n}.css (token-driven styles)
├── {page}-variant-{n}-notes.md (implementation notes)
└── design-tokens.css (CSS custom properties)
```
**New Agent Documentation**:
- **`ui-design-agent.md`**: Specialized agent for UI/UX design workflows
- Vision analysis, token generation, prototype creation capabilities
- Multi-modal vision provider strategy (Gemini primary, Codex fallback)
- Quality gates: WCAG AA, token coverage ≥90%, component mapping ≥95%
- Flow control specification for 3 design phases
#### Use Cases
**When to Use Design Workflow**:
- User-facing applications with visual design requirements
- Design system creation and maintenance
- Brand-critical user interfaces
- Projects requiring accessibility compliance
- Multi-page applications with consistent styling
**When to Skip Design Workflow**:
- Backend APIs without UI components
- CLI tools and command-line applications
- Quick prototypes and MVPs
- Projects with existing design systems
---
## [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

View File

@@ -28,6 +28,7 @@ For all CLI tool usage, command syntax, and integration guidelines:
- **Learning from existing code** - Study and plan before implementing
- **Clear intent over clever code** - Be boring and obvious
- **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
@@ -56,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

@@ -63,7 +63,9 @@ param(
[string]$SourceVersion = "",
[string]$SourceBranch = ""
[string]$SourceBranch = "",
[string]$SourceCommit = ""
)
# Set encoding for proper Unicode support
@@ -78,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) {
@@ -141,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) {
@@ -167,6 +179,7 @@ function Test-Prerequisites {
$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
@@ -188,6 +201,11 @@ function Test-Prerequisites {
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
}
@@ -632,24 +650,27 @@ function Create-VersionJson {
[string]$InstallationMode
)
# Determine version from source or default
$versionNumber = if ($SourceVersion) { $SourceVersion } else { $Version }
# 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 ($InstallationMode)" $ColorSuccess
Write-ColorOutput "Created version.json: $versionNumber ($commitSha) - $InstallationMode" $ColorSuccess
return $true
} catch {
Write-ColorOutput "WARNING: Failed to create version.json: $($_.Exception.Message)" $ColorWarning
@@ -666,6 +687,7 @@ function Install-Global {
$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
@@ -675,11 +697,12 @@ function Install-Global {
$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) -or (Test-Path $globalCodexDir) -or (Test-Path $globalGeminiDir)) {
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
@@ -690,6 +713,9 @@ function Install-Global {
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
@@ -717,6 +743,10 @@ function Install-Global {
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"
@@ -753,16 +783,18 @@ function Install-Path {
$sourceClaudeMd = Join-Path $sourceDir "CLAUDE.md"
$sourceCodexDir = Join-Path $sourceDir ".codex"
$sourceGeminiDir = Join-Path $sourceDir ".gemini"
$sourceQwenDir = Join-Path $sourceDir ".qwen"
# Local paths - for agents, commands, output-styles, .codex, .gemini
# 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 $localCodexDir) -or (Test-Path $localGeminiDir) -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
}
@@ -858,6 +890,10 @@ function Install-Path {
Write-ColorOutput "Merging .gemini directory contents to local location..." $ColorInfo
$geminiMerged = Merge-DirectoryContents -Source $sourceGeminiDir -Destination $localGeminiDir -Description ".gemini directory contents" -BackupFolder $backupFolder
# 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"
@@ -971,11 +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, .codex, .gemini"
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"
Write-Host " Global Components: .claude, .codex, .gemini, .qwen"
}
if ($NoBackup) {
@@ -991,10 +1027,11 @@ function Show-Summary {
Write-Host "1. Review CLAUDE.md - Customize guidelines for your project"
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. Configure settings - Edit .claude/settings.local.json as needed"
Write-Host "5. Start using Claude Code with Agent workflow coordination!"
Write-Host "6. Use /workflow commands for task execution"
Write-Host "7. Use /update-memory commands for memory system management"
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
@@ -1002,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

@@ -24,6 +24,9 @@ FORCE=false
NON_INTERACTIVE=false
BACKUP_ALL=true # Enabled by default
NO_BACKUP=false
SOURCE_VERSION="" # Version from remote installer
SOURCE_BRANCH="" # Branch from remote installer
SOURCE_COMMIT="" # Commit SHA from remote installer
# Functions
function write_color() {
@@ -87,8 +90,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
@@ -99,6 +102,7 @@ function test_prerequisites() {
local claude_md="$script_dir/CLAUDE.md"
local codex_dir="$script_dir/.codex"
local gemini_dir="$script_dir/.gemini"
local qwen_dir="$script_dir/.qwen"
if [ ! -d "$claude_dir" ]; then
write_color "ERROR: .claude directory not found in $script_dir" "$COLOR_ERROR"
@@ -120,6 +124,11 @@ function test_prerequisites() {
return 1
fi
if [ ! -d "$qwen_dir" ]; then
write_color "ERROR: .qwen directory not found in $script_dir" "$COLOR_ERROR"
return 1
fi
write_color "✓ Prerequisites check passed" "$COLOR_SUCCESS"
return 0
}
@@ -403,6 +412,7 @@ function install_global() {
local global_claude_md="${global_claude_dir}/CLAUDE.md"
local global_codex_dir="${user_home}/.codex"
local global_gemini_dir="${user_home}/.gemini"
local global_qwen_dir="${user_home}/.qwen"
write_color "Global installation path: $user_home" "$COLOR_INFO"
@@ -412,6 +422,7 @@ function install_global() {
local source_claude_md="${script_dir}/CLAUDE.md"
local source_codex_dir="${script_dir}/.codex"
local source_gemini_dir="${script_dir}/.gemini"
local source_qwen_dir="${script_dir}/.qwen"
# Create backup folder if needed
local backup_folder=""
@@ -424,6 +435,8 @@ function install_global() {
has_existing_files=true
elif [ -d "$global_gemini_dir" ] && [ "$(ls -A "$global_gemini_dir" 2>/dev/null)" ]; then
has_existing_files=true
elif [ -d "$global_qwen_dir" ] && [ "$(ls -A "$global_qwen_dir" 2>/dev/null)" ]; then
has_existing_files=true
elif [ -f "$global_claude_md" ]; then
has_existing_files=true
fi
@@ -450,6 +463,10 @@ function install_global() {
write_color "Merging .gemini directory contents..." "$COLOR_INFO"
merge_directory_contents "$source_gemini_dir" "$global_gemini_dir" ".gemini directory contents" "$backup_folder"
# Merge .qwen directory contents
write_color "Merging .qwen directory contents..." "$COLOR_INFO"
merge_directory_contents "$source_qwen_dir" "$global_qwen_dir" ".qwen 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
@@ -458,6 +475,10 @@ function install_global() {
fi
fi
# Create version.json in global .claude directory
write_color "Creating version.json..." "$COLOR_INFO"
create_version_json "$global_claude_dir" "Global"
return 0
}
@@ -477,16 +498,18 @@ function install_path() {
local source_claude_md="${script_dir}/CLAUDE.md"
local source_codex_dir="${script_dir}/.codex"
local source_gemini_dir="${script_dir}/.gemini"
local source_qwen_dir="${script_dir}/.qwen"
# Local paths
local local_claude_dir="${target_dir}/.claude"
local local_codex_dir="${target_dir}/.codex"
local local_gemini_dir="${target_dir}/.gemini"
local local_qwen_dir="${target_dir}/.qwen"
# Create backup folder if needed
local backup_folder=""
if [ "$NO_BACKUP" = false ]; then
if [ -d "$local_claude_dir" ] || [ -d "$local_codex_dir" ] || [ -d "$local_gemini_dir" ] || [ -d "$global_claude_dir" ]; then
if [ -d "$local_claude_dir" ] || [ -d "$local_codex_dir" ] || [ -d "$local_gemini_dir" ] || [ -d "$local_qwen_dir" ] || [ -d "$global_claude_dir" ]; then
backup_folder=$(get_backup_directory "$target_dir")
write_color "Backup folder created: $backup_folder" "$COLOR_INFO"
fi
@@ -575,6 +598,10 @@ function install_path() {
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"
# Merge .qwen directory contents to local location
write_color "Merging .qwen directory contents to local location..." "$COLOR_INFO"
merge_directory_contents "$source_qwen_dir" "$local_qwen_dir" ".qwen 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
@@ -583,12 +610,20 @@ function install_path() {
fi
fi
# Create version.json in local .claude directory
write_color "Creating version.json in local directory..." "$COLOR_INFO"
create_version_json "$local_claude_dir" "Path"
# Also create version.json in global .claude directory
write_color "Creating version.json in global directory..." "$COLOR_INFO"
create_version_json "$global_claude_dir" "Global"
return 0
}
function get_installation_mode() {
if [ -n "$INSTALL_MODE" ]; then
write_color "Installation mode: $INSTALL_MODE" "$COLOR_INFO"
write_color "Installation mode: $INSTALL_MODE" "$COLOR_INFO" >&2
echo "$INSTALL_MODE"
return
fi
@@ -658,6 +693,42 @@ function get_installation_path() {
done
}
function create_version_json() {
local target_claude_dir="$1"
local installation_mode="$2"
# Determine version from source parameter (passed from install-remote.sh)
local version_number="${SOURCE_VERSION:-unknown}"
local source_branch="${SOURCE_BRANCH:-unknown}"
local commit_sha="${SOURCE_COMMIT:-unknown}"
# Get current UTC timestamp
local installation_date_utc=$(date -u +"%Y-%m-%dT%H:%M:%SZ" 2>/dev/null || date -u +"%Y-%m-%dT%H:%M:%SZ")
# Create version.json content
local version_json_path="${target_claude_dir}/version.json"
cat > "$version_json_path" << EOF
{
"version": "$version_number",
"commit_sha": "$commit_sha",
"installation_mode": "$installation_mode",
"installation_path": "$target_claude_dir",
"installation_date_utc": "$installation_date_utc",
"source_branch": "$source_branch",
"installer_version": "$VERSION"
}
EOF
if [ -f "$version_json_path" ]; then
write_color "Created version.json: $version_number ($commit_sha) - $installation_mode" "$COLOR_SUCCESS"
return 0
else
write_color "WARNING: Failed to create version.json" "$COLOR_WARNING"
return 1
fi
}
function show_summary() {
local mode="$1"
local path="$2"
@@ -676,11 +747,11 @@ function show_summary() {
if [ "$mode" = "Path" ]; then
echo " Local Path: $path"
echo " Global Path: $HOME"
echo " Local Components: agents, commands, output-styles, .codex, .gemini"
echo " Local Components: agents, commands, output-styles, .codex, .gemini, .qwen"
echo " Global Components: workflows, scripts, python_script, etc."
else
echo " Path: $path"
echo " Global Components: .claude, .codex, .gemini"
echo " Global Components: .claude, .codex, .gemini, .qwen"
fi
if [ "$NO_BACKUP" = true ]; then
@@ -696,10 +767,11 @@ function show_summary() {
echo "1. Review CLAUDE.md - Customize guidelines for your project"
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 "4. Review .qwen/QWEN.md - Qwen agent execution protocol"
echo "5. Configure settings - Edit .claude/settings.local.json as needed"
echo "6. Start using Claude Code with Agent workflow coordination!"
echo "7. Use /workflow commands for task execution"
echo "8. Use /update-memory commands for memory system management"
echo ""
write_color "Documentation: https://github.com/catlog22/Claude-Code-Workflow" "$COLOR_INFO"
@@ -735,6 +807,18 @@ function parse_arguments() {
BACKUP_ALL=false
shift
;;
-SourceVersion)
SOURCE_VERSION="$2"
shift 2
;;
-SourceBranch)
SOURCE_BRANCH="$2"
shift 2
;;
-SourceCommit)
SOURCE_COMMIT="$2"
shift 2
;;
--help|-h)
show_help
exit 0
@@ -761,6 +845,9 @@ Options:
-NonInteractive Run in non-interactive mode with default options
-BackupAll Automatically backup all existing files (default)
-NoBackup Disable automatic backup functionality
-SourceVersion <ver> Source version (passed from install-remote.sh)
-SourceBranch <name> Source branch (passed from install-remote.sh)
-SourceCommit <sha> Source commit SHA (passed from install-remote.sh)
--help, -h Show this help message
Examples:
@@ -776,6 +863,9 @@ Examples:
# Installation without backup
$0 -NoBackup
# With version info (typically called by install-remote.sh)
$0 -InstallMode Global -Force -SourceVersion "3.4.2" -SourceBranch "main" -SourceCommit "abc1234"
EOF
}

226
README.md
View File

@@ -2,7 +2,7 @@
<div align="center">
[![Version](https://img.shields.io/badge/version-v3.2.3-blue.svg)](https://github.com/catlog22/Claude-Code-Workflow/releases)
[![Version](https://img.shields.io/badge/version-v3.5.0-blue.svg)](https://github.com/catlog22/Claude-Code-Workflow/releases)
[![License](https://img.shields.io/badge/license-MIT-green.svg)](LICENSE)
[![Platform](https://img.shields.io/badge/platform-Windows%20%7C%20Linux%20%7C%20macOS-lightgrey.svg)]()
[![MCP Tools](https://img.shields.io/badge/🔧_MCP_Tools-Experimental-orange.svg)](https://github.com/modelcontextprotocol)
@@ -15,14 +15,16 @@
**Claude Code Workflow (CCW)** is a next-generation multi-agent automation framework that orchestrates complex software development tasks through intelligent workflow management and autonomous execution.
> **🎉 Latest: v3.2.3** - Version management system with upgrade notifications. See [CHANGELOG.md](CHANGELOG.md) for details.
> **🎉 Latest: v3.5.0** - UI Design Workflow with Triple Vision Analysis. See [CHANGELOG.md](CHANGELOG.md) for details.
>
> **What's New in v3.2.3**:
> - 🔍 New `/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
> **What's New in v3.5.0**:
> - 🎨 **UI Design Workflow**: Complete design refinement workflow from style extraction to prototype generation
> - 👁️ **Triple Vision Analysis**: Combines Claude Code + Gemini + Codex vision capabilities for comprehensive style extraction
> - ⏸️ **Interactive Checkpoints**: User selection points for style variants and prototype confirmation
> - 🎯 **Zero Agent Overhead**: Direct bash execution for CLI tools, removing unnecessary agent wrappers
> - 🎨 **Style Customization**: Runtime override support with `--style-overrides` parameter
> - 📦 **Batch Task Generation**: Optional automatic task creation for selected prototypes with `--batch-plan`
> - 🔄 **Semi-Autonomous Workflow**: User-driven continuation at critical design decision points
---
@@ -143,6 +145,98 @@ After installation, run the following command to ensure CCW is working:
---
## ⚙️ 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
### Complete Development Workflow
@@ -157,7 +251,19 @@ After installation, run the following command to ensure CCW is working:
/workflow:brainstorm:synthesis # Generate consolidated specification
```
**Phase 2: Action Planning**
**Phase 2: UI Design Refinement** *(Optional for UI-heavy projects)*
```bash
# Extract design styles from reference images and generate prototypes
/workflow:design:auto --session WFS-auth --images "design-refs/*.png" --pages "login,register" --batch-plan
# Or run individual design phases
/workflow:design:style-extract --session WFS-auth --images "refs/*.png"
/workflow:design:style-consolidate --session WFS-auth --variants "variant-1,variant-3"
/workflow:design:ui-generate --session WFS-auth --pages "login,register" --variants 2
/workflow:design:design-update --session WFS-auth --selected-prototypes "login-variant-1,register-variant-2"
```
**Phase 3: Action Planning**
```bash
# Create executable implementation plan
/workflow:plan "Implement JWT-based authentication system"
@@ -166,7 +272,7 @@ After installation, run the following command to ensure CCW is working:
/workflow:tdd-plan "Implement authentication with test-first development"
```
**Phase 3: Execution**
**Phase 4: Execution**
```bash
# Execute tasks with AI agents
/workflow:execute
@@ -175,7 +281,7 @@ After installation, run the following command to ensure CCW is working:
/workflow:status
```
**Phase 4: Testing & Quality Assurance**
**Phase 5: Testing & Quality Assurance**
```bash
# Generate independent test-fix workflow (v3.2.2+)
/workflow:test-gen WFS-auth # Creates WFS-test-auth session
@@ -248,13 +354,21 @@ 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:design:auto` | **NEW** Semi-autonomous UI design workflow with interactive checkpoints for style and prototype selection. |
| `/workflow:design:style-extract` | **NEW** Extract design styles from reference images using triple vision analysis (Claude + Gemini + Codex). |
| `/workflow:design:style-consolidate` | **NEW** Consolidate selected style variants into validated design tokens and style guide. |
| `/workflow:design:ui-generate` | **NEW** Generate token-driven HTML/CSS prototypes with optional style overrides. |
| `/workflow:design:design-update` | **NEW** Integrate finalized design system into brainstorming artifacts. |
| `/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` | Create independent test-fix workflow for validating completed implementation. |
| `/workflow:test-gen [--use-codex] <session>` | Create test generation workflow with auto-diagnosis and fix cycle for completed implementations. |
| `/workflow:tdd-verify` | Verify TDD compliance and generate quality report. |
| `/workflow:review` | **Optional** manual review (only use when explicitly needed - passing tests = approved code). |
| `/workflow:tools:test-context-gather` | Analyze test coverage and identify missing test files. |
| `/workflow:tools:test-concept-enhanced` | Generate test strategy and requirements analysis using Gemini. |
| `/workflow:tools:test-task-generate` | Generate test task JSON with test-fix-cycle specification. |
### **Task & Memory Commands**
@@ -267,92 +381,6 @@ After installation, run the following command to ensure CCW is working:
---
## ⚙️ 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
```
### **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
---
## 🧩 How It Works: Design Philosophy
### The Core Problem

View File

@@ -2,7 +2,7 @@
<div align="center">
[![Version](https://img.shields.io/badge/version-v3.2.3-blue.svg)](https://github.com/catlog22/Claude-Code-Workflow/releases)
[![Version](https://img.shields.io/badge/version-v3.5.0-blue.svg)](https://github.com/catlog22/Claude-Code-Workflow/releases)
[![License](https://img.shields.io/badge/license-MIT-green.svg)](LICENSE)
[![Platform](https://img.shields.io/badge/platform-Windows%20%7C%20Linux%20%7C%20macOS-lightgrey.svg)]()
[![MCP工具](https://img.shields.io/badge/🔧_MCP工具-实验性-orange.svg)](https://github.com/modelcontextprotocol)
@@ -15,14 +15,16 @@
**Claude Code Workflow (CCW)** 是一个新一代的多智能体自动化开发框架,通过智能工作流管理和自主执行来协调复杂的软件开发任务。
> **🎉 最新版本: v3.2.3** - 版本管理系统与升级通知。详见 [CHANGELOG.md](CHANGELOG.md)。
> **🎉 最新版本: v3.5.0** - UI 设计工作流与三重视觉分析。详见 [CHANGELOG.md](CHANGELOG.md)。
>
> **v3.2.3 版本新特性**:
> - 🔍 新增 `/version` 命令用于检查已安装版本
> - 📊 GitHub API 集成,获取最新版本信息
> - 🔄 自动升级通知与建议
> - 📁 支持本地和全局安装的版本跟踪
> - ⚡ 一键版本检查,全面展示状态信息
> **v3.5.0 版本新特性**:
> - 🎨 **UI 设计工作流**: 从风格提取到原型生成的完整设计精炼工作流
> - 👁️ **三重视觉分析**: 融合 Claude Code + Gemini + Codex 视觉能力进行综合风格提取
> - ⏸️ **交互式检查点**: 用户选择风格变体和原型确认的决策点
> - 🎯 **零智能体开销**: CLI 工具直接 bash 执行,移除不必要的智能体包装
> - 🎨 **风格自定义**: 通过 `--style-overrides` 参数支持运行时样式覆盖
> - 📦 **批量任务生成**: 使用 `--batch-plan` 为选定原型自动创建实现任务
> - 🔄 **半自主工作流**: 在关键设计决策点由用户驱动继续
---
@@ -143,6 +145,98 @@ bash <(curl -fsSL https://raw.githubusercontent.com/catlog22/Claude-Code-Workflo
---
## ⚙️ 配置
### **前置要求:必需工具**
在使用 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 工具可用。如果没有安装,您可能会遇到:
- 代码分析和搜索操作速度较慢
- 某些场景下上下文质量降低
- 回退到效率较低的传统工具
- 高级工作流中可能出现意外行为
---
## 🚀 快速入门
### 完整开发工作流
@@ -157,7 +251,19 @@ bash <(curl -fsSL https://raw.githubusercontent.com/catlog22/Claude-Code-Workflo
/workflow:brainstorm:synthesis # 生成综合规范
```
**阶段 2行动规划**
**阶段 2UI 设计精炼** *(UI 密集型项目可选)*
```bash
# 从参考图像中提取设计风格并生成原型
/workflow:design:auto --session WFS-auth --images "design-refs/*.png" --pages "login,register" --batch-plan
# 或者运行单独的设计阶段
/workflow:design:style-extract --session WFS-auth --images "refs/*.png"
/workflow:design:style-consolidate --session WFS-auth --variants "variant-1,variant-3"
/workflow:design:ui-generate --session WFS-auth --pages "login,register" --variants 2
/workflow:design:design-update --session WFS-auth --selected-prototypes "login-variant-1,register-variant-2"
```
**阶段 3行动规划**
```bash
# 创建可执行的实现计划
/workflow:plan "实现基于 JWT 的认证系统"
@@ -166,7 +272,7 @@ bash <(curl -fsSL https://raw.githubusercontent.com/catlog22/Claude-Code-Workflo
/workflow:tdd-plan "使用测试优先开发实现认证"
```
**阶段 3:执行**
**阶段 4:执行**
```bash
# 使用 AI 智能体执行任务
/workflow:execute
@@ -175,7 +281,7 @@ bash <(curl -fsSL https://raw.githubusercontent.com/catlog22/Claude-Code-Workflo
/workflow:status
```
**阶段 4:测试与质量保证**
**阶段 5:测试与质量保证**
```bash
# 生成独立测试修复工作流v3.2.2+
/workflow:test-gen WFS-auth # 创建 WFS-test-auth 会话
@@ -248,13 +354,21 @@ bash <(curl -fsSL https://raw.githubusercontent.com/catlog22/Claude-Code-Workflo
|---|---|
| `/workflow:session:*` | 管理开发会话(`start`, `pause`, `resume`, `list`, `switch`, `complete`)。 |
| `/workflow:brainstorm:*` | 使用基于角色的智能体进行多视角规划。 |
| `/workflow:design:auto` | **新增** 带交互式检查点的半自主 UI 设计工作流,用于风格和原型选择。 |
| `/workflow:design:style-extract` | **新增** 使用三重视觉分析Claude + Gemini + Codex从参考图像提取设计风格。 |
| `/workflow:design:style-consolidate` | **新增** 将选定的风格变体整合为经过验证的设计令牌和风格指南。 |
| `/workflow:design:ui-generate` | **新增** 生成基于令牌的 HTML/CSS 原型,支持可选的风格覆盖。 |
| `/workflow:design:design-update` | **新增** 将最终确定的设计系统集成到头脑风暴产物中。 |
| `/workflow:plan` | 从描述创建详细、可执行的计划。 |
| `/workflow:tdd-plan` | 创建测试驱动开发工作流,包含 Red-Green-Refactor 循环。 |
| `/workflow:tdd-plan` | 创建 TDD 工作流6 阶段),包含测试覆盖分析和 Red-Green-Refactor 循环。 |
| `/workflow:execute` | 自主执行当前的工作流计划。 |
| `/workflow:status` | 显示工作流的当前状态。 |
| `/workflow:test-gen` | 创建独立测试修复工作流,用于验证已完成的实现。 |
| `/workflow:test-gen [--use-codex] <session>` | 为已完成实现创建独立测试生成工作流,支持自动诊断和修复。 |
| `/workflow:tdd-verify` | 验证 TDD 合规性并生成质量报告。 |
| `/workflow:review` | **可选** 手动审查(仅在明确需要时使用,测试通过即代表代码已批准)。 |
| `/workflow:tools:test-context-gather` | 分析测试覆盖率,识别缺失的测试文件。 |
| `/workflow:tools:test-concept-enhanced` | 使用 Gemini 生成测试策略和需求分析。 |
| `/workflow:tools:test-task-generate` | 生成测试任务 JSON包含 test-fix-cycle 规范。 |
### **任务与内存命令**
@@ -267,92 +381,6 @@ bash <(curl -fsSL https://raw.githubusercontent.com/catlog22/Claude-Code-Workflo
---
## ⚙️ 配置
### **前置要求:必需工具**
在使用 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 服务器 | 用途 | 安装指南 |
|------------|------|---------|
| **Exa MCP** | 外部 API 模式和最佳实践 | [安装指南](https://github.com/exa-labs/exa-mcp-server) |
| **Code Index MCP** | 高级内部代码搜索 | [安装指南](https://github.com/johnhuang316/code-index-mcp) |
#### 启用后的好处
- 📊 **更快分析**: 直接代码库索引 vs 手动搜索
- 🌐 **外部上下文**: 真实世界的 API 模式和示例
- 🔍 **高级搜索**: 模式匹配和相似性检测
-**自动回退**: MCP 不可用时使用传统工具
---
## 🧩 工作原理:设计理念
### 核心问题

View File

@@ -260,7 +260,8 @@ function Invoke-LocalInstaller {
param(
[string]$RepoDir,
[string]$VersionInfo = "",
[string]$BranchInfo = ""
[string]$BranchInfo = "",
[string]$CommitSha = ""
)
$installerPath = Join-Path $RepoDir "Install-Claude.ps1"
@@ -285,9 +286,10 @@ function Invoke-LocalInstaller {
if ($NonInteractive) { $params["NonInteractive"] = $NonInteractive }
if ($BackupAll) { $params["BackupAll"] = $BackupAll }
# Pass version and branch information
# 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
@@ -416,10 +418,10 @@ function Get-UserVersionChoice {
$response = Invoke-RestMethod -Uri $apiUrl -UseBasicParsing -TimeoutSec 5
$latestVersion = $response.tag_name
# Parse and format release date
# Parse and format release date to local time
if ($response.published_at) {
$publishDate = [DateTime]::Parse($response.published_at)
$latestStableDate = $publishDate.ToString("yyyy-MM-dd HH:mm UTC")
$publishDate = [DateTime]::Parse($response.published_at).ToLocalTime()
$latestStableDate = $publishDate.ToString("yyyy-MM-dd HH:mm")
}
Write-ColorOutput "Latest stable: $latestVersion ($latestStableDate)" $ColorSuccess
@@ -433,10 +435,10 @@ function Get-UserVersionChoice {
$commitResponse = Invoke-RestMethod -Uri $commitUrl -UseBasicParsing -TimeoutSec 5
$latestCommitId = $commitResponse.sha.Substring(0, 7)
# Parse and format commit date
# Parse and format commit date to local time
if ($commitResponse.commit.committer.date) {
$commitDate = [DateTime]::Parse($commitResponse.commit.committer.date)
$latestCommitDate = $commitDate.ToString("yyyy-MM-dd HH:mm UTC")
$commitDate = [DateTime]::Parse($commitResponse.commit.committer.date).ToLocalTime()
$latestCommitDate = $commitDate.ToString("yyyy-MM-dd HH:mm")
}
Write-ColorOutput "Latest commit: $latestCommitId ($latestCommitDate)" $ColorSuccess
@@ -562,14 +564,51 @@ function Main {
throw "Extraction failed"
}
# 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) { $Tag } else { "latest" }
$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)" $ColorInfo
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
$success = Invoke-LocalInstaller -RepoDir $repoDir -VersionInfo $versionToPass -BranchInfo $branchToPass -CommitSha $commitSha
if (-not $success) {
throw "Installation script failed"
}

View File

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