refactor: Simplify task commands and centralize documentation

- Move CORE.md to workflows/task-core.md for better organization
- Significantly reduce task command file sizes:
  * breakdown.md: 310 → 120 lines
  * create.md: 326 → 100 lines
  * replan.md: 594 → 150 lines
- Centralize task schema and implementation details in task-core.md
- Update all references to use consistent ~/.claude/workflows/task-core.md paths
- Maintain full functionality while improving clarity and maintainability
- Separate task-level concerns from workflow-level architecture

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

Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
catlog22
2025-09-14 11:00:15 +08:00
parent 56bd586506
commit 3536411419
4 changed files with 423 additions and 959 deletions

View File

@@ -12,282 +12,103 @@ examples:
# Task Breakdown Command (/task:breakdown)
## Overview
Intelligently breaks down complex tasks into manageable subtasks with automatic context distribution and agent assignment.
Breaks down complex tasks into executable subtasks with context inheritance and agent assignment.
## Core Principles
**Task Schema:** @~/.claude/workflows/workflow-architecture.md
**Task System:** @~/.claude/workflows/task-core.md
## Features
## Core Features
⚠️ **CRITICAL**: Before breakdown, MUST check for existing active session to avoid creating duplicate sessions.
⚠️ **CRITICAL**: Check for active session before breakdown to avoid conflicts.
### Session Check Process
1. **Check Active Session**: Check for `.workflow/.active-*` marker file to identify active session containing the parent task.
2. **Session Validation**: Use existing active session containing the parent task
3. **Context Integration**: Load existing session state and task hierarchy
### Smart Decomposition
- **Auto Strategy**: AI-powered subtask generation based on title
- **Interactive Mode**: Guided breakdown with suggestions
- **Context Distribution**: Subtasks inherit parent context
- **Agent Mapping**: Automatic agent assignment per subtask
### Simplified Task Management
- **JSON Task Hierarchy**: Creates hierarchical JSON subtasks (impl-N.M.P)
- **Context Distribution**: Subtasks inherit parent context
- **Basic Status Tracking**: Updates task relationships only
- **No Complex Synchronization**: Simple parent-child relationships
### Breakdown Process
1. **Session Check**: Verify active session contains parent task
2. **Task Validation**: Ensure parent is `pending` status
3. **AI Decomposition**: Generate subtasks based on parent title
4. **Context Distribution**: Inherit parent requirements and scope
5. **Agent Assignment**: Auto-assign agents based on subtask type
### Breakdown Rules
- Only `pending` tasks can be broken down
- Parent becomes container (not directly executable)
- Subtasks use hierarchical format: impl-N.M.P (e.g., impl-1.1.2)
- Maximum depth: 3 levels (impl-N.M.P)
- Parent-child relationships tracked in JSON only
- Parent becomes `container` status (not executable)
- Subtasks use format: impl-N.M (max 2 levels)
- Context flows from parent to subtasks
- All relationships tracked in JSON
## Usage
### Basic Breakdown
```bash
/task:breakdown IMPL-1
/task:breakdown impl-1
```
Interactive prompt:
Interactive process:
```
Task: Build authentication module
Suggested subtasks:
1. Design authentication schema
2. Implement login endpoint
3. Add JWT token handling
4. Write unit tests
2. Implement core auth logic
3. Add security middleware
4. Write comprehensive tests
Accept task breakdown? (y/n/edit): y
```
Accept breakdown? (y/n): y
### Auto Strategy
```bash
/task:breakdown impl-1 --strategy=auto
```
Automatic generation:
```
✅ Task impl-1 broken down:
▸ impl-1: Build authentication module (container)
├── impl-1.1: Design authentication schema
├── impl-1.2: Implement core auth logic
├── impl-1.3: Add security middleware
└── impl-1.4: Write comprehensive tests
├── impl-1.1: Design schema → planning-agent
├── impl-1.2: Implement logic → code-developer
├── impl-1.3: Add middleware → code-developer
└── impl-1.4: Write tests → code-review-test-agent
Agents assigned:
- impl-1.1 → planning-agent
- impl-1.2 → code-developer
- impl-1.3 → code-developer
- impl-1.4 → code-review-test-agent
JSON files created:
- .task/impl-1.json (container)
- .task/impl-1.1.json
- .task/impl-1.2.json
- .task/impl-1.3.json
- .task/impl-1.4.json
Files created: .task/impl-1.json + 4 subtask files
```
## Decomposition Patterns
## Decomposition Logic
### Feature Task Pattern
```
Feature: "Implement shopping cart"
├── Design data model
├── Build API endpoints
├── Add state management
├── Create UI components
└── Write tests
```
### Agent Assignment
- **Design/Planning** → `planning-agent`
- **Implementation** → `code-developer`
- **Testing** → `code-review-test-agent`
- **Review** → `review-agent`
### Bug Fix Pattern
```
Bug: "Fix performance issue"
├── Profile and identify bottleneck
├── Implement optimization
├── Verify fix
└── Add regression test
```
### Context Inheritance
- Subtasks inherit parent requirements
- Scope refined for specific subtask
- Implementation details distributed appropriately
### Refactor Pattern
```
Refactor: "Modernize auth system"
├── Analyze current implementation
├── Design new architecture
├── Migrate incrementally
├── Update documentation
└── Deprecate old code
```
## Implementation Details
## Context Distribution
Parent context is intelligently distributed:
```json
{
"parent": {
"id": "impl-1",
"context": {
"requirements": ["JWT auth", "2FA support"],
"scope": ["src/auth/*"],
"acceptance": ["Authentication system works"],
"inherited_from": "WFS-user-auth"
}
},
"subtasks": [
{
"id": "impl-1.1",
"title": "Design authentication schema",
"status": "pending",
"agent": "planning-agent",
"context": {
"requirements": ["JWT auth schema", "User model design"],
"scope": ["src/auth/models/*"],
"acceptance": ["Schema validates JWT tokens", "User model complete"],
"inherited_from": "impl-1"
},
"relations": {
"parent": "impl-1",
"subtasks": [],
"dependencies": []
},
"implementation": {
"files": [
{
"path": "src/auth/models/User.ts",
"location": {
"function": "UserSchema",
"lines": "auto-detect",
"description": "User schema definition for authentication"
},
"original_code": "// Requires gemini analysis for current schema structure",
"modifications": {
"current_state": "Basic user model without auth fields",
"proposed_changes": [
"Add JWT token storage fields",
"Include authentication provider fields",
"Add timestamp tracking for security"
],
"logic_flow": [
"defineSchema() ───► addAuthFields() ───► validateStructure()",
"◊─── if JWT ───► addTokenFields() ───► addExpirationLogic()",
"◊─── if OAuth ───► addProviderFields() ───► linkExternalAccounts()"
],
"reason": "Support comprehensive authentication system requirements",
"expected_outcome": "Robust user schema supporting multiple authentication methods"
}
}
],
"context_notes": {
"dependencies": ["mongoose", "jsonwebtoken"],
"affected_modules": ["auth-service", "user-controller"],
"risks": [
"Database migration required for existing users",
"Schema validation complexity with multiple auth types"
],
"performance_considerations": "Index auth fields for fast lookups",
"error_handling": "Graceful validation errors for schema changes"
},
"analysis_source": "auto-detected"
}
}
]
}
```
## Implementation Field Inheritance
### Parent to Subtask Context Flow
When breaking down tasks, implementation details are inherited and refined:
**Parent Implementation Context**:
- High-level file scope (e.g., "src/auth/*")
- General requirements and dependencies
- Architecture-level risks and considerations
**Subtask Implementation Refinement**:
- Specific file paths (e.g., "src/auth/models/User.ts")
- Precise function locations and line ranges
- Detailed modification steps and logic flows
- Subtask-specific risks and dependencies
**Auto-Population Strategy for Subtasks**:
1. **Inherit from Parent**: Copy relevant files from parent.implementation.files
2. **Refine Scope**: Narrow down to subtask-specific files and functions
3. **Generate Details**: Create subtask-specific modifications and logic flows
4. **Risk Analysis**: Identify subtask-level risks from parent context
5. **Gemini Trigger**: Mark analysis_source as "gemini" when details need extraction
## Agent Assignment Logic
Based on subtask type and implementation complexity:
- **Design/Planning** → `planning-agent` (architectural implementation planning)
- **Implementation** → `code-developer` (file-level code changes)
- **Testing** → `code-review-test-agent` (test implementation for specific functions)
- **Review** → `review-agent` (code review with implementation context)
See @~/.claude/workflows/task-core.md for:
- Complete task JSON schema
- Implementation field structure
- Context inheritance rules
- Agent assignment logic
## Validation
### Pre-breakdown Checks
1. Task exists and is valid
2. Task status is `pending`
3. Not already broken down
4. Workflow in IMPLEMENT phase
1. Active session exists
2. Task found in session
3. Task status is `pending`
4. Not already broken down
### Post-breakdown Actions
1. Update parent status to `container`
1. Update parent to `container` status
2. Create subtask JSON files
3. Update parent task with subtask references
4. Update workflow session stats
## Simple File Management
### File Structure Created
```
.workflow/WFS-[topic-slug]/
├── workflow-session.json # Session state
├── IMPL_PLAN.md # Static planning document
└── .task/
├── impl-1.json # Parent task (container)
├── impl-1.1.json # Subtask 1
└── impl-1.2.json # Subtask 2
```
### Output Files
- JSON subtask files in `.task/` directory
- Updated parent task JSON with subtask references
- Updated session stats in `workflow-session.json`
3. Update parent subtasks list
4. Update session stats
## Examples
### Simple Breakdown
### Basic Breakdown
```bash
/task:breakdown impl-1
Result:
▸ impl-1: Build authentication (container)
├── impl-1.1: Design auth schema
├── impl-1.2: Implement auth logic
── impl-1.3: Add security middleware
└── impl-1.4: Write tests
```
### Two-Level Breakdown
```bash
/task:breakdown impl-1 --depth=2
Result:
▸ impl-1: E-commerce checkout (container)
├── impl-1.1: Payment processing
│ ├── impl-1.1.1: Integrate gateway
│ └── impl-1.1.2: Handle transactions
├── impl-1.2: Order management
│ └── impl-1.2.1: Create order model
└── impl-1.3: Testing
├── impl-1.1: Design schema → planning-agent
├── impl-1.2: Implement logic → code-developer
── impl-1.3: Write tests → code-review-test-agent
```
## Error Handling
@@ -299,8 +120,8 @@ Result:
# Already broken down
⚠️ Task impl-1 already has subtasks
# Max depth exceeded
❌ Cannot create impl-1.2.3.4 (max 3 levels)
# Wrong status
❌ Cannot breakdown completed task impl-2
```
## Related Commands

View File

@@ -12,31 +12,26 @@ examples:
# Task Create Command (/task:create)
## Overview
Creates new implementation tasks during IMPLEMENT phase with automatic context awareness and ID generation.
Creates new implementation tasks with automatic context awareness and ID generation.
## Core Principles
**Task Management:** @~/.claude/workflows/workflow-architecture.md
**Task System:** @~/.claude/workflows/task-core.md
## Features
## Core Features
### Automatic Behaviors
- **ID Generation**: Auto-generates impl-N hierarchical format (impl-N.M.P max depth)
- **Context Inheritance**: Inherits from workflow session and IMPL_PLAN.md
- **JSON File Creation**: Generates task JSON in `.workflow/WFS-[topic-slug]/.task/`
- **Document Integration**: Creates/updates TODO_LIST.md based on complexity triggers
- **ID Generation**: Auto-generates impl-N format (max 2 levels)
- **Context Inheritance**: Inherits from active workflow session
- **JSON Creation**: Creates task JSON in active session
- **Status Setting**: Initial status = "pending"
- **Workflow Sync**: Updates workflow-session.json task list automatically
- **Agent Assignment**: Suggests agent based on task type
- **Hierarchy Support**: Creates parent-child relationships up to 3 levels
- **Progressive Structure**: Auto-triggers enhanced structure at complexity thresholds
- **Dynamic Complexity Escalation**: Automatically upgrades workflow complexity when thresholds are exceeded
- **Session Integration**: Updates workflow session stats
### Context Awareness
- Detects current workflow phase (must be IMPLEMENT)
- Reads existing tasks from `.task/` directory to avoid duplicates
- Inherits requirements and scope from workflow-session.json
- Suggests related tasks based on existing JSON task hierarchy
- Analyzes complexity for structure level determination (Level 0-2)
- Validates active workflow session exists
- Avoids duplicate task IDs
- Inherits session requirements and scope
- Suggests task relationships
## Usage
@@ -50,14 +45,8 @@ Output:
✅ Task created: impl-1
Title: Build authentication module
Type: feature
Agent: code-developer
Status: pending
Depth: 1 (main task)
Context inherited from workflow
```
### With Options
```bash
/task:create "Fix security vulnerability" --type=bugfix --priority=critical
```
### Task Types
@@ -65,188 +54,72 @@ Context inherited from workflow
- `bugfix` - Bug fixes
- `refactor` - Code improvements
- `test` - Test implementation
- `docs` - Documentation (handled by code-developer)
- `docs` - Documentation
### Priority Levels (Optional - moved to context)
- `low` - Can be deferred
- `normal` - Standard priority (default)
- `high` - Should be done soon
- `critical` - Must be done immediately
## Task Creation Process
**Note**: Priority is now stored in `context.priority` if needed, removed from top level for simplification.
1. **Session Validation**: Check active workflow session
2. **ID Generation**: Auto-increment impl-N
3. **Context Inheritance**: Load workflow context
4. **Implementation Setup**: Initialize implementation field
5. **Agent Assignment**: Select appropriate agent
6. **File Creation**: Save JSON to .task/ directory
7. **Session Update**: Update workflow stats
## Simplified Task Structure
**Task Schema**: See @~/.claude/workflows/task-core.md for complete JSON structure
```json
{
"id": "impl-1",
"title": "Build authentication module",
"status": "pending",
"type": "feature",
"agent": "code-developer",
"context": {
"requirements": ["JWT authentication", "OAuth2 support"],
"scope": ["src/auth/*", "tests/auth/*"],
"acceptance": ["Module handles JWT tokens", "OAuth2 flow implemented"],
"inherited_from": "WFS-user-auth"
},
"relations": {
"parent": null,
"subtasks": [],
"dependencies": []
},
"execution": {
"attempts": 0,
"last_attempt": null
},
"implementation": {
"files": [
{
"path": "src/auth/login.ts",
"location": {
"function": "handleLogin",
"lines": "auto-detect",
"description": "Login handler function"
},
"original_code": "// Requires gemini analysis for code extraction",
"modifications": {
"current_state": "Basic password authentication",
"proposed_changes": [
"Add JWT token generation",
"Integrate OAuth2 flow"
],
"logic_flow": [
"validateInput() ───► checkCredentials()",
"◊─── if valid ───► generateJWT() ───► return token"
],
"reason": "Implement modern authentication standards",
"expected_outcome": "Secure, flexible authentication system"
}
}
],
"context_notes": {
"dependencies": ["jsonwebtoken", "passport"],
"affected_modules": ["user-management", "session-handler"],
"risks": [
"Breaking changes to existing auth middleware",
"Database schema changes required"
],
"performance_considerations": "JWT validation adds ~5ms per request",
"error_handling": "Ensure no sensitive data in error responses"
},
"analysis_source": "auto-detected"
}
}
```
## Implementation Field Generation
## Implementation Field Setup
### Auto-Population Strategy
**Sufficient Information**: When task description contains specific details
- Extract file paths from scope or task description
- Identify functions/classes mentioned in requirements
- Generate basic implementation structure automatically
- **Detailed info**: Extract from task description and scope
- **Missing info**: Mark `analysis_source` as "gemini" for later analysis
- **Basic structure**: Initialize with standard template
**Insufficient Information**: When details are vague or missing
- Mark `analysis_source` as "gemini"
- Set `original_code` to "// Requires gemini analysis for code extraction"
- Prompt user for gemini analysis:
### Analysis Triggers
When implementation details incomplete:
```bash
⚠️ Implementation details incomplete for task: [task-title]
Recommend running:
gemini --all-files -p "@{scope-patterns} @{CLAUDE.md}
Analyze task: [task-description]
Extract: 1) File locations and functions 2) Current code state 3) Risks and dependencies"
⚠️ Task requires analysis for implementation details
Suggest running: gemini analysis for file locations and dependencies
```
### Implementation Quality Standards
- **File paths**: Must be specific (not wildcards like "src/*")
- **Location details**: Include function name or line range, not just file name
- **Logic flow**: Use standard symbols (───►, ◊───, ◄───)
- **Risk assessment**: At least 1 specific, actionable risk
- **Dependencies**: Actual package names, not generic descriptions
## File Management
### Simplified File Generation
### JSON Task File
- **Location**: `.task/impl-[N].json` in active session
- **Content**: Complete task with implementation field
- **Updates**: Session stats only
### JSON Task File Only
**File Location**: `.task/impl-[N].json`
**Naming**: Follows impl-N.M.P format for nested tasks
**Content**: Contains all task data including implementation details
### No Document Synchronization
- Creates JSON task file only with complete implementation field
- Updates workflow-session.json stats only
- No automatic TODO_LIST.md generation
- No complex cross-referencing needed
### View Generation On-Demand
- Use `/context` to generate views when needed
- No persistent markdown files created
- All data including implementation stored in JSON only
## Simplified Task Management
### Basic Task Statistics
- Task count tracked in workflow-session.json
- No automatic complexity escalation
- Manual workflow type selection during init
### Simple Creation Process
```
1. Create New Task → Generate JSON file only
2. Update Session Stats → Increment task count
3. Notify User → Confirm task created
```
### Benefits of Simplification
- **No Overhead**: Just create tasks, no complex logic
- **Predictable**: Same process every time
- **Fast**: Minimal processing needed
- **Clear**: User controls complexity level
### Simple Process
1. Validate session and inputs
2. Generate task JSON
3. Update session stats
4. Notify completion
## Context Inheritance
Tasks automatically inherit:
1. **Requirements** - From workflow-session.json and IMPL_PLAN.md
2. **Scope** - File patterns from workflow context
3. **Parent Context** - When created as subtasks, inherit from parent
4. **Session Context** - Global workflow context from active session
Tasks inherit from:
1. **Active Session** - Requirements and scope from workflow-session.json
2. **Planning Document** - Context from IMPL_PLAN.md
3. **Parent Task** - For subtasks (impl-N.M format)
## Smart Suggestions
## Agent Assignment
Based on title analysis:
```bash
/task:create "Write unit tests for auth module"
Suggestions:
- Related task: impl-1 (Build authentication module)
- Suggested agent: code-review-test-agent
- Estimated effort: 2h
- Dependencies: [impl-1]
- Suggested hierarchy: impl-1.3 (as subtask of impl-1)
```
Based on task type and title keywords:
- **Build/Implement** → `code-developer`
- **Design/Plan** → `planning-agent`
- **Test/Validate** → `code-review-test-agent`
- **Review/Audit** → `review-agent`
## Validation Rules
1. **Phase Check** - Must be in IMPLEMENT phase (from workflow-session.json)
2. **Duplicate Check** - Title similarity detection across existing JSON files
3. **Session Validation** - Active workflow session must exist in `.workflow/`
4. **ID Uniqueness** - Auto-increment to avoid conflicts in `.task/` directory
5. **Hierarchy Validation** - Parent-child relationships must be valid (max 3 levels)
6. **File System Validation** - Proper directory structure and naming conventions
7. **JSON Schema Validation** - All task files conform to unified schema
1. **Session Check** - Active workflow session required
2. **Duplicate Check** - Avoid similar task titles
3. **ID Uniqueness** - Auto-increment task IDs
4. **Schema Validation** - Ensure proper JSON structure
## Error Handling
```bash
# Not in IMPLEMENT phase
❌ Cannot create tasks in PLAN phase
→ Use: /workflow implement
# No workflow session
❌ No active workflow found
→ Use: /workflow init "project name"
@@ -255,72 +128,35 @@ Suggestions:
⚠️ Similar task exists: impl-3
→ Continue anyway? (y/n)
# Maximum depth exceeded
❌ Cannot create impl-1.2.3.1 (exceeds 3-level limit)
Suggest: impl-1.2.4 or promote to impl-2?
# Max depth exceeded
❌ Cannot create impl-1.2.1 (max 2 levels)
Use: impl-2 for new main task
```
## Batch Creation
Create multiple tasks at once:
```bash
/task:create --batch
> Enter tasks (empty line to finish):
> Build login endpoint
> Add session management
> Write authentication tests
>
Created 3 tasks:
- impl-1: Build login endpoint
- impl-2: Add session management
- impl-3: Write authentication tests
```
## File Output
### JSON Task File
**Location**: `.task/impl-[id].json`
**Schema**: Simplified task JSON schema
**Contents**: Complete task definition with context
### Session Updates
**File**: `workflow-session.json`
**Updates**: Basic task count and active task list only
## Integration
### Simple Integration
- Updates workflow-session.json stats
- Creates JSON task file
- No complex file coordination needed
### Next Steps
After creation, use:
- `/task:breakdown` - Split into subtasks
- `/task:execute` - Run the task
- `/context` - View task details and status
## Examples
### Feature Development
### Feature Task
```bash
/task:create "Implement shopping cart functionality" --type=feature
/task:create "Implement user authentication"
✅ Created impl-1: Implement user authentication
Type: feature
Agent: code-developer
Status: pending
```
### Bug Fix
```bash
/task:create "Fix memory leak in data processor" --type=bugfix --priority=high
```
/task:create "Fix login validation bug" --type=bugfix
### Refactoring
```bash
/task:create "Refactor database connection pool" --type=refactor
✅ Created impl-2: Fix login validation bug
Type: bugfix
Agent: code-developer
Status: pending
```
## Related Commands
- `/task:breakdown` - Break task into hierarchical subtasks
- `/task:context` - View/modify task context
- `/task:execute` - Execute task with agent
- `/task:status` - View task status and hierarchy
- `/task:breakdown` - Break into subtasks
- `/task:execute` - Execute with agent
- `/context` - View task details

