Initial release: Claude Code Workflow (CCW) v2.0

🚀 Revolutionary AI-powered development workflow orchestration system

## 🔥 Core Innovations
- **Document-State Separation**: Markdown for planning, JSON for execution state
- **Progressive Complexity Management**: Level 0-2 adaptive workflow depth
- **5-Agent Orchestration**: Specialized AI agents with context preservation
- **Session-First Architecture**: Auto-discovery and state inheritance

## 🏗️ Key Features
- Intelligent workflow orchestration (Simple/Medium/Complex patterns)
- Real-time document-state synchronization with conflict resolution
- Hierarchical task management with 3-level JSON structure
- Gemini CLI integration with 12+ specialized templates
- Comprehensive file output generation for all workflow commands

## 📦 Installation
Remote one-liner installation:
```
iex (iwr -useb https://raw.githubusercontent.com/catlog22/Claude-CCW/main/install-remote.ps1)
```

## 🎯 System Architecture
4-layer intelligent development architecture:
1. Command Layer - Smart routing and version management
2. Agent Layer - 5 specialized development agents
3. Workflow Layer - Gemini templates and task orchestration
4. Memory Layer - Distributed documentation and auto-sync

🤖 Generated with Claude Code

Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
catlog22
2025-09-07 17:39:54 +08:00
commit 445ac823ba
87 changed files with 19076 additions and 0 deletions

View File

@@ -0,0 +1,428 @@
---
name: workflow-action-plan
description: Action planning phase that integrates brainstorming insights or user input to create executable implementation plans
usage: /workflow:action-plan [--from-brainstorming] [--skip-brainstorming] [--replan] [--trigger=<reason>]
argument-hint: [optional: from brainstorming, skip brainstorming, replan mode, or replan trigger]
examples:
- /workflow:action-plan --from-brainstorming
- /workflow:action-plan --skip-brainstorming "implement OAuth authentication"
- /workflow:action-plan --replan --trigger=requirement-change
- /workflow:action-plan --from-brainstorming --scope=all --strategy=minimal-disruption
---
# Workflow Action Plan Command (/workflow:action-plan)
## Overview
Creates actionable implementation plans based on brainstorming insights or direct user input. Establishes project structure, understands existing workflow context, and generates executable plans with proper task decomposition and resource allocation.
## Core Principles
**System:** @~/.claude/workflows/unified-workflow-system-principles.md
## Input Sources & Planning Approaches
### Brainstorming-Based Planning (--from-brainstorming)
**Prerequisites**: Completed brainstorming session with multi-agent analysis
**Input Sources**:
- `.workflow/WFS-[topic-slug]/.brainstorming/[agent]/analysis.md` files
- `.workflow/WFS-[topic-slug]/.brainstorming/synthesis-analysis.md`
- `.workflow/WFS-[topic-slug]/.brainstorming/recommendations.md`
- `workflow-session.json` brainstorming phase results
### Direct User Input Planning (--skip-brainstorming)
**Prerequisites**: User provides task description and requirements
**Input Sources**:
- User task description and requirements
- Existing project structure analysis
- Session context from workflow-session.json (if exists)
### Session Context Detection
⚠️ **CRITICAL**: Before planning, MUST check for existing active session to avoid creating duplicate sessions.
**Session Check Process:**
1. **Query Session Registry**: Check `.workflow/session_status.jsonl` for active sessions
2. **Session Selection**: Use existing active session or create new one only if none exists
3. **Context Integration**: Load existing session state and brainstorming outputs
```json
{
"session_id": "WFS-[topic-slug]",
"type": "simple|medium|complex",
"current_phase": "PLAN",
"session_source": "existing_active|new_creation",
"brainstorming": {
"status": "completed|skipped",
"output_directory": ".workflow/WFS-[topic-slug]/.brainstorming/",
"insights_available": true|false
}
}
```
### Planning Depth & Document Generation
- **Simple**: Skip detailed planning, generate minimal IMPL_PLAN.md or go direct to IMPLEMENT
- **Medium**: Standard planning with IMPL_PLAN.md generation (1-2 agents)
- **Complex**: Full planning with comprehensive IMPL_PLAN.md (enhanced structure)
## Execution Flow
### Phase 1: Context Understanding & Structure Establishment
1. **Session Detection & Selection**:
- **Check Active Sessions**: Query `.workflow/session_status.jsonl` for existing active sessions
- **Session Priority**: Use existing active session if available, otherwise create new session
- **Session Analysis**: Read and understand workflow-session.json from selected session
- Detect existing brainstorming outputs
- Identify current phase and progress
- Understand project context and requirements
2. **File Structure Assessment**:
- **If brainstorming exists**: Verify `.workflow/WFS-[topic-slug]/.brainstorming/` structure
- **If no structure exists**: Create complete workflow directory structure
- **Document Discovery**: Identify all existing planning documents
3. **Input Source Determination**:
- **From Brainstorming**: Read all agent analyses and synthesis documents
- **Skip Brainstorming**: Collect user requirements and context directly
- **Hybrid**: Combine existing insights with new user input
### Phase 2: Context Integration & Requirements Analysis
4. **Requirements Synthesis**:
- **From Brainstorming**: Integrate multi-agent perspectives and recommendations
- **From User Input**: Analyze and structure user-provided requirements
- **Gap Analysis**: Identify missing information and clarify with user
5. **Complexity Assessment**: Determine planning depth needed based on:
- Scope of requirements (brainstorming insights or user input)
- Technical complexity indicators
- Resource and timeline constraints
- Risk assessment from available information
### Phase 3: Document Generation & Planning
6. **Create Document Directory**: Setup `.workflow/WFS-[topic-slug]/` structure (if needed)
7. **Execute Planning**:
- **Simple**: Minimal documentation, direct to IMPLEMENT
- **Medium**: Generate IMPL_PLAN.md with task breakdown
- **Complex**: Generate comprehensive IMPL_PLAN.md with staged approach and risk assessment
8. **Update Session**: Mark PLAN phase complete with document references
9. **Link Documents**: Update JSON state with generated document paths
## Session State Analysis & Document Understanding
### Workflow Session Discovery
**Command**: `workflow:action-plan` automatically detects and analyzes:
**Session Detection Process**:
1. **Find Active Sessions**: Locate `.workflow/WFS-*/workflow-session.json` files
2. **Session Validation**: Verify session completeness and current phase
3. **Context Extraction**: Read session metadata, progress, and phase outputs
**Session State Analysis**:
```json
{
"session_id": "WFS-user-auth-system",
"current_phase": "PLAN",
"brainstorming": {
"status": "completed",
"agents_completed": ["system-architect", "ui-designer", "security-expert"],
"synthesis_available": true,
"recommendations_count": 12
},
"documents": {
"brainstorming": {
"system-architect/analysis.md": {"status": "available", "insights": ["scalability", "microservices"]},
"synthesis-analysis.md": {"status": "available", "key_themes": ["security-first", "user-experience"]}
}
}
}
```
### Document Intelligence & Content Understanding
**Process**: Action planning reads and interprets existing workflow documents
**Brainstorming Document Analysis**:
- **Agent Analyses**: Extract key insights, recommendations, and constraints from each agent
- **Synthesis Reports**: Understand cross-perspective themes and convergent solutions
- **Recommendation Prioritization**: Identify high-impact, actionable items
- **Context Preservation**: Maintain user requirements and constraints from discussions
**Content Integration Strategy**:
- **Technical Requirements**: From system-architect, data-architect, security-expert analyses
- **User Experience**: From ui-designer, user-researcher perspectives
- **Business Context**: From product-manager, business-analyst insights
- **Implementation Constraints**: From all agent recommendations and user discussions
**Gap Detection**:
- Identify missing technical specifications
- Detect undefined user requirements
- Find unresolved architectural decisions
- Highlight conflicting recommendations requiring resolution
## Output Format
### IMPL_PLAN.md Structure (Enhanced for Action Planning)
```markdown
# Action Implementation Plan
## Context & Requirements
### From Brainstorming Analysis (if --from-brainstorming)
- **Key Insights**: Synthesized from multi-agent perspectives
- **Technical Requirements**: Architecture, security, data considerations
- **User Experience Requirements**: UI/UX design and usability needs
- **Business Requirements**: Product goals, stakeholder priorities, constraints
- **User Discussion Context**: Captured requirements from user interactions
### From User Input (if --skip-brainstorming)
- **User Provided Requirements**: Direct input and specifications
- **Context Analysis**: Interpreted requirements and technical implications
- **Gap Identification**: Areas needing clarification or additional information
## Strategic Approach
- **Implementation Philosophy**: Core principles guiding development
- **Success Metrics**: How progress and completion will be measured
- **Risk Mitigation**: Key risks identified and mitigation strategies
## Task Breakdown
- **IMPL-001**: Foundation/Infrastructure setup
- **IMPL-002**: Core functionality implementation
- **IMPL-003**: Integration and testing
- **IMPL-004**: [Additional tasks based on complexity]
## Dependencies & Sequence
- **Critical Path**: Essential task sequence
- **Parallel Opportunities**: Tasks that can run concurrently
- **External Dependencies**: Third-party integrations or resources needed
## Resource Allocation
- **Technical Resources**: Required skills and expertise
- **Timeline Estimates**: Duration estimates for each phase
- **Quality Gates**: Review and approval checkpoints
## Success Criteria
- **Functional Acceptance**: Core functionality validation
- **Technical Acceptance**: Performance, security, scalability criteria
- **User Acceptance**: Usability and experience validation
```
### Enhanced IMPL_PLAN.md Structure (Complex Workflows)
```markdown
# Implementation Plan - [Project Name]
## Context & Requirements
### From Brainstorming Analysis (if --from-brainstorming)
- **Key Insights**: Synthesized from multi-agent perspectives
- **Technical Requirements**: Architecture, security, data considerations
- **User Experience Requirements**: UI/UX design and usability needs
- **Business Requirements**: Product goals, stakeholder priorities, constraints
- **User Discussion Context**: Captured requirements from user interactions
### From User Input (if --skip-brainstorming)
- **User Provided Requirements**: Direct input and specifications
- **Context Analysis**: Interpreted requirements and technical implications
- **Gap Identification**: Areas needing clarification or additional information
## Strategic Approach
- **Implementation Philosophy**: Core principles guiding development
- **Success Metrics**: How progress and completion will be measured
- **Risk Mitigation**: Key risks identified and mitigation strategies
## Phase Breakdown
### Phase 1: Foundation
- **Objective**: [Core infrastructure/base components]
- **Tasks**: IMPL-001, IMPL-002
- **Duration**: [Estimate]
- **Success Criteria**: [Measurable outcomes]
### Phase 2: Core Implementation
- **Objective**: [Main functionality]
- **Tasks**: IMPL-003, IMPL-004, IMPL-005
- **Duration**: [Estimate]
- **Dependencies**: Phase 1 completion
### Phase 3: Integration & Testing
- **Objective**: [System integration and validation]
- **Tasks**: IMPL-006, IMPL-007
- **Duration**: [Estimate]
## Risk Assessment
- **High Risk**: [Description] - Mitigation: [Strategy]
- **Medium Risk**: [Description] - Mitigation: [Strategy]
## Quality Gates
- Code review requirements
- Testing coverage targets
- Performance benchmarks
- Security validation checks
## Rollback Strategy
- Rollback triggers and procedures
- Data preservation approach
```
## Document Storage
Generated documents are stored in session directory:
```
.workflow/WFS-[topic-slug]/
├── IMPL_PLAN.md # Combined planning document (all complexities)
└── workflow-session.json # Updated with document references
```
## Session Updates
```json
{
"phases": {
"PLAN": {
"status": "completed",
"output": {
"primary": "IMPL_PLAN.md"
},
"documents_generated": ["IMPL_PLAN.md"],
"completed_at": "2025-09-05T11:00:00Z",
"tasks_identified": ["IMPL-001", "IMPL-002", "IMPL-003"]
}
},
"documents": {
"planning": {
"IMPL_PLAN.md": {
"status": "generated",
"path": ".workflow/WFS-[topic-slug]/IMPL_PLAN.md"
}
}
}
}
```
## Complexity Decision Rules
### Document Generation Matrix
| Complexity | IMPL_PLAN.md | Structure | Agent Requirements |
|------------|--------------|-----------|-------------------|
| **Simple** | Optional/Skip | Minimal | Direct to IMPLEMENT |
| **Medium** | Required | Standard | planning-agent |
| **Complex** | Required | Enhanced with phases + risk assessment | planning-agent + detailed analysis |
### Auto-Detection Triggers
Complex planning triggered when:
- Architecture changes required
- Security implementation needed
- Performance optimization planned
- System integration involved
- Estimated effort > 8 hours
- Risk level assessed as high
### Manual Override
```bash
# Force complex planning even for medium tasks
/workflow:action-plan --force-complex
# Force simple planning for quick fixes
/workflow:action-plan --force-simple
```
## Skip Option
```bash
/workflow:action-plan --skip-to-implement
```
- Generates minimal plan
- Immediately transitions to IMPLEMENT
- Useful for urgent fixes
## Replanning Mode
### Usage
```bash
# Basic replanning
/workflow:action-plan --replan --trigger=requirement-change
# Strategic replanning with impact analysis
/workflow:action-plan --replan --trigger=new-issue --scope=all --strategy=minimal-disruption --impact-analysis
# Conflict resolution
/workflow:action-plan --replan --trigger=dependency-conflict --auto-resolve
```
### Replan Parameters
- `--trigger=<reason>` → Replanning trigger: `new-issue|requirement-change|dependency-conflict|optimization`
- `--scope=<scope>` → Scope: `current-phase|all|documents-only|tasks-only`
- `--strategy=<strategy>` → Strategy: `minimal-disruption|optimal-efficiency|risk-minimization|time-optimization`
- `--impact-analysis` → Detailed impact analysis
- `--auto-resolve` → Auto-resolve conflicts
- `--dry-run` → Simulation mode
### Replanning Strategies
#### Minimal Disruption
- Preserve completed tasks
- Minimize impact on active work
- Insert changes optimally
#### Optimal Efficiency
- Re-optimize task order
- Maximize parallelization
- Optimize critical path
#### Risk Minimization
- Prioritize high-risk tasks
- Add buffer time
- Strengthen dependencies
#### Time Optimization
- Focus on core requirements
- Defer non-critical tasks
- Maximize parallel execution
### Integration with Issues
When issues are created, replanning can be automatically triggered:
```bash
# Create issue then replan
/workflow:issue create --type=feature "OAuth2 support"
/workflow:action-plan --replan --trigger=new-issue --issue=ISS-001
```
## Integration with Workflow System
### Action Planning Integration Points
**Prerequisite Commands**:
- `/workflow:session start` → Initialize workflow session
- `/brainstorm` → (Optional) Multi-agent brainstorming phase
**Action Planning Execution**:
- `/workflow:action-plan --from-brainstorming` → Plan from completed brainstorming
- `/workflow:action-plan --skip-brainstorming "task description"` → Plan from user input
- `/workflow:action-plan --replan` → Revise existing plans
**Follow-up Commands**:
- `/workflow:implement` → Execute the action plan
- `/workflow:status` → View current workflow state
- `/task:create` → Create specific implementation tasks
- `/workflow:review` → Validate completed implementation
### Session State Updates
After action planning completion:
```json
{
"current_phase": "IMPLEMENT",
"phases": {
"BRAINSTORM": {"status": "completed|skipped"},
"PLAN": {
"status": "completed",
"input_source": "brainstorming|user_input",
"documents_generated": ["IMPL_PLAN.md"],
"tasks_identified": ["IMPL-001", "IMPL-002", "IMPL-003"],
"complexity_assessed": "simple|medium|complex"
}
}
}
```
### Quality Assurance
**Action Planning Excellence**:
- **Context Integration** → All brainstorming insights or user requirements incorporated
- **Actionable Output** → Plans translate directly to executable tasks
- **Comprehensive Coverage** → Technical, UX, and business considerations included
- **Clear Sequencing** → Dependencies and critical path clearly defined
- **Measurable Success** → Concrete acceptance criteria established
This action planning command bridges brainstorming insights and implementation execution, ensuring comprehensive planning based on multi-perspective analysis or direct user input.

