refactor: convert context-gather to agent-driven execution and fix path mismatch

- Refactor context-gather.md to use general-purpose agent delegation
  - Change from 4-phase manual execution to 2-phase agent-driven flow
  - Move project structure analysis and documentation loading to agent execution
  - Add Step 0: Foundation Setup for agent to execute first
  - Update agent context passing to minimal configuration
  - Add MCP tools integration guidance for agent

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

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

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

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

Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
catlog22
2025-10-18 17:39:45 +08:00
parent e94b2a250b
commit 199585b29c
3 changed files with 364 additions and 488 deletions

View File

@@ -84,7 +84,7 @@ CONTEXT: Existing user database schema, REST API endpoints
**Parse Output**:
- Extract: context-package.json path (store as `contextPath`)
- Typical pattern: `.workflow/[sessionId]/.context/context-package.json`
- Typical pattern: `.workflow/[sessionId]/.process/context-package.json`
**Validation**:
- Context package path extracted
@@ -96,45 +96,19 @@ CONTEXT: Existing user database schema, REST API endpoints
---
### Phase 3: Intelligent Analysis (Agent-Delegated)
### Phase 3: Intelligent Analysis
**Command**: `Task(subagent_type="cli-execution-agent", description="Intelligent Analysis", prompt="...")`
**Agent Task Prompt**:
```
Analyze project requirements and generate comprehensive solution blueprint for session [sessionId].
Context: Load context package from [contextPath]
Output: Generate ANALYSIS_RESULTS.md in .workflow/[sessionId]/.process/
Requirements:
- Review context-package.json and discover additional relevant files
- Analyze architecture patterns, data models, and dependencies
- Identify technical constraints and risks
- Generate comprehensive solution blueprint
- Include task breakdown recommendations
Session: [sessionId]
Mode: analysis (read-only during discovery, write for ANALYSIS_RESULTS.md)
```
**Command**: `SlashCommand(command="/workflow:tools:concept-enhanced --session [sessionId] --context [contextPath]")`
**Input**: `sessionId` from Phase 1, `contextPath` from Phase 2
**Agent Execution**:
- Phase 1: Understands analysis intent, extracts keywords
- Phase 2: Discovers additional context via MCP code-index
- Phase 3: Enhances prompt with discovered patterns
- Phase 4: Executes with Gemini (analysis mode), generates ANALYSIS_RESULTS.md
- Phase 5: Routes output to session directory
**Parse Output**:
- Agent returns execution log path
- Verify ANALYSIS_RESULTS.md created by agent
- Extract: Execution status (success/failed)
- Verify: ANALYSIS_RESULTS.md file path
**Validation**:
- File `.workflow/[sessionId]/.process/ANALYSIS_RESULTS.md` exists
- Contains task recommendations section
- Agent execution log saved to `.workflow/[sessionId]/.chat/`
**TodoWrite**: Mark phase 3 completed, phase 3.5 in_progress

View File

