feat: Add parallel explore agents to context-gather workflow

- context-gather.md: Add Step 2 with complexity assessment (Low/Medium/High)
  and parallel cli-explore-agent execution (1-4 agents based on complexity)
- context-search-agent.md: Add Track 0 for exploration aggregation with
  exploration_results schema including all_patterns and all_integration_points
- conflict-resolution.md: Consume exploration_results for enhanced conflict
  detection with pre-identified conflict indicators
- task-generate-agent.md: Use exploration critical_files for focus_paths
  and all_patterns/all_integration_points for implementation guidance

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

Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
catlog22
2025-11-28 23:08:20 +08:00
parent e75cdf0b61
commit 57a86ab36f
4 changed files with 223 additions and 33 deletions

View File

@@ -100,10 +100,56 @@ if (!memory.has("README.md")) Read(README.md)
### Phase 2: Multi-Source Context Discovery
Execute all 3 tracks in parallel for comprehensive coverage.
Execute all tracks in parallel for comprehensive coverage.
**Note**: Historical archive analysis (querying `.workflow/archives/manifest.json`) is optional and should be performed if the manifest exists. Inject findings into `conflict_detection.historical_conflicts[]`.
#### Track 0: Exploration Aggregation (Optional)
**Trigger**: When `explorations-manifest.json` exists in session `.process/` folder
```javascript
// Check for exploration results from context-gather parallel explore phase
const manifestPath = `.workflow/active/${session_id}/.process/explorations-manifest.json`;
if (file_exists(manifestPath)) {
const manifest = JSON.parse(Read(manifestPath));
// Load full exploration data from each file
const explorationData = manifest.explorations.map(exp => ({
...exp,
data: JSON.parse(Read(exp.path))
}));
// Build explorations array with summaries
const explorations = explorationData.map(exp => ({
angle: exp.angle,
file: exp.file,
path: exp.path,
index: exp.data._metadata?.exploration_index || exp.index,
summary: {
relevant_files_count: exp.data.relevant_files?.length || 0,
key_patterns: exp.data.patterns,
integration_points: exp.data.integration_points
}
}));
// Aggregate insights across all explorations (fixed data access)
const aggregated_insights = {
critical_files: deduplicateByRelevance(explorationData.flatMap(e => e.data.relevant_files || [])),
conflict_indicators: explorationData.flatMap(e => extractConflictIndicators(e.data, e.angle)),
clarification_needs: deduplicateQuestions(explorationData.flatMap(e => e.data.clarification_needs || [])),
constraints: explorationData.map(e => ({ constraint: e.data.constraints, source_angle: e.angle })).filter(c => c.constraint),
all_patterns: explorationData.map(e => ({ patterns: e.data.patterns, source_angle: e.angle })),
all_integration_points: explorationData.map(e => ({ points: e.data.integration_points, source_angle: e.angle }))
};
// Store for Phase 3 packaging
exploration_results = { manifest_path: manifestPath, exploration_count: manifest.exploration_count,
complexity: manifest.complexity, angles: manifest.angles_explored,
explorations, aggregated_insights };
}
```
#### Track 1: Reference Documentation
Extract from Phase 0 loaded docs:
@@ -393,10 +439,39 @@ Calculate risk level based on:
},
"affected_modules": ["auth", "user-model", "middleware"],
"mitigation_strategy": "Incremental refactoring with backward compatibility"
},
"exploration_results": {
"manifest_path": ".workflow/active/{session}/.process/explorations-manifest.json",
"exploration_count": 3,
"complexity": "Medium",
"angles": ["architecture", "dependencies", "testing"],
"explorations": [
{
"angle": "architecture",
"file": "exploration-architecture.json",
"path": ".workflow/active/{session}/.process/exploration-architecture.json",
"index": 1,
"summary": {
"relevant_files_count": 5,
"key_patterns": "Service layer with DI",
"integration_points": "Container.registerService:45-60"
}
}
],
"aggregated_insights": {
"critical_files": [{"path": "src/auth/AuthService.ts", "relevance": 0.95, "mentioned_by_angles": ["architecture"]}],
"conflict_indicators": [{"type": "pattern_mismatch", "description": "...", "source_angle": "architecture", "severity": "medium"}],
"clarification_needs": [{"question": "...", "context": "...", "options": [], "source_angle": "architecture"}],
"constraints": [{"constraint": "Must follow existing DI pattern", "source_angle": "architecture"}],
"all_patterns": [{"patterns": "Service layer with DI", "source_angle": "architecture"}],
"all_integration_points": [{"points": "Container.registerService:45-60", "source_angle": "architecture"}]
}
}
}
```
**Note**: `exploration_results` is populated when exploration files exist (from context-gather parallel explore phase). If no explorations, this field is omitted or empty.
## Quality Validation

View File

@@ -114,35 +114,44 @@ Task(subagent_type="cli-execution-agent", prompt=`
- Risk: {conflict_risk}
- Files: {existing_files_list}
## Exploration Context (from context-package.exploration_results)
- Exploration Count: ${contextPackage.exploration_results?.exploration_count || 0}
- Angles Analyzed: ${JSON.stringify(contextPackage.exploration_results?.angles || [])}
- Pre-identified Conflict Indicators: ${JSON.stringify(contextPackage.exploration_results?.aggregated_insights?.conflict_indicators || [])}
- Critical Files: ${JSON.stringify(contextPackage.exploration_results?.aggregated_insights?.critical_files?.map(f => f.path) || [])}
- All Patterns: ${JSON.stringify(contextPackage.exploration_results?.aggregated_insights?.all_patterns || [])}
- All Integration Points: ${JSON.stringify(contextPackage.exploration_results?.aggregated_insights?.all_integration_points || [])}
## Analysis Steps
### 1. Load Context
- Read existing files from conflict_detection.existing_files
- Load plan from .workflow/active/{session_id}/.process/context-package.json
- **NEW**: Load exploration_results and use aggregated_insights for enhanced analysis
- Extract role analyses and requirements
### 2. Execute CLI Analysis (Enhanced with Scenario Uniqueness Detection)
### 2. Execute CLI Analysis (Enhanced with Exploration + Scenario Uniqueness)
Primary (Gemini):
cd {project_root} && gemini -p "
PURPOSE: Detect conflicts between plan and codebase, including module scenario overlaps
PURPOSE: Detect conflicts between plan and codebase, using exploration insights
TASK:
Compare architectures
**Review pre-identified conflict_indicators from exploration results**
• Compare architectures (use exploration key_patterns)
• Identify breaking API changes
• Detect data model incompatibilities
• Assess dependency conflicts
• **NEW: Analyze module scenario uniqueness**
- Extract new module functionality from plan
- Search all existing modules with similar functionality
- Compare scenario coverage and identify overlaps
• **Analyze module scenario uniqueness**
- Use exploration integration_points for precise locations
- Cross-validate with exploration critical_files
- Generate clarification questions for boundary definition
MODE: analysis
CONTEXT: @**/*.ts @**/*.js @**/*.tsx @**/*.jsx @.workflow/active/{session_id}/**/*
EXPECTED: Conflict list with severity ratings, including ModuleOverlap conflicts with:
- Existing module list with scenarios
- Overlap analysis matrix
EXPECTED: Conflict list with severity ratings, including:
- Validation of exploration conflict_indicators
- ModuleOverlap conflicts with overlap_analysis
- Targeted clarification questions
RULES: $(cat ~/.claude/workflows/cli-templates/prompts/analysis/02-analyze-code-patterns.txt) | Focus on breaking changes, migration needs, and functional overlaps | analysis=READ-ONLY
RULES: $(cat ~/.claude/workflows/cli-templates/prompts/analysis/02-analyze-code-patterns.txt) | Focus on breaking changes, migration needs, and functional overlaps | Prioritize exploration-identified conflicts | analysis=READ-ONLY
"
Fallback: Qwen (same prompt) → Claude (manual analysis)