View File

@@ -0,0 +1,509 @@
---
name: brainstorm
description: Multi-perspective brainstorming coordination command that orchestrates multiple agents for comprehensive ideation and solution exploration
usage: /brainstorm <topic|challenge> [--mode=<creative|analytical|strategic>] [--perspectives=<role1,role2,...>] [--execution=<serial|parallel>]
argument-hint: "brainstorming topic or challenge description" [optional: mode, perspectives, execution]
examples:
- /brainstorm "innovative user authentication methods"
- /brainstorm "solving scalability challenges" --mode=analytical
- /brainstorm "redesigning the onboarding experience" --perspectives=ui-designer,user-researcher,product-manager
- /brainstorm "reducing system complexity" --mode=strategic --execution=parallel
allowed-tools: Task(conceptual-planning-agent), TodoWrite(*)
---
### 🚀 **Command Overview: `/brainstorm`**
- **Type**: Coordination Command
- **Purpose**: To orchestrate multiple specialized agents for comprehensive multi-perspective brainstorming on challenges and opportunities.
- **Core Tools**: `Task(conceptual-planning-agent)`, `TodoWrite(*)`
- **Core Principles**: @~/.claude/workflows/core-principles.md
- **Integration Rules**:
- @~/.claude/workflows/brainstorming-principles.md
- @~/.claude/workflows/todowrite-coordination-rules.md
### 🔄 **Overall Brainstorming Protocol**
`Phase 1: Coordination Setup` **->** `Phase 1.5: User Discussion & Validation` **->** `Phase 2: Agent Coordination` **->** `Phase 3: Synthesis & Documentation`
### ⚙️ **Brainstorming Modes**
- **`creative` (Default)**
- **Approach**: Divergent thinking, "what if" scenarios.
- **Agent Selection**: Auto-selects `innovation-lead`, `ui-designer`, `user-researcher`, and a business agent.
- **Execution**: Typically parallel.
- **`analytical`**
- **Approach**: Root cause analysis, data-driven insights.
- **Agent Selection**: Auto-selects `business-analyst`, `data-architect`, `system-architect`, and a domain expert.
- **Execution**: Typically serial.
- **`strategic`**
- **Approach**: Systems thinking, long-term visioning.
- **Agent Selection**: Auto-selects `innovation-lead`, `product-manager`, `business-analyst`, and a technical expert.
- **Execution**: Mixed serial/parallel.
### 🚦 **Execution Patterns**
- **`serial` (Default)**
- **Use Case**: When perspectives need to build on each other.
- **Process**: Agents run one at a time, informed by previous outputs.
- **`parallel`**
- **Use Case**: When diverse, independent perspectives are needed quickly.
- **Process**: All selected agents run simultaneously.
- **`hybrid`**
- **Use Case**: Complex, multi-phase brainstorming.
- **Process**: Combines parallel initial ideation with serial refinement phases.
### 🎭 **Available Perspectives (Agent Roles)**
- `product-manager`: User needs, business value, market positioning.
- `system-architect`: Technical architecture, scalability, integration.
- `ui-designer`: User experience, interface design, usability.
- `data-architect`: Data flow, storage, analytics, insights.
- `security-expert`: Security implications, threat modeling, compliance.
- `user-researcher`: User behavior, pain points, research insights.
- `business-analyst`: Process optimization, efficiency, ROI.
- `innovation-lead`: Emerging trends, disruptive technologies, opportunities.
- `feature-planner`: Feature planning and development strategy.
- `test-strategist`: Testing strategy and quality assurance.
### 🤖 **Agent Selection & Loading Logic**
This logic determines which agents participate in the brainstorming session.
```pseudo
FUNCTION select_agents(mode, perspectives_arg):
IF perspectives_arg is provided:
// User explicitly defines roles via --perspectives flag
RETURN perspectives_arg.split(',')
ELSE:
// Automatic selection based on mode or topic analysis
CASE topic_type:
WHEN "Technical Challenge":
selected = ["system-architect", "security-expert"]
IF topic is data_heavy: ADD "data-architect"
RETURN selected
WHEN "User-Facing Feature":
RETURN ["ui-designer", "user-researcher", "product-manager"]
WHEN "Business Process":
RETURN ["business-analyst", "product-manager"]
WHEN "Innovation/Strategy":
RETURN ["innovation-lead", "product-manager"]
DEFAULT:
// Fallback to mode-based selection
CASE mode:
WHEN "creative": RETURN ["innovation-lead", "ui-designer", "user-researcher", ...]
WHEN "analytical": RETURN ["business-analyst", "data-architect", "system-architect", ...]
WHEN "strategic": RETURN ["innovation-lead", "product-manager", "business-analyst", ...]
END CASE
END CASE
END IF
END FUNCTION
FUNCTION load_agent_role(role_name):
// Dynamically loads role capabilities using the specified shell script
execute_tool("Bash", "~/.claude/scripts/plan-executor.sh " + role_name)
END FUNCTION
```
### 🏗️ **Phase 1: Coordination Setup Protocol**
⚠️ **CRITICAL**: Before brainstorming, MUST check for existing active session to avoid creating duplicate sessions.
**Session Check Process:**
1. **Query Session Registry**: Check `.workflow/session_status.jsonl` for active sessions
2. **Session Selection**: Use existing active session or create new one only if none exists
3. **Context Integration**: Load existing session state and continue brainstorming phase
`Check Active Session` **->** `Generate Topic Slug (WFS-[topic-slug]) if needed` **->** `Create Project Directories (.workflow/WFS-[slug]/.brainstorming/{agent1}, {agent2}, ...)` **->** `Initialize/Update session-state.json` **->** `Verify Structure` **->** `Initialize TodoWrite`
### 📝 **Initial TodoWrite Structure (Template)**
This `TodoWrite` call establishes the complete workflow plan at the beginning of the session.
```
TodoWrite([
{"content": "Establish project structure and initialize session", "status": "completed", "activeForm": "Establishing project structure"},
{"content": "Set up brainstorming session and select perspectives", "status": "in_progress", "activeForm": "Setting up brainstorming session"},
{"content": "Discuss [agent1] scope and gather user requirements", "status": "pending", "activeForm": "Discussing [agent1] requirements with user"},
{"content": "Coordinate [selected_agent1] perspective analysis", "status": "pending", "activeForm": "Coordinating [agent1] perspective"},
{"content": "Discuss [agent2] scope and gather user requirements", "status": "pending", "activeForm": "Discussing [agent2] requirements with user"},
{"content": "Coordinate [selected_agent2] perspective analysis", "status": "pending", "activeForm": "Coordinating [agent2] perspective"},
{"content": "Discuss [agent3] scope and gather user requirements", "status": "pending", "activeForm": "Discussing [agent3] requirements with user"},
{"content": "Coordinate [selected_agent3] perspective analysis", "status": "pending", "activeForm": "Coordinating [agent3] perspective"},
{"content": "Synthesize multi-perspective insights", "status": "pending", "activeForm": "Synthesizing insights"},
{"content": "Generate prioritized recommendations", "status": "pending", "activeForm": "Generating recommendations"},
{"content": "Create comprehensive brainstorming documentation", "status": "pending", "activeForm": "Creating documentation"}
])
```
### 💬 **Phase 1.5: Mandatory User Discussion Protocol**
This validation loop is **required** before *each* agent is executed.
```pseudo
FUNCTION validate_and_run_agents(selected_agents):
FOR EACH agent in selected_agents:
// Update the task list to show which discussion is active
update_todowrite("Discuss " + agent + " scope", "in_progress") // Corresponds to TodoWrite(*) tool
present_agent_scope(agent)
user_context = ask_context_questions(agent) // Example questions in next card
present_task_roadmap(agent)
LOOP:
user_response = get_user_input("Ready to proceed with " + agent + " analysis?")
IF user_response is "Yes, proceed" or similar:
// User has given explicit approval
update_todowrite("Discuss " + agent + " scope", "completed") // Corresponds to TodoWrite(*)
execute_agent_task(agent, user_context) // Proceeds to Phase 2 for this agent
BREAK
ELSE IF user_response is "No", "Wait", or requests changes:
// User has feedback, revise the plan
revise_approach(user_feedback)
present_task_roadmap(agent) // Re-present the revised plan
END IF
END LOOP
END FOR
END FUNCTION
```
### ❓ **User Discussion Question Templates**
- **System Architect**: Technical constraints? Integrations? Scalability needs?
- **UI Designer**: Primary users? Usability challenges? Brand guidelines? Accessibility?
- **Product Manager**: Business goals? Key stakeholders? Market factors? Success metrics?
- **Data Architect**: Data sources? Privacy/compliance? Quality challenges?
- **Security Expert**: Threat models? Compliance needs (GDPR, etc.)? Security level?
### 🧠 **Phase 2: Agent Coordination Logic**
This logic executes after user approval for each agent.
```pseudo
FUNCTION execute_agent_task(agent, user_context):
update_todowrite("Coordinate " + agent + " perspective", "in_progress") // Corresponds to TodoWrite(*) tool
// This action corresponds to calling the allowed tool: Task(conceptual-planning-agent)
// The specific prompt templates are provided in the source documentation.
status = execute_tool("Task(conceptual-planning-agent)", agent, user_context)
IF status is 'SUCCESS':
update_todowrite("Coordinate " + agent + " perspective", "completed")
ELSE:
// Handle potential agent execution failure
log_error("Agent " + agent + " failed.")
HALT_WORKFLOW()
END IF
END FUNCTION
```
### 📋 **Agent Execution Task Templates (Serial & Parallel)**
These templates show the exact structure of the `Task(conceptual-planning-agent)` call.
- **For Serial Execution (one agent at a time):**
```
Task(conceptual-planning-agent): "Conduct brainstorming analysis for: [topic]. Use [mode] brainstorming approach. Required perspective: [agent1].
Load role definition using: ~/.claude/scripts/plan-executor.sh [agent1]
USER CONTEXT FROM DISCUSSION:
- Specific focus areas: [user_specified_challenges_goals]
- Constraints and requirements: [user_specified_constraints]
- Expected outcomes: [user_expected_outcomes]
- Additional user requirements: [other_user_inputs]
OUTPUT REQUIREMENT: Save all generated documents to: .workflow/WFS-[topic-slug]/.brainstorming/[agent1]/
- analysis.md (main perspective analysis incorporating user context)
- [agent1-specific-output].md (specialized deliverable addressing user requirements)
Apply the returned planning template and generate comprehensive analysis from this perspective, ensuring all user-specified requirements and context are fully incorporated."
```
- **For Parallel Execution (multiple agents at once):**
```
Task(conceptual-planning-agent): "Conduct multi-perspective brainstorming analysis for: [topic]. Use [mode] brainstorming approach. Required perspectives: [agent1, agent2, agent3].
For each perspective, follow this protocol:
1. Load role definition using: ~/.claude/scripts/plan-executor.sh [role]
2. Incorporate user discussion context for each agent:
- [Agent1]: Focus areas: [user_input_agent1], Constraints: [constraints_agent1], Expected outcomes: [outcomes_agent1]
- [Agent2]: Focus areas: [user_input_agent2], Constraints: [constraints_agent2], Expected outcomes: [outcomes_agent2]
- [Agent3]: Focus areas: [user_input_agent3], Constraints: [constraints_agent3], Expected outcomes: [outcomes_agent3]
3. OUTPUT REQUIREMENT: Save documents to: .workflow/WFS-[topic-slug]/.brainstorming/[role]/
- analysis.md (main perspective analysis incorporating user context)
- [role-specific-output].md (specialized deliverable addressing user requirements)
Apply all perspectives in parallel analysis, ensuring each agent's output incorporates their specific user discussion context and is saved to their designated directory."
```
### 🏁 **Phase 3: Synthesis & Documentation Flow**
`Integrate All Agent Insights` **->** `Prioritize Solutions (by feasibility & impact)` **->** `Generate Comprehensive Summary Document` **->** `Mark All Todos as 'completed'`
### ✅ **Core Principles & Quality Standards**
- **User-Driven Process**: Every agent execution **must** be preceded by user discussion and explicit approval.
- **Context Integration**: All user inputs (focus areas, constraints, goals) must be fully incorporated into agent analysis.
- **`TodoWrite` First**: A `TodoWrite` plan must be established before any agent coordination begins.
- **Single Active Task**: Only one `TodoWrite` item should be marked `"in_progress"` at any time.
- **Transparent & Flexible**: The user understands what each agent will do and can provide feedback to revise the plan.
### 📄 **Synthesis Output Structure**
A guide for the final comprehensive report generated at the end of the workflow.
- **Session Summary**:
- Coordination approach (serial/parallel)
- Agent perspectives involved
- Brainstorming mode applied
- **Individual Agent Insights**:
- Summary of each agent's analysis.
- Note areas of agreement or disagreement.
- **Cross-Perspective Synthesis**:
- Identify convergent themes and breakthrough ideas.
- **Actionable Recommendations**:
- Categorize actions (immediate, strategic, research).
- **Implementation Guidance**:
- Suggested phases, resource needs, success metrics.
## 📁 **File Generation System**
### Automatic File Generation
Every brainstorming session generates a comprehensive set of structured output files:
#### Generated File Structure
```
.workflow/WFS-[topic-slug]/.brainstorming/
├── synthesis-analysis.md # Cross-perspective analysis
├── recommendations.md # Actionable recommendations
├── brainstorm-session.json # Session metadata
├── [agent1]/ # Individual agent outputs
│ ├── analysis.md # Main perspective analysis
│ └── [specific-deliverable].md # Agent-specific outputs
├── [agent2]/
│ ├── analysis.md
│ └── [specific-deliverable].md
└── artifacts/ # Supporting materials
├── user-context.md # Captured user discussion
├── session-transcript.md # Brainstorming session log
└── export/ # Export formats
├── brainstorm-summary.pdf
└── recommendations.json
```
### Core Output Documents
#### 1. synthesis-analysis.md
Cross-perspective synthesis of all agent insights:
```markdown
# Brainstorming Synthesis Analysis
*Session: WFS-[topic-slug] | Generated: 2025-09-07 16:00:00*
## Session Overview
- **Topic**: [brainstorming topic]
- **Mode**: [creative|analytical|strategic]
- **Execution**: [serial|parallel]
- **Participants**: [list of agent roles]
- **Duration**: [session duration]
## Individual Agent Insights Summary
### 🎨 UI Designer Perspective
**Focus Areas**: User experience, interface design, usability
**Key Insights**:
- Modern, intuitive design approach
- Mobile-first considerations
- Accessibility requirements
**Recommendations**: [specific design recommendations]
### 🏗️ System Architect Perspective
**Focus Areas**: Technical architecture, scalability, integration
**Key Insights**:
- Microservices architecture benefits
- Database optimization strategies
- Security considerations
**Recommendations**: [specific technical recommendations]
[Additional agent perspectives...]
## Cross-Perspective Analysis
### Convergent Themes
1. **User-Centric Approach**: All agents emphasized user experience priority
2. **Scalability Focus**: Common concern for system growth capacity
3. **Security Integration**: Unanimous priority on security-by-design
### Breakthrough Ideas
1. **Unified Authentication System**: Cross-platform identity management
2. **Progressive Web App**: Mobile and desktop feature parity
3. **AI-Powered Analytics**: Smart user behavior insights
### Areas of Disagreement
1. **Technology Stack**: [description of disagreement and perspectives]
2. **Implementation Timeline**: [varying estimates and approaches]
## Strategic Synthesis
[Integrated analysis combining all perspectives into coherent strategy]
---
*Generated by /brainstorm synthesis phase*
```
#### 2. recommendations.md
Actionable recommendations categorized by priority and scope:
```markdown
# Brainstorming Recommendations
*Session: WFS-[topic-slug] | Generated: 2025-09-07 16:15:00*
## Executive Summary
[High-level summary of key recommendations]
## Immediate Actions (0-2 weeks)
### High Priority - Critical
- **REC-001**: [Recommendation title]
- **Context**: [Background and rationale]
- **Action**: [Specific steps to take]
- **Resources**: [Required resources/skills]
- **Impact**: [Expected outcomes]
- **Owner**: [Suggested responsible party]
### Medium Priority - Important
- **REC-002**: [Recommendation title]
[Same structure as above]
## Strategic Actions (2-8 weeks)
### Architecture & Infrastructure
- **REC-003**: [Technical improvements]
- **REC-004**: [System optimizations]
### User Experience & Design
- **REC-005**: [UX improvements]
- **REC-006**: [Design system updates]
## Research Actions (Future Investigation)
### Technical Research
- **REC-007**: [Emerging technology evaluation]
- **REC-008**: [Performance optimization study]
### Market Research
- **REC-009**: [User behavior analysis]
- **REC-010**: [Competitive analysis]
## Implementation Roadmap
### Phase 1: Foundation (Weeks 1-2)
- Execute REC-001, REC-002
- Establish core infrastructure
### Phase 2: Development (Weeks 3-6)
- Implement REC-003, REC-004, REC-005
- Build core features
### Phase 3: Enhancement (Weeks 7-8)
- Deploy REC-006
- Optimize and refine
## Success Metrics
- [Quantifiable measures of success]
- [Key performance indicators]
## Risk Assessment
- [Potential obstacles and mitigation strategies]
---
*Generated by /brainstorm recommendations synthesis*
```
#### 3. brainstorm-session.json
Session metadata and tracking:
```json
{
"session_id": "WFS-[topic-slug]",
"brainstorm_id": "BRM-2025-09-07-001",
"topic": "[brainstorming topic]",
"mode": "creative",
"execution": "parallel",
"created_at": "2025-09-07T15:30:00Z",
"completed_at": "2025-09-07T16:30:00Z",
"duration_minutes": 60,
"participants": {
"agents": ["ui-designer", "system-architect", "product-manager"],
"user_interaction": true
},
"outputs": {
"agent_analyses": {
"ui-designer": {
"analysis_path": ".brainstorming/ui-designer/analysis.md",
"deliverable_path": ".brainstorming/ui-designer/design-mockups.md",
"completed_at": "2025-09-07T15:50:00Z"
},
"system-architect": {
"analysis_path": ".brainstorming/system-architect/analysis.md",
"deliverable_path": ".brainstorming/system-architect/architecture-proposal.md",
"completed_at": "2025-09-07T15:55:00Z"
},
"product-manager": {
"analysis_path": ".brainstorming/product-manager/analysis.md",
"deliverable_path": ".brainstorming/product-manager/feature-roadmap.md",
"completed_at": "2025-09-07T16:00:00Z"
}
},
"synthesis": {
"analysis_path": "synthesis-analysis.md",
"recommendations_path": "recommendations.md",
"completed_at": "2025-09-07T16:30:00Z"
}
},
"user_context": {
"focus_areas": "[captured from user discussion]",
"constraints": "[user-specified limitations]",
"expected_outcomes": "[user goals and expectations]"
},
"metrics": {
"insights_generated": 24,
"recommendations_count": 10,
"breakthrough_ideas": 3,
"consensus_areas": 3,
"disagreement_areas": 2
}
}
```
### Session Integration
After brainstorming completion, the main workflow-session.json is updated:
```json
{
"phases": {
"BRAINSTORM": {
"status": "completed",
"completed_at": "2025-09-07T16:30:00Z",
"output_directory": ".workflow/WFS-[topic-slug]/.brainstorming/",
"documents_generated": [
"synthesis-analysis.md",
"recommendations.md",
"brainstorm-session.json"
],
"agents_participated": ["ui-designer", "system-architect", "product-manager"],
"insights_available": true
}
},
"documents": {
"brainstorming": {
"synthesis-analysis.md": {
"status": "generated",
"path": ".workflow/WFS-[topic-slug]/.brainstorming/synthesis-analysis.md",
"generated_at": "2025-09-07T16:30:00Z",
"type": "synthesis_analysis"
},
"recommendations.md": {
"status": "generated",
"path": ".workflow/WFS-[topic-slug]/.brainstorming/recommendations.md",
"generated_at": "2025-09-07T16:30:00Z",
"type": "actionable_recommendations"
}
}
}
}
```
### Export and Integration Features
- **PDF Export**: Automatic generation of consolidated brainstorming report
- **JSON Export**: Machine-readable recommendations for integration tools
- **Action Plan Integration**: Direct feeding into `/workflow:action-plan --from-brainstorming`
- **Cross-Referencing**: Links to specific agent insights from synthesis documents