@@ -17,55 +17,27 @@ Advanced solution design and feasibility analysis engine with parallel CLI execu
**Usage**: Standalone command or integrated into `/workflow:plan`. Accepts context packages and orchestrates Gemini/Codex for comprehensive analysis.
## Core Philosophy & Responsibilities
- **Agent Coordination**: Delegate analysis execution to specialized agent (cli-execution-agent)
- **Solution-Focused Analysis**: Emphasize design decisions, architectural rationale, and critical insights (exclude task planning)
- **Context-Driven**: Parse and validate context-package.json for precise analysis
- **Intelligent Tool Selection**: Gemini for design (all tasks), Codex for validation (complex tasks only)
- **Parallel Execution**: Execute multiple CLI tools simultaneously for efficiency
- **Agent-Driven Tool Selection**: Agent autonomously selects Gemini/Codex based on task complexity
- **Solution Design**: Evaluate architecture, identify key design decisions with rationale
- **Feasibility Assessment**: Analyze technical complexity, risks, implementation readiness
- **Optimization Recommendations**: Performance, security, and code quality improvements
- **Perspective Synthesis**: Integrate multi-tool insights into unified assessment
- **Output Validation**: Verify ANALYSIS_RESULTS.md generation and quality
- **Single Output**: Generate only ANALYSIS_RESULTS.md with technical analysis
## Analysis Strategy Selection
### Tool Selection by Task Complexity
**Agent-Driven Strategy**: cli-execution-agent autonomously determines tool selection based on:
- **Task Complexity**: Number of modules, integration scope, technical depth
- **Tech Stack**: Frontend (Gemini-focused), Backend (Codex-preferred), Fullstack (hybrid)
- **Analysis Focus**: Architecture design (Gemini), Feasibility validation (Codex), Performance optimization (both)
**Simple Tasks (≤3 modules)**:
- **Primary**: Gemini (rapid understanding + pattern recognition)
- **Support**: Code-index (structural analysis)
- **Mode**: Single-round analysis
**Medium Tasks (4-6 modules)**:
- **Primary**: Gemini (comprehensive analysis + architecture design)
- **Support**: Code-index + Exa (best practices)
- **Mode**: Single comprehensive round
**Complex Tasks (>6 modules)**:
- **Primary**: Gemini (comprehensive analysis) + Codex (validation)
- **Mode**: Parallel execution - Gemini design + Codex feasibility
### Tool Preferences by Tech Stack
```json
{
"frontend": {
"primary": "gemini",
"secondary": "codex",
"focus": ["component_design", "state_management", "ui_patterns"]
},
"backend": {
"primary": "codex",
"secondary": "gemini",
"focus": ["api_design", "data_flow", "security", "performance"]
},
"fullstack": {
"primary": "gemini",
"secondary": "codex",
"focus": ["system_architecture", "integration", "data_consistency"]
}
}
```
**Complexity Tiers** (Agent decides internally):
- **Simple (≤3 modules)**: Gemini-only analysis
- **Medium (4-6 modules)**: Gemini comprehensive analysis
- **Complex (>6 modules)**: Gemini + Codex parallel execution
## Execution Lifecycle
@@ -73,280 +45,158 @@ Advanced solution design and feasibility analysis engine with parallel CLI execu
1. **Session Validation**: Verify `.workflow/{session_id}/` exists, load `workflow-session.json`
2. **Context Package Validation**: Verify path, validate JSON format and structure
3. **Task Analysis**: Extract keywords, identify domain/complexity, determine scope
4. **Tool Selection**: Gemini (all tasks), +Codex (complex only), load templates
4. **Agent Preparation**: Prepare agent task prompt with complete analysis requirements
### Phase 2: Analysis Preparation
1. **Workspace Setup**: Create `.workflow/{session_id}/.process/`, initialize logs, set resource limits
2. **Context Optimization**: Filter high-priority assets, organize structure, prepare templates
3. **Execution Environment**: Configure CLI tools, set timeouts, prepare error handling
### Phase 2: Agent-Delegated Analysis
### Phase 3: Parallel Analysis Execution
1. **Gemini Solution Design & Architecture Analysis**
```bash
~/.claude/scripts/gemini-wrapper -p "
PURPOSE: Analyze and design optimal solution for {task_description}
TASK: Evaluate current architecture, propose solution design, identify key design decisions
CONTEXT: @{.workflow/{session_id}/.process/context-package.json,.workflow/{session_id}/workflow-session.json,CLAUDE.md}
**Agent Invocation**:
```javascript
Task(
subagent_type="cli-execution-agent",
description="Enhanced solution design and feasibility analysis",
prompt=`
## Execution Context
**MANDATORY**: Read context-package.json to understand task requirements, source files, tech stack, project structure
**Session ID**: {session_id}
**Mode**: Enhanced Analysis with CLI Tool Orchestration
**ANALYSIS PRIORITY**:
1. PRIMARY: Individual role analysis.md files (system-architect, ui-designer, etc.) - technical details, ADRs, decision context
2. SECONDARY: synthesis-specification.md - integrated requirements, cross-role alignment
3. REFERENCE: topic-framework.md - discussion context
## Input Context
EXPECTED:
1. CURRENT STATE: Existing patterns, code structure, integration points, technical debt
2. SOLUTION DESIGN: Core principles, system design, key decisions with rationale
3. CRITICAL INSIGHTS: Strengths, gaps, risks, tradeoffs
4. OPTIMIZATION: Performance, security, code quality recommendations
5. FEASIBILITY: Complexity analysis, compatibility, implementation readiness
6. OUTPUT: Write to .workflow/{session_id}/.process/gemini-solution-design.md
**Context Package**: {context_path}
**Session State**: .workflow/{session_id}/workflow-session.json
**Project Standards**: CLAUDE.md
RULES:
- Focus on SOLUTION IMPROVEMENTS and KEY DESIGN DECISIONS (NO task planning)
- Identify code targets: existing "file:function:lines", new files "file"
- Do NOT create task lists, implementation steps, or code examples
" --approval-mode yolo
```
Output: `.workflow/{session_id}/.process/gemini-solution-design.md`
## Analysis Task
2. **Codex Technical Feasibility Validation** (Complex Tasks Only)
```bash
codex --full-auto exec "
PURPOSE: Validate technical feasibility and identify implementation risks for {task_description}
TASK: Assess complexity, validate technology choices, evaluate performance/security implications
CONTEXT: @{.workflow/{session_id}/.process/context-package.json,.workflow/{session_id}/.process/gemini-solution-design.md,.workflow/{session_id}/workflow-session.json,CLAUDE.md}
### Analysis Templates (Use these to guide CLI tool execution)
- **Document Structure**: ~/.claude/workflows/cli-templates/prompts/workflow/analysis-results-structure.txt
- **Gemini Analysis**: ~/.claude/workflows/cli-templates/prompts/workflow/gemini-solution-design.txt
- **Codex Validation**: ~/.claude/workflows/cli-templates/prompts/workflow/codex-feasibility-validation.txt
**MANDATORY**: Read context-package.json, gemini-solution-design.md, and relevant source files
### Execution Strategy
1. **Load Context**: Read context-package.json to determine task complexity (module count, integration scope)
2. **Gemini Analysis** (ALL tasks): Execute using gemini-solution-design.txt template
- Output: .workflow/{session_id}/.process/gemini-solution-design.md
3. **Codex Validation** (COMPLEX tasks >6 modules only): Execute using codex-feasibility-validation.txt template
- Output: .workflow/{session_id}/.process/codex-feasibility-validation.md
4. **Synthesize Results**: Combine outputs into ANALYSIS_RESULTS.md following analysis-results-structure.txt
EXPECTED:
1. FEASIBILITY: Complexity rating, resource requirements, technology compatibility
2. RISK ANALYSIS: Implementation risks, integration challenges, performance/security concerns
3. VALIDATION: Development approach, quality standards, maintenance implications
4. RECOMMENDATIONS: Must-have requirements, optimization opportunities, security controls
5. OUTPUT: Write to .workflow/{session_id}/.process/codex-feasibility-validation.md
### Output Requirements
RULES:
- Focus on TECHNICAL FEASIBILITY and RISK ASSESSMENT (NO implementation planning)
- Verify code targets: existing "file:function:lines", new files "file"
- Do NOT create task breakdowns, step-by-step guides, or code examples
" --skip-git-repo-check -s danger-full-access
```
Output: `.workflow/{session_id}/.process/codex-feasibility-validation.md`
**Intermediate Outputs**:
- Gemini: \`.workflow/{session_id}/.process/gemini-solution-design.md\` (always required)
- Codex: \`.workflow/{session_id}/.process/codex-feasibility-validation.md\` (complex tasks only)
3. **Parallel Execution**: Launch tools simultaneously, monitor progress, handle completion/errors, maintain logs
**Final Output**:
- \`.workflow/{session_id}/.process/ANALYSIS_RESULTS.md\` (synthesized, required)
**⚠️ IMPORTANT**: CLI commands MUST execute in foreground (NOT background). Do NOT use `run_in_background` parameter for Gemini/Codex execution.
**Required Sections** (7 sections per analysis-results-structure.txt):
1. Executive Summary
2. Current State Analysis
3. Proposed Solution Design
4. Implementation Strategy
5. Solution Optimization
6. Critical Success Factors
7. Reference Information
### Phase 4: Results Collection & Synthesis
1. **Output Validation**: Validate gemini-solution-design.md (all), codex-feasibility-validation.md (complex), use logs if incomplete, classify status
2. **Quality Assessment**: Verify design rationale, insight depth, feasibility rigor, optimization value
3. **Synthesis Strategy**: Direct integration (simple/medium), multi-tool synthesis (complex), resolve conflicts, score confidence
### Synthesis Rules
- Follow 7-section structure from analysis-results-structure.txt
- Integrate Gemini insights as primary content
- Incorporate Codex validation findings (if executed)
- Resolve conflicts between tools with clear rationale
- Generate confidence scores (1-5 scale) for all assessment dimensions
- Provide final recommendation: PROCEED | PROCEED_WITH_MODIFICATIONS | RECONSIDER | REJECT
### Phase 5: ANALYSIS_RESULTS.md Generation
1. **Report Sections**: Executive Summary, Current State, Solution Design, Implementation Strategy, Optimization, Success Factors, Confidence Scores
2. **Guidelines**: Focus on solution improvements and design decisions (exclude task planning), emphasize rationale/tradeoffs/risk assessment
3. **Output**: Single file `ANALYSIS_RESULTS.md` at `.workflow/{session_id}/.process/` with technical insights and optimization strategies
## Output
Generate final ANALYSIS_RESULTS.md and report completion status:
- Gemini analysis: [completed/failed]
- Codex validation: [completed/skipped/failed]
- Synthesis: [completed/failed]
- Final output: .workflow/{session_id}/.process/ANALYSIS_RESULTS.md
`
)
```
**Agent Execution Flow** (Internal to cli-execution-agent):
1. Parse session ID and context path, load context-package.json
2. Analyze task complexity (module count, integration scope)
3. Discover additional context via MCP code-index
4. Execute Gemini analysis (all tasks) with template-guided prompt
5. Execute Codex validation (complex tasks >6 modules) with template-guided prompt
6. Synthesize Gemini + Codex outputs into ANALYSIS_RESULTS.md
7. Verify output file exists at correct path
8. Return execution log path
**Command Execution**: Launch agent via Task tool, wait for completion
### Phase 3: Output Validation
1. **File Verification**: Confirm `.workflow/{session_id}/.process/ANALYSIS_RESULTS.md` exists
2. **Content Validation**: Verify required sections present (Executive Summary, Solution Design, etc.)
3. **Quality Check**: Ensure design rationale, feasibility assessment, confidence scores included
4. **Agent Log**: Retrieve agent execution log from `.workflow/{session_id}/.chat/`
5. **Success Criteria**: File exists, contains all required sections, meets quality standards
## Analysis Results Format
Generated ANALYSIS_RESULTS.md focuses on **solution improvements, key design decisions, and critical insights** (NOT task planning):
**Template Reference**: `~/.claude/workflows/cli-templates/prompts/workflow/analysis-results-structure.txt`
```markdown
# Technical Analysis & Solution Design
Generated ANALYSIS_RESULTS.md focuses on **solution improvements, key design decisions, and critical insights** (NOT task planning).
## Executive Summary
- **Analysis Focus**: {core_problem_or_improvement_area}
- **Analysis Timestamp**: {timestamp}
- **Tools Used**: {analysis_tools}
- **Overall Assessment**: {feasibility_score}/5 - {recommendation_status}
### Required Structure (7 Sections)
---
1. **Executive Summary**: Analysis focus, tools used, overall assessment (X/5), recommendation status
2. **Current State Analysis**: Architecture overview, compatibility/dependencies, critical findings
3. **Proposed Solution Design**: Core principles, system design, key decisions with rationale, technical specs
4. **Implementation Strategy**: Development approach, code modification targets, feasibility assessment, risk mitigation
5. **Solution Optimization**: Performance, security, code quality recommendations
6. **Critical Success Factors**: Technical requirements, quality metrics, success validation
7. **Reference Information**: Tool analysis summary, context & resources
## 1. Current State Analysis
### Key Requirements
### Architecture Overview
- **Existing Patterns**: {key_architectural_patterns}
- **Code Structure**: {current_codebase_organization}
- **Integration Points**: {system_integration_touchpoints}
- **Technical Debt Areas**: {identified_debt_with_impact}
### Compatibility & Dependencies
- **Framework Alignment**: {framework_compatibility_assessment}
- **Dependency Analysis**: {critical_dependencies_and_risks}
- **Migration Considerations**: {backward_compatibility_concerns}
### Critical Findings
- **Strengths**: {what_works_well}
- **Gaps**: {missing_capabilities_or_issues}
- **Risks**: {identified_technical_and_business_risks}
---
## 2. Proposed Solution Design
### Core Architecture Principles
- **Design Philosophy**: {key_design_principles}
- **Architectural Approach**: {chosen_architectural_pattern_with_rationale}
- **Scalability Strategy**: {how_solution_scales}
### System Design
- **Component Architecture**: {high_level_component_design}
- **Data Flow**: {data_flow_patterns_and_state_management}
- **API Design**: {interface_contracts_and_specifications}
- **Integration Strategy**: {how_components_integrate}
### Key Design Decisions
1. **Decision**: {critical_design_choice}
- **Rationale**: {why_this_approach}
- **Alternatives Considered**: {other_options_and_tradeoffs}
- **Impact**: {implications_on_architecture}
2. **Decision**: {another_critical_choice}
- **Rationale**: {reasoning}
- **Alternatives Considered**: {tradeoffs}
- **Impact**: {consequences}
### Technical Specifications
- **Technology Stack**: {chosen_technologies_with_justification}
- **Code Organization**: {module_structure_and_patterns}
- **Testing Strategy**: {testing_approach_and_coverage}
- **Performance Targets**: {performance_requirements_and_benchmarks}
---
## 3. Implementation Strategy
### Development Approach
- **Core Implementation Pattern**: {primary_implementation_strategy}
- **Module Dependencies**: {dependency_graph_and_order}
- **Quality Assurance**: {qa_approach_and_validation}
### Code Modification Targets
**Purpose**: Specific code locations for modification AND new files to create
**Identified Targets**:
1. **Target**: `src/auth/AuthService.ts:login:45-52`
- **Type**: Modify existing
- **Modification**: Enhance error handling
- **Rationale**: Current logic lacks validation
2. **Target**: `src/auth/PasswordReset.ts`
- **Type**: Create new file
- **Purpose**: Password reset functionality
- **Rationale**: New feature requirement
**Format Rules**:
- Existing files: `file:function:lines` (with line numbers)
- New files: `file` (no function or lines)
**Code Modification Targets**:
- Existing files: `file:function:lines` (e.g., `src/auth/login.ts:validateUser:45-52`)
- New files: `file` only (e.g., `src/auth/PasswordReset.ts`)
- Unknown lines: `file:function:*`
- Task generation will refine these targets during `analyze_task_patterns` step
### Feasibility Assessment
- **Technical Complexity**: {complexity_rating_and_analysis}
- **Performance Impact**: {expected_performance_characteristics}
- **Resource Requirements**: {development_resources_needed}
- **Maintenance Burden**: {ongoing_maintenance_considerations}
**Key Design Decisions** (minimum 2):
- Decision statement
- Rationale (why this approach)
- Alternatives considered (tradeoffs)
- Impact (implications on architecture)
### Risk Mitigation
- **Technical Risks**: {implementation_risks_and_mitigation}
- **Integration Risks**: {compatibility_challenges_and_solutions}
- **Performance Risks**: {performance_concerns_and_strategies}
- **Security Risks**: {security_vulnerabilities_and_controls}
**Assessment Scores** (1-5 scale):
- Conceptual Integrity, Architectural Soundness, Technical Feasibility, Implementation Readiness
- Overall Confidence score
- Final Recommendation: PROCEED | PROCEED_WITH_MODIFICATIONS | RECONSIDER | REJECT
---
## 4. Solution Optimization
### Performance Optimization
- **Optimization Strategies**: {key_performance_improvements}
- **Caching Strategy**: {caching_approach_and_invalidation}
- **Resource Management**: {resource_utilization_optimization}
- **Bottleneck Mitigation**: {identified_bottlenecks_and_solutions}
### Security Enhancements
- **Security Model**: {authentication_authorization_approach}
- **Data Protection**: {data_security_and_encryption}
- **Vulnerability Mitigation**: {known_vulnerabilities_and_controls}
- **Compliance**: {regulatory_and_compliance_considerations}
### Code Quality
- **Code Standards**: {coding_conventions_and_patterns}
- **Testing Coverage**: {test_strategy_and_coverage_goals}
- **Documentation**: {documentation_requirements}
- **Maintainability**: {maintainability_practices}
---
## 5. Critical Success Factors
### Technical Requirements
- **Must Have**: {essential_technical_capabilities}
- **Should Have**: {important_but_not_critical_features}
- **Nice to Have**: {optional_enhancements}
### Quality Metrics
- **Performance Benchmarks**: {measurable_performance_targets}
- **Code Quality Standards**: {quality_metrics_and_thresholds}
- **Test Coverage Goals**: {testing_coverage_requirements}
- **Security Standards**: {security_compliance_requirements}
### Success Validation
- **Acceptance Criteria**: {how_to_validate_success}
- **Testing Strategy**: {validation_testing_approach}
- **Monitoring Plan**: {production_monitoring_strategy}
- **Rollback Plan**: {failure_recovery_strategy}
---
## 6. Analysis Confidence & Recommendations
### Assessment Scores
- **Conceptual Integrity**: {score}/5 - {brief_assessment}
- **Architectural Soundness**: {score}/5 - {brief_assessment}
- **Technical Feasibility**: {score}/5 - {brief_assessment}
- **Implementation Readiness**: {score}/5 - {brief_assessment}
- **Overall Confidence**: {overall_score}/5
### Final Recommendation
**Status**: {PROCEED|PROCEED_WITH_MODIFICATIONS|RECONSIDER|REJECT}
**Rationale**: {clear_explanation_of_recommendation}
**Critical Prerequisites**: {what_must_be_resolved_before_proceeding}
---
## 7. Reference Information
### Tool Analysis Summary
- **Gemini Insights**: {key_architectural_and_pattern_insights}
- **Codex Validation**: {technical_feasibility_and_implementation_notes}
- **Consensus Points**: {agreements_between_tools}
- **Conflicting Views**: {disagreements_and_resolution}
### Context & Resources
- **Analysis Context**: {context_package_reference}
- **Documentation References**: {relevant_documentation}
- **Related Patterns**: {similar_implementations_in_codebase}
- **External Resources**: {external_references_and_best_practices}
```
### Content Focus
- ✅ Solution improvements and architectural decisions
- ✅ Design rationale, alternatives, and tradeoffs
- ✅ Risk assessment with mitigation strategies
- ✅ Optimization opportunities (performance, security, quality)
- ❌ Task lists or implementation steps
- ❌ Code examples or snippets
- ❌ Project management timelines
## Execution Management
### Error Handling & Recovery
1. **Pre-execution**: Verify session/context package, confirm CLI tools, validate dependencies
2. **Monitoring & Timeout**: Track progress, 30-min limit, manage parallel execution, maintain status
3. **Partial Recovery**: Generate results with incomplete outputs, use logs, provide next steps
4. **Error Recovery**: Auto error detection, structured workflows, graceful degradation
1. **Pre-execution**: Verify session/context package exists and is valid
2. **Agent Monitoring**: Track agent execution status via Task tool
3. **Validation**: Check ANALYSIS_RESULTS.md generation on completion
4. **Error Recovery**:
- Agent execution failure → report error, check agent logs
- Missing output file → retry agent execution once
- Incomplete output → use agent logs to diagnose issue
5. **Graceful Degradation**: If agent fails, report specific error and suggest manual analysis
### Performance & Resource Optimization
- **Parallel Analysis**: Execute multiple tools simultaneously to reduce time
- **Context Sharding**: Analyze large projects by module shards
- **Caching**: Reuse results for similar contexts
- **Resource Management**: Monitor disk/CPU/memory, set limits, cleanup temporary files
- **Timeout Control**: `timeout 600s` with partial result generation on failure
### Agent Delegation Benefits
- **Autonomous Tool Selection**: Agent decides Gemini/Codex based on complexity
- **Context Discovery**: Agent discovers additional relevant files via MCP
- **Prompt Enhancement**: Agent optimizes prompts with discovered patterns
- **Error Handling**: Agent manages CLI tool failures internally
- **Log Tracking**: Agent execution logs saved to `.workflow/{session_id}/.chat/`
## Integration & Success Criteria
@@ -354,8 +204,6 @@ Generated ANALYSIS_RESULTS.md focuses on **solution improvements, key design dec
**Input**:
- `--session` (required): Session ID (e.g., WFS-auth)
- `--context` (required): Context package path
- `--depth` (optional): Analysis depth (quick|full|deep)
- `--focus` (optional): Analysis focus areas
**Output**:
- Single file: `ANALYSIS_RESULTS.md` at `.workflow/{session_id}/.process/`
@@ -366,13 +214,14 @@ Generated ANALYSIS_RESULTS.md focuses on **solution improvements, key design dec
**Success Criteria**:
- ✅ Solution-focused analysis (design decisions, critical insights, NO task planning)
- ✅ Single output file only
- ✅ Single output file only (ANALYSIS_RESULTS.md)
- ✅ Design decision depth with rationale/alternatives/tradeoffs
- ✅ Feasibility assessment (complexity, risks, readiness)
- ✅ Optimization strategies (performance, security, quality)
- ✅ Parallel execution efficiency (Gemini + Codex for complex tasks)
- ✅ Robust error handling (validation, timeout, partial recovery)
- ✅ Agent-driven tool selection (autonomous Gemini/Codex execution)
- ✅ Robust error handling (validation, retry, graceful degradation)
- ✅ Confidence scoring with clear recommendation status
- ✅ Agent execution log saved to session chat directory
## Related Commands
- `/context:gather` - Generate context packages required by this command

View File

@@ -1,6 +1,6 @@
---
name: gather
description: Intelligently collect project context based on task description and package into standardized JSON
description: Intelligently collect project context using general-purpose agent based on task description and package into standardized JSON
argument-hint: "--session WFS-session-id \"task description\""
examples:
- /workflow:tools:context-gather --session WFS-user-auth "Implement user authentication system"
@@ -11,25 +11,105 @@ examples:
# Context Gather Command (/workflow:tools:context-gather)
## Overview
Intelligent context collector that gathers relevant information from project codebase, documentation, and dependencies based on task descriptions, generating standardized context packages.
Agent-driven intelligent context collector that gathers relevant information from project codebase, documentation, and dependencies based on task descriptions, generating standardized context packages.
## Core Philosophy
- **Agent-Driven**: Delegate execution to general-purpose agent for autonomous operation
- **Two-Phase Flow**: Discovery (context loading) → Execution (context gathering and packaging)
- **Memory-First**: Reuse loaded documents from conversation memory
- **MCP-Enhanced**: Use MCP tools for advanced code analysis and file discovery
- **Intelligent Collection**: Auto-identify relevant resources based on keyword analysis
- **Comprehensive Coverage**: Collect code, documentation, configurations, and dependencies
- **Standardized Output**: Generate unified format context-package.json
- **Efficient Execution**: Optimize collection strategies to avoid irrelevant information
## Core Responsibilities
- **Keyword Extraction**: Extract core keywords from task descriptions
- **Smart Documentation Loading**: Load relevant project documentation based on keywords
- **Code Structure Analysis**: Analyze project structure to locate relevant code files
- **Dependency Discovery**: Identify tech stack and dependency relationships
- **MCP Tools Integration**: Leverage code-index tools for enhanced collection
- **Context Packaging**: Generate standardized JSON context packages
## Execution Lifecycle
## Execution Process
### Phase 1: Discovery & Context Loading
**⚡ Memory-First Rule**: Skip file loading if documents already in conversation memory
### Phase 1: Task Analysis
**Agent Context Package**:
```javascript
{
"session_id": "WFS-[session-id]",
"task_description": "[user provided task description]",
"session_metadata": {
// If in memory: use cached content
// Else: Load from .workflow/{session-id}/workflow-session.json
},
"mcp_capabilities": {
// Agent will use these tools to discover project context
"code_index": true,
"exa_code": true,
"exa_web": true
}
}
// Agent will autonomously execute:
// - Project structure analysis: bash(~/.claude/scripts/get_modules_by_depth.sh)
// - Documentation loading: Read(CLAUDE.md), Read(README.md)
```
**Discovery Actions**:
1. **Load Session Context** (if not in memory)
```javascript
if (!memory.has("workflow-session.json")) {
Read(.workflow/{session-id}/workflow-session.json)
}
```
### Phase 2: Agent Execution (Context Gathering & Packaging)
**Agent Invocation**:
```javascript
Task(
subagent_type="general-purpose",
description="Gather project context and generate context package",
prompt=`
## Execution Context
**Session ID**: WFS-{session-id}
**Task Description**: {task_description}
**Mode**: Agent-Driven Context Gathering
## Phase 1: Discovery Results (Provided Context)
### Session Metadata
{session_metadata_content}
### MCP Capabilities
- code-index: Available for file discovery and code search
- exa-code: Available for external research
- exa-web: Available for web search
## Phase 2: Context Gathering Task
### Core Responsibilities
1. **Project Structure Analysis**: Execute get_modules_by_depth.sh for architecture overview
2. **Documentation Loading**: Load CLAUDE.md, README.md and relevant documentation
3. **Keyword Extraction**: Extract core keywords from task description
4. **Smart File Discovery**: Use MCP code-index tools to locate relevant files
5. **Code Structure Analysis**: Analyze project structure to identify relevant modules
6. **Dependency Discovery**: Identify tech stack and dependency relationships
7. **Context Packaging**: Generate standardized JSON context package
### Execution Process
#### Step 0: Foundation Setup (Execute First)
1. **Project Structure Analysis**
Execute to get comprehensive architecture overview:
\`\`\`javascript
bash(~/.claude/scripts/get_modules_by_depth.sh)
\`\`\`
2. **Load Project Documentation** (if not in memory)
Load core project documentation:
\`\`\`javascript
Read(CLAUDE.md)
Read(README.md)
// Load other relevant documentation based on session context
\`\`\`
#### Step 1: Task Analysis
1. **Keyword Extraction**
- Parse task description to extract core keywords
- Identify technical domain (auth, API, frontend, backend, etc.)
@@ -40,23 +120,31 @@ Intelligent context collector that gathers relevant information from project cod
- Identify potentially involved modules and components
- Set file type filters
### Phase 2: Project Structure Exploration
1. **Architecture Analysis**
- Use `~/.claude/scripts/get_modules_by_depth.sh` for comprehensive project structure
- Analyze project layout and module organization
- Identify key directories and components
#### Step 2: MCP-Enhanced File Discovery
1. **Code File Location**
Use MCP code-index tools:
\`\`\`javascript
// Find files by pattern
mcp__code-index__find_files(pattern="*{keyword}*")
2. **Code File Location**
- Use MCP tools for precise search: `mcp__code-index__find_files()` and `mcp__code-index__search_code_advanced()`
- Search for relevant source code files based on keywords
- Locate implementation files, interfaces, and modules
// Search code content
mcp__code-index__search_code_advanced(
pattern="{keyword_patterns}",
file_pattern="*.{ts,js,py,go,md}",
context_lines=3
)
3. **Documentation Collection**
- Load CLAUDE.md and README.md
- Load relevant documentation from .workflow/docs/ based on keywords
- Collect configuration files (package.json, requirements.txt, etc.)
// Get file summaries
mcp__code-index__get_file_summary(file_path="relevant/file.ts")
\`\`\`
### Phase 3: Intelligent Filtering & Association
2. **Configuration Files Discovery**
Locate: package.json, requirements.txt, Cargo.toml, tsconfig.json, etc.
3. **Test Files Location**
Find test files related to task keywords
#### Step 3: Intelligent Filtering & Association
1. **Relevance Scoring**
- Score based on keyword match degree
- Score based on file path relevance
@@ -67,17 +155,15 @@ Intelligent context collector that gathers relevant information from project cod
- Identify inter-module dependencies
- Determine core and optional dependencies
### Phase 4: Context Packaging
1. **Standardized Output**
- Generate context-package.json
- Organize resources by type and importance
- Add relevance descriptions and usage recommendations
#### Step 4: Context Packaging
Generate standardized context-package.json following the format below
## Context Package Format
### Required Output
Generated context package format:
**Output Location**: \`.workflow/{session-id}/.process/context-package.json\`
```json
**Output Format**:
\`\`\`json
{
"metadata": {
"task_description": "Implement user authentication system",
@@ -138,163 +224,130 @@ Generated context package format:
"test_files": 1
}
}
```
\`\`\`
## MCP Tools Integration
### Quality Validation
### Code Index Integration
```bash
# Set project path
Before completion, verify:
- [ ] context-package.json created in correct location
- [ ] Valid JSON format with all required fields
- [ ] Metadata includes task description, keywords, complexity
- [ ] Assets array contains relevant files with priorities
- [ ] Tech stack accurately identified
- [ ] Statistics section provides file counts
- [ ] File relevance accuracy >80%
- [ ] No sensitive information exposed
### Performance Optimization
**Large Project Optimization**:
- File count limit: Maximum 50 files per type
- Size filtering: Skip oversized files (>10MB)
- Depth limit: Maximum search depth of 3 levels
- Use MCP tools for efficient discovery
**MCP Tools Integration**:
Agent should use MCP code-index tools when available:
\`\`\`javascript
// Set project path
mcp__code-index__set_project_path(path="{current_project_path}")
# Refresh index to ensure latest
// Refresh index
mcp__code-index__refresh_index()
# Search relevant files
// Find files by pattern
mcp__code-index__find_files(pattern="*{keyword}*")
# Search code content
// Search code content
mcp__code-index__search_code_advanced(
pattern="{keyword_patterns}",
file_pattern="*.{ts,js,py,go,md}",
context_lines=3
)
\`\`\`
**Fallback Strategy**:
When MCP tools unavailable, agent should use traditional commands:
- \`find\` for file discovery
- \`rg\` or \`grep\` for content search
- Bash commands from project structure analysis
## Output
Generate context-package.json and report completion:
- Task description: {description}
- Keywords extracted: {count}
- Files collected: {total}
- Source files: {count}
- Documentation: {count}
- Configuration: {count}
- Tests: {count}
- Tech stack identified: {frameworks/libraries}
- Output location: .workflow/{session-id}/.process/context-package.json
\`
)
\`\`\`
## Command Integration
### Usage
```bash
# Basic usage
/workflow:tools:context-gather --session WFS-auth "Implement JWT authentication"
# Called by /workflow:plan
SlashCommand(command="/workflow:tools:context-gather --session WFS-[id] \\"[task description]\\"")
```
### Agent Context Passing
**Memory-Aware Context Assembly**:
```javascript
// Assemble minimal context package for agent
// Agent will execute project structure analysis and documentation loading
const agentContext = {
session_id: "WFS-[id]",
task_description: "[user provided task description]",
// Use memory if available, else load
session_metadata: memory.has("workflow-session.json")
? memory.get("workflow-session.json")
: Read(.workflow/WFS-[id]/workflow-session.json),
// MCP capabilities - agent will use these tools
mcp_capabilities: {
code_index: true,
exa_code: true,
exa_web: true
}
}
// Note: Agent will execute these steps autonomously:
// - bash(~/.claude/scripts/get_modules_by_depth.sh) for project structure
// - Read(CLAUDE.md) and Read(README.md) for documentation
```
## Session ID Integration
### Session ID Usage
- **Required Parameter**: `--session WFS-session-id`
- **Session Context Loading**: Load existing session state and task summaries
- **Session Continuity**: Maintain context across pipeline phases
- **Session Context Loading**: Load existing session state and metadata
- **Session Continuity**: Maintain context across workflow pipeline phases
### Session State Management
```bash
# Validate session exists
if [ ! -d ".workflow/${session_id}" ]; then
echo "❌ Session ${session_id} not found"
exit 1
fi
# Load session metadata
session_metadata=".workflow/${session_id}/workflow-session.json"
```
## Output Location
Context package output location:
```
.workflow/{session_id}/.process/context-package.json
```
## Error Handling
### Common Error Handling
1. **No Active Session**: Create temporary session directory
2. **MCP Tools Unavailable**: Fallback to traditional bash commands
3. **Permission Errors**: Prompt user to check file permissions
4. **Large Project Optimization**: Limit file count, prioritize high-relevance files
### Graceful Degradation Strategy
```bash
# Fallback when MCP unavailable
if ! command -v mcp__code-index__find_files; then
# Use find command for file discovery
find . -name "*{keyword}*" -type f -not -path "*/node_modules/*" -not -path "*/.git/*"
# Alternative pattern matching
find . -type f \( -name "*.ts" -o -name "*.js" -o -name "*.py" -o -name "*.go" \) -exec grep -l "{keyword}" {} \;
fi
# Use ripgrep instead of MCP search
rg "{keywords}" --type-add 'source:*.{ts,js,py,go}' -t source --max-count 30
# Content-based search with context
rg -A 3 -B 3 "{keywords}" --type-add 'source:*.{ts,js,py,go}' -t source
# Quick relevance check
grep -r --include="*.{ts,js,py,go}" -l "{keywords}" . | head -15
# Test files discovery
find . -name "*test*" -o -name "*spec*" | grep -E "\.(ts|js|py|go)$" | head -10
# Import/dependency analysis
rg "^(import|from|require|#include)" --type-add 'source:*.{ts,js,py,go}' -t source | head -20
```
## Performance Optimization
### Large Project Optimization Strategy
- **File Count Limit**: Maximum 50 files per type
- **Size Filtering**: Skip oversized files (>10MB)
- **Depth Limit**: Maximum search depth of 3 levels
- **Caching Strategy**: Cache project structure analysis results
### Parallel Processing
- Documentation collection and code search in parallel
- MCP tool calls and traditional commands in parallel
- Reduce I/O wait time
## Essential Bash Commands (Max 10)
### 1. Project Structure Analysis
```bash
~/.claude/scripts/get_modules_by_depth.sh
```
### 2. File Discovery by Keywords
```bash
find . -name "*{keyword}*" -type f -not -path "*/node_modules/*" -not -path "*/.git/*"
```
### 3. Content Search in Code Files
```bash
rg "{keyword}" --type-add 'source:*.{ts,js,py,go}' -t source --max-count 20
```
### 4. Configuration Files Discovery
```bash
find . -maxdepth 3 \( -name "*.json" -o -name "package.json" -o -name "requirements.txt" -o -name "Cargo.toml" \) -not -path "*/node_modules/*"
```
### 5. Documentation Files Collection
```bash
find . -name "*.md" -o -name "README*" -o -name "CLAUDE.md" | grep -v node_modules | head -10
```
### 6. Test Files Location
```bash
find . \( -name "*test*" -o -name "*spec*" \) -type f | grep -E "\.(js|ts|py|go)$" | head -10
```
### 7. Function/Class Definitions Search
```bash
rg "^(function|def|func|class|interface)" --type-add 'source:*.{ts,js,py,go}' -t source -n --max-count 15
```
### 8. Import/Dependency Analysis
```bash
rg "^(import|from|require|#include)" --type-add 'source:*.{ts,js,py,go}' -t source | head -15
```
### 9. Workflow Session Information
```bash
find .workflow/ -name "*.json" -path "*/${session_id}/*" -o -name "workflow-session.json" | head -5
```
### 10. Context-Aware Content Search
```bash
rg -A 2 -B 2 "{keywords}" --type-add 'source:*.{ts,js,py,go}' -t source --max-count 10
### Session Validation
```javascript
// Validate session exists
const sessionPath = `.workflow/${session_id}`;
if (!fs.existsSync(sessionPath)) {
console.error(`❌ Session ${session_id} not found`);
process.exit(1);
}
```
## Success Criteria
- Generate valid context-package.json file
- Contains sufficient relevant information for subsequent analysis
- Execution time controlled within 30 seconds
- File relevance accuracy rate >80%
- Valid context-package.json generated in correct location
- Contains sufficient relevant information (>80% relevance)
- Execution completes within reasonable time (<2 minutes)
- All required fields present and properly formatted
- Agent reports completion status with statistics
## Related Commands
- `/workflow:tools:concept-enhanced` - Consumes output of this command for analysis
- `/workflow:plan` - Calls this command to gather context
- `/workflow:status` - Can display context collection status