Add session status file creation rule across workflow commands

Updates all workflow commands to create .workflow/session_status.jsonl if it doesn't exist when checking for active sessions. This ensures consistent behavior across:

- gemini-chat.md: Added creation rule and updated workflow pseudocode
- gemini-execute.md: Added session file creation requirement
- gemini-mode.md: Updated session check process
- workflow/action-plan.md: Updated both session check locations
- task/replan.md: Added creation rule to session validation
- task/breakdown.md: Updated session check process
- workflow/brainstorm.md: Added creation rule to session registry query

Also includes cleanup of deprecated command files (context.md, sync.md) and documentation updates for task creation complexity escalation.

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

Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
catlog22
2025-09-07 23:06:54 +08:00
parent 28124f1a95
commit b64fd30c5d
27 changed files with 648 additions and 3998 deletions

344
.claude/commands/context.md Normal file
View File

@@ -0,0 +1,344 @@
---
name: context
description: Unified context command - Single source of truth for all workflow and task status information
usage: /context [task-id] [--format=<tree|list|json|progress>] [--health-check] [--detailed] [--export]
argument-hint: [optional task-id] [display format] [analysis options] [export flag]
examples:
- /context
- /context IMPL-001
- /context --format=tree
- /context --health-check
- /context --detailed --export
- /context --format=progress
---
# Unified Context Command (/context)
## Overview
**Single Source of Truth**: This command replaces `/workflow:context` and `/task:context` with a unified interface that generates all views on-demand from JSON data. Eliminates synchronization complexity by making documents read-only views.
## Core Architecture
### Single Source of Truth Principle
- **JSON Authority**: All data read from `.task/*.json` and `workflow-session.json` files
- **Generated Views**: All markdown displays generated on-demand (never manually edited)
- **No Synchronization**: Documents are views, not synchronized states
- **Conflict-Free**: Single direction data flow eliminates conflicts
### Unified Command Interface
- **Global Context**: `/context` shows complete workflow status
- **Task-Specific**: `/context IMPL-001` shows individual task details
- **Health Checking**: `/context --health-check` validates JSON data integrity
- **Multiple Formats**: Tree, list, progress, and JSON output formats
## Usage Modes
### 1. Global Workflow Context (Default)
```bash
/context
```
**Generated Output** (from JSON data):
```
🔍 Workflow Status Overview
========================
📋 Session Information:
- Session ID: WFS-workflow-optimization
- Current Phase: IMPLEMENT
- Complexity: complex
- Start Time: 2025-09-07 14:30:22Z
- Duration: 4h 15m
📊 Task Progress (from .task/*.json):
✅ Completed: 2/5 (40%)
🔄 In Progress: 1 task
⏳ Pending: 2 tasks
🚫 Blocked: 0 tasks
📁 JSON Data Health:
✅ workflow-session.json - Valid JSON, complete data
✅ .task/ directory - 5 task files, all valid JSON
✅ Task relationships - All dependencies valid
✅ Progress calculations - Mathematically consistent
⏱️ Estimated Completion: 2025-09-07 20:45 (2h 30m remaining)
🎯 Next Actions (generated from JSON state):
1. Complete IMPL-003 (currently in progress)
2. Begin IMPL-004 (dependencies satisfied)
3. Review completed IMPL-001 and IMPL-002
```
### 2. Task-Specific Context
```bash
/context IMPL-001
```
**Generated Output** (from JSON file):
```
📋 Task Context: IMPL-001
━━━━━━━━━━━━━━━━━━━━━━
📄 JSON Source: .task/impl-001.json
Status: completed (from JSON authority)
Created: 2025-09-07T14:45:00Z
Completed: 2025-09-07T16:30:00Z
Duration: 1h 45m
🎯 Task Definition (from JSON):
Title: Implement single source of truth architecture by removing sync commands
Type: architecture
Agent: code-developer
Priority: critical
📋 Context (from JSON):
Requirements:
- Remove workflow:sync and task:sync commands
- Update coordination system documentation
- Establish JSON as single authority source
Scope:
- .claude/commands/workflow/sync.md
- .claude/commands/task/sync.md
- .claude/workflows/json-document-coordination-system.md
🔗 Dependencies (from JSON):
Upstream: None
Downstream: IMPL-002, IMPL-003
Parent: None
✅ Completion Status (from JSON):
Result: success
Files Modified: 3 files moved to deprecated, 1 file updated
Next Task: IMPL-002 ready to begin
```
### 3. Health Check Mode
```bash
/context --health-check
```
**Generated Analysis** (from JSON validation):
```
🏥 System Health Check (JSON Data Analysis)
========================================
✅ JSON File Integrity:
- workflow-session.json: ✅ Valid JSON, complete schema
- .task/impl-001.json: ✅ Valid JSON, all required fields
- .task/impl-002.json: ✅ Valid JSON, all required fields
- .task/impl-003.json: ✅ Valid JSON, all required fields
- .task/impl-004.json: ✅ Valid JSON, all required fields
- .task/impl-005.json: ✅ Valid JSON, all required fields
🔗 Data Consistency Check:
✅ Task IDs: All unique, follow impl-N format
✅ Dependencies: All referenced tasks exist
✅ Status Logic: All transitions valid
✅ Progress Math: Calculations consistent
✅ Timestamps: All valid, chronologically ordered
📊 Data Completeness:
✅ All tasks have required fields
✅ All tasks have context information
✅ All dependencies properly defined
✅ Session state complete
🎯 Overall System Health: 100% (Excellent)
- Zero data conflicts (Single source of truth benefit)
- All JSON files valid and consistent
- No synchronization issues (eliminated by design)
- Ready for continued execution
```
### 4. Tree Format Display
```bash
/context --format=tree
```
**Generated Tree** (from JSON hierarchy):
```
📁 WFS-workflow-optimization (from workflow-session.json)
├── 📋 PLAN [Completed]
│ └── Output: IMPL_PLAN.md, 5 tasks generated
├── 🔨 IMPLEMENT [Active - 40% complete]
│ ├── ✅ IMPL-001: Single source of truth architecture (completed)
│ ├── ✅ IMPL-002: Automated planning-to-execution flow (completed)
│ ├── 🔄 IMPL-003: Unified context commands (in_progress)
│ ├── ⏳ IMPL-004: Dynamic complexity escalation (pending)
│ └── ⏳ IMPL-005: Update session management (pending)
└── 📝 REVIEW [Pending]
└── Awaiting implementation completion
```
### 5. Progress Format
```bash
/context --format=progress
```
**Generated Progress View** (calculated from JSON data):
```
📊 Implementation Progress Report
==============================
🎯 Overall Progress: 40% (2/5 tasks complete)
📈 Progress by Phase:
┌─────────────┬─────────┬──────────┬─────────┐
│ Phase │ Status │ Progress │ Tasks │
├─────────────┼─────────┼──────────┼─────────┤
│ PLAN │ ✅ │ 100% │ N/A │
│ IMPLEMENT │ 🔄 │ 40% │ 2/5 │
│ REVIEW │ ⏳ │ 0% │ 0/0 │
└─────────────┴─────────┴──────────┴─────────┘
📋 Task Progress Details (from JSON files):
✅ IMPL-001: single source of truth [100%] ⏱️ 1h 45m
✅ IMPL-002: automated planning flow [100%] ⏱️ 2h 10m
🔄 IMPL-003: unified context commands [75%] ⏱️ 1h 30m (in progress)
⏳ IMPL-004: dynamic complexity [0%] ⏱️ 2h 00m (estimated)
⏳ IMPL-005: session management updates [0%] ⏱️ 1h 15m (estimated)
⏰ Time Analysis (calculated from JSON):
Time Spent: 5h 25m
Remaining: 2h 45m
Estimated Total: 8h 10m
Completion: 2025-09-07 21:15
```
## File Export Feature
### Export Generated Views
```bash
/context --export
```
**Generated Files** (all from JSON data):
```
.workflow/WFS-workflow-optimization/reports/
├── CONTEXT_REPORT.md # Current context view
├── PROGRESS_REPORT.md # Progress analysis
├── HEALTH_CHECK.md # System health status
└── context-exports/ # Historical exports
├── context-2025-09-07-14-30.md
├── progress-2025-09-07-15-45.md
└── health-2025-09-07-16-15.md
```
**Report Structure** (generated from JSON):
```markdown
# Workflow Context Report
*Generated: 2025-09-07 16:15:00 from JSON data sources*
## Data Sources
- workflow-session.json (last updated: 2025-09-07T15:45:00Z)
- 5 task JSON files in .task/ directory
- All sources validated and consistent
## Session Overview
[Generated from workflow-session.json]
## Task Analysis
[Generated from .task/*.json files]
## Health Assessment
[Validated from JSON data integrity]
---
*This report is a generated view from authoritative JSON data*
*No manual editing required - data updates automatically in JSON files*
```
## Advanced Features
### JSON Output for Scripting
```bash
/context --format=json
```
**Generated JSON** (compiled from all sources):
```json
{
"session": {
"id": "WFS-workflow-optimization",
"status": "active",
"phase": "implement",
"progress": 40,
"data_source": "workflow-session.json"
},
"tasks": [
{
"id": "IMPL-001",
"status": "completed",
"progress": 100,
"data_source": ".task/impl-001.json"
}
],
"health": {
"json_integrity": 100,
"data_consistency": 100,
"completeness": 100
},
"generated_at": "2025-09-07T16:15:00Z",
"data_freshness": "current"
}
```
### Health Check Integration
- **Validation Engine**: Checks all JSON files for schema compliance
- **Consistency Verification**: Validates cross-references between files
- **Data Integrity**: Ensures all dependencies and relationships are valid
- **Performance Monitoring**: Tracks data loading and generation speed
## Benefits of Unified Architecture
### Eliminated Complexity
- **No Sync Commands**: Removed `/workflow:sync` and `/task:sync`
- **No Conflicts**: Single source eliminates data drift
- **No Manual Document Editing**: All documents are generated views
- **Simplified User Experience**: One command for all context needs
### Enhanced Reliability
- **Data Consistency**: JSON authority ensures consistent state
- **Error Reduction**: No synchronization bugs or conflicts
- **Simplified Recovery**: Only JSON files need backup/restore
- **Predictable Behavior**: Views always reflect current JSON state
### Improved Performance
- **On-Demand Generation**: Views created only when requested
- **Efficient Data Access**: Direct JSON file reading
- **No Background Sync**: No overhead from synchronization processes
- **Cached Calculations**: Smart caching for expensive operations
## Technical Implementation
### Data Flow Architecture
```
JSON Files (.task/*.json + workflow-session.json)
↓ (Single Direction - Read Only)
View Generation Engine
Formatted Output (Console/File)
```
### View Generation Process
1. **Load JSON Data**: Read all relevant JSON files
2. **Validate Data**: Check integrity and consistency
3. **Calculate Views**: Generate requested format/content
4. **Format Output**: Apply formatting and display
5. **Export (Optional)**: Save generated views to files
### Error Handling
- **Missing Files**: Clear error messages with recovery suggestions
- **Invalid JSON**: Schema validation with specific error details
- **Broken References**: Dependency validation with repair recommendations
- **Data Inconsistencies**: Automatic detection and resolution suggestions
### Data Management
- All commands now work with JSON as single source of truth
- Document generation happens on-demand
- No synchronization commands needed
- Simplified data model improves reliability