View File

@@ -0,0 +1,398 @@
---
name: workflow-context
description: Unified workflow context analysis and status overview with file export capabilities
usage: /workflow:context [--detailed] [--health-check] [--format=<tree|json|summary>] [--export]
argument-hint: Optional flags for analysis depth, output format, and file export
examples:
- /workflow:context
- /workflow:context --detailed
- /workflow:context --health-check
- /workflow:context --format=tree
- /workflow:context --detailed --export
- /workflow:context --health-check --export
---
# Workflow Context Command (/workflow:context)
## Overview
Unified workflow context analysis command providing comprehensive state analysis and quick overview of current work status.
## Core Principles
**System:** @~/.claude/workflows/unified-workflow-system-principles.md
## Features
### Core Functionality
- **Real-time Status Snapshot** → Complete workflow state display
- **Task Progress Overview** → Completed, active, pending task statistics
- **Document Health Check** → Document consistency and completeness analysis
- **Dependency Analysis** → Task dependency and conflict identification
- **Time Estimation** → Completion time prediction based on current progress
### Advanced Analysis
- **Blocker Identification** → Automatic detection of progress obstacles
- **Priority Recommendations** → Next action suggestions based on dependencies
- **Risk Assessment** → Execution risk evaluation for current plan
## Core Principles
**System:** @~/.claude/workflows/unified-workflow-system-principles.md
## Display Modes
### Summary View (/workflow:context)
```
🔍 Workflow Status Overview
========================
📋 Session Information:
- Session ID: WFS-2025-001
- Current Phase: Implementation
- Start Time: 2025-01-15 09:30:00
- Duration: 2h 45m
📊 Task Progress:
✅ Completed: 9/15 (60%)
🔄 In Progress: 2 tasks
⏳ Pending: 4 tasks
🚫 Blocked: 0 tasks
📁 Document Status:
✅ IMPL_PLAN.md - Healthy
✅ TODO_LIST.md - Healthy
⚠️ TODO_CHECKLIST.md - Needs sync
❌ WORKFLOW_ISSUES.md - Missing
⏱️ Estimated Completion: 2025-01-15 16:45 (4h 15m remaining)
🎯 Next Steps:
1. Complete current API endpoint implementation
2. Update TODO_CHECKLIST.md status
3. Start frontend user interface development
```
### Detailed View (/workflow:context --detailed)
```
🔍 Detailed Workflow Analysis
========================
📋 Session Details:
Session ID: WFS-2025-001
Workflow Type: Complex
Main Task: "Implement OAuth2 User Authentication System"
📊 Detailed Progress Analysis:
✅ Completed Tasks (9):
- [PLAN-001] Requirements analysis and architecture design
- [PLAN-002] Database model design
- [IMPL-001] User model implementation
- [IMPL-002] JWT token service
- [IMPL-003] Password encryption service
- [TEST-001] Unit tests - User model
- [TEST-002] Unit tests - JWT service
- [DOC-001] API documentation - Auth endpoints
- [DOC-002] Database migration documentation
🔄 In Progress Tasks (2):
- [IMPL-004] OAuth2 provider integration (70% complete)
↳ Dependencies: [PLAN-002], [IMPL-001]
↳ Estimated remaining: 1.5h
- [TEST-003] Integration tests - OAuth flow (30% complete)
↳ Dependencies: [IMPL-004]
↳ Estimated remaining: 2h
⏳ Pending Tasks (4):
- [IMPL-005] Frontend login interface
- [IMPL-006] Session management middleware
- [TEST-004] End-to-end testing
- [DOC-003] User documentation
📁 Document Health Analysis:
✅ IMPL_PLAN.md:
- Status: Healthy
- Last updated: 2025-01-15 10:15
- Coverage: 100% (all tasks defined)
✅ TODO_LIST.md:
- Status: Healthy
- Progress tracking: 15 tasks, 4 levels
- Dependencies: Verified
⚠️ TODO_CHECKLIST.md:
- Status: Needs sync
- Issue: 3 completed tasks not marked
- Recommendation: Run /workflow:sync
🔗 Dependency Analysis:
Critical Path:
[IMPL-004] → [TEST-003] → [IMPL-005] → [TEST-004]
Potential Blockers:
❌ No blockers detected
Parallel Execution Suggestions:
- [IMPL-005] can start immediately after [TEST-003] completes
- [DOC-003] can run in parallel with [IMPL-006]
⚠️ Risk Assessment:
🟢 Low Risk (Current Status)
- OAuth2 integration progressing as expected
- All tests passing
- No technical debt accumulation
Potential Risks:
- Frontend interface design not finalized (Impact: Medium)
- Third-party OAuth service dependency (Impact: Low)
```
### Tree Format (/workflow:context --format=tree)
```
📁 WFS-2025-001: User Authentication
├── 📋 PLAN [Completed]
│ └── Output: IMPL_PLAN.md
├── 🔨 IMPLEMENT [Active - 45%]
│ ├── ✅ IMPL-001: Authentication
│ ├── ✅ IMPL-002: Database
│ ├── ✅ IMPL-003: JWT
│ ├── 🔄 IMPL-004: OAuth2 (70%)
│ ├── ⏳ IMPL-005: Testing
│ ├── 🚫 IMPL-006: Integration
│ └── ⏳ IMPL-007: Documentation
└── 📝 REVIEW [Pending]
```
### JSON Format (/workflow:context --format=json)
Returns merged workflow-session.json + task data for programmatic access.
## File Export Feature
### Export Mode (/workflow:context --export)
When `--export` flag is used, generates persistent status report files in addition to console output.
#### Generated Files
**Status Report Generation:**
- **Standard Mode**: Creates `reports/STATUS_REPORT.md`
- **Detailed Mode**: Creates `reports/DETAILED_STATUS_REPORT.md`
- **Health Check Mode**: Creates `reports/HEALTH_CHECK.md`
#### File Storage Location
```
.workflow/WFS-[topic-slug]/reports/
├── STATUS_REPORT.md # Standard context export
├── DETAILED_STATUS_REPORT.md # Detailed context export
├── HEALTH_CHECK.md # Health check export
└── context-exports/ # Historical exports
├── status-2025-09-07-14-30.md
├── detailed-2025-09-07-15-45.md
└── health-2025-09-07-16-15.md
```
#### Export File Structure
**STATUS_REPORT.md Format:**
```markdown
# Workflow Status Report
*Generated: 2025-09-07 14:30:00*
## Session Information
- **Session ID**: WFS-2025-001
- **Current Phase**: Implementation
- **Start Time**: 2025-01-15 09:30:00
- **Duration**: 2h 45m
## Task Progress Summary
- **Completed**: 9/15 (60%)
- **In Progress**: 2 tasks
- **Pending**: 4 tasks
- **Blocked**: 0 tasks
## Document Status
- ✅ IMPL_PLAN.md - Healthy
- ✅ TODO_LIST.md - Healthy
- ⚠️ TODO_CHECKLIST.md - Needs sync
- ❌ WORKFLOW_ISSUES.md - Missing
## Time Estimation
- **Estimated Completion**: 2025-01-15 16:45
- **Remaining Time**: 4h 15m
## Next Steps
1. Complete current API endpoint implementation
2. Update TODO_CHECKLIST.md status
3. Start frontend user interface development
---
*Report generated by /workflow:context --export*
```
**HEALTH_CHECK.md Format:**
```markdown
# Workflow Health Check Report
*Generated: 2025-09-07 16:15:00*
## Overall Health Score: 85/100 (Good)
## System Health Analysis
### ✅ Session State Check
- **workflow-session.json**: Exists and valid
- **Backup files**: 3 backups available
- **Data integrity**: Verified
### 📋 Document Consistency Check
- **IMPL_PLAN.md ↔ TODO_LIST.md**: ✅ 100% consistency
- **TODO_CHECKLIST.md ↔ TodoWrite status**: ⚠️ 80% (3 items out of sync)
- **WORKFLOW_ISSUES.md**: ❌ Missing file
### 🔄 Progress Tracking Health
- **TodoWrite integration**: ✅ Running normally
- **Timestamp recording**: ✅ Complete
- **Progress estimation**: ⚠️ 85% accuracy
## Recommendations
### Immediate Actions
1. Run /workflow:sync to sync document status
2. Execute /workflow:issue create to establish issue tracking
### Planned Actions
3. Consider creating more checkpoints to improve recovery capability
4. Optimize dependencies to reduce critical path length
## Detailed Analysis
[Detailed health metrics and analysis...]
---
*Health check generated by /workflow:context --health-check --export*
```
#### Session Updates
When files are exported, the workflow-session.json is updated:
```json
{
"documents": {
"reports": {
"STATUS_REPORT.md": {
"status": "generated",
"path": ".workflow/WFS-[topic-slug]/reports/STATUS_REPORT.md",
"generated_at": "2025-09-07T14:30:00Z",
"type": "status_report"
},
"HEALTH_CHECK.md": {
"status": "generated",
"path": ".workflow/WFS-[topic-slug]/reports/HEALTH_CHECK.md",
"generated_at": "2025-09-07T16:15:00Z",
"type": "health_check"
}
}
},
"export_history": [
{
"type": "status_report",
"timestamp": "2025-09-07T14:30:00Z",
"file": "reports/STATUS_REPORT.md"
}
]
}
```
#### Historical Exports
- **Automatic archiving**: Previous exports moved to `context-exports/` with timestamps
- **Retention policy**: Keep last 10 exports of each type
- **Cross-referencing**: Links to historical data in current reports
### Health Check Mode (/workflow:context --health-check)
```
🏥 Workflow Health Diagnosis
========================
✅ Session State Check:
- workflow-session.json: Exists and valid
- Backup files: 3 backups available
- Data integrity: Verified
📋 Document Consistency Check:
✅ IMPL_PLAN.md ↔ TODO_LIST.md
- Task definition consistency: ✅ 100%
- Progress synchronization: ✅ 100%
⚠️ TODO_CHECKLIST.md ↔ TodoWrite status
- Sync status: ❌ 80% (3 items out of sync)
- Recommended action: Run /workflow:sync
❌ WORKFLOW_ISSUES.md
- Status: File does not exist
- Recommendation: Create issue tracking document
🔄 Progress Tracking Health:
✅ TodoWrite integration: Running normally
✅ Timestamp recording: Complete
⚠️ Progress estimation: Based on historical data, 85% accuracy
🔧 System Recommendations:
Immediate Actions:
1. Run /workflow:sync to sync document status
2. Execute /workflow:issue create to establish issue tracking
Planned Actions:
3. Consider creating more checkpoints to improve recovery capability
4. Optimize dependencies to reduce critical path length
🎯 Overall Health Score: 85/100 (Good)
```
## Use Cases
### Case 1: Work Recovery
User returns after interrupting work and needs quick status understanding:
```bash
/workflow:context
# Get quick overview, understand progress and next actions
```
### Case 2: Status Reporting
Need to report project progress to team or management:
```bash
/workflow:context --detailed
# Get detailed progress analysis and estimates
```
### Case 3: Problem Diagnosis
Workflow shows anomalies and needs problem diagnosis:
```bash
/workflow:context --health-check
# Comprehensive health check and repair recommendations
```
### Case 4: Pre-change Assessment
Before adding new requirements or modifying plans, assess current state:
```bash
/workflow:context --detailed --health-check
# Complete status analysis to inform change decisions
```
## Technical Implementation
### Data Source Integration
- **workflow-session.json** - Session state and history
- **TodoWrite status** - Real-time task progress
- **Document analysis** - Workflow-related document parsing
- **Git status** - Code repository change tracking
### Intelligent Analysis Algorithms
- **Dependency graph construction** - Auto-build dependency graphs from task definitions
- **Critical path algorithm** - Identify key task sequences affecting overall progress
- **Health scoring** - Multi-dimensional workflow state health assessment
- **Time estimation model** - Intelligent estimation based on historical data and current progress
### Caching and Performance Optimization
- **Status caching** - Cache computationally intensive analysis results
- **Incremental updates** - Only recalculate changed portions
- **Asynchronous analysis** - Background execution of complex analysis tasks

