Compare commits

...

245 Commits

Author SHA1 Message Date
catlog22
51a0cb3a3c docs: release v4.6.2 - documentation optimization and /memory:load refinement
### Documentation Optimization

**Optimized `/memory:load` Command Specification**:
- Reduced documentation from 273 to 240 lines (12% reduction)
- Merged redundant sections for better information flow
- Removed unnecessary internal implementation details
- Simplified usage examples while preserving clarity
- Maintained all critical information (parameters, workflow, JSON structure)

### Documentation Updates

**CHANGELOG.md**:
- Added v4.6.2 release entry with documentation improvements

**COMMAND_SPEC.md**:
- Updated `/memory:load` specification to match actual implementation
- Corrected syntax: `[--tool gemini|qwen]` instead of outdated `[--agent] [--json]` flags
- Added agent-driven execution details

**GETTING_STARTED.md**:
- Added "Quick Context Loading for Specific Tasks" section
- Positioned between "Full Project Index Rebuild" and "Incremental Related Module Updates"
- Includes practical examples and use case guidance

**README.md**:
- Updated version badge to v4.6.2
- Updated latest release description

**COMMAND_REFERENCE.md**:
- Added `/memory:load` command reference entry

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

Co-Authored-By: Claude <noreply@anthropic.com>
2025-10-20 10:58:31 +08:00
catlog22
436c7909b0 feat: 添加完整的卸载功能支持
- 添加 -Uninstall 参数支持交互式和命令行卸载
- 实现 manifest 跟踪系统,记录每次安装的文件和目录
- 支持多个安装的选择性卸载
- 修复关键 bug: 从源目录扫描文件而非目标目录,避免误删用户文件
- 添加操作模式选择 UI (Install/Uninstall)
- 自动迁移旧版 manifest 到新的多文件系统
- PowerShell 和 Bash 版本功能完全对等

Closes #5

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

Co-Authored-By: Claude <noreply@anthropic.com>
2025-10-20 10:24:50 +08:00
catlog22
f8d5d908ea feat: 修复workflow用户意图传递链,确保原始提示词贯穿全流程
## 核心问题
根据Gemini深度分析,用户原始提示词在brainstorm→plan流程中逐步被稀释,
synthesis环节完全不接收用户提示词,导致最终产出偏离用户意图。

## 关键修改

### 1. synthesis.md - 修复最严重偏差环节
- 新增从workflow-session.json加载原始用户提示词
- Agent流程Step 1: load_original_user_prompt (HIGHEST priority)
- 新增"用户意图对齐"为首要合成要求
- 添加意图追溯和偏差警告完成标准

### 2. concept-clarify.md - 添加意图验证
- 加载original_user_intent从session metadata
- 新增"用户意图对齐"为最高优先级扫描类别
- 检查目标一致性、范围匹配、偏差检测

### 3. action-plan-verify.md - 强化验证门禁
- workflow-session.json作为主要参考源
- 新增"用户意图对齐"为CRITICAL级别检测
- 违反用户意图标记为CRITICAL严重性

### 4. plan.md - 确立意图优先级
- 明确用户原始意图始终为主要参考
- 优先级规则: 当前用户提示词 > synthesis > topic-framework

### 5. artifacts.md - 推广结构化格式
- 添加推荐的GOAL/SCOPE/CONTEXT结构化格式
- 强调用户意图保存的重要性

### 6. auto-parallel.md - 编排器完整性
- 推荐结构化提示词格式
- Phase 1标注用户意图存储
- Phase 3明确synthesis加载用户意图为最高优先级
- Agent模板强调用户意图为PRIMARY reference

## 影响力提升
用户提示词影响力: 30% → 95%

## 参考
分析报告由Gemini生成,识别了5个关键问题点并提供4条改进建议

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

Co-Authored-By: Claude <noreply@anthropic.com>
2025-10-19 20:25:45 +08:00
catlog22
ac8c3b3d0c docs: 优化文档准确性和安装说明
- 修正 Agent Skills 描述,明确区分 -e 和 --enhance 机制
- 简化 INSTALL.md,对齐 README.md 的清晰结构
- 移除不必要的远程安装参数说明
- 优化 MCP 工具配置说明

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

Co-Authored-By: Claude <noreply@anthropic.com>
2025-10-19 13:17:19 +08:00
catlog22
423289c539 docs: 更新 MCP 工具官方源码链接 2025-10-19 10:22:53 +08:00
catlog22
21ea77bdf3 docs: 更新 MCP 工具官方源链接 2025-10-19 10:20:47 +08:00
catlog22
03ffc91764 docs: 简化 MCP 工具安装说明
主要变更:
- INSTALL.md 和 INSTALL_CN.md
  - 简化 MCP 工具安装部分
  - 只保留工具名称、用途和官方源代码库链接
  - 移除具体安装步骤,让用户根据官方文档安装
  - 保持表格格式清晰易读

改进原因:
- MCP 工具安装方式可能随时更新
- 官方文档是最准确的安装指南
- 避免维护多份安装说明

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

Co-Authored-By: Claude <noreply@anthropic.com>
2025-10-19 09:51:03 +08:00
catlog22
ee3a420f60 docs: 完善文档引用和安装说明
主要变更:
1. README.md 和 README_CN.md
   - 添加 COMMAND_SPEC.md 引用链接
   - 区分用户友好参考和技术规范

2. GETTING_STARTED.md
   - 添加 Skill 系统介绍章节
   - 添加 UI 设计工作流介绍
   - 包含 prompt-enhancer 使用示例
   - 包含 explore-auto 和 imitate-auto 示例

3. INSTALL.md 和 INSTALL_CN.md
   - 添加推荐系统工具安装说明(ripgrep, jq)
   - 添加 MCP 工具安装说明(Exa, Code Index, Chrome DevTools)
   - 添加可选 CLI 工具说明(Gemini, Codex, Qwen)
   - 提供各平台安装命令和验证步骤
   - 标注必需和可选工具

改进效果:
- 用户可快速找到技术规范文档
- 新手指南更完整,覆盖高级功能
- 安装文档更详细,包含所有依赖工具

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

Co-Authored-By: Claude <noreply@anthropic.com>
2025-10-19 09:44:48 +08:00
catlog22
9151a82d1d docs: 优化 README 文档并创建命令参考文档
主要变更:
1. 精简 README.md 和 README_CN.md 结构
   - 移除冗长的功能描述和安装细节
   - 合并理念章节为"核心概念"
   - 简化安装说明,链接到详细 INSTALL.md
   - 移除详细命令列表,链接到新的 COMMAND_REFERENCE.md

2. 创建 COMMAND_REFERENCE.md
   - 完整的命令列表和分类
   - 按功能组织(Workflow, CLI, Task, Memory, UI Design, Testing)
   - 包含所有遗漏的命令(UI 设计、测试工作流等)

3. 创建 COMMAND_SPEC.md
   - 详细的命令技术规范
   - 包含参数、职责、Agent 调用、Skill 调用
   - 实际使用示例
   - 命令间的工作流集成说明

4. 修正 Critical 级别问题
   - 统一仓库 URL 为 Claude-Code-Workflow
   - 更新 INSTALL.md 中的过时信息

5. 文档引用优化
   - 在 README 中添加到 COMMAND_REFERENCE.md 和 COMMAND_SPEC.md 的链接
   - 保持中英文文档结构一致

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

Co-Authored-By: Claude <noreply@anthropic.com>
2025-10-18 23:37:24 +08:00
catlog22
24aad6238a feat: add dynamic output format for prompt-enhancer and update README
- Redesign output format to be dynamic and task-adaptive
- Replace fixed template with core + optional fields structure
- Add simple and complex task examples
- Update workflow and enhancement guidelines
- Add Agent Skills section to README.md and README_CN.md
- Document Prompt Enhancer skill usage with -e/--enhance flags
- Provide skill creation best practices

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

Co-Authored-By: Claude <noreply@anthropic.com>
2025-10-18 23:00:08 +08:00
catlog22
44734a447c refactor: clarify prompt-enhancer trigger condition in description
- Update description to follow skills.md best practices
- Explicitly state trigger condition: 'Use when user input contains -e or --enhance flag'
- Improve discoverability with clear when-to-use guidance

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

Co-Authored-By: Claude <noreply@anthropic.com>
2025-10-18 22:47:05 +08:00
catlog22
99cb29ed23 refactor: simplify prompt-enhancer skill description and internal analysis
- Update description: focus on intelligent analysis and session memory
- Simplify trigger mechanism to only -e/--enhance flags
- Condense internal analysis section to single concise statement
- Remove verbose semantic analysis details for cleaner documentation

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

Co-Authored-By: Claude <noreply@anthropic.com>
2025-10-18 22:41:25 +08:00
catlog22
b8935777e7 refactor: enhance prompt generation process with direct output and improved internal analysis 2025-10-18 22:33:29 +08:00
catlog22
49c2b189d4 refactor: streamline prompt-enhancer skill for faster execution
- Simplified process from 4 steps to 3 steps
- Changed to memory-only extraction (no file reading)
- Updated confirmation options: added "Suggest optimizations"
- Removed file operation tools (Bash, Read, Glob, Grep)
- Enhanced output format with structured sections
- Improved workflow efficiency and user interaction

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

Co-Authored-By: Claude <noreply@anthropic.com>
2025-10-18 22:11:41 +08:00
catlog22
1324fb8c2a feat: optimize prompt-enhancer skill with bilingual support
- Add Chinese semantic recognition (修复/优化/重构/更新/改进/清理)
- Support -e/--enhance flags for explicit triggering
- Streamline structure with tables and concise format
- Add bilingual confirmation workflow (EN/CN)
- Reduce examples section for better readability
- Implement 4-priority trigger system (P1-P4)
- Add visual workflow pipeline diagram

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

Co-Authored-By: Claude <noreply@anthropic.com>
2025-10-18 22:03:09 +08:00
catlog22
1073e43c0b refactor: split task JSON templates and improve CLI mode support
- Split task-json-schema.txt into two mode-specific templates:
  - task-json-agent-mode.txt: Agent execution (no command field)
  - task-json-cli-mode.txt: CLI execution (with command field)
- Update task-generate.md:
  - Remove outdated Codex resume mechanism description
  - Add clear execution mode examples (Agent/CLI)
  - Simplify CLI Execute Mode Details section
- Update task-generate-agent.md:
  - Add --cli-execute flag support
  - Command selects template path before invoking agent
  - Agent receives template path and reads it (not content)
  - Clarify responsibility: Command decides, Agent executes
- Improve architecture:
  - Clear separation: Command layer (template selection) vs Agent layer (content generation)
  - Template selection based on flag, not agent logic
  - Agent simplicity: receives path, reads template, generates content

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

Co-Authored-By: Claude <noreply@anthropic.com>
2025-10-18 20:44:46 +08:00
catlog22
393b2f480f Refactor task generation and implementation plan templates
- Updated task JSON schema to enhance structure and artifact integration.
- Simplified agent mode execution by omitting command fields in implementation steps.
- Introduced CLI execute mode with detailed command specifications for complex tasks.
- Added comprehensive IMPL_PLAN.md template with structured sections for project analysis, context, and execution strategy.
- Enhanced documentation for artifact usage and priority guidelines.
- Improved flow control definitions for task execution and context loading.
2025-10-18 20:26:58 +08:00
catlog22
3b0f067f0b docs: enhance task-generate documentation with detailed execution modes and principles 2025-10-18 19:49:24 +08:00
catlog22
0130a66642 refactor: optimize workflow execution with parallel agent support
## Key Changes

### execute.md
- Simplify Agent Prompt (77 lines → 34 lines, -56% tokens)
- Add dependency graph batch execution algorithm
- Implement parallel task execution with execution_group
- Clarify orchestrator vs agent responsibilities
- Add TodoWrite parallel task status support

### task-generate.md
- Update task decomposition: shared context merging + independent parallelization
- Add execution_group and context_signature fields to task JSON
- Implement context signature algorithm for intelligent task grouping
- Add automatic parallel group assignment logic

## Core Requirements Verified (by Gemini)
 Complete JSON context preserved in Agent Prompt
 Shared context merging logic implemented (context_signature algorithm)
 Independent parallelization enabled (execution_group + batch execution)
 All critical functionality retained and enhanced

## Performance Impact
- 3-5x execution speed improvement (parallel batch execution)
- Reduced token usage in Agent Prompt (56% reduction)
- Intelligent task grouping (automatic context reuse)

## Risk Assessment: LOW
- Removed content: orchestrator's flow control execution → transferred to agent
- Mitigation: clear Agent JSON Loading Specification and prompt template
- Result: clearer separation of concerns, more maintainable

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

Co-Authored-By: Claude <noreply@anthropic.com>
2025-10-18 19:36:03 +08:00
catlog22
e2711a7797 feat: add workflow prompt templates for planning phases
Add CLI prompt templates for workflow planning integration:
- analysis-results-structure.txt: ANALYSIS_RESULTS.md generation template
- gemini-solution-design.txt: Solution design analysis template
- codex-feasibility-validation.txt: Technical feasibility validation template

These templates support the workflow planning phase with standardized
analysis and design documentation formats.

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

Co-Authored-By: Claude <noreply@anthropic.com>
2025-10-18 19:04:50 +08:00
catlog22
3a6e88c0df refactor: replace replan commands with direct agent-based fixes
Replace batch replan workflow with TodoWrite tracking and direct agent calls:
- concept-clarify.md: Call conceptual-planning-agent for concept gaps
- action-plan-verify.md: Call action-planning-agent for task/plan issues

Both commands now require explicit user confirmation before fixes.

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

Co-Authored-By: Claude <noreply@anthropic.com>
2025-10-18 19:03:31 +08:00
catlog22
199585b29c refactor: convert context-gather to agent-driven execution and fix path mismatch
- Refactor context-gather.md to use general-purpose agent delegation
  - Change from 4-phase manual execution to 2-phase agent-driven flow
  - Move project structure analysis and documentation loading to agent execution
  - Add Step 0: Foundation Setup for agent to execute first
  - Update agent context passing to minimal configuration
  - Add MCP tools integration guidance for agent

- Fix critical path mismatch in workflow data flow
  - Update plan.md Phase 2 output path from .context/ to .process/
  - Align with context-gather.md output location (.process/context-package.json)
  - Ensure correct data flow: context-gather → concept-enhanced

- Update concept-enhanced.md line selection (minor formatting)

Verified path consistency across all workflow commands:
- context-gather.md outputs to .process/
- concept-enhanced.md reads from .process/
- plan.md passes correct .process/ path
- All workflow tools now use consistent .process/ directory

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

Co-Authored-By: Claude <noreply@anthropic.com>
2025-10-18 17:39:45 +08:00
catlog22
e94b2a250b docs: clarify installation verification in README
Improve installation verification section to clearly indicate
checking slash commands in Claude Code interface.

Changes:
- README.md: Add Claude Code context to verification section
- README_CN.md: Add Claude Code context to verification section (Chinese)

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

Co-Authored-By: Claude <noreply@anthropic.com>
2025-10-18 12:31:46 +08:00
catlog22
4193a17c27 docs: finalize v4.6.0 release documentation
Update version badges and CHANGELOG for v4.6.0 release

Changes:
- README.md: Update version badge to v4.6.0, add What's New section
- README_CN.md: Update version badge to v4.6.0, add What's New section
- CHANGELOG.md: Add comprehensive v4.6.0 release notes

Release highlights:
- Concept Clarification Quality Gate (Phase 3.5)
- Agent-Delegated Intelligent Analysis (Phase 3)
- Dual-mode support for brainstorm/plan workflows
- Enhanced planning workflow with 5 phases
- Test-cycle-execute documentation

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

Co-Authored-By: Claude <noreply@anthropic.com>
2025-10-18 12:28:37 +08:00
catlog22
f063fb0cde feat: enhance workflow planning with concept clarification and agent delegation
🎯 Major Enhancements:

1. Concept Clarification Quality Gate (concept-clarify.md)
   - Added dual-mode support: brainstorm & plan modes
   - Auto-detects mode based on artifact presence (ANALYSIS_RESULTS.md vs synthesis-specification.md)
   - Backward compatible with existing brainstorm workflow
   - Updates appropriate artifacts based on detected mode

2. Planning Workflow Enhancement (plan.md)
   - Added Phase 3.5: Concept Clarification as quality gate
   - Integrated Phase 3.5 between analysis and task generation
   - Enhanced with interactive Q&A to resolve ambiguities
   - Updated from 4-phase to 5-phase workflow model
   - Delegated Phase 3 (Intelligent Analysis) to cli-execution-agent
   - Autonomous context discovery and enhanced prompt generation

3. Documentation Updates (README.md, README_CN.md)
   - Added /workflow:test-cycle-execute command documentation
   - Explained dynamic task generation and iterative fix cycles
   - Included usage examples and key features
   - Updated both English and Chinese versions

🔧 Technical Details:
- concept-clarify now supports both ANALYSIS_RESULTS.md (plan) and synthesis-specification.md (brainstorm)
- plan.md Phase 3 now uses cli-execution-agent for MCP-powered context discovery
- Maintains auto-continue mechanism with one interactive quality gate (Phase 3.5)
- All changes preserve backward compatibility

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

Co-Authored-By: Claude <noreply@anthropic.com>
2025-10-18 12:22:18 +08:00
catlog22
945add4f4c docs: restructure test-fix-gen workflow documentation
Reorganize documentation with improved structure and clarity:
- Add comprehensive dual-mode support (session vs prompt mode)
- Enhance usage examples with clear mode comparison
- Detail task specifications for IMPL-001 and IMPL-002
- Improve phase execution flow descriptions
- Add complete artifacts and output structure
- Expand best practices and related commands sections

The restructured documentation maintains backward compatibility while
making dual-mode functionality more discoverable and easier to use.

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

Co-Authored-By: Claude <noreply@anthropic.com>
2025-10-17 22:44:13 +08:00
catlog22
79b3680f8c docs: simplify task-generate-tdd by removing subtask JSON examples
Remove redundant container and subtask JSON schema examples from TDD task
generation documentation. The command already defaults to task merging with
subtasks only created when complexity requires (>2500 lines or >6 files),
making these detailed schemas unnecessary for standard usage.

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

Co-Authored-By: Claude <noreply@anthropic.com>
2025-10-17 22:37:08 +08:00
catlog22
9db53a24cd Refactor TDD Task Generation Strategy: Consolidate tasks into single feature-complete units with internal Red-Green-Refactor cycles, enhancing dependency management and reducing task overhead. Update documentation to reflect new task structure, limits, and JSON format for implementation plans and TODO lists. 2025-10-17 22:21:17 +08:00
catlog22
b65cd49444 feat: add dual-mode support to test-fix-gen workflow
Enable test generation for existing codebases without requiring prior
workflow session. Supports both session-based (WFS-xxx) and prompt-based
(text description or file path) inputs with automatic mode detection.

Key improvements:
- Prompt mode: Generate tests from feature description or requirements file
- Backward compatible: Existing session-based usage unchanged
- Flexible input: Accepts session ID, text description, or file path
- Use case: Testing existing APIs without workflow history

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

Co-Authored-By: Claude <noreply@anthropic.com>
2025-10-17 22:20:01 +08:00
catlog22
c27e7f9cfb docs: update test workflow command references
Updated documentation to use the renamed command:
- README.md: Updated test workflow example to use /workflow:test-cycle-execute
- SKILL.md: Updated prompt-enhancer skill documentation

Changes align with test-execute → test-cycle-execute renaming for better
clarity on iterative test-fix cycle functionality.

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

Co-Authored-By: Claude <noreply@anthropic.com>
2025-10-17 19:09:07 +08:00
catlog22
af2c1668e4 refactor: rename test-execute to test-cycle-execute for clarity
Renamed /workflow:test-execute to /workflow:test-cycle-execute to better
communicate the iterative cycle nature of the command (test → diagnose → fix → retest).

Changes:
- Renamed test-execute.md to test-cycle-execute.md
- Updated command metadata and document title
- Updated 9 internal references within the command file
- Updated reference in test-fix-gen.md related commands section

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

Co-Authored-By: Claude <noreply@anthropic.com>
2025-10-17 19:05:30 +08:00
catlog22
8b5f655e41 Refactor Gemini and Qwen Documentation: Remove outdated examples and consolidate advanced workflows
- Deleted advanced workflows, analysis examples, context optimization, template usage, and write examples for both Gemini and Qwen to streamline documentation.
- Updated CLAUDE.md to include references to new context strategies and search commands.
- Enhanced clarity and focus on compliance, security, and performance in remaining documentation.
2025-10-17 16:43:36 +08:00
catlog22
b9be188415 feat: add Chinese keyword support to skill auto-triggers
- Gemini: add Chinese task examples (分析代码库, 理解架构, etc.)
- Qwen: add Chinese task labels (分析, 探索, 文档任务, etc.)
- Codex: add Chinese task examples (实现功能, 修复bug, 重构代码, etc.)
- Enable auto-trigger for both English and Chinese keywords
2025-10-17 16:22:41 +08:00
catlog22
9c02980a74 fix: remove exclamation mark from context-search SKILL.md
Remove glob pattern example with exclamation mark as it's not supported in skill files.

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

Co-Authored-By: Claude <noreply@anthropic.com>
2025-10-17 16:16:27 +08:00
catlog22
8b4042cd90 fix: remove exclamation mark from file pattern examples in SKILL.md
Exclamation marks are not supported in skill files for pattern exclusion.

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

Co-Authored-By: Claude <noreply@anthropic.com>
2025-10-17 16:13:17 +08:00
catlog22
2c33a03c90 Merge branch 'feat/batch-replan-and-skills' into main
Add comprehensive skill system and batch replan functionality:
- New skill modules for Gemini, Qwen, Codex, and context search
- Enhanced task replan command with batch mode
- Improved action plan verification
- Complete skill documentation with examples

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

Co-Authored-By: Claude <noreply@anthropic.com>
2025-10-17 16:12:23 +08:00
catlog22
d8649db5cb feat: add interactive user selection to UI design workflows
Enhanced layout-extract and style-extract workflows with two-phase generation
process, allowing users to preview and select preferred options before full
generation.

Key changes:
- Split generation into two agent tasks:
  * Task 1: Generate concept options with previews
  * Task 2: Develop selected option into complete output
- Add Phase 1.5 interactive user selection:
  * Present concept options with visual previews
  * Capture user selection via AskUserQuestion tool
  * Save selection to user-selection.json
- Layout workflow improvements:
  * Generate layout concept options with ASCII wireframes
  * User selects preferred structural approach
  * Generate detailed templates only for selected concepts
- Style workflow improvements:
  * Generate design direction options with color/typography previews
  * User selects preferred design philosophy
  * Generate complete design system only for selected direction
- Better user experience:
  * Avoid generating unwanted variants
  * Allow informed decisions before full generation
  * Reduce wasted computation on unused variants

This change improves workflow efficiency and user control over design output.

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

Co-Authored-By: Claude <noreply@anthropic.com>
2025-10-17 15:57:08 +08:00
catlog22
2dbc818894 refactor: enhance test workflow with dynamic execution and flexible task generation
Renamed test-gen to test-fix-gen and created new test-execute command for
dynamic iterative test-fix cycles. Improved task generation flexibility and
clarified data flow between planning and execution phases.

Key changes:
- Rename test-gen.md → test-fix-gen.md to reflect task generation purpose
- Add test-execute.md for dynamic test-fix workflow execution with CLI analysis
- Enhance test-fix-gen.md:
  * Emphasize code-developer's understanding and analysis responsibilities
  * Support flexible task count (minimum 2, expandable based on complexity)
  * Add examples for multi-module test generation scenarios
- Clarify test-execute.md data flow:
  * failure_context contains raw test output and error messages
  * fix_strategy generated by CLI tool (Gemini/Qwen) analysis
  * IMPL-001 (test generation) executes first, then IMPL-002 (test-fix cycle)

This improves workflow clarity and enables adaptive test-fix strategies for
complex projects requiring multiple test generation tasks.

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

Co-Authored-By: Claude <noreply@anthropic.com>
2025-10-17 15:54:09 +08:00
catlog22
b62b777a95 feat: add animation extraction phase to imitate-auto workflow 2025-10-17 12:39:49 +08:00
catlog22
b366924ae6 feat: add batch replan mode and comprehensive skill system
- Add batch processing mode to /task:replan command
  - Support for verification report input
  - TodoWrite integration for progress tracking
  - Automatic backup management
- Enhance /workflow:action-plan-verify with batch remediation
  - Save verification report to .process directory
  - Provide batch replan command suggestions
- Add comprehensive skill documentation
  - Codex: autonomous development workflows
  - Gemini/Qwen: code analysis and documentation
  - Context-search: strategic context gathering
  - Prompt-enhancer: ambiguous prompt refinement
- Clean up CLAUDE.md strategy references

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

Co-Authored-By: Claude <noreply@anthropic.com>
2025-10-17 11:44:37 +08:00
catlog22
80196cc0a0 feat: integrate animation token system into UI workflow
Fixes critical P0 issue where animation-tokens.json wasn't consumed by the
generate command, breaking the value chain. The animation extraction system
now properly flows through: animation-extract → tokens → generate → prototypes.

Changes:
- Added animation-extract command with hybrid CSS extraction + interactive
  fallback strategy
- Updated generate.md to load and inject animation tokens into prototypes
- Added CSS animation support (custom properties, keyframes, interactions,
  accessibility)
- Integrated animation extraction into explore-auto and imitate-auto workflows

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

Co-Authored-By: Claude <noreply@anthropic.com>
2025-10-17 11:01:22 +08:00
catlog22
b08abf4f93 chore: update auto-parallel argument-hint with --count parameter
Automatically updated by linter to reflect new --count parameter
in argument hint for command usage clarity.

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

Co-Authored-By: Claude <noreply@anthropic.com>
2025-10-16 21:43:27 +08:00
catlog22
5c23758359 fix: change synthesis agent from action-planning to conceptual-planning
**Problem**: synthesis.md incorrectly used action-planning-agent
- synthesis-specification.md is conceptual analysis document (WHAT to build)
- action-planning-agent is designed for execution plans (HOW to build)
- Mismatch between agent capabilities and task requirements

**Solution**: Change to conceptual-planning-agent
- Aligns with task nature (conceptual synthesis and multi-perspective integration)
- Consistent with other role analysis commands (data-architect, system-architect, etc.)
- Agent specializes in conceptual analysis rather than task decomposition

**Changes**:
- Update allowed-tools: action-planning-agent → conceptual-planning-agent
- Update description to note agent usage
- Add "Conceptual Focus" rationale explaining agent specialization
- Update all agent references throughout document (8 locations)
- Maintain consistency with role analysis command pattern

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

Co-Authored-By: Claude <noreply@anthropic.com>
2025-10-16 21:42:35 +08:00
catlog22
9ece4dab1a feat: add configurable role count to auto-parallel brainstorm
- Add --count N parameter to specify number of roles (default: 3, max: 9)
- Add Parameter Parsing section with count handling logic
- Update role selection logic to use dynamic count value
- Update Usage section with parameter documentation
- Update TodoWrite examples to reflect dynamic role count
- Update parallel agent invocation examples with N roles
- Add role ranking and diversity selection guidelines

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

Co-Authored-By: Claude <noreply@anthropic.com>
2025-10-16 21:26:47 +08:00
catlog22
7945e219f4 refactor: convert synthesis command to agent-based execution
- Convert synthesis.md to use action-planning-agent with FLOW_CONTROL
- Create synthesis-role.md template with comprehensive document structure
- Reorganize phase sequencing: validation → discovery → update check → agent execution
- Extract task tracking as protocol section outside phase sequence
- Add explicit OUTPUT_FILE and OUTPUT_PATH to agent context
- Move cross-role analysis logic into agent responsibilities
- Simplify Quality Assurance and Next Steps sections

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

Co-Authored-By: Claude <noreply@anthropic.com>
2025-10-16 21:23:26 +08:00
catlog22
5e59c1d2d9 fix: correct workflow:execute usage in docs command
Fixed incorrect usage of /workflow:execute with task IDs.
- Changed from: /workflow:execute IMPL-001 (incorrect)
- Changed to: /workflow:execute (correct - executes entire workflow)
- Simplified execution commands section
- Aligned with execute.md specification

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

Co-Authored-By: Claude <noreply@anthropic.com>
2025-10-16 16:54:00 +08:00
catlog22
872fb4995e feat: add progressive exploration to layout extraction script
Enhanced extract-layout-structure.js with intelligent selector discovery:
- Auto-detects missing main containers when <3 found
- Scans large visible containers (≥500×300px)
- Extracts class patterns (main/content/wrapper/container/page/layout/app)
- Suggests new selectors to add to script
- Returns exploration data with recommendations

Added commonClassSelectors strategy:
- .main, .content, .main-content, .page-content
- .container.main, .wrapper > .main
- div[class*="main-wrapper"], div[class*="content-wrapper"]

Updated layout-extract.md with progressive exploration documentation.

Version: 2.1.0 → 2.2.0

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

Co-Authored-By: Claude <noreply@anthropic.com>
2025-10-16 16:27:46 +08:00
catlog22
3066680f16 docs: add Chrome DevTools MCP requirement for UI workflows
Add documentation for Chrome DevTools MCP server requirement across
English and Chinese README files:

Changes:
- Add Chrome DevTools MCP to MCP servers table with installation link
- Mark as required for UI workflows (URL mode design extraction)
- Add UI Workflows benefit to MCP benefits section
- Add warning note before UI Design Workflow Commands section
- Document graceful fallback to visual analysis when unavailable

Reference: https://github.com/ChromeDevTools/chrome-devtools-mcp

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

Co-Authored-By: Claude <noreply@anthropic.com>
2025-10-16 14:37:55 +08:00
catlog22
610f75de52 feat: enhance UI design workflows with URL auto-trigger and streamlined output
- Add --urls parameter support to style-extract and layout-extract
- Auto-trigger computed styles extraction when URLs provided (no manual flag)
- Auto-trigger DOM structure extraction for layout analysis
- Streamline imitate-auto workflow by removing redundant REPORT statements
- Maintain clear phase headers while reducing verbose output
- Enable graceful fallback to visual analysis if Chrome DevTools unavailable

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

Co-Authored-By: Claude <noreply@anthropic.com>
2025-10-16 14:32:42 +08:00
catlog22
fb6569303a docs: update documentation for v4.5.0 release
- Update version badges from v4.4.0 to v4.5.0 in README files
- Add v4.5.0 release highlights:
  * Enhanced agent protocols with unified execution
  * Streamlined UI workflows and improved documentation
  * Optimized workflow templates for better clarity
  * Improved CLI commands and tool integration
  * New CLI execution agent for autonomous task handling
- Update Getting Started guides to reference v4.5.0
- Add cli-execution-agent to agent list in Getting Started guides

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

Co-Authored-By: Claude <noreply@anthropic.com>
2025-10-16 13:58:15 +08:00
catlog22
d2d9f16673 refactor: enhance Codex output standards with structured templates
- Add Format Priority section aligned with GEMINI.md style
- Expand default output formats into three comprehensive templates:
  * Single Task Implementation (with Summary, Key Decisions, Testing, Validation)
  * Multi-Task Execution (First Subtask and Subsequent Subtasks with context passing)
  * Partial Completion (with Blocked/Required/Recommendation sections)
- Add Code References section with standardized format
- Standardize Related Files section at output beginning
- Improve clarity and consistency with Gemini execution protocol

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

Co-Authored-By: Claude <noreply@anthropic.com>
2025-10-16 13:51:42 +08:00
catlog22
39a35c24b1 refactor: optimize workflow templates and prompt structures
- Streamlined analysis templates (architecture, pattern, performance, quality, security)
- Simplified development templates (component, debugging, feature, refactor, testing)
- Optimized documentation templates (api, folder-navigation, module-readme, project-architecture, project-examples, project-readme)
- Enhanced planning templates (concept-eval, migration, task-breakdown)
- Improved verification templates (codex-technical, cross-validation, gemini-strategic)
- Updated claude-module-unified memory template
- Refined workflow-architecture documentation

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

Co-Authored-By: Claude <noreply@anthropic.com>
2025-10-16 13:48:35 +08:00
catlog22
e95be40c2b refactor: streamline UI design workflow and add extraction scripts
- Simplified UI design command workflows (batch-generate, explore-auto, generate, update)
- Enhanced style-extract and layout-extract with improved documentation
- Refactored imitate-auto for better usability
- Removed obsolete consolidate workflow
- Added extract-computed-styles.js and extract-layout-structure.js utilities
- Updated UI generation and instantiation scripts

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

Co-Authored-By: Claude <noreply@anthropic.com>
2025-10-16 13:47:58 +08:00
catlog22
d2c66135fb refactor: update CLI commands and tool agent configurations
- Enhanced CLI command documentation for analyze, chat, and execute
- Updated mode-specific commands (bug-index, code-analysis, plan)
- Added cli-execution-agent for autonomous CLI task handling
- Refined agent configurations for Codex, Gemini, and Qwen

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

Co-Authored-By: Claude <noreply@anthropic.com>
2025-10-16 13:47:26 +08:00
catlog22
4aec163441 refactor: reorganize memory commands and update brainstorm workflows
Changes:
- Move memory commands to .claude/commands/memory/ directory
- Relocate update-memory-full.md and update-memory-related.md
- Add new docs.md command for documentation workflows
- Update brainstorm commands (api-designer, data-architect, system-architect, ui-designer, ux-expert)
- Remove deprecated workflow/tools/docs.md

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

Co-Authored-By: Claude <noreply@anthropic.com>
2025-10-16 10:41:38 +08:00
catlog22
7ac5412c97 docs: update Windows path format guidelines for MCP and Bash compatibility
Clarified path format requirements:
- MCP tools require double backslash format (D:\path)
- Bash commands support forward slash (D:/path) or POSIX (/d/path)
- Added quick reference for common conversions

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

Co-Authored-By: Claude <noreply@anthropic.com>
2025-10-16 10:40:09 +08:00
catlog22
25f6497933 feat: add api-designer command for generating framework-based analysis 2025-10-16 10:40:09 +08:00
catlog22
3eb3130b2b Merge pull request #4 from jayking0912/main
FIX:修复Gemini_base_url 不能自定义
2025-10-15 16:38:47 +08:00
jayNuc
1474e6c64b FIX:修复Gemini_base_url 不能自定义 2025-10-15 10:20:00 +08:00
catlog22
a4ca222db5 revert: restore intelligent-tools-strategy.md to commit b5d6870
Revert intelligent-tools-strategy.md to the version from commit b5d6870
(docs: enhance method parameter documentation in unified template).

This reverts the following commits for this file:
- 4524702 docs: restore Template System directory tree structure
- a7a157d docs: restore critical details to intelligent-tools-strategy.md
- 1e79866 refactor: optimize intelligent-tools-strategy.md and fix codex calls

File changes: 451 lines → 503 lines (+52 lines net)
- Restores original detailed structure
- Reverts optimization changes
- Returns to pre-refactor state

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

Co-Authored-By: Claude <noreply@anthropic.com>
2025-10-13 21:44:51 +08:00
catlog22
4524702cd4 docs: restore Template System directory tree structure
Restore the original directory tree visualization for Template System section,
replacing the compressed table format with a clear hierarchical structure.

Changes:
- Replace table format with ASCII directory tree
- Show complete file paths: prompts/, planning-roles/, tech-stacks/
- Display full template hierarchy with descriptions
- Improve path clarity for RULES field references

Benefits:
- Clear visualization of template file locations
- Easy to reference in $(cat ...) commands
- Better understanding of directory structure
- Facilitates accurate template path construction

File: intelligent-tools-strategy.md: 431 → 451 lines (+20 lines)

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

Co-Authored-By: Claude <noreply@anthropic.com>
2025-10-13 21:15:30 +08:00
catlog22
a7a157d40e docs: restore critical details to intelligent-tools-strategy.md
Restore important detailed content that was removed in commit 1e79866:

Key restorations (106 lines added):
- Session Management: Detailed explanation and multi-task pattern examples (15 lines)
- Auto-Resume Decision Rules: Complete criteria for when to use/not use (12 lines)
- RULES Field Format: Critical "template reference only, never read" rule (14 lines)
- File Pattern Reference: Complete 3-step workflow with rg/MCP examples (33 lines)
- Common Scenarios: Full examples including Feature Development 3-step workflow (82 lines)
- Best Practices: Detailed guidelines with context optimization strategy (8 lines)

Additional improvements:
- Enhanced CLAUDE.md references throughout the document
- Added CLAUDE.md to Planning Checklist and File Pattern examples
- Restored execution timeout configuration with specific millisecond values

File changes:
- intelligent-tools-strategy.md: 325 → 431 lines (balanced detail/conciseness)
- Removed design-tokens-schema.md (obsolete)

The document now maintains conciseness while restoring all critical guidance.

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

Co-Authored-By: Claude <noreply@anthropic.com>
2025-10-13 17:17:07 +08:00
catlog22
1e798660ab refactor: optimize intelligent-tools-strategy.md and fix codex calls
- Reduce intelligent-tools-strategy.md from 504 to 325 lines (35.5% reduction)
- Merge Gemini/Qwen tool specifications into unified Analysis Tools section
- Consolidate command templates and remove duplicate examples
- Compress usage scenarios while preserving all critical information
- Simplify guidelines to concise bullet points
- Fix incorrect codex chat calls in discuss-plan.md to use proper exec format

All core decision rules, permission framework, and command templates preserved.

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

Co-Authored-By: Claude <noreply@anthropic.com>
2025-10-13 16:51:45 +08:00
catlog22
b5d6870a44 docs: enhance method parameter documentation in unified template
Add comprehensive requirements for documenting method parameters, return values, and exceptions in code files. Include detailed guidelines for parameter types, descriptions, default values, and usage examples.

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

Co-Authored-By: Claude <noreply@anthropic.com>
2025-10-13 16:36:36 +08:00
catlog22
e5443d1776 docs: remove direct Gemini Wrapper script usage section
Removed the "Direct Gemini Wrapper Script Usage" section from Getting Started guides
as users cannot manually execute these commands in Claude Code - all tool invocations
are handled automatically by Claude through semantic understanding.

Changes:
- Removed "Gemini Wrapper 脚本直接使用" section (Chinese)
- Removed "Direct Gemini Wrapper Script Usage" section (English)
- Kept "Semantic Tool Invocation" section explaining natural language usage
- Streamlined documentation to focus on user-facing interaction patterns

Rationale:
- Users cannot run ~/.claude/scripts/gemini-wrapper commands directly in Claude Code
- These are internal implementation details handled automatically by Claude
- Documentation should focus on how users interact with the system, not internal mechanics

Files updated:
- GETTING_STARTED.md (-47 lines)
- GETTING_STARTED_CN.md (-47 lines)

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

Co-Authored-By: Claude <noreply@anthropic.com>
2025-10-13 11:24:19 +08:00
catlog22
9fe8d28218 docs: clarify semantic tool invocation concept in Getting Started guides
Fixed the "Semantic Tool Invocation" concept to accurately reflect its meaning:

**Before**: "Gemini 工具语义调用" referred to direct script usage
**After**: Properly describes semantic invocation as natural language interaction

Changes:
- Added "Semantic Tool Invocation" section explaining natural language usage
  - Example: User says "Use gemini to analyze architecture"
  - Claude understands and automatically executes appropriate commands
  - Highlighted advantages: natural interaction, intelligent understanding, auto optimization

- Renamed previous section to "Direct Gemini Wrapper Script Usage"
  - Clarified this is for scenarios requiring precise control
  - Maintained all existing script usage examples

Structure now clearly distinguishes:
1. Semantic invocation (natural language → Claude → tool execution)
2. Direct script usage (manual command execution)

Updated both:
- GETTING_STARTED.md (English)
- GETTING_STARTED_CN.md (Chinese)

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

Co-Authored-By: Claude <noreply@anthropic.com>
2025-10-13 11:21:56 +08:00
catlog22
9f4b0acca7 docs: add workflow-free standalone tools section to Getting Started guides
Added comprehensive "Workflow-Free Usage" section covering:

**Direct CLI Tool Usage:**
- Code analysis with /cli:analyze
- Interactive chat with /cli:chat
- Specialized modes (plan, code-analysis, bug-index)

**Semantic Gemini Invocation:**
- Read-only mode for exploration and analysis
- Write mode for document generation
- Context optimization techniques with cd

**Memory Management:**
- Full project index rebuild with /update-memory-full
- Incremental updates with /update-memory-related
- Execution timing recommendations
- Memory quality impact table

**CLI Tool Initialization:**
- Auto-configuration with /cli:cli-init
- Tool-specific setup options

Documentation style:
- Objective tone without first-person pronouns
- Clear command examples with copy-paste readiness
- Practical execution timing guidance
- Visual tables for decision making

Files updated:
- GETTING_STARTED.md (English, +167 lines)
- GETTING_STARTED_CN.md (Chinese, +167 lines)

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

Co-Authored-By: Claude <noreply@anthropic.com>
2025-10-13 11:19:39 +08:00
catlog22
8dc7abf707 docs: add prominent Getting Started guide links in README
Added eye-catching links to the beginner-friendly Getting Started guides
at the top of both README files, right after the version announcement.
This helps new users quickly discover the 5-minute tutorial.

Changes:
- README.md: Added link to GETTING_STARTED.md
- README_CN.md: Added link to GETTING_STARTED_CN.md

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

Co-Authored-By: Claude <noreply@anthropic.com>
2025-10-13 11:15:42 +08:00
catlog22
424770d58c docs: add beginner-friendly getting started guides
Generated comprehensive beginner guides using Gemini analysis:
- GETTING_STARTED.md (English version, 151 lines)
- GETTING_STARTED_CN.md (Chinese version, 151 lines)

Content includes:
- 5-minute quick start tutorial
- Core concepts explanation with simple language
- Common scenarios (feature development, UI design, bug fixing)
- Troubleshooting guide
- Advanced learning paths

Features:
- Emoji-enhanced readability
- Step-by-step instructions with copy-paste commands
- Real-world examples for each concept
- Progressive learning approach

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

Co-Authored-By: Claude <noreply@anthropic.com>
2025-10-13 11:14:20 +08:00
catlog22
5ca246a37c docs: clarify UI preview system works without server
Updated README documentation to emphasize that index.html and compare.html
can be opened directly in browser without requiring a local server.
Reorganized preview instructions to highlight direct browser preview as
the recommended approach, with local server as optional for advanced features.

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

Co-Authored-By: Claude <noreply@anthropic.com>
2025-10-13 11:03:35 +08:00
catlog22
bbf88826ba fix: convert all shell scripts to LF line endings for Linux/WSL compatibility
- Convert all .sh files from CRLF to LF line endings
- Add .gitattributes to enforce LF for shell scripts
- Fix "bash\r: No such file or directory" error in WSL environments

This resolves the installation failure on WSL/Linux systems where
Windows CRLF line endings cause shell scripts to fail.

Related to #1

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

Co-Authored-By: Claude <noreply@anthropic.com>
2025-10-13 10:00:33 +08:00
catlog22
ce5d903813 fix: improve environment detection and error handling in remote installers
- Add git availability check with helpful installation hints
- Improve version detection with automatic fallback to GitHub API
- Add detailed progress feedback during installation
- Enhance error messages for better user experience
- Fix WSL installation issue reported in #1

Changes:
- install-remote.sh: Add git check, improve commit SHA detection
- install-remote.ps1: Add git check, improve commit SHA detection

Fixes #1

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

Co-Authored-By: Claude <noreply@anthropic.com>
2025-10-13 09:54:45 +08:00
catlog22
703f22e331 feat: add codebase-retrieval semantic search tool
Add semantic file discovery via Gemini CLI --all-files parameter
- Define codebase-retrieval as primary semantic search tool
- Add tool selection matrix for search strategy
- Provide command templates with dynamic placeholders
- Document workflow integration with rg and other tools

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

Co-Authored-By: Claude <noreply@anthropic.com>
2025-10-13 09:38:25 +08:00
catlog22
61997f8db8 feat: add memory state check between Phase 3 and Phase 4
Add automatic memory compaction trigger when context usage exceeds 110K tokens:
- Evaluates memory state after analysis phase (Phase 3)
- Triggers /compact command if approaching context limits
- Prevents context overflow and ensures optimal performance
- Particularly important after extensive documentation generation

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

Co-Authored-By: Claude <noreply@anthropic.com>
2025-10-12 22:23:32 +08:00
catlog22
f090c713ca refactor: streamline concept-enhanced.md command (532→377 lines, 29% reduction)
Optimizations:
- Merge Overview & Philosophy sections (78→29 lines)
- Simplify Tool Selection Strategy (76→47 lines)
- Optimize Execution Lifecycle (242→119 lines)
- Reduce Code Modification Targets examples (4→2 examples)
- Merge Error Handling & Performance into Execution Management (52→14 lines)
- Merge Integration & Quality into unified section (30→25 lines)

Core features preserved:
- Complete output format template (kept internal)
- 5-phase execution lifecycle
- Tool selection complexity matrix
- Gemini/Codex bash configurations
- All essential functionality

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

Co-Authored-By: Claude <noreply@anthropic.com>
2025-10-12 22:21:29 +08:00
catlog22
177279b760 chore: remove deprecated templates and unused files
- Delete archived layer-based templates (Layer 1-4)
- Remove hierarchy-analysis.txt (no longer needed)
- Update intelligent-tools-strategy.md to remove references

Cleanup:
- Keep only claude-module-unified.txt in memory/ directory
- Remove outdated template references from strategy document
- Simplify template structure for installation

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

Co-Authored-By: Claude <noreply@anthropic.com>
2025-10-12 21:57:19 +08:00
catlog22
46f749605a fix: remove @ prefix from intelligent-tools-strategy.md reference
- Update enhance-prompt.md to use correct file reference format
- Change from @~/.claude/workflows/intelligent-tools-strategy.md to ~/.claude/workflows/intelligent-tools-strategy.md
- Align with other command files' reference format

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

Co-Authored-By: Claude <noreply@anthropic.com>
2025-10-12 21:52:59 +08:00
catlog22
8a849d651f refactor: simplify module documentation with unified template
- Replace 4-layer hierarchy (Layer 1-4) with single unified template
- New template: claude-module-unified.txt works for all modules and files
- Update update_module_claude.sh to remove layer detection logic
- Archive old layer-based templates to memory/archive/
- Update intelligent-tools-strategy.md to reference unified template

Benefits:
 Single template to maintain
 Simpler script logic
 Universal application for folders and code files
 Clearer documentation structure

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

Co-Authored-By: Claude <noreply@anthropic.com>
2025-10-12 21:50:01 +08:00
catlog22
0fd390f5d8 docs: optimize README with concise language and memory management emphasis
- Simplify introduction to highlight core value proposition
- Restructure "Key Features" to "Core Differentiators" with 6 key innovations
- Reduce content by 63% while maintaining 100% information completeness
- Add dedicated "Memory Management" section emphasizing its critical importance
- Add "Technical Architecture" section showing project organization
- Improve readability with concise bullet points and tables
- Synchronize English and Chinese versions

Key improvements:
- Context-First Architecture: Explain 1-to-N development drift solution
- JSON-First State Management: Highlight single source of truth design
- Autonomous Orchestration: Detail flow_control mechanism
- Multi-Model Strategy: Document 5-10x performance improvement
- Hierarchical Memory: Show 4-layer documentation structure
- Role-Based Agents: List specialized agents and workflows

Memory Management highlights:
- Document memory hierarchy (Root → Domain → Module → Sub-Module)
- Provide update triggers and best practices
- Emphasize quality impact on execution accuracy
- Show tool integration options (Gemini/Qwen/Codex)
2025-10-12 21:01:00 +08:00
catlog22
1dff4ff0c7 docs: add template reference rule - use $(cat ...) directly, never read first 2025-10-12 18:40:45 +08:00
catlog22
8a8090709f docs: add command substitution rules and fix template syntax
Key changes:
1. Add CRITICAL section for command substitution rules
   - Document why escape characters (\$, \", \') break commands
   - Explain correct syntax without quotes in $(cat ...) paths
   - Provide clear correct vs wrong examples

2. Fix all template references in examples
   - Remove single quotes from $(cat '...') → $(cat ...)
   - Ensure all 4 occurrences use correct syntax (lines 331, 356, 366, 379)

3. Add best practice guideline
   - Add warning in General Guidelines about escape characters
   - Emphasize this applies to all CLI command execution

Problem solved: Prevent automatic escape character insertion that breaks
shell command substitution and path expansion in actual CLI execution.
2025-10-12 18:36:53 +08:00
catlog22
4006234fa0 docs: add memory templates to intelligent tools strategy
Add memory hierarchy templates to Available Templates section and Selection Matrix:
- Layer 1-4 templates for hierarchical documentation
- Hierarchy analysis template for project structure
- Semantic triggers and use cases for each template level
2025-10-12 18:28:56 +08:00
catlog22
9d4d728ee7 docs: add bash execution rules and Windows path conversion guide
- Add rule to prevent run_in_background parameter in bash() calls
- Add Windows path conversion guidelines for Git Bash compatibility
- Simplify path handling: C:\path → /c/path, relative paths unchanged
2025-10-12 17:19:47 +08:00
catlog22
8e4710389d refactor: restructure memory update commands to command-style docs
Major improvements to /update-memory-full and /update-memory-related:

Structure:
- Adopt plan.md command-style format with clear phases
- Consolidate redundant sections and examples
- Add Coordinator Role and Core Rules sections
- Include detailed Coordinator Checklist

Features:
- Add --path parameter to target specific directories
- Update Task() call format to function-style syntax
- Merge execution examples into workflow phases
- Add Path Parameter Reference section

Documentation:
- Increase parallel job limit from 4 to 5
- Add comprehensive usage examples
- Include tool parameter reference
- Add comparison tables and best practices

Files changed:
- .claude/commands/update-memory-full.md: +285/-100 lines
- .claude/commands/update-memory-related.md: +229/-136 lines
2025-10-12 17:07:26 +08:00
catlog22
7ce76e1564 refactor: merge ARCHITECTURE and EXAMPLES into single task
- Combine IMPL-005 (ARCHITECTURE.md) and IMPL-006 (EXAMPLES.md) into one task
  - New IMPL-005: Generate both ARCHITECTURE.md and EXAMPLES.md together
  - Reduces task count and simplifies workflow execution
  - Both documents share similar analysis context from project README and modules

- Update HTTP API task from IMPL-007 to IMPL-006
  - Maintain sequential task numbering after merge

- Update all references:
  - Task hierarchy documentation
  - Task generation logic
  - Session structure examples
  - Execution command examples

Benefits:
- Streamlined workflow with fewer tasks to execute
- Architecture and examples are logically related (structure + usage)
- Reduced overhead in task management and execution
2025-10-12 16:37:10 +08:00
catlog22
42d7ad895e fix: improve docs workflow and module discovery
- Fix get_modules_by_depth.sh to avoid filtering 'core' directories
  - Remove overly broad "core" exclusion pattern
  - Keep "*.core" for actual core dump files
  - Resolves issue where directories named 'core' were incorrectly filtered

- Refactor docs workflow from path-based detection to mode selection
  - Replace is_root logic with explicit --mode parameter
  - Add --mode full: generate complete documentation (modules + project-level)
  - Add --mode partial: generate module documentation only
  - Default to full mode for better user experience
  - Simplify configuration by removing complex path comparison logic

These changes provide better control over documentation generation
and fix directory discovery issues in Python projects with core/ folders.
2025-10-12 15:40:11 +08:00
catlog22
03399259f4 feat: optimize docs workflow and add gitignore support to scripts
Major Changes:
1. Add classify-folders.sh script
   - Extract folder classification logic from inline script
   - Support for code/navigation/skip folder types
   - Placed in .claude/scripts/ for reusability

2. Optimize /workflow:docs command (docs.md)
   - Simplify Phase 1: single-step session initialization
   - Add Path Mirroring Strategy section
   - Document structure now mirrors source structure
   - Update to single config.json file (replace multiple .process files)
   - Fix path detection for Windows/Git Bash compatibility
   - Update all task templates with mirrored output paths

3. Add parent .gitignore support
   - detect_changed_modules.sh: parse .gitignore from current or git root
   - update_module_claude.sh: respect .gitignore patterns when counting files
   - Unified build_exclusion_filters() function across scripts

Key Improvements:
- Documentation output: .workflow/docs/ with project structure mirroring
- Session init: 4 steps → 1 bash command block
- Config files: multiple files → single config.json
- Path detection: improved Windows/Git Bash normalization
- Gitignore support: current dir → parent dir fallback

Related Issue: Fix core directory exclusion in get_modules_by_depth.sh
(Note: get_modules_by_depth.sh is in user global config, not in this repo)
2025-10-12 15:06:13 +08:00
catlog22
b0c3d0d0c1 Release v4.4.1: Implementation approach structure refactoring
- Refactor implementation_approach from object to array format
- Add step-based execution with dependency management
- Add CLI execution mode support with --cli-execute flag
- Add Codex resume mechanism for context continuity
- Update 15 files across agents, commands, and core architecture
- Major docs.md refactoring (67% size reduction)
- Enhanced workflow-architecture.md with flow control documentation
2025-10-12 14:15:33 +08:00
catlog22
58153ecb83 Refactor implementation approach structure across task generation files
- Updated implementation_approach in task-generate-tdd.md to use an array format with detailed steps for minimal code implementation and iterative testing.
- Enhanced task-generate.md to support CLI execution mode with Codex, including examples for task execution and session management.
- Modified test-task-generate.md to incorporate CLI execution mode, allowing Codex to autonomously generate tests and execute iterative test-fix cycles.
- Revised task-core.md and workflow-architecture.md to adopt a step-based implementation approach, improving clarity and dependency management in task execution.
- Improved documentation in workflow-architecture.md to clarify flow control structure and variable referencing.
2025-10-12 14:09:47 +08:00
catlog22
c5aac313ff Add discuss-plan command for multi-model collaborative planning and analysis
- Introduced the discuss-plan command to facilitate iterative discussions among Gemini, Codex, and Claude.
- Defined roles and priorities for each model in the discussion loop.
- Established a structured workflow for input processing, discussion rounds, and user review.
- Implemented TodoWrite tracking for progress across rounds.
- Specified output routing for logs and final plans.
- Included examples and best practices for effective usage.
2025-10-12 11:53:16 +08:00
catlog22
3ec5de821d Add comprehensive documentation templates for API, folder navigation, module README, project architecture, examples, and project-level README
- Introduced a unified API documentation template covering both Code API and HTTP API sections.
- Created a folder navigation documentation template for directories containing subdirectories.
- Developed a module README documentation template focusing on module purpose, usage, and dependencies.
- Added a project architecture documentation template synthesizing module information and system design.
- Implemented a project examples documentation template showcasing practical usage scenarios.
- Established a project-level documentation template outlining project overview, architecture, and navigation.
2025-10-12 11:22:07 +08:00
catlog22
75ec70ad23 更新 generate.md 和 layout-extract.md 文档:添加对参考图像的自动检测和使用说明 2025-10-12 10:11:08 +08:00
catlog22
be2d0f24b6 Sync Install-Claude.sh with Install-Claude.ps1: Selective folder replacement
**Summary:**
Applied the same selective replacement logic from Install-Claude.ps1 to Install-Claude.sh (Bash version).

**Changes:**
- Added `backup_and_replace_directory` function for folder-level operations
- Modified `install_global` to use selective replacement for .claude, .codex, .gemini, .qwen
- Modified `install_path` to use selective replacement for local folders and config directories
- Maintained `merge_directory_contents` for backward compatibility

**New Installation Flow:**
1. Backup entire existing directory to timestamped backup folder
2. Only remove items in destination that match source item names
3. Copy source items to destination
4. Preserve all other files in destination directory

**Benefits:**
- Protects user-created files and session data
- Only updates files that come from installation source
- Safer incremental updates
- Consistent behavior across PowerShell and Bash versions

**Example:**
Source: .claude/{commands, workflows, scripts}
Destination before: .claude/{commands, workflows, custom.json, .workflow/}
Destination after: .claude/{commands, workflows, scripts, custom.json, .workflow/}

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

Co-Authored-By: Claude <noreply@anthropic.com>
2025-10-11 23:57:12 +08:00
catlog22
543f655bc1 Fix Install-Claude.ps1: Only clear conflicting items, preserve other files
**Issue:**
Previous logic cleared entire destination directory, removing all existing files including user-created content.

**Fix:**
Modified `Backup-AndReplaceDirectory` to:
1. Backup entire destination directory (as before)
2. Only remove items in destination that match source item names
3. Copy source items to destination
4. Preserve all other files in destination directory

**New Behavior:**
- Removes: ~/.claude/commands (if exists in source)
- Removes: ~/.claude/workflows (if exists in source)
- Preserves: ~/.claude/custom-file.md (user-created)
- Preserves: ~/.claude/.workflow/ (session data)

**Example:**
Source: .claude/{commands, workflows, scripts}
Destination before: .claude/{commands, workflows, custom-config.json, .workflow/}
Destination after: .claude/{commands, workflows, scripts, custom-config.json, .workflow/}

**Benefits:**
- Protects user-created files and session data
- Only updates files that come from installation source
- Safer incremental updates

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

Co-Authored-By: Claude <noreply@anthropic.com>
2025-10-11 23:53:18 +08:00
catlog22
62161c9a16 Refactor Install-Claude.ps1: Replace file-by-file merge with folder replacement
**Summary:**
Modified installation logic to backup entire folders, clear destinations, and copy complete directories instead of merging individual files.

**Changes:**
- Added `Backup-AndReplaceDirectory` function for folder-level operations
- Modified `Install-Global` to use folder replacement for .claude, .codex, .gemini, .qwen
- Modified `Install-Path` to use folder replacement for local folders and config directories
- Maintained `Merge-DirectoryContents` for backward compatibility (not used in main flow)

**New Installation Flow:**
1. Backup entire existing directory to timestamped backup folder
2. Clear destination directory completely
3. Copy entire source directory to destination

**Benefits:**
- Faster installation (no file-by-file comparison)
- Cleaner installations (no orphaned files from previous versions)
- Simpler backup/restore process (complete directory snapshots)
- Better handling of renamed/moved files

**Testing:**
 Successfully tested Global installation mode
 Verified backup creation and folder replacement
 Confirmed all directories (.claude, .codex, .gemini, .qwen) installed correctly

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

Co-Authored-By: Claude <noreply@anthropic.com>
2025-10-11 23:51:18 +08:00
catlog22
369bfa8a08 Refactor command YAML headers: replace examples with argument-hint
**Summary:**
Updated all 62 command files in `.claude/commands` directory to improve parameter documentation clarity by replacing `examples` field with descriptive `argument-hint` field.

**Changes:**
- Added/improved `argument-hint` for all commands based on usage patterns
- Removed `examples` field and all example items from YAML headers
- Maintained all other YAML fields (name, description, usage, allowed-tools)
- Deleted obsolete commands: workflow/issue/*, workflow/session/pause.md, workflow/session/switch.md
- Cleaned up temporary analysis files

**Rationale:**
The `argument-hint` field provides clearer, more concise parameter documentation than example lists, improving command discoverability and usability in the Claude Code interface.

**Files Modified:** 62 command files
**Lines Changed:** -1570 insertions, +192 deletions

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

Co-Authored-By: Claude <noreply@anthropic.com>
2025-10-11 23:45:55 +08:00
catlog22
6b360939bc Update documentation with tool control system information
- Add Tool Control System section explaining optional external CLI tools
- Replace "Prerequisites: Required Tools" with optional tool configuration
- Document graceful degradation and progressive enhancement features
- Add configuration file reference and usage examples
- Update both English and Chinese versions

This addresses Issue #2 by documenting the new optional CLI dependency system.

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

Co-Authored-By: Claude <noreply@anthropic.com>
2025-10-11 23:06:48 +08:00
catlog22
3772cbd331 Add tool control configuration reference to CLAUDE.md
- Added reference to tool-control.yaml for CLI tool availability management
- Includes new tool-control.yaml configuration file
- Helps coordinate tool usage across commands and agent executions

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

Co-Authored-By: Claude <noreply@anthropic.com>
2025-10-11 23:02:57 +08:00
catlog22
7c8e75f363 Release v4.4.0: UI Design Workflow V3 - Layout/Style Separation Architecture
## Breaking Changes

- **Command Renamed**: `extract` → `style-extract`
- **New Required Phase**: `layout-extract` now mandatory before `generate`
- **Workflow Changed**: Old flow (extract → consolidate → generate)
  → New flow (style-extract → consolidate → layout-extract → generate)

## Added

**New Command: layout-extract**
- Extract structural layout separate from visual style
- Agent-powered with ui-design-agent
- Dual-mode: imitate (high-fidelity) / explore (multiple variants)
- Device-aware: desktop, mobile, tablet, responsive
- MCP-integrated layout pattern research (explore mode)
- Output: layout-templates.json with DOM structure + CSS layout rules

**Enhanced Architecture**
- Layout/Style Separation: Clear responsibility boundaries
- Pure Assembler: generate command combines pre-extracted components
- Device-Aware Layouts: Optimized structures for different devices
- Token-Based CSS: var() placeholders for spacing/breakpoints

## Changed

**style-extract (Renamed from extract)**
- File renamed: extract.md → style-extract.md
- Scope clarified: Visual style only (colors, typography, spacing)
- No functionality change, all features preserved

**generate (Refactored to Pure Assembler)**
- Before: Agent designed layout + applied style
- After: Pure assembly - combines layout-templates.json + design-tokens.json
- No design logic: All decisions made in previous phases
- Simplified agent instructions: Focus on assembly only

**Workflow Commands Updated**
- imitate-auto: Added Phase 2.5 (layout extraction)
- explore-auto: Added Phase 2.5 (layout extraction)
- Both workflows now include layout-extract step

## Removed

-  V2 Commands: generate-v2, explore-auto-v2 (merged into main commands)
-  Old extract command (renamed to style-extract)
-  ui-generate-preview-v2.sh (merged into ui-generate-preview.sh)

## Files Changed

- Renamed: extract.md → style-extract.md
- Added: layout-extract.md (370+ lines)
- Modified: generate.md, imitate-auto.md, explore-auto.md, consolidate.md
- Removed: 2 deprecated v2 command files
- Updated: CHANGELOG.md, README.md

## Benefits

-  Single Responsibility: Each phase has one clear job
-  Better Layout Variety: Explore mode generates structurally distinct layouts
-  Reusability: Layout templates work with any style
-  Clarity: All structural decisions visible in layout-templates.json
-  Testability: Layout structure and visual style tested independently

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

Co-Authored-By: Claude <noreply@anthropic.com>
2025-10-11 16:21:28 +08:00
catlog22
3857aa44ce 增强截图捕获工作流:添加格式选项(PNG、WebP、JPEG),更新错误处理和执行机制,优化用户体验 2025-10-11 15:42:50 +08:00
catlog22
9993d599f8 Add interactive layer exploration workflow for UI design
- Implemented the `/workflow:ui-design:explore-layers` command for depth-controlled UI capture.
- Defined depth levels from full-page screenshots to Shadow DOM exploration.
- Included setup, validation, and navigation phases with error handling.
- Captured screenshots at various depths and generated a comprehensive layer map.
- Added examples and usage instructions for ease of use.
2025-10-11 15:29:33 +08:00
catlog22
980f554b27 Refactor UI Generation Workflow: Optimize matrix generation process, enhance layout planning, and improve error handling. Consolidate steps for better performance and clarity, ensuring production-ready output with semantic HTML and responsive design. Update examples and documentation for clarity and usability. 2025-10-11 12:54:55 +08:00
catlog22
2fcd44e856 feat: Add imitate-auto-v3 workflow for high-speed multi-page UI replication
- Introduced a new workflow named `imitate-auto-v3` that allows for batch screenshot capture and optional token refinement.
- Implemented a comprehensive 5-phase execution protocol to handle initialization, screenshot capture, style extraction, token processing, and UI generation.
- Added support for multiple target URLs through a `--url-map` parameter, enhancing flexibility in design replication.
- Included optional parameters for session management and token refinement, allowing users to customize their workflow experience.
- Enhanced error handling and reporting throughout the workflow to ensure clarity and ease of debugging.
- Deprecated the previous `imitate-auto.md` workflow in favor of this more robust version.
2025-10-11 11:42:33 +08:00
catlog22
f07e77e9fa Enhance UI Design Workflow: Transition to Target-Style-Centric Generation
- Introduced Phase 0c for user confirmation before initiating the workflow.
- Updated phases to ensure immediate transitions between style extraction, consolidation, and UI generation.
- Revised documentation to reflect changes in phase execution and user interaction.
- Changed terminology from "style-centric" to "target-style-centric" to emphasize the new approach.
- Improved layout planning to focus on gathering layout inspiration rather than strict structural differences.
- Enhanced task descriptions and requirements for clarity and consistency across phases.
- Updated TodoWrite patterns to track progress accurately through the new workflow structure.
2025-10-10 23:11:47 +08:00
catlog22
f1ac41966f refactor(ui-design): optimize screenshot capture tool detection without installation
- Remove npx playwright to prevent auto-installation triggers
- Add explicit tool availability checks using 'which' command
- Check for playwright-cli, google-chrome, chrome, and chromium executables
- Only attempt screenshot capture if tools are already installed
- Provide clear tool availability reporting to users
- Gracefully fallback to manual mode when no tools available
- Support chromium browser on Linux systems

This ensures the workflow never triggers package installations and works
safely in environments without screenshot tools installed.
2025-10-10 22:33:09 +08:00
catlog22
db1b4aa43b feat(ui-design): add memory check mechanism to workflow commands
Add Phase 0.1/1.1 memory check to all UI design workflow commands to skip
execution when outputs already exist. This optimization dramatically reduces
redundant execution time from minutes to <1 second.

Changes:
- extract.md: Check for style-cards.json, skip Phase 0.5-3 if exists
- consolidate.md: Check for style-1/design-tokens.json, skip Phase 2-6
- generate.md: Check for compare.html, skip Phase 1.5-4
- update.md: Check for current design run in synthesis-spec, skip Phase 2-5

Benefits:
- >99% time reduction for repeated workflow execution
- Automatic cache detection without manual flags
- Clear reporting of skipped phases

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

Co-Authored-By: Claude <noreply@anthropic.com>
2025-10-10 21:24:50 +08:00
catlog22
ca8ee121a7 docs: update README_CN.md to v4.3.0 with self-contained CSS architecture highlights 2025-10-10 20:04:17 +08:00
catlog22
8b9cc411e9 docs: update README.md to v4.3.0 with self-contained CSS architecture highlights 2025-10-10 20:03:39 +08:00
catlog22
3fd087620b docs(changelog): add v4.3.0 release notes for UI Design Workflow V2
- Self-contained CSS architecture improvements
- Removed placeholder mechanism
- Enhanced agent CSS generation with direct token values
- Simplified workflow with 346 lines removed
- Better style differentiation and design quality

Features:
- generate-v2 command with independent CSS generation
- explore-auto-v2 updated for new architecture
- Agents read design-tokens.json directly
- No more tokens.css or placeholder replacement

Benefits:
- Faster execution (2 fewer intermediate steps)
- Better style diversity and differentiation
- Easier debugging and maintenance
- Self-contained, portable CSS files

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

Co-Authored-By: Claude <noreply@anthropic.com>
2025-10-10 19:32:53 +08:00
catlog22
6e37881588 refactor(ui-design): remove placeholder mechanism and simplify CSS generation workflow
- Agent now directly generates HTML with final CSS references (no placeholders)
- Remove tokens.css dependency - agents create self-contained CSS from design-tokens.json
- Simplify ui-generate-preview-v2.sh (no placeholder replacement logic)
- Update Phase 2.5 validation to check actual href attributes
- Remove Phase 1.6 (token conversion step)
- Improve agent instructions with direct CSS value usage from design tokens

Benefits:
- Simpler workflow with fewer intermediate steps
- More flexible CSS generation - agents can adapt token values based on design_attributes
- Better style differentiation across variants
- Reduced dependencies and potential error points

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

Co-Authored-By: Claude <noreply@anthropic.com>
2025-10-10 19:29:38 +08:00
catlog22
043a3f05ba refactor(ui-design): optimize layout planning to prevent architecture homogenization
- Replace exa-code with web-search for diverse layout inspiration
- Simplify from keyword pools to direct "common variations" search
- Add selection strategy for agents to pick different structural patterns
- Support unlimited layout variants with natural diversity

Impact: Prevents layout architecture convergence by leveraging web search
for real-world layout variations instead of code examples.

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

Co-Authored-By: Claude <noreply@anthropic.com>
2025-10-10 17:05:11 +08:00
catlog22
6b6367a669 feat: Add ui-generate-preview-v2.sh script for style-centric prototype preview generation
- Implemented a new script to generate compare.html and index.html for UI prototypes.
- Auto-detects styles, layouts, and targets from HTML file patterns.
- Generates an interactive comparison matrix and a simple index of prototypes.
- Includes a detailed PREVIEW.md guide with usage instructions and file structure.
2025-10-10 16:53:53 +08:00
catlog22
d255e633fe refactor(ui-design): remove internal parameter --continue-run for clarity and maintain backward compatibility 2025-10-10 15:22:11 +08:00
catlog22
6b6481dc3f refactor(ui-design): clean up command documentation by removing unused parameters and clarifying usage instructions 2025-10-10 15:12:24 +08:00
catlog22
e0d4bf2aee refactor(ui-design): optimize consolidate workflow - remove MCP calls and fix path inconsistency
## Major Changes

### 1. Remove MCP Calls (Philosophy-Driven Refinement)
- Eliminated all 13 MCP queries (4 per variant + 1 accessibility)
- Replaced with pure AI philosophy-driven token refinement
- Uses design_attributes from extract phase to map to token values
- Performance: ~50% faster execution (~60s vs ~120s)
- Quality: Better variant divergence (no trend pollution)

### 2. Fix Path Naming Inconsistency
- Fixed mismatch: `style-variant-1/` → `style-1/`
- mkdir creates: style-1/, style-2/, style-3/
- Agent now writes to matching directories using loop index {N}
- Added CRITICAL PATH MAPPING section for clarity

## Technical Details

**MCP Removal:**
- Step 1: Trend Research → Load Design Philosophy
- Step 2: Added attribute-to-token mapping rules
- Agent prompt: Removed MCP integration code
- All accessibility validation uses built-in AI knowledge

**Path Fix:**
- Unified on numeric index format: style-{N}/ (N = 1-based loop index)
- Updated 9 path references throughout the file
- Separated variant.id (metadata) from directory names (numeric index)
- Added examples and clarifications for agent implementation

## Impact

- MCP calls: 13 → 0 (-100%)
- Execution time: ~120s → ~60s (-50%)
- Variant divergence: Medium → High
- Path consistency: Broken → Fixed

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

Co-Authored-By: Claude <noreply@anthropic.com>
2025-10-10 14:39:53 +08:00
catlog22
c0921cd5ff feat(ui-design): add optional layout-specific token extension
- Allow agent to create layout-specific tokens if needed
- Use `--layout-*` prefix for layout-specific CSS variables
- Keep prompt minimal - let agent decide when extension is needed
- Examples: --layout-spacing-navbar-height, --layout-size-sidebar-width

Benefits:
-  Flexible token system (core + layout-specific)
-  Agent autonomy (decides when to extend)
-  Clear naming convention (--layout-* prefix)
-  Minimal workflow changes

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

Co-Authored-By: Claude <noreply@anthropic.com>
2025-10-10 14:25:27 +08:00
catlog22
cb6e44efde refactor(ui-design): optimize workflow phases and token refinement strategy
**generate.md - Fix CSS variable naming mismatch**:
- Move token conversion to Phase 1.6 (before agent generation)
- Add Phase 1.7 to extract actual variable names from tokens.css
- Update Phase 2a agent prompt to read tokens.css directly
- Eliminate variable name guessing - agent uses actual file reference
- Remove redundant token conversion from Phase 2b

Benefits:
-  Eliminates CSS variable name mismatches
-  Single source of truth (tokens.css)
-  More reliable agent generation
-  Easier debugging

**consolidate.md - Replace MCP research with philosophy-driven refinement**:
- Remove variant-specific MCP trend research (4 queries per variant)
- Use design_attributes from extraction phase as refinement rules
- Apply philosophy-driven token generation (no external calls)
- Preserve variant divergence through anti_keywords constraints
- Faster execution (~30-60s saved per variant)

Benefits:
-  Better divergence preservation
-  Faster workflow execution
-  Pure AI-driven refinement
-  Consistent with extraction phase philosophy

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

Co-Authored-By: Claude <noreply@anthropic.com>
2025-10-10 13:24:48 +08:00
catlog22
e3f8283386 docs(ui-design): eliminate output-then-save ambiguity in workflow documentation
Clarified file writing patterns across UI design workflows to prevent confusion
between "generate content as output then save" vs "direct write to file" approaches.

Changes:
- extract.md: Merged Phase 2 & 3 to unify style synthesis and file write operations
  * Updated phase title to emphasize direct file writing
  * Added explicit note about internal processing without context output
  * Consolidated parse-and-write step into single atomic operation

- imitate-auto.md: Added clarifying comments for orchestrator file transformation
  * Documented that Phase 2 uses orchestrator-level read-process-write pattern
  * Explained this as performance optimization to bypass consolidate phase

The entire UI design workflow now consistently follows clear file operation patterns
with no ambiguous intermediate output steps.

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

Co-Authored-By: Claude <noreply@anthropic.com>
2025-10-10 12:55:41 +08:00
catlog22
a1c1c95bf4 fix(ui-design): use mcp__exa__web_search_exa for design trend research and URL analysis
- Replace mcp__exa__get_code_context_exa with mcp__exa__web_search_exa in consolidate.md
  for trend research queries (colors, typography, layout, contrast, accessibility)
- Add Phase 0.75 URL Content Analysis in imitate-auto.md for screenshot fallback mode
- Use web_search_exa for design pattern extraction from URLs when screenshots unavailable
- Update workflow documentation to reflect new MCP tool usage

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

Co-Authored-By: Claude <noreply@anthropic.com>
2025-10-10 12:37:34 +08:00
catlog22
4e48803424 fix(ui-design): ensure component templates include CSS placeholders
Fix critical CSS loading issue where component templates were missing
style references due to contradictory instructions.

Changes:
- Require all templates (pages and components) to generate complete HTML5 documents
- Components now use full document structure with isolated body content
- Guarantees <head> tag presence for CSS placeholder injection
- Update validation to enforce <!DOCTYPE html> requirement
- Update documentation to reflect unified template approach

This ensures ui-instantiate-prototypes.sh can reliably inject STRUCTURAL_CSS
and TOKEN_CSS placeholders, fixing component styling issues.

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

Co-Authored-By: Claude <noreply@anthropic.com>
2025-10-10 12:30:17 +08:00
catlog22
36728b6e59 refactor(ui-design-agent): remove script execution details and clarify agent responsibilities
- Remove detailed shell script integration documentation (convert_tokens_to_css.sh, ui-instantiate-prototypes.sh)
- Scripts are orchestrator's responsibility, not agent's
- Simplify Performance Optimization section to focus on architecture concept
- Clarify Layer 1 (agent's creative work) vs Layer 2 (orchestrator's file operations)
- Keep agent documentation focused on design generation, MCP research, and file writing

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

Co-Authored-By: Claude <noreply@anthropic.com>
2025-10-10 11:26:51 +08:00
catlog22
9c1131e384 refactor(ui-design-agent): enhance MCP integration and add detailed shell script documentation
- Remove Code Index MCP integration (focus on design trends only)
- Replace mcp__exa__get_code_context_exa with mcp__exa__web_search_exa for design trend research
- Add detailed shell script integration documentation:
  - convert_tokens_to_css.sh: Token JSON to CSS conversion with usage patterns and error handling
  - ui-instantiate-prototypes.sh: Template instantiation with auto-detection and mode options
- Update MCP use cases to focus on design trends, color/typography, and accessibility patterns
- Clarify that agent uses web search for current design trends, not code implementation

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

Co-Authored-By: Claude <noreply@anthropic.com>
2025-10-10 11:24:40 +08:00
catlog22
a2a608f3ca refactor(ui-design): enhance imitate-auto workflow with key features and interactive confirmation 2025-10-10 11:12:34 +08:00
catlog22
83155ab662 refactor(ui-design-agent): optimize structure and remove version info
**Changes**:
- Merged duplicate Reference section into Design Standards
- Simplified Core Capabilities quality standards
- Consolidated Tool Operations sections
- Removed Version & Changelog section (40 lines)
- Reduced from 693 to 578 lines (16.6% reduction)

**Key improvements**:
- Eliminated content duplication (Token System, Quality Standards)
- Improved document flow and readability
- All technical details and requirements preserved
- Version history now maintained in CHANGELOG.md only

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

Co-Authored-By: Claude <noreply@anthropic.com>
2025-10-10 10:31:47 +08:00
catlog22
af7ff3a86a refactor(ui-design): enhance execution clarity and file writing process in consolidate command 2025-10-10 10:22:32 +08:00
catlog22
92c543aa45 release: v4.2.1 - Command rename and documentation updates
- Rename /workflow:concept-verify to /workflow:concept-clarify
- Update CHANGELOG.md with v4.2.1 release notes
- Improve command naming for better clarity

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

Co-Authored-By: Claude <noreply@anthropic.com>
2025-10-10 09:58:23 +08:00
catlog22
4cf66b41a4 refactor(ui-design): update workflow commands and agent configuration
**Agent Changes:**
- Update ui-design-agent.md with refined task definitions
- Improve agent prompt structure and guidelines

**Workflow Command Updates:**
- Simplify explore-auto.md workflow orchestration (-589 lines)
- Streamline imitate-auto.md for faster execution (-378 lines)
- Optimize update.md command flow and documentation (-136 lines)

**Architecture Updates:**
- Update workflow-architecture.md with current patterns
- Refine command parameter documentation

**Cleanup:**
- Remove outdated release-notes-v3.5.0.md

**Summary:**
- Net reduction: 729 lines removed
- Improved clarity and maintainability
- Better alignment with agent-driven execution model

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

Co-Authored-By: Claude <noreply@anthropic.com>
2025-10-10 09:46:27 +08:00
catlog22
f6292a6288 refactor(ui-design): relocate MCP research from extract to consolidate agent
**Extract Changes:**
- Remove Phase 1.5 MCP trend research (Exa queries)
- Save design-space-analysis.json with search keywords for consolidate
- Update to pure Claude-native analysis (aligns with philosophy)
- Simplify completion todos and output documentation

**Consolidate Changes:**
- Load design-space-analysis.json from extraction phase
- Add Step 1: Variant-Specific Trend Research (MCP) to agent prompt
- Agent performs 4 MCP queries per variant + shared accessibility research
- Refine tokens using trend insights while maintaining variant identity
- Update completion reporting and key features

**Generate Changes:**
- Enhance HTML placeholder documentation with critical warnings
- Add complete HTML template examples (page/component modes)
- Clarify {{STRUCTURAL_CSS}} and {{TOKEN_CSS}} placeholder rules
- Simplify agent completion requirements (remove detailed report format)
- Allow agent to self-report completion status

**Benefits:**
- Extract becomes truly Claude-native (no external tools)
- Consolidate agent handles all MCP research in one place
- Better separation of concerns between phases
- Clearer template generation instructions for agents
- More flexible agent reporting

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

Co-Authored-By: Claude <noreply@anthropic.com>
2025-10-10 09:41:49 +08:00
catlog22
29dfd49c90 Enhance UI Design Workflow: Parameter Validation and Documentation Improvements
- Added validation for --style-variants in generate command to ensure it matches actual style directories, preventing errors during prototype generation.
- Updated ui-instantiate-prototypes.sh script to validate style variants against existing directories, providing warnings and auto-correcting when necessary.
- Improved clarity in generate.md documentation regarding parameters, default values, and auto-detection mechanisms.
- Created a comprehensive UI Design Workflow Parameter Clarity Report to address inconsistencies in parameter naming and documentation across extract, consolidate, and generate commands.
- Unified parameter naming conventions to reduce confusion and improve user experience.
- Enhanced user guidance with a new README.md for the UI Design Workflow, outlining best practices and common mistakes.
2025-10-09 22:37:20 +08:00
catlog22
f0bed9e072 Refactor UI design workflow scripts and documentation
- Removed the generation of a unified consolidation report in the consolidate.md file, streamlining the output structure.
- Updated the extract.md file to prioritize the --base-path argument for session management and improved error handling for style variant detection.
- Enhanced generate.md to enforce critical requirements for layout templates, ensuring independence from other targets.
- Added a comprehensive analysis report for the ui-instantiate-prototypes.sh script, detailing issues with style variant mismatches and proposing solutions for validation and prevention.
2025-10-09 22:10:22 +08:00
catlog22
a7153dfc6d fix: unify agent output pattern in generate.md to match consolidate.md
Changes agent task delegation from direct file writing to labeled output format, giving main command control over file paths. Fixes path inconsistency issues when called from explore-auto workflow.

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

Co-Authored-By: Claude <noreply@anthropic.com>
2025-10-09 20:46:26 +08:00
catlog22
02448ccd21 refactor: unify UI design workflow target parameters for pages and components
Consolidate separate page/component modes into a unified target system to
reduce code duplication and simplify the workflow parameter model.

Changes:
- Merge --pages and --components into unified --targets parameter
- Add --target-type (auto|page|component) with intelligent detection
- Remove Phase 0d from explore-auto.md (131 lines of duplicate logic)
- Implement detect_target_type() helper for automatic classification
- Update generate.md to support adaptive wrapper generation
  - Full HTML structure for pages
  - Minimal wrapper for isolated components
- Update imitate-auto.md and update.md for parameter consistency
- Enhance ui-design-agent.md with adaptive design capabilities
- Maintain full backward compatibility with legacy syntax

Benefits:
- Code reduction: -35% in target inference logic (255 → 165 lines)
- Maintenance: Single unified logic path vs dual implementations
- Extensibility: Foundation for future mixed-mode support
- UX: Simpler parameter model with automatic type detection

Technical Details:
- explore-auto.md: 605 lines changed (unified Phase 0c)
- generate.md: 353 lines changed (targets + adaptive wrapper)
- Net change: +685 insertions, -504 deletions across 5 files

All existing workflows remain compatible via legacy parameter support.

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

Co-Authored-By: Claude <noreply@anthropic.com>
2025-10-09 20:33:09 +08:00
catlog22
1d573979c7 feat: refactor UI design workflow for agent-driven execution and default separate mode
## Core Changes

### 1. Fix Token Application Issues (v4.2.1-fix)
- Add convert_tokens_to_css.sh script for design-tokens.json → tokens.css conversion
- Auto-generate Google Fonts @import for web fonts
- Auto-generate global font application rules (body, headings)
- Add Phase 1.8 to generate.md: Token Variable Name Extraction
- Update generate.md Phase 2a: Inject exact variable names into agent prompt
- Fix CSS variable naming mismatches (20+ variables)

### 2. Refactor consolidate.md - Default to Separate Mode
- Remove --keep-separate parameter (now default behavior)
- Remove Unified Mode (Phase 4A) entirely
- Use ui-design-agent for multi-file generation (Phase 4)
- Generate N independent design systems by default
- Update documentation and completion messages
- Add Task(*) to allowed-tools

### 3. Update explore-auto.md Integration
- Remove --keep-separate from Phase 2 consolidate command
- Update comments to reflect default separate mode behavior

### 4. Refactor ui-design-agent.md (v2.0 → v3.0)
- Remove slash command execution logic
- Focus on consolidate.md and generate.md task execution
- Remove workflow orchestration content
- Add MCP integration strategies (Exa + Code Index)
- Integrate v4.2.1-fix changes

## Impact
- All workflows now default to separate design systems (matrix-ready)
- Agent handles multi-file generation efficiently
- Token application issues resolved
- Simplified user experience (fewer parameters)

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

Co-Authored-By: Claude <noreply@anthropic.com>
2025-10-09 19:42:50 +08:00
catlog22
447837df39 fix: ensure correct layout variant count generation in UI workflow
Fix layout strategy generation issues across UI design commands:
- consolidate.md: Enhance layout synthesis prompt with explicit examples and requirements
  * Add concrete 3-layout example to clarify expected output structure
  * Emphasize requirement to generate EXACTLY N strategies (not more, not less)
  * Add sequential ID validation (layout-1, layout-2, ..., layout-N)
- explore-auto.md: Add missing --layout-variants parameter to consolidate command call
  * Phase 2 now passes layout_variants count to ensure correct strategy generation
  * Prevents mismatch between requested layouts and generated strategies
- extract.md: Update next step suggestions to include --layout-variants parameter
  * Users now see optional [--layout-variants <count>] in command examples
  * Improves discoverability of layout customization option

Before: consolidate would only generate default 3 layouts even when user specified different count
After: consolidate receives and respects user-specified layout variant count

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

Co-Authored-By: Claude <noreply@anthropic.com>
2025-10-09 18:17:39 +08:00
catlog22
20c75c0060 feat: integrate Exa MCP for design trend research in UI workflow
Enhance UI Design Workflow with intelligent design trend research capabilities:
- Add design trend analysis in extract phase using Exa MCP API
- Integrate layout strategy planning with current UI/UX patterns (2024-2025)
- Update consolidation command to include dynamic layout generation
- Add ui-instantiate-prototypes.sh script for prototype management
- Simplify path structure by removing nested .design directories
- Update workflow architecture documentation

This integration enables context-aware design decisions based on modern design trends
and improves the quality of generated UI prototypes.

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

Co-Authored-By: Claude <noreply@anthropic.com>
2025-10-09 18:04:37 +08:00
catlog22
c7e2d6f82f Refactor documentation for UI Design Workflow (v4.2.1): Optimize explore-auto and imitate-auto commands, enhance clarity and maintainability, and reduce file sizes while preserving functionality. Remove CHANGELOG-v4.2.0.md as it is no longer needed. Update README and README_CN to reflect new version and features. 2025-10-09 15:51:23 +08:00
catlog22
561a04c193 feat: add imitate-auto workflow for rapid UI design replication
- Introduced a new command `/workflow:ui-design:imitate-auto` for imitating UI designs from URLs or images.
- Streamlined execution model with 5 phases: initialization, screenshot capture, style extraction, token adaptation, and prototype generation.
- Emphasized single style and layout generation, bypassing the consolidate step for improved speed.
- Implemented automated screenshot capture with fallback to manual input if necessary.
- Enhanced error handling for missing references and screenshot failures.
- Provided detailed documentation and examples for usage and execution flows.
2025-10-09 14:38:35 +08:00
catlog22
76fc10c2f9 feat: v4.2.0 - Enhance multi-page support with improved prompt parsing, cross-page consistency validation, and user confirmation mechanisms 2025-10-09 12:19:31 +08:00
catlog22
ad32e7f4a2 docs: move CHANGELOG files to root directory
Move version changelogs to project root for better visibility:
- CHANGELOG-v4.1.0.md (Pure matrix mode + path corrections)
- CHANGELOG-v4.1.1.md (Windows symlink fix + agent optimization)

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

Co-Authored-By: Claude <noreply@anthropic.com>
2025-10-09 11:37:25 +08:00
catlog22
184fd1475b fix: v4.1.1 - Windows symlink fix and layout-based agent optimization
## Fixes
- Fix Windows symlink creation using mklink /D instead of ln -s
- Resolve duplicate directory issue (latest/ vs runs/run-xxx/)

## Optimizations
- Redesign agent allocation from style-based to layout-based
- Add batch processing (max 8 styles per agent)
- Reduce agent count by 60%+ for high variant scenarios (32 styles: 32→12 agents)

## Files Changed
- auto.md: Phase 0b symlink creation (Windows-compatible)
- generate.md: Phase 2 agent allocation strategy (layout-based)
- CHANGELOG-v4.1.1.md: Complete documentation

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

Co-Authored-By: Claude <noreply@anthropic.com>
2025-10-09 11:27:23 +08:00
catlog22
b27708a7da feat: v4.1.0 - UI design workflow matrix mode refactoring
## Core Changes
- Pure matrix mode (style × layout combinations)
- Removed standard/creative mode selection
- Simplified parameters: --style-variants, --layout-variants
- Path corrections: standalone mode uses .workflow/.scratchpad/

## Modified Files
- auto.md: Simplified Phase 3, corrected paths
- generate.md: Complete rewrite for matrix-only mode
- consolidate.md: Path corrections for standalone mode
- extract.md: Path corrections for standalone mode

## New Files
- CHANGELOG-v4.1.0.md: Complete changelog
- _template-compare-matrix.html: Interactive visualization template

## Breaking Changes
- Deprecated: --variants, --creative-variants
- New: --style-variants, --layout-variants
- File naming: {page}-style-{s}-layout-{l}.html

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

Co-Authored-By: Claude <noreply@anthropic.com>
2025-10-09 10:52:34 +08:00
catlog22
56a3543031 chore: remove obsolete files
- Remove old RELEASE_NOTES_v3.2.3.md (use CHANGELOG.md instead)
- Remove accidentally added tailwind-tokens.js

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

Co-Authored-By: Claude <noreply@anthropic.com>
2025-10-09 09:39:34 +08:00
catlog22
28c93a0001 refactor: v4.0.2 - Complete UI design workflow refactoring
BREAKING CHANGES:
- Command paths: /workflow:design:* → /workflow:ui-design:*
- Removed --tool parameter from all commands
- Pure Claude execution, zero external tool dependencies

Major Changes:
- style-extract: Single-pass Claude analysis (1 file vs 4+)
- style-consolidate: Claude synthesis (no gemini-wrapper/codex)
- ui-generate: Unified agent-only execution
- File renames: style-extract.md → extract.md, etc.

Improvements:
- Zero external dependencies (no CLI tools)
- Faster execution, reduced I/O
- Enhanced reproducibility
- Streamlined data flow

Updated:
- CHANGELOG.md: Detailed v4.0.2 release notes
- README.md: Updated all UI design examples
- Command files: Complete rewrite for Claude-native execution

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

Co-Authored-By: Claude <noreply@anthropic.com>
2025-10-09 09:36:30 +08:00
catlog22
81e1d3e940 docs: update README for v4.0.1 with intelligent page inference
Updates:
- Version badge: v3.5.0 → v4.0.1
- What's New: Highlight intelligent page inference and agent mode
- Phase 2 examples: Show simplified commands with page inference
- UI Design Commands: Update all command examples and descriptions
- Command table: Update descriptions with v4.0 features

Key changes:
- Simplest command: /workflow:design:auto --prompt "Modern blog with home and article pages"
- All parameters now optional with smart defaults
- Agent mode examples with --use-agent flag
- Dual input sources (images + text prompts)

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

Co-Authored-By: Claude <noreply@anthropic.com>
2025-10-07 22:04:24 +08:00
catlog22
451b1a762e feat: intelligent page inference from prompt (v4.0.1)
Features:
- --pages parameter now optional with smart inference
- Auto-extract page names from prompt text
  Example: "blog with home, article pages" → ["home", "article"]
- Fallback to synthesis-specification.md in integrated mode
- Default to ["home"] if nothing specified

Changes:
- auto.md: Add Phase 0 page inference logic, update examples
- ui-generate.md: Add page inference in Phase 1, update examples
- CHANGELOG.md: Add v4.0.1 release notes with page inference

Benefits:
- Simplest command: /workflow:design:auto --prompt "Modern blog with home and article pages"
- No need to manually specify --pages in most cases
- More natural and intuitive user experience

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

Co-Authored-By: Claude <noreply@anthropic.com>
2025-10-07 22:00:56 +08:00
catlog22
59b4b57537 chore: remove backward compatibility mention in auto.md
🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-10-07 21:54:54 +08:00
catlog22
e31b93340d refactor: v4.0.0 breaking changes - remove backward compatibility
BREAKING CHANGES:
- Old command format no longer supported
- --session now optional (enables standalone mode)
- --images optional with default "design-refs/*"
- Removed --style-overrides (use --prompt instead)
- Only --pages is required

Migration required from v3.5.0 to v4.0.0
See CHANGELOG.md for migration guide

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

Co-Authored-By: Claude <noreply@anthropic.com>
2025-10-07 21:52:54 +08:00
catlog22
7e75cf8425 feat: enhance UI design workflow with agent mode and flexible inputs (v3.5.1)
Features:
- Unified variant control: --variants parameter controls both style cards and UI prototypes
- Agent creative exploration: --use-agent enables parallel generation of diverse designs
- Dual mode support: standalone (no --session) and integrated (with --session)
- Dual input sources: --images, --prompt, or hybrid (both)
- Command simplification: most parameters now optional with smart defaults

Changes:
- auto.md: Added --variants, --use-agent, --prompt; dual mode detection
- style-extract.md: Agent mode, text input, parallel variant generation
- ui-generate.md: Agent mode, layout diversity, simplified execution
- CHANGELOG.md: Complete v3.5.1 release notes

Backward compatible: All existing commands continue to work

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

Co-Authored-By: Claude <noreply@anthropic.com>
2025-10-07 21:46:45 +08:00
catlog22
bd9278bb02 feat: enhance workflow with CCW-aware IMPL_PLAN.md templates
- Add concept-verify and action-plan-verify quality gate commands
- Enhance IMPL_PLAN.md with CCW Workflow Context section
- Add Artifact Usage Strategy for clear CCW artifact hierarchy
- Update frontmatter with context_package, verification_history, phase_progression
- Synchronize enhancements across task-generate, task-generate-agent, task-generate-tdd
- Update synthesis, plan, and tdd-plan commands with verification guidance

Makes CCW's multi-phase workflow and intelligent context gathering visible in generated documentation.

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

Co-Authored-By: Claude <noreply@anthropic.com>
2025-10-07 20:58:11 +08:00
catlog22
51bd51ea60 refactor: optimize docs workflow with lightweight planning strategy
**Core Changes**:
- Shift from heavy analysis in planning to targeted analysis in execution
- Reduce main process context by collecting only metadata (paths, structure)
- Simplify pre_analysis steps to be more declarative

**docs.md optimizations**:
- Phase 2: Lightweight metadata collection (get_modules_by_depth.sh + Code Index MCP)
- Planning phase now collects only paths and structure, not file content
- IMPL-001: Simplified to 2 pre_analysis steps (structure + tech stack from config files only)
- IMPL-002: Removed system_context loading, single focused analysis step
- IMPL-N (API): Replace rg with mcp__code-index__search_code_advanced for better structure

**doc-generator.md optimizations**:
- Add "Scope-Limited Analysis" philosophy
- Add "Optimized Execution Model" section
- Emphasize analysis is always limited to focus_paths to prevent context explosion

**Benefits**:
- Main process context stays minimal (no risk of overflow)
- Each task has controlled, scoped context
- Better separation: planning = metadata, execution = deep analysis
- More maintainable pre_analysis steps (less nested commands)
- Better use of MCP tools for structured data

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

Co-Authored-By: Claude <noreply@anthropic.com>
2025-10-06 12:19:18 +08:00
catlog22
0e16c6ba4b feat: add interactive preview system for UI prototypes
🌐 Preview Enhancement System
- Auto-generate index.html for master navigation
- Auto-generate compare.html for side-by-side comparison
- Auto-generate PREVIEW.md with setup instructions

📊 Preview Features
- Master navigation with grid layout of all prototypes
- Side-by-side comparison with iframe-based variants
- Responsive viewport toggles (Desktop/Tablet/Mobile 100%/768px/375px)
- Synchronized scrolling for layout comparison
- Dynamic page switching dropdown
- Quick links to implementation notes

🛠️ Preview Options
- Direct browser opening (simplest - double-click index.html)
- Local server (recommended - Python/Node.js/PHP/VS Code Live Server)
- Complete standalone prototypes with no external dependencies

📚 Documentation Updates
- Add detailed UI design commands section to README.md
- Add Chinese UI design commands section to README_CN.md
- Update CHANGELOG.md with comprehensive preview system documentation
- Add usage examples and preview workflow guide
- Update ui-generate.md with preview file templates

🎯 Integration
- Phase 4 in ui-generate command generates all preview files
- Updated TodoWrite to track preview file generation
- Updated output structure to show new preview files
- Enhanced "Next Steps" section with preview instructions

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

Co-Authored-By: Claude <noreply@anthropic.com>
2025-10-06 00:13:33 +08:00
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
catlog22
f549dfcc9b release: v3.2.3 - Version Management System
Add comprehensive version management and upgrade notification system:

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Co-Authored-By: Claude <noreply@anthropic.com>
2025-10-03 12:07:35 +08:00
catlog22
2efd45b0ed feat: Redesign test-gen workflow with independent session and cross-session context
Major redesign of test-gen workflow based on simplified architecture:

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

See CHANGELOG.md for full details.

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

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

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

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

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

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

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

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

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

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

Co-Authored-By: Claude <noreply@anthropic.com>
2025-10-02 09:37:45 +08:00
catlog22
de63ad5797 feat: Add TDD workflow support (v3.1.0)
🧪 TDD Workflow Commands:
- /workflow:tdd-plan: 5-phase TDD planning with Red-Green-Refactor chains
- /workflow:tdd-verify: 4-phase TDD compliance verification
- /workflow:tools:task-generate-tdd: TDD task chain generator
- /workflow:tools:tdd-coverage-analysis: Test coverage and cycle analysis

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

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

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

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

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

Co-Authored-By: Claude <noreply@anthropic.com>
2025-10-02 09:18:08 +08:00
catlog22
c27ed8c900 docs: Add comprehensive configuration sections
### Added Configuration Details
- **Gemini CLI Setup**: Essential settings.json configuration
- **.geminiignore**: Performance optimization guidelines
- **MCP Tools**: Complete setup guide with links and benefits
  - Exa MCP Server for external API patterns
  - Code Index MCP for advanced code search
  - Benefits and automatic fallback explanation

### Improvements
- Organized configuration into three clear sections: Essential, Recommended, Optional
- Added installation guide links for MCP servers
- Clarified that MCP tools are completely optional
- Consistent bilingual documentation structure

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

Co-Authored-By: Claude <noreply@anthropic.com>
2025-10-01 23:48:32 +08:00
catlog22
39051e5dd3 chore: Release version v3.0.1
### Command Updates
- Remove test-strategist and user-researcher brainstorming roles
- Update to 8 core brainstorming roles for focused efficiency

### Documentation
- Update version badges to v3.0.1
- Add release notes to CHANGELOG.md
- Update version references in README files

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

Co-Authored-By: Claude <noreply@anthropic.com>
2025-10-01 23:45:35 +08:00
catlog22
b243bca577 docs: Streamline and optimize README files
- Reduced content by 81% while maintaining all essential information
- Improved structure with clearer sections and better navigation
- Added Quick Start guide for immediate usability
- Consolidated redundant sections and removed verbose explanations
- Simplified command reference tables
- Maintained all installation steps, badges, and links
- Ensured consistent structure between English and Chinese versions

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

Co-Authored-By: Claude <noreply@anthropic.com>
2025-10-01 23:43:14 +08:00
catlog22
247d52bbff docs: Remove test-strategist from brainstorming role lists
Remove test-strategist from documentation as it only has a planning
template but no corresponding brainstorm command implementation.

Current active brainstorming roles (8):
- system-architect
- data-architect
- subject-matter-expert
- product-manager
- product-owner
- scrum-master
- ui-designer
- ux-expert

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

Co-Authored-By: Claude <noreply@anthropic.com>
2025-10-01 23:36:10 +08:00
catlog22
17e8243d35 refactor: Update brainstorming workflow roles and documentation
Major role restructuring to improve workflow efficiency and clarity:

## New Roles Added (4)
- product-owner: Backlog management and user story definition
- scrum-master: Sprint planning and agile process facilitation
- ux-expert: User experience optimization and usability testing
- subject-matter-expert: Domain expertise and industry standards

## Roles Removed (5)
- business-analyst → functionality split to product-owner and scrum-master
- feature-planner → merged into product-owner responsibilities
- innovation-lead → integrated into subject-matter-expert
- security-expert → integrated into subject-matter-expert
- user-researcher → merged into ux-expert

## Files Updated
### Command Files (.claude/commands/workflow/brainstorm/)
- Created: product-owner.md, scrum-master.md, ux-expert.md, subject-matter-expert.md
- Deleted: business-analyst.md, feature-planner.md, innovation-lead.md, security-expert.md, user-researcher.md
- Updated: artifacts.md, auto-parallel.md, auto-squeeze.md, synthesis.md

### Planning Templates (.claude/workflows/cli-templates/planning-roles/)
- Created: product-owner.md, scrum-master.md, ux-expert.md, subject-matter-expert.md
- Archived: Moved 5 deprecated roles to _deprecated/ with migration guide
- Added: _deprecated/README.md with deprecation details and migration paths

### Agent Configurations
- Updated conceptual-planning-agent.md with new role mappings
- Updated action-planning-agent.md with new role references

### Documentation
- Updated README.md brainstorming role tables and descriptions
- Updated README_CN.md with Chinese translations for new roles
- Updated workflow documentation files with new role references

## Breaking Changes
Commands for removed roles are no longer available. Use replacement roles:
- /workflow:brainstorm:business-analyst → use product-owner or scrum-master
- /workflow:brainstorm:feature-planner → use product-owner
- /workflow:brainstorm:innovation-lead → use subject-matter-expert
- /workflow:brainstorm:security-expert → use subject-matter-expert
- /workflow:brainstorm:user-researcher → use ux-expert

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

Co-Authored-By: Claude <noreply@anthropic.com>
2025-10-01 23:31:10 +08:00
catlog22
35ef08fa9b fix: Rewrite install-remote.sh following PowerShell pattern
Major changes following install-remote.ps1 structure:
- All user messages redirected to stderr (>&2)
- Function return values via stdout only (echo path)
- Simplified download/extract logic without excessive validation
- Clear success/failure messages at each step
- Better error handling with status codes

This ensures output capture works correctly:
- $(download_repository) captures only the file path
- $(extract_repository) captures only the directory path
- All user-facing messages appear on screen via stderr

Fixes the "Extraction failed" issue by ensuring download
actually completes and returns a valid path before extraction.

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

Co-Authored-By: Claude <noreply@anthropic.com>
2025-10-01 22:46:51 +08:00
catlog22
260eb8283d fix: Improve error handling and diagnostics in install-remote.sh
Enhanced the extract_repository function to properly capture and display
unzip error messages, helping diagnose extraction failures during remote
installation.

Changes:
- Capture unzip output in variable for better error reporting
- Display detailed error messages when extraction fails
- Improve ZIP integrity test error handling

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

Co-Authored-By: Claude <noreply@anthropic.com>
2025-10-01 22:44:13 +08:00
catlog22
4a75787d31 fix: Improve error handling and diagnostics in install-remote.sh
- Add detailed file verification before extraction
- Check if downloaded file is a valid ZIP archive
- Add file type detection and display
- Better error messages showing actual file status
- Add ZIP integrity testing on extraction failure
- Display temp directory contents on extraction failure

Helps diagnose download/extraction issues by showing:
- File existence and size
- File type (ZIP vs other)
- First bytes of file (for debugging)
- ZIP integrity test results

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

Co-Authored-By: Claude <noreply@anthropic.com>
2025-10-01 22:37:12 +08:00
catlog22
d6f857ffa8 fix: Display installation mode menu in Install-Claude.sh
- Redirect menu prompts to stderr to prevent capture by command substitution
- Fixes issue where installation options were not visible to user
- Menu now displays correctly: "Global" and "Path" installation modes

Issue: When get_user_choice output was captured by $(command),
the menu display was suppressed because stdout was being captured.

Solution: Output all user-facing prompts to stderr (&2) while
keeping the selected value on stdout for function return.

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

Co-Authored-By: Claude <noreply@anthropic.com>
2025-10-01 22:31:33 +08:00
catlog22
f3c1061d1e docs: Add comprehensive installation documentation
- Add detailed installation section with both remote and local options
- Document all four installation scripts (ps1/sh for remote/local)
- Add installation scripts overview table
- Clarify platform-specific requirements
- Add verification steps
- Highlight native support without cross-platform dependencies

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

Co-Authored-By: Claude <noreply@anthropic.com>
2025-10-01 22:27:39 +08:00
catlog22
ef57dd5879 feat: Add native Linux/macOS installation support
- Create Install-Claude.sh for native Bash installation
- Update install-remote.sh to call Install-Claude.sh instead of PowerShell
- Move installation section to top of README files
- Add prominent shell installation instructions for all platforms
- Support true cross-platform installation without PowerShell dependency

Installation methods:
- Windows: PowerShell (install-remote.ps1 + Install-Claude.ps1)
- Linux/macOS: Bash (install-remote.sh + Install-Claude.sh)

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

Co-Authored-By: Claude <noreply@anthropic.com>
2025-10-01 22:26:23 +08:00
catlog22
afe918d146 feat: Enhanced installer with ASCII art banner and arrow key navigation
Major improvements:
- Add colorful ASCII art banner (CLAUDE/CODE/WORKFLOW in Cyan/Green/Yellow)
- Implement arrow key navigation (↑/↓) for installation mode selection
- Add new Path installation mode (hybrid: local agents/commands/output-styles + global workflows/scripts)
- Fix parameter type conversion error for $success variable
- Improve console capability detection with graceful fallback to numbered menu
- Use single-quoted strings to properly escape $ symbols in ASCII art

Technical enhancements:
- New Get-UserChoiceWithArrows function with keyboard input handling
- New Install-Path function for hybrid installation
- Enhanced Show-Banner with three-section colored ASCII art
- Better error handling and stack trace output

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

Co-Authored-By: Claude <noreply@anthropic.com>
2025-10-01 17:14:17 +08:00
catlog22
725adeb0c8 docs: update version to v3.0.0 and release notes
Changes:
- Update version badge from v2.1.0-experimental to v3.0.0
- Replace MCP tools release notes with v3.0.0 unified CLI structure
- Highlight breaking changes: deprecated tool-specific commands
- Add reference to migration guide for users upgrading from v2.x

English README:
- Latest Release v3.0.0: unified CLI command structure
- Breaking Changes: /gemini:*, /qwen:*, /codex:* deprecated

Chinese README:
- 最新版本 v3.0.0: 统一 CLI 命令结构
- 破坏性变更: 旧的工具特定命令已弃用

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

Co-Authored-By: Claude <noreply@anthropic.com>
2025-09-30 22:04:15 +08:00
catlog22
b298588dd5 fix(docs): correct execution strategy for bug fix workflow
Change complex task strategy from "Brainstorm → Planning → Execution"
to "Use /workflow:plan for structured planning and execution"

Rationale:
- Bug fixes and feature additions typically don't need brainstorming
- /workflow:plan is the appropriate entry point for complex tasks
- Brainstorming is reserved for large-scale architectural changes

Updated in both English and Chinese README files.

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

Co-Authored-By: Claude <noreply@anthropic.com>
2025-09-30 16:46:44 +08:00
catlog22
bb6f55d8db fix(docs): correct command references based on Gemini verification
Removed non-existent commands:
- Remove /context command (deprecated)
- Remove /workflow:plan-deep (doesn't exist)
- Remove /workflow:plan-verify (doesn't exist)
- Remove /workflow:brainstorm:auto (doesn't exist)

Added missing commands:
- Add /workflow:session:complete to session management
- Add /workflow:brainstorm:auto-parallel
- Add /workflow:brainstorm:auto-squeeze
- Add new "Workflow Tools (Internal)" section with:
  - /workflow:tools:context-gather
  - /workflow:tools:concept-enhanced
  - /workflow:tools:task-generate
  - /workflow:tools:task-generate-agent
  - /workflow:tools:status
  - /workflow:tools:docs

Fixed command paths:
- Change /workflow:docs to /workflow:tools:docs in examples
- Update workflow lifecycle diagram
- Update development examples

Updated documentation:
- Remove Plan Verification System section
- Update Enhanced Workflow Lifecycle (5 phases instead of 6)
- Update Key Innovations section

All commands now verified against actual implementations.

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

Co-Authored-By: Claude <noreply@anthropic.com>
2025-09-30 16:41:26 +08:00
catlog22
07eff2d115 docs: translate workflow guide to English and synchronize Chinese version
English README (README.md):
- Translate complete workflow guide from Chinese to English
- Maintain workflow structure and examples
- Update all technical terms to English

Chinese README (README_CN.md):
- Add comprehensive workflow guide
- Include brainstorming, planning, execution, and testing phases
- Add context package and task JSON structure examples
- Include LINUX DO community discussion link

Both versions now have consistent workflow documentation.

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

Co-Authored-By: Claude <noreply@anthropic.com>
2025-09-30 16:17:41 +08:00
catlog22
1acd33ee19 docs: add comprehensive Chinese workflow guide
- Add detailed workflow explanation (头脑风暴 → 规划 → 执行 → 测试)
- Document brainstorming phase with role commands
- Explain action planning phase with coordinator architecture
- Include context-package.json and task JSON structure examples
- Document execution phase with agent assignment
- Add testing workflow and multi-level test generation
- Include feature development and bug fix workflows
- Add LINUX DO community discussion link

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

Co-Authored-By: Claude <noreply@anthropic.com>
2025-09-30 16:14:27 +08:00
catlog22
61e7edb8c2 docs: update README for v3.0.0 unified CLI command structure
- Replace separate Gemini/Qwen/Codex command tables with unified CLI commands
- Add comprehensive v2 to v3.0.0 migration guide
- Document --tool flag for selecting specific tools (gemini/qwen/codex)
- Update quick development examples with new command syntax
- Update project structure diagram to reflect new cli/ directory

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

Co-Authored-By: Claude <noreply@anthropic.com>
2025-09-30 15:58:30 +08:00
catlog22
029f3a3c12 refactor: consolidate CLI commands and templates structure
- Consolidate Gemini, Qwen, and Codex commands into unified CLI commands
- Add new code-analysis mode template
- Update context-gather documentation
- Remove redundant tool-specific command files

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

Co-Authored-By: Claude <noreply@anthropic.com>
2025-09-30 15:52:26 +08:00
catlog22
76bd4885d3 feat(workflow): enhance session discovery with structured task description format and processing guidelines 2025-09-30 13:57:13 +08:00
catlog22
b7df856374 feat(workflow): add direct execution warning for synthesis command to clarify usage restrictions 2025-09-30 13:51:48 +08:00
catlog22
7775cb3b0a Refactor planning workflow documentation and enhance UI designer role template
- Updated the `/workflow:plan` command description to clarify its orchestration of a 4-phase planning workflow.
- Revised the execution flow and core planning principles for improved clarity and structure.
- Removed the `ANALYSIS_RESULTS.md` file as it is no longer needed in the workflow.
- Enhanced the `concept-enhanced` tool documentation to specify mandatory first steps and output requirements.
- Expanded the `ui-designer` role template to include detailed design workflows, output requirements, and collaboration strategies.
- Introduced new design phases with clear outputs and user approval checkpoints in the UI designer template.
2025-09-30 13:37:37 +08:00
catlog22
04876c80bd feat: Add task-generate-agent and task-generate commands for autonomous task generation and manual task creation
- Implemented task-generate-agent for autonomous task generation using action-planning-agent with discovery and output phases.
- Introduced task-generate command to generate task JSON files and IMPL_PLAN.md from analysis results with automatic artifact detection and integration.
- Enhanced documentation for both commands, detailing execution lifecycle, phases, and output structures.
- Established clear integration points and error handling for improved user experience.
2025-09-30 10:10:34 +08:00
catlog22
3db68ef15e feat(workflow): rename plan-enchanced to concept-enhanced and update usage instructions 2025-09-30 08:55:39 +08:00
catlog22
2fa9d4251e feat(workflow): enhance planning command documentation and execution lifecycle 2025-09-29 23:56:59 +08:00
catlog22
7e4d370d45 Enhance workflows and commands for intelligent tools strategy
- Updated intelligent-tools-strategy.md to include `--skip-git-repo-check` for Codex write access and development commands.
- Improved context gathering and analysis processes in mcp-tool-strategy.md with additional examples and guidelines for file searching.
- Introduced new command concept-enhanced.md for enhanced intelligent analysis with parallel CLI execution and design blueprint generation.
- Added context-gather.md command for intelligent collection of project context based on task descriptions, generating standardized JSON context packages.
2025-09-29 23:30:03 +08:00
catlog22
8b907ac80f feat(workflow): add comprehensive planning, resumption, review, status, and test generation commands
- Implemented `/workflow:plan` for creating detailed implementation plans with task decomposition and context gathering.
- Added `/workflow:resume` for intelligent session resumption with automatic progress analysis.
- Introduced `/workflow:review` for executing the final phase of quality validation and generating review reports.
- Developed `/workflow:status` to provide on-demand views of workflow status and task progress.
- Created `/workflow:test-gen` to generate comprehensive test workflows based on completed implementation tasks, ensuring full test coverage.
2025-09-29 21:22:39 +08:00
catlog22
84f4e47a50 feat: Add comprehensive test generation and evaluation commands
- Introduced `/workflow:test-gen` command to automate test workflow generation based on completed implementation tasks, including detailed lifecycle phases, task decomposition, and agent assignment.
- Implemented `/workflow:concept-eval` command for pre-planning evaluation of concepts, assessing feasibility, risks, and optimization recommendations using strategic and technical analysis tools.
- Added `/workflow:docs` command for generating hierarchical architecture and API documentation, with structured task creation and session management.
- Developed `/workflow:status` command to provide on-demand views of workflow state, supporting multiple formats and validation checks for task integrity and relationships.
2025-09-29 19:27:57 +08:00
catlog22
c7ec9dd040 feat: Refactor and enhance brainstorming workflow commands
- Removed deprecated `gemini-init.md` command and migrated its functionality to a new structure under `.claude/commands/gemini/`.
- Introduced `auto-parallel.md` for parallel brainstorming automation with dynamic role selection and concurrent execution.
- Added `auto-squeeze.md` for sequential command coordination in brainstorming workflows, ensuring structured execution from framework generation to synthesis.
- Updated `plan.md` to improve clarity on project structure analysis and command execution strategies.
- Enhanced error handling and session management across all commands to ensure robustness and user guidance.
- Improved documentation for generated files and command options to facilitate user understanding and usage.
2025-09-29 15:48:42 +08:00
catlog22
99a8c0d685 feat: Add core task merging principle to workflow plan
- Add "Task Merging Over Decomposition" as core principle
- Define concrete decomposition criteria (2500 lines or 6+ files)
- Standardize error messages to English for consistency
- Improve workflow planning efficiency by reducing unnecessary task splits

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

Co-Authored-By: Claude <noreply@anthropic.com>
2025-09-28 23:26:15 +08:00
catlog22
8d4473d817 refactor: Streamline workflow plan documentation structure
- Move MCP Tools Integration from prominent position to Task JSON Schema section
- Simplify complex command examples by breaking into multiple separate commands
- Remove repository URLs and make MCP integration information more concise
- Improve readability by avoiding complex bash conditionals in examples

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

Co-Authored-By: Claude <noreply@anthropic.com>
2025-09-28 21:23:01 +08:00
catlog22
e616cb402d docs: Add comprehensive MCP Tools configuration sections to both READMEs
## Documentation Enhancements
- **MCP Configuration Sections**: Added dedicated "MCP Tools Configuration" sections in both English and Chinese READMEs
- **Installation Guidance**: Clear step-by-step MCP server installation guides with direct repository links
- **Configuration Resources**: Comprehensive table with installation guides and purposes for each MCP server
- **Benefits Overview**: Detailed explanation of enhanced capabilities when MCP tools are enabled

## User Experience Improvements
- **Optional Enhancement Badging**: Blue "Optional" badges to indicate MCP tools are not required
- **Clear Navigation**: Direct links to GitHub repositories for easy access
- **Pro Tips**: Professional guidance on gradual adoption approach
- **Visual Structure**: Well-organized sections with emojis and clear headings

## Configuration Details
### English README.md
- Added "MCP Tools Configuration (Optional Enhancement)" section
- Quick MCP Setup with two installation options
- Benefits breakdown with specific capability improvements
- Configuration resources table with direct links

### Chinese README_CN.md
- Added "MCP 工具配置 (可选增强)" section
- Translated installation guides and benefits
- Localized professional tips and guidance
- Consistent structure with English version

## Technical Integration
- **Automatic Detection**: CCW automatically detects and uses available MCP tools
- **Fallback Strategy**: Traditional tools used when MCP unavailable
- **IDE Integration**: Simple restart-based activation process
- **No Breaking Changes**: Completely optional enhancement to existing functionality

🔧 Enhanced user onboarding and configuration guidance for MCP tools integration

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

Co-Authored-By: Claude <noreply@anthropic.com>
2025-09-28 16:52:02 +08:00
catlog22
c64493c01b docs: Add prominent MCP tools badges and experimental release announcements
## Documentation Updates
- **Badge Integration**: Added orange experimental MCP Tools badges to both English and Chinese READMEs
- **Version Updates**: Updated version badges to v2.1.0-experimental
- **Release Announcements**: Added prominent experimental release notifications with:
  - MCP tools integration highlights
  - Exa MCP Server and Code Index MCP mentions
  - Experimental feature warnings
- **Key Innovations**: Added MCP Tools Integration to core innovations list

## Visual Improvements
- Orange "Experimental" badges for clear visual distinction
- Links to Model Context Protocol GitHub organization
- Clear experimental warnings in both languages

## Release Features
- Enhanced codebase analysis through MCP tools
- External API patterns via Exa MCP Server
- Advanced internal code search via Code Index MCP
- Automatic fallback to traditional tools
- Optional installation with backward compatibility

🧪 **Experimental**: MCP integration is currently experimental and optional

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

Co-Authored-By: Claude <noreply@anthropic.com>
2025-09-28 16:43:40 +08:00
212 changed files with 40840 additions and 14912 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
---
@@ -23,61 +22,125 @@ You are a pure execution agent specialized in creating actionable implementation
### Input Processing
**What you receive:**
- **Execution Context Package**: Structured context from command layer
- `session_id`: Workflow session identifier (WFS-[topic])
- `session_metadata`: Session configuration and state
- `analysis_results`: Analysis recommendations and task breakdown
- `artifacts_inventory`: Detected brainstorming outputs (synthesis-spec, topic-framework, role analyses)
- `context_package`: Project context and assets
- `mcp_capabilities`: Available MCP tools (code-index, exa-code, exa-web)
- `mcp_analysis`: Optional pre-executed MCP analysis results
**Legacy Support** (backward compatibility):
- **pre_analysis configuration**: Multi-step array format with action, template, method fields
- **Brief actions**: 2-3 word descriptions to expand into comprehensive analysis tasks
- **Control flags**: DEEP_ANALYSIS_REQUIRED, etc.
- **Task requirements**: Direct task description
**What you receive:**
- Task requirements and context
- Control flags from command layer (DEEP_ANALYSIS_REQUIRED, etc.)
- Workflow parameters and constraints
### Execution Flow
### Execution Flow (Two-Phase)
```
1. Parse input requirements and extract control flags
2. Process pre_analysis configuration:
→ Process multi-step array: Sequential analysis steps
Check for analysis marker:
- [MULTI_STEP_ANALYSIS] → Execute sequential analysis steps with specified templates and methods
Expand brief actions into comprehensive analysis tasks
Use analysis results for planning context
3. Assess task complexity (simple/medium/complex)
4. Create staged implementation plan
5. Generate required documentation
6. Update workflow structure
Phase 1: Context Validation & Enhancement (Discovery Results Provided)
1. Receive and validate execution context package
2. Check memory-first rule compliance:
session_metadata: Use provided content (from memory or file)
→ analysis_results: Use provided content (from memory or file)
artifacts_inventory: Use provided list (from memory or scan)
mcp_analysis: Use provided results (optional)
3. Optional MCP enhancement (if not pre-executed):
→ mcp__code-index__find_files() for codebase structure
→ mcp__exa__get_code_context_exa() for best practices
4. Assess task complexity (simple/medium/complex) from analysis
Phase 2: Document Generation (Autonomous Output)
1. Extract task definitions from analysis_results
2. Generate task JSON files with 5-field schema + artifacts
3. Create IMPL_PLAN.md with context analysis and artifact references
4. Generate TODO_LIST.md with proper structure (▸, [ ], [x])
5. Update session state for execution readiness
```
**Pre-Execution Analysis Standards**:
- **Multi-step Pre-Analysis**: Execute comprehensive analysis BEFORE implementation begins
- **Purpose**: Gather context, understand patterns, identify requirements before coding
- **Sequential Processing**: Process each step sequentially, expanding brief actions
- **Example**: "analyze auth" → "Analyze existing authentication patterns, identify current implementation approaches, understand dependency relationships"
- **Template Usage**: Use full template paths with $(cat template_path) for enhanced prompts
- **Method Selection**: Use method specified in each step (gemini/codex/manual/auto-detected)
- **CLI Commands**:
- **Gemini**: `bash(~/.claude/scripts/gemini-wrapper -p "$(cat template_path) [expanded_action]")`
- **Codex**: `bash(codex --full-auto exec "$(cat template_path) [expanded_action]" -s danger-full-access)`
- **Follow Guidelines**: @~/.claude/workflows/intelligent-tools-strategy.md
### Context Package Usage
### Pre-Execution Analysis
**When [MULTI_STEP_ANALYSIS] marker is present:**
**Standard Context Structure**:
```javascript
{
"session_id": "WFS-auth-system",
"session_metadata": {
"project": "OAuth2 authentication",
"type": "medium",
"current_phase": "PLAN"
},
"analysis_results": {
"tasks": [
{"id": "IMPL-1", "title": "...", "requirements": [...]}
],
"complexity": "medium",
"dependencies": [...]
},
"artifacts_inventory": {
"synthesis_specification": ".workflow/WFS-auth/.brainstorming/synthesis-specification.md",
"topic_framework": ".workflow/WFS-auth/.brainstorming/topic-framework.md",
"role_analyses": [
".workflow/WFS-auth/.brainstorming/system-architect/analysis.md",
".workflow/WFS-auth/.brainstorming/subject-matter-expert/analysis.md"
]
},
"context_package": {
"assets": [...],
"focus_areas": [...]
},
"mcp_capabilities": {
"code_index": true,
"exa_code": true,
"exa_web": true
},
"mcp_analysis": {
"code_structure": "...",
"external_research": "..."
}
}
```
#### Multi-Step Pre-Analysis Execution
1. Process each analysis step sequentially from pre_analysis array
2. For each step:
- Expand brief action into comprehensive analysis task
- Use specified template with $(cat template_path)
- Execute with specified method (gemini/codex/manual/auto-detected)
3. Accumulate results across all steps for comprehensive context
4. Use consolidated analysis to inform implementation stages and task breakdown
**Using Context in Task Generation**:
1. **Extract Tasks**: Parse `analysis_results.tasks` array
2. **Map Artifacts**: Use `artifacts_inventory` to add artifact references to task.context
3. **Assess Complexity**: Use `analysis_results.complexity` for document structure decision
4. **Session Paths**: Use `session_id` to construct output paths (.workflow/{session_id}/)
#### Analysis Dimensions Coverage
- **Exa Research**: Use `mcp__exa__get_code_context_exa` for technology stack selection and API patterns
- Architecture patterns and component relationships
- Implementation conventions and coding standards
- Module dependencies and integration points
- Testing requirements and coverage patterns
- Security considerations and performance implications
3. Use Codex insights to create self-guided implementation stages
### MCP Integration Guidelines
**Code Index MCP** (`mcp_capabilities.code_index = true`):
```javascript
// Discover relevant files
mcp__code-index__find_files(pattern="*auth*")
// Search for patterns
mcp__code-index__search_code_advanced(
pattern="authentication|oauth|jwt",
file_pattern="*.{ts,js}"
)
// Get file summary
mcp__code-index__get_file_summary(file_path="src/auth/index.ts")
```
**Exa Code Context** (`mcp_capabilities.exa_code = true`):
```javascript
// Get best practices and examples
mcp__exa__get_code_context_exa(
query="TypeScript OAuth2 JWT authentication patterns",
tokensNum="dynamic"
)
```
**Integration in flow_control.pre_analysis**:
```json
{
"step": "mcp_codebase_exploration",
"action": "Explore codebase structure",
"command": "mcp__code-index__find_files(pattern=\"[task_patterns]\") && mcp__code-index__search_code_advanced(pattern=\"[relevant_patterns]\")",
"output_to": "codebase_structure"
}
```
## Core Functions
@@ -88,38 +151,153 @@ Break work into 3-5 logical implementation stages with:
- Dependencies on previous stages
- Estimated complexity and time requirements
### 2. Implementation Plan Creation
Generate `IMPL_PLAN.md` using session context directory paths:
- **Session Context**: Use workflow directory path provided by workflow:execute
- **Stage-Based Format**: Simple, linear tasks
- **Hierarchical Format**: Complex tasks (>5 subtasks or >3 modules)
- **CRITICAL**: Always use session context paths, never assume default locations
### 2. Task JSON Generation (5-Field Schema + Artifacts)
Generate individual `.task/IMPL-*.json` files with:
### 3. Task Decomposition (Complex Projects)
For tasks requiring >5 subtasks or spanning >3 modules:
- Create detailed task breakdown and tracking
- Generate TODO_LIST.md for progress monitoring using provided session context paths
- Use hierarchical structure (max 3 levels)
**Required Fields**:
```json
{
"id": "IMPL-N[.M]",
"title": "Descriptive task name",
"status": "pending",
"meta": {
"type": "feature|bugfix|refactor|test|docs",
"agent": "@code-developer"
},
"context": {
"requirements": ["from analysis_results"],
"focus_paths": ["src/paths"],
"acceptance": ["measurable criteria"],
"depends_on": ["IMPL-N"],
"artifacts": [
{
"type": "synthesis_specification",
"path": "{from artifacts_inventory}",
"priority": "highest"
}
]
},
"flow_control": {
"pre_analysis": [
{
"step": "load_synthesis_specification",
"commands": ["bash(ls {path} 2>/dev/null)", "Read({path})"],
"output_to": "synthesis_specification",
"on_error": "skip_optional"
},
{
"step": "mcp_codebase_exploration",
"command": "mcp__code-index__find_files() && mcp__code-index__search_code_advanced()",
"output_to": "codebase_structure"
}
],
"implementation_approach": [
{
"step": 1,
"title": "Load and analyze synthesis specification",
"description": "Load synthesis specification from artifacts and extract requirements",
"modification_points": ["Load synthesis specification", "Extract requirements and design patterns"],
"logic_flow": ["Read synthesis specification from artifacts", "Parse architecture decisions", "Extract implementation requirements"],
"depends_on": [],
"output": "synthesis_requirements"
},
{
"step": 2,
"title": "Implement following specification",
"description": "Implement task requirements following consolidated synthesis specification",
"modification_points": ["Apply requirements from [synthesis_requirements]", "Modify target files", "Integrate with existing code"],
"logic_flow": ["Apply changes based on [synthesis_requirements]", "Implement core logic", "Validate against acceptance criteria"],
"depends_on": [1],
"output": "implementation"
}
],
"target_files": ["file:function:lines", "path/to/NewFile.ts"]
}
}
```
### 4. Document Generation
Create workflow documents with proper linking:
- Todo items link to task JSON: `[📋 Details](./.task/IMPL-XXX.json)`
- Completed tasks link to summaries: `[✅ Summary](./.summaries/IMPL-XXX-summary.md)`
- Consistent ID schemes (IMPL-XXX, IMPL-XXX.Y, IMPL-XXX.Y.Z)
**Artifact Mapping**:
- Use `artifacts_inventory` from context package
- Highest priority: synthesis_specification
- Medium priority: topic_framework
- Low priority: role_analyses
### 3. Implementation Plan Creation
Generate `IMPL_PLAN.md` at `.workflow/{session_id}/IMPL_PLAN.md`:
**Structure**:
```markdown
---
identifier: {session_id}
source: "User requirements"
analysis: .workflow/{session_id}/.process/ANALYSIS_RESULTS.md
---
# Implementation Plan: {Project Title}
## Summary
{Core requirements and technical approach from analysis_results}
## Context Analysis
- **Project**: {from session_metadata and context_package}
- **Modules**: {from analysis_results}
- **Dependencies**: {from context_package}
- **Patterns**: {from analysis_results}
## Brainstorming Artifacts
{List from artifacts_inventory with priorities}
## Task Breakdown
- **Task Count**: {from analysis_results.tasks.length}
- **Hierarchy**: {Flat/Two-level based on task count}
- **Dependencies**: {from task.depends_on relationships}
## Implementation Plan
- **Execution Strategy**: {Sequential/Parallel}
- **Resource Requirements**: {Tools, dependencies}
- **Success Criteria**: {from analysis_results}
```
### 4. TODO List Generation
Generate `TODO_LIST.md` at `.workflow/{session_id}/TODO_LIST.md`:
**Structure**:
```markdown
# Tasks: {Session Topic}
## Task Progress
**IMPL-001**: [Main Task] → [📋](./.task/IMPL-001.json)
- [ ] **IMPL-001.1**: [Subtask] → [📋](./.task/IMPL-001.1.json)
- [ ] **IMPL-002**: [Simple Task] → [📋](./.task/IMPL-002.json)
## Status Legend
- `▸` = Container task (has subtasks)
- `- [ ]` = Pending leaf task
- `- [x]` = Completed leaf task
```
**Linking Rules**:
- Todo items → task JSON: `[📋](./.task/IMPL-XXX.json)`
- Completed tasks → summaries: `[✅](./.summaries/IMPL-XXX-summary.md)`
- Consistent ID schemes: IMPL-XXX, IMPL-XXX.Y (max 2 levels)
**Format Specifications**: @~/.claude/workflows/workflow-architecture.md
### 5. Complexity Assessment
Automatically determine planning approach:
### 5. Complexity Assessment & Document Structure
Use `analysis_results.complexity` or task count to determine structure:
**Simple Tasks** (<5 tasks):
- Single IMPL_PLAN.md with basic stages
**Simple Tasks** (5 tasks):
- Flat structure: IMPL_PLAN.md + TODO_LIST.md + task JSONs
- No container tasks, all leaf tasks
**Medium Tasks** (5-15 tasks):
- Enhanced IMPL_PLAN.md + TODO_LIST.md
**Medium Tasks** (6-10 tasks):
- Two-level hierarchy: IMPL_PLAN.md + TODO_LIST.md + task JSONs
- Optional container tasks for grouping
**Complex Tasks** (>15 tasks):
- Hierarchical IMPL_PLAN.md + TODO_LIST.md + detailed .task/*.json files
**Complex Tasks** (>10 tasks):
- **Re-scope required**: Maximum 10 tasks hard limit
- If analysis_results contains >10 tasks, consolidate or request re-scoping
## Quality Standards
@@ -142,12 +320,19 @@ Automatically determine planning approach:
## Key Reminders
**ALWAYS:**
- Focus on actionable deliverables
- Ensure each stage can be completed independently
- Include clear testing and validation steps
- Maintain incremental progress throughout
- **Use provided context package**: Extract all information from structured context
- **Respect memory-first rule**: Use provided content (already loaded from memory/file)
- **Follow 5-field schema**: All task JSONs must have id, title, status, meta, context, flow_control
- **Map artifacts**: Use artifacts_inventory to populate task.context.artifacts array
- **Add MCP integration**: Include MCP tool steps in flow_control.pre_analysis when capabilities available
- **Validate task count**: Maximum 10 tasks hard limit, request re-scope if exceeded
- **Use session paths**: Construct all paths using provided session_id
- **Link documents properly**: Use correct linking format (📋 for JSON, ✅ for summaries)
**NEVER:**
- Over-engineer simple tasks
- Create circular dependencies
- Skip quality gates for complex tasks
- Load files directly (use provided context package instead)
- Assume default locations (always use session_id in paths)
- Create circular dependencies in task.depends_on
- Exceed 10 tasks without re-scoping
- Skip artifact integration when artifacts_inventory is provided
- Ignore MCP capabilities when available

View File

@@ -0,0 +1,478 @@
---
name: cli-execution-agent
description: |
Intelligent CLI execution agent with automated context discovery and smart tool selection. Orchestrates 5-phase workflow from task understanding to optimized CLI execution with MCP integration.
Examples:
- Context: User provides task without context
user: "Implement user authentication"
assistant: "I'll discover relevant context, enhance the task description, select optimal tool, and execute"
commentary: Agent autonomously discovers context via MCP code-index, researches best practices, builds enhanced prompt, selects Codex for complex implementation
- Context: User provides analysis task
user: "Analyze API architecture patterns"
assistant: "I'll gather API-related files, analyze patterns, and execute with Gemini for comprehensive analysis"
commentary: Agent discovers API files, identifies patterns, selects Gemini for architecture analysis
- Context: User provides task with session context
user: "Execute IMPL-001 from active workflow"
assistant: "I'll load task context, discover implementation files, enhance requirements, and execute"
commentary: Agent loads task JSON, discovers code context, routes output to workflow session
color: purple
---
You are an intelligent CLI execution specialist that autonomously orchestrates comprehensive context discovery and optimal tool execution. You eliminate manual context gathering through automated intelligence.
## Core Execution Philosophy
- **Autonomous Intelligence** - Automatically discover context without user intervention
- **Smart Tool Selection** - Choose optimal CLI tool based on task characteristics
- **Context-Driven Enhancement** - Build precise prompts from discovered patterns
- **Session-Aware Routing** - Integrate seamlessly with workflow sessions
- **Graceful Degradation** - Fallback strategies when tools unavailable
## 5-Phase Execution Workflow
```
Phase 1: Task Understanding
↓ Intent, complexity, keywords
Phase 2: Context Discovery (MCP + Search)
↓ Relevant files, patterns, dependencies
Phase 3: Prompt Enhancement
↓ Structured enhanced prompt
Phase 4: Tool Selection & Execution
↓ CLI output and results
Phase 5: Output Routing
↓ Session logs and summaries
```
---
## Phase 1: Task Understanding
### Responsibilities
1. **Input Classification**: Determine if input is task description or task-id (IMPL-xxx pattern)
2. **Intent Detection**: Classify as analyze/execute/plan/discuss
3. **Complexity Assessment**: Rate as simple/medium/complex
4. **Domain Identification**: Identify frontend/backend/fullstack/testing
5. **Keyword Extraction**: Extract technical keywords for context search
### Classification Logic
**Intent Detection**:
- `analyze|review|understand|explain|debug`**analyze**
- `implement|add|create|build|fix|refactor`**execute**
- `design|plan|architecture|strategy`**plan**
- `discuss|evaluate|compare|trade-off`**discuss**
**Complexity Scoring**:
```
Score = 0
+ Keywords match ['system', 'architecture'] → +3
+ Keywords match ['refactor', 'migrate'] → +2
+ Keywords match ['component', 'feature'] → +1
+ Multiple tech stacks identified → +2
+ Critical systems ['auth', 'payment', 'security'] → +2
Score ≥ 5 → Complex
Score ≥ 2 → Medium
Score < 2 → Simple
```
**Keyword Extraction Categories**:
- **Domains**: auth, api, database, ui, component, service, middleware
- **Technologies**: react, typescript, node, express, jwt, oauth, graphql
- **Actions**: implement, refactor, optimize, test, debug
---
## Phase 2: Context Discovery
### Multi-Tool Parallel Strategy
**1. Project Structure Analysis**:
```bash
~/.claude/scripts/get_modules_by_depth.sh
```
Output: Module hierarchy and organization
**2. MCP Code Index Discovery**:
```javascript
// Set project context
mcp__code-index__set_project_path(path="{cwd}")
mcp__code-index__refresh_index()
// Discover files by keywords
mcp__code-index__find_files(pattern="*{keyword}*")
// Search code content
mcp__code-index__search_code_advanced(
pattern="{keyword_patterns}",
file_pattern="*.{ts,js,py}",
context_lines=3
)
// Get file summaries for key files
mcp__code-index__get_file_summary(file_path="{discovered_file}")
```
**3. Content Search (ripgrep fallback)**:
```bash
# Function/class definitions
rg "^(function|def|func|class|interface).*{keyword}" \
--type-add 'source:*.{ts,js,py,go}' -t source -n --max-count 15
# Import analysis
rg "^(import|from|require).*{keyword}" -t source | head -15
# Test files
find . \( -name "*{keyword}*test*" -o -name "*{keyword}*spec*" \) \
-type f | grep -E "\.(js|ts|py|go)$" | head -10
```
**4. External Research (MCP Exa - Optional)**:
```javascript
// Best practices for complex tasks
mcp__exa__get_code_context_exa(
query="{tech_stack} {task_type} implementation patterns",
tokensNum="dynamic"
)
```
### Relevance Scoring
**Score Calculation**:
```javascript
score = 0
+ Path contains keyword (exact match) +5
+ Filename contains keyword +3
+ Content keyword matches × 2
+ Source code file +2
+ Test file +1
+ Config file +1
```
**Context Optimization**:
- Sort files by relevance score
- Select top 15 files
- Group by type: source/test/config/docs
- Build structured context references
---
## Phase 3: Prompt Enhancement
### Enhancement Components
**1. Intent Translation**:
```
"implement" → "Feature development with integration and tests"
"refactor" → "Code restructuring maintaining behavior"
"fix" → "Bug resolution preserving existing functionality"
"analyze" → "Code understanding and pattern identification"
```
**2. Context Assembly**:
```bash
CONTEXT: @{CLAUDE.md} @{discovered_file1} @{discovered_file2} ...
## Discovered Context
- **Project Structure**: {module_summary}
- **Relevant Files**: {top_files_with_scores}
- **Code Patterns**: {identified_patterns}
- **Dependencies**: {tech_stack}
- **Session Memory**: {conversation_context}
## External Research
{optional_best_practices_from_exa}
```
**3. Template Selection**:
```
intent=analyze → ~/.claude/workflows/cli-templates/prompts/analysis/pattern.txt
intent=execute + complex → ~/.claude/workflows/cli-templates/prompts/development/feature.txt
intent=plan → ~/.claude/workflows/cli-templates/prompts/planning/task-breakdown.txt
```
**4. Structured Prompt**:
```bash
PURPOSE: {enhanced_intent}
TASK: {specific_task_with_details}
MODE: {analysis|write|auto}
CONTEXT: {structured_file_references}
## Discovered Context Summary
{context_from_phase_2}
EXPECTED: {clear_output_expectations}
RULES: $(cat {selected_template}) | {constraints}
```
---
## Phase 4: Tool Selection & Execution
### Tool Selection Logic
```
IF intent = 'analyze' OR 'plan':
tool = 'gemini' # Large context, pattern recognition
mode = 'analysis'
ELSE IF intent = 'execute':
IF complexity = 'simple' OR 'medium':
tool = 'gemini' # Fast, good for straightforward tasks
mode = 'write'
ELSE IF complexity = 'complex':
tool = 'codex' # Autonomous development
mode = 'auto'
ELSE IF intent = 'discuss':
tool = 'multi' # Gemini + Codex + synthesis
mode = 'discussion'
# User --tool flag overrides auto-selection
```
### Command Construction
**Gemini/Qwen (Analysis Mode)**:
```bash
cd {directory} && ~/.claude/scripts/{tool}-wrapper -p "
{enhanced_prompt}
"
```
**Gemini/Qwen (Write Mode)**:
```bash
cd {directory} && ~/.claude/scripts/{tool}-wrapper --approval-mode yolo -p "
{enhanced_prompt}
"
```
**Codex (Auto Mode)**:
```bash
codex -C {directory} --full-auto exec "
{enhanced_prompt}
" --skip-git-repo-check -s danger-full-access
```
**Codex (Resume for Related Tasks)**:
```bash
codex --full-auto exec "
{continuation_prompt}
" resume --last --skip-git-repo-check -s danger-full-access
```
### Timeout Configuration
```javascript
baseTimeout = {
simple: 20 * 60 * 1000, // 20min
medium: 40 * 60 * 1000, // 40min
complex: 60 * 60 * 1000 // 60min
}
if (tool === 'codex') {
timeout = baseTimeout * 1.5
}
```
---
## Phase 5: Output Routing
### Session Detection
```javascript
// Check for active session
activeSession = bash("find .workflow/ -name '.active-*' -type f")
if (activeSession.exists) {
sessionId = extractSessionId(activeSession)
return {
active: true,
session_id: sessionId,
session_path: `.workflow/${sessionId}/`
}
}
```
### Output Paths
**Active Session**:
```
.workflow/WFS-{id}/.chat/{agent}-{timestamp}.md
.workflow/WFS-{id}/.summaries/{task-id}-summary.md // if task-id
```
**Scratchpad (No Session)**:
```
.workflow/.scratchpad/{agent}-{description}-{timestamp}.md
```
### Execution Log Structure
```markdown
# CLI Execution Agent Log
**Timestamp**: {iso_timestamp}
**Session**: {session_id | "scratchpad"}
**Task**: {task_id | description}
---
## Phase 1: Task Understanding
- **Intent**: {analyze|execute|plan|discuss}
- **Complexity**: {simple|medium|complex}
- **Keywords**: {extracted_keywords}
## Phase 2: Context Discovery
**Discovered Files** ({N}):
1. {file} (score: {score}) - {description}
**Patterns**: {identified_patterns}
**Dependencies**: {tech_stack}
## Phase 3: Enhanced Prompt
```
{full_enhanced_prompt}
```
## Phase 4: Execution
**Tool**: {gemini|codex|qwen}
**Command**:
```bash
{executed_command}
```
**Result**: {success|partial|failed}
**Duration**: {elapsed_time}
## Phase 5: Output
- Log: {log_path}
- Summary: {summary_path | N/A}
## Next Steps
{recommended_actions}
```
---
## MCP Integration Guidelines
### Code Index Usage
**Project Setup**:
```javascript
mcp__code-index__set_project_path(path="{project_root}")
mcp__code-index__refresh_index()
```
**File Discovery**:
```javascript
// Find by pattern
mcp__code-index__find_files(pattern="*auth*")
// Search content
mcp__code-index__search_code_advanced(
pattern="function.*authenticate",
file_pattern="*.ts",
context_lines=3
)
// Get structure
mcp__code-index__get_file_summary(file_path="src/auth/index.ts")
```
### Exa Research Usage
**Best Practices**:
```javascript
mcp__exa__get_code_context_exa(
query="TypeScript authentication JWT patterns",
tokensNum="dynamic"
)
```
**When to Use Exa**:
- Complex tasks requiring best practices
- Unfamiliar technology stack
- Architecture design decisions
- Performance optimization
---
## Error Handling & Recovery
### Graceful Degradation
**MCP Unavailable**:
```bash
# Fallback to ripgrep + find
if ! mcp__code-index__find_files; then
find . -name "*{keyword}*" -type f | grep -v node_modules
rg "{keyword}" --type ts --max-count 20
fi
```
**Tool Unavailable**:
```
Gemini unavailable → Try Qwen
Codex unavailable → Try Gemini with write mode
All tools unavailable → Report error
```
**Timeout Handling**:
- Collect partial results
- Save intermediate output
- Report completion status
- Suggest task decomposition
---
## Quality Standards
### Execution Checklist
Before completing execution:
- [ ] Context discovery successful (≥3 relevant files)
- [ ] Enhanced prompt contains specific details
- [ ] Appropriate tool selected
- [ ] CLI execution completed
- [ ] Output properly routed
- [ ] Session state updated (if active session)
- [ ] Next steps documented
### Performance Targets
- **Phase 1**: 1-3 seconds
- **Phase 2**: 5-15 seconds (MCP + search)
- **Phase 3**: 2-5 seconds
- **Phase 4**: Variable (tool-dependent)
- **Phase 5**: 1-3 seconds
**Total (excluding Phase 4)**: ~10-25 seconds overhead
---
## Key Reminders
**ALWAYS:**
- Execute all 5 phases systematically
- Use MCP tools when available
- Score file relevance objectively
- Select tools based on complexity and intent
- Route output to correct location
- Provide clear next steps
- Handle errors gracefully with fallbacks
**NEVER:**
- Skip context discovery (Phase 2)
- Assume tool availability without checking
- Execute without session detection
- Ignore complexity assessment
- Make tool selection without logic
- Leave partial results without documentation

View File

@@ -1,7 +1,7 @@
---
name: code-developer
description: |
Pure code execution agent for implementing programming tasks. Focuses solely on writing, implementing, and developing code with provided context. Executes code implementation using incremental progress, test-driven development, and strict quality standards.
Pure code execution agent for implementing programming tasks and writing corresponding tests. Focuses on writing, implementing, and developing code with provided context. Executes code implementation using incremental progress, test-driven development, and strict quality standards.
Examples:
- Context: User provides task with sufficient context
@@ -13,7 +13,6 @@ description: |
user: "Add user authentication"
assistant: "I need to analyze the codebase first to understand the patterns"
commentary: Use Gemini to gather implementation context, then execute
model: sonnet
color: blue
---
@@ -91,6 +90,32 @@ ELIF context insufficient OR task has flow control marker:
- Get API examples: `mcp__exa__get_code_context_exa(query="React authentication hooks", tokensNum="dynamic")`
- Update after changes: `mcp__code-index__refresh_index()`
**Implementation Approach Execution**:
When task JSON contains `flow_control.implementation_approach` array:
1. **Sequential Processing**: Execute steps in order, respecting `depends_on` dependencies
2. **Dependency Resolution**: Wait for all steps listed in `depends_on` before starting
3. **Variable Substitution**: Use `[variable_name]` to reference outputs from previous steps
4. **Step Structure**:
- `step`: Unique identifier (1, 2, 3...)
- `title`: Step title
- `description`: Detailed description with variable references
- `modification_points`: Code modification targets
- `logic_flow`: Business logic sequence
- `command`: Optional CLI command (only when explicitly specified)
- `depends_on`: Array of step numbers that must complete first
- `output`: Variable name for this step's output
5. **Execution Rules**:
- Execute step 1 first (typically has `depends_on: []`)
- For each subsequent step, verify all `depends_on` steps completed
- Substitute `[variable_name]` with actual outputs from previous steps
- Store this step's result in the `output` variable for future steps
- If `command` field present, execute it; otherwise use agent capabilities
**CLI Command Execution (CLI Execute Mode)**:
When step contains `command` field with Codex CLI, execute via Bash tool. For Codex resume:
- First task (`depends_on: []`): `codex -C [path] --full-auto exec "..." --skip-git-repo-check -s danger-full-access`
- Subsequent tasks (has `depends_on`): Add `resume --last` flag to maintain session context
**Test-Driven Development**:
- Write tests first (red → green → refactor)
- Focus on core functionality and edge cases

View File

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

View File

@@ -20,7 +20,6 @@ description: |
auto.md: Assigns dedicated agent with ASSIGNED_ROLE: ui-designer
agent: "I'll execute ui-designer analysis for this topic, creating UX-focused conceptual analysis in .brainstorming/ui-designer/ directory"
model: sonnet
color: purple
---
@@ -84,19 +83,66 @@ def handle_brainstorm_assignment(prompt):
generate_brainstorm_analysis(role, context_vars, output_location, topic)
```
## Flow Control Format Handling
This agent processes **simplified inline [FLOW_CONTROL]** format from brainstorm workflows.
### Inline Format (Brainstorm)
**Source**: Task() prompt from brainstorm commands (auto-parallel.md, etc.)
**Structure**: Markdown list format (3-5 steps)
**Example**:
```markdown
[FLOW_CONTROL]
### Flow Control Steps
1. **load_topic_framework**
- Action: Load structured topic framework
- Command: Read(.workflow/WFS-{session}/.brainstorming/topic-framework.md)
- Output: topic_framework
2. **load_role_template**
- Action: Load role-specific planning template
- Command: bash($(cat "~/.claude/workflows/cli-templates/planning-roles/{role}.md"))
- Output: role_template
3. **load_session_metadata**
- Action: Load session metadata
- Command: bash(cat .workflow/WFS-{session}/workflow-session.json)
- Output: session_metadata
```
**Characteristics**:
- 3-5 simple context loading steps
- Written directly in prompt (not persistent)
- No dependency management
- Used for temporary context preparation
### NOT Handled by This Agent
**JSON format** (used by code-developer, test-fix-agent):
```json
"flow_control": {
"pre_analysis": [...],
"implementation_approach": [...]
}
```
This complete JSON format is stored in `.task/IMPL-*.json` files and handled by implementation agents, not conceptual-planning-agent.
### Role-Specific Analysis Dimensions
| Role | Primary Dimensions | Focus Areas | Exa Usage |
|------|-------------------|--------------|-----------|
| system-architect | architecture_patterns, scalability_analysis, integration_points | Technical design and system structure | `mcp__exa__get_code_context_exa("microservices patterns")` |
| ui-designer | user_flow_patterns, component_reuse, design_system_compliance | UI/UX patterns and consistency | `mcp__exa__get_code_context_exa("React design system patterns")` |
| business-analyst | process_optimization, cost_analysis, efficiency_metrics, workflow_patterns | Business process and ROI | `mcp__exa__get_code_context_exa("business workflow automation")` |
| data-architect | data_models, flow_patterns, storage_optimization | Data structure and flow | `mcp__exa__get_code_context_exa("database schema patterns")` |
| security-expert | vulnerability_assessment, threat_modeling, compliance_check | Security risks and compliance | `mcp__exa__get_code_context_exa("security authentication patterns")` |
| user-researcher | usage_patterns, pain_points, behavior_analysis | User behavior and needs | `mcp__exa__get_code_context_exa("user research methodologies")` |
| product-manager | feature_alignment, market_fit, competitive_analysis | Product strategy and positioning | `mcp__exa__get_code_context_exa("product management frameworks")` |
| innovation-lead | emerging_patterns, technology_trends, disruption_potential | Innovation opportunities | `mcp__exa__get_code_context_exa("emerging technology trends")` |
| feature-planner | implementation_complexity, dependency_mapping, risk_assessment | Development planning | `mcp__exa__get_code_context_exa("agile development patterns")` |
| product-owner | backlog_management, user_stories, acceptance_criteria | Product backlog and prioritization | `mcp__exa__get_code_context_exa("product backlog management patterns")` |
| scrum-master | sprint_planning, team_dynamics, process_optimization | Agile process and collaboration | `mcp__exa__get_code_context_exa("scrum agile methodologies")` |
| ux-expert | usability_optimization, interaction_design, design_systems | User experience and interface | `mcp__exa__get_code_context_exa("UX design patterns")` |
| subject-matter-expert | domain_standards, compliance, best_practices | Domain expertise and standards | `mcp__exa__get_code_context_exa("industry best practices standards")` |
### Output Integration
@@ -134,12 +180,12 @@ When called, you receive:
### Role Options Include:
- `system-architect` - Technical architecture, scalability, integration
- `ui-designer` - User experience, interface design, usability
- `ux-expert` - User experience optimization, interaction design, design systems
- `product-manager` - Business value, user needs, market positioning
- `product-owner` - Backlog management, user stories, acceptance criteria
- `scrum-master` - Sprint planning, team dynamics, agile process
- `data-architect` - Data flow, storage, analytics
- `security-expert` - Security implications, threat modeling, compliance
- `user-researcher` - User behavior, pain points, research insights
- `business-analyst` - Process optimization, efficiency, ROI
- `innovation-lead` - Emerging trends, disruptive technologies
- `subject-matter-expert` - Domain expertise, industry standards, compliance
- `test-strategist` - Testing strategy and quality assurance
### Single Role Execution

View File

@@ -1,291 +1,155 @@
---
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.
- **Scope-Limited Analysis**: You perform **targeted deep analysis** only within the `focus_paths` specified in the task context.
- **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.
## Optimized Execution Model
**Key Principle**: Lightweight metadata loading + targeted content analysis
- **Planning provides**: Module paths, file lists, structural metadata
- **You execute**: Deep analysis scoped to `focus_paths`, content generation
- **Context control**: Analysis is always limited to task's `focus_paths` - prevents context explosion
## 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**: Process the `implementation_approach` array from the `flow_control` block sequentially:
1. **Array Structure**: `implementation_approach` is an array of step objects
2. **Sequential Execution**: Execute steps in order, respecting `depends_on` dependencies
3. **Variable Substitution**: Use `[variable_name]` to reference outputs from previous steps
4. **Step Processing**:
- Verify all `depends_on` steps completed before starting
- Follow `modification_points` and `logic_flow` for each step
- Execute `command` if present, otherwise use agent capabilities
- Store result in `output` variable for future steps
5. **CLI Command Execution**: When step contains `command` field, execute via Bash tool (Codex/Gemini CLI). For Codex with dependencies, use `resume --last` flag.
- **Templates**: Apply templates as specified in `meta.template` or step-level templates.
- **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
---
@@ -91,100 +90,6 @@ ELIF context insufficient OR task has flow control marker:
- Work functions as specified
- Quality standards maintained
2. **Update TODO List**:
- Update TODO_LIST.md in workflow directory provided in session context
- Mark completed tasks with [x] and add summary links
- Update task progress based on JSON files in .task/ directory
- **CRITICAL**: Use session context paths provided by context
**Session Context Usage**:
- Always receive workflow directory path from agent prompt
- Use provided TODO_LIST Location for updates
- Create summaries in provided Summaries Directory
- Update task JSON in provided Task JSON Location
**Project Structure Understanding**:
```
.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
```
**Example TODO_LIST.md Update**:
```markdown
# Tasks: Market Analysis Project
## Task Progress
▸ **IMPL-001**: Research market trends → [📋](./.task/IMPL-001.json)
- [x] **IMPL-001.1**: Data collection → [📋](./.task/IMPL-001.1.json) | [✅](./.summaries/IMPL-001.1-summary.md)
- [ ] **IMPL-001.2**: Analysis report → [📋](./.task/IMPL-001.2.json)
- [ ] **IMPL-002**: Create presentation → [📋](./.task/IMPL-002.json)
- [ ] **IMPL-003**: Stakeholder review → [📋](./.task/IMPL-003.json)
## Status Legend
- `` = Container task (has subtasks)
- `- [ ]` = Pending leaf task
- `- [x]` = Completed leaf task
```
3. **Generate Summary** (using session context paths):
- **MANDATORY**: Create summary in provided summaries directory
- Use exact paths from session context (e.g., `.workflow/WFS-[session-id]/.summaries/`)
- Link summary in TODO_LIST.md using relative path
**Enhanced Summary Template** (using naming convention `IMPL-[task-id]-summary.md`):
```markdown
# Task: [Task-ID] [Name]
## Execution Summary
### Deliverables Created
- `[file-path]`: [brief description of content/purpose]
- `[resource-name]`: [brief description of deliverable]
### Key Outputs
- **[Deliverable Name]** (`[location]`): [purpose/content summary]
- **[Analysis/Report]** (`[location]`): [key findings/conclusions]
- **[Resource/Asset]** (`[location]`): [purpose/usage]
## Outputs for Dependent Tasks
### Available Resources
- **[Resource Name]**: Located at `[path]` - [description and usage]
- **[Analysis Results]**: Key findings in `[location]` - [summary of insights]
- **[Documentation]**: Reference material at `[path]` - [content overview]
### Integration Points
- **[Output/Resource]**: Use `[access method]` to leverage `[functionality]`
- **[Analysis/Data]**: Reference `[location]` for `[specific information]`
- **[Process/Workflow]**: Follow `[documented process]` for `[specific outcome]`
### Usage Guidelines
- [Instructions for using key deliverables]
- [Best practices for leveraging outputs]
- [Important considerations for dependent tasks]
## Status: ✅ Complete
```
**Summary Naming Convention**:
- **Main tasks**: `IMPL-[task-id]-summary.md` (e.g., `IMPL-001-summary.md`)
- **Subtasks**: `IMPL-[task-id].[subtask-id]-summary.md` (e.g., `IMPL-001.1-summary.md`)
- **Location**: Always in `.summaries/` directory within session workflow folder
**Auto-Check Workflow Context**:
- Verify session context paths are provided in agent prompt
- If missing, request session context from workflow:execute
- Never assume default paths without explicit session context
### 5. Problem-Solving
**When facing challenges** (max 3 attempts):

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

@@ -0,0 +1,214 @@
---
name: test-fix-agent
description: |
Execute tests, diagnose failures, and fix code until all tests pass. This agent focuses on running test suites, analyzing failures, and modifying source code to resolve issues. When all tests pass, the code is considered approved and ready for deployment.
Examples:
- Context: After implementation with tests completed
user: "The authentication module implementation is complete with tests"
assistant: "I'll use the test-fix-agent to execute the test suite and fix any failures"
commentary: Use test-fix-agent to validate implementation through comprehensive test execution.
- Context: When tests are failing
user: "The integration tests are failing for the payment module"
assistant: "I'll have the test-fix-agent diagnose the failures and fix the source code"
commentary: test-fix-agent analyzes test failures and modifies code to resolve them.
- Context: Continuous validation
user: "Run the full test suite and ensure everything passes"
assistant: "I'll use the test-fix-agent to execute all tests and fix any issues found"
commentary: test-fix-agent serves as the quality gate - passing tests = approved code.
color: green
---
You are a specialized **Test Execution & Fix Agent**. Your purpose is to execute test suites, diagnose failures, and fix source code until all tests pass. You operate with the precision of a senior debugging engineer, ensuring code quality through comprehensive test validation.
## Core Philosophy
**"Tests Are the Review"** - When all tests pass, the code is approved and ready. No separate review process is needed.
## Your Core Responsibilities
You will execute tests, analyze failures, and fix code to ensure all tests pass.
### Test Execution & Fixing Responsibilities:
1. **Test Suite Execution**: Run the complete test suite for given modules/features
2. **Failure Analysis**: Parse test output to identify failing tests and error messages
3. **Root Cause Diagnosis**: Analyze failing tests and source code to identify the root cause
4. **Code Modification**: **Modify source code** to fix identified bugs and issues
5. **Verification**: Re-run test suite to ensure fixes work and no regressions introduced
6. **Approval Certification**: When all tests pass, certify code as approved
## Execution Process
### Flow Control Execution
When task JSON contains `flow_control` field, execute preparation and implementation steps systematically.
**Pre-Analysis Steps** (`flow_control.pre_analysis`):
1. **Sequential Processing**: Execute steps in order, accumulating context
2. **Variable Substitution**: Use `[variable_name]` to reference previous outputs
3. **Error Handling**: Follow step-specific strategies (`skip_optional`, `fail`, `retry_once`)
**Implementation Approach** (`flow_control.implementation_approach`):
When task JSON contains implementation_approach array:
1. **Sequential Execution**: Process steps in order, respecting `depends_on` dependencies
2. **Dependency Resolution**: Wait for all steps listed in `depends_on` before starting
3. **Variable References**: Use `[variable_name]` to reference outputs from previous steps
4. **Step Structure**:
- `step`: Step number (1, 2, 3...)
- `title`: Step title
- `description`: Detailed description with variable references
- `modification_points`: Test and code modification targets
- `logic_flow`: Test-fix iteration sequence
- `command`: Optional CLI command (only when explicitly specified)
- `depends_on`: Array of step numbers that must complete first
- `output`: Variable name for this step's output
### 1. Context Assessment & Test Discovery
- Analyze task context to identify test files and source code paths
- Load test framework configuration (Jest, Pytest, Mocha, etc.)
- Identify test command from project configuration
```bash
# Detect test framework and command
if [ -f "package.json" ]; then
TEST_CMD=$(cat package.json | jq -r '.scripts.test')
elif [ -f "pytest.ini" ] || [ -f "setup.py" ]; then
TEST_CMD="pytest"
fi
```
### 2. Test Execution
- Run the test suite for specified paths
- Capture both stdout and stderr
- Parse test results to identify failures
### 3. Failure Diagnosis & Fixing Loop
**Execution Modes**:
**A. Manual Mode (Default, meta.use_codex=false)**:
```
WHILE tests are failing AND iterations < max_iterations:
1. Use Gemini to diagnose failure (bug-fix template)
2. Present fix recommendations to user
3. User applies fixes manually
4. Re-run test suite
5. Verify fix doesn't break other tests
END WHILE
```
**B. Codex Mode (meta.use_codex=true)**:
```
WHILE tests are failing AND iterations < max_iterations:
1. Use Gemini to diagnose failure (bug-fix template)
2. Use Codex to apply fixes automatically with resume mechanism
3. Re-run test suite
4. Verify fix doesn't break other tests
END WHILE
```
**Codex Resume in Test-Fix Cycle** (when `meta.use_codex=true`):
- First iteration: Start new Codex session with full context
- Subsequent iterations: Use `resume --last` to maintain fix history and apply consistent strategies
### 4. Code Quality Certification
- All tests pass → Code is APPROVED ✅
- Generate summary documenting:
- Issues found
- Fixes applied
- Final test results
## Fixing Criteria
### Bug Identification
- Logic errors causing test failures
- Edge cases not handled properly
- Integration issues between components
- Incorrect error handling
- Resource management problems
### Code Modification Approach
- **Minimal changes**: Fix only what's needed
- **Preserve functionality**: Don't change working code
- **Follow patterns**: Use existing code conventions
- **Test-driven fixes**: Let tests guide the solution
### Verification Standards
- All tests pass without errors
- No new test failures introduced
- Performance remains acceptable
- Code follows project conventions
## Output Format
When you complete a test-fix task, provide:
```markdown
# Test-Fix Summary: [Task-ID] [Feature Name]
## Execution Results
### Initial Test Run
- **Total Tests**: [count]
- **Passed**: [count]
- **Failed**: [count]
- **Errors**: [count]
## Issues Found & Fixed
### Issue 1: [Description]
- **Test**: `tests/auth/login.test.ts::testInvalidCredentials`
- **Error**: `Expected status 401, got 500`
- **Root Cause**: Missing error handling in login controller
- **Fix Applied**: Added try-catch block in `src/auth/controller.ts:45`
- **Files Modified**: `src/auth/controller.ts`
### Issue 2: [Description]
- **Test**: `tests/payment/process.test.ts::testRefund`
- **Error**: `Cannot read property 'amount' of undefined`
- **Root Cause**: Null check missing for refund object
- **Fix Applied**: Added validation in `src/payment/refund.ts:78`
- **Files Modified**: `src/payment/refund.ts`
## Final Test Results
**All tests passing**
- **Total Tests**: [count]
- **Passed**: [count]
- **Duration**: [time]
## Code Approval
**Status**: ✅ APPROVED
All tests pass - code is ready for deployment.
## Files Modified
- `src/auth/controller.ts`: Added error handling
- `src/payment/refund.ts`: Added null validation
```
## Important Reminders
**ALWAYS:**
- **Execute tests first** - Understand what's failing before fixing
- **Diagnose thoroughly** - Find root cause, not just symptoms
- **Fix minimally** - Change only what's needed to pass tests
- **Verify completely** - Run full suite after each fix
- **Document fixes** - Explain what was changed and why
- **Certify approval** - When tests pass, code is approved
**NEVER:**
- Skip test execution - always run tests first
- Make changes without understanding the failure
- Fix symptoms without addressing root cause
- Break existing passing tests
- Skip final verification
- Leave tests failing - must achieve 100% pass rate
## Quality Certification
**Your ultimate responsibility**: Ensure all tests pass. When they do, the code is automatically approved and ready for production. You are the final quality gate.
**Tests passing = Code approved = Mission complete**

View File

@@ -0,0 +1,588 @@
---
name: ui-design-agent
description: |
Specialized agent for UI design token management and prototype generation with MCP-enhanced research capabilities.
Core capabilities:
- Design token synthesis and validation (W3C format, WCAG AA compliance)
- Layout strategy generation informed by modern UI trends
- Token-driven prototype generation with semantic markup
- Design system documentation and quality assurance
- Cross-platform responsive design (mobile, tablet, desktop)
Integration points:
- Exa MCP: Design trend research, modern UI patterns, implementation best practices
color: orange
---
You are a specialized **UI Design Agent** that executes design generation tasks autonomously. You are invoked by orchestrator commands (e.g., `consolidate.md`, `generate.md`) to produce production-ready design systems and prototypes.
## Core Capabilities
### 1. Design Token Synthesis
**Invoked by**: `consolidate.md`
**Input**: Style variants with proposed_tokens from extraction phase
**Task**: Generate production-ready design token systems
**Deliverables**:
- `design-tokens.json`: W3C-compliant token definitions using OKLCH colors
- `style-guide.md`: Comprehensive design system documentation
- `layout-strategies.json`: MCP-researched layout variant definitions
- `tokens.css`: CSS custom properties with Google Fonts imports
### 2. Layout Strategy Generation
**Invoked by**: `consolidate.md` Phase 2.5
**Input**: Project context from synthesis-specification.md
**Task**: Research and generate adaptive layout strategies via Exa MCP (2024-2025 trends)
**Output**: layout-strategies.json with strategy definitions and rationale
### 3. UI Prototype Generation
**Invoked by**: `generate.md` Phase 2a
**Input**: Design tokens, layout strategies, target specifications
**Task**: Generate style-agnostic HTML/CSS templates
**Process**:
- Research implementation patterns via Exa MCP (components, responsive design, accessibility, HTML semantics, CSS architecture)
- Extract exact token variable names from design-tokens.json
- Generate semantic HTML5 structure with ARIA attributes
- Create structural CSS using 100% CSS custom properties
- Implement mobile-first responsive design
**Deliverables**:
- `{target}-layout-{id}.html`: Style-agnostic HTML structure
- `{target}-layout-{id}.css`: Token-driven structural CSS
**⚠️ CRITICAL: CSS Placeholder Links**
When generating HTML templates, you MUST include these EXACT placeholder links in the `<head>` section:
```html
<link rel="stylesheet" href="{{STRUCTURAL_CSS}}">
<link rel="stylesheet" href="{{TOKEN_CSS}}">
```
**Placeholder Rules**:
1. Use EXACTLY `{{STRUCTURAL_CSS}}` and `{{TOKEN_CSS}}` with double curly braces
2. Place in `<head>` AFTER `<meta>` tags, BEFORE `</head>` closing tag
3. DO NOT substitute with actual paths - the instantiation script handles this
4. DO NOT add any other CSS `<link>` tags
5. These enable runtime style switching for all variants
**Example HTML Template Structure**:
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>{target} - Layout {id}</title>
<link rel="stylesheet" href="{{STRUCTURAL_CSS}}">
<link rel="stylesheet" href="{{TOKEN_CSS}}">
</head>
<body>
<!-- Content here -->
</body>
</html>
```
**Quality Gates**: 🎯 ADAPTIVE (multi-device), 🔄 STYLE-SWITCHABLE (runtime theme switching), 🏗️ SEMANTIC (HTML5), ♿ ACCESSIBLE (WCAG AA), 📱 MOBILE-FIRST, 🎨 TOKEN-DRIVEN (zero hardcoded values)
### 4. Consistency Validation
**Invoked by**: `generate.md` Phase 3.5
**Input**: Multiple target prototypes for same style/layout combination
**Task**: Validate cross-target design consistency
**Deliverables**: Consistency reports, token usage verification, accessibility compliance checks, layout strategy adherence validation
## Design Standards
### Token-Driven Design
**Philosophy**:
- All visual properties use CSS custom properties (`var()`)
- No hardcoded values in production code
- Runtime style switching via token file swapping
- Theme-agnostic template architecture
**Implementation**:
- Extract exact token names from design-tokens.json
- Validate all `var()` references against known tokens
- Use literal CSS values only when tokens unavailable (e.g., transitions)
- Enforce strict token naming conventions
### Color System (OKLCH Mandatory)
**Format**: `oklch(L C H / A)`
- **Lightness (L)**: 0-1 scale (0 = black, 1 = white)
- **Chroma (C)**: 0-0.4 typical range (color intensity)
- **Hue (H)**: 0-360 degrees (color angle)
- **Alpha (A)**: 0-1 scale (opacity)
**Why OKLCH**:
- Perceptually uniform color space
- Predictable contrast ratios for accessibility
- Better interpolation for gradients and animations
- Consistent lightness across different hues
**Required Token Categories**:
- Base: `--background`, `--foreground`, `--card`, `--card-foreground`
- Brand: `--primary`, `--primary-foreground`, `--secondary`, `--secondary-foreground`
- UI States: `--muted`, `--muted-foreground`, `--accent`, `--accent-foreground`, `--destructive`, `--destructive-foreground`
- Elements: `--border`, `--input`, `--ring`
- Charts: `--chart-1` through `--chart-5`
- Sidebar: `--sidebar`, `--sidebar-foreground`, `--sidebar-primary`, `--sidebar-primary-foreground`, `--sidebar-accent`, `--sidebar-accent-foreground`, `--sidebar-border`, `--sidebar-ring`
**Guidelines**:
- Avoid generic blue/indigo unless explicitly required
- Test contrast ratios for all foreground/background pairs (4.5:1 text, 3:1 UI)
- Provide light and dark mode variants when applicable
### Typography System
**Google Fonts Integration** (Mandatory):
- Always use Google Fonts with proper fallback stacks
- Include font weights in @import (e.g., 400;500;600;700)
**Default Font Options**:
- **Monospace**: 'JetBrains Mono', 'Fira Code', 'Source Code Pro', 'IBM Plex Mono', 'Roboto Mono', 'Space Mono', 'Geist Mono'
- **Sans-serif**: 'Inter', 'Roboto', 'Open Sans', 'Poppins', 'Montserrat', 'Outfit', 'Plus Jakarta Sans', 'DM Sans', 'Geist'
- **Serif**: 'Merriweather', 'Playfair Display', 'Lora', 'Source Serif Pro', 'Libre Baskerville'
- **Display**: 'Space Grotesk', 'Oxanium', 'Architects Daughter'
**Required Tokens**:
- `--font-sans`: Primary body font with fallbacks
- `--font-serif`: Serif font for headings/emphasis
- `--font-mono`: Monospace for code/technical content
**Import Pattern**:
```css
@import url('https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&display=swap');
```
### Visual Effects System
**Shadow Tokens** (7-tier system):
- `--shadow-2xs`: Minimal elevation
- `--shadow-xs`: Very low elevation
- `--shadow-sm`: Low elevation (buttons, inputs)
- `--shadow`: Default elevation (cards)
- `--shadow-md`: Medium elevation (dropdowns)
- `--shadow-lg`: High elevation (modals)
- `--shadow-xl`: Very high elevation
- `--shadow-2xl`: Maximum elevation (overlays)
**Shadow Styles**:
```css
/* Modern style (soft, 0 offset with blur) */
--shadow-sm: 0 1px 3px 0px hsl(0 0% 0% / 0.10), 0 1px 2px -1px hsl(0 0% 0% / 0.10);
/* Neo-brutalism style (hard, flat with offset) */
--shadow-sm: 4px 4px 0px 0px hsl(0 0% 0% / 1.00), 4px 1px 2px -1px hsl(0 0% 0% / 1.00);
```
**Border Radius System**:
- `--radius`: Base value (0px for brutalism, 0.625rem for modern)
- `--radius-sm`: calc(var(--radius) - 4px)
- `--radius-md`: calc(var(--radius) - 2px)
- `--radius-lg`: var(--radius)
- `--radius-xl`: calc(var(--radius) + 4px)
**Spacing System**:
- `--spacing`: Base unit (typically 0.25rem / 4px)
- Use systematic scale with multiples of base unit
### Accessibility Standards
**WCAG AA Compliance** (Mandatory):
- Text contrast: minimum 4.5:1 (7:1 for AAA)
- UI component contrast: minimum 3:1
- Color alone not used to convey information
- Focus indicators visible and distinct
**Semantic Markup**:
- Proper heading hierarchy (h1 unique per page, logical h2-h6)
- Landmark roles (banner, navigation, main, complementary, contentinfo)
- ARIA attributes (labels, roles, states, describedby)
- Keyboard navigation support
### Responsive Design
**Mobile-First Strategy** (Mandatory):
- Base styles for mobile (375px+)
- Progressive enhancement for larger screens
- Fluid typography and spacing
- Touch-friendly interactive targets (44x44px minimum)
**Breakpoint Strategy**:
- Use token-based breakpoints (`--breakpoint-sm`, `--breakpoint-md`, `--breakpoint-lg`)
- Test at minimum: 375px, 768px, 1024px, 1440px
- Use relative units (rem, em, %, vw/vh) over fixed pixels
- Support container queries where appropriate
### Token Reference
**Color Tokens** (OKLCH format mandatory):
- Base: `--background`, `--foreground`, `--card`, `--card-foreground`
- Brand: `--primary`, `--primary-foreground`, `--secondary`, `--secondary-foreground`
- UI States: `--muted`, `--muted-foreground`, `--accent`, `--accent-foreground`, `--destructive`, `--destructive-foreground`
- Elements: `--border`, `--input`, `--ring`
- Charts: `--chart-1` through `--chart-5`
- Sidebar: `--sidebar`, `--sidebar-foreground`, `--sidebar-primary`, `--sidebar-primary-foreground`, `--sidebar-accent`, `--sidebar-accent-foreground`, `--sidebar-border`, `--sidebar-ring`
**Typography Tokens**:
- `--font-sans`: Primary body font (Google Fonts with fallbacks)
- `--font-serif`: Serif font for headings/emphasis
- `--font-mono`: Monospace for code/technical content
**Visual Effect Tokens**:
- Radius: `--radius` (base), `--radius-sm`, `--radius-md`, `--radius-lg`, `--radius-xl`
- Shadows: `--shadow-2xs`, `--shadow-xs`, `--shadow-sm`, `--shadow`, `--shadow-md`, `--shadow-lg`, `--shadow-xl`, `--shadow-2xl`
- Spacing: `--spacing` (base unit, typically 0.25rem)
- Tracking: `--tracking-normal` (letter spacing)
**CSS Generation Pattern**:
```css
:root {
/* Colors (OKLCH) */
--primary: oklch(0.5555 0.15 270);
--background: oklch(1.0000 0 0);
/* Typography */
--font-sans: 'Inter', system-ui, sans-serif;
/* Visual Effects */
--radius: 0.5rem;
--shadow-sm: 0 1px 3px 0 hsl(0 0% 0% / 0.1);
--spacing: 0.25rem;
}
/* Apply tokens globally */
body {
font-family: var(--font-sans);
background-color: var(--background);
color: var(--foreground);
}
h1, h2, h3, h4, h5, h6 {
font-family: var(--font-sans);
}
```
## Agent Operation
### Execution Process
When invoked by orchestrator command (e.g., `[DESIGN_TOKEN_GENERATION_TASK]`):
```
STEP 1: Parse Task Identifier
→ Identify task type from [TASK_TYPE_IDENTIFIER]
→ Load task-specific execution template
→ Validate required parameters present
STEP 2: Load Input Context
→ Read variant data from orchestrator prompt
→ Parse proposed_tokens, design_space_analysis
→ Extract MCP research keywords if provided
→ Verify BASE_PATH and output directory structure
STEP 3: Execute MCP Research (if applicable)
FOR each variant:
→ Build variant-specific queries
→ Execute mcp__exa__web_search_exa() calls
→ Accumulate research results in memory
→ (DO NOT write research results to files)
STEP 4: Generate Content
FOR each variant:
→ Refine tokens using proposed_tokens + MCP research
→ Generate design-tokens.json content
→ Generate style-guide.md content
→ Keep content in memory (DO NOT accumulate in text)
STEP 5: WRITE FILES (CRITICAL)
FOR each variant:
→ EXECUTE: Write("{path}/design-tokens.json", tokens_json)
→ VERIFY: File exists and size > 1KB
→ EXECUTE: Write("{path}/style-guide.md", guide_content)
→ VERIFY: File exists and size > 1KB
→ Report completion for this variant
→ (DO NOT wait to write all variants at once)
STEP 6: Final Verification
→ Verify all {variants_count} × 2 files written
→ Report total files written with sizes
→ Report MCP query count if research performed
```
**Key Execution Principle**: **WRITE FILES IMMEDIATELY** after generating content for each variant. DO NOT accumulate all content and try to output at the end.
### Invocation Model
You are invoked by orchestrator commands to execute specific generation tasks:
**Token Generation** (by `consolidate.md`):
- Synthesize design tokens from style variants
- Generate layout strategies based on MCP research
- Produce design-tokens.json, style-guide.md, layout-strategies.json
**Prototype Generation** (by `generate.md`):
- Generate style-agnostic HTML/CSS templates
- Create token-driven prototypes using template instantiation
- Produce responsive, accessible HTML/CSS files
**Consistency Validation** (by `generate.md` Phase 3.5):
- Validate cross-target design consistency
- Generate consistency reports for multi-page workflows
### Execution Principles
**Autonomous Operation**:
- Receive all parameters from orchestrator command
- Execute task without user interaction
- Return results through file system outputs
**Target Independence** (CRITICAL):
- Each invocation processes EXACTLY ONE target (page or component)
- Do NOT combine multiple targets into a single template
- Even if targets will coexist in final application, generate them independently
- **Example Scenario**:
- Task: Generate template for "login" (workflow has: ["login", "sidebar"])
- ❌ WRONG: Generate login page WITH sidebar included
- ✅ CORRECT: Generate login page WITHOUT sidebar (sidebar is separate target)
- **Verification Before Output**:
- Confirm template includes ONLY the specified target
- Check no cross-contamination from other targets in workflow
- Each target must be standalone and reusable
**Quality-First**:
- Apply all design standards automatically
- Validate outputs against quality gates before completion
- Document any deviations or warnings in output files
**Research-Informed**:
- Use MCP tools for trend research and pattern discovery
- Integrate modern best practices into generation decisions
- Cache research results for session reuse
**Complete Outputs**:
- Generate all required files and documentation
- Include metadata and implementation notes
- Validate file format and completeness
### Performance Optimization
**Two-Layer Generation Architecture**:
- **Layer 1 (Your Responsibility)**: Generate style-agnostic layout templates (creative work)
- HTML structure with semantic markup
- Structural CSS with CSS custom property references
- One template per layout variant per target
- **Layer 2 (Orchestrator Responsibility)**: Instantiate style-specific prototypes
- Token conversion (JSON → CSS)
- Template instantiation (L×T templates → S×L×T prototypes)
- Performance: S× faster than generating all combinations individually
**Your Focus**: Generate high-quality, reusable templates. Orchestrator handles file operations and instantiation.
### Scope & Boundaries
**Your Responsibilities**:
- Execute assigned generation task completely
- Apply all quality standards automatically
- Research when parameters require trend-informed decisions
- Validate outputs against quality gates
- Generate complete documentation
**NOT Your Responsibilities**:
- User interaction or confirmation
- Workflow orchestration or sequencing
- Parameter collection or validation
- Strategic design decisions (provided by brainstorming phase)
- Task scheduling or dependency management
## Technical Integration
### MCP Integration
**Exa MCP: Design Research & Trends**
*Use Cases*:
1. **Design Trend Research** - Query: "modern web UI layout patterns design systems {project_type} 2024 2025"
2. **Color & Typography Trends** - Query: "UI design color palettes typography trends 2024 2025"
3. **Accessibility Patterns** - Query: "WCAG 2.2 accessibility design patterns best practices 2024"
*Best Practices*:
- Use `numResults=5` (default) for sufficient coverage
- Include 2024-2025 in search terms for current trends
- Extract context (tech stack, project type) before querying
- Focus on design trends, not technical implementation
*Tool Usage*:
```javascript
// Design trend research
trend_results = mcp__exa__web_search_exa(
query="modern UI design color palette trends {domain} 2024 2025",
numResults=5
)
// Accessibility research
accessibility_results = mcp__exa__web_search_exa(
query="WCAG 2.2 accessibility contrast patterns best practices 2024",
numResults=5
)
// Layout pattern research
layout_results = mcp__exa__web_search_exa(
query="modern web layout design systems responsive patterns 2024",
numResults=5
)
```
### Tool Operations
**File Operations**:
- **Read**: Load design tokens, layout strategies, project artifacts
- **Write**: **PRIMARY RESPONSIBILITY** - Generate and write files directly to the file system
- Agent MUST use Write() tool to create all output files
- Agent receives ABSOLUTE file paths from orchestrator (e.g., `{base_path}/style-consolidation/style-1/design-tokens.json`)
- Agent MUST create directories if they don't exist (use Bash `mkdir -p` if needed)
- Agent MUST verify each file write operation succeeds
- Agent does NOT return file contents as text with labeled sections
- **Edit**: Update token definitions, refine layout strategies when files already exist
**Path Handling**:
- Orchestrator provides complete absolute paths in prompts
- Agent uses provided paths exactly as given without modification
- If path contains variables (e.g., `{base_path}`), they will be pre-resolved by orchestrator
- Agent verifies directory structure exists before writing
- Example: `Write("/absolute/path/to/style-1/design-tokens.json", content)`
**File Write Verification**:
- After writing each file, agent should verify file creation
- Report file path and size in completion message
- If write fails, report error immediately with details
- Example completion report:
```
✅ Written: style-1/design-tokens.json (12.5 KB)
✅ Written: style-1/style-guide.md (8.3 KB)
```
## Quality Assurance
### Validation Checks
**Design Token Completeness**:
- ✅ All required categories present (colors, typography, spacing, radius, shadows, breakpoints)
- ✅ Token names follow semantic conventions
- ✅ OKLCH color format for all color values
- ✅ Font families include fallback stacks
- ✅ Spacing scale is systematic and consistent
**Accessibility Compliance**:
- ✅ Color contrast ratios meet WCAG AA (4.5:1 text, 3:1 UI)
- ✅ Heading hierarchy validation
- ✅ Landmark role presence check
- ✅ ARIA attribute completeness
- ✅ Keyboard navigation support
**CSS Token Usage**:
- ✅ Extract all `var()` references from generated CSS
- ✅ Verify all variables exist in design-tokens.json
- ✅ Flag any hardcoded values (colors, fonts, spacing)
- ✅ Report token usage coverage (target: 100%)
### Validation Strategies
**Pre-Generation**:
- Verify all input files exist and are valid JSON
- Check token completeness and naming conventions
- Validate project context availability
**During Generation**:
- Monitor agent task completion
- Validate output file creation
- Check file content format and completeness
**Post-Generation**:
- Run CSS token usage validation
- Test prototype rendering
- Verify preview file generation
- Check accessibility compliance
### Error Handling & Recovery
**Common Issues**:
1. **Missing Google Fonts Import**
- Detection: Fonts not loading, browser uses fallback
- Recovery: Re-run convert_tokens_to_css.sh script
- Prevention: Script auto-generates import (version 4.2.1+)
2. **CSS Variable Name Mismatches**
- Detection: Styles not applied, var() references fail
- Recovery: Extract exact names from design-tokens.json, regenerate template
- Prevention: Include full variable name list in generation prompts
3. **Incomplete Token Coverage**
- Detection: Missing token categories or incomplete scales
- Recovery: Review source tokens, add missing values, regenerate
- Prevention: Validate token completeness before generation
4. **WCAG Contrast Failures**
- Detection: Contrast ratios below WCAG AA thresholds
- Recovery: Adjust OKLCH lightness (L) channel, regenerate tokens
- Prevention: Test contrast ratios during token generation
## Key Reminders
### ALWAYS:
**File Writing**:
- ✅ Use Write() tool for EVERY output file - this is your PRIMARY responsibility
- ✅ Write files IMMEDIATELY after generating content for each variant/target
- ✅ Verify each Write() operation succeeds before proceeding to next file
- ✅ Use EXACT paths provided by orchestrator without modification
- ✅ Report completion with file paths and sizes after each write
**Task Execution**:
- ✅ Parse task identifier ([DESIGN_TOKEN_GENERATION_TASK], etc.) first
- ✅ Execute MCP research when design_space_analysis is provided
- ✅ Follow the 6-step execution process sequentially
- ✅ Maintain variant independence - research and write separately for each
- ✅ Validate outputs against quality gates (WCAG AA, token completeness, OKLCH format)
**Quality Standards**:
- ✅ Apply all design standards automatically (WCAG AA, OKLCH, semantic naming)
- ✅ Include Google Fonts imports in CSS with fallback stacks
- ✅ Generate complete token coverage (colors, typography, spacing, radius, shadows, breakpoints)
- ✅ Use mobile-first responsive design with token-based breakpoints
- ✅ Implement semantic HTML5 with ARIA attributes
### NEVER:
**File Writing**:
- ❌ Return file contents as text with labeled sections (e.g., "## File 1: design-tokens.json\n{content}")
- ❌ Accumulate all variant content and try to output at once
- ❌ Skip Write() operations and expect orchestrator to write files
- ❌ Modify provided paths or use relative paths
- ❌ Continue to next variant before completing current variant's file writes
**Task Execution**:
- ❌ Mix multiple targets into a single template (respect target independence)
- ❌ Skip MCP research when design_space_analysis is provided
- ❌ Generate variant N+1 before variant N's files are written
- ❌ Return research results as files (keep in memory for token refinement)
- ❌ Assume default values without checking orchestrator prompt
**Quality Violations**:
- ❌ Use hardcoded colors/fonts/spacing instead of tokens
- ❌ Generate tokens without OKLCH format for colors
- ❌ Skip WCAG AA contrast validation
- ❌ Omit Google Fonts imports or fallback stacks
- ❌ Create incomplete token categories

View File

@@ -0,0 +1,151 @@
---
name: analyze
description: Quick codebase analysis using CLI tools (codex/gemini/qwen)
argument-hint: "[--agent] [--tool codex|gemini|qwen] [--enhance] analysis target"
allowed-tools: SlashCommand(*), Bash(*), TodoWrite(*), Read(*), Glob(*), Task(*)
---
# CLI Analyze Command (/cli:analyze)
## Purpose
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
- `--agent` - Use cli-execution-agent for automated context discovery (5-phase intelligent mode)
- `--tool <codex|gemini|qwen>` - Tool selection (default: gemini, ignored in agent mode)
- `--enhance` - Use `/enhance-prompt` for context-aware enhancement
- `<analysis-target>` - Description of what to analyze
## Execution Flow
### Standard Mode (Default)
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
### Agent Mode (`--agent` flag)
Delegate task to `cli-execution-agent` for intelligent execution with automated context discovery.
**Agent invocation**:
```javascript
Task(
subagent_type="cli-execution-agent",
description="Analyze codebase with automated context discovery",
prompt=`
Task: ${analysis_target}
Mode: analyze
Tool Preference: ${tool_flag || 'auto-select'}
${enhance_flag ? 'Enhance: true' : ''}
Agent will autonomously:
- Discover relevant files and patterns
- Build enhanced analysis prompt
- Select optimal tool and execute
- Route output to session/scratchpad
`
)
```
The agent handles all phases internally (understanding, discovery, enhancement, execution, routing).
## File Pattern Auto-Detection
Keywords trigger specific file patterns:
- "auth" → `@{**/*auth*,**/*user*}`
- "component" → `@{src/components/**/*,**/*.component.*}`
- "API" → `@{**/api/**/*,**/routes/**/*}`
- "test" → `@{**/*.test.*,**/*.spec.*}`
- "config" → `@{*.config.*,**/config/**/*}`
- Generic → `@{src/**/*}`
For complex patterns, use `rg` or MCP tools to discover files first, then execute CLI with precise file references.
## Command Template
```bash
cd . && ~/.claude/scripts/gemini-wrapper -p "
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]
"
```
## Examples
**Basic Analysis (Standard Mode)**:
```bash
/cli:analyze "authentication patterns"
# Executes: Gemini analysis with auth file patterns
# Returns: Pattern analysis, architecture insights, recommendations
```
**Intelligent Analysis (Agent Mode)**:
```bash
/cli:analyze --agent "authentication patterns"
# Phase 1: Classifies intent=analyze, complexity=simple, keywords=['auth', 'patterns']
# Phase 2: MCP discovers 12 auth files, identifies patterns
# Phase 3: Builds enhanced prompt with discovered context
# Phase 4: Executes Gemini with comprehensive file references
# Phase 5: Saves execution log with all 5 phases documented
# Returns: Comprehensive analysis + detailed execution log
```
**Architecture Analysis**:
```bash
/cli:analyze --tool qwen "component architecture"
# Executes: Qwen with component file patterns
# Returns: Architecture review, design patterns, improvement suggestions
```
**Performance Analysis**:
```bash
/cli:analyze --tool codex "performance bottlenecks"
# Executes: Codex deep analysis with performance focus
# Returns: Bottleneck identification, optimization recommendations
```
**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)
```
## Output Routing
**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`
**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`
## 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

@@ -0,0 +1,156 @@
---
name: chat
description: Simple CLI interaction command for direct codebase analysis
argument-hint: "[--agent] [--tool codex|gemini|qwen] [--enhance] inquiry"
allowed-tools: SlashCommand(*), Bash(*), Task(*)
---
# CLI Chat Command (/cli:chat)
## Purpose
Direct Q&A interaction with CLI tools for codebase analysis. **Analysis only - does NOT modify code**.
**Intent**: Ask questions, get explanations, understand codebase structure
**Supported Tools**: codex, gemini (default), qwen
## Core Behavior
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
## Parameters
- `<inquiry>` (Required) - Question or analysis request
- `--agent` - Use cli-execution-agent for automated context discovery (5-phase intelligent mode)
- `--tool <codex|gemini|qwen>` - Select CLI tool (default: gemini, ignored in agent mode)
- `--enhance` - Enhance inquiry with `/enhance-prompt` first
- `--all-files` - Include entire codebase in context
- `--save-session` - Save interaction to workflow session
## Execution Flow
### Standard Mode (Default)
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
### Agent Mode (`--agent` flag)
Delegate inquiry to `cli-execution-agent` for intelligent Q&A with automated context discovery.
**Agent invocation**:
```javascript
Task(
subagent_type="cli-execution-agent",
description="Answer question with automated context discovery",
prompt=`
Task: ${inquiry}
Mode: analyze (Q&A)
Tool Preference: ${tool_flag || 'auto-select'}
${all_files_flag ? 'Scope: all-files' : ''}
Agent will autonomously:
- Discover files relevant to the question
- Build Q&A prompt with precise context
- Execute and generate comprehensive answer
- Save conversation log
`
)
```
The agent handles all phases internally.
## Context Assembly
**Always included**: `@{CLAUDE.md,**/*CLAUDE.md}` (project guidelines)
**Optional**:
- User-explicit files from inquiry keywords
- `--all-files` flag includes entire codebase (`--all-files` wrapper parameter)
For targeted analysis, use `rg` or MCP tools to discover relevant files first, then build precise CONTEXT field.
## Command Template
```bash
cd . && ~/.claude/scripts/gemini-wrapper -p "
INQUIRY: [user question]
CONTEXT: @{CLAUDE.md,**/*CLAUDE.md} [inferred or --all-files]
MODE: analysis
RESPONSE: Direct answer, explanation, insights (NO code modification)
"
```
## Examples
**Basic Question (Standard Mode)**:
```bash
/cli:chat "analyze the authentication flow"
# Executes: Gemini analysis
# Returns: Explanation of auth flow, components involved, data flow
```
**Intelligent Q&A (Agent Mode)**:
```bash
/cli:chat --agent "how does JWT token refresh work in this codebase"
# Phase 1: Understands inquiry = JWT refresh mechanism
# Phase 2: Discovers JWT files, refresh logic, middleware patterns
# Phase 3: Builds Q&A prompt with discovered implementation details
# Phase 4: Executes Gemini with precise context for accurate answer
# Phase 5: Saves conversation log with discovered context
# Returns: Detailed answer with code references + execution log
```
**Architecture Question**:
```bash
/cli:chat --tool qwen "how does React component optimization work here"
# Executes: Qwen architecture analysis
# Returns: Component structure explanation, optimization patterns used
```
**Security Analysis**:
```bash
/cli:chat --tool codex "review security vulnerabilities"
# Executes: Codex security analysis
# Returns: Vulnerability assessment, security recommendations (NO automatic fixes)
```
**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
```
**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)
```
## Output Routing
**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`
**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`
## 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,449 @@
---
name: cli-init
description: Initialize CLI tool configurations (Gemini and Qwen) based on workspace analysis
argument-hint: "[--tool gemini|qwen|all] [--output path] [--preview]"
allowed-tools: Bash(*), Read(*), Write(*), Glob(*)
---
# CLI Initialization Command (/cli:cli-init)
## Overview
Initializes CLI tool configurations for the workspace by:
1. Analyzing current workspace using `get_modules_by_depth.sh` to identify technology stacks
2. Generating ignore files (`.geminiignore` and `.qwenignore`) with filtering rules optimized for detected technologies
3. Creating configuration directories (`.gemini/` and `.qwen/`) with settings.json files
**Supported Tools**: gemini, qwen, all (default: all)
## Core Functionality
### Configuration Generation
1. **Workspace Analysis**: Runs `get_modules_by_depth.sh` to analyze project structure
2. **Technology Stack Detection**: Identifies tech stacks based on file extensions, directories, and configuration files
3. **Config Creation**: Generates tool-specific configuration directories and settings files
4. **Ignore Rules Generation**: Creates ignore files with filtering patterns for detected technologies
### Generated Files
#### Configuration Directories
Creates tool-specific configuration directories:
**For Gemini** (`.gemini/`):
- `.gemini/settings.json`:
```json
{
"contextfilename": "CLAUDE.md"
}
```
**For Qwen** (`.qwen/`):
- `.qwen/settings.json`:
```json
{
"contextfilename": "CLAUDE.md"
}
```
#### Ignore Files
Uses gitignore syntax to filter files from CLI tool analysis:
- `.geminiignore` - For Gemini CLI
- `.qwenignore` - For Qwen CLI
Both files have identical content based on detected technologies.
### Supported Technology Stacks
#### Frontend Technologies
- **React/Next.js**: Ignores build artifacts, .next/, node_modules
- **Vue/Nuxt**: Ignores .nuxt/, dist/, .cache/
- **Angular**: Ignores dist/, .angular/, node_modules
- **Webpack/Vite**: Ignores build outputs, cache directories
#### Backend Technologies
- **Node.js**: Ignores node_modules, package-lock.json, npm-debug.log
- **Python**: Ignores __pycache__, .venv, *.pyc, .pytest_cache
- **Java**: Ignores target/, .gradle/, *.class, .mvn/
- **Go**: Ignores vendor/, *.exe, go.sum (when appropriate)
- **C#/.NET**: Ignores bin/, obj/, *.dll, *.pdb
#### Database & Infrastructure
- **Docker**: Ignores .dockerignore, docker-compose.override.yml
- **Kubernetes**: Ignores *.secret.yaml, helm charts temp files
- **Database**: Ignores *.db, *.sqlite, database dumps
### Generated Rules Structure
#### Base Rules (Always Included)
```
# Version Control
.git/
.svn/
.hg/
# OS Files
.DS_Store
Thumbs.db
*.tmp
*.swp
# IDE Files
.vscode/
.idea/
.vs/
# Logs
*.log
logs/
```
#### Technology-Specific Rules
Rules are added based on detected technologies:
**Node.js Projects** (package.json detected):
```
# Node.js
node_modules/
npm-debug.log*
.npm/
.yarn/
package-lock.json
yarn.lock
.pnpm-store/
```
**Python Projects** (requirements.txt, setup.py, pyproject.toml detected):
```
# Python
__pycache__/
*.py[cod]
.venv/
venv/
.pytest_cache/
.coverage
htmlcov/
```
**Java Projects** (pom.xml, build.gradle detected):
```
# Java
target/
.gradle/
*.class
*.jar
*.war
.mvn/
```
## Command Options
### Tool Selection
**Initialize All Tools (default)**:
```bash
/cli:cli-init
```
- Creates `.gemini/`, `.qwen/` directories with settings.json
- Creates `.geminiignore` and `.qwenignore` files
- Sets contextfilename to "CLAUDE.md" for both
**Initialize Gemini Only**:
```bash
/cli:cli-init --tool gemini
```
- Creates only `.gemini/` directory and `.geminiignore` file
**Initialize Qwen Only**:
```bash
/cli:cli-init --tool qwen
```
- Creates only `.qwen/` directory and `.qwenignore` file
### Preview Mode
```bash
/cli:cli-init --preview
```
- Shows what would be generated without creating files
- Displays detected technologies, configuration, and ignore rules
### Custom Output Path
```bash
/cli:cli-init --output=.config/
```
- Generates files in specified directory
- Creates directories if they don't exist
### Combined Options
```bash
/cli:cli-init --tool qwen --preview
/cli:cli-init --tool all --output=.config/
```
## EXECUTION INSTRUCTIONS ⚡ START HERE
**When this command is triggered, follow these exact steps:**
### Step 1: Parse Tool Selection
```bash
# Extract --tool flag (default: all)
# Options: gemini, qwen, all
```
### Step 2: Workspace Analysis (MANDATORY FIRST)
```bash
# Analyze workspace structure
bash(~/.claude/scripts/get_modules_by_depth.sh json)
```
### Step 3: Technology Detection
```bash
# Check for common tech stack indicators
bash(find . -name "package.json" -not -path "*/node_modules/*" | head -1)
bash(find . -name "requirements.txt" -o -name "setup.py" -o -name "pyproject.toml" | head -1)
bash(find . -name "pom.xml" -o -name "build.gradle" | head -1)
bash(find . -name "Dockerfile" | head -1)
```
### Step 4: Generate Configuration Files
**For Gemini** (if --tool is gemini or all):
```bash
# Create .gemini/ directory and settings.json
mkdir -p .gemini
echo '{"contextfilename": "CLAUDE.md"}' > .gemini/settings.json
# Create .geminiignore file with detected technology rules
# Backup existing files if present
```
**For Qwen** (if --tool is qwen or all):
```bash
# Create .qwen/ directory and settings.json
mkdir -p .qwen
echo '{"contextfilename": "CLAUDE.md"}' > .qwen/settings.json
# Create .qwenignore file with detected technology rules
# Backup existing files if present
```
### Step 5: Validation
```bash
# Verify generated files are valid
bash(ls -la .gemini* .qwen* 2>/dev/null || echo "Configuration files created")
```
## Implementation Process (Technical Details)
### Phase 1: Tool Selection
1. Parse `--tool` flag from command arguments
2. Determine which configurations to generate:
- `gemini`: Generate .gemini/ and .geminiignore only
- `qwen`: Generate .qwen/ and .qwenignore only
- `all` (default): Generate both sets of files
### Phase 2: Workspace Analysis
1. Execute `get_modules_by_depth.sh json` to get structured project data
2. Parse JSON output to identify directories and files
3. Scan for technology indicators:
- Configuration files (package.json, requirements.txt, etc.)
- Directory patterns (src/, tests/, etc.)
- File extensions (.js, .py, .java, etc.)
4. Detect project name from directory name or package.json
### Phase 3: Technology Detection
```bash
# Technology detection logic
detect_nodejs() {
[ -f "package.json" ] || find . -name "package.json" -not -path "*/node_modules/*" | head -1
}
detect_python() {
[ -f "requirements.txt" ] || [ -f "setup.py" ] || [ -f "pyproject.toml" ] || \
find . -name "*.py" -not -path "*/__pycache__/*" | head -1
}
detect_java() {
[ -f "pom.xml" ] || [ -f "build.gradle" ] || \
find . -name "*.java" | head -1
}
```
### Phase 4: Configuration Generation
**For each selected tool**, create:
1. **Config Directory**:
- Create `.gemini/` or `.qwen/` directory if it doesn't exist
- Generate `settings.json` with contextfilename setting
- Set contextfilename to "CLAUDE.md" by default
2. **Settings.json Format** (identical for both tools):
```json
{
"contextfilename": "CLAUDE.md"
}
```
### Phase 5: Ignore Rules Generation
1. Start with base rules (always included)
2. Add technology-specific rules based on detection
3. Add workspace-specific patterns if found
4. Sort and deduplicate rules
5. Generate identical content for both `.geminiignore` and `.qwenignore`
### Phase 6: File Creation
1. **Generate config directories**: Create `.gemini/` and/or `.qwen/` directories with settings.json
2. **Generate ignore files**: Create organized ignore files with sections
3. **Create backups**: Backup existing files if present
4. **Validate**: Check generated files are valid
## Generated File Format
### Configuration Files
```json
// .gemini/settings.json or .qwen/settings.json
{
"contextfilename": "CLAUDE.md"
}
```
### Ignore Files
```
# .geminiignore / .qwenignore
# Generated by Claude Code /cli:cli-init command
# Creation date: 2024-01-15 10:30:00
# Detected technologies: Node.js, Python, Docker
#
# This file uses gitignore syntax to filter files for CLI tool analysis
# Edit this file to customize filtering rules for your project
# ============================================================================
# Base Rules (Always Applied)
# ============================================================================
# Version Control
.git/
.svn/
.hg/
# ============================================================================
# Node.js (Detected: package.json found)
# ============================================================================
node_modules/
npm-debug.log*
.npm/
yarn-error.log
package-lock.json
# ============================================================================
# Python (Detected: requirements.txt, *.py files found)
# ============================================================================
__pycache__/
*.py[cod]
.venv/
.pytest_cache/
.coverage
# ============================================================================
# Docker (Detected: Dockerfile found)
# ============================================================================
.dockerignore
docker-compose.override.yml
# ============================================================================
# Custom Rules (Add your project-specific rules below)
# ============================================================================
```
## Error Handling
### Missing Dependencies
- If `get_modules_by_depth.sh` not found, show error with path to script
- Gracefully handle cases where script fails
### Write Permissions
- Check write permissions before attempting file creation
- Show clear error message if cannot write to target location
### Backup Existing Files
- If `.gemini/` directory exists, create backup as `.gemini.backup/`
- If `.qwen/` directory exists, create backup as `.qwen.backup/`
- If `.geminiignore` exists, create backup as `.geminiignore.backup`
- If `.qwenignore` exists, create backup as `.qwenignore.backup`
- Include timestamp in backup filename
## Integration Points
### Workflow Commands
- **After `/cli:plan`**: Suggest running cli-init for better analysis
- **Before analysis**: Recommend updating ignore patterns for cleaner results
### CLI Tool Integration
- Automatically update when new technologies detected
- Integrate with `intelligent-tools-strategy.md` recommendations
## Usage Examples
### Basic Project Setup
```bash
# Initialize all CLI tools (Gemini + Qwen)
/cli:cli-init
# Initialize only Gemini
/cli:cli-init --tool gemini
# Initialize only Qwen
/cli:cli-init --tool qwen
# Preview what would be generated
/cli:cli-init --preview
# Generate in subdirectory
/cli:cli-init --output=.config/
```
### Technology Migration
```bash
# After adding new tech stack (e.g., Docker)
/cli:cli-init # Regenerates all config and ignore files with new rules
# Check what changed
/cli:cli-init --preview # Compare with existing configuration
# Update only Qwen configuration
/cli:cli-init --tool qwen
```
### Tool-Specific Initialization
```bash
# Setup for Gemini-only workflow
/cli:cli-init --tool gemini
# Setup for Qwen-only workflow
/cli:cli-init --tool qwen
# Setup both with preview
/cli:cli-init --tool all --preview
```
## Key Benefits
- **Automatic Detection**: No manual configuration needed
- **Multi-Tool Support**: Configure Gemini and Qwen simultaneously
- **Technology Aware**: Rules adapted to actual project stack
- **Maintainable**: Clear sections for easy customization
- **Consistent**: Follows gitignore syntax standards
- **Safe**: Creates backups of existing files
- **Flexible**: Initialize specific tools or all at once
## Tool Selection Guide
| Scenario | Command | Result |
|----------|---------|--------|
| **New project, using both tools** | `/cli:cli-init` | Creates .gemini/, .qwen/, .geminiignore, .qwenignore |
| **Gemini-only workflow** | `/cli:cli-init --tool gemini` | Creates .gemini/ and .geminiignore only |
| **Qwen-only workflow** | `/cli:cli-init --tool qwen` | Creates .qwen/ and .qwenignore only |
| **Preview before commit** | `/cli:cli-init --preview` | Shows what would be generated |
| **Update configurations** | `/cli:cli-init` | Regenerates all files with backups |

View File

@@ -0,0 +1,520 @@
---
name: codex-execute
description: Automated task decomposition and execution with Codex using resume mechanism
argument-hint: "[--verify-git] task description or task-id"
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. Use AskUserQuestion for recovery decision:
```typescript
AskUserQuestion({
questions: [{
question: "Codex execution failed for the subtask. How should the workflow proceed?",
header: "Recovery",
options: [
{ label: "Retry Subtask", description: "Attempt to execute the same subtask again." },
{ label: "Skip Subtask", description: "Continue to the next subtask in the plan." },
{ label: "Abort Workflow", description: "Stop the entire execution." }
],
multiSelect: false
}]
})
```
**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

@@ -0,0 +1,321 @@
---
name: discuss-plan
description: Orchestrates an iterative, multi-model discussion for planning and analysis without implementation.
argument-hint: "[--topic '...'] [--task-id '...'] [--rounds N]"
allowed-tools: SlashCommand(*), Bash(*), TodoWrite(*), Read(*), Glob(*)
---
# CLI Discuss-Plan Command (/cli:discuss-plan)
## Purpose
Orchestrates a multi-model collaborative discussion for in-depth planning and problem analysis. This command facilitates an iterative dialogue between Gemini, Codex, and Claude (the orchestrating AI) to explore a topic from multiple perspectives, refine ideas, and build a robust plan.
**This command is for discussion and planning ONLY. It does NOT modify any code.**
## Core Workflow: The Discussion Loop
The command operates in iterative rounds, allowing the plan to evolve with each cycle. The user can choose to continue for more rounds or conclude when consensus is reached.
```
Topic Input → [Round 1: Gemini → Codex → Claude] → [User Review] →
[Round 2: Gemini → Codex → Claude] → ... → Final Plan
```
### Model Roles & Priority
**Priority Order**: Gemini > Codex > Claude
1. **Gemini (The Analyst)** - Priority 1
- Kicks off each round with deep analysis
- Provides foundational ideas and draft plans
- Analyzes current context or previous synthesis
2. **Codex (The Architect/Critic)** - Priority 2
- Reviews Gemini's output critically
- Uses deep reasoning for technical trade-offs
- Proposes alternative strategies
- **Participates purely in conversational/reasoning capacity**
- Uses resume mechanism to maintain discussion context
3. **Claude (The Synthesizer/Moderator)** - Priority 3
- Synthesizes discussion from Gemini and Codex
- Highlights agreements and contentions
- Structures refined plan
- Poses key questions for next round
## Parameters
- `<input>` (Required): Topic description or task ID (e.g., "Design a new caching layer" or `PLAN-002`)
- `--rounds <N>` (Optional): Maximum number of discussion rounds (default: prompts after each round)
- `--task-id <id>` (Optional): Associates discussion with workflow task ID
- `--topic <description>` (Optional): High-level topic for discussion
## Execution Flow
### Phase 1: Initial Setup
1. **Input Processing**: Parse topic or task ID
2. **Context Gathering**: Identify relevant files based on topic
### Phase 2: Discussion Round
Each round consists of three sequential steps, tracked via `TodoWrite`.
**Step 1: Gemini's Analysis (Priority 1)**
Gemini analyzes the topic and proposes preliminary plan.
```bash
# Round 1: CONTEXT_INPUT is the initial topic
# Subsequent rounds: CONTEXT_INPUT is the synthesis from previous round
~/.claude/scripts/gemini-wrapper -p "
PURPOSE: Analyze and propose a plan for '[topic]'
TASK: Provide initial analysis, identify key modules, and draft implementation plan
MODE: analysis
CONTEXT: @{CLAUDE.md} [auto-detected files]
INPUT: [CONTEXT_INPUT]
EXPECTED: Structured analysis and draft plan for discussion
RULES: Focus on technical depth and practical considerations
"
```
**Step 2: Codex's Critique (Priority 2)**
Codex reviews Gemini's output using conversational reasoning. Uses `resume --last` to maintain context across rounds.
```bash
# First round (new session)
codex --full-auto exec "
PURPOSE: Critically review technical plan
TASK: Review the provided plan, identify weaknesses, suggest alternatives, reason about trade-offs
MODE: analysis
CONTEXT: @{CLAUDE.md} [relevant files]
INPUT_PLAN: [Output from Gemini's analysis]
EXPECTED: Critical review with alternative ideas and risk analysis
RULES: Focus on architectural soundness and implementation feasibility
" --skip-git-repo-check
# Subsequent rounds (resume discussion)
codex --full-auto exec "
PURPOSE: Re-evaluate plan based on latest synthesis
TASK: Review updated plan and discussion points, provide further critique or refined ideas
MODE: analysis
CONTEXT: Previous discussion context (maintained via resume)
INPUT_PLAN: [Output from Gemini's analysis for current round]
EXPECTED: Updated critique building on previous discussion
RULES: Build on previous insights, avoid repeating points
" resume --last --skip-git-repo-check
```
**Step 3: Claude's Synthesis (Priority 3)**
Claude (orchestrating AI) synthesizes both outputs:
- Summarizes Gemini's proposal and Codex's critique
- Highlights agreements and disagreements
- Structures consolidated plan
- Presents open questions for next round
- This synthesis becomes input for next round
### Phase 3: User Review and Iteration
1. **Present Synthesis**: Show synthesized plan and key discussion points
2. **Continue or Conclude**: Use AskUserQuestion to prompt user:
```typescript
AskUserQuestion({
questions: [{
question: "Round of discussion complete. What is the next step?",
header: "Next Round",
options: [
{ label: "Start another round", description: "Continue the discussion to refine the plan further." },
{ label: "Conclude and finalize", description: "End the discussion and save the final plan." }
],
multiSelect: false
}]
})
```
3. **Loop or Finalize**:
- Continue → New round with Gemini analyzing latest synthesis
- Conclude → Save final synthesized document
## TodoWrite Tracking
Progress tracked for each round and model.
```javascript
// Example for 2-round discussion
TodoWrite({
todos: [
// Round 1
{ content: "[Round 1] Gemini: Analyzing topic", status: "completed", activeForm: "Analyzing with Gemini" },
{ content: "[Round 1] Codex: Critiquing plan", status: "completed", activeForm: "Critiquing with Codex" },
{ content: "[Round 1] Claude: Synthesizing discussion", status: "completed", activeForm: "Synthesizing discussion" },
{ content: "[User Action] Review Round 1 and decide next step", status: "in_progress", activeForm: "Awaiting user decision" },
// Round 2
{ content: "[Round 2] Gemini: Analyzing refined plan", status: "pending", activeForm: "Analyzing refined plan" },
{ content: "[Round 2] Codex: Re-evaluating plan [resume]", status: "pending", activeForm: "Re-evaluating with Codex" },
{ content: "[Round 2] Claude: Finalizing plan", status: "pending", activeForm: "Finalizing plan" },
{ content: "Discussion complete - Final plan generated", status: "pending", activeForm: "Generating final document" }
]
})
```
## Output Routing
- **Primary Log**: Entire multi-round discussion logged to single file:
- `.workflow/WFS-[id]/.chat/discuss-plan-[topic]-[timestamp].md`
- **Final Plan**: Clean final version saved upon conclusion:
- `.workflow/WFS-[id]/.summaries/plan-[topic].md`
- **Scratchpad**: If no session active:
- `.workflow/.scratchpad/discuss-plan-[topic]-[timestamp].md`
## Discussion Structure
Each round's output is structured as:
```markdown
## Round N: [Topic]
### Gemini's Analysis (Priority 1)
[Gemini's full analysis and proposal]
### Codex's Critique (Priority 2)
[Codex's critical review and alternatives]
### Claude's Synthesis (Priority 3)
**Points of Agreement:**
- [Agreement 1]
- [Agreement 2]
**Points of Contention:**
- [Issue 1]: Gemini suggests X, Codex suggests Y
- [Issue 2]: Trade-off between A and B
**Consolidated Plan:**
[Structured plan incorporating both perspectives]
**Open Questions for Next Round:**
1. [Question 1]
2. [Question 2]
```
## Examples
### Example 1: Multi-Round Architecture Discussion
**Command**: `/cli:discuss-plan --topic "Design a real-time notification system"`
**Round 1**:
1. **Gemini**: Proposes WebSocket-based architecture with RabbitMQ message queue
2. **Codex**: Critiques as overly complex for MVP. Suggests Server-Sent Events (SSE) for simplicity (one-way notifications). Questions RabbitMQ necessity, proposes simpler Redis Pub/Sub
3. **Claude**: Synthesizes views:
- **Plan A (Gemini)**: WebSockets + RabbitMQ (highly scalable, complex)
- **Plan B (Codex)**: SSE + Redis (simpler, less overhead)
- **Open Question**: Is bi-directional communication critical, or is simplicity priority?
4. **User Action**: Opts for another round to explore trade-offs
**Round 2**:
1. **Gemini**: Analyzes synthesized document. Notes that if features like "user is typing" indicators are roadmapped, WebSockets better long-term. Drafts plan starting with SSE/Redis but designing for easy migration
2. **Codex**: Reviews migration plan. Reasons that migration itself could be complex. If feature set likely to expand, starting with WebSockets using managed service might be best cost/benefit
3. **Claude**: Synthesizes new discussion:
- **Consensus**: Simple SSE/Redis too short-sighted
- **Refined Options**:
1. Phased approach (SSE → WebSocket) with clear migration plan
2. Direct WebSocket with managed service (Pusher, Ably) to reduce ops overhead
- **Recommendation**: Option 2 most robust and future-proof
4. **User Action**: Agrees with recommendation, concludes discussion
**Final Output**: Planning document saved with:
- Chosen architecture (Managed WebSocket service)
- Multi-round reasoning
- High-level implementation steps
### Example 2: Feature Design Discussion
**Command**: `/cli:discuss-plan --topic "Design user permission system" --rounds 2`
**Round 1**:
1. **Gemini**: Proposes RBAC (Role-Based Access Control) with predefined roles
2. **Codex**: Suggests ABAC (Attribute-Based Access Control) for more flexibility
3. **Claude**: Synthesizes trade-offs between simplicity (RBAC) vs flexibility (ABAC)
**Round 2**:
1. **Gemini**: Analyzes hybrid approach - RBAC for core permissions, attributes for fine-grained control
2. **Codex**: Reviews hybrid model, identifies implementation challenges
3. **Claude**: Final plan with phased rollout strategy
**Automatic Conclusion**: Command concludes after 2 rounds as specified
### Example 3: Problem-Solving Discussion
**Command**: `/cli:discuss-plan --topic "Debug memory leak in data pipeline" --task-id ISSUE-042`
**Round 1**:
1. **Gemini**: Identifies potential leak sources (unclosed handles, growing cache, event listeners)
2. **Codex**: Adds profiling tool recommendations, suggests memory monitoring
3. **Claude**: Structures debugging plan with phased approach
**User Decision**: Single round sufficient, concludes with debugging strategy
## Consensus Mechanisms
**When to Continue:**
- Significant disagreement between models
- Open questions requiring deeper analysis
- Trade-offs need more exploration
- User wants additional perspectives
**When to Conclude:**
- Models converge on solution
- All key questions addressed
- User satisfied with plan depth
- Maximum rounds reached (if specified)
## Comparison with Other Commands
| Command | Models | Rounds | Discussion | Implementation | Use Case |
|---------|--------|--------|------------|----------------|----------|
| `/cli:mode:plan` | Gemini | 1 | ❌ NO | ❌ NO | Single-model planning |
| `/cli:analyze` | Gemini/Qwen | 1 | ❌ NO | ❌ NO | Code analysis |
| `/cli:execute` | Any | 1 | ❌ NO | ✅ YES | Direct implementation |
| `/cli:codex-execute` | Codex | 1 | ❌ NO | ✅ YES | Multi-stage implementation |
| `/cli:discuss-plan` | **Gemini+Codex+Claude** | **Multiple** | ✅ **YES** | ❌ **NO** | **Multi-perspective planning** |
## Best Practices
1. **Use for Complex Decisions**: Ideal for architectural decisions, design trade-offs, problem-solving
2. **Start with Broad Topic**: Let first round establish scope, subsequent rounds refine
3. **Review Each Synthesis**: Claude's synthesis is key decision point - review carefully
4. **Know When to Stop**: Don't over-iterate - 2-3 rounds usually sufficient
5. **Task Association**: Use `--task-id` for traceability in workflow
6. **Save Intermediate Results**: Each round's synthesis saved automatically
7. **Let Models Disagree**: Divergent views often reveal important trade-offs
8. **Focus Questions**: Use Claude's open questions to guide next round
## Breaking Discussion Loops
**Detecting Loops:**
- Models repeating same arguments
- No new insights emerging
- Trade-offs well understood
**Breaking Strategies:**
1. **User Decision**: Make executive decision when enough info gathered
2. **Timeboxing**: Set max rounds upfront with `--rounds`
3. **Criteria-Based**: Define decision criteria before starting
4. **Hybrid Approach**: Accept multiple valid solutions in final plan
## Notes
- **Pure Discussion**: This command NEVER modifies code - only produces planning documents
- **Codex Role**: Codex participates as reasoning/critique tool, not executor
- **Resume Context**: Codex maintains discussion context via `resume --last`
- **Priority System**: Ensures Gemini leads analysis, Codex provides critique, Claude synthesizes
- **Output Quality**: Multi-perspective discussion produces more robust plans than single-model analysis
- Command patterns and session management: see intelligent-tools-strategy.md (loaded in memory)
- Output routing details: see workflow-architecture.md
- For implementation after discussion, use `/cli:execute` or `/cli:codex-execute` separately

View File

@@ -0,0 +1,222 @@
---
name: execute
description: Auto-execution of implementation tasks with YOLO permissions and intelligent context inference
argument-hint: "[--agent] [--tool codex|gemini|qwen] [--enhance] description or task-id"
allowed-tools: SlashCommand(*), Bash(*), Task(*)
---
# CLI Execute Command (/cli:execute)
## Purpose
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 Behavior
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
## Core Concepts
### YOLO Permissions
Auto-approves: file pattern inference, execution, **file modifications**, summary generation
**⚠️ 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
**3. Agent Mode** (`--agent` flag):
- Input: Description or task-id
- Process: 5-Phase Workflow → Context Discovery → Optimal Tool Selection → 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
# First task - establish session
codex -C [dir] --full-auto exec "[task]" --skip-git-repo-check -s danger-full-access
# Related task - continue session
codex --full-auto exec "[related-task]" resume --last --skip-git-repo-check -s danger-full-access
```
Use `resume --last` when current task extends/relates to previous execution. See intelligent-tools-strategy.md for auto-resume rules.
## Parameters
- `--agent` - Use cli-execution-agent for automated context discovery (5-phase intelligent mode)
- `--tool <codex|gemini|qwen>` - Select CLI tool (default: gemini, ignored in agent mode unless specified)
- `--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 `.workflow/.active-*` marker
- Active session: Save to `.workflow/WFS-[id]/.chat/execute-[timestamp].md`
- No session: Create new session or save to scratchpad
**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`
## Execution Modes
### Standard Mode (Default)
```bash
# Gemini/Qwen: MODE=write with --approval-mode yolo
cd . && ~/.claude/scripts/gemini-wrapper --approval-mode yolo -p "
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
```
### Agent Mode (`--agent` flag)
Delegate implementation to `cli-execution-agent` for intelligent execution with automated context discovery.
**Agent invocation**:
```javascript
Task(
subagent_type="cli-execution-agent",
description="Implement with automated context discovery and optimal tool selection",
prompt=`
Task: ${description_or_task_id}
Mode: execute
Tool Preference: ${tool_flag || 'auto-select'}
${enhance_flag ? 'Enhance: true' : ''}
Agent will autonomously:
- Discover implementation files and dependencies
- Assess complexity and select optimal tool
- Execute with YOLO permissions (auto-approve)
- Generate task summary if task-id provided
`
)
```
The agent handles all phases internally, including complexity-based tool selection.
## Examples
**Basic Implementation (Standard Mode)** (⚠️ modifies code):
```bash
/cli:execute "implement JWT authentication with middleware"
# Executes: Creates auth middleware, updates routes, modifies config
# Result: NEW/MODIFIED code files with JWT implementation
```
**Intelligent Implementation (Agent Mode)** (⚠️ modifies code):
```bash
/cli:execute --agent "implement OAuth2 authentication with token refresh"
# Phase 1: Classifies intent=execute, complexity=complex, keywords=['oauth2', 'auth', 'token', 'refresh']
# Phase 2: MCP discovers auth patterns, existing middleware, JWT dependencies
# Phase 3: Enhances prompt with discovered patterns and best practices
# Phase 4: Selects Codex (complex task), executes with comprehensive context
# Phase 5: Saves execution log + generates implementation summary
# Result: Complete OAuth2 implementation + detailed execution log
```
**Enhanced Implementation** (⚠️ modifies code):
```bash
/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
```
**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
```
**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
```
**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
```
## Comparison with Analysis Commands
| 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** |
## 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

@@ -0,0 +1,164 @@
---
name: bug-index
description: Bug analysis and fix suggestions using CLI tools
argument-hint: "[--agent] [--tool codex|gemini|qwen] [--enhance] [--cd path] bug description"
allowed-tools: SlashCommand(*), Bash(*), Task(*)
---
# CLI Mode: Bug Index (/cli:mode:bug-index)
## Purpose
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
- `--agent` - Use cli-execution-agent for automated context discovery (5-phase intelligent mode)
- `--tool <codex|gemini|qwen>` - Tool selection (default: gemini, ignored in agent mode)
- `--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
### Standard Mode (Default)
1. **Parse tool selection**: Extract `--tool` flag (default: gemini)
2. **If `--enhance` flag present**: Execute `/enhance-prompt "[bug-description]"` first
3. Parse bug description (original or enhanced)
4. Detect target directory (from `--cd` or auto-infer)
5. Build command for selected tool with bug-fix template
6. Execute analysis (read-only, provides fix recommendations)
7. Save to `.workflow/WFS-[id]/.chat/bug-index-[timestamp].md`
### Agent Mode (`--agent` flag)
Delegate bug analysis to `cli-execution-agent` for intelligent debugging with automated context discovery.
**Agent invocation**:
```javascript
Task(
subagent_type="cli-execution-agent",
description="Analyze bug with automated context discovery",
prompt=`
Task: ${bug_description}
Mode: debug (bug analysis)
Tool Preference: ${tool_flag || 'auto-select'}
${cd_flag ? `Directory Scope: ${cd_path}` : ''}
Template: bug-fix
Agent will autonomously:
- Discover bug-related files and error traces
- Build debug prompt with bug-fix template
- Execute analysis and provide fix recommendations
- Save analysis log
`
)
```
The agent handles all phases internally.
## Core Rules
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
```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 fix suggestions
RULES: $(cat ~/.claude/prompt-templates/bug-fix.md) | Bug: [description]
"
```
## Examples
**Basic Bug Analysis (Standard Mode)**:
```bash
/cli:mode:bug-index "null pointer error in login flow"
# Executes: Gemini with bug-fix template
# Returns: Root cause analysis, fix recommendations
```
**Intelligent Bug Analysis (Agent Mode)**:
```bash
/cli:mode:bug-index --agent "intermittent token validation failure"
# Phase 1: Classifies as debug task, extracts keywords ['token', 'validation', 'failure']
# Phase 2: MCP discovers token validation code, middleware, test files with errors
# Phase 3: Builds debug prompt with bug-fix template + discovered error patterns
# Phase 4: Executes Gemini with comprehensive bug context
# Phase 5: Saves analysis log with detailed fix recommendations
# Returns: Root cause analysis + code path traces + minimal fix suggestions
```
**Standard Template Example**:
```bash
cd . && ~/.claude/scripts/gemini-wrapper --all-files -p "
PURPOSE: Debug authentication null pointer error
TASK: Identify root cause and provide fix recommendations
MODE: analysis
CONTEXT: @{CLAUDE.md,**/*CLAUDE.md}
EXPECTED: Root cause, code path, minimal fix suggestion, impact assessment
RULES: $(cat ~/.claude/prompt-templates/bug-fix.md) | Bug: null pointer in login flow
"
```
**Directory-Specific**:
```bash
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 with minimal changes
RULES: $(cat ~/.claude/prompt-templates/bug-fix.md) | Bug: token validation fails intermittently
"
```
## Bug Investigation Workflow
```bash
# 1. Find bug-related files
rg "error_keyword" --files-with-matches
mcp__code-index__search_code_advanced(pattern="error|exception", file_pattern="*.ts")
# 2. Execute bug analysis with focused context (analysis only, no code changes)
/cli:mode:bug-index --cd "src/module" "specific error description"
```
## Output Routing
**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`
**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`
## 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/bug-fix.md`
- Always uses `--all-files` for comprehensive codebase context

View File

@@ -0,0 +1,170 @@
---
name: code-analysis
description: Deep code analysis and debugging using CLI tools with specialized template
argument-hint: "[--agent] [--tool codex|gemini|qwen] [--enhance] [--cd path] analysis target"
allowed-tools: SlashCommand(*), Bash(*), Task(*)
---
# CLI Mode: Code Analysis (/cli:mode:code-analysis)
## Purpose
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
- `--agent` - Use cli-execution-agent for automated context discovery (5-phase intelligent mode)
- `--tool <codex|gemini|qwen>` - Tool selection (default: gemini, ignored in agent mode)
- `--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
### Standard Mode (Default)
1. **Parse tool selection**: Extract `--tool` flag (default: gemini)
2. **If `--enhance` flag present**: Execute `/enhance-prompt "[analysis-target]"` first
3. Parse analysis target (original or enhanced)
4. Detect target directory (from `--cd` or auto-infer)
5. Build command for selected tool with code-analysis template
6. Execute deep analysis (read-only, no code modification)
7. Save to `.workflow/WFS-[id]/.chat/code-analysis-[timestamp].md`
### Agent Mode (`--agent` flag)
Delegate code analysis to `cli-execution-agent` for intelligent execution path tracing with automated context discovery.
**Agent invocation**:
```javascript
Task(
subagent_type="cli-execution-agent",
description="Analyze code execution paths with automated context discovery",
prompt=`
Task: ${analysis_target}
Mode: code-analysis (execution tracing)
Tool Preference: ${tool_flag || 'auto-select'}
${cd_flag ? `Directory Scope: ${cd_path}` : ''}
Template: code-analysis
Agent will autonomously:
- Discover execution paths and call flows
- Build analysis prompt with code-analysis template
- Execute deep tracing analysis
- Generate call diagrams and save log
`
)
```
The agent handles all phases internally.
## Core Rules
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 (via Template)
- **Systematic Code Analysis**: Break down complex code into manageable parts
- **Execution Path Tracing**: Track variable states and call stacks
- **Control & Data Flow**: Understand code logic and data transformations
- **Call Flow Visualization**: Diagram function calling sequences
- **Logical Reasoning**: Explain "why" behind code behavior
- **Debugging Insights**: Identify potential bugs or inefficiencies
## Command Template
```bash
cd [directory] && ~/.claude/scripts/gemini-wrapper --all-files -p "
PURPOSE: [analysis goal]
TASK: Systematic code analysis and execution path tracing
MODE: analysis
CONTEXT: @{CLAUDE.md,**/*CLAUDE.md} [entire codebase in directory]
EXPECTED: Execution trace, call flow diagram, debugging insights
RULES: $(cat ~/.claude/prompt-templates/code-analysis.md) | Focus on [aspect]
"
```
## Examples
**Basic Code Analysis (Standard Mode)**:
```bash
/cli:mode:code-analysis "trace authentication execution flow"
# Executes: Gemini with code-analysis template
# Returns: Execution trace, call diagram, debugging insights
```
**Intelligent Code Analysis (Agent Mode)**:
```bash
/cli:mode:code-analysis --agent "trace JWT token validation from request to database"
# Phase 1: Classifies as deep analysis, keywords ['jwt', 'token', 'validation', 'database']
# Phase 2: MCP discovers request handler → middleware → service → repository chain
# Phase 3: Builds analysis prompt with code-analysis template + complete call path
# Phase 4: Executes Gemini with traced execution paths
# Phase 5: Saves detailed analysis with call flow diagrams and variable states
# Returns: Complete execution trace + call diagram + data flow analysis
```
**Standard Template Example**:
```bash
cd . && ~/.claude/scripts/gemini-wrapper --all-files -p "
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 execution trace with call diagram, variable states
RULES: $(cat ~/.claude/prompt-templates/code-analysis.md) | Focus on control flow
"
```
**Directory-Specific Analysis**:
```bash
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: Validation flow diagram, token lifecycle analysis
RULES: $(cat ~/.claude/prompt-templates/code-analysis.md) | Focus on security
"
```
## Code Tracing Workflow
```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"
```
## Output Routing
**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`
**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`
## 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/code-analysis.md`
- Always uses `--all-files` for comprehensive code context

View File

@@ -0,0 +1,168 @@
---
name: plan
description: Project planning and architecture analysis using CLI tools
argument-hint: "[--agent] [--tool codex|gemini|qwen] [--enhance] [--cd path] topic"
allowed-tools: SlashCommand(*), Bash(*), Task(*)
---
# CLI Mode: Plan (/cli:mode:plan)
## Purpose
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
- `--agent` - Use cli-execution-agent for automated context discovery (5-phase intelligent mode)
- `--tool <codex|gemini|qwen>` - Tool selection (default: gemini, ignored in agent mode)
- `--enhance` - Enhance topic with `/enhance-prompt` first
- `--cd "path"` - Target directory for focused planning
- `<topic>` (Required) - Planning topic or architectural question
## Execution Flow
### Standard Mode (Default)
1. **Parse tool selection**: Extract `--tool` flag (default: gemini)
2. **If `--enhance` flag present**: Execute `/enhance-prompt "[topic]"` first
3. Parse topic (original or enhanced)
4. Detect target directory (from `--cd` or auto-infer)
5. Build command for selected tool with planning template
6. Execute analysis (read-only, no code modification)
7. Save to `.workflow/WFS-[id]/.chat/plan-[timestamp].md`
### Agent Mode (`--agent` flag)
Delegate planning to `cli-execution-agent` for intelligent strategic planning with automated architecture discovery.
**Agent invocation**:
```javascript
Task(
subagent_type="cli-execution-agent",
description="Create strategic plan with automated architecture discovery",
prompt=`
Task: ${planning_topic}
Mode: plan (strategic planning)
Tool Preference: ${tool_flag || 'auto-select'}
${cd_flag ? `Directory Scope: ${cd_path}` : ''}
Template: plan
Agent will autonomously:
- Discover project structure and existing architecture
- Build planning prompt with plan template
- Execute strategic planning analysis
- Generate implementation roadmap and save
`
)
```
The agent handles all phases internally.
## Core Rules
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
```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 recommendations, key decisions
RULES: $(cat ~/.claude/prompt-templates/plan.md) | Focus on [topic area]
"
```
## Examples
**Basic Planning Analysis (Standard Mode)**:
```bash
/cli:mode:plan "design user dashboard architecture"
# Executes: Gemini with planning template
# Returns: Architecture recommendations, component design, roadmap
```
**Intelligent Planning (Agent Mode)**:
```bash
/cli:mode:plan --agent "design microservices architecture for payment system"
# Phase 1: Classifies as architectural planning, keywords ['microservices', 'payment', 'architecture']
# Phase 2: MCP discovers existing services, payment flows, integration patterns
# Phase 3: Builds planning prompt with plan template + current architecture context
# Phase 4: Executes Gemini with comprehensive project understanding
# Phase 5: Saves planning document with implementation roadmap and migration strategy
# Returns: Strategic architecture plan + implementation roadmap + risk assessment
```
**Standard Template Example**:
```bash
cd . && ~/.claude/scripts/gemini-wrapper --all-files -p "
PURPOSE: Design user dashboard architecture
TASK: Plan dashboard component structure and data flow
MODE: analysis
CONTEXT: @{CLAUDE.md,**/*CLAUDE.md}
EXPECTED: Architecture recommendations, component design, data flow diagram
RULES: $(cat ~/.claude/prompt-templates/plan.md) | Focus on scalability
"
```
**Directory-Specific Planning**:
```bash
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: Refactoring roadmap, breaking change analysis, migration plan
RULES: $(cat ~/.claude/prompt-templates/plan.md) | Maintain backward compatibility
"
```
## Planning Workflow
```bash
# 1. Discover project structure
~/.claude/scripts/get_modules_by_depth.sh
mcp__code-index__find_files(pattern="*.ts")
# 2. Gather existing architecture info
rg "architecture|design" --files-with-matches
# 3. Execute planning analysis (analysis only, no code changes)
/cli:mode:plan "topic for strategic planning"
```
## Output Routing
**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`
**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,155 +0,0 @@
---
name: analyze
description: Quick analysis of codebase patterns, architecture, and code quality using Codex CLI
usage: /codex:analyze <analysis-type>
argument-hint: "analysis target or type"
examples:
- /codex:analyze "React hooks patterns"
- /codex:analyze "authentication security"
- /codex:analyze "performance bottlenecks"
- /codex:analyze "API design patterns"
model: haiku
---
# Codex Analysis Command (/codex:analyze)
## Overview
Quick analysis tool for codebase insights using intelligent pattern detection and template-driven analysis with Codex CLI.
**Core Guidelines**: @~/.claude/workflows/tools-implementation-guide.md
⚠️ **Critical Difference**: Codex has **NO `--all-files` flag** - you MUST use `@` patterns to reference files.
## Analysis Types
| Type | Purpose | Example |
|------|---------|---------|
| **pattern** | Code pattern detection | "React hooks usage patterns" |
| **architecture** | System structure analysis | "component hierarchy structure" |
| **security** | Security vulnerabilities | "authentication vulnerabilities" |
| **performance** | Performance bottlenecks | "rendering performance issues" |
| **quality** | Code quality assessment | "testing coverage analysis" |
| **dependencies** | Third-party analysis | "outdated package dependencies" |
## Quick Usage
### Basic Analysis
```bash
/codex:analyze "authentication patterns"
```
**Executes**: `codex --full-auto exec "@{**/*auth*} @{CLAUDE.md} $(cat ~/.claude/workflows/cli-templates/prompts/analysis/pattern.txt)" -s danger-full-access`
### Targeted Analysis
```bash
/codex:analyze "React component architecture"
```
**Executes**: `codex --full-auto exec "@{src/components/**/*} @{CLAUDE.md} $(cat ~/.claude/workflows/cli-templates/prompts/analysis/architecture.txt)" -s danger-full-access`
### Security Focus
```bash
/codex:analyze "API security vulnerabilities"
```
**Executes**: `codex --full-auto exec "@{**/api/**/*} @{CLAUDE.md} $(cat ~/.claude/workflows/cli-templates/prompts/analysis/security.txt)" -s danger-full-access`
## Codex-Specific Patterns
**Essential File Patterns** (Required for Codex):
```bash
@{**/*} # All files recursively
@{src/**/*} # All source files
@{*.ts,*.js} # Specific file types
@{CLAUDE.md,**/*CLAUDE.md} # Documentation hierarchy
@{package.json,*.config.*} # Configuration files
```
## Templates Used
Templates are automatically selected based on analysis type:
- **Pattern Analysis**: `~/.claude/workflows/cli-templates/prompts/analysis/pattern.txt`
- **Architecture Analysis**: `~/.claude/workflows/cli-templates/prompts/analysis/architecture.txt`
- **Security Analysis**: `~/.claude/workflows/cli-templates/prompts/analysis/security.txt`
- **Performance Analysis**: `~/.claude/workflows/cli-templates/prompts/analysis/performance.txt`
## Workflow Integration
⚠️ **Session Check**: Automatically detects active workflow session via `.workflow/.active-*` marker file.
**Analysis results saved to:**
- Active session: `.workflow/WFS-[topic]/.chat/analysis-[timestamp].md`
- No session: Temporary analysis output
## Common Patterns
### Technology Stack Analysis
```bash
/codex:analyze "project technology stack"
# Executes: codex --full-auto exec "@{package.json,*.config.*,CLAUDE.md} [analysis prompt]" -s danger-full-access
```
### Code Quality Review
```bash
/codex:analyze "code quality and standards"
# Executes: codex --full-auto exec "@{src/**/*,test/**/*,CLAUDE.md} [analysis prompt]" -s danger-full-access
```
### Migration Planning
```bash
/codex:analyze "legacy code modernization"
# Executes: codex --full-auto exec "@{**/*.{js,jsx,ts,tsx},CLAUDE.md} [analysis prompt]" -s danger-full-access
```
### Module-Specific Analysis
```bash
/codex:analyze "authentication module patterns"
# Executes: codex --full-auto exec "@{src/auth/**/*,**/*auth*,CLAUDE.md} [analysis prompt]" -s danger-full-access
```
## Output Format
Analysis results include:
- **File References**: Specific file:line locations
- **Code Examples**: Relevant code snippets
- **Patterns Found**: Common patterns and anti-patterns
- **Recommendations**: Actionable improvements
- **Integration Points**: How components connect
## Execution Templates
### Basic Analysis Template
```bash
codex --full-auto exec "@{inferred_patterns} @{CLAUDE.md,**/*CLAUDE.md}
Analysis Type: [analysis_type]
Provide:
- Pattern identification and analysis
- Code quality assessment
- Architecture insights
- Specific recommendations with file:line references" -s danger-full-access
```
### Template-Enhanced Analysis
```bash
codex --full-auto exec "@{inferred_patterns} @{CLAUDE.md,**/*CLAUDE.md} $(cat ~/.claude/workflows/cli-templates/prompts/analysis/[template].txt)
Focus: [analysis_type]
Context: [user_description]" -s danger-full-access
```
## Error Prevention
- **Always include @ patterns**: Commands without file references will fail
- **Test patterns first**: Validate @ patterns match existing files
- **Use comprehensive patterns**: `@{**/*}` when unsure of file structure
- **Include documentation**: Always add `@{CLAUDE.md,**/*CLAUDE.md}` for context
## Codex vs Gemini
| Feature | Codex | Gemini |
|---------|-------|--------|
| File Loading | `@` patterns **required** | `--all-files` available |
| Command Structure | `codex exec "@{patterns}"` | `gemini --all-files -p` |
| Pattern Flexibility | Must be explicit | Auto-includes with flag |
For detailed syntax, patterns, and advanced usage see:
**@~/.claude/workflows/tools-implementation-guide.md**

View File

@@ -1,189 +0,0 @@
---
name: chat
description: Simple Codex CLI interaction command for direct codebase analysis and development
usage: /codex:chat "inquiry"
argument-hint: "your question or development request"
examples:
- /codex:chat "analyze the authentication flow"
- /codex:chat "how can I optimize this React component performance?"
- /codex:chat "implement user profile editing functionality"
allowed-tools: Bash(codex:*)
model: sonnet
---
### 🚀 **Command Overview: `/codex:chat`**
- **Type**: Basic Codex CLI Wrapper
- **Purpose**: Direct interaction with the `codex` CLI for simple codebase analysis and development
- **Core Tool**: `Bash(codex:*)` - Executes the external Codex CLI tool
⚠️ **Critical Difference**: Codex has **NO `--all-files` flag** - you MUST use `@` patterns to reference files.
### 📥 **Parameters & Usage**
- **`<inquiry>` (Required)**: Your question or development request
- **`@{patterns}` (Required)**: File patterns must be explicitly specified
- **`--save-session` (Optional)**: Saves the interaction to current workflow session directory
- **`--full-auto` (Optional)**: Enable autonomous development mode
### 🔄 **Execution Workflow**
`Parse Input` **->** `Infer File Patterns` **->** `Construct Prompt` **->** `Execute Codex CLI` **->** `(Optional) Save Session`
### 📚 **Context Assembly**
Context is gathered from:
1. **Project Guidelines**: Always includes `@{CLAUDE.md,**/*CLAUDE.md}`
2. **Inferred Patterns**: Auto-detects relevant files based on inquiry keywords
3. **Comprehensive Fallback**: Uses `@{**/*}` when pattern inference unclear
### 📝 **Prompt Format**
```
=== CONTEXT ===
@{CLAUDE.md,**/*CLAUDE.md} [Project guidelines]
@{inferred_patterns} [Auto-detected or comprehensive patterns]
=== USER INPUT ===
[The user inquiry text]
```
### ⚙️ **Execution Implementation**
```pseudo
FUNCTION execute_codex_chat(user_inquiry, flags):
// Always include project guidelines
patterns = "@{CLAUDE.md,**/*CLAUDE.md}"
// Infer relevant file patterns from inquiry keywords
inferred_patterns = infer_file_patterns(user_inquiry)
IF inferred_patterns:
patterns += "," + inferred_patterns
ELSE:
patterns += ",@{**/*}" // Fallback to all files
// Construct prompt
prompt = "=== CONTEXT ===\n" + patterns + "\n"
prompt += "\n=== USER INPUT ===\n" + user_inquiry
// Execute codex CLI
IF flags contain "--full-auto":
result = execute_tool("Bash(codex:*)", "--full-auto", prompt)
ELSE:
result = execute_tool("Bash(codex:*)", "exec", prompt)
// Save session if requested
IF flags contain "--save-session":
save_chat_session(user_inquiry, patterns, result)
RETURN result
END FUNCTION
```
### 🎯 **Pattern Inference Logic**
**Auto-detects file patterns based on keywords:**
| Keywords | Inferred Pattern | Purpose |
|----------|-----------------|---------|
| "auth", "login", "user" | `@{**/*auth*,**/*user*}` | Authentication code |
| "React", "component" | `@{src/**/*.{jsx,tsx}}` | React components |
| "API", "endpoint", "route" | `@{**/api/**/*,**/routes/**/*}` | API code |
| "test", "spec" | `@{test/**/*,**/*.test.*,**/*.spec.*}` | Test files |
| "config", "setup" | `@{*.config.*,package.json}` | Configuration |
| "database", "db", "model" | `@{**/models/**/*,**/db/**/*}` | Database code |
| "style", "css" | `@{**/*.{css,scss,sass}}` | Styling files |
**Fallback**: If no keywords match, uses `@{**/*}` for comprehensive analysis.
### 💾 **Session Persistence**
When `--save-session` flag is used:
- Check for existing active session (`.workflow/.active-*` markers)
- Save to existing session's `.chat/` directory or create new session
- File format: `chat-YYYYMMDD-HHMMSS.md`
- Include query, context patterns, and response in saved file
**Session Template:**
```markdown
# Chat Session: [Timestamp]
## Query
[Original user inquiry]
## Context Patterns
[File patterns used in analysis]
## Codex Response
[Complete response from Codex CLI]
## Pattern Inference
[How file patterns were determined]
```
### 🔧 **Usage Examples**
#### Basic Development Chat
```bash
/codex:chat "implement password reset functionality"
# Executes: codex --full-auto exec "@{CLAUDE.md,**/*CLAUDE.md,**/*auth*,**/*user*} implement password reset functionality" -s danger-full-access
```
#### Architecture Discussion
```bash
/codex:chat "how should I structure the user management module?"
# Executes: codex --full-auto exec "@{CLAUDE.md,**/*CLAUDE.md,**/*user*,src/**/*} how should I structure the user management module?" -s danger-full-access
```
#### Performance Optimization
```bash
/codex:chat "optimize React component rendering performance"
# Executes: codex --full-auto exec "@{CLAUDE.md,**/*CLAUDE.md,src/**/*.{jsx,tsx}} optimize React component rendering performance" -s danger-full-access
```
#### Full Auto Mode
```bash
/codex:chat "create a complete user dashboard with charts" --full-auto
# Executes: codex --full-auto exec "@{CLAUDE.md,**/*CLAUDE.md,**/*user*,**/*dashboard*} create a complete user dashboard with charts" -s danger-full-access
```
### ⚠️ **Error Prevention**
- **Pattern validation**: Ensures @ patterns match existing files
- **Fallback patterns**: Uses comprehensive `@{**/*}` when inference fails
- **Context verification**: Always includes project guidelines
- **Session handling**: Graceful handling of missing workflow directories
### 📊 **Codex vs Gemini Chat**
| Feature | Codex Chat | Gemini Chat |
|---------|------------|-------------|
| File Loading | `@` patterns **required** | `--all-files` available |
| Pattern Inference | Automatic keyword-based | Manual or --all-files |
| Development Focus | Code generation & implementation | Analysis & exploration |
| Automation | `--full-auto` mode available | Interactive only |
| Command Structure | `codex exec "@{patterns}"` | `gemini --all-files -p` |
### 🚀 **Advanced Features**
#### Multi-Pattern Inference
```bash
/codex:chat "implement React authentication with API integration"
# Infers: @{CLAUDE.md,**/*CLAUDE.md,src/**/*.{jsx,tsx},**/*auth*,**/api/**/*}
```
#### Context-Aware Development
```bash
/codex:chat "add unit tests for the payment processing module"
# Infers: @{CLAUDE.md,**/*CLAUDE.md,**/*payment*,test/**/*,**/*.test.*}
```
#### Configuration Analysis
```bash
/codex:chat "review and optimize build configuration"
# Infers: @{CLAUDE.md,**/*CLAUDE.md,*.config.*,package.json,webpack.*,vite.*}
```
For detailed syntax, patterns, and advanced usage see:
**@~/.claude/workflows/tools-implementation-guide.md**

View File

@@ -1,223 +0,0 @@
---
name: execute
description: Auto-execution of implementation tasks with YOLO permissions and intelligent context inference using Codex CLI
usage: /codex:execute <description|task-id>
argument-hint: "implementation description or task-id"
examples:
- /codex:execute "implement user authentication system"
- /codex:execute "optimize React component performance"
- /codex:execute IMPL-001
- /codex:execute "fix API performance issues"
allowed-tools: Bash(codex:*)
model: sonnet
---
# Codex Execute Command (/codex:execute)
## Overview
**⚡ YOLO-enabled execution**: Auto-approves all confirmations for streamlined implementation workflow.
**Purpose**: Execute implementation tasks using intelligent context inference and Codex CLI with full permissions.
**Core Guidelines**: @~/.claude/workflows/tools-implementation-guide.md
⚠️ **Critical Difference**: Codex has **NO `--all-files` flag** - you MUST use `@` patterns to reference files.
## 🚨 YOLO Permissions
**All confirmations auto-approved by default:**
- ✅ File pattern inference confirmation
- ✅ Codex execution confirmation
- ✅ File modification confirmation
- ✅ Implementation summary generation
## Execution Modes
### 1. Description Mode
**Input**: Natural language description
```bash
/codex:execute "implement JWT authentication with middleware"
```
**Process**: Keyword analysis → Pattern inference → Context collection → Execution
### 2. Task ID Mode
**Input**: Workflow task identifier
```bash
/codex:execute IMPL-001
```
**Process**: Task JSON parsing → Scope analysis → Context integration → Execution
### 3. Full Auto Mode
**Input**: Complex development tasks
```bash
/codex:execute "create complete todo application with React and TypeScript"
```
**Process**: Uses `codex --full-auto ... -s danger-full-access` for autonomous implementation
## 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}`
## Essential Codex Patterns
**Required File Patterns** (No --all-files available):
```bash
@{**/*} # All files recursively (equivalent to --all-files)
@{src/**/*} # All source files
@{*.ts,*.js} # Specific file types
@{CLAUDE.md,**/*CLAUDE.md} # Documentation hierarchy
@{package.json,*.config.*} # Configuration files
```
## Command Options
| Option | Purpose |
|--------|---------|
| `--debug` | Verbose execution logging |
| `--save-session` | Save complete execution session to workflow |
| `--full-auto` | Enable autonomous development mode |
## Workflow Integration
### Session Management
⚠️ **Auto-detects active session**: Checks `.workflow/.active-*` marker file
**Session storage:**
- **Active session exists**: Saves to `.workflow/WFS-[topic]/.chat/execute-[timestamp].md`
- **No active session**: Creates new session directory
### Task Integration
```bash
# Execute specific workflow task
/codex:execute IMPL-001
# Loads from: .task/impl-001.json
# Uses: task context, brainstorming refs, scope definitions
# Updates: workflow status, generates summary
```
## Execution Templates
### User Description Template
```bash
codex --full-auto exec "@{inferred_patterns} @{CLAUDE.md,**/*CLAUDE.md}
Implementation Task: [user_description]
Provide:
- Specific implementation code
- File modification locations (file:line)
- Test cases
- Integration guidance" -s danger-full-access
```
### Task ID Template
```bash
codex --full-auto exec "@{task_files} @{brainstorming_refs} @{CLAUDE.md,**/*CLAUDE.md}
Task: [task_title] (ID: [task-id])
Type: [task_type]
Scope: [task_scope]
Execute implementation following task acceptance criteria." -s danger-full-access
```
### Full Auto Template
```bash
codex --full-auto exec "@{**/*} @{CLAUDE.md,**/*CLAUDE.md}
Development Task: [user_description]
Autonomous implementation with:
- Architecture decisions
- Code generation
- Testing
- Documentation" -s danger-full-access
```
## Auto-Generated Outputs
### 1. Implementation Summary
**Location**: `.summaries/[TASK-ID]-summary.md` or auto-generated ID
```markdown
# Task Summary: [Task-ID] [Description]
## Implementation
- **Files Modified**: [file:line references]
- **Features Added**: [specific functionality]
- **Context Used**: [inferred patterns]
## Integration
- [Links to workflow documents]
```
### 2. Execution Session
**Location**: `.chat/execute-[timestamp].md`
```markdown
# Execution Session: [Timestamp]
## Input
[User description or Task ID]
## Context Inference
[File patterns used with rationale]
## Implementation Results
[Generated code and modifications]
## Status Updates
[Workflow integration updates]
```
## Development Templates Used
Based on task type, automatically selects:
- **Feature Development**: `~/.claude/workflows/cli-templates/prompts/development/feature.txt`
- **Component Creation**: `~/.claude/workflows/cli-templates/prompts/development/component.txt`
- **Code Refactoring**: `~/.claude/workflows/cli-templates/prompts/development/refactor.txt`
- **Bug Fixing**: `~/.claude/workflows/cli-templates/prompts/development/debugging.txt`
- **Test Generation**: `~/.claude/workflows/cli-templates/prompts/development/testing.txt`
## Error Handling
- **Task ID not found**: Lists available tasks
- **Pattern inference failure**: Uses generic `@{src/**/*}` pattern
- **Execution failure**: Attempts fallback with simplified context
- **File modification errors**: Reports specific file/permission issues
- **Missing @ patterns**: Auto-adds `@{**/*}` for comprehensive context
## Performance Features
- **Smart caching**: Frequently used pattern mappings
- **Progressive inference**: Precise → broad pattern fallback
- **Parallel execution**: When multiple contexts needed
- **Directory optimization**: Uses `--cd` flag when beneficial
## Integration Workflow
**Typical sequence:**
1. `workflow:plan` → Creates tasks
2. `/codex:execute IMPL-001` → Executes with YOLO permissions
3. Auto-updates workflow status and generates summaries
4. `workflow:review` → Final validation
**vs. `/codex:analyze`**: Execute performs analysis **and implementation**, analyze is read-only.
## Codex vs Gemini Execution
| Feature | Codex | Gemini |
|---------|-------|--------|
| File Loading | `@` patterns **required** | `--all-files` available |
| Automation Level | Full autonomous with `--full-auto` | Manual implementation |
| Command Structure | `codex exec "@{patterns}"` | `gemini --all-files -p` |
| Development Focus | Code generation & implementation | Analysis & planning |
For detailed patterns, syntax, and templates see:
**@~/.claude/workflows/tools-implementation-guide.md**

View File

@@ -1,285 +0,0 @@
---
name: auto
description: Full autonomous development mode with intelligent template selection and execution
usage: /codex:mode:auto "description of development task"
argument-hint: "description of what you want to develop or implement"
examples:
- /codex:mode:auto "create user authentication system with JWT"
- /codex:mode:auto "build real-time chat application with React"
- /codex:mode:auto "implement payment processing with Stripe integration"
- /codex:mode:auto "develop REST API with user management features"
allowed-tools: Bash(ls:*), Bash(codex:*)
model: sonnet
---
# Full Auto Development Mode (/codex:mode:auto)
## Overview
Leverages Codex's `--full-auto` mode for autonomous development with intelligent template selection and comprehensive context gathering.
**Process**: Analyze Input → Select Templates → Gather Context → Execute Autonomous Development
⚠️ **Critical Feature**: Uses `codex --full-auto ... -s danger-full-access` for maximum autonomous capability with mandatory `@` pattern requirements.
## Usage
### Autonomous Development Examples
```bash
# Complete application development
/codex:mode:auto "create todo application with React and TypeScript"
# Feature implementation
/codex:mode:auto "implement user authentication with JWT and refresh tokens"
# System integration
/codex:mode:auto "add payment processing with Stripe to existing e-commerce system"
# Architecture implementation
/codex:mode:auto "build microservices API with user management and notification system"
```
## Template Selection Logic
### Dynamic Template Discovery
**Templates auto-discovered from**: `~/.claude/workflows/cli-templates/prompts/`
Templates are dynamically read from development-focused directories:
- `development/` - Feature implementation, component creation, refactoring
- `automation/` - Project scaffolding, migration, deployment
- `analysis/` - Architecture analysis, pattern detection
- `integration/` - API design, database operations
### Template Metadata Parsing
Each template contains YAML frontmatter with:
```yaml
---
name: template-name
description: Template purpose description
category: development|automation|analysis|integration
keywords: [keyword1, keyword2, keyword3]
development_type: feature|component|refactor|debug|testing
---
```
**Auto-selection based on:**
- **Development keywords**: Matches user input against development-specific keywords
- **Template type**: Direct matching for development types
- **Architecture patterns**: Semantic matching for system design
- **Technology stack**: Framework and library detection
## Command Execution
### Step 1: Template Discovery
```bash
# Dynamically discover development templates
cd "~/.claude/workflows/cli-templates/prompts" && echo "Discovering development templates..." && for dir in development automation analysis integration; do if [ -d "$dir" ]; then echo "=== $dir templates ==="; for template_file in "$dir"/*.txt; do if [ -f "$template_file" ]; then echo "Template: $(basename "$template_file")"; head -10 "$template_file" 2>/dev/null | grep -E "^(name|description|keywords):" || echo "No metadata"; echo; fi; done; fi; done
```
### Step 2: Dynamic Template Analysis & Selection
```pseudo
FUNCTION select_development_template(user_input):
template_dirs = ["development", "automation", "analysis", "integration"]
template_metadata = {}
# Parse all development templates for metadata
FOR each dir in template_dirs:
templates = list_files("~/.claude/workflows/cli-templates/prompts/" + dir + "/*.txt")
FOR each template_file in templates:
content = read_file(template_file)
yaml_front = extract_yaml_frontmatter(content)
template_metadata[template_file] = {
"name": yaml_front.name,
"description": yaml_front.description,
"keywords": yaml_front.keywords || [],
"category": yaml_front.category || dir,
"development_type": yaml_front.development_type || "general"
}
input_lower = user_input.toLowerCase()
best_match = null
highest_score = 0
# Score each template against user input
FOR each template, metadata in template_metadata:
score = 0
# Development keyword matching (highest weight)
development_keywords = ["implement", "create", "build", "develop", "add", "generate"]
FOR each dev_keyword in development_keywords:
IF input_lower.contains(dev_keyword):
score += 5
# Template-specific keyword matching
FOR each keyword in metadata.keywords:
IF input_lower.contains(keyword.toLowerCase()):
score += 3
# Development type matching
IF input_lower.contains(metadata.development_type.toLowerCase()):
score += 4
# Technology stack detection
tech_keywords = ["react", "vue", "angular", "node", "express", "api", "database", "auth"]
FOR each tech in tech_keywords:
IF input_lower.contains(tech):
score += 2
IF score > highest_score:
highest_score = score
best_match = template
# Default to feature.txt for development tasks
RETURN best_match || "development/feature.txt"
END FUNCTION
```
### Step 3: Execute with Full Auto Mode
```bash
# Autonomous development execution with comprehensive context
codex --full-auto "@{**/*} @{CLAUDE.md,**/*CLAUDE.md} $(cat ~/.claude/workflows/cli-templates/prompts/[selected_template])
Development Task: [user_input]
Autonomous Implementation Requirements:
- Complete feature development
- Code generation with best practices
- Automatic testing integration
- Documentation updates
- Error handling and validation" -s danger-full-access
```
## Essential Codex Auto Patterns
**Required File Patterns** (Comprehensive context for autonomous development):
```bash
@{**/*} # All files for full context understanding
@{src/**/*} # Source code for pattern detection
@{package.json,*.config.*} # Configuration and dependencies
@{CLAUDE.md,**/*CLAUDE.md} # Project guidelines and standards
@{test/**/*,**/*.test.*} # Existing tests for pattern matching
@{docs/**/*,README.*} # Documentation for context
```
## Development Template Categories
### Feature Development Templates
- **feature.txt**: Complete feature implementation with integration
- **component.txt**: Reusable component creation with props and state
- **refactor.txt**: Code improvement and optimization
### Automation Templates
- **scaffold.txt**: Project structure and boilerplate generation
- **migration.txt**: System upgrades and data migrations
- **deployment.txt**: CI/CD and deployment automation
### Analysis Templates (for context)
- **architecture.txt**: System structure understanding
- **pattern.txt**: Code pattern detection for consistency
- **security.txt**: Security analysis for safe development
### Integration Templates
- **api-design.txt**: RESTful API development
- **database.txt**: Database schema and operations
## Options
| Option | Purpose |
|--------|---------|
| `--list-templates` | Show available development templates and exit |
| `--template <name>` | Force specific template (overrides auto-selection) |
| `--debug` | Show template selection reasoning and context patterns |
| `--save-session` | Save complete development session to workflow |
| `--no-auto` | Use `codex exec` instead of `--full-auto` mode |
### Manual Template Override
```bash
# Force specific development template
/codex:mode:auto "user authentication" --template component.txt
/codex:mode:auto "fix login issues" --template debugging.txt
```
### Development Template Listing
```bash
# List all available development templates
/codex:mode:auto --list-templates
# Output:
# Development templates in ~/.claude/workflows/cli-templates/prompts/:
# - development/feature.txt (Complete feature implementation) [Keywords: implement, feature, integration]
# - development/component.txt (Reusable component creation) [Keywords: component, react, vue]
# - automation/scaffold.txt (Project structure generation) [Keywords: scaffold, setup, boilerplate]
# - [any-new-template].txt (Auto-discovered from any category)
```
## Auto-Selection Examples
### Development Task Detection
```bash
# Feature development → development/feature.txt
"implement user dashboard with analytics charts"
# Component creation → development/component.txt
"create reusable button component with multiple variants"
# System architecture → automation/scaffold.txt
"build complete e-commerce platform with React and Node.js"
# API development → integration/api-design.txt
"develop REST API for user management with authentication"
# Performance optimization → development/refactor.txt
"optimize React application performance and bundle size"
```
## Autonomous Development Workflow
### Full Context Gathering
1. **Project Analysis**: `@{**/*}` provides complete codebase context
2. **Pattern Detection**: Understands existing code patterns and conventions
3. **Dependency Analysis**: Reviews package.json and configuration files
4. **Test Pattern Recognition**: Follows existing test structures
### Intelligent Implementation
1. **Architecture Decisions**: Makes informed choices based on existing patterns
2. **Code Generation**: Creates code matching project style and conventions
3. **Integration**: Ensures new code integrates seamlessly with existing system
4. **Quality Assurance**: Includes error handling, validation, and testing
### Autonomous Features
- **Smart File Creation**: Creates necessary files and directories
- **Dependency Management**: Adds required packages automatically
- **Test Generation**: Creates comprehensive test suites
- **Documentation Updates**: Updates relevant documentation files
- **Configuration Updates**: Modifies config files as needed
## Session Integration
When `--save-session` used, saves to:
`.workflow/WFS-[topic]/.chat/auto-[template]-[timestamp].md`
**Session includes:**
- Original development request
- Template selection reasoning
- Complete context patterns used
- Autonomous development results
- Files created/modified
- Integration guidance
## Performance Features
- **Parallel Context Loading**: Loads multiple file patterns simultaneously
- **Smart Caching**: Caches template selections for similar requests
- **Progressive Development**: Builds features incrementally with validation
- **Rollback Capability**: Can revert changes if issues detected
## Codex vs Gemini Auto Mode
| Feature | Codex Auto | Gemini Auto |
|---------|------------|-------------|
| Primary Purpose | Autonomous development | Analysis and planning |
| File Loading | `@{**/*}` required | `--all-files` available |
| Output | Complete implementations | Analysis and recommendations |
| Template Focus | Development-oriented | Analysis-oriented |
| Execution Mode | `--full-auto` autonomous | Interactive guidance |
This command maximizes Codex's autonomous development capabilities while ensuring comprehensive context and intelligent template selection for optimal results.

View File

@@ -1,269 +0,0 @@
---
name: bug-index
description: Bug analysis, debugging, and automated fix implementation using Codex
usage: /codex:mode:bug-index "bug description"
argument-hint: "description of the bug or error you're experiencing"
examples:
- /codex:mode:bug-index "authentication null pointer error in login flow"
- /codex:mode:bug-index "React component not re-rendering after state change"
- /codex:mode:bug-index "database connection timeout in production"
- /codex:mode:bug-index "API endpoints returning 500 errors randomly"
allowed-tools: Bash(codex:*)
model: sonnet
---
# Bug Analysis & Fix Command (/codex:mode:bug-index)
## Overview
Systematic bug analysis, debugging, and automated fix implementation using expert diagnostic templates with Codex CLI.
**Core Guidelines**: @~/.claude/workflows/tools-implementation-guide.md
⚠️ **Critical Difference**: Codex has **NO `--all-files` flag** - you MUST use `@` patterns to reference files.
**Enhancement over Gemini**: Codex can **analyze AND implement fixes**, not just provide recommendations.
## Usage
### Basic Bug Analysis & Fix
```bash
/codex:mode:bug-index "authentication error during login"
```
**Executes**: `codex --full-auto exec "@{**/*auth*,**/*login*} @{CLAUDE.md} $(cat ~/.claude/workflows/cli-templates/prompts/development/debugging.txt)" -s danger-full-access`
### Comprehensive Bug Investigation
```bash
/codex:mode:bug-index "React state not updating in dashboard"
```
**Executes**: `codex --full-auto exec "@{src/**/*.{jsx,tsx},**/*dashboard*} @{CLAUDE.md} $(cat ~/.claude/workflows/cli-templates/prompts/development/debugging.txt)" -s danger-full-access`
### Production Error Analysis
```bash
/codex:mode:bug-index "API timeout issues in production environment"
```
**Executes**: `codex --full-auto exec "@{**/api/**/*,*.config.*} @{CLAUDE.md} $(cat ~/.claude/workflows/cli-templates/prompts/development/debugging.txt)" -s danger-full-access`
## Codex-Specific Debugging Patterns
**Essential File Patterns** (Required for effective debugging):
```bash
@{**/*error*,**/*bug*} # Error-related files
@{src/**/*} # Source code for bug analysis
@{**/logs/**/*} # Log files for error traces
@{test/**/*,**/*.test.*} # Tests to understand expected behavior
@{CLAUDE.md,**/*CLAUDE.md} # Project guidelines
@{*.config.*,package.json} # Configuration for environment issues
```
## Command Execution
**Debugging Template Used**: `~/.claude/workflows/cli-templates/prompts/development/debugging.txt`
**Executes**:
```bash
codex exec "@{inferred_bug_patterns} @{CLAUDE.md,**/*CLAUDE.md} $(cat ~/.claude/workflows/cli-templates/prompts/development/debugging.txt)
Context: Comprehensive codebase analysis for bug investigation
Bug Description: [user_description]
Fix Implementation: Provide working code solutions" -s danger-full-access
```
## Bug Pattern Inference
**Auto-detects relevant files based on bug description:**
| Bug Keywords | Inferred Patterns | Focus Area |
|-------------|------------------|------------|
| "auth", "login", "token" | `@{**/*auth*,**/*user*,**/*login*}` | Authentication code |
| "React", "component", "render" | `@{src/**/*.{jsx,tsx}}` | React components |
| "API", "endpoint", "server" | `@{**/api/**/*,**/routes/**/*}` | Backend code |
| "database", "db", "query" | `@{**/models/**/*,**/db/**/*}` | Database code |
| "timeout", "connection" | `@{*.config.*,**/*config*}` | Configuration issues |
| "test", "spec" | `@{test/**/*,**/*.test.*}` | Test-related bugs |
| "build", "compile" | `@{*.config.*,package.json,webpack.*}` | Build issues |
| "style", "css", "layout" | `@{**/*.{css,scss,sass}}` | Styling bugs |
## Analysis & Fix Focus
### Comprehensive Bug Analysis Provides:
- **Root Cause Analysis**: Systematic investigation with file:line references
- **Code Path Tracing**: Following execution flow through the codebase
- **Error Pattern Detection**: Identifying similar issues across the codebase
- **Context Understanding**: Leveraging existing code patterns
- **Impact Assessment**: Understanding potential side effects of fixes
### Codex Enhancement - Automated Fixes:
- **Working Code Solutions**: Actual implementation fixes
- **Multiple Fix Options**: Different approaches with trade-offs
- **Test Case Generation**: Tests to prevent regression
- **Configuration Updates**: Environment and config fixes
- **Documentation Updates**: Updated comments and documentation
## Debugging Templates & Approaches
### Error Investigation
```bash
# Uses: debugging.txt template for systematic analysis
/codex:mode:bug-index "null pointer exception in user service"
# Provides: Stack trace analysis, variable state inspection, fix implementation
```
### Performance Bug Analysis
```bash
# Uses: debugging.txt + performance.txt combination
/codex:mode:bug-index "slow database queries causing timeout"
# Provides: Query optimization, indexing suggestions, connection pool fixes
```
### Integration Bug Fixes
```bash
# Uses: debugging.txt + integration/api-design.txt
/codex:mode:bug-index "third-party API integration failing randomly"
# Provides: Error handling, retry logic, fallback implementations
```
## Options
| Option | Purpose |
|--------|---------|
| `--comprehensive` | Use `@{**/*}` for complete codebase analysis |
| `--save-session` | Save bug analysis and fixes to workflow session |
| `--implement-fix` | Auto-implement the recommended fix (default in Codex) |
| `--generate-tests` | Create tests to prevent regression |
| `--debug-mode` | Verbose debugging output with pattern explanations |
### Comprehensive Debugging
```bash
/codex:mode:bug-index "intermittent authentication failures" --comprehensive
# Uses: @{**/*} for complete system analysis
```
### Bug Fix with Testing
```bash
/codex:mode:bug-index "user registration validation errors" --generate-tests
# Provides: Bug fix + comprehensive test suite
```
## Session Output
When `--save-session` used, saves to:
`.workflow/WFS-[topic]/.chat/bug-index-[timestamp].md`
**Session includes:**
- Bug description and symptoms
- File patterns used for analysis
- Root cause analysis with evidence
- Implemented fix with code changes
- Test cases to prevent regression
- Monitoring and prevention recommendations
## Debugging Output Structure
### Bug Analysis Template Output:
```markdown
# Bug Analysis: [Description]
## Problem Investigation
- Symptoms and error messages
- Affected components and files
- Reproduction steps
## Root Cause Analysis
- Code path analysis with file:line references
- Variable states and data flow
- Configuration and environment factors
## Implemented Fixes
- Primary solution with code changes
- Alternative approaches considered
- Trade-offs and design decisions
## Testing & Validation
- Test cases to verify fix
- Regression prevention tests
- Performance impact assessment
## Monitoring & Prevention
- Error handling improvements
- Logging enhancements
- Code quality improvements
```
## Context-Aware Bug Fixing
### Existing Pattern Integration
```bash
/codex:mode:bug-index "authentication middleware not working"
# Analyzes existing auth patterns in codebase
# Implements fix consistent with current architecture
# Updates related middleware to match patterns
```
### Technology Stack Compatibility
```bash
/codex:mode:bug-index "React hooks causing infinite renders"
# Reviews current React version and patterns
# Implements fix using appropriate hooks API
# Updates other components with similar issues
```
## Advanced Debugging Features
### Multi-File Bug Tracking
```bash
/codex:mode:bug-index "user data inconsistency between frontend and backend"
# Analyzes both frontend and backend code
# Identifies data flow discrepancies
# Implements synchronized fixes across stack
```
### Production Issue Investigation
```bash
/codex:mode:bug-index "memory leak in production server"
# Reviews server code and configuration
# Analyzes log patterns and resource usage
# Implements monitoring and leak prevention
```
### Error Handling Enhancement
```bash
/codex:mode:bug-index "unhandled promise rejections causing crashes"
# Identifies all async operations without error handling
# Implements comprehensive error handling strategy
# Adds logging and monitoring for similar issues
```
## Bug Prevention Features
- **Pattern Analysis**: Identifies similar bugs across codebase
- **Code Quality Improvements**: Suggests structural improvements
- **Error Handling Enhancement**: Adds robust error handling
- **Test Coverage**: Creates tests to prevent similar issues
- **Documentation Updates**: Improves code documentation
## Codex vs Gemini Bug Analysis
| Feature | Codex Bug-Index | Gemini Bug-Index |
|---------|-----------------|------------------|
| File Context | `@` patterns **required** | `--all-files` available |
| Output | Analysis + working fixes | Analysis + recommendations |
| Implementation | Automatic code changes | Manual implementation needed |
| Testing | Auto-generates test cases | Suggests testing approach |
| Integration | Updates related code | Focuses on specific bug |
## Workflow Integration
### Bug Fixing Workflow
```bash
# 1. Analyze and fix the bug
/codex:mode:bug-index "user login failing with token errors"
# 2. Review the implemented changes
/workflow:review
# 3. Execute any additional tasks identified
/codex:execute "implement additional error handling for edge cases"
```
For detailed syntax, patterns, and advanced usage see:
**@~/.claude/workflows/tools-implementation-guide.md**

View File

@@ -1,260 +0,0 @@
---
name: plan
description: Development planning and implementation strategy using specialized templates with Codex
usage: /codex:mode:plan "planning topic"
argument-hint: "development planning topic or implementation challenge"
examples:
- /codex:mode:plan "design user dashboard feature architecture"
- /codex:mode:plan "plan microservices migration with implementation"
- /codex:mode:plan "implement real-time notification system with React"
allowed-tools: Bash(codex:*)
model: sonnet
---
# Development Planning Command (/codex:mode:plan)
## Overview
Comprehensive development planning and implementation strategy using expert planning templates with Codex CLI.
- **Directory Analysis Rule**: When user intends to analyze specific directory (cd XXX), use: `codex --cd XXX --full-auto exec "prompt" -s danger-full-access` or `cd "XXX" && codex --full-auto exec "@{**/*} prompt" -s danger-full-access`
- **Default Mode**: `--full-auto exec` autonomous development mode (RECOMMENDED for all tasks).
⚠️ **Critical Difference**: Codex has **NO `--all-files` flag** - you MUST use `@` patterns to reference files.
## Usage
### Basic Development Planning
```bash
/codex:mode:plan "design authentication system with implementation"
```
**Executes**: `codex --full-auto exec "@{**/*} @{CLAUDE.md} $(cat ~/.claude/workflows/cli-templates/prompts/planning/task-breakdown.txt) design authentication system with implementation" -s danger-full-access`
### Architecture Planning with Context
```bash
/codex:mode:plan "microservices migration strategy"
```
**Executes**: `codex --full-auto exec "@{src/**/*,*.config.*,CLAUDE.md} $(cat ~/.claude/workflows/cli-templates/prompts/planning/migration.txt) microservices migration strategy" -s danger-full-access`
### Feature Implementation Planning
```bash
/codex:mode:plan "real-time notifications with WebSocket integration"
```
**Executes**: `codex --full-auto exec "@{**/*} @{CLAUDE.md} $(cat ~/.claude/workflows/cli-templates/prompts/development/feature.txt) Additional Planning Context:$(cat ~/.claude/workflows/cli-templates/prompts/planning/task-breakdown.txt) real-time notifications with WebSocket integration" -s danger-full-access`
## Codex-Specific Planning Patterns
**Essential File Patterns** (Required for comprehensive planning):
```bash
@{**/*} # All files for complete context
@{src/**/*} # Source code architecture
@{*.config.*,package.json} # Configuration and dependencies
@{CLAUDE.md,**/*CLAUDE.md} # Project guidelines
@{docs/**/*,README.*} # Documentation for context
@{test/**/*} # Testing patterns
```
## Command Execution
**Planning Templates Used**:
- Primary: `~/.claude/workflows/cli-templates/prompts/planning/task-breakdown.txt`
- Migration: `~/.claude/workflows/cli-templates/prompts/planning/migration.txt`
- Combined with development templates for implementation guidance
**Executes**:
```bash
codex exec "@{**/*} @{CLAUDE.md,**/*CLAUDE.md} $(cat ~/.claude/workflows/cli-templates/prompts/planning/task-breakdown.txt)
Context: Complete codebase analysis for informed planning
Planning Topic: [user_description]
Implementation Focus: Development strategy with code generation guidance"
```
## Planning Focus Areas
### Development Planning Provides:
- **Requirements Analysis**: Functional and technical requirements
- **Architecture Design**: System structure with implementation details
- **Implementation Strategy**: Step-by-step development approach with code examples
- **Technology Selection**: Framework and library recommendations
- **Task Decomposition**: Detailed task breakdown with dependencies
- **Code Structure Planning**: File organization and module design
- **Testing Strategy**: Test planning and coverage approach
- **Integration Planning**: API design and data flow
### Codex Enhancement:
- **Implementation Guidance**: Actual code patterns and examples
- **Automated Scaffolding**: Template generation for planned components
- **Dependency Analysis**: Required packages and configurations
- **Pattern Detection**: Leverages existing codebase patterns
## Planning Templates
### Task Breakdown Planning
```bash
# Uses: planning/task-breakdown.txt
/codex:mode:plan "implement user authentication system"
# Provides: Detailed task list, dependencies, implementation order
```
### Migration Planning
```bash
# Uses: planning/migration.txt
/codex:mode:plan "migrate from REST to GraphQL API"
# Provides: Migration strategy, compatibility planning, rollout approach
```
### Feature Planning with Implementation
```bash
# Uses: development/feature.txt + planning/task-breakdown.txt
/codex:mode:plan "build real-time chat application"
# Provides: Architecture + implementation roadmap + code examples
```
## Options
| Option | Purpose |
|--------|---------|
| `--comprehensive` | Use `@{**/*}` for complete codebase context |
| `--save-session` | Save planning analysis to workflow session |
| `--with-implementation` | Include code generation in planning |
| `--template <name>` | Force specific planning template |
### Comprehensive Planning
```bash
/codex:mode:plan "design payment system architecture" --comprehensive
# Uses: @{**/*} pattern for maximum context
```
### Planning with Implementation
```bash
/codex:mode:plan "implement user dashboard" --with-implementation
# Combines planning templates with development templates for actionable output
```
## Session Output
When `--save-session` used, saves to:
`.workflow/WFS-[topic]/.chat/plan-[timestamp].md`
**Session includes:**
- Planning topic and requirements
- Template combination used
- Complete architecture analysis
- Implementation roadmap with tasks
- Code structure recommendations
- Technology stack decisions
- Integration strategies
- Next steps and action items
## Planning Template Structure
### Task Breakdown Template Output:
```markdown
# Development Plan: [Topic]
## Requirements Analysis
- Functional requirements
- Technical requirements
- Constraints and dependencies
## Architecture Design
- System components
- Data flow
- Integration points
## Implementation Strategy
- Development phases
- Task breakdown
- Dependencies and blockers
- Estimated effort
## Code Structure
- File organization
- Module design
- Component hierarchy
## Technology Decisions
- Framework selection
- Library recommendations
- Configuration requirements
## Testing Approach
- Testing strategy
- Coverage requirements
- Test automation
## Action Items
- [ ] Detailed task list with priorities
- [ ] Implementation order
- [ ] Review checkpoints
```
## Context-Aware Planning
### Existing Codebase Integration
```bash
/codex:mode:plan "add user roles and permissions system"
# Analyzes existing authentication patterns
# Plans integration with current user management
# Suggests compatible implementation approach
```
### Technology Stack Analysis
```bash
/codex:mode:plan "implement real-time features"
# Reviews current tech stack (React, Node.js, etc.)
# Recommends compatible WebSocket/SSE solutions
# Plans integration with existing architecture
```
## Planning Workflow Integration
### Pre-Development Planning
1. **Architecture Analysis**: Understand current system structure
2. **Requirement Planning**: Define scope and objectives
3. **Implementation Strategy**: Create detailed development plan
4. **Task Creation**: Generate actionable tasks for execution
### Planning to Execution Flow
```bash
# 1. Plan the implementation
/codex:mode:plan "implement user dashboard with analytics"
# 2. Execute the plan
/codex:execute "implement user dashboard based on planning analysis"
# 3. Review and iterate
/workflow:review
```
## Codex vs Gemini Planning
| Feature | Codex Planning | Gemini Planning |
|---------|----------------|-----------------|
| File Context | `@` patterns **required** | `--all-files` available |
| Output Focus | Implementation-ready plans | Analysis and strategy |
| Code Examples | Includes actual code patterns | Conceptual guidance |
| Integration | Direct execution pathway | Planning only |
| Templates | Development + planning combined | Planning focused |
## Advanced Planning Features
### Multi-Phase Planning
```bash
/codex:mode:plan "modernize legacy application architecture"
# Provides: Phase-by-phase migration strategy
# Includes: Compatibility planning, risk assessment
# Generates: Implementation timeline with milestones
```
### Cross-System Integration Planning
```bash
/codex:mode:plan "integrate third-party payment system with existing e-commerce"
# Analyzes: Current system architecture
# Plans: Integration approach and data flow
# Recommends: Security and error handling strategies
```
For detailed syntax, patterns, and advanced usage see:
**@~/.claude/workflows/intelligent-tools-strategy.md**

View File

@@ -1,201 +1,112 @@
---
name: enhance-prompt
description: Dynamic prompt enhancement for complex requirements - Structured enhancement of user prompts before agent execution
usage: /enhance-prompt <user_input>
argument-hint: [--gemini] "user input to enhance"
examples:
- /enhance-prompt "add user profile editing"
- /enhance-prompt "fix login button"
- /enhance-prompt "clean up the payment code"
description: Context-aware prompt enhancement using session memory and codebase analysis
argument-hint: "user input to enhance"
---
### 🚀 **Command Overview: `/enhance-prompt`**
## Overview
- **Type**: Prompt Engineering Command
- **Purpose**: To systematically enhance raw user prompts, translating them into clear, context-rich, and actionable specifications before agent execution.
- **Key Feature**: Dynamically integrates with Gemini for deep, codebase-aware analysis.
Systematically enhances user prompts by combining session memory context with codebase patterns, translating ambiguous requests into actionable specifications.
### 📥 **Command Parameters**
## Core Protocol
- `<user_input>`: **(Required)** The raw text prompt from the user that needs enhancement.
- `--gemini`: **(Optional)** An explicit flag to force the full Gemini collaboration flow, ensuring codebase analysis is performed even for simple prompts.
**Enhancement Pipeline:**
`Intent Translation``Context Integration``Gemini Analysis (if needed)``Structured Output`
### 🔄 **Core Enhancement Protocol**
**Context Sources:**
- Session memory (conversation history, previous analysis)
- Codebase patterns (via Gemini when triggered)
- Implicit technical requirements
This is the standard pipeline every prompt goes through for structured enhancement.
`Step 1: Intent Translation` **->** `Step 2: Context Extraction` **->** `Step 3: Key Points Identification` **->** `Step 4: Optional Gemini Consultation`
### 🧠 **Gemini Collaboration Logic**
This logic determines when to invoke Gemini for deeper, codebase-aware insights.
## Gemini Trigger Logic
```pseudo
FUNCTION decide_enhancement_path(user_prompt, options):
// Set of keywords that indicate high complexity or architectural changes.
FUNCTION should_use_gemini(user_prompt):
critical_keywords = ["refactor", "migrate", "redesign", "auth", "payment", "security"]
// Conditions for triggering Gemini analysis.
use_gemini = FALSE
IF options.gemini_flag is TRUE:
use_gemini = TRUE
ELSE IF prompt_affects_multiple_modules(user_prompt, threshold=3):
use_gemini = TRUE
ELSE IF any_keyword_in_prompt(critical_keywords, user_prompt):
use_gemini = TRUE
// Execute the appropriate enhancement flow.
enhanced_prompt = run_standard_enhancement(user_prompt) // Steps 1-3
IF use_gemini is TRUE:
// This action corresponds to calling the Gemini CLI tool programmatically.
// e.g., `gemini --all-files -p "..."` based on the derived context.
gemini_insights = execute_tool("gemini","-P" enhanced_prompt) // Calls the Gemini CLI
enhanced_prompt.append(gemini_insights)
RETURN enhanced_prompt
END FUNCTION
RETURN (
prompt_affects_multiple_modules(user_prompt, threshold=3) OR
any_keyword_in_prompt(critical_keywords, user_prompt)
)
END
```
### 📚 **Enhancement Rules**
**Gemini Integration:** ~/.claude/workflows/intelligent-tools-strategy.md
- **Ambiguity Resolution**: Generic terms are translated into specific technical intents.
- `"fix"` → Identify the specific bug and preserve existing functionality.
- `"improve"` → Enhance performance or readability while maintaining compatibility.
- `"add"` → Implement a new feature and integrate it with existing code.
- `"refactor"` → Restructure code to improve quality while preserving external behavior.
- **Implicit Context Inference**: Missing technical context is automatically inferred.
```bash
# User: "add login"
# Inferred Context:
# - Authentication system implementation
# - Frontend login form + backend validation
# - Session management considerations
# - Security best practices (e.g., password handling)
```
- **Technical Translation**: Business goals are converted into technical specifications.
```bash
# User: "make it faster"
# Translated Intent:
# - Identify performance bottlenecks
# - Define target metrics/benchmarks
# - Profile before optimizing
# - Document performance gains and trade-offs
```
## Enhancement Rules
### 🗺️ **Enhancement Translation Matrix**
### Intent Translation
| User Says | → Translate To | Key Context | Focus Areas |
| ------------------ | ----------------------- | ----------------------- | --------------------------- |
| "make it work" | Fix functionality | Debug implementation | Root cause → fix → test |
| "add [feature]" | Implement capability | Integration points | Core function + edge cases |
| "improve [area]" | Optimize/enhance | Current limits | Measurable improvements |
| "fix [bug]" | Resolve issue | Bug symptoms | Root cause + prevention |
| "refactor [code]" | Restructure quality | Structure pain points | Maintain behavior |
| "update [component]" | Modernize | Version compatibility | Migration path |
| User Says | Translate To | Focus |
|-----------|--------------|-------|
| "fix" | Debug and resolve | Root cause → preserve behavior |
| "improve" | Enhance/optimize | Performance/readability |
| "add" | Implement feature | Integration + edge cases |
| "refactor" | Restructure quality | Maintain behavior |
| "update" | Modernize | Version compatibility |
### ⚡ **Automatic Invocation Triggers**
### Context Integration Strategy
The `/enhance-prompt` command is designed to run automatically when the system detects:
- Ambiguous user language (e.g., "fix", "improve", "clean up").
- Tasks impacting multiple modules or components (>3).
- Requests for system architecture changes.
- Modifications to critical systems (auth, payment, security).
- Complex refactoring requests.
**Session Memory First:**
- Reference recent conversation context
- Reuse previously identified patterns
- Build on established understanding
### 🛠️ **Gemini Integration Protocol (Internal)**
**Codebase Analysis (via Gemini):**
- Only when complexity requires it
- Focus on integration points
- Identify existing patterns
**Gemini Integration**: @~/.claude/workflows/intelligent-tools-strategy.md
This section details how the system programmatically interacts with the Gemini CLI.
- **Primary Tool**: All Gemini analysis is performed via direct calls to the `gemini` command-line tool (e.g., `gemini --all-files -p "..."`).
- **Central Guidelines**: All CLI usage patterns, syntax, and context detection rules are defined in the central guidelines document:
- **Template Selection**: For specific analysis types, the system references the template selection guide:
- **All Templates**: `gemini-template-rules.md` - provides guidance on selecting appropriate templates
- **Template Library**: `cli-templates/` - contains actual prompt and command templates
### 📝 **Enhancement Examples**
This card contains the original, unmodified examples to demonstrate the command's output.
#### Example 1: Feature Request (with Gemini Integration)
**Example:**
```bash
# User Input: "add user profile editing"
# Standard Enhancement:
TRANSLATED_INTENT: Implement user profile editing feature
DOMAIN_CONTEXT: User management system
ACTION_TYPE: Create new feature
COMPLEXITY: Medium (multi-component)
# Gemini Analysis Added:
GEMINI_PATTERN_ANALYSIS: FormValidator used in AccountSettings, PreferencesEditor
GEMINI_ARCHITECTURE: UserService → ProfileRepository → UserModel pattern
# Final Enhanced Structure:
ENRICHED_CONTEXT:
- Frontend: Profile form using FormValidator pattern
- Backend: API endpoints following UserService pattern
- Database: User model via ProfileRepository
- Auth: Permission checks using AuthGuard pattern
KEY_POINTS:
- Data validation using existing FormValidator
- Image upload via SecureUploadService
- Field permissions with AuthGuard middleware
ATTENTION_AREAS:
- Security: Use SecureUploadService for file handling
- Performance: Lazy loading patterns (ProfileImage.tsx)
# User: "add login"
# Session Memory: Previous auth discussion, JWT mentioned
# Inferred: JWT-based auth, integrate with existing session management
# Gemini (if multi-module): Analyze AuthService patterns, middleware structure
```
#### Example 2: Bug Fix
## Output Structure
```bash
# User Input: "login button doesn't work"
# Enhanced Structure:
TRANSLATED_INTENT: Debug and fix non-functional login button
DOMAIN_CONTEXT: Authentication UI
ACTION_TYPE: Fix bug
COMPLEXITY: Simple (single component)
KEY_POINTS:
- Identify root cause (event/state/API)
- Preserve existing auth flow
- Add error handling if missing
ATTENTION_AREAS:
- Don't break existing functionality
- Test edge cases and user states
INTENT: [Clear technical goal]
CONTEXT: [Session memory + codebase patterns]
ACTION: [Specific implementation steps]
ATTENTION: [Critical constraints]
```
#### Example 3: Refactoring Request
### Output Examples
**Simple (no Gemini):**
```bash
# User Input: "clean up the payment code"
# Enhanced Structure:
TRANSLATED_INTENT: Refactor payment module for maintainability
DOMAIN_CONTEXT: Payment processing system
ACTION_TYPE: Refactor
COMPLEXITY: Complex (critical system)
KEY_POINTS:
- Maintain exact functionality
- Improve code organization
- Extract reusable components
ATTENTION_AREAS:
- Critical: No behavior changes
- Security: Maintain PCI compliance
- Testing: Comprehensive coverage
# Input: "fix login button"
INTENT: Debug non-functional login button
CONTEXT: From session - OAuth flow discussed, known state issue
ACTION: Check event binding → verify state updates → test auth flow
ATTENTION: Preserve existing OAuth integration
```
### ✨ **Key Benefits**
**Complex (with Gemini):**
```bash
# Input: "refactor payment code"
INTENT: Restructure payment module for maintainability
CONTEXT: Session memory - PCI compliance requirements
Gemini - PaymentService → StripeAdapter pattern identified
ACTION: Extract reusable validators → isolate payment gateway logic
ATTENTION: Zero behavior change, maintain PCI compliance, full test coverage
```
1. **Clarity**: Ambiguous requests become clear specifications.
2. **Completeness**: Implicit requirements become explicit.
3. **Context**: Missing context is automatically inferred.
4. **Codebase Awareness**: Gemini provides actual patterns from the project.
5. **Quality**: Attention areas prevent common mistakes.
6. **Efficiency**: Agents receive structured, actionable input.
7. **Smart Flow Control**: Seamless integration with workflows.
## Automatic Triggers
- Ambiguous language: "fix", "improve", "clean up"
- Multi-module impact (>3 modules)
- Architecture changes
- Critical systems: auth, payment, security
- Complex refactoring
## Key Principles
1. **Memory First**: Leverage session context before analysis
2. **Minimal Gemini**: Only when complexity demands it
3. **Context Reuse**: Build on previous understanding
4. **Clear Output**: Structured, actionable specifications
5. **Avoid Duplication**: Reference existing context, don't repeat

View File

@@ -1,96 +0,0 @@
---
name: analyze
description: Quick analysis of codebase patterns, architecture, and code quality using Gemini CLI
usage: /gemini:analyze <analysis-type>
argument-hint: "analysis target or type"
examples:
- /gemini:analyze "React hooks patterns"
- /gemini:analyze "authentication security"
- /gemini:analyze "performance bottlenecks"
- /gemini:analyze "API design patterns"
model: haiku
---
# Gemini Analysis Command (/gemini:analyze)
## Overview
Quick analysis tool for codebase insights using intelligent pattern detection and template-driven analysis.
**Core Guidelines**: @~/.claude/workflows/intelligent-tools-strategy.md
## Analysis Types
| Type | Purpose | Example |
|------|---------|---------|
| **pattern** | Code pattern detection | "React hooks usage patterns" |
| **architecture** | System structure analysis | "component hierarchy structure" |
| **security** | Security vulnerabilities | "authentication vulnerabilities" |
| **performance** | Performance bottlenecks | "rendering performance issues" |
| **quality** | Code quality assessment | "testing coverage analysis" |
| **dependencies** | Third-party analysis | "outdated package dependencies" |
## Quick Usage
### Basic Analysis
```bash
/gemini:analyze "authentication patterns"
```
**Executes**: `gemini -p -a "@{**/*auth*} @{CLAUDE.md} $(template:analysis/pattern.txt)"`
### Targeted Analysis
```bash
/gemini:analyze "React component architecture"
```
**Executes**: `gemini -p -a "@{src/components/**/*} @{CLAUDE.md} $(template:analysis/architecture.txt)"`
### Security Focus
```bash
/gemini:analyze "API security vulnerabilities"
```
**Executes**: `gemini -p -a "@{**/api/**/*} @{CLAUDE.md} $(template:analysis/security.txt)"`
## Templates Used
Templates are automatically selected based on analysis type:
- **Pattern Analysis**: `~/.claude/workflows/cli-templates/prompts/analysis/pattern.txt`
- **Architecture Analysis**: `~/.claude/workflows/cli-templates/prompts/analysis/architecture.txt`
- **Security Analysis**: `~/.claude/workflows/cli-templates/prompts/analysis/security.txt`
- **Performance Analysis**: `~/.claude/workflows/cli-templates/prompts/analysis/performance.txt`
## Workflow Integration
⚠️ **Session Check**: Automatically detects active workflow session via `.workflow/.active-*` marker file.
**Analysis results saved to:**
- Active session: `.workflow/WFS-[topic]/.chat/analysis-[timestamp].md`
- No session: Temporary analysis output
## Common Patterns
### Technology Stack Analysis
```bash
/gemini:analyze "project technology stack"
# Auto-detects: package.json, config files, dependencies
```
### Code Quality Review
```bash
/gemini:analyze "code quality and standards"
# Auto-targets: source files, test files, CLAUDE.md
```
### Migration Planning
```bash
/gemini:analyze "legacy code modernization"
# Focuses: older patterns, deprecated APIs, upgrade paths
```
## Output Format
Analysis results include:
- **File References**: Specific file:line locations
- **Code Examples**: Relevant code snippets
- **Patterns Found**: Common patterns and anti-patterns
- **Recommendations**: Actionable improvements
- **Integration Points**: How components connect

View File

@@ -1,93 +0,0 @@
---
name: chat
description: Simple Gemini CLI interaction command for direct codebase analysis
usage: /gemini:chat "inquiry"
argument-hint: "your question or analysis request"
examples:
- /gemini:chat "analyze the authentication flow"
- /gemini:chat "how can I optimize this React component performance?"
- /gemini:chat "review security vulnerabilities in src/auth/"
allowed-tools: Bash(gemini:*)
model: sonnet
---
### 🚀 **Command Overview: `/gemini:chat`**
- **Type**: Basic Gemini CLI Wrapper
- **Purpose**: Direct interaction with the `gemini` CLI for simple codebase analysis
- **Core Tool**: `Bash(gemini:*)` - Executes the external Gemini CLI tool
### 📥 **Parameters & Usage**
- **`<inquiry>` (Required)**: Your question or analysis request
- **`--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
### 🔄 **Execution Workflow**
`Parse Input` **->** `Assemble Context` **->** `Construct Prompt` **->** `Execute Gemini CLI` **->** `(Optional) Save Session`
### 📚 **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**
```
=== CONTEXT ===
@{CLAUDE.md,**/*CLAUDE.md} [Project guidelines]
@{target_files} [User-specified files or all files if --all-files is used]
=== USER INPUT ===
[The user inquiry text]
```
### ⚙️ **Execution Implementation**
```pseudo
FUNCTION execute_gemini_chat(user_inquiry, flags):
// Construct basic prompt
prompt = "=== CONTEXT ===\n"
prompt += "@{CLAUDE.md,**/*CLAUDE.md}\n"
// Add user-specified files or all files
IF flags contain "--all-files":
result = execute_tool("Bash(gemini:*)", "--all-files", "-p", prompt + user_inquiry)
ELSE:
prompt += "\n=== USER INPUT ===\n" + user_inquiry
result = execute_tool("Bash(gemini:*)", "-p", prompt)
// Save session if requested
IF flags contain "--save-session":
save_chat_session(user_inquiry, result)
RETURN result
END FUNCTION
```
### 💾 **Session Persistence**
When `--save-session` flag is used:
- Check for existing active session (`.workflow/.active-*` markers)
- Save to existing session's `.chat/` directory or create new session
- File format: `chat-YYYYMMDD-HHMMSS.md`
- Include query, context, and response in saved file
**Session Template:**
```markdown
# Chat Session: [Timestamp]
## Query
[Original user inquiry]
## Context
[Files and patterns included in analysis]
## Gemini Response
[Complete response from Gemini CLI]
```

View File

@@ -1,168 +0,0 @@
---
name: execute
description: Auto-execution of implementation tasks with YOLO permissions and intelligent context inference
usage: /gemini:execute <description|task-id>
argument-hint: "implementation description or task-id"
examples:
- /gemini:execute "implement user authentication system"
- /gemini:execute "optimize React component performance"
- /gemini:execute IMPL-001
- /gemini:execute "fix API performance issues"
allowed-tools: Bash(gemini:*)
model: sonnet
---
# Gemini Execute Command (/gemini:execute)
## Overview
**⚡ YOLO-enabled execution**: Auto-approves all confirmations for streamlined implementation workflow.
**Purpose**: Execute implementation tasks using intelligent context inference and Gemini CLI with full permissions.
**Core Guidelines**: @~/.claude/workflows/intelligent-tools-strategy.md
## 🚨 YOLO Permissions
**All confirmations auto-approved by default:**
- ✅ File pattern inference confirmation
- ✅ Gemini execution confirmation
- ✅ File modification confirmation
- ✅ Implementation summary generation
## Execution Modes
### 1. Description Mode
**Input**: Natural language description
```bash
/gemini:execute "implement JWT authentication with middleware"
```
**Process**: Keyword analysis → Pattern inference → Context collection → Execution
### 2. Task ID Mode
**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 |
## Workflow Integration
### Session Management
⚠️ **Auto-detects active session**: Checks `.workflow/.active-*` marker file
**Session storage:**
- **Active session exists**: Saves to `.workflow/WFS-[topic]/.chat/execute-[timestamp].md`
- **No active session**: Creates new session directory
### 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
### User Description Template
```bash
gemini --all-files -p "@{inferred_patterns} @{CLAUDE.md,**/*CLAUDE.md}
Implementation Task: [user_description]
Provide:
- Specific implementation code
- File modification locations (file:line)
- Test cases
- Integration guidance"
```
### Task ID Template
```bash
gemini --all-files -p "@{task_files} @{brainstorming_refs} @{CLAUDE.md,**/*CLAUDE.md}
Task: [task_title] (ID: [task-id])
Type: [task_type]
Scope: [task_scope]
Execute implementation following task acceptance criteria."
```
## Auto-Generated Outputs
### 1. Implementation Summary
**Location**: `.summaries/[TASK-ID]-summary.md` or auto-generated ID
```markdown
# Task Summary: [Task-ID] [Description]
## Implementation
- **Files Modified**: [file:line references]
- **Features Added**: [specific functionality]
- **Context Used**: [inferred patterns]
## Integration
- [Links to workflow documents]
```
### 2. Execution Session
**Location**: `.chat/execute-[timestamp].md`
```markdown
# Execution Session: [Timestamp]
## Input
[User description or Task ID]
## Context Inference
[File patterns used with rationale]
## Implementation Results
[Generated code and modifications]
## Status Updates
[Workflow integration updates]
```
## Error Handling
- **Task ID not found**: Lists available tasks
- **Pattern inference failure**: Uses generic `src/**/*` pattern
- **Execution failure**: Attempts fallback with simplified context
- **File modification errors**: Reports specific file/permission issues
## Performance Features
- **Smart caching**: Frequently used pattern mappings
- **Progressive inference**: Precise → broad pattern fallback
- **Parallel execution**: When multiple contexts needed
- **Directory optimization**: Switches to optimal execution path
## Integration Workflow
**Typical sequence:**
1. `workflow:plan` → Creates tasks
2. `/gemini:execute IMPL-001` → Executes with YOLO permissions
3. Auto-updates workflow status and generates summaries
4. `workflow:review` → Final validation
**vs. `/gemini:analyze`**: Execute performs analysis **and implementation**, analyze is read-only.

View File

@@ -1,188 +0,0 @@
---
name: auto
description: Auto-select and execute appropriate template based on user input analysis
usage: /gemini:mode:auto "description of task or problem"
argument-hint: "description of what you want to analyze or plan"
examples:
- /gemini:mode:auto "authentication system keeps crashing during login"
- /gemini:mode:auto "design a real-time notification architecture"
- /gemini:mode:auto "database connection errors in production"
- /gemini:mode:auto "plan user dashboard with analytics features"
allowed-tools: Bash(ls:*), Bash(gemini:*)
model: sonnet
---
# Auto Template Selection (/gemini:mode:auto)
## Overview
Automatically analyzes user input to select the most appropriate template and execute Gemini CLI with optimal context.
**Directory Analysis Rule**: Intelligent detection of directory context intent - automatically navigate to target directory when analysis scope is directory-specific.
**--cd Parameter Rule**: When `--cd` parameter is provided, always execute `cd "[path]" && gemini --all-files -p "prompt"` to ensure analysis occurs in the specified directory context.
**Process**: List Templates → Analyze Input → Select Template → Execute with Context
## Usage
### Auto-Detection Examples
```bash
# Bug-related keywords → selects bug-fix.md
/gemini:mode:auto "React component not rendering after state update"
# Planning keywords → selects plan.md
/gemini:mode:auto "design microservices architecture for user management"
# Error/crash keywords → selects bug-fix.md
/gemini:mode:auto "API timeout errors in production environment"
# Architecture/design keywords → selects plan.md
/gemini:mode:auto "implement real-time chat system architecture"
# With directory context
/gemini:mode:auto "authentication issues" --cd "src/auth"
```
## Template Selection Logic
### Dynamic Template Discovery
**Templates auto-discovered from**: `~/.claude/prompt-templates/`
Templates are dynamically read from the directory, including their metadata (name, description, keywords) from the YAML frontmatter.
### Template Metadata Parsing
Each template contains YAML frontmatter with:
```yaml
---
name: template-name
description: Template purpose description
category: template-category
keywords: [keyword1, keyword2, keyword3]
---
```
**Auto-selection based on:**
- **Template keywords**: Matches user input against template-defined keywords
- **Template name**: Direct name matching (e.g., "bug-fix" matches bug-related queries)
- **Template description**: Semantic matching against description text
## Command Execution
### Step 1: Template Discovery
```bash
# Dynamically discover all templates and extract YAML frontmatter
cd "~/.claude/prompt-templates" && echo "Discovering templates..." && for template_file in *.md; do echo "=== $template_file ==="; head -6 "$template_file" 2>/dev/null || echo "Error reading $template_file"; echo; done
```
### Step 2: Dynamic Template Analysis & Selection
```pseudo
FUNCTION select_template(user_input):
templates = list_directory("~/.claude/prompt-templates/")
template_metadata = {}
# Parse all templates for metadata
FOR each template_file in templates:
content = read_file(template_file)
yaml_front = extract_yaml_frontmatter(content)
template_metadata[template_file] = {
"name": yaml_front.name,
"description": yaml_front.description,
"keywords": yaml_front.keywords || [],
"category": yaml_front.category || "general"
}
input_lower = user_input.toLowerCase()
best_match = null
highest_score = 0
# Score each template against user input
FOR each template, metadata in template_metadata:
score = 0
# Keyword matching (highest weight)
FOR each keyword in metadata.keywords:
IF input_lower.contains(keyword.toLowerCase()):
score += 3
# Template name matching
IF input_lower.contains(metadata.name.toLowerCase()):
score += 2
# Description semantic matching
FOR each word in metadata.description.split():
IF input_lower.contains(word.toLowerCase()) AND word.length > 3:
score += 1
IF score > highest_score:
highest_score = score
best_match = template
# Default to first template if no matches
RETURN best_match || templates[0]
END FUNCTION
```
### Step 3: Execute with Dynamically Selected Template
```bash
# Basic execution with selected template
gemini --all-files -p "$(cat ~/.claude/prompt-templates/[selected_template])
User Input: [user_input]"
# With --cd parameter
cd "[specified_directory]" && gemini --all-files -p "$(cat ~/.claude/prompt-templates/[selected_template])
User Input: [user_input]"
```
**Template selection is completely dynamic** - any new templates added to the directory will be automatically discovered and available for selection based on their YAML frontmatter.
### Manual Template Override
```bash
# Force specific template
/gemini:mode:auto "user authentication" --template bug-fix.md
/gemini:mode:auto "fix login issues" --template plan.md
```
### Dynamic Template Listing
```bash
# List all dynamically discovered templates
/gemini:mode:auto --list-templates
# Output:
# Dynamically discovered templates in ~/.claude/prompt-templates/:
# - bug-fix.md (用于定位bug并提供修改建议) [Keywords: 规划, bug, 修改方案]
# - plan.md (软件架构规划和技术实现计划分析模板) [Keywords: 规划, 架构, 实现计划, 技术设计, 修改方案]
# - [any-new-template].md (Auto-discovered description) [Keywords: auto-parsed]
```
**Complete template discovery** - new templates are automatically detected and their metadata parsed from YAML frontmatter.
## Auto-Selection Examples
### Dynamic Selection Examples
```bash
# Selection based on template keywords and metadata
"login system crashes on startup" → Matches template with keywords: [bug, 修改方案]
"design user dashboard with analytics" → Matches template with keywords: [规划, 架构, 技术设计]
"database timeout errors in production" → Matches template with keywords: [bug, 修改方案]
"implement real-time notification system" → Matches template with keywords: [规划, 实现计划, 技术设计]
# Any new templates added will be automatically matched
"[user input]" → Dynamically matches against all template keywords and descriptions
```
## Session Integration
saves to:
`.workflow/WFS-[topic]/.chat/auto-[template]-[timestamp].md`
**Session includes:**
- Original user input
- Template selection reasoning
- Template used
- Complete analysis results
This command streamlines template usage by automatically detecting user intent and selecting the optimal template for analysis.

View File

@@ -1,76 +0,0 @@
---
name: bug-index
description: Bug analysis and fix suggestions using specialized template
usage: /gemini:mode:bug-index "bug description"
argument-hint: "description of the bug or error you're experiencing"
examples:
- /gemini:mode:bug-index "authentication null pointer error in login flow"
- /gemini:mode:bug-index "React component not re-rendering after state change"
- /gemini:mode:bug-index "database connection timeout in production"
allowed-tools: Bash(gemini:*)
model: sonnet
---
# Bug Analysis Command (/gemini:mode:bug-index)
## Overview
Systematic bug analysis and fix suggestions using expert diagnostic template.
**Directory Analysis Rule**: Intelligent detection of directory context intent - automatically navigate to target directory when analysis scope is directory-specific.
**--cd Parameter Rule**: When `--cd` parameter is provided, always execute `cd "[path]" && gemini --all-files -p "prompt"` to ensure analysis occurs in the specified directory context.
## Usage
### Basic Bug Analysis
```bash
/gemini:mode:bug-index "authentication null pointer error"
```
### Bug Analysis with Directory Context
```bash
/gemini:mode:bug-index "authentication error" --cd "src/auth"
```
### Save to Workflow Session
```bash
/gemini:mode:bug-index "API timeout issues" --save-session
```
## Command Execution
**Template Used**: `~/.claude/prompt-templates/bug-fix.md`
**Executes**:
```bash
# Basic usage
gemini --all-files -p "$(cat ~/.claude/prompt-templates/bug-fix.md)
Bug Description: [user_description]"
# With --cd parameter
cd "[specified_directory]" && gemini --all-files -p "$(cat ~/.claude/prompt-templates/bug-fix.md)
Bug Description: [user_description]"
```
## Analysis Focus
The bug-fix template provides:
- **Root Cause Analysis**: Systematic investigation
- **Code Path Tracing**: Following execution flow
- **Targeted Solutions**: Specific, minimal fixes
- **Impact Assessment**: Understanding side effects
## Session Output
saves to:
`.workflow/WFS-[topic]/.chat/bug-index-[timestamp].md`
**Includes:**
- Bug description
- Template used
- Analysis results
- Recommended actions

View File

@@ -1,140 +0,0 @@
---
name: plan-precise
description: Precise path planning analysis for complex projects
usage: /gemini:mode:plan-precise "planning topic"
examples:
- /gemini:mode:plan-precise "design authentication system"
- /gemini:mode:plan-precise "refactor database layer architecture"
---
### 🚀 Command Overview: `/gemini:mode:plan-precise`
Precise path-based planning analysis using user-specified directories instead of --all-files.
### 📝 Execution Template
```pseudo
# Precise path planning with user-specified scope
PLANNING_TOPIC = user_argument
PATHS_FILE = "./planning-paths.txt"
# Step 1: Check paths file exists
IF not file_exists(PATHS_FILE):
Write(PATHS_FILE, template_content)
echo "📝 Created planning-paths.txt in project root"
echo "Please edit file and add paths to analyze"
# USER_INPUT: User edits planning-paths.txt and presses Enter
wait_for_user_input()
ELSE:
echo "📁 Using existing planning-paths.txt"
echo "Current paths preview:"
Bash(grep -v '^#' "$PATHS_FILE" | grep -v '^$' | head -5)
# USER_INPUT: User confirms y/n
user_confirm = prompt("Continue with these paths? (y/n): ")
IF user_confirm != "y":
echo "Please edit planning-paths.txt and retry"
exit
# Step 2: Read and validate paths
paths_ref = Bash(.claude/scripts/read-paths.sh "$PATHS_FILE")
IF paths_ref is empty:
echo "❌ No valid paths found in planning-paths.txt"
echo "Please add at least one path and retry"
exit
echo "🎯 Analysis paths: $paths_ref"
echo "📋 Planning topic: $PLANNING_TOPIC"
# BASH_EXECUTION_STOPS → MODEL_ANALYSIS_BEGINS
```
### 🧠 Model Analysis Phase
After bash script prepares paths, model takes control to:
1. **Present Configuration**: Show user the detected paths and analysis scope
2. **Request Confirmation**: Wait for explicit user approval
3. **Execute Analysis**: Run gemini with precise path references
### 📋 Execution Flow
```pseudo
# Step 1: Present plan to user
PRESENT_PLAN:
📋 Precise Path Planning Configuration:
Topic: design authentication system
Paths: src/auth/**/* src/middleware/auth* tests/auth/**/* config/auth.json
Gemini Reference: $(.claude/scripts/read-paths.sh ./planning-paths.txt)
⚠️ Continue with analysis? (y/n)
# Step 2: MANDATORY user confirmation
IF user_confirms():
# Step 3: Execute gemini analysis
Bash(gemini -p "$(.claude/scripts/read-paths.sh ./planning-paths.txt) @{CLAUDE.md} $(cat ~/.claude/prompt-templates/plan.md)
Planning Topic: $PLANNING_TOPIC")
ELSE:
abort_execution()
echo "Edit planning-paths.txt and retry"
```
### ✨ Features
- **Root Level Config**: `./planning-paths.txt` in project root (no subdirectories)
- **Simple Workflow**: Check file → Present plan → Confirm → Execute
- **Path Focused**: Only analyzes user-specified paths, not entire project
- **No Complexity**: No validation, suggestions, or result saving - just core function
- **Template Creation**: Auto-creates template file if missing
### 📚 Usage Examples
```bash
# Create analysis for authentication system
/gemini:mode:plan-precise "design authentication system"
# System creates planning-paths.txt (if needed)
# User edits: src/auth/**/* tests/auth/**/* config/auth.json
# System confirms paths and executes analysis
```
### 🔍 Complete Execution Example
```bash
# 1. Command execution
$ /gemini:mode:plan-precise "design authentication system"
# 2. System output
📋 Precise Path Planning Configuration:
Topic: design authentication system
Paths: src/auth/**/* src/middleware/auth* tests/auth/**/* config/auth.json
Gemini Reference: @{src/auth/**/*,src/middleware/auth*,tests/auth/**/*,config/auth.json}
⚠️ Continue with analysis? (y/n)
# 3. User confirms
$ y
# 4. Actual gemini command executed
$ gemini -p "$(.claude/scripts/read-paths.sh ./planning-paths.txt) @{CLAUDE.md} $(cat ~/.claude/prompt-templates/plan.md)
Planning Topic: design authentication system"
```
### 🔧 Path File Format
Simple text file in project root: `./planning-paths.txt`
```
# Comments start with #
src/auth/**/*
src/middleware/auth*
tests/auth/**/*
config/auth.json
docs/auth/*.md
```

View File

@@ -1,62 +0,0 @@
---
name: plan
description: Project planning and architecture analysis using Gemini CLI with specialized template
usage: /gemini:mode:plan "planning topic"
argument-hint: "planning topic or architectural challenge to analyze"
examples:
- /gemini:mode:plan "design user dashboard feature architecture"
- /gemini:mode:plan "plan microservices migration strategy"
- /gemini:mode:plan "implement real-time notification system"
allowed-tools: Bash(gemini:*)
model: sonnet
---
# Planning Analysis Command (/gemini:mode:plan)
## Overview
**This command uses Gemini CLI for comprehensive project planning and architecture analysis.** It leverages Gemini CLI's powerful codebase analysis capabilities combined with expert planning templates to provide strategic insights and implementation roadmaps.
### Key Features
- **Gemini CLI Integration**: Utilizes Gemini CLI's deep codebase analysis for informed planning decisions
**--cd Parameter Rule**: When `--cd` parameter is provided, always execute `cd "[path]" && gemini --all-files -p "prompt"` to ensure analysis occurs in the specified directory context.
## Usage
### Basic Usage
```bash
/gemini:mode:plan "design authentication system"
```
### Directory-Specific Analysis
```bash
/gemini:mode:plan "design authentication system" --cd "src/auth"
```
## Command Execution
**Smart Directory Detection**: Auto-detects relevant directories based on topic keywords
**Executes**:
```bash
# Project-wide analysis
gemini --all-files -p "$(cat ~/.claude/prompt-templates/plan.md)
Planning Topic: [user_description]"
# Directory-specific analysis
cd "[directory]" && gemini --all-files -p "$(cat ~/.claude/prompt-templates/plan.md)
Planning Topic: [user_description]"
```
## Session Output
saves to:
`.workflow/WFS-[topic]/.chat/plan-[timestamp].md`
**Includes:**
- Planning topic
- Template used
- Analysis results
- Implementation roadmap
- Key decisions

View File

@@ -0,0 +1,816 @@
---
name: docs
description: Documentation planning and orchestration - creates structured documentation tasks for execution
argument-hint: "[path] [--tool <gemini|qwen|codex>] [--mode <full|partial>] [--cli-generate]"
---
# Documentation Workflow (/memory:docs)
## Overview
Lightweight planner that analyzes project structure, decomposes documentation work into tasks, and generates execution plans. Does NOT generate documentation content itself - delegates to doc-generator agent.
**Documentation Output**: All generated documentation is placed in `.workflow/docs/` directory with **mirrored project structure**. For example:
- Source: `src/modules/auth/index.ts` → Docs: `.workflow/docs/src/modules/auth/API.md`
- Source: `lib/core/utils.js` → Docs: `.workflow/docs/lib/core/README.md`
**Two Execution Modes**:
- **Default**: CLI analyzes in `pre_analysis` (MODE=analysis), agent writes docs in `implementation_approach`
- **--cli-generate**: CLI generates docs in `implementation_approach` (MODE=write)
## Path Mirroring Strategy
**Principle**: Documentation structure **mirrors** source code structure.
| Source Path | Documentation Path |
|------------|-------------------|
| `src/modules/auth/index.ts` | `.workflow/docs/src/modules/auth/API.md` |
| `src/modules/auth/middleware/` | `.workflow/docs/src/modules/auth/middleware/README.md` |
| `lib/core/utils.js` | `.workflow/docs/lib/core/API.md` |
| `lib/core/helpers/` | `.workflow/docs/lib/core/helpers/README.md` |
**Benefits**:
- Easy to locate documentation for any source file
- Maintains logical organization
- Clear 1:1 mapping between code and docs
- Supports any project structure (src/, lib/, packages/, etc.)
## Parameters
```bash
/memory:docs [path] [--tool <gemini|qwen|codex>] [--mode <full|partial>] [--cli-generate]
```
- **path**: Target directory (default: current directory)
- Specifies the directory to generate documentation for
- **--mode**: Documentation generation mode (default: full)
- `full`: Complete documentation (modules + project README + ARCHITECTURE + EXAMPLES)
- Level 1: Module tree documentation
- Level 2: Project README.md
- Level 3: ARCHITECTURE.md + EXAMPLES.md + HTTP API (optional)
- `partial`: Module documentation only
- Level 1: Module tree documentation (API.md + README.md)
- Skips project-level documentation
- **--tool**: CLI tool selection (default: gemini)
- `gemini`: Comprehensive documentation, pattern recognition
- `qwen`: Architecture analysis, system design focus
- `codex`: Implementation validation, code quality
- **--cli-generate**: Enable CLI-based documentation generation (optional)
- When enabled: CLI generates docs with MODE=write in implementation_approach
- When disabled (default): CLI analyzes with MODE=analysis in pre_analysis
## Planning Workflow
### Phase 1: Initialize Session
#### Step 1: Create Session and Generate Config
```bash
# Create session structure and initialize config in one step
bash(
# Parse arguments
path="${1:-.}"
tool="gemini"
mode="full"
cli_generate=false
shift
while [[ $# -gt 0 ]]; do
case "$1" in
--tool) tool="$2"; shift 2 ;;
--mode) mode="$2"; shift 2 ;;
--cli-generate) cli_generate=true; shift ;;
*) shift ;;
esac
done
# Detect paths
project_root=$(git rev-parse --show-toplevel 2>/dev/null || pwd)
if [[ "$path" == /* ]] || [[ "$path" == [A-Z]:* ]]; then
target_path="$path"
else
target_path=$(cd "$path" 2>/dev/null && pwd || echo "$PWD/$path")
fi
# Create session
timestamp=$(date +%Y%m%d-%H%M%S)
session="WFS-docs-${timestamp}"
mkdir -p ".workflow/${session}"/{.task,.process,.summaries}
touch ".workflow/.active-${session}"
# Generate single config file with all info
cat > ".workflow/${session}/.process/config.json" <<EOF
{
"session_id": "${session}",
"timestamp": "$(date -Iseconds)",
"path": "${path}",
"target_path": "${target_path}",
"project_root": "${project_root}",
"mode": "${mode}",
"tool": "${tool}",
"cli_generate": ${cli_generate}
}
EOF
echo "✓ Session initialized: ${session}"
echo "✓ Target: ${target_path}"
echo "✓ Mode: ${mode}"
echo "✓ Tool: ${tool}, CLI generate: ${cli_generate}"
)
```
**Output**:
```
✓ Session initialized: WFS-docs-20240120-143022
✓ Target: /d/Claude_dms3
✓ Mode: full
✓ Tool: gemini, CLI generate: false
```
### Phase 2: Analyze Structure
#### Step 1: Discover and Classify Folders
```bash
# Run analysis pipeline (module discovery + folder classification)
bash(~/.claude/scripts/get_modules_by_depth.sh | ~/.claude/scripts/classify-folders.sh > .workflow/WFS-docs-20240120/.process/folder-analysis.txt)
```
**Output Sample** (folder-analysis.txt):
```
./src/modules/auth|code|code:5|dirs:2
./src/modules/api|code|code:3|dirs:0
./src/utils|navigation|code:0|dirs:4
```
#### Step 2: Extract Top-Level Directories
```bash
# Group folders by top-level directory
bash(awk -F'|' '{
path = $1
gsub(/^\.\//, "", path)
split(path, parts, "/")
if (length(parts) >= 2) print parts[1] "/" parts[2]
else if (length(parts) == 1 && parts[1] != ".") print parts[1]
}' .workflow/WFS-docs-20240120/.process/folder-analysis.txt | sort -u > .workflow/WFS-docs-20240120/.process/top-level-dirs.txt)
```
**Output** (top-level-dirs.txt):
```
src/modules
src/utils
lib/core
```
#### Step 3: Generate Analysis Summary
```bash
# Calculate statistics
bash(
total=$(wc -l < .workflow/WFS-docs-20240120/.process/folder-analysis.txt)
code_count=$(grep '|code|' .workflow/WFS-docs-20240120/.process/folder-analysis.txt | wc -l)
nav_count=$(grep '|navigation|' .workflow/WFS-docs-20240120/.process/folder-analysis.txt | wc -l)
top_dirs=$(wc -l < .workflow/WFS-docs-20240120/.process/top-level-dirs.txt)
echo "📊 Folder Analysis Complete:"
echo " - Total folders: $total"
echo " - Code folders: $code_count"
echo " - Navigation folders: $nav_count"
echo " - Top-level dirs: $top_dirs"
)
# Update config with statistics
bash(jq '. + {analysis: {total: "15", code: "8", navigation: "7", top_level: "3"}}' .workflow/WFS-docs-20240120/.process/config.json > .workflow/WFS-docs-20240120/.process/config.json.tmp && mv .workflow/WFS-docs-20240120/.process/config.json.tmp .workflow/WFS-docs-20240120/.process/config.json)
```
### Phase 3: Detect Update Mode
#### Step 1: Count Existing Documentation in .workflow/docs/
```bash
# Check .workflow/docs/ directory and count existing files
bash(if [[ -d ".workflow/docs" ]]; then
find .workflow/docs -name "*.md" 2>/dev/null | wc -l
else
echo "0"
fi)
```
**Output**: `5` (existing docs in .workflow/docs/)
#### Step 2: List Existing Documentation
```bash
# List existing files in .workflow/docs/ (for task context)
bash(if [[ -d ".workflow/docs" ]]; then
find .workflow/docs -name "*.md" 2>/dev/null > .workflow/WFS-docs-20240120/.process/existing-docs.txt
else
touch .workflow/WFS-docs-20240120/.process/existing-docs.txt
fi)
```
**Output** (existing-docs.txt):
```
.workflow/docs/src/modules/auth/API.md
.workflow/docs/src/modules/auth/README.md
.workflow/docs/lib/core/README.md
.workflow/docs/README.md
```
#### Step 3: Update Config with Update Status
```bash
# Determine update status (create or update) and update config
bash(
existing_count=$(find .workflow/docs -name "*.md" 2>/dev/null | wc -l)
if [[ $existing_count -gt 0 ]]; then
jq ". + {update_mode: \"update\", existing_docs: $existing_count}" .workflow/WFS-docs-20240120/.process/config.json > .workflow/WFS-docs-20240120/.process/config.json.tmp && mv .workflow/WFS-docs-20240120/.process/config.json.tmp .workflow/WFS-docs-20240120/.process/config.json
else
jq '. + {update_mode: "create", existing_docs: 0}' .workflow/WFS-docs-20240120/.process/config.json > .workflow/WFS-docs-20240120/.process/config.json.tmp && mv .workflow/WFS-docs-20240120/.process/config.json.tmp .workflow/WFS-docs-20240120/.process/config.json
fi
)
# Display strategy summary
bash(
mode=$(jq -r '.mode' .workflow/WFS-docs-20240120/.process/config.json)
update_mode=$(jq -r '.update_mode' .workflow/WFS-docs-20240120/.process/config.json)
existing=$(jq -r '.existing_docs' .workflow/WFS-docs-20240120/.process/config.json)
tool=$(jq -r '.tool' .workflow/WFS-docs-20240120/.process/config.json)
cli_gen=$(jq -r '.cli_generate' .workflow/WFS-docs-20240120/.process/config.json)
echo "📋 Documentation Strategy:"
echo " - Path: $(jq -r '.target_path' .workflow/WFS-docs-20240120/.process/config.json)"
echo " - Mode: $mode ($([ "$mode" = "full" ] && echo "complete docs" || echo "modules only"))"
echo " - Update: $update_mode ($existing existing files)"
echo " - Tool: $tool, CLI generate: $cli_gen"
)
```
### Phase 4: Decompose Tasks
#### Task Hierarchy
```
Level 1: Module Trees (always, parallel execution)
├─ IMPL-001: Document 'src/modules/'
├─ IMPL-002: Document 'src/utils/'
└─ IMPL-003: Document 'lib/'
Level 2: Project README (mode=full only, depends on Level 1)
└─ IMPL-004: Generate Project README
Level 3: Architecture & Examples (mode=full only, depends on Level 2)
├─ IMPL-005: Generate ARCHITECTURE.md + EXAMPLES.md
└─ IMPL-006: Generate HTTP API (optional)
```
#### Step 1: Generate Level 1 Tasks (Module Trees)
```bash
# Read top-level directories and create tasks
bash(
task_count=0
while read -r top_dir; do
task_count=$((task_count + 1))
task_id=$(printf "IMPL-%03d" $task_count)
echo "Creating $task_id for '$top_dir'"
# Generate task JSON (see Task Templates section)
done < .workflow/WFS-docs-20240120/.process/top-level-dirs.txt
)
```
**Output**:
```
Creating IMPL-001 for 'src/modules'
Creating IMPL-002 for 'src/utils'
Creating IMPL-003 for 'lib'
```
#### Step 2: Generate Level 2-3 Tasks (Full Mode Only)
```bash
# Check documentation mode
bash(jq -r '.mode' .workflow/WFS-docs-20240120/.process/config.json)
# If full mode, create project-level tasks
bash(
mode=$(jq -r '.mode' .workflow/WFS-docs-20240120/.process/config.json)
if [[ "$mode" == "full" ]]; then
echo "Creating IMPL-004: Project README"
echo "Creating IMPL-005: ARCHITECTURE.md + EXAMPLES.md"
# Optional: Check for HTTP API endpoints
if grep -r "router\.|@Get\|@Post" src/ >/dev/null 2>&1; then
echo "Creating IMPL-006: HTTP API docs"
fi
else
echo "Partial mode: Skipping project-level tasks"
fi
)
```
### Phase 5: Generate Task JSONs
#### Step 1: Extract Configuration
```bash
# Read config values from JSON
bash(jq -r '.tool' .workflow/WFS-docs-20240120/.process/config.json)
bash(jq -r '.cli_generate' .workflow/WFS-docs-20240120/.process/config.json)
```
**Output**: `tool=gemini`, `cli_generate=false`
#### Step 2: Determine CLI Command Strategy
```bash
# Determine MODE and placement based on cli_generate flag
bash(
cli_generate=$(jq -r '.cli_generate' .workflow/WFS-docs-20240120/.process/config.json)
if [[ "$cli_generate" == "true" ]]; then
echo "mode=write"
echo "placement=implementation_approach"
echo "approval_flag=--approval-mode yolo"
else
echo "mode=analysis"
echo "placement=pre_analysis"
echo "approval_flag="
fi
)
```
**Output**:
```
mode=analysis
placement=pre_analysis
approval_flag=
```
#### Step 3: Build Tool-Specific Commands
```bash
# Generate command templates based on tool selection
bash(
tool=$(jq -r '.tool' .workflow/WFS-docs-20240120/.process/config.json)
if [[ "$tool" == "codex" ]]; then
echo "codex -C \${dir} --full-auto exec \"...\" --skip-git-repo-check -s danger-full-access"
else
echo "bash(cd \${dir} && ~/.claude/scripts/${tool}-wrapper ${approval_flag} -p \"...\")"
fi
)
```
## Task Templates
### Level 1: Module Tree Task
**Path Mapping**: Source `src/modules/` → Output `.workflow/docs/src/modules/`
**Default Mode (cli_generate=false)**:
```json
{
"id": "IMPL-001",
"title": "Document Module Tree: 'src/modules/'",
"status": "pending",
"meta": {
"type": "docs-tree",
"agent": "@doc-generator",
"tool": "gemini",
"cli_generate": false,
"source_path": "src/modules",
"output_path": ".workflow/docs/src/modules"
},
"context": {
"requirements": [
"Analyze source code in src/modules/",
"Generate docs to .workflow/docs/src/modules/ (mirrored structure)",
"For code folders: generate API.md + README.md",
"For navigation folders: generate README.md only"
],
"focus_paths": ["src/modules"],
"folder_analysis_file": "${session_dir}/.process/folder-analysis.txt"
},
"flow_control": {
"pre_analysis": [
{
"step": "load_existing_docs",
"command": "bash(find .workflow/docs/${top_dir} -name '*.md' 2>/dev/null | xargs cat || echo 'No existing docs')",
"output_to": "existing_module_docs"
},
{
"step": "load_folder_analysis",
"command": "bash(grep '^src/modules' ${session_dir}/.process/folder-analysis.txt)",
"output_to": "target_folders"
},
{
"step": "analyze_module_tree",
"command": "bash(cd src/modules && ~/.claude/scripts/gemini-wrapper -p \"PURPOSE: Analyze module structure\\nTASK: Generate documentation outline\\nMODE: analysis\\nCONTEXT: @{**/*} [target_folders]\\nEXPECTED: Structure outline\\nRULES: Analyze only\")",
"output_to": "tree_outline",
"note": "CLI for analysis only"
}
],
"implementation_approach": [
{
"step": 1,
"title": "Generate module tree documentation",
"description": "Analyze source folders and generate docs to .workflow/docs/ with mirrored structure",
"modification_points": [
"Parse folder types from [target_folders]",
"Parse structure from [tree_outline]",
"For src/modules/auth/ → write to .workflow/docs/src/modules/auth/",
"Generate API.md for code folders",
"Generate README.md for all folders"
],
"logic_flow": [
"Parse [target_folders] to get folder types",
"Parse [tree_outline] for structure",
"For each folder in source:",
" - Map source_path to .workflow/docs/{source_path}",
" - If type == 'code': Generate API.md + README.md",
" - Elif type == 'navigation': Generate README.md only"
],
"depends_on": [],
"output": "module_docs"
}
],
"target_files": [
".workflow/docs/${top_dir}/*/API.md",
".workflow/docs/${top_dir}/*/README.md"
]
}
}
```
**CLI Generate Mode (cli_generate=true)**:
```json
{
"id": "IMPL-001",
"title": "Document Module Tree: 'src/modules/'",
"status": "pending",
"meta": {
"type": "docs-tree",
"agent": "@doc-generator",
"tool": "gemini",
"cli_generate": true,
"source_path": "src/modules",
"output_path": ".workflow/docs/src/modules"
},
"context": {
"requirements": [
"Analyze source code in src/modules/",
"Generate docs to .workflow/docs/src/modules/ (mirrored structure)",
"CLI generates documentation files directly"
],
"focus_paths": ["src/modules"]
},
"flow_control": {
"pre_analysis": [
{
"step": "load_existing_docs",
"command": "bash(find .workflow/docs/${top_dir} -name '*.md' 2>/dev/null | xargs cat || echo 'No existing docs')",
"output_to": "existing_module_docs"
},
{
"step": "load_folder_analysis",
"command": "bash(grep '^src/modules' ${session_dir}/.process/folder-analysis.txt)",
"output_to": "target_folders"
}
],
"implementation_approach": [
{
"step": 1,
"title": "Parse folder analysis",
"description": "Parse [target_folders] to get folder types and structure",
"modification_points": ["Extract folder types", "Identify code vs navigation folders"],
"logic_flow": ["Parse [target_folders] to get folder types", "Prepare folder list for CLI generation"],
"depends_on": [],
"output": "folder_types"
},
{
"step": 2,
"title": "Generate documentation via CLI",
"description": "Call CLI to generate docs to .workflow/docs/ with mirrored structure using MODE=write",
"modification_points": [
"Execute CLI generation command",
"Generate files to .workflow/docs/src/modules/ (mirrored path)",
"Generate API.md and README.md files"
],
"logic_flow": [
"CLI analyzes source code in src/modules/",
"CLI writes documentation to .workflow/docs/src/modules/",
"Maintains directory structure mirroring"
],
"command": "bash(cd src/modules && ~/.claude/scripts/gemini-wrapper --approval-mode yolo -p \"PURPOSE: Generate module docs\\nTASK: Create documentation files in .workflow/docs/src/modules/\\nMODE: write\\nCONTEXT: @{**/*} [target_folders] [existing_module_docs]\\nEXPECTED: API.md and README.md in .workflow/docs/src/modules/\\nRULES: Mirror source structure, generate complete docs\")",
"depends_on": [1],
"output": "generated_docs"
}
],
"target_files": [
".workflow/docs/${top_dir}/*/API.md",
".workflow/docs/${top_dir}/*/README.md"
]
}
}
```
### Level 2: Project README Task
**Default Mode**:
```json
{
"id": "IMPL-004",
"title": "Generate Project README",
"status": "pending",
"depends_on": ["IMPL-001", "IMPL-002", "IMPL-003"],
"meta": {
"type": "docs",
"agent": "@doc-generator",
"tool": "gemini",
"cli_generate": false
},
"flow_control": {
"pre_analysis": [
{
"step": "load_existing_readme",
"command": "bash(cat .workflow/docs/README.md 2>/dev/null || echo 'No existing README')",
"output_to": "existing_readme"
},
{
"step": "load_module_docs",
"command": "bash(find .workflow/docs -type f -name '*.md' ! -path '.workflow/docs/README.md' ! -path '.workflow/docs/ARCHITECTURE.md' ! -path '.workflow/docs/EXAMPLES.md' ! -path '.workflow/docs/api/*' | xargs cat)",
"output_to": "all_module_docs",
"note": "Load all module docs from mirrored structure"
},
{
"step": "analyze_project",
"command": "bash(~/.claude/scripts/gemini-wrapper -p \"PURPOSE: Analyze project structure\\nTASK: Extract overview from modules\\nMODE: analysis\\nCONTEXT: [all_module_docs]\\nEXPECTED: Project outline\")",
"output_to": "project_outline"
}
],
"implementation_approach": [
{
"step": 1,
"title": "Generate project README",
"description": "Generate project README with navigation links while preserving existing user modifications",
"modification_points": ["Parse [project_outline] and [all_module_docs]", "Generate project README structure", "Add navigation links to modules", "Preserve [existing_readme] user modifications"],
"logic_flow": ["Parse [project_outline] and [all_module_docs]", "Generate project README with navigation links", "Preserve [existing_readme] user modifications"],
"depends_on": [],
"output": "project_readme"
}
],
"target_files": [".workflow/docs/README.md"]
}
}
```
### Level 3: Architecture & Examples Documentation Task
**Default Mode**:
```json
{
"id": "IMPL-005",
"title": "Generate Architecture & Examples Documentation",
"status": "pending",
"depends_on": ["IMPL-004"],
"meta": {
"type": "docs",
"agent": "@doc-generator",
"tool": "gemini",
"cli_generate": false
},
"flow_control": {
"pre_analysis": [
{
"step": "load_existing_docs",
"command": "bash(cat .workflow/docs/ARCHITECTURE.md 2>/dev/null || echo 'No existing ARCHITECTURE'; echo '---SEPARATOR---'; cat .workflow/docs/EXAMPLES.md 2>/dev/null || echo 'No existing EXAMPLES')",
"output_to": "existing_arch_examples"
},
{
"step": "load_all_docs",
"command": "bash(cat .workflow/docs/README.md && find .workflow/docs -type f -name '*.md' ! -path '.workflow/docs/README.md' ! -path '.workflow/docs/ARCHITECTURE.md' ! -path '.workflow/docs/EXAMPLES.md' ! -path '.workflow/docs/api/*' | xargs cat)",
"output_to": "all_docs",
"note": "Load README + all module docs from mirrored structure"
},
{
"step": "analyze_architecture_and_examples",
"command": "bash(~/.claude/scripts/gemini-wrapper -p \"PURPOSE: Analyze system architecture and generate examples\\nTASK: Synthesize architectural overview and usage patterns\\nMODE: analysis\\nCONTEXT: [all_docs]\\nEXPECTED: Architecture outline + Examples outline\")",
"output_to": "arch_examples_outline"
}
],
"implementation_approach": [
{
"step": 1,
"title": "Generate architecture and examples documentation",
"description": "Generate ARCHITECTURE.md and EXAMPLES.md while preserving existing user modifications",
"modification_points": [
"Parse [arch_examples_outline] and [all_docs]",
"Generate ARCHITECTURE.md structure with system design and patterns",
"Generate EXAMPLES.md structure with code snippets and usage examples",
"Preserve [existing_arch_examples] user modifications"
],
"logic_flow": [
"Parse [arch_examples_outline] and [all_docs]",
"Generate ARCHITECTURE.md with system design",
"Generate EXAMPLES.md with code snippets",
"Preserve [existing_arch_examples] modifications"
],
"depends_on": [],
"output": "arch_examples_docs"
}
],
"target_files": [
".workflow/docs/ARCHITECTURE.md",
".workflow/docs/EXAMPLES.md"
]
}
}
```
### Level 3: HTTP API Documentation Task (Optional)
**Default Mode**:
```json
{
"id": "IMPL-006",
"title": "Generate HTTP API Documentation",
"status": "pending",
"depends_on": ["IMPL-004"],
"meta": {
"type": "docs",
"agent": "@doc-generator",
"tool": "gemini",
"cli_generate": false
},
"flow_control": {
"pre_analysis": [
{
"step": "discover_api_endpoints",
"command": "mcp__code-index__search_code_advanced(pattern='router\\.|@(Get|Post)', file_pattern='*.{ts,js}')",
"output_to": "endpoint_discovery"
},
{
"step": "load_existing_api_docs",
"command": "bash(cat .workflow/docs/api/README.md 2>/dev/null || echo 'No existing API docs')",
"output_to": "existing_api_docs"
},
{
"step": "analyze_api",
"command": "bash(~/.claude/scripts/gemini-wrapper -p \"PURPOSE: Document HTTP API\\nTASK: Analyze API endpoints\\nMODE: analysis\\nCONTEXT: @{src/api/**/*} [endpoint_discovery]\\nEXPECTED: API outline\")",
"output_to": "api_outline"
}
],
"implementation_approach": [
{
"step": 1,
"title": "Generate HTTP API documentation",
"description": "Generate HTTP API documentation while preserving existing user modifications",
"modification_points": ["Parse [api_outline] and [endpoint_discovery]", "Generate HTTP API documentation", "Document endpoints and request/response formats", "Preserve [existing_api_docs] modifications"],
"logic_flow": ["Parse [api_outline] and [endpoint_discovery]", "Generate HTTP API documentation", "Preserve [existing_api_docs] modifications"],
"depends_on": [],
"output": "api_docs"
}
],
"target_files": [".workflow/docs/api/README.md"]
}
}
```
## Session Structure
```
.workflow/
├── .active-WFS-docs-20240120-143022 # Active session marker
└── WFS-docs-20240120-143022/
├── IMPL_PLAN.md # Implementation plan
├── TODO_LIST.md # Progress tracker
├── .process/
│ ├── config.json # Single config (all settings + stats)
│ ├── folder-analysis.txt # Folder classification results
│ ├── top-level-dirs.txt # Top-level directory list
│ └── existing-docs.txt # Existing documentation paths
└── .task/
├── IMPL-001.json # Module tree task
├── IMPL-002.json # Module tree task
├── IMPL-003.json # Module tree task
├── IMPL-004.json # Project README (full mode)
├── IMPL-005.json # ARCHITECTURE.md + EXAMPLES.md (full mode)
└── IMPL-006.json # HTTP API docs (optional)
```
**Config File Structure** (config.json):
```json
{
"session_id": "WFS-docs-20240120-143022",
"timestamp": "2024-01-20T14:30:22+08:00",
"path": ".",
"target_path": "/d/Claude_dms3",
"project_root": "/d/Claude_dms3",
"mode": "full",
"tool": "gemini",
"cli_generate": false,
"update_mode": "update",
"existing_docs": 5,
"analysis": {
"total": "15",
"code": "8",
"navigation": "7",
"top_level": "3"
}
}
```
## Generated Documentation
**Structure mirrors project source directories**:
```
.workflow/docs/
├── src/ # Mirrors src/ directory
│ ├── modules/ # Level 1 output
│ │ ├── README.md # Navigation for src/modules/
│ │ ├── auth/
│ │ │ ├── API.md # Auth module API signatures
│ │ │ ├── README.md # Auth module documentation
│ │ │ └── middleware/
│ │ │ ├── API.md # Middleware API
│ │ │ └── README.md # Middleware docs
│ │ └── api/
│ │ ├── API.md # API module signatures
│ │ └── README.md # API module docs
│ └── utils/ # Level 1 output
│ └── README.md # Utils navigation
├── lib/ # Mirrors lib/ directory
│ └── core/
│ ├── API.md
│ └── README.md
├── README.md # Level 2 output (root only)
├── ARCHITECTURE.md # Level 3 output (root only)
├── EXAMPLES.md # Level 3 output (root only)
└── api/ # Level 3 output (optional)
└── README.md # HTTP API reference
```
## Execution Commands
```bash
# Execute entire workflow (auto-discovers active session)
/workflow:execute
# Or specify session
/workflow:execute --resume-session="WFS-docs-yyyymmdd-hhmmss"
# Individual task execution (if needed)
/task:execute IMPL-001
```
## Simple Bash Commands
### Session Management
```bash
# Create session and initialize config (all in one)
bash(
session="WFS-docs-$(date +%Y%m%d-%H%M%S)"
mkdir -p ".workflow/${session}"/{.task,.process,.summaries}
touch ".workflow/.active-${session}"
cat > ".workflow/${session}/.process/config.json" <<EOF
{"session_id":"${session}","timestamp":"$(date -Iseconds)","path":".","mode":"full","tool":"gemini","cli_generate":false}
EOF
echo "Session: ${session}"
)
# Read session config
bash(cat .workflow/WFS-docs-20240120/.process/config.json)
# Extract config values
bash(jq -r '.tool' .workflow/WFS-docs-20240120/.process/config.json)
bash(jq -r '.mode' .workflow/WFS-docs-20240120/.process/config.json)
# List session tasks
bash(ls .workflow/WFS-docs-20240120/.task/*.json)
```
### Analysis Commands
```bash
# Discover and classify folders (scans project source)
bash(~/.claude/scripts/get_modules_by_depth.sh | ~/.claude/scripts/classify-folders.sh)
# Count existing docs (in .workflow/docs/ directory)
bash(if [[ -d ".workflow/docs" ]]; then find .workflow/docs -name "*.md" 2>/dev/null | wc -l; else echo "0"; fi)
# List existing documentation (in .workflow/docs/ directory)
bash(if [[ -d ".workflow/docs" ]]; then find .workflow/docs -name "*.md" 2>/dev/null; fi)
```
## Template Reference
**Available Templates**:
- `api.txt`: Unified template for Code API (Part A) and HTTP API (Part B)
- `module-readme.txt`: Module purpose, usage, dependencies
- `folder-navigation.txt`: Navigation README for folders with subdirectories
- `project-readme.txt`: Project overview, getting started, module navigation
- `project-architecture.txt`: System structure, module map, design patterns
- `project-examples.txt`: End-to-end usage examples
**Template Location**: `~/.claude/workflows/cli-templates/prompts/documentation/`
## CLI Generate Mode Summary
| Mode | CLI Placement | CLI MODE | Agent Role |
|------|---------------|----------|------------|
| **Default** | pre_analysis | analysis | Generates documentation files |
| **--cli-generate** | implementation_approach | write | Validates and coordinates CLI output |
## Related Commands
- `/workflow:execute` - Execute documentation tasks
- `/workflow:status` - View task progress
- `/workflow:session:complete` - Mark session complete

View File

@@ -0,0 +1,240 @@
---
name: load
description: Load project memory by delegating to agent, returns structured core content package for subsequent operations
argument-hint: "[--tool gemini|qwen] \"task context description\""
allowed-tools: Task(*), Bash(*)
examples:
- /memory:load "在当前前端基础上开发用户认证功能"
- /memory:load --tool qwen "重构支付模块API"
---
# Memory Load Command (/memory:load)
## 1. Overview
The `memory:load` command **delegates to a general-purpose agent** to analyze the project and return a structured "Core Content Pack". This pack is loaded into the main thread's memory, providing essential context for subsequent agent operations while minimizing token consumption.
**Core Philosophy**:
- **Agent-Driven**: Fully delegates execution to general-purpose agent
- **Read-Only Analysis**: Does not modify code, only extracts context
- **Structured Output**: Returns standardized JSON content package
- **Memory Optimization**: Package loaded directly into main thread memory
- **Token Efficiency**: CLI analysis executed within agent to save tokens
## 2. Parameters
- `"task context description"` (Required): Task description to guide context extraction
- Example: "在当前前端基础上开发用户认证功能"
- Example: "重构支付模块API"
- Example: "修复数据库查询性能问题"
- `--tool <gemini|qwen>` (Optional): Specify CLI tool for agent to use (default: gemini)
- gemini: Large context window, suitable for complex project analysis
- qwen: Alternative to Gemini with similar capabilities
## 3. Agent-Driven Execution Flow
The command fully delegates to **general-purpose agent**, which autonomously:
1. **Analyzes Project Structure**: Executes `get_modules_by_depth.sh` to understand architecture
2. **Loads Documentation**: Reads CLAUDE.md, README.md and other key docs
3. **Extracts Keywords**: Derives core keywords from task description
4. **Discovers Files**: Uses MCP code-index or rg/find to locate relevant files
5. **CLI Deep Analysis**: Executes Gemini/Qwen CLI for deep context analysis
6. **Generates Content Package**: Returns structured JSON core content package
## 4. Core Content Package Structure
**Output Format** - Loaded into main thread memory for subsequent use:
```json
{
"task_context": "在当前前端基础上开发用户认证功能",
"keywords": ["前端", "用户", "认证", "auth", "login"],
"project_summary": {
"architecture": "TypeScript + React frontend with Vite build system",
"tech_stack": ["React", "TypeScript", "Vite", "TailwindCSS"],
"key_patterns": [
"State management via Context API",
"Functional components with Hooks pattern",
"API calls encapsulated in custom hooks"
]
},
"relevant_files": [
{
"path": "src/components/Auth/LoginForm.tsx",
"relevance": "Existing login form component",
"priority": "high"
},
{
"path": "src/contexts/AuthContext.tsx",
"relevance": "Authentication state management context",
"priority": "high"
},
{
"path": "CLAUDE.md",
"relevance": "Project development standards",
"priority": "high"
}
],
"integration_points": [
"Must integrate with existing AuthContext",
"Follow component organization pattern: src/components/[Feature]/",
"API calls should use src/hooks/useApi.ts wrapper"
],
"constraints": [
"Maintain backward compatibility",
"Follow TypeScript strict mode",
"Use existing UI component library"
]
}
```
## 5. Agent Invocation
```javascript
Task(
subagent_type="general-purpose",
description="Load project memory: ${task_description}",
prompt=`
## Mission: Load Project Memory Context
**Task Context**: "${task_description}"
**Mode**: Read-only analysis
**Tool**: ${tool || 'gemini'}
## Execution Steps
### Step 1: Foundation Analysis
1. **Project Structure**
\`\`\`bash
bash(~/.claude/scripts/get_modules_by_depth.sh)
\`\`\`
2. **Core Documentation**
\`\`\`javascript
Read(CLAUDE.md)
Read(README.md)
\`\`\`
### Step 2: Keyword Extraction & File Discovery
1. Extract core keywords from task description
2. Discover relevant files using MCP code-index or rg:
\`\`\`javascript
// Prefer MCP tools
mcp__code-index__find_files(pattern="*{keyword}*")
mcp__code-index__search_code_advanced(pattern="{keyword}", context_lines=2)
// Fallback: use rg
bash(rg -l "{keyword}" --type ts --type md)
\`\`\`
### Step 3: Deep Analysis via CLI
Execute Gemini/Qwen CLI for deep analysis (saves main thread tokens):
\`\`\`bash
cd . && ~/.claude/scripts/${tool}-wrapper -p "
PURPOSE: Extract project core context for task: ${task_description}
TASK: Analyze project architecture, tech stack, key patterns, relevant files
MODE: analysis
CONTEXT: @{CLAUDE.md,README.md,${discovered_files}}
EXPECTED: Structured project summary and integration point analysis
RULES:
- Focus on task-relevant core information
- Identify key architecture patterns and technical constraints
- Extract integration points and development standards
- Output concise, structured format
"
\`\`\`
### Step 4: Generate Core Content Package
Generate structured JSON content package (format shown above)
**Required Fields**:
- task_context: Original task description
- keywords: Extracted keyword array
- project_summary: Architecture, tech stack, key patterns
- relevant_files: File list with path, relevance, priority
- integration_points: Integration guidance
- constraints: Development constraints
### Step 5: Return Content Package
Return JSON content package as final output for main thread to load into memory.
## Quality Checklist
Before returning:
- [ ] Valid JSON format
- [ ] All required fields complete
- [ ] relevant_files contains 3-10 files minimum
- [ ] project_summary accurately reflects architecture
- [ ] integration_points clearly specify integration paths
- [ ] keywords accurately extracted (3-8 keywords)
- [ ] Content concise, avoiding redundancy (< 5KB total)
`
)
```
## 6. Usage Examples
### Example 1: Load Context for New Feature
```bash
/memory:load "在当前前端基础上开发用户认证功能"
```
**Agent Execution**:
1. Analyzes project structure (`get_modules_by_depth.sh`)
2. Reads CLAUDE.md, README.md
3. Extracts keywords: ["前端", "用户", "认证", "auth"]
4. Uses MCP to search relevant files
5. Executes Gemini CLI for deep analysis
6. Returns core content package
**Returned Package** (loaded into memory):
```json
{
"task_context": "在当前前端基础上开发用户认证功能",
"keywords": ["前端", "认证", "auth", "login"],
"project_summary": { ... },
"relevant_files": [ ... ],
"integration_points": [ ... ],
"constraints": [ ... ]
}
```
### Example 2: Using Qwen Tool
```bash
/memory:load --tool qwen "重构支付模块API"
```
Agent uses Qwen CLI for analysis, returns same structured package.
### Example 3: Bug Fix Context
```bash
/memory:load "修复登录验证错误"
```
Returns core context related to login validation, including test files and validation logic.
### Memory Persistence
- **Session-Scoped**: Content package valid for current session
- **Subsequent Reference**: All subsequent agents/commands can access
- **Reload Required**: New sessions need to re-execute /memory:load
## 8. Notes
- **Read-Only**: Does not modify any code, pure analysis
- **Token Optimization**: CLI analysis executed within agent, saves main thread tokens
- **Memory Loading**: Returned JSON loaded directly into main thread memory
- **Subsequent Use**: Other commands/agents can reference this package for development
- **Session-Level**: Content package valid for current session

View File

@@ -0,0 +1,330 @@
---
name: update-full
description: Complete project-wide CLAUDE.md documentation update
argument-hint: "[--tool gemini|qwen|codex] [--path <directory>]"
---
# Full Documentation Update (/memory:update-full)
## Coordinator Role
**This command orchestrates project-wide CLAUDE.md updates** using depth-parallel execution strategy with intelligent complexity detection.
**Execution Model**:
1. **Initial Analysis**: Cache git changes, discover module structure
2. **Complexity Detection**: Analyze module count, determine strategy
3. **Plan Presentation**: Show user exactly what will be updated
4. **Depth-Parallel Execution**: Update modules by depth (highest to lowest)
5. **Safety Verification**: Ensure only CLAUDE.md files modified
**Tool Selection**:
- `--tool gemini` (default): Documentation generation, pattern recognition
- `--tool qwen`: Architecture analysis, system design docs
- `--tool codex`: Implementation validation, code quality analysis
**Path Parameter**:
- `--path <directory>` (optional): Target specific directory for updates
- If not specified: Updates entire project from current directory
- If specified: Changes to target directory before discovery
## Core Rules
1. **Analyze First**: Run git cache and module discovery before any updates
2. **Scope Control**: Use --path to target specific directories, default is entire project
3. **Wait for Approval**: Present plan, no execution without user confirmation
4. **Depth-Parallel**: Same depth runs parallel (max 4 jobs), different depths sequential
5. **Safety Check**: Verify only CLAUDE.md files modified, revert if source files touched
6. **Independent Commands**: Each update is a separate bash() call
7. **No Background Bash Tool**: Never use `run_in_background` parameter in bash() calls; use shell `&` for parallelism
## Execution Workflow
### Phase 1: Discovery & Analysis
**Cache git changes:**
```bash
bash(git add -A 2>/dev/null || true)
```
**Get module structure:**
*If no --path parameter:*
```bash
bash(~/.claude/scripts/get_modules_by_depth.sh list)
```
*If --path parameter specified:*
```bash
bash(cd <target-path> && ~/.claude/scripts/get_modules_by_depth.sh list)
```
**Example with path:**
```bash
# Update only .claude directory
bash(cd .claude && ~/.claude/scripts/get_modules_by_depth.sh list)
# Update specific feature directory
bash(cd src/features/auth && ~/.claude/scripts/get_modules_by_depth.sh list)
```
**Parse Output**:
- Extract module paths from `depth:N|path:<PATH>|...` format
- Count total modules
- Identify which modules have/need CLAUDE.md
**Example output:**
```
depth:5|path:./.claude/workflows/cli-templates/prompts/analysis|files:5|has_claude:no
depth:4|path:./.claude/commands/cli/mode|files:3|has_claude:no
depth:3|path:./.claude/commands/cli|files:6|has_claude:no
depth:0|path:.|files:14|has_claude:yes
```
**Validation**:
- If --path specified, directory exists and is accessible
- Module list contains depth and path information
- At least one module exists
- All paths are relative to target directory (if --path used)
---
### Phase 2: Plan Presentation
**Decision Logic**:
- **Simple projects (≤20 modules)**: Present plan to user, wait for approval
- **Complex projects (>20 modules)**: Delegate to memory-bridge agent
**Plan format:**
```
📋 Update Plan:
Tool: gemini
Total modules: 31
NEW CLAUDE.md files (30):
- ./.claude/workflows/cli-templates/prompts/analysis/CLAUDE.md
- ./.claude/commands/cli/mode/CLAUDE.md
- ... (28 more)
UPDATE existing CLAUDE.md files (1):
- ./CLAUDE.md
⚠️ Confirm execution? (y/n)
```
**User Confirmation Required**: No execution without explicit approval
---
### Phase 3: Depth-Parallel Execution
**Pattern**: Process highest depth first, parallel within depth, sequential across depths.
**Command structure:**
```bash
bash(cd <module-path> && ~/.claude/scripts/update_module_claude.sh "." "full" "<tool>" &)
```
**Example - Depth 5 (8 modules):**
```bash
bash(cd ./.claude/workflows/cli-templates/prompts/analysis && ~/.claude/scripts/update_module_claude.sh "." "full" "gemini" &)
```
```bash
bash(cd ./.claude/workflows/cli-templates/prompts/development && ~/.claude/scripts/update_module_claude.sh "." "full" "gemini" &)
```
```bash
bash(cd ./.claude/workflows/cli-templates/prompts/documentation && ~/.claude/scripts/update_module_claude.sh "." "full" "gemini" &)
```
```bash
bash(cd ./.claude/workflows/cli-templates/prompts/implementation && ~/.claude/scripts/update_module_claude.sh "." "full" "gemini" &)
```
*Wait for depth 5 completion...*
**Example - Depth 4 (7 modules):**
```bash
bash(cd ./.claude/commands/cli/mode && ~/.claude/scripts/update_module_claude.sh "." "full" "gemini" &)
```
```bash
bash(cd ./.claude/commands/workflow/brainstorm && ~/.claude/scripts/update_module_claude.sh "." "full" "gemini" &)
```
*Continue for remaining depths (3 → 2 → 1 → 0)...*
**Execution Rules**:
- Each command is separate bash() call
- Up to 4 concurrent jobs per depth
- Wait for all jobs in current depth before proceeding
- Extract path from `depth:N|path:<PATH>|...` format
- All paths relative to target directory (current dir or --path value)
**Path Context**:
- Without --path: Paths relative to current directory
- With --path: Paths relative to specified target directory
- Module discovery runs in target directory context
---
### Phase 4: Safety Verification
**Check modified files:**
```bash
bash(git diff --cached --name-only | grep -v "CLAUDE.md" || echo "✅ Only CLAUDE.md files modified")
```
**Expected output:**
```
✅ Only CLAUDE.md files modified
```
**If non-CLAUDE.md files detected:**
```
⚠️ Warning: Non-CLAUDE.md files were modified
Modified files: src/index.ts, package.json
→ Run: git restore --staged .
```
**Display final status:**
```bash
bash(git status --short)
```
**Example output:**
```
A .claude/workflows/cli-templates/prompts/analysis/CLAUDE.md
A .claude/commands/cli/mode/CLAUDE.md
M CLAUDE.md
... (30 more files)
```
## Command Pattern Reference
**Single module update:**
```bash
bash(cd <module-path> && ~/.claude/scripts/update_module_claude.sh "." "full" "<tool>" &)
```
**Components**:
- `cd <module-path>` - Navigate to module (from `path:` field)
- `&&` - Ensure cd succeeds
- `update_module_claude.sh` - Update script
- `"."` - Current directory
- `"full"` - Full update mode
- `"<tool>"` - gemini/qwen/codex
- `&` - Background execution
**Path extraction:**
```bash
# From: depth:5|path:./src/auth|files:10|has_claude:no
# Extract: ./src/auth
# Command: bash(cd ./src/auth && ~/.claude/scripts/update_module_claude.sh "." "full" "gemini" &)
```
## Complex Projects Strategy
For projects >20 modules, delegate to memory-bridge agent:
```javascript
Task(
subagent_type="memory-bridge",
description="Complex project full update",
prompt=`
CONTEXT:
- Total modules: ${module_count}
- Tool: ${tool}
- Mode: full
MODULE LIST:
${modules_output}
REQUIREMENTS:
1. Use TodoWrite to track each depth level
2. Process depths N→0 sequentially, max 4 parallel per depth
3. Command: cd "<path>" && update_module_claude.sh "." "full" "${tool}" &
4. Extract path from "depth:N|path:<PATH>|..." format
5. Verify all modules processed
6. Run safety check
7. Display git status
`
)
```
## Error Handling
- **Invalid path parameter**: Report error if --path directory doesn't exist, abort execution
- **Module discovery failure**: Report error, abort execution
- **User declines approval**: Abort execution, no changes made
- **Safety check failure**: Automatic staging revert, report modified files
- **Update script failure**: Report failed modules, continue with remaining
## Coordinator Checklist
✅ Parse `--tool` parameter (default: gemini)
✅ Parse `--path` parameter (optional, default: current directory)
✅ Execute git cache in current directory
✅ Execute module discovery (with cd if --path specified)
✅ Parse module list, count total modules
✅ Determine strategy based on module count (≤20 vs >20)
✅ Present plan with exact file paths
**Wait for user confirmation** (simple projects only)
✅ Organize modules by depth
✅ For each depth (highest to lowest):
- Launch up to 5 parallel updates
- Wait for depth completion
- Proceed to next depth
✅ Run safety check after all updates
✅ Display git status
✅ Report completion summary
## Tool Parameter Reference
**Gemini** (default):
- Best for: Documentation generation, pattern recognition, architecture review
- Context window: Large, handles complex codebases
- Output style: Comprehensive, detailed explanations
**Qwen**:
- Best for: Architecture analysis, system design documentation
- Context window: Large, similar to Gemini
- Output style: Structured, systematic analysis
**Codex**:
- Best for: Implementation validation, code quality analysis
- Capabilities: Mathematical reasoning, autonomous development
- Output style: Technical, implementation-focused
## Path Parameter Reference
**Use Cases**:
**Update configuration directory only:**
```bash
/memory:update-full --path .claude
```
- Updates only .claude directory and subdirectories
- Useful after workflow or command modifications
- Faster than full project update
**Update specific feature module:**
```bash
/memory:update-full --path src/features/auth
```
- Updates authentication feature and sub-modules
- Ideal for feature-specific documentation
- Isolates scope for targeted updates
**Update nested structure:**
```bash
/memory:update-full --path .claude/workflows/cli-templates
```
- Updates deeply nested directory tree
- Maintains relative path structure in output
- All module paths relative to specified directory
**Best Practices**:
- Use `--path` when working on specific features/modules
- Omit `--path` for project-wide architectural changes
- Combine with `--tool` for specialized documentation needs
- Verify directory exists before execution (automatic validation)

View File

@@ -0,0 +1,306 @@
---
name: update-related
description: Context-aware CLAUDE.md documentation updates based on recent changes
argument-hint: "[--tool gemini|qwen|codex]"
---
# Related Documentation Update (/memory:update-related)
## Coordinator Role
**This command orchestrates context-aware CLAUDE.md updates** for modules affected by recent changes using intelligent change detection.
**Execution Model**:
1. **Change Detection**: Analyze git changes to identify affected modules
2. **Complexity Analysis**: Evaluate change count and determine strategy
3. **Plan Presentation**: Show user which modules need updates
4. **Depth-Parallel Execution**: Update affected modules by depth (highest to lowest)
5. **Safety Verification**: Ensure only CLAUDE.md files modified
**Tool Selection**:
- `--tool gemini` (default): Documentation generation, pattern recognition
- `--tool qwen`: Architecture analysis, system design docs
- `--tool codex`: Implementation validation, code quality analysis
## Core Rules
1. **Detect Changes First**: Use git diff to identify affected modules before updates
2. **Wait for Approval**: Present plan, no execution without user confirmation
3. **Related Mode**: Update only changed modules and their parent contexts
4. **Depth-Parallel**: Same depth runs parallel (max 4 jobs), different depths sequential
5. **Safety Check**: Verify only CLAUDE.md files modified, revert if source files touched
6. **No Background Bash Tool**: Never use `run_in_background` parameter in bash() calls; use shell `&` for parallelism
## Execution Workflow
### Phase 1: Change Detection & Analysis
**Refresh code index:**
```bash
bash(mcp__code-index__refresh_index)
```
**Detect changed modules:**
```bash
bash(~/.claude/scripts/detect_changed_modules.sh list)
```
**Cache git changes:**
```bash
bash(git add -A 2>/dev/null || true)
```
**Parse Output**:
- Extract changed module paths from `depth:N|path:<PATH>|...` format
- Count affected modules
- Identify which modules have/need CLAUDE.md updates
**Example output:**
```
depth:3|path:./src/api/auth|files:5|types:[ts]|has_claude:no|change:new
depth:2|path:./src/api|files:12|types:[ts]|has_claude:yes|change:modified
depth:1|path:./src|files:8|types:[ts]|has_claude:yes|change:parent
depth:0|path:.|files:14|has_claude:yes|change:parent
```
**Fallback behavior**:
- If no git changes detected, use recent modules (first 10 by depth)
**Validation**:
- Changed module list contains valid paths
- At least one affected module exists
---
### Phase 2: Plan Presentation
**Decision Logic**:
- **Simple changes (≤15 modules)**: Present plan to user, wait for approval
- **Complex changes (>15 modules)**: Delegate to memory-bridge agent
**Plan format:**
```
📋 Related Update Plan:
Tool: gemini
Changed modules: 4
NEW CLAUDE.md files (1):
- ./src/api/auth/CLAUDE.md [new module]
UPDATE existing CLAUDE.md files (3):
- ./src/api/CLAUDE.md [parent of changed auth/]
- ./src/CLAUDE.md [parent context]
- ./CLAUDE.md [root level]
⚠️ Confirm execution? (y/n)
```
**User Confirmation Required**: No execution without explicit approval
---
### Phase 3: Depth-Parallel Execution
**Pattern**: Process highest depth first, parallel within depth, sequential across depths.
**Command structure:**
```bash
bash(cd <module-path> && ~/.claude/scripts/update_module_claude.sh "." "related" "<tool>" &)
```
**Example - Depth 3 (new module):**
```bash
bash(cd ./src/api/auth && ~/.claude/scripts/update_module_claude.sh "." "related" "gemini" &)
```
*Wait for depth 3 completion...*
**Example - Depth 2 (modified parent):**
```bash
bash(cd ./src/api && ~/.claude/scripts/update_module_claude.sh "." "related" "gemini" &)
```
*Wait for depth 2 completion...*
**Example - Depth 1 & 0 (parent contexts):**
```bash
bash(cd ./src && ~/.claude/scripts/update_module_claude.sh "." "related" "gemini" &)
```
```bash
bash(cd . && ~/.claude/scripts/update_module_claude.sh "." "related" "gemini" &)
```
*Wait for all depths completion...*
**Execution Rules**:
- Each command is separate bash() call
- Up to 4 concurrent jobs per depth
- Wait for all jobs in current depth before proceeding
- Use "related" mode (not "full") for context-aware updates
- Extract path from `depth:N|path:<PATH>|...` format
**Related Mode Behavior**:
- Updates module based on recent git changes
- Includes parent context for better documentation coherence
- More efficient than full updates for iterative development
---
### Phase 4: Safety Verification
**Check modified files:**
```bash
bash(git diff --cached --name-only | grep -v "CLAUDE.md" || echo "✅ Only CLAUDE.md files modified")
```
**Expected output:**
```
✅ Only CLAUDE.md files modified
```
**If non-CLAUDE.md files detected:**
```
⚠️ Warning: Non-CLAUDE.md files were modified
Modified files: src/api/auth/index.ts, package.json
→ Run: git restore --staged .
```
**Display final statistics:**
```bash
bash(git diff --stat)
```
**Example output:**
```
.claude/workflows/cli-templates/prompts/analysis/CLAUDE.md | 45 +++++++++++++++++++++
src/api/CLAUDE.md | 23 +++++++++--
src/CLAUDE.md | 12 ++++--
CLAUDE.md | 8 ++--
4 files changed, 82 insertions(+), 6 deletions(-)
```
## Command Pattern Reference
**Single module update:**
```bash
bash(cd <module-path> && ~/.claude/scripts/update_module_claude.sh "." "related" "<tool>" &)
```
**Components**:
- `cd <module-path>` - Navigate to module (from `path:` field)
- `&&` - Ensure cd succeeds
- `update_module_claude.sh` - Update script
- `"."` - Current directory
- `"related"` - Related mode (context-aware, change-based)
- `"<tool>"` - gemini/qwen/codex
- `&` - Background execution
**Path extraction:**
```bash
# From: depth:3|path:./src/api/auth|files:5|change:new|has_claude:no
# Extract: ./src/api/auth
# Command: bash(cd ./src/api/auth && ~/.claude/scripts/update_module_claude.sh "." "related" "gemini" &)
```
**Mode comparison:**
- `"full"` - Complete module documentation regeneration
- `"related"` - Context-aware update based on recent changes (faster)
## Complex Changes Strategy
For changes affecting >15 modules, delegate to memory-bridge agent:
```javascript
Task(
subagent_type="memory-bridge",
description="Complex project related update",
prompt=`
CONTEXT:
- Total modules: ${change_count}
- Tool: ${tool}
- Mode: related
MODULE LIST:
${changed_modules_output}
REQUIREMENTS:
1. Use TodoWrite to track each depth level
2. Process depths N→0 sequentially, max 4 parallel per depth
3. Command: cd "<path>" && update_module_claude.sh "." "related" "${tool}" &
4. Extract path from "depth:N|path:<PATH>|..." format
5. Verify all ${change_count} modules processed
6. Run safety check
7. Display git diff --stat
`
)
```
## Error Handling
- **No changes detected**: Use fallback mode (recent 10 modules)
- **Change detection failure**: Report error, abort execution
- **User declines approval**: Abort execution, no changes made
- **Safety check failure**: Automatic staging revert, report modified files
- **Update script failure**: Report failed modules, continue with remaining
## Coordinator Checklist
✅ Parse `--tool` parameter (default: gemini)
✅ Refresh code index for accurate change detection
✅ Detect changed modules via detect_changed_modules.sh
✅ Cache git changes to protect current state
✅ Parse changed module list, count affected modules
✅ Apply fallback if no changes detected (recent 10 modules)
✅ Determine strategy based on change count (≤15 vs >15)
✅ Present plan with exact file paths and change types
**Wait for user confirmation** (simple changes only)
✅ Organize modules by depth
✅ For each depth (highest to lowest):
- Launch up to 4 parallel updates with "related" mode
- Wait for depth completion
- Proceed to next depth
✅ Run safety check after all updates
✅ Display git diff statistics
✅ Report completion summary
## Usage Examples
```bash
# Daily development update (default: gemini)
/memory:update-related
# After feature work with specific tool
/memory:update-related --tool qwen
# Code quality review after implementation
/memory:update-related --tool codex
```
## Tool Parameter Reference
**Gemini** (default):
- Best for: Documentation generation, pattern recognition
- Use case: Daily development updates, feature documentation
- Output style: Comprehensive, contextual explanations
**Qwen**:
- Best for: Architecture analysis, system design
- Use case: Structural changes, API design updates
- Output style: Structured, systematic documentation
**Codex**:
- Best for: Implementation validation, code quality
- Use case: After implementation, refactoring work
- Output style: Technical, implementation-focused
## Comparison with Full Update
| Aspect | Related Update | Full Update |
|--------|----------------|-------------|
| **Scope** | Changed modules only | All project modules |
| **Speed** | Fast (minutes) | Slower (10-30 min) |
| **Use case** | Daily development | Major refactoring |
| **Mode** | `"related"` | `"full"` |
| **Trigger** | After commits | After major changes |
| **Complexity threshold** | ≤15 modules | ≤20 modules |

View File

@@ -1,96 +0,0 @@
---
name: analyze
description: Quick analysis of codebase patterns, architecture, and code quality using qwen CLI
usage: /qwen:analyze <analysis-type>
argument-hint: "analysis target or type"
examples:
- /qwen:analyze "React hooks patterns"
- /qwen:analyze "authentication security"
- /qwen:analyze "performance bottlenecks"
- /qwen:analyze "API design patterns"
model: haiku
---
# qwen Analysis Command (/qwen:analyze)
## Overview
Quick analysis tool for codebase insights using intelligent pattern detection and template-driven analysis.
**Core Guidelines**: @~/.claude/workflows/intelligent-tools-strategy.md
## Analysis Types
| Type | Purpose | Example |
|------|---------|---------|
| **pattern** | Code pattern detection | "React hooks usage patterns" |
| **architecture** | System structure analysis | "component hierarchy structure" |
| **security** | Security vulnerabilities | "authentication vulnerabilities" |
| **performance** | Performance bottlenecks | "rendering performance issues" |
| **quality** | Code quality assessment | "testing coverage analysis" |
| **dependencies** | Third-party analysis | "outdated package dependencies" |
## Quick Usage
### Basic Analysis
```bash
/qwen:analyze "authentication patterns"
```
**Executes**: `qwen -p -a "@{**/*auth*} @{CLAUDE.md} $(template:analysis/pattern.txt)"`
### Targeted Analysis
```bash
/qwen:analyze "React component architecture"
```
**Executes**: `qwen -p -a "@{src/components/**/*} @{CLAUDE.md} $(template:analysis/architecture.txt)"`
### Security Focus
```bash
/qwen:analyze "API security vulnerabilities"
```
**Executes**: `qwen -p -a "@{**/api/**/*} @{CLAUDE.md} $(template:analysis/security.txt)"`
## Templates Used
Templates are automatically selected based on analysis type:
- **Pattern Analysis**: `~/.claude/workflows/cli-templates/prompts/analysis/pattern.txt`
- **Architecture Analysis**: `~/.claude/workflows/cli-templates/prompts/analysis/architecture.txt`
- **Security Analysis**: `~/.claude/workflows/cli-templates/prompts/analysis/security.txt`
- **Performance Analysis**: `~/.claude/workflows/cli-templates/prompts/analysis/performance.txt`
## Workflow Integration
⚠️ **Session Check**: Automatically detects active workflow session via `.workflow/.active-*` marker file.
**Analysis results saved to:**
- Active session: `.workflow/WFS-[topic]/.chat/analysis-[timestamp].md`
- No session: Temporary analysis output
## Common Patterns
### Technology Stack Analysis
```bash
/qwen:analyze "project technology stack"
# Auto-detects: package.json, config files, dependencies
```
### Code Quality Review
```bash
/qwen:analyze "code quality and standards"
# Auto-targets: source files, test files, CLAUDE.md
```
### Migration Planning
```bash
/qwen:analyze "legacy code modernization"
# Focuses: older patterns, deprecated APIs, upgrade paths
```
## Output Format
Analysis results include:
- **File References**: Specific file:line locations
- **Code Examples**: Relevant code snippets
- **Patterns Found**: Common patterns and anti-patterns
- **Recommendations**: Actionable improvements
- **Integration Points**: How components connect

View File

@@ -1,93 +0,0 @@
---
name: chat
description: Simple qwen CLI interaction command for direct codebase analysis
usage: /qwen:chat "inquiry"
argument-hint: "your question or analysis request"
examples:
- /qwen:chat "analyze the authentication flow"
- /qwen:chat "how can I optimize this React component performance?"
- /qwen:chat "review security vulnerabilities in src/auth/"
allowed-tools: Bash(qwen:*)
model: sonnet
---
### 🚀 **Command Overview: `/qwen:chat`**
- **Type**: Basic qwen CLI Wrapper
- **Purpose**: Direct interaction with the `qwen` CLI for simple codebase analysis
- **Core Tool**: `Bash(qwen:*)` - Executes the external qwen CLI tool
### 📥 **Parameters & Usage**
- **`<inquiry>` (Required)**: Your question or analysis request
- **`--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
### 🔄 **Execution Workflow**
`Parse Input` **->** `Assemble Context` **->** `Construct Prompt` **->** `Execute qwen CLI` **->** `(Optional) Save Session`
### 📚 **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**
```
=== CONTEXT ===
@{CLAUDE.md,**/*CLAUDE.md} [Project guidelines]
@{target_files} [User-specified files or all files if --all-files is used]
=== USER INPUT ===
[The user inquiry text]
```
### ⚙️ **Execution Implementation**
```pseudo
FUNCTION execute_qwen_chat(user_inquiry, flags):
// Construct basic prompt
prompt = "=== CONTEXT ===\n"
prompt += "@{CLAUDE.md,**/*CLAUDE.md}\n"
// Add user-specified files or all files
IF flags contain "--all-files":
result = execute_tool("Bash(qwen:*)", "--all-files", "-p", prompt + user_inquiry)
ELSE:
prompt += "\n=== USER INPUT ===\n" + user_inquiry
result = execute_tool("Bash(qwen:*)", "-p", prompt)
// Save session if requested
IF flags contain "--save-session":
save_chat_session(user_inquiry, result)
RETURN result
END FUNCTION
```
### 💾 **Session Persistence**
When `--save-session` flag is used:
- Check for existing active session (`.workflow/.active-*` markers)
- Save to existing session's `.chat/` directory or create new session
- File format: `chat-YYYYMMDD-HHMMSS.md`
- Include query, context, and response in saved file
**Session Template:**
```markdown
# Chat Session: [Timestamp]
## Query
[Original user inquiry]
## Context
[Files and patterns included in analysis]
## qwen Response
[Complete response from qwen CLI]
```

View File

@@ -1,168 +0,0 @@
---
name: execute
description: Auto-execution of implementation tasks with YOLO permissions and intelligent context inference
usage: /qwen:execute <description|task-id>
argument-hint: "implementation description or task-id"
examples:
- /qwen:execute "implement user authentication system"
- /qwen:execute "optimize React component performance"
- /qwen:execute IMPL-001
- /qwen:execute "fix API performance issues"
allowed-tools: Bash(qwen:*)
model: sonnet
---
# qwen Execute Command (/qwen:execute)
## Overview
**⚡ YOLO-enabled execution**: Auto-approves all confirmations for streamlined implementation workflow.
**Purpose**: Execute implementation tasks using intelligent context inference and qwen CLI with full permissions.
**Core Guidelines**: @~/.claude/workflows/intelligent-tools-strategy.md
## 🚨 YOLO Permissions
**All confirmations auto-approved by default:**
- ✅ File pattern inference confirmation
- ✅ qwen execution confirmation
- ✅ File modification confirmation
- ✅ Implementation summary generation
## Execution Modes
### 1. Description Mode
**Input**: Natural language description
```bash
/qwen:execute "implement JWT authentication with middleware"
```
**Process**: Keyword analysis → Pattern inference → Context collection → Execution
### 2. Task ID Mode
**Input**: Workflow task identifier
```bash
/qwen: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 |
## Workflow Integration
### Session Management
⚠️ **Auto-detects active session**: Checks `.workflow/.active-*` marker file
**Session storage:**
- **Active session exists**: Saves to `.workflow/WFS-[topic]/.chat/execute-[timestamp].md`
- **No active session**: Creates new session directory
### Task Integration
```bash
# Execute specific workflow task
/qwen:execute IMPL-001
# Loads from: .task/IMPL-001.json
# Uses: task context, brainstorming refs, scope definitions
# Updates: workflow status, generates summary
```
## Execution Templates
### User Description Template
```bash
qwen --all-files -p "@{inferred_patterns} @{CLAUDE.md,**/*CLAUDE.md}
Implementation Task: [user_description]
Provide:
- Specific implementation code
- File modification locations (file:line)
- Test cases
- Integration guidance"
```
### Task ID Template
```bash
qwen --all-files -p "@{task_files} @{brainstorming_refs} @{CLAUDE.md,**/*CLAUDE.md}
Task: [task_title] (ID: [task-id])
Type: [task_type]
Scope: [task_scope]
Execute implementation following task acceptance criteria."
```
## Auto-Generated Outputs
### 1. Implementation Summary
**Location**: `.summaries/[TASK-ID]-summary.md` or auto-generated ID
```markdown
# Task Summary: [Task-ID] [Description]
## Implementation
- **Files Modified**: [file:line references]
- **Features Added**: [specific functionality]
- **Context Used**: [inferred patterns]
## Integration
- [Links to workflow documents]
```
### 2. Execution Session
**Location**: `.chat/execute-[timestamp].md`
```markdown
# Execution Session: [Timestamp]
## Input
[User description or Task ID]
## Context Inference
[File patterns used with rationale]
## Implementation Results
[Generated code and modifications]
## Status Updates
[Workflow integration updates]
```
## Error Handling
- **Task ID not found**: Lists available tasks
- **Pattern inference failure**: Uses generic `src/**/*` pattern
- **Execution failure**: Attempts fallback with simplified context
- **File modification errors**: Reports specific file/permission issues
## Performance Features
- **Smart caching**: Frequently used pattern mappings
- **Progressive inference**: Precise → broad pattern fallback
- **Parallel execution**: When multiple contexts needed
- **Directory optimization**: Switches to optimal execution path
## Integration Workflow
**Typical sequence:**
1. `workflow:plan` → Creates tasks
2. `/qwen:execute IMPL-001` → Executes with YOLO permissions
3. Auto-updates workflow status and generates summaries
4. `workflow:review` → Final validation
**vs. `/qwen:analyze`**: Execute performs analysis **and implementation**, analyze is read-only.

View File

@@ -1,188 +0,0 @@
---
name: auto
description: Auto-select and execute appropriate template based on user input analysis
usage: /qwen:mode:auto "description of task or problem"
argument-hint: "description of what you want to analyze or plan"
examples:
- /qwen:mode:auto "authentication system keeps crashing during login"
- /qwen:mode:auto "design a real-time notification architecture"
- /qwen:mode:auto "database connection errors in production"
- /qwen:mode:auto "plan user dashboard with analytics features"
allowed-tools: Bash(ls:*), Bash(qwen:*)
model: sonnet
---
# Auto Template Selection (/qwen:mode:auto)
## Overview
Automatically analyzes user input to select the most appropriate template and execute qwen CLI with optimal context.
**Directory Analysis Rule**: Intelligent detection of directory context intent - automatically navigate to target directory when analysis scope is directory-specific.
**--cd Parameter Rule**: When `--cd` parameter is provided, always execute `cd "[path]" && qwen --all-files -p "prompt"` to ensure analysis occurs in the specified directory context.
**Process**: List Templates → Analyze Input → Select Template → Execute with Context
## Usage
### Auto-Detection Examples
```bash
# Bug-related keywords → selects bug-fix.md
/qwen:mode:auto "React component not rendering after state update"
# Planning keywords → selects plan.md
/qwen:mode:auto "design microservices architecture for user management"
# Error/crash keywords → selects bug-fix.md
/qwen:mode:auto "API timeout errors in production environment"
# Architecture/design keywords → selects plan.md
/qwen:mode:auto "implement real-time chat system architecture"
# With directory context
/qwen:mode:auto "authentication issues" --cd "src/auth"
```
## Template Selection Logic
### Dynamic Template Discovery
**Templates auto-discovered from**: `~/.claude/prompt-templates/`
Templates are dynamically read from the directory, including their metadata (name, description, keywords) from the YAML frontmatter.
### Template Metadata Parsing
Each template contains YAML frontmatter with:
```yaml
---
name: template-name
description: Template purpose description
category: template-category
keywords: [keyword1, keyword2, keyword3]
---
```
**Auto-selection based on:**
- **Template keywords**: Matches user input against template-defined keywords
- **Template name**: Direct name matching (e.g., "bug-fix" matches bug-related queries)
- **Template description**: Semantic matching against description text
## Command Execution
### Step 1: Template Discovery
```bash
# Dynamically discover all templates and extract YAML frontmatter
cd "~/.claude/prompt-templates" && echo "Discovering templates..." && for template_file in *.md; do echo "=== $template_file ==="; head -6 "$template_file" 2>/dev/null || echo "Error reading $template_file"; echo; done
```
### Step 2: Dynamic Template Analysis & Selection
```pseudo
FUNCTION select_template(user_input):
templates = list_directory("~/.claude/prompt-templates/")
template_metadata = {}
# Parse all templates for metadata
FOR each template_file in templates:
content = read_file(template_file)
yaml_front = extract_yaml_frontmatter(content)
template_metadata[template_file] = {
"name": yaml_front.name,
"description": yaml_front.description,
"keywords": yaml_front.keywords || [],
"category": yaml_front.category || "general"
}
input_lower = user_input.toLowerCase()
best_match = null
highest_score = 0
# Score each template against user input
FOR each template, metadata in template_metadata:
score = 0
# Keyword matching (highest weight)
FOR each keyword in metadata.keywords:
IF input_lower.contains(keyword.toLowerCase()):
score += 3
# Template name matching
IF input_lower.contains(metadata.name.toLowerCase()):
score += 2
# Description semantic matching
FOR each word in metadata.description.split():
IF input_lower.contains(word.toLowerCase()) AND word.length > 3:
score += 1
IF score > highest_score:
highest_score = score
best_match = template
# Default to first template if no matches
RETURN best_match || templates[0]
END FUNCTION
```
### Step 3: Execute with Dynamically Selected Template
```bash
# Basic execution with selected template
qwen --all-files -p "$(cat ~/.claude/prompt-templates/[selected_template])
User Input: [user_input]"
# With --cd parameter
cd "[specified_directory]" && qwen --all-files -p "$(cat ~/.claude/prompt-templates/[selected_template])
User Input: [user_input]"
```
**Template selection is completely dynamic** - any new templates added to the directory will be automatically discovered and available for selection based on their YAML frontmatter.
### Manual Template Override
```bash
# Force specific template
/qwen:mode:auto "user authentication" --template bug-fix.md
/qwen:mode:auto "fix login issues" --template plan.md
```
### Dynamic Template Listing
```bash
# List all dynamically discovered templates
/qwen:mode:auto --list-templates
# Output:
# Dynamically discovered templates in ~/.claude/prompt-templates/:
# - bug-fix.md (用于定位bug并提供修改建议) [Keywords: 规划, bug, 修改方案]
# - plan.md (软件架构规划和技术实现计划分析模板) [Keywords: 规划, 架构, 实现计划, 技术设计, 修改方案]
# - [any-new-template].md (Auto-discovered description) [Keywords: auto-parsed]
```
**Complete template discovery** - new templates are automatically detected and their metadata parsed from YAML frontmatter.
## Auto-Selection Examples
### Dynamic Selection Examples
```bash
# Selection based on template keywords and metadata
"login system crashes on startup" → Matches template with keywords: [bug, 修改方案]
"design user dashboard with analytics" → Matches template with keywords: [规划, 架构, 技术设计]
"database timeout errors in production" → Matches template with keywords: [bug, 修改方案]
"implement real-time notification system" → Matches template with keywords: [规划, 实现计划, 技术设计]
# Any new templates added will be automatically matched
"[user input]" → Dynamically matches against all template keywords and descriptions
```
## Session Integration
saves to:
`.workflow/WFS-[topic]/.chat/auto-[template]-[timestamp].md`
**Session includes:**
- Original user input
- Template selection reasoning
- Template used
- Complete analysis results
This command streamlines template usage by automatically detecting user intent and selecting the optimal template for analysis.

View File

@@ -1,76 +0,0 @@
---
name: bug-index
description: Bug analysis and fix suggestions using specialized template
usage: /qwen:mode:bug-index "bug description"
argument-hint: "description of the bug or error you're experiencing"
examples:
- /qwen:mode:bug-index "authentication null pointer error in login flow"
- /qwen:mode:bug-index "React component not re-rendering after state change"
- /qwen:mode:bug-index "database connection timeout in production"
allowed-tools: Bash(qwen:*)
model: sonnet
---
# Bug Analysis Command (/qwen:mode:bug-index)
## Overview
Systematic bug analysis and fix suggestions using expert diagnostic template.
**Directory Analysis Rule**: Intelligent detection of directory context intent - automatically navigate to target directory when analysis scope is directory-specific.
**--cd Parameter Rule**: When `--cd` parameter is provided, always execute `cd "[path]" && qwen --all-files -p "prompt"` to ensure analysis occurs in the specified directory context.
## Usage
### Basic Bug Analysis
```bash
/qwen:mode:bug-index "authentication null pointer error"
```
### Bug Analysis with Directory Context
```bash
/qwen:mode:bug-index "authentication error" --cd "src/auth"
```
### Save to Workflow Session
```bash
/qwen:mode:bug-index "API timeout issues" --save-session
```
## Command Execution
**Template Used**: `~/.claude/prompt-templates/bug-fix.md`
**Executes**:
```bash
# Basic usage
qwen --all-files -p "$(cat ~/.claude/prompt-templates/bug-fix.md)
Bug Description: [user_description]"
# With --cd parameter
cd "[specified_directory]" && qwen --all-files -p "$(cat ~/.claude/prompt-templates/bug-fix.md)
Bug Description: [user_description]"
```
## Analysis Focus
The bug-fix template provides:
- **Root Cause Analysis**: Systematic investigation
- **Code Path Tracing**: Following execution flow
- **Targeted Solutions**: Specific, minimal fixes
- **Impact Assessment**: Understanding side effects
## Session Output
saves to:
`.workflow/WFS-[topic]/.chat/bug-index-[timestamp].md`
**Includes:**
- Bug description
- Template used
- Analysis results
- Recommended actions

View File

@@ -1,140 +0,0 @@
---
name: plan-precise
description: Precise path planning analysis for complex projects
usage: /qwen:mode:plan-precise "planning topic"
examples:
- /qwen:mode:plan-precise "design authentication system"
- /qwen:mode:plan-precise "refactor database layer architecture"
---
### 🚀 Command Overview: `/qwen:mode:plan-precise`
Precise path-based planning analysis using user-specified directories instead of --all-files.
### 📝 Execution Template
```pseudo
# Precise path planning with user-specified scope
PLANNING_TOPIC = user_argument
PATHS_FILE = "./planning-paths.txt"
# Step 1: Check paths file exists
IF not file_exists(PATHS_FILE):
Write(PATHS_FILE, template_content)
echo "📝 Created planning-paths.txt in project root"
echo "Please edit file and add paths to analyze"
# USER_INPUT: User edits planning-paths.txt and presses Enter
wait_for_user_input()
ELSE:
echo "📁 Using existing planning-paths.txt"
echo "Current paths preview:"
Bash(grep -v '^#' "$PATHS_FILE" | grep -v '^$' | head -5)
# USER_INPUT: User confirms y/n
user_confirm = prompt("Continue with these paths? (y/n): ")
IF user_confirm != "y":
echo "Please edit planning-paths.txt and retry"
exit
# Step 2: Read and validate paths
paths_ref = Bash(.claude/scripts/read-paths.sh "$PATHS_FILE")
IF paths_ref is empty:
echo "❌ No valid paths found in planning-paths.txt"
echo "Please add at least one path and retry"
exit
echo "🎯 Analysis paths: $paths_ref"
echo "📋 Planning topic: $PLANNING_TOPIC"
# BASH_EXECUTION_STOPS → MODEL_ANALYSIS_BEGINS
```
### 🧠 Model Analysis Phase
After bash script prepares paths, model takes control to:
1. **Present Configuration**: Show user the detected paths and analysis scope
2. **Request Confirmation**: Wait for explicit user approval
3. **Execute Analysis**: Run qwen with precise path references
### 📋 Execution Flow
```pseudo
# Step 1: Present plan to user
PRESENT_PLAN:
📋 Precise Path Planning Configuration:
Topic: design authentication system
Paths: src/auth/**/* src/middleware/auth* tests/auth/**/* config/auth.json
qwen Reference: $(.claude/scripts/read-paths.sh ./planning-paths.txt)
⚠️ Continue with analysis? (y/n)
# Step 2: MANDATORY user confirmation
IF user_confirms():
# Step 3: Execute qwen analysis
Bash(qwen -p "$(.claude/scripts/read-paths.sh ./planning-paths.txt) @{CLAUDE.md} $(cat ~/.claude/prompt-templates/plan.md)
Planning Topic: $PLANNING_TOPIC")
ELSE:
abort_execution()
echo "Edit planning-paths.txt and retry"
```
### ✨ Features
- **Root Level Config**: `./planning-paths.txt` in project root (no subdirectories)
- **Simple Workflow**: Check file → Present plan → Confirm → Execute
- **Path Focused**: Only analyzes user-specified paths, not entire project
- **No Complexity**: No validation, suggestions, or result saving - just core function
- **Template Creation**: Auto-creates template file if missing
### 📚 Usage Examples
```bash
# Create analysis for authentication system
/qwen:mode:plan-precise "design authentication system"
# System creates planning-paths.txt (if needed)
# User edits: src/auth/**/* tests/auth/**/* config/auth.json
# System confirms paths and executes analysis
```
### 🔍 Complete Execution Example
```bash
# 1. Command execution
$ /qwen:mode:plan-precise "design authentication system"
# 2. System output
📋 Precise Path Planning Configuration:
Topic: design authentication system
Paths: src/auth/**/* src/middleware/auth* tests/auth/**/* config/auth.json
qwen Reference: @{src/auth/**/*,src/middleware/auth*,tests/auth/**/*,config/auth.json}
⚠️ Continue with analysis? (y/n)
# 3. User confirms
$ y
# 4. Actual qwen command executed
$ qwen -p "$(.claude/scripts/read-paths.sh ./planning-paths.txt) @{CLAUDE.md} $(cat ~/.claude/prompt-templates/plan.md)
Planning Topic: design authentication system"
```
### 🔧 Path File Format
Simple text file in project root: `./planning-paths.txt`
```
# Comments start with #
src/auth/**/*
src/middleware/auth*
tests/auth/**/*
config/auth.json
docs/auth/*.md
```

View File

@@ -1,62 +0,0 @@
---
name: plan
description: Project planning and architecture analysis using qwen CLI with specialized template
usage: /qwen:mode:plan "planning topic"
argument-hint: "planning topic or architectural challenge to analyze"
examples:
- /qwen:mode:plan "design user dashboard feature architecture"
- /qwen:mode:plan "plan microservices migration strategy"
- /qwen:mode:plan "implement real-time notification system"
allowed-tools: Bash(qwen:*)
model: sonnet
---
# Planning Analysis Command (/qwen:mode:plan)
## Overview
**This command uses qwen CLI for comprehensive project planning and architecture analysis.** It leverages qwen CLI's powerful codebase analysis capabilities combined with expert planning templates to provide strategic insights and implementation roadmaps.
### Key Features
- **qwen CLI Integration**: Utilizes qwen CLI's deep codebase analysis for informed planning decisions
**--cd Parameter Rule**: When `--cd` parameter is provided, always execute `cd "[path]" && qwen --all-files -p "prompt"` to ensure analysis occurs in the specified directory context.
## Usage
### Basic Usage
```bash
/qwen:mode:plan "design authentication system"
```
### Directory-Specific Analysis
```bash
/qwen:mode:plan "design authentication system" --cd "src/auth"
```
## Command Execution
**Smart Directory Detection**: Auto-detects relevant directories based on topic keywords
**Executes**:
```bash
# Project-wide analysis
qwen --all-files -p "$(cat ~/.claude/prompt-templates/plan.md)
Planning Topic: [user_description]"
# Directory-specific analysis
cd "[directory]" && qwen --all-files -p "$(cat ~/.claude/prompt-templates/plan.md)
Planning Topic: [user_description]"
```
## Session Output
saves to:
`.workflow/WFS-[topic]/.chat/plan-[timestamp].md`
**Includes:**
- Planning topic
- Template used
- Analysis results
- Implementation roadmap
- Key decisions

View File

@@ -1,12 +1,7 @@
---
name: breakdown
description: Intelligent task decomposition with context-aware subtask generation
usage: /task:breakdown <task-id>
argument-hint: task-id
examples:
- /task:breakdown IMPL-1
- /task:breakdown IMPL-1.1
- /task:breakdown impl-3
argument-hint: "task-id"
---
# Task Breakdown Command (/task:breakdown)
@@ -73,7 +68,21 @@ Define subtasks manually (remaining capacity: 4 tasks):
- "User authentication" and "OAuth integration" both handle auth
- Consider combining into single task
Proceed with breakdown? (y/n): y
# Use AskUserQuestion for confirmation
AskUserQuestion({
questions: [{
question: "File conflicts and/or similar functionality detected. How do you want to proceed?",
header: "Confirm",
options: [
{ label: "Proceed with breakdown", description: "Accept the risks and create the subtasks as defined." },
{ label: "Restart breakdown", description: "Discard current subtasks and start over." },
{ label: "Cancel breakdown", description: "Abort the operation and leave the parent task as is." }
],
multiSelect: false
}]
})
User selected: "Proceed with breakdown"
✅ Task IMPL-1 broken down:
▸ IMPL-1: Build authentication module (container)
@@ -88,8 +97,9 @@ Files updated: .task/IMPL-1.json + 2 subtask files + TODO_LIST.md
### Agent Assignment
- **Design/Planning** → `@planning-agent`
- **Implementation** → `@code-developer`
- **Testing** → `@code-review-test-agent`
- **Review** → `@review-agent`
- **Testing** → `@code-developer` (type: "test-gen")
- **Test Validation** → `@test-fix-agent` (type: "test-fix")
- **Review** → `@general-purpose` (optional)
### Context Inheritance
- Subtasks inherit parent requirements
@@ -161,8 +171,8 @@ See @~/.claude/workflows/workflow-architecture.md for:
▸ impl-1: Build authentication (container)
├── impl-1.1: Design schema → @planning-agent
├── impl-1.2: Implement logic → @code-developer
└── impl-1.3: Write tests → @code-review-test-agent
├── impl-1.2: Implement logic + tests → @code-developer
└── impl-1.3: Execute & fix tests → @test-fix-agent
```
## Error Handling

View File

@@ -1,12 +1,7 @@
---
name: create
description: Create implementation tasks with automatic context awareness
usage: /task:create "title"
argument-hint: "task title"
examples:
- /task:create "Implement user authentication"
- /task:create "Build REST API endpoints"
- /task:create "Fix login validation bug"
argument-hint: "\"task title\""
---
# Task Create Command (/task:create)
@@ -107,8 +102,9 @@ Tasks inherit from:
Based on task type and title keywords:
- **Build/Implement** → @code-developer
- **Design/Plan** → @planning-agent
- **Test/Validate** → @code-review-test-agent
- **Review/Audit** → @review-agent`
- **Test Generation** → @code-developer (type: "test-gen")
- **Test Execution/Fix** → @test-fix-agent (type: "test-fix")
- **Review/Audit** → @general-purpose (optional, only when explicitly requested)
## Validation Rules

View File

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

View File

@@ -1,68 +1,95 @@
---
name: replan
description: Replan individual tasks with detailed user input and change tracking
usage: /task:replan <task-id> [input]
argument-hint: task-id ["text"|file.md|ISS-001]
examples:
- /task:replan IMPL-1 "Add OAuth2 authentication support"
- /task:replan IMPL-1 updated-specs.md
- /task:replan IMPL-1 ISS-001
argument-hint: "task-id [\"text\"|file.md] | --batch [verification-report.md]"
allowed-tools: Read(*), Write(*), Edit(*), TodoWrite(*), Glob(*), Bash(*)
---
# Task Replan Command (/task:replan)
## Overview
Replans individual tasks with multiple input options, change tracking, and version management.
Replans individual tasks or batch processes multiple tasks with change tracking and backup management.
**Modes**:
- **Single Task Mode**: Replan one task with specific changes
- **Batch Mode**: Process multiple tasks from action-plan verification report
## Core Principles
**Task System:** @~/.claude/workflows/task-core.md
## Key Features
- **Single-Task Focus**: Operates on individual tasks only
- **Multiple Input Sources**: Text, files, or issue references
- **Version Tracking**: Backup previous versions
- **Single/Batch Operations**: Single task or multiple tasks from verification report
- **Multiple Input Sources**: Text, files, or verification report
- **Backup Management**: Automatic backup of previous versions
- **Change Documentation**: Track all modifications
- **Progress Tracking**: TodoWrite integration for batch operations
⚠️ **CRITICAL**: Validates active session before replanning
## Input Sources
## Operation Modes
### Direct Text (Default)
### Single Task Mode
#### Direct Text (Default)
```bash
/task:replan IMPL-1 "Add OAuth2 authentication support"
```
### File-based Input
#### File-based Input
```bash
/task:replan IMPL-1 updated-specs.md
```
Supports: .md, .txt, .json, .yaml
### Issue Reference
```bash
/task:replan IMPL-1 ISS-001
```
Loads issue description and requirements
### Interactive Mode
#### Interactive Mode
```bash
/task:replan IMPL-1 --interactive
```
Guided step-by-step modification process with validation
### Batch Mode
#### From Verification Report
```bash
/task:replan --batch ACTION_PLAN_VERIFICATION.md
```
**Workflow**:
1. Parse verification report to extract replan recommendations
2. Create TodoWrite task list for all modifications
3. Process each task sequentially with confirmation
4. Track progress and generate summary report
**Auto-detection**: If input file contains "Action Plan Verification Report" header, automatically enters batch mode
## Replanning Process
### Single Task Process
1. **Load & Validate**: Read task JSON and validate session
2. **Parse Input**: Process changes from input source
3. **Backup Version**: Create previous version backup
3. **Create Backup**: Save previous version to backup folder
4. **Update Task**: Modify JSON structure and relationships
5. **Save Changes**: Write updated task and increment version
6. **Update Session**: Reflect changes in workflow stats
## Version Management
### Batch Process
### Version Tracking
Tasks maintain version history:
1. **Parse Verification Report**: Extract all replan recommendations
2. **Initialize TodoWrite**: Create task list for tracking
3. **For Each Task**:
- Mark todo as in_progress
- Load and validate task JSON
- Create backup
- Apply recommended changes
- Save updated task
- Mark todo as completed
4. **Generate Summary**: Report all changes and backup locations
## Backup Management
### Backup Tracking
Tasks maintain backup history:
```json
{
"id": "IMPL-1",
@@ -72,7 +99,8 @@ Tasks maintain version history:
"version": "1.2",
"reason": "Add OAuth2 support",
"input_source": "direct_text",
"backup_location": ".task/versions/IMPL-1-v1.1.json"
"backup_location": ".task/backup/IMPL-1-v1.1.json",
"timestamp": "2025-10-17T10:30:00Z"
}
]
}
@@ -84,11 +112,15 @@ Tasks maintain version history:
```
.task/
├── IMPL-1.json # Current version
├── versions/
── IMPL-1-v1.1.json # Previous backup
├── backup/
── IMPL-1-v1.0.json # Original version
│ ├── IMPL-1-v1.1.json # Previous backup
│ └── IMPL-1-v1.2.json # Latest backup
└── [new subtasks as needed]
```
**Backup Naming**: `{task-id}-v{version}.json`
## Implementation Updates
### Change Detection
@@ -138,18 +170,68 @@ Updates workflow-session.json with:
/task:replan IMPL-1 --rollback v1.1
Rollback to version 1.1:
- Restore task from backup
- Restore task from backup/.../IMPL-1-v1.1.json
- Remove new subtasks if any
- Update session stats
Confirm rollback? (y/n): y
# Use AskUserQuestion for confirmation
AskUserQuestion({
questions: [{
question: "Are you sure you want to roll back this task to a previous version?",
header: "Confirm",
options: [
{ label: "Yes, rollback", description: "Restore the task from the selected backup." },
{ label: "No, cancel", description: "Keep the current version of the task." }
],
multiSelect: false
}]
})
User selected: "Yes, rollback"
✅ Task rolled back to version 1.1
```
## Batch Processing with TodoWrite
### Progress Tracking
When processing multiple tasks, automatically creates TodoWrite task list:
```markdown
**Batch Replan Progress**:
- [x] IMPL-002: Add FR-12 draft saving acceptance criteria
- [x] IMPL-003: Add FR-14 history tracking acceptance criteria
- [⧗] IMPL-004: Add FR-09 response surface explicit coverage
- [ ] IMPL-008: Add NFR performance validation steps
```
### Batch Report
After completion, generates summary:
```markdown
## Batch Replan Summary
**Total Tasks**: 4
**Successful**: 3
**Failed**: 1
**Skipped**: 0
### Changes Made
- IMPL-002 v1.0 → v1.1: Added FR-12 acceptance criteria
- IMPL-003 v1.0 → v1.1: Added FR-14 acceptance criteria
- IMPL-004 v1.0 → v1.1: Added FR-09 explicit coverage
### Backups Created
- .task/backup/IMPL-002-v1.0.json
- .task/backup/IMPL-003-v1.0.json
- .task/backup/IMPL-004-v1.0.json
### Errors
- IMPL-008: File not found (task may have been renamed)
```
## Examples
### Text Input
### Single Task - Text Input
```bash
/task:replan IMPL-1 "Add OAuth2 authentication support"
@@ -158,14 +240,27 @@ Proposed updates:
+ Add OAuth2 integration
+ Update authentication flow
Apply changes? (y/n): y
# Use AskUserQuestion for confirmation
AskUserQuestion({
questions: [{
question: "Do you want to apply these changes to the task?",
header: "Apply",
options: [
{ label: "Yes, apply", description: "Create new version with these changes." },
{ label: "No, cancel", description: "Discard changes and keep current version." }
],
multiSelect: false
}]
})
User selected: "Yes, apply"
✓ Version 1.2 created
✓ Context updated
✓ Backup saved
✓ Backup saved to .task/backup/IMPL-1-v1.1.json
```
### File Input
### Single Task - File Input
```bash
/task:replan IMPL-2 requirements.md
@@ -174,14 +269,59 @@ Applying specification changes...
✓ Task updated with new requirements
✓ Version 1.1 created
✓ Backup saved to .task/backup/IMPL-2-v1.0.json
```
### Batch Mode - From Verification Report
```bash
/task:replan --batch .workflow/WFS-{session}/.process/ACTION_PLAN_VERIFICATION.md
Parsing verification report...
Found 4 tasks requiring replanning:
- IMPL-002: Add FR-12 draft saving acceptance criteria
- IMPL-003: Add FR-14 history tracking acceptance criteria
- IMPL-004: Add FR-09 response surface explicit coverage
- IMPL-008: Add NFR performance validation steps
Creating task tracking list...
Processing IMPL-002...
✓ Backup created: .task/backup/IMPL-002-v1.0.json
✓ Updated to v1.1
Processing IMPL-003...
✓ Backup created: .task/backup/IMPL-003-v1.0.json
✓ Updated to v1.1
Processing IMPL-004...
✓ Backup created: .task/backup/IMPL-004-v1.0.json
✓ Updated to v1.1
Processing IMPL-008...
✓ Backup created: .task/backup/IMPL-008-v1.0.json
✓ Updated to v1.1
✅ Batch replan completed: 4/4 successful
📋 Summary report saved
```
### Batch Mode - Auto-detection
```bash
# If file contains "Action Plan Verification Report", auto-enters batch mode
/task:replan ACTION_PLAN_VERIFICATION.md
Detected verification report format
Entering batch mode...
[same as above]
```
## Error Handling
### Single Task Errors
```bash
# Task not found
❌ Task IMPL-5 not found
→ Check task ID with /context
→ Check task ID with /workflow:status
# Task completed
⚠️ Task IMPL-1 is completed (cannot replan)
@@ -193,12 +333,112 @@ Applying specification changes...
# No input provided
❌ Please specify changes needed
→ Provide text, file, or issue reference
→ Provide text, file, or verification report
```
### Batch Mode Errors
```bash
# Invalid verification report
❌ File does not contain valid verification report format
→ Check report structure or use single task mode
# Partial failures
⚠️ Batch completed with errors: 3/4 successful
→ Review error details in summary report
# No replan recommendations found
❌ Verification report contains no replan recommendations
→ Check report content or use /workflow:action-plan-verify first
```
## Batch Mode Integration
### Input Format Expectations
Batch mode parses verification reports looking for:
1. **Required Actions Section**: Commands like `/task:replan IMPL-X "changes"`
2. **Findings Table**: Task IDs with recommendations
3. **Next Actions Section**: Specific replan commands
**Example Patterns**:
```markdown
#### 1. HIGH Priority - Address FR Coverage Gaps
/task:replan IMPL-004 "
Add explicit acceptance criteria:
- FR-09: Response surface 3D visualization
"
#### 2. MEDIUM Priority - Enhance NFR Coverage
/task:replan IMPL-008 "
Add performance testing:
- NFR-01: Load test API endpoints
"
```
### Extraction Logic
1. Scan for `/task:replan` commands in report
2. Extract task ID and change description
3. Group by priority (HIGH, MEDIUM, LOW)
4. Process in priority order with TodoWrite tracking
### Confirmation Behavior
- **Default**: Confirm each task before applying
- **With `--auto-confirm`**: Apply all changes without prompting
```bash
/task:replan --batch report.md --auto-confirm
```
## Implementation Details
### Backup Management
```typescript
// Backup file naming convention
const backupPath = `.task/backup/${taskId}-v${previousVersion}.json`;
// Backup metadata in task JSON
{
"replan_history": [
{
"version": "1.2",
"timestamp": "2025-10-17T10:30:00Z",
"reason": "Add FR-09 explicit coverage",
"input_source": "batch_verification_report",
"backup_location": ".task/backup/IMPL-004-v1.1.json"
}
]
}
```
### TodoWrite Integration
```typescript
// Initialize tracking for batch mode
TodoWrite({
todos: taskList.map(task => ({
content: `${task.id}: ${task.changeDescription}`,
status: "pending",
activeForm: `Replanning ${task.id}`
}))
});
// Update progress during processing
TodoWrite({
todos: updateTaskStatus(taskId, "in_progress")
});
// Mark completed
TodoWrite({
todos: updateTaskStatus(taskId, "completed")
});
```
## Related Commands
- `/context` - View updated task structure
- `/workflow:status` - View task structure and versions
- `/workflow:action-plan-verify` - Generate verification report for batch mode
- `/task:execute` - Execute replanned task
- `/task:create` - Create new tasks
- `/workflow:action-plan` - For workflow-wide changes
- `/task:breakdown` - Break down complex tasks
## Context
$ARGUMENTS

View File

@@ -1,132 +0,0 @@
---
name: update-memory-full
description: Complete project-wide CLAUDE.md documentation update
usage: /update-memory-full
examples:
- /update-memory-full # Full project documentation update
---
### 🚀 Command Overview: `/update-memory-full`
Complete project-wide documentation update using depth-parallel execution.
### 📝 Execution Template
```bash
#!/bin/bash
# Complete project-wide CLAUDE.md documentation update
# 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: Cache git changes
Bash(git add -A 2>/dev/null || true)
# Step 3: 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
# 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"
# ELSE:
# → Present plan and WAIT FOR USER APPROVAL before execution
```
### 🧠 Model Analysis Phase
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**:
- Simple projects: Present execution plan with CLAUDE.md paths to user
- Complex projects: Delegate to memory-gemini-bridge agent
4. **Present Detailed Plan**: Show user exactly which CLAUDE.md files will be created/updated
5. **⚠️ CRITICAL: WAIT FOR USER APPROVAL**: No execution without explicit user consent
### 📋 Execution Strategies
**For Simple Projects (≤20 modules):**
Model will present detailed plan:
```
📋 Update Plan:
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)
```
```pseudo
# ⚠️ MANDATORY: User confirmation → MUST await explicit approval
IF user_explicitly_confirms():
continue_execution()
ELSE:
abort_execution()
# Step 4: Organize modules by depth → Prepare execution
depth_modules = organize_by_depth(modules)
# Step 5: 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" "full" &)
wait_all_jobs()
# Step 6: Safety check and restore staging state
non_claude=$(Bash(git diff --cached --name-only | grep -v "CLAUDE.md" || true))
if [ -n "$non_claude" ]; then
Bash(git restore --staged .)
echo "⚠️ Warning: Non-CLAUDE.md files were modified, staging reverted"
echo "Modified files: $non_claude"
else
echo "✅ Only CLAUDE.md files modified, staging preserved"
fi
# Step 7: Display changes → Final status
Bash(git status --short)
```
**For Complex Projects (>20 modules):**
The model will delegate to the memory-gemini-bridge agent using the Task tool:
```
Task "Complex project full update"
prompt: "Execute full documentation update for [count] modules using depth-parallel execution"
subagent_type: "memory-gemini-bridge"
```
### 📚 Usage Examples
```bash
# Complete project documentation refresh
/update-memory-full
# After major architectural changes
/update-memory-full
```
### ✨ Features
- **Separated Commands**: Each bash operation is a discrete, trackable step
- **Intelligent Complexity Detection**: Model analyzes project context for optimal strategy
- **Depth-Parallel Execution**: Same depth modules run in parallel, depths run sequentially
- **Git Integration**: Auto-cache changes before, safety check and show status after
- **Safety Protection**: Automatic detection and revert of unintended source code modifications
- **Module Detection**: Uses get_modules_by_depth.sh for structure discovery
- **User Confirmation**: Clear plan presentation with approval step
- **CLAUDE.md Only**: Only updates documentation, never source code

View File

@@ -1,139 +0,0 @@
---
name: update-memory-related
description: Context-aware CLAUDE.md documentation updates based on recent changes
usage: /update-memory-related
examples:
- /update-memory-related # Update documentation based on recent changes
---
### 🚀 Command Overview: `/update-memory-related`
Context-aware documentation update for modules affected by recent changes.
### 📝 Execution Template
```bash
#!/bin/bash
# Context-aware CLAUDE.md documentation update
# Step 1: 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)
changed=$(Bash(~/.claude/scripts/detect_changed_modules.sh list))
# Step 3: Cache git changes (protect current state)
Bash(git add -A 2>/dev/null || true)
# Step 3: 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
# 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"
# ELSE:
# → Present plan and WAIT FOR USER APPROVAL before execution
```
### 🧠 Model Analysis Phase
After the bash script completes change detection, the model takes control to:
1. **Analyze Changes**: Review change count and complexity
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
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
### 📋 Execution Strategies
**For Simple Changes (≤15 modules):**
Model will present detailed plan for affected modules:
```
📋 Related Update Plan:
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)
```
```pseudo
# ⚠️ MANDATORY: User confirmation → MUST await explicit approval
IF user_explicitly_confirms():
continue_execution()
ELSE:
abort_execution()
# Step 4: Organize modules by depth → Prepare execution
depth_modules = organize_by_depth(changed_modules)
# Step 5: 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" "related" &)
wait_all_jobs()
# Step 6: Safety check and restore staging state
non_claude=$(Bash(git diff --cached --name-only | grep -v "CLAUDE.md" || true))
if [ -n "$non_claude" ]; then
Bash(git restore --staged .)
echo "⚠️ Warning: Non-CLAUDE.md files were modified, staging reverted"
echo "Modified files: $non_claude"
else
echo "✅ Only CLAUDE.md files modified, staging preserved"
fi
# Step 7: Display changes → Final status
Bash(git diff --stat)
```
**For Complex Changes (>15 modules):**
The model will delegate to the memory-gemini-bridge agent using the Task tool:
```
Task "Complex project related update"
prompt: "Execute context-aware update for [count] changed modules using depth-parallel execution"
subagent_type: "memory-gemini-bridge"
```
### 📚 Usage Examples
```bash
# Daily development update
/update-memory-related
# After feature work
/update-memory-related
```
### ✨ Features
- **Separated Commands**: Each bash operation is a discrete, trackable step
- **Intelligent Change Analysis**: Model analyzes change complexity for optimal strategy
- **Change Detection**: Automatically finds affected modules using git diff
- **Depth-Parallel Execution**: Same depth modules run in parallel, depths run sequentially
- **Git Integration**: Auto-cache changes, show diff statistics after
- **Fallback Mode**: Updates recent files when no git changes found
- **User Confirmation**: Clear plan presentation with approval step
- **CLAUDE.md Only**: Only updates documentation, never source code

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

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

View File

@@ -0,0 +1,382 @@
---
name: action-plan-verify
description: Perform non-destructive cross-artifact consistency and quality analysis of IMPL_PLAN.md and task.json before execution
argument-hint: "[optional: --session session-id]"
allowed-tools: Read(*), TodoWrite(*), Glob(*), Bash(*)
---
## User Input
```text
$ARGUMENTS
```
You **MUST** consider the user input before proceeding (if not empty).
## Goal
Identify inconsistencies, duplications, ambiguities, and underspecified items between action planning artifacts (`IMPL_PLAN.md`, `task.json`) and brainstorming artifacts (`synthesis-specification.md`) before implementation. This command MUST run only after `/workflow:plan` has successfully produced complete `IMPL_PLAN.md` and task JSON files.
## Operating Constraints
**STRICTLY READ-ONLY**: Do **not** modify any files. Output a structured analysis report. Offer an optional remediation plan (user must explicitly approve before any follow-up editing commands).
**Synthesis Authority**: The `synthesis-specification.md` is **authoritative** for requirements and design decisions. Any conflicts between IMPL_PLAN/tasks and synthesis are automatically CRITICAL and require adjustment of the plan/tasks—not reinterpretation of requirements.
## Execution Steps
### 1. Initialize Analysis Context
```bash
# Detect active workflow session
IF --session parameter provided:
session_id = provided session
ELSE:
CHECK: .workflow/.active-* marker files
IF active_session EXISTS:
session_id = get_active_session()
ELSE:
ERROR: "No active workflow session found. Use --session <session-id>"
EXIT
# Derive absolute paths
session_dir = .workflow/WFS-{session}
brainstorm_dir = session_dir/.brainstorming
task_dir = session_dir/.task
# Validate required artifacts
SYNTHESIS = brainstorm_dir/synthesis-specification.md
IMPL_PLAN = session_dir/IMPL_PLAN.md
TASK_FILES = Glob(task_dir/*.json)
# Abort if missing
IF NOT EXISTS(SYNTHESIS):
ERROR: "synthesis-specification.md not found. Run /workflow:brainstorm:synthesis first"
EXIT
IF NOT EXISTS(IMPL_PLAN):
ERROR: "IMPL_PLAN.md not found. Run /workflow:plan first"
EXIT
IF TASK_FILES.count == 0:
ERROR: "No task JSON files found. Run /workflow:plan first"
EXIT
```
### 2. Load Artifacts (Progressive Disclosure)
Load only minimal necessary context from each artifact:
**From workflow-session.json** (NEW - PRIMARY REFERENCE):
- Original user prompt/intent (project or description field)
- User's stated goals and objectives
- User's scope definition
**From synthesis-specification.md**:
- Functional Requirements (IDs, descriptions, acceptance criteria)
- Non-Functional Requirements (IDs, targets)
- Business Requirements (IDs, success metrics)
- Key Architecture Decisions
- Risk factors and mitigation strategies
- Implementation Roadmap (high-level phases)
**From IMPL_PLAN.md**:
- Summary and objectives
- Context Analysis
- Implementation Strategy
- Task Breakdown Summary
- Success Criteria
- Brainstorming Artifacts References (if present)
**From task.json files**:
- Task IDs
- Titles and descriptions
- Status
- Dependencies (depends_on, blocks)
- Context (requirements, focus_paths, acceptance, artifacts)
- Flow control (pre_analysis, implementation_approach)
- Meta (complexity, priority, use_codex)
### 3. Build Semantic Models
Create internal representations (do not include raw artifacts in output):
**Requirements inventory**:
- Each functional/non-functional/business requirement with stable ID
- Requirement text, acceptance criteria, priority
**Architecture decisions inventory**:
- ADRs from synthesis
- Technology choices
- Data model references
**Task coverage mapping**:
- Map each task to one or more requirements (by ID reference or keyword inference)
- Map each requirement to covering tasks
**Dependency graph**:
- Task-to-task dependencies (depends_on, blocks)
- Requirement-level dependencies (from synthesis)
### 4. Detection Passes (Token-Efficient Analysis)
Focus on high-signal findings. Limit to 50 findings total; aggregate remainder in overflow summary.
#### A. User Intent Alignment (NEW - CRITICAL)
- **Goal Alignment**: IMPL_PLAN objectives match user's original intent
- **Scope Drift**: Plan covers user's stated scope without unauthorized expansion
- **Success Criteria Match**: Plan's success criteria reflect user's expectations
- **Intent Conflicts**: Tasks contradicting user's original objectives
#### B. Requirements Coverage Analysis
- **Orphaned Requirements**: Requirements in synthesis with zero associated tasks
- **Unmapped Tasks**: Tasks with no clear requirement linkage
- **NFR Coverage Gaps**: Non-functional requirements (performance, security, scalability) not reflected in tasks
#### B. Consistency Validation
- **Requirement Conflicts**: Tasks contradicting synthesis requirements
- **Architecture Drift**: IMPL_PLAN architecture not matching synthesis ADRs
- **Terminology Drift**: Same concept named differently across IMPL_PLAN and tasks
- **Data Model Inconsistency**: Tasks referencing entities/fields not in synthesis data model
#### C. Dependency Integrity
- **Circular Dependencies**: Task A depends on B, B depends on C, C depends on A
- **Missing Dependencies**: Task requires outputs from another task but no explicit dependency
- **Broken Dependencies**: Task depends on non-existent task ID
- **Logical Ordering Issues**: Implementation tasks before foundational setup without dependency note
#### D. Synthesis Alignment
- **Priority Conflicts**: High-priority synthesis requirements mapped to low-priority tasks
- **Success Criteria Mismatch**: IMPL_PLAN success criteria not covering synthesis acceptance criteria
- **Risk Mitigation Gaps**: Critical risks in synthesis without corresponding mitigation tasks
#### E. Task Specification Quality
- **Ambiguous Focus Paths**: Tasks with vague or missing focus_paths
- **Underspecified Acceptance**: Tasks without clear acceptance criteria
- **Missing Artifacts References**: Tasks not referencing relevant brainstorming artifacts in context.artifacts
- **Weak Flow Control**: Tasks without clear implementation_approach or pre_analysis steps
- **Missing Target Files**: Tasks without flow_control.target_files specification
#### F. Duplication Detection
- **Overlapping Task Scope**: Multiple tasks with nearly identical descriptions
- **Redundant Requirements Coverage**: Same requirement covered by multiple tasks without clear partitioning
#### G. Feasibility Assessment
- **Complexity Misalignment**: Task marked "simple" but requires multiple file modifications
- **Resource Conflicts**: Parallel tasks requiring same resources/files
- **Skill Gap Risks**: Tasks requiring skills not in team capability assessment (from synthesis)
### 5. Severity Assignment
Use this heuristic to prioritize findings:
- **CRITICAL**:
- Violates user's original intent (goal misalignment, scope drift)
- Violates synthesis authority (requirement conflict)
- Core requirement with zero coverage
- Circular dependencies
- Broken dependencies
- **HIGH**:
- NFR coverage gaps
- Priority conflicts
- Missing risk mitigation tasks
- Ambiguous acceptance criteria
- **MEDIUM**:
- Terminology drift
- Missing artifacts references
- Weak flow control
- Logical ordering issues
- **LOW**:
- Style/wording improvements
- Minor redundancy not affecting execution
### 6. Produce Compact Analysis Report
Output a Markdown report (no file writes) with the following structure:
```markdown
## Action Plan Verification Report
**Session**: WFS-{session-id}
**Generated**: {timestamp}
**Artifacts Analyzed**: synthesis-specification.md, IMPL_PLAN.md, {N} task files
---
### Executive Summary
- **Overall Risk Level**: CRITICAL | HIGH | MEDIUM | LOW
- **Recommendation**: BLOCK_EXECUTION | PROCEED_WITH_FIXES | PROCEED_WITH_CAUTION | PROCEED
- **Critical Issues**: {count}
- **High Issues**: {count}
- **Medium Issues**: {count}
- **Low Issues**: {count}
---
### Findings Summary
| ID | Category | Severity | Location(s) | Summary | Recommendation |
|----|----------|----------|-------------|---------|----------------|
| C1 | Coverage | CRITICAL | synthesis:FR-03 | Requirement "User auth" has zero task coverage | Add authentication implementation task |
| H1 | Consistency | HIGH | IMPL-1.2 vs synthesis:ADR-02 | Task uses REST while synthesis specifies GraphQL | Align task with ADR-02 decision |
| M1 | Specification | MEDIUM | IMPL-2.1 | Missing context.artifacts reference | Add @synthesis reference |
| L1 | Duplication | LOW | IMPL-3.1, IMPL-3.2 | Similar scope | Consider merging |
(Add one row per finding; generate stable IDs prefixed by severity initial.)
---
### Requirements Coverage Analysis
| Requirement ID | Requirement Summary | Has Task? | Task IDs | Priority Match | Notes |
|----------------|---------------------|-----------|----------|----------------|-------|
| FR-01 | User authentication | ✅ Yes | IMPL-1.1, IMPL-1.2 | ✅ Match | Complete |
| FR-02 | Data export | ✅ Yes | IMPL-2.3 | ⚠️ Mismatch | High req → Med priority task |
| FR-03 | Profile management | ❌ No | - | - | **CRITICAL: Zero coverage** |
| NFR-01 | Response time <200ms | ❌ No | - | - | **HIGH: No performance tasks** |
**Coverage Metrics**:
- Functional Requirements: 85% (17/20 covered)
- Non-Functional Requirements: 40% (2/5 covered)
- Business Requirements: 100% (5/5 covered)
---
### Unmapped Tasks
| Task ID | Title | Issue | Recommendation |
|---------|-------|-------|----------------|
| IMPL-4.5 | Refactor utils | No requirement linkage | Link to technical debt or remove |
---
### Dependency Graph Issues
**Circular Dependencies**: None detected ✅
**Broken Dependencies**:
- IMPL-2.3 depends on "IMPL-2.4" (non-existent)
**Logical Ordering Issues**:
- IMPL-5.1 (integration test) has no dependency on IMPL-1.* (implementation tasks)
---
### Synthesis Alignment Issues
| Issue Type | Synthesis Reference | IMPL_PLAN/Task | Impact | Recommendation |
|------------|---------------------|----------------|--------|----------------|
| Architecture Conflict | synthesis:ADR-01 (JWT auth) | IMPL_PLAN uses session cookies | HIGH | Update IMPL_PLAN to use JWT |
| Priority Mismatch | synthesis:FR-02 (High) | IMPL-2.3 (Medium) | MEDIUM | Elevate task priority |
| Missing Risk Mitigation | synthesis:Risk-03 (API rate limits) | No mitigation tasks | HIGH | Add rate limiting implementation task |
---
### Task Specification Quality Issues
**Missing Artifacts References**: 12 tasks lack context.artifacts
**Weak Flow Control**: 5 tasks lack implementation_approach
**Missing Target Files**: 8 tasks lack flow_control.target_files
**Sample Issues**:
- IMPL-1.2: No context.artifacts reference to synthesis
- IMPL-3.1: Missing flow_control.target_files specification
- IMPL-4.2: Vague focus_paths ["src/"] - needs refinement
---
### Feasibility Concerns
| Concern | Tasks Affected | Issue | Recommendation |
|---------|----------------|-------|----------------|
| Skill Gap | IMPL-6.1, IMPL-6.2 | Requires Kubernetes expertise not in team | Add training task or external consultant |
| Resource Conflict | IMPL-3.1, IMPL-3.2 | Both modify src/auth/service.ts in parallel | Add dependency or serialize |
---
### Metrics
- **Total Requirements**: 30 (20 functional, 5 non-functional, 5 business)
- **Total Tasks**: 25
- **Overall Coverage**: 77% (23/30 requirements with ≥1 task)
- **Critical Issues**: 2
- **High Issues**: 5
- **Medium Issues**: 8
- **Low Issues**: 3
---
### Next Actions
#### Action Recommendations
**If CRITICAL Issues Exist**:
-**BLOCK EXECUTION** - Resolve critical issues before proceeding
- Use `/task:create` for missing requirements coverage
- Fix broken dependencies and circular references
**If Only HIGH/MEDIUM/LOW Issues**:
- ⚠️ **PROCEED WITH CAUTION** - Fix high-priority issues first
- Use batch replan mode to apply all task improvements systematically
#### Batch Remediation
**Report Location**: `.workflow/WFS-{session}/.process/ACTION_PLAN_VERIFICATION.md`
**Apply All Task Improvements** (Recommended):
```bash
# Batch process all task replan recommendations
/task:replan --batch .workflow/WFS-{session}/.process/ACTION_PLAN_VERIFICATION.md
# Or with auto-confirmation (no prompts)
/task:replan --batch ACTION_PLAN_VERIFICATION.md --auto-confirm
```
**Manual Selective Fixes**:
```bash
# Fix critical coverage gaps first
/task:create "Implement user authentication (FR-03)"
/task:create "Add performance optimization (NFR-01)"
# Then apply task refinements individually
/task:replan IMPL-1.2 "Add context.artifacts and target_files"
```
**Notes**:
- Batch mode extracts all `/task:replan` commands from report
- Processes by priority: CRITICAL → HIGH → MEDIUM → LOW
- Creates TodoWrite tracking for all modifications
- Architecture drift in IMPL_PLAN requires manual editing
```
### 7. Save Report and Provide Remediation Options
**Save Analysis Report**:
```bash
report_path = ".workflow/WFS-{session}/.process/ACTION_PLAN_VERIFICATION.md"
Write(report_path, full_report_content)
```
At end of report, provide batch remediation guidance:
```markdown
### 🔧 Remediation Options
**Recommended Workflow**:
1. **TodoWrite Tracking**: Create task list for all fixes
2. **Agent-Based Fixes**: Call action-planning-agent to regenerate task files
3. **User Confirmation**: Wait for approval before executing fixes
**Note**: All fixes require explicit user confirmation.

View File

@@ -0,0 +1,585 @@
---
name: api-designer
description: Generate or update api-designer/analysis.md addressing topic-framework discussion points
argument-hint: "optional topic - uses existing framework if available"
allowed-tools: Task(conceptual-planning-agent), TodoWrite(*), Read(*), Write(*)
---
## 🔌 **API Designer Analysis Generator**
### Purpose
**Specialized command for generating api-designer/analysis.md** that addresses topic-framework.md discussion points from backend API design perspective. Creates or updates role-specific analysis with framework references.
### Core Function
- **Framework-based Analysis**: Address each discussion point in topic-framework.md
- **API Design Focus**: RESTful/GraphQL API design, endpoint structure, and contract definition
- **Update Mechanism**: Create new or update existing analysis.md
- **Agent Delegation**: Use conceptual-planning-agent for analysis generation
### Analysis Scope
- **API Architecture**: RESTful/GraphQL design patterns and best practices
- **Endpoint Design**: Resource modeling, URL structure, and HTTP method selection
- **Data Contracts**: Request/response schemas, validation rules, and data transformation
- **API Documentation**: OpenAPI/Swagger specifications and developer experience
### Role Boundaries & Responsibilities
#### **What This Role OWNS (API Contract Within Architectural Framework)**
- **API Contract Definition**: Specific endpoint paths, HTTP methods, and status codes
- **Resource Modeling**: Mapping domain entities to RESTful resources or GraphQL types
- **Request/Response Schemas**: Detailed data contracts, validation rules, and error formats
- **API Versioning Strategy**: Version management, deprecation policies, and migration paths
- **Developer Experience**: API documentation (OpenAPI/Swagger), code examples, and SDKs
#### **What This Role DOES NOT Own (Defers to Other Roles)**
- **System Architecture Decisions**: Microservices vs monolithic, overall communication patterns → Defers to **System Architect**
- **Canonical Data Model**: Underlying data schemas and entity relationships → Defers to **Data Architect**
- **UI/Frontend Integration**: How clients consume the API → Defers to **UI Designer**
#### **Handoff Points**
- **FROM System Architect**: Receives architectural constraints (REST vs GraphQL, sync vs async) that define the design space
- **FROM Data Architect**: Receives canonical data model and translates it into public API data contracts (as projection/view)
- **TO Frontend Teams**: Provides complete API specifications, documentation, and integration guides
## ⚙️ **Execution Protocol**
### Phase 1: Session & Framework Detection
```bash
# Check active session and framework
CHECK: .workflow/.active-* marker files
IF active_session EXISTS:
session_id = get_active_session()
brainstorm_dir = .workflow/WFS-{session}/.brainstorming/
CHECK: brainstorm_dir/topic-framework.md
IF EXISTS:
framework_mode = true
load_framework = true
ELSE:
IF topic_provided:
framework_mode = false # Create analysis without framework
ELSE:
ERROR: "No framework found and no topic provided"
```
### Phase 2: Analysis Mode Detection
```bash
# Check existing analysis
CHECK: brainstorm_dir/api-designer/analysis.md
IF EXISTS:
SHOW existing analysis summary
ASK: "Analysis exists. Do you want to:"
OPTIONS:
1. "Update with new insights" → Update existing
2. "Replace completely" → Generate new
3. "Cancel" → Exit without changes
ELSE:
CREATE new analysis
```
### Phase 3: Agent Task Generation
**Framework-Based Analysis** (when topic-framework.md exists):
```bash
Task(subagent_type="conceptual-planning-agent",
prompt="Generate API designer analysis addressing topic framework
## Framework Integration Required
**MANDATORY**: Load and address topic-framework.md discussion points
**Framework Reference**: @{session.brainstorm_dir}/topic-framework.md
**Output Location**: {session.brainstorm_dir}/api-designer/analysis.md
## Analysis Requirements
1. **Load Topic Framework**: Read topic-framework.md completely
2. **Address Each Discussion Point**: Respond to all 5 framework sections from API design perspective
3. **Include Framework Reference**: Start analysis.md with @../topic-framework.md
4. **API Design Focus**: Emphasize endpoint structure, data contracts, versioning strategies
5. **Structured Response**: Use framework structure for analysis organization
## Framework Sections to Address
- Core Requirements (from API design perspective)
- Technical Considerations (detailed API architecture analysis)
- User Experience Factors (developer experience and API usability)
- Implementation Challenges (API design risks and solutions)
- Success Metrics (API performance metrics and adoption tracking)
## Output Structure Required
```markdown
# API Designer Analysis: [Topic]
**Framework Reference**: @../topic-framework.md
**Role Focus**: Backend API Design and Contract Definition
## Core Requirements Analysis
[Address framework requirements from API design perspective]
## Technical Considerations
[Detailed API architecture and endpoint design analysis]
## Developer Experience Factors
[API usability, documentation, and integration ease]
## Implementation Challenges
[API design risks and mitigation strategies]
## Success Metrics
[API performance metrics, adoption rates, and developer satisfaction]
## API Design-Specific Recommendations
[Detailed API design recommendations and best practices]
```",
description="Generate API designer framework-based analysis")
```
### Phase 4: Update Mechanism
**Analysis Update Process**:
```bash
# For existing analysis updates
IF update_mode = "incremental":
Task(subagent_type="conceptual-planning-agent",
prompt="Update existing API designer analysis
## Current Analysis Context
**Existing Analysis**: @{session.brainstorm_dir}/api-designer/analysis.md
**Framework Reference**: @{session.brainstorm_dir}/topic-framework.md
## Update Requirements
1. **Preserve Structure**: Maintain existing analysis structure
2. **Add New Insights**: Integrate new API design insights and recommendations
3. **Framework Alignment**: Ensure continued alignment with topic framework
4. **API Updates**: Add new endpoint patterns, versioning strategies, documentation improvements
5. **Maintain References**: Keep @../topic-framework.md reference
## Update Instructions
- Read existing analysis completely
- Identify areas for enhancement or new insights
- Add API design depth while preserving original structure
- Update recommendations with new API design patterns and approaches
- Maintain framework discussion point addressing",
description="Update API designer analysis incrementally")
```
## Document Structure
### Output Files
```
.workflow/WFS-[topic]/.brainstorming/
├── topic-framework.md # Input: Framework (if exists)
└── api-designer/
└── analysis.md # ★ OUTPUT: Framework-based analysis
```
### Analysis Structure
**Required Elements**:
- **Framework Reference**: @../topic-framework.md (if framework exists)
- **Role Focus**: Backend API Design and Contract Definition perspective
- **5 Framework Sections**: Address each framework discussion point
- **API Design Recommendations**: Endpoint-specific insights and solutions
## ⚡ **Two-Step Execution Flow**
### ⚠️ Session Management - FIRST STEP
Session detection and selection:
```bash
# Check for active sessions
active_sessions=$(find .workflow -name ".active-*" 2>/dev/null)
if [ multiple_sessions ]; then
prompt_user_to_select_session()
else
use_existing_or_create_new()
fi
```
### Step 1: Context Gathering Phase
**API Designer Perspective Questioning**
Before agent assignment, gather comprehensive API design context:
#### 📋 Role-Specific Questions
1. **API Type & Architecture**
- RESTful, GraphQL, or hybrid API approach?
- Synchronous vs asynchronous communication patterns?
- Real-time requirements (WebSocket, Server-Sent Events)?
2. **Resource Modeling & Endpoints**
- What are the core domain resources/entities?
- Expected CRUD operations for each resource?
- Complex query requirements (filtering, sorting, pagination)?
3. **Data Contracts & Validation**
- Request/response data format requirements (JSON, XML, Protocol Buffers)?
- Input validation and sanitization requirements?
- Data transformation and mapping needs?
4. **API Management & Governance**
- API versioning strategy requirements?
- Authentication and authorization mechanisms?
- Rate limiting and throttling requirements?
- API documentation and developer portal needs?
5. **Integration & Compatibility**
- Client platforms consuming the API (web, mobile, third-party)?
- Backward compatibility requirements?
- External API integrations needed?
#### Context Validation
- **Minimum Response**: Each answer must be ≥50 characters
- **Re-prompting**: Insufficient detail triggers follow-up questions
- **Context Storage**: Save responses to `.brainstorming/api-designer-context.md`
### Step 2: Agent Assignment with Flow Control
**Dedicated Agent Execution**
```bash
Task(conceptual-planning-agent): "
[FLOW_CONTROL]
Execute dedicated api-designer conceptual analysis for: {topic}
ASSIGNED_ROLE: api-designer
OUTPUT_LOCATION: .brainstorming/api-designer/
USER_CONTEXT: {validated_responses_from_context_gathering}
Flow Control Steps:
[
{
\"step\": \"load_role_template\",
\"action\": \"Load api-designer planning template\",
\"command\": \"bash($(cat ~/.claude/workflows/cli-templates/planning-roles/api-designer.md))\",
\"output_to\": \"role_template\"
}
]
Conceptual Analysis Requirements:
- Apply api-designer perspective to topic analysis
- Focus on endpoint design, data contracts, and API governance
- Use loaded role template framework for analysis structure
- Generate role-specific deliverables in designated output location
- Address all user context from questioning phase
Deliverables:
- analysis.md: Main API design analysis
- api-specification.md: Detailed endpoint specifications
- data-contracts.md: Request/response schemas and validation rules
- api-documentation.md: API documentation strategy and templates
Embody api-designer role expertise for comprehensive conceptual planning."
```
### Progress Tracking
TodoWrite tracking for two-step process:
```json
[
{"content": "Gather API designer context through role-specific questioning", "status": "in_progress", "activeForm": "Gathering context"},
{"content": "Validate context responses and save to api-designer-context.md", "status": "pending", "activeForm": "Validating context"},
{"content": "Load api-designer planning template via flow control", "status": "pending", "activeForm": "Loading template"},
{"content": "Execute dedicated conceptual-planning-agent for api-designer role", "status": "pending", "activeForm": "Executing agent"}
]
```
## 📊 **Output Specification**
### Output Location
```
.workflow/WFS-{topic-slug}/.brainstorming/api-designer/
├── analysis.md # Primary API design analysis
├── api-specification.md # Detailed endpoint specifications (OpenAPI/Swagger)
├── data-contracts.md # Request/response schemas and validation rules
├── versioning-strategy.md # API versioning and backward compatibility plan
└── developer-guide.md # API usage documentation and integration examples
```
### Document Templates
#### analysis.md Structure
```markdown
# API Design Analysis: {Topic}
*Generated: {timestamp}*
## Executive Summary
[Key API design findings and recommendations overview]
## API Architecture Overview
### API Type Selection (REST/GraphQL/Hybrid)
### Communication Patterns
### Authentication & Authorization Strategy
## Resource Modeling
### Core Domain Resources
### Resource Relationships
### URL Structure and Naming Conventions
## Endpoint Design
### Resource Endpoints
- GET /api/v1/resources
- POST /api/v1/resources
- GET /api/v1/resources/{id}
- PUT /api/v1/resources/{id}
- DELETE /api/v1/resources/{id}
### Query Parameters
- Filtering: ?filter[field]=value
- Sorting: ?sort=field,-field2
- Pagination: ?page=1&limit=20
### HTTP Methods and Status Codes
- Success responses (2xx)
- Client errors (4xx)
- Server errors (5xx)
## Data Contracts
### Request Schemas
[JSON Schema or OpenAPI definitions]
### Response Schemas
[JSON Schema or OpenAPI definitions]
### Validation Rules
- Required fields
- Data types and formats
- Business logic constraints
## API Versioning Strategy
### Versioning Approach (URL/Header/Accept)
### Version Lifecycle Management
### Deprecation Policy
### Migration Paths
## Security & Governance
### Authentication Mechanisms
- OAuth 2.0 / JWT / API Keys
### Authorization Patterns
- RBAC / ABAC / Resource-based
### Rate Limiting & Throttling
### CORS and Security Headers
## Error Handling
### Standard Error Response Format
```json
{
"error": {
"code": "ERROR_CODE",
"message": "Human-readable error message",
"details": [],
"trace_id": "uuid"
}
}
```
### Error Code Taxonomy
### Validation Error Responses
## API Documentation
### OpenAPI/Swagger Specification
### Developer Portal Requirements
### Code Examples and SDKs
### Changelog and Migration Guides
## Performance Optimization
### Response Caching Strategies
### Compression (gzip, brotli)
### Field Selection (sparse fieldsets)
### Bulk Operations and Batch Endpoints
## Monitoring & Observability
### API Metrics
- Request count, latency, error rates
- Endpoint usage analytics
### Logging Strategy
### Distributed Tracing
## Developer Experience
### API Usability Assessment
### Integration Complexity
### SDK and Client Library Needs
### Sandbox and Testing Environments
```
#### api-specification.md Structure
```markdown
# API Specification: {Topic}
*OpenAPI 3.0 Specification*
## API Information
- **Title**: {API Name}
- **Version**: 1.0.0
- **Base URL**: https://api.example.com/v1
- **Contact**: api-team@example.com
## Endpoints
### Users API
#### GET /users
**Description**: Retrieve a list of users
**Parameters**:
- `page` (query, integer): Page number (default: 1)
- `limit` (query, integer): Items per page (default: 20, max: 100)
- `sort` (query, string): Sort field (e.g., "created_at", "-updated_at")
- `filter[status]` (query, string): Filter by user status
**Response 200**:
```json
{
"data": [
{
"id": "uuid",
"username": "string",
"email": "string",
"created_at": "2025-10-15T00:00:00Z"
}
],
"meta": {
"page": 1,
"limit": 20,
"total": 100
},
"links": {
"self": "/users?page=1",
"next": "/users?page=2",
"prev": null
}
}
```
#### POST /users
**Description**: Create a new user
**Request Body**:
```json
{
"username": "string (required, 3-50 chars)",
"email": "string (required, valid email)",
"password": "string (required, min 8 chars)",
"profile": {
"first_name": "string (optional)",
"last_name": "string (optional)"
}
}
```
**Response 201**:
```json
{
"data": {
"id": "uuid",
"username": "string",
"email": "string",
"created_at": "2025-10-15T00:00:00Z"
}
}
```
**Response 400** (Validation Error):
```json
{
"error": {
"code": "VALIDATION_ERROR",
"message": "Request validation failed",
"details": [
{
"field": "email",
"message": "Invalid email format"
}
]
}
}
```
[Continue for all endpoints...]
## Authentication
### OAuth 2.0 Flow
1. Client requests authorization
2. User grants permission
3. Client receives access token
4. Client uses token in requests
**Header Format**:
```
Authorization: Bearer {access_token}
```
## Rate Limiting
**Headers**:
- `X-RateLimit-Limit`: 1000
- `X-RateLimit-Remaining`: 999
- `X-RateLimit-Reset`: 1634270400
**Response 429** (Too Many Requests):
```json
{
"error": {
"code": "RATE_LIMIT_EXCEEDED",
"message": "API rate limit exceeded",
"retry_after": 3600
}
}
```
```
## 🔄 **Session Integration**
### Status Synchronization
Upon completion, update `workflow-session.json`:
```json
{
"phases": {
"BRAINSTORM": {
"api_designer": {
"status": "completed",
"completed_at": "timestamp",
"output_directory": ".workflow/WFS-{topic}/.brainstorming/api-designer/",
"key_insights": ["endpoint_design", "versioning_strategy", "data_contracts"]
}
}
}
}
```
### Cross-Role Collaboration
API designer perspective provides:
- **API Contract Specifications** → Frontend Developer
- **Data Schema Requirements** → Data Architect
- **Security Requirements** → Security Expert
- **Integration Endpoints** → System Architect
- **Performance Constraints** → DevOps Engineer
## ✅ **Quality Assurance**
### Required Analysis Elements
- [ ] Complete endpoint inventory with HTTP methods and paths
- [ ] Detailed request/response schemas with validation rules
- [ ] Clear versioning strategy and backward compatibility plan
- [ ] Comprehensive error handling and status code usage
- [ ] API documentation strategy (OpenAPI/Swagger)
### API Design Principles
- [ ] **Consistency**: Uniform naming conventions and patterns across all endpoints
- [ ] **Simplicity**: Intuitive resource modeling and URL structures
- [ ] **Flexibility**: Support for filtering, sorting, pagination, and field selection
- [ ] **Security**: Proper authentication, authorization, and input validation
- [ ] **Performance**: Caching strategies, compression, and efficient data structures
### Developer Experience Validation
- [ ] API is self-documenting with clear endpoint descriptions
- [ ] Error messages are actionable and helpful for debugging
- [ ] Response formats are consistent and predictable
- [ ] Code examples and integration guides are provided
- [ ] Sandbox environment available for testing
### Technical Completeness
- [ ] **Resource Modeling**: All domain entities mapped to API resources
- [ ] **CRUD Coverage**: Complete create, read, update, delete operations
- [ ] **Query Capabilities**: Advanced filtering, sorting, and search functionality
- [ ] **Versioning**: Clear version management and migration paths
- [ ] **Monitoring**: API metrics, logging, and tracing strategies defined
### Integration Readiness
- [ ] **Client Compatibility**: API works with all target client platforms
- [ ] **External Integration**: Third-party API dependencies identified
- [ ] **Backward Compatibility**: Changes don't break existing clients
- [ ] **Migration Path**: Clear upgrade paths for API consumers
- [ ] **SDK Support**: Client libraries and code generation considered

View File

@@ -1,51 +1,65 @@
---
name: artifacts
description: Topic discussion, decomposition, and analysis artifacts generation through structured inquiry
usage: /workflow:brainstorm:artifacts "<topic>"
argument-hint: "topic or challenge description for discussion and analysis"
examples:
- /workflow:brainstorm:artifacts "Build real-time collaboration feature"
- /workflow:brainstorm:artifacts "Optimize database performance for millions of users"
- /workflow:brainstorm:artifacts "Implement secure authentication system"
description: Generate role-specific topic-framework.md dynamically based on selected roles
argument-hint: "topic or challenge description for framework generation"
allowed-tools: TodoWrite(*), Read(*), Write(*), Bash(*), Glob(*)
---
# Workflow Brainstorm Artifacts Command
# Topic Framework Generator Command
## Usage
```bash
/workflow:brainstorm:artifacts "<topic>"
/workflow:brainstorm:artifacts "<topic>" [--roles "role1,role2,role3"]
```
**Recommended Structured Format**:
```bash
/workflow:brainstorm:artifacts "GOAL: [objective] SCOPE: [boundaries] CONTEXT: [background]" [--roles "..."]
```
## Purpose
Dedicated command for topic discussion, decomposition, and analysis artifacts generation. This command focuses on interactive exploration and documentation creation without complex agent workflows.
**Generate dynamic topic-framework.md tailored to selected roles**. Creates role-specific discussion frameworks that address relevant perspectives. If no roles specified, generates comprehensive framework covering common analysis areas.
**⚠️ User Intent Preservation**: Topic description is stored in session metadata and serves as authoritative reference throughout workflow lifecycle.
## Role-Based Framework Generation
**Dynamic Generation**: Framework content adapts based on selected roles
- **With roles**: Generate targeted discussion points for specified roles only
- **Without roles**: Generate comprehensive framework covering all common areas
## Core Workflow
### Discussion & Artifacts Generation Process
### Topic Framework Generation Process
**0. Session Management** ⚠️ FIRST STEP
- **MCP Tools Integration**: Use Code Index for technical context, Exa for industry insights
**Phase 1: Session Management** ⚠️ FIRST STEP
- **Active session detection**: Check `.workflow/.active-*` markers
- **Session selection**: Prompt user if multiple active sessions found
- **Auto-creation**: Create `WFS-[topic-slug]` only if no active session exists
- **Context isolation**: Each session maintains independent analysis state
- **Framework check**: Check if `topic-framework.md` exists (update vs create mode)
**1. Topic Discussion & Inquiry**
- **Interactive exploration**: Direct conversation about topic aspects
- **Structured questioning**: Key areas of investigation
- **Context gathering**: User input and requirements clarification
- **Perspective collection**: Multiple viewpoints and considerations
**Phase 2: Role Analysis** ⚠️ NEW
- **Parse roles parameter**: Extract roles from `--roles "role1,role2,role3"` if provided
- **Role validation**: Verify each role is valid (matches available role commands)
- **Store role list**: Save selected roles to session metadata for reference
- **Default behavior**: If no roles specified, use comprehensive coverage
**2. Topic Decomposition**
- **Component identification**: Break down topic into key areas
- **Relationship mapping**: Connections between components
- **Priority assessment**: Importance and urgency evaluation
- **Constraint analysis**: Limitations and requirements
**Phase 3: Dynamic Topic Analysis**
- **Scope definition**: Define topic boundaries and objectives
- **Stakeholder identification**: Identify key users and stakeholders based on selected roles
- **Requirements gathering**: Extract requirements relevant to selected roles
- **Context collection**: Gather context appropriate for role perspectives
**3. Analysis Artifacts Generation**
- **Discussion summary**: `.workflow/WFS-[topic]/.brainstorming/discussion-summary.md` - Key points and insights
- **Component analysis**: `.workflow/WFS-[topic]/.brainstorming/component-analysis.md` - Detailed decomposition
**Phase 4: Role-Specific Framework Generation**
- **Discussion points creation**: Generate 3-5 discussion areas **tailored to selected roles**
- **Role-targeted questions**: Create questions specifically for chosen roles
- **Framework document**: Generate `topic-framework.md` with role-specific sections
- **Validation check**: Ensure framework addresses all selected role perspectives
**Phase 5: Metadata Storage**
- **Save role assignment**: Store selected roles in session metadata
- **Framework versioning**: Track which roles framework addresses
- **Update tracking**: Maintain role evolution if framework updated
## Implementation Standards
@@ -74,62 +88,200 @@ Dedicated command for topic discussion, decomposition, and analysis artifacts ge
## Document Generation
**Workflow**: Topic Discussion → Component Analysis → Documentation
**Primary Output**: Single structured `topic-framework.md` document
**Document Structure**:
```
.workflow/WFS-[topic]/.brainstorming/
── discussion-summary.md # Main conversation and insights
└── component-analysis.md # Detailed topic breakdown
── topic-framework.md # ★ STRUCTURED FRAMEWORK DOCUMENT
```
**Document Templates**:
**Note**: `workflow-session.json` is located at `.workflow/WFS-[topic]/workflow-session.json` (session root), not inside `.brainstorming/`.
### discussion-summary.md
## Framework Template Structures
### Dynamic Role-Based Framework
Framework content adapts based on `--roles` parameter:
#### Option 1: Specific Roles Provided
```markdown
# Topic Discussion Summary: [topic]
# [Topic] - Discussion Framework
## Overview
Brief description of the topic and its scope.
## Topic Overview
- **Scope**: [Topic boundaries relevant to selected roles]
- **Objectives**: [Goals from perspective of selected roles]
- **Context**: [Background focusing on role-specific concerns]
- **Target Roles**: ui-designer, system-architect, subject-matter-expert
## Key Insights
- Major points discovered during discussion
- Important considerations identified
- Critical success factors
## Role-Specific Discussion Points
## Questions Explored
- Primary areas of investigation
- User responses and clarifications
- Open questions requiring further research
### For UI Designer
1. **User Interface Requirements**
- What interface components are needed?
- What user interactions must be supported?
- What visual design considerations apply?
## Next Steps
- Recommended follow-up actions
- Areas needing deeper analysis
2. **User Experience Challenges**
- What are the key user journeys?
- What accessibility requirements exist?
- How to balance aesthetics with functionality?
### For System Architect
1. **Architecture Decisions**
- What architectural patterns fit this solution?
- What scalability requirements exist?
- How does this integrate with existing systems?
2. **Technical Implementation**
- What technology stack is appropriate?
- What are the performance requirements?
- What dependencies must be managed?
### For Subject Matter Expert
1. **Domain Expertise & Standards**
- What industry standards and best practices apply?
- What regulatory compliance requirements exist?
- What domain-specific patterns should be followed?
2. **Technical Quality & Risk**
- What technical debt considerations exist?
- What scalability and maintenance implications apply?
- What knowledge transfer and documentation is needed?
## Cross-Role Integration Points
- How do UI decisions impact architecture?
- How does architecture constrain UI possibilities?
- What domain standards affect both UI and architecture?
## Framework Usage
**For Role Agents**: Address your specific section + integration points
**Reference Format**: @../topic-framework.md in your analysis.md
**Update Process**: Use /workflow:brainstorm:artifacts to update
---
*Generated for roles: ui-designer, system-architect, subject-matter-expert*
*Last updated: [timestamp]*
```
### component-analysis.md
#### Option 2: No Roles Specified (Comprehensive)
```markdown
# Component Analysis: [topic]
# [Topic] - Discussion Framework
## Core Components
Detailed breakdown of main topic elements:
## Topic Overview
- **Scope**: [Comprehensive topic boundaries]
- **Objectives**: [All-encompassing goals]
- **Context**: [Full background and constraints]
- **Stakeholders**: [All relevant parties]
### Component 1: [Name]
- **Purpose**: What it does
- **Dependencies**: What it relies on
- **Interfaces**: How it connects to other components
## Core Discussion Areas
### Component 2: [Name]
- **Purpose**:
- **Dependencies**:
- **Interfaces**:
### 1. Requirements & Objectives
- What are the fundamental requirements?
- What are the critical success factors?
- What constraints must be considered?
## Component Relationships
- How components interact
- Data flow between components
- Critical dependencies
### 2. Technical & Architecture
- What are the technical challenges?
- What architectural decisions are needed?
- What integration points exist?
### 3. User Experience & Design
- Who are the primary users?
- What are the key user journeys?
- What usability requirements exist?
### 4. Security & Compliance
- What security requirements exist?
- What compliance considerations apply?
- What data protection is needed?
### 5. Implementation & Operations
- What are the implementation risks?
- What resources are required?
- How will this be maintained?
## Available Role Perspectives
Framework supports analysis from any of these roles:
- **Technical**: system-architect, data-architect, subject-matter-expert
- **Product & Design**: ui-designer, ux-expert, product-manager, product-owner
- **Agile & Quality**: scrum-master, test-strategist
---
*Comprehensive framework - adaptable to any role*
*Last updated: [timestamp]*
```
## Role-Specific Content Generation
### Available Roles and Their Focus Areas
**Technical Roles**:
- `system-architect`: Architecture patterns, scalability, technology stack, integration
- `data-architect`: Data modeling, processing workflows, analytics, storage
- `subject-matter-expert`: Domain expertise, industry standards, compliance, best practices
**Product & Design Roles**:
- `ui-designer`: User interface, visual design, interaction patterns, accessibility
- `ux-expert`: User experience optimization, usability testing, interaction design, design systems
- `product-manager`: Business value, feature prioritization, market positioning, roadmap
- `product-owner`: Backlog management, user stories, acceptance criteria, stakeholder alignment
**Agile & Quality Roles**:
- `scrum-master`: Sprint planning, team dynamics, process optimization, delivery management
- `test-strategist`: Testing strategies, quality assurance, test automation, validation approaches
### Dynamic Discussion Point Generation
**For each selected role, generate**:
1. **2-3 core discussion areas** specific to that role's perspective
2. **3-5 targeted questions** per discussion area
3. **Cross-role integration points** showing how roles interact
**Example mapping**:
```javascript
// If roles = ["ui-designer", "system-architect"]
Generate:
- UI Designer section: UI Requirements, UX Challenges
- System Architect section: Architecture Decisions, Technical Implementation
- Integration Points: UIArchitecture dependencies
```
### Framework Generation Examples
#### Example 1: Architecture-Heavy Topic
```bash
/workflow:brainstorm:artifacts "Design scalable microservices platform" --roles "system-architect,data-architect,subject-matter-expert"
```
**Generated framework focuses on**:
- Service architecture and communication patterns
- Data flow and storage strategies
- Domain standards and best practices
#### Example 2: User-Focused Topic
```bash
/workflow:brainstorm:artifacts "Improve user onboarding experience" --roles "ui-designer,ux-expert,product-manager"
```
**Generated framework focuses on**:
- Onboarding flow and UI components
- User experience optimization and usability
- Business value and success metrics
#### Example 3: Agile Delivery Topic
```bash
/workflow:brainstorm:artifacts "Optimize sprint delivery process" --roles "scrum-master,product-owner,test-strategist"
```
**Generated framework focuses on**:
- Sprint planning and team collaboration
- Backlog management and prioritization
- Quality assurance and testing strategies
#### Example 4: Comprehensive Analysis
```bash
/workflow:brainstorm:artifacts "Build real-time collaboration feature"
```
**Generated framework covers** all aspects (no roles specified)
## Session Management ⚠️ CRITICAL
- **⚡ FIRST ACTION**: Check for all `.workflow/.active-*` markers before processing
- **Multiple sessions support**: Different Claude instances can have different active sessions
@@ -162,19 +314,46 @@ Detailed breakdown of main topic elements:
- **Alternatives**: What other approaches exist?
- **Migration**: How do we transition from current state?
## Quality Standards
## Update Mechanism ⚠️ SMART UPDATES
### Discussion Excellence
- **Comprehensive exploration**: Cover all relevant aspects of the topic
- **Clear documentation**: Capture insights in structured, readable format
- **Actionable outcomes**: Generate practical next steps and recommendations
- **User-driven**: Follow user interests and priorities in the discussion
### Framework Update Logic
```bash
# Check existing framework
IF topic-framework.md EXISTS:
SHOW current framework to user
ASK: "Framework exists. Do you want to:"
OPTIONS:
1. "Replace completely" → Generate new framework
2. "Add discussion points" → Append to existing
3. "Refine existing points" → Interactive editing
4. "Cancel" → Exit without changes
ELSE:
CREATE new framework
```
### Documentation Quality
- **Structured format**: Use consistent templates for easy navigation
- **Complete coverage**: Document all important discussion points
- **Clear language**: Avoid jargon, explain technical concepts
- **Practical focus**: Emphasize actionable insights and recommendations
### Update Strategies
**1. Complete Replacement**
- Backup existing framework as `topic-framework-[timestamp].md.backup`
- Generate completely new framework
- Preserve role-specific analysis points from previous version
**2. Incremental Addition**
- Load existing framework
- Identify new discussion areas through user interaction
- Add new sections while preserving existing structure
- Update framework usage instructions
**3. Refinement Mode**
- Interactive editing of existing discussion points
- Allow modification of scope, objectives, and questions
- Preserve framework structure and role assignments
- Update timestamp and version info
### Version Control
- **Backup Creation**: Always backup before major changes
- **Change Tracking**: Include change summary in framework footer
- **Rollback Support**: Keep previous version accessible
## Error Handling
- **Session creation failure**: Provide clear error message and retry option
@@ -191,4 +370,4 @@ Detailed breakdown of main topic elements:
### Integration Points
- **Compatible with**: Other brainstorming commands in the same session
- **Builds foundation for**: More detailed planning and implementation phases
- **Outputs used by**: `/workflow:brainstorm:synthesis` command for cross-analysis integration
- **Outputs used by**: `/workflow:brainstorm:synthesis` command for cross-analysis integration

View File

@@ -0,0 +1,378 @@
---
name: auto-parallel
description: Parallel brainstorming automation with dynamic role selection and concurrent execution
argument-hint: "topic or challenge description" [--count N]
allowed-tools: SlashCommand(*), Task(*), TodoWrite(*), Read(*), Write(*), Bash(*), Glob(*)
---
# Workflow Brainstorm Parallel Auto Command
## Usage
```bash
/workflow:brainstorm:auto-parallel "<topic>" [--count N]
```
**Recommended Structured Format**:
```bash
/workflow:brainstorm:auto-parallel "GOAL: [objective] SCOPE: [boundaries] CONTEXT: [background]" [--count N]
```
**Parameters**:
- `topic` (required): Topic or challenge description (structured format recommended)
- `--count N` (optional): Number of roles to auto-select (default: 3, max: 9)
**⚠️ User Intent Preservation**: Topic description is stored in session metadata as authoritative reference throughout entire brainstorming workflow and plan generation.
## Role Selection Logic
- **Technical & Architecture**: `architecture|system|performance|database|security` → system-architect, data-architect, security-expert, subject-matter-expert
- **API & Backend**: `api|endpoint|rest|graphql|backend|interface|contract|service` → api-designer, system-architect, data-architect
- **Product & UX**: `user|ui|ux|interface|design|product|feature|experience` → ui-designer, user-researcher, product-manager, ux-expert, product-owner
- **Business & Process**: `business|process|workflow|cost|innovation|testing` → business-analyst, innovation-lead, test-strategist
- **Agile & Delivery**: `agile|sprint|scrum|team|collaboration|delivery` → scrum-master, product-owner
- **Domain Expertise**: `domain|standard|compliance|expertise|regulation` → subject-matter-expert
- **Multi-role**: Complex topics automatically select N complementary roles (N specified by --count, default 3)
- **Default**: `product-manager` if no clear match
- **Count Parameter**: `--count N` determines number of roles to auto-select (default: 3, max: 9)
**Template Loading**: `bash($(cat "~/.claude/workflows/cli-templates/planning-roles/<role-name>.md"))`
**Template Source**: `.claude/workflows/cli-templates/planning-roles/`
**Available Roles**: api-designer, data-architect, product-manager, product-owner, scrum-master, subject-matter-expert, system-architect, test-strategist, ui-designer, ux-expert
**Example**:
```bash
bash($(cat "~/.claude/workflows/cli-templates/planning-roles/system-architect.md"))
bash($(cat "~/.claude/workflows/cli-templates/planning-roles/ui-designer.md"))
```
## Core Workflow
### Structured Topic Processing → Role Analysis → Synthesis
The command follows a structured three-phase approach with dedicated document types:
**Phase 1: Framework Generation** ⚠️ COMMAND EXECUTION
- **Role selection**: Auto-select N roles based on topic keywords and --count parameter (default: 3, see Role Selection Logic)
- **Call artifacts command**: Execute `/workflow:brainstorm:artifacts "{topic}" --roles "{role1,role2,...,roleN}"` using SlashCommand tool
- **Role-specific framework**: Generate framework with sections tailored to selected roles
- **⚠️ User intent storage**: Topic saved in workflow-session.json as primary reference for all downstream phases
**Phase 2: Role Analysis Execution** ⚠️ PARALLEL AGENT ANALYSIS
- **Parallel execution**: Multiple roles execute simultaneously for faster completion
- **Independent agents**: Each role gets dedicated conceptual-planning-agent running in parallel
- **Shared framework**: All roles reference the same topic framework for consistency
- **Concurrent generation**: Role-specific analysis documents generated simultaneously
- **Progress tracking**: Parallel agents update progress independently
**Phase 3: Synthesis Generation** ⚠️ COMMAND EXECUTION
- **Call synthesis command**: Execute `/workflow:brainstorm:synthesis` using SlashCommand tool
- **⚠️ User intent injection**: Synthesis loads original topic from session metadata as highest priority reference
- **Intent alignment**: Synthesis validates all role insights against user's original objectives
## Implementation Standards
### Simplified Command Orchestration ⚠️ STREAMLINED
Auto command coordinates independent specialized commands:
**Command Sequence**:
1. **Role Selection**: Auto-select N relevant roles based on topic keywords and --count parameter (default: 3)
2. **Generate Role-Specific Framework**: Use SlashCommand to execute `/workflow:brainstorm:artifacts "{topic}" --roles "{role1,role2,...,roleN}"` (stores user intent in session)
3. **Parallel Role Analysis**: Execute selected role agents in parallel, each reading their specific framework section
4. **Generate Synthesis**: Use SlashCommand to execute `/workflow:brainstorm:synthesis` (loads user intent from session as primary reference)
**SlashCommand Integration**:
1. **artifacts command**: Called via SlashCommand tool with `--roles` parameter for role-specific framework generation
2. **role agents**: Each agent reads its dedicated section in the role-specific framework
3. **synthesis command**: Called via SlashCommand tool for final integration with role-targeted insights
4. **Command coordination**: SlashCommand handles execution and validation
**Role Selection Logic**:
- **Technical**: `architecture|system|performance|database` → system-architect, data-architect, subject-matter-expert
- **API & Backend**: `api|endpoint|rest|graphql|backend|interface|contract|service` → api-designer, system-architect, data-architect
- **Product & UX**: `user|ui|ux|interface|design|product|feature|experience` → ui-designer, ux-expert, product-manager, product-owner
- **Agile & Delivery**: `agile|sprint|scrum|team|collaboration|delivery` → scrum-master, product-owner
- **Domain Expertise**: `domain|standard|compliance|expertise|regulation` → subject-matter-expert
- **Auto-select**: N most relevant roles based on topic analysis (N from --count parameter, default: 3)
### Parameter Parsing
**Count Parameter Handling**:
```bash
# Parse --count parameter from user input
IF user_input CONTAINS "--count":
EXTRACT count_value FROM "--count N" pattern
IF count_value > 9:
count_value = 9 # Cap at maximum 9 roles
END IF
ELSE:
count_value = 3 # Default to 3 roles
END IF
```
**Role Selection with Count**:
1. **Analyze topic keywords**: Identify relevant role categories
2. **Rank roles by relevance**: Score based on keyword matches
3. **Select top N roles**: Pick N most relevant roles (N = count_value)
4. **Ensure diversity**: Balance across different expertise areas
5. **Minimum guarantee**: Always include at least one role (default to product-manager if no matches)
### Simplified Processing Standards
**Core Principles**:
1. **Minimal preprocessing** - Only workflow-session.json and basic role selection
2. **Agent autonomy** - Agents handle their own context and validation
3. **Parallel execution** - Multiple agents can work simultaneously
4. **Post-processing synthesis** - Integration happens after agent completion
5. **TodoWrite control** - Progress tracking throughout all phases
**Implementation Rules**:
- **Role count**: N roles auto-selected based on --count parameter (default: 3, max: 9) and keyword mapping
- **No upfront validation**: Agents handle their own context requirements
- **Parallel execution**: Each agent operates concurrently without dependencies
- **Synthesis at end**: Integration only after all agents complete
**Agent Self-Management** (Agents decide their own approach):
- **Context gathering**: Agents determine what questions to ask
- **Template usage**: Agents load and apply their own role templates
- **Analysis depth**: Agents determine appropriate level of detail
- **Documentation**: Agents create their own file structure and content
### Session Management ⚠️ CRITICAL
- **⚡ FIRST ACTION**: Check for all `.workflow/.active-*` markers before role processing
- **Multiple sessions support**: Different Claude instances can have different active brainstorming sessions
- **User selection**: If multiple active sessions found, prompt user to select which one to work with
- **Auto-session creation**: `WFS-[topic-slug]` only if no active session exists
- **Session continuity**: MUST use selected active session for all role processing
- **Context preservation**: Each role's context and agent output stored in session directory
- **Session isolation**: Each session maintains independent brainstorming state and role assignments
## Document Generation
**Command Coordination Workflow**: artifacts → parallel role analysis → synthesis
**Output Structure**: Coordinated commands generate framework, role analyses, and synthesis documents as defined in their respective command specifications.
## Agent Prompt Templates
### Task Agent Invocation Template
```bash
Task(subagent_type="conceptual-planning-agent",
prompt="Execute brainstorming analysis: {role-name} perspective for {topic}
## Role Assignment
**ASSIGNED_ROLE**: {role-name}
**TOPIC**: {user-provided-topic}
**OUTPUT_LOCATION**: .workflow/WFS-{topic}/.brainstorming/{role}/
## Execution Instructions
[FLOW_CONTROL]
### Flow Control Steps
**AGENT RESPONSIBILITY**: Execute these pre_analysis steps sequentially with context accumulation:
1. **load_topic_framework**
- Action: Load structured topic discussion framework
- Command: bash(cat .workflow/WFS-{topic}/.brainstorming/topic-framework.md 2>/dev/null || echo 'Topic framework not found')
- Output: topic_framework
2. **load_role_template**
- Action: Load {role-name} planning template
- Command: bash($(cat "~/.claude/workflows/cli-templates/planning-roles/{role}.md"))
- Output: role_template
3. **load_session_metadata**
- Action: Load session metadata and original user intent
- Command: bash(cat .workflow/WFS-{topic}/workflow-session.json 2>/dev/null || echo '{}')
- Output: session_metadata (contains original user prompt in 'project' or 'description' field)
### Implementation Context
**⚠️ User Intent Authority**: Original user prompt from session_metadata.project is PRIMARY reference
**Topic Framework**: Use loaded topic-framework.md for structured analysis
**Role Focus**: {role-name} domain expertise and perspective aligned with user intent
**Analysis Type**: Address framework discussion points from role perspective, filtered by user objectives
**Template Framework**: Combine role template with topic framework structure
**Structured Approach**: Create analysis.md addressing all topic framework points relevant to user's goals
### Session Context
**Workflow Directory**: .workflow/WFS-{topic}/.brainstorming/
**Output Directory**: .workflow/WFS-{topic}/.brainstorming/{role}/
**Session JSON**: .workflow/WFS-{topic}/workflow-session.json
### Dependencies & Context
**Topic**: {user-provided-topic}
**Role Template**: "~/.claude/workflows/cli-templates/planning-roles/{role}.md"
**User Requirements**: To be gathered through interactive questioning
## Completion Requirements
1. Execute all flow control steps in sequence (load topic framework, role template, session metadata with user intent)
2. **⚠️ User Intent Alignment**: Validate analysis aligns with original user objectives from session_metadata
3. **Address Topic Framework**: Respond to all discussion points in topic-framework.md from role perspective
4. **Filter by User Goals**: Prioritize insights directly relevant to user's stated objectives
5. Apply role template guidelines within topic framework structure
6. Generate structured role analysis addressing framework points aligned with user intent
7. Create single comprehensive deliverable in OUTPUT_LOCATION:
- analysis.md (structured analysis addressing all topic framework points with role-specific insights filtered by user goals)
8. Include framework reference: @../topic-framework.md in analysis.md
9. Update workflow-session.json with completion status",
description="Execute {role-name} brainstorming analysis")
```
### Parallel Role Agent调用示例
```bash
# Execute N roles in parallel using single message with multiple Task calls
# (N determined by --count parameter, default 3, shown below with 3 roles as example)
Task(subagent_type="conceptual-planning-agent",
prompt="Execute brainstorming analysis: {role-1} perspective for {topic}...",
description="Execute {role-1} brainstorming analysis")
Task(subagent_type="conceptual-planning-agent",
prompt="Execute brainstorming analysis: {role-2} perspective for {topic}...",
description="Execute {role-2} brainstorming analysis")
Task(subagent_type="conceptual-planning-agent",
prompt="Execute brainstorming analysis: {role-3} perspective for {topic}...",
description="Execute {role-3} brainstorming analysis")
# ... repeat for remaining N-3 roles if --count > 3
```
### Direct Synthesis Process (Command-Driven)
**Synthesis execution**: Use SlashCommand to execute `/workflow:brainstorm:synthesis` after role completion
## TodoWrite Control Flow ⚠️ CRITICAL
### Workflow Progress Tracking
**MANDATORY**: Use Claude Code's built-in TodoWrite tool throughout entire brainstorming workflow:
```javascript
// Phase 1: Create initial todo list for command-coordinated brainstorming workflow
TodoWrite({
todos: [
{
content: "Initialize brainstorming session and detect active sessions",
status: "pending",
activeForm: "Initializing brainstorming session"
},
{
content: "Parse --count parameter and select N roles based on topic keyword analysis",
status: "pending",
activeForm: "Parsing parameters and selecting roles for brainstorming"
},
{
content: "Execute artifacts command with selected roles for role-specific framework",
status: "pending",
activeForm: "Generating role-specific topic framework"
},
{
content: "Execute [role-1] analysis [conceptual-planning-agent] [FLOW_CONTROL] addressing framework",
status: "pending",
activeForm: "Executing [role-1] structured framework analysis"
},
{
content: "Execute [role-2] analysis [conceptual-planning-agent] [FLOW_CONTROL] addressing framework",
status: "pending",
activeForm: "Executing [role-2] structured framework analysis"
},
// ... repeat for N roles (N determined by --count parameter, default 3)
{
content: "Execute [role-N] analysis [conceptual-planning-agent] [FLOW_CONTROL] addressing framework",
status: "pending",
activeForm: "Executing [role-N] structured framework analysis"
},
{
content: "Execute synthesis command using SlashCommand for final integration",
status: "pending",
activeForm: "Executing synthesis command for integrated analysis"
}
]
});
// Phase 2: Update status as workflow progresses - ONLY ONE task should be in_progress at a time
TodoWrite({
todos: [
{
content: "Initialize brainstorming session and detect active sessions",
status: "completed", // Mark completed preprocessing
activeForm: "Initializing brainstorming session"
},
{
content: "Select roles for topic analysis and create workflow-session.json",
status: "in_progress", // Mark current task as in_progress
activeForm: "Selecting roles and creating session metadata"
},
// ... other tasks remain pending
]
});
// Phase 3: Parallel agent execution tracking (N roles, N from --count parameter)
TodoWrite({
todos: [
// ... previous completed tasks
{
content: "Execute [role-1] analysis [conceptual-planning-agent] [FLOW_CONTROL]",
status: "in_progress", // Executing in parallel
activeForm: "Executing [role-1] brainstorming analysis"
},
{
content: "Execute [role-2] analysis [conceptual-planning-agent] [FLOW_CONTROL]",
status: "in_progress", // Executing in parallel
activeForm: "Executing [role-2] brainstorming analysis"
},
// ... repeat for remaining N-2 roles
{
content: "Execute [role-N] analysis [conceptual-planning-agent] [FLOW_CONTROL]",
status: "in_progress", // Executing in parallel
activeForm: "Executing [role-N] brainstorming analysis"
}
]
});
```
**TodoWrite Integration Rules**:
1. **Create initial todos**: All workflow phases at start
2. **Mark in_progress**: Multiple parallel tasks can be in_progress simultaneously
3. **Update immediately**: After each task completion
4. **Track agent execution**: Include [agent-type] and [FLOW_CONTROL] markers for parallel agents
5. **Final synthesis**: Mark synthesis as in_progress only after all parallel agents complete
## Reference Information
### Structured Processing Schema
Each role processing follows structured framework pattern:
- **topic_framework**: Structured discussion framework document
- **role**: Selected planning role name with framework reference
- **agent**: Dedicated conceptual-planning-agent instance
- **structured_analysis**: Agent addresses all framework discussion points
- **output**: Role-specific analysis.md addressing topic framework structure
### File Structure Reference
**Architecture**: @~/.claude/workflows/workflow-architecture.md
**Role Templates**: @~/.claude/workflows/cli-templates/planning-roles/
### Execution Integration
Command coordination model: artifacts command → parallel role analysis → synthesis command
## Error Handling
- **Role selection failure**: Default to `product-manager` with explanation
- **Agent execution failure**: Agent-specific retry with minimal dependencies
- **Template loading issues**: Agent handles graceful degradation
- **Synthesis conflicts**: Synthesis agent highlights disagreements without resolution
## Quality Standards
### Agent Autonomy Excellence
- **Single role focus**: Each agent handles exactly one role independently
- **Self-contained execution**: Agent manages own context, validation, and output
- **Parallel processing**: Multiple agents can execute simultaneously
- **Complete ownership**: Agent produces entire role-specific analysis package
### Minimal Coordination Excellence
- **Lightweight handoff**: Only topic and role assignment provided
- **Agent self-management**: Agents handle their own workflow and validation
- **Concurrent operation**: No inter-agent dependencies enabling parallel execution
- **Reference-based synthesis**: Post-processing integration without content duplication
- **TodoWrite orchestration**: Progress tracking and workflow control throughout entire process

View File

@@ -1,245 +0,0 @@
---
name: auto
description: Intelligent brainstorming automation with dynamic role selection and guided context gathering
usage: /workflow:brainstorm:auto "<topic>"
argument-hint: "topic or challenge description"
examples:
- /workflow:brainstorm:auto "Build real-time collaboration feature"
- /workflow:brainstorm:auto "Optimize database performance for millions of users"
- /workflow:brainstorm:auto "Implement secure authentication system"
allowed-tools: Task(*), TodoWrite(*), Read(*), Write(*), Bash(*), Glob(*)
---
# Workflow Brainstorm Auto Command
## Usage
```bash
/workflow:brainstorm:auto "<topic>"
```
## Role Selection Logic
- **Technical & Architecture**: `architecture|system|performance|database|security` → system-architect, data-architect, security-expert
- **Product & UX**: `user|ui|ux|interface|design|product|feature` → ui-designer, user-researcher, product-manager
- **Business & Process**: `business|process|workflow|cost|innovation|testing` → business-analyst, innovation-lead, test-strategist
- **Multi-role**: Complex topics automatically select 2-3 complementary roles
- **Default**: `product-manager` if no clear match
**Template Loading**: `bash($(cat ~/.claude/workflows/cli-templates/planning-roles/<role-name>.md))`
**Template Source**: `.claude/workflows/cli-templates/planning-roles/`
**Available Roles**: business-analyst, data-architect, feature-planner, innovation-lead, product-manager, security-expert, system-architect, test-strategist, ui-designer, user-researcher
**Example**:
```bash
bash($(cat ~/.claude/workflows/cli-templates/planning-roles/system-architect.md))
bash($(cat ~/.claude/workflows/cli-templates/planning-roles/ui-designer.md))
ls ~/.claude/workflows/cli-templates/planning-roles/ # Show all available roles
```
## Core Workflow
### Analysis & Planning Process
The command performs dedicated role analysis through:
**0. Session Management** ⚠️ FIRST STEP
- **MCP Tools Integration**: Use Code Index for codebase context, Exa for external insights
- **Active session detection**: Check `.workflow/.active-*` markers
- **Session selection**: Prompt user if multiple active sessions found
- **Auto-creation**: Create `WFS-[topic-slug]` only if no active session exists
- **Context isolation**: Each session maintains independent brainstorming state
**1. Role Selection & Template Loading**
- **Keyword analysis**: Extract topic keywords and map to planning roles
- **Template loading**: Load role templates via `bash($(cat ~/.claude/workflows/cli-templates/planning-roles/<role>.md))`
- **Role validation**: Verify against `.claude/workflows/cli-templates/planning-roles/`
- **Multi-role detection**: Select 1-3 complementary roles based on topic complexity
**2. Sequential Role Processing** ⚠️ CRITICAL ARCHITECTURE
- **One Role = One Agent**: Each role gets dedicated conceptual-planning-agent
- **Context gathering**: Role-specific questioning with validation
- **Agent submission**: Complete context handoff to single-role agents
- **Progress tracking**: Real-time TodoWrite updates per role
**3. Analysis Artifacts Generated**
- **Role contexts**: `.workflow/WFS-[topic]/.brainstorming/[role]-context.md` - User responses per role
- **Agent outputs**: `.workflow/WFS-[topic]/.brainstorming/[role]/analysis.md` - Dedicated role analysis
- **Session metadata**: `.workflow/WFS-[topic]/.brainstorming/auto-session.json` - Agent assignments and validation
- **Synthesis**: `.workflow/WFS-[topic]/.brainstorming/synthesis/integrated-analysis.md` - Multi-role integration
## Implementation Standards
### Dedicated Agent Architecture ⚠️ CRITICAL
Agents receive dedicated role assignments with complete context isolation:
```json
"agent_assignment": {
"role": "system-architect",
"agent_id": "conceptual-planning-agent-system-architect",
"context_source": ".workflow/WFS-[topic]/.brainstorming/system-architect-context.md",
"output_location": ".workflow/WFS-[topic]/.brainstorming/system-architect/",
"flow_control": {
"pre_analysis": [
{
"step": "load_role_template",
"action": "Load system-architect planning template",
"command": "bash($(cat ~/.claude/workflows/cli-templates/planning-roles/system-architect.md))",
"output_to": "role_template"
},
{
"step": "load_user_context",
"action": "Load user responses and context for role analysis",
"command": "bash(cat .workflow/WFS-[topic]/.brainstorming/system-architect-context.md)",
"output_to": "user_context"
},
{
"step": "load_content_analysis",
"action": "Load existing content analysis documents if available",
"command": "bash(find .workflow/*/.brainstorming/ -name '*.md' -path '*/analysis/*' -o -name 'content-analysis.md' | head -5 | xargs cat 2>/dev/null || echo 'No content analysis found')",
"output_to": "content_analysis"
},
{
"step": "load_session_metadata",
"action": "Load session metadata and previous analysis state",
"command": "bash(cat .workflow/WFS-[topic]/.brainstorming/auto-session.json 2>/dev/null || echo '{}')",
"output_to": "session_metadata"
}
],
"implementation_approach": {
"task_description": "Execute dedicated system-architect conceptual analysis for: [topic]",
"role_focus": "system-architect",
"user_context": "Direct user responses from context gathering phase",
"deliverables": "conceptual_analysis, strategic_recommendations, role_perspective"
}
}
}
```
**Context Accumulation & Role Isolation**:
1. **Role template loading**: Planning role template with domain expertise via CLI
2. **User context loading**: Direct user responses and context from interactive questioning
3. **Content analysis integration**: Existing analysis documents and session metadata
4. **Context validation**: Minimum response requirements with re-prompting
5. **Conceptual analysis**: Role-specific perspective on topic without implementation details
6. **Agent delegation**: Complete context handoff to dedicated conceptual-planning-agent with all references
**Content Sources**:
- Role templates: `bash($(cat ~/.claude/workflows/cli-templates/planning-roles/<role>.md))` from `.claude/workflows/cli-templates/planning-roles/`
- User responses: `bash(cat .workflow/WFS-[topic]/.brainstorming/<role>-context.md)` from interactive questioning phase
- Content analysis: `bash(find .workflow/*/.brainstorming/ -name '*.md' -path '*/analysis/*')` existing analysis documents
- Session metadata: `bash(cat .workflow/WFS-[topic]/.brainstorming/auto-session.json)` for analysis state and context
- Conceptual focus: Strategic and planning perspective without technical implementation
**Trigger Conditions**: Topic analysis matches role domains, user provides adequate context responses, role template successfully loaded
### Role Processing Standards
**Core Principles**:
1. **Sequential Processing** - Complete each role fully before proceeding to next
2. **Context Validation** - Ensure adequate detail before agent submission
3. **Dedicated Assignment** - One conceptual-planning-agent per role
4. **Progress Tracking** - Real-time TodoWrite updates for role processing stages
**Implementation Rules**:
- **Maximum 3 roles**: Auto-selected based on topic complexity and domain overlap
- **Context validation**: Minimum response length and completeness checks
- **Agent isolation**: Each agent receives only role-specific context
- **Error recovery**: Role-specific validation and retry logic
**Role Question Templates**:
- **system-architect**: Scale requirements, integration needs, technology constraints, non-functional requirements
- **security-expert**: Sensitive data types, compliance requirements, threat concerns, auth/authz needs
- **ui-designer**: User personas, platform support, design guidelines, accessibility requirements
- **product-manager**: Business objectives, stakeholders, success metrics, timeline constraints
- **data-architect**: Data types, volume projections, compliance needs, analytics requirements
### Session Management ⚠️ CRITICAL
- **⚡ FIRST ACTION**: Check for all `.workflow/.active-*` markers before role processing
- **Multiple sessions support**: Different Claude instances can have different active brainstorming sessions
- **User selection**: If multiple active sessions found, prompt user to select which one to work with
- **Auto-session creation**: `WFS-[topic-slug]` only if no active session exists
- **Session continuity**: MUST use selected active session for all role processing
- **Context preservation**: Each role's context and agent output stored in session directory
- **Session isolation**: Each session maintains independent brainstorming state and role assignments
## Document Generation
**Workflow**: Interactive Discussion → Topic Decomposition → Role Selection → Context Gathering → Agent Delegation → Documentation → Synthesis
**Always Created**:
- **discussion-summary.md**: Main conversation points and key insights from interactive discussion
- **component-analysis.md**: Detailed breakdown of topic components from discussion phase
- **auto-session.json**: Agent assignments, context validation, completion tracking
- **[role]-context.md**: User responses per role with question-answer pairs
**Auto-Created (per role)**:
- **[role]/analysis.md**: Main role analysis from dedicated agent
- **[role]/recommendations.md**: Role-specific recommendations
- **[role]-template.md**: Loaded role planning template
**Auto-Created (multi-role)**:
- **synthesis/integrated-analysis.md**: Cross-role integration and consensus analysis
- **synthesis/consensus-matrix.md**: Agreement/disagreement analysis
- **synthesis/priority-recommendations.md**: Prioritized action items
**Document Structure**:
```
.workflow/WFS-[topic]/.brainstorming/
├── discussion-summary.md # Main conversation and insights
├── component-analysis.md # Detailed topic breakdown
├── auto-session.json # Session metadata and agent tracking
├── system-architect-context.md # User responses for system-architect
├── system-architect-template.md# Loaded role template
├── system-architect/ # Dedicated agent outputs
│ ├── analysis.md
│ ├── recommendations.md
│ └── deliverables/
├── ui-designer-context.md # User responses for ui-designer
├── ui-designer/ # Dedicated agent outputs
│ └── analysis.md
└── synthesis/ # Multi-role integration
├── integrated-analysis.md
├── consensus-matrix.md
└── priority-recommendations.md
```
## Reference Information
### Role Processing Schema (Sequential Architecture)
Each role processing follows dedicated agent pattern:
- **role**: Selected planning role name
- **template**: Loaded from cli-templates/planning-roles/
- **context**: User responses with validation
- **agent**: Dedicated conceptual-planning-agent instance
- **output**: Role-specific analysis directory
### File Structure Reference
**Architecture**: @~/.claude/workflows/workflow-architecture.md
**Role Templates**: @~/.claude/workflows/cli-templates/planning-roles/
### Execution Integration
Documents created for synthesis and action planning:
- **auto-session.json**: Agent tracking and session metadata
- **[role]-context.md**: Context loading for role analysis
- **[role]/analysis.md**: Role-specific analysis outputs
- **synthesis/**: Multi-role integration for comprehensive planning
## Error Handling
- **Role selection failure**: Default to `product-manager` with explanation
- **Context validation failure**: Re-prompt with minimum requirements
- **Agent execution failure**: Role-specific retry with corrected context
- **Template loading issues**: Graceful degradation with fallback questions
- **Multi-role conflicts**: Synthesis agent handles disagreement resolution
## Quality Standards
### Dedicated Agent Excellence
- **Single role focus**: Each agent handles exactly one role - no multi-role assignments
- **Complete context**: Each agent receives comprehensive role-specific context
- **Sequential processing**: Roles processed one at a time with full validation
- **Dedicated output**: Each agent produces role-specific analysis and deliverables
### Context Collection Excellence
- **Role-specific questioning**: Targeted questions for each role's domain expertise
- **Context validation**: Verification before agent submission to ensure completeness
- **User guidance**: Clear explanations of role perspective and question importance
- **Response quality**: Minimum response requirements with re-prompting for insufficient detail

View File

@@ -1,273 +0,0 @@
---
name: business-analyst
description: Business analyst perspective brainstorming for process optimization and business efficiency analysis
usage: /workflow:brainstorm:business-analyst <topic>
argument-hint: "topic or challenge to analyze from business analysis perspective"
examples:
- /workflow:brainstorm:business-analyst "workflow automation opportunities"
- /workflow:brainstorm:business-analyst "business process optimization"
- /workflow:brainstorm:business-analyst "cost reduction initiatives"
allowed-tools: Task(conceptual-planning-agent), TodoWrite(*)
---
## 📊 **Role Overview: Business Analyst**
### Role Definition
Business process expert responsible for analyzing workflows, identifying requirements, and optimizing business operations to maximize value and efficiency.
### Core Responsibilities
- **Process Analysis**: Analyze existing business processes for efficiency and improvement opportunities
- **Requirements Analysis**: Identify and define business requirements and functional specifications
- **Value Assessment**: Evaluate solution business value and return on investment
- **Change Management**: Plan and manage business process changes
### Focus Areas
- **Process Optimization**: Workflows, automation opportunities, efficiency improvements
- **Data Analysis**: Business metrics, KPI design, performance measurement
- **Cost-Benefit**: ROI analysis, cost optimization, value creation
- **Risk Management**: Business risks, compliance requirements, change risks
### Success Metrics
- Process efficiency improvements (time/cost reduction)
- Requirements clarity and completeness
- Stakeholder satisfaction levels
- ROI achievement and value delivery
## 🧠 **Analysis Framework**
@~/.claude/workflows/brainstorming-principles.md
### Key Analysis Questions
**1. Business Process Analysis**
- What are the bottlenecks and inefficiencies in current business processes?
- Which processes can be automated or simplified?
- What are the obstacles in cross-departmental collaboration?
**2. Business Requirements Identification**
- What are the core needs of stakeholders?
- What are the business objectives and success metrics?
- How should functional and non-functional requirements be prioritized?
**3. Value and Benefit Analysis**
- What is the expected business value of the solution?
- How does implementation cost compare to expected benefits?
- What are the risk assessments and mitigation strategies?
**4. Implementation and Change Management**
- How will changes impact existing processes?
- What training and adaptation requirements exist?
- What success metrics and monitoring mechanisms are needed?
## ⚡ **Two-Step Execution Flow**
### ⚠️ Session Management - FIRST STEP
Session detection and selection:
```bash
# Check for active sessions
active_sessions=$(find .workflow -name ".active-*" 2>/dev/null)
if [ multiple_sessions ]; then
prompt_user_to_select_session()
else
use_existing_or_create_new()
fi
```
### Step 1: Context Gathering Phase
**Business Analyst Perspective Questioning**
Before agent assignment, gather comprehensive business analyst context:
#### 📋 Role-Specific Questions
**1. Business Process Analysis**
- What are the current business processes and workflows that need analysis?
- Which departments, teams, or stakeholders are involved in these processes?
- What are the key bottlenecks, inefficiencies, or pain points you've observed?
- What metrics or KPIs are currently used to measure process performance?
**2. Cost and Resource Analysis**
- What are the current costs associated with these processes (time, money, resources)?
- How much time do stakeholders spend on these activities daily/weekly?
- What technology, tools, or systems are currently being used?
- What budget constraints or financial targets need to be considered?
**3. Business Requirements and Objectives**
- What are the primary business objectives this analysis should achieve?
- Who are the key stakeholders and what are their specific needs?
- What are the success criteria and how will you measure improvement?
- Are there any compliance, regulatory, or governance requirements?
**4. Change Management and Implementation**
- How ready is the organization for process changes?
- What training or change management support might be needed?
- What timeline or deadlines are we working with?
- What potential resistance or challenges do you anticipate?
#### Context Validation
- **Minimum Response**: Each answer must be ≥50 characters
- **Re-prompting**: Insufficient detail triggers follow-up questions
- **Context Storage**: Save responses to `.brainstorming/business-analyst-context.md`
### Step 2: Agent Assignment with Flow Control
**Dedicated Agent Execution**
```bash
Task(conceptual-planning-agent): "
[FLOW_CONTROL]
Execute dedicated business analyst conceptual analysis for: {topic}
ASSIGNED_ROLE: business-analyst
OUTPUT_LOCATION: .brainstorming/business-analyst/
USER_CONTEXT: {validated_responses_from_context_gathering}
Flow Control Steps:
[
{
\"step\": \"load_role_template\",
\"action\": \"Load business-analyst planning template\",
\"command\": \"bash($(cat ~/.claude/workflows/cli-templates/planning-roles/business-analyst.md))\",
\"output_to\": \"role_template\"
}
]
Conceptual Analysis Requirements:
- Apply business analyst perspective to topic analysis
- Focus on process optimization, cost-benefit analysis, and change management
- Use loaded role template framework for analysis structure
- Generate role-specific deliverables in designated output location
- Address all user context from questioning phase
Deliverables:
- analysis.md: Main business analyst analysis
- recommendations.md: Business analyst recommendations
- deliverables/: Business analyst-specific outputs as defined in role template
Embody business analyst role expertise for comprehensive conceptual planning."
```
### Progress Tracking
TodoWrite tracking for two-step process:
```json
[
{"content": "Gather business analyst context through role-specific questioning", "status": "in_progress", "activeForm": "Gathering context"},
{"content": "Validate context responses and save to business-analyst-context.md", "status": "pending", "activeForm": "Validating context"},
{"content": "Load business-analyst planning template via flow control", "status": "pending", "activeForm": "Loading template"},
{"content": "Execute dedicated conceptual-planning-agent for business-analyst role", "status": "pending", "activeForm": "Executing agent"}
]
```
## 📊 **Output Structure**
### Output Location
```
.workflow/WFS-{topic-slug}/.brainstorming/business-analyst/
├── analysis.md # Main business analysis and process assessment
├── requirements.md # Detailed business requirements and specifications
├── business-case.md # Cost-benefit analysis and financial justification
└── implementation-plan.md # Change management and implementation strategy
```
### Document Templates
#### analysis.md Structure
```markdown
# Business Analyst Analysis: {Topic}
*Generated: {timestamp}*
## Executive Summary
[Overview of key business analysis findings and recommendations]
## Current State Assessment
### Business Process Mapping
### Stakeholder Analysis
### Performance Metrics Analysis
### Pain Points and Inefficiencies
## Business Requirements
### Functional Requirements
### Non-Functional Requirements
### Stakeholder Needs Analysis
### Requirements Prioritization
## Process Optimization Opportunities
### Automation Potential
### Workflow Improvements
### Resource Optimization
### Quality Enhancements
## Financial Analysis
### Cost-Benefit Analysis
### ROI Calculations
### Budget Requirements
### Financial Projections
## Risk Assessment
### Business Risks
### Operational Risks
### Mitigation Strategies
### Contingency Planning
## Implementation Strategy
### Change Management Plan
### Training Requirements
### Timeline and Milestones
### Success Metrics and KPIs
## Recommendations
### Immediate Actions (0-3 months)
### Medium-term Initiatives (3-12 months)
### Long-term Strategic Goals (12+ months)
### Resource Requirements
```
## 🔄 **Session Integration**
### Status Synchronization
After analysis completion, update `workflow-session.json`:
```json
{
"phases": {
"BRAINSTORM": {
"business_analyst": {
"status": "completed",
"completed_at": "timestamp",
"output_directory": ".workflow/WFS-{topic}/.brainstorming/business-analyst/",
"key_insights": ["process_optimization", "cost_saving", "efficiency_gain"]
}
}
}
}
```
### Collaboration with Other Roles
Business analyst perspective provides to other roles:
- **Business requirements and constraints** → Product Manager
- **Process technology requirements** → System Architect
- **Business process interface needs** → UI Designer
- **Business data requirements** → Data Architect
- **Business security requirements** → Security Expert
## ✅ **Quality Standards**
### Required Analysis Elements
- [ ] Detailed business process mapping
- [ ] Clear requirements specifications and priorities
- [ ] Quantified cost-benefit analysis
- [ ] Comprehensive risk assessment
- [ ] Actionable implementation plan
### Business Analysis Principles Checklist
- [ ] Value-oriented: Focus on business value creation
- [ ] Data-driven: Analysis based on facts and data
- [ ] Holistic thinking: Consider entire business ecosystem
- [ ] Risk awareness: Identify and manage various risks
- [ ] Sustainability: Long-term maintainability and improvement
### Analysis Quality Metrics
- [ ] Requirements completeness and accuracy
- [ ] Quantified benefits from process optimization
- [ ] Comprehensiveness of risk assessment
- [ ] Feasibility of implementation plan
- [ ] Stakeholder satisfaction levels

View File

@@ -1,274 +1,220 @@
---
name: data-architect
description: Data architect perspective brainstorming for data modeling, flow, and analytics analysis
usage: /workflow:brainstorm:data-architect <topic>
argument-hint: "topic or challenge to analyze from data architecture perspective"
examples:
- /workflow:brainstorm:data-architect "user analytics data pipeline"
- /workflow:brainstorm:data-architect "real-time data processing system"
- /workflow:brainstorm:data-architect "data warehouse modernization"
allowed-tools: Task(conceptual-planning-agent), TodoWrite(*)
description: Generate or update data-architect/analysis.md addressing topic-framework discussion points
argument-hint: "optional topic - uses existing framework if available"
allowed-tools: Task(conceptual-planning-agent), TodoWrite(*), Read(*), Write(*)
---
## 📊 **Role Overview: Data Architect**
## 📊 **Data Architect Analysis Generator**
### Role Definition
Strategic data professional responsible for designing scalable, efficient data architectures that enable data-driven decision making through robust data models, processing pipelines, and analytics platforms.
### Purpose
**Specialized command for generating data-architect/analysis.md** that addresses topic-framework.md discussion points from data architecture perspective. Creates or updates role-specific analysis with framework references.
### Core Responsibilities
- **Data Model Design**: Create efficient and scalable data models and schemas
- **Data Flow Design**: Plan data collection, processing, and storage workflows
- **Data Quality Management**: Ensure data accuracy, completeness, and consistency
- **Analytics and Insights**: Design data analysis and business intelligence solutions
### Core Function
- **Framework-based Analysis**: Address each discussion point in topic-framework.md
- **Data Architecture Focus**: Data models, pipelines, governance, and analytics perspective
- **Update Mechanism**: Create new or update existing analysis.md
- **Agent Delegation**: Use conceptual-planning-agent for analysis generation
### Focus Areas
- **Data Modeling**: Relational models, NoSQL, data warehouses, lakehouse architectures
- **Data Pipelines**: ETL/ELT processes, real-time processing, batch processing
- **Data Governance**: Data quality, security, privacy, compliance frameworks
- **Analytics Platforms**: BI tools, machine learning infrastructure, reporting systems
### Analysis Scope
- **Data Model Design**: Efficient and scalable data models and schemas
- **Data Flow Design**: Data collection, processing, and storage workflows
- **Data Quality Management**: Data accuracy, completeness, and consistency
- **Analytics and Insights**: Data analysis and business intelligence solutions
### Success Metrics
- Data quality and consistency metrics
- Processing performance and throughput
- Analytics accuracy and business impact
- Data governance and compliance adherence
### Role Boundaries & Responsibilities
## 🧠 **Analysis Framework**
#### **What This Role OWNS (Canonical Data Model - Source of Truth)**
- **Canonical Data Model**: The authoritative, system-wide data schema representing domain entities and relationships
- **Entity-Relationship Design**: Defining entities, attributes, relationships, and constraints
- **Data Normalization & Optimization**: Ensuring data integrity, reducing redundancy, and optimizing storage
- **Database Schema Design**: Physical database structures, indexes, partitioning strategies
- **Data Pipeline Architecture**: ETL/ELT processes, data warehousing, and analytics pipelines
- **Data Governance**: Data quality standards, retention policies, and compliance requirements
@~/.claude/workflows/brainstorming-principles.md
#### **What This Role DOES NOT Own (Defers to Other Roles)**
- **API Data Contracts**: Public-facing request/response schemas exposed by APIs → Defers to **API Designer**
- **System Integration Patterns**: How services communicate at the macro level → Defers to **System Architect**
- **UI Data Presentation**: How data is displayed to users → Defers to **UI Designer**
### Key Analysis Questions
#### **Handoff Points**
- **TO API Designer**: Provides canonical data model that API Designer translates into public API data contracts (as projection/view)
- **TO System Architect**: Provides data flow requirements and storage constraints to inform system design
- **FROM System Architect**: Receives system-level integration requirements and scalability constraints
**1. Data Requirements and Sources**
- What data is needed to support business decisions and analytics?
- How reliable and high-quality are the available data sources?
- What is the balance between real-time and historical data needs?
## ⚙️ **Execution Protocol**
**2. Data Architecture and Storage**
- What is the most appropriate data storage solution for requirements?
- How should we design scalable and maintainable data models?
- What are the optimal data partitioning and indexing strategies?
**3. Data Processing and Workflows**
- What are the performance requirements for data processing?
- How should we design fault-tolerant and resilient data pipelines?
- What data versioning and change management strategies are needed?
**4. Analytics and Reporting**
- How can we support diverse analytical requirements and use cases?
- What balance between real-time dashboards and periodic reports is optimal?
- What self-service analytics and data visualization capabilities are needed?
## ⚡ **Two-Step Execution Flow**
### ⚠️ Session Management - FIRST STEP
Session detection and selection:
### Phase 1: Session & Framework Detection
```bash
# Check for active sessions
active_sessions=$(find .workflow -name ".active-*" 2>/dev/null)
if [ multiple_sessions ]; then
prompt_user_to_select_session()
else
use_existing_or_create_new()
fi
# Check active session and framework
CHECK: .workflow/.active-* marker files
IF active_session EXISTS:
session_id = get_active_session()
brainstorm_dir = .workflow/WFS-{session}/.brainstorming/
CHECK: brainstorm_dir/topic-framework.md
IF EXISTS:
framework_mode = true
load_framework = true
ELSE:
IF topic_provided:
framework_mode = false # Create analysis without framework
ELSE:
ERROR: "No framework found and no topic provided"
```
### Step 1: Context Gathering Phase
**Data Architect Perspective Questioning**
### Phase 2: Analysis Mode Detection
```bash
# Determine execution mode
IF framework_mode == true:
mode = "framework_based_analysis"
topic_ref = load_framework_topic()
discussion_points = extract_framework_points()
ELSE:
mode = "standalone_analysis"
topic_ref = provided_topic
discussion_points = generate_basic_structure()
```
Before agent assignment, gather comprehensive data architect context:
#### 📋 Role-Specific Questions
**1. Data Models and Flow Patterns**
- What types of data will you be working with (structured, semi-structured, unstructured)?
- What are the expected data volumes and growth projections?
- What are the primary data sources and how frequently will data be updated?
- Are there existing data models or schemas that need to be considered?
**2. Storage Strategies and Performance**
- What are the query performance requirements and expected response times?
- Do you need real-time processing, batch processing, or both?
- What are the data retention and archival requirements?
- Are there specific compliance or regulatory requirements for data storage?
**3. Analytics Requirements and Insights**
- What types of analytics and reporting capabilities are needed?
- Who are the primary users of the data and what are their skill levels?
- What business intelligence or machine learning use cases need to be supported?
- Are there specific dashboard or visualization requirements?
**4. Data Governance and Quality**
- What data quality standards and validation rules need to be implemented?
- Who owns the data and what are the access control requirements?
- Are there data privacy or security concerns that need to be addressed?
- What data lineage and auditing capabilities are required?
#### Context Validation
- **Minimum Response**: Each answer must be ≥50 characters
- **Re-prompting**: Insufficient detail triggers follow-up questions
- **Context Storage**: Save responses to `.brainstorming/data-architect-context.md`
### Step 2: Agent Assignment with Flow Control
**Dedicated Agent Execution**
### Phase 3: Agent Execution with Flow Control
**Framework-Based Analysis Generation**
```bash
Task(conceptual-planning-agent): "
[FLOW_CONTROL]
Execute dedicated data architect conceptual analysis for: {topic}
Execute data-architect analysis for existing topic framework
## Context Loading
ASSIGNED_ROLE: data-architect
OUTPUT_LOCATION: .brainstorming/data-architect/
USER_CONTEXT: {validated_responses_from_context_gathering}
OUTPUT_LOCATION: .workflow/WFS-{session}/.brainstorming/data-architect/
ANALYSIS_MODE: {framework_mode ? "framework_based" : "standalone"}
Flow Control Steps:
[
{
\"step\": \"load_role_template\",
\"action\": \"Load data-architect planning template\",
\"command\": \"bash($(cat ~/.claude/workflows/cli-templates/planning-roles/data-architect.md))\",
\"output_to\": \"role_template\"
}
]
## Flow Control Steps
1. **load_topic_framework**
- Action: Load structured topic discussion framework
- Command: Read(.workflow/WFS-{session}/.brainstorming/topic-framework.md)
- Output: topic_framework_content
Conceptual Analysis Requirements:
- Apply data architect perspective to topic analysis
- Focus on data models, flow patterns, storage strategies, and analytics requirements
- Use loaded role template framework for analysis structure
- Generate role-specific deliverables in designated output location
- Address all user context from questioning phase
2. **load_role_template**
- Action: Load data-architect planning template
- Command: bash($(cat ~/.claude/workflows/cli-templates/planning-roles/data-architect.md))
- Output: role_template_guidelines
Deliverables:
- analysis.md: Main data architect analysis
- recommendations.md: Data architect recommendations
- deliverables/: Data architect-specific outputs as defined in role template
3. **load_session_metadata**
- Action: Load session metadata and existing context
- Command: Read(.workflow/WFS-{session}/workflow-session.json)
- Output: session_context
Embody data architect role expertise for comprehensive conceptual planning."
## Analysis Requirements
**Framework Reference**: Address all discussion points in topic-framework.md from data architecture perspective
**Role Focus**: Data models, pipelines, governance, analytics platforms
**Structured Approach**: Create analysis.md addressing framework discussion points
**Template Integration**: Apply role template guidelines within framework structure
## Expected Deliverables
1. **analysis.md**: Comprehensive data architecture analysis addressing all framework discussion points
2. **Framework Reference**: Include @../topic-framework.md reference in analysis
## Completion Criteria
- Address each discussion point from topic-framework.md with data architecture expertise
- Provide data model designs, pipeline architectures, and governance strategies
- Include scalability, performance, and quality considerations
- Reference framework document using @ notation for integration
"
```
### Progress Tracking
TodoWrite tracking for two-step process:
```json
[
{"content": "Gather data architect context through role-specific questioning", "status": "in_progress", "activeForm": "Gathering context"},
{"content": "Validate context responses and save to data-architect-context.md", "status": "pending", "activeForm": "Validating context"},
{"content": "Load data-architect planning template via flow control", "status": "pending", "activeForm": "Loading template"},
{"content": "Execute dedicated conceptual-planning-agent for data-architect role", "status": "pending", "activeForm": "Executing agent"}
]
## 📋 **TodoWrite Integration**
### Workflow Progress Tracking
```javascript
TodoWrite({
todos: [
{
content: "Detect active session and locate topic framework",
status: "in_progress",
activeForm: "Detecting session and framework"
},
{
content: "Load topic-framework.md and session metadata for context",
status: "pending",
activeForm: "Loading framework and session context"
},
{
content: "Execute data-architect analysis using conceptual-planning-agent with FLOW_CONTROL",
status: "pending",
activeForm: "Executing data-architect framework analysis"
},
{
content: "Generate analysis.md addressing all framework discussion points",
status: "pending",
activeForm: "Generating structured data-architect analysis"
},
{
content: "Update workflow-session.json with data-architect completion status",
status: "pending",
activeForm: "Updating session metadata"
}
]
});
```
## 📊 **Output Specification**
## 📊 **Output Structure**
### Output Location
### Framework-Based Analysis
```
.workflow/WFS-{topic-slug}/.brainstorming/data-architect/
── analysis.md # Primary data architecture analysis
├── data-model.md # Data models, schemas, and relationships
├── pipeline-design.md # Data processing and ETL/ELT workflows
└── governance-plan.md # Data quality, security, and governance
.workflow/WFS-{session}/.brainstorming/data-architect/
── analysis.md # Structured analysis addressing topic-framework.md discussion points
```
### Document Templates
#### analysis.md Structure
### Analysis Document Structure
```markdown
# Data Architect Analysis: {Topic}
*Generated: {timestamp}*
# Data Architect Analysis: [Topic from Framework]
## Executive Summary
[Key data architecture findings and recommendations overview]
## Framework Reference
**Topic Framework**: @../topic-framework.md
**Role Focus**: Data Architecture perspective
## Current Data Landscape
### Existing Data Sources
### Current Data Architecture
### Data Quality Assessment
### Performance Bottlenecks
## Discussion Points Analysis
[Address each point from topic-framework.md with data architecture expertise]
## Data Requirements Analysis
### Business Data Needs
### Technical Data Requirements
### Data Volume and Growth Projections
### Real-time vs Batch Processing Needs
### Core Requirements (from framework)
[Data architecture perspective on requirements]
## Proposed Data Architecture
### Data Model Design
### Storage Architecture
### Processing Pipeline Design
### Integration Patterns
### Technical Considerations (from framework)
[Data model, pipeline, and storage considerations]
## Data Quality and Governance
### Data Quality Framework
### Governance Policies
### Security and Privacy Controls
### Compliance Requirements
### User Experience Factors (from framework)
[Data access patterns and analytics user experience]
## Analytics and Reporting Strategy
### Business Intelligence Architecture
### Self-Service Analytics Design
### Performance Monitoring
### Scalability Planning
### Implementation Challenges (from framework)
[Data migration, quality, and governance challenges]
## Implementation Roadmap
### Migration Strategy
### Technology Stack Recommendations
### Resource Requirements
### Risk Mitigation Plan
### Success Metrics (from framework)
[Data quality metrics and analytics success criteria]
## Data Architecture Specific Recommendations
[Role-specific data architecture recommendations and solutions]
---
*Generated by data-architect analysis addressing structured framework*
```
## 🔄 **Session Integration**
### Status Synchronization
Upon completion, update `workflow-session.json`:
### Completion Status Update
```json
{
"phases": {
"BRAINSTORM": {
"data_architect": {
"status": "completed",
"completed_at": "timestamp",
"output_directory": ".workflow/WFS-{topic}/.brainstorming/data-architect/",
"key_insights": ["data_model_optimization", "pipeline_architecture", "analytics_strategy"]
}
}
"data_architect": {
"status": "completed",
"framework_addressed": true,
"output_location": ".workflow/WFS-{session}/.brainstorming/data-architect/analysis.md",
"framework_reference": "@../topic-framework.md"
}
}
```
### Cross-Role Collaboration
Data architect perspective provides:
- **Data Storage Requirements** → System Architect
- **Analytics Data Requirements** → Product Manager
- **Data Visualization Specifications** → UI Designer
- **Data Security Framework** → Security Expert
- **Feature Data Requirements** → Feature Planner
## ✅ **Quality Assurance**
### Required Architecture Elements
- [ ] Comprehensive data model with clear relationships and constraints
- [ ] Scalable data pipeline design with error handling and monitoring
- [ ] Data quality framework with validation rules and metrics
- [ ] Governance plan addressing security, privacy, and compliance
- [ ] Analytics architecture supporting business intelligence needs
### Data Architecture Principles
- [ ] **Scalability**: Architecture can handle data volume and velocity growth
- [ ] **Quality**: Built-in data validation, cleansing, and quality monitoring
- [ ] **Security**: Data protection, access controls, and privacy compliance
- [ ] **Performance**: Optimized for query performance and processing efficiency
- [ ] **Maintainability**: Clear data lineage, documentation, and change management
### Implementation Validation
- [ ] **Technical Feasibility**: All proposed solutions are technically achievable
- [ ] **Performance Requirements**: Architecture meets processing and query performance needs
- [ ] **Cost Effectiveness**: Storage and processing costs are optimized and sustainable
- [ ] **Governance Compliance**: Meets regulatory and organizational data requirements
- [ ] **Future Readiness**: Design accommodates anticipated growth and changing needs
### Data Quality Standards
- [ ] **Accuracy**: Data validation rules ensure correctness and consistency
- [ ] **Completeness**: Strategies for handling missing data and ensuring coverage
- [ ] **Timeliness**: Data freshness requirements met through appropriate processing
- [ ] **Consistency**: Data definitions and formats standardized across systems
- [ ] **Lineage**: Complete data lineage tracking from source to consumption
### Integration Points
- **Framework Reference**: @../topic-framework.md for structured discussion points
- **Cross-Role Synthesis**: Data architecture insights available for synthesis-report.md integration
- **Agent Autonomy**: Independent execution with framework guidance

View File

@@ -1,273 +0,0 @@
---
name: feature-planner
description: Feature planner perspective brainstorming for feature development and planning analysis
usage: /workflow:brainstorm:feature-planner <topic>
argument-hint: "topic or challenge to analyze from feature planning perspective"
examples:
- /workflow:brainstorm:feature-planner "user dashboard enhancement"
- /workflow:brainstorm:feature-planner "mobile app feature roadmap"
- /workflow:brainstorm:feature-planner "integration capabilities planning"
allowed-tools: Task(conceptual-planning-agent), TodoWrite(*)
---
## 🔧 **Role Overview: Feature Planner**
### Role Definition
Feature development specialist responsible for transforming business requirements into actionable feature specifications, managing development priorities, and ensuring successful feature delivery through strategic planning and execution.
### Core Responsibilities
- **Feature Specification**: Transform business requirements into detailed feature specifications
- **Development Planning**: Create development roadmaps and manage feature priorities
- **Quality Assurance**: Design testing strategies and acceptance criteria
- **Delivery Management**: Plan feature releases and manage implementation timelines
### Focus Areas
- **Feature Design**: User stories, acceptance criteria, feature specifications
- **Development Planning**: Sprint planning, milestones, dependency management
- **Quality Assurance**: Testing strategies, quality gates, acceptance processes
- **Release Management**: Release planning, version control, change management
### Success Metrics
- Feature delivery on time and within scope
- Quality standards and acceptance criteria met
- User satisfaction with delivered features
- Development team productivity and efficiency
## 🧠 **分析框架**
@~/.claude/workflows/brainstorming-principles.md
### Key Analysis Questions
**1. Feature Requirements and Scope**
- What are the core feature requirements and user stories?
- How should MVP and full feature versions be planned?
- What cross-feature dependencies and integration requirements exist?
**2. Implementation Complexity and Feasibility**
- What is the technical implementation complexity and what challenges exist?
- What extensions or modifications to existing systems are required?
- What third-party services and API integrations are needed?
**3. Development Resources and Timeline**
- What are the development effort estimates and time projections?
- What skills and team configurations are required?
- What development risks exist and how can they be mitigated?
**4. Testing and Quality Assurance**
- What testing strategies and test case designs are needed?
- What quality standards and acceptance criteria should be defined?
- What user acceptance and feedback mechanisms are required?
## ⚡ **Two-Step Execution Flow**
### ⚠️ Session Management - FIRST STEP
Session detection and selection:
```bash
# Check for active sessions
active_sessions=$(find .workflow -name ".active-*" 2>/dev/null)
if [ multiple_sessions ]; then
prompt_user_to_select_session()
else
use_existing_or_create_new()
fi
```
### Step 1: Context Gathering Phase
**Feature Planner Perspective Questioning**
Before agent assignment, gather comprehensive feature planner context:
#### 📋 Role-Specific Questions
**1. Implementation Complexity and Scope**
- What is the scope and complexity of the features you want to plan?
- Are there existing features or systems that need to be extended or integrated?
- What are the technical constraints or requirements that need to be considered?
- How do these features fit into the overall product roadmap?
**2. Dependency Mapping and Integration**
- What other features, systems, or teams does this depend on?
- Are there any external APIs, services, or third-party integrations required?
- What are the data dependencies and how will data flow between components?
- What are the potential blockers or risks that could impact development?
**3. Risk Assessment and Mitigation**
- What are the main technical, business, or timeline risks?
- Are there any unknowns or areas that need research or prototyping?
- What fallback plans or alternative approaches should be considered?
- How will quality and testing be ensured throughout development?
**4. Technical Feasibility and Resource Planning**
- What is the estimated development effort and timeline?
- What skills, expertise, or team composition is needed?
- Are there any specific technologies, tools, or frameworks required?
- What are the performance, scalability, or maintenance considerations?
#### Context Validation
- **Minimum Response**: Each answer must be ≥50 characters
- **Re-prompting**: Insufficient detail triggers follow-up questions
- **Context Storage**: Save responses to `.brainstorming/feature-planner-context.md`
### Step 2: Agent Assignment with Flow Control
**Dedicated Agent Execution**
```bash
Task(conceptual-planning-agent): "
[FLOW_CONTROL]
Execute dedicated feature planner conceptual analysis for: {topic}
ASSIGNED_ROLE: feature-planner
OUTPUT_LOCATION: .brainstorming/feature-planner/
USER_CONTEXT: {validated_responses_from_context_gathering}
Flow Control Steps:
[
{
\"step\": \"load_role_template\",
\"action\": \"Load feature-planner planning template\",
\"command\": \"bash($(cat ~/.claude/workflows/cli-templates/planning-roles/feature-planner.md))\",
\"output_to\": \"role_template\"
}
]
Conceptual Analysis Requirements:
- Apply feature planner perspective to topic analysis
- Focus on implementation complexity, dependency mapping, risk assessment, and technical feasibility
- Use loaded role template framework for analysis structure
- Generate role-specific deliverables in designated output location
- Address all user context from questioning phase
Deliverables:
- analysis.md: Main feature planner analysis
- recommendations.md: Feature planner recommendations
- deliverables/: Feature planner-specific outputs as defined in role template
Embody feature planner role expertise for comprehensive conceptual planning."
```
### Progress Tracking
TodoWrite tracking for two-step process:
```json
[
{"content": "Gather feature planner context through role-specific questioning", "status": "in_progress", "activeForm": "Gathering context"},
{"content": "Validate context responses and save to feature-planner-context.md", "status": "pending", "activeForm": "Validating context"},
{"content": "Load feature-planner planning template via flow control", "status": "pending", "activeForm": "Loading template"},
{"content": "Execute dedicated conceptual-planning-agent for feature-planner role", "status": "pending", "activeForm": "Executing agent"}
]
```
## 📊 **输出结构**
### 保存位置
```
.workflow/WFS-{topic-slug}/.brainstorming/feature-planner/
├── analysis.md # 主要功能分析和规范
├── user-stories.md # 详细用户故事和验收标准
├── development-plan.md # 开发时间线和资源规划
└── testing-strategy.md # 质量保证和测试方法
```
### 文档模板
#### analysis.md 结构
```markdown
# Feature Planner Analysis: {Topic}
*Generated: {timestamp}*
## Executive Summary
[核心功能规划发现和建议概述]
## Feature Requirements Overview
### Core Feature Specifications
### User Story Summary
### Feature Scope and Boundaries
### Success Criteria and KPIs
## Feature Architecture Design
### Feature Components and Modules
### Integration Points and Dependencies
### APIs and Data Interfaces
### Configuration and Customization
## Development Planning
### Effort Estimation and Complexity
### Development Phases and Milestones
### Resource Requirements
### Risk Assessment and Mitigation
## Quality Assurance Strategy
### Testing Approach and Coverage
### Performance and Scalability Testing
### User Acceptance Testing Plan
### Quality Gates and Standards
## Delivery and Release Strategy
### Release Planning and Versioning
### Deployment Strategy
### Feature Rollout Plan
### Post-Release Support
## Feature Prioritization
### Priority Matrix (High/Medium/Low)
### Business Value Assessment
### Development Complexity Analysis
### Recommended Implementation Order
## Implementation Roadmap
### Phase 1: Core Features (Weeks 1-4)
### Phase 2: Enhanced Features (Weeks 5-8)
### Phase 3: Advanced Features (Weeks 9-12)
### Continuous Improvement Plan
```
## 🔄 **会话集成**
### 状态同步
分析完成后,更新 `workflow-session.json`:
```json
{
"phases": {
"BRAINSTORM": {
"feature_planner": {
"status": "completed",
"completed_at": "timestamp",
"output_directory": ".workflow/WFS-{topic}/.brainstorming/feature-planner/",
"key_insights": ["feature_specification", "development_timeline", "quality_requirement"]
}
}
}
}
```
### 与其他角色的协作
功能规划师视角为其他角色提供:
- **功能优先级和规划** → Product Manager
- **技术实现需求** → System Architect
- **界面功能要求** → UI Designer
- **数据功能需求** → Data Architect
- **功能安全需求** → Security Expert
## ✅ **质量标准**
### 必须包含的规划元素
- [ ] 详细的功能规范和用户故事
- [ ] 现实的开发时间估算
- [ ] 全面的测试策略
- [ ] 明确的质量标准
- [ ] 可执行的发布计划
### 功能规划原则检查
- [ ] 用户价值:每个功能都有明确的用户价值
- [ ] 可测试性:所有功能都有验收标准
- [ ] 可维护性:考虑长期维护和扩展
- [ ] 可交付性:计划符合团队能力和资源
- [ ] 可测量性:有明确的成功指标
### 交付质量评估
- [ ] 功能完整性和正确性
- [ ] 性能和稳定性指标
- [ ] 用户体验和满意度
- [ ] 代码质量和可维护性
- [ ] 文档完整性和准确性

View File

@@ -1,273 +0,0 @@
---
name: innovation-lead
description: Innovation lead perspective brainstorming for emerging technologies and future opportunities analysis
usage: /workflow:brainstorm:innovation-lead <topic>
argument-hint: "topic or challenge to analyze from innovation and emerging technology perspective"
examples:
- /workflow:brainstorm:innovation-lead "AI integration opportunities"
- /workflow:brainstorm:innovation-lead "future technology trends"
- /workflow:brainstorm:innovation-lead "disruptive innovation strategy"
allowed-tools: Task(conceptual-planning-agent), TodoWrite(*)
---
## 🚀 **Role Overview: Innovation Lead**
### Role Definition
Visionary technology strategist responsible for identifying emerging technology trends, evaluating disruptive innovation opportunities, and designing future-ready solutions that create competitive advantage and drive market transformation.
### Core Responsibilities
- **Trend Identification**: Identify and analyze emerging technology trends and market opportunities
- **Innovation Strategy**: Develop innovation roadmaps and technology development strategies
- **Technology Assessment**: Evaluate new technology application potential and feasibility
- **Future Planning**: Design forward-looking product and service concepts
### Focus Areas
- **Emerging Technologies**: AI, blockchain, IoT, AR/VR, quantum computing, and other frontier technologies
- **Market Trends**: Industry transformation, user behavior evolution, business model innovation
- **Innovation Opportunities**: Disruptive innovation, blue ocean markets, technology convergence opportunities
- **Future Vision**: Long-term technology roadmaps, proof of concepts, prototype development
### Success Metrics
- Innovation impact and market differentiation
- Technology adoption rates and competitive advantage
- Future readiness and strategic positioning
- Breakthrough opportunity identification and validation
## 🧠 **Analysis Framework**
@~/.claude/workflows/brainstorming-principles.md
### Key Analysis Questions
**1. Emerging Trends and Technology Opportunities**
- Which emerging technologies will have the greatest impact on our industry?
- What is the technology maturity level and adoption timeline?
- What new opportunities does technology convergence create?
**2. Disruption Potential and Innovation Assessment**
- What is the potential for disruptive innovation and its impact?
- What innovation opportunities exist within current solutions?
- What unmet market needs and demands exist?
**3. Competitive Advantage and Market Analysis**
- What are competitors' innovation strategies and directions?
- What market gaps and blue ocean opportunities exist?
- What technological barriers and first-mover advantages are available?
**4. Implementation and Risk Assessment**
- What is the feasibility and risk of technology implementation?
- What are the investment requirements and expected returns?
- What organizational innovation capabilities and adaptability are needed?
## ⚡ **Two-Step Execution Flow**
### ⚠️ Session Management - FIRST STEP
Session detection and selection:
```bash
# Check for active sessions
active_sessions=$(find .workflow -name ".active-*" 2>/dev/null)
if [ multiple_sessions ]; then
prompt_user_to_select_session()
else
use_existing_or_create_new()
fi
```
### Step 1: Context Gathering Phase
**Innovation Lead Perspective Questioning**
Before agent assignment, gather comprehensive innovation lead context:
#### 📋 Role-Specific Questions
**1. Emerging Trends and Future Technologies**
- What emerging technologies or trends do you think will be most relevant to this topic?
- Are there any specific industries or markets you want to explore for innovation opportunities?
- What time horizon are you considering (near-term, medium-term, long-term disruption)?
- Are there any particular technology domains you want to focus on (AI, IoT, blockchain, etc.)?
**2. Innovation Opportunities and Market Potential**
- What current limitations or pain points could be addressed through innovation?
- Are there any unmet market needs or underserved segments you're aware of?
- What would disruptive success look like in this context?
- Are there cross-industry innovations that could be applied to this domain?
**3. Disruption Potential and Competitive Landscape**
- Who are the current market leaders and what are their innovation strategies?
- What startup activity or venture capital investment trends are you seeing?
- Are there any potential platform shifts or ecosystem changes on the horizon?
- What would make a solution truly differentiated in the marketplace?
**4. Implementation and Strategic Considerations**
- What organizational capabilities or partnerships would be needed for innovation?
- Are there regulatory, technical, or market barriers to consider?
- What level of risk tolerance exists for breakthrough vs. incremental innovation?
- How important is first-mover advantage versus fast-follower strategies?
#### Context Validation
- **Minimum Response**: Each answer must be ≥50 characters
- **Re-prompting**: Insufficient detail triggers follow-up questions
- **Context Storage**: Save responses to `.brainstorming/innovation-lead-context.md`
### Step 2: Agent Assignment with Flow Control
**Dedicated Agent Execution**
```bash
Task(conceptual-planning-agent): "
[FLOW_CONTROL]
Execute dedicated innovation lead conceptual analysis for: {topic}
ASSIGNED_ROLE: innovation-lead
OUTPUT_LOCATION: .brainstorming/innovation-lead/
USER_CONTEXT: {validated_responses_from_context_gathering}
Flow Control Steps:
[
{
\"step\": \"load_role_template\",
\"action\": \"Load innovation-lead planning template\",
\"command\": \"bash($(cat ~/.claude/workflows/cli-templates/planning-roles/innovation-lead.md))\",
\"output_to\": \"role_template\"
}
]
Conceptual Analysis Requirements:
- Apply innovation lead perspective to topic analysis
- Focus on emerging trends, disruption potential, competitive advantage, and future opportunities
- Use loaded role template framework for analysis structure
- Generate role-specific deliverables in designated output location
- Address all user context from questioning phase
Deliverables:
- analysis.md: Main innovation lead analysis
- recommendations.md: Innovation lead recommendations
- deliverables/: Innovation lead-specific outputs as defined in role template
Embody innovation lead role expertise for comprehensive conceptual planning."
```
### Progress Tracking
TodoWrite tracking for two-step process:
```json
[
{"content": "Gather innovation lead context through role-specific questioning", "status": "in_progress", "activeForm": "Gathering context"},
{"content": "Validate context responses and save to innovation-lead-context.md", "status": "pending", "activeForm": "Validating context"},
{"content": "Load innovation-lead planning template via flow control", "status": "pending", "activeForm": "Loading template"},
{"content": "Execute dedicated conceptual-planning-agent for innovation-lead role", "status": "pending", "activeForm": "Executing agent"}
]
```
## 📊 **输出结构**
### 保存位置
```
.workflow/WFS-{topic-slug}/.brainstorming/innovation-lead/
├── analysis.md # 主要创新分析和机会评估
├── technology-roadmap.md # 技术趋势和未来场景
├── innovation-concepts.md # 突破性想法和概念开发
└── strategy-implementation.md # 创新策略和执行计划
```
### 文档模板
#### analysis.md 结构
```markdown
# Innovation Lead Analysis: {Topic}
*Generated: {timestamp}*
## Executive Summary
[核心创新机会和战略建议概述]
## Technology Landscape Assessment
### Emerging Technologies Overview
### Technology Maturity Analysis
### Convergence Opportunities
### Disruptive Potential Assessment
## Innovation Opportunity Analysis
### Market Whitespace Identification
### Unmet Needs and Pain Points
### Disruptive Innovation Potential
### Blue Ocean Opportunities
## Competitive Intelligence
### Competitor Innovation Strategies
### Patent Landscape Analysis
### Startup Ecosystem Insights
### Investment and Funding Trends
## Future Scenarios and Trends
### Short-term Innovations (0-2 years)
### Medium-term Disruptions (2-5 years)
### Long-term Transformations (5+ years)
### Wild Card Scenarios
## Innovation Concepts
### Breakthrough Ideas
### Proof-of-Concept Opportunities
### Platform Innovation Possibilities
### Ecosystem Partnership Ideas
## Strategic Recommendations
### Innovation Investment Priorities
### Technology Partnership Strategy
### Capability Building Requirements
### Risk Mitigation Approaches
## Implementation Roadmap
### Innovation Pilot Programs
### Technology Validation Milestones
### Scaling and Commercialization Plan
### Success Metrics and KPIs
```
## 🔄 **会话集成**
### 状态同步
分析完成后,更新 `workflow-session.json`:
```json
{
"phases": {
"BRAINSTORM": {
"innovation_lead": {
"status": "completed",
"completed_at": "timestamp",
"output_directory": ".workflow/WFS-{topic}/.brainstorming/innovation-lead/",
"key_insights": ["breakthrough_opportunity", "emerging_technology", "disruptive_potential"]
}
}
}
}
```
### 与其他角色的协作
创新领导视角为其他角色提供:
- **创新机会和趋势** → Product Manager
- **新技术可行性** → System Architect
- **未来用户体验趋势** → UI Designer
- **新兴数据技术** → Data Architect
- **创新安全挑战** → Security Expert
## ✅ **质量标准**
### 必须包含的创新元素
- [ ] 全面的技术趋势分析
- [ ] 明确的创新机会识别
- [ ] 具体的概念验证方案
- [ ] 现实的实施路线图
- [ ] 前瞻性的风险评估
### 创新思维原则检查
- [ ] 前瞻性关注未来3-10年趋势
- [ ] 颠覆性:寻找破坏性创新机会
- [ ] 系统性:考虑技术生态系统影响
- [ ] 可行性:平衡愿景与现实可能
- [ ] 差异化:创造独特竞争优势
### 创新价值评估
- [ ] 市场影响的潜在规模
- [ ] 技术可行性和成熟度
- [ ] 竞争优势的可持续性
- [ ] 投资回报的时间框架
- [ ] 组织实施的复杂度

View File

@@ -1,248 +1,200 @@
---
name: product-manager
description: Product manager perspective brainstorming for user needs and business value analysis
usage: /workflow:brainstorm:product-manager <topic>
argument-hint: "topic or challenge to analyze from product management perspective"
examples:
- /workflow:brainstorm:product-manager "user authentication redesign"
- /workflow:brainstorm:product-manager "mobile app performance optimization"
- /workflow:brainstorm:product-manager "feature prioritization strategy"
allowed-tools: Task(conceptual-planning-agent), TodoWrite(*)
description: Generate or update product-manager/analysis.md addressing topic-framework discussion points
argument-hint: "optional topic - uses existing framework if available"
allowed-tools: Task(conceptual-planning-agent), TodoWrite(*), Read(*), Write(*)
---
## 🎯 **Role Overview: Product Manager**
## 🎯 **Product Manager Analysis Generator**
### Role Definition
Strategic product leader focused on maximizing user value and business impact through data-driven decisions and market-oriented thinking.
### Purpose
**Specialized command for generating product-manager/analysis.md** that addresses topic-framework.md discussion points from product strategy perspective. Creates or updates role-specific analysis with framework references.
### Core Responsibilities
- **User Needs Analysis**: Identify and validate genuine user problems and requirements
- **Business Value Assessment**: Quantify commercial impact and return on investment
- **Market Positioning**: Analyze competitive landscape and identify opportunities
- **Product Strategy**: Develop roadmaps, priorities, and go-to-market approaches
### Core Function
- **Framework-based Analysis**: Address each discussion point in topic-framework.md
- **Product Strategy Focus**: User needs, business value, and market positioning
- **Update Mechanism**: Create new or update existing analysis.md
- **Agent Delegation**: Use conceptual-planning-agent for analysis generation
### Focus Areas
- **User Experience**: Journey mapping, satisfaction metrics, conversion optimization
- **Business Metrics**: ROI, user growth, retention rates, revenue impact
- **Market Dynamics**: Competitive analysis, differentiation, market trends
- **Product Lifecycle**: Feature evolution, technical debt management, scalability
### Analysis Scope
- **User Needs Analysis**: Target users, problems, and value propositions
- **Business Impact Assessment**: ROI, metrics, and commercial outcomes
- **Market Positioning**: Competitive analysis and differentiation
- **Product Strategy**: Roadmaps, priorities, and go-to-market approaches
### Success Metrics
- User satisfaction scores and engagement metrics
- Business KPIs (revenue, growth, retention)
- Market share and competitive positioning
- Product adoption and feature utilization rates
## ⚙️ **Execution Protocol**
## 🧠 **Analysis Framework**
@~/.claude/workflows/brainstorming-principles.md
### Key Analysis Questions
**1. User Value Assessment**
- What genuine user problem does this solve?
- Who are the target users and what are their core needs?
- How does this improve the user experience measurably?
**2. Business Impact Evaluation**
- What are the expected business outcomes?
- How does the cost-benefit analysis look?
- What impact will this have on existing workflows?
**3. Market Opportunity Analysis**
- What gaps exist in current market solutions?
- What is our unique competitive advantage?
- Is the timing right for this initiative?
**4. Execution Feasibility**
- What resources and timeline are required?
- What are the technical and market risks?
- Do we have the right team capabilities?
## ⚡ **Two-Step Execution Flow**
### ⚠️ Session Management - FIRST STEP
Session detection and selection:
### Phase 1: Session & Framework Detection
```bash
# Check for active sessions
active_sessions=$(find .workflow -name ".active-*" 2>/dev/null)
if [ multiple_sessions ]; then
prompt_user_to_select_session()
else
use_existing_or_create_new()
fi
# Check active session and framework
CHECK: .workflow/.active-* marker files
IF active_session EXISTS:
session_id = get_active_session()
brainstorm_dir = .workflow/WFS-{session}/.brainstorming/
CHECK: brainstorm_dir/topic-framework.md
IF EXISTS:
framework_mode = true
load_framework = true
ELSE:
IF topic_provided:
framework_mode = false # Create analysis without framework
ELSE:
ERROR: "No framework found and no topic provided"
```
### Step 1: Context Gathering Phase
**Product Manager Perspective Questioning**
### Phase 2: Analysis Mode Detection
```bash
# Determine execution mode
IF framework_mode == true:
mode = "framework_based_analysis"
topic_ref = load_framework_topic()
discussion_points = extract_framework_points()
ELSE:
mode = "standalone_analysis"
topic_ref = provided_topic
discussion_points = generate_basic_structure()
```
Before agent assignment, gather comprehensive product management context:
#### 📋 Role-Specific Questions
1. **Business Objectives & Metrics**
- Primary business goals and success metrics?
- Revenue impact expectations and timeline?
- Key stakeholders and decision makers?
2. **Target Users & Market**
- Primary user segments and personas?
- User pain points and current solutions?
- Competitive landscape and differentiation needs?
3. **Product Strategy & Scope**
- Feature priorities and user value propositions?
- Resource constraints and timeline expectations?
- Integration with existing product ecosystem?
4. **Success Criteria & Risk Assessment**
- How will success be measured and validated?
- Market and technical risks to consider?
- Go-to-market strategy requirements?
#### Context Validation
- **Minimum Response**: Each answer must be ≥50 characters
- **Re-prompting**: Insufficient detail triggers follow-up questions
- **Context Storage**: Save responses to `.brainstorming/product-manager-context.md`
### Step 2: Agent Assignment with Flow Control
**Dedicated Agent Execution**
### Phase 3: Agent Execution with Flow Control
**Framework-Based Analysis Generation**
```bash
Task(conceptual-planning-agent): "
[FLOW_CONTROL]
Execute dedicated product-manager conceptual analysis for: {topic}
Execute product-manager analysis for existing topic framework
## Context Loading
ASSIGNED_ROLE: product-manager
OUTPUT_LOCATION: .brainstorming/product-manager/
USER_CONTEXT: {validated_responses_from_context_gathering}
OUTPUT_LOCATION: .workflow/WFS-{session}/.brainstorming/product-manager/
ANALYSIS_MODE: {framework_mode ? "framework_based" : "standalone"}
Flow Control Steps:
[
{
\"step\": \"load_role_template\",
\"action\": \"Load product-manager planning template\",
\"command\": \"bash($(cat ~/.claude/workflows/cli-templates/planning-roles/product-manager.md))\",
\"output_to\": \"role_template\"
}
]
## Flow Control Steps
1. **load_topic_framework**
- Action: Load structured topic discussion framework
- Command: Read(.workflow/WFS-{session}/.brainstorming/topic-framework.md)
- Output: topic_framework_content
Conceptual Analysis Requirements:
- Apply product-manager perspective to topic analysis
- Focus on user value, business impact, and market positioning
- Use loaded role template framework for analysis structure
- Generate role-specific deliverables in designated output location
- Address all user context from questioning phase
2. **load_role_template**
- Action: Load product-manager planning template
- Command: bash($(cat ~/.claude/workflows/cli-templates/planning-roles/product-manager.md))
- Output: role_template_guidelines
Deliverables:
- analysis.md: Main product management analysis
- recommendations.md: Product strategy recommendations
- deliverables/: Product-specific outputs as defined in role template
3. **load_session_metadata**
- Action: Load session metadata and existing context
- Command: Read(.workflow/WFS-{session}/workflow-session.json)
- Output: session_context
Embody product-manager role expertise for comprehensive conceptual planning."
## Analysis Requirements
**Framework Reference**: Address all discussion points in topic-framework.md from product strategy perspective
**Role Focus**: User value, business impact, market positioning, product strategy
**Structured Approach**: Create analysis.md addressing framework discussion points
**Template Integration**: Apply role template guidelines within framework structure
## Expected Deliverables
1. **analysis.md**: Comprehensive product strategy analysis addressing all framework discussion points
2. **Framework Reference**: Include @../topic-framework.md reference in analysis
## Completion Criteria
- Address each discussion point from topic-framework.md with product management expertise
- Provide actionable business strategies and user value propositions
- Include market analysis and competitive positioning insights
- Reference framework document using @ notation for integration
"
```
### Progress Tracking
TodoWrite tracking for two-step process:
```json
[
{"content": "Gather product manager context through role-specific questioning", "status": "in_progress", "activeForm": "Gathering context"},
{"content": "Validate context responses and save to product-manager-context.md", "status": "pending", "activeForm": "Validating context"},
{"content": "Load product-manager planning template via flow control", "status": "pending", "activeForm": "Loading template"},
{"content": "Execute dedicated conceptual-planning-agent for product-manager role", "status": "pending", "activeForm": "Executing agent"}
]
## 📋 **TodoWrite Integration**
### Workflow Progress Tracking
```javascript
TodoWrite({
todos: [
{
content: "Detect active session and locate topic framework",
status: "in_progress",
activeForm: "Detecting session and framework"
},
{
content: "Load topic-framework.md and session metadata for context",
status: "pending",
activeForm: "Loading framework and session context"
},
{
content: "Execute product-manager analysis using conceptual-planning-agent with FLOW_CONTROL",
status: "pending",
activeForm: "Executing product-manager framework analysis"
},
{
content: "Generate analysis.md addressing all framework discussion points",
status: "pending",
activeForm: "Generating structured product-manager analysis"
},
{
content: "Update workflow-session.json with product-manager completion status",
status: "pending",
activeForm: "Updating session metadata"
}
]
});
```
## 📊 **Output Specification**
## 📊 **Output Structure**
### Output Location
### Framework-Based Analysis
```
.workflow/WFS-{topic-slug}/.brainstorming/product-manager/
── analysis.md # Primary product management analysis
├── business-case.md # Business justification and metrics
├── user-research.md # User research and market insights
└── roadmap.md # Strategic recommendations and timeline
.workflow/WFS-{session}/.brainstorming/product-manager/
── analysis.md # Structured analysis addressing topic-framework.md discussion points
```
### Document Templates
#### analysis.md Structure
### Analysis Document Structure
```markdown
# Product Manager Analysis: {Topic}
*Generated: {timestamp}*
# Product Manager Analysis: [Topic from Framework]
## Executive Summary
[Key findings and recommendations overview]
## Framework Reference
**Topic Framework**: @../topic-framework.md
**Role Focus**: Product Strategy perspective
## User Needs Analysis
### Target User Segments
### Core Problems Identified
### User Journey Mapping
### Priority Requirements
## Discussion Points Analysis
[Address each point from topic-framework.md with product management expertise]
## Business Impact Assessment
### Revenue Impact
### Cost Analysis
### ROI Projections
### Risk Assessment
### Core Requirements (from framework)
[Product strategy perspective on user needs and requirements]
## Competitive Analysis
### Market Position
### Differentiation Opportunities
### Competitive Advantages
### Technical Considerations (from framework)
[Business and technical feasibility considerations]
## Strategic Recommendations
### Immediate Actions (0-3 months)
### Medium-term Initiatives (3-12 months)
### Long-term Vision (12+ months)
### User Experience Factors (from framework)
[User value proposition and market positioning analysis]
### Implementation Challenges (from framework)
[Business execution and go-to-market considerations]
### Success Metrics (from framework)
[Product success metrics and business KPIs]
## Product Strategy Specific Recommendations
[Role-specific product management strategies and business solutions]
---
*Generated by product-manager analysis addressing structured framework*
```
## 🔄 **Session Integration**
### Status Synchronization
Upon completion, update `workflow-session.json`:
### Completion Status Update
```json
{
"phases": {
"BRAINSTORM": {
"product_manager": {
"status": "completed",
"completed_at": "timestamp",
"output_directory": ".workflow/WFS-{topic}/.brainstorming/product-manager/",
"key_insights": ["user_value_proposition", "business_impact_assessment", "strategic_recommendations"]
}
}
"product_manager": {
"status": "completed",
"framework_addressed": true,
"output_location": ".workflow/WFS-{session}/.brainstorming/product-manager/analysis.md",
"framework_reference": "@../topic-framework.md"
}
}
```
### Cross-Role Collaboration
Product manager perspective provides:
- **User Requirements Definition** → UI Designer
- **Business Constraints and Objectives** → System Architect
- **Feature Prioritization** → Feature Planner
- **Market Requirements** → Innovation Lead
- **Success Metrics** → Business Analyst
## ✅ **Quality Assurance**
### Required Analysis Elements
- [ ] Clear user value proposition with supporting evidence
- [ ] Quantified business impact assessment with metrics
- [ ] Actionable product strategy recommendations
- [ ] Data-driven priority rankings
- [ ] Well-defined success criteria and KPIs
### Output Quality Standards
- [ ] Analysis grounded in real user needs and market data
- [ ] Business justification with clear logic and assumptions
- [ ] Recommendations are specific and actionable
- [ ] Timeline and milestones are realistic and achievable
- [ ] Risk identification is comprehensive and accurate
### Product Management Principles
- [ ] **User-Centric**: All decisions prioritize user value and experience
- [ ] **Data-Driven**: Conclusions supported by metrics and research
- [ ] **Market-Aware**: Considers competitive landscape and trends
- [ ] **Business-Focused**: Aligns with commercial objectives and constraints
- [ ] **Execution-Ready**: Provides clear next steps and success measures
### Integration Points
- **Framework Reference**: @../topic-framework.md for structured discussion points
- **Cross-Role Synthesis**: Product strategy insights available for synthesis-report.md integration
- **Agent Autonomy**: Independent execution with framework guidance

View File

@@ -0,0 +1,200 @@
---
name: product-owner
description: Generate or update product-owner/analysis.md addressing topic-framework discussion points
argument-hint: "optional topic - uses existing framework if available"
allowed-tools: Task(conceptual-planning-agent), TodoWrite(*), Read(*), Write(*)
---
## 🎯 **Product Owner Analysis Generator**
### Purpose
**Specialized command for generating product-owner/analysis.md** that addresses topic-framework.md discussion points from product backlog and feature prioritization perspective. Creates or updates role-specific analysis with framework references.
### Core Function
- **Framework-based Analysis**: Address each discussion point in topic-framework.md
- **Product Backlog Focus**: Feature prioritization, user stories, and acceptance criteria
- **Update Mechanism**: Create new or update existing analysis.md
- **Agent Delegation**: Use conceptual-planning-agent for analysis generation
### Analysis Scope
- **Backlog Management**: User story creation, refinement, and prioritization
- **Stakeholder Alignment**: Requirements gathering, value definition, and expectation management
- **Feature Prioritization**: ROI analysis, MoSCoW method, and value-driven delivery
- **Acceptance Criteria**: Definition of Done, acceptance testing, and quality standards
## ⚙️ **Execution Protocol**
### Phase 1: Session & Framework Detection
```bash
# Check active session and framework
CHECK: .workflow/.active-* marker files
IF active_session EXISTS:
session_id = get_active_session()
brainstorm_dir = .workflow/WFS-{session}/.brainstorming/
CHECK: brainstorm_dir/topic-framework.md
IF EXISTS:
framework_mode = true
load_framework = true
ELSE:
IF topic_provided:
framework_mode = false # Create analysis without framework
ELSE:
ERROR: "No framework found and no topic provided"
```
### Phase 2: Analysis Mode Detection
```bash
# Determine execution mode
IF framework_mode == true:
mode = "framework_based_analysis"
topic_ref = load_framework_topic()
discussion_points = extract_framework_points()
ELSE:
mode = "standalone_analysis"
topic_ref = provided_topic
discussion_points = generate_basic_structure()
```
### Phase 3: Agent Execution with Flow Control
**Framework-Based Analysis Generation**
```bash
Task(conceptual-planning-agent): "
[FLOW_CONTROL]
Execute product-owner analysis for existing topic framework
## Context Loading
ASSIGNED_ROLE: product-owner
OUTPUT_LOCATION: .workflow/WFS-{session}/.brainstorming/product-owner/
ANALYSIS_MODE: {framework_mode ? "framework_based" : "standalone"}
## Flow Control Steps
1. **load_topic_framework**
- Action: Load structured topic discussion framework
- Command: Read(.workflow/WFS-{session}/.brainstorming/topic-framework.md)
- Output: topic_framework_content
2. **load_role_template**
- Action: Load product-owner planning template
- Command: bash($(cat ~/.claude/workflows/cli-templates/planning-roles/product-owner.md))
- Output: role_template_guidelines
3. **load_session_metadata**
- Action: Load session metadata and existing context
- Command: Read(.workflow/WFS-{session}/workflow-session.json)
- Output: session_context
## Analysis Requirements
**Framework Reference**: Address all discussion points in topic-framework.md from product backlog and feature prioritization perspective
**Role Focus**: Backlog management, stakeholder alignment, feature prioritization, acceptance criteria
**Structured Approach**: Create analysis.md addressing framework discussion points
**Template Integration**: Apply role template guidelines within framework structure
## Expected Deliverables
1. **analysis.md**: Comprehensive product ownership analysis addressing all framework discussion points
2. **Framework Reference**: Include @../topic-framework.md reference in analysis
## Completion Criteria
- Address each discussion point from topic-framework.md with product ownership expertise
- Provide actionable user stories and acceptance criteria definitions
- Include feature prioritization and stakeholder alignment strategies
- Reference framework document using @ notation for integration
"
```
## 📋 **TodoWrite Integration**
### Workflow Progress Tracking
```javascript
TodoWrite({
todos: [
{
content: "Detect active session and locate topic framework",
status: "in_progress",
activeForm: "Detecting session and framework"
},
{
content: "Load topic-framework.md and session metadata for context",
status: "pending",
activeForm: "Loading framework and session context"
},
{
content: "Execute product-owner analysis using conceptual-planning-agent with FLOW_CONTROL",
status: "pending",
activeForm: "Executing product-owner framework analysis"
},
{
content: "Generate analysis.md addressing all framework discussion points",
status: "pending",
activeForm: "Generating structured product-owner analysis"
},
{
content: "Update workflow-session.json with product-owner completion status",
status: "pending",
activeForm: "Updating session metadata"
}
]
});
```
## 📊 **Output Structure**
### Framework-Based Analysis
```
.workflow/WFS-{session}/.brainstorming/product-owner/
└── analysis.md # Structured analysis addressing topic-framework.md discussion points
```
### Analysis Document Structure
```markdown
# Product Owner Analysis: [Topic from Framework]
## Framework Reference
**Topic Framework**: @../topic-framework.md
**Role Focus**: Product Backlog & Feature Prioritization perspective
## Discussion Points Analysis
[Address each point from topic-framework.md with product ownership expertise]
### Core Requirements (from framework)
[User story formulation and backlog refinement perspective]
### Technical Considerations (from framework)
[Technical feasibility and implementation sequencing considerations]
### User Experience Factors (from framework)
[User value definition and acceptance criteria analysis]
### Implementation Challenges (from framework)
[Sprint planning, dependency management, and delivery strategies]
### Success Metrics (from framework)
[Feature adoption, value delivery metrics, and stakeholder satisfaction indicators]
## Product Owner Specific Recommendations
[Role-specific backlog management and feature prioritization strategies]
---
*Generated by product-owner analysis addressing structured framework*
```
## 🔄 **Session Integration**
### Completion Status Update
```json
{
"product_owner": {
"status": "completed",
"framework_addressed": true,
"output_location": ".workflow/WFS-{session}/.brainstorming/product-owner/analysis.md",
"framework_reference": "@../topic-framework.md"
}
}
```
### Integration Points
- **Framework Reference**: @../topic-framework.md for structured discussion points
- **Cross-Role Synthesis**: Product ownership insights available for synthesis-report.md integration
- **Agent Autonomy**: Independent execution with framework guidance

View File

@@ -0,0 +1,200 @@
---
name: scrum-master
description: Generate or update scrum-master/analysis.md addressing topic-framework discussion points
argument-hint: "optional topic - uses existing framework if available"
allowed-tools: Task(conceptual-planning-agent), TodoWrite(*), Read(*), Write(*)
---
## 🎯 **Scrum Master Analysis Generator**
### Purpose
**Specialized command for generating scrum-master/analysis.md** that addresses topic-framework.md discussion points from agile process and team collaboration perspective. Creates or updates role-specific analysis with framework references.
### Core Function
- **Framework-based Analysis**: Address each discussion point in topic-framework.md
- **Agile Process Focus**: Sprint planning, team dynamics, and delivery optimization
- **Update Mechanism**: Create new or update existing analysis.md
- **Agent Delegation**: Use conceptual-planning-agent for analysis generation
### Analysis Scope
- **Sprint Planning**: Task breakdown, estimation, and iteration planning
- **Team Collaboration**: Communication patterns, impediment removal, and facilitation
- **Process Optimization**: Agile ceremonies, retrospectives, and continuous improvement
- **Delivery Management**: Velocity tracking, burndown analysis, and release planning
## ⚙️ **Execution Protocol**
### Phase 1: Session & Framework Detection
```bash
# Check active session and framework
CHECK: .workflow/.active-* marker files
IF active_session EXISTS:
session_id = get_active_session()
brainstorm_dir = .workflow/WFS-{session}/.brainstorming/
CHECK: brainstorm_dir/topic-framework.md
IF EXISTS:
framework_mode = true
load_framework = true
ELSE:
IF topic_provided:
framework_mode = false # Create analysis without framework
ELSE:
ERROR: "No framework found and no topic provided"
```
### Phase 2: Analysis Mode Detection
```bash
# Determine execution mode
IF framework_mode == true:
mode = "framework_based_analysis"
topic_ref = load_framework_topic()
discussion_points = extract_framework_points()
ELSE:
mode = "standalone_analysis"
topic_ref = provided_topic
discussion_points = generate_basic_structure()
```
### Phase 3: Agent Execution with Flow Control
**Framework-Based Analysis Generation**
```bash
Task(conceptual-planning-agent): "
[FLOW_CONTROL]
Execute scrum-master analysis for existing topic framework
## Context Loading
ASSIGNED_ROLE: scrum-master
OUTPUT_LOCATION: .workflow/WFS-{session}/.brainstorming/scrum-master/
ANALYSIS_MODE: {framework_mode ? "framework_based" : "standalone"}
## Flow Control Steps
1. **load_topic_framework**
- Action: Load structured topic discussion framework
- Command: Read(.workflow/WFS-{session}/.brainstorming/topic-framework.md)
- Output: topic_framework_content
2. **load_role_template**
- Action: Load scrum-master planning template
- Command: bash($(cat ~/.claude/workflows/cli-templates/planning-roles/scrum-master.md))
- Output: role_template_guidelines
3. **load_session_metadata**
- Action: Load session metadata and existing context
- Command: Read(.workflow/WFS-{session}/workflow-session.json)
- Output: session_context
## Analysis Requirements
**Framework Reference**: Address all discussion points in topic-framework.md from agile process and team collaboration perspective
**Role Focus**: Sprint planning, team dynamics, process optimization, delivery management
**Structured Approach**: Create analysis.md addressing framework discussion points
**Template Integration**: Apply role template guidelines within framework structure
## Expected Deliverables
1. **analysis.md**: Comprehensive agile process analysis addressing all framework discussion points
2. **Framework Reference**: Include @../topic-framework.md reference in analysis
## Completion Criteria
- Address each discussion point from topic-framework.md with scrum mastery expertise
- Provide actionable sprint planning and team facilitation strategies
- Include process optimization and impediment removal insights
- Reference framework document using @ notation for integration
"
```
## 📋 **TodoWrite Integration**
### Workflow Progress Tracking
```javascript
TodoWrite({
todos: [
{
content: "Detect active session and locate topic framework",
status: "in_progress",
activeForm: "Detecting session and framework"
},
{
content: "Load topic-framework.md and session metadata for context",
status: "pending",
activeForm: "Loading framework and session context"
},
{
content: "Execute scrum-master analysis using conceptual-planning-agent with FLOW_CONTROL",
status: "pending",
activeForm: "Executing scrum-master framework analysis"
},
{
content: "Generate analysis.md addressing all framework discussion points",
status: "pending",
activeForm: "Generating structured scrum-master analysis"
},
{
content: "Update workflow-session.json with scrum-master completion status",
status: "pending",
activeForm: "Updating session metadata"
}
]
});
```
## 📊 **Output Structure**
### Framework-Based Analysis
```
.workflow/WFS-{session}/.brainstorming/scrum-master/
└── analysis.md # Structured analysis addressing topic-framework.md discussion points
```
### Analysis Document Structure
```markdown
# Scrum Master Analysis: [Topic from Framework]
## Framework Reference
**Topic Framework**: @../topic-framework.md
**Role Focus**: Agile Process & Team Collaboration perspective
## Discussion Points Analysis
[Address each point from topic-framework.md with scrum mastery expertise]
### Core Requirements (from framework)
[Sprint planning and iteration breakdown perspective]
### Technical Considerations (from framework)
[Technical debt management and process considerations]
### User Experience Factors (from framework)
[User story refinement and acceptance criteria analysis]
### Implementation Challenges (from framework)
[Impediment identification and removal strategies]
### Success Metrics (from framework)
[Velocity tracking, burndown metrics, and team performance indicators]
## Scrum Master Specific Recommendations
[Role-specific agile process optimization and team facilitation strategies]
---
*Generated by scrum-master analysis addressing structured framework*
```
## 🔄 **Session Integration**
### Completion Status Update
```json
{
"scrum_master": {
"status": "completed",
"framework_addressed": true,
"output_location": ".workflow/WFS-{session}/.brainstorming/scrum-master/analysis.md",
"framework_reference": "@../topic-framework.md"
}
}
```
### Integration Points
- **Framework Reference**: @../topic-framework.md for structured discussion points
- **Cross-Role Synthesis**: Agile process insights available for synthesis-report.md integration
- **Agent Autonomy**: Independent execution with framework guidance

View File

@@ -1,328 +0,0 @@
---
name: security-expert
description: Security expert perspective brainstorming for threat modeling and security architecture analysis
usage: /workflow:brainstorm:security-expert <topic>
argument-hint: "topic or challenge to analyze from cybersecurity perspective"
examples:
- /workflow:brainstorm:security-expert "user authentication security review"
- /workflow:brainstorm:security-expert "API security architecture"
- /workflow:brainstorm:security-expert "data protection compliance strategy"
allowed-tools: Task(conceptual-planning-agent), TodoWrite(*)
---
## 🔒 **Role Overview: Security Expert**
### Role Definition
Cybersecurity specialist focused on identifying threats, designing security controls, and ensuring comprehensive protection of systems, data, and users through proactive security architecture and risk management.
### Core Responsibilities
- **Threat Modeling**: Identify and analyze potential security threats and attack vectors
- **Security Architecture**: Design robust security controls and defensive measures
- **Risk Assessment**: Evaluate security risks and develop mitigation strategies
- **Compliance Management**: Ensure adherence to security standards and regulations
### Focus Areas
- **Application Security**: Code security, input validation, authentication, authorization
- **Infrastructure Security**: Network security, system hardening, access controls
- **Data Protection**: Encryption, privacy controls, data classification, compliance
- **Operational Security**: Monitoring, incident response, security awareness, procedures
### Success Metrics
- Vulnerability reduction and remediation rates
- Security incident prevention and response times
- Compliance audit results and regulatory adherence
- Security awareness and training effectiveness
## 🧠 **Analysis Framework**
@~/.claude/workflows/brainstorming-principles.md
### Key Analysis Questions
**1. Threat Landscape Assessment**
- What are the primary threat vectors and attack scenarios?
- Who are the potential threat actors and what are their motivations?
- What are the current vulnerabilities and exposure risks?
**2. Security Architecture Design**
- What security controls and defensive measures are needed?
- How should we implement defense-in-depth strategies?
- What authentication and authorization mechanisms are appropriate?
**3. Risk Management and Compliance**
- What are the regulatory and compliance requirements?
- How should we prioritize and manage identified security risks?
- What security policies and procedures need to be established?
**4. Implementation and Operations**
- How should we integrate security into development and operations?
- What monitoring and detection capabilities are required?
- How should we plan for incident response and recovery?
## ⚡ **Two-Step Execution Flow**
### ⚠️ Session Management - FIRST STEP
Session detection and selection:
```bash
# Check for active sessions
active_sessions=$(find .workflow -name ".active-*" 2>/dev/null)
if [ multiple_sessions ]; then
prompt_user_to_select_session()
else
use_existing_or_create_new()
fi
```
### Step 1: Context Gathering Phase
**Security Expert Perspective Questioning**
Before agent assignment, gather comprehensive security context:
#### 📋 Role-Specific Questions
1. **Threat Assessment & Attack Vectors**
- Sensitive data types and classification levels?
- Known threat actors and attack scenarios?
- Current security vulnerabilities and concerns?
2. **Compliance & Regulatory Requirements**
- Applicable compliance standards (GDPR, SOX, HIPAA)?
- Industry-specific security requirements?
- Audit and reporting obligations?
3. **Security Architecture & Controls**
- Authentication and authorization needs?
- Data encryption and protection requirements?
- Network security and access control strategy?
4. **Incident Response & Monitoring**
- Security monitoring and detection capabilities?
- Incident response procedures and team readiness?
- Business continuity and disaster recovery plans?
#### Context Validation
- **Minimum Response**: Each answer must be ≥50 characters
- **Re-prompting**: Insufficient detail triggers follow-up questions
- **Context Storage**: Save responses to `.brainstorming/security-expert-context.md`
### Step 2: Agent Assignment with Flow Control
**Dedicated Agent Execution**
```bash
Task(conceptual-planning-agent): "
[FLOW_CONTROL]
Execute dedicated security-expert conceptual analysis for: {topic}
ASSIGNED_ROLE: security-expert
OUTPUT_LOCATION: .brainstorming/security-expert/
USER_CONTEXT: {validated_responses_from_context_gathering}
Flow Control Steps:
[
{
\"step\": \"load_role_template\",
\"action\": \"Load security-expert planning template\",
\"command\": \"bash($(cat ~/.claude/workflows/cli-templates/planning-roles/security-expert.md))\",
\"output_to\": \"role_template\"
}
]
Conceptual Analysis Requirements:
- Apply security-expert perspective to topic analysis
- Focus on threat modeling, security architecture, and risk assessment
- Use loaded role template framework for analysis structure
- Generate role-specific deliverables in designated output location
- Address all user context from questioning phase
Deliverables:
- analysis.md: Main security analysis
- recommendations.md: Security recommendations
- deliverables/: Security-specific outputs as defined in role template
Embody security-expert role expertise for comprehensive conceptual planning."
```
### Progress Tracking
TodoWrite tracking for two-step process:
```json
[
{"content": "Gather security expert context through role-specific questioning", "status": "in_progress", "activeForm": "Gathering context"},
{"content": "Validate context responses and save to security-expert-context.md", "status": "pending", "activeForm": "Validating context"},
{"content": "Load security-expert planning template via flow control", "status": "pending", "activeForm": "Loading template"},
{"content": "Execute dedicated conceptual-planning-agent for security-expert role", "status": "pending", "activeForm": "Executing agent"}
]
```
### Phase 4: Conceptual Planning Agent Coordination
```bash
Task(conceptual-planning-agent): "
Conduct security expert perspective brainstorming for: {topic}
ROLE CONTEXT: Security Expert
- Focus Areas: Threat modeling, security architecture, risk management, compliance
- Analysis Framework: Security-first approach with emphasis on defense-in-depth and risk mitigation
- Success Metrics: Vulnerability reduction, incident prevention, compliance adherence, security maturity
USER CONTEXT: {captured_user_requirements_from_session}
ANALYSIS REQUIREMENTS:
1. Threat Modeling and Risk Assessment
- Identify potential threat actors and their capabilities
- Map attack vectors and potential attack paths
- Analyze system vulnerabilities and exposure points
- Assess business impact and likelihood of security incidents
2. Security Architecture Design
- Design authentication and authorization mechanisms
- Plan encryption and data protection strategies
- Design network security and access controls
- Plan security monitoring and logging architecture
3. Application Security Analysis
- Review secure coding practices and input validation
- Analyze session management and state security
- Assess API security and integration points
- Plan for secure software development lifecycle
4. Infrastructure and Operations Security
- Design system hardening and configuration management
- Plan security monitoring and SIEM integration
- Design incident response and recovery procedures
- Plan security awareness and training programs
5. Compliance and Regulatory Analysis
- Identify applicable compliance frameworks (GDPR, SOX, PCI-DSS, etc.)
- Map security controls to regulatory requirements
- Plan compliance monitoring and audit procedures
- Design privacy protection and data handling policies
6. Security Implementation Planning
- Prioritize security controls based on risk assessment
- Plan phased security implementation approach
- Design security testing and validation procedures
- Plan ongoing security maintenance and updates
OUTPUT REQUIREMENTS: Save comprehensive analysis to:
.workflow/WFS-{topic-slug}/.brainstorming/security-expert/
- analysis.md (main security analysis and threat model)
- security-architecture.md (security controls and defensive measures)
- compliance-plan.md (regulatory compliance and policy framework)
- implementation-guide.md (security implementation and operational procedures)
Apply cybersecurity expertise to create comprehensive security solutions that protect against threats while enabling business objectives."
```
## 📊 **Output Specification**
### Output Location
```
.workflow/WFS-{topic-slug}/.brainstorming/security-expert/
├── analysis.md # Primary security analysis and threat modeling
├── security-architecture.md # Security controls and defensive measures
├── compliance-plan.md # Regulatory compliance and policy framework
└── implementation-guide.md # Security implementation and operational procedures
```
### Document Templates
#### analysis.md Structure
```markdown
# Security Expert Analysis: {Topic}
*Generated: {timestamp}*
## Executive Summary
[Key security findings and recommendations overview]
## Threat Landscape Assessment
### Threat Actor Analysis
### Attack Vector Identification
### Vulnerability Assessment
### Risk Prioritization Matrix
## Security Requirements Analysis
### Functional Security Requirements
### Compliance and Regulatory Requirements
### Business Continuity Requirements
### Privacy and Data Protection Needs
## Security Architecture Design
### Authentication and Authorization Framework
### Data Protection and Encryption Strategy
### Network Security and Access Controls
### Monitoring and Detection Capabilities
## Risk Management Strategy
### Risk Assessment Methodology
### Risk Mitigation Controls
### Residual Risk Acceptance Criteria
### Continuous Risk Monitoring Plan
## Implementation Security Plan
### Security Control Implementation Priorities
### Security Testing and Validation Approach
### Incident Response and Recovery Procedures
### Security Awareness and Training Program
## Compliance and Governance
### Regulatory Compliance Framework
### Security Policy and Procedure Requirements
### Audit and Assessment Planning
### Governance and Oversight Structure
```
## 🔄 **Session Integration**
### Status Synchronization
Upon completion, update `workflow-session.json`:
```json
{
"phases": {
"BRAINSTORM": {
"security_expert": {
"status": "completed",
"completed_at": "timestamp",
"output_directory": ".workflow/WFS-{topic}/.brainstorming/security-expert/",
"key_insights": ["threat_model", "security_controls", "compliance_requirements"]
}
}
}
}
```
### Cross-Role Collaboration
Security expert perspective provides:
- **Security Architecture Requirements** → System Architect
- **Security Compliance Constraints** → Product Manager
- **Secure Interface Design Requirements** → UI Designer
- **Data Protection Requirements** → Data Architect
- **Security Feature Specifications** → Feature Planner
## ✅ **Quality Assurance**
### Required Security Elements
- [ ] Comprehensive threat model with identified attack vectors and mitigations
- [ ] Security architecture design with layered defensive controls
- [ ] Risk assessment with prioritized mitigation strategies
- [ ] Compliance framework addressing all relevant regulatory requirements
- [ ] Implementation plan with security testing and validation procedures
### Security Architecture Principles
- [ ] **Defense-in-Depth**: Multiple layers of security controls and protective measures
- [ ] **Least Privilege**: Minimal access rights granted based on need-to-know basis
- [ ] **Zero Trust**: Verify and validate all access requests regardless of location
- [ ] **Security by Design**: Security considerations integrated from initial design phase
- [ ] **Fail Secure**: System failures default to secure state with controlled recovery
### Risk Management Standards
- [ ] **Threat Coverage**: All identified threats have corresponding mitigation controls
- [ ] **Risk Tolerance**: Security risks align with organizational risk appetite
- [ ] **Continuous Monitoring**: Ongoing security monitoring and threat detection capabilities
- [ ] **Incident Response**: Comprehensive incident response and recovery procedures
- [ ] **Compliance Adherence**: Full compliance with applicable regulatory frameworks
### Implementation Readiness
- [ ] **Control Effectiveness**: Security controls are tested and validated for effectiveness
- [ ] **Integration Planning**: Security solutions integrate with existing infrastructure
- [ ] **Operational Procedures**: Clear procedures for security operations and maintenance
- [ ] **Training and Awareness**: Security awareness programs for all stakeholders
- [ ] **Continuous Improvement**: Framework for ongoing security assessment and enhancement

View File

@@ -0,0 +1,200 @@
---
name: subject-matter-expert
description: Generate or update subject-matter-expert/analysis.md addressing topic-framework discussion points
argument-hint: "optional topic - uses existing framework if available"
allowed-tools: Task(conceptual-planning-agent), TodoWrite(*), Read(*), Write(*)
---
## 🎯 **Subject Matter Expert Analysis Generator**
### Purpose
**Specialized command for generating subject-matter-expert/analysis.md** that addresses topic-framework.md discussion points from domain knowledge and technical expertise perspective. Creates or updates role-specific analysis with framework references.
### Core Function
- **Framework-based Analysis**: Address each discussion point in topic-framework.md
- **Domain Expertise Focus**: Deep technical knowledge, industry standards, and best practices
- **Update Mechanism**: Create new or update existing analysis.md
- **Agent Delegation**: Use conceptual-planning-agent for analysis generation
### Analysis Scope
- **Domain Knowledge**: Industry-specific expertise, regulatory requirements, and compliance
- **Technical Standards**: Best practices, design patterns, and architectural guidelines
- **Risk Assessment**: Technical debt, scalability concerns, and maintenance implications
- **Knowledge Transfer**: Documentation strategies, training requirements, and expertise sharing
## ⚙️ **Execution Protocol**
### Phase 1: Session & Framework Detection
```bash
# Check active session and framework
CHECK: .workflow/.active-* marker files
IF active_session EXISTS:
session_id = get_active_session()
brainstorm_dir = .workflow/WFS-{session}/.brainstorming/
CHECK: brainstorm_dir/topic-framework.md
IF EXISTS:
framework_mode = true
load_framework = true
ELSE:
IF topic_provided:
framework_mode = false # Create analysis without framework
ELSE:
ERROR: "No framework found and no topic provided"
```
### Phase 2: Analysis Mode Detection
```bash
# Determine execution mode
IF framework_mode == true:
mode = "framework_based_analysis"
topic_ref = load_framework_topic()
discussion_points = extract_framework_points()
ELSE:
mode = "standalone_analysis"
topic_ref = provided_topic
discussion_points = generate_basic_structure()
```
### Phase 3: Agent Execution with Flow Control
**Framework-Based Analysis Generation**
```bash
Task(conceptual-planning-agent): "
[FLOW_CONTROL]
Execute subject-matter-expert analysis for existing topic framework
## Context Loading
ASSIGNED_ROLE: subject-matter-expert
OUTPUT_LOCATION: .workflow/WFS-{session}/.brainstorming/subject-matter-expert/
ANALYSIS_MODE: {framework_mode ? "framework_based" : "standalone"}
## Flow Control Steps
1. **load_topic_framework**
- Action: Load structured topic discussion framework
- Command: Read(.workflow/WFS-{session}/.brainstorming/topic-framework.md)
- Output: topic_framework_content
2. **load_role_template**
- Action: Load subject-matter-expert planning template
- Command: bash($(cat ~/.claude/workflows/cli-templates/planning-roles/subject-matter-expert.md))
- Output: role_template_guidelines
3. **load_session_metadata**
- Action: Load session metadata and existing context
- Command: Read(.workflow/WFS-{session}/workflow-session.json)
- Output: session_context
## Analysis Requirements
**Framework Reference**: Address all discussion points in topic-framework.md from domain expertise and technical standards perspective
**Role Focus**: Domain knowledge, technical standards, risk assessment, knowledge transfer
**Structured Approach**: Create analysis.md addressing framework discussion points
**Template Integration**: Apply role template guidelines within framework structure
## Expected Deliverables
1. **analysis.md**: Comprehensive domain expertise analysis addressing all framework discussion points
2. **Framework Reference**: Include @../topic-framework.md reference in analysis
## Completion Criteria
- Address each discussion point from topic-framework.md with subject matter expertise
- Provide actionable technical standards and best practices recommendations
- Include risk assessment and compliance considerations
- Reference framework document using @ notation for integration
"
```
## 📋 **TodoWrite Integration**
### Workflow Progress Tracking
```javascript
TodoWrite({
todos: [
{
content: "Detect active session and locate topic framework",
status: "in_progress",
activeForm: "Detecting session and framework"
},
{
content: "Load topic-framework.md and session metadata for context",
status: "pending",
activeForm: "Loading framework and session context"
},
{
content: "Execute subject-matter-expert analysis using conceptual-planning-agent with FLOW_CONTROL",
status: "pending",
activeForm: "Executing subject-matter-expert framework analysis"
},
{
content: "Generate analysis.md addressing all framework discussion points",
status: "pending",
activeForm: "Generating structured subject-matter-expert analysis"
},
{
content: "Update workflow-session.json with subject-matter-expert completion status",
status: "pending",
activeForm: "Updating session metadata"
}
]
});
```
## 📊 **Output Structure**
### Framework-Based Analysis
```
.workflow/WFS-{session}/.brainstorming/subject-matter-expert/
└── analysis.md # Structured analysis addressing topic-framework.md discussion points
```
### Analysis Document Structure
```markdown
# Subject Matter Expert Analysis: [Topic from Framework]
## Framework Reference
**Topic Framework**: @../topic-framework.md
**Role Focus**: Domain Expertise & Technical Standards perspective
## Discussion Points Analysis
[Address each point from topic-framework.md with subject matter expertise]
### Core Requirements (from framework)
[Domain-specific requirements and industry standards perspective]
### Technical Considerations (from framework)
[Deep technical analysis, architectural patterns, and best practices]
### User Experience Factors (from framework)
[Domain-specific usability standards and industry conventions]
### Implementation Challenges (from framework)
[Technical risks, scalability concerns, and maintenance implications]
### Success Metrics (from framework)
[Domain-specific KPIs, compliance metrics, and quality standards]
## Subject Matter Expert Specific Recommendations
[Role-specific technical expertise and industry best practices]
---
*Generated by subject-matter-expert analysis addressing structured framework*
```
## 🔄 **Session Integration**
### Completion Status Update
```json
{
"subject_matter_expert": {
"status": "completed",
"framework_addressed": true,
"output_location": ".workflow/WFS-{session}/.brainstorming/subject-matter-expert/analysis.md",
"framework_reference": "@../topic-framework.md"
}
}
```
### Integration Points
- **Framework Reference**: @../topic-framework.md for structured discussion points
- **Cross-Role Synthesis**: Domain expertise insights available for synthesis-report.md integration
- **Agent Autonomy**: Independent execution with framework guidance

View File

@@ -1,258 +1,289 @@
---
name: synthesis
description: Synthesize all brainstorming role perspectives into comprehensive analysis and recommendations
usage: /workflow:brainstorm:synthesis
argument-hint: "no arguments required - analyzes existing brainstorming session outputs"
examples:
- /workflow:brainstorm:synthesis
allowed-tools: Read(*), Write(*), TodoWrite(*), Glob(*)
description: Generate synthesis-specification.md from topic-framework and role analyses with @ references using conceptual-planning-agent
argument-hint: "[optional: --session session-id]"
allowed-tools: Task(conceptual-planning-agent), TodoWrite(*), Read(*), Write(*)
---
## 🧩 **Command Overview: Brainstorm Synthesis**
## 🧩 **Synthesis Document Generator**
### Core Function
Cross-role integration command that synthesizes all brainstorming role perspectives into comprehensive strategic analysis, actionable recommendations, and prioritized implementation roadmaps.
**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
- **Cross-Role Integration**: Consolidate analysis results from all brainstorming role perspectives
- **Insight Synthesis**: Identify consensus areas, disagreement points, and breakthrough opportunities
- **Decision Support**: Generate prioritized recommendations and strategic action plans
- **Comprehensive Reporting**: Create integrated brainstorming summary reports with implementation guidance
- **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+)
### Analysis Scope Coverage
- **Product Management**: User needs, business value, market opportunities
- **System Architecture**: Technical design, technology selection, implementation feasibility
- **User Experience**: Interface design, usability, accessibility standards
- **Data Architecture**: Data models, processing workflows, analytics capabilities
- **Security Expert**: Threat assessment, security controls, compliance requirements
- **User Research**: Behavioral insights, needs validation, experience optimization
- **Business Analysis**: Process optimization, cost-benefit analysis, change management
- **Innovation Leadership**: Technology trends, innovation opportunities, future planning
- **Feature Planning**: Development planning, quality assurance, delivery management
### 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-specification.md** → Complete integrated specification (output)
## ⚙️ **Execution Protocol**
### Phase 1: Session Detection & Data Collection
```bash
# Detect active brainstorming session
CHECK: .workflow/.active-* marker files
IF active_session EXISTS:
session_id = get_active_session()
load_context_from(session_id)
ELSE:
ERROR: "No active brainstorming session found. Please run role-specific brainstorming commands first."
EXIT
```
### ⚠️ Agent Execution with Flow Control
**Execution Model**: Uses conceptual-planning-agent for synthesis generation with structured file loading.
### Phase 2: Role Output Scanning
```bash
# Scan all role brainstorming outputs
SCAN_DIRECTORY: .workflow/WFS-{session}/.brainstorming/
COLLECT_OUTPUTS: [
product-manager/analysis.md,
system-architect/analysis.md,
ui-designer/analysis.md,
data-architect/analysis.md,
security-expert/analysis.md,
user-researcher/analysis.md,
business-analyst/analysis.md,
innovation-lead/analysis.md,
feature-planner/analysis.md
]
```
**Rationale**:
- **Autonomous Execution**: Agent independently loads and processes all required documents
- **Flow Control**: Structured document loading ensures systematic analysis
- **Complex Cognitive Analysis**: Leverages agent's analytical capabilities for cross-role synthesis
- **Conceptual Focus**: Agent specializes in conceptual analysis and multi-perspective integration
### Phase 3: Task Tracking Initialization
Initialize synthesis analysis task tracking:
**Agent Responsibility**: All file reading and synthesis generation performed by conceptual-planning-agent with FLOW_CONTROL instructions.
### 📋 Task Tracking Protocol
Initialize synthesis task tracking using TodoWrite at command start:
```json
[
{"content": "Initialize brainstorming synthesis session", "status": "completed", "activeForm": "Initializing synthesis"},
{"content": "Collect and analyze all role perspectives", "status": "in_progress", "activeForm": "Collecting role analyses"},
{"content": "Identify cross-role insights and patterns", "status": "pending", "activeForm": "Identifying insights"},
{"content": "Generate consensus and disagreement analysis", "status": "pending", "activeForm": "Analyzing consensus"},
{"content": "Create prioritized recommendations matrix", "status": "pending", "activeForm": "Creating recommendations"},
{"content": "Generate comprehensive synthesis report", "status": "pending", "activeForm": "Generating synthesis report"},
{"content": "Create action plan with implementation priorities", "status": "pending", "activeForm": "Creating action plan"}
{"content": "Detect active session and validate topic-framework.md existence", "status": "in_progress", "activeForm": "Detecting session and validating framework"},
{"content": "Discover participating role analyses dynamically", "status": "pending", "activeForm": "Discovering role analyses"},
{"content": "Check existing synthesis and confirm user action", "status": "pending", "activeForm": "Checking update mechanism"},
{"content": "Execute synthesis generation using conceptual-planning-agent with FLOW_CONTROL", "status": "pending", "activeForm": "Executing agent-based synthesis generation"},
{"content": "Agent performs cross-role analysis and generates synthesis-specification.md", "status": "pending", "activeForm": "Agent analyzing and generating synthesis"},
{"content": "Update workflow-session.json with synthesis completion status", "status": "pending", "activeForm": "Updating session metadata"}
]
```
### Phase 4: Cross-Role Analysis Execution
### Phase 1: Document Discovery & Validation
```bash
# Detect active brainstorming session
IF --session parameter provided:
session_id = provided session
ELSE:
CHECK: .workflow/.active-* marker files
IF active_session EXISTS:
session_id = get_active_session()
ELSE:
ERROR: "No active brainstorming session found"
EXIT
#### 4.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)
END IF
END FOR
brainstorm_dir = .workflow/WFS-{session}/.brainstorming/
# Validate required documents
CHECK: brainstorm_dir/topic-framework.md
IF NOT EXISTS:
ERROR: "topic-framework.md not found. Run /workflow:brainstorm:artifacts first"
EXIT
# Load user's original prompt from session metadata
session_metadata = Read(.workflow/WFS-{session}/workflow-session.json)
original_user_prompt = session_metadata.project || session_metadata.description
IF NOT original_user_prompt:
WARN: "No original user prompt found in session metadata"
original_user_prompt = "Not available"
```
#### 4.2 Cross-Role Insight Analysis
```pseudo
# Consensus identification
consensus_areas = identify_common_themes(role_insights)
agreement_matrix = create_agreement_matrix(role_recommendations)
### Phase 2: Role Analysis Discovery
```bash
# Dynamically discover available role analyses
SCAN_DIRECTORY: .workflow/WFS-{session}/.brainstorming/
FIND_ANALYSES: [
Scan all subdirectories for */analysis.md files
Extract role names from directory names
]
# Disagreement analysis
disagreement_areas = identify_conflicting_views(role_insights)
tension_points = analyze_role_conflicts(role_recommendations)
# 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
# Innovation opportunity extraction
innovation_opportunities = extract_breakthrough_ideas(role_insights)
synergy_opportunities = identify_cross_role_synergies(role_insights)
LOAD_DOCUMENTS: {
"original_user_prompt": original_user_prompt (from session metadata),
"topic_framework": topic-framework.md,
"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
# CRITICAL: Original user prompt MUST be primary reference for synthesis
```
#### 4.3 Priority and Decision Matrix Generation
```pseudo
# Create comprehensive evaluation matrix
FOR each recommendation:
impact_score = calculate_business_impact(recommendation, role_insights)
feasibility_score = calculate_technical_feasibility(recommendation, role_insights)
effort_score = calculate_implementation_effort(recommendation, role_insights)
risk_score = calculate_associated_risks(recommendation, role_insights)
priority_score = weighted_score(impact_score, feasibility_score, effort_score, risk_score)
END FOR
### Phase 3: Update Mechanism Check
```bash
# Check for existing synthesis
IF synthesis-specification.md EXISTS:
SHOW current synthesis summary to user
ASK: "Synthesis exists. Do you want to:"
OPTIONS:
1. "Regenerate completely" → Create new synthesis
2. "Update with new analyses" → Integrate new role analyses
3. "Preserve existing" → Exit without changes
ELSE:
CREATE new synthesis
```
SORT recommendations BY priority_score DESC
### Phase 4: Agent Execution with Flow Control
**Synthesis Generation using conceptual-planning-agent**
Delegate synthesis generation to conceptual-planning-agent with structured file loading:
```bash
Task(conceptual-planning-agent): "
[FLOW_CONTROL]
Execute comprehensive synthesis generation from topic framework and role analyses
## Context Loading
OUTPUT_FILE: synthesis-specification.md
OUTPUT_PATH: .workflow/WFS-{session}/.brainstorming/synthesis-specification.md
SESSION_ID: {session_id}
ANALYSIS_MODE: cross_role_synthesis
## ⚠️ CRITICAL: User Intent Authority
**ORIGINAL USER PROMPT IS THE PRIMARY REFERENCE**: {original_user_prompt}
All synthesis MUST align with user's original intent. Topic framework and role analyses are supplementary context.
## Flow Control Steps
1. **load_original_user_prompt**
- Action: Load user's original intent from session metadata
- Command: Read(.workflow/WFS-{session}/workflow-session.json)
- Extract: project field or description field
- Output: original_user_prompt (PRIMARY REFERENCE)
- Priority: HIGHEST - This is the authoritative source of user intent
2. **load_topic_framework**
- Action: Load structured topic discussion framework
- Command: Read(.workflow/WFS-{session}/.brainstorming/topic-framework.md)
- Output: topic_framework_content
- Note: Validate alignment with original_user_prompt
3. **discover_role_analyses**
- Action: Dynamically discover all participating role analysis files
- Command: Glob(.workflow/WFS-{session}/.brainstorming/*/analysis.md)
- Output: role_analysis_paths, participating_roles
4. **load_role_analyses**
- Action: Load all discovered role analysis documents
- Command: Read(each path from role_analysis_paths)
- Output: role_analyses_content
- Note: Filter insights relevant to original_user_prompt
5. **check_existing_synthesis**
- Action: Check if synthesis-specification.md already exists
- Command: Read(.workflow/WFS-{session}/.brainstorming/synthesis-specification.md) [if exists]
- Output: existing_synthesis_content [optional]
6. **load_synthesis_template**
- Action: Load synthesis role template for structure and guidelines
- Command: Read(~/.claude/workflows/cli-templates/planning-roles/synthesis-role.md)
- Output: synthesis_template_guidelines
## Synthesis Requirements
### ⚠️ PRIMARY REQUIREMENT: User Intent Alignment
**User's Original Goal is Supreme**: Synthesis MUST directly address {original_user_prompt}
**Intent Validation**: Every requirement, design decision, and recommendation must trace back to user's original intent
**Deviation Detection**: Flag any role analysis points that drift from user's stated goals
**Refocus Mechanism**: When role discussions diverge, explicitly refocus on original user prompt
**Traceability**: Each section should reference how it fulfills user's original intent
### Core Integration
**Cross-Role Analysis**: Integrate all discovered role analyses with comprehensive coverage
**Framework Integration**: Address how each role responded to topic-framework.md discussion points
**User Intent Filter**: Prioritize insights that directly serve user's original prompt
**Decision Transparency**: Document both adopted solutions and rejected alternatives with rationale
**Process Integration**: Include team capability gaps, process risks, and collaboration patterns
**Visual Documentation**: Include key diagrams (architecture, data model, user journey) via Mermaid
**Priority Matrix**: Create quantified recommendation matrix aligned with user's goals
**Actionable Plan**: Provide phased implementation roadmap addressing user's original objectives
### Cross-Role Analysis Process (Agent Internal Execution)
Perform systematic cross-role analysis following these steps:
1. **Data Collection**: Extract key insights, recommendations, concerns, and diagrams from each discovered role analysis
2. **Consensus Identification**: Identify common themes and agreement areas across all participating roles
3. **Disagreement Analysis**: Document conflicting views and track which specific roles disagree on each point
4. **Innovation Extraction**: Identify breakthrough ideas and cross-role synergy opportunities
5. **Priority Scoring**: Calculate multi-dimensional priority scores (impact, feasibility, effort, risk) for each recommendation
6. **Decision Matrix**: Create comprehensive evaluation matrix and sort recommendations by priority
## Synthesis Quality Standards
Follow synthesis-specification.md structure defined in synthesis-role.md template:
- Use template structure for comprehensive document organization
- Apply analysis guidelines for cross-role synthesis process
- Include all required sections from template (Executive Summary, Key Designs, Requirements, etc.)
- Follow @ reference system for traceability to source role analyses
- Apply quality standards from template (completeness, visual clarity, decision transparency)
- Validate output against template's output validation checklist
## Expected Deliverables
1. **synthesis-specification.md**: Complete integrated specification consolidating all role perspectives
2. **@ References**: Include cross-references to source role analyses
3. **Session Metadata Update**: Update workflow-session.json with synthesis completion status
## Completion Criteria
- ⚠️ **USER INTENT ALIGNMENT**: Synthesis directly addresses user's original prompt
- All discovered role analyses integrated without gaps
- Framework discussion points addressed across all roles
- **Intent traceability**: Each major section references user's original goals
- Controversial points documented with dissenting roles identified
- Process concerns (team capabilities, risks, collaboration) captured
- Quantified priority recommendations aligned with user's objectives
- Actionable implementation plan addressing user's stated goals
- Comprehensive risk assessment with mitigation strategies
- **Deviation warnings**: Any significant departures from user intent flagged explicitly
## Execution Notes
- Dynamic role participation: Only synthesize roles that produced analysis.md files
- Update mechanism: If synthesis exists, prompt user for regenerate/update/preserve decision
- Timeout allocation: Complex synthesis task (60-90 min recommended)
- Reference @intelligent-tools-strategy.md for timeout guidelines
"
```
## 📊 **Output Specification**
### Output Location
The synthesis process creates **one consolidated document** that integrates all role perspectives:
```
.workflow/WFS-{topic-slug}/.brainstorming/
├── synthesis-report.md # Comprehensive synthesis analysis report
├── recommendations-matrix.md # Priority recommendation matrix
── action-plan.md # Implementation action plan
├── consensus-analysis.md # Consensus and disagreement analysis
└── brainstorm-summary.json # Machine-readable synthesis data
├── topic-framework.md # Input: Framework structure
├── [role]/analysis.md # Input: Role analyses (multiple)
── synthesis-specification.md # ★ OUTPUT: Complete integrated specification
```
### Core Output Documents
#### synthesis-specification.md Structure
#### synthesis-report.md Structure
```markdown
# Brainstorming Synthesis Report: {Topic}
*Generated: {timestamp} | Session: WFS-{topic-slug}*
**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).
## Executive Summary
### Key Findings Overview
### Strategic Recommendations
### Implementation Priority
### Success Metrics
**Template Reference**: Complete document structure and content guidelines available in `synthesis-role.md` template, including:
- Executive Summary with strategic overview
- Key Designs & Decisions (architecture diagrams, ADRs, user journeys)
- Controversial Points & Alternatives (decision transparency)
- Requirements & Acceptance Criteria (Functional, Non-Functional, Business)
- Design Specifications (UI/UX, Architecture, Domain Expertise)
- Process & Collaboration Concerns (team skills, risks, patterns, constraints)
- Implementation Roadmap (high-level phases)
- Risk Assessment & Mitigation strategies
## Participating Perspectives Analysis
### Roles Analyzed: {list_of_completed_roles}
### Coverage Assessment: {completeness_percentage}%
### Analysis Quality Score: {quality_assessment}
## Cross-Role Insights Synthesis
### 🤝 Consensus Areas
**Strong Agreement (3+ roles)**:
1. **{consensus_theme_1}**
- Supporting roles: {role1, role2, role3}
- Key insight: {shared_understanding}
- Business impact: {impact_assessment}
2. **{consensus_theme_2}**
- Supporting roles: {role1, role2, role4}
- Key insight: {shared_understanding}
- Business impact: {impact_assessment}
### ⚡ Breakthrough Ideas
**Innovation Opportunities**:
1. **{breakthrough_idea_1}**
- Origin: {source_role}
- Cross-role support: {supporting_roles}
- Innovation potential: {potential_assessment}
2. **{breakthrough_idea_2}**
- Origin: {source_role}
- Cross-role support: {supporting_roles}
- Innovation potential: {potential_assessment}
### 🔄 Areas of Disagreement
**Tension Points Requiring Resolution**:
1. **{disagreement_area_1}**
- Conflicting views: {role1_view} vs {role2_view}
- Root cause: {underlying_issue}
- Resolution approach: {recommended_resolution}
2. **{disagreement_area_2}**
- Conflicting views: {role1_view} vs {role2_view}
- Root cause: {underlying_issue}
- Resolution approach: {recommended_resolution}
## Comprehensive Recommendations Matrix
### 🎯 High Priority (Immediate Action)
| Recommendation | Business Impact | Technical Feasibility | Implementation Effort | Risk Level | Supporting Roles |
|----------------|-----------------|----------------------|---------------------|------------|------------------|
| {rec_1} | High | High | Medium | Low | PM, Arch, UX |
| {rec_2} | High | Medium | Low | Medium | BA, PM, FP |
### 📋 Medium Priority (Strategic Planning)
| Recommendation | Business Impact | Technical Feasibility | Implementation Effort | Risk Level | Supporting Roles |
|----------------|-----------------|----------------------|---------------------|------------|------------------|
| {rec_3} | Medium | High | High | Medium | Arch, DA, Sec |
| {rec_4} | Medium | Medium | Medium | Low | UX, UR, PM |
### 🔬 Research Priority (Future Investigation)
| Recommendation | Business Impact | Technical Feasibility | Implementation Effort | Risk Level | Supporting Roles |
|----------------|-----------------|----------------------|---------------------|------------|------------------|
| {rec_5} | High | Unknown | High | High | IL, Arch, PM |
| {rec_6} | Medium | Low | High | High | IL, DA, Sec |
## Implementation Strategy
### Phase 1: Foundation (0-3 months)
- **Focus**: High-priority, low-effort recommendations
- **Key Actions**: {action_list}
- **Success Metrics**: {metrics_list}
- **Required Resources**: {resource_list}
### Phase 2: Development (3-9 months)
- **Focus**: Medium-priority strategic initiatives
- **Key Actions**: {action_list}
- **Success Metrics**: {metrics_list}
- **Required Resources**: {resource_list}
### Phase 3: Innovation (9+ months)
- **Focus**: Research and breakthrough opportunities
- **Key Actions**: {action_list}
- **Success Metrics**: {metrics_list}
- **Required Resources**: {resource_list}
## Risk Assessment and Mitigation
### Critical Risks Identified
1. **{risk_1}**: {description} | Mitigation: {strategy}
2. **{risk_2}**: {description} | Mitigation: {strategy}
### Success Factors
- {success_factor_1}
- {success_factor_2}
- {success_factor_3}
## Next Steps and Follow-up
### Immediate Actions Required
### Decision Points Needing Resolution
### Continuous Monitoring Requirements
### Future Brainstorming Sessions Recommended
---
*This synthesis integrates insights from {role_count} perspectives to provide comprehensive strategic guidance.*
```
**Agent Usage**: The conceptual-planning-agent loads this template to understand expected structure and quality standards.
## 🔄 **Session Integration**
### Status Synchronization
### 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": {
@@ -260,18 +291,47 @@ Upon completion, update `workflow-session.json`:
"status": "completed",
"synthesis_completed": true,
"completed_at": "timestamp",
"participating_roles": ["product-manager", "system-architect", "ui-designer", ...],
"key_outputs": {
"synthesis_report": ".workflow/WFS-{topic}/.brainstorming/synthesis-report.md",
"action_plan": ".workflow/WFS-{topic}/.brainstorming/action-plan.md",
"recommendations_matrix": ".workflow/WFS-{topic}/.brainstorming/recommendations-matrix.md"
"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"
},
"metrics": {
"roles_analyzed": 9,
"consensus_areas": 5,
"breakthrough_ideas": 3,
"high_priority_recommendations": 8,
"implementation_phases": 3
"synthesis_quality": {
"role_integration": "complete",
"requirement_coverage": "comprehensive",
"decision_transparency": "alternatives_documented",
"process_risks_identified": true,
"implementation_readiness": "ready"
},
"content_metrics": {
"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
}
}
}
@@ -280,30 +340,39 @@ Upon completion, update `workflow-session.json`:
## ✅ **Quality Assurance**
### Required Synthesis Elements
- [ ] Integration of all available role analyses with comprehensive coverage
- [ ] Clear identification of consensus areas and disagreement points
- [ ] Quantified priority recommendation matrix with evaluation criteria
- [ ] Actionable implementation plan with phased approach
- [ ] Comprehensive risk assessment with mitigation strategies
Verify synthesis output meets these standards (detailed criteria in `synthesis-role.md` template):
### Synthesis Analysis Quality Standards
- [ ] **Completeness**: Integrates all available role analyses without gaps
- [ ] **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
- [ ] **Forward-Looking**: Includes long-term strategic and innovation considerations
### Content Completeness
- [ ] All discovered role analyses integrated without gaps
- [ ] Key designs documented (architecture diagrams, ADRs, user journeys via Mermaid)
- [ ] Controversial points captured with alternatives and rationale
- [ ] Process concerns included (team skills, risks, collaboration patterns)
- [ ] Requirements documented (Functional, Non-Functional, Business) with sources
### 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
- [ ] **Measurable Success**: Clear success metrics and monitoring frameworks
- [ ] **Clear Actions**: Specific next steps with assigned responsibilities and timelines
### Analysis Quality
- [ ] Cross-role synthesis identifies consensus and conflicts
- [ ] Decision transparency documents both adopted and rejected alternatives
- [ ] Priority recommendations with multi-dimensional evaluation
- [ ] Implementation roadmap with phased approach
- [ ] Risk assessment with mitigation strategies
- [ ] @ references to source role analyses throughout
### Integration Excellence Standards
- [ ] **Cross-Role Synthesis**: Successfully identifies and resolves role perspective conflicts
- [ ] **Strategic Coherence**: Recommendations form coherent strategic direction
- [ ] **Implementation Readiness**: Plans are detailed enough for immediate execution
- [ ] **Stakeholder Alignment**: Addresses needs and concerns of all key stakeholders
- [ ] **Continuous Improvement**: Establishes framework for ongoing optimization and learning
## 🚀 **Recommended Next Steps**
After synthesis completion, proceed to action planning:
### Standard Workflow (Recommended)
```bash
/workflow:concept-clarify --session WFS-{session-id} # Optional: Clarify ambiguities
/workflow:plan --session WFS-{session-id} # Generate IMPL_PLAN.md and tasks
/workflow:action-plan-verify --session WFS-{session-id} # Optional: Verify plan quality
/workflow:execute --session WFS-{session-id} # Start implementation
```
### TDD Workflow
```bash
/workflow:concept-clarify --session WFS-{session-id} # Optional: Clarify ambiguities
/workflow:tdd-plan --session WFS-{session-id} "Feature description"
/workflow:action-plan-verify --session WFS-{session-id} # Optional: Verify plan quality
/workflow:execute --session WFS-{session-id}
```

View File

@@ -1,57 +1,179 @@
---
name: system-architect
description: System architect perspective brainstorming for technical architecture and scalability analysis
usage: /workflow:brainstorm:system-architect <topic>
argument-hint: "topic or challenge to analyze from system architecture perspective"
examples:
- /workflow:brainstorm:system-architect "user authentication redesign"
- /workflow:brainstorm:system-architect "microservices migration strategy"
- /workflow:brainstorm:system-architect "system performance optimization"
allowed-tools: Task(conceptual-planning-agent), TodoWrite(*)
description: Generate or update system-architect/analysis.md addressing topic-framework discussion points
argument-hint: "optional topic - uses existing framework if available"
allowed-tools: Task(conceptual-planning-agent), TodoWrite(*), Read(*), Write(*)
---
## 🏗️ **Role Overview: System Architect**
## 🏗️ **System Architect Analysis Generator**
### Role Definition
Technical leader responsible for designing scalable, maintainable, and high-performance system architectures that align with business requirements and industry best practices.
### Purpose
**Specialized command for generating system-architect/analysis.md** that addresses topic-framework.md discussion points from system architecture perspective. Creates or updates role-specific analysis with framework references.
### Core Responsibilities
- **Technical Architecture Design**: Create scalable and maintainable system architectures
- **Technology Selection**: Evaluate and choose appropriate technology stacks and tools
- **System Integration**: Design inter-system communication and integration patterns
- **Performance Optimization**: Identify bottlenecks and propose optimization solutions
### Core Function
- **Framework-based Analysis**: Address each discussion point in topic-framework.md
- **Architecture Focus**: Technical architecture, scalability, and system design perspective
- **Update Mechanism**: Create new or update existing analysis.md
- **Agent Delegation**: Use conceptual-planning-agent for analysis generation
### Focus Areas
- **Scalability**: Capacity planning, load handling, elastic scaling strategies
- **Reliability**: High availability design, fault tolerance, disaster recovery
- **Security**: Architectural security, data protection, access control patterns
- **Maintainability**: Code quality, modular design, technical debt management
### Analysis Scope
- **Technical Architecture**: Scalable and maintainable system design
- **Technology Selection**: Stack evaluation and architectural decisions
- **Performance & Scalability**: Capacity planning and optimization strategies
- **Integration Patterns**: System communication and data flow design
### Success Metrics
- System performance benchmarks (latency, throughput)
- Availability and uptime metrics
- Scalability handling capacity growth
- Technical debt and maintenance efficiency
### Role Boundaries & Responsibilities
## 🧠 **Analysis Framework**
#### **What This Role OWNS (Macro-Architecture)**
- **System-Level Architecture**: Service boundaries, deployment topology, and system composition
- **Cross-Service Communication Patterns**: Choosing between microservices/monolithic, event-driven/request-response, sync/async patterns
- **Technology Stack Decisions**: Language, framework, database, and infrastructure choices
- **Non-Functional Requirements**: Scalability, performance, availability, disaster recovery, and monitoring strategies
- **Integration Planning**: How systems and services connect at the macro level (not specific API contracts)
@~/.claude/workflows/brainstorming-principles.md
#### **What This Role DOES NOT Own (Defers to Other Roles)**
- **API Contract Details**: Specific endpoint definitions, URL structures, HTTP methods → Defers to **API Designer**
- **Data Schemas**: Detailed data model design and entity relationships → Defers to **Data Architect**
- **UI/UX Design**: Interface design and user experience → Defers to **UX Expert** and **UI Designer**
### Key Analysis Questions
#### **Handoff Points**
- **TO API Designer**: Provides architectural constraints (REST vs GraphQL, sync vs async) that define the API design space
- **TO Data Architect**: Provides system-level data flow requirements and integration patterns
- **FROM Data Architect**: Receives canonical data model to inform system integration design
**1. Architecture Design Assessment**
- What are the strengths and limitations of current architecture?
- How should we design architecture to meet business requirements?
- What are the trade-offs between microservices vs monolithic approaches?
## ⚙️ **Execution Protocol**
**2. Technology Selection Strategy**
- Which technology stack best fits current requirements?
- What are the risks and benefits of introducing new technologies?
- How well does team expertise align with technology choices?
### Phase 1: Session & Framework Detection
```bash
# Check active session and framework
CHECK: .workflow/.active-* marker files
IF active_session EXISTS:
session_id = get_active_session()
brainstorm_dir = .workflow/WFS-{session}/.brainstorming/
**3. System Integration Planning**
- How should systems efficiently integrate and communicate?
- What are the third-party service integration strategies?
CHECK: brainstorm_dir/topic-framework.md
IF EXISTS:
framework_mode = true
load_framework = true
ELSE:
IF topic_provided:
framework_mode = false # Create analysis without framework
ELSE:
ERROR: "No framework found and no topic provided"
```
### Phase 2: Analysis Mode Detection
```bash
# Check existing analysis
CHECK: brainstorm_dir/system-architect/analysis.md
IF EXISTS:
SHOW existing analysis summary
ASK: "Analysis exists. Do you want to:"
OPTIONS:
1. "Update with new insights" → Update existing
2. "Replace completely" → Generate new
3. "Cancel" → Exit without changes
ELSE:
CREATE new analysis
```
### Phase 3: Agent Task Generation
**Framework-Based Analysis** (when topic-framework.md exists):
```bash
Task(subagent_type="conceptual-planning-agent",
prompt="Generate system architect analysis addressing topic framework
## Framework Integration Required
**MANDATORY**: Load and address topic-framework.md discussion points
**Framework Reference**: @{session.brainstorm_dir}/topic-framework.md
**Output Location**: {session.brainstorm_dir}/system-architect/analysis.md
## Analysis Requirements
1. **Load Topic Framework**: Read topic-framework.md completely
2. **Address Each Discussion Point**: Respond to all 5 framework sections from system architecture perspective
3. **Include Framework Reference**: Start analysis.md with @../topic-framework.md
4. **Technical Focus**: Emphasize scalability, architecture patterns, technology decisions
5. **Structured Response**: Use framework structure for analysis organization
## Framework Sections to Address
- Core Requirements (from architecture perspective)
- Technical Considerations (detailed architectural analysis)
- User Experience Factors (technical UX considerations)
- Implementation Challenges (architecture risks and solutions)
- Success Metrics (technical metrics and monitoring)
## Output Structure Required
```markdown
# System Architect Analysis: [Topic]
**Framework Reference**: @../topic-framework.md
**Role Focus**: System Architecture and Technical Design
## Core Requirements Analysis
[Address framework requirements from architecture perspective]
## Technical Considerations
[Detailed architectural analysis]
## User Experience Factors
[Technical aspects of UX implementation]
## Implementation Challenges
[Architecture risks and mitigation strategies]
## Success Metrics
[Technical metrics and system monitoring]
## Architecture-Specific Recommendations
[Detailed technical recommendations]
```",
description="Generate system architect framework-based analysis")
```
### Phase 4: Update Mechanism
**Analysis Update Process**:
```bash
# For existing analysis updates
IF update_mode = "incremental":
Task(subagent_type="conceptual-planning-agent",
prompt="Update existing system architect analysis
## Current Analysis Context
**Existing Analysis**: @{session.brainstorm_dir}/system-architect/analysis.md
**Framework Reference**: @{session.brainstorm_dir}/topic-framework.md
## Update Requirements
1. **Preserve Structure**: Maintain existing analysis structure
2. **Add New Insights**: Integrate new technical insights and recommendations
3. **Framework Alignment**: Ensure continued alignment with topic framework
4. **Technical Updates**: Add new architecture patterns, technology considerations
5. **Maintain References**: Keep @../topic-framework.md reference
## Update Instructions
- Read existing analysis completely
- Identify areas for enhancement or new insights
- Add technical depth while preserving original structure
- Update recommendations with new architectural approaches
- Maintain framework discussion point addressing",
description="Update system architect analysis incrementally")
```
## Document Structure
### Output Files
```
.workflow/WFS-[topic]/.brainstorming/
├── topic-framework.md # Input: Framework (if exists)
└── system-architect/
└── analysis.md # ★ OUTPUT: Framework-based analysis
```
### Analysis Structure
**Required Elements**:
- **Framework Reference**: @../topic-framework.md (if framework exists)
- **Role Focus**: System Architecture and Technical Design perspective
- **5 Framework Sections**: Address each framework discussion point
- **Technical Recommendations**: Architecture-specific insights and solutions
- How should we design APIs and manage versioning?
**4. Performance and Scalability**
@@ -262,4 +384,4 @@ System architect perspective provides:
- [ ] **Resource Planning**: Resource requirements clearly defined and realistic
- [ ] **Risk Management**: Technical risks identified with mitigation plans
- [ ] **Performance Validation**: Architecture can meet performance requirements
- [ ] **Evolution Strategy**: Design allows for future growth and changes
- [ ] **Evolution Strategy**: Design allows for future growth and changes

View File

@@ -1,328 +1,221 @@
---
name: ui-designer
description: UI designer perspective brainstorming for user experience and interface design analysis
usage: /workflow:brainstorm:ui-designer <topic>
argument-hint: "topic or challenge to analyze from UI/UX design perspective"
examples:
- /workflow:brainstorm:ui-designer "user authentication redesign"
- /workflow:brainstorm:ui-designer "mobile app navigation improvement"
- /workflow:brainstorm:ui-designer "accessibility enhancement strategy"
allowed-tools: Task(conceptual-planning-agent), TodoWrite(*)
description: Generate or update ui-designer/analysis.md addressing topic-framework discussion points
argument-hint: "optional topic - uses existing framework if available"
allowed-tools: Task(conceptual-planning-agent), TodoWrite(*), Read(*), Write(*)
---
## 🎨 **Role Overview: UI Designer**
## 🎨 **UI Designer Analysis Generator**
### Role Definition
Creative professional responsible for designing intuitive, accessible, and visually appealing user interfaces that create exceptional user experiences aligned with business goals and user needs.
### Purpose
**Specialized command for generating ui-designer/analysis.md** that addresses topic-framework.md discussion points from UI/UX design perspective. Creates or updates role-specific analysis with framework references.
### Core Responsibilities
- **User Experience Design**: Create intuitive and efficient user experiences
- **Interface Design**: Design beautiful and functional user interfaces
- **Interaction Design**: Design smooth user interaction flows and micro-interactions
- **Accessibility Design**: Ensure products are inclusive and accessible to all users
### Core Function
- **Framework-based Analysis**: Address each discussion point in topic-framework.md
- **UI/UX Focus**: User experience, interface design, and accessibility perspective
- **Update Mechanism**: Create new or update existing analysis.md
- **Agent Delegation**: Use conceptual-planning-agent for analysis generation
### Focus Areas
- **User Experience**: User journeys, usability, satisfaction metrics, conversion optimization
- **Visual Design**: Interface aesthetics, brand consistency, visual hierarchy
- **Interaction Design**: Workflow optimization, feedback mechanisms, responsiveness
- **Accessibility**: WCAG compliance, inclusive design, assistive technology support
### Analysis Scope
- **Visual Design**: Color palettes, typography, spacing, and visual hierarchy implementation
- **High-Fidelity Mockups**: Polished, pixel-perfect interface designs
- **Design System Implementation**: Component libraries, design tokens, and style guides
- **Micro-Interactions & Animations**: Transition effects, loading states, and interactive feedback
- **Responsive Design**: Layout adaptations for different screen sizes and devices
### Success Metrics
- User satisfaction scores and usability metrics
- Task completion rates and conversion metrics
- Accessibility compliance scores
- Visual design consistency and brand alignment
### Role Boundaries & Responsibilities
## 🧠 **Analysis Framework**
#### **What This Role OWNS (Concrete Visual Interface Implementation)**
- **Visual Design Language**: Colors, typography, iconography, spacing, and overall aesthetic
- **High-Fidelity Mockups**: Polished designs showing exactly how the interface will look
- **Design System Components**: Building and documenting reusable UI components (buttons, inputs, cards, etc.)
- **Design Tokens**: Defining variables for colors, spacing, typography that can be used in code
- **Micro-Interactions**: Hover states, transitions, animations, and interactive feedback details
- **Responsive Layouts**: Adapting designs for mobile, tablet, and desktop breakpoints
@~/.claude/workflows/brainstorming-principles.md
#### **What This Role DOES NOT Own (Defers to Other Roles)**
- **User Research & Personas**: User behavior analysis and needs assessment → Defers to **UX Expert**
- **Information Architecture**: Content structure and navigation strategy → Defers to **UX Expert**
- **Low-Fidelity Wireframes**: Structural layouts without visual design → Defers to **UX Expert**
### Key Analysis Questions
#### **Handoff Points**
- **FROM UX Expert**: Receives wireframes, user flows, and information architecture as the foundation for visual design
- **TO Frontend Developers**: Provides design specifications, component libraries, and design tokens for implementation
- **WITH API Designer**: Coordinates on data presentation and form validation feedback (visual aspects only)
**1. User Needs and Behavior Analysis**
- What are the main pain points users experience during interactions?
- What gaps exist between user expectations and actual experience?
- What are the specific needs of different user segments?
## ⚙️ **Execution Protocol**
**2. Interface and Interaction Design**
- How can we simplify operational workflows?
- Is the information architecture logical and intuitive?
- Are interaction feedback mechanisms timely and clear?
**3. Visual and Brand Strategy**
- Does the visual design support and strengthen brand identity?
- Are color schemes, typography, and layouts appropriate and effective?
- How can we ensure cross-platform consistency?
**4. Technical Implementation Considerations**
- What are the technical feasibility constraints for design concepts?
- What responsive design requirements must be addressed?
- How do performance considerations impact user experience?
## ⚡ **Two-Step Execution Flow**
### ⚠️ Session Management - FIRST STEP
Session detection and selection:
### Phase 1: Session & Framework Detection
```bash
# Check for active sessions
active_sessions=$(find .workflow -name ".active-*" 2>/dev/null)
if [ multiple_sessions ]; then
prompt_user_to_select_session()
else
use_existing_or_create_new()
fi
# Check active session and framework
CHECK: .workflow/.active-* marker files
IF active_session EXISTS:
session_id = get_active_session()
brainstorm_dir = .workflow/WFS-{session}/.brainstorming/
CHECK: brainstorm_dir/topic-framework.md
IF EXISTS:
framework_mode = true
load_framework = true
ELSE:
IF topic_provided:
framework_mode = false # Create analysis without framework
ELSE:
ERROR: "No framework found and no topic provided"
```
### Step 1: Context Gathering Phase
**UI Designer Perspective Questioning**
### Phase 2: Analysis Mode Detection
```bash
# Determine execution mode
IF framework_mode == true:
mode = "framework_based_analysis"
topic_ref = load_framework_topic()
discussion_points = extract_framework_points()
ELSE:
mode = "standalone_analysis"
topic_ref = provided_topic
discussion_points = generate_basic_structure()
```
Before agent assignment, gather comprehensive UI/UX design context:
#### 📋 Role-Specific Questions
1. **User Experience & Personas**
- Primary user personas and their key characteristics?
- Current user pain points and usability issues?
- Platform requirements (web, mobile, desktop)?
2. **Design System & Branding**
- Existing design system and brand guidelines?
- Visual design preferences and constraints?
- Accessibility and compliance requirements?
3. **User Journey & Interactions**
- Key user workflows and task flows?
- Critical interaction points and user goals?
- Performance and responsive design requirements?
4. **Implementation & Integration**
- Technical constraints and development capabilities?
- Integration with existing UI components?
- Testing and validation approach?
#### Context Validation
- **Minimum Response**: Each answer must be ≥50 characters
- **Re-prompting**: Insufficient detail triggers follow-up questions
- **Context Storage**: Save responses to `.brainstorming/ui-designer-context.md`
### Step 2: Agent Assignment with Flow Control
**Dedicated Agent Execution**
### Phase 3: Agent Execution with Flow Control
**Framework-Based Analysis Generation**
```bash
Task(conceptual-planning-agent): "
[FLOW_CONTROL]
Execute dedicated ui-designer conceptual analysis for: {topic}
Execute ui-designer analysis for existing topic framework
## Context Loading
ASSIGNED_ROLE: ui-designer
OUTPUT_LOCATION: .brainstorming/ui-designer/
USER_CONTEXT: {validated_responses_from_context_gathering}
OUTPUT_LOCATION: .workflow/WFS-{session}/.brainstorming/ui-designer/
ANALYSIS_MODE: {framework_mode ? "framework_based" : "standalone"}
Flow Control Steps:
[
{
\"step\": \"load_role_template\",
\"action\": \"Load ui-designer planning template\",
\"command\": \"bash($(cat ~/.claude/workflows/cli-templates/planning-roles/ui-designer.md))\",
\"output_to\": \"role_template\"
}
]
## Flow Control Steps
1. **load_topic_framework**
- Action: Load structured topic discussion framework
- Command: Read(.workflow/WFS-{session}/.brainstorming/topic-framework.md)
- Output: topic_framework_content
Conceptual Analysis Requirements:
- Apply ui-designer perspective to topic analysis
- Focus on user experience, interface design, and interaction patterns
- Use loaded role template framework for analysis structure
- Generate role-specific deliverables in designated output location
- Address all user context from questioning phase
2. **load_role_template**
- Action: Load ui-designer planning template
- Command: bash($(cat ~/.claude/workflows/cli-templates/planning-roles/ui-designer.md))
- Output: role_template_guidelines
Deliverables:
- analysis.md: Main UI/UX design analysis
- recommendations.md: Design recommendations
- deliverables/: UI-specific outputs as defined in role template
3. **load_session_metadata**
- Action: Load session metadata and existing context
- Command: Read(.workflow/WFS-{session}/workflow-session.json)
- Output: session_context
Embody ui-designer role expertise for comprehensive conceptual planning."
## Analysis Requirements
**Framework Reference**: Address all discussion points in topic-framework.md from UI/UX perspective
**Role Focus**: User experience design, interface optimization, accessibility compliance
**Structured Approach**: Create analysis.md addressing framework discussion points
**Template Integration**: Apply role template guidelines within framework structure
## Expected Deliverables
1. **analysis.md**: Comprehensive UI/UX analysis addressing all framework discussion points
2. **Framework Reference**: Include @../topic-framework.md reference in analysis
## Completion Criteria
- Address each discussion point from topic-framework.md with UI/UX design expertise
- Provide actionable design recommendations and interface solutions
- Include accessibility considerations and WCAG compliance planning
- Reference framework document using @ notation for integration
"
```
### Progress Tracking
TodoWrite tracking for two-step process:
```json
[
{"content": "Gather ui-designer context through role-specific questioning", "status": "in_progress", "activeForm": "Gathering context"},
{"content": "Validate context responses and save to ui-designer-context.md", "status": "pending", "activeForm": "Validating context"},
{"content": "Load ui-designer planning template via flow control", "status": "pending", "activeForm": "Loading template"},
{"content": "Execute dedicated conceptual-planning-agent for ui-designer role", "status": "pending", "activeForm": "Executing agent"}
]
## 📋 **TodoWrite Integration**
### Workflow Progress Tracking
```javascript
TodoWrite({
todos: [
{
content: "Detect active session and locate topic framework",
status: "in_progress",
activeForm: "Detecting session and framework"
},
{
content: "Load topic-framework.md and session metadata for context",
status: "pending",
activeForm: "Loading framework and session context"
},
{
content: "Execute ui-designer analysis using conceptual-planning-agent with FLOW_CONTROL",
status: "pending",
activeForm: "Executing ui-designer framework analysis"
},
{
content: "Generate analysis.md addressing all framework discussion points",
status: "pending",
activeForm: "Generating structured ui-designer analysis"
},
{
content: "Update workflow-session.json with ui-designer completion status",
status: "pending",
activeForm: "Updating session metadata"
}
]
});
```
### Phase 4: Conceptual Planning Agent Coordination
```bash
Task(conceptual-planning-agent): "
Conduct UI designer perspective brainstorming for: {topic}
## 📊 **Output Structure**
ROLE CONTEXT: UI Designer
- Focus Areas: User experience, interface design, visual design, accessibility
- Analysis Framework: User-centered design approach with emphasis on usability and accessibility
- Success Metrics: User satisfaction, task completion rates, accessibility compliance, visual appeal
USER CONTEXT: {captured_user_requirements_from_session}
ANALYSIS REQUIREMENTS:
1. User Experience Analysis
- Identify current UX pain points and friction areas
- Map user journeys and identify optimization opportunities
- Analyze user behavior patterns and preferences
- Evaluate task completion flows and success rates
2. Interface Design Assessment
- Review current interface design and information architecture
- Identify visual hierarchy and navigation issues
- Assess consistency across different screens and states
- Evaluate mobile and desktop interface differences
3. Visual Design Strategy
- Develop visual design concepts aligned with brand guidelines
- Create color schemes, typography, and spacing systems
- Design iconography and visual elements
- Plan for dark mode and theme variations
4. Interaction Design Planning
- Design micro-interactions and animation strategies
- Plan feedback mechanisms and loading states
- Create error handling and validation UX
- Design responsive behavior and breakpoints
5. Accessibility and Inclusion
- Evaluate WCAG 2.1 compliance requirements
- Design for screen readers and assistive technologies
- Plan for color blindness and visual impairments
- Ensure keyboard navigation and focus management
6. Prototyping and Testing Strategy
- Plan for wireframes, mockups, and interactive prototypes
- Design user testing scenarios and success metrics
- Create A/B testing strategies for key interactions
- Plan for iterative design improvements
OUTPUT REQUIREMENTS: Save comprehensive analysis to:
.workflow/WFS-{topic-slug}/.brainstorming/ui-designer/
- analysis.md (main UI/UX analysis)
- design-system.md (visual design guidelines and components)
- user-flows.md (user journey maps and interaction flows)
- accessibility-plan.md (accessibility requirements and implementation)
Apply UI/UX design expertise to create user-centered, accessible, and visually appealing solutions."
### Framework-Based Analysis
```
.workflow/WFS-{session}/.brainstorming/ui-designer/
└── analysis.md # Structured analysis addressing topic-framework.md discussion points
```
## 📊 **Output Specification**
### Output Location
```
.workflow/WFS-{topic-slug}/.brainstorming/ui-designer/
├── analysis.md # Primary UI/UX analysis
├── design-system.md # Visual design guidelines and components
├── user-flows.md # User journey maps and interaction flows
└── accessibility-plan.md # Accessibility requirements and implementation
```
### Document Templates
#### analysis.md Structure
### Analysis Document Structure
```markdown
# UI Designer Analysis: {Topic}
*Generated: {timestamp}*
# UI Designer Analysis: [Topic from Framework]
## Executive Summary
[Key UX findings and design recommendations overview]
## Framework Reference
**Topic Framework**: @../topic-framework.md
**Role Focus**: UI/UX Design perspective
## Current UX Assessment
### User Pain Points
### Interface Issues
### Accessibility Gaps
### Performance Impact on UX
## Discussion Points Analysis
[Address each point from topic-framework.md with UI/UX expertise]
## User Experience Strategy
### Target User Personas
### User Journey Mapping
### Key Interaction Points
### Success Metrics
### Core Requirements (from framework)
[UI/UX perspective on requirements]
## Visual Design Approach
### Brand Alignment
### Color and Typography Strategy
### Layout and Spacing System
### Iconography and Visual Elements
### Technical Considerations (from framework)
[Interface and design system considerations]
## Interface Design Plan
### Information Architecture
### Navigation Strategy
### Component Library
### Responsive Design Approach
### User Experience Factors (from framework)
[Detailed UX analysis and recommendations]
## Accessibility Implementation
### WCAG Compliance Plan
### Assistive Technology Support
### Inclusive Design Features
### Testing Strategy
### Implementation Challenges (from framework)
[Design implementation and accessibility considerations]
## Prototyping and Validation
### Wireframe Strategy
### Interactive Prototype Plan
### User Testing Approach
### Iteration Framework
### Success Metrics (from framework)
[UX metrics and usability success criteria]
## UI/UX Specific Recommendations
[Role-specific design recommendations and solutions]
---
*Generated by ui-designer analysis addressing structured framework*
```
## 🔄 **Session Integration**
### Status Synchronization
Upon completion, update `workflow-session.json`:
### Completion Status Update
```json
{
"phases": {
"BRAINSTORM": {
"ui_designer": {
"status": "completed",
"completed_at": "timestamp",
"output_directory": ".workflow/WFS-{topic}/.brainstorming/ui-designer/",
"key_insights": ["ux_improvement", "accessibility_requirement", "design_pattern"]
}
}
"ui_designer": {
"status": "completed",
"framework_addressed": true,
"output_location": ".workflow/WFS-{session}/.brainstorming/ui-designer/analysis.md",
"framework_reference": "@../topic-framework.md"
}
}
```
### Cross-Role Collaboration
UI designer perspective provides:
- **User Interface Requirements** → System Architect
- **User Experience Metrics and Goals** → Product Manager
- **Data Visualization Requirements** → Data Architect
- **Secure Interaction Design Patterns** → Security Expert
- **Feature Interface Specifications** → Feature Planner
## ✅ **Quality Assurance**
### Required Design Elements
- [ ] Comprehensive user journey analysis with pain points identified
- [ ] Complete interface design solution with visual mockups
- [ ] Accessibility compliance plan meeting WCAG 2.1 standards
- [ ] Responsive design strategy for multiple devices and screen sizes
- [ ] Usability testing plan with clear success metrics
### Design Principles Validation
- [ ] **User-Centered**: All design decisions prioritize user needs and goals
- [ ] **Consistency**: Interface elements and interactions maintain visual and functional consistency
- [ ] **Accessibility**: Design meets WCAG guidelines and supports assistive technologies
- [ ] **Usability**: Operations are simple, intuitive, with minimal learning curve
- [ ] **Visual Appeal**: Design supports brand identity while creating positive user emotions
### UX Quality Metrics
- [ ] **Task Success**: High task completion rates with minimal errors
- [ ] **Efficiency**: Optimal task completion times with streamlined workflows
- [ ] **Satisfaction**: Positive user feedback and high satisfaction scores
- [ ] **Accessibility**: Full compliance with accessibility standards and inclusive design
- [ ] **Consistency**: Uniform experience across different devices and platforms
### Implementation Readiness
- [ ] **Design System**: Comprehensive component library and style guide
- [ ] **Prototyping**: Interactive prototypes demonstrating key user flows
- [ ] **Documentation**: Clear specifications for development implementation
- [ ] **Testing Plan**: Structured approach for usability and accessibility validation
- [ ] **Iteration Strategy**: Framework for continuous design improvement based on user feedback
### Integration Points
- **Framework Reference**: @../topic-framework.md for structured discussion points
- **Cross-Role Synthesis**: UI/UX insights available for synthesis-report.md integration
- **Agent Autonomy**: Independent execution with framework guidance

View File

@@ -1,267 +0,0 @@
---
name: user-researcher
description: User researcher perspective brainstorming for user behavior analysis and research insights
usage: /workflow:brainstorm:user-researcher <topic>
argument-hint: "topic or challenge to analyze from user research perspective"
examples:
- /workflow:brainstorm:user-researcher "user onboarding experience"
- /workflow:brainstorm:user-researcher "mobile app usability issues"
- /workflow:brainstorm:user-researcher "feature adoption analysis"
allowed-tools: Task(conceptual-planning-agent), TodoWrite(*)
---
## 🔍 **Role Overview: User Researcher**
### Role Definition
User experience research specialist responsible for understanding user behavior, identifying needs and pain points, and transforming research insights into actionable product improvements that enhance user satisfaction and engagement.
### Core Responsibilities
- **User Behavior Research**: Deep analysis of user behavior patterns and motivations
- **User Needs Discovery**: Research to discover unmet user needs and requirements
- **Usability Assessment**: Evaluate product usability and user experience issues
- **User Insights Generation**: Transform research findings into actionable product insights
### Focus Areas
- **User Behavior**: Usage patterns, decision paths, task completion methods
- **User Needs**: Explicit needs, implicit needs, emotional requirements
- **User Experience**: Pain points, satisfaction levels, emotional responses, expectations
- **Market Segmentation**: User personas, demographic segments, usage scenarios
### Success Metrics
- User satisfaction and engagement scores
- Task success rates and completion times
- Quality and actionability of research insights
- Impact of research on product decisions
## 🧠 **分析框架**
@~/.claude/workflows/brainstorming-principles.md
### Key Analysis Questions
**1. User Understanding and Insights**
- What are the real needs and pain points of target users?
- What are the user behavior patterns and usage scenarios?
- What are the differentiated needs of various user groups?
**2. User Experience Analysis**
- What are the main issues with the current user experience?
- What obstacles and friction points exist in user task completion?
- What gaps exist between user satisfaction and expectations?
**3. Research Methods and Validation**
- Which research methods are most suitable for the current problem?
- How can hypotheses and design decisions be validated?
- How can continuous user feedback be collected?
**4. Insights Translation and Application**
- How can research findings be translated into product improvements?
- How can product decisions and design be influenced?
- How can a user-centered culture be established?
## ⚡ **Two-Step Execution Flow**
### ⚠️ Session Management - FIRST STEP
Session detection and selection:
```bash
# Check for active sessions
active_sessions=$(find .workflow -name ".active-*" 2>/dev/null)
if [ multiple_sessions ]; then
prompt_user_to_select_session()
else
use_existing_or_create_new()
fi
```
### Step 1: Context Gathering Phase
**User Researcher Perspective Questioning**
Before agent assignment, gather comprehensive user researcher context:
#### 📋 Role-Specific Questions
**1. User Behavior Patterns and Insights**
- Who are the primary users and what are their key characteristics?
- What user behaviors, patterns, or pain points have you observed?
- Are there specific user segments or personas you're particularly interested in?
- What user feedback or data do you already have available?
**2. Research Focus and Pain Points**
- What specific user experience problems or questions need to be addressed?
- Are there particular user tasks, workflows, or touchpoints to focus on?
- What assumptions about users need to be validated or challenged?
- What gaps exist in your current understanding of user needs?
**3. Research Context and Constraints**
- What research has been done previously and what were the key findings?
- Are there specific research methods you prefer or want to avoid?
- What timeline and resources are available for user research?
- Who are the key stakeholders that need to understand user insights?
**4. User Testing Strategy and Goals**
- What specific user experience improvements are you hoping to achieve?
- How do you currently measure user satisfaction or success?
- Are there competitive products or experiences you want to benchmark against?
- What would successful user research outcomes look like for this project?
#### Context Validation
- **Minimum Response**: Each answer must be ≥50 characters
- **Re-prompting**: Insufficient detail triggers follow-up questions
- **Context Storage**: Save responses to `.brainstorming/user-researcher-context.md`
### Step 2: Agent Assignment with Flow Control
**Dedicated Agent Execution**
```bash
Task(conceptual-planning-agent): "
[FLOW_CONTROL]
Execute dedicated user researcher conceptual analysis for: {topic}
ASSIGNED_ROLE: user-researcher
OUTPUT_LOCATION: .brainstorming/user-researcher/
USER_CONTEXT: {validated_responses_from_context_gathering}
Flow Control Steps:
[
{
\"step\": \"load_role_template\",
\"action\": \"Load user-researcher planning template\",
\"command\": \"bash($(cat ~/.claude/workflows/cli-templates/planning-roles/user-researcher.md))\",
\"output_to\": \"role_template\"
}
]
Conceptual Analysis Requirements:
- Apply user researcher perspective to topic analysis
- Focus on user behavior patterns, pain points, research insights, and user testing strategy
- Use loaded role template framework for analysis structure
- Generate role-specific deliverables in designated output location
- Address all user context from questioning phase
Deliverables:
- analysis.md: Main user researcher analysis
- recommendations.md: User researcher recommendations
- deliverables/: User researcher-specific outputs as defined in role template
Embody user researcher role expertise for comprehensive conceptual planning."
```
### Progress Tracking
TodoWrite tracking for two-step process:
```json
[
{"content": "Gather user researcher context through role-specific questioning", "status": "in_progress", "activeForm": "Gathering context"},
{"content": "Validate context responses and save to user-researcher-context.md", "status": "pending", "activeForm": "Validating context"},
{"content": "Load user-researcher planning template via flow control", "status": "pending", "activeForm": "Loading template"},
{"content": "Execute dedicated conceptual-planning-agent for user-researcher role", "status": "pending", "activeForm": "Executing agent"}
]
```
## 📊 **输出结构**
### 保存位置
```
.workflow/WFS-{topic-slug}/.brainstorming/user-researcher/
├── analysis.md # 主要用户研究分析
├── user-personas.md # 详细用户画像和细分
├── research-plan.md # 方法论和研究方法
└── insights-recommendations.md # 关键发现和可执行建议
```
### 文档模板
#### analysis.md 结构
```markdown
# User Researcher Analysis: {Topic}
*Generated: {timestamp}*
## Executive Summary
[核心用户研究发现和建议概述]
## Current User Landscape
### User Base Overview
### Behavioral Patterns
### Usage Statistics and Trends
### Satisfaction Metrics
## User Needs Analysis
### Primary User Needs
### Unmet Needs and Gaps
### Need Prioritization Matrix
### Emotional and Functional Needs
## User Experience Assessment
### Current UX Strengths
### Major Pain Points and Friction
### Usability Issues Identified
### Accessibility Gaps
## User Behavior Insights
### User Journey Mapping
### Decision-Making Patterns
### Task Completion Analysis
### Behavioral Segments
## Research Recommendations
### Recommended Research Methods
### Key Research Questions
### Success Metrics and KPIs
### Research Timeline and Resources
## Actionable Insights
### Immediate UX Improvements
### Product Feature Recommendations
### Long-term User Strategy
### Success Measurement Plan
```
## 🔄 **会话集成**
### 状态同步
分析完成后,更新 `workflow-session.json`:
```json
{
"phases": {
"BRAINSTORM": {
"user_researcher": {
"status": "completed",
"completed_at": "timestamp",
"output_directory": ".workflow/WFS-{topic}/.brainstorming/user-researcher/",
"key_insights": ["user_behavior_pattern", "unmet_need", "usability_issue"]
}
}
}
}
```
### 与其他角色的协作
用户研究员视角为其他角色提供:
- **用户需求和洞察** → Product Manager
- **用户行为数据** → Data Architect
- **用户体验要求** → UI Designer
- **用户安全需求** → Security Expert
- **功能使用场景** → Feature Planner
## ✅ **质量标准**
### 必须包含的研究元素
- [ ] 详细的用户行为分析
- [ ] 明确的用户需求识别
- [ ] 全面的用户体验评估
- [ ] 科学的研究方法设计
- [ ] 可执行的改进建议
### 用户研究原则检查
- [ ] 以人为本:所有分析以用户为中心
- [ ] 基于证据:结论有数据和研究支撑
- [ ] 行为导向:关注实际行为而非声明意图
- [ ] 情境考虑:分析使用场景和环境因素
- [ ] 持续迭代:建立持续研究和改进机制
### 洞察质量评估
- [ ] 洞察的新颖性和深度
- [ ] 建议的可操作性和具体性
- [ ] 影响评估的准确性
- [ ] 研究方法的科学性
- [ ] 用户代表性的覆盖度

View File

@@ -0,0 +1,221 @@
---
name: ux-expert
description: Generate or update ux-expert/analysis.md addressing topic-framework discussion points
argument-hint: "optional topic - uses existing framework if available"
allowed-tools: Task(conceptual-planning-agent), TodoWrite(*), Read(*), Write(*)
---
## 🎯 **UX Expert Analysis Generator**
### Purpose
**Specialized command for generating ux-expert/analysis.md** that addresses topic-framework.md discussion points from user experience and interface design perspective. Creates or updates role-specific analysis with framework references.
### Core Function
- **Framework-based Analysis**: Address each discussion point in topic-framework.md
- **UX Design Focus**: User interface, interaction patterns, and usability optimization
- **Update Mechanism**: Create new or update existing analysis.md
- **Agent Delegation**: Use conceptual-planning-agent for analysis generation
### Analysis Scope
- **User Research**: User personas, behavioral analysis, and needs assessment
- **Information Architecture**: Content structure, navigation hierarchy, and mental models
- **User Journey Mapping**: User flows, task analysis, and interaction models
- **Usability Strategy**: Accessibility planning, cognitive load reduction, and user testing frameworks
- **Wireframing**: Low-fidelity layouts and structural prototypes (not visual design)
### Role Boundaries & Responsibilities
#### **What This Role OWNS (Abstract User Experience & Research)**
- **User Research & Personas**: Understanding target users, their goals, pain points, and behaviors
- **Information Architecture**: Organizing content and defining navigation structures at a conceptual level
- **User Journey Mapping**: Defining user flows, task sequences, and interaction models
- **Wireframes & Low-Fidelity Prototypes**: Structural layouts showing information hierarchy (boxes and arrows, not colors/fonts)
- **Usability Testing Strategy**: Planning user testing, A/B tests, and validation methods
- **Accessibility Planning**: WCAG compliance strategy and inclusive design principles
#### **What This Role DOES NOT Own (Defers to Other Roles)**
- **Visual Design**: Colors, typography, spacing, visual style → Defers to **UI Designer**
- **High-Fidelity Mockups**: Polished, pixel-perfect designs → Defers to **UI Designer**
- **Component Implementation**: Design system components, CSS, animations → Defers to **UI Designer**
#### **Handoff Points**
- **TO UI Designer**: Provides wireframes, user flows, and information architecture that UI Designer will transform into high-fidelity visual designs
- **FROM User Research**: May receive external research data to inform UX decisions
- **TO Product Owner**: Provides user insights and validation results to inform feature prioritization
## ⚙️ **Execution Protocol**
### Phase 1: Session & Framework Detection
```bash
# Check active session and framework
CHECK: .workflow/.active-* marker files
IF active_session EXISTS:
session_id = get_active_session()
brainstorm_dir = .workflow/WFS-{session}/.brainstorming/
CHECK: brainstorm_dir/topic-framework.md
IF EXISTS:
framework_mode = true
load_framework = true
ELSE:
IF topic_provided:
framework_mode = false # Create analysis without framework
ELSE:
ERROR: "No framework found and no topic provided"
```
### Phase 2: Analysis Mode Detection
```bash
# Determine execution mode
IF framework_mode == true:
mode = "framework_based_analysis"
topic_ref = load_framework_topic()
discussion_points = extract_framework_points()
ELSE:
mode = "standalone_analysis"
topic_ref = provided_topic
discussion_points = generate_basic_structure()
```
### Phase 3: Agent Execution with Flow Control
**Framework-Based Analysis Generation**
```bash
Task(conceptual-planning-agent): "
[FLOW_CONTROL]
Execute ux-expert analysis for existing topic framework
## Context Loading
ASSIGNED_ROLE: ux-expert
OUTPUT_LOCATION: .workflow/WFS-{session}/.brainstorming/ux-expert/
ANALYSIS_MODE: {framework_mode ? "framework_based" : "standalone"}
## Flow Control Steps
1. **load_topic_framework**
- Action: Load structured topic discussion framework
- Command: Read(.workflow/WFS-{session}/.brainstorming/topic-framework.md)
- Output: topic_framework_content
2. **load_role_template**
- Action: Load ux-expert planning template
- Command: bash($(cat ~/.claude/workflows/cli-templates/planning-roles/ux-expert.md))
- Output: role_template_guidelines
3. **load_session_metadata**
- Action: Load session metadata and existing context
- Command: Read(.workflow/WFS-{session}/workflow-session.json)
- Output: session_context
## Analysis Requirements
**Framework Reference**: Address all discussion points in topic-framework.md from user experience and interface design perspective
**Role Focus**: UI design, interaction patterns, usability optimization, design systems
**Structured Approach**: Create analysis.md addressing framework discussion points
**Template Integration**: Apply role template guidelines within framework structure
## Expected Deliverables
1. **analysis.md**: Comprehensive UX design analysis addressing all framework discussion points
2. **Framework Reference**: Include @../topic-framework.md reference in analysis
## Completion Criteria
- Address each discussion point from topic-framework.md with UX design expertise
- Provide actionable interface design and usability optimization strategies
- Include accessibility considerations and interaction pattern recommendations
- Reference framework document using @ notation for integration
"
```
## 📋 **TodoWrite Integration**
### Workflow Progress Tracking
```javascript
TodoWrite({
todos: [
{
content: "Detect active session and locate topic framework",
status: "in_progress",
activeForm: "Detecting session and framework"
},
{
content: "Load topic-framework.md and session metadata for context",
status: "pending",
activeForm: "Loading framework and session context"
},
{
content: "Execute ux-expert analysis using conceptual-planning-agent with FLOW_CONTROL",
status: "pending",
activeForm: "Executing ux-expert framework analysis"
},
{
content: "Generate analysis.md addressing all framework discussion points",
status: "pending",
activeForm: "Generating structured ux-expert analysis"
},
{
content: "Update workflow-session.json with ux-expert completion status",
status: "pending",
activeForm: "Updating session metadata"
}
]
});
```
## 📊 **Output Structure**
### Framework-Based Analysis
```
.workflow/WFS-{session}/.brainstorming/ux-expert/
└── analysis.md # Structured analysis addressing topic-framework.md discussion points
```
### Analysis Document Structure
```markdown
# UX Expert Analysis: [Topic from Framework]
## Framework Reference
**Topic Framework**: @../topic-framework.md
**Role Focus**: User Experience & Interface Design perspective
## Discussion Points Analysis
[Address each point from topic-framework.md with UX design expertise]
### Core Requirements (from framework)
[User interface and interaction design requirements perspective]
### Technical Considerations (from framework)
[Design system implementation and technical feasibility considerations]
### User Experience Factors (from framework)
[Usability optimization, accessibility, and user-centered design analysis]
### Implementation Challenges (from framework)
[Design implementation challenges and progressive enhancement strategies]
### Success Metrics (from framework)
[UX metrics including usability testing, user satisfaction, and design KPIs]
## UX Expert Specific Recommendations
[Role-specific interface design patterns and usability optimization strategies]
---
*Generated by ux-expert analysis addressing structured framework*
```
## 🔄 **Session Integration**
### Completion Status Update
```json
{
"ux_expert": {
"status": "completed",
"framework_addressed": true,
"output_location": ".workflow/WFS-{session}/.brainstorming/ux-expert/analysis.md",
"framework_reference": "@../topic-framework.md"
}
}
```
### Integration Points
- **Framework Reference**: @../topic-framework.md for structured discussion points
- **Cross-Role Synthesis**: UX design insights available for synthesis-report.md integration
- **Agent Autonomy**: Independent execution with framework guidance

View File

@@ -0,0 +1,353 @@
---
name: concept-clarify
description: Identify underspecified areas in brainstorming artifacts through targeted clarification questions before action planning
argument-hint: "[optional: --session session-id]"
allowed-tools: Read(*), Write(*), Edit(*), TodoWrite(*), Glob(*), Bash(*)
---
## User Input
```text
$ARGUMENTS
```
You **MUST** consider the user input before proceeding (if not empty).
## Outline
**Goal**: Detect and reduce ambiguity or missing decision points in planning artifacts before moving to task generation. Supports both brainstorm and plan workflows.
**Timing**:
- **Brainstorm mode**: Runs AFTER `/workflow:brainstorm:synthesis` and BEFORE `/workflow:plan`
- **Plan mode**: Runs AFTER Phase 3 (concept-enhanced) and BEFORE Phase 4 (task-generate) within `/workflow:plan`
This serves as a quality gate to ensure conceptual clarity before detailed task planning or generation.
**Execution steps**:
1. **Session Detection & Validation**
```bash
# Detect active workflow session
IF --session parameter provided:
session_id = provided session
ELSE:
CHECK: .workflow/.active-* marker files
IF active_session EXISTS:
session_id = get_active_session()
ELSE:
ERROR: "No active workflow session found. Use --session <session-id> or start a session."
EXIT
# Mode detection: plan vs brainstorm
brainstorm_dir = .workflow/WFS-{session}/.brainstorming/
process_dir = .workflow/WFS-{session}/.process/
IF EXISTS(process_dir/ANALYSIS_RESULTS.md):
clarify_mode = "plan"
primary_artifact = process_dir/ANALYSIS_RESULTS.md
INFO: "Plan mode: Analyzing ANALYSIS_RESULTS.md"
ELSE IF EXISTS(brainstorm_dir/synthesis-specification.md):
clarify_mode = "brainstorm"
primary_artifact = brainstorm_dir/synthesis-specification.md
INFO: "Brainstorm mode: Analyzing synthesis-specification.md"
ELSE:
ERROR: "No valid artifact found. Run /workflow:brainstorm:synthesis or /workflow:plan first"
EXIT
# Mode-specific validation
IF clarify_mode == "brainstorm":
CHECK: brainstorm_dir/topic-framework.md
IF NOT EXISTS:
WARN: "topic-framework.md not found. Verification will be limited."
```
2. **Load Artifacts (Mode-Aware)**
```bash
# Load primary artifact (determined in step 1)
primary_content = Read(primary_artifact)
# Load user's original intent from session metadata
session_metadata = Read(.workflow/WFS-{session}/workflow-session.json)
original_user_intent = session_metadata.project || session_metadata.description
IF NOT original_user_intent:
WARN: "No original user intent found in session metadata"
original_user_intent = "Not available"
# Load mode-specific supplementary artifacts
IF clarify_mode == "brainstorm":
topic_framework = Read(brainstorm_dir + "/topic-framework.md") # if exists
role_analyses = Glob(brainstorm_dir + "/*/analysis.md")
participating_roles = extract_role_names(role_analyses)
# Plan mode: primary_content (ANALYSIS_RESULTS.md) is self-contained
```
3. **Ambiguity & Coverage Scan**
Perform structured scan using this taxonomy. For each category, mark status: **Clear** / **Partial** / **Missing**.
**⚠️ User Intent Alignment** (NEW - HIGHEST PRIORITY):
- Primary artifact alignment with original user intent
- Goal consistency between artifact and user's stated objectives
- Scope match with user's requirements
- Success criteria reflects user's expectations
- Any unexplained deviations from user intent
**Requirements Clarity**:
- Functional requirements specificity and measurability
- Non-functional requirements with quantified targets
- Business requirements with success metrics
- Acceptance criteria completeness
**Architecture & Design Clarity**:
- Architecture decisions with rationale
- Data model completeness (entities, relationships, constraints)
- Technology stack justification
- Integration points and API contracts
**User Experience & Interface**:
- User journey completeness
- Critical interaction flows
- Error/edge case handling
- Accessibility and localization considerations
**Implementation Feasibility**:
- Team capability vs. required skills
- External dependencies and failure modes
- Resource constraints (timeline, personnel)
- Technical constraints and tradeoffs
**Risk & Mitigation**:
- Critical risks identified
- Mitigation strategies defined
- Success factors clarity
- Monitoring and quality gates
**Process & Collaboration**:
- Role responsibilities and handoffs
- Collaboration patterns defined
- Timeline and milestone clarity
- Dependency management strategy
**Decision Traceability**:
- Controversial points documented
- Alternatives considered and rejected
- Decision rationale clarity
- Consensus vs. dissent tracking
**Terminology & Consistency**:
- Canonical terms defined
- Consistent naming across artifacts
- No unresolved placeholders (TODO, TBD, ???)
For each category with **Partial** or **Missing** status, add to candidate question queue unless:
- Clarification would not materially change implementation strategy
- Information is better deferred to planning phase
4. **Generate Prioritized Question Queue**
Internally generate prioritized queue of candidate questions (maximum 5):
**Constraints**:
- Maximum 5 questions per session
- Each question must be answerable with:
* Multiple-choice (2-5 mutually exclusive options), OR
* Short answer (≤5 words)
- Only include questions whose answers materially impact:
* Architecture decisions
* Data modeling
* Task decomposition
* Risk mitigation
* Success criteria
- Ensure category coverage balance
- Favor clarifications that reduce downstream rework risk
**Prioritization Heuristic**:
```
priority_score = (impact_on_planning * 0.4) +
(uncertainty_level * 0.3) +
(risk_if_unresolved * 0.3)
```
If zero high-impact ambiguities found, proceed to **Step 8** (report success).
5. **Sequential Question Loop** (Interactive)
Present **EXACTLY ONE** question at a time:
**Multiple-choice format**:
```markdown
**Question {N}/5**: {Question text}
| Option | Description |
|--------|-------------|
| A | {Option A description} |
| B | {Option B description} |
| C | {Option C description} |
| D | {Option D description} |
| Short | Provide different answer (≤5 words) |
```
**Short-answer format**:
```markdown
**Question {N}/5**: {Question text}
Format: Short answer (≤5 words)
```
**Answer Validation**:
- Validate answer maps to option or fits ≤5 word constraint
- If ambiguous, ask quick disambiguation (doesn't count as new question)
- Once satisfactory, record in working memory and proceed to next question
**Stop Conditions**:
- All critical ambiguities resolved
- User signals completion ("done", "no more", "proceed")
- Reached 5 questions
**Never reveal future queued questions in advance**.
6. **Integration After Each Answer** (Incremental Update)
After each accepted answer:
```bash
# Ensure Clarifications section exists
IF primary_content NOT contains "## Clarifications":
Insert "## Clarifications" section after first heading
# Create session subsection
IF NOT contains "### Session YYYY-MM-DD":
Create "### Session {today's date}" under "## Clarifications"
# Append clarification entry
APPEND: "- Q: {question} → A: {answer}"
# Apply clarification to appropriate section
CASE category:
Functional Requirements → Update "## Requirements" or equivalent section
Architecture → Update "## Architecture" or "## Design" sections
User Experience → Update "## UI/UX" or "## User Experience" sections
Risk → Update "## Risks" or "## Risk Assessment" sections
Process → Update "## Process" or "## Implementation" sections
Data Model → Update "## Data Model" or "## Database" sections
Non-Functional → Update "## Non-Functional Requirements" or equivalent
# Remove obsolete/contradictory statements
IF clarification invalidates existing statement:
Replace statement instead of duplicating
# Save immediately to primary_artifact
Write(primary_artifact)
```
7. **Validation After Each Write**
- [ ] Clarifications section contains exactly one bullet per accepted answer
- [ ] Total asked questions ≤ 5
- [ ] Updated sections contain no lingering placeholders
- [ ] No contradictory earlier statements remain
- [ ] Markdown structure valid
- [ ] Terminology consistent across all updated sections
8. **Completion Report**
After questioning loop ends or early termination:
```markdown
## ✅ Concept Verification Complete
**Session**: WFS-{session-id}
**Mode**: {clarify_mode}
**Questions Asked**: {count}/5
**Artifacts Updated**: {primary_artifact filename}
**Sections Touched**: {list section names}
### Coverage Summary
| Category | Status | Notes |
|----------|--------|-------|
| Requirements Clarity | ✅ Resolved | Acceptance criteria quantified |
| Architecture & Design | ✅ Clear | No ambiguities found |
| Implementation Feasibility | ⚠️ Deferred | Team training plan to be defined in IMPL_PLAN |
| Risk & Mitigation | ✅ Resolved | Critical risks now have mitigation strategies |
| ... | ... | ... |
**Legend**:
- ✅ Resolved: Was Partial/Missing, now addressed
- ✅ Clear: Already sufficient
- ⚠️ Deferred: Low impact, better suited for planning phase
- ❌ Outstanding: Still Partial/Missing but question quota reached
### Recommendations
- ✅ **PROCEED to /workflow:plan**: Conceptual foundation is clear
- OR ⚠️ **Address Outstanding Items First**: {list critical outstanding items}
- OR 🔄 **Run /workflow:concept-clarify Again**: If new information available
### Next Steps
**If Outstanding Items Exist**:
1. TodoWrite tracking for outstanding issues
2. Call conceptual-planning-agent to fix conceptual gaps
3. Wait for user confirmation before proceeding
**If No Issues**:
```bash
/workflow:plan # Generate IMPL_PLAN.md and task.json
```
```
9. **Update Session Metadata**
```bash
# Update metadata based on mode
IF clarify_mode == "brainstorm":
phase_key = "BRAINSTORM"
ELSE: # plan mode
phase_key = "PLAN"
# Update session metadata
{
"phases": {
"{phase_key}": {
"status": "concept_verified",
"concept_verification": {
"completed": true,
"completed_at": "timestamp",
"mode": "{clarify_mode}",
"questions_asked": {count},
"categories_clarified": [{list}],
"outstanding_items": [],
"recommendation": "PROCEED" # or "ADDRESS_OUTSTANDING"
}
}
}
}
```
## Behavior Rules
- **If no meaningful ambiguities found**: Report "No critical ambiguities detected. Conceptual foundation is clear." and suggest proceeding to `/workflow:plan`.
- **If synthesis-specification.md missing**: Instruct user to run `/workflow:brainstorm:synthesis` first.
- **Never exceed 5 questions** (disambiguation retries don't count as new questions).
- **Respect user early termination**: Signals like "stop", "done", "proceed" should stop questioning.
- **If quota reached with high-impact items unresolved**: Explicitly flag them under "Outstanding" with recommendation to address before planning.
- **Avoid speculative tech stack questions** unless absence blocks conceptual clarity.
## Operating Principles
### Context Efficiency
- **Minimal high-signal tokens**: Focus on actionable clarifications
- **Progressive disclosure**: Load artifacts incrementally
- **Deterministic results**: Rerunning without changes produces consistent analysis
### Verification Guidelines
- **NEVER hallucinate missing sections**: Report them accurately
- **Prioritize high-impact ambiguities**: Focus on what affects planning
- **Use examples over exhaustive rules**: Cite specific instances
- **Report zero issues gracefully**: Emit success report with coverage statistics
- **Update incrementally**: Save after each answer to minimize context loss
## Context
{ARGS}

View File

@@ -1,407 +0,0 @@
---
name: concept-eval
description: Evaluate concept planning before implementation with intelligent tool analysis
usage: /workflow:concept-eval [--tool gemini|codex|both] <input>
argument-hint: [--tool gemini|codex|both] "concept description"|file.md|ISS-001
examples:
- /workflow:concept-eval "Build microservices architecture"
- /workflow:concept-eval --tool gemini requirements.md
- /workflow:concept-eval --tool both ISS-001
allowed-tools: Task(*), TodoWrite(*), Read(*), Write(*), Edit(*), Bash(*), Glob(*)
---
# Workflow Concept Evaluation Command
## Overview
Pre-planning evaluation command that assesses concept feasibility, identifies potential issues, and provides optimization recommendations before formal planning begins. **Works before `/workflow:plan`** to catch conceptual problems early and improve initial design quality.
## Core Responsibilities
- **Concept Analysis**: Evaluate design concepts for architectural soundness
- **Feasibility Assessment**: Technical and resource feasibility evaluation
- **Risk Identification**: Early identification of potential implementation risks
- **Optimization Suggestions**: Generate actionable improvement recommendations
- **Context Integration**: Leverage existing codebase patterns and documentation
- **Tool Selection**: Use gemini for strategic analysis, codex for technical assessment
## Usage
```bash
/workflow:concept-eval [--tool gemini|codex|both] <input>
```
## Parameters
- **--tool**: Specify evaluation tool (default: both)
- `gemini`: Strategic and architectural evaluation
- `codex`: Technical feasibility and implementation assessment
- `both`: Comprehensive dual-perspective analysis
- **input**: Concept description, file path, or issue reference
## Input Detection
- **Files**: `.md/.txt/.json/.yaml/.yml` → Reads content and extracts concept requirements
- **Issues**: `ISS-*`, `ISSUE-*`, `*-request-*` → Loads issue data and requirement specifications
- **Text**: Everything else → Parses natural language concept descriptions
## Core Workflow
### Evaluation Process
The command performs comprehensive concept evaluation through:
**0. Context Preparation** ⚠️ FIRST STEP
- **MCP Tools Integration**: Use Code Index for codebase exploration, Exa for external context
- **Documentation loading**: Automatic context gathering based on concept scope
- **Always check**: `CLAUDE.md`, `README.md` - Project context and conventions
- **For architecture concepts**: `.workflow/docs/architecture/`, existing system patterns
- **For specific modules**: `.workflow/docs/modules/[relevant-module]/` documentation
- **For API concepts**: `.workflow/docs/api/` specifications
- **Claude Code Memory Integration**: Access conversation history and previous work context
- **Session Memory**: Current session analysis and decisions
- **Project Memory**: Previous implementations and lessons learned
- **Pattern Memory**: Successful approaches and anti-patterns identified
- **Context Continuity**: Reference previous concept evaluations and outcomes
- **Context-driven selection**: Only load documentation relevant to the concept scope
- **Pattern analysis**: Identify existing implementation patterns and conventions
**1. Input Processing & Context Gathering**
- Parse input to extract concept requirements and scope
- Automatic tool assignment based on evaluation needs:
- **Strategic evaluation** (gemini): Architectural soundness, design patterns, business alignment
- **Technical assessment** (codex): Implementation complexity, technical feasibility, resource requirements
- **Comprehensive analysis** (both): Combined strategic and technical evaluation
- Load relevant project documentation and existing patterns
**2. Concept Analysis** ⚠️ CRITICAL EVALUATION PHASE
- **Conceptual integrity**: Evaluate design coherence and completeness
- **Architectural soundness**: Assess alignment with existing system architecture
- **Technical feasibility**: Analyze implementation complexity and resource requirements
- **Risk assessment**: Identify potential technical and business risks
- **Dependency analysis**: Map required dependencies and integration points
**3. Evaluation Execution**
Based on tool selection, execute appropriate analysis:
**Gemini Strategic Analysis**:
```bash
~/.claude/scripts/gemini-wrapper -p "
PURPOSE: Strategic evaluation of concept design and architecture
TASK: Analyze concept for architectural soundness, design patterns, and strategic alignment
CONTEXT: @{CLAUDE.md,README.md,.workflow/docs/**/*} Concept requirements and existing patterns | Previous conversation context and Claude Code session memory for continuity and pattern recognition
EXPECTED: Strategic assessment with architectural recommendations informed by session history
RULES: $(cat ~/.claude/workflows/cli-templates/prompts/planning/concept-eval.txt) | Focus on strategic soundness and design quality | Reference previous evaluations and lessons learned
"
```
**Codex Technical Assessment**:
```bash
codex --full-auto exec "
PURPOSE: Technical feasibility assessment of concept implementation
TASK: Evaluate implementation complexity, technical risks, and resource requirements
CONTEXT: @{CLAUDE.md,README.md,src/**/*} Concept requirements and existing codebase | Current session work context and previous technical decisions
EXPECTED: Technical assessment with implementation recommendations building on session memory
RULES: $(cat ~/.claude/workflows/cli-templates/prompts/planning/concept-eval.txt) | Focus on technical feasibility and implementation complexity | Consider previous technical approaches and outcomes
" -s danger-full-access
```
**Combined Analysis** (when --tool both):
Execute both analyses in parallel, then synthesize results for comprehensive evaluation.
**4. Optimization Recommendations**
- **Design improvements**: Architectural and design optimization suggestions
- **Risk mitigation**: Strategies to address identified risks
- **Implementation approach**: Recommended technical approaches and patterns
- **Resource optimization**: Efficient resource utilization strategies
- **Integration suggestions**: Optimal integration with existing systems
## Implementation Standards
### Evaluation Criteria ⚠️ CRITICAL
Concept evaluation focuses on these key dimensions:
**Strategic Evaluation (Gemini)**:
1. **Architectural Soundness**: Design coherence and system integration
2. **Business Alignment**: Concept alignment with business objectives
3. **Scalability Considerations**: Long-term growth and expansion potential
4. **Design Patterns**: Appropriate use of established design patterns
5. **Risk Assessment**: Strategic and business risk identification
**Technical Assessment (Codex)**:
1. **Implementation Complexity**: Technical difficulty and effort estimation
2. **Technical Feasibility**: Availability of required technologies and skills
3. **Resource Requirements**: Development time, infrastructure, and team resources
4. **Integration Challenges**: Technical integration complexity and risks
5. **Performance Implications**: System performance and scalability impact
### Evaluation Context Loading ⚠️ CRITICAL
Context preparation ensures comprehensive evaluation:
```json
// Context loading strategy for concept evaluation
"context_preparation": {
"required_docs": [
"CLAUDE.md",
"README.md"
],
"conditional_docs": {
"architecture_concepts": [
".workflow/docs/architecture/",
"docs/system-design.md"
],
"api_concepts": [
".workflow/docs/api/",
"api-documentation.md"
],
"module_concepts": [
".workflow/docs/modules/[relevant-module]/",
"src/[module]/**/*.md"
]
},
"pattern_analysis": {
"existing_implementations": "src/**/*",
"configuration_patterns": "config/",
"test_patterns": "test/**/*"
},
"claude_code_memory": {
"session_context": "Current session conversation history and decisions",
"project_memory": "Previous implementations and lessons learned across sessions",
"pattern_memory": "Successful approaches and anti-patterns identified",
"evaluation_history": "Previous concept evaluations and their outcomes",
"technical_decisions": "Past technical choices and their rationale",
"architectural_evolution": "System architecture changes and migration patterns"
}
}
```
### Analysis Output Structure
**Evaluation Categories**:
```markdown
## Concept Evaluation Summary
### ✅ Strengths Identified
- [ ] **Design Quality**: Well-defined architectural approach
- [ ] **Technical Approach**: Appropriate technology selection
- [ ] **Integration**: Good fit with existing systems
### ⚠️ Areas for Improvement
- [ ] **Complexity**: Reduce implementation complexity in module X
- [ ] **Dependencies**: Simplify dependency management approach
- [ ] **Scalability**: Address potential performance bottlenecks
### ❌ Critical Issues
- [ ] **Architecture**: Conflicts with existing system design
- [ ] **Resources**: Insufficient resources for proposed timeline
- [ ] **Risk**: High technical risk in component Y
### 🎯 Optimization Recommendations
- [ ] **Alternative Approach**: Consider microservices instead of monolithic design
- [ ] **Technology Stack**: Use existing React patterns instead of Vue
- [ ] **Implementation Strategy**: Phase implementation to reduce risk
```
## Document Generation & Output
**Evaluation Workflow**: Input Processing → Context Loading → Analysis Execution → Report Generation → Recommendations
**Always Created**:
- **CONCEPT_EVALUATION.md**: Complete evaluation results and recommendations
- **evaluation-session.json**: Evaluation metadata and tool configuration
- **OPTIMIZATION_SUGGESTIONS.md**: Actionable improvement recommendations
**Auto-Created (for comprehensive analysis)**:
- **strategic-analysis.md**: Gemini strategic evaluation results
- **technical-assessment.md**: Codex technical feasibility analysis
- **risk-assessment-matrix.md**: Comprehensive risk evaluation
- **implementation-roadmap.md**: Recommended implementation approach
**Document Structure**:
```
.workflow/WFS-[topic]/.evaluation/
├── evaluation-session.json # Evaluation session metadata
├── CONCEPT_EVALUATION.md # Complete evaluation results
├── OPTIMIZATION_SUGGESTIONS.md # Actionable recommendations
├── strategic-analysis.md # Gemini strategic evaluation
├── technical-assessment.md # Codex technical assessment
├── risk-assessment-matrix.md # Risk evaluation matrix
└── implementation-roadmap.md # Recommended approach
```
### Evaluation Implementation
**Session-Aware Evaluation**:
```bash
# Check for existing sessions and context
active_sessions=$(find .workflow/ -name ".active-*" 2>/dev/null)
if [ -n "$active_sessions" ]; then
echo "Found active sessions: $active_sessions"
echo "Concept evaluation will consider existing session context"
fi
# Create evaluation session directory
evaluation_session="CE-$(date +%Y%m%d_%H%M%S)"
mkdir -p ".workflow/.evaluation/$evaluation_session"
# Store evaluation metadata
cat > ".workflow/.evaluation/$evaluation_session/evaluation-session.json" << EOF
{
"session_id": "$evaluation_session",
"timestamp": "$(date -Iseconds)",
"concept_input": "$input_description",
"tool_selection": "$tool_choice",
"context_loaded": [
"CLAUDE.md",
"README.md"
],
"evaluation_scope": "$evaluation_scope"
}
EOF
```
**Tool Execution Pattern**:
```bash
# Execute based on tool selection
case "$tool_choice" in
"gemini")
echo "Performing strategic concept evaluation with Gemini..."
~/.claude/scripts/gemini-wrapper -p "$gemini_prompt" > ".workflow/.evaluation/$evaluation_session/strategic-analysis.md"
;;
"codex")
echo "Performing technical assessment with Codex..."
codex --full-auto exec "$codex_prompt" -s danger-full-access > ".workflow/.evaluation/$evaluation_session/technical-assessment.md"
;;
"both"|*)
echo "Performing comprehensive evaluation with both tools..."
~/.claude/scripts/gemini-wrapper -p "$gemini_prompt" > ".workflow/.evaluation/$evaluation_session/strategic-analysis.md" &
codex --full-auto exec "$codex_prompt" -s danger-full-access > ".workflow/.evaluation/$evaluation_session/technical-assessment.md" &
wait # Wait for both analyses to complete
# Synthesize results
~/.claude/scripts/gemini-wrapper -p "
PURPOSE: Synthesize strategic and technical concept evaluations
TASK: Combine analyses and generate integrated recommendations
CONTEXT: @{.workflow/.evaluation/$evaluation_session/strategic-analysis.md,.workflow/.evaluation/$evaluation_session/technical-assessment.md}
EXPECTED: Integrated evaluation with prioritized recommendations
RULES: Focus on actionable insights and clear next steps
" > ".workflow/.evaluation/$evaluation_session/CONCEPT_EVALUATION.md"
;;
esac
```
## Integration with Workflow Commands
### Workflow Position
**Pre-Planning Phase**: Use before formal planning to optimize concept quality
```
concept-eval → plan → plan-verify → execute
```
### Usage Scenarios
**Early Concept Validation**:
```bash
# Validate initial concept before detailed planning
/workflow:concept-eval "Build real-time notification system using WebSockets"
```
**Architecture Review**:
```bash
# Strategic architecture evaluation
/workflow:concept-eval --tool gemini architecture-proposal.md
```
**Technical Feasibility Check**:
```bash
# Technical implementation assessment
/workflow:concept-eval --tool codex "Implement ML-based recommendation engine"
```
**Comprehensive Analysis**:
```bash
# Full strategic and technical evaluation
/workflow:concept-eval --tool both ISS-042
```
### Integration Benefits
- **Early Risk Detection**: Identify issues before detailed planning
- **Quality Improvement**: Optimize concepts before implementation planning
- **Resource Efficiency**: Avoid detailed planning of infeasible concepts
- **Decision Support**: Data-driven concept selection and refinement
- **Team Alignment**: Clear evaluation criteria and recommendations
## Error Handling & Edge Cases
### Input Validation
```bash
# Validate input format and accessibility
if [[ -z "$input" ]]; then
echo "Error: Concept input required"
echo "Usage: /workflow:concept-eval [--tool gemini|codex|both] <input>"
exit 1
fi
# Check file accessibility for file inputs
if [[ "$input" =~ \.(md|txt|json|yaml|yml)$ ]] && [[ ! -f "$input" ]]; then
echo "Error: File not found: $input"
echo "Please provide a valid file path or concept description"
exit 1
fi
```
### Tool Availability
```bash
# Check tool availability
if [[ "$tool_choice" == "gemini" ]] || [[ "$tool_choice" == "both" ]]; then
if ! command -v ~/.claude/scripts/gemini-wrapper &> /dev/null; then
echo "Warning: Gemini wrapper not available, using codex only"
tool_choice="codex"
fi
fi
if [[ "$tool_choice" == "codex" ]] || [[ "$tool_choice" == "both" ]]; then
if ! command -v codex &> /dev/null; then
echo "Warning: Codex not available, using gemini only"
tool_choice="gemini"
fi
fi
```
### Recovery Strategies
```bash
# Fallback to manual evaluation if tools fail
if [[ "$evaluation_failed" == "true" ]]; then
echo "Automated evaluation failed, generating manual evaluation template..."
cat > ".workflow/.evaluation/$evaluation_session/manual-evaluation-template.md" << EOF
# Manual Concept Evaluation
## Concept Description
$input_description
## Evaluation Checklist
- [ ] **Architectural Soundness**: Does the concept align with existing architecture?
- [ ] **Technical Feasibility**: Are required technologies available and mature?
- [ ] **Resource Requirements**: Are time and team resources realistic?
- [ ] **Integration Complexity**: How complex is integration with existing systems?
- [ ] **Risk Assessment**: What are the main technical and business risks?
## Recommendations
[Provide manual evaluation and recommendations]
EOF
fi
```
## Quality Standards
### Evaluation Excellence
- **Comprehensive Analysis**: Consider all aspects of concept feasibility
- **Context-Rich Assessment**: Leverage full project context and existing patterns
- **Actionable Recommendations**: Provide specific, implementable suggestions
- **Risk-Aware Evaluation**: Identify and assess potential implementation risks
### User Experience Excellence
- **Clear Results**: Present evaluation results in actionable format
- **Focused Recommendations**: Prioritize most critical optimization suggestions
- **Integration Guidance**: Provide clear next steps for concept refinement
- **Tool Transparency**: Clear indication of which tools were used and why
### Output Quality
- **Structured Reports**: Consistent, well-organized evaluation documentation
- **Evidence-Based**: All recommendations backed by analysis and reasoning
- **Prioritized Actions**: Clear indication of critical vs. optional improvements
- **Implementation Ready**: Evaluation results directly usable for planning phase

View File

@@ -1,256 +0,0 @@
---
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"
examples:
- /workflow:docs all
- /workflow:docs architecture src/modules
- /workflow:docs api --scope api/
---
# Workflow Documentation Command
## Usage
```bash
/workflow:docs <type> [scope]
```
## Input Detection
- **Document Types**: `architecture`, `api`, `all` → Creates appropriate documentation tasks
- **Scope**: Optional module/directory filtering → Focuses documentation generation
- **Default**: `all` → Complete documentation suite
## Core Workflow
### Planning & Task Creation Process
The command performs structured planning and task creation:
**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
**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
**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
### 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
## Output 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
│ ├── system-design.md
│ ├── module-map.md
│ ├── data-flow.md
│ └── tech-stack.md
└── api/ # Level 2: Unified API docs
├── unified-api.md
└── openapi.yaml
```
## Task Decomposition Standards
### 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
```
### Task Flow Control Templates
**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"]
}
```
**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"]
}
```
## 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
## 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
## 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
### 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
## Usage Examples
### 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.

View File

@@ -1,10 +1,7 @@
---
name: execute
description: Coordinate agents for existing workflow tasks with automatic discovery
usage: /workflow:execute
argument-hint: none
examples:
- /workflow:execute
argument-hint: "[--resume-session=\"session-id\"]"
---
# Workflow Execute Command
@@ -12,9 +9,12 @@ examples:
## Overview
Orchestrates autonomous workflow execution through systematic task discovery, agent coordination, and progress tracking. **Executes entire workflow without user interruption**, providing complete context to agents and ensuring proper flow control execution with comprehensive TodoWrite tracking.
**Resume Mode**: When called with `--resume-session` flag, skips discovery phase and directly enters TodoWrite generation and agent execution for the specified session.
## Core Rules
**Complete entire workflow autonomously without user interruption, using TodoWrite for comprehensive progress tracking.**
**Execute all discovered pending tasks sequentially until workflow completion or blocking dependency.**
**Auto-complete session when all tasks finished: Call `/workflow:session:complete` upon workflow completion.**
## Core Responsibilities
- **Session Discovery**: Identify and select active workflow sessions
@@ -24,6 +24,7 @@ Orchestrates autonomous workflow execution through systematic task discovery, ag
- **Flow Control Execution**: Execute pre-analysis steps and context accumulation
- **Status Synchronization**: Update task JSON files and workflow state
- **Autonomous Completion**: Continue execution until all tasks complete or reach blocking state
- **Session Auto-Complete**: Call `/workflow:session:complete` when all workflow tasks finished
## Execution Philosophy
- **Discovery-first**: Auto-discover existing plans and tasks
@@ -34,47 +35,61 @@ Orchestrates autonomous workflow execution through systematic task discovery, ag
- **Autonomous completion**: **Execute all tasks without user interruption until workflow complete**
## Flow Control Execution
**[FLOW_CONTROL]** marker indicates sequential step execution required for context gathering and preparation. **These steps are executed BY THE AGENT, not by the workflow:execute command.**
**[FLOW_CONTROL]** marker indicates task JSON contains `flow_control.pre_analysis` steps for context preparation.
### Flow Control Rules
1. **Auto-trigger**: When `task.flow_control.pre_analysis` array exists in task JSON, agents execute these steps
2. **Sequential Processing**: Agents execute steps in order, accumulating context
3. **Variable Passing**: Agents use `[variable_name]` syntax to reference step outputs
4. **Error Handling**: Agents follow step-specific error strategies (`fail`, `skip_optional`, `retry_once`)
### Orchestrator Responsibility
- Pass complete task JSON to agent (including `flow_control` block)
- Provide session paths for artifact access
- Monitor agent completion
### Execution Pattern
```
Step 1: load_dependencies → dependency_context
Step 2: analyze_patterns [dependency_context] → pattern_analysis
Step 3: implement_solution [pattern_analysis] [dependency_context] → implementation
```
### Agent Responsibility
- Parse `flow_control.pre_analysis` array from JSON
- Execute steps sequentially with variable substitution
- Accumulate context from artifacts and dependencies
- Follow error handling per `step.on_error`
- Complete implementation using accumulated context
### Context Accumulation Process (Executed by Agents)
- **Load Dependencies**: Agents retrieve summaries from `context.depends_on` tasks
- **Execute Analysis**: Agents run CLI tools with accumulated context
- **Prepare Implementation**: Agents build comprehensive context for implementation
- **Continue Implementation**: Agents use all accumulated context for task execution
**Orchestrator does NOT execute flow control steps - Agent interprets and executes them from JSON.**
## Execution Lifecycle
### Phase 1: Discovery
### Resume Mode Detection
**Special Flag Processing**: When `--resume-session="session-id"` is provided:
1. **Skip Discovery Phase**: Use provided session ID directly
2. **Load Specified Session**: Read session state from `.workflow/{session-id}/`
3. **Direct TodoWrite Generation**: Skip to Phase 3 (Planning) immediately
4. **Accelerated Execution**: Enter agent coordination without validation delays
### Phase 1: Discovery (Normal Mode Only)
1. **Check Active Sessions**: Find `.workflow/.active-*` markers
2. **Select Session**: If multiple found, prompt user selection
3. **Load Session State**: Read `workflow-session.json` and `IMPL_PLAN.md`
4. **Scan Tasks**: Analyze `.task/*.json` files for ready tasks
### Phase 2: Analysis
**Note**: In resume mode, this phase is completely skipped.
### Phase 2: Analysis (Normal Mode Only)
1. **Dependency Resolution**: Build execution order based on `depends_on`
2. **Status Validation**: Filter tasks with `status: "pending"` and met dependencies
3. **Agent Assignment**: Determine agent type from `meta.agent` or `meta.type`
4. **Context Preparation**: Load dependency summaries and inherited context
### Phase 3: Planning
1. **Create TodoWrite List**: Generate task list with status markers
2. **Mark Initial Status**: Set first task as `in_progress`
3. **Prepare Session Context**: Inject workflow paths for agent use
**Note**: In resume mode, this phase is also skipped as session analysis was already completed by `/workflow:status`.
### Phase 3: Planning (Resume Mode Entry Point)
**This is where resume mode directly enters after skipping Phases 1 & 2**
1. **Create TodoWrite List**: Generate task list with status markers from session state
2. **Mark Initial Status**: Set first pending task as `in_progress`
3. **Prepare Session Context**: Inject workflow paths for agent use (using provided session-id)
4. **Prepare Complete Task JSON**: Include pre_analysis and flow control steps for agent consumption
5. **Validate Prerequisites**: Ensure all required context is available
5. **Validate Prerequisites**: Ensure all required context is available from existing session
**Resume Mode Behavior**:
- Load existing session state directly from `.workflow/{session-id}/`
- Use session's task files and summaries without discovery
- Generate TodoWrite from current session progress
- Proceed immediately to agent execution
### Phase 4: Execution
1. **Pass Task with Flow Control**: Include complete task JSON with `pre_analysis` steps for agent execution
@@ -88,10 +103,12 @@ Step 3: implement_solution [pattern_analysis] [dependency_context] → implement
2. **Generate Summary**: Create task summary in `.summaries/`
3. **Update TodoWrite**: Mark current task complete, advance to next
4. **Synchronize State**: Update session state and workflow status
5. **Check Workflow Complete**: Verify all tasks are completed
6. **Auto-Complete Session**: Call `/workflow:session:complete` when all tasks finished
## Task Discovery & Queue Building
### Session Discovery Process
### Session Discovery Process (Normal Mode)
```
├── Check for .active-* markers in .workflow/
├── If multiple active sessions found → Prompt user to select
@@ -102,6 +119,16 @@ Step 3: implement_solution [pattern_analysis] [dependency_context] → implement
└── Build execution queue of ready tasks from selected session
```
### Resume Mode Process (--resume-session flag)
```
├── Use provided session-id directly (skip discovery)
├── Validate .workflow/{session-id}/ directory exists
├── Load session's workflow-session.json and IMPL_PLAN.md directly
├── Scan session's .task/ directory for task JSON files
├── Use existing task statuses and dependencies (no re-analysis needed)
└── Build execution queue from session state (prioritize pending/in-progress tasks)
```
### Task Status Logic
```
pending + dependencies_met → executable
@@ -109,50 +136,194 @@ completed → skip
blocked → skip until dependencies clear
```
## Batch Execution with Dependency Graph
### Parallel Execution Algorithm
**Core principle**: Execute independent tasks concurrently in batches based on dependency graph.
#### Algorithm Steps
```javascript
function executeBatchWorkflow(sessionId) {
// 1. Build dependency graph from task JSONs
const graph = buildDependencyGraph(`.workflow/${sessionId}/.task/*.json`);
// 2. Process batches until graph is empty
while (!graph.isEmpty()) {
// 3. Identify current batch (tasks with in-degree = 0)
const batch = graph.getNodesWithInDegreeZero();
// 4. Check for parallel execution opportunities
const parallelGroups = groupByExecutionGroup(batch);
// 5. Execute batch concurrently
await Promise.all(
parallelGroups.map(group => executeBatch(group))
);
// 6. Update graph: remove completed tasks and their edges
graph.removeNodes(batch);
// 7. Update TodoWrite to reflect completed batch
updateTodoWriteAfterBatch(batch);
}
// 8. All tasks complete - auto-complete session
SlashCommand("/workflow:session:complete");
}
function buildDependencyGraph(taskFiles) {
const tasks = loadAllTaskJSONs(taskFiles);
const graph = new DirectedGraph();
tasks.forEach(task => {
graph.addNode(task.id, task);
// Add edges for dependencies
task.context.depends_on?.forEach(depId => {
graph.addEdge(depId, task.id); // Edge from dependency to task
});
});
return graph;
}
function groupByExecutionGroup(tasks) {
const groups = {};
tasks.forEach(task => {
const groupId = task.meta.execution_group || task.id;
if (!groups[groupId]) groups[groupId] = [];
groups[groupId].push(task);
});
return Object.values(groups);
}
async function executeBatch(tasks) {
// Execute all tasks in batch concurrently
return Promise.all(
tasks.map(task => executeTask(task))
);
}
```
#### Execution Group Rules
1. **Same `execution_group` ID** → Execute in parallel (independent, different contexts)
2. **No `execution_group` (null)** → Execute sequentially (has dependencies)
3. **Different `execution_group` IDs** → Execute in parallel (independent batches)
4. **Same `context_signature`** → Should have been merged (warning if not)
#### Parallel Execution Example
```
Batch 1 (no dependencies):
- IMPL-1.1 (execution_group: "parallel-auth-api") → Agent 1
- IMPL-1.2 (execution_group: "parallel-ui-comp") → Agent 2
- IMPL-1.3 (execution_group: "parallel-db-schema") → Agent 3
Wait for Batch 1 completion...
Batch 2 (depends on Batch 1):
- IMPL-2.1 (execution_group: null, depends_on: [IMPL-1.1, IMPL-1.2]) → Agent 1
Wait for Batch 2 completion...
Batch 3 (independent of Batch 2):
- IMPL-3.1 (execution_group: "parallel-tests-1") → Agent 1
- IMPL-3.2 (execution_group: "parallel-tests-2") → Agent 2
```
## TodoWrite Coordination
**Comprehensive workflow tracking** with immediate status updates throughout entire execution without user interruption:
#### TodoWrite Workflow Rules
1. **Initial Creation**: Generate TodoWrite from discovered pending tasks for entire workflow
2. **Single In-Progress**: Mark ONLY ONE task as `in_progress` at a time
3. **Immediate Updates**: Update status after each task completion without user interruption
- **Normal Mode**: Create from discovery results
- **Resume Mode**: Create from existing session state and current progress
2. **Parallel Task Support**:
- **Single-task execution**: Mark ONLY ONE task as `in_progress` at a time
- **Batch execution**: Mark ALL tasks in current batch as `in_progress` simultaneously
- **Execution group indicator**: Show `[execution_group: group-id]` for parallel tasks
3. **Immediate Updates**: Update status after each task/batch completion without user interruption
4. **Status Synchronization**: Sync with JSON task files after updates
5. **Continuous Tracking**: Maintain TodoWrite throughout entire workflow execution until completion
#### Resume Mode TodoWrite Generation
**Special behavior when `--resume-session` flag is present**:
- Load existing session progress from `.workflow/{session-id}/TODO_LIST.md`
- Identify currently in-progress or next pending task
- Generate TodoWrite starting from interruption point
- Preserve completed task history in TodoWrite display
- Focus on remaining pending tasks for execution
#### TodoWrite Tool Usage
**Use Claude Code's built-in TodoWrite tool** to track workflow progress in real-time:
```javascript
// Create initial todo list from discovered pending tasks
// Example 1: Sequential execution (traditional)
TodoWrite({
todos: [
{
content: "Execute IMPL-1.1: Design auth schema [code-developer] [FLOW_CONTROL]",
status: "pending",
status: "in_progress", // Single task in progress
activeForm: "Executing IMPL-1.1: Design auth schema"
},
{
content: "Execute IMPL-1.2: Implement auth logic [code-developer] [FLOW_CONTROL]",
status: "pending",
activeForm: "Executing IMPL-1.2: Implement auth logic"
},
{
content: "Execute IMPL-2: Review implementations [code-review-agent]",
status: "pending",
activeForm: "Executing IMPL-2: Review implementations"
}
]
});
// Update status as tasks progress - ONLY ONE task should be in_progress at a time
// Example 2: Batch execution (parallel tasks with execution_group)
TodoWrite({
todos: [
{
content: "Execute IMPL-1.1: Design auth schema [code-developer] [FLOW_CONTROL]",
status: "in_progress", // Mark current task as in_progress
activeForm: "Executing IMPL-1.1: Design auth schema"
content: "Execute IMPL-1.1: Build Auth API [code-developer] [execution_group: parallel-auth-api]",
status: "in_progress", // Batch task 1
activeForm: "Executing IMPL-1.1: Build Auth API"
},
// ... other tasks remain pending
{
content: "Execute IMPL-1.2: Build User UI [code-developer] [execution_group: parallel-ui-comp]",
status: "in_progress", // Batch task 2 (running concurrently)
activeForm: "Executing IMPL-1.2: Build User UI"
},
{
content: "Execute IMPL-1.3: Setup Database [code-developer] [execution_group: parallel-db-schema]",
status: "in_progress", // Batch task 3 (running concurrently)
activeForm: "Executing IMPL-1.3: Setup Database"
},
{
content: "Execute IMPL-2.1: Integration Tests [test-fix-agent] [depends_on: IMPL-1.1, IMPL-1.2, IMPL-1.3]",
status: "pending", // Next batch (waits for current batch completion)
activeForm: "Executing IMPL-2.1: Integration Tests"
}
]
});
// Example 3: After batch completion
TodoWrite({
todos: [
{
content: "Execute IMPL-1.1: Build Auth API [code-developer] [execution_group: parallel-auth-api]",
status: "completed", // Batch completed
activeForm: "Executing IMPL-1.1: Build Auth API"
},
{
content: "Execute IMPL-1.2: Build User UI [code-developer] [execution_group: parallel-ui-comp]",
status: "completed", // Batch completed
activeForm: "Executing IMPL-1.2: Build User UI"
},
{
content: "Execute IMPL-1.3: Setup Database [code-developer] [execution_group: parallel-db-schema]",
status: "completed", // Batch completed
activeForm: "Executing IMPL-1.3: Setup Database"
},
{
content: "Execute IMPL-2.1: Integration Tests [test-fix-agent]",
status: "in_progress", // Next batch started
activeForm: "Executing IMPL-2.1: Integration Tests"
}
]
});
```
@@ -164,41 +335,57 @@ TodoWrite({
- **Immediate Completion**: Mark tasks `completed` immediately after finishing
- **Status Sync**: Sync TodoWrite status with JSON task files after each update
- **Full Execution**: Continue TodoWrite tracking until all workflow tasks complete
- **Workflow Completion Check**: When all tasks marked `completed`, auto-call `/workflow:session:complete`
#### TODO_LIST.md Update Timing
- **Before Agent Launch**: Update TODO_LIST.md to mark task as `in_progress` (⚠️)
- **After Task Complete**: Update TODO_LIST.md to mark as `completed` (✅), advance to next
- **On Error**: Keep as `in_progress` in TODO_LIST.md, add error note
- **Workflow Complete**: When all tasks completed, call `/workflow:session:complete`
- **Session End**: Sync all TODO_LIST.md statuses with JSON task files
### 3. Agent Context Management
**Comprehensive context preparation** for autonomous agent execution:
#### Context Sources (Priority Order)
1. **Complete Task JSON**: Full task definition including all fields
2. **Flow Control Context**: Accumulated outputs from pre_analysis steps
3. **Dependency Summaries**: Previous task completion summaries
4. **Session Context**: Workflow paths and session metadata
5. **Inherited Context**: Parent task context and shared variables
1. **Complete Task JSON**: Full task definition including all fields and artifacts
2. **Artifacts Context**: Brainstorming outputs and synthesis specifications from task.context.artifacts
3. **Flow Control Context**: Accumulated outputs from pre_analysis steps (including artifact loading)
4. **Dependency Summaries**: Previous task completion summaries
5. **Session Context**: Workflow paths and session metadata
6. **Inherited Context**: Parent task context and shared variables
#### Context Assembly Process
```
1. Load Task JSON → Base context
2. Execute Flow Control → Accumulated context
3. Load Dependencies → Dependency context
4. Prepare Session Paths → Session context
5. Combine All → Complete agent context
1. Load Task JSON → Base context (including artifacts array)
2. Load Artifacts → Synthesis specifications and brainstorming outputs
3. Execute Flow Control → Accumulated context (with artifact loading steps)
4. Load Dependencies → Dependency context
5. Prepare Session Paths → Session context
6. Combine All → Complete agent context with artifact integration
```
#### Agent Context Package Structure
```json
{
"task": { /* Complete task JSON */ },
"task": { /* Complete task JSON with artifacts array */ },
"artifacts": {
"synthesis_specification": { "path": ".workflow/WFS-session/.brainstorming/synthesis-specification.md", "priority": "highest" },
"topic_framework": { "path": ".workflow/WFS-session/.brainstorming/topic-framework.md", "priority": "medium" },
"role_analyses": [ /* Individual role analysis files */ ],
"available_artifacts": [ /* All detected brainstorming artifacts */ ]
},
"flow_context": {
"step_outputs": { "pattern_analysis": "...", "dependency_context": "..." }
"step_outputs": {
"synthesis_specification": "...",
"individual_artifacts": "...",
"pattern_analysis": "...",
"dependency_context": "..."
}
},
"session": {
"workflow_dir": ".workflow/WFS-session/",
"brainstorming_dir": ".workflow/WFS-session/.brainstorming/",
"todo_list_path": ".workflow/WFS-session/TODO_LIST.md",
"summaries_dir": ".workflow/WFS-session/.summaries/",
"task_json_path": ".workflow/WFS-session/.task/IMPL-1.1.json"
@@ -209,10 +396,11 @@ TodoWrite({
```
#### Context Validation Rules
- **Task JSON Complete**: All 5 fields present and valid
- **Flow Control Ready**: All pre_analysis steps completed if present
- **Task JSON Complete**: All 5 fields present and valid, including artifacts array in context
- **Artifacts Available**: Synthesis specifications and brainstorming outputs accessible
- **Flow Control Ready**: All pre_analysis steps completed including artifact loading steps
- **Dependencies Loaded**: All depends_on summaries available
- **Session Paths Valid**: All workflow paths exist and accessible
- **Session Paths Valid**: All workflow paths exist and accessible, including .brainstorming directory
- **Agent Assignment**: Valid agent type specified in meta.agent
### 4. Agent Execution Pattern
@@ -220,61 +408,151 @@ TodoWrite({
#### Agent Prompt Template
```bash
Task(subagent_type="{agent_type}",
prompt="Execute {task_id}: {task_title}
Task(subagent_type="{meta.agent}",
prompt="**EXECUTE TASK FROM JSON**
## Task Definition
**ID**: {task_id}
**Type**: {task_type}
**Agent**: {assigned_agent}
## Task JSON Location
{session.task_json_path}
## Execution Instructions
{flow_control_marker}
## Instructions
1. **Load Complete Task JSON**: Read and validate all fields (id, title, status, meta, context, flow_control)
2. **Execute Flow Control**: If `flow_control.pre_analysis` exists, execute steps sequentially:
- Load artifacts (synthesis-specification.md, role analyses) using commands in each step
- Accumulate context from step outputs using variable substitution [variable_name]
- Handle errors per step.on_error (skip_optional | fail | retry_once)
3. **Implement Solution**: Follow `flow_control.implementation_approach` using accumulated context
4. **Complete Task**:
- Update task status: `jq '.status = \"completed\"' {session.task_json_path} > temp.json && mv temp.json {session.task_json_path}`
- Update TODO list: {session.todo_list_path}
- Generate summary: {session.summaries_dir}/{task.id}-summary.md
- Check workflow completion and call `/workflow:session:complete` if all tasks done
### Flow Control Steps (if [FLOW_CONTROL] present)
**AGENT RESPONSIBILITY**: Execute these pre_analysis steps sequentially with context accumulation:
{pre_analysis_steps}
## Context Sources (All from JSON)
- Requirements: `context.requirements`
- Focus Paths: `context.focus_paths`
- Acceptance: `context.acceptance`
- Artifacts: `context.artifacts` (synthesis specs, brainstorming outputs)
- Dependencies: `context.depends_on`
- Target Files: `flow_control.target_files`
### Implementation Context
**Requirements**: {context.requirements}
**Focus Paths**: {context.focus_paths}
**Acceptance Criteria**: {context.acceptance}
**Target Files**: {flow_control.target_files}
## Session Paths
- Workflow Dir: {session.workflow_dir}
- TODO List: {session.todo_list_path}
- Summaries: {session.summaries_dir}
- Flow Context: {flow_context.step_outputs}
### Session Context
**Workflow Directory**: {session.workflow_dir}
**TODO List Path**: {session.todo_list_path}
**Summaries Directory**: {session.summaries_dir}
**Task JSON Path**: {session.task_json_path}
**Complete JSON structure is authoritative - load and follow it exactly.**"),
description="Execute task: {task.id}")
```
### Dependencies & Context
**Dependencies**: {context.depends_on}
**Inherited Context**: {context.inherited}
**Previous Outputs**: {flow_context.step_outputs}
#### Agent JSON Loading Specification
**MANDATORY AGENT PROTOCOL**: All agents must follow this exact loading sequence:
## Completion Requirements
1. Execute all flow control steps if present
2. Implement according to acceptance criteria
3. Update TODO_LIST.md at provided path
4. Generate summary in summaries directory
5. Mark task as completed in task JSON",
description="{task_description}")
1. **JSON Loading**: First action must be `cat {session.task_json_path}`
2. **Field Validation**: Verify all 5 required fields exist: `id`, `title`, `status`, `meta`, `context`, `flow_control`
3. **Structure Parsing**: Parse nested fields correctly:
- `meta.type` and `meta.agent` (NOT flat `task_type`)
- `context.requirements`, `context.focus_paths`, `context.acceptance`
- `context.depends_on`, `context.inherited`
- `flow_control.pre_analysis` array, `flow_control.target_files`
4. **Flow Control Execution**: If `flow_control.pre_analysis` exists, execute steps sequentially
5. **Status Management**: Update JSON status upon completion
**JSON Field Reference**:
```json
{
"id": "IMPL-1.2",
"title": "Task title",
"status": "pending|active|completed|blocked",
"meta": {
"type": "feature|bugfix|refactor|test-gen|test-fix|docs",
"agent": "@code-developer|@test-fix-agent|@general-purpose"
},
"context": {
"requirements": ["req1", "req2"],
"focus_paths": ["src/path1", "src/path2"],
"acceptance": ["criteria1", "criteria2"],
"depends_on": ["IMPL-1.1"],
"inherited": { "from": "parent", "context": ["info"] },
"artifacts": [
{
"type": "synthesis_specification",
"source": "brainstorm_synthesis",
"path": ".workflow/WFS-[session]/.brainstorming/synthesis-specification.md",
"priority": "highest",
"contains": "complete_integrated_specification"
},
{
"type": "individual_role_analysis",
"source": "brainstorm_roles",
"path": ".workflow/WFS-[session]/.brainstorming/[role]/analysis.md",
"priority": "low",
"contains": "role_specific_analysis_fallback"
}
]
},
"flow_control": {
"pre_analysis": [
{
"step": "load_synthesis_specification",
"action": "Load consolidated synthesis specification from brainstorming",
"commands": [
"bash(ls .workflow/WFS-[session]/.brainstorming/synthesis-specification.md 2>/dev/null || echo 'synthesis specification not found')",
"Read(.workflow/WFS-[session]/.brainstorming/synthesis-specification.md)"
],
"output_to": "synthesis_specification",
"on_error": "skip_optional"
},
{
"step": "step_name",
"command": "bash_command",
"output_to": "variable",
"on_error": "skip_optional|fail|retry_once"
}
],
"implementation_approach": [
{
"step": 1,
"title": "Implement task following synthesis specification",
"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": [
"Load synthesis specification",
"Parse architecture and requirements",
"Implement following specification",
"Consult artifacts for technical details when needed",
"Validate against acceptance criteria"
],
"depends_on": [],
"output": "implementation"
}
],
"target_files": ["file:function:lines", "path/to/NewFile.ts"]
}
}
```
#### Execution Flow
1. **Prepare Agent Context**: Assemble complete context package
2. **Generate Prompt**: Fill template with task and context data
3. **Launch Agent**: Invoke specialized agent with structured prompt
4. **Monitor Execution**: Track progress and handle errors
5. **Collect Results**: Process agent outputs and update status
1. **Load Task JSON**: Agent reads and validates complete JSON structure
2. **Execute Flow Control**: Agent runs pre_analysis steps if present
3. **Prepare Implementation**: Agent uses implementation_approach from JSON
4. **Launch Implementation**: Agent follows focus_paths and target_files
5. **Update Status**: Agent marks JSON status as completed
6. **Generate Summary**: Agent creates completion summary
#### Agent Assignment Rules
```
meta.agent specified → Use specified agent
meta.agent missing → Infer from meta.type:
- "feature" → @code-developer
- "test" → @code-review-test-agent
- "review" → @code-review-agent
- "test-gen" → @code-developer
- "test-fix" → @test-fix-agent
- "review" → @general-purpose
- "docs" → @doc-generator
```
@@ -307,7 +585,7 @@ meta.agent missing → Infer from meta.type:
|-------|-------|------------|---------|
| No active session | No `.active-*` markers found | Create or resume session | `/workflow:plan "project"` |
| Multiple sessions | Multiple `.active-*` markers | Select specific session | Manual choice prompt |
| Corrupted session | Invalid JSON files | Recreate session structure | `/workflow:status --validate` |
| Corrupted session | Invalid JSON files | Recreate session structure | `/workflow:session:status --validate` |
| Missing task files | Broken task references | Regenerate tasks | `/task:create` or repair |
### Execution Phase Errors
@@ -381,7 +659,7 @@ fi
### Basic Usage
```bash
/workflow:execute # Execute all pending tasks autonomously
/workflow:status # Check progress
/workflow:session:status # Check progress
/task:execute IMPL-1.2 # Execute specific task
```

View File

@@ -1,300 +0,0 @@
---
name: gemini-init
description: Initialize Gemini CLI configuration with .gemini config and .geminiignore based on workspace analysis
usage: /workflow:gemini-init [--output=<path>] [--preview]
argument-hint: [optional: output path, preview flag]
examples:
- /workflow:gemini-init
- /workflow:gemini-init --output=.config/
- /workflow:gemini-init --preview
---
# Gemini Initialization Command
## Overview
Initializes Gemini CLI configuration for the workspace by:
1. Analyzing current workspace using `get_modules_by_depth.sh` to identify technology stacks
2. Generating `.geminiignore` file with filtering rules optimized for detected technologies
3. Creating `.gemini` configuration file with contextfilename and other settings
## Core Functionality
### Configuration Generation
1. **Workspace Analysis**: Runs `get_modules_by_depth.sh` to analyze project structure
2. **Technology Stack Detection**: Identifies tech stacks based on file extensions, directories, and configuration files
3. **Gemini Config Creation**: Generates `.gemini` file with contextfilename and workspace-specific settings
4. **Ignore Rules Generation**: Creates `.geminiignore` file with filtering patterns for detected technologies
### Generated Files
#### .gemini Configuration File
Contains Gemini CLI contextfilename setting:
```json
{
"contextfilename": "CLAUDE.md"
}
```
#### .geminiignore Filter File
Uses gitignore syntax to filter files from Gemini CLI analysis
### Supported Technology Stacks
#### Frontend Technologies
- **React/Next.js**: Ignores build artifacts, .next/, node_modules
- **Vue/Nuxt**: Ignores .nuxt/, dist/, .cache/
- **Angular**: Ignores dist/, .angular/, node_modules
- **Webpack/Vite**: Ignores build outputs, cache directories
#### Backend Technologies
- **Node.js**: Ignores node_modules, package-lock.json, npm-debug.log
- **Python**: Ignores __pycache__, .venv, *.pyc, .pytest_cache
- **Java**: Ignores target/, .gradle/, *.class, .mvn/
- **Go**: Ignores vendor/, *.exe, go.sum (when appropriate)
- **C#/.NET**: Ignores bin/, obj/, *.dll, *.pdb
#### Database & Infrastructure
- **Docker**: Ignores .dockerignore, docker-compose.override.yml
- **Kubernetes**: Ignores *.secret.yaml, helm charts temp files
- **Database**: Ignores *.db, *.sqlite, database dumps
### Generated Rules Structure
#### Base Rules (Always Included)
```
# Version Control
.git/
.svn/
.hg/
# OS Files
.DS_Store
Thumbs.db
*.tmp
*.swp
# IDE Files
.vscode/
.idea/
.vs/
# Logs
*.log
logs/
```
#### Technology-Specific Rules
Rules are added based on detected technologies:
**Node.js Projects** (package.json detected):
```
# Node.js
node_modules/
npm-debug.log*
.npm/
.yarn/
package-lock.json
yarn.lock
.pnpm-store/
```
**Python Projects** (requirements.txt, setup.py, pyproject.toml detected):
```
# Python
__pycache__/
*.py[cod]
.venv/
venv/
.pytest_cache/
.coverage
htmlcov/
```
**Java Projects** (pom.xml, build.gradle detected):
```
# Java
target/
.gradle/
*.class
*.jar
*.war
.mvn/
```
## Command Options
### Basic Usage
```bash
/workflow:gemini-init
```
- Analyzes workspace and generates `.gemini` and `.geminiignore` in current directory
- Creates backup of existing files if present
- Sets contextfilename to "CLAUDE.md" by default
### Preview Mode
```bash
/workflow:gemini-init --preview
```
- Shows what would be generated without creating files
- Displays detected technologies, configuration, and ignore rules
### Custom Output Path
```bash
/workflow:gemini-init --output=.config/
```
- Generates files in specified directory
- Creates directories if they don't exist
## Implementation Process
### Phase 1: Workspace Analysis
1. Execute `get_modules_by_depth.sh json` to get structured project data
2. Parse JSON output to identify directories and files
3. Scan for technology indicators:
- Configuration files (package.json, requirements.txt, etc.)
- Directory patterns (src/, tests/, etc.)
- File extensions (.js, .py, .java, etc.)
4. Detect project name from directory name or package.json
### Phase 2: Technology Detection
```bash
# Technology detection logic
detect_nodejs() {
[ -f "package.json" ] || find . -name "package.json" -not -path "*/node_modules/*" | head -1
}
detect_python() {
[ -f "requirements.txt" ] || [ -f "setup.py" ] || [ -f "pyproject.toml" ] || \
find . -name "*.py" -not -path "*/__pycache__/*" | head -1
}
detect_java() {
[ -f "pom.xml" ] || [ -f "build.gradle" ] || \
find . -name "*.java" | head -1
}
```
### Phase 3: Configuration Generation
1. **Gemini Config (.gemini)**:
- Generate simple JSON config with contextfilename setting
- Set contextfilename to "CLAUDE.md" by default
### Phase 4: Ignore Rules Generation
1. Start with base rules (always included)
2. Add technology-specific rules based on detection
3. Add workspace-specific patterns if found
4. Sort and deduplicate rules
### Phase 5: File Creation
1. **Generate .gemini config**: Write JSON configuration file
2. **Generate .geminiignore**: Create organized ignore file with sections
3. **Create backups**: Backup existing files if present
4. **Validate**: Check generated files are valid
## Generated File Format
```
# .geminiignore
# Generated by Claude Code workflow:gemini-ignore command
# Creation date: 2024-01-15 10:30:00
# Detected technologies: Node.js, Python, Docker
#
# This file uses gitignore syntax to filter files for Gemini CLI analysis
# Edit this file to customize filtering rules for your project
# ============================================================================
# Base Rules (Always Applied)
# ============================================================================
# Version Control
.git/
.svn/
.hg/
# ============================================================================
# Node.js (Detected: package.json found)
# ============================================================================
node_modules/
npm-debug.log*
.npm/
yarn-error.log
package-lock.json
# ============================================================================
# Python (Detected: requirements.txt, *.py files found)
# ============================================================================
__pycache__/
*.py[cod]
.venv/
.pytest_cache/
.coverage
# ============================================================================
# Docker (Detected: Dockerfile found)
# ============================================================================
.dockerignore
docker-compose.override.yml
# ============================================================================
# Custom Rules (Add your project-specific rules below)
# ============================================================================
```
## Error Handling
### Missing Dependencies
- If `get_modules_by_depth.sh` not found, show error with path to script
- Gracefully handle cases where script fails
### Write Permissions
- Check write permissions before attempting file creation
- Show clear error message if cannot write to target location
### Backup Existing Files
- If `.geminiignore` exists, create backup as `.geminiignore.backup`
- Include timestamp in backup filename
## Integration Points
### Workflow Commands
- **After `/workflow:plan`**: Suggest running gemini-ignore for better analysis
- **Before analysis**: Recommend updating ignore patterns for cleaner results
### CLI Tool Integration
- Automatically update when new technologies detected
- Integrate with `intelligent-tools-strategy.md` recommendations
## Usage Examples
### Basic Project Setup
```bash
# New project - initialize Gemini configuration
/workflow:gemini-init
# Preview what would be generated
/workflow:gemini-init --preview
# Generate in subdirectory
/workflow:gemini-init --output=.config/
```
### Technology Migration
```bash
# After adding new tech stack (e.g., Docker)
/workflow:gemini-init # Regenerates both config and ignore files with new rules
# Check what changed
/workflow:gemini-init --preview # Compare with existing configuration
```
## Key Benefits
- **Automatic Detection**: No manual configuration needed
- **Technology Aware**: Rules adapted to actual project stack
- **Maintainable**: Clear sections for easy customization
- **Consistent**: Follows gitignore syntax standards
- **Safe**: Creates backups of existing files

View File

@@ -1,142 +0,0 @@
---
name: close
description: Close a completed or obsolete workflow issue
usage: /workflow:issue:close <issue-id> [reason]
examples:
- /workflow:issue:close ISS-001
- /workflow:issue:close ISS-001 "Feature implemented in PR #42"
- /workflow:issue:close ISS-002 "Duplicate of ISS-001"
---
# Close Workflow Issue (/workflow:issue:close)
## Purpose
Mark an issue as closed/resolved with optional reason documentation.
## Usage
```bash
/workflow:issue:close <issue-id> ["reason"]
```
## Closing Process
### Quick Close
Simple closure without reason:
```bash
/workflow:issue:close ISS-001
```
### Close with Reason
Include closure reason:
```bash
/workflow:issue:close ISS-001 "Feature implemented in PR #42"
/workflow/issue/close ISS-002 "Duplicate of ISS-001"
/workflow/issue/close ISS-003 "No longer relevant"
```
### Interactive Close (Default)
Without reason, prompts for details:
```
Closing Issue ISS-001: Add OAuth2 social login support
Current Status: Open | Priority: High | Type: Feature
Why is this issue being closed?
1. ✅ Completed - Issue resolved successfully
2. 🔄 Duplicate - Duplicate of another issue
3. ❌ Invalid - Issue is invalid or not applicable
4. 🚫 Won't Fix - Decided not to implement
5. 📝 Custom reason
Choice: _
```
## Closure Categories
### Completed (Default)
- Issue was successfully resolved
- Implementation finished
- Requirements met
- Ready for review/testing
### Duplicate
- Same as existing issue
- Consolidated into another issue
- Reference to primary issue provided
### Invalid
- Issue description unclear
- Not a valid problem/request
- Outside project scope
- Misunderstanding resolved
### Won't Fix
- Decided not to implement
- Business decision to decline
- Technical constraints prevent
- Priority too low
### Custom Reason
- Specific project context
- Detailed explanation needed
- Complex closure scenario
## Closure Effects
### Status Update
- Changes status from "open" to "closed"
- Records closure details
- Saves closure reason and category
### Integration Cleanup
- Unlinks from workflow tasks (if integrated)
- Removes from active TodoWrite items
- Updates session statistics
### History Preservation
- Maintains full issue history
- Records closure details
- Preserves for future reference
## Session Updates
### Statistics
Updates session issue counts:
- Decrements open issues
- Increments closed issues
- Updates completion metrics
### Progress Tracking
- Updates workflow progress
- Refreshes TodoWrite status
- Updates session health metrics
## Output
Displays:
- Issue closure confirmation
- Closure reason and category
- Updated session statistics
- Related actions taken
## Reopening
Closed issues can be reopened:
```bash
/workflow/issue/update ISS-001 --status=open
```
## Error Handling
- **Issue not found**: Lists available open issues
- **Already closed**: Shows current status and closure info
- **Integration conflicts**: Handles task unlinking gracefully
- **File errors**: Validates and repairs issue files
## Archive Management
Closed issues:
- Remain in .issues/ directory
- Are excluded from default listings
- Can be viewed with `/workflow/issue/list --closed`
- Maintain full searchability
---
**Result**: Issue properly closed with documented reason and session cleanup

View File

@@ -1,106 +0,0 @@
---
name: create
description: Create a new issue or change request
usage: /workflow:issue:create "issue description"
examples:
- /workflow:issue:create "Add OAuth2 social login support"
- /workflow:issue:create "Fix user avatar security vulnerability"
---
# Create Workflow Issue (/workflow:issue:create)
## Purpose
Create a new issue or change request within the current workflow session.
## Usage
```bash
/workflow:issue:create "issue description"
```
## Automatic Behavior
### Issue ID Generation
- Generates unique ID: ISS-001, ISS-002, etc.
- Sequential numbering within session
- Stored in session's .issues/ directory
### Type Detection
Automatically detects issue type from description:
- **Bug**: Contains words like "fix", "error", "bug", "broken"
- **Feature**: Contains words like "add", "implement", "create", "new"
- **Optimization**: Contains words like "improve", "optimize", "performance"
- **Documentation**: Contains words like "document", "readme", "docs"
- **Refactor**: Contains words like "refactor", "cleanup", "restructure"
### Priority Assessment
Auto-assigns priority based on keywords:
- **Critical**: "critical", "urgent", "blocker", "security"
- **High**: "important", "major", "significant"
- **Medium**: Default for most issues
- **Low**: "minor", "enhancement", "nice-to-have"
## Issue Storage
### File Structure
```
.workflow/WFS-[session]/.issues/
├── ISS-001.json # Issue metadata
├── ISS-002.json # Another issue
└── issue-registry.json # Issue index
```
### Issue Metadata
Each issue stores:
```json
{
"id": "ISS-001",
"title": "Add OAuth2 social login support",
"type": "feature",
"priority": "high",
"status": "open",
"created_at": "2025-09-08T10:00:00Z",
"category": "authentication",
"estimated_impact": "medium",
"blocking": false,
"session_id": "WFS-oauth-integration"
}
```
## Session Integration
### Active Session Check
- Uses current active session (marker file)
- Creates .issues/ directory if needed
- Updates session's issue tracking
### TodoWrite Integration
Optionally adds to task list:
- Creates todo for issue investigation
- Links issue to implementation tasks
- Updates progress tracking
## Output
Displays:
- Generated issue ID
- Detected type and priority
- Storage location
- Integration status
- Quick actions available
## Quick Actions
After creation:
- **View**: `/workflow:issue:list`
- **Update**: `/workflow:issue:update ISS-001`
- **Integrate**: Link to workflow tasks
- **Close**: `/workflow:issue:close ISS-001`
## Error Handling
- **No active session**: Prompts to start session first
- **Directory creation**: Handles permission issues
- **Duplicate description**: Warns about similar issues
- **Invalid description**: Prompts for meaningful description
---
**Result**: New issue created and ready for management within workflow

View File

@@ -1,104 +0,0 @@
---
name: list
description: List and filter workflow issues
usage: /workflow:issue:list
examples:
- /workflow:issue:list
- /workflow:issue:list --open
- /workflow:issue:list --priority=high
---
# List Workflow Issues (/workflow:issue:list)
## Purpose
Display all issues and change requests within the current workflow session.
## Usage
```bash
/workflow:issue:list [filter]
```
## Optional Filters
Simple keyword-based filtering:
```bash
/workflow:issue:list --open # Only open issues
/workflow:issue:list --closed # Only closed issues
/workflow:issue:list --critical # Critical priority
/workflow:issue:list --high # High priority
/workflow:issue:list --bug # Bug type issues
/workflow:issue:list --feature # Feature type issues
/workflow:issue:list --blocking # Blocking issues only
```
## Display Format
### Open Issues
```
🔴 ISS-001: Add OAuth2 social login support
Type: Feature | Priority: High | Created: 2025-09-07
Status: Open | Impact: Medium
🔴 ISS-002: Fix user avatar security vulnerability
Type: Bug | Priority: Critical | Created: 2025-09-08
Status: Open | Impact: High | 🚫 BLOCKING
```
### Closed Issues
```
✅ ISS-003: Update authentication documentation
Type: Documentation | Priority: Low
Status: Closed | Completed: 2025-09-05
Reason: Documentation updated in PR #45
```
### Integrated Issues
```
🔗 ISS-004: Implement rate limiting
Type: Feature | Priority: Medium
Status: Integrated → IMPL-003
Integrated: 2025-09-06 | Task: IMPL-3.json
```
## Summary Stats
```
📊 Issue Summary for WFS-oauth-integration:
Total: 4 issues
🔴 Open: 2 | ✅ Closed: 1 | 🔗 Integrated: 1
🚫 Blocking: 1 | ⚡ Critical: 1 | 📈 High: 1
```
## Empty State
If no issues exist:
```
No issues found for current session.
Create your first issue:
/workflow:issue:create "describe the issue or request"
```
## Quick Actions
For each issue, shows available actions:
- **Update**: `/workflow:issue:update ISS-001`
- **Integrate**: Link to workflow tasks
- **Close**: `/workflow:issue:close ISS-001`
- **View Details**: Full issue information
## Session Context
- Lists issues from current active session
- Shows session name and directory
- Indicates if .issues/ directory exists
## Sorting
Issues are sorted by:
1. Blocking status (blocking first)
2. Priority (critical → high → medium → low)
3. Creation date (newest first)
## Performance
- Fast loading from JSON files
- Cached issue registry
- Efficient filtering
---
**Result**: Complete overview of all workflow issues with their current status

View File

@@ -1,135 +0,0 @@
---
name: update
description: Update an existing workflow issue
usage: /workflow:issue:update <issue-id> [changes]
examples:
- /workflow:issue:update ISS-001
- /workflow:issue:update ISS-001 --priority=critical
- /workflow:issue:update ISS-001 --status=closed
---
# Update Workflow Issue (/workflow:issue:update)
## Purpose
Modify attributes and status of an existing workflow issue.
## Usage
```bash
/workflow:issue:update <issue-id> [options]
```
## Quick Updates
Simple attribute changes:
```bash
/workflow:issue:update ISS-001 --priority=critical
/workflow:issue:update ISS-001 --status=closed
/workflow:issue:update ISS-001 --blocking
/workflow:issue:update ISS-001 --type=bug
```
## Interactive Mode (Default)
Without options, opens interactive editor:
```
Issue ISS-001: Add OAuth2 social login support
Current Status: Open | Priority: High | Type: Feature
What would you like to update?
1. Status (open → closed/integrated)
2. Priority (high → critical/medium/low)
3. Type (feature → bug/optimization/etc)
4. Description
5. Add comment
6. Toggle blocking status
7. Cancel
Choice: _
```
## Available Updates
### Status Changes
- **open** → **closed**: Issue resolved
- **open** → **integrated**: Linked to workflow task
- **closed** → **open**: Reopen issue
- **integrated** → **open**: Unlink from tasks
### Priority Levels
- **critical**: Urgent, blocking progress
- **high**: Important, should address soon
- **medium**: Standard priority
- **low**: Nice-to-have, can defer
### Issue Types
- **bug**: Something broken that needs fixing
- **feature**: New functionality to implement
- **optimization**: Performance or efficiency improvement
- **refactor**: Code structure improvement
- **documentation**: Documentation updates
### Additional Options
- **blocking/non-blocking**: Whether issue blocks progress
- **description**: Update issue description
- **comments**: Add notes and updates
## Update Process
### Validation
- Verifies issue exists in current session
- Checks valid status transitions
- Validates priority and type values
### Change Tracking
- Records update details
- Tracks who made changes
- Maintains change history
### File Updates
- Updates ISS-XXX.json file
- Refreshes issue-registry.json
- Updates session statistics
## Change History
Maintains audit trail:
```json
{
"changes": [
{
"field": "priority",
"old_value": "high",
"new_value": "critical",
"reason": "Security implications discovered"
}
]
}
```
## Integration Effects
### Task Integration
When status changes to "integrated":
- Links to workflow task (optional)
- Updates task context with issue reference
- Creates bidirectional linking
### Session Updates
- Updates session issue statistics
- Refreshes TodoWrite if applicable
- Updates workflow progress tracking
## Output
Shows:
- What was changed
- Before and after values
- Integration status
- Available next actions
## Error Handling
- **Issue not found**: Lists available issues
- **Invalid status**: Shows valid transitions
- **Permission errors**: Clear error messages
- **File corruption**: Validates and repairs
---
**Result**: Issue successfully updated with change tracking and integration

View File

@@ -1,550 +0,0 @@
---
name: plan-verify
description: Cross-validate action plans using gemini and codex analysis before execution
usage: /workflow:plan-verify
argument-hint: none
examples:
- /workflow:plan-verify
allowed-tools: Task(*), TodoWrite(*), Read(*), Write(*), Edit(*), Bash(*), Glob(*)
---
# Workflow Plan Verify Command
## Overview
Cross-validates existing workflow plans using gemini and codex analysis to ensure plan quality, feasibility, and completeness before execution. **Works between `/workflow:plan` and `/workflow:execute`** to catch potential issues early and suggest improvements.
## Core Responsibilities
- **Session Discovery**: Identify active workflow sessions with completed plans
- **Dual Analysis**: Independent gemini and codex plan evaluation
- **Cross-Validation**: Compare analyses to identify consensus and conflicts
- **Modification Suggestions**: Generate actionable improvement recommendations
- **User Approval**: Interactive approval process for suggested changes
- **Plan Updates**: Apply approved modifications to workflow documents
## Execution Philosophy
- **Quality Assurance**: Comprehensive plan validation before implementation
- **Dual Perspective**: Technical feasibility (codex) + strategic assessment (gemini)
- **User Control**: All modifications require explicit user approval
- **Non-Destructive**: Original plans preserved with versioned updates
- **Context-Rich**: Full workflow context provided to both analysis tools
## Core Workflow
### Verification Process
The command performs comprehensive cross-validation through:
**0. Session Management** ⚠️ FIRST STEP
- **Active session detection**: Check `.workflow/.active-*` markers
- **Session validation**: Ensure session has completed IMPL_PLAN.md
- **Plan readiness check**: Verify tasks exist in `.task/` directory
- **Context availability**: Confirm analysis artifacts are present
**1. Context Preparation & Analysis Setup**
- **Plan context loading**: Load IMPL_PLAN.md, task definitions, and analysis results
- **Documentation gathering**: Collect relevant CLAUDE.md, README.md, and workflow docs
- **Dependency mapping**: Analyze task relationships and constraints
- **Validation criteria setup**: Establish evaluation framework
**2. Parallel Dual Analysis** ⚠️ CRITICAL ARCHITECTURE
- **Gemini Analysis**: Strategic and architectural plan evaluation
- **Codex Analysis**: Technical feasibility and implementation assessment
- **Independent execution**: Both tools analyze simultaneously with full context
- **Comprehensive evaluation**: Each tool evaluates different aspects
**3. Cross-Validation & Synthesis**
- **Consensus identification**: Areas where both analyses agree
- **Conflict analysis**: Discrepancies between gemini and codex evaluations
- **Risk assessment**: Combined evaluation of potential issues
- **Improvement opportunities**: Synthesized recommendations
**4. Interactive Approval Process**
- **Results presentation**: Clear display of findings and suggestions
- **User decision points**: Approval/rejection of each modification category
- **Selective application**: User controls which changes to implement
- **Confirmation workflow**: Multi-step approval for significant changes
## Implementation Standards
### Dual Analysis Architecture ⚠️ CRITICAL
Both tools receive identical context but focus on different validation aspects:
```json
{
"gemini_analysis": {
"focus": "strategic_validation",
"aspects": [
"architectural_soundness",
"task_decomposition_logic",
"dependency_coherence",
"business_alignment",
"risk_identification"
],
"context_sources": [
"IMPL_PLAN.md",
".process/ANALYSIS_RESULTS.md",
"CLAUDE.md",
".workflow/docs/"
]
},
"codex_analysis": {
"focus": "technical_feasibility",
"aspects": [
"implementation_complexity",
"technical_dependencies",
"code_structure_assessment",
"testing_completeness",
"execution_readiness"
],
"context_sources": [
".task/*.json",
"target_files from flow_control",
"existing codebase patterns",
"technical documentation"
]
}
}
```
### Analysis Execution Pattern
**Gemini Strategic Analysis**:
```bash
~/.claude/scripts/gemini-wrapper -p "
PURPOSE: Strategic validation of workflow implementation plan
TASK: Evaluate plan architecture, task decomposition, and business alignment
CONTEXT: @{.workflow/WFS-*/IMPL_PLAN.md,.workflow/WFS-*/.process/ANALYSIS_RESULTS.md,CLAUDE.md}
EXPECTED: Strategic assessment with architectural recommendations
RULES: $(cat ~/.claude/workflows/cli-templates/prompts/verification/gemini-strategic.txt) | Focus on strategic soundness and risk identification
"
```
**Codex Technical Analysis**:
```bash
codex --full-auto exec "
PURPOSE: Technical feasibility assessment of workflow implementation plan
TASK: Evaluate implementation complexity, dependencies, and execution readiness
CONTEXT: @{.workflow/WFS-*/.task/*.json,CLAUDE.md,README.md} Target files and flow control definitions
EXPECTED: Technical assessment with implementation recommendations
RULES: $(cat ~/.claude/workflows/cli-templates/prompts/verification/codex-technical.txt) | Focus on technical feasibility and code quality
" -s danger-full-access
```
**Cross-Validation Analysis**:
```bash
~/.claude/scripts/gemini-wrapper -p "
PURPOSE: Cross-validate and synthesize strategic and technical assessments
TASK: Compare analyses, resolve conflicts, and generate integrated recommendations
CONTEXT: @{.workflow/WFS-*/.verification/gemini-analysis.md,.workflow/WFS-*/.verification/codex-analysis.md}
EXPECTED: Synthesized recommendations with user approval framework
RULES: $(cat ~/.claude/workflows/cli-templates/prompts/verification/cross-validation.txt) | Focus on balanced integration and user decision points
"
```
### Cross-Validation Matrix
**Validation Categories**:
1. **Task Decomposition**: Is breakdown logical and complete?
2. **Dependency Management**: Are task relationships correctly modeled?
3. **Implementation Scope**: Is each task appropriately sized?
4. **Technical Feasibility**: Are implementation approaches viable?
5. **Context Completeness**: Do tasks have adequate context?
6. **Testing Coverage**: Are testing requirements sufficient?
7. **Documentation Quality**: Are requirements clear and complete?
**Consensus Analysis**:
- **Agreement Areas**: Both tools identify same strengths/issues
- **Divergent Views**: Different perspectives requiring user decision
- **Risk Levels**: Combined assessment of implementation risks
- **Priority Recommendations**: Most critical improvements identified
### User Approval Workflow
**Interactive Approval Process**:
1. **Results Presentation**: Show analysis summary and key findings
2. **Category-based Approval**: Present modifications grouped by type
3. **Impact Assessment**: Explain consequences of each change
4. **Selective Implementation**: User chooses which changes to apply
5. **Confirmation Steps**: Final review before plan modification
**Step-by-Step User Interaction**:
**Step 1: Present Analysis Summary**
```
## Verification Results for WFS-[session-name]
### Analysis Summary
- **Gemini Strategic Grade**: B+ (Strong architecture, minor business alignment issues)
- **Codex Technical Grade**: A- (High implementation feasibility, good code structure)
- **Combined Risk Level**: Medium (Dependency complexity, timeline concerns)
- **Overall Recommendation**: Proceed with modifications
### Key Findings
✅ **Strengths Identified**: Task decomposition logical, technical approach sound
⚠️ **Areas for Improvement**: Missing error handling, unclear success criteria
❌ **Critical Issues**: Circular dependency in IMPL-3 → IMPL-1 chain
```
**Step 2: Category-based Modification Approval**
```bash
# Interactive prompts for each category
echo "Review the following modification categories:"
echo ""
echo "=== CRITICAL CHANGES (Must be addressed) ==="
read -p "1. Fix circular dependency IMPL-3 → IMPL-1? [Y/n]: " fix_dependency
read -p "2. Add missing error handling context to IMPL-2? [Y/n]: " add_error_handling
echo ""
echo "=== IMPORTANT IMPROVEMENTS (Recommended) ==="
read -p "3. Merge granular tasks IMPL-1.1 + IMPL-1.2? [Y/n]: " merge_tasks
read -p "4. Enhance success criteria for IMPL-4? [Y/n]: " enhance_criteria
echo ""
echo "=== OPTIONAL ENHANCEMENTS (Nice to have) ==="
read -p "5. Add API documentation task? [y/N]: " add_docs_task
read -p "6. Include performance testing in IMPL-3? [y/N]: " add_perf_tests
```
**Step 3: Impact Assessment Display**
For each approved change, show detailed impact:
```
Change: Merge tasks IMPL-1.1 + IMPL-1.2
Impact:
- Files affected: .task/IMPL-1.1.json, .task/IMPL-1.2.json → .task/IMPL-1.json
- Dependencies: IMPL-2.depends_on changes from ["IMPL-1.1", "IMPL-1.2"] to ["IMPL-1"]
- Estimated time: Reduces from 8h to 6h (reduced coordination overhead)
- Risk: Low (combining related functionality)
```
**Step 4: Modification Confirmation**
```bash
echo "Summary of approved changes:"
echo "✓ Fix circular dependency IMPL-3 → IMPL-1"
echo "✓ Add error handling context to IMPL-2"
echo "✓ Merge tasks IMPL-1.1 + IMPL-1.2"
echo "✗ Enhance success criteria for IMPL-4 (user declined)"
echo ""
read -p "Apply these modifications to the workflow plan? [Y/n]: " final_approval
if [[ "$final_approval" =~ ^[Yy]$ ]] || [[ -z "$final_approval" ]]; then
echo "Creating backups and applying modifications..."
else
echo "Modifications cancelled. Original plan preserved."
fi
```
**Approval Categories**:
```markdown
## Verification Results Summary
### ✅ Consensus Recommendations (Both gemini and codex agree)
- [ ] **Task Decomposition**: Merge IMPL-1.1 and IMPL-1.2 (too granular)
- [ ] **Dependencies**: Add missing dependency IMPL-3 → IMPL-4
- [ ] **Context**: Enhance context.requirements for IMPL-2
### ⚠️ Conflicting Assessments (gemini vs codex differ)
- [ ] **Scope**: gemini suggests splitting IMPL-5, codex suggests keeping merged
- [ ] **Testing**: gemini prioritizes integration tests, codex emphasizes unit tests
### 🔍 Individual Tool Recommendations
#### Gemini (Strategic)
- [ ] **Architecture**: Consider API versioning strategy
- [ ] **Risk**: Add rollback plan for database migrations
#### Codex (Technical)
- [ ] **Implementation**: Use existing auth patterns in /src/auth/
- [ ] **Dependencies**: Update package.json dependencies first
```
## Document Generation & Modification
**Verification Workflow**: Analysis → Cross-Validation → User Approval → Plan Updates → Versioning
**Always Created**:
- **VERIFICATION_RESULTS.md**: Complete analysis results and recommendations
- **verification-session.json**: Analysis metadata and user decisions
- **PLAN_MODIFICATIONS.md**: Record of approved changes
**Auto-Created (if modifications approved)**:
- **IMPL_PLAN.md.backup**: Original plan backup before modifications
- **Updated task JSONs**: Modified .task/*.json files with improvements
- **MODIFICATION_LOG.md**: Detailed change log with timestamps
**Document Structure**:
```
.workflow/WFS-[topic]/.verification/
├── verification-session.json # Analysis session metadata
├── VERIFICATION_RESULTS.md # Complete analysis results
├── PLAN_MODIFICATIONS.md # Approved changes record
├── gemini-analysis.md # Gemini strategic analysis
├── codex-analysis.md # Codex technical analysis
├── cross-validation-matrix.md # Comparison analysis
└── backups/
├── IMPL_PLAN.md.backup # Original plan backup
└── task-backups/ # Original task JSON backups
```
### Modification Implementation
**Safe Modification Process**:
1. **Backup Creation**: Save original files before any changes
2. **Atomic Updates**: Apply all approved changes together
3. **Validation**: Verify modified plans are still valid
4. **Rollback Capability**: Easy restoration if issues arise
**Implementation Commands**:
**Step 1: Create Backups**
```bash
# Create backup directory with timestamp
backup_dir=".workflow/WFS-$session/.verification/backups/$(date +%Y%m%d_%H%M%S)"
mkdir -p "$backup_dir/task-backups"
# Backup main plan and task files
cp IMPL_PLAN.md "$backup_dir/IMPL_PLAN.md.backup"
cp -r .task/ "$backup_dir/task-backups/"
# Create backup manifest
echo "Backup created at $(date)" > "$backup_dir/backup-manifest.txt"
echo "Session: $session" >> "$backup_dir/backup-manifest.txt"
echo "Files backed up:" >> "$backup_dir/backup-manifest.txt"
ls -la IMPL_PLAN.md .task/*.json >> "$backup_dir/backup-manifest.txt"
```
**Step 2: Apply Approved Modifications**
```bash
# Example: Merge tasks IMPL-1.1 + IMPL-1.2
if [[ "$merge_tasks" =~ ^[Yy]$ ]]; then
echo "Merging IMPL-1.1 and IMPL-1.2..."
# Combine task contexts
jq -s '
{
"id": "IMPL-1",
"title": (.[0].title + " and " + .[1].title),
"status": "pending",
"meta": .[0].meta,
"context": {
"requirements": (.[0].context.requirements + " " + .[1].context.requirements),
"focus_paths": (.[0].context.focus_paths + .[1].context.focus_paths | unique),
"acceptance": (.[0].context.acceptance + .[1].context.acceptance),
"depends_on": (.[0].context.depends_on + .[1].context.depends_on | unique)
},
"flow_control": {
"target_files": (.[0].flow_control.target_files + .[1].flow_control.target_files | unique),
"implementation_approach": .[0].flow_control.implementation_approach
}
}
' .task/IMPL-1.1.json .task/IMPL-1.2.json > .task/IMPL-1.json
# Remove old task files
rm .task/IMPL-1.1.json .task/IMPL-1.2.json
# Update dependent tasks
for task_file in .task/*.json; do
jq '
if .context.depends_on then
.context.depends_on = [
.context.depends_on[] |
if . == "IMPL-1.1" or . == "IMPL-1.2" then "IMPL-1"
else .
end
] | unique
else . end
' "$task_file" > "$task_file.tmp" && mv "$task_file.tmp" "$task_file"
done
fi
# Example: Fix circular dependency
if [[ "$fix_dependency" =~ ^[Yy]$ ]]; then
echo "Fixing circular dependency IMPL-3 → IMPL-1..."
# Remove problematic dependency
jq 'if .id == "IMPL-3" then .context.depends_on = (.context.depends_on - ["IMPL-1"]) else . end' \
.task/IMPL-3.json > .task/IMPL-3.json.tmp && mv .task/IMPL-3.json.tmp .task/IMPL-3.json
fi
# Example: Add error handling context
if [[ "$add_error_handling" =~ ^[Yy]$ ]]; then
echo "Adding error handling context to IMPL-2..."
jq '.context.requirements += " Include comprehensive error handling and user feedback for all failure scenarios."' \
.task/IMPL-2.json > .task/IMPL-2.json.tmp && mv .task/IMPL-2.json.tmp .task/IMPL-2.json
fi
```
**Step 3: Validation and Cleanup**
```bash
# Validate modified JSON files
echo "Validating modified task files..."
for task_file in .task/*.json; do
if ! jq empty "$task_file" 2>/dev/null; then
echo "ERROR: Invalid JSON in $task_file - restoring backup"
cp "$backup_dir/task-backups/$(basename $task_file)" "$task_file"
else
echo "$task_file is valid"
fi
done
# Update IMPL_PLAN.md with modification summary
cat >> IMPL_PLAN.md << EOF
## Plan Verification and Modifications
**Verification Date**: $(date)
**Modifications Applied**:
$(if [[ "$merge_tasks" =~ ^[Yy]$ ]]; then echo "- Merged IMPL-1.1 and IMPL-1.2 for better cohesion"; fi)
$(if [[ "$fix_dependency" =~ ^[Yy]$ ]]; then echo "- Fixed circular dependency in IMPL-3"; fi)
$(if [[ "$add_error_handling" =~ ^[Yy]$ ]]; then echo "- Enhanced error handling requirements in IMPL-2"; fi)
**Backup Location**: $backup_dir
**Analysis Reports**: .verification/VERIFICATION_RESULTS.md
EOF
# Generate modification log
cat > .verification/MODIFICATION_LOG.md << EOF
# Plan Modification Log
## Session: $session
## Date: $(date)
### Applied Modifications
$(echo "Changes applied based on cross-validation analysis")
### Backup Information
- Backup Directory: $backup_dir
- Original Files: IMPL_PLAN.md, .task/*.json
- Restore Command: cp $backup_dir/* ./
### Validation Results
$(echo "All modified files validated successfully")
EOF
echo "Modifications applied successfully!"
echo "Backup created at: $backup_dir"
echo "Modification log: .verification/MODIFICATION_LOG.md"
```
**Change Categories & Implementation**:
**Task Modifications**:
- **Task Merging**: Combine related tasks with dependency updates
- **Task Splitting**: Divide complex tasks with new dependencies
- **Context Enhancement**: Add missing requirements or acceptance criteria
- **Dependency Updates**: Add/remove/modify depends_on relationships
**Plan Enhancements**:
- **Requirements Clarification**: Improve requirement definitions
- **Success Criteria**: Add measurable acceptance criteria
- **Risk Mitigation**: Add risk assessment and mitigation steps
- **Documentation Updates**: Enhance context and documentation
## Session Management ⚠️ CRITICAL
- **⚡ FIRST ACTION**: Check for all `.workflow/.active-*` markers
- **Plan validation**: Ensure active session has completed IMPL_PLAN.md
- **Task readiness**: Verify .task/ directory contains valid task definitions
- **Analysis prerequisites**: Confirm planning analysis artifacts exist
- **Context isolation**: Each session maintains independent verification state
## Error Handling & Recovery
### Verification Phase Errors
| Error | Cause | Resolution |
|-------|-------|------------|
| No active session | Missing `.active-*` markers | Run `/workflow:plan` first |
| Incomplete plan | Missing IMPL_PLAN.md | Complete planning phase |
| No task definitions | Empty .task/ directory | Regenerate tasks |
| Analysis tool failure | Tool execution error | Retry with fallback context |
### Recovery Procedures
**Session Recovery**:
```bash
# Validate session readiness
if [ ! -f ".workflow/$session/IMPL_PLAN.md" ]; then
echo "Plan incomplete - run /workflow:plan first"
exit 1
fi
# Check task definitions exist
if [ ! -d ".workflow/$session/.task/" ] || [ -z "$(ls .workflow/$session/.task/)" ]; then
echo "No task definitions found - regenerate tasks"
exit 1
fi
```
**Analysis Recovery**:
```bash
# Retry failed analysis with reduced context
if [ "$GEMINI_FAILED" = "true" ]; then
echo "Retrying gemini analysis with minimal context..."
fi
# Use fallback analysis if tools unavailable
if [ "$TOOLS_UNAVAILABLE" = "true" ]; then
echo "Using manual validation checklist..."
fi
```
## Usage Examples & Integration
### Complete Verification Workflow
```bash
# 1. After completing planning
/workflow:plan "Build authentication system"
# 2. Verify the plan before execution
/workflow:verify
# 3. Review and approve suggested modifications
# (Interactive prompts guide through approval process)
# 4. Execute verified plan
/workflow:execute
```
### Common Scenarios
#### Quick Verification Check
```bash
/workflow:verify --quick # Basic validation without modifications
```
#### Re-verification After Changes
```bash
/workflow:verify --recheck # Re-run after manual plan modifications
```
#### Verification with Custom Focus
```bash
/workflow:verify --focus=technical # Emphasize technical analysis
/workflow:verify --focus=strategic # Emphasize strategic analysis
```
### Integration Points
- **After Planning**: Use after `/workflow:plan` to validate created plans
- **Before Execution**: Use before `/workflow:execute` to ensure quality
- **Plan Iteration**: Use during iterative planning refinement
- **Quality Assurance**: Use as standard practice for complex workflows
### Key Benefits
- **Early Issue Detection**: Catch problems before implementation starts
- **Dual Perspective**: Both strategic and technical validation
- **Quality Assurance**: Systematic plan evaluation and improvement
- **Risk Mitigation**: Identify potential issues and dependencies
- **User Control**: All changes require explicit approval
- **Non-Destructive**: Original plans preserved with full rollback capability
## Quality Standards
### Analysis Excellence
- **Comprehensive Context**: Both tools receive complete workflow context
- **Independent Analysis**: Tools analyze separately to avoid bias
- **Focused Evaluation**: Each tool evaluates its domain expertise
- **Objective Assessment**: Clear criteria and measurable recommendations
### User Experience Excellence
- **Clear Presentation**: Results displayed in actionable format
- **Informed Decisions**: Impact assessment for all suggested changes
- **Selective Control**: Granular approval of individual modifications
- **Safe Operations**: Full backup and rollback capability
- **Transparent Process**: Complete audit trail of all changes

View File

@@ -1,308 +1,366 @@
---
name: plan
description: Create implementation plans with intelligent input detection
usage: /workflow:plan <input>
argument-hint: "text description"|file.md|ISS-001
examples:
- /workflow:plan "Build authentication system"
- /workflow:plan requirements.md
- /workflow:plan ISS-001
description: Orchestrate 5-phase planning workflow with quality gate, executing commands and passing context between phases
argument-hint: "[--agent] [--cli-execute] \"text description\"|file.md"
allowed-tools: SlashCommand(*), TodoWrite(*), Read(*), Bash(*)
---
# Workflow Plan Command
# Workflow Plan Command (/workflow:plan)
## 🚀 MCP Tools Integration (NEW!)
## Coordinator Role
**Enhanced with MCP (Model Context Protocol) tools for advanced codebase analysis:**
**This command is a pure orchestrator**: Execute 5 slash commands in sequence (including a quality gate), parse their outputs, pass context between them, and ensure complete execution through **automatic continuation**.
### Required MCP Servers
1. **Exa MCP Server** - External API patterns and examples
- Repository: https://github.com/exa-labs/exa-mcp-server
- Function: `mcp__exa__get_code_context_exa()` - Get external best practices
**Execution Model - Auto-Continue Workflow with Quality Gate**:
2. **Code Index MCP** - Internal codebase exploration
- Repository: https://github.com/johnhuang316/code-index-mcp
- Functions:
- `mcp__code-index__find_files()` - File pattern matching
- `mcp__code-index__search_code_advanced()` - Advanced code search
This workflow runs **mostly autonomously** once triggered, with one interactive quality gate (Phase 3.5). Phases 3 and 4 are delegated to specialized agents for complex analysis and task generation.
### Installation & Setup
Please install these MCP servers to enable enhanced codebase analysis. The workflow will automatically use them when available.
1. **User triggers**: `/workflow:plan "task"`
2. **Phase 1 executes** → Session discovery → Auto-continues
3. **Phase 2 executes** → Context gathering → Auto-continues
4. **Phase 3 executes** (cli-execution-agent) → Intelligent analysis → Auto-continues
5. **Phase 3.5 executes****Pauses for user Q&A** → User answers clarification questions → Auto-continues
6. **Phase 4 executes** (task-generate-agent if --agent) → Task generation → Reports final summary
## Usage
**Auto-Continue Mechanism**:
- TodoList tracks current phase status
- After each phase completion, automatically executes next pending phase
- **Phase 3.5 requires user interaction** - answers clarification questions (up to 5)
- If no ambiguities found, Phase 3.5 auto-skips and continues to Phase 4
- Progress updates shown at each phase for visibility
**Execution Modes**:
- **Manual Mode** (default): Use `/workflow:tools:task-generate`
- **Agent Mode** (`--agent`): Use `/workflow:tools:task-generate-agent`
- **CLI Execute Mode** (`--cli-execute`): Generate tasks with Codex execution commands
## 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, analyze structure, or gather context before Phase 1
3. **Parse Every Output**: Extract required data from each command/agent output for next phase
4. **Auto-Continue via TodoList**: Check TodoList status to execute next pending phase automatically
5. **Track Progress**: Update TodoWrite after every phase completion
6. **Agent Delegation**: Phase 3 uses cli-execution-agent for autonomous intelligent analysis
## 5-Phase Execution
### Phase 1: Session Discovery
**Command**: `SlashCommand(command="/workflow:session:start --auto \"[structured-task-description]\"")`
**Task Description Structure**:
```
GOAL: [Clear, concise objective]
SCOPE: [What's included/excluded]
CONTEXT: [Relevant background or constraints]
```
**Example**:
```
GOAL: Build JWT-based authentication system
SCOPE: User registration, login, token validation
CONTEXT: Existing user database schema, REST API endpoints
```
**Parse Output**:
- Extract: `SESSION_ID: WFS-[id]` (store as `sessionId`)
**Validation**:
- Session ID successfully extracted
- Session directory `.workflow/[sessionId]/` exists
**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
**Command**: `SlashCommand(command="/workflow:tools:context-gather --session [sessionId] \"[structured-task-description]\"")`
**Use Same Structured Description**: Pass the same structured format from Phase 1
**Input**: `sessionId` from Phase 1
**Parse Output**:
- Extract: context-package.json path (store as `contextPath`)
- Typical pattern: `.workflow/[sessionId]/.process/context-package.json`
**Validation**:
- Context package path extracted
- File exists and is valid JSON
**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
**Command**: `SlashCommand(command="/workflow:tools:concept-enhanced --session [sessionId] --context [contextPath]")`
**Input**: `sessionId` from Phase 1, `contextPath` from Phase 2
**Parse Output**:
- Extract: Execution status (success/failed)
- Verify: ANALYSIS_RESULTS.md file path
**Validation**:
- File `.workflow/[sessionId]/.process/ANALYSIS_RESULTS.md` exists
**TodoWrite**: Mark phase 3 completed, phase 3.5 in_progress
**After Phase 3**: Return to user showing Phase 3 results, then auto-continue to Phase 3.5
**Memory State Check**:
- Evaluate current context window usage and memory state
- If memory usage is high (>110K tokens or approaching context limits):
- **Command**: `SlashCommand(command="/compact")`
- This optimizes memory before proceeding to Phase 3.5
- Memory compaction is particularly important after analysis phase which may generate extensive documentation
- Ensures optimal performance and prevents context overflow
---
### Phase 3.5: Concept Clarification (Quality Gate)
**Command**: `SlashCommand(command="/workflow:concept-clarify --session [sessionId]")`
**Purpose**: Quality gate to verify and clarify analysis results before task generation
**Input**: `sessionId` from Phase 1
**Behavior**:
- Auto-detects plan mode (ANALYSIS_RESULTS.md exists)
- Interactively asks up to 5 targeted questions to resolve ambiguities
- Updates ANALYSIS_RESULTS.md with clarifications
- Pauses workflow for user input (breaks auto-continue temporarily)
**Parse Output**:
- Verify clarifications added to ANALYSIS_RESULTS.md
- Check recommendation: "PROCEED" or "ADDRESS_OUTSTANDING"
**Validation**:
- ANALYSIS_RESULTS.md updated with `## Clarifications` section
- All critical ambiguities resolved or documented as outstanding
**TodoWrite**: Mark phase 3.5 completed, phase 4 in_progress
**After Phase 3.5**: Return to user showing clarification summary, then auto-continue to Phase 4
**Skip Conditions**:
- If `/workflow:concept-clarify` reports "No critical ambiguities detected", automatically proceed to Phase 4
- User can skip by responding "skip" or "proceed" immediately
---
### Phase 4: Task Generation
**Relationship with Brainstorm Phase**:
- If brainstorm synthesis exists (synthesis-specification.md), Phase 3 analysis incorporates it as input
- **⚠️ User's original intent is ALWAYS primary**: New or refined user goals override synthesis recommendations
- **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
- **Intent priority**: Current user prompt > synthesis-specification.md > topic-framework.md
**Command Selection**:
- Manual: `SlashCommand(command="/workflow:tools:task-generate --session [sessionId]")`
- Agent: `SlashCommand(command="/workflow:tools:task-generate-agent --session [sessionId]")`
- CLI Execute: Add `--cli-execute` flag to either command
**Flag Combination**:
- `--cli-execute` alone: Manual task generation with CLI execution
- `--agent --cli-execute`: Agent task generation with CLI execution
**Command Examples**:
```bash
/workflow:plan <input>
# Manual with CLI execution
/workflow:tools:task-generate --session WFS-auth --cli-execute
# Agent with CLI execution
/workflow:tools:task-generate-agent --session WFS-auth --cli-execute
```
## Input Detection
- **Files**: `.md/.txt/.json/.yaml/.yml` → Reads content and extracts requirements
- **Issues**: `ISS-*`, `ISSUE-*`, `*-request-*` → Loads issue data and acceptance criteria
- **Text**: Everything else → Parses natural language requirements
**Input**: `sessionId` from Phase 1
## Core Workflow
**Validation**:
- `.workflow/[sessionId]/IMPL_PLAN.md` exists
- `.workflow/[sessionId]/.task/IMPL-*.json` exists (at least one)
- `.workflow/[sessionId]/TODO_LIST.md` exists
### Analysis & Planning Process
The command performs comprehensive analysis through:
**TodoWrite**: Mark phase 4 completed
**0. Pre-Analysis Documentation Check** ⚠️ FIRST STEP
- **Selective documentation loading based on task requirements**:
- **Always check**: `.workflow/docs/README.md` - System navigation and module index
- **For architecture tasks**: `.workflow/docs/architecture/system-design.md`, `module-map.md`
- **For specific modules**: `.workflow/docs/modules/[relevant-module]/overview.md`
- **For API tasks**: `.workflow/docs/api/unified-api.md`
- **Context-driven selection**: Only load documentation relevant to the specific task scope
- **Foundation for analysis**: Use relevant docs to understand affected components and dependencies
**Return to User**:
```
Planning complete for session: [sessionId]
Tasks generated: [count]
Plan: .workflow/[sessionId]/IMPL_PLAN.md
**1. Context Gathering & Intelligence Selection**
- Reading relevant CLAUDE.md documentation based on task requirements
- Automatic tool assignment based on complexity:
- **Simple tasks** (≤3 modules): Direct CLI tools with intelligent path navigation and multi-round analysis
```bash
# Analyze specific directory
cd "src/auth" && ~/.claude/scripts/gemini-wrapper -p "
PURPOSE: Analyze authentication patterns
TASK: Review auth implementation for security patterns
CONTEXT: Focus on JWT handling and user validation
EXPECTED: Security assessment and recommendations
RULES: Focus on security vulnerabilities and best practices
"
✅ Recommended Next Steps:
1. /workflow:action-plan-verify --session [sessionId] # Verify plan quality before execution
2. /workflow:status # Review task breakdown
3. /workflow:execute # Start implementation (after verification)
# Implement in specific directory
codex -C src/components --full-auto exec "
PURPOSE: Create user profile component
TASK: Build responsive profile component with form validation
CONTEXT: Use existing component patterns
EXPECTED: Complete component with tests
RULES: Follow existing component architecture
" -s danger-full-access
```
- **Complex tasks** (>3 modules): Specialized task agents with autonomous CLI tool orchestration and cross-module coordination
- Flow control integration with automatic tool selection
**2. Project Structure Analysis** ⚠️ CRITICAL PRE-PLANNING STEP
- **Documentation Context First**: Reference `.workflow/docs/` content from `/workflow:docs` command if available
- **Complexity assessment**: Count total saturated tasks
- **Decomposition strategy**: Flat (≤5) | Hierarchical (6-10) | Re-scope (>10)
- **Module boundaries**: Identify relationships and dependencies using existing documentation
- **File grouping**: Cohesive file sets and target_files generation
- **Pattern recognition**: Existing implementations and conventions
**3. Analysis Artifacts Generated**
- **ANALYSIS_RESULTS.md**: Context analysis, codebase structure, pattern identification, task decomposition
- **Context mapping**: Project structure, dependencies, cohesion groups
- **Implementation strategy**: Tool selection and execution approach
## Implementation Standards
### Context Management & Agent Execution
**Agent Context Loading** ⚠️ CRITICAL
The following pre_analysis steps are generated for agent execution:
```json
// Example pre_analysis steps generated by /workflow:plan for agent execution
"flow_control": {
"pre_analysis": [
{
"step": "load_planning_context",
"action": "Load plan-generated analysis and context",
"command": "bash(cat .workflow/WFS-[session]/.process/ANALYSIS_RESULTS.md 2>/dev/null || echo 'planning analysis not found')",
"output_to": "planning_context"
},
{
"step": "mcp_codebase_exploration",
"action": "Explore codebase structure and patterns using MCP tools",
"command": "mcp__code-index__find_files(pattern=\"[task_focus_patterns]\") && mcp__code-index__search_code_advanced(pattern=\"[relevant_patterns]\", file_pattern=\"[target_extensions]\")",
"output_to": "codebase_structure"
},
{
"step": "mcp_external_context",
"action": "Get external API examples and best practices",
"command": "mcp__exa__get_code_context_exa(query=\"[task_technology] [task_patterns]\", tokensNum=\"dynamic\")",
"output_to": "external_context"
},
{
"step": "load_dependencies",
"action": "Retrieve dependency task summaries",
"command": "bash(cat .workflow/WFS-[session]/.summaries/IMPL-[dependency_id]-summary.md 2>/dev/null || echo 'dependency summary not found')",
"output_to": "dependency_context"
},
{
"step": "load_documentation",
"action": "Retrieve relevant documentation based on task scope and requirements",
"command": "bash(cat .workflow/docs/README.md $(if [[ \"$TASK_TYPE\" == *\"architecture\"* ]]; then echo .workflow/docs/architecture/*.md; fi) $(if [[ \"$TASK_MODULES\" ]]; then for module in $TASK_MODULES; do echo .workflow/docs/modules/$module/*.md; done; fi) $(if [[ \"$TASK_TYPE\" == *\"api\"* ]]; then echo .workflow/docs/api/*.md; fi) CLAUDE.md README.md 2>/dev/null || echo 'documentation not found')",
"output_to": "doc_context"
},
{
"step": "gather_task_context",
"action": "Analyze task context and dependencies without implementation",
"command": "bash(cd \"[task_focus_paths]\" && ~/.claude/scripts/gemini-wrapper -p \"PURPOSE: Analyze task context and patterns TASK: Review existing patterns and dependencies for '[task_title]' CONTEXT: Task ID [task_id], Focus paths: [task_focus_paths], MCP findings: [codebase_structure] [external_context] EXPECTED: Pattern analysis, dependency mapping, and architectural insights RULES: Focus on understanding existing code patterns, no implementation\")",
"output_to": "task_context",
"on_error": "fail"
}
]
}
⚠️ Quality Gate: Consider running /workflow:action-plan-verify to catch issues early
```
**Context Accumulation Guidelines**:
Flow_control design should follow these principles:
1. **Structure Analysis**: Project hierarchy and patterns
2. **Dependency Mapping**: Previous task summaries → inheritance context
3. **Task Context Generation**: Combined analysis → task.context fields
4. **CLI Tool Analysis**: Use Gemini/Codex appropriately for pattern analysis when needed
## TodoWrite Pattern
**MCP Integration Principles**:
- **Code Index First**: Use `mcp__code-index__` for internal codebase exploration before external tools
- **Exa for Context**: Use `mcp__exa__get_code_context_exa` to supplement with external API patterns and examples
- **Automatic Fallback**: If MCP tools unavailable, workflow uses traditional bash/CLI tools
- **Enhanced Analysis**: MCP tools provide deeper codebase understanding and external best practices
```javascript
// Initialize (before Phase 1)
TodoWrite({todos: [
{"content": "Execute session discovery", "status": "in_progress", "activeForm": "Executing session discovery"},
{"content": "Execute context gathering", "status": "pending", "activeForm": "Executing context gathering"},
{"content": "Execute intelligent analysis", "status": "pending", "activeForm": "Executing intelligent analysis"},
{"content": "Execute concept clarification", "status": "pending", "activeForm": "Executing concept clarification"},
{"content": "Execute task generation", "status": "pending", "activeForm": "Executing task generation"}
]})
**Benefits of MCP Integration**:
- **Faster Analysis**: Direct codebase indexing vs. manual file searching
- **External Context**: Real-world API patterns and implementation examples
- **Pattern Recognition**: Advanced code pattern matching and similarity detection
- **Comprehensive Coverage**: Both internal code exploration and external best practice lookup
// After Phase 1
TodoWrite({todos: [
{"content": "Execute session discovery", "status": "completed", "activeForm": "Executing session discovery"},
{"content": "Execute context gathering", "status": "in_progress", "activeForm": "Executing context gathering"},
{"content": "Execute intelligent analysis", "status": "pending", "activeForm": "Executing intelligent analysis"},
{"content": "Execute concept clarification", "status": "pending", "activeForm": "Executing concept clarification"},
{"content": "Execute task generation", "status": "pending", "activeForm": "Executing task generation"}
]})
**Implementation Approach Planning**:
Each task's `flow_control.implementation_approach` defines execution strategy (planning phase):
1. **task_description**: Implementation strategy definition:
- Clear implementation goal to be executed later
- Planned reference to patterns from pre_analysis results
- Integration strategy with existing codebase
2. **modification_points**: Planned code modification targets:
- Specific code changes to be made during execution
- Planned use of parent task patterns via `[parent]` context
- Integration points with existing components via `[context]` from dependencies
3. **logic_flow**: Business logic execution plan:
- Step-by-step workflow to be implemented
- Planned data flow between components
- Integration points using `[inherited]` and `[shared]` context
4. **target_files**: Target file specifications for execution:
- `src/auth/login.ts:handleLogin:75-120` (planned function and line range)
- `src/middleware/auth.ts:validateToken` (planned function target)
- Must align with task's `context.focus_paths`
**Variable Reference System**:
- `[design]` - Results from pre_analysis steps
- `[parent]` - Context inherited from parent tasks
- `[context]` - Dependencies from related tasks
- `[inherited]` - Shared context from session
- `[shared]` - Global rules and patterns
**Content Sources**:
- Task summaries: `.workflow/WFS-[session]/.summaries/`
- Documentation: `.workflow/docs/`, `CLAUDE.md`, `README.md`, config files
- Analysis artifacts: `.workflow/WFS-[session]/.process/ANALYSIS_RESULTS.md`
- Dependency contexts: `.workflow/WFS-[session]/.task/IMPL-*.json`
### Task Decomposition Standards
**Rules**:
- **Maximum 10 tasks**: Hard limit - exceeding requires re-scoping
- **Function-based**: Complete functional units with related files (logic + UI + tests + config)
- **File cohesion**: Group tightly coupled components in same task
- **Hierarchy**: Flat (≤5 tasks) | Two-level (6-10 tasks) | Re-scope (>10 tasks)
### Session Management ⚠️ CRITICAL
- **⚡ FIRST ACTION**: Check for all `.workflow/.active-*` markers before any planning
- **Multiple sessions support**: Different Claude instances can have different active sessions
- **User selection**: If multiple active sessions found, prompt user to select which one to work with
- **Auto-session creation**: `WFS-[topic-slug]` only if no active session exists
- **Session continuity**: MUST use selected active session to maintain context
- **⚠️ Dependency context**: MUST read ALL previous task summary documents from selected session before planning
- **Session isolation**: Each session maintains independent context and state
**Task Patterns**:
- ✅ **Correct (Function-based)**: `IMPL-001: User authentication system` (models + routes + components + middleware + tests)
- ❌ **Wrong (File/step-based)**: `IMPL-001: Create database model`, `IMPL-002: Create API endpoint`
## Document Generation
**Workflow**: Identifier Creation → Folder Structure → IMPL_PLAN.md → .task/IMPL-NNN.json → TODO_LIST.md
**Always Created**:
- **IMPL_PLAN.md**: Requirements, task breakdown, success criteria
- **Session state**: Task references and paths
**Auto-Created (complexity > simple)**:
- **TODO_LIST.md**: Hierarchical progress tracking
- **.task/*.json**: Individual task definitions with flow_control
- **.process/ANALYSIS_RESULTS.md**: Analysis results and planning artifacts
**Document Structure**:
```
.workflow/WFS-[topic]/
├── IMPL_PLAN.md # Main planning document
├── TODO_LIST.md # Progress tracking (if complex)
├── .process/
│ └── ANALYSIS_RESULTS.md # Analysis results and planning artifacts
└── .task/
├── IMPL-001.json # Task definitions with flow_control
└── IMPL-002.json
// Continue pattern for Phase 2, 3, 3.5, 4...
```
### IMPL_PLAN.md Structure ⚠️ REQUIRED FORMAT
## Input Processing
**File Header** (required)
- **Identifier**: Unique project identifier and session ID, format WFS-[topic]
- **Source**: Input type, e.g. "User requirements analysis"
- **Analysis**: Analysis document reference
**Convert User Input to Structured Format**:
**Summary** (execution overview)
- Concise description of core requirements and objectives
- Technical direction and implementation approach
1. **Simple Text** → Structure it:
```
User: "Build authentication system"
**Context Analysis** (context analysis)
- **Project** - Project type and architectural patterns
- **Modules** - Involved modules and component list
- **Dependencies** - Dependency mapping and constraints
- **Patterns** - Identified code patterns and conventions
Structured:
GOAL: Build authentication system
SCOPE: Core authentication features
CONTEXT: New implementation
```
**Task Breakdown** (task decomposition)
- **Task Count** - Total task count and complexity level
- **Hierarchy** - Task organization structure (flat/hierarchical)
- **Dependencies** - Inter-task dependency graph
2. **Detailed Text** → Extract components:
```
User: "Add JWT authentication with email/password login and token refresh"
**Implementation Plan** (implementation plan)
- **Execution Strategy** - Execution strategy and methodology
- **Resource Requirements** - Required resources and tool selection
- **Success Criteria** - Success criteria and acceptance conditions
Structured:
GOAL: Implement JWT-based authentication
SCOPE: Email/password login, token generation, token refresh endpoints
CONTEXT: JWT token-based security, refresh token rotation
```
3. **File Reference** (e.g., `requirements.md`) → Read and structure:
- Read file content
- Extract goal, scope, requirements
- Format into structured description
## Reference Information
## Data Flow
### Task JSON Schema (5-Field Architecture)
Each task.json uses the workflow-architecture.md 5-field schema:
- **id**: IMPL-N[.M] format (max 2 levels)
- **title**: Descriptive task name
- **status**: pending|active|completed|blocked|container
- **meta**: { type, agent }
- **context**: { requirements, focus_paths, acceptance, parent, depends_on, inherited, shared_context }
- **flow_control**: { pre_analysis[], implementation_approach, target_files[] }
```
User Input (task description)
[Convert to Structured Format]
↓ Structured Description:
↓ GOAL: [objective]
↓ SCOPE: [boundaries]
↓ CONTEXT: [background]
Phase 1: session:start --auto "structured-description"
↓ Output: sessionId
↓ Session Memory: Previous tasks, context, artifacts
Phase 2: context-gather --session sessionId "structured-description"
↓ Input: sessionId + session memory + structured description
↓ Output: contextPath (context-package.json)
Phase 3: cli-execution-agent (Intelligent Analysis)
↓ Input: sessionId + contextPath + task description
↓ Agent discovers context, enhances prompt, executes with Gemini
↓ Output: ANALYSIS_RESULTS.md + execution log
Phase 3.5: concept-clarify --session sessionId (Quality Gate)
↓ Input: sessionId + ANALYSIS_RESULTS.md (auto-detected)
↓ Interactive: User answers clarification questions
↓ Output: Updated ANALYSIS_RESULTS.md with clarifications
Phase 4: task-generate[--agent] --session sessionId
↓ Input: sessionId + clarified ANALYSIS_RESULTS.md + session memory
↓ Output: IMPL_PLAN.md, task JSONs, TODO_LIST.md
Return summary to user
```
### File Structure Reference
**Architecture**: @~/.claude/workflows/workflow-architecture.md
**Session Memory Flow**: Each phase receives session ID, which provides access to:
- Previous task summaries
- Existing context and analysis
- Brainstorming artifacts
- Session-specific configuration
### Execution Integration
Documents created for `/workflow:execute`:
- **IMPL_PLAN.md**: Context loading and requirements
- **.task/*.json**: Agent implementation context
- **TODO_LIST.md**: Status tracking (container tasks with ▸, leaf tasks with checkboxes)
**Structured Description Benefits**:
- **Clarity**: Clear separation of goal, scope, and context
- **Consistency**: Same format across all phases
- **Traceability**: Easy to track what was requested
- **Precision**: Better context gathering and analysis
## Error Handling
- **Vague input**: Auto-reject ("fix it", "make better", etc.)
- **File not found**: Clear suggestions
- **>10 tasks**: Force re-scoping into iterations
## Planning-Only Constraint
This command creates implementation plans but does not execute them.
Use `/workflow:execute` for actual implementation.
- **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 to next phase
## Coordinator Checklist
✅ **Pre-Phase**: Convert user input to structured format (GOAL/SCOPE/CONTEXT)
✅ Initialize TodoWrite before any command (include Phase 3.5)
✅ Execute Phase 1 immediately with structured description
✅ 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, store in memory
✅ **Launch Phase 3 agent**: Build Task prompt with sessionId and contextPath
✅ Wait for agent completion, parse execution log path
✅ Verify ANALYSIS_RESULTS.md created by agent
✅ **Execute Phase 3.5**: Pass session ID to `/workflow:concept-clarify`
✅ Wait for user interaction (clarification Q&A)
✅ Verify ANALYSIS_RESULTS.md updated with clarifications
✅ Check recommendation: proceed if "PROCEED", otherwise alert user
✅ **Build Phase 4 command** based on flags:
- Base command: `/workflow:tools:task-generate` (or `-agent` if `--agent` flag)
- Add `--session [sessionId]`
- Add `--cli-execute` if flag present
✅ Pass session ID to Phase 4 command
✅ Verify all Phase 4 outputs
✅ Update TodoWrite after each phase
✅ After each phase, automatically continue to next phase based on TodoList status
## Structure Template Reference
**Minimal Structure**:
```
GOAL: [What to achieve]
SCOPE: [What's included]
CONTEXT: [Relevant info]
```
**Detailed Structure** (optional, when more context available):
```
GOAL: [Primary objective]
SCOPE: [Included features/components]
CONTEXT: [Existing system, constraints, dependencies]
REQUIREMENTS: [Specific technical requirements]
CONSTRAINTS: [Limitations or boundaries]
```
**Usage in Commands**:
```bash
# Phase 1
/workflow:session:start --auto "GOAL: Build authentication\nSCOPE: JWT, login, registration\nCONTEXT: REST API"
# Phase 2
/workflow:tools:context-gather --session WFS-123 "GOAL: Build authentication\nSCOPE: JWT, login, registration\nCONTEXT: REST API"
```

View File

@@ -1,419 +1,93 @@
---
name: resume
description: Intelligent workflow resumption with automatic interruption point detection
usage: /workflow:resume [options]
argument-hint: [--from TASK-ID] [--retry] [--skip TASK-ID] [--force]
examples:
- /workflow:resume
- /workflow:resume --from impl-1.2
- /workflow:resume --retry impl-1.1
- /workflow:resume --skip impl-2.1 --from impl-2.2
description: Intelligent workflow session resumption with automatic progress analysis
argument-hint: "session-id for workflow session to resume"
allowed-tools: SlashCommand(*), TodoWrite(*), Read(*), Bash(*)
---
# Workflow Resume Command (/workflow:resume)
## Overview
Intelligently resumes interrupted workflows with automatic detection of interruption points, context restoration, and flexible recovery strategies. Maintains execution continuity while adapting to various interruption scenarios.
## Core Principles
**File Structure:** @~/.claude/workflows/workflow-architecture.md
**Dependency Context Rules:**
- **For tasks with dependencies**: MUST read previous task summary documents before resuming
- **Context inheritance**: Use dependency summaries to maintain consistency and avoid duplicate work
# Sequential Workflow Resume Command
## Usage
```bash
/workflow:resume [--from TASK-ID] [--retry] [--skip TASK-ID] [--force]
/workflow:resume "<session-id>"
```
### Recovery Options
## Purpose
**Sequential command coordination for workflow resumption** by first analyzing current session status, then continuing execution with special resume context. This command orchestrates intelligent session resumption through two-step process.
#### Automatic Recovery (Default)
## Command Coordination Workflow
### Phase 1: Status Analysis
1. **Call status command**: Execute `/workflow:status` to analyze current session state
2. **Verify session information**: Check session ID, progress, and current task status
3. **Identify resume point**: Determine where workflow was interrupted
### Phase 2: Resume Execution
1. **Call execute with resume flag**: Execute `/workflow:execute --resume-session="{session-id}"`
2. **Pass session context**: Provide analyzed session information to execute command
3. **Direct agent execution**: Skip discovery phase, directly enter TodoWrite and agent execution
## Implementation Protocol
### Sequential Command Execution
```bash
/workflow:resume
```
**Behavior**:
- Auto-detects interruption point from task statuses
- Resumes from first incomplete task in dependency order
- Rebuilds agent context automatically
# Phase 1: Analyze current session status
SlashCommand(command="/workflow:status")
#### Targeted Recovery
```bash
/workflow:resume --from impl-1.2
```
**Behavior**:
- Resumes from specific task ID
- Validates dependencies are met
- Updates subsequent task readiness
#### Retry Failed Tasks
```bash
/workflow:resume --retry impl-1.1
```
**Behavior**:
- Retries previously failed task
- Analyzes failure context
- Applies enhanced error handling
#### Skip Blocked Tasks
```bash
/workflow:resume --skip impl-2.1 --from impl-2.2
```
**Behavior**:
- Marks specified task as skipped
- Continues execution from target task
- Adjusts dependency chain
#### Force Recovery
```bash
/workflow:resume --force
```
**Behavior**:
- Bypasses dependency validation
- Forces execution regardless of task states
- For emergency recovery scenarios
## Interruption Detection Logic
### Session State Analysis
```
Interruption Analysis:
├── Load active session from .workflow/.active-* marker
├── Read workflow-session.json for last execution state
├── Scan .task/ directory for task statuses
├── Analyze TODO_LIST.md progress markers
├── Check .summaries/ for completion records
└── Detect interruption point and failure patterns
# Phase 2: Resume execution with special flag
SlashCommand(command="/workflow:execute --resume-session=\"{session-id}\"")
```
**Detection Criteria**:
- **Normal Interruption**: Last task marked as "in_progress" without completion
- **Failure Interruption**: Task marked as "failed" with error context
- **Dependency Interruption**: Tasks blocked due to failed dependencies
- **Agent Interruption**: Agent execution terminated without status update
### Context Restoration Process
```json
{
"interruption_analysis": {
"session_id": "WFS-user-auth",
"last_active_task": "impl-1.2",
"interruption_type": "agent_timeout",
"interruption_time": "2025-09-15T14:30:00Z",
"affected_tasks": ["impl-1.2", "impl-1.3"],
"pending_dependencies": [],
"recovery_strategy": "retry_with_enhanced_context"
},
"execution_state": {
"completed_tasks": ["impl-1.1"],
"failed_tasks": [],
"in_progress_tasks": ["impl-1.2"],
"pending_tasks": ["impl-1.3", "impl-2.1"],
"skipped_tasks": [],
"blocked_tasks": []
}
}
```
## Resume Execution Flow
### 1. Session Discovery & Validation
```
Session Validation:
├── Verify active session exists (.workflow/.active-*)
├── Load session metadata (workflow-session.json)
├── Validate task files integrity (.task/*.json)
├── Check IMPL_PLAN.md consistency
└── Rebuild execution context
```
**Validation Checks**:
- **Session Integrity**: All required files present and readable
- **Task Consistency**: Task JSON files match TODO_LIST.md entries
- **Dependency Chain**: Task dependencies are logically consistent
- **Agent Context**: Previous agent outputs available in .summaries/
### 2. Interruption Point Analysis
```pseudo
function detect_interruption():
last_execution = read_session_state()
task_statuses = scan_task_files()
for task in dependency_order:
if task.status == "in_progress" and no_completion_summary():
return InterruptionPoint(task, "agent_interruption")
elif task.status == "failed":
return InterruptionPoint(task, "task_failure")
elif task.status == "pending" and dependencies_met(task):
return InterruptionPoint(task, "ready_to_execute")
return InterruptionPoint(null, "workflow_complete")
```
### 3. Context Reconstruction
**Agent Context Rebuilding**:
```bash
# Reconstruct complete agent context from interruption point
Task(subagent_type="code-developer",
prompt="[RESUME_CONTEXT] [FLOW_CONTROL] Resume impl-1.2: Implement JWT authentication
RESUMPTION CONTEXT:
- Interruption Type: agent_timeout
- Previous Attempt: 2025-09-15T14:30:00Z
- Completed Tasks: impl-1.1 (auth schema design)
- Current Task State: in_progress
- Recovery Strategy: retry_with_enhanced_context
- Interrupted at Flow Step: analyze_patterns
AVAILABLE CONTEXT:
- Completed Task Summaries: .workflow/WFS-user-auth/.summaries/impl-1.1-summary.md
- Previous Progress: Check .workflow/WFS-user-auth/TODO_LIST.md for partial completion
- Task Definition: .workflow/WFS-user-auth/.task/impl-1.2.json
- Session State: .workflow/WFS-user-auth/workflow-session.json
FLOW CONTROL RECOVERY:
Resume from step: analyze_patterns
$(cat .workflow/WFS-user-auth/.task/impl-1.2.json | jq -r '.flow_control.pre_analysis[] | "- Step: " + .step + " | Action: " + .action + " | Command: " + .command')
CONTEXT RECOVERY STEPS:
1. MANDATORY: Read previous task summary documents for all dependencies
2. Load dependency summaries from context.depends_on
3. Restore previous step outputs if available
4. Resume from interrupted flow control step
5. Execute remaining steps with accumulated context
6. Generate comprehensive summary with dependency outputs
Focus Paths: $(cat .workflow/WFS-user-auth/.task/impl-1.2.json | jq -r '.context.focus_paths[]')
Target Files: $(cat .workflow/WFS-user-auth/.task/impl-1.2.json | jq -r '.flow_control.target_files[]')
IMPORTANT:
1. Resume flow control from interrupted step with error recovery
2. Ensure context continuity through step chain
3. Create enhanced summary for dependent tasks
4. Update progress tracking upon successful completion",
description="Resume interrupted task with flow control step recovery")
```
### 4. Resume Coordination with TodoWrite
**Always First**: Update TodoWrite with resumption plan
```markdown
# Workflow Resume Coordination
*Session: WFS-[topic-slug] - RESUMPTION*
## Interruption Analysis
- **Interruption Point**: impl-1.2 (JWT implementation)
- **Interruption Type**: agent_timeout
- **Last Activity**: 2025-09-15T14:30:00Z
- **Recovery Strategy**: retry_with_enhanced_context
## Resume Execution Plan
- [x] **TASK-001**: [Completed] Design auth schema (impl-1.1)
- [ ] **TASK-002**: [RESUME] [Agent: code-developer] [FLOW_CONTROL] Implement JWT authentication (impl-1.2)
- [ ] **TASK-003**: [Pending] [Agent: code-review-agent] Review implementations (impl-1.3)
- [ ] **TASK-004**: Update session state and mark workflow complete
**Resume Markers**:
- [RESUME] = Task being resumed from interruption point
- [RETRY] = Task being retried after failure
- [SKIP] = Task marked as skipped in recovery
```
## Recovery Strategies
### Strategy Selection Matrix
| Interruption Type | Default Strategy | Alternative Options |
|------------------|------------------|-------------------|
| Agent Timeout | retry_with_enhanced_context | skip_and_continue, manual_review |
| Task Failure | analyze_and_retry | skip_task, force_continue |
| Dependency Block | resolve_dependencies | skip_blockers, manual_intervention |
| Context Loss | rebuild_full_context | partial_recovery, restart_from_checkpoint |
### Enhanced Context Recovery
```bash
# For agent timeout or context loss scenarios
1. Load all completion summaries
2. Analyze current codebase state
3. Compare against expected task progress
4. Rebuild comprehensive agent context
5. Resume with enhanced error handling
```
### Failure Analysis Recovery
```bash
# For task failure scenarios
1. Parse failure logs and error context
2. Identify root cause (code, dependency, logic)
3. Apply targeted recovery strategy
4. Retry with failure-specific enhancements
5. Escalate to manual review if repeated failures
```
### Dependency Resolution Recovery
```bash
# For dependency block scenarios
1. Analyze blocked dependency chain
2. Identify minimum viable completion set
3. Offer skip options for non-critical dependencies
4. Resume with adjusted execution plan
```
## Status Synchronization
### Task Status Updates
```json
// Before resumption
{
"id": "impl-1.2",
"status": "in_progress",
"execution": {
"attempts": 1,
"last_attempt": "2025-09-15T14:30:00Z",
"interruption_reason": "agent_timeout"
}
}
// After successful resumption
{
"id": "impl-1.2",
"status": "completed",
"execution": {
"attempts": 2,
"last_attempt": "2025-09-15T15:45:00Z",
"completion_time": "2025-09-15T15:45:00Z",
"recovery_strategy": "retry_with_enhanced_context"
}
}
```
### Session State Updates
```json
{
"current_phase": "EXECUTE",
"last_execute_run": "2025-09-15T15:45:00Z",
"resume_count": 1,
"interruption_history": [
### Progress Tracking
```javascript
TodoWrite({
todos: [
{
"timestamp": "2025-09-15T14:30:00Z",
"reason": "agent_timeout",
"affected_task": "impl-1.2",
"recovery_strategy": "retry_with_enhanced_context"
content: "Analyze current session status and progress",
status: "in_progress",
activeForm: "Analyzing session status"
},
{
content: "Resume workflow execution with session context",
status: "pending",
activeForm: "Resuming workflow execution"
}
]
}
});
```
## Error Handling & Recovery
## Resume Information Flow
### Detection Failures
```bash
# No active session
❌ No active workflow session found
→ Use: /workflow:session:start or /workflow:plan first
### Status Analysis Results
The `/workflow:status` command provides:
- **Session ID**: Current active session identifier
- **Current Progress**: Completed, in-progress, and pending tasks
- **Interruption Point**: Last executed task and next pending task
- **Session State**: Overall workflow status
# Corrupted session state
⚠️ Session state corrupted or inconsistent
→ Use: /workflow:resume --force for emergency recovery
### Execute Command Context
The special `--resume-session` flag tells `/workflow:execute`:
- **Skip Discovery**: Don't search for sessions, use provided session ID
- **Direct Execution**: Go straight to TodoWrite generation and agent launching
- **Context Restoration**: Use existing session state and summaries
- **Resume Point**: Continue from identified interruption point
# Task dependency conflicts
❌ Task dependency chain has conflicts
→ Use: /workflow:resume --skip [task-id] to bypass blockers
```
## Error Handling
### Recovery Failures
```bash
# Repeated task failures
❌ Task impl-1.2 failed 3 times
→ Manual Review Required: Check .summaries/impl-1.2-failure-analysis.md
→ Use: /workflow:resume --skip impl-1.2 to continue
### Session Validation Failures
- **Session not found**: Report missing session, suggest available sessions
- **Session inactive**: Recommend activating session first
- **Status command fails**: Retry once, then report analysis failure
# Agent context reconstruction failures
⚠️ Cannot rebuild agent context for impl-1.2
→ Use: /workflow:resume --force --from impl-1.3 to skip problematic task
### Execute Resumption Failures
- **No pending tasks**: Report workflow completion status
- **Execute command fails**: Report resumption failure, suggest manual intervention
# Critical dependency failures
❌ Critical dependency impl-1.1 failed validation
→ Use: /workflow:plan to regenerate tasks or manual intervention required
```
## Success Criteria
1. **Status analysis complete**: Session state properly analyzed and reported
2. **Execute command launched**: Resume execution started with proper context
3. **Agent coordination**: TodoWrite and agent execution initiated successfully
4. **Context preservation**: Session state and progress properly maintained
## Advanced Resume Features
### Step-Level Recovery
- **Flow Control Interruption Detection**: Identify which flow control step was interrupted
- **Step Context Restoration**: Restore accumulated context up to interruption point
- **Partial Step Recovery**: Resume from specific flow control step
- **Context Chain Validation**: Verify context continuity through step sequence
#### Step-Level Resume Options
```bash
# Resume from specific flow control step
/workflow:resume --from-step analyze_patterns impl-1.2
# Retry specific step with enhanced context
/workflow:resume --retry-step gather_context impl-1.2
# Skip failing step and continue with next
/workflow:resume --skip-step analyze_patterns impl-1.2
```
### Enhanced Context Recovery
- **Dependency Summary Integration**: Automatic loading of prerequisite task summaries
- **Variable State Restoration**: Restore step output variables from previous execution
- **Command State Recovery**: Detect partial command execution and resume appropriately
- **Error Context Preservation**: Maintain error information for improved retry strategies
### Checkpoint System
- **Step-Level Checkpoints**: Created after each successful flow control step
- **Context State Snapshots**: Save variable states at each checkpoint
- **Rollback Capability**: Option to resume from previous valid step checkpoint
### Parallel Task Recovery
```bash
# Resume multiple independent tasks simultaneously
/workflow:resume --parallel --from impl-2.1,impl-3.1
```
### Resume with Analysis Refresh
```bash
# Resume with updated project analysis
/workflow:resume --refresh-analysis --from impl-1.2
```
### Conditional Resume
```bash
# Resume only if specific conditions are met
/workflow:resume --if-dependencies-met --from impl-1.3
```
## Integration Points
### Automatic Behaviors
- **Interruption Detection**: Continuous monitoring during execution
- **Context Preservation**: Automatic context saving at task boundaries
- **Recovery Planning**: Dynamic strategy selection based on interruption type
- **Progress Restoration**: Seamless continuation of TodoWrite coordination
### Next Actions
```bash
# After successful resumption
/context # View updated workflow status
/workflow:execute # Continue normal execution
/workflow:review # Move to review phase when complete
```
## Resume Command Workflow Integration
```mermaid
graph TD
A[/workflow:resume] --> B[Detect Active Session]
B --> C[Analyze Interruption Point]
C --> D[Select Recovery Strategy]
D --> E[Rebuild Agent Context]
E --> F[Update TodoWrite Plan]
F --> G[Execute Resume Coordination]
G --> H[Monitor & Update Status]
H --> I[Continue Normal Workflow]
```
**System ensures**: Robust workflow continuity with intelligent interruption handling and seamless recovery integration.
---
*Sequential command coordination for workflow session resumption*

View File

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

View File

@@ -1,185 +1,105 @@
---
name: complete
description: Mark the active workflow session as complete and remove active flag
usage: /workflow:session:complete
examples:
- /workflow:session:complete
- /workflow:session:complete --detailed
---
# Complete Workflow Session (/workflow:session:complete)
## Purpose
## Overview
Mark the currently active workflow session as complete, update its status, and remove the active flag marker.
## Usage
```bash
/workflow:session:complete
/workflow:session:complete # Complete current active session
/workflow:session:complete --detailed # Show detailed completion summary
```
## Behavior
## Implementation Flow
### Session Completion Process
1. **Locate Active Session**: Find current active session via `.workflow/.active-*` marker file
2. **Update Session Status**: Modify `workflow-session.json` with completion data
3. **Remove Active Flag**: Delete `.workflow/.active-[session-name]` marker file
4. **Generate Summary**: Display completion report and statistics
### Status Updates
Updates `workflow-session.json` with:
- **status**: "completed"
- **completed_at**: Current timestamp
- **final_phase**: Current phase at completion
- **completion_type**: "manual" (distinguishes from automatic completion)
### State Preservation
Preserves all session data:
- Implementation plans and documents
- Task execution history
- Generated artifacts and reports
- Session configuration and metadata
## Completion Summary Display
### Session Overview
```
✅ Session Completed: WFS-oauth-integration
Description: Implement OAuth2 authentication
Created: 2025-09-07 14:30:00
Completed: 2025-09-12 16:45:00
Duration: 5 days, 2 hours, 15 minutes
Final Phase: IMPLEMENTATION
```
### Progress Summary
```
📊 Session Statistics:
- Tasks completed: 5/5 (100%)
- Files modified: 12
- Tests created: 8
- Documentation updated: 3 files
- Average task duration: 2.5 hours
```
### Generated Artifacts
```
📄 Session Artifacts:
✅ IMPL_PLAN.md (Complete implementation plan)
✅ TODO_LIST.md (Final task status)
✅ .task/ (5 completed task files)
📊 reports/ (Session reports available)
```
### Archive Information
```
🗂️ Session Archive:
Directory: .workflow/WFS-oauth-integration/
Status: Completed and archived
Access: Use /context WFS-oauth-integration for review
```
## No Active Session
If no active session exists:
```
⚠️ No Active Session to Complete
Available Options:
- View all sessions: /workflow:session:list
- Start new session: /workflow:session:start "task description"
- Resume paused session: /workflow:session:resume
```
## Next Steps Suggestions
After completion, displays contextual actions:
```
🎯 What's Next:
- View session archive: /context WFS-oauth-integration
- Start related session: /workflow:session:start "build on OAuth work"
- Review all sessions: /workflow:session:list
- Create project report: /workflow/report
```
## Error Handling
### Common Error Scenarios
- **No active session**: Clear message with alternatives
- **Corrupted session state**: Validates before completion, offers recovery
- **File system issues**: Handles permissions and access problems
- **Incomplete tasks**: Warns about unfinished work, allows forced completion
### Validation Checks
Before completing, verifies:
- Session directory exists and is accessible
- `workflow-session.json` is valid and readable
- Marker file exists and matches session
- No critical errors in session state
### Forced Completion
For problematic sessions:
### Step 1: Find Active Session
```bash
# Option to force completion despite issues
/workflow:session:complete --force
ls .workflow/.active-* 2>/dev/null | head -1
```
## Integration with Workflow System
### Session Lifecycle
Completes the session workflow:
- INIT → PLAN → IMPLEMENT → **COMPLETE**
- Maintains session history for reference
- Preserves all artifacts and documentation
### TodoWrite Integration
- Synchronizes final TODO state
- Marks all remaining tasks as archived
- Preserves task history in session directory
### Context System
- Session remains accessible via `/context <session-id>`
- All documents and reports remain available
- Can be referenced for future sessions
## Command Variations
### Basic Completion
### Step 2: Get Session Name
```bash
/workflow:session:complete
basename .workflow/.active-WFS-session-name | sed 's/^\.active-//'
```
### With Summary Options
### Step 3: Update Session Status
```bash
/workflow:session:complete --detailed # Show detailed statistics
/workflow:session:complete --quiet # Minimal output
/workflow:session:complete --force # Force completion despite issues
jq '.status = "completed"' .workflow/WFS-session/workflow-session.json > temp.json
mv temp.json .workflow/WFS-session/workflow-session.json
```
## Session State After Completion
### Directory Structure Preserved
```
.workflow/WFS-[session-name]/
├── workflow-session.json # Updated with completion data
├── IMPL_PLAN.md # Preserved
├── TODO_LIST.md # Final state preserved
├── .task/ # All task files preserved
└── reports/ # Generated reports preserved
### Step 4: Add Completion Timestamp
```bash
jq '.completed_at = "'$(date -u +%Y-%m-%dT%H:%M:%SZ)'"' .workflow/WFS-session/workflow-session.json > temp.json
mv temp.json .workflow/WFS-session/workflow-session.json
```
### Session JSON Example
```json
{
"id": "WFS-oauth-integration",
"description": "Implement OAuth2 authentication",
"status": "completed",
"created_at": "2025-09-07T14:30:00Z",
"completed_at": "2025-09-12T16:45:00Z",
"completion_type": "manual",
"final_phase": "IMPLEMENTATION",
"tasks_completed": 5,
"tasks_total": 5
}
### Step 5: Count Final Statistics
```bash
find .workflow/WFS-session/.task/ -name "*.json" -type f 2>/dev/null | wc -l
find .workflow/WFS-session/.summaries/ -name "*.md" -type f 2>/dev/null | wc -l
```
---
### Step 6: Remove Active Marker
```bash
rm .workflow/.active-WFS-session-name
```
**Result**: Current active session is marked as complete, archived, and no longer active. All session data is preserved for future reference.
## Simple Bash Commands
### Basic Operations
- **Find active session**: `find .workflow/ -name ".active-*" -type f`
- **Get session name**: `basename marker | sed 's/^\.active-//'`
- **Update status**: `jq '.status = "completed"' session.json > temp.json`
- **Add timestamp**: `jq '.completed_at = "'$(date -u +%Y-%m-%dT%H:%M:%SZ)'"'`
- **Count tasks**: `find .task/ -name "*.json" -type f | wc -l`
- **Count completed**: `find .summaries/ -name "*.md" -type f 2>/dev/null | wc -l`
- **Remove marker**: `rm .workflow/.active-session`
### Completion Result
```
Session WFS-user-auth completed
- Status: completed
- Started: 2025-09-15T10:00:00Z
- Completed: 2025-09-15T16:30:00Z
- Duration: 6h 30m
- Total tasks: 8
- Completed tasks: 8
- Success rate: 100%
```
### Detailed Summary (--detailed flag)
```
Session Completion Summary:
├── Session: WFS-user-auth
├── Project: User authentication system
├── Total time: 6h 30m
├── Tasks completed: 8/8 (100%)
├── Files generated: 24 files
├── Summaries created: 8 summaries
├── Status: All tasks completed successfully
└── Location: .workflow/WFS-user-auth/
```
### Error Handling
```bash
# No active session
find .workflow/ -name ".active-*" -type f 2>/dev/null || echo "No active session found"
# Incomplete tasks
task_count=$(find .task/ -name "*.json" -type f | wc -l)
summary_count=$(find .summaries/ -name "*.md" -type f 2>/dev/null | wc -l)
test $task_count -eq $summary_count || echo "Warning: Not all tasks completed"
```
## Related Commands
- `/workflow:session:list` - View all sessions including completed
- `/workflow:session:start` - Start new session
- `/workflow:status` - Check completion status before completing

View File

@@ -1,83 +1,104 @@
---
name: list
description: List all workflow sessions with status
usage: /workflow:session:list
examples:
- /workflow:session:list
---
# List Workflow Sessions (/workflow/session/list)
# List Workflow Sessions (/workflow:session:list)
## Purpose
## Overview
Display all workflow sessions with their current status, progress, and metadata.
## Usage
```bash
/workflow/session/list
/workflow:session:list # Show all sessions with status
```
## Output Format
## Implementation Flow
### Active Session (Highlighted)
### Step 1: Find All Sessions
```bash
ls .workflow/WFS-* 2>/dev/null
```
### Step 2: Check Active Session
```bash
ls .workflow/.active-* 2>/dev/null | head -1
```
### Step 3: Read Session Metadata
```bash
jq -r '.session_id, .status, .project' .workflow/WFS-session/workflow-session.json
```
### Step 4: Count Task Progress
```bash
find .workflow/WFS-session/.task/ -name "*.json" -type f 2>/dev/null | wc -l
find .workflow/WFS-session/.summaries/ -name "*.md" -type f 2>/dev/null | wc -l
```
### Step 5: Get Creation Time
```bash
jq -r '.created_at // "unknown"' .workflow/WFS-session/workflow-session.json
```
## Simple Bash Commands
### Basic Operations
- **List sessions**: `find .workflow/ -maxdepth 1 -type d -name "WFS-*"`
- **Find active**: `find .workflow/ -name ".active-*" -type f`
- **Read session data**: `jq -r '.session_id, .status' session.json`
- **Count tasks**: `find .task/ -name "*.json" -type f | wc -l`
- **Count completed**: `find .summaries/ -name "*.md" -type f 2>/dev/null | wc -l`
- **Get timestamp**: `jq -r '.created_at' session.json`
## Simple Output Format
### Session List Display
```
Workflow Sessions:
✅ WFS-oauth-integration (ACTIVE)
Description: Implement OAuth2 authentication
Phase: IMPLEMENTATION
Created: 2025-09-07 14:30:00
Directory: .workflow/WFS-oauth-integration/
Progress: 3/5 tasks completed
Project: OAuth2 authentication system
Status: active
Progress: 3/8 tasks completed
Created: 2025-09-15T10:30:00Z
⏸️ WFS-user-profile (PAUSED)
Project: User profile management
Status: paused
Progress: 1/5 tasks completed
Created: 2025-09-14T14:15:00Z
📁 WFS-database-migration (COMPLETED)
Project: Database schema migration
Status: completed
Progress: 4/4 tasks completed
Created: 2025-09-13T09:00:00Z
Total: 3 sessions (1 active, 1 paused, 1 completed)
```
### Paused Sessions
```
⏸️ WFS-user-profile (PAUSED)
Description: Build user profile management
Phase: PLANNING
Created: 2025-09-06 10:15:00
Last active: 2025-09-07 09:20:00
Directory: .workflow/WFS-user-profile/
### Status Indicators
- **✅**: Active session
- **⏸️**: Paused session
- **📁**: Completed session
- **❌**: Error/corrupted session
### Quick Commands
```bash
# Count all sessions
ls .workflow/WFS-* | wc -l
# Show only active
ls .workflow/.active-* | basename | sed 's/^\.active-//'
# Show recent sessions
ls -t .workflow/WFS-*/workflow-session.json | head -3
```
### Completed Sessions
```
✅ WFS-bug-fix-123 (COMPLETED)
Description: Fix login security vulnerability
Completed: 2025-09-05 16:45:00
Directory: .workflow/WFS-bug-fix-123/
```
## Status Indicators
- **✅ ACTIVE**: Currently active session (has marker file)
- **⏸️ PAUSED**: Session paused, can be resumed
- **✅ COMPLETED**: Session finished successfully
- **❌ FAILED**: Session ended with errors
- **🔄 INTERRUPTED**: Session was interrupted unexpectedly
## Session Discovery
Searches for:
- `.workflow/WFS-*` directories
- Reads `workflow-session.json` from each
- Checks for `.active-*` marker files
- Sorts by last activity date
## Quick Actions
For each session, shows available actions:
- **Resume**: `/workflow/session/resume` (paused sessions)
- **Switch**: `/workflow/session/switch <session-id>`
- **View**: `/context <session-id>`
## Empty State
If no sessions exist:
```
No workflow sessions found.
Create a new session:
/workflow/session/start "your task description"
```
## Error Handling
- **Directory access**: Handles permission issues
- **Corrupted sessions**: Shows warning but continues listing
- **Missing metadata**: Shows partial info with warnings
---
**Result**: Complete overview of all workflow sessions and their current state
## Related Commands
- `/workflow:session:start` - Create new session
- `/workflow:session:switch` - Switch to different session
- `/workflow:session:status` - Detailed session info

View File

@@ -1,65 +0,0 @@
---
name: pause
description: Pause the active workflow session
usage: /workflow:session:pause
---
# Pause Workflow Session (/workflow:session:pause)
## Purpose
Pause the currently active workflow session, saving all state for later resumption.
## Usage
```bash
/workflow:session:pause
```
## Behavior
### State Preservation
- Saves complete session state to `workflow-session.json`
- Preserves context across all phases
- Maintains TodoWrite synchronization
- Creates checkpoint timestamp
### Active Session Handling
- Removes `.workflow/.active-[session-name]` marker file
- Session becomes paused (no longer active)
- Other commands will work in temporary mode
### Context Saved
- Current phase and progress
- Generated documents and artifacts
- Task execution state
- Agent context and history
## Status Update
Updates session status to:
- **status**: "paused"
- **paused_at**: Current timestamp
- **resumable**: true
## Output
Displays:
- Session ID that was paused
- Current phase and progress
- Resume instructions
- Session directory location
## Resume Instructions
Shows how to resume:
```bash
/workflow:session:resume # Resume this session
/workflow:session:list # View all sessions
/workflow:session:switch <id> # Switch to different session
```
## Error Handling
- **No active session**: Clear message that no session is active
- **Save errors**: Handles file system issues gracefully
- **State corruption**: Validates session state before saving
---
**Result**: Active session is safely paused and can be resumed later

View File

@@ -1,82 +1,72 @@
---
name: resume
description: Resume the most recently paused workflow session
usage: /workflow:session:resume
---
# Resume Workflow Session (/workflow:session:resume)
## Purpose
## Overview
Resume the most recently paused workflow session, restoring all context and state.
## Usage
```bash
/workflow:session:resume
/workflow:session:resume # Resume most recent paused session
```
## Resume Logic
## Implementation Flow
### Session Detection
- Finds most recently paused session
- Loads session state from `workflow-session.json`
- Validates session integrity
### Step 1: Find Paused Sessions
```bash
ls .workflow/WFS-* 2>/dev/null
```
### State Restoration
- Creates `.workflow/.active-[session-name]` marker file
- Loads current phase from session state
- Restores appropriate agent context
- Continues from exact interruption point
### Step 2: Check Session Status
```bash
jq -r '.status' .workflow/WFS-session/workflow-session.json
```
### Context Continuity
- Restores TodoWrite state
- Loads phase-specific context
- Maintains full audit trail
- Preserves document references
### Step 3: Find Most Recent Paused
```bash
ls -t .workflow/WFS-*/workflow-session.json | head -1
```
## Phase-Specific Resume
### Step 4: Update Session Status
```bash
jq '.status = "active"' .workflow/WFS-session/workflow-session.json > temp.json
mv temp.json .workflow/WFS-session/workflow-session.json
```
### Planning Phase
- Resumes planning document generation
- Maintains requirement analysis progress
- Continues task breakdown where left off
### Step 5: Add Resume Timestamp
```bash
jq '.resumed_at = "'$(date -u +%Y-%m-%dT%H:%M:%SZ)'"' .workflow/WFS-session/workflow-session.json > temp.json
mv temp.json .workflow/WFS-session/workflow-session.json
```
### Implementation Phase
- Resumes task execution state
- Maintains agent coordination
- Continues from current task
### Step 6: Create Active Marker
```bash
touch .workflow/.active-WFS-session-name
```
### Review Phase
- Resumes validation process
- Maintains quality checks
- Continues review workflow
## Simple Bash Commands
## Session Validation
Before resuming, validates:
- Session directory exists
- Required documents present
- State consistency
- No corruption detected
### Basic Operations
- **List sessions**: `ls .workflow/WFS-*`
- **Check status**: `jq -r '.status' session.json`
- **Find recent**: `ls -t .workflow/*/workflow-session.json | head -1`
- **Update status**: `jq '.status = "active"' session.json > temp.json`
- **Add timestamp**: `jq '.resumed_at = "'$(date -u +%Y-%m-%dT%H:%M:%SZ)'"'`
- **Create marker**: `touch .workflow/.active-session`
## Output
Displays:
- Resumed session ID and description
- Current phase and progress
- Available next actions
- Session directory location
### Resume Result
```
Session WFS-user-auth resumed
- Status: active
- Paused at: 2025-09-15T14:30:00Z
- Resumed at: 2025-09-15T15:45:00Z
- Ready for: /workflow:execute
```
## Error Handling
- **No paused sessions**: Lists available sessions to switch to
- **Corrupted session**: Attempts recovery or suggests manual repair
- **Directory missing**: Clear error with recovery options
- **State inconsistency**: Validates and repairs where possible
## Next Actions
After resuming:
- Use `/context` to view current session state
- Continue with phase-appropriate commands
- Check TodoWrite status for next steps
---
**Result**: Previously paused session is now active and ready to continue
## Related Commands
- `/workflow:session:pause` - Pause current session
- `/workflow:execute` - Continue workflow execution
- `/workflow:session:list` - Show all sessions

View File

@@ -1,69 +1,220 @@
---
name: start
description: Start a new workflow session
usage: /workflow:session:start "task description"
description: Discover existing sessions or start a new workflow session with intelligent session management
argument-hint: [--auto|--new] [optional: task description for new session]
examples:
- /workflow:session:start "implement OAuth2 authentication"
- /workflow:session:start "fix login bug"
- /workflow:session:start
- /workflow:session:start --auto "implement OAuth2 authentication"
- /workflow:session:start --new "fix login bug"
---
# Start Workflow Session (/workflow:session:start)
## Purpose
Initialize a new workflow session for the given task description.
## Overview
Manages workflow sessions with three operation modes: discovery (manual), auto (intelligent), and force-new.
## Usage
## Mode 1: Discovery Mode (Default)
### Usage
```bash
/workflow/session/start "task description"
/workflow:session:start
```
## Automatic Behaviors
### Session Creation
- Generates unique session ID: WFS-[topic-slug]
- Creates `.workflow/.active-[session-name]` marker file
- Deactivates any existing active session
### Complexity Detection
Automatically determines complexity based on task description:
- **Simple**: Single module, <5 tasks
- **Medium**: Multiple modules, 5-15 tasks
- **Complex**: Large scope, >15 tasks
### Directory Structure
Creates session directory with:
```
.workflow/WFS-[topic-slug]/
├── workflow-session.json # Session metadata
├── IMPL_PLAN.md # Initial planning template
├── .task/ # Task management
└── reports/ # Report generation
### Step 1: Check Active Sessions
```bash
bash(ls .workflow/.active-* 2>/dev/null)
```
### Phase Initialization
- **Simple**: Ready for direct implementation
- **Medium/Complex**: Ready for planning phase
### Step 2: List All Sessions
```bash
bash(ls -1 .workflow/WFS-* 2>/dev/null | head -5)
```
## Session State
Creates `workflow-session.json` with:
- Session ID and description
- Current phase: INIT → PLAN
- Document tracking
- Task system configuration
- Active marker reference
### Step 3: Display Session Metadata
```bash
bash(cat .workflow/WFS-promptmaster-platform/workflow-session.json)
```
## Next Steps
After starting a session:
- Use `/workflow/plan` to create implementation plan
- Use `/workflow/execute` to begin implementation
- Use `/context` to view session status
### Step 4: User Decision
Present session information and wait for user to select or create session.
## Error Handling
- **Duplicate session**: Warns if similar session exists
- **Invalid description**: Prompts for valid task description
- **Directory conflicts**: Handles existing directories gracefully
**Output**: `SESSION_ID: WFS-[user-selected-id]`
---
## Mode 2: Auto Mode (Intelligent)
**Creates**: New active workflow session ready for planning and execution
### Usage
```bash
/workflow:session:start --auto "task description"
```
### Step 1: Check Active Sessions Count
```bash
bash(ls .workflow/.active-* 2>/dev/null | wc -l)
```
### Step 2a: No Active Sessions → Create New
```bash
# Generate session slug
bash(echo "implement OAuth2 auth" | sed 's/[^a-zA-Z0-9]/-/g' | tr '[:upper:]' '[:lower:]' | cut -c1-50)
# Create directory structure
bash(mkdir -p .workflow/WFS-implement-oauth2-auth/.process)
bash(mkdir -p .workflow/WFS-implement-oauth2-auth/.task)
bash(mkdir -p .workflow/WFS-implement-oauth2-auth/.summaries)
# Create metadata
bash(echo '{"session_id":"WFS-implement-oauth2-auth","project":"implement OAuth2 auth","status":"planning"}' > .workflow/WFS-implement-oauth2-auth/workflow-session.json)
# Mark as active
bash(touch .workflow/.active-WFS-implement-oauth2-auth)
```
**Output**: `SESSION_ID: WFS-implement-oauth2-auth`
### Step 2b: Single Active Session → Check Relevance
```bash
# Extract session ID
bash(ls .workflow/.active-* 2>/dev/null | head -1 | xargs basename | sed 's/^\.active-//')
# Read project name from metadata
bash(cat .workflow/WFS-promptmaster-platform/workflow-session.json | grep -o '"project":"[^"]*"' | cut -d'"' -f4)
# Check keyword match (manual comparison)
# If task contains project keywords → Reuse session
# If task unrelated → Create new session (use Step 2a)
```
**Output (reuse)**: `SESSION_ID: WFS-promptmaster-platform`
**Output (new)**: `SESSION_ID: WFS-[new-slug]`
### Step 2c: Multiple Active Sessions → Use First
```bash
# Get first active session
bash(ls .workflow/.active-* 2>/dev/null | head -1 | xargs basename | sed 's/^\.active-//')
# Output warning and session ID
# WARNING: Multiple active sessions detected
# SESSION_ID: WFS-first-session
```
## Mode 3: Force New Mode
### Usage
```bash
/workflow:session:start --new "task description"
```
### Step 1: Generate Unique Session Slug
```bash
# Convert to slug
bash(echo "fix login bug" | sed 's/[^a-zA-Z0-9]/-/g' | tr '[:upper:]' '[:lower:]' | cut -c1-50)
# Check if exists, add counter if needed
bash(ls .workflow/WFS-fix-login-bug 2>/dev/null && echo "WFS-fix-login-bug-2" || echo "WFS-fix-login-bug")
```
### Step 2: Create Session Structure
```bash
bash(mkdir -p .workflow/WFS-fix-login-bug/.process)
bash(mkdir -p .workflow/WFS-fix-login-bug/.task)
bash(mkdir -p .workflow/WFS-fix-login-bug/.summaries)
```
### Step 3: Create Metadata
```bash
bash(echo '{"session_id":"WFS-fix-login-bug","project":"fix login bug","status":"planning"}' > .workflow/WFS-fix-login-bug/workflow-session.json)
```
### Step 4: Mark Active and Clean Old Markers
```bash
bash(rm .workflow/.active-* 2>/dev/null)
bash(touch .workflow/.active-WFS-fix-login-bug)
```
**Output**: `SESSION_ID: WFS-fix-login-bug`
## Output Format Specification
### Success
```
SESSION_ID: WFS-session-slug
```
### Error
```
ERROR: --auto mode requires task description
ERROR: Failed to create session directory
```
### Analysis (Auto Mode)
```
ANALYSIS: Task relevance = high
DECISION: Reusing existing session
SESSION_ID: WFS-promptmaster-platform
```
## Command Integration
### For /workflow:plan (Use Auto Mode)
```bash
SlashCommand(command="/workflow:session:start --auto \"implement OAuth2 authentication\"")
# Parse session ID from output
grep "^SESSION_ID:" | awk '{print $2}'
```
### For Interactive Workflows (Use Discovery Mode)
```bash
SlashCommand(command="/workflow:session:start")
```
### For New Isolated Work (Use Force New Mode)
```bash
SlashCommand(command="/workflow:session:start --new \"experimental feature\"")
```
## Simple Bash Commands
### Basic Operations
```bash
# Check active sessions
bash(ls .workflow/.active-*)
# List all sessions
bash(ls .workflow/WFS-*)
# Read session metadata
bash(cat .workflow/WFS-[session-id]/workflow-session.json)
# Create session directories
bash(mkdir -p .workflow/WFS-[session-id]/.process)
bash(mkdir -p .workflow/WFS-[session-id]/.task)
bash(mkdir -p .workflow/WFS-[session-id]/.summaries)
# Mark session as active
bash(touch .workflow/.active-WFS-[session-id])
# Clean active markers
bash(rm .workflow/.active-*)
```
### Generate Session Slug
```bash
bash(echo "Task Description" | sed 's/[^a-zA-Z0-9]/-/g' | tr '[:upper:]' '[:lower:]' | cut -c1-50)
```
### Create Metadata JSON
```bash
bash(echo '{"session_id":"WFS-test","project":"test project","status":"planning"}' > .workflow/WFS-test/workflow-session.json)
```
## Session ID Format
- Pattern: `WFS-[lowercase-slug]`
- Characters: `a-z`, `0-9`, `-` only
- Max length: 50 characters
- Uniqueness: Add numeric suffix if collision (`WFS-auth-2`, `WFS-auth-3`)
## Related Commands
- `/workflow:plan` - Uses `--auto` mode for session management
- `/workflow:execute` - Uses discovery mode for session selection
- `/workflow:session:status` - Shows detailed session information

View File

@@ -1,112 +0,0 @@
---
name: status
description: Show detailed status of active workflow session
usage: /workflow:session:status
---
# Workflow Session Status (/workflow:session:status)
## Purpose
Display comprehensive status information for the currently active workflow session.
## Usage
```bash
/workflow:session:status
```
## Status Display
### Active Session Overview
```
🚀 Active Session: WFS-oauth-integration
Description: Implement OAuth2 authentication
Created: 2025-09-07 14:30:00
Last updated: 2025-09-08 09:15:00
Directory: .workflow/WFS-oauth-integration/
```
### Phase Information
```
📋 Current Phase: IMPLEMENTATION
Status: In Progress
Started: 2025-09-07 15:00:00
Progress: 60% complete
Completed Phases: ✅ INIT ✅ PLAN
Current Phase: 🔄 IMPLEMENT
Pending Phases: ⏳ REVIEW
```
### Task Progress
```
📝 Task Status (3/5 completed):
✅ IMPL-001: Setup OAuth2 client configuration
✅ IMPL-002: Implement Google OAuth integration
🔄 IMPL-003: Add Facebook OAuth support (IN PROGRESS)
⏳ IMPL-004: Create user profile mapping
⏳ IMPL-005: Add OAuth security validation
```
### Document Status
```
📄 Generated Documents:
✅ IMPL_PLAN.md (Complete)
✅ TODO_LIST.md (Auto-updated)
📝 .task/IMPL-*.json (5 tasks)
📊 reports/ (Ready for generation)
```
### Session Health
```
🔍 Session Health: ✅ HEALTHY
- Marker file: ✅ Present
- Directory: ✅ Accessible
- State file: ✅ Valid
- Task files: ✅ Consistent
- Last checkpoint: 2025-09-08 09:10:00
```
## No Active Session
If no session is active:
```
⚠️ No Active Session
Available Sessions:
- WFS-user-profile (PAUSED) - Use: /workflow/session/switch WFS-user-profile
- WFS-bug-fix-123 (COMPLETED) - Use: /context WFS-bug-fix-123
Create New Session:
/workflow:session:start "your task description"
```
## Quick Actions
Shows contextual next steps:
```
🎯 Suggested Actions:
- Continue current task: /task/execute IMPL-003
- View full context: /context
- Execute workflow: /workflow/execute
- Plan next steps: /workflow/plan
```
## Error Detection
Identifies common issues:
- Missing marker file
- Corrupted session state
- Inconsistent task files
- Directory permission problems
## Performance Info
```
⚡ Session Performance:
- Tasks completed: 3/5 (60%)
- Average task time: 2.5 hours
- Estimated completion: 2025-09-08 14:00:00
- Files modified: 12
- Tests passing: 98%
```
---
**Result**: Comprehensive view of active session status and health

View File

@@ -1,85 +0,0 @@
---
name: switch
description: Switch to a different workflow session
usage: /workflow:session:switch <session-id>
examples:
- /workflow:session:switch WFS-oauth-integration
- /workflow:session:switch WFS-user-profile
---
# Switch Workflow Session (/workflow:session:switch)
## Purpose
Switch the active session to a different workflow session.
## Usage
```bash
/workflow:session:switch <session-id>
```
## Session Switching Process
### Validation
- Verifies target session exists
- Checks session directory integrity
- Validates session state
### Active Session Handling
- Automatically pauses currently active session
- Saves current session state
- Removes current `.active-*` marker file
### Target Session Activation
- Creates `.active-[target-session]` marker file
- Updates session status to "active"
- Loads session context and state
### State Transition
```
Current Active → Paused (auto-saved)
Target Session → Active (context loaded)
```
## Context Loading
After switching:
- Loads target session's phase and progress
- Restores appropriate agent context
- Makes session's documents available
- Updates TodoWrite to target session's tasks
## Output
Displays:
- Previous active session (now paused)
- New active session details
- Current phase and progress
- Available next actions
## Session ID Formats
Accepts various formats:
- Full ID: `WFS-oauth-integration`
- Partial match: `oauth` (if unique)
- Index from list: `1` (from session list order)
## Error Handling
- **Session not found**: Lists available sessions
- **Invalid session**: Shows session validation errors
- **Already active**: No-op with confirmation message
- **Switch failure**: Maintains current session, shows error
## Quick Reference
After switching, shows:
- Session description and phase
- Recent activity and progress
- Suggested next commands
- Directory location
## Integration
Commands executed after switch will:
- Use new active session context
- Save artifacts to new session directory
- Update new session's state and progress
---
**Result**: Different session is now active and ready for work

View File

@@ -1,13 +1,7 @@
---
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
argument-hint: "[optional: task-id]"
---
# Workflow Status Command (/workflow:status)
@@ -15,244 +9,116 @@ examples:
## 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
/workflow:status # Show current workflow overview
/workflow:status impl-1 # Show specific task details
/workflow:status --validate # Validate workflow integrity
```
Generates current workflow overview:
## Implementation Flow
### Step 1: Find Active Session
```bash
find .workflow/ -name ".active-*" -type f 2>/dev/null | head -1
```
### Step 2: Load Session Data
```bash
cat .workflow/WFS-session/workflow-session.json
```
### Step 3: Scan Task Files
```bash
find .workflow/WFS-session/.task/ -name "*.json" -type f 2>/dev/null
```
### Step 4: Generate Task Status
```bash
cat .workflow/WFS-session/.task/impl-1.json | jq -r '.status'
```
### Step 5: Count Task Progress
```bash
find .workflow/WFS-session/.task/ -name "*.json" -type f | wc -l
find .workflow/WFS-session/.summaries/ -name "*.md" -type f 2>/dev/null | wc -l
```
### Step 6: Display Overview
```markdown
# Workflow Overview
**Session**: WFS-user-auth
**Phase**: IMPLEMENT
**Type**: medium
**Session**: WFS-session-name
**Progress**: 3/8 tasks completed
## Active Tasks
- [⚠️] impl-1: Build authentication module (code-developer)
- [⚠️] impl-2: Setup user management (code-developer)
- [⚠️] impl-1: Current task in progress
- [ ] impl-2: Next pending task
## Completed Tasks
- [✅] impl-0: Project setup
## Stats
- **Total**: 8 tasks
- **Completed**: 3
- **Active**: 2
- **Remaining**: 3
- [✅] impl-0: Setup completed
```
### Specific Task View
## Simple Bash Commands
### Basic Operations
- **Find active session**: `find .workflow/ -name ".active-*" -type f`
- **Read session info**: `cat .workflow/session/workflow-session.json`
- **List tasks**: `find .workflow/session/.task/ -name "*.json" -type f`
- **Check task status**: `cat task.json | jq -r '.status'`
- **Count completed**: `find .summaries/ -name "*.md" -type f | wc -l`
### Task Status Check
- **pending**: Not started yet
- **active**: Currently in progress
- **completed**: Finished with summary
- **blocked**: Waiting for dependencies
### Validation Commands
```bash
/workflow:status impl-1
# Check session exists
test -f .workflow/.active-* && echo "Session active"
# Validate task files
for f in .workflow/session/.task/*.json; do jq empty "$f" && echo "Valid: $f"; done
# Check summaries match
find .task/ -name "*.json" -type f | wc -l
find .summaries/ -name "*.md" -type f 2>/dev/null | wc -l
```
Shows detailed task information:
```markdown
# Task: impl-1
## Simple Output Format
**Title**: Build authentication module
**Status**: active
**Agent**: @code-developer
**Type**: feature
### Default Overview
```
Session: WFS-user-auth
Status: ACTIVE
Progress: 5/12 tasks
## 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
Current: impl-3 (Building API endpoints)
Next: impl-4 (Adding authentication)
Completed: impl-1, impl-2
```
### Hierarchy View
```bash
/workflow:status --format=hierarchy
### Task Details
```
Task: impl-1
Title: Build authentication module
Status: completed
Agent: code-developer
Created: 2025-09-15
Completed: 2025-09-15
Summary: .summaries/impl-1-summary.md
```
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
### Validation Results
```
## 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
✅ Session file valid
✅ 8 task files found
✅ 3 summaries found
⚠️ 5 tasks pending completion
```
## 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.
- `/workflow:execute` - Uses this for task discovery
- `/workflow:resume` - Uses this for progress analysis
- `/workflow:session:status` - Shows session metadata

View File

@@ -0,0 +1,306 @@
---
name: tdd-plan
description: Orchestrate TDD workflow planning with Red-Green-Refactor task chains
argument-hint: "[--agent] \"feature description\"|file.md"
allowed-tools: SlashCommand(*), TodoWrite(*), Read(*), Bash(*)
---
# TDD Workflow Plan Command (/workflow:tdd-plan)
## Coordinator Role
**This command is a pure orchestrator**: Execute 5 slash commands in sequence, parse outputs, pass context, and ensure complete TDD workflow creation.
**Execution Modes**:
- **Manual Mode** (default): Use `/workflow:tools:task-generate-tdd`
- **Agent Mode** (`--agent`): Use `/workflow:tools:task-generate-tdd --agent`
## Core Rules
1. **Start Immediately**: First action is TodoWrite initialization, second action is Phase 1 execution
2. **No Preliminary Analysis**: Do not read files before Phase 1
3. **Parse Every Output**: Extract required data for next phase
4. **Sequential Execution**: Each phase depends on previous output
5. **Complete All Phases**: Do not return until Phase 7 completes (with concept verification)
6. **TDD Context**: All descriptions include "TDD:" prefix
7. **Quality Gate**: Phase 5 concept verification ensures clarity before task generation
## 7-Phase Execution (with Concept Verification)
### Phase 1: Session Discovery
**Command**: `/workflow:session:start --auto "TDD: [structured-description]"`
**TDD Structured Format**:
```
TDD: [Feature Name]
GOAL: [Objective]
SCOPE: [Included/excluded]
CONTEXT: [Background]
TEST_FOCUS: [Test scenarios]
```
**Parse**: Extract sessionId
### Phase 2: Context Gathering
**Command**: `/workflow:tools:context-gather --session [sessionId] "TDD: [structured-description]"`
**Parse**: Extract contextPath
### Phase 3: 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]`
**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
**Parse**: Verify ANALYSIS_RESULTS.md contains TDD breakdown sections
### Phase 5: Concept Verification (NEW QUALITY GATE)
**Command**: `/workflow:concept-verify --session [sessionId]`
**Purpose**: Verify conceptual clarity before TDD task generation
- Clarify test requirements and acceptance criteria
- Resolve ambiguities in expected behavior
- Validate TDD approach is appropriate
**Behavior**:
- If no ambiguities found → Auto-proceed to Phase 6
- If ambiguities exist → Interactive clarification (up to 5 questions)
- After clarifications → Auto-proceed to Phase 6
**Parse**: Verify concept verification completed (check for clarifications section in ANALYSIS_RESULTS.md or synthesis file if exists)
### Phase 6: TDD Task Generation
**Command**:
- Manual: `/workflow:tools:task-generate-tdd --session [sessionId]`
- Agent: `/workflow:tools:task-generate-tdd --session [sessionId] --agent`
**Parse**: Extract feature count, task count (not chain count - tasks now contain internal TDD cycles)
**Validate**:
- IMPL_PLAN.md exists (unified plan with TDD Implementation Tasks section)
- IMPL-*.json files exist (one per feature, or container + subtasks for complex features)
- TODO_LIST.md exists with internal TDD phase indicators
- Each IMPL task includes:
- `meta.tdd_workflow: true`
- `flow_control.implementation_approach` with 3 steps (red/green/refactor)
- Green phase includes test-fix-cycle configuration
- IMPL_PLAN.md contains workflow_type: "tdd" in frontmatter
- Task count ≤10 (compliance with task limit)
### Phase 7: TDD Structure Validation & Action Plan Verification (RECOMMENDED)
**Internal validation first, then recommend external verification**
**Internal Validation**:
1. Each task contains complete TDD workflow (Red-Green-Refactor internally)
2. Task structure validation:
- `meta.tdd_workflow: true` in all IMPL tasks
- `flow_control.implementation_approach` has exactly 3 steps
- Each step has correct `tdd_phase`: "red", "green", "refactor"
3. Dependency validation:
- Sequential features: IMPL-N depends_on ["IMPL-(N-1)"] if needed
- Complex features: IMPL-N.M depends_on ["IMPL-N.(M-1)"] for subtasks
4. Agent assignment: All IMPL tasks use @code-developer
5. Test-fix cycle: Green phase step includes test-fix-cycle logic with max_iterations
6. Task count: Total tasks ≤10 (simple + subtasks)
**Return Summary**:
```
TDD Planning complete for session: [sessionId]
Features analyzed: [N]
Total tasks: [M] (1 task per simple feature + subtasks for complex features)
Task breakdown:
- Simple features: [K] tasks (IMPL-1 to IMPL-K)
- Complex features: [L] features with [P] subtasks
- Total task count: [M] (within 10-task limit ✅)
Structure:
- IMPL-1: {Feature 1 Name} (Internal: 🔴 Red → 🟢 Green → 🔵 Refactor)
- IMPL-2: {Feature 2 Name} (Internal: 🔴 Red → 🟢 Green → 🔵 Refactor)
- IMPL-3: {Complex Feature} (Container)
- IMPL-3.1: {Sub-feature A} (Internal: 🔴 Red → 🟢 Green → 🔵 Refactor)
- IMPL-3.2: {Sub-feature B} (Internal: 🔴 Red → 🟢 Green → 🔵 Refactor)
[...]
Plans generated:
- Unified Implementation Plan: .workflow/[sessionId]/IMPL_PLAN.md
(includes TDD Implementation Tasks section with workflow_type: "tdd")
- Task List: .workflow/[sessionId]/TODO_LIST.md
(with internal TDD phase indicators)
TDD Configuration:
- Each task contains complete Red-Green-Refactor cycle
- Green phase includes test-fix cycle (max 3 iterations)
- Auto-revert on max iterations reached
✅ Recommended Next Steps:
1. /workflow:action-plan-verify --session [sessionId] # Verify TDD plan quality and dependencies
2. /workflow:execute --session [sessionId] # Start TDD execution
3. /workflow:tdd-verify [sessionId] # Post-execution TDD compliance check
⚠️ Quality Gate: Consider running /workflow:action-plan-verify to validate TDD task structure and dependencies
```
## TodoWrite Pattern
```javascript
// Initialize (7 phases now with concept verification)
[
{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 concept verification", status: "pending", activeForm": "Executing concept verification"},
{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"
```
## Input Processing
Convert user input to TDD-structured format:
**Simple text** → Add TDD context
**Detailed text** → Extract components with TEST_FOCUS
**File/Issue** → Read and structure with TDD
## Error Handling
- **Parsing failure**: Retry once, then report
- **Validation failure**: Report missing/invalid data
- **Command failure**: Keep phase in_progress, report error
- **TDD validation failure**: Report incomplete chains or wrong dependencies
## Related Commands
- `/workflow:plan` - Standard (non-TDD) planning
- `/workflow:execute` - Execute TDD tasks
- `/workflow:tdd-verify` - Verify TDD compliance
- `/workflow:status` - View progress
## 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 (Optimized) |
|--------|----------|---------------------|
| **Phases** | 6 (with test coverage) | 7 (added concept verification) |
| **Context** | Greenfield assumption | Existing codebase aware |
| **Task Structure** | 1 feature = 3 tasks (TEST/IMPL/REFACTOR) | 1 feature = 1 task (internal TDD cycle) |
| **Task Count** | 5 features = 15 tasks | 5 features = 5 tasks (70% reduction) |
| **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 |
| **Task Management** | High overhead (15 tasks) | Low overhead (5 tasks) |
| **Execution Efficiency** | Frequent context switching | Continuous context per feature |
### 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 Implementation Tasks section)
├── TODO_LIST.md (with internal TDD phase indicators)
├── .process/
│ ├── context-package.json
│ ├── test-context-package.json
│ ├── ANALYSIS_RESULTS.md (enhanced with TDD breakdown)
│ └── green-fix-iteration-*.md (fix logs from Green phase cycles)
└── .task/
├── IMPL-1.json (Complete TDD task: Red-Green-Refactor internally)
├── IMPL-2.json (Complete TDD task)
├── IMPL-3.json (Complex feature container, if needed)
├── IMPL-3.1.json (Complex feature subtask, if needed)
└── IMPL-3.2.json (Complex feature subtask, if needed)
```
**File Count Comparison**:
- **Old structure**: 5 features = 15 task files (TEST/IMPL/REFACTOR × 5)
- **New structure**: 5 features = 5 task files (IMPL-N × 5)
- **Complex features**: Add container + subtasks only when necessary
**Configuration Options** (in IMPL tasks):
- `meta.max_iterations`: Fix attempts (default: 3)
- `meta.use_codex`: Auto-fix mode (default: false)

View File

@@ -0,0 +1,358 @@
---
name: tdd-verify
description: Verify TDD workflow compliance and generate quality report
argument-hint: "[optional: WFS-session-id]"
allowed-tools: SlashCommand(*), TodoWrite(*), Read(*), Bash(gemini-wrapper:*)
---
# TDD Verification Command (/workflow:tdd-verify)
## Coordinator Role
**This command is a pure orchestrator**: Execute 4 phases to verify TDD workflow compliance, test coverage, and Red-Green-Refactor cycle execution.
## Core Responsibilities
- Verify TDD task chain structure
- Analyze test coverage
- Validate TDD cycle execution
- Generate compliance report
## 4-Phase Execution
### Phase 1: Session Discovery
**Auto-detect or use provided session**
```bash
# If session-id provided
sessionId = argument
# Else auto-detect active session
find .workflow/ -name '.active-*' | head -1 | sed 's/.*active-//'
```
**Extract**: sessionId
**Validation**: Session directory exists
**TodoWrite**: Mark phase 1 completed, phase 2 in_progress
---
### Phase 2: Task Chain Validation
**Validate TDD structure using bash commands**
```bash
# Load all task JSONs
find .workflow/{sessionId}/.task/ -name '*.json'
# Extract task IDs
find .workflow/{sessionId}/.task/ -name '*.json' -exec jq -r '.id' {} \;
# Check dependencies
find .workflow/{sessionId}/.task/ -name 'IMPL-*.json' -exec jq -r '.context.depends_on[]?' {} \;
find .workflow/{sessionId}/.task/ -name 'REFACTOR-*.json' -exec jq -r '.context.depends_on[]?' {} \;
# Check meta fields
find .workflow/{sessionId}/.task/ -name '*.json' -exec jq -r '.meta.tdd_phase' {} \;
find .workflow/{sessionId}/.task/ -name '*.json' -exec jq -r '.meta.agent' {} \;
```
**Validation**:
- For each feature N, verify TEST-N.M → IMPL-N.M → REFACTOR-N.M exists
- IMPL-N.M.context.depends_on includes TEST-N.M
- REFACTOR-N.M.context.depends_on includes IMPL-N.M
- TEST tasks have tdd_phase="red" and agent="@code-review-test-agent"
- IMPL/REFACTOR tasks have tdd_phase="green"/"refactor" and agent="@code-developer"
**Extract**: Chain validation report
**TodoWrite**: Mark phase 2 completed, phase 3 in_progress
---
### Phase 3: Test Execution Analysis
**Command**: `SlashCommand(command="/workflow:tools:tdd-coverage-analysis --session [sessionId]")`
**Input**: sessionId from Phase 1
**Parse Output**:
- Coverage metrics (line, branch, function percentages)
- TDD cycle verification results
- Compliance score
**Validation**:
- `.workflow/{sessionId}/.process/test-results.json` exists
- `.workflow/{sessionId}/.process/coverage-report.json` exists
- `.workflow/{sessionId}/.process/tdd-cycle-report.md` exists
**TodoWrite**: Mark phase 3 completed, phase 4 in_progress
---
### Phase 4: Compliance Report Generation
**Gemini analysis for comprehensive TDD compliance report**
```bash
cd project-root && ~/.claude/scripts/gemini-wrapper -p "
PURPOSE: Generate TDD compliance report
TASK: Analyze TDD workflow execution and generate quality report
CONTEXT: @{.workflow/{sessionId}/.task/*.json,.workflow/{sessionId}/.summaries/*,.workflow/{sessionId}/.process/tdd-cycle-report.md}
EXPECTED:
- TDD compliance score (0-100)
- Chain completeness verification
- Test coverage analysis summary
- Quality recommendations
- Red-Green-Refactor cycle validation
- Best practices adherence assessment
RULES: Focus on TDD best practices and workflow adherence. Be specific about violations and improvements.
" > .workflow/{sessionId}/TDD_COMPLIANCE_REPORT.md
```
**Output**: TDD_COMPLIANCE_REPORT.md
**TodoWrite**: Mark phase 4 completed
**Return to User**:
```
TDD Verification Report - Session: {sessionId}
## Chain Validation
✅ Feature 1: TEST-1.1 → IMPL-1.1 → REFACTOR-1.1 (Complete)
✅ Feature 2: TEST-2.1 → IMPL-2.1 → REFACTOR-2.1 (Complete)
⚠️ Feature 3: TEST-3.1 → IMPL-3.1 (Missing REFACTOR phase)
## Test Execution
✅ All TEST tasks produced failing tests
✅ All IMPL tasks made tests pass
✅ All REFACTOR tasks maintained green tests
## Coverage Metrics
Line Coverage: {percentage}%
Branch Coverage: {percentage}%
Function Coverage: {percentage}%
## Compliance Score: {score}/100
Detailed report: .workflow/{sessionId}/TDD_COMPLIANCE_REPORT.md
Recommendations:
- Complete missing REFACTOR-3.1 task
- Consider additional edge case tests for Feature 2
- Improve test failure message clarity in Feature 1
```
## TodoWrite Pattern
```javascript
// Initialize (before Phase 1)
TodoWrite({todos: [
{"content": "Identify target session", "status": "in_progress", "activeForm": "Identifying target session"},
{"content": "Validate task chain structure", "status": "pending", "activeForm": "Validating task chain structure"},
{"content": "Analyze test execution", "status": "pending", "activeForm": "Analyzing test execution"},
{"content": "Generate compliance report", "status": "pending", "activeForm": "Generating compliance report"}
]})
// After Phase 1
TodoWrite({todos: [
{"content": "Identify target session", "status": "completed", "activeForm": "Identifying target session"},
{"content": "Validate task chain structure", "status": "in_progress", "activeForm": "Validating task chain structure"},
{"content": "Analyze test execution", "status": "pending", "activeForm": "Analyzing test execution"},
{"content": "Generate compliance report", "status": "pending", "activeForm": "Generating compliance report"}
]})
// Continue pattern for Phase 2, 3, 4...
```
## Validation Logic
### Chain Validation Algorithm
```
1. Load all task JSONs from .workflow/{sessionId}/.task/
2. Extract task IDs and group by feature number
3. For each feature:
- Check TEST-N.M exists
- Check IMPL-N.M exists
- Check REFACTOR-N.M exists (optional but recommended)
- Verify IMPL-N.M depends_on TEST-N.M
- Verify REFACTOR-N.M depends_on IMPL-N.M
- Verify meta.tdd_phase values
- Verify meta.agent assignments
4. Calculate chain completeness score
5. Report incomplete or invalid chains
```
### Compliance Scoring
```
Base Score: 100 points
Deductions:
- Missing TEST task: -30 points per feature
- Missing IMPL task: -30 points per feature
- Missing REFACTOR task: -10 points per feature
- Wrong dependency: -15 points per error
- Wrong agent: -5 points per error
- Wrong tdd_phase: -5 points per error
- Test didn't fail initially: -10 points per feature
- Tests didn't pass after IMPL: -20 points per feature
- Tests broke during REFACTOR: -15 points per feature
Final Score: Max(0, Base Score - Deductions)
```
## Output Files
```
.workflow/{session-id}/
├── TDD_COMPLIANCE_REPORT.md # Comprehensive compliance report ⭐
└── .process/
├── test-results.json # From tdd-coverage-analysis
├── coverage-report.json # From tdd-coverage-analysis
└── tdd-cycle-report.md # From tdd-coverage-analysis
```
## Error Handling
### Session Discovery Errors
| Error | Cause | Resolution |
|-------|-------|------------|
| No active session | No .active-* file | Provide session-id explicitly |
| Multiple active sessions | Multiple .active-* files | Provide session-id explicitly |
| Session not found | Invalid session-id | Check available sessions |
### Validation Errors
| Error | Cause | Resolution |
|-------|-------|------------|
| Task files missing | Incomplete planning | Run tdd-plan first |
| Invalid JSON | Corrupted task files | Regenerate tasks |
| Missing summaries | Tasks not executed | Execute tasks before verify |
### Analysis Errors
| Error | Cause | Resolution |
|-------|-------|------------|
| Coverage tool missing | No test framework | Configure testing first |
| Tests fail to run | Code errors | Fix errors before verify |
| Gemini analysis fails | Token limit / API error | Retry or reduce context |
## Integration & Usage
### Command Chain
- **Called After**: `/workflow:execute` (when TDD tasks completed)
- **Calls**: `/workflow:tools:tdd-coverage-analysis`, Gemini wrapper
- **Related**: `/workflow:tdd-plan`, `/workflow:status`
### Basic Usage
```bash
# Auto-detect active session
/workflow:tdd-verify
# Specify session
/workflow:tdd-verify WFS-auth
```
### When to Use
- After completing all TDD tasks in a workflow
- Before merging TDD workflow branch
- For TDD process quality assessment
- To identify missing TDD steps
## TDD Compliance Report Structure
```markdown
# TDD Compliance Report - {Session ID}
**Generated**: {timestamp}
**Session**: {sessionId}
**Workflow Type**: TDD
## Executive Summary
Overall Compliance Score: {score}/100
Status: {EXCELLENT | GOOD | NEEDS IMPROVEMENT | FAILED}
## Chain Analysis
### Feature 1: {Feature Name}
**Status**: ✅ Complete
**Chain**: TEST-1.1 → IMPL-1.1 → REFACTOR-1.1
-**Red Phase**: Test created and failed with clear message
-**Green Phase**: Minimal implementation made test pass
-**Refactor Phase**: Code improved, tests remained green
### Feature 2: {Feature Name}
**Status**: ⚠️ Incomplete
**Chain**: TEST-2.1 → IMPL-2.1 (Missing REFACTOR-2.1)
-**Red Phase**: Test created and failed
- ⚠️ **Green Phase**: Implementation seems over-engineered
-**Refactor Phase**: Missing
**Issues**:
- REFACTOR-2.1 task not completed
- IMPL-2.1 implementation exceeded minimal scope
[Repeat for all features]
## Test Coverage Analysis
### Coverage Metrics
- Line Coverage: {percentage}% {status}
- Branch Coverage: {percentage}% {status}
- Function Coverage: {percentage}% {status}
### Coverage Gaps
- {file}:{lines} - Uncovered error handling
- {file}:{lines} - Uncovered edge case
## TDD Cycle Validation
### Red Phase (Write Failing Test)
- ✅ {N}/{total} features had failing tests initially
- ⚠️ Feature 3: No evidence of initial test failure
### Green Phase (Make Test Pass)
- ✅ {N}/{total} implementations made tests pass
- ✅ All implementations minimal and focused
### Refactor Phase (Improve Quality)
- ⚠️ {N}/{total} features completed refactoring
- ❌ Feature 2, 4: Refactoring step skipped
## Best Practices Assessment
### Strengths
- Clear test descriptions
- Good test coverage
- Consistent naming conventions
- Well-structured code
### Areas for Improvement
- Some implementations over-engineered in Green phase
- Missing refactoring steps
- Test failure messages could be more descriptive
## Recommendations
### High Priority
1. Complete missing REFACTOR tasks (Features 2, 4)
2. Verify initial test failures for Feature 3
3. Simplify over-engineered implementations
### Medium Priority
1. Add edge case tests for Features 1, 3
2. Improve test failure message clarity
3. Increase branch coverage to >85%
### Low Priority
1. Add more descriptive test names
2. Consider parameterized tests for similar scenarios
3. Document TDD process learnings
## Conclusion
{Summary of compliance status and next steps}
```
## Related Commands
- `/workflow:tdd-plan` - Creates TDD workflow
- `/workflow:execute` - Executes TDD tasks
- `/workflow:tools:tdd-coverage-analysis` - Analyzes test coverage
- `/workflow:status` - Views workflow progress

View File

@@ -0,0 +1,651 @@
---
name: test-cycle-execute
description: Execute test-fix workflow with dynamic task generation and iterative fix cycles
argument-hint: "[--resume-session=\"session-id\"] [--max-iterations=N]"
allowed-tools: SlashCommand(*), TodoWrite(*), Read(*), Bash(*), Task(*)
---
# Workflow Test-Cycle-Execute Command
## Overview
Orchestrates dynamic test-fix workflow execution through iterative cycles of testing, analysis, and fixing. **Unlike standard execute, this command dynamically generates intermediate tasks** during execution based on test results and CLI analysis, enabling adaptive problem-solving.
**Resume Mode**: When called with `--resume-session` flag, skips discovery and continues from interruption point.
## Core Philosophy
### Dynamic vs Static Execution
**Standard Execute**: Pre-defined task queue → Sequential execution → Complete
**Test Execute**: Initial tasks → Test → Analyze → Generate fix tasks → Execute → Re-test → Repeat
### Iteration Loop Pattern
```
1. Execute current task (test/implement)
2. Run tests and collect results
3. If failures: CLI analysis → Generate fix tasks → Execute → Back to 2
4. If success: Mark complete → Next task
5. Repeat until all tests pass or max iterations reached
```
### Agent Coordination
- **@code-developer**: Understands requirements, generates implementations
- **@test-fix-agent**: Executes tests, applies fixes, validates results
- **CLI Tools (Gemini/Qwen)**: Analyzes failures, suggests fix strategies
## Core Rules
1. **Dynamic Task Generation**: Create intermediate fix tasks based on test failures
2. **Iterative Execution**: Repeat test-fix cycles until success or max iterations
3. **CLI-Driven Analysis**: Use Gemini/Qwen to analyze failures and plan fixes
4. **Agent Delegation**: All execution delegated to specialized agents
5. **Context Accumulation**: Each iteration builds on previous attempt context
6. **Autonomous Completion**: Continue until all tests pass without user interruption
## Core Responsibilities
- **Session Discovery**: Identify test-fix workflow sessions
- **Task Queue Management**: Maintain dynamic task queue with runtime additions
- **Test Execution**: Run tests through @test-fix-agent
- **Failure Analysis**: Use CLI tools to diagnose test failures
- **Fix Task Generation**: Create intermediate fix tasks dynamically
- **Iteration Control**: Manage fix cycles with max iteration limits
- **Context Propagation**: Pass failure context and fix history between iterations
- **Progress Tracking**: TodoWrite updates for entire iteration cycle
- **Session Auto-Complete**: Call `/workflow:session:complete` when all tests pass
## Responsibility Matrix
**Clear division of labor between orchestrator and agents:**
| Responsibility | test-cycle-execute (Orchestrator) | @test-fix-agent (Executor) |
|----------------|----------------------------|---------------------------|
| Manage iteration loop | ✅ Controls loop flow | ❌ Executes single task |
| Run CLI analysis (Gemini/Qwen) | ✅ Runs between agent tasks | ❌ Not involved |
| Generate IMPL-fix-N.json | ✅ Creates task files | ❌ Not involved |
| Run tests | ❌ Delegates to agent | ✅ Executes test command |
| Apply fixes | ❌ Delegates to agent | ✅ Modifies code |
| Detect test failures | ✅ Analyzes agent output | ✅ Reports results |
| Add tasks to queue | ✅ Manages queue | ❌ Not involved |
| Update iteration state | ✅ Maintains state files | ✅ Updates task status |
**Key Principle**: Orchestrator manages the "what" and "when"; agents execute the "how".
## Execution Lifecycle
### Phase 1: Discovery & Initialization
1. **Detect Session Type**: Identify test-fix session from `workflow_type: "test_session"`
2. **Load Session State**: Read `workflow-session.json`, `IMPL_PLAN.md`, `TODO_LIST.md`
3. **Scan Initial Tasks**: Analyze `.task/*.json` files
4. **Initialize TodoWrite**: Create task list including initial tasks
5. **Prepare Iteration Context**: Setup iteration counter and max limits
**Resume Mode**: Load existing iteration context from `.process/iteration-state.json`
### Phase 2: Task Execution Loop
**Main execution loop with dynamic task generation (executed by test-cycle-execute orchestrator):**
**Execution Order**: The workflow begins by executing IMPL-001 (test generation) first. Upon successful completion, IMPL-002 (test-fix cycle) is initiated, starting the iterative test-fix loop.
```
For each task in queue:
1. [Orchestrator] Load task JSON and context
2. [Orchestrator] Determine task type (test-gen, test-fix, fix-iteration)
3. [Orchestrator] Execute task through appropriate agent
4. [Orchestrator] Collect agent results and check exit conditions
5. If test failures detected:
a. [Orchestrator] Run CLI analysis (Gemini/Qwen)
b. [Orchestrator] Generate fix task JSON (IMPL-fix-N.json)
c. [Orchestrator] Insert fix task at front of queue
d. [Orchestrator] Continue loop
6. If test success:
a. [Orchestrator] Mark task complete
b. [Orchestrator] Update TodoWrite
c. [Orchestrator] Continue to next task
7. [Orchestrator] Check max iterations limit
```
**Note**: The orchestrator controls the loop. Agents execute individual tasks and return results.
### Phase 3: Iteration Cycle (Test-Fix Loop)
**Orchestrator-controlled iteration with agent delegation:**
#### Iteration Structure
```
Iteration N (managed by test-cycle-execute orchestrator):
├── 1. Test Execution
│ ├── [Orchestrator] Launch @test-fix-agent with test task
│ ├── [Agent] Run test suite
│ ├── [Agent] Collect failures and report back
│ └── [Orchestrator] Receive failure report
├── 2. Failure Analysis
│ ├── [Orchestrator] Run CLI tool (Gemini/Qwen)
│ ├── [CLI Tool] Analyze error messages and failure context
│ ├── [CLI Tool] Identify root causes
│ └── [CLI Tool] Generate fix strategy → saved to iteration-N-analysis.md
├── 3. Fix Task Generation
│ ├── [Orchestrator] Parse CLI analysis results
│ ├── [Orchestrator] Create IMPL-fix-N.json with:
│ │ ├── meta.agent: "@test-fix-agent"
│ │ ├── Failure context (content, not just path)
│ │ └── Fix strategy from CLI analysis
│ └── [Orchestrator] Insert into task queue (front position)
├── 4. Fix Execution
│ ├── [Orchestrator] Launch @test-fix-agent with fix task
│ ├── [Agent] Load fix strategy from task context
│ ├── [Agent] Apply fixes to code/tests
│ └── [Agent] Report completion
└── 5. Re-test
└── [Orchestrator] Return to step 1 with updated code
```
**Key**: Orchestrator runs CLI analysis between agent tasks, then generates new fix tasks.
#### Iteration Task JSON Template
```json
{
"id": "IMPL-fix-{iteration}",
"title": "Fix test failures - Iteration {N}",
"status": "pending",
"meta": {
"type": "test-fix-iteration",
"agent": "@test-fix-agent",
"iteration": N,
"parent_task": "IMPL-002",
"max_iterations": 5
},
"context": {
"requirements": [
"Fix identified test failures",
"Address root causes from analysis"
],
"failure_context": {
"failed_tests": ["test1", "test2"],
"error_messages": ["error1", "error2"],
"failure_analysis": "Raw test output and error messages",
"previous_attempts": ["iteration-1 context"]
},
"fix_strategy": {
"approach": "Generated by CLI tool (Gemini/Qwen) analysis",
"modification_points": ["file1:func1", "file2:func2"],
"expected_outcome": "All tests pass"
},
"depends_on": ["IMPL-fix-{N-1}"],
"inherited": {
"iteration_history": [...]
}
},
"flow_control": {
"pre_analysis": [
{
"step": "load_failure_context",
"command": "Read(.workflow/{session}/.process/iteration-{N-1}-failures.json)",
"output_to": "previous_failures",
"on_error": "skip_optional"
},
{
"step": "load_fix_strategy",
"command": "Read(.workflow/{session}/.process/iteration-{N}-strategy.md)",
"output_to": "fix_strategy",
"on_error": "fail"
}
],
"implementation_approach": [
{
"step": 1,
"title": "Apply fixes from strategy",
"description": "Implement fixes identified by CLI analysis",
"modification_points": "From fix_strategy",
"logic_flow": [
"Load failure context and strategy",
"Apply surgical fixes",
"Run tests",
"Validate fixes"
]
}
],
"target_files": ["from fix_strategy"],
"exit_conditions": {
"success": "all_tests_pass",
"failure": "max_iterations_reached",
"max_iterations": 5
}
}
}
```
### Phase 4: CLI Analysis Integration
**Orchestrator executes CLI analysis between agent tasks:**
#### When Test Failures Occur
1. **[Orchestrator]** Detects failures from agent output
2. **[Orchestrator]** Collects failure context from `.process/test-results.json` and logs
3. **[Orchestrator]** Runs Gemini/Qwen wrapper with failure context
4. **[CLI Tool]** Analyzes failures and generates fix strategy
5. **[Orchestrator]** Saves analysis to `.process/iteration-N-analysis.md`
6. **[Orchestrator]** Generates `IMPL-fix-N.json` with strategy content (not just path)
#### CLI Analysis Command (executed by orchestrator)
```bash
cd {project_root} && ~/.claude/scripts/gemini-wrapper -p "
PURPOSE: Analyze test failures and generate fix strategy
TASK: Review test failures and identify root causes
MODE: analysis
CONTEXT: @{test files, implementation files}
[Test failure context and requirements...]
EXPECTED: Detailed fix strategy in markdown format
RULES: Focus on minimal changes, avoid over-engineering
"
```
#### Analysis Output Structure
```markdown
# Test Failure Analysis - Iteration {N}
## Root Cause Analysis
1. **Test: test_auth_flow**
- Error: `Expected 200, got 401`
- Root Cause: Missing authentication token in request headers
- Affected Code: `src/auth/client.ts:45`
2. **Test: test_data_validation**
- Error: `TypeError: Cannot read property 'name' of undefined`
- Root Cause: Null check missing before property access
- Affected Code: `src/validators/user.ts:23`
## Fix Strategy
### Priority 1: Authentication Issue
- **File**: src/auth/client.ts
- **Function**: sendRequest (line 45)
- **Change**: Add token header: `headers['Authorization'] = 'Bearer ' + token`
- **Verification**: Run test_auth_flow
### Priority 2: Null Check
- **File**: src/validators/user.ts
- **Function**: validateUser (line 23)
- **Change**: Add check: `if (!user?.name) return false`
- **Verification**: Run test_data_validation
## Verification Plan
1. Apply fixes in order
2. Run test suite after each fix
3. Check for regressions
4. Validate all tests pass
## Risk Assessment
- Low risk: Changes are surgical and isolated
- No breaking changes expected
- Existing tests should remain green
```
### Phase 5: Task Queue Management
**Orchestrator maintains dynamic task queue with runtime insertions:**
#### Dynamic Queue Operations
```
Initial Queue: [IMPL-001, IMPL-002]
After IMPL-002 execution (test failures detected by orchestrator):
[Orchestrator] Generates IMPL-fix-1.json
[Orchestrator] Inserts at front: [IMPL-fix-1, IMPL-002-retest, ...]
After IMPL-fix-1 execution (still failures):
[Orchestrator] Generates IMPL-fix-2.json
[Orchestrator] Inserts at front: [IMPL-fix-2, IMPL-002-retest, ...]
After IMPL-fix-2 execution (success):
[Orchestrator] Continues to: [IMPL-002-complete, ...]
```
#### Queue Priority Rules (orchestrator-managed)
1. **Fix tasks**: Inserted at queue front for immediate execution
2. **Retest tasks**: Automatically scheduled after fix tasks
3. **Regular tasks**: Standard dependency order preserved
4. **Iteration limit**: Max 5 fix iterations per test task (orchestrator enforces)
### Phase 6: Completion & Session Management
#### Success Conditions
- All initial tasks completed
- All generated fix tasks completed
- All tests passing
- No pending tasks in queue
#### Completion Steps
1. **Final Validation**: Run full test suite one more time
2. **Update Session State**: Mark all tasks completed
3. **Generate Summary**: Create session completion summary
4. **Update TodoWrite**: Mark all items completed
5. **Auto-Complete**: Call `/workflow:session:complete`
#### Failure Conditions
- Max iterations reached without success
- Unrecoverable test failures
- Agent execution errors
#### Failure Handling
1. **Document State**: Save current iteration context
2. **Generate Report**: Create failure analysis report
3. **Preserve Context**: Keep all iteration logs
4. **Mark Blocked**: Update task status to blocked
5. **Return Control**: Return to user with detailed report
## TodoWrite Coordination
### TodoWrite Structure for Test-Execute
```javascript
TodoWrite({
todos: [
{
content: "Execute IMPL-001: Generate tests [code-developer]",
status: "completed",
activeForm: "Executing test generation"
},
{
content: "Execute IMPL-002: Test & Fix Cycle [test-fix-agent] [ITERATION]",
status: "in_progress",
activeForm: "Running test-fix iteration cycle"
},
{
content: " → Iteration 1: Initial test run",
status: "completed",
activeForm: "Running initial tests"
},
{
content: " → Iteration 2: Fix auth issues",
status: "in_progress",
activeForm: "Fixing authentication issues"
},
{
content: " → Iteration 3: Re-test and validate",
status: "pending",
activeForm: "Re-testing after fixes"
}
]
});
```
### TodoWrite Update Rules
1. **Initial Tasks**: Standard task list
2. **Iteration Start**: Add nested iteration item
3. **Fix Task Added**: Add fix task as nested item
4. **Iteration Complete**: Mark iteration item completed
5. **All Complete**: Mark parent task completed
## Agent Context Package
**Generated by test-cycle-execute orchestrator before launching agents.**
The orchestrator assembles this context package from:
- Task JSON file (IMPL-*.json)
- Iteration state files
- Test results and failure context
- Session metadata
This package is passed to agents via the Task tool's prompt context.
### Enhanced Context for Test-Fix Agent
```json
{
"task": { /* IMPL-fix-N.json */ },
"iteration_context": {
"current_iteration": N,
"max_iterations": 5,
"previous_attempts": [
{
"iteration": N-1,
"failures": ["test1", "test2"],
"fixes_attempted": ["fix1", "fix2"],
"result": "partial_success"
}
],
"failure_analysis": {
"source": "gemini_cli",
"analysis_file": ".process/iteration-N-analysis.md",
"fix_strategy": { /* from CLI */ }
}
},
"test_context": {
"test_framework": "jest|pytest|...",
"test_files": ["path/to/test1.test.ts"],
"test_command": "npm test",
"coverage_target": 80
},
"session": {
"workflow_dir": ".workflow/WFS-test-{session}/",
"iteration_state_file": ".process/iteration-state.json",
"test_results_file": ".process/test-results.json",
"fix_history_file": ".process/fix-history.json"
}
}
```
## File Structure
### Test-Fix Session Files
```
.workflow/WFS-test-{session}/
├── workflow-session.json # Session metadata with workflow_type
├── IMPL_PLAN.md # Test plan
├── TODO_LIST.md # Progress tracking
├── .task/
│ ├── IMPL-001.json # Test generation task
│ ├── IMPL-002.json # Initial test-fix task
│ ├── IMPL-fix-1.json # Generated: Iteration 1 fix
│ ├── IMPL-fix-2.json # Generated: Iteration 2 fix
│ └── ...
├── .summaries/
│ ├── IMPL-001-summary.md
│ ├── IMPL-002-summary.md
│ └── iteration-summaries/
│ ├── iteration-1.md
│ ├── iteration-2.md
│ └── ...
└── .process/
├── TEST_ANALYSIS_RESULTS.md # From planning phase
├── iteration-state.json # Current iteration state
├── test-results.json # Latest test results
├── test-output.log # Full test output
├── fix-history.json # All fix attempts
├── iteration-1-analysis.md # CLI analysis for iteration 1
├── iteration-1-failures.json # Failures from iteration 1
├── iteration-1-strategy.md # Fix strategy for iteration 1
├── iteration-2-analysis.md
└── ...
```
### Iteration State JSON
```json
{
"session_id": "WFS-test-user-auth",
"current_task": "IMPL-002",
"current_iteration": 2,
"max_iterations": 5,
"started_at": "2025-10-17T10:00:00Z",
"iterations": [
{
"iteration": 1,
"started_at": "2025-10-17T10:05:00Z",
"completed_at": "2025-10-17T10:15:00Z",
"test_results": {
"total": 10,
"passed": 7,
"failed": 3,
"failures": ["test1", "test2", "test3"]
},
"analysis_file": ".process/iteration-1-analysis.md",
"fix_task": "IMPL-fix-1",
"result": "partial_success"
}
],
"status": "active",
"next_action": "execute_fix_task"
}
```
## Agent Prompt Template
**Unified template for all agent tasks (orchestrator invokes with Task tool):**
```bash
Task(subagent_type="{meta.agent}",
prompt="**TASK EXECUTION: {task.title}**
## STEP 1: Load Complete Task JSON
**MANDATORY**: First load the complete task JSON from: {session.task_json_path}
cat {session.task_json_path}
**CRITICAL**: Validate all required fields present
## STEP 2: Task Context (From Loaded JSON)
**ID**: {task.id}
**Type**: {task.meta.type}
**Agent**: {task.meta.agent}
## STEP 3: Execute Task Based on Type
### For test-gen (IMPL-001):
- Generate tests based on TEST_ANALYSIS_RESULTS.md
- Follow test framework conventions
- Create test files in target_files
### For test-fix (IMPL-002):
- Run test suite: {test_command}
- Collect results to .process/test-results.json
- If failures: Save context, return to orchestrator
- If success: Mark complete
### For test-fix-iteration (IMPL-fix-N):
- Load fix strategy from context.fix_strategy (CONTENT, not path)
- Apply surgical fixes to identified files
- Run tests to verify
- If still failures: Save context with new failure data
- Update iteration state
## STEP 4: Implementation Context (From JSON)
**Requirements**: {context.requirements}
**Fix Strategy**: {context.fix_strategy} (full content provided in task JSON)
**Failure Context**: {context.failure_context}
**Iteration History**: {context.inherited.iteration_history}
## STEP 5: Flow Control Execution
If flow_control.pre_analysis exists, execute steps sequentially
## STEP 6: Agent Completion
1. Execute task following implementation_approach
2. Update task status in JSON
3. Update TODO_LIST.md
4. Generate summary in .summaries/
5. **CRITICAL**: Save results for orchestrator to analyze
**Output Requirements**:
- test-results.json: Structured test results
- test-output.log: Full test output
- iteration-state.json: Current iteration state (if applicable)
- task-summary.md: Completion summary
**Return to Orchestrator**: Agent completes and returns. Orchestrator decides next action.
"),
description="Execute {task.type} task with JSON validation")
```
**Key Points**:
- Agent executes single task and returns
- Orchestrator analyzes results and decides next step
- Fix strategy content (not path) embedded in task JSON by orchestrator
- Agent does not manage iteration loop
## Error Handling & Recovery
### Iteration Failure Scenarios
| Scenario | Handling | Recovery |
|----------|----------|----------|
| Test execution error | Log error, save context | Retry with error context |
| CLI analysis failure | Fallback to Qwen, or manual analysis | Retry analysis with different tool |
| Agent execution error | Save iteration state | Retry agent with simplified context |
| Max iterations reached | Generate failure report | Mark blocked, return to user |
| Unexpected test regression | Rollback last fix | Analyze regression, add to fix strategy |
### Recovery Procedures
#### Resume from Interruption
```bash
# Load iteration state
iteration_state=$(cat .workflow/{session}/.process/iteration-state.json)
current_iteration=$(jq -r '.current_iteration' <<< "$iteration_state")
# Determine resume point
if [[ "$(jq -r '.next_action' <<< "$iteration_state")" == "execute_fix_task" ]]; then
# Resume fix task execution
task_id="IMPL-fix-${current_iteration}"
else
# Resume test execution
task_id="IMPL-002"
fi
```
#### Rollback Failed Fix
```bash
# Revert last commit (if fixes were committed)
git revert HEAD
# Remove failed fix task
rm .workflow/{session}/.task/IMPL-fix-{N}.json
# Restore iteration state
jq '.current_iteration -= 1' iteration-state.json > temp.json
mv temp.json iteration-state.json
# Re-run analysis with additional context
# Include failure reason in next analysis
```
## Usage Examples
### Basic Usage
```bash
# Execute test-fix workflow
/workflow:test-cycle-execute
# Resume interrupted session
/workflow:test-cycle-execute --resume-session="WFS-test-user-auth"
# Set custom iteration limit
/workflow:test-cycle-execute --max-iterations=10
```
### Integration with Planning
```bash
# 1. Plan test workflow
/workflow:test-fix-gen WFS-user-auth
# 2. Execute with dynamic iteration
/workflow:test-cycle-execute
# 3. Monitor progress
/workflow:status
# 4. Resume if interrupted
/workflow:test-cycle-execute --resume-session="WFS-test-user-auth"
```
## Best Practices
1. **Set Realistic Iteration Limits**: Default 5, increase for complex fixes
2. **Commit Between Iterations**: Easier rollback if needed
3. **Monitor Iteration Logs**: Review CLI analysis for insights
4. **Incremental Fixes**: Prefer multiple small iterations over large changes
5. **Verify No Regressions**: Check all tests pass, not just previously failing ones
6. **Preserve Context**: All iteration artifacts saved for debugging
## Related Commands
- `/workflow:test-fix-gen` - Planning phase (creates initial tasks)
- `/workflow:execute` - Standard workflow execution (no dynamic iteration)
- `/workflow:status` - Check progress and iteration state
- `/workflow:session:complete` - Mark session complete (auto-called on success)
- `/task:create` - Manually create additional tasks if needed

View File

@@ -0,0 +1,470 @@
---
name: test-fix-gen
description: Create independent test-fix workflow session from existing implementation (session or prompt-based)
argument-hint: "[--use-codex] [--cli-execute] (source-session-id | \"feature description\" | /path/to/file.md)"
allowed-tools: SlashCommand(*), TodoWrite(*), Read(*), Bash(*)
---
# Workflow Test-Fix Generation Command (/workflow:test-fix-gen)
## Overview
### What It Does
This command creates an independent test-fix workflow session for existing code. It orchestrates a 5-phase process to analyze implementation, generate test requirements, and create executable test generation and fix tasks.
**⚠️ Command Scope**: Prepares test workflow artifacts only. Task execution requires separate commands (`/workflow:test-cycle-execute` or `/workflow:execute`).
### Dual-Mode Support
**Automatic mode detection** based on input pattern:
| Mode | Input Pattern | Context Source | Use Case |
|------|--------------|----------------|----------|
| **Session Mode** | `WFS-xxx` | Source session summaries | Test validation for completed workflow |
| **Prompt Mode** | Text or file path | Direct codebase analysis | Test generation from description |
**Detection Logic**:
```bash
if [[ "$input" == WFS-* ]]; then
MODE="session" # Use test-context-gather
else
MODE="prompt" # Use context-gather
fi
```
### Core Principles
- **Dual Input Support**: Accepts session ID (WFS-xxx) or feature description/file path
- **Session Isolation**: Creates independent `WFS-test-[slug]` session
- **Context-First**: Gathers implementation context via appropriate method
- **Format Reuse**: Creates standard `IMPL-*.json` tasks with `meta.type: "test-fix"`
- **Manual First**: Default to manual fixes, use `--use-codex` for automation
- **Automatic Detection**: Input pattern determines execution mode
### Coordinator Role
This command is a **pure orchestrator**:
- Does NOT analyze code directly
- Does NOT generate tests or documentation
- ONLY coordinates slash commands in sequence
- Parses outputs to pass data between phases
- Creates independent test workflow session
---
## Usage
### Command Syntax
```bash
# Basic syntax
/workflow:test-fix-gen [FLAGS] <INPUT>
# Flags (optional)
--use-codex # Enable Codex automated fixes in IMPL-002
--cli-execute # Enable CLI execution in IMPL-001
# Input
<INPUT> # Session ID, description, or file path
```
### Usage Examples
#### Session Mode
```bash
# Test validation for completed implementation
/workflow:test-fix-gen WFS-user-auth-v2
# With automated fixes
/workflow:test-fix-gen --use-codex WFS-api-endpoints
# With CLI execution
/workflow:test-fix-gen --cli-execute --use-codex WFS-payment-flow
```
#### Prompt Mode - Text Description
```bash
# Generate tests from feature description
/workflow:test-fix-gen "Test the user authentication API endpoints in src/auth/api.ts"
# With automated fixes
/workflow:test-fix-gen --use-codex "Test user registration and login flows"
```
#### Prompt Mode - File Reference
```bash
# Generate tests from requirements file
/workflow:test-fix-gen ./docs/api-requirements.md
# With flags
/workflow:test-fix-gen --use-codex --cli-execute ./specs/feature.md
```
### Mode Comparison
| Aspect | Session Mode | Prompt Mode |
|--------|-------------|-------------|
| **Phase 1** | Create `WFS-test-[source]` with `source_session_id` | Create `WFS-test-[slug]` without `source_session_id` |
| **Phase 2** | `/workflow:tools:test-context-gather` | `/workflow:tools:context-gather` |
| **Phase 3-5** | Identical | Identical |
| **Context** | Source session summaries + artifacts | Direct codebase analysis |
---
## Execution Flow
### Core Execution Rules
1. **Start Immediately**: First action is TodoWrite, second is Phase 1 session creation
2. **No Preliminary Analysis**: Do not read files before Phase 1
3. **Parse Every Output**: Extract required data from each phase for next phase
4. **Sequential Execution**: Each phase depends on previous phase's output
5. **Complete All Phases**: Do not return until Phase 5 completes
6. **Track Progress**: Update TodoWrite after every phase
7. **Automatic Detection**: Mode auto-detected from input pattern
8. **Parse Flags**: Extract `--use-codex` and `--cli-execute` flags for Phase 4
### 5-Phase Execution
#### Phase 1: Create Test Session
**Command**:
- **Session Mode**: `SlashCommand("/workflow:session:start --new \"Test validation for [sourceSessionId]\"")`
- **Prompt Mode**: `SlashCommand("/workflow:session:start --new \"Test generation for: [description]\"")`
**Input**: User argument (session ID, description, or file path)
**Expected Behavior**:
- Creates new session: `WFS-test-[slug]`
- Writes `workflow-session.json` metadata:
- **Session Mode**: Includes `workflow_type: "test_session"`, `source_session_id: "[sourceId]"`
- **Prompt Mode**: Includes `workflow_type: "test_session"` only
- Returns new session ID
**Parse Output**:
- Extract: `testSessionId` (pattern: `WFS-test-[slug]`)
**Validation**:
- **Session Mode**: Source session exists with completed IMPL tasks
- **Both Modes**: New test session directory created with metadata
**TodoWrite**: Mark phase 1 completed, phase 2 in_progress
---
#### Phase 2: Gather Test Context
**Command**:
- **Session Mode**: `SlashCommand("/workflow:tools:test-context-gather --session [testSessionId]")`
- **Prompt Mode**: `SlashCommand("/workflow:tools:context-gather --session [testSessionId] \"[task_description]\"")`
**Input**: `testSessionId` from Phase 1
**Expected Behavior**:
- **Session Mode**:
- Load source session implementation context and summaries
- Analyze test coverage using MCP tools
- Identify files requiring tests
- **Prompt Mode**:
- Analyze codebase based on description
- Identify relevant files and dependencies
- Detect test framework and conventions
- Generate context package JSON
**Parse Output**:
- Extract: `contextPath` (pattern: `.workflow/[testSessionId]/.process/[test-]context-package.json`)
**Validation**:
- Context package created with coverage analysis
- Test framework detected
- Test conventions documented
**TodoWrite**: Mark phase 2 completed, phase 3 in_progress
---
#### Phase 3: Test Generation Analysis
**Command**: `SlashCommand("/workflow:tools:test-concept-enhanced --session [testSessionId] --context [contextPath]")`
**Input**:
- `testSessionId` from Phase 1
- `contextPath` from Phase 2
**Expected Behavior**:
- Use Gemini to analyze coverage gaps and implementation
- Study existing test patterns and conventions
- Generate test requirements for missing test files
- Design test generation strategy
- Generate `TEST_ANALYSIS_RESULTS.md`
**Parse Output**:
- Verify `.workflow/[testSessionId]/.process/TEST_ANALYSIS_RESULTS.md` created
**Validation**:
- TEST_ANALYSIS_RESULTS.md exists with complete sections:
- Coverage Assessment
- Test Framework & Conventions
- Test Requirements by File
- Test Generation Strategy
- Implementation Targets
- Success Criteria
**TodoWrite**: Mark phase 3 completed, phase 4 in_progress
---
#### Phase 4: Generate Test Tasks
**Command**: `SlashCommand("/workflow:tools:test-task-generate [--use-codex] [--cli-execute] --session [testSessionId]")`
**Input**:
- `testSessionId` from Phase 1
- `--use-codex` flag (if present) - Controls IMPL-002 fix mode
- `--cli-execute` flag (if present) - Controls IMPL-001 generation mode
**Expected Behavior**:
- Parse TEST_ANALYSIS_RESULTS.md from Phase 3
- Generate **minimum 2 task JSON files** (expandable based on complexity):
- **IMPL-001.json**: Test Understanding & Generation (`@code-developer`)
- **IMPL-002.json**: Test Execution & Fix Cycle (`@test-fix-agent`)
- **IMPL-003+**: Additional tasks if needed for complex projects
- Generate `IMPL_PLAN.md` with test strategy
- Generate `TODO_LIST.md` with task checklist
**Parse Output**:
- Verify `.workflow/[testSessionId]/.task/IMPL-001.json` exists
- Verify `.workflow/[testSessionId]/.task/IMPL-002.json` exists
- Verify additional `.task/IMPL-*.json` if applicable
- Verify `IMPL_PLAN.md` and `TODO_LIST.md` created
**TodoWrite**: Mark phase 4 completed, phase 5 in_progress
---
#### Phase 5: Return Summary
**Return to User**:
```
Independent test-fix workflow created successfully!
Input: [original input]
Mode: [Session|Prompt]
Test Session: [testSessionId]
Tasks Created:
- IMPL-001: Test Understanding & Generation (@code-developer)
- IMPL-002: Test Execution & Fix Cycle (@test-fix-agent)
[- IMPL-003+: Additional tasks if applicable]
Test Framework: [detected framework]
Test Files to Generate: [count]
Max Fix Iterations: 5
Fix Mode: [Manual|Codex Automated]
Review artifacts:
- Test plan: .workflow/[testSessionId]/IMPL_PLAN.md
- Task list: .workflow/[testSessionId]/TODO_LIST.md
Next Steps:
- Review IMPL_PLAN.md
- Execute: /workflow:test-cycle-execute [testSessionId]
```
**TodoWrite**: Mark phase 5 completed
**Note**: Command completes here. Task execution requires separate workflow commands.
---
### TodoWrite Progress Tracking
Track all 5 phases:
```javascript
TodoWrite({todos: [
{"content": "Create independent test session", "status": "in_progress|completed", "activeForm": "Creating test session"},
{"content": "Gather test coverage context", "status": "pending|in_progress|completed", "activeForm": "Gathering test coverage context"},
{"content": "Analyze test requirements with Gemini", "status": "pending|in_progress|completed", "activeForm": "Analyzing test requirements"},
{"content": "Generate test generation and execution tasks", "status": "pending|in_progress|completed", "activeForm": "Generating test tasks"},
{"content": "Return workflow summary", "status": "pending|in_progress|completed", "activeForm": "Returning workflow summary"}
]})
```
Update status to `in_progress` when starting each phase, `completed` when done.
---
## Task Specifications
Generates minimum 2 tasks (expandable for complex projects):
### IMPL-001: Test Understanding & Generation
**Agent**: `@code-developer`
**Purpose**: Understand source implementation and generate test files
**Task Configuration**:
- Task ID: `IMPL-001`
- `meta.type: "test-gen"`
- `meta.agent: "@code-developer"`
- `context.requirements`: Understand source implementation and generate tests
- `flow_control.target_files`: Test files to create from TEST_ANALYSIS_RESULTS.md section 5
**Execution Flow**:
1. **Understand Phase**:
- Load TEST_ANALYSIS_RESULTS.md and test context
- Understand source code implementation patterns
- Analyze test requirements and conventions
- Identify test scenarios and edge cases
2. **Generation Phase**:
- Generate test files following existing patterns
- Ensure test coverage aligns with requirements
3. **Verification Phase**:
- Verify test completeness and correctness
### IMPL-002: Test Execution & Fix Cycle
**Agent**: `@test-fix-agent`
**Purpose**: Execute tests and apply iterative fixes (max 5 iterations)
**Task Configuration**:
- 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
**Test-Fix Cycle Specification**:
- **Cycle Pattern**: test → gemini_diagnose → manual_fix (or codex) → retest
- **Tools Configuration**:
- Gemini for analysis with bug-fix template → surgical fix suggestions
- Manual fix application (default) OR Codex if `--use-codex` flag (resume mechanism)
- **Exit Conditions**:
- Success: All tests pass
- Failure: Max iterations reached (5)
**Execution Flow**:
1. **Phase 1**: Initial test execution
2. **Phase 2**: Iterative Gemini diagnosis + manual/Codex fixes
3. **Phase 3**: Final validation and certification
### IMPL-003+: Additional Tasks (Optional)
**Scenarios for Multiple Tasks**:
- Large projects requiring per-module test generation
- Separate integration vs unit test tasks
- Specialized test types (performance, security, etc.)
**Agent**: `@code-developer` or specialized agents based on requirements
---
## Artifacts & Output
### Output Files Structure
Created in `.workflow/WFS-test-[session]/`:
```
WFS-test-[session]/
├── workflow-session.json # Session metadata
├── IMPL_PLAN.md # Test generation and execution strategy
├── TODO_LIST.md # Task checklist
├── .task/
│ ├── IMPL-001.json # Test understanding & generation
│ ├── IMPL-002.json # Test execution & fix cycle
│ └── IMPL-*.json # Additional tasks (if applicable)
└── .process/
├── [test-]context-package.json # Context and coverage analysis
└── TEST_ANALYSIS_RESULTS.md # Test requirements and strategy
```
### Session Metadata
**File**: `workflow-session.json`
**Session Mode** includes:
- `workflow_type: "test_session"`
- `source_session_id: "[sourceSessionId]"` (enables automatic cross-session context)
**Prompt Mode** includes:
- `workflow_type: "test_session"`
- No `source_session_id` field
### Complete Data Flow
**Example Command**: `/workflow:test-fix-gen WFS-user-auth`
**Phase Execution Chain**:
1. Phase 1: `session-start``WFS-test-user-auth`
2. Phase 2: `test-context-gather``test-context-package.json`
3. Phase 3: `test-concept-enhanced``TEST_ANALYSIS_RESULTS.md`
4. Phase 4: `test-task-generate``IMPL-001.json` + `IMPL-002.json` (+ additional if needed)
5. Phase 5: Return summary
**Command completes after Phase 5**
---
## Reference
### Error Handling
| Phase | Error Condition | Action |
|-------|----------------|--------|
| 1 | Source session not found (session mode) | Return error with source session ID |
| 1 | No completed IMPL tasks (session mode) | Return error, source incomplete |
| 2 | Context gathering failed | Return error, check source artifacts |
| 3 | Gemini analysis failed | Return error, check context package |
| 4 | Task generation failed | Retry once, then return error with details |
### Best Practices
1. **Before Running**:
- Ensure implementation is complete (session mode: check summaries exist)
- Commit all implementation changes
- Review source code quality
2. **After Running**:
- Review generated `IMPL_PLAN.md` before execution
- Check `TEST_ANALYSIS_RESULTS.md` for completeness
- Verify task dependencies in `TODO_LIST.md`
3. **During Execution**:
- Monitor iteration logs in `.process/fix-iteration-*`
- Track progress with `/workflow:status`
- Review Gemini diagnostic outputs
4. **Mode Selection**:
- Use **Session Mode** for completed workflow validation
- Use **Prompt Mode** for ad-hoc test generation
- Use `--use-codex` for autonomous fix application
- Use `--cli-execute` for enhanced generation capabilities
### Related Commands
**Planning Phase**:
- `/workflow:plan` - Create implementation workflow
- `/workflow:session:start` - Initialize workflow session
**Context Gathering**:
- `/workflow:tools:test-context-gather` - Session-based context (Phase 2 for session mode)
- `/workflow:tools:context-gather` - Prompt-based context (Phase 2 for prompt mode)
**Analysis & Task Generation**:
- `/workflow:tools:test-concept-enhanced` - Gemini test analysis (Phase 3)
- `/workflow:tools:test-task-generate` - Generate test tasks (Phase 4)
**Execution**:
- `/workflow:test-cycle-execute` - Execute test-fix workflow (recommended for IMPL-002)
- `/workflow:execute` - Execute standard workflow tasks
- `/workflow:status` - Check task progress
**Review & Management**:
- `/workflow:review` - Review workflow results
- `/workflow:session:complete` - Mark session complete

View File

@@ -1,319 +1,337 @@
---
name: test-gen
description: Generate comprehensive test workflow based on completed implementation tasks
usage: /workflow:test-gen [session-id]
argument-hint: "WFS-session-id"
examples:
- /workflow:test-gen
- /workflow:test-gen WFS-user-auth
description: Create independent test-fix workflow session by analyzing completed implementation
argument-hint: "[--use-codex] [--cli-execute] source-session-id"
allowed-tools: SlashCommand(*), TodoWrite(*), Read(*), Bash(*)
---
# Workflow Test Generation Command
# Workflow Test Generation Command (/workflow:test-gen)
## Overview
Automatically generates comprehensive test workflows based on completed implementation tasks. **Creates dedicated test session with full test coverage planning**, including unit tests, integration tests, and validation workflows that mirror the implementation structure.
## Coordinator Role
**This command is a pure orchestrator**: Creates an independent test-fix workflow session for validating a completed implementation. It reuses the standard planning toolchain with automatic cross-session context gathering.
**Core Principles**:
- **Session Isolation**: Creates new `WFS-test-[source]` session to keep verification separate from implementation
- **Context-First**: Prioritizes gathering code changes and summaries from source session
- **Format Reuse**: Creates standard `IMPL-*.json` task, using `meta.type: "test-fix"` for agent assignment
- **Parameter Simplification**: Tools auto-detect test session type via metadata, no manual cross-session parameters needed
- **Manual First**: Default to manual fixes, use `--use-codex` flag for automated Codex fix application
**Execution Flow**:
1. Initialize TodoWrite → Create test session → Parse session ID
2. Gather cross-session context (automatic) → Parse context path
3. Analyze implementation with concept-enhanced → Parse ANALYSIS_RESULTS.md
4. Generate test task from analysis → Return summary
**⚠️ Command Scope**: This command ONLY prepares test workflow artifacts. It does NOT execute tests or implementation. Task execution requires separate user action.
## Core Rules
**Analyze completed implementation workflows to generate comprehensive test coverage workflows.**
**Create dedicated test session with systematic test task decomposition following implementation patterns.**
## Core Responsibilities
- **Implementation Analysis**: Analyze completed tasks and their deliverables
- **Test Coverage Planning**: Generate comprehensive test strategies for all implementations
- **Test Workflow Creation**: Create structured test session following workflow architecture
- **Task Decomposition**: Break down test requirements into executable test tasks
- **Dependency Mapping**: Establish test dependencies based on implementation relationships
- **Agent Assignment**: Assign appropriate test agents for different test types
1. **Start Immediately**: First action is TodoWrite initialization, second action is Phase 1 test session creation
2. **No Preliminary Analysis**: Do not read files or analyze before Phase 1
3. **Parse Every Output**: Extract required data from each phase for next phase
4. **Sequential Execution**: Each phase depends on previous phase's output
5. **Complete All Phases**: Do not return to user until Phase 5 completes (summary returned)
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)
9. **⚠️ Command Boundary**: This command ends at Phase 5 summary. Test execution is NOT part of this command.
## Execution Philosophy
- **Coverage-driven**: Ensure all implemented features have corresponding tests
- **Implementation-aware**: Tests reflect actual implementation patterns and dependencies
- **Systematic approach**: Follow established workflow patterns for test planning
- **Agent-optimized**: Assign specialized agents for different test types
- **Continuous validation**: Include ongoing test execution and maintenance tasks
## 5-Phase Execution
## Test Generation Lifecycle
### Phase 1: Create Test Session
**Command**: `SlashCommand(command="/workflow:session:start --new \"Test validation for [sourceSessionId]\"")`
### Phase 1: Implementation Discovery
1. **Session Analysis**: Identify active or recently completed implementation session
2. **Task Analysis**: Parse completed IMPL-* tasks and their deliverables
3. **Code Analysis**: Examine implemented files and functionality
4. **Pattern Recognition**: Identify testing requirements from implementation patterns
**Input**: `sourceSessionId` from user argument (e.g., `WFS-user-auth`)
### Phase 2: Test Strategy Planning
1. **Coverage Mapping**: Map implementation components to test requirements
2. **Test Type Classification**: Categorize tests (unit, integration, e2e, performance)
3. **Dependency Analysis**: Establish test execution dependencies
4. **Tool Selection**: Choose appropriate testing frameworks and tools
**Expected Behavior**:
- Creates new session with pattern `WFS-test-[source-slug]` (e.g., `WFS-test-user-auth`)
- Writes metadata to `workflow-session.json`:
- `workflow_type: "test_session"`
- `source_session_id: "[sourceSessionId]"`
- Returns new session ID for subsequent phases
### Phase 3: Test Workflow Creation
1. **Session Creation**: Create dedicated test session `WFS-test-[base-session]`
2. **Plan Generation**: Create TEST_PLAN.md with comprehensive test strategy
3. **Task Decomposition**: Generate TEST-* task definitions following workflow patterns
4. **Agent Assignment**: Assign specialized test agents for execution
**Parse Output**:
- Extract: new test session ID (store as `testSessionId`)
- Pattern: `WFS-test-[slug]`
### Phase 4: Test Session Setup
1. **Structure Creation**: Establish test workflow directory structure
2. **Context Preparation**: Link test tasks to implementation context
3. **Flow Control Setup**: Configure test execution flow and dependencies
4. **Documentation Generation**: Create test documentation and tracking files
**Validation**:
- Source session `.workflow/[sourceSessionId]/` exists
- Source session has completed IMPL tasks (`.summaries/IMPL-*-summary.md`)
- New test session directory created
- Metadata includes `workflow_type` and `source_session_id`
## Test Discovery & Analysis Process
**TodoWrite**: Mark phase 1 completed, phase 2 in_progress
### Implementation Analysis
---
### Phase 2: Gather Test Context
**Command**: `SlashCommand(command="/workflow:tools:test-context-gather --session [testSessionId]")`
**Input**: `testSessionId` from Phase 1 (e.g., `WFS-test-user-auth`)
**Expected Behavior**:
- Load source session implementation context and summaries
- Analyze test coverage using MCP tools (find existing tests)
- Identify files requiring tests (coverage gaps)
- Detect test framework and conventions
- Generate `test-context-package.json`
**Parse Output**:
- Extract: test context package path (store as `testContextPath`)
- Pattern: `.workflow/[testSessionId]/.process/test-context-package.json`
**Validation**:
- Test context package created
- Contains source session summaries
- Includes coverage gap analysis
- Test framework detected
- Test conventions documented
**TodoWrite**: Mark phase 2 completed, phase 3 in_progress
---
### Phase 3: Test Generation Analysis
**Command**: `SlashCommand(command="/workflow:tools:test-concept-enhanced --session [testSessionId] --context [testContextPath]")`
**Input**:
- `testSessionId` from Phase 1
- `testContextPath` from Phase 2
**Expected Behavior**:
- Use Gemini to analyze coverage gaps and implementation context
- Study existing test patterns and conventions
- Generate test requirements for each missing test file
- Design test generation strategy
- Generate `TEST_ANALYSIS_RESULTS.md`
**Parse Output**:
- Verify `.workflow/[testSessionId]/.process/TEST_ANALYSIS_RESULTS.md` created
- Contains test requirements and generation strategy
- Lists test files to create with specifications
**Validation**:
- TEST_ANALYSIS_RESULTS.md exists with complete sections:
- Coverage Assessment
- Test Framework & Conventions
- Test Requirements by File
- Test Generation Strategy
- Implementation Targets (test files to create)
- Success Criteria
**TodoWrite**: Mark phase 3 completed, phase 4 in_progress
---
### Phase 4: Generate Test Tasks
**Command**: `SlashCommand(command="/workflow:tools:test-task-generate [--use-codex] [--cli-execute] --session [testSessionId]")`
**Input**:
- `testSessionId` from Phase 1
- `--use-codex` flag (if present in original command) - Controls IMPL-002 fix mode
- `--cli-execute` flag (if present in original command) - Controls IMPL-001 generation mode
**Expected Behavior**:
- Parse TEST_ANALYSIS_RESULTS.md from Phase 3
- Extract test requirements and generation strategy
- Generate **TWO task JSON files**:
- **IMPL-001.json**: Test Generation task (calls @code-developer)
- **IMPL-002.json**: Test Execution and Fix Cycle task (calls @test-fix-agent)
- Generate IMPL_PLAN.md with test generation and execution strategy
- Generate TODO_LIST.md with both tasks
**Parse Output**:
- Verify `.workflow/[testSessionId]/.task/IMPL-001.json` exists (test generation)
- Verify `.workflow/[testSessionId]/.task/IMPL-002.json` exists (test execution & fix)
- Verify `.workflow/[testSessionId]/IMPL_PLAN.md` created
- Verify `.workflow/[testSessionId]/TODO_LIST.md` created
**Validation - IMPL-001.json (Test Generation)**:
- Task ID: `IMPL-001`
- `meta.type: "test-gen"`
- `meta.agent: "@code-developer"`
- `context.requirements`: Generate tests based on TEST_ANALYSIS_RESULTS.md
- `flow_control.pre_analysis`: Load TEST_ANALYSIS_RESULTS.md and test context
- `flow_control.implementation_approach`: Test generation steps
- `flow_control.target_files`: Test files to create from analysis section 5
**Validation - IMPL-002.json (Test Execution & Fix)**:
- Task ID: `IMPL-002`
- `meta.type: "test-fix"`
- `meta.agent: "@test-fix-agent"`
- `meta.use_codex: true|false` (based on --use-codex flag)
- `context.depends_on: ["IMPL-001"]`
- `context.requirements`: Execute and fix tests
- `flow_control.implementation_approach.test_fix_cycle`: Complete cycle specification
- **Cycle pattern**: test → gemini_diagnose → manual_fix (or codex if --use-codex) → retest
- **Tools configuration**: Gemini for analysis with bug-fix template, manual or Codex for fixes
- **Exit conditions**: Success (all pass) or failure (max iterations)
- `flow_control.implementation_approach.modification_points`: 3-phase execution flow
- Phase 1: Initial test execution
- Phase 2: Iterative Gemini diagnosis + manual/Codex fixes (based on flag)
- Phase 3: Final validation and certification
**TodoWrite**: Mark phase 4 completed, phase 5 in_progress
---
### Phase 5: Return Summary (⚠️ Command Ends Here)
**⚠️ Important**: This is the final phase of `/workflow:test-gen`. The command completes and returns control to the user. No automatic execution occurs.
**Return to User**:
```
├── Load completed implementation session
├── Analyze IMPL_PLAN.md and completed tasks
├── Scan .summaries/ for implementation deliverables
├── Examine target_files from task definitions
├── Identify implemented features and components
├── Map code coverage requirements
└── Generate test coverage matrix
✅ Test workflow preparation complete!
Source Session: [sourceSessionId]
Test Session: [testSessionId]
Artifacts Created:
- Test context analysis
- Test generation strategy
- Task definitions (IMPL-001, IMPL-002)
- Implementation plan
Test Framework: [detected framework]
Test Files to Generate: [count]
Fix Mode: [Manual|Codex Automated] (based on --use-codex flag)
📋 Review Generated Artifacts:
- Test plan: .workflow/[testSessionId]/IMPL_PLAN.md
- Task list: .workflow/[testSessionId]/TODO_LIST.md
- Analysis: .workflow/[testSessionId]/.process/TEST_ANALYSIS_RESULTS.md
⚠️ Ready for execution. Use appropriate workflow commands to proceed.
```
### Test Pattern Recognition
```
Implementation Pattern → Test Pattern
├── API endpoints → API testing + contract testing
├── Database models → Data validation + migration testing
├── UI components → Component testing + user workflow testing
├── Business logic → Unit testing + integration testing
├── Authentication → Security testing + access control testing
├── Configuration → Environment testing + deployment testing
└── Performance critical → Load testing + performance testing
**TodoWrite**: Mark phase 5 completed
**⚠️ Command Boundary**: After this phase, the command terminates and returns to user prompt.
---
## TodoWrite Pattern
Track progress through 5 phases:
```javascript
TodoWrite({todos: [
{"content": "Create independent test session", "status": "in_progress|completed", "activeForm": "Creating test session"},
{"content": "Gather test coverage context", "status": "pending|in_progress|completed", "activeForm": "Gathering test coverage context"},
{"content": "Analyze test requirements with Gemini", "status": "pending|in_progress|completed", "activeForm": "Analyzing test requirements"},
{"content": "Generate test generation and execution tasks", "status": "pending|in_progress|completed", "activeForm": "Generating test tasks"},
{"content": "Return workflow summary", "status": "pending|in_progress|completed", "activeForm": "Returning workflow summary"}
]})
```
## Test Workflow Structure
Update status to `in_progress` when starting each phase, mark `completed` when done.
## Data Flow
### Generated Test Session Structure
```
.workflow/WFS-test-[base-session]/
├── TEST_PLAN.md # Comprehensive test planning document
├── TODO_LIST.md # Test execution progress tracking
├── .process/
├── TEST_ANALYSIS.md # Test coverage analysis results
└── COVERAGE_MATRIX.md # Implementation-to-test mapping
├── .task/
├── TEST-001.json # Unit test tasks
├── TEST-002.json # Integration test tasks
├── TEST-003.json # E2E test tasks
└── TEST-004.json # Performance test tasks
├── .summaries/ # Test execution summaries
└── .context/
├── impl-context.md # Implementation context reference
└── test-fixtures.md # Test data and fixture planning
┌─────────────────────────────────────────────────────────┐
│ /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 │
└─────────────────────────────────────────────────────────┘
⚠️ COMMAND ENDS - Control returns to user
Artifacts Created:
├── .workflow/WFS-test-[session]/
│ ├── workflow-session.json
│ ├── IMPL_PLAN.md
│ ├── TODO_LIST.md
│ ├── .task/
│ │ ├── IMPL-001.json (test generation task)
│ │ └── IMPL-002.json (test execution task)
│ └── .process/
│ ├── test-context-package.json
│ └── TEST_ANALYSIS_RESULTS.md
```
## Test Task Types & Agent Assignment
## Session Metadata
### Task Categories
1. **Unit Tests** (`TEST-U-*`)
- **Agent**: `code-review-test-agent`
- **Scope**: Individual function/method testing
- **Dependencies**: Implementation files
Test session includes `workflow_type: "test_session"` and `source_session_id` for automatic context gathering.
2. **Integration Tests** (`TEST-I-*`)
- **Agent**: `code-review-test-agent`
- **Scope**: Component interaction testing
- **Dependencies**: Unit tests completion
## Task Output
3. **End-to-End Tests** (`TEST-E-*`)
- **Agent**: `general-purpose`
- **Scope**: User workflow and system testing
- **Dependencies**: Integration tests completion
Generates two task definition files:
- **IMPL-001.json**: Test generation task specification
- Agent: @code-developer
- Input: TEST_ANALYSIS_RESULTS.md
- Output: Test files based on analysis
- **IMPL-002.json**: Test execution and fix cycle specification
- Agent: @test-fix-agent
- Dependency: IMPL-001 must complete first
- Max iterations: 5
- Fix mode: Manual or Codex (based on --use-codex flag)
4. **Performance Tests** (`TEST-P-*`)
- **Agent**: `code-developer`
- **Scope**: Load, stress, and performance validation
- **Dependencies**: E2E tests completion
See `/workflow:tools:test-task-generate` for complete task JSON schemas.
5. **Security Tests** (`TEST-S-*`)
- **Agent**: `code-review-test-agent`
- **Scope**: Security validation and vulnerability testing
- **Dependencies**: Implementation completion
## Error Handling
6. **Documentation Tests** (`TEST-D-*`)
- **Agent**: `doc-generator`
- **Scope**: Documentation validation and example testing
- **Dependencies**: Feature tests completion
| 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 |
## Test Task JSON Schema
## Output Files
Each test task follows the 5-field workflow architecture with test-specific extensions:
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
### Basic Test Task Structure
```json
{
"id": "TEST-U-001",
"title": "Unit tests for authentication service",
"status": "pending",
"meta": {
"type": "unit-test",
"agent": "code-review-test-agent",
"test_framework": "jest",
"coverage_target": "90%",
"impl_reference": "IMPL-001"
},
"context": {
"requirements": "Test all authentication service functions with edge cases",
"focus_paths": ["src/auth/", "tests/unit/auth/"],
"acceptance": [
"All auth service functions tested",
"Edge cases covered",
"90% code coverage achieved",
"Tests pass in CI/CD pipeline"
],
"depends_on": [],
"impl_context": "IMPL-001-summary.md",
"test_data": "auth-test-fixtures.json"
},
"flow_control": {
"pre_analysis": [
{
"step": "load_impl_context",
"action": "Load implementation context and deliverables",
"command": "bash(cat .workflow/WFS-[base-session]/.summaries/IMPL-001-summary.md)",
"output_to": "impl_context"
},
{
"step": "analyze_test_coverage",
"action": "Analyze existing test coverage and gaps",
"command": "bash(find src/auth/ -name '*.js' -o -name '*.ts' | head -20)",
"output_to": "coverage_analysis"
}
],
"implementation_approach": "test-driven",
"target_files": [
"tests/unit/auth/auth-service.test.js",
"tests/unit/auth/auth-utils.test.js",
"tests/fixtures/auth-test-data.json"
]
}
}
```
## Task Specifications
## Test Context Management
**IMPL-001.json Structure**:
- `meta.type: "test-gen"`
- `meta.agent: "@code-developer"`
- `context.requirements`: Generate tests based on TEST_ANALYSIS_RESULTS.md
- `flow_control.target_files`: Test files to create
- `flow_control.implementation_approach`: Test generation strategy
### Implementation Context Integration
Test tasks automatically inherit context from corresponding implementation tasks:
**IMPL-002.json Structure**:
- `meta.type: "test-fix"`
- `meta.agent: "@test-fix-agent"`
- `meta.use_codex`: true/false (based on --use-codex flag)
- `context.depends_on: ["IMPL-001"]`
- `flow_control.implementation_approach.test_fix_cycle`: Complete cycle specification
- Gemini diagnosis template
- Fix application mode (manual/codex)
- Max iterations: 5
- `flow_control.implementation_approach.modification_points`: 3-phase flow
```json
"context": {
"impl_reference": "IMPL-001",
"impl_summary": ".workflow/WFS-[base-session]/.summaries/IMPL-001-summary.md",
"impl_files": ["src/auth/service.js", "src/auth/middleware.js"],
"test_requirements": "derived from implementation acceptance criteria",
"coverage_requirements": "90% line coverage, 80% branch coverage"
}
```
See `/workflow:tools:test-task-generate` for complete JSON schemas.
### Flow Control for Test Execution
```json
"flow_control": {
"pre_analysis": [
{
"step": "load_impl_deliverables",
"action": "Load implementation files and analyze test requirements",
"command": "~/.claude/scripts/gemini-wrapper -p \"PURPOSE: Analyze implementation for test requirements TASK: Review [impl_files] and identify test cases CONTEXT: @{[impl_files]} EXPECTED: Comprehensive test case list RULES: Focus on edge cases and integration points\""
},
{
"step": "setup_test_environment",
"action": "Prepare test environment and fixtures",
"command": "codex --full-auto exec \"Setup test environment for [test_framework] with fixtures for [feature_name]\" -s danger-full-access"
}
]
}
```
## Best Practices
## Session Management & Integration
1. **Prerequisites**: Ensure source session has completed IMPL tasks with summaries
2. **Clean State**: Commit implementation changes before running test-gen
3. **Review Artifacts**: Check generated IMPL_PLAN.md and TODO_LIST.md before proceeding
4. **Understand Scope**: This command only prepares artifacts; it does not execute tests
### Test Session Creation Process
1. **Base Session Discovery**: Identify implementation session to test
2. **Test Session Creation**: Create `WFS-test-[base-session]` directory structure
3. **Context Linking**: Establish references to implementation context
4. **Active Marker**: Create `.active-test-[base-session]` marker for session management
## Related Commands
### Integration with Execute Command
Test workflows integrate seamlessly with existing execute infrastructure:
- Use same TodoWrite progress tracking
- Follow same agent orchestration patterns
- Support same flow control mechanisms
- Maintain same session isolation and management
## Usage Examples
### Generate Tests for Completed Implementation
```bash
# After completing an implementation workflow
/workflow:execute # Complete implementation tasks
# Generate comprehensive test workflow
/workflow:test-gen # Auto-detects active session
# Execute test workflow
/workflow:execute # Runs test tasks
```
### Generate Tests for Specific Session
```bash
# Generate tests for specific implementation session
/workflow:test-gen WFS-user-auth-system
# Check test workflow status
/workflow:status --session=WFS-test-user-auth-system
# Execute specific test category
/task:execute TEST-U-001 # Run unit tests
```
### Multi-Phase Test Generation
```bash
# Generate and execute tests in phases
/workflow:test-gen WFS-api-implementation
/task:execute TEST-U-* # Unit tests first
/task:execute TEST-I-* # Integration tests
/task:execute TEST-E-* # E2E tests last
```
## Error Handling & Recovery
### Implementation Analysis Errors
| Error | Cause | Resolution |
|-------|-------|------------|
| No completed implementations | No IMPL-* tasks found | Complete implementation tasks first |
| Missing implementation context | Corrupted summaries | Regenerate summaries from task results |
| Invalid implementation files | File references broken | Update file paths and re-analyze |
### Test Generation Errors
| Error | Cause | Recovery Strategy |
|-------|-------|------------------|
| Test framework not detected | No testing setup found | Prompt for test framework selection |
| Insufficient implementation context | Missing implementation details | Request additional implementation documentation |
| Test session collision | Test session already exists | Merge or create versioned test session |
## Key Benefits
### Comprehensive Coverage
- **Implementation-driven**: Tests generated based on actual implementation patterns
- **Multi-layered**: Unit, integration, E2E, and specialized testing
- **Dependency-aware**: Test execution follows logical dependency chains
- **Agent-optimized**: Specialized agents for different test types
### Workflow Integration
- **Seamless execution**: Uses existing workflow infrastructure
- **Progress tracking**: Full TodoWrite integration for test progress
- **Context preservation**: Maintains links to implementation context
- **Session management**: Independent test sessions with proper isolation
### Maintenance & Evolution
- **Updateable**: Test workflows can evolve with implementation changes
- **Traceable**: Clear mapping from implementation to test requirements
- **Extensible**: Support for new test types and frameworks
- **Documentable**: Comprehensive test documentation and coverage reports
## Integration Points
- **Planning**: Integrates with `/workflow:plan` for test planning
- **Execution**: Uses `/workflow:execute` for test task execution
- **Status**: Works with `/workflow:status` for test progress tracking
- **Documentation**: Coordinates with `/workflow:docs` for test documentation
- **Review**: Supports `/workflow:review` for test validation and coverage analysis
- `/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

@@ -0,0 +1,229 @@
---
name: concept-enhanced
description: Enhanced intelligent analysis with parallel CLI execution and design blueprint generation
argument-hint: "--session WFS-session-id --context path/to/context-package.json"
examples:
- /workflow:tools:concept-enhanced --session WFS-auth --context .workflow/WFS-auth/.process/context-package.json
- /workflow:tools:concept-enhanced --session WFS-payment --context .workflow/WFS-payment/.process/context-package.json
---
# Enhanced Analysis Command (/workflow:tools:concept-enhanced)
## Overview
Advanced solution design and feasibility analysis engine with parallel CLI execution. Processes standardized context packages to produce ANALYSIS_RESULTS.md focused on solution improvements, key design decisions, and critical insights.
**Scope**: Solution-focused technical analysis only. Does NOT generate task breakdowns or implementation plans.
**Usage**: Standalone command or integrated into `/workflow:plan`. Accepts context packages and orchestrates Gemini/Codex for comprehensive analysis.
## Core Philosophy & Responsibilities
- **Agent Coordination**: Delegate analysis execution to specialized agent (cli-execution-agent)
- **Solution-Focused Analysis**: Emphasize design decisions, architectural rationale, and critical insights (exclude task planning)
- **Context-Driven**: Parse and validate context-package.json for precise analysis
- **Agent-Driven Tool Selection**: Agent autonomously selects Gemini/Codex based on task complexity
- **Solution Design**: Evaluate architecture, identify key design decisions with rationale
- **Feasibility Assessment**: Analyze technical complexity, risks, implementation readiness
- **Optimization Recommendations**: Performance, security, and code quality improvements
- **Output Validation**: Verify ANALYSIS_RESULTS.md generation and quality
- **Single Output**: Generate only ANALYSIS_RESULTS.md with technical analysis
## Analysis Strategy Selection
**Agent-Driven Strategy**: cli-execution-agent autonomously determines tool selection based on:
- **Task Complexity**: Number of modules, integration scope, technical depth
- **Tech Stack**: Frontend (Gemini-focused), Backend (Codex-preferred), Fullstack (hybrid)
- **Analysis Focus**: Architecture design (Gemini), Feasibility validation (Codex), Performance optimization (both)
**Complexity Tiers** (Agent decides internally):
- **Simple (≤3 modules)**: Gemini-only analysis
- **Medium (4-6 modules)**: Gemini comprehensive analysis
- **Complex (>6 modules)**: Gemini + Codex parallel execution
## Execution Lifecycle
### Phase 1: Validation & Preparation
1. **Session Validation**: Verify `.workflow/{session_id}/` exists, load `workflow-session.json`
2. **Context Package Validation**: Verify path, validate JSON format and structure
3. **Task Analysis**: Extract keywords, identify domain/complexity, determine scope
4. **Agent Preparation**: Prepare agent task prompt with complete analysis requirements
### Phase 2: Agent-Delegated Analysis
**Agent Invocation**:
```javascript
Task(
subagent_type="cli-execution-agent",
description="Enhanced solution design and feasibility analysis",
prompt=`
## Execution Context
**Session ID**: {session_id}
**Mode**: Enhanced Analysis with CLI Tool Orchestration
## Input Context
**Context Package**: {context_path}
**Session State**: .workflow/{session_id}/workflow-session.json
**Project Standards**: CLAUDE.md
## Analysis Task
### Analysis Templates (Use these to guide CLI tool execution)
- **Document Structure**: ~/.claude/workflows/cli-templates/prompts/workflow/analysis-results-structure.txt
- **Gemini Analysis**: ~/.claude/workflows/cli-templates/prompts/workflow/gemini-solution-design.txt
- **Codex Validation**: ~/.claude/workflows/cli-templates/prompts/workflow/codex-feasibility-validation.txt
### Execution Strategy
1. **Load Context**: Read context-package.json to determine task complexity (module count, integration scope)
2. **Gemini Analysis** (ALL tasks): Execute using gemini-solution-design.txt template
- Output: .workflow/{session_id}/.process/gemini-solution-design.md
3. **Codex Validation** (COMPLEX tasks >6 modules only): Execute using codex-feasibility-validation.txt template
- Output: .workflow/{session_id}/.process/codex-feasibility-validation.md
4. **Synthesize Results**: Combine outputs into ANALYSIS_RESULTS.md following analysis-results-structure.txt
### Output Requirements
**Intermediate Outputs**:
- Gemini: \`.workflow/{session_id}/.process/gemini-solution-design.md\` (always required)
- Codex: \`.workflow/{session_id}/.process/codex-feasibility-validation.md\` (complex tasks only)
**Final Output**:
- \`.workflow/{session_id}/.process/ANALYSIS_RESULTS.md\` (synthesized, required)
**Required Sections** (7 sections per analysis-results-structure.txt):
1. Executive Summary
2. Current State Analysis
3. Proposed Solution Design
4. Implementation Strategy
5. Solution Optimization
6. Critical Success Factors
7. Reference Information
### Synthesis Rules
- Follow 7-section structure from analysis-results-structure.txt
- Integrate Gemini insights as primary content
- Incorporate Codex validation findings (if executed)
- Resolve conflicts between tools with clear rationale
- Generate confidence scores (1-5 scale) for all assessment dimensions
- Provide final recommendation: PROCEED | PROCEED_WITH_MODIFICATIONS | RECONSIDER | REJECT
## Output
Generate final ANALYSIS_RESULTS.md and report completion status:
- Gemini analysis: [completed/failed]
- Codex validation: [completed/skipped/failed]
- Synthesis: [completed/failed]
- Final output: .workflow/{session_id}/.process/ANALYSIS_RESULTS.md
`
)
```
**Agent Execution Flow** (Internal to cli-execution-agent):
1. Parse session ID and context path, load context-package.json
2. Analyze task complexity (module count, integration scope)
3. Discover additional context via MCP code-index
4. Execute Gemini analysis (all tasks) with template-guided prompt
5. Execute Codex validation (complex tasks >6 modules) with template-guided prompt
6. Synthesize Gemini + Codex outputs into ANALYSIS_RESULTS.md
7. Verify output file exists at correct path
8. Return execution log path
**Command Execution**: Launch agent via Task tool, wait for completion
### Phase 3: Output Validation
1. **File Verification**: Confirm `.workflow/{session_id}/.process/ANALYSIS_RESULTS.md` exists
2. **Content Validation**: Verify required sections present (Executive Summary, Solution Design, etc.)
3. **Quality Check**: Ensure design rationale, feasibility assessment, confidence scores included
4. **Agent Log**: Retrieve agent execution log from `.workflow/{session_id}/.chat/`
5. **Success Criteria**: File exists, contains all required sections, meets quality standards
## Analysis Results Format
**Template Reference**: `~/.claude/workflows/cli-templates/prompts/workflow/analysis-results-structure.txt`
Generated ANALYSIS_RESULTS.md focuses on **solution improvements, key design decisions, and critical insights** (NOT task planning).
### Required Structure (7 Sections)
1. **Executive Summary**: Analysis focus, tools used, overall assessment (X/5), recommendation status
2. **Current State Analysis**: Architecture overview, compatibility/dependencies, critical findings
3. **Proposed Solution Design**: Core principles, system design, key decisions with rationale, technical specs
4. **Implementation Strategy**: Development approach, code modification targets, feasibility assessment, risk mitigation
5. **Solution Optimization**: Performance, security, code quality recommendations
6. **Critical Success Factors**: Technical requirements, quality metrics, success validation
7. **Reference Information**: Tool analysis summary, context & resources
### Key Requirements
**Code Modification Targets**:
- Existing files: `file:function:lines` (e.g., `src/auth/login.ts:validateUser:45-52`)
- New files: `file` only (e.g., `src/auth/PasswordReset.ts`)
- Unknown lines: `file:function:*`
**Key Design Decisions** (minimum 2):
- Decision statement
- Rationale (why this approach)
- Alternatives considered (tradeoffs)
- Impact (implications on architecture)
**Assessment Scores** (1-5 scale):
- Conceptual Integrity, Architectural Soundness, Technical Feasibility, Implementation Readiness
- Overall Confidence score
- Final Recommendation: PROCEED | PROCEED_WITH_MODIFICATIONS | RECONSIDER | REJECT
### Content Focus
- ✅ Solution improvements and architectural decisions
- ✅ Design rationale, alternatives, and tradeoffs
- ✅ Risk assessment with mitigation strategies
- ✅ Optimization opportunities (performance, security, quality)
- ❌ Task lists or implementation steps
- ❌ Code examples or snippets
- ❌ Project management timelines
## Execution Management
### Error Handling & Recovery
1. **Pre-execution**: Verify session/context package exists and is valid
2. **Agent Monitoring**: Track agent execution status via Task tool
3. **Validation**: Check ANALYSIS_RESULTS.md generation on completion
4. **Error Recovery**:
- Agent execution failure → report error, check agent logs
- Missing output file → retry agent execution once
- Incomplete output → use agent logs to diagnose issue
5. **Graceful Degradation**: If agent fails, report specific error and suggest manual analysis
### Agent Delegation Benefits
- **Autonomous Tool Selection**: Agent decides Gemini/Codex based on complexity
- **Context Discovery**: Agent discovers additional relevant files via MCP
- **Prompt Enhancement**: Agent optimizes prompts with discovered patterns
- **Error Handling**: Agent manages CLI tool failures internally
- **Log Tracking**: Agent execution logs saved to `.workflow/{session_id}/.chat/`
## Integration & Success Criteria
### Input/Output Interface
**Input**:
- `--session` (required): Session ID (e.g., WFS-auth)
- `--context` (required): Context package path
**Output**:
- Single file: `ANALYSIS_RESULTS.md` at `.workflow/{session_id}/.process/`
- No supplementary files (JSON, roadmap, templates)
### Quality & Success Validation
**Quality Checks**: Completeness, consistency, feasibility validation
**Success Criteria**:
- ✅ Solution-focused analysis (design decisions, critical insights, NO task planning)
- ✅ Single output file only (ANALYSIS_RESULTS.md)
- ✅ Design decision depth with rationale/alternatives/tradeoffs
- ✅ Feasibility assessment (complexity, risks, readiness)
- ✅ Optimization strategies (performance, security, quality)
- ✅ Agent-driven tool selection (autonomous Gemini/Codex execution)
- ✅ Robust error handling (validation, retry, graceful degradation)
- ✅ Confidence scoring with clear recommendation status
- ✅ Agent execution log saved to session chat directory
## Related Commands
- `/context:gather` - Generate context packages required by this command
- `/workflow:plan` - Call this command for analysis
- `/task:create` - Create specific tasks based on analysis results

View File

@@ -0,0 +1,353 @@
---
name: gather
description: Intelligently collect project context using general-purpose agent based on task description and package into standardized JSON
argument-hint: "--session WFS-session-id \"task description\""
examples:
- /workflow:tools:context-gather --session WFS-user-auth "Implement user authentication system"
- /workflow:tools:context-gather --session WFS-payment "Refactor payment module API"
- /workflow:tools:context-gather --session WFS-bugfix "Fix login validation error"
---
# Context Gather Command (/workflow:tools:context-gather)
## Overview
Agent-driven intelligent context collector that gathers relevant information from project codebase, documentation, and dependencies based on task descriptions, generating standardized context packages.
## Core Philosophy
- **Agent-Driven**: Delegate execution to general-purpose agent for autonomous operation
- **Two-Phase Flow**: Discovery (context loading) → Execution (context gathering and packaging)
- **Memory-First**: Reuse loaded documents from conversation memory
- **MCP-Enhanced**: Use MCP tools for advanced code analysis and file discovery
- **Intelligent Collection**: Auto-identify relevant resources based on keyword analysis
- **Comprehensive Coverage**: Collect code, documentation, configurations, and dependencies
- **Standardized Output**: Generate unified format context-package.json
## Execution Lifecycle
### Phase 1: Discovery & Context Loading
**⚡ Memory-First Rule**: Skip file loading if documents already in conversation memory
**Agent Context Package**:
```javascript
{
"session_id": "WFS-[session-id]",
"task_description": "[user provided task description]",
"session_metadata": {
// If in memory: use cached content
// Else: Load from .workflow/{session-id}/workflow-session.json
},
"mcp_capabilities": {
// Agent will use these tools to discover project context
"code_index": true,
"exa_code": true,
"exa_web": true
}
}
// Agent will autonomously execute:
// - Project structure analysis: bash(~/.claude/scripts/get_modules_by_depth.sh)
// - Documentation loading: Read(CLAUDE.md), Read(README.md)
```
**Discovery Actions**:
1. **Load Session Context** (if not in memory)
```javascript
if (!memory.has("workflow-session.json")) {
Read(.workflow/{session-id}/workflow-session.json)
}
```
### Phase 2: Agent Execution (Context Gathering & Packaging)
**Agent Invocation**:
```javascript
Task(
subagent_type="general-purpose",
description="Gather project context and generate context package",
prompt=`
## Execution Context
**Session ID**: WFS-{session-id}
**Task Description**: {task_description}
**Mode**: Agent-Driven Context Gathering
## Phase 1: Discovery Results (Provided Context)
### Session Metadata
{session_metadata_content}
### MCP Capabilities
- code-index: Available for file discovery and code search
- exa-code: Available for external research
- exa-web: Available for web search
## Phase 2: Context Gathering Task
### Core Responsibilities
1. **Project Structure Analysis**: Execute get_modules_by_depth.sh for architecture overview
2. **Documentation Loading**: Load CLAUDE.md, README.md and relevant documentation
3. **Keyword Extraction**: Extract core keywords from task description
4. **Smart File Discovery**: Use MCP code-index tools to locate relevant files
5. **Code Structure Analysis**: Analyze project structure to identify relevant modules
6. **Dependency Discovery**: Identify tech stack and dependency relationships
7. **Context Packaging**: Generate standardized JSON context package
### Execution Process
#### Step 0: Foundation Setup (Execute First)
1. **Project Structure Analysis**
Execute to get comprehensive architecture overview:
\`\`\`javascript
bash(~/.claude/scripts/get_modules_by_depth.sh)
\`\`\`
2. **Load Project Documentation** (if not in memory)
Load core project documentation:
\`\`\`javascript
Read(CLAUDE.md)
Read(README.md)
// Load other relevant documentation based on session context
\`\`\`
#### Step 1: Task Analysis
1. **Keyword Extraction**
- Parse task description to extract core keywords
- Identify technical domain (auth, API, frontend, backend, etc.)
- Determine complexity level (simple, medium, complex)
2. **Scope Determination**
- Define collection scope based on keywords
- Identify potentially involved modules and components
- Set file type filters
#### Step 2: MCP-Enhanced File Discovery
1. **Code File Location**
Use MCP code-index tools:
\`\`\`javascript
// Find files by pattern
mcp__code-index__find_files(pattern="*{keyword}*")
// Search code content
mcp__code-index__search_code_advanced(
pattern="{keyword_patterns}",
file_pattern="*.{ts,js,py,go,md}",
context_lines=3
)
// Get file summaries
mcp__code-index__get_file_summary(file_path="relevant/file.ts")
\`\`\`
2. **Configuration Files Discovery**
Locate: package.json, requirements.txt, Cargo.toml, tsconfig.json, etc.
3. **Test Files Location**
Find test files related to task keywords
#### Step 3: Intelligent Filtering & Association
1. **Relevance Scoring**
- Score based on keyword match degree
- Score based on file path relevance
- Score based on code content relevance
2. **Dependency Analysis**
- Analyze import/require statements
- Identify inter-module dependencies
- Determine core and optional dependencies
#### Step 4: Context Packaging
Generate standardized context-package.json following the format below
### Required Output
**Output Location**: \`.workflow/{session-id}/.process/context-package.json\`
**Output Format**:
\`\`\`json
{
"metadata": {
"task_description": "Implement user authentication system",
"timestamp": "2025-09-29T10:30:00Z",
"keywords": ["user", "authentication", "JWT", "login"],
"complexity": "medium",
"tech_stack": ["typescript", "node.js", "express"],
"session_id": "WFS-user-auth"
},
"assets": [
{
"type": "documentation",
"path": "CLAUDE.md",
"relevance": "Project development standards and conventions",
"priority": "high"
},
{
"type": "documentation",
"path": ".workflow/docs/architecture/security.md",
"relevance": "Security architecture design guidance",
"priority": "high"
},
{
"type": "source_code",
"path": "src/auth/AuthService.ts",
"relevance": "Existing authentication service implementation",
"priority": "high"
},
{
"type": "source_code",
"path": "src/models/User.ts",
"relevance": "User data model definition",
"priority": "medium"
},
{
"type": "config",
"path": "package.json",
"relevance": "Project dependencies and tech stack",
"priority": "medium"
},
{
"type": "test",
"path": "tests/auth/*.test.ts",
"relevance": "Authentication related test cases",
"priority": "medium"
}
],
"tech_stack": {
"frameworks": ["express", "typescript"],
"libraries": ["jsonwebtoken", "bcrypt"],
"testing": ["jest", "supertest"]
},
"statistics": {
"total_files": 15,
"source_files": 8,
"docs_files": 4,
"config_files": 2,
"test_files": 1
}
}
\`\`\`
### Quality Validation
Before completion, verify:
- [ ] context-package.json created in correct location
- [ ] Valid JSON format with all required fields
- [ ] Metadata includes task description, keywords, complexity
- [ ] Assets array contains relevant files with priorities
- [ ] Tech stack accurately identified
- [ ] Statistics section provides file counts
- [ ] File relevance accuracy >80%
- [ ] No sensitive information exposed
### Performance Optimization
**Large Project Optimization**:
- File count limit: Maximum 50 files per type
- Size filtering: Skip oversized files (>10MB)
- Depth limit: Maximum search depth of 3 levels
- Use MCP tools for efficient discovery
**MCP Tools Integration**:
Agent should use MCP code-index tools when available:
\`\`\`javascript
// Set project path
mcp__code-index__set_project_path(path="{current_project_path}")
// Refresh index
mcp__code-index__refresh_index()
// Find files by pattern
mcp__code-index__find_files(pattern="*{keyword}*")
// Search code content
mcp__code-index__search_code_advanced(
pattern="{keyword_patterns}",
file_pattern="*.{ts,js,py,go,md}",
context_lines=3
)
\`\`\`
**Fallback Strategy**:
When MCP tools unavailable, agent should use traditional commands:
- \`find\` for file discovery
- \`rg\` or \`grep\` for content search
- Bash commands from project structure analysis
## Output
Generate context-package.json and report completion:
- Task description: {description}
- Keywords extracted: {count}
- Files collected: {total}
- Source files: {count}
- Documentation: {count}
- Configuration: {count}
- Tests: {count}
- Tech stack identified: {frameworks/libraries}
- Output location: .workflow/{session-id}/.process/context-package.json
\`
)
\`\`\`
## Command Integration
### Usage
```bash
# Basic usage
/workflow:tools:context-gather --session WFS-auth "Implement JWT authentication"
# Called by /workflow:plan
SlashCommand(command="/workflow:tools:context-gather --session WFS-[id] \\"[task description]\\"")
```
### Agent Context Passing
**Memory-Aware Context Assembly**:
```javascript
// Assemble minimal context package for agent
// Agent will execute project structure analysis and documentation loading
const agentContext = {
session_id: "WFS-[id]",
task_description: "[user provided task description]",
// Use memory if available, else load
session_metadata: memory.has("workflow-session.json")
? memory.get("workflow-session.json")
: Read(.workflow/WFS-[id]/workflow-session.json),
// MCP capabilities - agent will use these tools
mcp_capabilities: {
code_index: true,
exa_code: true,
exa_web: true
}
}
// Note: Agent will execute these steps autonomously:
// - bash(~/.claude/scripts/get_modules_by_depth.sh) for project structure
// - Read(CLAUDE.md) and Read(README.md) for documentation
```
## Session ID Integration
### Session ID Usage
- **Required Parameter**: `--session WFS-session-id`
- **Session Context Loading**: Load existing session state and metadata
- **Session Continuity**: Maintain context across workflow pipeline phases
### Session Validation
```javascript
// Validate session exists
const sessionPath = `.workflow/${session_id}`;
if (!fs.existsSync(sessionPath)) {
console.error(`❌ Session ${session_id} not found`);
process.exit(1);
}
```
## Success Criteria
- Valid context-package.json generated in correct location
- Contains sufficient relevant information (>80% relevance)
- Execution completes within reasonable time (<2 minutes)
- All required fields present and properly formatted
- Agent reports completion status with statistics

View File

@@ -0,0 +1,340 @@
---
name: task-generate-agent
description: Autonomous task generation using action-planning-agent with discovery and output phases
argument-hint: "--session WFS-session-id [--cli-execute]"
examples:
- /workflow:tools:task-generate-agent --session WFS-auth
- /workflow:tools:task-generate-agent --session WFS-auth --cli-execute
---
# Autonomous Task Generation Command
## Overview
Autonomous task JSON and IMPL_PLAN.md generation using action-planning-agent with two-phase execution: discovery and document generation. Supports both agent-driven execution (default) and CLI tool execution modes.
## Core Philosophy
- **Agent-Driven**: Delegate execution to action-planning-agent for autonomous operation
- **Two-Phase Flow**: Discovery (context gathering) → Output (document generation)
- **Memory-First**: Reuse loaded documents from conversation memory
- **MCP-Enhanced**: Use MCP tools for advanced code analysis and research
- **Pre-Selected Templates**: Command selects correct template based on `--cli-execute` flag **before** invoking agent
- **Agent Simplicity**: Agent receives pre-selected template and focuses only on content generation
## Execution Lifecycle
### Phase 1: Discovery & Context Loading
**⚡ Memory-First Rule**: Skip file loading if documents already in conversation memory
**Agent Context Package**:
```javascript
{
"session_id": "WFS-[session-id]",
"execution_mode": "agent-mode" | "cli-execute-mode", // Determined by flag
"task_json_template_path": "~/.claude/workflows/cli-templates/prompts/workflow/task-json-agent-mode.txt"
| "~/.claude/workflows/cli-templates/prompts/workflow/task-json-cli-mode.txt",
// Path selected by command based on --cli-execute flag, agent reads it
"session_metadata": {
// If in memory: use cached content
// Else: Load from .workflow/{session-id}/workflow-session.json
},
"analysis_results": {
// If in memory: use cached content
// Else: Load from .workflow/{session-id}/.process/ANALYSIS_RESULTS.md
},
"artifacts_inventory": {
// If in memory: use cached list
// Else: Scan .workflow/{session-id}/.brainstorming/ directory
"synthesis_specification": "path or null",
"topic_framework": "path or null",
"role_analyses": ["paths"]
},
"context_package": {
// If in memory: use cached content
// Else: Load from .workflow/{session-id}/.process/context-package.json
},
"mcp_capabilities": {
"code_index": true,
"exa_code": true,
"exa_web": true
}
}
```
**Discovery Actions**:
1. **Load Session Context** (if not in memory)
```javascript
if (!memory.has("workflow-session.json")) {
Read(.workflow/{session-id}/workflow-session.json)
}
```
2. **Load Analysis Results** (if not in memory)
```javascript
if (!memory.has("ANALYSIS_RESULTS.md")) {
Read(.workflow/{session-id}/.process/ANALYSIS_RESULTS.md)
}
```
3. **Discover Artifacts** (if not in memory)
```javascript
if (!memory.has("artifacts_inventory")) {
bash(find .workflow/{session-id}/.brainstorming/ -name "*.md" -type f)
}
```
4. **MCP Code Analysis** (optional - enhance understanding)
```javascript
// Find relevant files for task context
mcp__code-index__find_files(pattern="*auth*")
mcp__code-index__search_code_advanced(
pattern="authentication|oauth",
file_pattern="*.ts"
)
```
5. **MCP External Research** (optional - gather best practices)
```javascript
// Get external examples for implementation
mcp__exa__get_code_context_exa(
query="TypeScript JWT authentication best practices",
tokensNum="dynamic"
)
```
### Phase 2: Agent Execution (Document Generation)
**Pre-Agent Template Selection** (Command decides path before invoking agent):
```javascript
// Command checks flag and selects template PATH (not content)
const templatePath = hasCliExecuteFlag
? "~/.claude/workflows/cli-templates/prompts/workflow/task-json-cli-mode.txt"
: "~/.claude/workflows/cli-templates/prompts/workflow/task-json-agent-mode.txt";
```
**Agent Invocation**:
```javascript
Task(
subagent_type="action-planning-agent",
description="Generate task JSON and implementation plan",
prompt=`
## Execution Context
**Session ID**: WFS-{session-id}
**Execution Mode**: {agent-mode | cli-execute-mode}
**Task JSON Template Path**: {template_path}
## Phase 1: Discovery Results (Provided Context)
### Session Metadata
{session_metadata_content}
### Analysis Results
{analysis_results_content}
### Artifacts Inventory
- **Synthesis Specification**: {synthesis_spec_path}
- **Topic Framework**: {topic_framework_path}
- **Role Analyses**: {role_analyses_list}
### Context Package
{context_package_summary}
### MCP Analysis Results (Optional)
**Code Structure**: {mcp_code_index_results}
**External Research**: {mcp_exa_research_results}
## Phase 2: Document Generation Task
### Task Decomposition Standards
**Core Principle**: Task Merging Over Decomposition
- **Merge Rule**: Execute together when possible
- **Decompose Only When**:
- Excessive workload (>2500 lines or >6 files)
- Different tech stacks or domains
- Sequential dependency blocking
- Parallel execution needed
**Task Limits**:
- **Maximum 10 tasks** (hard limit)
- **Function-based**: Complete units (logic + UI + tests + config)
- **Hierarchy**: Flat (≤5) | Two-level (6-10) | Re-scope (>10)
### Required Outputs
#### 1. Task JSON Files (.task/IMPL-*.json)
**Location**: .workflow/{session-id}/.task/
**Template**: Read from the template path provided above
**Task JSON Template Loading**:
\`\`\`
Read({template_path})
\`\`\`
**Important**:
- Read the template from the path provided in context
- Use the template structure exactly as written
- Replace placeholder variables ({synthesis_spec_path}, {role_analysis_path}, etc.) with actual session-specific paths
- Include MCP tool integration in pre_analysis steps
- Map artifacts based on task domain (UI → ui-designer, Backend → system-architect)
#### 2. IMPL_PLAN.md
**Location**: .workflow/{session-id}/IMPL_PLAN.md
**IMPL_PLAN Template**:
\`\`\`
$(cat ~/.claude/workflows/cli-templates/prompts/workflow/impl-plan-template.txt)
\`\`\`
**Important**:
- Use the template above for IMPL_PLAN.md generation
- Replace all {placeholder} variables with actual session-specific values
- Populate CCW Workflow Context based on actual phase progression
- Extract content from ANALYSIS_RESULTS.md and context-package.json
- List all detected brainstorming artifacts with correct paths
#### 3. TODO_LIST.md
**Location**: .workflow/{session-id}/TODO_LIST.md
**Structure**:
\`\`\`markdown
# Tasks: {Session Topic}
## Task Progress
**IMPL-001**: [Main Task Group] → [📋](./.task/IMPL-001.json)
- [ ] **IMPL-001.1**: [Subtask] → [📋](./.task/IMPL-001.1.json)
- [ ] **IMPL-001.2**: [Subtask] → [📋](./.task/IMPL-001.2.json)
- [ ] **IMPL-002**: [Simple Task] → [📋](./.task/IMPL-002.json)
## Status Legend
- \`▸\` = Container task (has subtasks)
- \`- [ ]\` = Pending leaf task
- \`- [x]\` = Completed leaf task
\`\`\`
### Execution Instructions for Agent
**Agent Task**: Generate task JSON files, IMPL_PLAN.md, and TODO_LIST.md based on analysis results
**Note**: The correct task JSON template path has been pre-selected by the command based on the `--cli-execute` flag and is provided in the context as `{template_path}`.
**Step 1: Load Task JSON Template**
- Read template from the provided path: `Read({template_path})`
- This template is already the correct one based on execution mode
**Step 2: Extract and Decompose Tasks**
- Parse ANALYSIS_RESULTS.md for task recommendations
- Apply task merging rules (merge when possible, decompose only when necessary)
- Map artifacts to tasks based on domain (UI/Backend/Data)
- Ensure task count ≤10
**Step 3: Generate Task JSON Files**
- Use the template structure from Step 1
- Create .task/IMPL-*.json files with proper structure
- Replace all {placeholder} variables with actual session paths
- Embed artifacts array with brainstorming outputs
- Include MCP tool integration in pre_analysis steps
**Step 4: Create IMPL_PLAN.md**
- Use IMPL_PLAN template
- Populate all sections with session-specific content
- List artifacts with priorities and usage guidelines
- Document execution strategy and dependencies
**Step 5: Generate TODO_LIST.md**
- Create task progress checklist matching generated JSONs
- Use proper status indicators (▸, [ ], [x])
- Link to task JSON files
**Step 6: Update Session State**
- Update workflow-session.json with task count and artifact inventory
- Mark session ready for execution
### MCP Enhancement Examples
**Code Index Usage**:
\`\`\`javascript
// Discover authentication-related files
mcp__code-index__find_files(pattern="*auth*")
// Search for OAuth patterns
mcp__code-index__search_code_advanced(
pattern="oauth|jwt|authentication",
file_pattern="*.{ts,js}"
)
// Get file summary for key components
mcp__code-index__get_file_summary(
file_path="src/auth/index.ts"
)
\`\`\`
**Exa Research Usage**:
\`\`\`javascript
// Get best practices for task implementation
mcp__exa__get_code_context_exa(
query="TypeScript OAuth2 implementation patterns",
tokensNum="dynamic"
)
// Research specific API usage
mcp__exa__get_code_context_exa(
query="Express.js JWT middleware examples",
tokensNum=5000
)
\`\`\`
### Quality Validation
Before completion, verify:
- [ ] All task JSON files created in .task/ directory
- [ ] Each task JSON has 5 required fields
- [ ] Artifact references correctly mapped
- [ ] Flow control includes artifact loading steps
- [ ] MCP tool integration added where appropriate
- [ ] IMPL_PLAN.md follows required structure
- [ ] TODO_LIST.md matches task JSONs
- [ ] Dependency graph is acyclic
- [ ] Task count within limits (≤10)
- [ ] Session state updated
## Output
Generate all three documents and report completion status:
- Task JSON files created: N files
- Artifacts integrated: synthesis-spec, topic-framework, N role analyses
- MCP enhancements: code-index, exa-research
- Session ready for execution: /workflow:execute
`
)
```
### Agent Context Passing
**Memory-Aware Context Assembly**:
```javascript
// Assemble context package for agent
const agentContext = {
session_id: "WFS-[id]",
// Use memory if available, else load
session_metadata: memory.has("workflow-session.json")
? memory.get("workflow-session.json")
: Read(.workflow/WFS-[id]/workflow-session.json),
analysis_results: memory.has("ANALYSIS_RESULTS.md")
? memory.get("ANALYSIS_RESULTS.md")
: Read(.workflow/WFS-[id]/.process/ANALYSIS_RESULTS.md),
artifacts_inventory: memory.has("artifacts_inventory")
? memory.get("artifacts_inventory")
: discoverArtifacts(),
context_package: memory.has("context-package.json")
? memory.get("context-package.json")
: Read(.workflow/WFS-[id]/.process/context-package.json),
// Optional MCP enhancements
mcp_analysis: executeMcpDiscovery()
}
```

Some files were not shown because too many files have changed in this diff Show More