View File

@@ -131,7 +131,7 @@ END FUNCTION
- **Trigger**: Activated by the `--save-session` flag.
- **Action**: Saves the complete interaction, including the template used, context, and Gemini's output.
- **Session Check**: Query `.workflow/session_status.jsonl` to identify current active session.
- **Session Check**: Query `.workflow/session_status.jsonl` to identify current active session. If the file doesn't exist, create it.
- **Location Strategy**:
- **IF active session exists**: Save to existing `.workflow/WFS-[topic-slug]/.chat/` directory
- **IF no active session**: Create new session directory following WFS naming convention
@@ -146,7 +146,11 @@ END FUNCTION
**Session Detection Workflow:**
```pseudo
FUNCTION determine_save_location():
// STEP 1: Check for existing active session
// STEP 1: Ensure session status file exists
IF NOT file_exists(".workflow/session_status.jsonl"):
create_empty_session_registry(".workflow/session_status.jsonl")
// STEP 2: Check for existing active session
active_sessions = query_session_registry(".workflow/session_status.jsonl")
IF active_sessions.count > 0:

View File

@@ -192,7 +192,7 @@ This template is automatically filled and generated after execution.
- **Trigger**: Activated by the `--save-session` flag.
- **Action**: Saves the complete execution session, including inferred context, Gemini analysis, and implementation results.
- **Session Check**: Query `.workflow/session_status.jsonl` to identify current active session.
- **Session Check**: Query `.workflow/session_status.jsonl` to identify current active session. If the file doesn't exist, create it.
- **Location Strategy**:
- **IF active session exists**: Save to existing `.workflow/WFS-[topic-slug]/.chat/` directory
- **IF no active session**: Create new session directory following WFS naming convention

View File

@@ -128,7 +128,7 @@ END FUNCTION
⚠️ **CRITICAL**: Before analysis, MUST check for existing active session to ensure proper workflow context and documentation storage.
**Session Check Process:**
1. **Query Session Registry**: Check `.workflow/session_status.jsonl` for active sessions
1. **Query Session Registry**: Check `.workflow/session_status.jsonl` for active sessions. If the file doesn't exist, create it.
2. **Context Integration**: Use existing active session for proper analysis context
3. **Documentation Strategy**: Store analysis results in appropriate session directory structure

View File

@@ -23,7 +23,7 @@ Intelligently breaks down complex tasks into manageable subtasks with automatic
⚠️ **CRITICAL**: Before breakdown, 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
1. **Query Session Registry**: Check `.workflow/session_status.jsonl` for active sessions. If the file doesn't exist, create it.
2. **Session Validation**: Use existing active session containing the parent task
3. **Context Integration**: Load existing session state and task hierarchy

View File

@@ -1,349 +0,0 @@
---
name: task-context
description: Unified task context analysis, status management, and intelligent execution support
usage: /task:context [task-id|--filter=<filter>] [--analyze] [--update] [--sync] [--format=<tree|list|json>] [--detailed]
argument-hint: [task-id or filter] [optional: actions and format options]
examples:
- /task:context
- /task:context IMPL-001 --analyze --detailed
- /task:context --filter="status:active" --format=tree
- /task:context IMPL-001 --update
- /task:context --sync
---
### 🚀 Command Overview: /task:context
- **Purpose**: Provides unified task context analysis, status visualization, progress tracking, and intelligent execution support.
- **Core Function**: Acts as a central hub for understanding and managing the state of tasks within a workflow.
### 📜 Core Principles
- **Task Management**: @~/.claude/workflows/task-management-principles.md
- **File Structure**: @~/.claude/workflows/file-structure-standards.md
- **Session Management**: @~/.claude/workflows/session-management-principles.md
### ✨ Core Capabilities
- **Context Awareness**
- Analyzes current state and progress from JSON task files.
- Tracks hierarchical task dependencies.
- Detects changes in JSON files and status.
- Assesses the impact of changes across tasks and files.
- Suggests next actions based on current context.
- Monitors compliance with file structure standards.
- **Status Management**
- Visualizes task status in `tree`, `list`, and `json` formats.
- Tracks hierarchical progress from task files.
- Performs batch operations on tasks using filters.
- Monitors file integrity and task health.
- Exports analysis and status data to various file formats.
- Generates status reports and analysis documents.
### 🧠 Primary Operations Logic
The command's behavior is determined by the provided arguments.
```pseudo
FUNCTION main(arguments):
// Options like --filter and --format modify the behavior of display functions.
IF --sync is present:
// Corresponds to: /task:context --sync
run_context_synchronization()
ELSE IF --update is present AND task_id is given:
// Corresponds to: /task:context <task-id> --update
run_interactive_update_for(task_id)
ELSE IF --analyze is present AND task_id is given:
// Corresponds to: /task:context <task-id> --analyze
run_detailed_analysis_for(task_id)
ELSE IF --health, --progress, --timeline, etc. are present:
// Corresponds to specific reporting sub-commands
generate_specific_report(report_type)
ELSE IF task_id is provided without other primary action flags:
// Corresponds to: /task:context <task-id>
display_task_context_and_quick_actions(task_id)
ELSE:
// Default action with no arguments or only filters/formatters
// Corresponds to: /task:context
display_global_context_view(filters, format)
END FUNCTION
```
### 🎯 Main Usage Modes & Examples
#### 1. Global Context View
- **Command**: `/task:context`
- **Description**: Provides a high-level overview of the entire workflow's task status.
- **Example Output**:
```
📊 Task Context Overview
━━━━━━━━━━━━━━━━━━━━━━
Workflow: WFS-[topic-slug]
Phase: IMPLEMENT
Progress: 45% (5/11 tasks)
Summary:
✅ Completed: 5
🔄 Active: 2
⏳ Pending: 3
🚫 Blocked: 1
Active Context:
- Current focus: IMPL-002 (In Progress)
- Dependencies clear: Yes
- Blockers: IMPL-004 blocked by IMPL-003
Critical Path:
IMPL-001 → IMPL-003 → IMPL-006
Next Actions:
1. Complete IMPL-002 (90% done)
2. Unblock IMPL-004
3. Start IMPL-005 (ready)
```
#### 2. Task-Specific Analysis
- **Command**: `/task:context IMPL-001 --analyze`
- **Description**: Shows a detailed breakdown of a single task's context, dependencies, and related changes.
- **Example Output**:
```
📋 Task Context: IMPL-001
━━━━━━━━━━━━━━━━━━━━
Status: In Progress
Started: 2h ago
Progress: 60% (2/3 subtasks complete)
Dependencies:
✅ No upstream dependencies
⬇️ Blocks: IMPL-003, IMPL-004
Context Data:
- Requirements: [inherited from workflow]
- Scope: src/auth/*, tests/auth/*
- Agent: code-developer
- Priority: high
Related Changes:
- src/auth/login.ts modified 30m ago
- New issue: "Login timeout too short"
- Workflow update: Security requirement added
Impact if delayed:
⚠️ Will block 2 downstream tasks
⚠️ Critical path - affects timeline
```
#### 3. Interactive Context Update
- **Command**: `/task:context IMPL-001 --update`
- **Description**: Initiates an interactive prompt to modify a task's context data.
- **Example Interaction**:
```
Current context for IMPL-001:
1. Requirements: [JWT, OAuth2]
2. Scope: [src/auth/*]
3. Priority: normal
What to update?
1. Add requirement
2. Modify scope
3. Change priority
4. Add note
> 1
Enter new requirement: Add 2FA support
✅ Context updated
```
#### 4. Context Synchronization
- **Command**: `/task:context --sync`
- **Description**: Reconciles context across the entire task hierarchy, propagating changes and resolving conflicts.
- **Example Output**:
```
🔄 Synchronizing task contexts...
- Workflow → Tasks: Updated 3 tasks
- Parent → Children: Propagated 2 changes
- Dependencies: Resolved 1 conflict
✅ All contexts synchronized
```
### 🖥️ Display Formats (`--format`)
#### Tree Format (`--format=tree`)
```
📁 IMPLEMENT Tasks
├── ✅ IMPL-001: Authentication [Complete]
│ ├── ✅ IMPL-001.1: Design schema
│ ├── ✅ IMPL-001.2: Core implementation
│ └── ✅ IMPL-001.3: Tests
├── 🔄 IMPL-002: Database layer [60%]
│ ├── ✅ IMPL-002.1: Models
│ ├── 🔄 IMPL-002.2: Migrations
│ └── ⏳ IMPL-002.3: Seeds
├── ⏳ IMPL-003: API endpoints [Pending]
└── 🚫 IMPL-004: Integration [Blocked by IMPL-003]
```
#### List Format (`--format=list`)
```
ID | Title | Status | Progress | Agent | Priority
---------|--------------------------|-----------|----------|-----------------|----------
IMPL-001 | Authentication | completed | 100% | code-developer | normal
IMPL-002 | Database layer | active | 60% | code-developer | high
IMPL-003 | API endpoints | pending | 0% | planning-agent | normal
IMPL-004 | Integration | blocked | 0% | - | low
```
#### JSON Format (`--format=json`)
- **Description**: Outputs machine-readable JSON, suitable for scripting and tool integration.
### 🔍 Filtering (`--filter`)
- **By Status**:
- `status:active`
- `status:pending`
- `status:blocked`
- `status:completed`
- **By Other Attributes**:
- `type:feature`
- `priority:high`
- **Combining Filters**:
- `status:active,priority:high`
### 🧠 Context Intelligence Features
- **Change Detection**: Automatically detects file modifications, new issues, workflow updates, and dependency status changes.
- **Impact Analysis**: Assesses the effect of delays or failures on downstream tasks and the overall timeline (`--impact`).
- **Smart Recommendations**: Provides actionable suggestions like which task to focus on, what can be parallelized, or which tasks need breaking down (`--recommend`).
### 📄 Context Data Structure (JSON Schema)
This is the standard schema for a task's context data stored in JSON files.
```json
{
"task_id": "IMPL-001",
"title": "Build authentication module",
"type": "feature",
"status": "active",
"priority": "high",
"agent": "code-developer",
"context": {
"inherited_from": "WFS-[topic-slug]",
"requirements": ["JWT authentication", "OAuth2 support", "2FA support"],
"scope": ["src/auth/*", "tests/auth/*"],
"acceptance": ["Module handles JWT tokens", "OAuth2 flow implemented", "2FA integration works"]
},
"dependencies": {
"upstream": [],
"downstream": ["IMPL-003", "IMPL-004"]
},
"execution": {
"attempts": 1,
"current_attempt": {
"started_at": "2025-09-05T10:35:00Z",
"checkpoints": ["setup", "implement", "test", "validate"],
"completed_checkpoints": ["setup", "implement"]
},
"history": []
},
"environment": {
"files_modified": ["src/auth/login.ts", "src/auth/middleware.ts"],
"issues": ["ISS-001"],
"last_activity": "2025-09-05T12:15:00Z"
},
"recommendations": {
"next_action": "Complete test checkpoint",
"risk": "low",
"priority_adjustment": "none"
}
}
```
### 📊 Analysis & Monitoring
- **Progress Report (`--progress`)**: Shows overall progress broken down by type, priority, and velocity.
- **Health Checks (`--health`)**: Reports on task health, highlighting issues like blockers, delays, and repeated failures.
- **Timeline View (`--timeline`)**: Displays a chronological view of recent and upcoming task activities.
### 🛠️ Advanced Features
- **Conflict Detection (`--conflicts`)**: Identifies potential conflicts, such as multiple tasks modifying the same file.
- **Historical Context (`--history`)**: Shows the version history of a task's context data.
- **Context Validation (`--validate`)**: Checks a task's context for completeness and validity against defined rules.
### 🚦 Status Management
- **Update Status**: Change a single task's status using `--set`. Example: `/task:context IMPL-002 --set=active`
- **Bulk Update**: Update multiple tasks matching a filter. Example: `/task:context --filter="status:pending" --set=blocked --reason="Waiting for API"`
- **Valid Status Transitions**:
`pending` -> `active` -> `completed`
`pending` -> `blocked`
`active` -> `blocked`
`active` -> `failed` -> `pending`
### 💾 File Output Generation
- **Analysis Report (`--report --save`)**:
- Generates a comprehensive markdown report.
- **Output**: `.workflow/WFS-[topic-slug]/.summaries/analysis-[timestamp].md`
- **Data Export (`--export=<format>`)**:
- Exports task data to various formats (`markdown`, `json`, `csv`).
- **Output**: `.summaries/[output-name]-[timestamp].[format]`
- **Validation Report (`--validate --save`)**:
- Saves the output of context validation to a file.
- **Output**: `.summaries/validation-report-[timestamp].md`
- **TODO_LIST.md Generation (`--generate-todo-list`)**:
- Creates a `TODO_LIST.md` file from the current state of JSON task files.
- **Output**: `.workflow/WFS-[topic-slug]/TODO_LIST.md`
### 🔗 Integration Points
- **Workflow**: Inherits context from the main workflow and updates `session.json`.
- **Task Relationships**: Manages parent-child and sibling dependencies, including circular dependency detection.
- **Agent Context**: Prepares and optimizes context data for execution by different agent types.
- **TodoWrite Tool**: Coordinates bidirectionally with the TodoWrite tool and `TODO_LIST.md` for seamless status updates (`--sync-todos`).
### ⚠️ Error Handling Examples
- **No Active Workflow**:
- `❌ No workflow context found`
- `→ Initialize with: /workflow init`
- **Task Not Found**:
- `❌ Task IMPL-999 does not exist`
- `→ View tasks with: /task:status`
- **Context Conflict**:
- `⚠️ Context conflict detected`
- `→ Resolve with: /task:context --resolve`
### ⚡ Quick Actions
- **Description**: When viewing a single task, an interactive menu of relevant actions is presented.
- **Example Interaction**:
```bash
/task:context IMPL-002
Quick actions available:
1. Execute task (/task:execute IMPL-002)
2. Analyze context (/task:context IMPL-002 --analyze)
3. Replan task (/task:replan IMPL-002)
4. Break down (/task:breakdown IMPL-002)
Select action: 1
→ Executing IMPL-002...
```
### 🤝 Related Commands
- `/task:create`: Creates new tasks.
- `/task:execute`: Executes a specific task.
- `/task:replan`: Replans a task.
- `/task:breakdown`: Breaks a task into subtasks.
- `/task:sync`: Synchronizes all file systems.
- `/workflow:context`: Provides overall workflow status.

View File

@@ -30,6 +30,7 @@ Creates new implementation tasks during IMPLEMENT phase with automatic context a
- **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
### Context Awareness
- Detects current workflow phase (must be IMPLEMENT)
@@ -165,6 +166,127 @@ TODO_LIST.md auto-generation conditions:
- workflow-session.json maintains task list with hierarchy depth
- Automatic validation of cross-file references
## Dynamic Complexity Escalation (NEW FEATURE)
### Automatic Workflow Upgrade System
After each task creation, the system automatically evaluates current workflow complexity and upgrades structure when thresholds are exceeded.
### Escalation Process
```
1. Create New Task → Generate JSON file
2. Count All Tasks → Read all .task/*.json files
3. Calculate Metrics → Tasks, modules, dependencies, effort
4. Check Thresholds → Compare against complexity criteria
5. Trigger Upgrade → If threshold exceeded, escalate complexity
6. Generate Documents → Auto-create missing structure documents
7. Update Session → Record complexity change in workflow-session.json
8. Notify User → Inform about automatic upgrade
```
### Escalation Triggers
#### Simple → Medium Escalation
**Triggered when ANY condition met:**
- Task count reaches 5 (primary trigger)
- Module count exceeds 3
- Total estimated effort > 4 hours
- Complex dependencies detected
- Cross-component changes required
**Actions taken:**
```bash
✅ Task created: impl-5
⚠️ Complexity threshold reached: 5 tasks (exceeds Simple limit)
🔄 Escalating workflow: Simple → Medium
Auto-generating enhanced structure:
✅ Created TODO_LIST.md with hierarchical task display
✅ Created .summaries/ directory for task completion tracking
✅ Updated workflow-session.json complexity level
✅ Enabled 2-level task hierarchy (impl-N.M)
Workflow now supports:
- Progress tracking via TODO_LIST.md
- Task decomposition up to 2 levels
- Summary generation for completed tasks
```
#### Medium → Complex Escalation
**Triggered when ANY condition met:**
- Task count reaches 15 (primary trigger)
- Module count exceeds 5
- Total estimated effort > 2 days
- Multi-repository impacts detected
- Architecture pattern changes required
**Actions taken:**
```bash
✅ Task created: impl-15
⚠️ Complexity threshold reached: 15 tasks (exceeds Medium limit)
🔄 Escalating workflow: Medium → Complex
Auto-generating comprehensive structure:
✅ Enhanced IMPL_PLAN.md with detailed phases and risk assessment
✅ Expanded TODO_LIST.md with progress monitoring
✅ Created comprehensive .summaries/ structure
✅ Updated workflow-session.json complexity level
✅ Enabled 3-level task hierarchy (impl-N.M.P maximum)
Workflow now supports:
- Comprehensive progress tracking and monitoring
- Full 3-level task decomposition
- Enhanced documentation and audit trails
- Advanced dependency management
```
### Complexity Calculation Algorithm
```javascript
function calculateComplexity(tasks, modules, effort, dependencies) {
// Primary thresholds (hard limits)
if (tasks >= 15 || modules > 5 || effort > 48) return 'complex';
if (tasks >= 5 || modules > 3 || effort > 4) return 'medium';
// Override factors (can force higher complexity)
if (dependencies.includes('multi-repo') ||
dependencies.includes('architecture-change')) return 'complex';
if (dependencies.includes('cross-component') ||
dependencies.includes('complex-integration')) return 'medium';
return 'simple';
}
```
### Session State Updates During Escalation
```json
{
"complexity": "medium",
"escalation_history": [
{
"from": "simple",
"to": "medium",
"triggered_at": "2025-09-07T16:45:00Z",
"trigger_reason": "task_count_threshold",
"task_count_at_escalation": 5,
"auto_generated_documents": ["TODO_LIST.md", ".summaries/"],
"task_hierarchy_enabled": 2
}
],
"task_system": {
"max_depth": 2,
"structure_level": "enhanced",
"documents_generated": ["TODO_LIST.md"],
"auto_escalation_enabled": true
}
}
```
### Benefits of Dynamic Escalation
- **Seamless Growth**: Workflows grow naturally without user intervention
- **No Overhead for Simple Tasks**: Simple workflows remain minimal
- **Automatic Structure**: Enhanced documentation appears when needed
- **Progressive Enhancement**: Users get appropriate tooling for current complexity
- **Transparent Process**: All escalations logged and reversible
## Context Inheritance
Tasks automatically inherit:

View File

@@ -23,7 +23,7 @@ Dynamically adjusts task planning based on changes, new requirements, blockers,
⚠️ **CRITICAL**: Before replanning, 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
1. **Query Session Registry**: Check `.workflow/session_status.jsonl` for active sessions. If the file doesn't exist, create it.
2. **Session Validation**: Use existing active session containing the task to be replanned
3. **Context Integration**: Load existing session state and task hierarchy

View File

@@ -1,280 +0,0 @@
---
name: task-sync
description: Synchronize task data with workflow session
usage: /task:sync [--force] [--dry-run]
argument-hint: [optional: force sync or dry run]
examples:
- /task:sync
- /task:sync --force
- /task:sync --dry-run
---
# Task Sync Command (/task:sync)
## Overview
Ensures bidirectional synchronization between hierarchical JSON tasks, TODO_LIST.md, and workflow-session.json.
## Core Principles
**System Architecture:** @~/.claude/workflows/unified-workflow-system-principles.md
## Bidirectional Sync Operations
### 1. JSON Task Files → TODO_LIST.md Sync
**Authoritative Source**: JSON task files in `.task/` directory
- **Status Updates**: pending → active → completed reflected in checkboxes
- **Hierarchical Progress**: Parent progress = average of children (up to 3 levels)
- **Structure Sync**: TODO_LIST.md hierarchy matches JSON parent_id relationships
- **Cross-References**: Links to JSON files and summary files validated
- **Progress Rollup**: Automatic calculation from leaf tasks to root
### 2. JSON Task Files → Workflow Session Sync
**Session State Updates**: workflow-session.json reflects current task state
- **Task Lists**: Main task IDs updated per phase
- **Progress Metrics**: Overall and phase-specific completion percentages
- **Complexity Assessment**: Structure level based on current task count
- **Blocked Task Detection**: Dependency analysis across entire hierarchy
- **Session Metadata**: Last sync timestamps and validation status
### 3. Workflow Session → JSON Task Sync
**Context Propagation**: Session context distributed to individual tasks
- **Global Context**: Workflow requirements inherited by all tasks
- **Requirement Updates**: Changes in session context propagated
- **Issue Associations**: Workflow-level issues linked to relevant tasks
- **Phase Transitions**: Task context updated when phases change
### 4. TodoWrite Tool → File System Sync
**Real-time Coordination**: TodoWrite tool state synced with persistent files
- **Active Task Sync**: TodoWrite status reflected in JSON files
- **Completion Triggers**: TodoWrite completion updates JSON and TODO_LIST.md
- **Progress Coordination**: TodoWrite progress synced with file-based tracking
- **Session Continuity**: TodoWrite state preserved in TODO_LIST.md
## Sync Rules
### Automatic Sync Points
- After `/task:create` - Add to workflow
- After `/task:execute` - Update progress
- After `/task:replan` - Sync changes
- After `/workflow:*` commands - Propagate context
### Conflict Resolution
Priority order:
1. Recently modified (timestamp)
2. More complete data
3. User confirmation (if needed)
## Usage Examples
### Standard Sync with Report Generation
```bash
/task:sync
🔄 Comprehensive Task Synchronization
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
Analyzing file system state...
- JSON task files: 8 tasks across 3 levels in .task/
- TODO_LIST.md: Present, 8 displayed tasks, last modified 2h ago
- workflow-session.json: 3 main tasks tracked, Level 1 structure
- Summary files: 3 completed task summaries in .summaries/
Validating cross-references...
✅ Parent-child relationships: All valid
✅ Hierarchy depth: Within limits (max 3 levels)
✅ File naming: Follows impl-N.M.P format
Found synchronization differences:
- Task impl-1.2: completed in JSON, pending in TODO_LIST.md checkbox
- Progress: impl-1 shows 75% (from subtasks) vs 45% in session
- Hierarchy: impl-2.3.1 exists in JSON but missing from TODO_LIST.md
- Cross-refs: Summary link for impl-1.2 missing in TODO_LIST.md
Synchronizing files...
✅ Updated impl-1.2 checkbox: [ ][x] in TODO_LIST.md
✅ Recalculated hierarchical progress: impl-1 = 75%
✅ Added impl-2.3.1 to TODO_LIST.md hierarchy display
✅ Updated summary link: impl-1.2 → .summaries/IMPL-1.2-summary.md
✅ Propagated context updates to 3 task files
✅ Updated workflow-session.json progress metrics
Generating sync report...
✅ Sync report saved: .summaries/sync-report-20250907-160000.md
Sync complete: 6 updates applied, 0 conflicts resolved
Next sync recommended: In 1 hour or after next task operation
```
### Dry Run with Detailed Analysis
```bash
/task:sync --dry-run
🔍 Sync Analysis (Dry Run Mode)
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
Scanning .task/ directory: 8 JSON files found
Analyzing TODO_LIST.md: Last modified 2h ago
Checking workflow-session.json: In sync
Validating .summaries/: 3 summary files present
Potential changes identified:
Update 2 task statuses: impl-1.2, impl-1.3
Recalculate progress for parent: impl-1 (67% → 75%)
Add 1 missing cross-reference in TODO_LIST.md
Update workflow session progress: 45% → 62%
Generate missing summary link for impl-1.2
File changes would be made to:
- TODO_LIST.md (3 line changes)
- workflow-session.json (progress update)
- No JSON task files need changes (already authoritative)
Conflicts detected: None
Risk level: Low
Estimated sync time: <5 seconds
(No actual changes made - run without --dry-run to apply)
```
### Force Sync with Backup
```bash
/task:sync --force
⚠️ Force Sync Mode - Creating Backups
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
Backing up current state...
✅ TODO_LIST.md → .summaries/backup-TODO_LIST-20250907-160000.md
✅ workflow-session.json → .summaries/backup-session-20250907-160000.json
Force sync operations:
❗ Using JSON task files as authoritative source
❗ Overwriting TODO_LIST.md without conflict resolution
❗ Rebuilding workflow-session.json task data
❗ Regenerating all cross-references
❗ Recalculating all progress from scratch
Sync completed with authority conflicts resolved:
3 conflicts overwritten in favor of JSON files
✅ TODO_LIST.md completely regenerated
✅ workflow-session.json task list rebuilt
✅ All cross-references validated and updated
Backup files available for rollback if needed:
- .summaries/backup-TODO_LIST-20250907-160000.md
- .summaries/backup-session-20250907-160000.json
Force sync report: .summaries/force-sync-20250907-160000.md
```
## Data Integrity Checks
### Validation Steps
1. **File Existence**: Both JSON files exist
2. **Session Match**: Same session_id
3. **ID Consistency**: All task IDs valid
4. **Status Logic**: No impossible states
5. **Progress Math**: Calculation accurate
### Error Recovery
```bash
❌ Sync failed: tasks.json corrupted
→ Attempting recovery from backup...
✅ Restored from backup
→ Retry sync? (y/n)
```
## Progress Calculation
```javascript
progress = (completed_tasks / total_tasks) * 100
// With subtasks
weighted_progress = sum(task.weight * task.progress) / total_weight
```
## JSON Updates
### workflow-session.json
```json
{
"phases": {
"IMPLEMENT": {
"tasks": ["IMPL-001", "IMPL-002", "IMPL-003"],
"completed_tasks": ["IMPL-001", "IMPL-002"],
"progress": 67,
"last_sync": "2025-01-16T14:00:00Z"
}
}
}
```
### Individual Task Files
Each task file maintains sync metadata:
```json
{
"id": "IMPL-001",
"title": "Build authentication module",
"status": "completed",
"type": "feature",
"agent": "code-developer",
"metadata": {
"created_at": "2025-09-05T10:30:00Z",
"started_at": "2025-09-05T10:35:00Z",
"completed_at": "2025-09-05T13:15:00Z",
"last_updated": "2025-09-05T13:15:00Z",
"last_sync": "2025-09-05T13:15:00Z",
"version": "1.0"
}
}
```
## Performance & File Management
### Sync Performance
- **Incremental Analysis**: Only processes changed files since last sync
- **Cached Validation**: Reuses validation results for unchanged files
- **Batch File Updates**: Groups related changes for efficiency
- **Typical Sync Time**: <100ms for standard workflows, <500ms for complex
### Generated Reports
**Automatic Documentation**: Every sync creates audit trail
- **Standard Sync Report**: `.summaries/sync-report-[timestamp].md`
- **Dry Run Analysis**: `.summaries/sync-analysis-[timestamp].md`
- **Force Sync Report**: `.summaries/force-sync-[timestamp].md`
- **Conflict Resolution Log**: Embedded in sync reports
- **Backup Files**: Created during force operations
### File System Maintenance
- **Cleanup Policy**: Keep last 10 sync reports, archive older ones
- **Backup Management**: Automatic cleanup of force sync backups after 7 days
- **Error Recovery**: Complete rollback capability from backup files
- **Integrity Monitoring**: Continuous validation of file system consistency
## File System Integration
### Integration Points
- **JSON Task Files**: Authoritative source for all task data
- **TODO_LIST.md**: Display layer synchronized from JSON files
- **workflow-session.json**: High-level session state and progress
- **Summary Files**: Completion documentation linked from TODO_LIST.md
- **TodoWrite Tool**: Real-time task management interface
### File Output Summary
**Generated Files**:
- **Sync Reports**: `.summaries/sync-report-[timestamp].md`
- **Backup Files**: `.summaries/backup-[file]-[timestamp].[ext]`
- **Analysis Reports**: `.summaries/sync-analysis-[timestamp].md`
- **Updated TODO_LIST.md**: Refreshed with current task state
- **Updated workflow-session.json**: Current progress and task references
### Quality Assurance
- **Pre-sync Validation**: File existence and format checks
- **Post-sync Verification**: Cross-reference validation
- **Rollback Testing**: Backup restoration validation
- **Performance Monitoring**: Sync time and efficiency tracking
## Related Commands
- `/task:context --sync-check` - Validate current sync status
- `/task:create` - Creates tasks requiring sync
- `/task:execute` - Generates summaries requiring sync
- `/task:replan` - Structural changes requiring sync
- `/workflow:sync` - Full workflow document synchronization

View File

@@ -40,7 +40,7 @@ Creates actionable implementation plans based on brainstorming insights or direc
⚠️ **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
1. **Query Session Registry**: Check `.workflow/session_status.jsonl` for active sessions. If the file doesn't exist, create it.
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
@@ -67,7 +67,7 @@ Creates actionable implementation plans based on brainstorming insights or direc
### Phase 1: Context Understanding & Structure Establishment
1. **Session Detection & Selection**:
- **Check Active Sessions**: Query `.workflow/session_status.jsonl` for existing active sessions
- **Check Active Sessions**: Query `.workflow/session_status.jsonl` for existing active sessions. If the file doesn't exist, create it.
- **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
@@ -104,9 +104,70 @@ Creates actionable implementation plans based on brainstorming insights or direc
- **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
8. **Auto-Generate Tasks (NEW)**: Parse IMPL_PLAN.md and automatically create corresponding task JSON files
- **Extract Tasks**: Parse task identifiers (IMPL-001, IMPL-002, etc.) from plan
- **Create Task Files**: Generate `.task/impl-*.json` files with plan context
- **Link to Plan**: Include `source_plan_ref` field linking tasks back to plan sections
- **Set Dependencies**: Establish task dependencies based on plan structure
9. **Link Documents**: Update JSON state with generated document paths
9. **Update Session**: Mark PLAN phase complete with document references and generated task list
10. **Link Documents**: Update JSON state with generated document paths and task file references
## Automated Task Generation (Single Source of Truth Integration)
### Planning-to-Execution Automation
**NEW FEATURE**: Eliminates the gap between planning and execution by automatically creating executable task files from planning documents.
### Task Extraction Process
1. **Parse IMPL_PLAN.md**: Scan for task identifiers in standardized format:
- `IMPL-001`, `IMPL-002`, etc. (main tasks)
- `IMPL-1.1`, `IMPL-1.2`, etc. (subtasks)
- Task titles and descriptions from plan sections
2. **Generate Task JSON Files**: For each identified task, create structured JSON:
```json
{
"id": "IMPL-001",
"title": "Foundation/Infrastructure setup",
"status": "pending",
"type": "infrastructure",
"agent": "code-developer",
"effort": "2h",
"context": {
"inherited_from": "WFS-[topic-slug]",
"source_plan_ref": "IMPL_PLAN.md#phase-1-foundation",
"requirements": ["Extracted from plan description"],
"scope": ["Derived from plan context"],
"acceptance": ["Extracted from success criteria"]
},
"dependencies": {
"upstream": [],
"downstream": ["IMPL-002"],
"phase_group": "Phase 1: Foundation"
},
"metadata": {
"created_at": "2025-09-07T15:00:00Z",
"created_by": "workflow:action-plan",
"auto_generated": true,
"plan_version": "1.0"
}
}
```
3. **Link Bidirectionally**:
- Task files reference plan sections
- Session state includes all generated task IDs
- Ready for immediate execution via `/task:execute`
### Benefits of Automation
- **Zero Manual Task Creation**: Plans immediately become executable
- **Consistency**: All tasks derive from same authoritative plan
- **Traceability**: Clear linkage from requirements through plan to tasks
- **Immediate Execution**: Can run `/task:execute IMPL-001` immediately after planning
## Session State Analysis & Document Understanding
@@ -269,27 +330,42 @@ Generated documents are stored in session directory:
└── workflow-session.json # Updated with document references
```
## Session Updates
## Session Updates (Enhanced with Task Generation)
```json
{
"phases": {
"PLAN": {
"status": "completed",
"output": {
"primary": "IMPL_PLAN.md"
"primary": "IMPL_PLAN.md",
"tasks_generated": [".task/impl-001.json", ".task/impl-002.json", ".task/impl-003.json"]
},
"documents_generated": ["IMPL_PLAN.md"],
"tasks_auto_created": 3,
"completed_at": "2025-09-05T11:00:00Z",
"tasks_identified": ["IMPL-001", "IMPL-002", "IMPL-003"]
"tasks_identified": ["IMPL-001", "IMPL-002", "IMPL-003"],
"ready_for_implementation": true
}
},
"documents": {
"planning": {
"IMPL_PLAN.md": {
"status": "generated",
"path": ".workflow/WFS-[topic-slug]/IMPL_PLAN.md"
"path": ".workflow/WFS-[topic-slug]/IMPL_PLAN.md",
"tasks_extracted": 3,
"auto_generation": "completed"
}
}
},
"task_system": {
"enabled": true,
"auto_generated": true,
"directory": ".workflow/WFS-[topic-slug]/.task/",
"task_count": {
"total": 3,
"pending": 3,
"from_planning": 3
}
}
}
```

View File

@@ -109,7 +109,7 @@ END FUNCTION
⚠️ **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
1. **Query Session Registry**: Check `.workflow/session_status.jsonl` for active sessions. If the file doesn't exist, create it.
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

View File

@@ -1,398 +0,0 @@
---
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

@@ -179,24 +179,6 @@ When starting a new session, the following files are automatically generated:
*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`

View File

@@ -1,311 +0,0 @@
---
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

View File

@@ -61,8 +61,8 @@ Your response **MUST** be in Chinese and structured in Markdown as follows:
* **观察到的行为 (Observed Behavior):** [清晰、客观地转述用户报告的异常现象或日志中的错误信息。]
* **预期的行为 (Expected Behavior):** [描述在正常情况下,系统或功能应有的表现。]
* **1.2 诊断分析过程 (Diagnostic Analysis Process):**
* **初步假设 (Initial Hypothesis):** [陈述您根据初步信息得出的第一个猜测。例如:初步判断,问题可能出在数据解析环节,因为错误日志显示了格式不匹配’。”]
* **根本原因分析 (Root Cause Analysis - RCA):** [**这是报告的核心。** 详细阐述您的逻辑推理过程,说明您是如何从表象追踪到根源的。例如:通过检查 `data_parser.py``parse_record` 函数,发现当输入记录的某个可选字段缺失时,代码并未处理该 `None` 值,而是直接对其调用了 `strip()` 方法,从而导致了 `AttributeError`。因此,**根本原因**是:**对可能为 None 的变量在未进行空值检查的情况下直接调用了方法**。]
* **初步假设 (Initial Hypothesis):** [陈述您根据初步信息得出的第一个猜测。例如:初步判断,问题可能出在数据解析环节,因为错误日志显示了格式不匹配]
* **根本原因分析 (Root Cause Analysis - RCA):** [**这是报告的核心。** 详细阐述您的逻辑推理过程,说明您是如何从表象追踪到根源的。例如:通过检查 `data_parser.py``parse_record` 函数,发现当输入记录的某个可选字段缺失时,代码并未处理该 `None` 值,而是直接对其调用了 `strip()` 方法,从而导致了 `AttributeError`。因此,**根本原因**是:**对可能为 None 的变量在未进行空值检查的情况下直接调用了方法**。]
* **1.3 根本原因摘要 (Root Cause Summary):** [用一句话高度概括 bug 的根本原因。]
### **第二部分:涉及文件概览 (Part 2: Involved Files Overview)**
@@ -86,7 +86,7 @@ Your response **MUST** be in Chinese and structured in Markdown as follows:
* **3. 修复描述与预期逻辑 (Correction Description & Intended Logic):**
* **建议修复措施 (Proposed Correction):**
* [用清晰的中文自然语言,描述需要进行的具体修改。例如:在调用 `.strip()` 方法之前,增加一个条件判断,检查 `value` 变量是否不为 `None`。]
* [用清晰的中文自然语言,描述需要进行的具体修改。例如:在调用 `.strip()` 方法之前,增加一个条件判断,检查 `value` 变量是否不为 `None`。]
* **修复后逻辑示意 (Corrected Logic Sketch):**
* [使用简洁的 `diff` 风格或伪代码来直观展示修改。]
* **示例:**
@@ -104,11 +104,11 @@ Your response **MUST** be in Chinese and structured in Markdown as follows:
END IF
... (后续逻辑使用 processed_value) ...
```
* **修复理由 (Reason for Correction):** [解释为什么这个修改能解决之前分析出的**根本原因**。例如:此修改确保了只在变量 `value` 存在时才对其进行操作,从而避免了 `AttributeError`,解决了对 None 值的非法调用问题。]
* **修复理由 (Reason for Correction):** [解释为什么这个修改能解决之前分析出的**根本原因**。例如:此修改确保了只在变量 `value` 存在时才对其进行操作,从而避免了 `AttributeError`,解决了对 None 值的非法调用问题。]
* **4. 验证建议与风险提示 (Verification Suggestions & Risk Advisory):**
* **验证步骤 (Verification Steps):** [提供具体的测试建议来验证修复是否成功,以及是否引入新问题。例如:1. 构造一个optional_field字段存在的测试用例确认其能被正常处理。2. **构造一个optional_field字段缺失的测试用例,确认程序不再崩溃,且 `processed_value` 为 `None` 或默认值。**]
* **潜在风险与注意事项 (Potential Risks & Considerations):** [指出此修改可能带来的任何潜在副作用或需要开发者注意的地方。例如:请注意,下游消费 `processed_value` 的代码现在必须能够正确处理 `None` 值。请检查相关调用方是否已做相应处理。]
* **验证步骤 (Verification Steps):** [提供具体的测试建议来验证修复是否成功以及是否引入新问题。例如1. 构造一个optional_field字段存在的测试用例确认其能被正常处理。2. **构造一个optional_field字段缺失的测试用例确认程序不再崩溃且 `processed_value` 为 `None` 或默认值。**]
* **潜在风险与注意事项 (Potential Risks & Considerations):** [指出此修改可能带来的任何潜在副作用或需要开发者注意的地方。例如:请注意,下游消费 `processed_value` 的代码现在必须能够正确处理 `None` 值。请检查相关调用方是否已做相应处理。]
---
*(对每个需要修改的文件重复上述格式)*

View File

@@ -57,7 +57,7 @@ Your response **MUST** be in Chinese and structured in Markdown as follows:
### **代码修改规划方案 (Code Modification Plan)**
### **第一部分:需求分析与规划总览 (Part 1: Requirements Analysis & Planning Overview)**
* **1.1 用户原始需求结构化解析 (Structured Analysis of User's Original Requirements):**
* **1.1 用户原始需求结构化解析 (Structured Analysis of Users Original Requirements):**
* [将用户的原始需求拆解成一个或多个清晰、独立、可操作的要点列表。每个要点都是一个明确的目标。]
* **- 需求点 A:** [描述第一个具体需求]
* **- 需求点 B:** [描述第二个具体需求]
@@ -78,7 +78,7 @@ Your response **MUST** be in Chinese and structured in Markdown as follows:
* [清晰说明函数、类、方法或具体的代码区域,如果可能,指出大致行号范围。示例: 函数 `calculate_total_price` 内部,约第 75-80 行]
* **1.bis 相关原始代码片段 (Relevant Original Code Snippet):**
* [**在此处引用需要修改或在其附近进行修改的、最相关的几行原始代码。** 这为开发者提供了直接的上下文。如果代码未提供,则注明相关代码未提供,根据描述进行规划。]
* [**在此处引用需要修改或在其附近进行修改的、最相关的几行原始代码。** 这为开发者提供了直接的上下文。如果代码未提供,则注明相关代码未提供,根据描述进行规划。]
* ```[language]
// 引用相关的1-5行原始代码
```
@@ -109,16 +109,16 @@ Your response **MUST** be in Chinese and structured in Markdown as follows:
## VII. KEY DIRECTIVES & CONSTRAINTS
1. **Language**: **All** descriptive parts of your plan **MUST** be in **Chinese**.
2. **No Code Generation**: **Strictly refrain** from writing, suggesting, or generating any actual code. Your output is *purely* a descriptive modification plan.
3. **Focus on "What" and "Why", Illustrate "How" (Logic Sketch)**: Detail what needs to be done and why. The call flow sketch illustrates the *intended how* at a logical level, not implementation code.
4. **Completeness & Accuracy**: Ensure the plan is comprehensive. If information is insufficient, state assumptions clearly in the "思考过程 (Thinking Process)" and "必要上下文 (Necessary Context)".
3. **Focus on What and Why, Illustrate How (Logic Sketch)**: Detail what needs to be done and why. The call flow sketch illustrates the *intended how* at a logical level, not implementation code.
4. **Completeness & Accuracy**: Ensure the plan is comprehensive. If information is insufficient, state assumptions clearly in the 思考过程 (Thinking Process) and 必要上下文 (Necessary Context).
5. **Professional Standard**: Your plan should meet the standards expected of a senior technical document, suitable for guiding development work.
## VIII. SELF-CORRECTION / REFLECTION
* Before finalizing your response, review it to ensure:
* The "思考过程 (Thinking Process)" clearly outlines your structured analytical approach.
* All user requirements from "需求分析" have been addressed in the plan.
* The 思考过程 (Thinking Process) clearly outlines your structured analytical approach.
* All user requirements from 需求分析 have been addressed in the plan.
* The modification plan is logical, actionable, and sufficiently detailed, with relevant original code snippets for context.
* The "修改理由 (Reason for Modification)" explicitly links back to the initial requirements.
* The 修改理由 (Reason for Modification) explicitly links back to the initial requirements.
* All crucial context and risks are highlighted.
* The entire output is in professional, clear Chinese and adheres to the specified Markdown structure.
* You have strictly avoided generating any code.

View File

@@ -1,8 +1,10 @@
# JSON-Document Coordination System
# JSON-Document Coordination System (Single Source of Truth)
## Overview
This document provides technical implementation details for JSON file structures, synchronization mechanisms, conflict resolution, and performance optimization.
This document defines the **Single Source of Truth** architecture where JSON files are the authoritative state source and all markdown documents are read-only, generated views. This eliminates bidirectional synchronization complexity and data conflicts.
**Key Principle**: `.task/*.json` files are the **only** authoritative source of task state. All markdown documents (`TODO_LIST.md`, progress displays, etc.) are generated on-demand from JSON data.
### JSON File Hierarchy
```
@@ -184,23 +186,13 @@ TODO_LIST.md serves as both the task registry and progress display:
}
```
## Coordination Mechanisms
## Single Source of Truth Architecture
### 1. Data Ownership Rules
### 1. Data Authority (Simplified)
#### Documents Own (Authoritative)
**IMPL_PLAN.md:**
- **Implementation Strategy**: Overall approach, phases, risk assessment
- **Requirements**: High-level functional requirements
- **Context**: Global project context, constraints
**TODO_LIST.md:**
- **Progress Visualization**: Task status display, completion tracking
- **Checklist Format**: Checkbox representation of task hierarchy
#### JSON Files Own (Authoritative)
- **Complete Task Definitions**: Full task context, requirements, acceptance criteria
- **Hierarchical Relationships**: Parent-child links, depth management
#### JSON Files Own (ONLY Authoritative Source)
- **ALL Task State**: Complete task definitions, status, progress, metadata
- **Hierarchical Relationships**: Parent-child links, depth management
- **Execution State**: pending/active/completed/blocked/failed
- **Progress Data**: Percentages, timing, checkpoints
- **Agent Assignment**: Current agent, execution history
@@ -208,154 +200,95 @@ TODO_LIST.md serves as both the task registry and progress display:
- **Session Metadata**: Timestamps, versions, attempt counts
- **Runtime State**: Current attempt, active processes
#### Shared Responsibility (Synchronized)
- **Task Status**: JSON authoritative, TODO_LIST.md displays current state
- **Progress Calculations**: Derived from JSON hierarchy, shown in TODO_LIST.md
- **Cross-References**: JSON contains document refs, documents link to relevant tasks
- **Task Hierarchy**: JSON defines structure, TODO_LIST.md visualizes it
#### Documents Are Read-Only Views (Generated Only)
- **IMPL_PLAN.md**: Static planning document (manually created, rarely changes)
- **TODO_LIST.md**: **Generated view** from JSON files (never manually edited)
- **Progress Reports**: **Generated views** from JSON data
- **Status Displays**: **Generated views** from JSON state
### 2. Synchronization Events
#### No Shared Responsibility (Eliminates Conflicts)
- **Single Direction Flow**: JSON → Markdown (never Markdown → JSON)
- **No Synchronization**: Documents are generated, not synchronized
- **No Conflicts**: Only one source of truth eliminates data conflicts
#### Document → JSON Synchronization
### 2. View Generation (Replaces Synchronization)
#### No Document → JSON Flow (Eliminated)
**Documents are read-only**: No parsing, no status updates from documents
**No bidirectional sync**: Documents cannot modify JSON state
**No conflict resolution needed**: Single direction eliminates conflicts
#### JSON → View Generation (On Demand)
**Trigger Events**:
- IMPL_PLAN.md modified (strategy/context changes)
- TODO_LIST.md checkboxes changed (manual status updates)
- Document structure changes affecting task references
- User requests context view (`/context`)
- Task status changed in JSON files
- View generation requested by commands
**Actions**:
```javascript
// Pseudo-code for document sync process
on_document_change(document_path) {
if (document_path.includes('IMPL_PLAN.md')) {
const context_changes = parse_context_updates(document_path);
propagate_context_to_tasks(context_changes);
log_sync_event('impl_plan_to_json', document_path);
// Pseudo-code for view generation process
on_view_request(view_type, options) {
const task_data = load_all_task_json_files();
const session_data = load_workflow_session();
if (view_type === 'todo_list') {
const todo_view = generate_todo_list_view(task_data);
return render_markdown_view(todo_view);
}
if (document_path.includes('TODO_LIST.md')) {
const status_changes = parse_checkbox_updates(document_path);
update_task_status_from_todos(status_changes);
recalculate_hierarchy_progress(status_changes);
update_session_progress();
log_sync_event('todo_list_to_json', document_path);
if (view_type === 'progress') {
const progress = calculate_progress_from_json(task_data);
return render_progress_view(progress, session_data);
}
if (view_type === 'status') {
const status = compile_status_from_json(task_data, session_data);
return render_status_view(status);
}
}
```
#### JSON → Document Synchronization
**Trigger Events**:
- Task status changed in JSON files
- New task created via decomposition
- Task hierarchy modified (parent-child relationships)
- Progress checkpoint reached
- Task completion cascading up hierarchy
### 3. View Generation Process (Replaces Real-Time Sync)
**Actions**:
```javascript
// Pseudo-code for JSON sync process
on_task_change(task_id, change_type, data) {
// Update TODO_LIST.md with current task status
update_todo_list_display(task_id, data.status);
if (change_type === 'status_change' && data.new_status === 'completed') {
// Recalculate parent task progress
update_parent_progress(task_id);
check_dependency_unblocking(task_id);
}
if (change_type === 'task_decomposition') {
// Add new subtasks to TODO_LIST.md
add_subtasks_to_todo_list(data.subtasks);
update_todo_list_hierarchy(task_id, data.subtasks);
}
update_session_coordination_metadata();
log_sync_event('json_to_todo_list', task_id);
}
#### On-Demand View Process
```
1. Command Request → User requests view (`/context`)
2. JSON Loader → Reads all task JSON files
3. Data Processor → Calculates progress, status, hierarchy
4. View Generator → Creates markdown representation
5. Display → Returns formatted view to user
```
### 3. Real-Time Coordination Process
#### Automatic Sync Process
```
1. File System Watcher → Detects document changes
2. Change Parser → Extracts structured data from documents
3. Conflict Detector → Identifies synchronization conflicts
4. Sync Engine → Applies changes based on ownership rules
5. Validation → Verifies consistency across all files
6. Audit Logger → Records all sync events
```
#### Manual Sync Triggers
#### Context Command (Replaces Sync Commands)
```bash
# Force complete synchronization
/task:sync --all
# Generate todo list view
/context
# Sync specific task
/task:sync IMPL-001
# Generate task-specific view
/context IMPL-001
# Validate and repair sync issues
/task:sync --validate --repair
# Generate progress view
/context --format=progress
# View sync status
/task:sync --status
# Generate status view with health check
/context --health-check
```
## Conflict Resolution
## No Conflict Resolution Needed (Architecture Benefit)
### Conflict Types and Resolution
### Eliminated Conflict Types
#### 1. Timestamp Conflicts
**Scenario**: Both document and JSON modified simultaneously
**Resolution**: Most recent timestamp wins, with manual review option
#### Conflicts That No Longer Exist
- **Timestamp Conflicts**: No bidirectional updates means no timestamp conflicts
- **Data Authority Conflicts**: Only JSON has authority, documents are read-only
- **Hierarchy Conflicts**: JSON defines structure, documents display it (no conflicts)
- **Sync State Conflicts**: No synchronization means no sync state issues
```json
{
"conflict_type": "timestamp",
"document_timestamp": "2025-09-05T11:20:00Z",
"json_timestamp": "2025-09-05T11:19:30Z",
"resolution": "document_wins",
"manual_review_required": false
}
```
#### 2. Data Authority Conflicts
**Scenario**: Task status changed directly in TODO_LIST.md vs JSON file
**Resolution**: Determine if change is authorized checkbox update or unauthorized edit
```json
{
"conflict_type": "data_authority",
"field": "task_status",
"document_value": "completed",
"json_value": "active",
"change_source": "checkbox|direct_edit",
"resolution": "checkbox_authorized|json_authority",
"action": "accept_checkbox_change|revert_document_change"
}
```
#### 3. Hierarchy Conflicts
**Scenario**: Task decomposition modified in JSON but TODO_LIST.md structure differs
**Resolution**: JSON hierarchy is authoritative, TODO_LIST.md updated
```json
{
"conflict_type": "hierarchy",
"conflict_description": "Task impl-1 subtasks differ between JSON and TODO display",
"json_subtasks": ["impl-1.1", "impl-1.2", "impl-1.3"],
"todo_display": ["impl-1.1", "impl-1.2"],
"resolution": "json_authority",
"action": "update_todo_list_structure",
"manual_validation_required": false
}
```
### Conflict Resolution Priority
1. **Data Ownership Rules**: Respect authoritative source
2. **Recent Timestamp**: When ownership is shared
3. **User Intent**: Manual resolution for complex conflicts
4. **System Consistency**: Maintain cross-file integrity
### Simplified Data Model Benefits
- **Zero Conflicts**: Single source of truth eliminates all data conflicts
- **No Resolution Logic**: No complex conflict detection or resolution needed
- **Reduced Complexity**: Eliminates entire conflict resolution subsystem
- **Improved Reliability**: Cannot have data drift or inconsistency issues
## Validation and Integrity