View File

@@ -0,0 +1,345 @@
---
name: workflow-implement
description: Implementation phase with simple, medium, and complex execution modes
usage: /workflow:implement [--type=<simple|medium|complex>] [--auto-create-tasks]
argument-hint: [optional: complexity type and auto-create]
examples:
- /workflow:implement
- /workflow:implement --type=simple
- /workflow:implement --type=complex --auto-create-tasks
---
# Workflow Implement Command (/workflow:implement)
## Overview
Executes implementation phase with three complexity modes (simple/medium/complex), replacing separate complexity commands.
## Core Principles
**Session Management:** @~/.claude/workflows/session-management-principles.md
## Complexity Modes
### Simple Mode (Single file, bug fixes)
```bash
/workflow:implement --type=simple
```
**Agent Flow:** code-developer → code-review-agent
**TodoWrite:** 3-4 items
**Documents:** TODO_LIST.md + IMPLEMENTATION_LOG.md (auto-generated)
- Streamlined planning, direct implementation
- Quick review cycle
- < 2 hours effort
### Medium Mode (Multi-file features)
```bash
/workflow:implement --type=medium
```
**Agent Flow:** planning-agent → code-developer → code-review-agent
**TodoWrite:** 5-7 items
**Documents:** IMPL_PLAN.md + TODO_LIST.md (auto-triggered)
- Structured planning with hierarchical JSON task decomposition
- Test-driven development
- Comprehensive review
- 2-8 hours effort
### Complex Mode (System-level changes)
```bash
/workflow:implement --type=complex
```
**Agent Flow:** planning-agent → code-developer → code-review-agent → iterate
**TodoWrite:** 7-10 items
**Documents:** IMPL_PLAN.md + TODO_LIST.md (mandatory)
- Detailed planning with mandatory 3-level JSON task hierarchy
- Risk assessment and quality gates
- Multi-faceted review with multiple iterations
- > 8 hours effort
## Execution Flow
1. **Detect Complexity** (if not specified)
- Read from workflow-session.json
- Auto-detect from task description
- Default to medium if unclear
2. **Initialize Based on Complexity**
**Simple:**
- Use existing IMPL_PLAN.md (minimal updates)
- Direct JSON task creation (impl-*.json)
- Minimal state tracking
**Medium:**
- Update IMPL_PLAN.md with implementation strategy
- Auto-trigger TODO_LIST.md creation
- Create hierarchical JSON tasks (impl-*.*.json up to 2 levels)
- Standard agent flow
**Complex:**
- Comprehensive IMPL_PLAN.md with risk assessment
- Mandatory TODO_LIST.md with progress tracking
- Full 3-level JSON task hierarchy (impl-*.*.*.json)
- Full iteration support with cross-document synchronization
3. **Update Session**
```json
{
"current_phase": "IMPLEMENT",
"type": "simple|medium|complex",
"phases": {
"IMPLEMENT": {
"status": "active",
"complexity": "simple|medium|complex",
"agent_flow": [...],
"todos": [...],
"tasks": ["impl-1", "impl-2", "impl-3"],
"progress": 0,
"documents_generated": ["TODO_LIST.md", "IMPLEMENTATION_LOG.md"],
"documents_updated": ["IMPL_PLAN.md"]
}
},
"documents": {
"IMPL_PLAN.md": {
"status": "updated",
"path": ".workflow/WFS-[topic-slug]/IMPL_PLAN.md",
"last_updated": "2025-09-05T10:30:00Z"
},
"TODO_LIST.md": {
"status": "generated",
"path": ".workflow/WFS-[topic-slug]/TODO_LIST.md",
"last_updated": "2025-09-05T11:20:00Z",
"type": "task_tracking"
},
"IMPLEMENTATION_LOG.md": {
"status": "generated",
"path": ".workflow/WFS-[topic-slug]/IMPLEMENTATION_LOG.md",
"last_updated": "2025-09-05T11:20:00Z",
"type": "execution_log",
"auto_update": true
}
},
"task_system": {
"max_depth": 3,
"task_count": {
"main_tasks": 3,
"total_tasks": 8
}
}
}
```
4. **Execute Agent Flow**
- Create TodoWrite entries
- Execute agents based on complexity
- Track checkpoints
- Support pause/resume
## Document Generation Rules
### Decomposition Triggers (Medium Workflows)
Task decomposition documents generated when ANY condition met:
- Task involves >3 modules/components
- >5 distinct subtasks identified
- Complex interdependencies detected
- Estimated effort >4 hours
- Cross-team coordination required
### Mandatory Generation (Complex Workflows)
Always generates complete document suite:
- **Enhanced IMPL_PLAN.md structure** - Hierarchical task breakdown integrated into main plan
- **TODO_LIST.md** - Progress tracking with cross-links
- Links to existing IMPL_PLAN.md from planning phase
### Document-JSON Synchronization
- **Document Creation** → Update workflow session with document references
- **Task Status Changes** → Update TODO_LIST.md progress
- **Task Completion** → Mark items complete in checklist
- **New Tasks Added** → Add to both JSON and enhanced implementation plan
### Document Storage Structure
```
.workflow/WFS-[topic-slug]/
├── IMPL_PLAN.md # From planning phase (all complexities)
├── (enhanced IMPL_PLAN.md) # Enhanced structure in implement phase (medium+/complex)
├── TODO_LIST.md # Generated in implement phase (ALL complexities)
├── IMPLEMENTATION_LOG.md # Execution progress log (ALL complexities)
├── workflow-session.json # Updated with document references
└── artifacts/
├── logs/
├── backups/ # Task state backups
└── implementation/ # Implementation artifacts
```
## File Generation Details
### TODO_LIST.md Generation (All Complexities)
**Always Generated**: Now created for Simple, Medium, and Complex workflows
**Simple Workflow Structure:**
```markdown
# Implementation Task List
*Session: WFS-[topic-slug]*
## Quick Implementation Tasks
- [ ] **IMPL-001**: Core implementation
- [ ] **IMPL-002**: Basic testing
- [ ] **IMPL-003**: Review and cleanup
## Progress Tracking
- **Total Tasks**: 3
- **Completed**: 0/3 (0%)
- **Estimated Time**: < 2 hours
---
*Generated by /workflow:implement --type=simple*
```
**Medium/Complex Workflow Structure:**
```markdown
# Implementation Task List
*Session: WFS-[topic-slug]*
## Main Implementation Tasks
### Phase 1: Foundation
- [ ] **IMPL-001**: Set up base infrastructure
- Dependencies: None
- Effort: 2h
- Agent: code-developer
### Phase 2: Core Features
- [ ] **IMPL-002**: Implement main functionality
- Dependencies: IMPL-001
- Effort: 4h
- Agent: code-developer
### Phase 3: Testing & Review
- [ ] **IMPL-003**: Comprehensive testing
- Dependencies: IMPL-002
- Effort: 2h
- Agent: code-review-agent
## Progress Summary
- **Total Tasks**: 8
- **Completed**: 0/8 (0%)
- **Current Phase**: Foundation
- **Estimated Completion**: 2025-09-07 18:00
---
*Generated by /workflow:implement --type=medium*
```
### IMPLEMENTATION_LOG.md Generation (All Complexities)
**Always Generated**: Real-time execution progress tracking
```markdown
# Implementation Execution Log
*Session: WFS-[topic-slug] | Started: 2025-09-07 14:00:00*
## Execution Summary
- **Workflow Type**: Medium
- **Total Tasks**: 8
- **Current Status**: In Progress
- **Progress**: 3/8 (37.5%)
## Execution Timeline
### 2025-09-07 14:00:00 - Implementation Started
- **Phase**: IMPLEMENT
- **Agent**: code-developer
- **Status**: Task execution initialized
### 2025-09-07 14:15:00 - IMPL-001 Started
- **Task**: Set up base infrastructure
- **Agent**: code-developer
- **Approach**: Standard project structure setup
### 2025-09-07 14:45:00 - IMPL-001 Completed
- **Duration**: 30 minutes
- **Status**: ✅ Successful
- **Output**: Base project structure created
- **Next**: IMPL-002
### 2025-09-07 15:00:00 - IMPL-002 Started
- **Task**: Implement main functionality
- **Agent**: code-developer
- **Dependencies**: IMPL-001 ✅
## Current Task Progress
- **Active Task**: IMPL-002
- **Progress**: 60%
- **Estimated Completion**: 15:30
- **Agent**: code-developer
## Issues & Resolutions
- No issues reported
## Next Actions
1. Complete IMPL-002 implementation
2. Begin IMPL-003 testing phase
3. Schedule review checkpoint
---
*Log updated: 2025-09-07 15:15:00*
```
## Individual Task Files Structure
```json
{
"id": "IMPL-001",
"title": "Build authentication module",
"status": "pending",
"type": "feature",
"agent": "code-developer",
"effort": "4h",
"context": {
"inherited_from": "WFS-2025-001",
"requirements": ["JWT authentication"],
"scope": ["src/auth/*"],
"acceptance": ["Module handles JWT tokens"]
},
"dependencies": {
"upstream": [],
"downstream": ["IMPL-002"]
},
"subtasks": [],
"execution": {
"attempts": 0,
"current_attempt": null,
"history": []
},
"metadata": {
"created_at": "2025-09-05T10:30:00Z",
"version": "1.0"
}
}
```
## Integration Points
### Automatic Behaviors
- Creates individual task JSON files (.task/tasks/IMPL-XXX.json) as needed
- Generates decomposition documents based on complexity triggers
- Links documents to workflow-session.json with paths and status
- Enables task commands (/task:*) with document integration
- Starts progress tracking in both JSON and TODO_CHECKLIST.md
- Synchronizes task creation between documents and JSON states
### Next Actions
```bash
# After /workflow:implement
/task:create "First task" # Create tasks
/task:status # View task list
/task:execute IMPL-001 # Execute tasks
```
## Sync Mechanism
- Every task operation updates workflow-session.json
- Progress calculated from task completion
- Issues automatically linked
## Related Commands
- `/workflow:plan` - Should complete first
- `/task:create` - Create implementation tasks
- `/task:status` - Monitor progress
- `/workflow:review` - Next phase after implementation