View File

@@ -12,583 +12,193 @@ examples:
# Task Replan Command (/task:replan)
## Overview
Replans individual tasks based on detailed user input with comprehensive change tracking, version management, and document synchronization. Focuses exclusively on single-task modifications with rich input options.
Replans individual tasks with multiple input options, change tracking, and version management.
## Core Principles
**Task Management:** @~/.claude/workflows/workflow-architecture.md
**Task System:** @~/.claude/workflows/task-core.md
## Single-Task Focus
This command operates on **individual tasks only**. For workflow-wide changes, use `/workflow:action-plan` instead.
## Key Features
- **Single-Task Focus**: Operates on individual tasks only
- **Multiple Input Sources**: Text, files, or issue references
- **Version Tracking**: Backup previous versions
- **Change Documentation**: Track all modifications
⚠️ **CRITICAL**: Before replanning, checks for existing active session to avoid conflicts.
⚠️ **CRITICAL**: Validates active session before replanning
## Input Sources for Replanning
## Input Sources
### Direct Text Input (Default)
### Direct Text (Default)
```bash
/task:replan impl-1 "Add OAuth2 authentication support"
```
**Processing**:
- Parse specific changes and requirements
- Extract new features or modifications needed
- Apply directly to target task structure
### File-based Requirements
### File-based Input
```bash
/task:replan impl-1 --from-file updated-specs.md
/task:replan impl-1 --from-file requirements-change.txt
/task:replan impl-1 updated-specs.md
```
**Supported formats**: .md, .txt, .json, .yaml
**Processing**:
- Read detailed requirement changes from file
- Parse structured specifications and updates
- Apply file content to task replanning
Supports: .md, .txt, .json, .yaml
### Issue-based Replanning
### Issue Reference
```bash
/task:replan impl-1 --from-issue ISS-001
/task:replan impl-1 --from-issue "bug-report"
/task:replan impl-1 ISS-001
```
**Processing**:
- Load issue description and requirements
- Extract necessary changes for task
- Apply issue resolution to task structure
### Detailed Mode
```bash
/task:replan impl-1 --detailed
```
**Guided Input**:
1. **New Requirements**: What needs to be added/changed?
2. **Scope Changes**: Expand/reduce task scope?
3. **Subtask Modifications**: Add/remove/modify subtasks?
4. **Dependencies**: Update task relationships?
5. **Success Criteria**: Modify completion conditions?
6. **Agent Assignment**: Change assigned agent?
7. **Implementation Details**: Update file paths, code locations, and logic flows?
Loads issue description and requirements
### Interactive Mode
```bash
/task:replan impl-1 --interactive
```
**Step-by-Step Process**:
1. **Current Analysis**: Review existing task structure
2. **Change Identification**: What needs modification?
3. **Impact Assessment**: How changes affect task?
4. **Structure Updates**: Add/modify subtasks
5. **Validation**: Confirm changes before applying
Guided step-by-step modification process with validation
## Replanning Flow with Change Tracking
## Replanning Process
### 1. Task Loading & Validation
```
Load Task → Read current task JSON file
Validate → Check task exists and can be modified
Session Check → Verify active workflow session
```
1. **Load & Validate**: Read task JSON and validate session
2. **Parse Input**: Process changes from input source
3. **Backup Version**: Create previous version backup
4. **Update Task**: Modify JSON structure and relationships
5. **Save Changes**: Write updated task and increment version
6. **Update Session**: Reflect changes in workflow stats
### 2. Input Processing
```
Detect Input Type → Identify source type
Extract Requirements → Parse change requirements
Analyze Impact → Determine modifications needed
```
### 3. Version Management
```
Create Version → Backup current task state
Update Version → Increment task version number
Archive → Store previous version in versions/
```
### 4. Task Structure Updates
```
Modify Task → Update task JSON structure
Update Subtasks → Add/remove/modify as needed
Update Relations → Fix dependencies and hierarchy
Update Context → Modify requirements and scope
```
### 5. Document Synchronization
```
Update IMPL_PLAN → Regenerate task section
Update TODO_LIST → Sync task hierarchy (if exists)
Update Session → Reflect changes in workflow state
```
### 6. Change Documentation
```
Create Change Log → Document all modifications
Generate Summary → Create replan report
Update History → Add to task replan history
```
## Version Management (Simplified)
## Version Management
### Version Tracking
Each replan creates a new version with complete history:
Tasks maintain version history:
```json
{
"id": "impl-1",
"title": "Build authentication module",
"version": "1.2",
"replan_history": [
{
"version": "1.1",
"reason": "Original plan",
"input_source": "initial_creation"
},
{
"version": "1.2",
"reason": "Add OAuth2 authentication support",
"reason": "Add OAuth2 support",
"input_source": "direct_text",
"changes": [
"Added subtask impl-1.3: OAuth2 integration",
"Added subtask impl-1.4: Token management",
"Modified scope to include external auth"
],
"backup_location": ".task/versions/impl-1-v1.1.json"
}
],
"context": {
"requirements": ["Basic auth", "Session mgmt", "OAuth2 support"],
"scope": ["src/auth/*", "tests/auth/*"],
"acceptance": ["All auth methods work"]
},
"implementation": {
"files": [
{
"path": "src/auth/oauth.ts",
"location": {
"function": "handleOAuthCallback",
"lines": "45-80",
"description": "OAuth callback handler (added in replan)"
},
"original_code": "// New file - requires creation",
"modifications": {
"current_state": "File does not exist",
"proposed_changes": [
"Create OAuth2 callback handler",
"Integrate with existing auth system"
],
"logic_flow": [
"receiveCallback() ───► validateAuthCode()",
"◊─── if valid ───► exchangeForToken() ───► storeUserSession()",
"◊─── if invalid ───► logError() ───► redirectToLogin()"
],
"reason": "Support external authentication providers",
"expected_outcome": "Seamless OAuth2 integration"
}
}
],
"context_notes": {
"dependencies": ["passport-oauth2", "express-session"],
"affected_modules": ["auth-middleware", "user-session"],
"risks": [
"OAuth provider configuration complexity",
"Session management conflicts with existing auth"
],
"performance_considerations": "External API calls may add 200-500ms latency",
"error_handling": "Graceful fallback to standard login on OAuth failure"
},
"analysis_source": "manual"
}
]
}
```
### File Structure After Replan
**Complete schema**: See @~/.claude/workflows/task-core.md
### File Structure
```
.task/
├── impl-1.json # Current version (1.2)
├── impl-1.3.json # New subtask
├── impl-1.4.json # New subtask
├── impl-1.json # Current version
├── versions/
│ └── impl-1-v1.1.json # Previous version backup
└── summaries/
└── replan-impl-1-20250908.md # Change log
│ └── impl-1-v1.1.json # Previous backup
└── [new subtasks as needed]
```
## Implementation Field Updates
## Implementation Updates
### Implementation Change Detection
When replanning, the system analyzes changes to the implementation field:
### Change Detection
Tracks modifications to:
- Files in implementation.files array
- Dependencies and affected modules
- Risk assessments and performance notes
- Logic flows and code locations
**Implementation Changes Tracked**:
- New files added to implementation.files array
- Modified file paths or locations
- Updated original_code snippets (via gemini re-analysis if needed)
- Changed logic flows and data flow diagrams
- Modified dependencies and risk assessments
- Updated performance considerations and error handling
### Analysis Triggers
May require gemini re-analysis when:
- New files need code extraction
- Function locations change
- Dependencies require re-evaluation
**Gemini Re-analysis Triggers**:
- New file paths that need code extraction
- Changed function locations requiring updated code snippets
- Modified scope requiring dependency re-evaluation
- When analysis_source was "gemini" and major changes occur
## Document Updates
**Example Implementation Update**:
```json
"implementation": {
"files": [
{
"path": "src/auth/oauth.ts", // NEW FILE ADDED
"original_code": "// New file - requires creation",
"modifications": {
"logic_flow": [
"// NEW FLOW ADDED FOR OAUTH"
]
}
}
],
"context_notes": {
"dependencies": ["passport-oauth2"], // NEW DEPENDENCY
"risks": [
"OAuth provider configuration complexity" // NEW RISK
]
}
}
```
### Planning Document
May update IMPL_PLAN.md sections when task structure changes significantly
## IMPL_PLAN.md Updates
### Automatic Plan Regeneration
When task is replanned, the corresponding section in IMPL_PLAN.md is updated:
**Before Replan**:
```markdown
## Task Breakdown
- **IMPL-001**: Build authentication module
- Basic login functionality
- Session management
- Password reset
```
**After Replan**:
```markdown
## Task Breakdown
- **IMPL-001**: Build authentication module (v1.2)
- Basic login functionality
- Session management
- OAuth2 integration (added)
- Token management (added)
- Password reset
*Last updated via task:replan*
```
### Plan Update Process
1. **Locate Task Section**: Find task in IMPL_PLAN.md by ID
2. **Update Description**: Modify task title if changed
3. **Update Subtasks**: Add/remove bullet points for subtasks
4. **Add Version Info**: Include version number and update timestamp
5. **Preserve Context**: Keep surrounding plan structure intact
## TODO_LIST.md Synchronization
### Automatic TODO List Updates
If TODO_LIST.md exists in workflow, synchronize task changes:
**Before Replan**:
```markdown
## Implementation Tasks
- [ ] impl-1: Build authentication module
- [x] impl-1.1: Design schema
- [ ] impl-1.2: Implement logic
```
**After Replan**:
```markdown
## Implementation Tasks
- [ ] impl-1: Build authentication module (updated v1.2)
- [x] impl-1.1: Design schema
- [ ] impl-1.2: Implement logic
- [ ] impl-1.3: OAuth2 integration (new)
- [ ] impl-1.4: Token management (new)
```
### TODO Update Rules
- **Preserve Status**: Keep existing checkbox states [x] or [ ]
- **Add New Items**: New subtasks get [ ] checkbox
- **Mark Changes**: Add (updated), (new), (modified) indicators
- **Remove Items**: Delete subtasks that were removed
- **Update Hierarchy**: Maintain proper indentation structure
### TODO List Sync
If TODO_LIST.md exists, synchronizes:
- New subtasks (with [ ] checkbox)
- Modified tasks (marked as updated)
- Removed subtasks (deleted from list)
## Change Documentation
### Comprehensive Change Log
Every replan generates detailed documentation:
### Change Summary
Generates brief change log with:
- Version increment (1.1 → 1.2)
- Input source and reason
- Key modifications made
- Files updated/created
- Backup location
```markdown
# Task Replan Log: impl-1
*Date: 2025-09-08T14:00:00Z*
*Version: 1.1 → 1.2*
*Input: Direct text - "Add OAuth2 authentication support"*
## Session Updates
## Changes Applied
Updates workflow-session.json with:
- Modified task tracking
- Task count changes (if subtasks added/removed)
- Last modification timestamps
### Task Structure Updates
- **Added Subtasks**:
- impl-1.3: OAuth2 provider integration
- impl-1.4: Token management system
- **Modified Subtasks**:
- impl-1.2: Updated to include OAuth flow integration
- **Removed Subtasks**: None
## Rollback Support
### Context Modifications
- **Requirements**: Added OAuth2 external authentication
- **Scope**: Expanded to include third-party auth integration
- **Acceptance**: Include OAuth2 token validation
- **Dependencies**: No changes
### File System Updates
- **Updated**: .task/impl-1.json (version 1.2)
- **Created**: .task/impl-1.3.json, .task/impl-1.4.json
- **Backed Up**: .task/versions/impl-1-v1.1.json
- **Updated**: IMPL_PLAN.md (task section regenerated)
- **Updated**: TODO_LIST.md (2 new items added)
## Impact Analysis
- **Timeline**: +2 days for OAuth implementation
- **Complexity**: Increased (simple → medium)
- **Agent**: Remains code-developer, may need OAuth expertise
- **Dependencies**: Task impl-2 may need OAuth context
## Related Tasks Affected
- impl-2: May need OAuth integration context
- impl-5: Authentication dependency updated
## Rollback Information
- **Previous Version**: 1.1
- **Backup Location**: .task/versions/impl-1-v1.1.json
- **Rollback Command**: `/task:replan impl-1 --rollback v1.1`
```
## Session State Updates
### Workflow Integration
After task replanning, update session information:
```json
{
"phases": {
"IMPLEMENT": {
"tasks": ["impl-1", "impl-2", "impl-3"],
"completed_tasks": [],
"modified_tasks": {
"impl-1": {
"version": "1.2",
"last_replan": "2025-09-08T14:00:00Z",
"reason": "OAuth2 integration added"
}
},
"task_count": {
"total": 6,
"added_today": 2
}
}
},
"documents": {
"IMPL_PLAN.md": {
"last_updated": "2025-09-08T14:00:00Z",
"updated_sections": ["IMPL-001"]
},
"TODO_LIST.md": {
"last_updated": "2025-09-08T14:00:00Z",
"items_added": 2
}
}
}
```
## Rollback Support (Simple)
### Basic Version Rollback
```bash
/task:replan impl-1 --rollback v1.1
Rollback Analysis:
Current Version: 1.2
Target Version: 1.1
Changes to Revert:
- Remove subtasks: impl-1.3, impl-1.4
- Restore previous context
- Update IMPL_PLAN.md section
- Update TODO_LIST.md structure
Files Affected:
- Restore: .task/impl-1.json from backup
- Remove: .task/impl-1.3.json, .task/impl-1.4.json
- Update: IMPL_PLAN.md, TODO_LIST.md
Rollback to version 1.1:
- Restore task from backup
- Remove new subtasks if any
- Update session stats
Confirm rollback? (y/n): y
Rolling back...
✅ Task impl-1 rolled back to version 1.1
✅ Documents updated
✅ Change log created
✅ Task rolled back to version 1.1
```
## Practical Examples
## Examples
### Example 1: Add Feature with Full Tracking
### Text Input
```bash
/task:replan impl-1 "Add two-factor authentication"
/task:replan impl-1 "Add OAuth2 authentication support"
Loading task impl-1 (current version: 1.2)...
Processing request: "Add two-factor authentication"
Analyzing required changes...
Proposed Changes:
+ Add impl-1.5: Two-factor setup
+ Add impl-1.6: 2FA validation
~ Modify impl-1.2: Include 2FA in auth flow
Processing changes...
Proposed updates:
+ Add OAuth2 integration
+ Update authentication flow
Apply changes? (y/n): y
Executing replan...
Version 1.3 created
Added 2 new subtasks
✓ Modified 1 existing subtask
✓ IMPL_PLAN.md updated
✓ TODO_LIST.md synchronized
✓ Change log saved
Result:
- Task version: 1.2 → 1.3
- Subtasks: 46
- Documents updated: 2
- Backup: .task/versions/impl-1-v1.2.json
✓ Version 1.2 created
Context updated
Backup saved
```
### Example 2: Issue-based Replanning
### File Input
```bash
/task:replan impl-2 --from-issue ISS-001
/task:replan impl-2 requirements.md
Loading issue ISS-001...
Issue: "Database queries too slow - need caching"
Priority: High
Loading requirements.md...
Applying specification changes...
Applying to task impl-2...
Required changes for performance fix:
+ Add impl-2.4: Implement Redis caching
+ Add impl-2.5: Query optimization
~ Modify impl-2.1: Add cache checks
Documents updating:
✓ Task JSON updated (v1.0 → v1.1)
✓ IMPL_PLAN.md section regenerated
✓ TODO_LIST.md: 2 new items added
✓ Issue ISS-001 linked to task
Summary:
Performance improvements added to impl-2
Timeline impact: +1 day for caching setup
```
### Example 3: Interactive Replanning
```bash
/task:replan impl-3 --interactive
Interactive Replan for impl-3: API integration
Current version: 1.0
1. What needs to change? "API spec updated, need webhook support"
2. Add new requirements? "Webhook handling, signature validation"
3. Add subtasks? "y"
- New subtask 1: "Webhook receiver endpoint"
- New subtask 2: "Signature validation"
- Add more? "n"
4. Modify existing subtasks? "n"
5. Update dependencies? "Now depends on impl-1 (auth for webhooks)"
6. Change agent assignment? "n"
Applying interactive changes...
✓ Added 2 subtasks for webhook functionality
✓ Updated dependencies
✓ Context expanded for webhook requirements
✓ Task updated with new requirements
✓ Version 1.1 created
✓ All documents synchronized
Interactive replan complete!
```
## Error Handling
### Input Validation Errors
```bash
# Task not found
❌ Task impl-5 not found in current session
❌ Task impl-5 not found
→ Check task ID with /context
# No input provided
❌ Please specify changes needed for replanning
→ Use descriptive text or --detailed/--interactive
# Task completed
⚠️ Task impl-1 is completed (cannot replan)
→ Create new task for additional work
# File not found
❌ File updated-specs.md not found
→ Check file path and try again
❌ File requirements.md not found
→ Check file path
# No input provided
❌ Please specify changes needed
→ Provide text, file, or issue reference
```
### Document Update Issues
```bash
# Missing IMPL_PLAN.md
⚠️ IMPL_PLAN.md not found in workflow
→ Task update proceeding, plan regeneration skipped
# TODO_LIST.md not writable
⚠️ Cannot update TODO_LIST.md (permissions)
→ Task updated, manual TODO sync needed
# Session conflict
⚠️ Task impl-1 being modified in another session
→ Complete other operation first
```
## Integration Points
### Command Workflow
```bash
# 1. Replan task with new requirements
/task:replan impl-1 "Add advanced security features"
# 2. View updated task structure
/context impl-1
→ Shows new version with changes
# 3. Check updated planning documents
cat IMPL_PLAN.md
→ Task section shows v1.3 with new features
# 4. Verify TODO list synchronization
cat TODO_LIST.md
→ New subtasks appear with [ ] checkboxes
# 5. Execute replanned task
/task:execute impl-1
→ Works with updated task structure
```
### Session Integration
- **Task Count Updates**: Reflect additions/removals in session stats
- **Document Sync**: Keep IMPL_PLAN.md and TODO_LIST.md current
- **Version Tracking**: Complete audit trail in task JSON
- **Change Traceability**: Link replans to input sources
## Related Commands
- `/context` - View task structure and version history
- `/task:execute` - Execute replanned tasks with new structure
- `/workflow:action-plan` - For workflow-wide replanning
- `/task:create` - Create new tasks for additional work
---
**System ensures**: Focused single-task replanning with comprehensive change tracking, document synchronization, and complete audit trail
- `/context` - View updated task structure
- `/task:execute` - Execute replanned task
- `/task:create` - Create new tasks
- `/workflow:action-plan` - For workflow-wide changes