View File

@@ -36,24 +36,23 @@ Step 1: Context-Package Detection
├─ Valid package exists → Return existing (skip execution)
└─ No valid package → Continue to Step 2
Step 2: Invoke Context-Search Agent
├─ Phase 1: Initialization & Pre-Analysis
│ ├─ Load project.json as primary context
│ ├─ Initialize code-index
│ └─ Classify complexity
Phase 2: Multi-Source Discovery
│ ├─ Track 1: Historical archive analysis
│ ├─ Track 2: Reference documentation
│ ├─ Track 3: Web examples (Exa MCP)
│ └─ Track 4: Codebase analysis (5-layer)
└─ Phase 3: Synthesis & Packaging
├─ Apply relevance scoring
├─ Integrate brainstorm artifacts
├─ Perform conflict detection
└─ Generate context-package.json
Step 2: Complexity Assessment & Parallel Explore (NEW)
├─ Analyze task_description → classify Low/Medium/High
├─ Select exploration angles (1-4 based on complexity)
├─ Launch N cli-explore-agents in parallel
│ └─ Each outputs: exploration-{angle}.json
Generate explorations-manifest.json
Step 3: Output Verification
Verify context-package.json created
Step 3: Invoke Context-Search Agent (with exploration input)
Phase 1: Initialization & Pre-Analysis
├─ Phase 2: Multi-Source Discovery
│ ├─ Track 0: Exploration aggregation (NEW)
│ ├─ Track 1-4: Existing tracks
└─ Phase 3: Synthesis & Packaging
└─ Generate context-package.json with exploration_results
Step 4: Output Verification
└─ Verify context-package.json contains exploration_results
```
## Execution Flow
@@ -80,10 +79,93 @@ if (file_exists(contextPackagePath)) {
}
```
### Step 2: Invoke Context-Search Agent
### Step 2: Complexity Assessment & Parallel Explore
**Only execute if Step 1 finds no valid package**
```javascript
// 2.1 Complexity Assessment
function analyzeTaskComplexity(taskDescription) {
const text = taskDescription.toLowerCase();
if (/architect|refactor|restructure|modular|cross-module/.test(text)) return 'High';
if (/multiple|several|integrate|migrate|extend/.test(text)) return 'Medium';
return 'Low';
}
const ANGLE_PRESETS = {
architecture: ['architecture', 'dependencies', 'modularity', 'integration-points'],
security: ['security', 'auth-patterns', 'dataflow', 'validation'],
performance: ['performance', 'bottlenecks', 'caching', 'data-access'],
bugfix: ['error-handling', 'dataflow', 'state-management', 'edge-cases'],
feature: ['patterns', 'integration-points', 'testing', 'dependencies'],
refactor: ['architecture', 'patterns', 'dependencies', 'testing']
};
function selectAngles(taskDescription, complexity) {
const text = taskDescription.toLowerCase();
let preset = 'feature';
if (/refactor|architect|restructure/.test(text)) preset = 'architecture';
else if (/security|auth|permission/.test(text)) preset = 'security';
else if (/performance|slow|optimi/.test(text)) preset = 'performance';
else if (/fix|bug|error|issue/.test(text)) preset = 'bugfix';
const count = complexity === 'High' ? 4 : (complexity === 'Medium' ? 3 : 1);
return ANGLE_PRESETS[preset].slice(0, count);
}
const complexity = analyzeTaskComplexity(task_description);
const selectedAngles = selectAngles(task_description, complexity);
const sessionFolder = `.workflow/active/${session_id}/.process`;
// 2.2 Launch Parallel Explore Agents
const explorationTasks = selectedAngles.map((angle, index) =>
Task(
subagent_type="cli-explore-agent",
description=`Explore: ${angle}`,
prompt=`
## Task Objective
Execute **${angle}** exploration for context gathering.
## Assigned Context
- **Exploration Angle**: ${angle}
- **Task Description**: ${task_description}
- **Session ID**: ${session_id}
- **Exploration Index**: ${index + 1} of ${selectedAngles.length}
- **Output File**: ${sessionFolder}/exploration-${angle}.json
## MANDATORY FIRST STEPS
1. Run: ~/.claude/scripts/get_modules_by_depth.sh
2. Run: rg -l "{keywords}" --type ts
3. Execute: cat ~/.claude/workflows/cli-templates/schemas/explore-json-schema.json
## Output
File: ${sessionFolder}/exploration-${angle}.json (following explore-json-schema.json)
Return: 2-3 sentence summary of ${angle} findings
`
)
);
// 2.3 Generate Manifest after all complete
const explorationFiles = bash(`find ${sessionFolder} -name "exploration-*.json" -type f`).split('\n').filter(f => f.trim());
const explorationManifest = {
session_id,
task_description,
timestamp: new Date().toISOString(),
complexity,
exploration_count: selectedAngles.length,
angles_explored: selectedAngles,
explorations: explorationFiles.map(file => {
const data = JSON.parse(Read(file));
return { angle: data._metadata.exploration_angle, file: file.split('/').pop(), path: file, index: data._metadata.exploration_index };
})
};
Write(`${sessionFolder}/explorations-manifest.json`, JSON.stringify(explorationManifest, null, 2));
```
### Step 3: Invoke Context-Search Agent
**Only execute after Step 2 completes**
```javascript
Task(
subagent_type="context-search-agent",
@@ -97,6 +179,12 @@ Task(
- **Task Description**: ${task_description}
- **Output Path**: .workflow/${session_id}/.process/context-package.json
## Exploration Input (from Step 2)
- **Manifest**: ${sessionFolder}/explorations-manifest.json
- **Exploration Count**: ${explorationManifest.exploration_count}
- **Angles**: ${explorationManifest.angles_explored.join(', ')}
- **Complexity**: ${complexity}
## Mission
Execute complete context-search-agent workflow for implementation planning:
@@ -107,7 +195,8 @@ Execute complete context-search-agent workflow for implementation planning:
4. **Analysis**: Extract keywords, determine scope, classify complexity based on task description and project state
### Phase 2: Multi-Source Context Discovery
Execute all 4 discovery tracks:
Execute all discovery tracks:
- **Track 0**: Exploration aggregation (load ${sessionFolder}/explorations-manifest.json and aggregate)
- **Track 1**: Historical archive analysis (query manifest.json for lessons learned)
- **Track 2**: Reference documentation (CLAUDE.md, architecture docs)
- **Track 3**: Web examples (use Exa MCP for unfamiliar tech/APIs)
@@ -130,6 +219,7 @@ Complete context-package.json with:
- **dependencies**: {internal[], external[]} with dependency graph
- **brainstorm_artifacts**: {guidance_specification, role_analyses[], synthesis_output} with content
- **conflict_detection**: {risk_level, risk_factors, affected_modules[], mitigation_strategy, historical_conflicts[]}
- **exploration_results**: {manifest_path, exploration_count, angles, explorations[], aggregated_insights} (from Track 0)
## Quality Validation
Before completion verify:
@@ -146,7 +236,7 @@ Report completion with statistics.
)
```
### Step 3: Output Verification
### Step 4: Output Verification
After agent completes, verify output:
@@ -156,6 +246,12 @@ const outputPath = `.workflow/${session_id}/.process/context-package.json`;
if (!file_exists(outputPath)) {
throw new Error("❌ Agent failed to generate context-package.json");
}
// Verify exploration_results included
const pkg = JSON.parse(Read(outputPath));
if (pkg.exploration_results?.exploration_count > 0) {
console.log(`✅ Exploration results aggregated: ${pkg.exploration_results.exploration_count} angles`);
}
```
## Parameter Reference
@@ -176,6 +272,7 @@ Refer to `context-search-agent.md` Phase 3.7 for complete `context-package.json`
- **dependencies**: Internal and external dependency graphs
- **brainstorm_artifacts**: Brainstorm documents with full content (if exists)
- **conflict_detection**: Risk assessment with mitigation strategies and historical conflicts
- **exploration_results**: Aggregated exploration insights (from parallel explore phase)
## Historical Archive Analysis

View File

@@ -100,12 +100,21 @@ Session ID: {session-id}
Planning Mode: {agent-mode | cli-execute-mode}
MCP Capabilities: {exa_code, exa_web, code_index}
## EXPLORATION CONTEXT (from context-package.exploration_results)
- Load exploration_results from context-package.json
- Use aggregated_insights.critical_files for focus_paths generation
- Apply aggregated_insights.constraints to acceptance criteria
- Reference aggregated_insights.all_patterns for implementation approach
- Use aggregated_insights.all_integration_points for precise modification locations
- Use conflict_indicators for risk-aware task sequencing
## EXPECTED DELIVERABLES
1. Task JSON Files (.task/IMPL-*.json)
- 6-field schema (id, title, status, context_package_path, meta, context, flow_control)
- Quantified requirements with explicit counts
- Artifacts integration from context package
- Flow control with pre_analysis steps
- **focus_paths enhanced with exploration critical_files**
- Flow control with pre_analysis steps (include exploration integration_points analysis)
2. Implementation Plan (IMPL_PLAN.md)
- Context analysis and artifact references