View File

@@ -0,0 +1,356 @@
---
name: workflow-issue
description: Comprehensive issue and change request management within workflow sessions
usage: /workflow:issue <subcommand> [options]
argument-hint: create|list|update|integrate|close [additional parameters]
examples:
- /workflow:issue create --type=feature "Add OAuth2 social login support"
- /workflow:issue create --type=bug --priority=high "User avatar security vulnerability"
- /workflow:issue list
- /workflow:issue list --status=open --priority=high
- /workflow:issue update ISS-001 --status=integrated --priority=medium
- /workflow:issue integrate ISS-001 --position=after-current
- /workflow:issue close ISS-002 --reason="Duplicate of ISS-001"
---
### 🚀 Command Overview: `/workflow:issue`
- **Purpose**: A comprehensive issue and change request management system for use within workflow sessions.
- **Function**: Enables dynamic creation, tracking, integration, and closure of tasks and changes.
### 🏛️ Subcommand Architecture
- **`create`**: Creates a new issue or change request.
- **`list`**: Lists and filters existing issues.
- **`update`**: Modifies the status, priority, or other attributes of an issue.
- **`integrate`**: Integrates an issue into the current workflow plan.
- **`close`**: Closes a completed or obsolete issue.
### 📜 Core Principles
- **Dynamic Change Management**: @~/.claude/workflows/dynamic-change-management.md
- **Session State Management**: @~/.claude/workflows/session-management-principles.md
- **TodoWrite Coordination Rules**: @~/.claude/workflows/todowrite-coordination-rules.md
### (1) Subcommand: `create`
Creates a new issue or change request.
- **Syntax**: `/workflow:issue create [options] "issue description"`
- **Options**:
- `--type=<type>`: `feature|bug|optimization|refactor|documentation`
- `--priority=<priority>`: `critical|high|medium|low`
- `--category=<category>`: `frontend|backend|database|testing|deployment`
- `--estimated-impact=<impact>`: `high|medium|low`
- `--blocking`: Marks the issue as a blocker.
- `--parent=<issue-id>`: Specifies a parent issue for creating a sub-task.
### (2) Subcommand: `list`
Lists and filters all issues related to the current workflow.
- **Syntax**: `/workflow:issue list [options]`
- **Options**:
- `--status=<status>`: Filter by `open|integrated|completed|closed`.
- `--type=<type>`: Filter by issue type.
- `--priority=<priority>`: Filter by priority level.
- `--category=<category>`: Filter by category.
- `--blocking-only`: Shows only blocking issues.
- `--sort=<field>`: Sort by `priority|created|updated|impact`.
- `--detailed`: Displays more detailed information for each issue.
### (3) Subcommand: `update`
Updates attributes of an existing issue.
- **Syntax**: `/workflow:issue update <issue-id> [options]`
- **Options**:
- `--status=<status>`: Update issue status.
- `--priority=<priority>`: Update issue priority.
- `--description="<new-desc>"`: Update the description.
- `--category=<category>`: Update the category.
- `--estimated-impact=<impact>`: Update estimated impact.
- `--add-comment="<comment>"`: Add a new comment to the issue history.
- `--assign-to=<assignee>`: Assign the issue to a person or team.
- `--blocking` / `--non-blocking`: Change the blocking status.
### (4) Subcommand: `integrate`
Integrates a specified issue into the current workflow plan.
- **Syntax**: `/workflow:issue integrate <issue-id> [options]`
- **Options**:
- `--position=<position>`: `immediate|after-current|next-phase|end-of-workflow`
- `--mode=<mode>`: `insert|replace|merge`
- `--impact-analysis`: Performs a detailed impact analysis before integration.
- `--auto-replan`: Automatically replans the workflow after integration.
- `--preserve-dependencies`: Tries to maintain existing task dependencies.
- `--dry-run`: Simulates integration without making actual changes.
- **Execution Logic**:
```pseudo
FUNCTION integrate_issue(issue_id, options):
// Perform an analysis of how the issue affects the project plan.
analysis_report = create_impact_analysis(issue_id, options)
present_report_to_user(analysis_report)
// Require explicit user confirmation before modifying the workflow.
user_response = get_user_input("Confirm integration? (y/N)")
IF user_response is "y":
log("Executing integration...")
// These steps correspond to the "集成步骤" in the example output.
update_document("IMPL_PLAN.md")
update_document("TODO_CHECKLIST.md")
update_tool_state("TodoWrite")
update_session_file("workflow-session.json")
log("Integration complete!")
ELSE:
log("Integration cancelled by user.")
HALT_OPERATION()
END FUNCTION
```
### (5) Subcommand: `close`
Closes an issue that is completed or no longer relevant.
- **Syntax**: `/workflow:issue close <issue-id> [options]`
- **Options**:
- `--reason=<reason>`: `completed|duplicate|wont-fix|invalid`
- `--comment="<comment>"`: Provides a final closing comment.
- `--reference=<issue-id>`: References a related issue (e.g., a duplicate).
- `--auto-cleanup`: Automatically cleans up references to this issue in other documents.
### ✨ Advanced Features
- **Batch Operations**:
- Update multiple issues at once: `/workflow:issue update ISS-001,ISS-002 --priority=high`
- Integrate a parent issue with its children: `/workflow:issue integrate ISS-001,ISS-001-1,ISS-001-2`
- **Smart Analysis**:
- Performs conflict detection, dependency analysis, priority suggestions, and effort estimations.
- **Reporting**:
- Generate reports on impact or priority: `/workflow:issue report --type=impact`
### 🤝 Command Integrations
- **Automatic Triggers**:
- `/workflow:context`: Automatically displays the status of relevant issues.
- `/workflow:replan`: Can be automatically called by `integrate` to update the plan.
- `/workflow:sync`: Ensures issue status is synchronized with project documents.
- **Shared Data**:
- `workflow-session.json`: Stores core issue data and statistics.
- `WORKFLOW_ISSUES.md`: Provides a human-readable tracking document.
- `CHANGE_LOG.md`: Logs all historical changes related to issues.
### 🗄️ File Generation System
- **Process Flow**: All issue operations trigger a file system update.
`Issue Operation` -> `Generate/Update issues/ISS-###.json` -> `Update WORKFLOW_ISSUES.md` -> `Update workflow-session.json`
### 📄 Template: Individual Issue File (`issues/ISS-###.json`)
This file stores all details for a single issue.
```json
{
"id": "ISS-003",
"title": "Add OAuth2 social login support",
"description": "Add OAuth2 social login support (Google, GitHub, Facebook)",
"type": "feature",
"priority": "high",
"category": "backend",
"status": "open",
"estimated_impact": "medium",
"blocking": false,
"created_at": "2025-01-15T14:30:00Z",
"created_by": "WFS-2025-001",
"parent_issue": null,
"sub_issues": [],
"integration": {
"status": "pending",
"position": "after-current",
"estimated_effort": "6h",
"dependencies": []
},
"history": [
{
"action": "created",
"timestamp": "2025-01-15T14:30:00Z",
"details": "Initial issue creation"
}
],
"metadata": {
"session_id": "WFS-2025-001",
"version": "1.0"
}
}
```
### 📋 Template: Tracking Master File (`WORKFLOW_ISSUES.md`)
This Markdown file provides a human-readable overview of all issues.
```markdown
# Workflow Issues Tracking
*Session: WFS-2025-001 | Updated: 2025-01-15 14:30:00*
## Issue Summary
- **Total Issues**: 3
- **Open**: 2
- **In Progress**: 1
- **Closed**: 0
- **Blocking Issues**: 0
## Open Issues
### 🔥 High Priority
- **[ISS-003](issues/ISS-003.json)** - Add OAuth2 social login support
- Type: Feature | Category: Backend | Created: 2025-01-15
- Status: Open | Impact: Medium
- Integration: Pending (after current phase)
- **[ISS-001](issues/ISS-001.json)** - User avatar security vulnerability
- Type: Bug | Category: Frontend | Created: 2025-01-14
- Status: Open | Impact: High | 🚫 **BLOCKING**
- Integration: Immediate (critical security fix)
### 📊 Medium Priority
- **[ISS-002](issues/ISS-002.json)** - Database performance optimization
- Type: Optimization | Category: Database | Created: 2025-01-14
- Status: In Progress | Impact: High
- Integration: Phase 3 (optimization phase)
## Integration Queue
1. **ISS-001** - Immediate (blocking security issue)
2. **ISS-002** - Phase 3 (performance optimization)
3. **ISS-003** - After current phase (new feature)
## Recent Activity
- **2025-01-15 14:30** - ISS-003 created: Add OAuth2 social login support
- **2025-01-15 10:15** - ISS-002 status updated: In Progress
- **2025-01-14 16:45** - ISS-001 created: User avatar security vulnerability
---
*Generated by /workflow:issue create*
```
### 📁 Template: File Storage Structure
The command organizes all related files within a dedicated workflow directory.
```
.workflow/WFS-[topic-slug]/
├── WORKFLOW_ISSUES.md # 主问题跟踪文件
├── issues/ # 个别问题详情目录
│ ├── ISS-001.json # 问题详细信息
│ ├── ISS-002.json
│ ├── ISS-003.json
│ └── archive/ # 已关闭问题存档
│ └── ISS-###.json
├── issue-reports/ # 问题报告和分析
│ ├── priority-analysis.md
│ ├── integration-impact.md
│ └── resolution-summary.md
└── workflow-session.json # 会话状态更新
```
### 🔄 Template: Session State Update (`workflow-session.json`)
This file is updated after each issue operation to reflect the new state.
```json
{
"issues": {
"total_count": 3,
"open_count": 2,
"blocking_count": 1,
"last_issue_id": "ISS-003",
"integration_queue": ["ISS-001", "ISS-002", "ISS-003"]
},
"documents": {
"WORKFLOW_ISSUES.md": {
"status": "updated",
"path": ".workflow/WFS-[topic-slug]/WORKFLOW_ISSUES.md",
"last_updated": "2025-01-15T14:30:00Z",
"type": "issue_tracking"
},
"issues": {
"ISS-003.json": {
"status": "generated",
"path": ".workflow/WFS-[topic-slug]/issues/ISS-003.json",
"created_at": "2025-01-15T14:30:00Z",
"type": "issue_detail",
"priority": "high",
"blocking": false
}
}
},
"recent_activity": [
{
"type": "issue_created",
"issue_id": "ISS-003",
"timestamp": "2025-01-15T14:30:00Z",
"description": "Add OAuth2 social login support"
}
]
}
```
### 🧱 Issue Data Structure
The canonical JSON structure for an issue object.
```json
{
"id": "ISS-001",
"type": "feature|bug|optimization|refactor|documentation",
"status": "open|integrated|in-progress|completed|closed",
"priority": "critical|high|medium|low",
"category": "frontend|backend|database|testing|deployment",
"blocking": false,
"metadata": {
"title": "OAuth2 social login support",
"description": "Add OAuth2 integration for Google, GitHub, Facebook",
"created_at": "2025-01-15T14:30:00Z",
"updated_at": "2025-01-15T15:45:00Z",
"created_by": "workflow-session:WFS-2025-001"
},
"estimation": {
"impact": "high|medium|low",
"effort": "2-4 hours|1-2 days|3-5 days",
"complexity": "simple|medium|complex"
},
"integration": {
"integrated_at": "2025-01-15T16:00:00Z",
"position": "after-current",
"affected_documents": ["IMPL_PLAN.md"],
"added_tasks": 5,
"modified_tasks": 2
},
"relationships": {
"parent": "ISS-000",
"children": ["ISS-001-1", "ISS-001-2"],
"blocks": ["ISS-002"],
"blocked_by": [],
"relates_to": ["ISS-003"]
},
"comments": [
{
"timestamp": "2025-01-15T15:30:00Z",
"content": "需要考虑用户隐私设置集成",
"type": "note|decision|change"
}
],
"closure": {
"closed_at": "2025-01-16T10:30:00Z",
"reason": "completed|duplicate|wont-fix|invalid",
"final_comment": "功能实现完成,测试通过"
}
}
```

