Refactor workflow plan command and architecture documentation

- Simplified argument hints and examples in plan.md
- Enhanced input detection logic for files, issues, and text
- Introduced analysis levels for improved context analysis
- Updated core rules for task limits and decomposition strategies
- Improved session management with active session marker system
- Expanded file structure reference and naming conventions
- Clarified task hierarchy and status rules
- Added detailed validation and error handling procedures
- Streamlined document templates for implementation plans and task summaries
This commit is contained in:
catlog22
2025-09-15 22:11:31 +08:00
parent 9371af8d8d
commit 6570af264d
3 changed files with 515 additions and 733 deletions

View File

@@ -7,69 +7,46 @@ examples:
- /workflow:execute - /workflow:execute
--- ---
# Workflow Execute Command (/workflow:execute) # Workflow Execute Command
## Overview ## Overview
Coordinates multiple agents for executing existing workflow tasks through automatic discovery and intelligent task orchestration. Analyzes workflow folders, checks task statuses, and coordinates agent execution based on discovered plans. Coordinates agents for executing workflow tasks through automatic discovery and orchestration. Discovers plans, checks statuses, and executes ready tasks with complete context.
## Core Principles
## Execution Philosophy ## Execution Philosophy
- **Discovery-first**: Auto-discover existing plans and tasks
- **Status-aware**: Execute only ready tasks
- **Context-rich**: Use complete task JSON data for agents
- **Progress tracking**: Update status after completion
The intelligent execution approach focuses on: ## Flow Control Execution
- **Discovery-first execution** - Automatically discover existing plans and tasks **[FLOW_CONTROL]** marker indicates sequential step execution required:
- **Status-aware coordination** - Execute only tasks that are ready - **Auto-trigger**: When `task.flow_control.pre_analysis` exists
- **Context-rich agent assignment** - Use complete task JSON data for agent context - **Process**: Execute steps sequentially BEFORE implementation
- **Dynamic task orchestration** - Coordinate based on discovered task relationships - Load dependency summaries and parent context
- **Progress tracking** - Update task status after agent completion - Execute CLI tools, scripts, and commands as specified
- Pass context between steps via `${variable_name}`
**Flow Control Execution**: - Handle errors per step strategy
- **[FLOW_CONTROL]**: Indicates sequential flow control execution required
- **Auto-trigger**: When task.flow_control.pre_analysis is an array (default format)
- **Agent Action**: Execute flow control steps sequentially BEFORE implementation begins
- Process each step with command execution and context accumulation
- Load dependency summaries and parent task context
- Execute CLI tools, scripts, and agent commands as specified
- Pass context between steps via named variables
- Handle errors according to per-step error strategies
**Flow Control Step Processing**:
- **Sequential Execution**: Steps processed in order with context flow
- Each step can use outputs from previous steps via ${variable_name}
- Dependency summaries loaded automatically from .summaries/
- Context accumulates through the execution chain
- Error handling per step (skip_optional, fail, retry_once, manual_intervention)
## Execution Flow ## Execution Flow
### 1. Discovery & Analysis Phase ### 1. Discovery Phase
``` ```
Workflow Discovery: ├── Locate workflow folder (current session)
├── Locate workflow folder (provided or current session) ├── Load workflow-session.json and IMPL_PLAN.md
├── Load workflow-session.json for session state ├── Scan .task/ directory for task JSON files
├── Scan .task/ directory for all task JSON files
├── Read IMPL_PLAN.md for workflow context
├── Analyze task statuses and dependencies ├── Analyze task statuses and dependencies
└── Determine executable tasks └── Build execution queue of ready tasks
``` ```
**Discovery Logic:** ### 2. TodoWrite Coordination
- **Folder Detection**: Use provided folder or find current active session Create comprehensive TodoWrite based on discovered tasks:
- **Task Inventory**: Load all IMPL-*.json files from .task/ directory
- **Status Analysis**: Check pending/active/completed/blocked states
- **Dependency Check**: Verify all task dependencies are met
- **Execution Queue**: Build list of ready-to-execute tasks
### 2. TodoWrite Coordination Setup
**Always First**: Create comprehensive TodoWrite based on discovered tasks
```markdown ```markdown
# Workflow Execute Coordination # Workflow Execute Coordination
*Session: WFS-[topic-slug]* *Session: WFS-[topic-slug]*
## Execution Plan - [ ] **TASK-001**: [Agent: code-developer] [FLOW_CONTROL] Design auth schema (IMPL-1.1)
- [ ] **TASK-001**: [Agent: planning-agent] [FLOW_CONTROL] Design auth schema (IMPL-1.1) - [ ] **TASK-002**: [Agent: code-developer] [FLOW_CONTROL] Implement auth logic (IMPL-1.2)
- [ ] **TASK-002**: [Agent: code-developer] [FLOW_CONTROL] Implement auth logic (IMPL-1.2)
- [ ] **TASK-003**: [Agent: code-review-agent] Review implementations - [ ] **TASK-003**: [Agent: code-review-agent] Review implementations
- [ ] **TASK-004**: Update task statuses and session state - [ ] **TASK-004**: Update task statuses and session state
@@ -78,84 +55,45 @@ Workflow Discovery:
``` ```
### 3. Agent Context Assignment ### 3. Agent Context Assignment
For each executable task:
**Task JSON Structure**:
```json ```json
{ {
"task": { "id": "IMPL-1.1",
"id": "IMPL-1.1", "title": "Design auth schema",
"title": "Design auth schema", "status": "pending",
"status": "pending", "meta": { "type": "feature", "agent": "code-developer" },
"context": {
"meta": { "requirements": ["JWT authentication", "User model design"],
"type": "feature", "focus_paths": ["src/auth/models", "tests/auth"],
"agent": "code-developer" "acceptance": ["Schema validates JWT tokens"],
}, "depends_on": [],
"inherited": { "from": "IMPL-1", "context": ["..."] }
"context": {
"requirements": ["JWT authentication", "User model design"],
"focus_paths": ["src/auth/models", "tests/auth"],
"acceptance": ["Schema validates JWT tokens"],
"parent": "IMPL-1",
"depends_on": [],
"inherited": {
"from": "IMPL-1",
"context": ["Authentication system architecture completed"]
},
"shared_context": {
"auth_strategy": "JWT with refresh tokens"
}
},
"flow_control": {
"pre_analysis": [
{
"step": "gather_context",
"action": "Load dependency summaries",
"command": "bash(echo 'No dependencies for this initial task')",
"output_to": "dependency_context",
"on_error": "skip_optional"
},
{
"step": "analyze_patterns",
"action": "Analyze existing auth patterns",
"command": "bash(~/.claude/scripts/gemini-wrapper -p '@{src/auth/**/*} analyze authentication patterns with context: [dependency_context]')",
"output_to": "pattern_analysis",
"on_error": "fail"
},
{
"step": "implement",
"action": "Design JWT schema based on analysis",
"command": "bash(codex --full-auto exec 'Design JWT schema using analysis: [pattern_analysis] and context: [dependency_context]')",
"on_error": "manual_intervention"
}
],
"implementation_approach": "Design flexible user schema supporting JWT and OAuth authentication",
"target_files": [
"src/auth/models/User.ts:UserSchema:10-50"
]
}
}, },
"workflow": { "flow_control": {
"session": "WFS-user-auth", "pre_analysis": [
"phase": "IMPLEMENT", {
"plan_context": "Authentication system with OAuth2 support" "step": "analyze_patterns",
"action": "Analyze existing auth patterns",
"command": "~/.claude/scripts/gemini-wrapper -p '@{src/auth/**/*} analyze patterns'",
"output_to": "pattern_analysis",
"on_error": "fail"
}
],
"implementation_approach": "Design flexible user schema",
"target_files": ["src/auth/models/User.ts:UserSchema:10-50"]
} }
} }
``` ```
**Context Assignment Rules:** **Context Assignment Rules**:
- **Complete Context**: Use full task JSON context including flow_control field for agent execution - Use complete task JSON including flow_control
- **Flow Control Processing**: Execute flow_control.pre_analysis steps sequentially with context accumulation - Load dependency summaries from context.depends_on
- **Dependency Integration**: Load summaries from context.depends_on automatically - Execute flow_control.pre_analysis steps sequentially
- **Mandatory Dependency Reading**: For tasks with dependencies, MUST read previous task summary documents - Direct agents to context.focus_paths
- **Context Inheritance**: Use dependency summaries to maintain consistency and include context.inherited data from parent tasks - Auto-add [FLOW_CONTROL] marker when pre_analysis exists
- **Workflow Integration**: Include session state and IMPL_PLAN.md context
- **Focus Scope**: Direct agents to specific paths from context.focus_paths array
- **Flow Control Marker**: Auto-add [FLOW_CONTROL] when flow_control.pre_analysis exists
- **Target File Guidance**: Use flow_control.target_files for precise file targeting
### 4. Agent Execution & Progress Tracking ### 4. Agent Execution Pattern
```bash ```bash
Task(subagent_type="code-developer", Task(subagent_type="code-developer",
@@ -198,182 +136,83 @@ Task(subagent_type="code-developer",
description="Execute task with flow control step processing") description="Execute task with flow control step processing")
``` ```
**Execution Protocol:** **Execution Protocol**:
- **Sequential Execution**: Respect task dependencies and execution order - Sequential execution respecting dependencies
- **Progress Monitoring**: Track through TodoWrite updates - Progress tracking through TodoWrite updates
- **Status Updates**: Update task JSON status after each completion - Status updates after completion
- **Cross-Agent Handoffs**: Coordinate results between related tasks - Cross-agent result coordination
## Discovery & Analysis Process ## File Structure & Analysis
### File Structure Analysis ### Workflow Structure
``` ```
.workflow/WFS-[topic-slug]/ .workflow/WFS-[topic-slug]/
├── workflow-session.json # Session state and stats ├── workflow-session.json # Session state
├── IMPL_PLAN.md # Workflow context and requirements ├── IMPL_PLAN.md # Requirements
├── .task/ # Task definitions ├── .task/ # Task definitions
│ ├── IMPL-1.json # Main tasks │ ├── IMPL-1.json
── IMPL-1.1.json # Subtasks ── IMPL-1.1.json
│ └── IMPL-1.2.json # Detailed tasks └── .summaries/ # Completion summaries
└── .summaries/ # Completed task summaries
``` ```
### Task Status Assessment ### Task Status Logic
```pseudo ```
function analyze_tasks(task_files): pending + dependencies_met → executable
executable_tasks = [] completed → skip
blocked → skip until dependencies clear
for task in task_files:
if task.status == "pending" and dependencies_met(task):
if task.subtasks.length == 0: // leaf task
executable_tasks.append(task)
else: // container task - check subtasks
if all_subtasks_ready(task):
executable_tasks.extend(task.subtasks)
return executable_tasks
``` ```
### Automatic Agent Assignment ### Agent Assignment
Based on discovered task data: - **task.agent field**: Use specified agent
- **task.agent field**: Use specified agent from task JSON - **task.type fallback**:
- **task.type analysis**:
- "feature" → code-developer - "feature" → code-developer
- "test" → code-review-test-agent - "test" → code-review-test-agent
- "docs" → code-developer
- "review" → code-review-agent - "review" → code-review-agent
- **Gemini context**: Auto-assign based on task.context.scope and requirements
## Agent Task Assignment Patterns ## Status Management & Coordination
### Discovery-Based Assignment
```bash
# Agent receives complete discovered context with saturation handling
Task(subagent_type="code-developer",
prompt="[FLOW_CONTROL] Execute IMPL-1.2: Analyze and implement auth logic
TASK TYPE: Saturated task (preparation_complexity: simple)
PREPARATION PHASE:
- Review existing auth patterns and conventions
- Check JWT library compatibility
- Analyze current session management
EXECUTION PHASE:
Implement JWT authentication based on preparation findings
Context from discovery:
- Requirements: JWT authentication, OAuth2 support
- Scope: src/auth/*, tests/auth/*
- Dependencies: IMPL-1.1 (completed)
- Workflow: WFS-user-auth authentication system
Session Context:
- Workflow Directory: .workflow/WFS-user-auth/
- TODO_LIST Location: .workflow/WFS-user-auth/TODO_LIST.md
- Summaries Directory: .workflow/WFS-user-auth/.summaries/
- Task JSON: .workflow/WFS-user-auth/.task/IMPL-1.2.json
Focus Paths: $(~/.claude/scripts/read-task-paths.sh .workflow/WFS-user-auth/.task/IMPL-1.2.json)
Analysis Command: Use ~/.claude/scripts/gemini-wrapper -p \"$(~/.claude/scripts/read-task-paths.sh .workflow/WFS-user-auth/.task/IMPL-1.2.json) @{CLAUDE.md}\"
CRITICAL:
1. Execute preparation phase first, then use findings for implementation
2. Use task-specific paths for focused analysis
3. Document both phases in completion summary
4. Update TODO_LIST.md and create completion summary using provided paths.",
description="Agent executes saturated task with preparation and implementation phases")
```
### Status Tracking Integration
```bash
# After agent completion, update discovered task status
update_task_status("IMPL-1.2", "completed")
mark_dependent_tasks_ready(task_dependencies)
```
## Coordination Strategies
### Automatic Coordination
- **Task Dependencies**: Execute in dependency order from discovered relationships
- **Agent Handoffs**: Pass results between agents based on task hierarchy
- **Progress Updates**: Update TodoWrite and JSON files after each completion
### Context Distribution
- **Rich Context**: Each agent gets complete task JSON + workflow context
- **Focus Areas**: Direct agents to specific files from task.context.scope
- **Inheritance**: Subtasks inherit parent context automatically
- **Session Integration**: Include workflow-session.json state in agent context
## Status Management
### Task Status Updates ### Task Status Updates
```json ```json
// Before execution // Before execution
{ { "id": "IMPL-1.2", "status": "pending", "execution": { "attempts": 0 } }
"id": "IMPL-1.2",
"status": "pending",
"execution": {
"attempts": 0,
"last_attempt": null
}
}
// After execution // After execution
{ { "id": "IMPL-1.2", "status": "completed", "execution": { "attempts": 1, "last_attempt": "2025-09-08T14:30:00Z" } }
"id": "IMPL-1.2",
"status": "completed",
"execution": {
"attempts": 1,
"last_attempt": "2025-09-08T14:30:00Z"
}
}
``` ```
### Session State Updates ### Coordination Strategies
```json - **Dependencies**: Execute in dependency order
{ - **Agent Handoffs**: Pass results between agents
"current_phase": "EXECUTE", - **Progress Updates**: Update TodoWrite and JSON files
"last_execute_run": "2025-09-08T14:30:00Z" - **Context Distribution**: Complete task JSON + workflow context
} - **Focus Areas**: Direct agents to specific paths from task.context.focus_paths
```
## Error Handling & Recovery ## Error Handling
### Discovery Issues ### Discovery Issues
```bash ```bash
# No active session found No active workflow session → Use: /workflow:session:start "project"
❌ No active workflow session found ⚠️ All tasks completed/blocked → Check: /context for status
→ Use: /workflow:session:start "project name" first ❌ Missing task files → Fix: /task/create or repair references
# No executable tasks
⚠️ All tasks completed or blocked
→ Check: /context for task status overview
# Missing task files
❌ Task IMPL-1.2 referenced but JSON file missing
→ Fix: /task/create or repair task references
``` ```
### Execution Recovery ### Execution Recovery
- **Failed Agent**: Retry with adjusted context or different agent - **Failed Agent**: Retry with adjusted context
- **Blocked Dependencies**: Skip and continue with available tasks - **Blocked Dependencies**: Skip and continue with available tasks
- **Context Issues**: Reload from JSON files and session state - **Context Issues**: Reload from JSON files and session state
## Integration Points ## Integration & Next Steps
### Automatic Behaviors ### Automatic Behaviors
- **Discovery on start** - Analyze workflow folder structure - Discovery on start - analyze workflow folder structure
- **TodoWrite coordination** - Generate based on discovered tasks - TodoWrite coordination - generate based on discovered tasks
- **Agent context preparation** - Use complete task JSON data - Agent context preparation - use complete task JSON data
- **Status synchronization** - Update JSON files after completion - Status synchronization - update JSON files after completion
### Next Actions ### Next Actions
```bash ```bash
# After /workflow:execute completion
/context # View updated task status /context # View updated task status
/task:execute IMPL-X # Execute specific remaining tasks /task:execute IMPL-X # Execute specific remaining tasks
/workflow:review # Move to review phase when complete /workflow:review # Move to review phase when complete
``` ```

View File

@@ -2,303 +2,116 @@
name: plan name: plan
description: Create implementation plans with intelligent input detection description: Create implementation plans with intelligent input detection
usage: /workflow:plan <input> usage: /workflow:plan <input>
argument-hint: "text description"|file.md|ISS-001|template-name argument-hint: "text description"|file.md|ISS-001
examples: examples:
- /workflow:plan "Build authentication system" - /workflow:plan "Build authentication system"
- /workflow:plan requirements.md - /workflow:plan requirements.md
- /workflow:plan ISS-001 - /workflow:plan ISS-001
--- ---
# Workflow Plan Command (/workflow:plan) # Workflow Plan Command
## Overview
Creates actionable implementation plans with intelligent input source detection. Supports text, files, issues, and templates through automatic recognition.
## Core Principles
**File Structure:** @~/.claude/workflows/workflow-architecture.md
**Dependency Context Rules:**
- **For tasks with dependencies**: MUST read previous task summary documents before planning
- **Context inheritance**: Use dependency summaries to maintain consistency and avoid duplicate work
## Usage ## Usage
```bash ```bash
/workflow:plan [--AM gemini|codex] <input> /workflow:plan [--AM gemini|codex] [--analyze|--deep] <input>
``` ```
### Analysis Method Flag (--AM) ## Input Detection
Optional flag to specify which CLI tool to use for context analysis: - **Files**: `.md/.txt/.json/.yaml/.yml` → Reads content and extracts requirements
- **gemini** (default): Uses Gemini CLI for pattern-based analysis, architectural understanding, and broader context acquisition - **Issues**: `ISS-*`, `ISSUE-*`, `*-request-*` → Loads issue data and acceptance criteria
- **codex**: Uses Codex CLI for autonomous development context gathering with intelligent file discovery - **Text**: Everything else → Parses natural language requirements
**Examples**: ## Analysis Levels
```bash - **Quick** (default): Structure only (5s)
/workflow:plan --AM codex "Build authentication system" - **--analyze**: Structure + context analysis (30s)
/workflow:plan --AM gemini requirements.md - **--deep**: Structure + comprehensive parallel analysis (1-2m)
```
## Input Detection Logic ## Core Rules
The command automatically detects input type:
### File Input (Auto-detected) ### File Structure Reference
```bash **Architecture**: @~/.claude/workflows/workflow-architecture.md
/workflow:plan requirements.md
/workflow:plan config.json
```
**Triggers**: Extensions: .md, .txt, .json, .yaml, .yml
**Processing**: Reads file contents and extracts requirements
### Issue Input (Auto-detected) ### Task Limits & Decomposition
```bash - **Maximum 10 tasks**: Hard enforced limit - projects exceeding must be re-scoped
/workflow:plan ISS-001 - **Function-based decomposition**: By complete functional units, not files/steps
/workflow:plan ISSUE-123 - **File cohesion**: Group related files (UI + logic + tests + config) in same task
``` - **Task saturation**: Merge "analyze + implement" by default (0.5 count for complex prep tasks)
**Triggers**: Patterns: ISS-*, ISSUE-*, *-request-*
**Processing**: Loads issue data and acceptance criteria
### Pre-Planning Analysis (CRITICAL)
### Text Input (Default) ⚠️ **Must complete BEFORE generating any plan documents**
```bash 1. **Complexity assessment**: Count total saturated tasks
/workflow:plan "Build user authentication with JWT and OAuth2" 2. **Decomposition strategy**: Flat (≤5) | Hierarchical (6-10) | Re-scope (>10)
``` 3. **File grouping**: Identify cohesive file sets
**Triggers**: Everything else 4. **Quantity prediction**: Estimate main tasks, subtasks, container vs leaf ratio
**Processing**: Parse natural language requirements
## Automatic Behaviors
### Session Management ### Session Management
- Creates new session if none exists - **Active session check**: Check for `.workflow/.active-*` marker first
- Uses active session if available - Auto-creates new session: `WFS-[topic-slug]`
- Generates session ID: WFS-[topic-slug] - Uses existing active session if available
- **Dependency context**: MUST read previous task summary documents before planning
### Pre-Planning Analysis ## Task Patterns
⚠️ **CRITICAL**: Determine decomposition strategy BEFORE generating any plan documents
**Required Pre-Analysis Steps**: ### ✅ Correct (Function-based)
1. **Complexity Assessment**: Analyze requirements to determine total saturated task count - `IMPL-001: User authentication system` (models + routes + components + middleware + tests)
2. **Decomposition Strategy**: Based on complexity, decide: - `IMPL-002: Data export functionality` (service + routes + UI + utils + tests)
- Task structure (flat vs hierarchical)
- Re-scoping necessity (>10 tasks triggers re-scoping)
- Task saturation level (merged vs separated)
- File grouping strategy (cohesive files together)
3. **Quantity Prediction**: Calculate expected:
- Total main tasks (IMPL-XXX)
- Subtasks per main task (IMPL-N.M)
- Container vs leaf task ratio
**Pre-Planning Outputs**: ### ❌ Wrong (File/step-based)
- Complexity level: Simple (≤5) | Medium (6-10) | Over-scoped (>10, requires re-scoping) - `IMPL-001: Create database model`
- Decomposition approach: Flat | Two-level hierarchy | Re-scope required - `IMPL-002: Create API endpoint`
- Estimated task count: [number] main tasks, [number] total leaf tasks (max 10) - `IMPL-003: Create frontend component`
- Document set: Which documents will be generated (IMPL_PLAN.md, TODO_LIST.md, .task/*.json)
- **Re-scoping recommendation**: If >10 tasks, provide guidance for breaking into iterations
**Only after completing pre-planning analysis**: Proceed to generate actual plan documents
### Complexity Detection with Saturation
*Based on Pre-Planning Analysis results:*
- **Simple**: ≤5 saturated tasks → Direct IMPL_PLAN.md
- **Medium**: 6-10 saturated tasks → IMPL_PLAN.md + TODO_LIST.md
- **Complex**: Exceeding 10 tasks requires re-scoping (maximum enforced)
**10-Task Hard Limit**: Projects exceeding 10 tasks must be re-scoped into smaller iterations
**Note**: 1 complex preparation task = 0.5 saturated task for counting
### Task Granularity Principles
- **Decompose by function, not by file**: Each task should complete a whole functional unit
- **Maintain functional integrity**: Each task produces independently runnable or testable functionality
- **Group related files together**: Keep related files (UI, logic, tests, config) in same task
- **File cohesion rule**: Files that work together should be modified in the same task
- **Avoid technical step decomposition**: Don't make "create file" or "add function" as separate tasks
- **Maximum 10 tasks**: Hard limit enforced; re-scope if exceeded
### Task Decomposition Anti-patterns
**Wrong Example - File/Step-based Decomposition**:
- IMPL-001: Create database model
- IMPL-002: Create API endpoint
- IMPL-003: Create frontend component
- IMPL-004: Add routing configuration
- IMPL-005: Write unit tests
**Wrong Example - Same File Split Across Tasks**:
- IMPL-001: Add authentication routes to routes/auth.js
- IMPL-002: Add user validation to routes/auth.js
- IMPL-003: Add session handling to routes/auth.js
**Correct Example - Function-based with File Cohesion**:
- IMPL-001: Implement user authentication (includes models/User.js, routes/auth.js, components/LoginForm.jsx, middleware/auth.js, tests/auth.test.js)
- IMPL-002: Implement data export functionality (includes services/export.js, routes/export.js, components/ExportButton.jsx, utils/fileGenerator.js, tests/export.test.js)
**Correct Example - Related Files Grouped**:
- IMPL-001: User management system (includes User model, UserController, UserService, user routes, user tests)
- IMPL-002: Product catalog system (includes Product model, ProductController, catalog components, product tests)
### Task Generation with Saturation Control
*Using decomposition strategy determined in Pre-Planning Analysis:*
- **Task Saturation Assessment**: Evaluates whether to merge preparation and execution
- **Default merge mode**: "Analyze and implement X" instead of "Analyze X" + "Implement X"
- **Smart splitting**: Only separate when preparation complexity > threshold
- Automatically creates .task/ files when complexity warrants
- Generates hierarchical task structure (max 2 levels)
- Main tasks with subtasks become container tasks (not directly executable)
- Updates session state with task references
- Runs project structure analysis to populate paths field
### Project Analysis Options
Three analysis levels available:
```bash
# Quick - Structure only (5 seconds)
/workflow:plan "requirements"
# Standard - Structure + Gemini analysis (30 seconds)
/workflow:plan --analyze "requirements"
# Deep - Structure + Parallel comprehensive analysis (1-2 minutes)
/workflow:plan --deep "requirements"
```
**Analysis Selection**:
- Default: Auto-selects based on project complexity
- Manual: Use flags to override automatic selection
- Strategy: See @~/.claude/workflows/intelligent-tools-strategy.md for tool selection principles
**Execution**:
1. Always runs `get_modules_by_depth.sh` for structure
2. Applies selected analysis level
3. Populates task paths automatically
### Task Saturation Assessment
Evaluates whether to merge preparation and execution within 10-task limit:
**Default Merge Principles** (Saturated Tasks):
- All components of the same functional module
- Related files that work together (UI, logic, tests, config)
- Features with their corresponding tests and documentation
- Configuration with its usage code
- Multiple small interdependent functions
- Files that share common interfaces or data structures
**Only Separate Tasks When**:
- Completely independent functional modules (no shared code or interfaces)
- Independent services with different tech stacks (e.g., separate deployment units)
- Modules requiring different expertise (e.g., ML model training vs Web development)
- Large features with clear sequential dependencies
- **Critical**: Would exceed 10-task limit otherwise
**File Cohesion Examples**:
- **Merged**: "IMPL-001: Implement user authentication (includes models/User.js, routes/auth.js, components/LoginForm.jsx, tests/auth.test.js)"
- **Separated**: "IMPL-001: User service authentication" + "IMPL-002: Admin dashboard authentication" (different user contexts)
**10-Task Compliance**: Always prioritize related file grouping to stay within limit
### Task Breakdown Process
- **Automatic decomposition**: Only when task count >10 triggers re-scoping (not decomposition)
- **Function-based decomposition**: Split by independent functional boundaries, not by technical layers
- **Container tasks**: Parent tasks with subtasks become containers (marked with ▸ in TODO_LIST)
- **Smart decomposition**: AI analyzes task title to suggest logical functional subtask structure
- **Complete unit principle**: Each subtask must still represent a complete functional unit
- **Context inheritance**: Subtasks inherit parent's requirements and scope, refined for specific needs
- **Agent assignment**: Automatic agent mapping based on subtask type (planning/code/test/review)
- **Maximum depth**: 2 levels (IMPL-N.M) to maintain manageable hierarchy
- **10-task enforcement**: Exceeding 10 tasks requires project re-scoping
### Flow Control Field Requirements
- **flow_control**: Universal process manager containing:
- `pre_analysis`: Array of sequential process steps with:
- `step`: Unique identifier for the step
- `action`: Human-readable description
- `command`: Executable command with embedded context variables (e.g., `${variable_name}`)
- `output_to`: Variable name to store step results (optional for final steps)
- `on_error`: Error handling strategy
- `implementation_approach`: Brief one-line strategy description
- `target_files`: Array of "file:function:lines" format strings
- **Auto-generation**: Creates flow based on task type and complexity
- **Required fields**: meta (type, agent), context (requirements, focus_paths, acceptance, depends_on), flow_control
- **Focus paths format**: Array of strings (e.g., ["src/auth", "tests/auth", "config/auth.json"])
## Session Check Process
⚠️ **CRITICAL**: Check for existing active session before planning
1. **Check Active Session**: Check for `.workflow/.active-*` marker file
2. **Session Selection**: Use existing active session or create new
3. **Context Integration**: Load session state and existing context
## Output Documents ## Output Documents
### Document References for Execution ### Always Created
- **IMPL_PLAN.md**: Requirements, task breakdown, success criteria
- **Session state**: Task references and paths
#### Primary References ### Auto-Created (complexity > simple)
- **Planning Document**: `.workflow/WFS-[topic-slug]/IMPL_PLAN.md` - **TODO_LIST.md**: Hierarchical progress tracking
- Used by: `/workflow:execute` for context loading - **.task/*.json**: Individual task definitions with flow_control
- Contains: Requirements, task overview, success criteria
- **Task Definitions**: `.workflow/WFS-[topic-slug]/.task/IMPL-*.json` ### Document Structure
- Used by: Agents for implementation context ```
- Contains: Complete task details with 7-field structure including flow_control process manager .workflow/WFS-[topic]/
├── IMPL_PLAN.md # Main planning document
- **Progress Tracking**: `.workflow/WFS-[topic-slug]/TODO_LIST.md` ├── TODO_LIST.md # Progress tracking (if complex)
- Used by: `/workflow:execute` for status tracking └── .task/
- Updated by: Agents after task completion ├── IMPL-001.json # Task definitions
└── IMPL-002.json
### IMPL_PLAN.md (Always Created)
```markdown
# Implementation Plan - [Project Name]
*Generated from: [input_source]*
## Requirements
[Extracted requirements from input source]
## Task Breakdown
- **IMPL-001**: [Saturated task description with merged preparation and execution]
- **IMPL-002**: [Task description]
## Success Criteria
[Measurable completion conditions]
``` ```
### Optional TODO_LIST.md (Auto-triggered) ## Task Saturation Assessment
Created when complexity > simple or task count > 3 **Default Merge** (cohesive files together):
- Functional modules with UI + logic + tests + config
- Features with their tests and documentation
- Files sharing common interfaces/data structures
**TODO_LIST Structure**: Uses unified hierarchical list format **Only Separate When**:
- Container tasks (with subtasks) marked with `▸` symbol - Completely independent functional modules
- Leaf tasks use standard `- [ ]` / `- [x]` checkboxes - Different tech stacks or deployment units
- Indentation shows hierarchy (2 spaces per level) - Would exceed 10-task limit otherwise
- Container tasks represent logical grouping, not executable items
### Task JSON Files (Auto-created) ## Flow Control Schema
Generated in .task/ directory when decomposition enabled Each task.json includes required fields:
- **meta**: type, agent assignment
- **context**: requirements, focus_paths, acceptance, depends_on
- **flow_control**:
- `pre_analysis`: Steps with commands and context variables (${var})
- `implementation_approach`: One-line strategy
- `target_files`: "file:function:lines" format
## Execution Integration
Documents created for `/workflow:execute`:
- **IMPL_PLAN.md**: Context loading and requirements
- **.task/*.json**: Agent implementation context
- **TODO_LIST.md**: Status tracking (container tasks with ▸, leaf tasks with checkboxes)
## Error Handling ## Error Handling
- **Vague input**: Auto-reject ("fix it", "make better", etc.)
- **File not found**: Clear suggestions
- **>10 tasks**: Force re-scoping into iterations
### Input Processing Errors ## Analysis Method (--AM)
- **File not found**: Clear error message with suggestions - **gemini** (default): Pattern analysis, architectural understanding
- **Invalid issue**: Verify issue ID exists - **codex**: Autonomous development, intelligent file discovery
- **Unknown template**: List available templates
- **Empty input**: Prompt for valid input
- **Vague text input**: Auto-reject without guidance
- Rejected examples: "do something", "fix it", "make it better", "add feature"
- Response: Direct rejection message, no further assistance
### Recommended Task Patterns
#### Complete Feature Implementation
"Implement user management system" - includes all related files: models/User.js, controllers/UserController.js, routes/users.js, components/UserList.jsx, services/UserService.js, tests/user.test.js
#### End-to-End Features
"Add Excel export functionality" - includes cohesive file set: services/ExportService.js, utils/excelGenerator.js, routes/export.js, components/ExportButton.jsx, middleware/downloadHandler.js, tests/export.test.js
#### System Integration
"Integrate payment gateway" - includes integration files: services/PaymentService.js, controllers/PaymentController.js, models/Payment.js, components/PaymentForm.jsx, webhooks/paymentWebhook.js, tests/payment.test.js
#### Problem Resolution
"Fix and optimize search functionality" - includes related files: services/SearchService.js, utils/searchOptimizer.js, components/SearchBar.jsx, controllers/SearchController.js, tests/search.test.js
#### Module Development
"Create notification system" - includes module files: services/NotificationService.js, models/Notification.js, templates/emailTemplates.js, components/NotificationCenter.jsx, workers/notificationQueue.js, tests/notification.test.js
**File Cohesion Principle**: Each task includes ALL files that work together to deliver the complete functionality
**System ensures**: Unified planning interface with intelligent input detection, function-based task granularity, file cohesion enforcement, and 10-task maximum limit

View File

@@ -1,23 +1,77 @@
# Workflow Architecture # Workflow Architecture
## Overview & Core Principles ## Overview
This document defines a streamlined workflow system architecture featuring **JSON-only data model**, **marker-based session management**, and **unified file structure** with dynamic task decomposition. This document defines the complete workflow system architecture using a **JSON-only data model**, **marker-based session management**, and **unified file structure** with dynamic task decomposition.
### Design Philosophy ## Core Architecture Principles
- **JSON-first data model** - JSON files are single source of truth; markdown is generated views
- **Marker-based sessions** - Ultra-simple active session tracking via marker files
- **Unified structure** - Same file template for all workflows, created on-demand
- **Dynamic decomposition** - Tasks break down as needed during execution
- **On-demand creation** - Files and directories created only when required
- **Agent autonomy** - Complete context preserved for independent execution
## Data Architecture ### Key Design Decisions
- **JSON files are the single source of truth** - All markdown documents are read-only generated views
- **Marker files for session tracking** - Ultra-simple active session management
- **Unified file structure definition** - Same structure template for all workflows, created on-demand
- **Dynamic task decomposition** - Subtasks created as needed during execution
- **On-demand file creation** - Directories and files created only when required
- **Agent-agnostic task definitions** - Complete context preserved for autonomous execution
### JSON-Only Data Model ## Session Management
**Core Principle**: JSON files are the authoritative source; markdown documents are read-only generated views.
- **Task State**: Stored exclusively in `.task/IMPL-*.json` files ### Active Session Marker System
**Ultra-Simple Active Tracking**: `.workflow/.active-[session-name]`
```bash
.workflow/
├── WFS-oauth-integration/ # Session directory (paused)
├── WFS-user-profile/ # Session directory (paused)
├── WFS-bug-fix-123/ # Session directory (completed)
└── .active-WFS-user-profile # Marker file (indicates active session)
```
**Marker File Benefits**:
- **Zero Parsing**: File existence check is atomic and instant
- **Atomic Operations**: File creation/deletion is naturally atomic
- **Visual Discovery**: `ls .workflow/.active-*` shows active session immediately
- **Simple Switching**: Delete old marker + create new marker = session switch
### Session Operations
#### Detect Active Session
```bash
active_session=$(find .workflow -name ".active-*" | head -1)
if [ -n "$active_session" ]; then
session_name=$(basename "$active_session" | sed 's/^\.active-//')
echo "Active session: $session_name"
fi
```
#### Switch Session
```bash
find .workflow -name ".active-*" -delete && touch .workflow/.active-WFS-new-feature
```
### Individual Session Tracking
Each session directory contains `workflow-session.json`:
```json
{
"session_id": "WFS-[topic-slug]",
"project": "feature description",
"type": "simple|medium|complex",
"current_phase": "PLAN|IMPLEMENT|REVIEW",
"status": "active|paused|completed",
"progress": {
"completed_phases": ["PLAN"],
"current_tasks": ["IMPL-1", "IMPL-2"]
}
}
```
## Data Model
### JSON-Only Architecture
**JSON files (.task/IMPL-*.json) are the only authoritative source of task state. All markdown documents are read-only generated views.**
- **Task State**: Stored exclusively in JSON files
- **Documents**: Generated on-demand from JSON data - **Documents**: Generated on-demand from JSON data
- **No Synchronization**: Eliminates bidirectional sync complexity - **No Synchronization**: Eliminates bidirectional sync complexity
- **Performance**: Direct JSON access without parsing overhead - **Performance**: Direct JSON access without parsing overhead
@@ -59,12 +113,35 @@ All task files use this simplified 5-field schema:
"command": "bash(cat .workflow/*/summaries/IMPL-1.1-summary.md)", "command": "bash(cat .workflow/*/summaries/IMPL-1.1-summary.md)",
"output_to": "auth_design_context", "output_to": "auth_design_context",
"on_error": "skip_optional" "on_error": "skip_optional"
},
{
"step": "analyze_patterns",
"action": "Analyze existing auth patterns",
"command": "bash(~/.claude/scripts/gemini-wrapper -p '@{src/auth/**/*} analyze authentication patterns using context: [auth_design_context]')",
"output_to": "pattern_analysis",
"on_error": "fail"
},
{
"step": "implement",
"action": "Implement JWT based on analysis",
"command": "bash(codex --full-auto exec 'Implement JWT using analysis: [pattern_analysis] and dependency context: [auth_design_context]')",
"on_error": "manual_intervention"
} }
], ],
"implementation_approach": { "implementation_approach": {
"task_description": "Implement comprehensive JWT authentication system...", "task_description": "Implement comprehensive JWT authentication system with secure token management and validation middleware. Reference [inherited.context] from parent task [parent] for architectural consistency. Apply [shared_context.auth_strategy] across authentication modules. Focus implementation on [focus_paths] directories following established patterns.",
"modification_points": ["Add JWT token generation...", "..."], "modification_points": [
"logic_flow": ["User login request → validate credentials...", "..."] "Add JWT token generation in login handler (src/auth/login.ts:handleLogin:75-120) following [shared_context.auth_strategy]",
"Implement token validation middleware (src/middleware/auth.ts:validateToken) referencing [inherited.context] design patterns",
"Add refresh token mechanism for session management using [shared_context] token strategy",
"Update user authentication flow to support JWT tokens in [focus_paths] modules"
],
"logic_flow": [
"User login request → validate credentials → generate JWT token using [shared_context.auth_strategy] → store refresh token",
"Protected route access → extract JWT from headers → validate token against [inherited.context] schema → allow/deny access",
"Token expiry handling → use refresh token following [shared_context] strategy → generate new JWT → continue session",
"Logout process → invalidate refresh token → clear client-side tokens in [focus_paths] components"
]
}, },
"target_files": [ "target_files": [
"src/auth/login.ts:handleLogin:75-120", "src/auth/login.ts:handleLogin:75-120",
@@ -137,32 +214,45 @@ Each step contains:
- **retry_once**: Retry step once, then fail if still unsuccessful - **retry_once**: Retry step once, then fail if still unsuccessful
- **manual_intervention**: Pause execution for manual review - **manual_intervention**: Pause execution for manual review
#### Example Flow Control Patterns #### Example Flow Control
**Pattern 1: Multi-Step Analysis**
```json ```json
"pre_analysis": [ {
{ "pre_analysis": [
"step": "gather_dependencies", {
"command": "bash(for dep in ${depends_on}; do cat .summaries/$dep-summary.md; done)", "step": "gather_dependencies",
"output_to": "dependency_context" "action": "Load context from completed dependencies",
"command": "bash(for dep in ${depends_on}; do cat .summaries/$dep-summary.md 2>/dev/null || echo \"No summary for $dep\"; done)",
"output_to": "dependency_context",
"on_error": "skip_optional"
},
{
"step": "analyze_codebase",
"action": "Understand current implementation",
"command": "bash(gemini -p '@{[focus_paths]} analyze current patterns using context: [dependency_context]')",
"output_to": "codebase_analysis",
"on_error": "fail"
},
{
"step": "implement",
"action": "Execute implementation based on analysis",
"command": "bash(codex --full-auto exec 'Implement based on: [codebase_analysis] with dependency context: [dependency_context]')",
"on_error": "manual_intervention"
}
],
"implementation_approach": {
"task_description": "Execute implementation following [codebase_analysis] patterns and [dependency_context] requirements",
"modification_points": [
"Update target files in [focus_paths] following established patterns",
"Apply [dependency_context] insights to maintain consistency"
],
"logic_flow": [
"Analyze existing patterns → apply dependency context → implement changes → validate results"
]
}, },
{ "target_files": [
"step": "analyze_codebase", "file:function:lines format for precise targeting"
"command": "bash(gemini -p '@{[focus_paths]} using context: [dependency_context]')", ]
"output_to": "codebase_analysis" }
}
]
```
**Pattern 2: Direct Implementation**
```json
"pre_analysis": [
{
"step": "implement",
"command": "bash(codex --full-auto exec 'Implement [title] in [focus_paths]')"
}
]
``` ```
#### Benefits of Flow Control #### Benefits of Flow Control
@@ -172,205 +262,146 @@ Each step contains:
- **Command Flexibility**: Supports any executable command or agent - **Command Flexibility**: Supports any executable command or agent
- **Dependency Integration**: Automatic loading of prerequisite task results - **Dependency Integration**: Automatic loading of prerequisite task results
### Task Hierarchy ### Hierarchical Task System
**Structure**: Maximum 2 levels (IMPL-N.M format) **Maximum Depth**: 2 levels (IMPL-N.M format)
``` ```
IMPL-1 # Main task IMPL-1 # Main task
IMPL-1.1 # Subtask (dynamically created) IMPL-1.1 # Subtask of IMPL-1 (dynamically created)
IMPL-1.2 # Another subtask IMPL-1.2 # Another subtask of IMPL-1
IMPL-2 # Another main task IMPL-2 # Another main task
IMPL-2.1 # Subtask (dynamically created) IMPL-2.1 # Subtask of IMPL-2 (dynamically created)
``` ```
**Rules**: **Task Status Rules**:
- **Container tasks**: Parent tasks with subtasks (cannot execute directly) - **Container tasks**: Parent tasks with subtasks (cannot be directly executed)
- **Leaf tasks**: Only executable tasks - **Leaf tasks**: Only these can be executed directly
- **Status inheritance**: Parent status derived from subtask completion - **Status inheritance**: Parent status derived from subtask completion
## Session Management ## File Structure
### Active Session Marker System ### Unified File Structure
**Ultra-Simple Tracking**: `.workflow/.active-[session-name]` All workflows use the same file structure definition regardless of complexity. **Directories and files are created on-demand as needed**, not all at once during initialization.
```bash
.workflow/
├── WFS-oauth-integration/ # Session directory (paused)
├── WFS-user-profile/ # Session directory (paused)
├── WFS-bug-fix-123/ # Session directory (completed)
└── .active-WFS-user-profile # Marker file (active session)
```
**Benefits**:
- **Zero Parsing**: File existence check is atomic
- **Atomic Operations**: File creation/deletion is naturally atomic
- **Visual Discovery**: `ls .workflow/.active-*` shows active session
- **Simple Switching**: Delete old + create new marker
### Session Operations
```bash
# Detect active session
active_session=$(find .workflow -name ".active-*" | head -1)
if [ -n "$active_session" ]; then
session_name=$(basename "$active_session" | sed 's/^\.active-//')
echo "Active session: $session_name"
fi
# Switch session
find .workflow -name ".active-*" -delete && touch .workflow/.active-WFS-new-feature
```
### Session State
Each session directory contains `workflow-session.json`:
```json
{
"session_id": "WFS-[topic-slug]",
"project": "feature description",
"type": "simple|medium|complex",
"current_phase": "PLAN|IMPLEMENT|REVIEW",
"status": "active|paused|completed",
"progress": {
"completed_phases": ["PLAN"],
"current_tasks": ["IMPL-1", "IMPL-2"]
}
}
```
## File Organization
### Unified Structure
All workflows use the same structure regardless of complexity. **Files created on-demand only.**
#### Complete Structure Reference
``` ```
.workflow/WFS-[topic-slug]/ .workflow/WFS-[topic-slug]/
├── workflow-session.json # Session state (REQUIRED) ├── workflow-session.json # Session metadata and state (REQUIRED)
├── IMPL_PLAN.md # Planning document (REQUIRED) ├── [.brainstorming/] # Optional brainstorming phase (created when needed)
├── TODO_LIST.md # Progress tracking (REQUIRED) ├── [.chat/] # CLI interaction sessions (created when analysis is run)
├── .task/ # Task definitions (REQUIRED)
│ ├── IMPL-*.json # Main task definitions
│ └── IMPL-*.*.json # Subtask definitions (dynamic)
├── [.brainstorming/] # Brainstorming phase (on-demand)
├── [.chat/] # CLI sessions (on-demand)
│ ├── chat-*.md # Saved chat sessions │ ├── chat-*.md # Saved chat sessions
│ └── analysis-*.md # Analysis results │ └── analysis-*.md # Analysis results
── [.summaries/] # Task summaries (on-demand) ── IMPL_PLAN.md # Planning document (REQUIRED)
├── IMPL-*.md # Main task summaries ├── TODO_LIST.md # Progress tracking (REQUIRED)
└── IMPL-*.*.md # Subtask summaries ├── [.summaries/] # Task completion summaries (created when tasks complete)
│ ├── IMPL-*.md # Main task summaries
│ └── IMPL-*.*.md # Subtask summaries
└── .task/ # Task definitions (REQUIRED)
├── IMPL-*.json # Main task definitions
└── IMPL-*.*.json # Subtask definitions (created dynamically)
``` ```
### Creation Strategy #### Creation Strategy
- **Initial**: Only `workflow-session.json`, `IMPL_PLAN.md`, `TODO_LIST.md`, `.task/` - **Initial Setup**: Create only `workflow-session.json`, `IMPL_PLAN.md`, `TODO_LIST.md`, and `.task/` directory
- **On-Demand**: - **On-Demand Creation**: Other directories created when first needed:
- `.brainstorming/` → When brainstorming initiated - `.brainstorming/` → When brainstorming phase is initiated
- `.chat/` → When analysis commands executed - `.chat/` → When CLI analysis commands are executed
- `.summaries/` → When first task completed - `.summaries/` → When first task is completed
- **Dynamic Files**: Subtask JSON files created during task decomposition
### Naming Conventions ### File Naming Conventions
- **Sessions**: `WFS-[topic-slug]` (lowercase with hyphens)
- **Conflicts**: Add `-NNN` suffix if needed
- **Documents**: Standard names (`workflow-session.json`, `IMPL_PLAN.md`, etc.)
- **Chat**: `chat-analysis-*.md`
- **Summaries**: `IMPL-[task-id]-summary.md`
## Workflow Classification #### Session Identifiers
**Format**: `WFS-[topic-slug]`
- Convert topic to lowercase with hyphens (e.g., "User Auth System" → `WFS-user-auth-system`)
- Add `-NNN` suffix only if conflicts exist (e.g., `WFS-payment-integration-002`)
### Complexity Types #### Document Naming
**Based on task count and decomposition needs:** - `workflow-session.json` - Session state (required)
- `IMPL_PLAN.md` - Planning document (required)
- `TODO_LIST.md` - Progress tracking (auto-generated when needed)
- Chat sessions: `chat-analysis-*.md`
- Task summaries: `IMPL-[task-id]-summary.md`
| Type | Tasks | Depth | Behavior | ## Complexity Classification
|------|-------|-------|----------|
| **Simple** | ≤5 | 1 level | Direct execution, minimal decomposition |
| **Medium** | 6-10 | 2 levels | Moderate decomposition, context coordination |
| **Over-scope** | >10 | Re-scope | Requires project re-scoping into iterations |
### Characteristics ### Task Complexity Rules
**Complexity is determined by task count and decomposition needs:**
**Simple**: Bug fixes, small features, config changes | Complexity | Task Count | Hierarchy Depth | Decomposition Behavior |
- Single-level tasks, direct execution, ≤5 tasks |------------|------------|----------------|----------------------|
| **Simple** | <5 tasks | 1 level (IMPL-N) | Direct execution, minimal decomposition |
| **Medium** | 5-15 tasks | 2 levels (IMPL-N.M) | Moderate decomposition, context coordination |
| **Complex** | >15 tasks | 2 levels (IMPL-N.M) | Frequent decomposition, multi-agent orchestration |
**Medium**: New features, API endpoints, schema changes ### Simple Workflows
- Two-level hierarchy, context coordination, 6-10 tasks **Characteristics**: Direct implementation tasks with clear, limited scope
- **Examples**: Bug fixes, small feature additions, configuration changes
- **Task Decomposition**: Usually single-level tasks, minimal breakdown needed
- **Agent Coordination**: Direct execution without complex orchestration
**Over-scope**: Major features exceeding 10 tasks ### Medium Workflows
- Requires re-scoping into smaller iterations, never >10 tasks **Characteristics**: Feature implementation requiring moderate task breakdown
- **Examples**: New features, API endpoints with integration, database schema changes
- **Task Decomposition**: Two-level hierarchy when decomposition is needed
- **Agent Coordination**: Context coordination between related tasks
### Assessment Rules ### Complex Workflows
- **Creation**: System evaluates and assigns complexity **Characteristics**: System-wide changes requiring detailed decomposition
- **10-task limit**: Hard limit enforced - exceeding requires re-scoping - **Examples**: Major features, architecture refactoring, security implementations, multi-service deployments
- **Execution**: Can upgrade (Simple→Medium→Over-scope), triggers re-scoping - **Task Decomposition**: Frequent use of two-level hierarchy with dynamic subtask creation
- **Override**: Users can manually specify complexity within 10-task limit - **Agent Coordination**: Multi-agent orchestration with deep context analysis
## Task Execution Framework ### Automatic Assessment & Upgrades
- **During Creation**: System evaluates requirements and assigns complexity
- **During Execution**: Can upgrade (Simple→Medium→Complex) but never downgrade
- **Override Allowed**: Users can specify higher complexity manually
### Agent Integration ## Document Templates
**Assignment Rules** (based on task type/keywords): ### IMPL_PLAN.md
- **Planning** → planning-agent Generated based on task complexity and requirements. Contains overview, requirements, and task structure.
- **Implementation** → code-developer
- **Testing** → code-review-test-agent
- **Review** → review-agent
**Execution Context** (agents receive): ### Task Summary Template (.summaries/IMPL-X.X-summary.md)
Enhanced summary documents for context inheritance and dependency resolution:
```markdown
# Task Summary: [task-id] - [title]
## Context Provided
- **Parent Context**: [inherited context from parent task]
- **Dependencies Resolved**:
- [dep-1]: [brief description of what was provided]
- [dep-2]: [brief description of what was provided]
## Implementation Details
### Approach
[Brief description of the implementation strategy used]
### Files Modified
- `[file-path]`: [description of changes made]
- `[file-path]`: [description of changes made]
### Key Decisions
- [Decision 1]: [rationale]
- [Decision 2]: [rationale]
## Outputs for Dependent Tasks
### Shared Context
```json ```json
{ {
"task": { /* complete task JSON */ }, "key_component": "location or identifier",
"workflow": { "configuration": {
"session": "WFS-user-auth", "setting1": "value1",
"phase": "IMPLEMENT" "setting2": "value2"
},
"integration_points": ["endpoint1", "function2"],
"important_constants": {
"timeout": "30s",
"max_retries": 3
} }
} }
``` ```
## Operations Guide
### Basic Operations
```bash
# Session initialization
mkdir -p .workflow/WFS-topic-slug/.task
echo '{"session_id":"WFS-topic-slug",...}' > .workflow/WFS-topic-slug/workflow-session.json
echo '# Implementation Plan' > .workflow/WFS-topic-slug/IMPL_PLAN.md
echo '# Tasks' > .workflow/WFS-topic-slug/TODO_LIST.md
# Task creation
echo '{"id":"IMPL-1","title":"New task",...}' > .task/IMPL-1.json
# Task updates
jq '.status = "active"' .task/IMPL-1.json > temp && mv temp .task/IMPL-1.json
# Document generation
generate_todo_list_from_json .task/
```
### Validation Rules
1. **ID Uniqueness**: All task IDs must be unique
2. **Format**: IMPL-N[.M] pattern (max 2 levels)
3. **References**: Parent IDs must exist as JSON files
4. **Fields**: All 5 core fields required (id, title, status, meta, context, flow_control)
5. **Paths**: context.focus_paths must contain valid project paths
6. **Dependencies**: context.depends_on task IDs must exist
### Error Recovery
- **Missing Session**: Remove orphaned active marker
- **Multiple Active**: Keep newest, remove others
- **Corrupted Session**: Recreate from template
- **Broken Hierarchy**: Reconstruct parent-child relationships
```bash
# Session consistency check
active_marker=$(find .workflow -name ".active-*" | head -1)
if [ -n "$active_marker" ]; then
session_name=$(basename "$active_marker" | sed 's/^\.active-//')
session_dir=".workflow/$session_name"
if [ ! -d "$session_dir" ]; then
echo "⚠️ Orphaned active marker, removing..."
rm "$active_marker"
fi
fi
```
## Reference Templates
### Integration Points ### Integration Points
- **[Component Name]**: [how to use/integrate] - **[Component Name]**: [how to use/integrate]
@@ -385,7 +416,15 @@ fi
## Notes for Future Tasks ## Notes for Future Tasks
[Any important considerations, limitations, or follow-up items] [Any important considerations, limitations, or follow-up items]
``` ```
### TODO List (TODO_LIST.md)
#### Summary Document Purpose
- **Context Inheritance**: Provides structured context for dependent tasks
- **Integration Guidance**: Offers clear integration points and usage instructions
- **Quality Assurance**: Documents testing and validation performed
- **Decision History**: Preserves rationale for implementation choices
- **Dependency Chain**: Enables automatic context accumulation through task dependencies
### TODO_LIST.md Template
```markdown ```markdown
# Tasks: [Session Topic] # Tasks: [Session Topic]
@@ -393,7 +432,7 @@ fi
▸ **IMPL-001**: [Main Task Group] → [📋](./.task/IMPL-001.json) ▸ **IMPL-001**: [Main Task Group] → [📋](./.task/IMPL-001.json)
- [ ] **IMPL-001.1**: [Subtask] → [📋](./.task/IMPL-001.1.json) - [ ] **IMPL-001.1**: [Subtask] → [📋](./.task/IMPL-001.1.json)
- [x] **IMPL-001.2**: [Subtask] → [📋](./.task/IMPL-001.2.json) | [✅](./.summaries/IMPL-001.2.md) - [x] **IMPL-001.2**: [Subtask] → [📋](./.task/IMPL-001.2.json) | [✅](./.summaries/IMPL-001.2.md)
- [x] **IMPL-002**: [Simple Task] → [📋](./.task/IMPL-002.json) | [✅](./.summaries/IMPL-002.md) - [x] **IMPL-002**: [Simple Task] → [📋](./.task/IMPL-002.json) | [✅](./.summaries/IMPL-002.md)
▸ **IMPL-003**: [Main Task Group] → [📋](./.task/IMPL-003.json) ▸ **IMPL-003**: [Main Task Group] → [📋](./.task/IMPL-003.json)
@@ -402,7 +441,7 @@ fi
## Status Legend ## Status Legend
- `▸` = Container task (has subtasks) - `▸` = Container task (has subtasks)
- `- [ ]` = Pending leaf task - `- [ ]` = Pending leaf task
- `- [x]` = Completed leaf task - `- [x]` = Completed leaf task
- Maximum 2 levels: Main tasks and subtasks only - Maximum 2 levels: Main tasks and subtasks only
@@ -410,6 +449,97 @@ fi
[Optional notes] [Optional notes]
``` ```
## Agent Integration
### Agent Assignment
Based on task type and title keywords:
- **Planning tasks** → planning-agent
- **Implementation** → code-developer
- **Testing** → code-review-test-agent
- **Review** → review-agent
### Execution Context
Agents receive complete task JSON plus workflow context:
```json
{
"task": { /* complete task JSON */ },
"workflow": {
"session": "WFS-user-auth",
"phase": "IMPLEMENT"
}
}
```
## Data Operations
### Session Initialization
```bash
# Create minimal required structure
mkdir -p .workflow/WFS-topic-slug/.task
echo '{"session_id":"WFS-topic-slug",...}' > .workflow/WFS-topic-slug/workflow-session.json
echo '# Implementation Plan' > .workflow/WFS-topic-slug/IMPL_PLAN.md
echo '# Tasks' > .workflow/WFS-topic-slug/TODO_LIST.md
```
### Task Creation
```bash
echo '{"id":"IMPL-1","title":"New task",...}' > .task/IMPL-1.json
```
### Directory Creation (On-Demand)
```bash
# Create directories only when needed
mkdir -p .brainstorming # When brainstorming is initiated
mkdir -p .chat # When analysis commands are run
mkdir -p .summaries # When first task completes
```
### Task Updates
```bash
jq '.status = "active"' .task/IMPL-1.json > temp && mv temp .task/IMPL-1.json
```
### Document Generation
```bash
# Generate TODO_LIST.md from current JSON state
generate_todo_list_from_json .task/
```
## Validation and Error Handling
### Task Integrity Rules
1. **ID Uniqueness**: All task IDs must be unique
2. **Hierarchical Format**: Must follow IMPL-N[.M] pattern (maximum 2 levels)
3. **Parent References**: All parent IDs must exist as JSON files
4. **Depth Limits**: Maximum 2 levels deep
5. **Status Consistency**: Status values from defined enumeration
6. **Required Fields**: All 5 core fields must be present (id, title, status, meta, context, flow_control)
7. **Focus Paths Structure**: context.focus_paths array must contain valid project paths
8. **Flow Control Format**: flow_control.pre_analysis must be array with step, action, command fields
9. **Dependency Integrity**: All context.depends_on task IDs must exist as JSON files
### Session Consistency Checks
```bash
# Validate active session integrity
active_marker=$(find .workflow -name ".active-*" | head -1)
if [ -n "$active_marker" ]; then
session_name=$(basename "$active_marker" | sed 's/^\.active-//')
session_dir=".workflow/$session_name"
if [ ! -d "$session_dir" ]; then
echo "⚠️ Orphaned active marker, removing..."
rm "$active_marker"
fi
fi
```
### Recovery Strategies
- **Missing Session Directory**: Remove orphaned active marker
- **Multiple Active Markers**: Keep newest, remove others
- **Corrupted Session File**: Recreate from template
- **Broken Task Hierarchy**: Reconstruct parent-child relationships
--- ---
**System Design**: Unified workflow architecture featuring ultra-fast session management, JSON-only data model, and consistent file structure across all workflow types. **System ensures**: Unified workflow architecture with ultra-fast session management, JSON-only data model, and unified file structure for all workflows regardless of complexity.