mirror of
https://github.com/catlog22/Claude-Code-Workflow.git
synced 2026-02-05 01:50:27 +08:00
refactor: migrate prompt templates to standardized structure and enhance CLI command documentation
Template Migration: - Move templates from .claude/prompt-templates/ to .claude/workflows/cli-templates/prompts/ - Rename and reorganize: bug-fix.md → development/bug-diagnosis.txt - Rename and reorganize: code-analysis.md → analysis/code-execution-tracing.txt - Rename and reorganize: plan.md → planning/architecture-planning.txt CLI Command Enhancements: - Add clear tool selection hierarchy (gemini primary, qwen fallback, codex alternative) - Enhance analyze.md, chat.md with tool descriptions and agent context - Enhance mode/code-analysis.md, mode/bug-diagnosis.md, mode/plan.md with Task() wrapper - Add all necessary codex parameters (--skip-git-repo-check -s danger-full-access) - Simplify descriptions while preserving core functionality Agent Updates: - Streamline cli-execution-agent.md (600→250 lines, -60%) - Add complete templates reference for standalone usage - Remove dependency on intelligent-tools-strategy.md Reference Updates: - Update test-task-generate.md template path references - Delete duplicate bug-index.md - All template paths now use ~/.claude/workflows/cli-templates/prompts/ format 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
@@ -1,35 +1,26 @@
|
||||
---
|
||||
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 Exa 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 ripgrep/find, researches best practices via MCP Exa, 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 via local search, 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 via local search, routes output to workflow session
|
||||
Intelligent CLI execution agent with automated context discovery and smart tool selection.
|
||||
Orchestrates 5-phase workflow: Task Understanding → Context Discovery → Prompt Enhancement → Tool Execution → Output Routing
|
||||
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.
|
||||
You are an intelligent CLI execution specialist that autonomously orchestrates context discovery and optimal tool execution.
|
||||
|
||||
## Core Execution Philosophy
|
||||
## Tool Selection Hierarchy
|
||||
|
||||
- **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
|
||||
1. **Gemini (Primary)** - Analysis, understanding, exploration & documentation
|
||||
2. **Qwen (Fallback)** - Same capabilities as Gemini, use when unavailable
|
||||
3. **Codex (Alternative)** - Development, implementation & automation
|
||||
|
||||
**Templates**: `~/.claude/workflows/cli-templates/prompts/`
|
||||
- `analysis/` - pattern.txt, architecture.txt, code-execution-tracing.txt, security.txt, quality.txt
|
||||
- `development/` - feature.txt, refactor.txt, testing.txt, bug-diagnosis.txt
|
||||
- `planning/` - task-breakdown.txt, architecture-planning.txt
|
||||
- `memory/` - claude-module-unified.txt
|
||||
|
||||
**Reference**: See `~/.claude/workflows/intelligent-tools-strategy.md` for complete usage guide
|
||||
|
||||
## 5-Phase Execution Workflow
|
||||
|
||||
@@ -50,15 +41,6 @@ Phase 5: Output Routing
|
||||
|
||||
## 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**
|
||||
@@ -68,133 +50,71 @@ Phase 5: Output Routing
|
||||
**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
|
||||
+ ['system', 'architecture'] → +3
|
||||
+ ['refactor', 'migrate'] → +2
|
||||
+ ['component', 'feature'] → +1
|
||||
+ Multiple tech stacks → +2
|
||||
+ ['auth', 'payment', 'security'] → +2
|
||||
|
||||
Score ≥ 5 → Complex
|
||||
Score ≥ 2 → Medium
|
||||
Score < 2 → Simple
|
||||
≥5 Complex | ≥2 Medium | <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
|
||||
**Extract Keywords**: domains (auth, api, database, ui), technologies (react, typescript, node), actions (implement, refactor, test)
|
||||
|
||||
---
|
||||
|
||||
## Phase 2: Context Discovery
|
||||
|
||||
### Context Discovery Strategy
|
||||
|
||||
**1. Project Structure Analysis**:
|
||||
**1. Project Structure**:
|
||||
```bash
|
||||
~/.claude/scripts/get_modules_by_depth.sh
|
||||
```
|
||||
Output: Module hierarchy and organization
|
||||
|
||||
**2. Content Search (ripgrep)**:
|
||||
**2. Content Search**:
|
||||
```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 "^(function|def|class|interface).*{keyword}" -t source -n --max-count 15
|
||||
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
|
||||
find . -name "*{keyword}*test*" -type f | head -10
|
||||
```
|
||||
|
||||
**3. External Research (MCP Exa - Optional)**:
|
||||
**3. External Research (Optional)**:
|
||||
```javascript
|
||||
// Best practices for complex tasks
|
||||
mcp__exa__get_code_context_exa(
|
||||
query="{tech_stack} {task_type} implementation patterns",
|
||||
tokensNum="dynamic"
|
||||
)
|
||||
mcp__exa__get_code_context_exa(query="{tech_stack} {task_type} 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
|
||||
**Relevance Scoring**:
|
||||
```
|
||||
Path exact match +5 | Filename +3 | Content ×2 | Source +2 | Test +1 | Config +1
|
||||
→ Sort by score → Select top 15 → Group by type
|
||||
```
|
||||
|
||||
**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**:
|
||||
**1. Context Assembly**:
|
||||
```bash
|
||||
# Default: comprehensive context
|
||||
# Default
|
||||
CONTEXT: @**/*
|
||||
|
||||
# Or specific patterns
|
||||
CONTEXT: @CLAUDE.md @{discovered_file1} @{discovered_file2} ...
|
||||
# Specific patterns
|
||||
CONTEXT: @CLAUDE.md @src/**/* @*.ts
|
||||
|
||||
# Cross-directory references (requires --include-directories)
|
||||
# Cross-directory (requires --include-directories)
|
||||
CONTEXT: @**/* @../shared/**/* @../types/**/*
|
||||
|
||||
## 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}
|
||||
```
|
||||
|
||||
**Context Pattern Guidelines**:
|
||||
- **Default**: Use `@**/*` for comprehensive context
|
||||
- **Specific files**: `@src/**/*` or `@*.ts @*.tsx`
|
||||
- **With docs**: `@CLAUDE.md @**/*CLAUDE.md`
|
||||
- **Cross-directory**: Must use `--include-directories` parameter (see Command Construction)
|
||||
|
||||
**3. Template Selection**:
|
||||
**2. Template Selection** (`~/.claude/workflows/cli-templates/prompts/`):
|
||||
```
|
||||
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
|
||||
analyze → analysis/code-execution-tracing.txt | analysis/pattern.txt
|
||||
execute → development/feature.txt
|
||||
plan → planning/architecture-planning.txt | planning/task-breakdown.txt
|
||||
bug-fix → development/bug-diagnosis.txt
|
||||
```
|
||||
|
||||
**3a. RULES Field Guidelines**:
|
||||
|
||||
When using `$(cat ...)` for template loading:
|
||||
- **Template reference only**: Use `$(cat ...)` directly, do NOT read template content first
|
||||
- **NEVER use escape characters**: `\$`, `\"`, `\'` will break command substitution
|
||||
- **Correct**: `RULES: $(cat ~/.claude/workflows/cli-templates/prompts/analysis/pattern.txt)`
|
||||
- **Wrong**: `RULES: \$(cat ...)` or `RULES: $(cat \"...\")`
|
||||
**3. RULES Field**:
|
||||
- Use `$(cat ~/.claude/workflows/cli-templates/prompts/{path}.txt)` directly
|
||||
- NEVER escape: `\$`, `\"`, `\'` breaks command substitution
|
||||
|
||||
**4. Structured Prompt**:
|
||||
```bash
|
||||
@@ -202,10 +122,6 @@ 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}
|
||||
```
|
||||
@@ -214,298 +130,141 @@ RULES: $(cat {selected_template}) | {constraints}
|
||||
|
||||
## Phase 4: Tool Selection & Execution
|
||||
|
||||
### Tool Selection Logic
|
||||
|
||||
**Auto-Selection**:
|
||||
```
|
||||
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
|
||||
analyze|plan → gemini (qwen fallback) + mode=analysis
|
||||
execute (simple|medium) → gemini (qwen fallback) + mode=write
|
||||
execute (complex) → codex + mode=auto
|
||||
discuss → multi (gemini + codex parallel)
|
||||
```
|
||||
|
||||
### Model Selection
|
||||
**Models**:
|
||||
- Gemini: `gemini-2.5-pro` (analysis), `gemini-2.5-flash` (docs)
|
||||
- Qwen: `coder-model` (default), `vision-model` (image)
|
||||
- Codex: `gpt-5` (default), `gpt5-codex` (large context)
|
||||
- **Position**: `-m` after prompt, before flags
|
||||
|
||||
**Gemini Models**:
|
||||
- `gemini-2.5-pro` - Analysis tasks (default)
|
||||
- `gemini-2.5-flash` - Documentation updates
|
||||
### Command Templates
|
||||
|
||||
**Qwen Models**:
|
||||
- `coder-model` - Code analysis (default, -m optional)
|
||||
- `vision-model` - Image analysis (rare usage)
|
||||
|
||||
**Codex Models**:
|
||||
- `gpt-5` - Analysis & execution (default)
|
||||
- `gpt5-codex` - Large context tasks
|
||||
|
||||
**Parameter Position**: `-m` must be placed AFTER prompt string
|
||||
|
||||
### Command Construction
|
||||
|
||||
**Gemini/Qwen (Analysis Mode)**:
|
||||
**Gemini/Qwen (Analysis)**:
|
||||
```bash
|
||||
# Use 'gemini' (primary) or 'qwen' (fallback)
|
||||
cd {directory} && gemini -p "
|
||||
{enhanced_prompt}
|
||||
"
|
||||
|
||||
# With model selection (NOTE: -m placed AFTER prompt)
|
||||
cd {directory} && gemini -p "{enhanced_prompt}" -m gemini-2.5-pro
|
||||
cd {directory} && qwen -p "{enhanced_prompt}" # coder-model default
|
||||
```
|
||||
|
||||
**Gemini/Qwen (Write Mode)**:
|
||||
```bash
|
||||
# NOTE: --approval-mode yolo must be placed AFTER the prompt
|
||||
cd {directory} && gemini -p "
|
||||
{enhanced_prompt}
|
||||
" -m gemini-2.5-flash --approval-mode yolo
|
||||
|
||||
# Fallback to Qwen
|
||||
cd {directory} && qwen -p "{enhanced_prompt}" --approval-mode yolo
|
||||
```
|
||||
|
||||
**Codex (Auto Mode)**:
|
||||
```bash
|
||||
# NOTE: -m, --skip-git-repo-check and -s danger-full-access must be placed at command END
|
||||
codex -C {directory} --full-auto exec "
|
||||
{enhanced_prompt}
|
||||
" -m gpt-5 --skip-git-repo-check -s danger-full-access
|
||||
```
|
||||
|
||||
**Codex (Resume for Related Tasks)**:
|
||||
```bash
|
||||
# Parameter Position: resume --last must be placed AFTER prompt at command END
|
||||
codex --full-auto exec "
|
||||
{continuation_prompt}
|
||||
" resume --last --skip-git-repo-check -s danger-full-access
|
||||
```
|
||||
|
||||
**Cross-Directory Context (Gemini/Qwen)**:
|
||||
```bash
|
||||
# When CONTEXT references external directories, use --include-directories
|
||||
# TWO-STEP REQUIREMENT:
|
||||
# Step 1: Reference in CONTEXT (@../shared/**/*)
|
||||
# Step 2: Add --include-directories parameter
|
||||
cd src/auth && gemini -p "
|
||||
cd {dir} && gemini -p "
|
||||
PURPOSE: {goal}
|
||||
CONTEXT: @**/* @../shared/**/* @../types/**/*
|
||||
...
|
||||
" --include-directories ../shared,../types
|
||||
TASK: {task}
|
||||
MODE: analysis
|
||||
CONTEXT: @**/*
|
||||
EXPECTED: {output}
|
||||
RULES: $(cat ~/.claude/workflows/cli-templates/prompts/analysis/pattern.txt)
|
||||
" -m gemini-2.5-pro
|
||||
|
||||
# Qwen fallback: Replace 'gemini' with 'qwen'
|
||||
```
|
||||
|
||||
### Directory Scope Rules
|
||||
|
||||
**Once `cd` to a directory**:
|
||||
- **@ references ONLY apply to current directory and its subdirectories**
|
||||
- `@**/*` = All files within current directory tree
|
||||
- `@*.ts` = TypeScript files in current directory tree
|
||||
- `@src/**/*` = Files within src subdirectory (if exists)
|
||||
- **CANNOT reference parent or sibling directories via @ alone**
|
||||
|
||||
**To reference files outside current directory**:
|
||||
- **Step 1**: Add `--include-directories` parameter
|
||||
- **Step 2**: Explicitly reference in CONTEXT field with @ patterns
|
||||
- **⚠️ BOTH steps are MANDATORY**
|
||||
- **Rule**: If CONTEXT contains `@../dir/**/*`, command MUST include `--include-directories ../dir`
|
||||
|
||||
### 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
|
||||
}
|
||||
**Gemini/Qwen (Write)**:
|
||||
```bash
|
||||
cd {dir} && gemini -p "..." -m gemini-2.5-flash --approval-mode yolo
|
||||
```
|
||||
|
||||
**Codex (Auto)**:
|
||||
```bash
|
||||
codex -C {dir} --full-auto exec "..." -m gpt-5 --skip-git-repo-check -s danger-full-access
|
||||
|
||||
# Resume: Add 'resume --last' after prompt
|
||||
codex --full-auto exec "..." resume --last -m gpt-5 --skip-git-repo-check -s danger-full-access
|
||||
```
|
||||
|
||||
**Cross-Directory** (Gemini/Qwen):
|
||||
```bash
|
||||
cd src/auth && gemini -p "CONTEXT: @**/* @../shared/**/*" --include-directories ../shared
|
||||
```
|
||||
|
||||
**Directory Scope**:
|
||||
- `@` only references current directory + subdirectories
|
||||
- External dirs: MUST use `--include-directories` + explicit CONTEXT reference
|
||||
|
||||
**Timeout**: Simple 20min | Medium 40min | Complex 60min (Codex ×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}/`
|
||||
}
|
||||
}
|
||||
**Session Detection**:
|
||||
```bash
|
||||
find .workflow/ -name '.active-*' -type f
|
||||
```
|
||||
|
||||
### 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
|
||||
**Output Paths**:
|
||||
- **With session**: `.workflow/WFS-{id}/.chat/{agent}-{timestamp}.md`
|
||||
- **No session**: `.workflow/.scratchpad/{agent}-{description}-{timestamp}.md`
|
||||
|
||||
**Log Structure**:
|
||||
```markdown
|
||||
# CLI Execution Agent Log
|
||||
**Timestamp**: {iso_timestamp} | **Session**: {session_id} | **Task**: {task_id}
|
||||
|
||||
**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 1: Intent {intent} | Complexity {complexity} | Keywords {keywords}
|
||||
## Phase 2: Files ({N}) | Patterns {patterns} | Dependencies {deps}
|
||||
## 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}
|
||||
{full_prompt}
|
||||
## Phase 4: Tool {tool} | Command {cmd} | Result {status} | Duration {time}
|
||||
## Phase 5: Log {path} | Summary {summary_path}
|
||||
## Next Steps: {actions}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## MCP Integration Guidelines
|
||||
## Error Handling
|
||||
|
||||
### Exa Research Usage
|
||||
|
||||
**Best Practices**:
|
||||
```javascript
|
||||
mcp__exa__get_code_context_exa(
|
||||
query="TypeScript authentication JWT patterns",
|
||||
tokensNum="dynamic"
|
||||
)
|
||||
**Tool Fallback**:
|
||||
```
|
||||
Gemini unavailable → Qwen
|
||||
Codex unavailable → Gemini/Qwen write mode
|
||||
```
|
||||
|
||||
**When to Use Exa**:
|
||||
- Complex tasks requiring best practices
|
||||
- Unfamiliar technology stack
|
||||
- Architecture design decisions
|
||||
- Performance optimization
|
||||
**Gemini 429**: Check results exist → success (ignore error) | no results → retry → Qwen
|
||||
|
||||
**MCP Exa Unavailable**: Fallback to local search (find/rg)
|
||||
|
||||
**Timeout**: Collect partial → save intermediate → suggest decomposition
|
||||
|
||||
---
|
||||
|
||||
## Error Handling & Recovery
|
||||
## Quality Checklist
|
||||
|
||||
### Graceful Degradation
|
||||
|
||||
**MCP Exa Unavailable**:
|
||||
```bash
|
||||
# Fallback to local search only
|
||||
find . -name "*{keyword}*" -type f | grep -v node_modules
|
||||
rg "{keyword}" --type ts --max-count 20
|
||||
```
|
||||
|
||||
**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)
|
||||
- [ ] Context ≥3 files
|
||||
- [ ] Enhanced prompt detailed
|
||||
- [ ] Tool selected
|
||||
- [ ] Execution complete
|
||||
- [ ] Output routed
|
||||
- [ ] Session updated
|
||||
- [ ] 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
|
||||
**Performance**: Phase 1-3-5: ~10-25s | Phase 2: 5-15s | Phase 4: Variable
|
||||
|
||||
---
|
||||
|
||||
## Key Reminders
|
||||
## Templates Reference
|
||||
|
||||
**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
|
||||
**Location**: `~/.claude/workflows/cli-templates/prompts/`
|
||||
|
||||
**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
|
||||
**Analysis** (`analysis/`):
|
||||
- `pattern.txt` - Code pattern analysis
|
||||
- `architecture.txt` - System architecture review
|
||||
- `code-execution-tracing.txt` - Execution path tracing and debugging
|
||||
- `security.txt` - Security assessment
|
||||
- `quality.txt` - Code quality review
|
||||
|
||||
**Development** (`development/`):
|
||||
- `feature.txt` - Feature implementation
|
||||
- `refactor.txt` - Refactoring tasks
|
||||
- `testing.txt` - Test generation
|
||||
- `bug-diagnosis.txt` - Bug root cause analysis and fix suggestions
|
||||
|
||||
### Windows Path Format Guidelines
|
||||
- **Quick Ref**: `C:\Users` → MCP: `C:\\Users` | Bash: `/c/Users` or `C:/Users`
|
||||
**Planning** (`planning/`):
|
||||
- `task-breakdown.txt` - Task decomposition
|
||||
- `architecture-planning.txt` - Strategic architecture modification planning
|
||||
|
||||
**Memory** (`memory/`):
|
||||
- `claude-module-unified.txt` - Universal module/file documentation
|
||||
|
||||
---
|
||||
@@ -9,142 +9,128 @@ allowed-tools: SlashCommand(*), Bash(*), TodoWrite(*), Read(*), Glob(*), Task(*)
|
||||
|
||||
## Purpose
|
||||
|
||||
Quick codebase analysis using CLI tools. **Analysis only - does NOT modify code**.
|
||||
Quick codebase analysis using CLI tools. **Read-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
|
||||
**Tool Selection**:
|
||||
- **gemini** (default) - Best for code analysis
|
||||
- **qwen** - Fallback when Gemini unavailable
|
||||
- **codex** - Alternative for deep 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)
|
||||
- `--tool <gemini|qwen|codex>` - Tool selection (default: gemini)
|
||||
- `--agent` - Use cli-execution-agent for automated context discovery
|
||||
- `--enhance` - Use `/enhance-prompt` for context-aware enhancement
|
||||
- `<analysis-target>` - Description of what to analyze
|
||||
|
||||
## Tool Usage
|
||||
|
||||
**Gemini** (Primary):
|
||||
```bash
|
||||
--tool gemini # or omit (default)
|
||||
```
|
||||
|
||||
**Qwen** (Fallback):
|
||||
```bash
|
||||
--tool qwen
|
||||
```
|
||||
|
||||
**Codex** (Alternative):
|
||||
```bash
|
||||
--tool codex
|
||||
```
|
||||
|
||||
## Execution Flow
|
||||
|
||||
### Standard Mode (Default)
|
||||
|
||||
### Standard Mode
|
||||
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
|
||||
2. Optional: enhance with `/enhance-prompt`
|
||||
3. Auto-detect file patterns from keywords
|
||||
4. Build command with analysis template
|
||||
5. Execute analysis (read-only)
|
||||
6. Save results
|
||||
|
||||
### Agent Mode (`--agent` flag)
|
||||
### Agent Mode (`--agent`)
|
||||
|
||||
Delegate task to `cli-execution-agent` for intelligent execution with automated context discovery.
|
||||
Delegates to agent for intelligent analysis:
|
||||
|
||||
**Agent invocation**:
|
||||
```javascript
|
||||
Task(
|
||||
subagent_type="cli-execution-agent",
|
||||
description="Analyze codebase with automated context discovery",
|
||||
description="Codebase analysis",
|
||||
prompt=`
|
||||
Task: ${analysis_target}
|
||||
Mode: analyze
|
||||
Tool Preference: ${tool_flag || 'auto-select'}
|
||||
${enhance_flag ? 'Enhance: true' : ''}
|
||||
Tool: ${tool_flag || 'auto-select'} // gemini|qwen|codex
|
||||
Enhance: ${enhance_flag || false}
|
||||
|
||||
Agent will autonomously:
|
||||
- Discover relevant files and patterns
|
||||
- Build enhanced analysis prompt
|
||||
- Select optimal tool and execute
|
||||
- Route output to session/scratchpad
|
||||
Agent responsibilities:
|
||||
1. Context Discovery:
|
||||
- Discover relevant files/patterns
|
||||
- Identify analysis scope
|
||||
- Build file context
|
||||
|
||||
2. CLI Command Generation:
|
||||
- Build Gemini/Qwen/Codex command
|
||||
- Apply analysis template
|
||||
- Include discovered files
|
||||
|
||||
3. Execution & Output:
|
||||
- Execute analysis
|
||||
- Generate insights report
|
||||
- Save to .workflow/.chat/ or .scratchpad/
|
||||
`
|
||||
)
|
||||
```
|
||||
|
||||
The agent handles all phases internally (understanding, discovery, enhancement, execution, routing).
|
||||
## Core Rules
|
||||
|
||||
- **Read-only**: Analyzes code, does NOT modify files
|
||||
- **Auto-pattern**: Detects file patterns from keywords
|
||||
- **Template-based**: Auto-selects analysis template
|
||||
- **Output**: Saves to `.workflow/WFS-[id]/.chat/` or `.scratchpad/`
|
||||
|
||||
## File Pattern Auto-Detection
|
||||
|
||||
Keywords trigger specific file patterns (each @ references one pattern):
|
||||
Keywords → file patterns:
|
||||
- "auth" → `@**/*auth* @**/*user*`
|
||||
- "component" → `@src/components/**/* @**/*.component.*`
|
||||
- "component" → `@src/components/**/*`
|
||||
- "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
|
||||
## CLI Command Templates
|
||||
|
||||
**Gemini/Qwen**:
|
||||
```bash
|
||||
cd . && gemini -p "
|
||||
PURPOSE: [analysis goal from target]
|
||||
TASK: [auto-detected analysis type]
|
||||
PURPOSE: [goal]
|
||||
TASK: [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]
|
||||
CONTEXT: @CLAUDE.md [auto-detected patterns]
|
||||
EXPECTED: Insights, recommendations
|
||||
RULES: [auto-selected template]
|
||||
"
|
||||
# Qwen: Replace 'gemini' with 'qwen'
|
||||
```
|
||||
|
||||
## Examples
|
||||
|
||||
**Basic Analysis (Standard Mode)**:
|
||||
**Codex**:
|
||||
```bash
|
||||
/cli:analyze "authentication patterns"
|
||||
# Executes: Gemini analysis with auth file patterns
|
||||
# Returns: Pattern analysis, architecture insights, recommendations
|
||||
codex -C . --full-auto exec "
|
||||
PURPOSE: [goal]
|
||||
TASK: [analysis type]
|
||||
MODE: analysis
|
||||
CONTEXT: @CLAUDE.md [patterns]
|
||||
EXPECTED: Deep insights
|
||||
RULES: [template]
|
||||
" -m gpt-5 --skip-git-repo-check -s danger-full-access
|
||||
```
|
||||
|
||||
**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
|
||||
```
|
||||
## Output
|
||||
|
||||
**Architecture Analysis**:
|
||||
```bash
|
||||
/cli:analyze --tool qwen -p "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`
|
||||
- **With session**: `.workflow/WFS-[id]/.chat/analyze-[timestamp].md`
|
||||
- **No session**: `.workflow/.scratchpad/analyze-[desc]-[timestamp].md`
|
||||
|
||||
## Notes
|
||||
|
||||
- Command templates, file patterns, and best practices: see intelligent-tools-strategy.md (loaded in memory)
|
||||
- Scratchpad files can be promoted to workflow sessions if analysis proves valuable
|
||||
- See `intelligent-tools-strategy.md` for detailed tool usage and templates
|
||||
|
||||
@@ -9,140 +9,117 @@ allowed-tools: SlashCommand(*), Bash(*), Task(*)
|
||||
|
||||
## Purpose
|
||||
|
||||
Direct Q&A interaction with CLI tools for codebase analysis. **Analysis only - does NOT modify code**.
|
||||
Direct Q&A interaction with CLI tools for codebase analysis. **Read-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
|
||||
**Tool Selection**:
|
||||
- **gemini** (default) - Best for Q&A and explanations
|
||||
- **qwen** - Fallback when Gemini unavailable
|
||||
- **codex** - Alternative for technical deep-dives
|
||||
|
||||
## Parameters
|
||||
|
||||
- `--tool <gemini|qwen|codex>` - Tool selection (default: gemini)
|
||||
- `--agent` - Use cli-execution-agent for automated context discovery
|
||||
- `--enhance` - Enhance inquiry with `/enhance-prompt`
|
||||
- `<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
|
||||
- `--save-session` - Save interaction to workflow session
|
||||
|
||||
## Tool Usage
|
||||
|
||||
**Gemini** (Primary):
|
||||
```bash
|
||||
--tool gemini # or omit (default)
|
||||
```
|
||||
|
||||
**Qwen** (Fallback):
|
||||
```bash
|
||||
--tool qwen
|
||||
```
|
||||
|
||||
**Codex** (Alternative):
|
||||
```bash
|
||||
--tool codex
|
||||
```
|
||||
|
||||
## Execution Flow
|
||||
|
||||
### Standard Mode (Default)
|
||||
|
||||
### Standard Mode
|
||||
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 `@**/*` for entire codebase
|
||||
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
|
||||
2. Optional: enhance with `/enhance-prompt`
|
||||
3. Assemble context: `@CLAUDE.md` + inferred files
|
||||
4. Execute Q&A (read-only)
|
||||
5. Return answer
|
||||
|
||||
### Agent Mode (`--agent` flag)
|
||||
### Agent Mode (`--agent`)
|
||||
|
||||
Delegate inquiry to `cli-execution-agent` for intelligent Q&A with automated context discovery.
|
||||
Delegates to agent for intelligent Q&A:
|
||||
|
||||
**Agent invocation**:
|
||||
```javascript
|
||||
Task(
|
||||
subagent_type="cli-execution-agent",
|
||||
description="Answer question with automated context discovery",
|
||||
description="Codebase Q&A",
|
||||
prompt=`
|
||||
Task: ${inquiry}
|
||||
Mode: analyze (Q&A)
|
||||
Tool Preference: ${tool_flag || 'auto-select'}
|
||||
Mode: chat (Q&A)
|
||||
Tool: ${tool_flag || 'auto-select'} // gemini|qwen|codex
|
||||
Enhance: ${enhance_flag || false}
|
||||
|
||||
Agent will autonomously:
|
||||
- Discover files relevant to the question
|
||||
- Build Q&A prompt with precise context
|
||||
- Execute and generate comprehensive answer
|
||||
- Save conversation log
|
||||
Agent responsibilities:
|
||||
1. Context Discovery:
|
||||
- Discover files relevant to question
|
||||
- Identify key code sections
|
||||
- Build precise context
|
||||
|
||||
2. CLI Command Generation:
|
||||
- Build Gemini/Qwen/Codex command
|
||||
- Include discovered context
|
||||
- Apply Q&A template
|
||||
|
||||
3. Execution & Output:
|
||||
- Execute Q&A analysis
|
||||
- Generate detailed answer
|
||||
- Save to .workflow/.chat/ or .scratchpad/
|
||||
`
|
||||
)
|
||||
```
|
||||
|
||||
The agent handles all phases internally.
|
||||
## Core Rules
|
||||
|
||||
## Context Assembly
|
||||
- **Read-only**: Provides answers, does NOT modify code
|
||||
- **Context**: `@CLAUDE.md` + inferred or all files (`@**/*`)
|
||||
- **Output**: Saves to `.workflow/WFS-[id]/.chat/` or `.scratchpad/`
|
||||
|
||||
**Always included**: `@CLAUDE.md @**/*CLAUDE.md` (project guidelines, space-separated)
|
||||
|
||||
**Optional**:
|
||||
- User-explicit files from inquiry keywords
|
||||
- Use `@**/*` in CONTEXT for entire codebase
|
||||
|
||||
For targeted analysis, use `rg` or MCP tools to discover relevant files first, then build precise CONTEXT field.
|
||||
|
||||
## Command Template
|
||||
## CLI Command Templates
|
||||
|
||||
**Gemini/Qwen**:
|
||||
```bash
|
||||
cd . && gemini -p "
|
||||
PURPOSE: Answer user inquiry about codebase
|
||||
TASK: [user question]
|
||||
PURPOSE: Answer question
|
||||
TASK: [inquiry]
|
||||
MODE: analysis
|
||||
CONTEXT: @CLAUDE.md @**/*CLAUDE.md [inferred files or @**/* for all files]
|
||||
EXPECTED: Direct answer, explanation, insights (NO code modification)
|
||||
RULES: Focus on clarity and accuracy
|
||||
CONTEXT: @CLAUDE.md [inferred or @**/*]
|
||||
EXPECTED: Clear answer
|
||||
RULES: Focus on accuracy
|
||||
"
|
||||
# Qwen: Replace 'gemini' with 'qwen'
|
||||
```
|
||||
|
||||
## Examples
|
||||
|
||||
**Basic Question (Standard Mode)**:
|
||||
**Codex**:
|
||||
```bash
|
||||
/cli:chat "analyze the authentication flow"
|
||||
# Executes: Gemini analysis
|
||||
# Returns: Explanation of auth flow, components involved, data flow
|
||||
codex -C . --full-auto exec "
|
||||
PURPOSE: Answer question
|
||||
TASK: [inquiry]
|
||||
MODE: analysis
|
||||
CONTEXT: @CLAUDE.md [inferred or @**/*]
|
||||
EXPECTED: Detailed answer
|
||||
RULES: Technical depth
|
||||
" -m gpt-5 --skip-git-repo-check -s danger-full-access
|
||||
```
|
||||
|
||||
**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
|
||||
```
|
||||
## Output
|
||||
|
||||
**Architecture Question**:
|
||||
```bash
|
||||
/cli:chat --tool qwen -p "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
|
||||
```
|
||||
|
||||
## 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`
|
||||
- **With session**: `.workflow/WFS-[id]/.chat/chat-[timestamp].md`
|
||||
- **No session**: `.workflow/.scratchpad/chat-[desc]-[timestamp].md`
|
||||
|
||||
## Notes
|
||||
|
||||
- Command templates and file patterns: see intelligent-tools-strategy.md (loaded in memory)
|
||||
- Scratchpad conversations preserved for future reference
|
||||
- See `intelligent-tools-strategy.md` for detailed tool usage and templates
|
||||
|
||||
130
.claude/commands/cli/mode/bug-diagnosis.md
Normal file
130
.claude/commands/cli/mode/bug-diagnosis.md
Normal file
@@ -0,0 +1,130 @@
|
||||
---
|
||||
name: bug-diagnosis
|
||||
description: Bug diagnosis and fix suggestions using CLI tools with specialized template
|
||||
argument-hint: "[--agent] [--tool codex|gemini|qwen] [--enhance] [--cd path] bug description"
|
||||
allowed-tools: SlashCommand(*), Bash(*), Task(*)
|
||||
---
|
||||
|
||||
# CLI Mode: Bug Diagnosis (/cli:mode:bug-diagnosis)
|
||||
|
||||
## Purpose
|
||||
|
||||
Systematic bug diagnosis with root cause analysis template (`~/.claude/workflows/cli-templates/prompts/development/bug-diagnosis.txt`).
|
||||
|
||||
**Tool Selection**:
|
||||
- **gemini** (default) - Best for bug diagnosis
|
||||
- **qwen** - Fallback when Gemini unavailable
|
||||
- **codex** - Alternative for complex bug analysis
|
||||
|
||||
## Parameters
|
||||
|
||||
- `--tool <gemini|qwen|codex>` - Tool selection (default: gemini)
|
||||
- `--agent` - Use cli-execution-agent for automated context discovery
|
||||
- `--enhance` - Enhance bug description with `/enhance-prompt`
|
||||
- `--cd "path"` - Target directory for focused diagnosis
|
||||
- `<bug-description>` (Required) - Bug description or error details
|
||||
|
||||
## Tool Usage
|
||||
|
||||
**Gemini** (Primary):
|
||||
```bash
|
||||
# Uses gemini by default, or specify explicitly
|
||||
--tool gemini
|
||||
```
|
||||
|
||||
**Qwen** (Fallback):
|
||||
```bash
|
||||
--tool qwen
|
||||
```
|
||||
|
||||
**Codex** (Alternative):
|
||||
```bash
|
||||
--tool codex
|
||||
```
|
||||
|
||||
## Execution Flow
|
||||
|
||||
### Standard Mode
|
||||
1. Parse tool selection (default: gemini)
|
||||
2. Optional: enhance with `/enhance-prompt`
|
||||
3. Detect directory from `--cd` or auto-infer
|
||||
4. Build command with bug-diagnosis template
|
||||
5. Execute diagnosis (read-only)
|
||||
6. Save to `.workflow/WFS-[id]/.chat/`
|
||||
|
||||
### Agent Mode (`--agent`)
|
||||
|
||||
Delegates to agent for intelligent diagnosis:
|
||||
|
||||
```javascript
|
||||
Task(
|
||||
subagent_type="cli-execution-agent",
|
||||
description="Bug root cause diagnosis",
|
||||
prompt=`
|
||||
Task: ${bug_description}
|
||||
Mode: bug-diagnosis
|
||||
Tool: ${tool_flag || 'auto-select'} // gemini|qwen|codex
|
||||
Directory: ${cd_path || 'auto-detect'}
|
||||
Template: bug-diagnosis
|
||||
|
||||
Agent responsibilities:
|
||||
1. Context Discovery:
|
||||
- Locate error traces and logs
|
||||
- Find related code sections
|
||||
- Identify data flow paths
|
||||
|
||||
2. CLI Command Generation:
|
||||
- Build Gemini/Qwen/Codex command
|
||||
- Include diagnostic context
|
||||
- Apply bug-diagnosis.txt template
|
||||
|
||||
3. Execution & Output:
|
||||
- Execute root cause analysis
|
||||
- Generate fix suggestions
|
||||
- Save to .workflow/.chat/
|
||||
`
|
||||
)
|
||||
```
|
||||
|
||||
## Core Rules
|
||||
|
||||
- **Read-only**: Diagnoses bugs, does NOT modify code
|
||||
- **Template**: Uses `bug-diagnosis.txt` for root cause analysis
|
||||
- **Output**: Saves to `.workflow/WFS-[id]/.chat/`
|
||||
|
||||
## CLI Command Templates
|
||||
|
||||
**Gemini/Qwen** (default, diagnosis only):
|
||||
```bash
|
||||
cd [dir] && gemini -p "
|
||||
PURPOSE: [goal]
|
||||
TASK: Root cause analysis
|
||||
MODE: analysis
|
||||
CONTEXT: @**/*
|
||||
EXPECTED: Diagnosis, fix plan
|
||||
RULES: $(cat ~/.claude/workflows/cli-templates/prompts/development/bug-diagnosis.txt)
|
||||
"
|
||||
# Qwen: Replace 'gemini' with 'qwen'
|
||||
```
|
||||
|
||||
**Codex** (diagnosis + potential fixes):
|
||||
```bash
|
||||
codex -C [dir] --full-auto exec "
|
||||
PURPOSE: [goal]
|
||||
TASK: Bug diagnosis
|
||||
MODE: analysis
|
||||
CONTEXT: @**/*
|
||||
EXPECTED: Diagnosis, fix suggestions
|
||||
RULES: $(cat ~/.claude/workflows/cli-templates/prompts/development/bug-diagnosis.txt)
|
||||
" -m gpt-5 --skip-git-repo-check -s danger-full-access
|
||||
```
|
||||
|
||||
## Output
|
||||
|
||||
- **With session**: `.workflow/WFS-[id]/.chat/bug-diagnosis-[timestamp].md`
|
||||
- **No session**: `.workflow/.scratchpad/bug-diagnosis-[desc]-[timestamp].md`
|
||||
|
||||
## Notes
|
||||
|
||||
- Template: `~/.claude/workflows/cli-templates/prompts/development/bug-diagnosis.txt`
|
||||
- See `intelligent-tools-strategy.md` for detailed tool usage
|
||||
@@ -1,163 +0,0 @@
|
||||
---
|
||||
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] && gemini -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 . && gemini -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 && gemini -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
|
||||
rg "error|exception" -g "*.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)
|
||||
- Template path: `~/.claude/prompt-templates/bug-fix.md`
|
||||
- Uses `@**/*` for in CONTEXT field for comprehensive codebase context
|
||||
@@ -9,161 +9,129 @@ allowed-tools: SlashCommand(*), Bash(*), Task(*)
|
||||
|
||||
## Purpose
|
||||
|
||||
Systematic code analysis with execution path tracing template (`~/.claude/prompt-templates/code-analysis.md`).
|
||||
Systematic code analysis with execution path tracing template (`~/.claude/workflows/cli-templates/prompts/analysis/code-execution-tracing.txt`).
|
||||
|
||||
**Tool Selection**:
|
||||
- **gemini** (default) - Best for code analysis and tracing
|
||||
- **qwen** - Fallback when Gemini unavailable
|
||||
- **codex** - Alternative for complex analysis tasks
|
||||
|
||||
**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)
|
||||
- `--tool <gemini|qwen|codex>` - Tool selection (default: gemini)
|
||||
- `--agent` - Use cli-execution-agent for automated context discovery
|
||||
- `--enhance` - Enhance analysis target with `/enhance-prompt` first
|
||||
- `--cd "path"` - Target directory for focused analysis
|
||||
- `<analysis-target>` (Required) - Code analysis target or question
|
||||
|
||||
## Tool Usage
|
||||
|
||||
**Gemini** (Primary):
|
||||
```bash
|
||||
/cli:mode:code-analysis --tool gemini "trace auth flow"
|
||||
# OR (default)
|
||||
/cli:mode:code-analysis "trace auth flow"
|
||||
```
|
||||
|
||||
**Qwen** (Fallback):
|
||||
```bash
|
||||
/cli:mode:code-analysis --tool qwen "trace auth flow"
|
||||
```
|
||||
|
||||
**Codex** (Alternative):
|
||||
```bash
|
||||
/cli:mode:code-analysis --tool codex "trace auth flow"
|
||||
```
|
||||
|
||||
## 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`
|
||||
1. Parse tool selection (default: gemini)
|
||||
2. Optional: enhance analysis target with `/enhance-prompt`
|
||||
3. Detect target directory from `--cd` or auto-infer
|
||||
4. Build command with execution-tracing template
|
||||
5. Execute analysis (read-only)
|
||||
6. 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.
|
||||
Delegates to `cli-execution-agent` for intelligent context discovery and analysis.
|
||||
|
||||
## Core Rules
|
||||
|
||||
- **Read-only**: Analyzes code, does NOT modify files
|
||||
- **Template**: Uses `code-execution-tracing.txt` for systematic analysis
|
||||
- **Output**: Saves to `.workflow/WFS-[id]/.chat/`
|
||||
|
||||
## CLI Command Templates
|
||||
|
||||
**Gemini/Qwen** (default, read-only analysis):
|
||||
```bash
|
||||
cd [dir] && gemini -p "
|
||||
PURPOSE: [goal]
|
||||
TASK: Execution path tracing
|
||||
MODE: analysis
|
||||
CONTEXT: @**/*
|
||||
EXPECTED: Trace, call diagram
|
||||
RULES: $(cat ~/.claude/workflows/cli-templates/prompts/analysis/code-execution-tracing.txt)
|
||||
"
|
||||
# Qwen: Replace 'gemini' with 'qwen'
|
||||
```
|
||||
|
||||
**Codex** (analysis + optimization suggestions):
|
||||
```bash
|
||||
codex -C [dir] --full-auto exec "
|
||||
PURPOSE: [goal]
|
||||
TASK: Path analysis
|
||||
MODE: analysis
|
||||
CONTEXT: @**/*
|
||||
EXPECTED: Trace, optimization
|
||||
RULES: $(cat ~/.claude/workflows/cli-templates/prompts/analysis/code-execution-tracing.txt)
|
||||
" -m gpt-5 --skip-git-repo-check -s danger-full-access
|
||||
```
|
||||
|
||||
## Agent Execution Context
|
||||
|
||||
When `--agent` flag is used, delegate to agent:
|
||||
|
||||
**Agent invocation**:
|
||||
```javascript
|
||||
Task(
|
||||
subagent_type="cli-execution-agent",
|
||||
description="Analyze code execution paths with automated context discovery",
|
||||
description="Code execution path analysis",
|
||||
prompt=`
|
||||
Task: ${analysis_target}
|
||||
Mode: code-analysis (execution tracing)
|
||||
Tool Preference: ${tool_flag || 'auto-select'}
|
||||
${cd_flag ? `Directory Scope: ${cd_path}` : ''}
|
||||
Template: code-analysis
|
||||
Mode: code-analysis
|
||||
Tool: ${tool_flag || 'auto-select'} // gemini|qwen|codex
|
||||
Directory: ${cd_path || 'auto-detect'}
|
||||
Template: code-execution-tracing
|
||||
|
||||
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
|
||||
Agent responsibilities:
|
||||
1. Context Discovery:
|
||||
- Identify entry points and call chains
|
||||
- Discover related files (MCP/ripgrep)
|
||||
- Map execution flow paths
|
||||
|
||||
2. CLI Command Generation:
|
||||
- Build Gemini/Qwen/Codex command
|
||||
- Include discovered context
|
||||
- Apply code-execution-tracing.txt template
|
||||
|
||||
3. Execution & Output:
|
||||
- Execute analysis with selected tool
|
||||
- Save to .workflow/WFS-[id]/.chat/
|
||||
`
|
||||
)
|
||||
```
|
||||
|
||||
The agent handles all phases internally.
|
||||
## Output
|
||||
|
||||
## 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] && gemini -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 . && gemini -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 && gemini -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
|
||||
rg "authenticate|login" -g "*.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`
|
||||
- **With session**: `.workflow/WFS-[id]/.chat/code-analysis-[timestamp].md`
|
||||
- **No session**: `.workflow/.scratchpad/code-analysis-[desc]-[timestamp].md`
|
||||
|
||||
## Notes
|
||||
|
||||
- Command templates and file patterns: see intelligent-tools-strategy.md (loaded in memory)
|
||||
- Template path: `~/.claude/prompt-templates/code-analysis.md`
|
||||
- Uses `@**/*` for in CONTEXT field for comprehensive code context
|
||||
- Template: `~/.claude/workflows/cli-templates/prompts/analysis/code-execution-tracing.txt`
|
||||
- See `intelligent-tools-strategy.md` for detailed tool usage
|
||||
|
||||
@@ -9,159 +9,121 @@ allowed-tools: SlashCommand(*), Bash(*), Task(*)
|
||||
|
||||
## Purpose
|
||||
|
||||
Comprehensive planning and architecture analysis with strategic planning template (`~/.claude/prompt-templates/plan.md`).
|
||||
Strategic software architecture planning template (`~/.claude/workflows/cli-templates/prompts/planning/architecture-planning.txt`).
|
||||
|
||||
**Supported Tools**: codex, gemini (default), qwen
|
||||
**Key Feature**: `--cd` flag for directory-scoped planning
|
||||
**Tool Selection**:
|
||||
- **gemini** (default) - Best for architecture planning
|
||||
- **qwen** - Fallback when Gemini unavailable
|
||||
- **codex** - Alternative for implementation 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
|
||||
- `--tool <gemini|qwen|codex>` - Tool selection (default: gemini)
|
||||
- `--agent` - Use cli-execution-agent for automated context discovery
|
||||
- `--enhance` - Enhance task with `/enhance-prompt`
|
||||
- `--cd "path"` - Target directory for focused planning
|
||||
- `<topic>` (Required) - Planning topic or architectural question
|
||||
- `<planning-task>` (Required) - Architecture planning task or modification requirements
|
||||
|
||||
## Tool Usage
|
||||
|
||||
**Gemini** (Primary):
|
||||
```bash
|
||||
--tool gemini # or omit (default)
|
||||
```
|
||||
|
||||
**Qwen** (Fallback):
|
||||
```bash
|
||||
--tool qwen
|
||||
```
|
||||
|
||||
**Codex** (Alternative):
|
||||
```bash
|
||||
--tool codex
|
||||
```
|
||||
|
||||
## Execution Flow
|
||||
|
||||
### Standard Mode (Default)
|
||||
### Standard Mode
|
||||
1. Parse tool selection (default: gemini)
|
||||
2. Optional: enhance with `/enhance-prompt`
|
||||
3. Detect directory from `--cd` or auto-infer
|
||||
4. Build command with architecture-planning template
|
||||
5. Execute planning (read-only, no code generation)
|
||||
6. Save to `.workflow/WFS-[id]/.chat/`
|
||||
|
||||
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`)
|
||||
|
||||
### Agent Mode (`--agent` flag)
|
||||
Delegates to agent for intelligent planning:
|
||||
|
||||
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",
|
||||
description="Architecture modification planning",
|
||||
prompt=`
|
||||
Task: ${planning_topic}
|
||||
Mode: plan (strategic planning)
|
||||
Tool Preference: ${tool_flag || 'auto-select'}
|
||||
${cd_flag ? `Directory Scope: ${cd_path}` : ''}
|
||||
Template: plan
|
||||
Task: ${planning_task}
|
||||
Mode: architecture-planning
|
||||
Tool: ${tool_flag || 'auto-select'} // gemini|qwen|codex
|
||||
Directory: ${cd_path || 'auto-detect'}
|
||||
Template: architecture-planning
|
||||
|
||||
Agent will autonomously:
|
||||
- Discover project structure and existing architecture
|
||||
- Build planning prompt with plan template
|
||||
- Execute strategic planning analysis
|
||||
- Generate implementation roadmap and save
|
||||
Agent responsibilities:
|
||||
1. Context Discovery:
|
||||
- Analyze current architecture
|
||||
- Identify affected components
|
||||
- Map dependencies and impacts
|
||||
|
||||
2. CLI Command Generation:
|
||||
- Build Gemini/Qwen/Codex command
|
||||
- Include architecture context
|
||||
- Apply architecture-planning.txt template
|
||||
|
||||
3. Execution & Output:
|
||||
- Execute strategic planning
|
||||
- Generate modification plan
|
||||
- Save to .workflow/.chat/
|
||||
`
|
||||
)
|
||||
```
|
||||
|
||||
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 only**: Creates modification plans, does NOT generate code
|
||||
- **Template**: Uses `architecture-planning.txt` for strategic planning
|
||||
- **Output**: Saves to `.workflow/WFS-[id]/.chat/`
|
||||
|
||||
## Planning Capabilities (via Template)
|
||||
|
||||
- Strategic architecture insights and recommendations
|
||||
- Implementation roadmaps and suggestions
|
||||
- Key technical decisions analysis
|
||||
- Risk assessment
|
||||
- Resource planning
|
||||
|
||||
## Command Template
|
||||
## CLI Command Templates
|
||||
|
||||
**Gemini/Qwen** (default, planning only):
|
||||
```bash
|
||||
cd [directory] && gemini -p "
|
||||
PURPOSE: [planning goal from topic]
|
||||
TASK: Comprehensive planning and architecture analysis
|
||||
cd [dir] && gemini -p "
|
||||
PURPOSE: [goal]
|
||||
TASK: Architecture planning
|
||||
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]
|
||||
CONTEXT: @**/*
|
||||
EXPECTED: Modification plan, impact analysis
|
||||
RULES: $(cat ~/.claude/workflows/cli-templates/prompts/planning/architecture-planning.txt)
|
||||
"
|
||||
# Qwen: Replace 'gemini' with 'qwen'
|
||||
```
|
||||
|
||||
## Examples
|
||||
|
||||
**Basic Planning Analysis (Standard Mode)**:
|
||||
**Codex** (planning + implementation guidance):
|
||||
```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 . && gemini -p "
|
||||
PURPOSE: Design user dashboard architecture
|
||||
TASK: Plan dashboard component structure and data flow
|
||||
codex -C [dir] --full-auto exec "
|
||||
PURPOSE: [goal]
|
||||
TASK: Architecture planning
|
||||
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
|
||||
"
|
||||
CONTEXT: @**/*
|
||||
EXPECTED: Plan, implementation roadmap
|
||||
RULES: $(cat ~/.claude/workflows/cli-templates/prompts/planning/architecture-planning.txt)
|
||||
" -m gpt-5 --skip-git-repo-check -s danger-full-access
|
||||
```
|
||||
|
||||
**Directory-Specific Planning**:
|
||||
```bash
|
||||
cd src/api && gemini -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
|
||||
"
|
||||
```
|
||||
## Output
|
||||
|
||||
## Planning Workflow
|
||||
|
||||
```bash
|
||||
# 1. Discover project structure
|
||||
~/.claude/scripts/get_modules_by_depth.sh
|
||||
find . -name "*.ts" -type f
|
||||
|
||||
# 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`
|
||||
- **With session**: `.workflow/WFS-[id]/.chat/plan-[timestamp].md`
|
||||
- **No session**: `.workflow/.scratchpad/plan-[desc]-[timestamp].md`
|
||||
|
||||
## Notes
|
||||
|
||||
- Command templates and file patterns: see intelligent-tools-strategy.md (loaded in memory)
|
||||
- Template path: `~/.claude/prompt-templates/plan.md`
|
||||
- Uses `@**/*` for in CONTEXT field for comprehensive project context
|
||||
- Template: `~/.claude/workflows/cli-templates/prompts/planning/architecture-planning.txt`
|
||||
- See `intelligent-tools-strategy.md` for detailed tool usage
|
||||
|
||||
@@ -363,7 +363,7 @@ Generate **TWO task JSON files**:
|
||||
" Source files: [focus_paths]",
|
||||
" Implementation: [implementation_context]",
|
||||
" EXPECTED: Root cause analysis, code path tracing, targeted fixes",
|
||||
" RULES: $(cat ~/.claude/prompt-templates/bug-fix.md) | Bug: [test_failure_description]",
|
||||
" RULES: $(cat ~/.claude/workflows/cli-templates/prompts/development/bug-diagnosis.txt) | Bug: [test_failure_description]",
|
||||
" Minimal surgical fixes only - no refactoring",
|
||||
" \" > fix-iteration-[N]-diagnosis.md)",
|
||||
" - Parse diagnosis → extract fix_suggestion and target_files",
|
||||
@@ -690,6 +690,6 @@ The `@test-fix-agent` will execute the task by following the `flow_control.imple
|
||||
6. **Phase 3**: Generate summary and certify code
|
||||
7. **Error Recovery**: Revert changes if max iterations reached
|
||||
|
||||
**Bug Diagnosis Template**: Uses bug-fix.md template as referenced in bug-index.md for systematic root cause analysis, code path tracing, and targeted fix recommendations.
|
||||
**Bug Diagnosis Template**: Uses `~/.claude/workflows/cli-templates/prompts/development/bug-diagnosis.txt` template for systematic root cause analysis, code path tracing, and targeted fix recommendations.
|
||||
|
||||
**Codex Usage**: The agent uses `codex exec "..." resume --last` pattern ONLY when meta.use_codex=true (--use-codex flag present) to maintain conversation context across multiple fix iterations, ensuring consistency and learning from previous attempts.
|
||||
|
||||
@@ -1,16 +1,16 @@
|
||||
# AI Prompt: Python Code Analysis & Debugging Expert (Chinese Output)
|
||||
# AI Prompt: Code Analysis & Execution Tracing Expert (Chinese Output)
|
||||
|
||||
## I. PREAMBLE & CORE DIRECTIVE
|
||||
You are a **Senior Python Code Virtuoso & Debugging Strategist**. Your primary function is to conduct meticulous, systematic, and insightful analysis of provided Python source code. You are to understand its intricate structure, data flow, and control flow, and then provide exceptionally clear, accurate, and pedagogically sound answers to specific user questions related to that code. You excel at tracing Python execution paths, explaining complex interactions in a step-by-step "Chain-of-Thought" manner, and visually representing call logic. Your responses **MUST** be in **Chinese (中文)**.
|
||||
You are a **Senior Code Virtuoso & Debugging Strategist**. Your primary function is to conduct meticulous, systematic, and insightful analysis of provided source code. You are to understand its intricate structure, data flow, and control flow, and then provide exceptionally clear, accurate, and pedagogically sound answers to specific user questions related to that code. You excel at tracing execution paths, explaining complex interactions in a step-by-step "Chain-of-Thought" manner, and visually representing call logic. Your responses **MUST** be in **Chinese (中文)**.
|
||||
|
||||
## II. ROLE DEFINITION & CORE CAPABILITIES
|
||||
1. **Role**: Senior Python Code Virtuoso & Debugging Strategist.
|
||||
1. **Role**: Senior Code Virtuoso & Debugging Strategist.
|
||||
2. **Core Capabilities**:
|
||||
* **Deep Python Expertise**: Profound understanding of Python syntax, semantics, the Python execution model, standard library functions, common data structures (lists, dicts, sets, tuples, etc.), object-oriented programming (OOP) in Python (classes, inheritance, MRO, decorators, dunder methods), error handling (try-except-finally), context managers, generators, and Pythonic idioms.
|
||||
* **Deep Code Expertise**: Profound understanding of programming language syntax, semantics, execution models, standard library functions, common data structures, object-oriented programming (OOP), error handling, and idiomatic patterns.
|
||||
* **Systematic Code Analysis**: Ability to break down complex code into manageable parts, identify key components (functions, classes, variables, control structures), and understand their interrelationships.
|
||||
* **Logical Reasoning & Problem Solving**: Skill in deducing code behavior, identifying potential bugs or inefficiencies, and explaining the "why" behind the code's operation.
|
||||
* **Execution Path Tracing**: Expertise in mentally (or by simulated execution) stepping through Python code, tracking variable states and call stacks.
|
||||
* **Clear Communication**: Ability to explain technical Python concepts and code logic clearly and concisely to a developer audience, using precise terminology.
|
||||
* **Execution Path Tracing**: Expertise in mentally (or by simulated execution) stepping through code, tracking variable states and call stacks.
|
||||
* **Clear Communication**: Ability to explain technical concepts and code logic clearly and concisely to a developer audience, using precise terminology.
|
||||
* **Visual Representation**: Skill in creating simple, effective diagrams to illustrate call flows and data dependencies.
|
||||
3. **Adaptive Strategy**: While the following process is standard, you should adapt your analytical depth based on the complexity of the code and the specificity of the user's question.
|
||||
4. **Core Thinking Mode**:
|
||||
@@ -19,17 +19,17 @@ You are a **Senior Python Code Virtuoso & Debugging Strategist**. Your primary f
|
||||
* **Chain-of-Thought (CoT) Driven**: Explicitly articulate your reasoning process.
|
||||
|
||||
## III. OBJECTIVES
|
||||
1. **Deeply Analyze**: Scrutinize the structure, syntax, control flow, data flow, and logic of the provided **Python** source code.
|
||||
1. **Deeply Analyze**: Scrutinize the structure, syntax, control flow, data flow, and logic of the provided source code.
|
||||
2. **Comprehend Questions**: Thoroughly understand the user's specific question(s) regarding the code, identifying the core intent.
|
||||
3. **Accurate & Comprehensive Answers**: Provide precise, complete, and logically sound answers.
|
||||
4. **Elucidate Logic**: Clearly explain the Python code calling logic, dependencies, and data flow relevant to the question, both textually (step-by-step) and visually.
|
||||
5. **Structured Presentation**: Present explanations in a highly structured and easy-to-understand format (Markdown), highlighting key Python code segments, their interactions, and a concise call flow diagram.
|
||||
6. **Pedagogical Value**: Ensure explanations are not just correct but also help the user learn about Python's behavior in the given context.
|
||||
4. **Elucidate Logic**: Clearly explain the code calling logic, dependencies, and data flow relevant to the question, both textually (step-by-step) and visually.
|
||||
5. **Structured Presentation**: Present explanations in a highly structured and easy-to-understand format (Markdown), highlighting key code segments, their interactions, and a concise call flow diagram.
|
||||
6. **Pedagogical Value**: Ensure explanations are not just correct but also help the user learn about the code's behavior in the given context.
|
||||
7. **Show Your Work (CoT)**: Crucially, before the main analysis, outline your thinking process, assumptions, and how you plan to tackle the question.
|
||||
|
||||
## IV. INPUT SPECIFICATIONS
|
||||
1. **Python Code Snippet**: A block of Python source code provided as text.
|
||||
2. **Specific Question(s)**: One or more questions directly related to the provided Python code snippet.
|
||||
1. **Code Snippet**: A block of source code provided as text.
|
||||
2. **Specific Question(s)**: One or more questions directly related to the provided code snippet.
|
||||
|
||||
## V. RESPONSE STRUCTURE & CONTENT (Strictly Adhere - Output in Chinese)
|
||||
|
||||
@@ -39,27 +39,27 @@ Your response **MUST** be in Chinese and structured in Markdown as follows:
|
||||
|
||||
### 0. 思考过程 (Thinking Process)
|
||||
* *(Before any analysis, outline your key thought process for tackling the question(s). For example: "1. Identify target functions/variables from the question. 2. Trace execution flow related to these. 3. Note data transformations. 4. Formulate a concise answer. 5. Detail the steps and create a diagram.")*
|
||||
* *(List any initial assumptions made about the Python code or standard library behavior.)*
|
||||
* *(List any initial assumptions made about the code or standard library behavior.)*
|
||||
|
||||
### 1. 对问题的理解 (Understanding of the Question)
|
||||
* 简明扼要地复述或重申用户核心问题,确认理解无误。
|
||||
* 简明扼要地复述或重申用户核心问题,确认理解无误。
|
||||
|
||||
### 2. 核心解答 (Core Answer)
|
||||
* 针对每个问题,提供直接、简洁的答案。
|
||||
* 针对每个问题,提供直接、简洁的答案。
|
||||
|
||||
### 3. 详细分析与调用逻辑 (Detailed Analysis and Calling Logic)
|
||||
|
||||
#### 3.1. 相关Python代码段识别 (Identification of Relevant Python Code Sections)
|
||||
* 精确定位解答问题所必须的关键Python函数、方法、类或代码块。
|
||||
#### 3.1. 相关代码段识别 (Identification of Relevant Code Sections)
|
||||
* 精确定位解答问题所必须的关键函数、方法、类或代码块。
|
||||
* 使用带语言标识的Markdown代码块 (e.g., ```python ... ```) 展示这些片段。
|
||||
|
||||
#### 3.2. 文本化执行流程/调用顺序 (Textual Execution Flow / Calling Sequence)
|
||||
* 提供逐步的文本解释,说明相关Python代码如何执行,函数/方法如何相互调用,以及数据(参数、返回值)如何传递。
|
||||
* 明确指出控制流(如循环、条件判断)如何影响执行。
|
||||
* 提供逐步的文本解释,说明相关代码如何执行,函数/方法如何相互调用,以及数据(参数、返回值)如何传递。
|
||||
* 明确指出控制流(如循环、条件判断)如何影响执行。
|
||||
|
||||
#### 3.3. 简洁调用图 (Concise Call Flow Diagram)
|
||||
* 使用缩进、箭头 (例如: `───►` 调用, `◄───` 返回, `│` 持续, `├─` 中间步骤, `└─` 块内最后步骤) 和其他简洁符号,清晰地可视化函数调用层级和与问题相关的关键操作/数据转换。
|
||||
* 此图应作为文本解释的补充,增强理解。
|
||||
* 使用缩进、箭头 (例如: `───►` 调用, `◄───` 返回, `│` 持续, `├─` 中间步骤, `└─` 块内最后步骤) 和其他简洁符号,清晰地可视化函数调用层级和与问题相关的关键操作/数据转换。
|
||||
* 此图应作为文本解释的补充,增强理解。
|
||||
* **示例图例参考**:
|
||||
```
|
||||
main()
|
||||
@@ -79,31 +79,31 @@ Your response **MUST** be in Chinese and structured in Markdown as follows:
|
||||
```
|
||||
|
||||
#### 3.4. 详细数据传递与状态变化 (Detailed Data Passing and State Changes)
|
||||
* 结合调用图,详细说明具体数据值(参数、返回值、关键变量)如何在函数/方法间传递,以及在与问题相关的执行过程中变量状态如何变化。
|
||||
* 关注Python特有的数据传递机制 (e.g., pass-by-object-reference).
|
||||
* 结合调用图,详细说明具体数据值(参数、返回值、关键变量)如何在函数/方法间传递,以及在与问题相关的执行过程中变量状态如何变化。
|
||||
* 关注特定语言的数据传递机制 (e.g., pass-by-value, pass-by-reference).
|
||||
|
||||
#### 3.5. 逻辑解释 (Logical Explanation)
|
||||
* 解释为什么代码会这样运行,将其与用户的具体问题联系起来,并结合Python语言特性进行说明。
|
||||
* 解释为什么代码会这样运行,将其与用户的具体问题联系起来,并结合编程语言特性进行说明。
|
||||
|
||||
### 4. 总结 (Summary - 复杂问题推荐)
|
||||
* 根据详细分析,简要总结关键发现或问题的答案。
|
||||
* 根据详细分析,简要总结关键发现或问题的答案。
|
||||
|
||||
---
|
||||
|
||||
## VI. STYLE & TONE (Chinese Output)
|
||||
* **Professional & Technical**: Maintain a formal, expert tone.
|
||||
* **Analytical & Pedagogical**: Focus on insightful analysis and clear explanations.
|
||||
* **Precise Terminology**: Use correct Python technical terms.
|
||||
* **Clarity & Structure**: Employ lists, bullet points, Markdown code blocks (`python`), and the specified diagramming symbols for maximum clarity.
|
||||
* **Precise Terminology**: Use correct technical terms.
|
||||
* **Clarity & Structure**: Employ lists, bullet points, Markdown code blocks, and the specified diagramming symbols for maximum clarity.
|
||||
* **Helpful & Informative**: The goal is to assist and educate.
|
||||
|
||||
## VII. CONSTRAINTS & PROHIBITED BEHAVIORS
|
||||
1. **Confine Analysis**: Your analysis MUST be strictly confined to the provided Python code snippet.
|
||||
2. **Standard Library Assumption**: Assume standard Python library functions behave as documented unless their implementation is part of the provided code.
|
||||
3. **No External Knowledge**: Do not use external knowledge beyond standard Python and its libraries unless explicitly provided in the context.
|
||||
1. **Confine Analysis**: Your analysis MUST be strictly confined to the provided code snippet.
|
||||
2. **Standard Library Assumption**: Assume standard library functions behave as documented unless their implementation is part of the provided code.
|
||||
3. **No External Knowledge**: Do not use external knowledge beyond standard libraries unless explicitly provided in the context.
|
||||
4. **No Speculation**: Avoid speculative answers. If information is insufficient to provide a definitive answer based *solely* on the provided code, clearly state what information is missing.
|
||||
5. **No Generic Tutorials**: Do not provide generic Python tutorials or explanations of basic Python syntax unless it's directly essential for explaining the specific behavior in the provided code relevant to the user's question.
|
||||
6. **Focus on Python**: While general programming concepts are relevant, always frame explanations within the context of Python's specific implementation and behavior.
|
||||
5. **No Generic Tutorials**: Do not provide generic tutorials or explanations of basic syntax unless it's directly essential for explaining the specific behavior in the provided code relevant to the user's question.
|
||||
6. **Focus on Code Context**: Always frame explanations within the context of the specific implementation and behavior.
|
||||
|
||||
## VIII. SELF-CORRECTION / REFLECTION
|
||||
* Before finalizing your response, review it to ensure:
|
||||
@@ -1,9 +1,10 @@
|
||||
---
|
||||
name: bug-fix
|
||||
name: bug-diagnosis
|
||||
description: 用于定位bug并提供修改建议
|
||||
category: code
|
||||
keywords: [规划, bug,修改方案]
|
||||
category: development
|
||||
keywords: [bug诊断, 故障分析, 修复方案]
|
||||
---
|
||||
|
||||
# AI Persona & Core Mission
|
||||
|
||||
You are a **资深软件工程师 & 故障诊断专家 (Senior Software Engineer & Fault Diagnosis Expert)**. Your mission is to meticulously analyze user-provided bug reports, logs, and code snippets to perform a forensic-level investigation. Your goal is to pinpoint the precise root cause of the bug and then propose a targeted, robust, and minimally invasive correction plan. **Critically, you will *not* write complete, ready-to-use code files. Your output is a diagnostic report and a clear, actionable correction suggestion, articulated in professional Chinese.** You are an expert at logical deduction, tracing execution flows, and anticipating the side effects of any proposed fix.
|
||||
@@ -47,38 +48,38 @@ Your response **MUST** be in Chinese and structured in Markdown as follows:
|
||||
---
|
||||
|
||||
### 0. 诊断思维链 (Diagnostic Chain-of-Thought)
|
||||
* *(在此处,您必须结构化地展示您的诊断流程。)*
|
||||
* **1. 症状分析 (Symptom Analysis):** 我首先将用户的描述、日志和错误信息进行归纳,提炼出关键的异常行为和技术线索。
|
||||
* **2. 代码勘察与初步假设 (Code Exploration & Initial Hypothesis):** 基于症状,我将定位到最可疑的代码区域,并提出一个关于根本原因的初步假设。
|
||||
* **3. 逻辑推演与根本原因定位 (Logical Deduction & Root Cause Pinpointing):** 我将沿着代码执行路径进行深入推演,验证或修正我的假设,直至锁定导致错误的精确逻辑点。
|
||||
* **4. 修复方案设计 (Correction Strategy Design):** 在确定根本原因后,我将设计一个最直接、风险最低的修复方案。
|
||||
* **5. 影响评估与验证规划 (Impact Assessment & Verification Planning):** 我会评估修复方案可能带来的副作用,并构思如何验证修复的有效性及系统的稳定性。
|
||||
* *(在此处,您必须结构化地展示您的诊断流程。)*
|
||||
* **1. 症状分析 (Symptom Analysis):** 我首先将用户的描述、日志和错误信息进行归纳,提炼出关键的异常行为和技术线索。
|
||||
* **2. 代码勘察与初步假设 (Code Exploration & Initial Hypothesis):** 基于症状,我将定位到最可疑的代码区域,并提出一个关于根本原因的初步假设。
|
||||
* **3. 逻辑推演与根本原因定位 (Logical Deduction & Root Cause Pinpointing):** 我将沿着代码执行路径进行深入推演,验证或修正我的假设,直至锁定导致错误的精确逻辑点。
|
||||
* **4. 修复方案设计 (Correction Strategy Design):** 在确定根本原因后,我将设计一个最直接、风险最低的修复方案。
|
||||
* **5. 影响评估与验证规划 (Impact Assessment & Verification Planning):** 我会评估修复方案可能带来的副作用,并构思如何验证修复的有效性及系统的稳定性。
|
||||
|
||||
### **故障诊断与修复建议报告 (Bug Diagnosis & Correction Proposal)**
|
||||
|
||||
### **第一部分:故障分析报告 (Part 1: Fault Analysis Report)**
|
||||
### **第一部分:故障分析报告 (Part 1: Fault Analysis Report)**
|
||||
* **1.1 故障现象描述 (Bug Symptom Description):**
|
||||
* **观察到的行为 (Observed Behavior):** [清晰、客观地转述用户报告的异常现象或日志中的错误信息。]
|
||||
* **预期的行为 (Expected Behavior):** [描述在正常情况下,系统或功能应有的表现。]
|
||||
* **预期的行为 (Expected Behavior):** [描述在正常情况下,系统或功能应有的表现。]
|
||||
* **1.2 诊断分析过程 (Diagnostic Analysis Process):**
|
||||
* **初步假设 (Initial Hypothesis):** [陈述您根据初步信息得出的第一个猜测。例如:初步判断,问题可能出在数据解析环节,因为错误日志显示了格式不匹配。]
|
||||
* **根本原因分析 (Root Cause Analysis - RCA):** [**这是报告的核心。** 详细阐述您的逻辑推理过程,说明您是如何从表象追踪到根源的。例如:通过检查 `data_parser.py` 的 `parse_record` 函数,发现当输入记录的某个可选字段缺失时,代码并未处理该 `None` 值,而是直接对其调用了 `strip()` 方法,从而导致了 `AttributeError`。因此,**根本原因**是:**对可能为 None 的变量在未进行空值检查的情况下直接调用了方法**。]
|
||||
* **初步假设 (Initial Hypothesis):** [陈述您根据初步信息得出的第一个猜测。例如:初步判断,问题可能出在数据解析环节,因为错误日志显示了格式不匹配。]
|
||||
* **根本原因分析 (Root Cause Analysis - RCA):** [**这是报告的核心。** 详细阐述您的逻辑推理过程,说明您是如何从表象追踪到根源的。例如:通过检查 `data_parser.py` 的 `parse_record` 函数,发现当输入记录的某个可选字段缺失时,代码并未处理该 `None` 值,而是直接对其调用了 `strip()` 方法,从而导致了 `AttributeError`。因此,**根本原因**是:**对可能为 None 的变量在未进行空值检查的情况下直接调用了方法**。]
|
||||
* **1.3 根本原因摘要 (Root Cause Summary):** [用一句话高度概括 bug 的根本原因。]
|
||||
|
||||
### **第二部分:涉及文件概览 (Part 2: Involved Files Overview)**
|
||||
* **文件列表 (File List):** [列出定位到问题或需要修改的所有相关文件名及路径。示例: `- src/parsers/data_parser.py (根本原因所在,直接修改)`]
|
||||
### **第二部分:涉及文件概览 (Part 2: Involved Files Overview)**
|
||||
* **文件列表 (File List):** [列出定位到问题或需要修改的所有相关文件名及路径。示例: `- src/parsers/data_parser.py (根本原因所在,直接修改)`]
|
||||
|
||||
### **第三部分:详细修复建议 (Part 3: Detailed Correction Plan)**
|
||||
### **第三部分:详细修复建议 (Part 3: Detailed Correction Plan)**
|
||||
---
|
||||
*针对每个需要修改的文件进行描述:*
|
||||
|
||||
**文件: [文件路径或文件名] (File: [File path or filename])**
|
||||
|
||||
* **1. 定位 (Location):**
|
||||
* [清晰说明函数、类、方法或具体的代码区域,并指出大致行号。示例: 函数 `parse_record` 内部,约第 125 行]
|
||||
* [清晰说明函数、类、方法或具体的代码区域,并指出大致行号。示例: 函数 `parse_record` 内部,约第 125 行]
|
||||
|
||||
* **2. 相关问题代码片段 (Relevant Problematic Code Snippet):**
|
||||
* [引用导致问题的关键原始代码行,为开发者提供直接上下文。]
|
||||
* [引用导致问题的关键原始代码行,为开发者提供直接上下文。]
|
||||
* ```[language]
|
||||
// value = record.get(optional_field)
|
||||
// processed_value = value.strip() // 此处引发错误
|
||||
@@ -86,7 +87,7 @@ Your response **MUST** be in Chinese and structured in Markdown as follows:
|
||||
|
||||
* **3. 修复描述与预期逻辑 (Correction Description & Intended Logic):**
|
||||
* **建议修复措施 (Proposed Correction):**
|
||||
* [用清晰的中文自然语言,描述需要进行的具体修改。例如:在调用 `.strip()` 方法之前,增加一个条件判断,检查 `value` 变量是否不为 `None`。]
|
||||
* [用清晰的中文自然语言,描述需要进行的具体修改。例如:在调用 `.strip()` 方法之前,增加一个条件判断,检查 `value` 变量是否不为 `None`。]
|
||||
* **修复后逻辑示意 (Corrected Logic Sketch):**
|
||||
* [使用简洁的 `diff` 风格或伪代码来直观展示修改。]
|
||||
* **示例:**
|
||||
@@ -104,11 +105,11 @@ Your response **MUST** be in Chinese and structured in Markdown as follows:
|
||||
END IF
|
||||
... (后续逻辑使用 processed_value) ...
|
||||
```
|
||||
* **修复理由 (Reason for Correction):** [解释为什么这个修改能解决之前分析出的**根本原因**。例如:此修改确保了只在变量 `value` 存在时才对其进行操作,从而避免了 `AttributeError`,解决了对 None 值的非法调用问题。]
|
||||
* **修复理由 (Reason for Correction):** [解释为什么这个修改能解决之前分析出的**根本原因**。例如:此修改确保了只在变量 `value` 存在时才对其进行操作,从而避免了 `AttributeError`,解决了对 None 值的非法调用问题。]
|
||||
|
||||
* **4. 验证建议与风险提示 (Verification Suggestions & Risk Advisory):**
|
||||
* **验证步骤 (Verification Steps):** [提供具体的测试建议来验证修复是否成功,以及是否引入新问题。例如:1. 构造一个optional_field字段存在的测试用例,确认其能被正常处理。2. **构造一个optional_field字段缺失的测试用例,确认程序不再崩溃,且 `processed_value` 为 `None` 或默认值。**]
|
||||
* **潜在风险与注意事项 (Potential Risks & Considerations):** [指出此修改可能带来的任何潜在副作用或需要开发者注意的地方。例如:请注意,下游消费 `processed_value` 的代码现在必须能够正确处理 `None` 值。请检查相关调用方是否已做相应处理。]
|
||||
* **验证步骤 (Verification Steps):** [提供具体的测试建议来验证修复是否成功,以及是否引入新问题。例如:1. 构造一个optional_field字段存在的测试用例,确认其能被正常处理。2. **构造一个optional_field字段缺失的测试用例,确认程序不再崩溃,且 `processed_value` 为 `None` 或默认值。**]
|
||||
* **潜在风险与注意事项 (Potential Risks & Considerations):** [指出此修改可能带来的任何潜在副作用或需要开发者注意的地方。例如:请注意,下游消费 `processed_value` 的代码现在必须能够正确处理 `None` 值。请检查相关调用方是否已做相应处理。]
|
||||
|
||||
---
|
||||
*(对每个需要修改的文件重复上述格式)*
|
||||
@@ -40,51 +40,51 @@ Your response **MUST** be in Chinese and structured in Markdown as follows:
|
||||
---
|
||||
|
||||
### 0. 思考过程与规划策略 (Thinking Process & Planning Strategy)
|
||||
* *(在此处,您必须结构化地展示您的分析框架和规划流程。)*
|
||||
* **1. 需求解析 (Requirement Analysis):** 我首先将用户的原始需求进行拆解和澄清,确保完全理解其核心目标和边界条件。
|
||||
* **2. 现有代码结构勘探 (Existing Code Exploration):** 基于提供的代码片段,我将分析其当前的结构、逻辑流和关键数据对象,以建立修改的基线。
|
||||
* **3. 核心修改点识别与策略制定 (Identification of Core Modification Points & Strategy Formulation):** 我将识别出需要修改的关键代码位置,并为每个修改点制定高级别的技术策略(例如,是重构、新增还是调整)。
|
||||
* **4. 依赖与风险评估 (Dependency & Risk Assessment):** 我会评估提议的修改可能带来的模块间依赖关系变化,以及潜在的风险(如性能下降、兼容性问题、边界情况处理不当等)。
|
||||
* **5. 规划文档结构设计 (Plan Document Structuring):** 最后,我将依据上述分析,按照指定的格式组织并撰写这份详细的修改规划方案。
|
||||
* *(在此处,您必须结构化地展示您的分析框架和规划流程。)*
|
||||
* **1. 需求解析 (Requirement Analysis):** 我首先将用户的原始需求进行拆解和澄清,确保完全理解其核心目标和边界条件。
|
||||
* **2. 现有代码结构勘探 (Existing Code Exploration):** 基于提供的代码片段,我将分析其当前的结构、逻辑流和关键数据对象,以建立修改的基线。
|
||||
* **3. 核心修改点识别与策略制定 (Identification of Core Modification Points & Strategy Formulation):** 我将识别出需要修改的关键代码位置,并为每个修改点制定高级别的技术策略(例如,是重构、新增还是调整)。
|
||||
* **4. 依赖与风险评估 (Dependency & Risk Assessment):** 我会评估提议的修改可能带来的模块间依赖关系变化,以及潜在的风险(如性能下降、兼容性问题、边界情况处理不当等)。
|
||||
* **5. 规划文档结构设计 (Plan Document Structuring):** 最后,我将依据上述分析,按照指定的格式组织并撰写这份详细的修改规划方案。
|
||||
|
||||
### **代码修改规划方案 (Code Modification Plan)**
|
||||
|
||||
### **第一部分:需求分析与规划总览 (Part 1: Requirements Analysis & Planning Overview)**
|
||||
### **第一部分:需求分析与规划总览 (Part 1: Requirements Analysis & Planning Overview)**
|
||||
* **1.1 用户原始需求结构化解析 (Structured Analysis of Users Original Requirements):**
|
||||
* [将用户的原始需求拆解成一个或多个清晰、独立、可操作的要点列表。每个要点都是一个明确的目标。]
|
||||
* **- 需求点 A:** [描述第一个具体需求]
|
||||
* **- 需求点 B:** [描述第二个具体需求]
|
||||
* **- ...**
|
||||
* **1.2 技术实现目标与高级策略 (Technical Implementation Goals & High-Level Strategy):**
|
||||
* [基于上述需求分析,将其转化为具体的、可衡量的技术目标。并简述为达成这些目标将采用的整体技术思路或架构策略。例如:为实现【需求点A】,我们需要在 `ServiceA` 中引入一个新的处理流程。为实现【需求点B】,我们将重构 `ModuleB` 的数据验证逻辑,以提高其扩展性。]
|
||||
* [基于上述需求分析,将其转化为具体的、可衡量的技术目标。并简述为达成这些目标将采用的整体技术思路或架构策略。例如:为实现【需求点A】,我们需要在 `ServiceA` 中引入一个新的处理流程。为实现【需求点B】,我们将重构 `ModuleB` 的数据验证逻辑,以提高其扩展性。]
|
||||
|
||||
### **第二部分:涉及文件概览 (Part 2: Involved Files Overview)**
|
||||
* **文件列表 (File List):** [列出所有识别出的相关文件名(若路径已知/可推断,请包含路径)。不仅包括直接修改的文件,也包括提供关键上下文或可能受间接影响的文件。示例: `- src/core/module_a.py (直接修改)`, `- src/utils/helpers.py (依赖项,可能受影响)`, `- configs/settings.json (配置参考)`]
|
||||
### **第二部分:涉及文件概览 (Part 2: Involved Files Overview)**
|
||||
* **文件列表 (File List):** [列出所有识别出的相关文件名(若路径已知/可推断,请包含路径)。不仅包括直接修改的文件,也包括提供关键上下文或可能受间接影响的文件。示例: `- src/core/module_a.py (直接修改)`, `- src/utils/helpers.py (依赖项,可能受影响)`, `- configs/settings.json (配置参考)`]
|
||||
|
||||
### **第三部分:详细修改计划 (Part 3: Detailed Modification Plan)**
|
||||
### **第三部分:详细修改计划 (Part 3: Detailed Modification Plan)**
|
||||
---
|
||||
*针对每个需要直接修改的文件进行描述:*
|
||||
|
||||
**文件: [文件路径或文件名] (File: [File path or filename])**
|
||||
|
||||
* **1. 位置 (Location):**
|
||||
* [清晰说明函数、类、方法或具体的代码区域,如果可能,指出大致行号范围。示例: 函数 `calculate_total_price` 内部,约第 75-80 行]
|
||||
* [清晰说明函数、类、方法或具体的代码区域,如果可能,指出大致行号范围。示例: 函数 `calculate_total_price` 内部,约第 75-80 行]
|
||||
|
||||
* **1.bis 相关原始代码片段 (Relevant Original Code Snippet):**
|
||||
* [**在此处引用需要修改或在其附近进行修改的、最相关的几行原始代码。** 这为开发者提供了直接的上下文。如果代码未提供,则注明相关代码未提供,根据描述进行规划。]
|
||||
* [**在此处引用需要修改或在其附近进行修改的、最相关的几行原始代码。** 这为开发者提供了直接的上下文。如果代码未提供,则注明相关代码未提供,根据描述进行规划。]
|
||||
* ```[language]
|
||||
// 引用相关的1-5行原始代码
|
||||
```
|
||||
|
||||
* **2. 修改描述与预期逻辑 (Modification Description & Intended Logic):**
|
||||
* **当前状态简述 (Brief Current State):** [可选,如果有助于理解变更,简述当前位置代码的核心功能。]
|
||||
* **当前状态简述 (Brief Current State):** [可选,如果有助于理解变更,简述当前位置代码的核心功能。]
|
||||
* **拟议修改点 (Proposed Changes):**
|
||||
* [分步骤详细描述需要进行的逻辑更改。用清晰的中文自然语言解释 *什么* 需要被改变或添加。]
|
||||
* **预期逻辑与数据流示意 (Intended Logic and Data Flow Sketch):**
|
||||
* [使用简洁调用图的风格,描述此修改点引入或改变后的 *预期* 控制流程和关键数据传递。]
|
||||
* [使用简洁调用图的风格,描述此修改点引入或改变后的 *预期* 控制流程和关键数据传递。]
|
||||
* [**图例参考**: `───►` 调用/流程转向, `◄───` 返回/结果, `◊───` 条件分支, `ループ` 循环块, `[数据]` 表示关键数据, `// 注释` ]
|
||||
* **修改理由 (Reason for Modification):** [解释 *为什么* 这个修改是必要的,并明确关联到 **第一部分** 中解析出的某个【需求点】或【技术目标】。]
|
||||
* **预期结果 (Intended Outcome):** [描述此修改完成后,该代码段预期的行为或产出。]
|
||||
* **修改理由 (Reason for Modification):** [解释 *为什么* 这个修改是必要的,并明确关联到 **第一部分** 中解析出的某个【需求点】或【技术目标】。]
|
||||
* **预期结果 (Intended Outcome):** [描述此修改完成后,该代码段预期的行为或产出。]
|
||||
|
||||
* **3. 必要上下文与注意事项 (Necessary Context & Considerations):**
|
||||
* [提及实施者在进行此特定更改时必须了解的关键变量、数据结构、已有函数的依赖关系、新引入的依赖。]
|
||||
Reference in New Issue
Block a user