View File

@@ -0,0 +1,88 @@
---
name: workflow-review
description: Execute review phase for quality validation
usage: /workflow:review [--auto-fix]
argument-hint: [optional: auto-fix identified issues]
examples:
- /workflow:review
- /workflow:review --auto-fix
---
# Workflow Review Command (/workflow:review)
## Overview
Final phase for quality validation, testing, and completion.
## Core Principles
**Session Management:** @~/.claude/workflows/session-management-principles.md
## Review Process
1. **Validation Checks**
- All tasks completed
- Tests passing
- Code quality metrics
- Documentation complete
2. **Generate Review Report**
```markdown
# Review Report
## Task Completion
- Total: 10
- Completed: 10
- Success Rate: 100%
## Quality Metrics
- Test Coverage: 85%
- Code Quality: A
- Documentation: Complete
## Issues Found
- Minor: 2
- Major: 0
- Critical: 0
```
3. **Update Session**
```json
{
"current_phase": "REVIEW",
"phases": {
"REVIEW": {
"status": "completed",
"output": "REVIEW.md",
"test_results": {
"passed": 45,
"failed": 0,
"coverage": 85
}
}
}
}
```
## Auto-fix Option
```bash
/workflow:review --auto-fix
```
- Automatically fixes minor issues
- Runs formatters and linters
- Updates documentation
- Re-runs tests
## Completion Criteria
- All tasks marked complete
- Tests passing (configurable threshold)
- No critical issues
- Documentation updated
## Output Files
- `REVIEW.md` - Review report
- `workflow-session.json` - Updated with results
- `test-results.json` - Detailed test output
## Related Commands
- `/workflow:implement` - Must complete first
- `/task:status` - Check task completion
- `/workflow:status` - View overall status

