refactor: migrate agents to path-based context loading

- Update action-planning-agent and task-generate-agent to load context
  via file paths instead of embedded context packages
- Streamline test-cycle-execute workflow execution
- Remove redundant content from conflict-resolution and context-gather
- Update SKILL.md and tdd-plan documentation
This commit is contained in:
catlog22
2025-11-23 22:06:13 +08:00
parent 3915f7cb35
commit 4bb4bdc124
7 changed files with 348 additions and 453 deletions

View File

@@ -21,15 +21,15 @@ You are a pure execution agent specialized in creating actionable implementation
## Execution Process
### Input Processing
**What you receive:**
- **Execution Context Package**: Structured context from command layer
**What you receive from command layer:**
- **Session Paths**: File paths to load content autonomously
- `session_metadata_path`: Session configuration and user input
- `context_package_path`: Context package with brainstorming artifacts catalog
- **Metadata**: Simple values
- `session_id`: Workflow session identifier (WFS-[topic])
- `session_metadata`: Session configuration and state
- `analysis_results`: Analysis recommendations and task breakdown
- `artifacts_inventory`: Detected brainstorming outputs (role analyses, guidance-specification, role analyses)
- `context_package`: Project context and assets
- `mcp_capabilities`: Available MCP tools (exa-code, exa-web)
- `mcp_analysis`: Optional pre-executed MCP analysis results
- `execution_mode`: agent-mode | cli-execute-mode
- `mcp_capabilities`: Available MCP tools (exa_code, exa_web, code_index)
**Legacy Support** (backward compatibility):
- **pre_analysis configuration**: Multi-step array format with action, template, method fields
@@ -37,73 +37,103 @@ You are a pure execution agent specialized in creating actionable implementation
- **Task requirements**: Direct task description
### Execution Flow (Two-Phase)
```
Phase 1: Context Validation & Enhancement (Discovery Results Provided)
1. Receive and validate execution context package
2. Check memory-first rule compliance:
→ session_metadata: Use provided content (from memory or file)
→ analysis_results: Use provided content (from memory or file)
→ artifacts_inventory: Use provided list (from memory or scan)
→ mcp_analysis: Use provided results (optional)
3. Optional MCP enhancement (if not pre-executed):
Phase 1: Content Loading & Context Assembly
1. Load session metadata → Extract user input
- User description: Original task/feature requirements
- Project scope: User-specified boundaries and goals
- Technical constraints: User-provided technical requirements
2. Load context package → Extract key fields
- brainstorm_artifacts: Catalog of brainstorming outputs
- guidance_specification: Path to overall framework
- role_analyses[]: Array of role analysis files with priorities
- synthesis_output: Path to synthesis results (if exists)
- conflict_resolution: Conflict status and affected files
- focus_areas: Target directories for implementation
- assets: Existing code patterns to reuse
- conflict_risk: Risk level (low/medium/high)
3. Load brainstorming artifacts (in priority order)
a. guidance-specification.md (Highest Priority)
→ Overall design framework and architectural decisions
b. Role analyses (High Priority - load ALL files)
→ system-architect/analysis.md
→ subject-matter-expert/analysis.md
→ (Other roles as listed in context package)
c. Synthesis output (if exists)
→ Integrated view with clarifications
d. Conflict resolution (if conflict_risk ≥ medium)
→ Review resolved conflicts in artifacts
4. Optional MCP enhancement
→ mcp__exa__get_code_context_exa() for best practices
→ mcp__exa__web_search_exa() for external research
4. Assess task complexity (simple/medium/complex) from analysis
5. Assess task complexity (simple/medium/complex)
Phase 2: Document Generation (Autonomous Output)
1. Extract task definitions from analysis_results
2. Generate task JSON files with 5-field schema + artifacts
1. Synthesize requirements from all sources (user input + brainstorming artifacts)
2. Generate task JSON files with 6-field schema + artifacts integration
3. Create IMPL_PLAN.md with context analysis and artifact references
4. Generate TODO_LIST.md with proper structure (▸, [ ], [x])
5. Update session state for execution readiness
```
### Context Package Usage
### Context Package Fields to Load
**Standard Context Structure**:
**Load from `context_package_path` - fields defined by context-search-agent**:
**Always Present**:
- `metadata.task_description`: User's original task description
- `metadata.keywords`: Extracted technical keywords
- `metadata.complexity`: Task complexity level (simple/medium/complex)
- `metadata.session_id`: Workflow session identifier
- `project_context.architecture_patterns`: Architecture patterns (MVC, Service layer, etc.)
- `project_context.tech_stack`: Language, frameworks, libraries
- `project_context.coding_conventions`: Naming, error handling, async patterns
- `assets.source_code[]`: Relevant existing files with paths and metadata
- `assets.documentation[]`: Reference docs (CLAUDE.md, API docs)
- `assets.config[]`: Configuration files (package.json, .env.example)
- `assets.tests[]`: Test files
- `dependencies.internal[]`: Module dependencies
- `dependencies.external[]`: Package dependencies
- `conflict_detection.risk_level`: Conflict risk (low/medium/high)
**Conditionally Present** (check existence before loading):
- `brainstorm_artifacts.guidance_specification`: Overall design framework (if exists)
- Check: `brainstorm_artifacts?.guidance_specification?.exists === true`
- Content: Use `content` field if present, else load from `path`
- `brainstorm_artifacts.role_analyses[]`: Role-specific analyses (if array not empty)
- Each role: `role_analyses[i].files[j]` has `path` and `content`
- `brainstorm_artifacts.synthesis_output`: Synthesis results (if exists)
- Check: `brainstorm_artifacts?.synthesis_output?.exists === true`
- Content: Use `content` field if present, else load from `path`
- `conflict_detection.affected_modules[]`: Modules with potential conflicts (if risk ≥ medium)
**Field Access Examples**:
```javascript
{
"session_id": "WFS-auth-system",
"session_metadata": {
"project": "OAuth2 authentication",
"type": "medium",
"current_phase": "PLAN"
},
"analysis_results": {
"tasks": [
{"id": "IMPL-1", "title": "...", "requirements": [...]}
],
"complexity": "medium",
"dependencies": [...]
},
"artifacts_inventory": {
"synthesis_specification": ".workflow/WFS-auth/.brainstorming/role analysis documents",
"topic_framework": ".workflow/WFS-auth/.brainstorming/guidance-specification.md",
"role_analyses": [
".workflow/WFS-auth/.brainstorming/system-architect/analysis.md",
".workflow/WFS-auth/.brainstorming/subject-matter-expert/analysis.md"
]
},
"context_package": {
"assets": [...],
"focus_areas": [...]
},
"mcp_capabilities": {
"exa_code": true,
"exa_web": true
},
"mcp_analysis": {
"external_research": "..."
}
// Always safe - direct field access
const techStack = contextPackage.project_context.tech_stack;
const riskLevel = contextPackage.conflict_detection.risk_level;
const existingCode = contextPackage.assets.source_code; // Array of files
// Conditional - use content if available, else load from path
if (contextPackage.brainstorm_artifacts?.guidance_specification?.exists) {
const spec = contextPackage.brainstorm_artifacts.guidance_specification;
const content = spec.content || Read(spec.path);
}
if (contextPackage.brainstorm_artifacts?.role_analyses?.length > 0) {
contextPackage.brainstorm_artifacts.role_analyses.forEach(role => {
role.files.forEach(file => {
const analysis = file.content || Read(file.path);
});
});
}
```
**Using Context in Task Generation**:
1. **Extract Tasks**: Parse `analysis_results.tasks` array
2. **Map Artifacts**: Use `artifacts_inventory` to add artifact references to task.context
3. **Assess Complexity**: Use `analysis_results.complexity` for document structure decision
4. **Session Paths**: Use `session_id` to construct output paths (.workflow/active/{session_id}/)
### MCP Integration Guidelines
**Exa Code Context** (`mcp_capabilities.exa_code = true`):
@@ -503,13 +533,13 @@ Use `analysis_results.complexity` or task count to determine structure:
- Flat structure: IMPL_PLAN.md + TODO_LIST.md + task JSONs
- No container tasks, all leaf tasks
**Medium Tasks** (6-10 tasks):
**Medium Tasks** (6-12 tasks):
- Two-level hierarchy: IMPL_PLAN.md + TODO_LIST.md + task JSONs
- Optional container tasks for grouping
**Complex Tasks** (>10 tasks):
- **Re-scope required**: Maximum 10 tasks hard limit
- If analysis_results contains >10 tasks, consolidate or request re-scoping
**Complex Tasks** (>12 tasks):
- **Re-scope required**: Maximum 12 tasks hard limit
- If analysis_results contains >12 tasks, consolidate or request re-scoping
## Quantification Requirements (MANDATORY)
@@ -566,7 +596,7 @@ Use `analysis_results.complexity` or task count to determine structure:
- **Follow 5-field schema**: All task JSONs must have id, title, status, meta, context, flow_control
- **Map artifacts**: Use artifacts_inventory to populate task.context.artifacts array
- **Add MCP integration**: Include MCP tool steps in flow_control.pre_analysis when capabilities available
- **Validate task count**: Maximum 10 tasks hard limit, request re-scope if exceeded
- **Validate task count**: Maximum 12 tasks hard limit, request re-scope if exceeded
- **Use session paths**: Construct all paths using provided session_id
- **Link documents properly**: Use correct linking format (📋 for JSON, ✅ for summaries)
- **Run validation checklist**: Verify all quantification requirements before finalizing task JSONs
@@ -575,6 +605,6 @@ Use `analysis_results.complexity` or task count to determine structure:
- Load files directly (use provided context package instead)
- Assume default locations (always use session_id in paths)
- Create circular dependencies in task.depends_on
- Exceed 10 tasks without re-scoping
- Exceed 12 tasks without re-scoping
- Skip artifact integration when artifacts_inventory is provided
- Ignore MCP capabilities when available