View File

@@ -0,0 +1,197 @@
# Task System Core Reference
## Overview
Task commands provide single-execution workflow capabilities with full context awareness, hierarchical organization, and agent orchestration.
## Task JSON Schema
All task files use this unified 10-field structure:
```json
{
"id": "impl-1",
"title": "Build authentication module",
"status": "pending|active|completed|blocked|container",
"type": "feature|bugfix|refactor|test|docs",
"agent": "code-developer|planning-agent|code-review-test-agent",
"paths": "src/auth;tests/auth;config/auth.json;src/middleware/auth.ts",
"context": {
"requirements": ["JWT authentication", "OAuth2 support"],
"scope": ["src/auth/*", "tests/auth/*"],
"acceptance": ["Module handles JWT tokens", "OAuth2 flow implemented"],
"inherited_from": "WFS-user-auth"
},
"relations": {
"parent": null,
"subtasks": ["impl-1.1", "impl-1.2"],
"dependencies": ["impl-0"]
},
"execution": {
"attempts": 0,
"last_attempt": null
},
"implementation": {
"preparation_complexity": "simple|moderate|complex",
"preparation_tasks": [
"Review existing auth patterns",
"Check JWT library compatibility"
],
"estimated_prep_time": "20min",
"files": [
{
"path": "src/auth/login.ts",
"location": {
"function": "handleLogin",
"lines": "75-120",
"description": "Core login handler function"
},
"original_code": "// Requires gemini analysis for code extraction",
"modifications": {
"current_state": "Basic password validation",
"proposed_changes": [
"Add JWT token generation",
"Integrate OAuth2 flow"
],
"logic_flow": [
"validateInput() ───► checkCredentials()",
"◊─── if valid ───► generateJWT() ───► return token"
],
"reason": "Meet JWT and OAuth2 requirements",
"expected_outcome": "Flexible login system"
}
}
],
"context_notes": {
"dependencies": ["jsonwebtoken", "passport-oauth2"],
"affected_modules": ["user-profile", "session-manager"],
"risks": ["Breaking auth middleware changes"],
"performance_considerations": "JWT adds ~5ms latency",
"error_handling": "No sensitive data in errors"
},
"analysis_source": "manual|gemini|codex|auto-detected"
}
}
```
## Implementation Field Details
### preparation_complexity Assessment
- **simple**: <30min prep, ≤3 files, single module → merge with execution
- **moderate**: Cross-module analysis, 30min-2h → consider separation
- **complex**: Architecture design, >2h, >5 modules → separate preparation
### files Array Structure
- **path**: Specific file path
- **location**: Function/class/line range
- **original_code**: Current code (or "requires gemini analysis")
- **modifications**: Detailed change specification
### context_notes Requirements
- **dependencies**: Required packages
- **affected_modules**: Impact scope
- **risks**: Specific implementation risks
- **performance_considerations**: Performance impact
- **error_handling**: Error handling requirements
### analysis_source Options
- **manual**: User-provided details
- **auto-detected**: System-inferred
- **gemini**: Requires Gemini CLI analysis
- **codex**: Requires Codex CLI analysis
## Hierarchical System
### Task Hierarchy Rules
- **Format**: impl-N (main), impl-N.M (subtasks)
- **Maximum Depth**: 2 levels only
- **Container Tasks**: Parents with subtasks (not executable)
- **Leaf Tasks**: No subtasks (executable)
### Status Rules
- **pending**: Ready for execution
- **active**: Currently being executed
- **completed**: Successfully finished
- **blocked**: Waiting for dependencies
- **container**: Has subtasks (parent only)
## Session Integration
### Active Session Detection
```bash
# Check for active session marker
active_session=$(ls .workflow/.active-* 2>/dev/null | head -1)
```
### Workflow Context Inheritance
Tasks inherit from:
1. `workflow-session.json` - Session metadata
2. Parent task context (for subtasks)
3. `IMPL_PLAN.md` - Planning document
### File Locations
- **Task JSON**: `.workflow/WFS-[topic]/.task/impl-*.json`
- **Session State**: `.workflow/WFS-[topic]/workflow-session.json`
- **Planning Doc**: `.workflow/WFS-[topic]/IMPL_PLAN.md`
- **Progress**: `.workflow/WFS-[topic]/TODO_LIST.md`
## Agent Mapping
### Automatic Agent Selection
- **code-developer**: Implementation tasks, coding
- **planning-agent**: Design, architecture planning
- **code-review-test-agent**: Testing, validation
- **review-agent**: Code review, quality checks
### Agent Context Filtering
Each agent receives tailored context:
- **code-developer**: Complete implementation details
- **planning-agent**: High-level requirements, risks
- **test-agent**: Files to test, logic flows to validate
- **review-agent**: Quality standards, security considerations
## Paths Field Format
### Structure
Semicolon-separated list of concrete paths:
```json
"paths": "src/auth;tests/auth;config/auth.json;src/middleware/auth.ts"
```
### Selection Strategy
- **Directories**: Relevant module directories
- **Specific Files**: Explicitly mentioned files
- **No Wildcards**: Use concrete paths only
- **Focus Scope**: Only task-related paths
## Validation Rules
### Pre-execution Checks
1. Task exists and is valid JSON
2. Task status allows operation
3. Dependencies are met
4. Active workflow session exists
5. Implementation field is complete
### Hierarchy Validation
- Parent-child relationships valid
- Maximum depth not exceeded
- Container tasks have subtasks
- No circular dependencies
## Error Handling Patterns
### Common Errors
- **Task not found**: Check ID format and session
- **Invalid status**: Verify task can be operated on
- **Missing session**: Ensure active workflow exists
- **Max depth exceeded**: Restructure hierarchy
- **Missing implementation**: Complete required fields
### Recovery Strategies
- Session validation with clear guidance
- Automatic ID correction suggestions
- Implementation field completion prompts
- Hierarchy restructuring options