View File

@@ -0,0 +1,352 @@
---
name: workflow-session
description: Workflow session management with multi-session registry support
usage: /workflow:session <start|pause|resume|list|switch|status> [complexity] ["task description"]
argument-hint: start|pause|resume|list|switch|status [simple|medium|complex] ["task description or session ID"]
examples:
- /workflow:session start complex "implement OAuth2 authentication"
- /workflow:session start simple "fix login bug"
- /workflow:session pause
- /workflow:session resume
- /workflow:session list
- /workflow:session switch WFS-oauth-integration
- /workflow:session status
---
# Workflow Session Management Commands
## Overview
Enhanced session management with multi-session registry support. Provides unified state tracking through `workflow-session.json` (individual sessions) and `session_status.jsonl` (lightweight registry).
## Core Principles
**Session Management:** @~/.claude/workflows/session-management-principles.md
## Session Registry System
### Multi-Session Management
The system maintains a lightweight registry (`.workflow/session_status.jsonl`) tracking all sessions:
```jsonl
{"id":"WFS-oauth-integration","status":"paused","description":"OAuth2 authentication implementation","created":"2025-09-07T10:00:00Z","directory":".workflow/WFS-oauth-integration"}
{"id":"WFS-user-profile","status":"active","description":"User profile feature","created":"2025-09-07T11:00:00Z","directory":".workflow/WFS-user-profile"}
{"id":"WFS-bug-fix-123","status":"completed","description":"Fix login timeout issue","created":"2025-09-06T14:00:00Z","directory":".workflow/WFS-bug-fix-123"}
```
### Registry Rules
- **Single Active Session**: Only one session can be active at a time
- **Automatic Registration**: New sessions auto-register on creation
- **Session Discovery**: Commands query registry to find active session
- **Context Inheritance**: Active session provides default context for all commands
## Commands
### Start Workflow Session (初始化)
```bash
/workflow:session start <complexity> "task description"
```
**Session Initialization Process:**
- **Replaces /workflow:init** - Initializes new workflow session
- Generates unique session ID (WFS-[topic-slug] format)
- **Registers in session registry** - Adds entry to `.workflow/session_status.jsonl`
- **Sets as active session** - Deactivates other sessions automatically
- Creates comprehensive directory structure
- Determines complexity (auto-detect if not specified)
- Sets initial phase based on complexity
**Directory Structure Creation:**
```
.workflow/WFS-[topic-slug]/
├── workflow-session.json # Session state and metadata
├── IMPL_PLAN.md # Combined planning document (always created)
├── [.brainstorming/] # Optional brainstorming phase
├── [TODO_LIST.md] # Progress tracking (auto-triggered)
├── reports/ # Generated reports directory
└── .task/ # Task management directory
├── impl-*.json # Hierarchical task definitions
├── impl-*.*.json # Subtasks (up to 3 levels deep)
└── impl-*.*.*.json # Detailed subtasks
```
**File Generation Standards:**
- **workflow-session.json**: Core session state with comprehensive document tracking
- **IMPL_PLAN.md**: Initial planning document template (all complexity levels)
- **reports/ directory**: Created for future report generation by other workflow commands
- **.task/ directory**: Hierarchical task management system setup
- **Automatic backups**: Session state backups created during critical operations
**Phase Initialization:**
- **Simple**: Ready for direct IMPLEMENT (minimal documentation)
- **Medium/Complex**: Ready for PLAN phase (document generation enabled)
**Session State Setup:**
- Creates workflow-session.json with simplified document tracking
- Initializes hierarchical task management system (max 3 levels)
- Creates IMPL_PLAN.md for all complexity levels
- Auto-triggers TODO_LIST.md for Medium/Complex workflows
- **NOTE:** Does NOT execute workflow - only sets up infrastructure
**Next Steps After Initialization:**
- Use `/workflow:plan` to populate IMPL_PLAN.md (all workflows)
- Use `/workflow:implement` for task execution (all workflows)
- Use `/workflow:review` for validation phase
## File Generation and State Management
### Initial File Creation
When starting a new session, the following files are automatically generated:
#### workflow-session.json Structure
```json
{
"session_id": "WFS-[topic-slug]",
"created_at": "2025-09-07T14:00:00Z",
"type": "simple|medium|complex",
"description": "[user task description]",
"current_phase": "INIT",
"status": "active",
"phases": {
"INIT": {
"status": "completed",
"completed_at": "2025-09-07T14:00:00Z",
"files_created": ["IMPL_PLAN.md", "workflow-session.json"],
"directories_created": [".task", "reports"]
},
"BRAINSTORM": {
"status": "pending",
"enabled": false
},
"PLAN": {
"status": "pending",
"enabled": true
},
"IMPLEMENT": {
"status": "pending",
"enabled": true
},
"REVIEW": {
"status": "pending",
"enabled": true
}
},
"documents": {
"planning": {
"IMPL_PLAN.md": {
"status": "template_created",
"path": ".workflow/WFS-[topic-slug]/IMPL_PLAN.md",
"created_at": "2025-09-07T14:00:00Z",
"type": "planning_document"
}
}
},
"task_system": {
"enabled": true,
"max_depth": 3,
"task_count": 0,
"directory": ".task"
},
"registry": {
"registered_in": ".workflow/session_status.jsonl",
"active_session": true
}
}
```
#### Initial IMPL_PLAN.md Template
```markdown
# Implementation Plan
*Session: WFS-[topic-slug] | Created: 2025-09-07 14:00:00*
## Project Overview
- **Description**: [user task description]
- **Complexity**: [simple|medium|complex]
- **Estimated Effort**: [TBD]
- **Target Completion**: [TBD]
## Requirements Analysis
*To be populated by planning phase*
## Task Breakdown
*To be populated by planning phase*
## Implementation Strategy
*To be populated by planning phase*
## Success Criteria
*To be populated by planning phase*
---
*Template created by /workflow:session start*
*Use /workflow:plan to populate this document*
```
### Backup and Recovery System
#### Automatic Backup Creation
- **Trigger Events**: Session pause, critical state changes, error recovery
- **Backup Location**: `.workflow/WFS-[topic-slug]/.backups/`
- **Retention**: Last 5 backups per session
- **Format**: Timestamped JSON and markdown backups
#### Backup Structure
```
.workflow/WFS-[topic-slug]/.backups/
├── session-2025-09-07-14-00.json # Session state backup
├── session-2025-09-07-15-30.json
├── session-2025-09-07-16-45.json
├── IMPL_PLAN-2025-09-07-14-00.md # Document backups
└── TODO_LIST-2025-09-07-15-30.md
```
#### Recovery Operations
- **Auto-recovery**: On session corruption or inconsistency
- **Manual recovery**: Via `/workflow:session recover --from-backup`
- **Integrity checks**: Automatic validation on session load
### Session Registry Management
#### Session Status Registry (.workflow/session_status.jsonl)
```jsonl
{"id":"WFS-oauth-integration","status":"active","description":"OAuth2 authentication implementation","created":"2025-09-07T14:00:00Z","directory":".workflow/WFS-oauth-integration","complexity":"complex"}
```
#### Registry Operations
- **Registration**: Automatic on session creation
- **Status Updates**: Real-time status synchronization
- **Cleanup**: Automatic removal of completed sessions (optional)
- **Discovery**: Used by all workflow commands for session context
### Pause Workflow
```bash
/workflow:session pause
```
- Immediately saves complete session state
- Preserves context across all phases (conceptual/action/implementation)
- Sets status to "interrupted" with timestamp
- Shows resume instructions
- Maintains TodoWrite synchronization
### Resume Workflow
```bash
/workflow:session resume
```
- Detects current phase from workflow-session.json
- Loads appropriate agent context and state
- Continues from exact interruption point
- Maintains full context continuity
- Restores TodoWrite state
### List Sessions
```bash
/workflow:session list
```
- Displays all sessions from registry with status
- Shows session ID, status, description, and creation date
- Highlights currently active session
- Provides quick overview of all workflow sessions
### Switch Active Session
```bash
/workflow:session switch <session-id>
```
- Switches the active session to the specified session ID
- Automatically pauses the currently active session
- Updates registry to set new session as active
- Validates that target session exists and is valid
- Commands executed after switch will use new active session context
### Session Status
```bash
/workflow:session status
```
- Shows current active session details
- Displays session phase, progress, and document status
- Lists available sessions from registry
- Provides quick session health check
### Session State
Session state is tracked through two complementary systems:
#### Registry State (`.workflow/session_status.jsonl`)
Lightweight multi-session tracking:
```jsonl
{"id":"WFS-user-auth-system","status":"active","description":"OAuth2 authentication","created":"2025-09-07T10:30:00Z","directory":".workflow/WFS-user-auth-system"}
```
#### Individual Session State (`workflow-session.json`)
Detailed session state with document management:
```json
{
"session_id": "WFS-user-auth-system",
"project": "OAuth2 authentication",
"type": "complex",
"status": "active|paused|completed",
"current_phase": "PLAN|IMPLEMENT|REVIEW",
"created": "2025-09-05T10:30:00Z",
"directory": ".workflow/WFS-user-auth-system",
"documents": {
"IMPL_PLAN.md": {
"status": "generated",
"path": ".workflow/WFS-user-auth-system/IMPL_PLAN.md",
"last_updated": "2025-09-05T10:30:00Z"
},
"TODO_LIST.md": {
"status": "auto_triggered",
"path": ".workflow/WFS-user-auth-system/TODO_LIST.md",
"last_updated": "2025-09-05T11:20:00Z"
}
},
"task_system": {
"enabled": true,
"directory": ".workflow/WFS-user-auth-system/.task",
"next_main_task_id": 1,
"max_depth": 3,
"task_count": {
"total": 0,
"main_tasks": 0,
"subtasks": 0
}
}
}
```
To check status, use: `/workflow:status`
To mark complete: Simply finish all tasks and review phase
## Session State Management
### Session Responsibilities
- **Lifecycle Management**: Start, pause, resume sessions
- **State Persistence**: Save and restore workflow state
- **Phase Tracking**: Monitor current phase (PLAN/IMPLEMENT/REVIEW)
- **Context Preservation**: Maintain context across interruptions
### What Session Does NOT Do
- **No Execution**: Does not run agents or execute tasks
- **No Planning**: Does not generate planning documents
- **No Implementation**: Does not run code development
- **Execution Delegation**: All execution via appropriate phase commands:
- `/workflow:plan` - Planning execution
- `/workflow:implement` - Implementation execution
- `/workflow:review` - Review execution
## Automatic Checkpoints
@~/.claude/workflows/session-management-principles.md
Checkpoints created by phase commands:
- `/workflow:plan` creates checkpoints during planning
- `/workflow:implement` creates checkpoints after agents
- `/workflow:review` creates final validation checkpoint
- Session commands only manage checkpoint restoration
## Cross-Phase Context Preservation
- All phase outputs preserved in session
- Context automatically transferred between phases
- PRD documents bridge conceptual → action planning
- Implementation plans bridge action → implementation
- Full audit trail maintained for decisions
## State Validation
- Verify required artifacts exist for resumption
- Check file system consistency with session state
- Validate TodoWrite synchronization
- Ensure agent context completeness

