From 2dbf5504200322d8667016da03ffe75aaa066c75 Mon Sep 17 00:00:00 2001 From: catlog22 Date: Sun, 5 Oct 2025 12:22:23 +0800 Subject: [PATCH] docs: clarify CLI command intent and add output routing MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - **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 --- .claude/commands/cli/analyze.md | 76 +++++- .claude/commands/cli/chat.md | 82 ++++++- .claude/commands/cli/codex-execute.md | 46 +++- .claude/commands/cli/execute.md | 122 ++++++++-- .claude/commands/cli/mode/bug-index.md | 87 +++++-- .claude/commands/cli/mode/code-analysis.md | 98 ++++++-- .claude/commands/cli/mode/plan.md | 88 +++++-- .claude/commands/workflow/tools/status.md | 258 --------------------- .claude/workflows/workflow-architecture.md | 77 ++++-- 9 files changed, 556 insertions(+), 378 deletions(-) delete mode 100644 .claude/commands/workflow/tools/status.md diff --git a/.claude/commands/cli/analyze.md b/.claude/commands/cli/analyze.md index 331aa2fd..93f30007 100644 --- a/.claude/commands/cli/analyze.md +++ b/.claude/commands/cli/analyze.md @@ -14,10 +14,18 @@ allowed-tools: SlashCommand(*), Bash(*), TodoWrite(*), Read(*), Glob(*) ## Purpose -Quick codebase analysis using CLI tools. Automatically detects analysis type and selects appropriate template. +Quick codebase analysis using CLI tools. **Analysis only - does NOT modify code**. +**Intent**: Understand code patterns, architecture, and provide insights/recommendations **Supported Tools**: codex, gemini (default), qwen +## Core Behavior + +1. **Read-Only Analysis**: This command ONLY analyzes code and provides insights +2. **No Code Modification**: Results are recommendations and analysis reports +3. **Template-Based**: Automatically selects appropriate analysis template +4. **Smart Pattern Detection**: Infers relevant files based on analysis target + ## Parameters - `--tool ` - Tool selection (default: gemini) @@ -29,8 +37,9 @@ Quick codebase analysis using CLI tools. Automatically detects analysis type and 1. Parse tool selection (default: gemini) 2. If `--enhance`: Execute `/enhance-prompt` first to expand user intent 3. Auto-detect analysis type from keywords → select template -4. Build command with auto-detected file patterns -5. Execute and return results +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 ## File Pattern Auto-Detection @@ -44,17 +53,64 @@ Keywords trigger specific file patterns: For complex patterns, use `rg` or MCP tools to discover files first, then execute CLI with precise file references. -## Examples +## Command Template ```bash -/cli:analyze "authentication patterns" # Auto: gemini + auth patterns -/cli:analyze --tool qwen "component architecture" # Qwen architecture analysis -/cli:analyze --tool codex "performance bottlenecks" # Codex deep analysis -/cli:analyze --enhance "fix auth issues" # Enhanced prompt → analysis +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**: +```bash +/cli:analyze "authentication patterns" +# Executes: Gemini analysis with auth file patterns +# Returns: Pattern analysis, architecture insights, recommendations +``` + +**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) -- Active workflow session: results saved to `.workflow/WFS-[id]/.chat/` -- No session: results returned directly +- Scratchpad directory details: see workflow-architecture.md +- Scratchpad files can be promoted to workflow sessions if analysis proves valuable diff --git a/.claude/commands/cli/chat.md b/.claude/commands/cli/chat.md index 6b163db4..479fd7c8 100644 --- a/.claude/commands/cli/chat.md +++ b/.claude/commands/cli/chat.md @@ -14,10 +14,18 @@ allowed-tools: SlashCommand(*), Bash(*) ## Purpose -Direct Q&A interaction with CLI tools for codebase analysis. +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 - `` (Required) - Question or analysis request @@ -31,8 +39,9 @@ Direct Q&A interaction with CLI tools for codebase analysis. 1. Parse tool selection (default: gemini) 2. If `--enhance`: Execute `/enhance-prompt` to expand user intent 3. Assemble context: `@{CLAUDE.md}` + user-specified files or `--all-files` -4. Execute CLI tool with assembled context -5. Optionally save to workflow session +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 ## Context Assembly @@ -44,18 +53,69 @@ Direct Q&A interaction with CLI tools for codebase analysis. For targeted analysis, use `rg` or MCP tools to discover relevant files first, then build precise CONTEXT field. -## Examples +## Command Template ```bash -/cli:chat "analyze the authentication flow" # Gemini (default) -/cli:chat --tool qwen "optimize React component" # Qwen -/cli:chat --tool codex "review security vulnerabilities" # Codex -/cli:chat --enhance "fix the login" # Enhanced prompt first -/cli:chat --all-files "find all API endpoints" # Full codebase context +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**: +```bash +/cli:chat "analyze the authentication flow" +# Executes: Gemini analysis +# Returns: Explanation of auth flow, components involved, data flow +``` + +**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) -- Active workflow session: results saved to `.workflow/WFS-[id]/.chat/` -- No session: results returned directly +- Scratchpad directory details: see workflow-architecture.md +- Scratchpad conversations preserved for future reference diff --git a/.claude/commands/cli/codex-execute.md b/.claude/commands/cli/codex-execute.md index 31d99726..1fa1c32d 100644 --- a/.claude/commands/cli/codex-execute.md +++ b/.claude/commands/cli/codex-execute.md @@ -457,10 +457,45 @@ codex exec "CONTINUE TO NEXT SUBTASK: ..." resume --last --skip-git-repo-check - } ``` +## 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: `.chat/codex-execute-[timestamp].md` (if workflow active) -- Summary: `.summaries/[TASK-ID]-summary.md` (if task ID provided) -- TodoWrite tracking embedded in session +- 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 @@ -471,3 +506,8 @@ codex exec "CONTINUE TO NEXT SUBTASK: ..." resume --last --skip-git-repo-check - **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 diff --git a/.claude/commands/cli/execute.md b/.claude/commands/cli/execute.md index 7cc67606..e79b5007 100644 --- a/.claude/commands/cli/execute.md +++ b/.claude/commands/cli/execute.md @@ -15,15 +15,25 @@ allowed-tools: SlashCommand(*), Bash(*) ## Purpose -Execute implementation tasks with **YOLO permissions** (auto-approves all confirmations). +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 +Auto-approves: file pattern inference, execution, **file modifications**, summary generation + +**⚠️ WARNING**: This command will make actual code changes without manual confirmation ### Execution Modes @@ -70,30 +80,106 @@ Use `resume --last` when current task extends/relates to previous execution. See **Session Management**: Auto-detects `.workflow/.active-*` marker - Active session: Save to `.workflow/WFS-[id]/.chat/execute-[timestamp].md` -- No session: Create new session +- No session: Create new session or save to scratchpad **Task Integration**: Load from `.task/[TASK-ID].json`, update status, generate summary -## Examples +## Output Routing + +**Execution Log Destination**: +- **IF** active workflow session exists: + - Save to `.workflow/WFS-[id]/.chat/execute-[timestamp].md` + - Update task status in `.task/[TASK-ID].json` (if task ID provided) + - Generate summary in `.workflow/WFS-[id]/.summaries/[TASK-ID]-summary.md` +- **ELSE** (no active session): + - **Option 1**: Create new workflow session for task + - **Option 2**: Save to `.workflow/.scratchpad/execute-[description]-[timestamp].md` + +**Output Files** (when active session exists): +- Execution log: `.workflow/WFS-[id]/.chat/execute-[timestamp].md` +- Task summary: `.workflow/WFS-[id]/.summaries/[TASK-ID]-summary.md` (if task ID) +- Modified code: Project files per implementation + +**Examples**: +- During session `WFS-auth-system`, executing `IMPL-001`: + - Log: `.workflow/WFS-auth-system/.chat/execute-20250105-143022.md` + - Summary: `.workflow/WFS-auth-system/.summaries/IMPL-001-summary.md` +- No session, ad-hoc implementation: + - Log: `.workflow/.scratchpad/execute-jwt-auth-20250105-143045.md` + +## Command Template ```bash -# Description mode with auto-detection -/cli:execute "implement JWT authentication with middleware" +# 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 +" -# Enhanced prompt -/cli:execute --enhance "implement JWT authentication" - -# Task ID mode -/cli:execute IMPL-001 - -# Codex execution -/cli:execute --tool codex "optimize database queries" - -# Qwen with enhancement -/cli:execute --tool qwen --enhance "refactor auth module" +# 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 ``` +## Examples + +**Basic Implementation** (⚠️ 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 +``` + +**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) -- Auto-generated outputs: `.summaries/[TASK-ID]-summary.md`, `.chat/execute-[timestamp].md` +- Output routing and scratchpad details: see workflow-architecture.md +- **⚠️ Code Modification**: This command modifies code - execution logs document changes made diff --git a/.claude/commands/cli/mode/bug-index.md b/.claude/commands/cli/mode/bug-index.md index 85676d47..4728ab57 100644 --- a/.claude/commands/cli/mode/bug-index.md +++ b/.claude/commands/cli/mode/bug-index.md @@ -28,33 +28,66 @@ Systematic bug analysis with diagnostic template (`~/.claude/prompt-templates/bu ## Execution Flow -1. Parse tool and directory options -2. If `--enhance`: Execute `/enhance-prompt` to expand bug context -3. Use bug-fix template: `~/.claude/prompt-templates/bug-fix.md` -4. Execute with `--all-files` in target directory -5. Save to `.workflow/WFS-[id]/.chat/bug-index-[timestamp].md` +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` + +## 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 -- Code path tracing -- Targeted minimal fixes -- Impact assessment +- 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**: ```bash -# Basic bug analysis -/cli:mode:bug-index "null pointer in authentication" +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 -/cli:mode:bug-index --cd "src/auth" "token validation fails" - -# Enhanced description -/cli:mode:bug-index --enhance "login broken" - -# Qwen for architecture-related bugs -/cli:mode:bug-index --tool qwen "circular dependency in modules" +**Directory-Specific**: +```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 @@ -62,13 +95,27 @@ Systematic bug analysis with diagnostic template (`~/.claude/prompt-templates/bu ```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 +# 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 diff --git a/.claude/commands/cli/mode/code-analysis.md b/.claude/commands/cli/mode/code-analysis.md index 43441f07..55b335b3 100644 --- a/.claude/commands/cli/mode/code-analysis.md +++ b/.claude/commands/cli/mode/code-analysis.md @@ -28,48 +28,100 @@ Systematic code analysis with execution path tracing template (`~/.claude/prompt ## Execution Flow -1. Parse tool and directory options -2. If `--enhance`: Execute `/enhance-prompt` to expand analysis intent -3. Use code-analysis template: `~/.claude/prompt-templates/code-analysis.md` -4. Execute with `--all-files` in target directory -5. Save to `.workflow/WFS-[id]/.chat/code-analysis-[timestamp].md` +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` + +## 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) -- Execution path tracing with variable states -- Call flow visualization and diagrams -- Control & data flow analysis -- Logical reasoning ("why" behind code behavior) -- Debugging insights and inefficiency detection +- **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**: ```bash -# Basic code analysis -/cli:mode:code-analysis "trace authentication flow" +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 with enhancement -/cli:mode:code-analysis --cd "src/auth" --enhance "how does JWT work" - -# Qwen for architecture analysis -/cli:mode:code-analysis --tool qwen "explain microservices communication" - -# Codex for deep tracing -/cli:mode:code-analysis --tool codex --cd "src/api" "trace request lifecycle" +**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 -rg "function.*main|export.*handler" --files-with-matches +# 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. Execute deep analysis +# 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 diff --git a/.claude/commands/cli/mode/plan.md b/.claude/commands/cli/mode/plan.md index 8f30473d..1e78adfc 100644 --- a/.claude/commands/cli/mode/plan.md +++ b/.claude/commands/cli/mode/plan.md @@ -28,48 +28,98 @@ Comprehensive planning and architecture analysis with strategic planning templat ## Execution Flow -1. Parse tool and directory options -2. If `--enhance`: Execute `/enhance-prompt` to expand planning context -3. Use planning template: `~/.claude/prompt-templates/plan.md` -4. Execute with `--all-files` in target directory -5. Save to `.workflow/WFS-[id]/.chat/plan-[timestamp].md` +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` + +## 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 -- Implementation roadmaps -- Key technical decisions +- Strategic architecture insights and recommendations +- Implementation roadmaps and suggestions +- Key technical decisions analysis - Risk assessment - Resource planning -## Examples +## Command Template ```bash -# Basic planning -/cli:mode:plan "design user dashboard" +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] +" +``` -# Enhanced with directory scope -/cli:mode:plan --cd "src/api" --enhance "plan API refactoring" +## Examples -# Qwen for architecture planning -/cli:mode:plan --tool qwen "plan microservices migration" +**Basic Planning Analysis**: +```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 +" +``` -# Codex for technical planning -/cli:mode:plan --tool codex "plan testing strategy" +**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. Gather existing architecture info +# 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 -# 2. Execute planning analysis +# 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 diff --git a/.claude/commands/workflow/tools/status.md b/.claude/commands/workflow/tools/status.md deleted file mode 100644 index 3d1da6f4..00000000 --- a/.claude/commands/workflow/tools/status.md +++ /dev/null @@ -1,258 +0,0 @@ ---- -name: workflow:status -description: Generate on-demand views from JSON task data -usage: /workflow:status [task-id] [--format=] [--validate] -argument-hint: [optional: task-id, format, validation] -examples: - - /workflow:status - - /workflow:status impl-1 - - /workflow:status --format=hierarchy - - /workflow:status --validate ---- - -# Workflow Status Command (/workflow:status) - -## Overview -Generates on-demand views from JSON task data. No synchronization needed - all views are calculated from the current state of JSON files. - -## Core Principles -**Data Source:** @~/.claude/workflows/workflow-architecture.md - -## Key Features - -### Pure View Generation -- **No Sync**: Views are generated, not synchronized -- **Always Current**: Reads latest JSON data every time -- **No Persistence**: Views are temporary, not saved -- **Single Source**: All data comes from JSON files only - -### Multiple View Formats -- **Overview** (default): Current tasks and status -- **Hierarchy**: Task relationships and structure -- **Details**: Specific task information - -## Usage - -### Default Overview -```bash -/workflow:status -``` - -Generates current workflow overview: -```markdown -# Workflow Overview -**Session**: WFS-user-auth -**Phase**: IMPLEMENT -**Type**: medium - -## Active Tasks -- [⚠️] impl-1: Build authentication module (code-developer) -- [⚠️] impl-2: Setup user management (code-developer) - -## Completed Tasks -- [✅] impl-0: Project setup - -## Stats -- **Total**: 8 tasks -- **Completed**: 3 -- **Active**: 2 -- **Remaining**: 3 -``` - -### Specific Task View -```bash -/workflow:status impl-1 -``` - -Shows detailed task information: -```markdown -# Task: impl-1 - -**Title**: Build authentication module -**Status**: active -**Agent**: @code-developer -**Type**: feature - -## Context -- **Requirements**: JWT authentication, OAuth2 support -- **Scope**: src/auth/*, tests/auth/* -- **Acceptance**: Module handles JWT tokens, OAuth2 flow implemented -- **Inherited From**: WFS-user-auth - -## Relations -- **Parent**: none -- **Subtasks**: impl-1.1, impl-1.2 -- **Dependencies**: impl-0 - -## Execution -- **Attempts**: 0 -- **Last Attempt**: never - -## Metadata -- **Created**: 2025-09-05T10:30:00Z -- **Updated**: 2025-09-05T10:35:00Z -``` - -### Hierarchy View -```bash -/workflow:status --format=hierarchy -``` - -Shows task relationships: -```markdown -# Task Hierarchy - -## Main Tasks -- impl-0: Project setup ✅ -- impl-1: Build authentication module ⚠️ - - impl-1.1: Design auth schema - - impl-1.2: Implement auth logic -- impl-2: Setup user management ⚠️ - -## Dependencies -- impl-1 → depends on → impl-0 -- impl-2 → depends on → impl-1 -``` - -## View Generation Process - -### Data Loading -```pseudo -function generate_workflow_status(task_id, format): - // Load all current data - session = load_workflow_session() - all_tasks = load_all_task_json_files() - - // Filter if specific task requested - if task_id: - target_task = find_task(all_tasks, task_id) - return generate_task_detail_view(target_task) - - // Generate requested format - switch format: - case 'hierarchy': - return generate_hierarchy_view(all_tasks) - default: - return generate_overview(session, all_tasks) -``` - -### Real-Time Calculation -- **Task Counts**: Calculated from JSON file status fields -- **Relationships**: Built from JSON relations fields -- **Status**: Read directly from current JSON state - -## Validation Mode - -### Basic Validation -```bash -/workflow:status --validate -``` - -Performs integrity checks: -```markdown -# Validation Results - -## JSON File Validation -✅ All task JSON files are valid -✅ Session file is valid and readable - -## Relationship Validation -✅ All parent-child relationships are valid -✅ All dependencies reference existing tasks -✅ No circular dependencies detected - -## Hierarchy Validation -✅ Task hierarchy within depth limits (max 3 levels) -✅ All subtask references are bidirectional - -## Issues Found -⚠️ impl-3: No subtasks defined (expected for leaf task) - -**Status**: All systems operational -``` - -### Validation Checks -- **JSON Schema**: All files parse correctly -- **References**: All task IDs exist -- **Hierarchy**: Parent-child relationships are valid -- **Dependencies**: No circular dependencies -- **Depth**: Task hierarchy within limits - -## Error Handling - -### Missing Files -```bash -❌ Session file not found -→ Initialize new workflow session? (y/n) - -❌ Task impl-5 not found -→ Available tasks: impl-1, impl-2, impl-3, impl-4 -``` - -### Invalid Data -```bash -❌ Invalid JSON in impl-2.json -→ Cannot generate view for impl-2 -→ Repair file manually or recreate task - -⚠️ Circular dependency detected: impl-1 → impl-2 → impl-1 -→ Task relationships may be incorrect -``` - -## Performance Benefits - -### Fast Generation -- **No File Writes**: Only reads JSON files -- **No Sync Logic**: No complex synchronization -- **Instant Results**: Generate views on demand -- **No Conflicts**: No state consistency issues - -### Scalability -- **Large Task Sets**: Handles hundreds of tasks efficiently -- **Complex Hierarchies**: No performance degradation -- **Concurrent Access**: Multiple views can be generated simultaneously - -## Integration - -### Workflow Integration -- Use after task creation to see current state -- Use for debugging task relationships - -### Command Integration -```bash -# Common workflow -/task:create "New feature" -/workflow:status # Check current state -/task:breakdown impl-1 -/workflow:status --format=hierarchy # View new structure -/task:execute impl-1.1 -``` - -## Output Formats - -### Supported Formats -- `overview` (default): General workflow status -- `hierarchy`: Task relationships -- `tasks`: Simple task list -- `details`: Comprehensive information - -### Custom Filtering -```bash -# Show only active tasks -/workflow:status --format=tasks --filter=active - -# Show completed tasks only -/workflow:status --format=tasks --filter=completed - -# Show tasks for specific agent -/workflow:status --format=tasks --agent=@code-developer -``` - -## Related Commands - -- `/task:create` - Create tasks (generates JSON data) -- `/task:execute` - Execute tasks (updates JSON data) -- `/task:breakdown` - Create subtasks (generates more JSON data) -- `/workflow:vibe` - Coordinate agents (uses workflow status for coordination) - -This workflow status system provides instant, accurate views of workflow state without any synchronization complexity or performance overhead. \ No newline at end of file diff --git a/.claude/workflows/workflow-architecture.md b/.claude/workflows/workflow-architecture.md index 8802a7b3..0d3d724e 100644 --- a/.claude/workflows/workflow-architecture.md +++ b/.claude/workflows/workflow-architecture.md @@ -266,28 +266,73 @@ All workflows use the same file structure definition regardless of complexity. * #### Complete Structure Reference ``` -.workflow/WFS-[topic-slug]/ -├── workflow-session.json # Session metadata and state (REQUIRED) -├── [.brainstorming/] # Optional brainstorming phase (created when needed) -├── [.chat/] # CLI interaction sessions (created when analysis is run) -│ ├── chat-*.md # Saved chat sessions -│ └── analysis-*.md # Analysis results -├── [.process/] # Planning analysis results (created by /workflow:plan) -│ └── ANALYSIS_RESULTS.md # Analysis results and planning artifacts -├── IMPL_PLAN.md # Planning document (REQUIRED) -├── TODO_LIST.md # Progress tracking (REQUIRED) -├── [.summaries/] # Task completion summaries (created when tasks complete) -│ ├── IMPL-*-summary.md # Main task summaries -│ └── IMPL-*.*-summary.md # Subtask summaries -└── .task/ # Task definitions (REQUIRED) - ├── IMPL-*.json # Main task definitions - └── IMPL-*.*.json # Subtask definitions (created dynamically) +.workflow/ +├── [.scratchpad/] # Non-session-specific outputs (created when needed) +│ ├── analyze-*-[timestamp].md # One-off analysis results +│ ├── chat-*-[timestamp].md # Standalone chat sessions +│ ├── plan-*-[timestamp].md # Ad-hoc planning notes +│ ├── bug-index-*-[timestamp].md # Quick bug analyses +│ ├── code-analysis-*-[timestamp].md # Standalone code analysis +│ ├── execute-*-[timestamp].md # Ad-hoc implementation logs +│ └── codex-execute-*-[timestamp].md # Multi-stage execution logs +│ +└── WFS-[topic-slug]/ + ├── workflow-session.json # Session metadata and state (REQUIRED) + ├── [.brainstorming/] # Optional brainstorming phase (created when needed) + ├── [.chat/] # CLI interaction sessions (created when analysis is run) + │ ├── chat-*.md # Saved chat sessions + │ └── analysis-*.md # Analysis results + ├── [.process/] # Planning analysis results (created by /workflow:plan) + │ └── ANALYSIS_RESULTS.md # Analysis results and planning artifacts + ├── IMPL_PLAN.md # Planning document (REQUIRED) + ├── TODO_LIST.md # Progress tracking (REQUIRED) + ├── [.summaries/] # Task completion summaries (created when tasks complete) + │ ├── IMPL-*-summary.md # Main task summaries + │ └── IMPL-*.*-summary.md # Subtask summaries + └── .task/ # Task definitions (REQUIRED) + ├── IMPL-*.json # Main task definitions + └── IMPL-*.*.json # Subtask definitions (created dynamically) ``` #### Creation Strategy - **Initial Setup**: Create only `workflow-session.json`, `IMPL_PLAN.md`, `TODO_LIST.md`, and `.task/` directory - **On-Demand Creation**: Other directories created when first needed - **Dynamic Files**: Subtask JSON files created during task decomposition +- **Scratchpad Usage**: `.scratchpad/` created when CLI commands run without active session + +#### Scratchpad Directory (.scratchpad/) +**Purpose**: Centralized location for non-session-specific CLI outputs + +**When to Use**: +1. **No Active Session**: CLI analysis/chat commands run without an active workflow session +2. **Unrelated Analysis**: Quick analysis not related to current active session +3. **Exploratory Work**: Ad-hoc investigation before creating formal workflow +4. **One-Off Queries**: Standalone questions or debugging without workflow context + +**Output Routing Logic**: +- **IF** active session exists AND command is session-relevant: + - Save to `.workflow/WFS-[id]/.chat/[command]-[timestamp].md` +- **ELSE** (no session OR one-off analysis): + - Save to `.workflow/.scratchpad/[command]-[description]-[timestamp].md` + +**File Naming Pattern**: `[command-type]-[brief-description]-[timestamp].md` + +**Examples**: + +*Analysis Commands (read-only):* +- `/cli:analyze "security"` (no session) → `.scratchpad/analyze-security-20250105-143022.md` +- `/cli:chat "build process"` (unrelated to active session) → `.scratchpad/chat-build-process-20250105-143045.md` +- `/cli:mode:plan "feature idea"` (exploratory) → `.scratchpad/plan-feature-idea-20250105-143110.md` +- `/cli:mode:code-analysis "trace auth flow"` (no session) → `.scratchpad/code-analysis-auth-flow-20250105-143130.md` + +*Implementation Commands (⚠️ modifies code):* +- `/cli:execute "implement JWT auth"` (no session) → `.scratchpad/execute-jwt-auth-20250105-143200.md` +- `/cli:codex-execute "refactor API layer"` (no session) → `.scratchpad/codex-execute-api-refactor-20250105-143230.md` + +**Maintenance**: +- Periodically review and clean up old scratchpad files +- Promote useful analyses to formal workflow sessions if needed +- No automatic cleanup - manual management recommended ### File Naming Conventions