View File

@@ -278,57 +278,85 @@ Task(
subagent_type="cli-planning-agent",
description=`Analyze test failures and generate fix task (iteration ${currentIteration})`,
prompt=`
## Context Package
{
"session_id": "${sessionId}",
"iteration": ${currentIteration},
"analysis_type": "test-failure",
"failure_context": {
"failed_tests": ${JSON.stringify(failedTests)},
"error_messages": ${JSON.stringify(errorMessages)},
"test_output": "${testOutputPath}",
"pass_rate": ${passRate},
"previous_attempts": ${JSON.stringify(previousAttempts)}
},
"cli_config": {
"tool": "gemini",
"model": "gemini-3-pro-preview-11-2025",
"template": "01-diagnose-bug-root-cause.txt",
"timeout": 2400000,
"fallback": "qwen"
},
"task_config": {
"agent": "@test-fix-agent",
"type": "test-fix-iteration",
"max_iterations": ${maxIterations},
"use_codex": false
}
}
## Task Objective
Analyze test failures and generate structured fix task JSON for iteration ${currentIteration}
## Your Task
1. Execute CLI analysis using Gemini (fallback to Qwen if needed)
2. Parse CLI output and extract fix strategy with specific modification points
3. Generate IMPL-fix-${currentIteration}.json using your internal task template
4. Save analysis report to .process/iteration-${currentIteration}-analysis.md
5. Report success and task ID back to orchestrator
## MANDATORY FIRST STEPS
1. Read test results: {session.test_results_path}
2. Read test output: {session.test_output_path}
3. Read iteration state: {session.iteration_state_path}
4. Read fix history (if exists): {session.fix_history_path}
## Session Paths
- Workflow Dir: {session.workflow_dir}
- Test Results: {session.test_results_path}
- Test Output: {session.test_output_path}
- Iteration State: {session.iteration_state_path}
- Fix History: {session.fix_history_path}
- Task Output Dir: {session.task_dir}
- Analysis Output: {session.process_dir}/iteration-${currentIteration}-analysis.md
- CLI Output: {session.process_dir}/iteration-${currentIteration}-cli-output.txt
## Context Metadata
- Session ID: ${sessionId}
- Current Iteration: ${currentIteration}
- Max Iterations: ${maxIterations}
- Current Pass Rate: ${passRate}%
## CLI Configuration
- Tool: gemini (fallback: qwen)
- Model: gemini-3-pro-preview-11-2025
- Template: 01-diagnose-bug-root-cause.txt
- Timeout: 2400000ms
## Expected Deliverables
1. Task JSON file: {session.task_dir}/IMPL-fix-${currentIteration}.json
2. Analysis report: {session.process_dir}/iteration-${currentIteration}-analysis.md
3. CLI raw output: {session.process_dir}/iteration-${currentIteration}-cli-output.txt
4. Return task ID to orchestrator
## Quality Standards
- Fix strategy must include specific modification points (file:function:lines)
- Analysis must identify root causes, not just symptoms
- Task JSON must be valid and complete with all required fields
- All deliverables saved to specified paths
## Success Criteria
Generate valid IMPL-fix-${currentIteration}.json with:
- Concrete fix strategy with modification points
- Root cause analysis from CLI tool
- All required task JSON fields (id, title, status, meta, context, flow_control)
- Return task ID for orchestrator to queue
`
)
```
#### Agent Response
#### Agent Response Format
**Agent must return structured response with deliverable paths:**
```javascript
{
"status": "success",
"task_id": "IMPL-fix-${iteration}",
"task_path": ".workflow/${session}/.task/IMPL-fix-${iteration}.json",
"analysis_report": ".process/iteration-${iteration}-analysis.md",
"cli_output": ".process/iteration-${iteration}-cli-output.txt",
"summary": "Fix authentication token validation and null check issues",
"modification_points_count": 2,
"estimated_complexity": "low"
"deliverables": {
"task_json": ".workflow/${session}/.task/IMPL-fix-${iteration}.json",
"analysis_report": ".workflow/${session}/.process/iteration-${iteration}-analysis.md",
"cli_output": ".workflow/${session}/.process/iteration-${iteration}-cli-output.txt"
},
"summary": {
"root_causes": ["Authentication token validation missing", "Null check missing"],
"modification_points": [
"src/auth/client.ts:sendRequest:45-50",
"src/validators/user.ts:validateUser:23-25"
],
"estimated_complexity": "low",
"expected_pass_rate_improvement": "85% → 95%"
}
}
```
**Orchestrator validates all deliverable paths exist before proceeding.**
#### Generated Analysis Report Structure
The @cli-planning-agent generates `.process/iteration-N-analysis.md`:
@@ -503,54 +531,55 @@ TodoWrite({
4. **Iteration Complete**: Mark iteration item completed
5. **All Complete**: Mark parent task completed
## Agent Context Package
## Agent Context Loading
**Generated by test-cycle-execute orchestrator before launching agents.**
**Orchestrator provides file paths, agents load content themselves.**
The orchestrator assembles this context package from:
- Task JSON file (IMPL-*.json)
- Iteration state files
- Test results and failure context
- Session metadata
### Path References Provided to Agents
This package is passed to agents via the Task tool's prompt context.
**Orchestrator passes these paths via Task tool prompt:**
### Enhanced Context for Test-Fix Agent
```json
```javascript
{
"task": { /* IMPL-fix-N.json */ },
"iteration_context": {
"current_iteration": N,
"max_iterations": 5,
"previous_attempts": [
{
"iteration": N-1,
"failures": ["test1", "test2"],
"fixes_attempted": ["fix1", "fix2"],
"result": "partial_success"
}
],
"failure_analysis": {
"source": "gemini_cli",
"analysis_file": ".process/iteration-N-analysis.md",
"fix_strategy": { /* from CLI */ }
}
},
"test_context": {
"test_framework": "jest|pytest|...",
"test_files": ["path/to/test1.test.ts"],
"test_command": "npm test",
"coverage_target": 80
},
"session": {
"workflow_dir": ".workflow/active/WFS-test-{session}/",
"iteration_state_file": ".process/iteration-state.json",
"test_results_file": ".process/test-results.json",
"fix_history_file": ".process/fix-history.json"
}
// Primary Task Definition
"task_json_path": ".workflow/active/WFS-test-{session}/.task/IMPL-fix-N.json",
// Iteration Context Paths
"iteration_state_path": ".workflow/active/WFS-test-{session}/.process/iteration-state.json",
"fix_history_path": ".workflow/active/WFS-test-{session}/.process/fix-history.json",
// Test Context Paths
"test_results_path": ".workflow/active/WFS-test-{session}/.process/test-results.json",
"test_output_path": ".workflow/active/WFS-test-{session}/.process/test-output.log",
"test_context_path": ".workflow/active/WFS-test-{session}/.process/TEST_ANALYSIS_RESULTS.md",
// Analysis & Strategy Paths (for fix-iteration tasks)
"analysis_path": ".workflow/active/WFS-test-{session}/.process/iteration-N-analysis.md",
"cli_output_path": ".workflow/active/WFS-test-{session}/.process/iteration-N-cli-output.txt",
// Session Management Paths
"workflow_dir": ".workflow/active/WFS-test-{session}/",
"summaries_dir": ".workflow/active/WFS-test-{session}/.summaries/",
"todo_list_path": ".workflow/active/WFS-test-{session}/TODO_LIST.md",
// Metadata (simple values, not file content)
"session_id": "WFS-test-{session}",
"current_iteration": N,
"max_iterations": 5
}
```
### Agent Loading Sequence
**Agents must load files in this order:**
1. **Task JSON** (`task_json_path`) - Get task definition, requirements, fix strategy
2. **Iteration State** (`iteration_state_path`) - Understand current iteration context
3. **Test Results** (`test_results_path`) - Analyze current test status
4. **Test Output** (`test_output_path`) - Review detailed test execution logs
5. **Analysis Report** (`analysis_path`, for fix tasks) - Load CLI-generated fix strategy
6. **Fix History** (`fix_history_path`) - Review previous fix attempts to avoid repetition
## File Structure
### Test-Fix Session Files
@@ -616,77 +645,66 @@ This package is passed to agents via the Task tool's prompt context.
## Agent Prompt Template
**Unified template for all agent tasks (orchestrator invokes with Task tool):**
**Dynamic Generation**: Before agent invocation, orchestrator reads task JSON and extracts key requirements.
```bash
Task(subagent_type="{meta.agent}",
prompt="**TASK EXECUTION: {task.title}**
prompt="Execute task: {task.title}
## STEP 1: Load Complete Task JSON
**MANDATORY**: First load the complete task JSON from: {session.task_json_path}
{[FLOW_CONTROL]}
cat {session.task_json_path}
**Task Objectives** (from task JSON):
{task.context.requirements}
**CRITICAL**: Validate all required fields present
**Expected Deliverables**:
- For test-gen: Test files in target directories, test coverage report
- For test-fix: Test execution results saved to test-results.json, test-output.log
- For test-fix-iteration: Fixed code files, updated test results, iteration summary
## STEP 2: Task Context (From Loaded JSON)
**ID**: {task.id}
**Type**: {task.meta.type}
**Agent**: {task.meta.agent}
**Quality Standards**:
- All tests must execute without errors
- Test results must be saved in structured JSON format
- All deliverables must be saved to specified paths
- Task status must be updated in task JSON
## STEP 3: Execute Task Based on Type
**MANDATORY FIRST STEPS**:
1. Read complete task JSON: {session.task_json_path}
2. Load iteration state (if applicable): {session.iteration_state_path}
3. Load test context: {session.test_context_path}
### For test-gen (IMPL-001):
- Generate tests based on TEST_ANALYSIS_RESULTS.md
- Follow test framework conventions
- Create test files in target_files
Follow complete execution guidelines in @.claude/agents/{meta.agent}.md
### For test-fix (IMPL-002):
- Run test suite: {test_command}
- Collect results to .process/test-results.json
- Report results to orchestrator (do NOT analyze failures)
- Orchestrator will handle failure detection and iteration decisions
- If success: Mark complete
**Session Paths** (use these for all file operations):
- Workflow Dir: {session.workflow_dir}
- Task JSON: {session.task_json_path}
- TODO List: {session.todo_list_path}
- Summaries Dir: {session.summaries_dir}
- Test Results: {session.test_results_path}
- Test Output Log: {session.test_output_path}
- Iteration State: {session.iteration_state_path}
- Fix History: {session.fix_history_path}
### For test-fix-iteration (IMPL-fix-N):
- Load fix strategy from context.fix_strategy (CONTENT, not path)
- Apply surgical fixes to identified files
- Return results to orchestrator
- Do NOT run tests independently - orchestrator manages all test execution
- Do NOT handle failures - orchestrator analyzes and decides next iteration
**Critical Rules**:
- For test-fix tasks: Run tests and save results, do NOT analyze failures
- For fix-iteration tasks: Apply fixes from task JSON, do NOT run tests independently
- Orchestrator manages iteration loop and failure analysis
- Return results to orchestrator for next-step decisions
## STEP 4: Implementation Context (From JSON)
**Requirements**: {context.requirements}
**Fix Strategy**: {context.fix_strategy} (full content provided in task JSON)
**Failure Context**: {context.failure_context}
**Iteration History**: {context.inherited.iteration_history}
## STEP 5: Flow Control Execution
If flow_control.pre_analysis exists, execute steps sequentially
## STEP 6: Agent Completion
1. Execute task following implementation_approach
2. Update task status in JSON
3. Update TODO_LIST.md
4. Generate summary in .summaries/
5. **CRITICAL**: Save results for orchestrator to analyze
**Output Requirements**:
- test-results.json: Structured test results
- test-output.log: Full test output
- iteration-state.json: Current iteration state (if applicable)
- task-summary.md: Completion summary
**Return to Orchestrator**: Agent completes and returns. Orchestrator decides next action.
"),
description="Execute {task.type} task with JSON validation")
**Success Criteria**:
- Complete all task objectives as specified in task JSON
- Deliver all required outputs to specified paths
- Update task status and TODO_LIST.md
- Generate completion summary in .summaries/
",
description="Executing: {task.title}")
```
**Key Points**:
- Agent executes single task and returns
- Orchestrator analyzes results and decides next step
- Fix strategy content (not path) embedded in task JSON by orchestrator
- Agent does not manage iteration loop
**Key Changes from Previous Version**:
1. **Paths over Content**: Provide JSON paths for agent to read, not embedded content
2. **MANDATORY FIRST STEPS**: Explicit requirement to load task JSON and context
3. **Complete Session Paths**: All file paths provided for agent operations
4. **Emphasized Deliverables**: Clear deliverable requirements per task type
5. **Simplified Structure**: Removed type-specific instructions (agent reads from JSON)
## Error Handling & Recovery