View File

@@ -0,0 +1,311 @@
---
name: workflow-sync
description: Synchronize workflow documents and validate data integrity with comprehensive reporting
usage: /workflow:sync [--check] [--fix] [--force] [--export-report]
argument-hint: [optional: check-only, auto-fix, force, or export report]
examples:
- /workflow:sync
- /workflow:sync --check
- /workflow:sync --fix
- /workflow:sync --force
- /workflow:sync --export-report
---
# Workflow Sync Command (/workflow:sync)
## Overview
Ensures consistency between workflow-session.json, tasks.json, and related documents.
## Core Principles
**Dynamic Change Management:** @~/.claude/workflows/dynamic-change-management.md
## Sync Targets
### Primary Files
- `workflow-session.json` - Workflow state
- `tasks.json` - Task data
- `IMPL_PLAN.md` - Planning document
- `REVIEW.md` - Review results
### Validation Checks
- Session ID consistency
- Task ID references
- Progress calculations
- Status transitions
- Timestamp logic
## Usage Modes
### Default Mode
```bash
/workflow:sync
🔄 Workflow Synchronization
━━━━━━━━━━━━━━━━━━━━━
Checking consistency...
Issues found:
- Progress mismatch: 45% vs 60%
- Task IMPL-003 status differs
- 2 tasks missing from workflow
Fixing...
✅ Updated progress to 60%
✅ Synced IMPL-003 status
✅ Added missing tasks
Sync complete: 3 fixes applied
```
### Check Mode (--check)
```bash
/workflow:sync --check
```
- Read-only validation
- Reports issues without fixing
- Safe for production
### Fix Mode (--fix)
```bash
/workflow:sync --fix
```
- Auto-fixes safe issues
- Prompts for conflicts
- Creates backup first
### Force Mode (--force)
```bash
/workflow:sync --force
```
- Overwrites all conflicts
- No confirmation prompts
- Use with caution
## Sync Rules
### Data Authority
1. **workflow-session.json** - Highest (main state)
2. **tasks.json** - High (task details)
3. **Markdown files** - Medium (documentation)
4. **TodoWrite** - Low (temporary state)
### Conflict Resolution
- Recent changes win (timestamp)
- More complete data preferred
- User confirmation for ambiguous
### Auto-fix Scenarios
- Progress calculation errors
- Missing task references
- Invalid status transitions
## Report Generation
### Sync Report Export (--export-report)
When `--export-report` flag is used, generates comprehensive sync reports:
#### Generated Files
- **reports/SYNC_REPORT.md** - Detailed synchronization analysis
- **reports/sync-backups/** - Backup files created during sync
- **reports/sync-history/** - Historical sync reports
#### File Storage Structure
```
.workflow/WFS-[topic-slug]/reports/
├── SYNC_REPORT.md # Latest sync report
├── sync-backups/ # Pre-sync backups
│ ├── workflow-session-backup.json
│ ├── TODO_LIST-backup.md
│ └── IMPL_PLAN-backup.md
├── sync-history/ # Historical reports
│ ├── sync-2025-09-07-14-30.md
│ ├── sync-2025-09-07-15-45.md
│ └── sync-2025-09-07-16-15.md
└── sync-logs/ # Detailed sync logs
└── sync-operations.jsonl
```
### SYNC_REPORT.md Structure
```markdown
# Workflow Synchronization Report
*Generated: 2025-09-07 14:30:00*
## Sync Operation Summary
- **Operation Type**: Full Sync with Auto-fix
- **Duration**: 2.3 seconds
- **Files Processed**: 5
- **Issues Found**: 3
- **Issues Fixed**: 3
- **Backup Created**: Yes
## Pre-Sync State Analysis
### Document Integrity Check
-**workflow-session.json**: Valid JSON structure
- ⚠️ **TODO_LIST.md**: 3 completed tasks not marked
-**IMPL_PLAN.md**: Missing 2 task references
-**WORKFLOW_ISSUES.md**: Healthy
- ⚠️ **IMPLEMENTATION_LOG.md**: Timestamp inconsistency
### Data Consistency Analysis
- **Task References**: 85% consistent (missing 2 references)
- **Progress Tracking**: 78% accurate (3 items out of sync)
- **Cross-Document Links**: 92% valid (1 broken link)
## Synchronization Operations
### 1. Progress Calculation Fix
- **Issue**: Progress mismatch between JSON and markdown
- **Before**: workflow-session.json: 45%, TODO_LIST.md: 60%
- **Action**: Updated workflow-session.json progress to 60%
- **Result**: ✅ Progress synchronized
### 2. Task Reference Update
- **Issue**: Missing task references in IMPL_PLAN.md
- **Before**: 8 tasks in JSON, 6 tasks in IMPL_PLAN.md
- **Action**: Added IMPL-007 and IMPL-008 references
- **Result**: ✅ All tasks referenced
### 3. TodoWrite Status Sync
- **Issue**: 3 completed tasks not marked in checklist
- **Before**: TodoWrite showed completed, TODO_LIST.md showed pending
- **Action**: Updated TODO_LIST.md completion status
- **Result**: ✅ TodoWrite and documents synchronized
## Post-Sync State
### Document Health Status
-**workflow-session.json**: Healthy (100% consistent)
-**TODO_LIST.md**: Healthy (100% accurate)
-**IMPL_PLAN.md**: Healthy (all references valid)
-**WORKFLOW_ISSUES.md**: Healthy (no issues)
-**IMPLEMENTATION_LOG.md**: Healthy (timestamps corrected)
### Data Integrity Metrics
- **Task References**: 100% consistent
- **Progress Tracking**: 100% accurate
- **Cross-Document Links**: 100% valid
- **Timestamp Consistency**: 100% aligned
## Backup Information
### Created Backups
- **workflow-session-backup.json**: Original session state
- **TODO_LIST-backup.md**: Original task list
- **IMPL_PLAN-backup.md**: Original implementation plan
### Backup Location
```
.workflow/WFS-[topic-slug]/reports/sync-backups/2025-09-07-14-30/
```
## Recommendations
### Immediate Actions
- No immediate actions required
- All issues successfully resolved
### Preventive Measures
1. Consider running sync more frequently during active development
2. Enable auto-sync triggers for task completion events
3. Review document update procedures to maintain consistency
## Next Sync Recommendation
- **Frequency**: Every 2 hours during active development
- **Trigger Events**: After task completion, before major operations
- **Auto-fix**: Enabled for minor consistency issues
---
*Report generated by /workflow:sync --export-report*
```
### Session Updates
After sync operations, workflow-session.json is updated with sync metadata:
```json
{
"sync_history": [
{
"timestamp": "2025-09-07T14:30:00Z",
"type": "full_sync_with_autofix",
"duration_seconds": 2.3,
"issues_found": 3,
"issues_fixed": 3,
"backup_created": true,
"report_path": "reports/SYNC_REPORT.md"
}
],
"last_sync": {
"timestamp": "2025-09-07T14:30:00Z",
"status": "successful",
"integrity_score": 100
},
"documents": {
"reports": {
"SYNC_REPORT.md": {
"status": "generated",
"path": ".workflow/WFS-[topic-slug]/reports/SYNC_REPORT.md",
"generated_at": "2025-09-07T14:30:00Z",
"type": "sync_report"
}
}
}
}
```
### Sync Operation Logging
All sync operations are logged in `sync-logs/sync-operations.jsonl`:
```jsonl
{"timestamp":"2025-09-07T14:30:00Z","operation":"progress_fix","before":{"session":45,"checklist":60},"after":{"session":60,"checklist":60},"status":"success"}
{"timestamp":"2025-09-07T14:30:01Z","operation":"task_reference_update","tasks_added":["IMPL-007","IMPL-008"],"status":"success"}
{"timestamp":"2025-09-07T14:30:02Z","operation":"todowrite_sync","tasks_updated":3,"status":"success"}
```
- Timestamp inconsistencies
## Example Outputs
### Success
```
✅ All documents in sync
- Files checked: 4
- Issues found: 0
- Last sync: 2 minutes ago
```
### With Issues
```
⚠️ Sync issues detected:
1. Progress: 45% (should be 60%)
2. Task IMPL-003: 'completed' vs 'active'
3. Missing: IMPL-005 not in workflow
Run with --fix to resolve
```
### After Fix
```
✅ Sync completed:
- Fixed: 3 issues
- Backup: .backup/sync-20250116
- Verified: All consistent
```
## Error Handling
### Common Errors
```bash
❌ workflow-session.json not found
→ Run: /workflow:init first
❌ tasks.json corrupted
→ Restoring from backup...
✅ Restored successfully
❌ Permission denied
→ Check file permissions
```
## Performance
- Incremental checks (fast)
- Cached validations
- Typical time: < 200ms
## Related Commands
- `/task:sync` - Task-specific sync
- `/workflow:status` - View current state
- `/task:status` - Task details