View File

@@ -12,11 +12,6 @@ examples:
## Purpose
Analyzes conflicts between implementation plans and existing codebase, **including module scenario uniqueness detection**, generating multiple resolution strategies with **iterative clarification until boundaries are clear**.
**Key Enhancements**:
- **Scenario Uniqueness Detection**: Agent searches all existing modules to identify functional overlaps
- **Iterative Clarification Loop**: Unlimited questions per conflict until scenario boundaries are uniquely defined (max 10 rounds)
- **Dynamic Re-analysis**: Agent updates strategies based on user clarifications
**Scope**: Detection and strategy generation only - NO code modification or task creation.
**Trigger**: Auto-executes in `/workflow:plan` Phase 3 when `conflict_risk ≥ medium`.

View File

@@ -57,8 +57,6 @@ Task(
subagent_type="context-search-agent",
description="Gather comprehensive context for plan",
prompt=`
You are executing as context-search-agent (.claude/agents/context-search-agent.md).
## Execution Mode
**PLAN MODE** (Comprehensive) - Full Phase 1-3 execution

View File

@@ -17,240 +17,140 @@ Autonomous task JSON and IMPL_PLAN.md generation using action-planning-agent wit
- **Two-Phase Flow**: Discovery (context gathering) → Output (document generation)
- **Memory-First**: Reuse loaded documents from conversation memory
- **MCP-Enhanced**: Use MCP tools for advanced code analysis and research
- **Pre-Selected Templates**: Command selects correct template based on `--cli-execute` flag **before** invoking agent
- **Agent Simplicity**: Agent receives pre-selected template and focuses only on content generation
- **Path Clarity**: All `focus_paths` prefer absolute paths (e.g., `D:\\project\\src\\module`), or clear relative paths from project root (e.g., `./src/module`)
## Execution Lifecycle
### Phase 1: Discovery & Context Loading
**⚡ Memory-First Rule**: Skip file loading if documents already in conversation memory
### Phase 1: Context Preparation (Command Responsibility)
**Agent Context Package**:
```javascript
{
"session_id": "WFS-[session-id]",
"execution_mode": "agent-mode" | "cli-execute-mode", // Determined by flag
"task_json_template_path": "~/.claude/workflows/cli-templates/prompts/workflow/task-json-agent-mode.txt"
| "~/.claude/workflows/cli-templates/prompts/workflow/task-json-cli-mode.txt",
// Path selected by command based on --cli-execute flag, agent reads it
"session_metadata": {
// If in memory: use cached content
// Else: Load from .workflow/active//{session-id}/workflow-session.json
},
"brainstorm_artifacts": {
// Loaded from context-package.json → brainstorm_artifacts section
"role_analyses": [
{
"role": "system-architect",
"files": [{"path": "...", "type": "primary|supplementary"}]
}
],
"guidance_specification": {"path": "...", "exists": true},
"synthesis_output": {"path": "...", "exists": true},
"conflict_resolution": {"path": "...", "exists": true} // if conflict_risk >= medium
},
"context_package_path": ".workflow/active//{session-id}/.process/context-package.json",
"context_package": {
// If in memory: use cached content
// Else: Load from .workflow/active//{session-id}/.process/context-package.json
},
"mcp_capabilities": {
"code_index": true,
"exa_code": true,
"exa_web": true
}
}
**Command prepares session paths and metadata, agent loads content autonomously.**
**Session Path Structure**:
```
.workflow/active/WFS-{session-id}/
├── workflow-session.json # Session metadata
├── .process/
└── context-package.json # Context package with artifact catalog
├── .task/ # Output: Task JSON files
├── IMPL_PLAN.md # Output: Implementation plan
└── TODO_LIST.md # Output: TODO list
```
**Discovery Actions**:
1. **Load Session Context** (if not in memory)
```javascript
if (!memory.has("workflow-session.json")) {
Read(.workflow/active//{session-id}/workflow-session.json)
}
```
**Command Preparation**:
1. **Assemble Session Paths** for agent prompt:
- `session_metadata_path`
- `context_package_path`
- Output directory paths
2. **Load Context Package** (if not in memory)
```javascript
if (!memory.has("context-package.json")) {
Read(.workflow/active//{session-id}/.process/context-package.json)
}
```
2. **Provide Metadata** (simple values):
- `session_id`
- `execution_mode` (agent-mode | cli-execute-mode)
- `mcp_capabilities` (available MCP tools)
3. **Extract & Load Role Analyses** (from context-package.json)
```javascript
// Extract role analysis paths from context package
const roleAnalysisPaths = contextPackage.brainstorm_artifacts.role_analyses
.flatMap(role => role.files.map(f => f.path));
// Load each role analysis file
roleAnalysisPaths.forEach(path => Read(path));
```
4. **Load Conflict Resolution** (from context-package.json, if exists)
```javascript
if (contextPackage.brainstorm_artifacts.conflict_resolution?.exists) {
Read(contextPackage.brainstorm_artifacts.conflict_resolution.path)
}
```
5. **Code Analysis with Native Tools** (optional - enhance understanding)
```bash
# Find relevant files for task context
find . -name "*auth*" -type f
rg "authentication|oauth" -g "*.ts"
```
6. **MCP External Research** (optional - gather best practices)
```javascript
// Get external examples for implementation
mcp__exa__get_code_context_exa(
query="TypeScript JWT authentication best practices",
tokensNum="dynamic"
)
```
**Note**: Agent autonomously loads files based on context package content (dynamic, not fixed template). Brainstorming artifacts only loaded if they exist in session.
### Phase 2: Agent Execution (Document Generation)
**Pre-Agent Template Selection** (Command decides path before invoking agent):
```javascript
// Command checks flag and selects template PATH (not content)
const templatePath = hasCliExecuteFlag
? "~/.claude/workflows/cli-templates/prompts/workflow/task-json-cli-mode.txt"
: "~/.claude/workflows/cli-templates/prompts/workflow/task-json-agent-mode.txt";
```
**Agent Invocation**:
```javascript
Task(
subagent_type="action-planning-agent",
description="Generate task JSON and implementation plan",
prompt=`
## Execution Context
## Task Objective
Generate implementation plan (IMPL_PLAN.md), task JSONs, and TODO list for workflow session
**Session ID**: WFS-{session-id}
**Execution Mode**: {agent-mode | cli-execute-mode}
**Task JSON Template Path**: {template_path}
## MANDATORY FIRST STEPS
1. Read session metadata: {session.session_metadata_path}
2. Load context package: {session.context_package_path}
3. **Dynamically load files based on context package content** (see below)
## Phase 1: Discovery Results (Provided Context)
## Dynamic Content Loading Strategy
### Session Metadata
{session_metadata_content}
**Load files based on what exists in context package - NOT a fixed template**
### Role Analyses (Enhanced by Synthesis)
{role_analyses_content}
- Includes requirements, design specs, enhancements, and clarifications from synthesis phase
### Step 1: Always Load (Required)
- **Session Metadata** → Extract user input
- User description: Original task requirements
- Project scope and boundaries
- Technical constraints
### Artifacts Inventory
- **Guidance Specification**: {guidance_spec_path}
- **Role Analyses**: {role_analyses_list}
### Step 2: Check Context Package (Conditional Loading)
### Context Package
{context_package_summary}
- Includes conflict_risk assessment
**If `brainstorm_artifacts` exists in context package:**
- Load artifacts **in priority order** as listed below
- **If `brainstorm_artifacts` does NOT exist**: Skip to Step 3
### Conflict Resolution (Conditional)
If conflict_risk was medium/high, modifications have been applied to:
- **guidance-specification.md**: Design decisions updated to resolve conflicts
- **Role analyses (*.md)**: Recommendations adjusted for compatibility
- **context-package.json**: Marked as "resolved" with conflict IDs
- NO separate CONFLICT_RESOLUTION.md file (conflicts resolved in-place)
**Priority Loading (when artifacts exist):**
1. **guidance-specification.md** (if `guidance_specification.exists = true`)
- Overall design framework - use as primary reference
### MCP Analysis Results (Optional)
**Code Structure**: {mcp_code_index_results}
**External Research**: {mcp_exa_research_results}
2. **Role Analyses** (if `role_analyses[]` array exists)
- Load ALL role analysis files listed in array
- Each file path: `role_analyses[i].files[j].path`
## Phase 2: Document Generation Task
3. **Synthesis Output** (if `synthesis_output.exists = true`)
- Integrated view with clarifications
**Agent Configuration Reference**: All task generation rules, quantification requirements, quality standards, and execution details are defined in action-planning-agent.
4. **Conflict Resolution** (if `conflict_risk` = "medium" or "high")
- Check `conflict_resolution.status`
- If "resolved": Use updated artifacts (conflicts pre-addressed)
Refer to: @.claude/agents/action-planning-agent.md for:
- Task Decomposition Standards
- Quantification Requirements (MANDATORY)
- 5-Field Task JSON Schema
- IMPL_PLAN.md Structure
- TODO_LIST.md Format
- Execution Flow & Quality Validation
### Step 3: Extract Project Context
- `focus_areas`: Target directories for implementation
- `assets`: Existing code patterns to reuse
### Required Outputs Summary
## Session Paths
- Session Metadata: .workflow/active/{session-id}/workflow-session.json
- Context Package: .workflow/active/{session-id}/.process/context-package.json
- Output Task Dir: .workflow/active/{session-id}/.task/
- Output IMPL_PLAN: .workflow/active/{session-id}/IMPL_PLAN.md
- Output TODO_LIST: .workflow/active/{session-id}/TODO_LIST.md
#### 1. Task JSON Files (.task/IMPL-*.json)
- **Location**: `.workflow/active//{session-id}/.task/`
- **Template**: Read from `{template_path}` (pre-selected by command based on `--cli-execute` flag)
- **Schema**: 5-field structure (id, title, status, meta, context, flow_control) with artifacts integration
- **Details**: See action-planning-agent.md § Task JSON Generation
## Context Metadata
- Session ID: {session-id}
- Execution Mode: {agent-mode | cli-execute-mode}
- MCP Capabilities Available: {exa_code, exa_web, code_index}
#### 2. IMPL_PLAN.md
- **Location**: `.workflow/active//{session-id}/IMPL_PLAN.md`
- **Template**: `~/.claude/workflows/cli-templates/prompts/workflow/impl-plan-template.txt`
- **Details**: See action-planning-agent.md § Implementation Plan Creation
**Note**: Content loading is **dynamic** based on actual files in session, not a fixed template
#### 3. TODO_LIST.md
- **Location**: `.workflow/active//{session-id}/TODO_LIST.md`
- **Format**: Hierarchical task list with status indicators (▸, [ ], [x]) and JSON links
- **Details**: See action-planning-agent.md § TODO List Generation
## 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
### Agent Execution Summary
2. **Implementation Plan** (IMPL_PLAN.md)
- Context analysis and artifact references
- Task breakdown and execution strategy
- Complete structure per agent definition
**Key Steps** (Detailed instructions in action-planning-agent.md):
1. Load task JSON template from provided path
2. Extract and decompose tasks with quantification
3. Generate task JSON files enforcing quantification requirements
4. Create IMPL_PLAN.md using template
5. Generate TODO_LIST.md matching task JSONs
6. Update session state
3. **TODO List** (TODO_LIST.md)
- Hierarchical structure with status indicators (▸, [ ], [x])
- Links to task JSONs and summaries
- Matches task JSON hierarchy
**Quality Gates** (Full checklist in action-planning-agent.md):
- ✓ Quantification requirements enforced (explicit counts, measurable acceptance, exact targets)
- ✓ Task count ≤10 (hard limit)
- ✓ Artifact references mapped correctly
- ✓ MCP tool integration added
- ✓ Documents follow template structure
## Quality Standards
- Task count ≤12 (hard limit)
- All requirements quantified (explicit counts and lists)
- Acceptance criteria measurable (verification commands)
- Artifact references mapped from context package
- All documents follow agent-defined structure
## Output
Generate all three documents and report completion status:
- Task JSON files created: N files
- Artifacts integrated: synthesis-spec, guidance-specification, N role analyses
## Success Criteria
- All task JSONs valid and saved to .task/ directory
- IMPL_PLAN.md created with complete structure
- TODO_LIST.md generated matching task JSONs
- Return completion status with file count
`
)
```
### Agent Context Passing
**Memory-Aware Context Assembly**:
```javascript
// Assemble context package for agent
const agentContext = {
session_id: "WFS-[id]",
// Use memory if available, else load
session_metadata: memory.has("workflow-session.json")
? memory.get("workflow-session.json")
: Read(.workflow/active/WFS-[id]/workflow-session.json),
context_package_path: ".workflow/active/WFS-[id]/.process/context-package.json",
context_package: memory.has("context-package.json")
? memory.get("context-package.json")
: Read(".workflow/active/WFS-[id]/.process/context-package.json"),
// Extract brainstorm artifacts from context package
brainstorm_artifacts: extractBrainstormArtifacts(context_package),
// Load role analyses using paths from context package
role_analyses: brainstorm_artifacts.role_analyses
.flatMap(role => role.files)
.map(file => Read(file.path)),
// Load conflict resolution if exists (from context package)
conflict_resolution: brainstorm_artifacts.conflict_resolution?.exists
? Read(brainstorm_artifacts.conflict_resolution.path)
: null,
// Optional MCP enhancements
mcp_analysis: executeMcpDiscovery()
}
```
**Key Changes from Previous Version**:
1. **Paths over Content**: Provide file paths for agent to read, not embedded content
2. **MANDATORY FIRST STEPS**: Explicit requirement to load session metadata and context package
3. **Complete Session Paths**: All file paths provided for agent operations
4. **Emphasized Deliverables**: Clear deliverable requirements with quality standards
5. **No Agent Self-Reference**: Removed "Refer to action-planning-agent.md" (agent knows its own definition)
6. **No Template Paths**: Removed all template references (agent has complete schema/structure definitions)

View File

@@ -32,9 +32,9 @@ Comprehensive command guide for Claude DMS3 workflow system covering 75 commands
- Creates feature-specific SKILL packages for code understanding
- Progressive loading (2K → 30K tokens) for efficient context management
### Agent Enhancements
### Agent
- **cli-explore-agent** (New) - Specialized code exploration with Deep Scan mode (Bash + Gemini)
- **cli-explore-agent** - Specialized code exploration with Deep Scan mode (Bash + Gemini)
- **cli-planning-agent** - Enhanced task generation with improved context handling
- **ui-design-agent** - Major refactoring for better design system extraction

View File

@@ -417,52 +417,6 @@ Convert user input to TDD-structured format:
- **Command failure**: Keep phase in_progress, report error
- **TDD validation failure**: Report incomplete chains or wrong dependencies
## TDD Workflow Enhancements
### Overview
The TDD workflow has been significantly enhanced by integrating best practices from both traditional `plan --agent` and `test-gen` workflows, creating a hybrid approach that bridges the gap between idealized TDD and real-world development complexity.
### Key Improvements
#### 1. Test Coverage Analysis (Phase 3)
**Adopted from test-gen workflow**
Before planning TDD tasks, the workflow now analyzes the existing codebase:
- Detects existing test patterns and conventions
- Identifies current test coverage
- Discovers related components and integration points
- Detects test framework automatically
**Benefits**:
- Context-aware TDD planning
- Avoids duplicate test creation
- Enables integration with existing tests
- No longer assumes greenfield scenarios
#### 2. Iterative Green Phase with Test-Fix Cycle
**Adopted from test-gen workflow**
IMPL (Green phase) tasks now include automatic test-fix cycle for resilient implementation:
**Enhanced IMPL Task Flow**:
```
1. Write minimal implementation code
2. Execute test suite
3. IF tests pass → Complete task
4. IF tests fail → Enter fix cycle:
a. Gemini diagnoses with bug-fix template
b. Apply fix (manual or Codex)
c. Retest
d. Repeat (max 3 iterations)
5. IF max iterations → Auto-revert changes 🔄
```
**Benefits**:
- Faster feedback within Green phase
- Autonomous recovery from implementation errors
- Systematic debugging with Gemini
- Safe rollback prevents broken state
#### 3. Agent-Driven Planning
**From plan --agent workflow**