refactor: consolidate workflow documentation into unified architecture

- Create unified workflow-architecture.md combining:
  - data-model.md (JSON-only architecture, task schemas)
  - file-structure-standards.md (progressive structures, templates)
  - session-management-principles.md (marker files, session ops)
  - complexity-rules.md (classification thresholds, behaviors)

- Update 11 files with references to new consolidated document
- Remove redundant documentation while preserving all functionality
- Streamline maintenance with single source of truth

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

Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
catlog22
2025-09-09 22:15:17 +08:00
parent 48843cc256
commit f76e5edbdf
17 changed files with 657 additions and 1593 deletions

View File

@@ -177,7 +177,7 @@ Your primary responsibilities:
2. **Stage Design**: Break complex work into 3-5 logical stages. 2. **Stage Design**: Break complex work into 3-5 logical stages.
**Stage format specification**: @~/.claude/workflows/file-structure-standards.md#stage-based-format-simple-tasks **Stage format specification**: @~/.claude/workflows/workflow-architecture.md#stage-based-format-simple-tasks
Each stage should include: Each stage should include:
- A specific, measurable deliverable - A specific, measurable deliverable
@@ -188,13 +188,13 @@ Your primary responsibilities:
3. **Implementation Plan Creation**: Generate a structured `IMPL_PLAN.md` document in the `.workflow/WFS-[session-id]/` directory. 3. **Implementation Plan Creation**: Generate a structured `IMPL_PLAN.md` document in the `.workflow/WFS-[session-id]/` directory.
**Document Format Standards**: @~/.claude/workflows/file-structure-standards.md#impl_planmd-structure **Document Format Standards**: @~/.claude/workflows/workflow-architecture.md#impl_planmd-templates
- Use **Stage-Based Format** for simple, linear tasks - Use **Stage-Based Format** for simple, linear tasks
- Use **Hierarchical Format** for complex tasks (>5 subtasks or >3 modules) - Use **Hierarchical Format** for complex tasks (>5 subtasks or >3 modules)
4. **Task Decomposition for Complex Projects**: For complex tasks involving >5 subtasks or spanning >3 modules, create detailed task decomposition and tracking documents. 4. **Task Decomposition for Complex Projects**: For complex tasks involving >5 subtasks or spanning >3 modules, create detailed task decomposition and tracking documents.
**Hierarchical format specification**: @~/.claude/workflows/file-structure-standards.md#hierarchical-format-complex-tasks **Hierarchical format specification**: @~/.claude/workflows/workflow-architecture.md#hierarchical-format-complex-tasks
**Task Decomposition Criteria**: **Task Decomposition Criteria**:
- Tasks requiring >5 distinct subtasks - Tasks requiring >5 distinct subtasks
@@ -204,10 +204,10 @@ Your primary responsibilities:
- Tasks with significant uncertainty or risk factors - Tasks with significant uncertainty or risk factors
**Enhanced IMPL_PLAN.md structure for complex tasks**: **Enhanced IMPL_PLAN.md structure for complex tasks**:
See @~/.claude/workflows/file-structure-standards.md#hierarchical-format-complex-tasks See @~/.claude/workflows/workflow-architecture.md#hierarchical-format-complex-tasks
**Generate TODO_LIST.md** in `.workflow/WFS-[session-id]/` directory: **Generate TODO_LIST.md** in `.workflow/WFS-[session-id]/` directory:
See @~/.claude/workflows/file-structure-standards.md#todo_listmd-structure See @~/.claude/workflows/workflow-architecture.md#todo_listmd-template
**Note**: Keep TODO_LIST.md format simple and focused on task tracking. Avoid complex sections unless specifically needed. **Note**: Keep TODO_LIST.md format simple and focused on task tracking. Avoid complex sections unless specifically needed.
@@ -218,7 +218,7 @@ Your primary responsibilities:
- All documents created in `.workflow/WFS-[session-id]/` directory - All documents created in `.workflow/WFS-[session-id]/` directory
- Unified session tracking in `.workflow/WFS-[session-id]/workflow-session.json` - Unified session tracking in `.workflow/WFS-[session-id]/workflow-session.json`
**Full format specifications**: @~/.claude/workflows/file-structure-standards.md **Full format specifications**: @~/.claude/workflows/workflow-architecture.md
6. **Incremental Progress Focus**: Ensure each stage: 6. **Incremental Progress Focus**: Ensure each stage:
- Can be completed independently - Can be completed independently
@@ -256,11 +256,11 @@ Your primary responsibilities:
**Planning Session Management and Automatic Document Generation Logic**: **Planning Session Management and Automatic Document Generation Logic**:
**Directory structure standards**: @~/.claude/workflows/file-structure-standards.md#progressive-structure-system **Directory structure standards**: @~/.claude/workflows/workflow-architecture.md#progressive-structure-system
### Feature-Based Directory Structure ### Feature-Based Directory Structure
**See complete directory structure standards**: @~/.claude/workflows/file-structure-standards.md#progressive-structure-system **See complete directory structure standards**: @~/.claude/workflows/workflow-architecture.md#progressive-structure-system
Directory organization follows progressive complexity levels: Directory organization follows progressive complexity levels:
- **Level 0**: Minimal structure (<5 tasks) - **Level 0**: Minimal structure (<5 tasks)
@@ -269,11 +269,11 @@ Directory organization follows progressive complexity levels:
**Note**: When DEEP_ANALYSIS_REQUIRED mode is active, Gemini analysis results are integrated directly into IMPL_PLAN.md rather than as a separate file. **Note**: When DEEP_ANALYSIS_REQUIRED mode is active, Gemini analysis results are integrated directly into IMPL_PLAN.md rather than as a separate file.
**Session Tracker Format**: See @~/.claude/workflows/file-structure-standards.md for `workflow-session.json` structure **Session Tracker Format**: See @~/.claude/workflows/workflow-architecture.md for `workflow-session.json` structure
**File Naming Conventions**: @~/.claude/workflows/file-structure-standards.md#file-naming-conventions **File Naming Conventions**: @~/.claude/workflows/workflow-architecture.md#file-naming-conventions
**Session Naming**: Follow @~/.claude/workflows/file-structure-standards.md#session-identifiers **Session Naming**: Follow @~/.claude/workflows/workflow-architecture.md#session-identifiers
- Format: `WFS-[topic-slug]` - Format: `WFS-[topic-slug]`
- Convert to kebab-case - Convert to kebab-case
- Add numeric suffix only if conflicts exist - Add numeric suffix only if conflicts exist
@@ -326,7 +326,7 @@ Directory organization follows progressive complexity levels:
}) })
# Step 4: Generate planning documents in workflow directory # Step 4: Generate planning documents in workflow directory
# All document formats follow: @~/.claude/workflows/file-structure-standards.md # All document formats follow: @~/.claude/workflows/workflow-architecture.md
combined_context = merge_contexts(session_context, gemini_context) # Merge session and Gemini contexts combined_context = merge_contexts(session_context, gemini_context) # Merge session and Gemini contexts
if (subtasks > 5 OR modules > 3 OR high_complexity): if (subtasks > 5 OR modules > 3 OR high_complexity):
@@ -334,7 +334,7 @@ Directory organization follows progressive complexity levels:
generate_task_decomposition(combined_context, workflow_dir) # Architecture-aligned hierarchy with session decisions generate_task_decomposition(combined_context, workflow_dir) # Architecture-aligned hierarchy with session decisions
generate_todo_list(combined_context, workflow_dir) # Pattern-aware task list with session continuity generate_todo_list(combined_context, workflow_dir) # Pattern-aware task list with session continuity
create_document_links() # Cross-reference linking with relative paths create_document_links() # Cross-reference linking with relative paths
create_summaries_directory(f"{workflow_dir}/.summaries/") # See @~/.claude/workflows/file-structure-standards.md#summary-management create_summaries_directory(f"{workflow_dir}/.summaries/") # See @~/.claude/workflows/workflow-architecture.md#file-structure
update_session_action_checkpoint() # Save action phase progress update_session_action_checkpoint() # Save action phase progress
elif (components > 3 OR estimated_loc > 100): elif (components > 3 OR estimated_loc > 100):
generate_implementation_plan(combined_context, workflow_dir) # Session + context-aware staged plan generate_implementation_plan(combined_context, workflow_dir) # Session + context-aware staged plan

View File

@@ -16,7 +16,7 @@ examples:
Generates on-demand views from JSON task data. No synchronization needed - all views are calculated from the current state of JSON files. Generates on-demand views from JSON task data. No synchronization needed - all views are calculated from the current state of JSON files.
## Core Principles ## Core Principles
**Data Source:** @~/.claude/workflows/data-model.md **Data Source:** @~/.claude/workflows/workflow-architecture.md
## Key Features ## Key Features

View File

@@ -198,7 +198,7 @@ This template is automatically filled and generated after execution.
- **IF active session exists**: Save to existing `.workflow/WFS-[topic-slug]/.chat/` directory - **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 - **IF no active session**: Create new session directory following WFS naming convention
**Session Management**: @~/.claude/workflows/session-management-principles.md **Session Management**: @~/.claude/workflows/workflow-architecture.md
- **File Format**: `execute-YYYYMMDD-HHMMSS.md` with timestamp for unique identification. - **File Format**: `execute-YYYYMMDD-HHMMSS.md` with timestamp for unique identification.
- **Structure**: Integrates with session management system using WFS-[topic-slug] format for consistency. - **Structure**: Integrates with session management system using WFS-[topic-slug] format for consistency.
- **Coordination**: Session files coordinate with workflow-session.json and maintain document-state separation. - **Coordination**: Session files coordinate with workflow-session.json and maintain document-state separation.

View File

@@ -15,7 +15,7 @@ examples:
Intelligently breaks down complex tasks into manageable subtasks with automatic context distribution and agent assignment. Intelligently breaks down complex tasks into manageable subtasks with automatic context distribution and agent assignment.
## Core Principles ## Core Principles
**Task Schema:** @~/.claude/workflows/data-model.md **Task Schema:** @~/.claude/workflows/workflow-architecture.md
## Features ## Features

View File

@@ -15,7 +15,7 @@ examples:
Creates new implementation tasks during IMPLEMENT phase with automatic context awareness and ID generation. Creates new implementation tasks during IMPLEMENT phase with automatic context awareness and ID generation.
## Core Principles ## Core Principles
**Task Management:** @~/.claude/workflows/data-model.md **Task Management:** @~/.claude/workflows/workflow-architecture.md
## Features ## Features

View File

@@ -12,7 +12,7 @@ examples:
### 🚀 **Command Overview: `/task:execute`** ### 🚀 **Command Overview: `/task:execute`**
- **Purpose**: Executes tasks using intelligent agent selection, context preparation, and progress tracking. - **Purpose**: Executes tasks using intelligent agent selection, context preparation, and progress tracking.
- **Core Principles**: @~/.claude/workflows/data-model.md - **Core Principles**: @~/.claude/workflows/workflow-architecture.md
### ⚙️ **Execution Modes** ### ⚙️ **Execution Modes**

View File

@@ -15,7 +15,7 @@ examples:
Replans individual tasks based on detailed user input with comprehensive change tracking, version management, and document synchronization. Focuses exclusively on single-task modifications with rich input options. Replans individual tasks based on detailed user input with comprehensive change tracking, version management, and document synchronization. Focuses exclusively on single-task modifications with rich input options.
## Core Principles ## Core Principles
**Task Management:** @~/.claude/workflows/data-model.md **Task Management:** @~/.claude/workflows/workflow-architecture.md
## Single-Task Focus ## Single-Task Focus
This command operates on **individual tasks only**. For workflow-wide changes, use `/workflow:action-plan` instead. This command operates on **individual tasks only**. For workflow-wide changes, use `/workflow:action-plan` instead.

View File

@@ -14,7 +14,7 @@ Coordinates multiple agents for executing existing workflow tasks through automa
## Core Principles ## Core Principles
**Session Management:** @~/.claude/workflows/session-management-principles.md **Session Management:** @~/.claude/workflows/workflow-architecture.md
**Agent Orchestration:** @~/.claude/workflows/agent-orchestration-patterns.md **Agent Orchestration:** @~/.claude/workflows/agent-orchestration-patterns.md
## Execution Philosophy ## Execution Philosophy

View File

@@ -16,7 +16,7 @@ examples:
Creates actionable implementation plans with intelligent input source detection. Supports text, files, issues, and templates through automatic recognition. Creates actionable implementation plans with intelligent input source detection. Supports text, files, issues, and templates through automatic recognition.
## Core Principles ## Core Principles
**File Structure:** @~/.claude/workflows/file-structure-standards.md **File Structure:** @~/.claude/workflows/workflow-architecture.md
## Usage ## Usage
```bash ```bash

View File

@@ -13,7 +13,7 @@ examples:
Final phase for quality validation, testing, and completion. Final phase for quality validation, testing, and completion.
## Core Principles ## Core Principles
**Session Management:** @~/.claude/workflows/session-management-principles.md **Session Management:** @~/.claude/workflows/workflow-architecture.md
## Review Process ## Review Process

View File

@@ -1,199 +0,0 @@
# Workflow Complexity Rules
## Overview
This document defines unified complexity classification rules across all workflow components, ensuring consistent thresholds and scaling behavior throughout the system.
## Complexity Classification
### Unified Thresholds
**Based on task count for consistent classification across all system components**
| Complexity | Task Count | Max Hierarchy Depth | File Structure Level |
|------------|------------|-------------------|-------------------|
| **Simple** | <5 tasks | 1 level (impl-N) | Level 0 - Minimal |
| **Medium** | 5-15 tasks | 2 levels (impl-N.M) | Level 1 - Enhanced |
| **Complex** | >15 tasks | 3 levels (impl-N.M.P) | Level 2 - Complete |
## Simple Workflows
### Characteristics
- **Direct implementation tasks** with clear, limited scope
- **Single-file or small-module changes**
- **Clear requirements** without complex dependencies
- **Atomic functionality** that can be implemented in one session
### System Behavior
- **File Structure**: Minimal directory structure (Level 0)
- **Task Hierarchy**: Single level only (impl-1, impl-2, etc.)
- **Documentation**: Basic IMPL_PLAN.md, no TODO_LIST.md
- **Agent Coordination**: Direct execution without complex orchestration
### Examples
- Bug fixes in existing functionality
- Small feature additions to existing modules
- Documentation updates
- Configuration changes
- Simple utility functions
## Medium Workflows
### Characteristics
- **Feature implementation** requiring task breakdown
- **Multiple file modifications** across related modules
- **Some integration requirements** with existing systems
- **Clear feature boundaries** with moderate complexity
### System Behavior
- **File Structure**: Enhanced directory structure (Level 1)
- **Task Hierarchy**: Two levels (impl-N.M format)
- **Documentation**: IMPL_PLAN.md + auto-triggered TODO_LIST.md
- **Agent Coordination**: Context-driven coordination with shared state
### Auto-trigger Conditions
TODO_LIST.md and enhanced structure triggered when:
- Task count > 5 OR
- Modules affected > 3 OR
- Estimated effort > 4h OR
- Complex inter-module dependencies exist
### Examples
- New feature implementation within existing architecture
- API endpoint creation with frontend integration
- Database schema changes with application updates
- Authentication/authorization enhancements
- Performance optimization across multiple components
## Complex Workflows
### Characteristics
- **System-wide changes** requiring detailed decomposition
- **Architectural modifications** affecting multiple systems
- **Cross-team coordination** or external dependencies
- **High-risk changes** requiring extensive testing and review
### System Behavior
- **File Structure**: Complete directory structure (Level 2)
- **Task Hierarchy**: Three levels maximum (impl-N.M.P format)
- **Documentation**: Comprehensive planning + progress tracking + summaries
- **Agent Coordination**: Multi-agent orchestration with deep context analysis
### Examples
- New major feature development
- System architecture refactoring
- Third-party service integrations
- Security implementations (OAuth, encryption)
- Database migrations with application changes
- Multi-service deployments
## Complexity Assessment Rules
### Automatic Classification
**System evaluates tasks during creation and applies appropriate complexity level**
```pseudo
function classify_complexity(tasks, scope, dependencies):
task_count = count(tasks)
if task_count < 5 and scope.is_simple() and not dependencies.complex():
return SIMPLE
elif task_count <= 15 and scope.is_moderate():
return MEDIUM
else:
return COMPLEX
```
### Upgrade Triggers
**Complexity can be upgraded during workflow execution**
- **Simple → Medium**: When subtasks are created or scope expands
- **Medium → Complex**: When task count exceeds 15 or deep hierarchy needed
- **No Downgrades**: Complexity level never decreases to prevent data loss
### Override Rules
**Manual complexity override allowed for edge cases**
- User can specify higher complexity at workflow creation
- System warnings issued for mismatched complexity/scope
- Cannot specify lower complexity than system assessment
## Component Integration
### File Structure Mapping
**Complexity directly determines file structure level**
| Complexity | Directory Structure | Required Files |
|------------|-------------------|---------------|
| Simple | Minimal (.task/, .summaries/) | workflow-session.json, IMPL_PLAN.md |
| Medium | Enhanced (+ TODO_LIST.md) | + Auto-generated progress tracking |
| Complex | Complete (+ comprehensive docs) | + Full documentation suite |
### Agent Orchestration Mapping
**Complexity determines agent coordination patterns**
| Complexity | Gemini Analysis | Agent Coordination | Review Process |
|------------|----------------|-------------------|---------------|
| Simple | Focused file-level | Direct context-aware execution | Quick validation |
| Medium | Comprehensive multi-file | Context-driven coordination | Thorough single-pass |
| Complex | Deep system-wide | Multi-agent orchestration | Multiple review iterations |
### Task Hierarchy Mapping
**Complexity enforces hierarchy depth limits**
- **Simple**: Single level (impl-N)
- **Medium**: Two levels (impl-N.M)
- **Complex**: Three levels maximum (impl-N.M.P)
## Decision Tree
### Workflow Creation
```
Start: Analyze user requirements
├─ Task count < 5 AND single module AND clear scope?
│ └─ YES → SIMPLE workflow
├─ Task count ≤ 15 AND moderate scope AND some integration?
│ └─ YES → MEDIUM workflow
└─ Task count > 15 OR system-wide OR high-risk?
└─ YES → COMPLEX workflow
```
### Complexity Upgrade Assessment
```
During Execution: Monitor task growth
├─ Simple workflow + subtasks created?
│ └─ Upgrade to MEDIUM
├─ Medium workflow + task count > 15?
│ └─ Upgrade to COMPLEX
└─ Any workflow + architectural changes?
└─ Consider upgrade to COMPLEX
```
## Quality Assurance
### Validation Rules
- Complexity level must match actual task count
- File structure must align with complexity level
- Agent coordination patterns must match complexity
- Documentation completeness must match complexity requirements
### Performance Monitoring
- Track completion times by complexity level
- Monitor accuracy of initial complexity assessments
- Adjust thresholds based on historical data
- Measure overhead costs of each complexity level
### Consistency Checks
- All system components use same complexity thresholds
- Cross-references between complexity-dependent files are valid
- Upgrade paths preserve existing work and structure
- No orphaned files after complexity changes
---
**System ensures**: Unified complexity classification across all workflow components with consistent scaling behavior and automatic optimization for task scope and system performance

View File

@@ -1,264 +0,0 @@
# Workflow Data Model
## Overview
This document defines the complete data model for the workflow system using a **JSON-only architecture**. JSON task files are the single source of truth, with all documents generated on-demand as read-only views.
## Core Data Architecture
### Key Principle: JSON-Only Data Model
**JSON files (.task/impl-*.json) are the only authoritative source of task state. All markdown documents are read-only generated views that never persist state.**
- **Task State**: Stored exclusively in JSON files
- **Documents**: Generated on-demand from JSON data
- **No Synchronization**: Eliminates bidirectional sync complexity
- **Performance**: Direct JSON access without parsing overhead
## Task JSON Schema
### Core Task Structure
All task files use this simplified 8-field schema:
```json
{
"id": "impl-1",
"title": "Build authentication module",
"status": "pending",
"type": "feature",
"agent": "code-developer",
"context": {
"requirements": ["JWT authentication", "OAuth2 support"],
"scope": ["src/auth/*", "tests/auth/*"],
"acceptance": ["Module handles JWT tokens", "OAuth2 flow implemented"],
"inherited_from": "WFS-user-auth"
},
"relations": {
"parent": null,
"subtasks": ["impl-1.1", "impl-1.2"],
"dependencies": ["impl-0"]
},
"execution": {
"attempts": 0,
"last_attempt": null
},
"meta": {
"created": "2025-09-05T10:30:00Z",
"updated": "2025-09-05T10:30:00Z"
}
}
```
### Status Values
- **pending**: Task created but not started
- **active**: Task currently being worked on
- **completed**: Task successfully finished
- **blocked**: Task cannot proceed due to dependencies
- **container**: Parent task with subtasks (not directly executable)
### Task Types
- **feature**: New functionality implementation
- **bugfix**: Fixing existing issues
- **refactor**: Code improvement without functionality change
- **test**: Test implementation or testing tasks
- **docs**: Documentation creation or updates
## Hierarchical Task System
### Task Hierarchy Rules
**Maximum Depth**: 3 levels (impl-N.M.P format)
```
impl-1 # Main task
impl-1.1 # Subtask of impl-1
impl-1.1.1 # Detailed subtask of impl-1.1
impl-1.2 # Another subtask of impl-1
impl-2 # Another main task
```
### Parent-Child Relationships
```json
// Parent task
{
"id": "impl-1",
"title": "Build authentication module",
"status": "pending",
"relations": {
"parent": null,
"subtasks": ["impl-1.1", "impl-1.2"],
"dependencies": []
}
}
// Child task
{
"id": "impl-1.1",
"title": "Design auth schema",
"status": "pending",
"relations": {
"parent": "impl-1",
"subtasks": [],
"dependencies": []
}
}
```
### Task Status Rules
#### Container Task Rules
- Parent tasks become "container" status when broken down
- Cannot be directly executed (must execute subtasks)
- Status derived from subtask completion
#### Leaf Task Rules
- Only leaf tasks can be executed directly
- Status reflects actual execution state
- Progress tracked at leaf level only
## Context Management
### Context Structure
Context provides complete information for agent execution:
- **requirements**: Specific functional requirements
- **scope**: File patterns and modules affected
- **acceptance**: Success criteria and completion definition
- **inherited_from**: Source workflow or parent task
### Context Inheritance
- **Workflow → Task**: Global requirements and constraints
- **Parent → Subtask**: Refined scope and specific requirements
- **Context Preservation**: All fields maintained for agent execution
## Complexity Classification
### Simple Workflows
**Criteria**: Direct implementation tasks with clear scope
- **Structure**: Single-level tasks (impl-N format)
- **Task Files**: impl-*.json only
- **Max Depth**: 1 level
- **Task Count**: <5 tasks
### Medium Workflows
**Criteria**: Feature implementation requiring task breakdown
- **Structure**: Two-level hierarchy (impl-N.M format)
- **Task Files**: Parent and child JSON files
- **Max Depth**: 2 levels
- **Task Count**: 5-15 tasks
### Complex Workflows
**Criteria**: System-wide changes requiring detailed decomposition
- **Structure**: Three-level hierarchy (impl-N.M.P format)
- **Task Files**: Multi-level JSON hierarchy
- **Max Depth**: 3 levels (maximum allowed)
- **Task Count**: >15 tasks
## Agent Integration
### Agent Assignment
Based on task type and title keywords:
- **Planning tasks** → planning-agent
- **Implementation** → code-developer
- **Testing** → test-agent
- **Documentation** → docs-agent
- **Review** → review-agent
### Execution Context
Agents receive complete task JSON plus workflow context:
```json
{
"task": { /* complete task JSON */ },
"workflow": {
"session": "WFS-user-auth",
"phase": "IMPLEMENT"
}
}
```
## File Organization
### JSON Task Files
**Location**: `.task/impl-[id].json`
**Naming**: Follows hierarchical ID format
**Content**: Complete task definition
### Document Generation
**On-Demand**: Documents generated from JSON when requested
**Read-Only**: Documents never store state
**Templates**: Standard templates for consistent output
#### Generated Documents
- `TODO_LIST.md`: Task progress view generated from JSON
- `IMPL_PLAN.md`: Planning document with task references
- Task summaries: Generated from completed task JSON
## Data Operations
### Task Creation
```bash
# Create new task JSON file
echo '{"id":"impl-1","title":"New task",...}' > .task/impl-1.json
```
### Task Updates
```bash
# Update task status directly in JSON
jq '.status = "active"' .task/impl-1.json > temp && mv temp .task/impl-1.json
```
### Document Generation
```bash
# Generate TODO_LIST.md from current JSON state
generate_todo_list_from_json .task/
```
## Validation Rules
### Task Integrity
1. **ID Uniqueness**: All task IDs must be unique
2. **Hierarchical Format**: Must follow impl-N[.M[.P]] pattern
3. **Parent References**: All parent IDs must exist as JSON files
4. **Depth Limits**: Maximum 3 levels deep
5. **Status Consistency**: Status values from defined enumeration
6. **Required Fields**: All 8 core fields must be present
### Relationship Validation
- Parent-child relationships must be bidirectional
- Dependencies must reference existing tasks
- Container tasks cannot be completed until all subtasks complete
- No circular dependencies allowed
## Error Handling
### Common Scenarios
1. **Missing JSON File**: Indicates broken reference - must repair
2. **Invalid Status**: Update to valid status value
3. **Broken Hierarchy**: Reconstruct parent-child relationships
4. **Orphaned Task**: Reassign to proper parent or workflow
### Recovery Strategy
- **JSON Authoritative**: Task JSON files are source of truth
- **Validation Warnings**: For non-critical inconsistencies
- **Manual Resolution**: For complex relationship conflicts
- **Document Regeneration**: Recreate documents from JSON when corrupted
## Performance Benefits
### JSON-Only Architecture
- **Direct Access**: No document parsing overhead
- **Atomic Updates**: Single file operations
- **No Sync Conflicts**: Eliminates coordination complexity
- **Fast Queries**: Direct JSON traversal
- **Scalability**: Handles hundreds of tasks efficiently
### On-Demand Generation
- **Memory Efficient**: Documents created only when needed
- **Always Fresh**: Generated views reflect current state
- **No Stale Data**: Eliminates sync lag issues
---
**System ensures**: Consistent task management using simplified JSON-only data model with complete context preservation for agent execution and on-demand document generation for human readability

View File

@@ -1,388 +0,0 @@
# Workflow File Structure Standards
## Overview
This document defines directory layouts, file naming conventions, and progressive complexity structures for workflow sessions.
## Progressive Structure System
**Complexity → Structure Level**
File structure scales with task complexity to minimize overhead for simple tasks while providing comprehensive organization for complex workflows.
### Level 0: Minimal Structure (<5 tasks)
**Target**: Simple workflows with clear, limited scope
```
.workflow/WFS-[topic-slug]/
├── workflow-session.json # Session metadata and state
├── [.brainstorming/] # Optional brainstorming phase
├── [.chat/] # Gemini CLI interaction sessions
│ └── chat-*.md # Saved chat sessions with timestamps
├── IMPL_PLAN.md # Combined planning document
├── .summaries/ # Task completion summaries
│ └── IMPL-*.md # Individual task summaries
└── .task/
└── impl-*.json # Task definitions
```
### Level 1: Enhanced Structure (5-15 tasks)
**Target**: Medium complexity workflows with multiple phases
```
.workflow/WFS-[topic-slug]/
├── workflow-session.json # Session metadata and state
├── [.brainstorming/] # Optional brainstorming phase
├── [.chat/] # Gemini CLI interaction sessions
│ └── chat-*.md # Saved chat sessions with timestamps
├── IMPL_PLAN.md # Combined planning document
├── TODO_LIST.md # Auto-triggered progress tracking
├── .summaries/ # Task completion summaries
│ ├── IMPL-*.md # Main task summaries
│ └── IMPL-*.*.md # Subtask summaries
└── .task/
├── impl-*.json # Main task definitions
└── impl-*.*.json # Subtask definitions (up to 3 levels)
```
### Level 2: Complete Structure (>15 tasks)
**Target**: Complex workflows with extensive documentation needs
```
.workflow/WFS-[topic-slug]/
├── workflow-session.json # Session metadata and state
├── [.brainstorming/] # Optional brainstorming phase
├── [.chat/] # Gemini CLI interaction sessions
│ ├── chat-*.md # Saved chat sessions with timestamps
│ └── analysis-*.md # Comprehensive analysis results
├── IMPL_PLAN.md # Comprehensive planning document
├── TODO_LIST.md # Progress tracking and monitoring
├── .summaries/ # Task completion summaries
│ ├── IMPL-*.md # Main task summaries
│ ├── IMPL-*.*.md # Subtask summaries
│ └── IMPL-*.*.*.md # Detailed subtask summaries
└── .task/
├── impl-*.json # Task hierarchy (max 3 levels deep)
├── impl-*.*.json # Subtasks
└── impl-*.*.*.json # Detailed subtasks
```
## File Naming Conventions
### Session Identifiers
**Format**: `WFS-[topic-slug]`
- Convert topic to lowercase with hyphens (e.g., "User Auth System" → `WFS-user-auth-system`)
- Add `-NNN` suffix only if conflicts exist (e.g., `WFS-payment-integration-002`)
### Task File Naming
**Hierarchical ID Format**:
```
impl-1 # Main task
impl-1.1 # Subtask of impl-1
impl-1.1.1 # Detailed subtask of impl-1.1
impl-1.2 # Another subtask of impl-1
impl-2 # Another main task
```
**Maximum Depth**: 3 levels (impl-N.M.P)
### Document Naming
- `workflow-session.json` - Session state (required)
- `IMPL_PLAN.md` - Planning document (required)
- `TODO_LIST.md` - Progress tracking (auto-generated when needed)
- Chat sessions: `chat-YYYYMMDD-HHMMSS.md`
- Analysis results: `analysis-[topic].md`
- Task summaries: `IMPL-[task-id]-summary.md`
## Directory Structure Rules
### Required Directories
- `.task/` - Always present, contains JSON task definitions
- `.summaries/` - Always present, contains task completion documentation
### Optional Directories
- `.brainstorming/` - Present when brainstorming phase was used
- `.chat/` - Present when Gemini CLI sessions were saved
### Directory Permissions and Access
- All workflow directories are project-local
- Active session marked by `.workflow/.active-[session-name]` marker file (global)
- Individual sessions in `.workflow/WFS-[topic-slug]/` (session-specific)
## Document Generation Triggers
### Automatic Document Creation
**Based on complexity assessment**:
| **Complexity** | **IMPL_PLAN.md** | **TODO_LIST.md** | **Task Files** |
|----------------|------------------|------------------|----------------|
| Simple (<5 tasks) | Always | No | impl-*.json |
| Medium (5-15 tasks) | Always | Auto-trigger* | impl-*.*.json |
| Complex (>15 tasks) | Always | Always | impl-*.*.*.json |
**Auto-trigger conditions (*):**
- Tasks > 5 OR modules > 3 OR estimated effort > 4h OR complex dependencies
### Document Template Standards
#### IMPL_PLAN.md Structure
Two formats available based on task complexity:
##### Stage-Based Format (Simple Tasks)
Use for tasks with clear, linear progression:
```markdown
# Implementation Plan: [Task Name]
## Overview
[Brief description of the overall goal and approach]
## Requirements
[Functional and non-functional requirements]
## [Brainstorming Integration]
[If .brainstorming/ exists - reference analysis results]
## Stage 1: [Name]
**Goal**: [Specific deliverable]
**Success Criteria**:
- [Testable outcome 1]
- [Testable outcome 2]
**Tests**:
- [Specific test case 1]
- [Specific test case 2]
**Dependencies**: [Previous stages or external requirements]
**Estimated Effort**: [Small/Medium/Large]
**Review Status**: [Not Started]
**Status**: [Not Started]
## Stage 2: [Name]
[Repeat stage structure]
## Stage 3: [Name]
[Repeat stage structure]
## Risk Mitigation
[Identified risks and mitigation strategies]
## Rollback Strategy
[How to revert if issues arise]
```
##### Hierarchical Format (Complex Tasks)
Use for tasks requiring >5 subtasks or spanning >3 modules:
```markdown
# Implementation Plan: [Project Name]
## Overview
[Brief description and strategic approach]
## Requirements
[Functional and non-functional requirements]
## Task Hierarchy
### Main Task: [IMPL-001] [Primary Goal]
**Description**: [Detailed description]
**Complexity**: [High/Medium/Low]
**Estimated Effort**: [Time estimate]
**Dependencies**: [External dependencies]
**Status**: [Not Started]
#### Subtask: [IMPL-001.1] [Subtask Name]
**Description**: [Specific deliverable]
**Assigned Agent**: [code-developer/code-review-agent/general-purpose]
**Dependencies**: [Parent/peer task dependencies]
**Acceptance Criteria**:
- [Testable criteria 1]
- [Testable criteria 2]
**Estimated Effort**: [Time estimate]
**Assigned Module**: [Component/file location]
**Status**: [Not Started]
**Links**: [Related documentation/requirements]
##### Action Item: [IMPL-001.1.1] [Specific Action]
**Type**: [Code/Test/Documentation/Review]
**Recommended Agent**: [code-developer/code-review-agent/general-purpose]
**Description**: [Concrete action]
**Files Affected**: [List of files]
**Verification**: [How to verify completion]
**Status**: [Not Started]
[Repeat structure for all tasks/subtasks/actions]
### Main Task: [IMPL-002] [Secondary Goal]
[Repeat task structure]
## Dependency Graph
[Visual or text representation of task dependencies]
## Resource Requirements
[Tools, libraries, external dependencies needed]
## Risk Assessment
[Task-specific risks and mitigation strategies]
## Rollback Strategy
[System-wide rollback procedures]
```
#### TODO_LIST.md Structure
**Keep simple and focused on task tracking:**
```markdown
# Task Progress List: [Session Topic]
## Implementation Tasks
### Main Tasks
- [ ] **IMPL-001**: [Task Description] → [📋 Details](./.task/impl-001.json)
- [x] **IMPL-002**: [Completed Task] → [📋 Details](./.task/impl-002.json) | [✅ Summary](./.summaries/IMPL-002-summary.md)
### Subtasks (Auto-expanded when active)
- [ ] **IMPL-001.1**: [Subtask Description] → [📋 Details](./.task/impl-001.1.json)
- [ ] **IMPL-001.1.1**: [Action Item] → [📋 Details](./.task/impl-001.1.1.json)
- [ ] **IMPL-001.2**: [Subtask Description] → [📋 Details](./.task/impl-001.2.json)
## Notes
[Quick notes and reminders for the project]
```
**Format Notes**:
- Main tasks use bold formatting: `**IMPL-XXX**`
- Subtasks indent under parent tasks
- Links to task JSON files for details
- Links to summaries when completed
- Keep format simple and scannable
## Chat Session Management
### Chat Directory Structure
```
.chat/
├── chat-YYYYMMDD-HHMMSS.md # Individual chat sessions with timestamps
├── analysis-[topic].md # Comprehensive analysis results
└── context-[phase].md # Phase-specific context gathering
```
### Chat Session Template
```markdown
# Chat Session: [Timestamp] - [Topic]
## Query
[Original user inquiry]
## Template Used
[Auto-selected template name and rationale]
## Context
[Files and patterns included in analysis]
## Gemini Response
[Complete response from Gemini CLI]
## Key Insights
- [Important findings]
- [Architectural insights]
- [Implementation recommendations]
## Links
- [🔙 Back to Workflow](../workflow-session.json)
- [📋 Implementation Plan](../IMPL_PLAN.md)
```
## Summary Management
### Summary Directory Structure
```
.summaries/
├── IMPL-001-summary.md # Main task summaries
├── IMPL-001.1-summary.md # Subtask summaries
└── IMPL-001.1.1-summary.md # Detailed subtask summaries
```
### Summary Template
```markdown
# Task Summary: [Task-ID] [Task Name]
## What Was Done
- [Files modified/created]
- [Functionality implemented]
- [Key changes made]
## Issues Resolved
- [Problems solved]
- [Bugs fixed]
## Links
- [🔙 Back to Task List](../TODO_LIST.md#[Task-ID])
- [📋 Implementation Plan](../IMPL_PLAN.md#[Task-ID])
```
## Brainstorming Integration
When `.brainstorming/` directory exists, documents MUST reference brainstorming results:
### In IMPL_PLAN.md
```markdown
## Brainstorming Integration
Based on multi-role analysis from `.brainstorming/`:
- **Architecture Insights**: [Reference system-architect/analysis.md]
- **User Experience Considerations**: [Reference ui-designer/analysis.md]
- **Technical Requirements**: [Reference relevant role analyses]
- **Implementation Priorities**: [Reference synthesis-analysis.md]
```
### In JSON Task Context
```json
{
"context": {
"brainstorming_refs": [
".workflow/WFS-[topic-slug]/.brainstorming/system-architect/technical-specifications.md",
".workflow/WFS-[topic-slug]/.brainstorming/ui-designer/user-experience-plan.md"
],
"requirements": ["derived from brainstorming analysis"]
}
}
```
## Quality Control
### File System Validation
- Verify directory structure matches complexity level
- Validate file naming conventions
- Check for required vs optional directories
- Ensure proper file permissions
### Cross-Reference Validation
- All document links point to existing files
- Task IDs consistent across JSON files and TODO_LIST.md
- Brainstorming references are valid when .brainstorming/ exists
- Summary links properly reference parent tasks
### Performance Considerations
- Lazy directory creation (create only when needed)
- Efficient file structure scanning
- Minimal overhead for simple workflows
- Scalable organization for complex projects
## Error Recovery
### Missing File Scenarios
- **workflow-session.json missing**: Recreate from available documents
- **Required directories missing**: Auto-create with proper structure
- **Template files corrupted**: Regenerate from templates
- **Naming convention violations**: Auto-correct or flag for manual resolution
### Structure Consistency
- Validate structure level matches task complexity
- Auto-upgrade structure when complexity increases
- Maintain backward compatibility during transitions
- Preserve existing content during structure changes
---
**System ensures**: Consistent, scalable file organization with minimal overhead for simple tasks → comprehensive structure for complex projects

View File

@@ -1,239 +1,201 @@
```markdown
--- ---
name: gemini-unified name: gemini-unified
description: Consolidated Gemini CLI guidelines - core rules, syntax, patterns, templates, and best practices description: Consolidated Gemini CLI guidelines - core rules, syntax, patterns, templates, and best practices
type: technical-guideline type: technical-guideline
--- ---
# Unified Gemini CLI Guidelines ### 🚀 Command Overview: `gemini`
## 🚀 Core Rules - **Purpose**: A CLI tool for comprehensive codebase analysis, context gathering, and pattern detection across multiple files.
- **Primary Triggers**:
- When user intent is to "analyze", "get context", or "understand the codebase".
- When a task requires understanding relationships between multiple files.
- When the problem scope exceeds a single file.
- **Core Use Cases**:
- Project-wide context acquisition.
- Architectural analysis and pattern detection.
- Identification of coding standards and conventions.
### When to Trigger ### ⚙️ Command Syntax & Arguments
- **Semantic Intent**: User asks to "analyze with Gemini", "get context", or "understand codebase"
- **Context Need**: Task requires understanding multiple files or relationships
- **Complex Analysis**: Problem exceeds single-file scope
### Primary Use Cases - **Basic Structure**:
- Project context acquisition and codebase understanding ```bash
- Pattern detection and architectural analysis gemini [flags] -p "@{patterns} {template} prompt"
- Standards extraction and convention identification ```
- **Key Arguments**:
- `--all-files`: Includes all files in the current working directory.
- `-p`: The prompt string, which must contain file reference patterns and the analysis query.
- `{template}`: Template injection using `$(cat ~/.claude/workflows/gemini-templates/prompts/[category]/[template].txt)` for standardized analysis
- `@{pattern}`: A special syntax for referencing files and directories.
### Standard Template Structure - **Template Usage**:
```bash
# Without template (manual prompt)
gemini -p "@{src/**/*} @{CLAUDE.md} Analyze code patterns and conventions"
# With template (recommended)
gemini -p "@{src/**/*} @{CLAUDE.md} $(cat ~/.claude/workflows/gemini-templates/prompts/analysis/pattern.txt)"
# Multi-template composition
gemini -p "@{src/**/*} @{CLAUDE.md} $(cat <<'EOF'
$(cat ~/.claude/workflows/gemini-templates/prompts/analysis/architecture.txt)
Additional Security Focus:
$(cat ~/.claude/workflows/gemini-templates/prompts/analysis/security.txt)
EOF
)"
```
#### Basic Structure (Manual Prompts) ### 🔄 Execution Modes
```bash
gemini --all-files -p "@{target_patterns} @{CLAUDE.md,**/*CLAUDE.md}
Context: [Analysis type] targeting @{target_patterns} - **1. Directory-Scoped**: Navigate to a directory first, then run `gemini`.
Guidelines: Include CLAUDE.md standards ```bash
cd src/components && gemini --all-files -p "@{CLAUDE.md} Analyze component patterns"
```
- **2. Pattern-Based**: Target files directly from any location using patterns.
```bash
gemini -p "@{src/components/**/*} @{CLAUDE.md} Analyze component patterns"
```
- **3. Template-Injected**: Use `$(cat)` to inject a predefined prompt template.
```bash
gemini -p "@{src/**/*} $(cat ~/.claude/workflows/gemini-templates/prompts/analysis/pattern.txt)"
```
- **4. Parallel Execution**: Run multiple analyses concurrently for efficiency.
```bash
(
gemini -p "@{**/*auth*} @{CLAUDE.md} Auth patterns" &
gemini -p "@{**/api/**/*} @{CLAUDE.md} API patterns" &
wait
)
```
## Analysis: ### 📂 File Pattern Rules
1. [Point 1]
2. [Point 2]
3. [Point 3]
## Output: - **Syntax**:
- File:line references - `@{pattern}`: Single file or directory pattern.
- Code examples - `@{pattern1,pattern2}`: Multiple patterns, comma-separated.
- Actionable guidance - **Wildcards**:
- Standards compliance" ```bash
* # Any character (excluding path separators)
** # Any directory levels (recursive)
? # Any single character
[abc] # Any character within the brackets
{a,b,c} # Any of the options within the braces
```
- **Cross-Platform Rules**:
- Always use forward slashes (`/`) for paths.
- Enclose paths with spaces in quotes: `@{"My Project/src/**/*"}`.
- Escape special characters like brackets: `@{src/**/*\[bracket\]*}`.
### 🧠 Smart Pattern Discovery - Logic Flow
This feature automates the process of finding relevant files for analysis.
`Step 1: Analyze File Extensions` -> `Step 2: Generate Patterns` -> `Step 3: Execute Gemini`
```pseudo
FUNCTION analyze_and_run_gemini(analysis_type):
// Step 1: Analyze the project's file types.
// Corresponds to the `discover_extensions` shell function.
discovered_extensions = analyze_project_extensions()
log("Discovered extensions:", discovered_extensions)
// Also identify the likely primary programming language.
// Corresponds to the `detect_primary_language` shell function.
primary_language = detect_main_language(discovered_extensions)
log("Primary language:", primary_language)
// Step 2: Generate file patterns based on the analysis type (e.g., "code", "config").
// Corresponds to the `generate_patterns_by_extension` shell function.
patterns = generate_patterns(analysis_type, discovered_extensions)
log("Generated patterns:", patterns)
// Step 3: Construct and execute the gemini command.
// Always include project standards from CLAUDE.md.
// Uses a pre-defined analysis template for consistency.
command = "gemini -p \"" + patterns + " @{CLAUDE.md} $(cat ~/.claude/workflows/gemini-templates/prompts/analysis/pattern.txt)\""
execute_shell(command)
END FUNCTION
``` ```
#### Template-Enhanced Structure (Recommended) ### 📜 Smart Discovery - Shell Implementation
```bash
# Using predefined templates for consistent analysis
gemini --all-files -p "@{target_patterns} @{CLAUDE.md,**/*CLAUDE.md}
$(cat ~/.claude/workflows/gemini-templates/prompts/[category]/[template].txt)"
```
#### Template Reference Examples These functions provide the concrete implementation for the smart discovery logic.
```bash
# Pattern analysis with template
gemini -p "@{src/**/*} @{CLAUDE.md} $(cat ~/.claude/workflows/gemini-templates/prompts/analysis/pattern.txt)"
# Architecture analysis with template - **Step 1: Analyze File Extensions & Language**
gemini -p "@{src/**/*} @{CLAUDE.md} $(cat ~/.claude/workflows/gemini-templates/prompts/analysis/architecture.txt)" ```bash
# Discover actual file types in project
discover_extensions() {
echo "=== File Extension Analysis ==="
find . -type f -name "*.*" 2>/dev/null | \
sed 's/.*\.//' | \
sort | uniq -c | sort -rn | \
head -10
}
# Multi-template composition # Identify primary language
gemini -p "@{src/**/*} @{CLAUDE.md} $(cat <<'EOF' detect_primary_language() {
$(cat ~/.claude/workflows/gemini-templates/prompts/analysis/pattern.txt) local extensions=$(find . -type f -name "*.*" 2>/dev/null | sed 's/.*\.//' | sort | uniq -c | sort -rn)
if echo "$extensions" | grep -q "js\|jsx\|ts\|tsx"; then
echo "JavaScript/TypeScript"
elif echo "$extensions" | grep -q "py\|pyw"; then
echo "Python"
# ... other language checks ...
else
echo "Unknown/Mixed"
fi
}
```
- **Step 2: Generate Patterns**
```bash
# Generate patterns from discovered extensions
generate_patterns_by_extension() {
local analysis_type="$1"
local top_exts=$(find . -type f -name "*.*" 2>/dev/null | sed 's/.*\.//' | sort | uniq -c | sort -rn | head -5 | awk '{print $2}')
local pattern=""
case "$analysis_type" in
"code")
for ext in $top_exts; do
case $ext in
js|ts|jsx|tsx|py|java|go|rs|cpp|c|h)
pattern="${pattern}**/*.${ext},"
;;
esac
done
echo "@{${pattern%,}}"
;;
"config") echo "@{*.json,*.yml,*.yaml,*.toml,*.ini,*.env}" ;;
"docs") echo "@{**/*.md,**/*.txt,**/README*}" ;;
"all")
for ext in $top_exts; do pattern="${pattern}**/*.${ext},"; done
echo "@{${pattern%,}}"
;;
esac
}
```
Additional Security Focus: ### ⚡ Smart Discovery - Quick Commands
$(cat ~/.claude/workflows/gemini-templates/prompts/analysis/security.txt)
EOF
)"
```
**Template Benefits:** | Need | Command | Description |
- **Consistency**: Standardized analysis structure across all uses |------|---------|-------------|
- **Completeness**: Pre-defined analysis points ensure comprehensive coverage | Analyze Extensions | `discover_extensions` | View project file type distribution. |
- **Quality**: Proven analysis frameworks with specific output requirements | Code Files | `generate_patterns_by_extension "code"` | Generate patterns for source code files only. |
- **Efficiency**: No need to manually construct analysis prompts | Config Files | `generate_patterns_by_extension "config"` | Generate patterns for configuration files. |
| Docs | `generate_patterns_by_extension "docs"` | Generate patterns for documentation. |
| All Top Types | `generate_patterns_by_extension "all"` | Generate patterns for all discovered file types. |
**Mandatory**: Always include `@{CLAUDE.md,**/*CLAUDE.md}` for project standards. ### TPL (Templates)
## Command Syntax #### 🗂 Template Directory Structure
This structure must be located at `~/.claude/workflows/gemini-templates/`.
### Basic Structure
```bash
gemini [flags] -p "@{patterns} prompt"
```
### Key Arguments
- `--all-files`: Includes all files in current directory (path-dependent)
- `-p`: Prompt string with file patterns and query
- `@{pattern}`: File reference pattern
### Execution Modes
#### 1. Directory-Scoped
Navigate first, then execute:
```bash
cd src/components && gemini --all-files -p "@{CLAUDE.md} Analyze patterns"
```
#### 2. Pattern-Based
Target files directly:
```bash
gemini -p "@{src/components/**/*} @{CLAUDE.md} Component analysis"
```
#### 3. Template-Injected
Use `$(cat)` for templates:
```bash
gemini -p "@{src/**/*} $(cat ~/.claude/workflows/gemini-templates/prompts/analysis/pattern.txt)"
```
#### 4. Parallel Execution
Multiple analyses concurrently:
```bash
(
gemini -p "@{**/*auth*} @{CLAUDE.md} Auth patterns" &
gemini -p "@{**/api/**/*} @{CLAUDE.md} API patterns" &
wait
)
```
## 📂 File Patterns
### Pattern Syntax
```bash
@{pattern} # Single pattern
@{pattern1,pattern2} # Multiple patterns
```
### Wildcards
```bash
* # Any character (not path separators)
** # Any directory levels
? # Single character
[abc] # Character in brackets
{a,b,c} # Any option in braces
```
### Frontend Patterns
```bash
# React
@{src/components/**/*.{jsx,tsx}}
@{src/hooks/**/*.{js,ts}}
@{src/context/**/*.{jsx,tsx}}
# Vue
@{src/components/**/*.vue}
@{src/composables/**/*.{js,ts}}
# Angular
@{src/app/**/*.component.{ts,html}}
@{src/app/**/*.service.ts}
```
### Backend Patterns
```bash
# Node.js
@{routes/**/*.js,controllers/**/*.js}
@{middleware/**/*.js}
@{models/**/*.js}
# Python
@{**/views.py,**/models.py,**/urls.py}
@{**/serializers.py}
# Java
@{**/*Controller.java}
@{**/*Service.java,**/*Repository.java}
```
### Config & Testing
```bash
# Configuration
@{*.config.{js,ts},**/*.config.*}
@{package.json,yarn.lock}
@{Dockerfile,docker-compose.yml}
# Tests
@{**/*.test.{js,ts,jsx,tsx}}
@{**/*.spec.{js,ts}}
@{**/__tests__/**/*}
# Documentation
@{**/*.md,**/README*}
@{**/*.d.ts,**/types/**/*.ts}
```
### Domain Patterns
```bash
# Auth & Security
@{**/*auth*,**/*login*,**/*session*}
@{**/*permission*,**/*role*}
@{**/*crypto*,**/*hash*}
# API & Data
@{**/api/**/*,**/routes/**/*}
@{**/controllers/**/*,**/handlers/**/*}
@{**/models/**/*,**/entities/**/*}
# UI & Styling
@{src/components/**/*,src/ui/**/*}
@{src/styles/**/*,**/*.{css,scss,sass}}
@{src/layouts/**/*}
```
### Cross-Platform Rules
- Always use forward slashes: `@{src/components/**/*}`
- Quote paths with spaces: `@{"My Project/src/**/*"}`
- Escape special chars: `@{src/**/*\[bracket\]*}`
## 📋 Template System
### Template Categories and Functions
#### Analysis Templates (`prompts/analysis/`)
- **`pattern.txt`** - 分析代码模式、工具库、编码标准和反模式
- **`architecture.txt`** - 映射模块依赖、集成点、可扩展性评估
- **`security.txt`** - 扫描安全漏洞、认证问题、加密方法
- **`performance.txt`** - 识别瓶颈、算法复杂度、缓存策略
- **`quality.txt`** - 评估可维护性、技术债务、代码组织
#### Planning Templates (`prompts/planning/`)
- **`task-breakdown.txt`** - 任务分解、依赖关系、工作量估算
- **`migration.txt`** - 系统迁移规划、兼容性、风险评估
#### Implementation Templates (`prompts/implementation/`)
- **`component.txt`** - 组件接口设计、状态管理、测试方法
#### Review Templates (`prompts/review/`)
- **`code-review.txt`** - 全面代码审查、质量检查、标准合规
#### DMS Templates (`prompts/dms/`)
- **`hierarchy-analysis.txt`** - 项目复杂度分析、文档结构优化
### Directory Structure
``` ```
~/.claude/workflows/gemini-templates/ ~/.claude/workflows/gemini-templates/
├── prompts/ ├── prompts/
│ ├── analysis/ # Code analysis templates │ ├── analysis/ # Code analysis templates
│ │ ├── pattern.txt # ✨ Implementation patterns & conventions │ │ ├── pattern.txt # ✨ Implementation patterns & conventions
│ │ ├── architecture.txt # 🏗️ System architecture & dependencies │ │ ├── architecture.txt # 🏗️ System architecture & dependencies
│ │ ├── security.txt # 🔒 Security vulnerabilities & protection │ │ ├── security.txt # 🔒 Security vulnerabilities & protection
│ │ ├── performance.txt # ⚡ Performance bottlenecks & optimization │ │ ├── performance.txt # ⚡ Performance bottlenecks & optimization
│ │ └── quality.txt # 📊 Code quality & maintainability │ │ └── quality.txt # 📊 Code quality & maintainability
@@ -247,127 +209,86 @@ Multiple analyses concurrently:
│ └── dms/ # DMS-specific │ └── dms/ # DMS-specific
│ └── hierarchy-analysis.txt # 📚 Documentation structure optimization │ └── hierarchy-analysis.txt # 📚 Documentation structure optimization
└── commands/ # Command examples └── commands/ # Command examples
├── context-analysis.md # Complete context gathering examples
├── parallel-execution.md # Parallel analysis patterns
└── folder-analysis.md # Directory-specific analysis
``` ```
### Template Selection Guide #### 🧭 Template Selection Guide
| 任务类型 | 主要模板 | 用途 | | Task Type | Primary Template | Purpose |
|---------|---------|------| |---|---|---|
| 理解现有代码 | `pattern.txt` | 学习代码库、入职培训 | | Understand Existing Code | `pattern.txt` | Codebase learning, onboarding. |
| 规划新功能 | `task-breakdown.txt` | 功能开发规划 | | Plan New Features | `task-breakdown.txt`| Feature development planning. |
| 安全审查 | `security.txt` | 安全审计、漏洞评估 | | Security Review | `security.txt` | Security audits, vulnerability assessment. |
| 性能优化 | `performance.txt` | 性能问题排查 | | Performance Tuning | `performance.txt` | Bottleneck investigation. |
| 代码质量改进 | `quality.txt` | 重构、技术债务减少 | | Code Quality Improvement | `quality.txt` | Refactoring, technical debt reduction. |
| 系统现代化 | `migration.txt` | 技术升级、架构变更 | | System Modernization | `migration.txt` | Tech upgrades, architectural changes. |
| 组件开发 | `component.txt` | 构建可复用组件 | | Component Development | `component.txt` | Building reusable components. |
| 发布前审查 | `code-review.txt` | 发布就绪检查 | | Pre-Release Review | `code-review.txt` | Release readiness checks. |
### Template Usage Examples
#### Basic Template Usage ### 📦 Standard Command Structures
```bash
# Single template - pattern analysis
gemini -p "@{src/**/*} $(cat ~/.claude/workflows/gemini-templates/prompts/analysis/pattern.txt)"
# Multi-template composition These are recommended command templates for common scenarios.
gemini -p "@{src/**/*} $(cat <<'EOF'
$(cat ~/.claude/workflows/gemini-templates/prompts/analysis/architecture.txt)
Additional Quality Focus: - **Basic Structure (Manual Prompt)**
$(cat ~/.claude/workflows/gemini-templates/prompts/analysis/quality.txt) ```bash
EOF gemini --all-files -p "@{target_patterns} @{CLAUDE.md,**/*CLAUDE.md}
)"
```
#### Common Use Cases Context: [Analysis type] targeting @{target_patterns}
```bash Guidelines: Include CLAUDE.md standards
# New feature development workflow
gemini -p "@{src/**/*similar*} $(cat ~/.claude/workflows/gemini-templates/prompts/analysis/pattern.txt)"
gemini -p "@{src/**/*} $(cat ~/.claude/workflows/gemini-templates/prompts/planning/task-breakdown.txt)"
# Security audit ## Analysis:
gemini -p "@{**/*auth*,**/*login*} $(cat ~/.claude/workflows/gemini-templates/prompts/analysis/security.txt)" 1. [Point 1]
2. [Point 2]
# Performance optimization ## Output:
gemini -p "@{src/**/*} $(cat ~/.claude/workflows/gemini-templates/prompts/analysis/performance.txt)" - File:line references
``` - Code examples"
```
#### Template Best Practices - **Template-Enhanced (Recommended)**
- **Single Template**: 专注分析、特定问题、时间限制 ```bash
- **Multiple Templates**: 综合审查、复杂项目、全面规划 # Using a predefined template for consistent, high-quality analysis
- **Performance**: 合并相关模板到单个命令,使用特定文件模式减少范围 gemini --all-files -p "@{target_patterns} @{CLAUDE.md,**/*CLAUDE.md} $(cat ~/.claude/workflows/gemini-templates/prompts/[category]/[template].txt)
## 🧠 Intelligent Features ## Analysis:
1. [Point 1]
2. [Point 2]
### Technology Detection ## Output:
```python - File:line references
# Simplified logic - Code examples"
indicators = { "
'React': ['package.json contains react', '**/*.jsx'], ```
'Vue': ['package.json contains vue', '**/*.vue'],
'Python': ['requirements.txt', '**/*.py'],
'Java': ['pom.xml', '**/*.java']
}
```
### Domain Extraction - **Multi-Template Composition**
```python ```bash
# Domain mapping gemini -p "@{src/**/*} @{CLAUDE.md}
domains = { $(cat ~/.claude/workflows/gemini-templates/prompts/analysis/pattern.txt)
'auth': ['authentication', 'login', 'session'],
'api': ['api', 'endpoint', 'route'],
'frontend': ['component', 'ui', 'react'],
'backend': ['server', 'database', 'model']
}
```
### Fallback Strategy Additional Security Focus:
1. **Primary Pattern**: Try user-specified pattern $(cat ~/.claude/workflows/gemini-templates/prompts/analysis/security.txt)
2. **Simplified Pattern**: Remove extensions/specificity
3. **Directory Pattern**: Use common directories like `@{src/**/*}`
### Performance Tips ## Analysis:
- Avoid patterns matching >1000 files 1. [Point 1]
- Use directory-scoped execution for large projects 2. [Point 2]
- Prefer specific patterns over broad ones
- Process large datasets in parallel chunks
## ⭐ Best Practices ## Output:
- File:line references
- Code examples"
"
```
### Core Principles ### ⭐ Best Practices & Rules
- **Always include** `@{CLAUDE.md,**/*CLAUDE.md}` for project context
- **Be specific** with patterns to reduce scope and improve performance
- **Group logically** related patterns in single commands
- **Use forward slashes** for cross-platform compatibility
### Common Patterns - **Mandatory Context**: Always include `@{CLAUDE.md,**/*CLAUDE.md}` to ground the analysis in project-specific standards.
```bash - **Specificity**: Use precise file patterns to reduce scope, improve performance, and increase accuracy.
# Get project context - **Performance**: Avoid overly broad patterns (`@{**/*}`) on large projects. Prefer directory-scoped execution or parallel chunks.
gemini --all-files -p "@{src/**/*} @{CLAUDE.md} Extract patterns and standards" - **Agent Integration**: All agent workflows **must** begin with a context analysis step using `gemini`.
```bash
# Mandatory first step for any agent task
gemini --all-files -p "@{relevant_patterns} @{CLAUDE.md} Context for: [task_description]"
```
- **Error Handling**:
- Validate patterns match existing files before executing a long analysis.
- Quote paths that contain spaces or special characters.
- Test complex patterns on a small subset of files first.
# Domain analysis
gemini -p "@{**/*auth*} @{CLAUDE.md} Authentication implementation analysis"
# Technology-specific
gemini -p "@{src/components/**/*} $(cat ~/.claude/workflows/gemini-templates/prompts/tech/react-component.txt)"
```
### Error Handling
- Validate patterns match files before execution
- Use fallback patterns for robustness
- Quote paths with spaces or special characters
- Test patterns on small subsets first
### Agent Integration
All agent workflows should begin with context analysis:
```bash
# Mandatory first step
gemini --all-files -p "@{relevant_patterns} @{CLAUDE.md} Context for: [task_description]"
```
### Integration References
- This unified guide replaces all individual Gemini guideline files
- Templates are stored in `~/.claude/workflows/gemini-templates/`
- Always reference this file for Gemini CLI usage patterns

View File

@@ -1,278 +0,0 @@
# Workflow Session Management Principles
## Overview
This document provides simplified session state management using marker files for active session tracking.
## Multi-Session Architecture
### Active Session Marker System
**Ultra-Simple Active Tracking**: `.workflow/.active-[session-name]`
The system supports multiple concurrent sessions with a single active session marked by file presence:
```bash
.workflow/
├── WFS-oauth-integration/ # Session directory (paused)
├── WFS-user-profile/ # Session directory (paused)
├── WFS-bug-fix-123/ # Session directory (completed)
└── .active-WFS-user-profile # Marker file (indicates active session)
```
**Marker File Benefits**:
- **Zero Parsing**: File existence check is atomic and instant
- **Atomic Operations**: File creation/deletion is naturally atomic
- **Visual Discovery**: `ls .workflow/.active-*` shows active session immediately
- **No Corruption Risk**: No JSON parsing, no file format issues
- **Simple Switching**: Delete old marker + create new marker = session switch
### Command Pre-execution Protocol
**Universal Session Awareness**: All commands automatically detect active session through marker file
```pseudo
FUNCTION execute_command(command, args):
active_marker = find_file(".workflow/.active-*")
IF active_marker EXISTS:
session_name = extract_name_from_marker(active_marker)
session_dir = ".workflow/" + session_name
context = load_session_context(session_dir + "/workflow-session.json")
workspace = session_dir
ELSE:
context = create_temporary_workspace()
workspace = temporary_directory
execute_with_context(command, args, context, workspace)
END FUNCTION
```
**Protocol Benefits**:
- **Instant Discovery**: No file parsing, just check file existence
- **Context Inheritance**: Use active session directory for all operations
- **Fallback Mode**: Commands work without any active session
- **Output Location**: Active session determines file creation location
- **Task Context**: Active session provides current workflow context
### Session State Management
#### Active Session Detection
```bash
# Check for active session
active_session=$(ls .workflow/.active-* 2>/dev/null | head -1)
if [ -n "$active_session" ]; then
session_name=$(basename "$active_session" | sed 's/^\.active-//')
echo "Active session: $session_name"
else
echo "No active session"
fi
```
#### Session Activation
```bash
# Switch to different session
rm .workflow/.active-* 2>/dev/null # Remove any existing active marker
touch .workflow/.active-WFS-new-feature # Mark new session as active
```
#### Session Discovery
```bash
# List all available sessions
ls -d .workflow/WFS-*/ 2>/dev/null | sed 's|.workflow/||;s|/$||'
# Show active session status
if ls .workflow/.active-* >/dev/null 2>&1; then
active=$(ls .workflow/.active-* | sed 's|.workflow/.active-||')
echo "✅ Active: $active"
else
echo "⏸️ No active session"
fi
```
## Individual Session Tracking
All workflow state for each session managed through `workflow-session.json` in each session directory:
### Session State Structure
```json
{
"session_id": "WFS-[topic-slug]",
"project": "feature description",
"type": "simple|medium|complex",
"current_phase": "PLAN|IMPLEMENT|REVIEW",
"status": "active|paused|completed",
"progress": {
"completed_phases": ["PLAN"],
"current_tasks": ["impl-1", "impl-2"],
"last_checkpoint": "2025-09-07T10:00:00Z"
},
"meta": {
"created": "2025-09-05T10:00:00Z",
"updated": "2025-09-07T10:00:00Z"
}
}
```
**Note**: The `status` field in individual session files is informational only. The actual active status is determined by the presence of `.active-[session-name]` marker file.
## Session Lifecycle Operations
### Create New Session
```bash
# 1. Create session directory
mkdir .workflow/WFS-new-feature
# 2. Initialize workflow-session.json
echo '{"session_id":"WFS-new-feature","status":"active",...}' > .workflow/WFS-new-feature/workflow-session.json
# 3. Set as active (deactivate others automatically)
rm .workflow/.active-* 2>/dev/null
touch .workflow/.active-WFS-new-feature
```
### Switch Session
```bash
# Atomic session switching
rm .workflow/.active-* 2>/dev/null && touch .workflow/.active-WFS-different-feature
```
### Pause Session (Deactivate)
```bash
# Remove active marker (session becomes paused)
rm .workflow/.active-WFS-current-feature
```
### Resume Session
```bash
# Reactivate paused session
rm .workflow/.active-* 2>/dev/null # Clear any active session
touch .workflow/.active-WFS-paused-session # Activate target session
```
### Complete Session
```bash
# 1. Update session status
echo '{"session_id":"WFS-feature","status":"completed",...}' > .workflow/WFS-feature/workflow-session.json
# 2. Remove active marker
rm .workflow/.active-WFS-feature
# 3. Optional: Archive session directory
mv .workflow/WFS-feature .workflow/completed/WFS-feature
```
## Simplified Phase Management
### Phase-Level Tracking Only
- **Planning Phase**: Track completion status only
- **Implementation Phase**: Track active tasks, not detailed progress
- **Review Phase**: Track completion status only
### Minimal Checkpoint Strategy
- **Phase Transitions**: Save state when moving between phases
- **User Request**: Manual checkpoint on explicit user action
- **Session End**: Final state save before closing
### Checkpoint Data (Minimal)
```json
{
"save_triggers": ["phase_complete", "user_request", "session_end"],
"save_data": ["phase_status", "active_tasks", "session_meta"],
"resume_logic": "resume_from_last_phase_checkpoint"
}
```
## Simplified Context Preservation
### Essential Context Only
- Planning documents available to implementation phase
- Implementation results available to review phase
- Minimal handoff data between phases
### Simple State Transitions
```json
{
"phase_completed": "PLAN",
"next_phase": "IMPLEMENT",
"completed_at": "2025-09-07T10:00:00Z",
"artifacts": {
"plan_document": "IMPL_PLAN.md"
}
}
```
## Error Recovery and Validation
### Session Consistency Checks
```bash
# Validate active session integrity
active_marker=$(ls .workflow/.active-* 2>/dev/null | head -1)
if [ -n "$active_marker" ]; then
session_name=$(basename "$active_marker" | sed 's/^\.active-//')
session_dir=".workflow/$session_name"
if [ ! -d "$session_dir" ]; then
echo "⚠️ Orphaned active marker: $active_marker"
echo " Session directory missing: $session_dir"
echo " Removing orphaned marker..."
rm "$active_marker"
fi
fi
```
### Multi-Active Session Detection
```bash
# Detect multiple active markers (error condition)
active_count=$(ls .workflow/.active-* 2>/dev/null | wc -l)
if [ "$active_count" -gt 1 ]; then
echo "❌ Multiple active sessions detected:"
ls .workflow/.active-* | sed 's|.workflow/.active-| - |'
echo " Keeping most recent, removing others..."
# Keep newest, remove others
newest=$(ls -t .workflow/.active-* 2>/dev/null | head -1)
ls .workflow/.active-* 2>/dev/null | grep -v "$newest" | xargs rm -f
echo " ✅ Resolved: $(basename "$newest" | sed 's/^\.active-//')"
fi
```
### Recovery Strategies
- **Missing Session Directory**: Remove orphaned active marker
- **Multiple Active Markers**: Keep newest, remove others
- **Corrupted Session File**: Recreate from template with session name
- **No Active Session**: Commands work in temporary mode
## Performance Benefits
### Ultra-Fast Operations
- **Session Detection**: Single `ls` command (< 1ms)
- **Session Switching**: Two file operations (delete + create)
- **Status Check**: File existence test (instant)
- **No Parsing Overhead**: Zero JSON/text processing
### Scalability
- **Hundreds of Sessions**: No performance degradation
- **Concurrent Access**: File system handles locking automatically
- **Atomic Operations**: No race conditions or corruption risk
## Implementation Guidelines
### Key Principles
- **File Existence = Truth**: Marker file presence is the single source of truth
- **Atomic State Changes**: All session operations are atomic file operations
- **Visual Management**: Users can see and manage active sessions directly
- **Zero Configuration**: No registry files to maintain or repair
- **Self-Healing**: Automatic detection and resolution of inconsistent states
### Success Metrics
- Fast session resume (< 100ms)
- Zero parsing overhead
- Visual session management
- Self-healing consistency
- No registry maintenance needed
---
**System ensures**: Ultra-simple session management using marker files for instant, atomic, and visually manageable session state tracking.

View File

@@ -1,129 +0,0 @@
# Workflow System Architecture
## Core Philosophy
### Document-State Separation
**"Documents store plans, JSON manages state"**
- **Markdown Files** → Planning, requirements, task structure, implementation strategies
- **JSON Files** → Execution state, progress tracking, session metadata, dynamic changes
- **JSON-Only Data Model** → Single source of truth for all task state and workflow coordination
### Progressive Complexity
**"Minimal overhead → comprehensive structure"**
- **Simple** → Lightweight JSON + optional docs
- **Medium** → Structured planning + conditional documents
- **Complex** → Complete document suite + full coordination
### Session-First Architecture
**"All commands check active session for context"**
All workflow operations inherit from active session context through `.active-[session-name]` marker file system for seamless workflow integration.
## System Components
### Session Management
**Marker File System**: Ultra-simple active tracking using `.workflow/.active-[session-name]`
- **Multi-Session Architecture**: Supports concurrent sessions with single active session pattern
- **Command Pre-execution Protocol**: All commands automatically detect active session through marker file
- **State Management**: Individual session state with phase-aware progress tracking
**Technical Details**: @./session-management-principles.md
### Data Model System
**JSON-Only Architecture**: Single source of truth with on-demand document generation
- **Task Definitions**: JSON files contain all task data with hierarchical structure
- **No Synchronization**: Documents generated on-demand from JSON, no bidirectional sync
- **State Coordination**: Real-time coordination through JSON task files only
**Technical Details**: @./data-model.md
### File Structure System
**Progressive Structure**: Scales from minimal structure for simple tasks to comprehensive organization for complex workflows
- **Complexity Levels**: Three levels (0-2) with automatic structure generation based on task count and scope
- **Standard Templates**: Consistent directory layouts and file naming across all complexity levels
**Technical Details**: @./file-structure-standards.md
### Agent Orchestration
**Context-Driven Coordination**: Gemini context analysis mandatory before agent execution
- **Gemini Context Analysis**: MANDATORY context gathering before any agent execution
- **Dynamic Agent Selection**: Choose agents based on discovered context and patterns
- **Cross-Agent Context Sharing**: Maintain shared context state across all agents
**Technical Details**: @./agent-orchestration-patterns.md
## Architectural Principles
### Fundamental Design Patterns
#### Session-First Architecture
- All workflow operations inherit from active session context
- Multi-session support with single active session pattern
- Context switching preserves complete state
#### Hierarchical Task Management
- JSON-based task definitions with up to 3 levels of decomposition
- Progress tracking with dependency management
- JSON-only data model eliminates synchronization issues
#### Complexity-Driven Structure
- File structure scales automatically with task complexity
- Document generation triggered by complexity thresholds
- Progressive enhancement without breaking simple workflows
#### Real-time Coordination
- TodoWrite tool provides immediate task visibility
- JSON task files maintain cross-session continuity
- Agent coordination through unified JSON interface
## Quality Assurance Principles
### Data Integrity
- Single source of truth: JSON task files
- Automatic validation and consistency checks
- Error recovery with graceful degradation
### Performance Guidelines
- Lazy loading of complex structures
- Minimal overhead for simple workflows
- Real-time updates without blocking operations
### Extensibility Rules
- Plugin architecture for specialized agents
- Template-based document generation
- Configurable complexity thresholds
## Implementation Flow
**Workflow Phases**: Session initialization → [Optional brainstorming] → Planning → Implementation → Review
**Progressive Complexity**: Structure and documentation automatically scale with task complexity
**Cross-Integration**: Real-time coordination across all system components through JSON-only data model
## Command Integration
### Embedded Workflow Logic
**Workflow Commands**: Session management, planning, and implementation with embedded document generation
**Task Commands**: Task creation, breakdown, execution, and status with automatic JSON coordination
**Manual Tools**: Maintenance operations for edge cases and manual intervention
## Architecture Integration
This document provides the technical architecture framework. For complete system documentation, see:
**📋 Complete Documentation**:
- **Session Management**: @./session-management-principles.md
- **Data Model**: @./data-model.md
- **Complexity Rules**: @./complexity-rules.md
- **File Structure**: @./file-structure-standards.md
- **Agent Orchestration**: @./agent-orchestration-patterns.md
- **Brainstorming Integration**: @./brainstorming-principles.md
---
**Architecture ensures**: Consistent scalable workflow management with JSON-only data model, marker file sessions, and progressive complexity scaling from simple tasks → comprehensive project coordination

View File

@@ -0,0 +1,401 @@
# Workflow Architecture
## Overview
This document defines the complete workflow system architecture using a **JSON-only data model**, **marker-based session management**, and **progressive file structures** that scale with task complexity.
## Core Architecture Principles
### Key Design Decisions
- **JSON files are the single source of truth** - All markdown documents are read-only generated views
- **Marker files for session tracking** - Ultra-simple active session management
- **Progressive complexity structure** - File organization scales from simple to complex workflows
- **Agent-agnostic task definitions** - Complete context preserved for autonomous execution
## Session Management
### Active Session Marker System
**Ultra-Simple Active Tracking**: `.workflow/.active-[session-name]`
```bash
.workflow/
├── WFS-oauth-integration/ # Session directory (paused)
├── WFS-user-profile/ # Session directory (paused)
├── WFS-bug-fix-123/ # Session directory (completed)
└── .active-WFS-user-profile # Marker file (indicates active session)
```
**Marker File Benefits**:
- **Zero Parsing**: File existence check is atomic and instant
- **Atomic Operations**: File creation/deletion is naturally atomic
- **Visual Discovery**: `ls .workflow/.active-*` shows active session immediately
- **Simple Switching**: Delete old marker + create new marker = session switch
### Session Operations
#### Detect Active Session
```bash
active_session=$(ls .workflow/.active-* 2>/dev/null | head -1)
if [ -n "$active_session" ]; then
session_name=$(basename "$active_session" | sed 's/^\.active-//')
echo "Active session: $session_name"
fi
```
#### Switch Session
```bash
rm .workflow/.active-* 2>/dev/null && touch .workflow/.active-WFS-new-feature
```
### Individual Session Tracking
Each session directory contains `workflow-session.json`:
```json
{
"session_id": "WFS-[topic-slug]",
"project": "feature description",
"type": "simple|medium|complex",
"current_phase": "PLAN|IMPLEMENT|REVIEW",
"status": "active|paused|completed",
"progress": {
"completed_phases": ["PLAN"],
"current_tasks": ["impl-1", "impl-2"],
"last_checkpoint": "2025-09-07T10:00:00Z"
},
"meta": {
"created": "2025-09-05T10:00:00Z",
"updated": "2025-09-07T10:00:00Z"
}
}
```
## Data Model
### JSON-Only Architecture
**JSON files (.task/impl-*.json) are the only authoritative source of task state. All markdown documents are read-only generated views.**
- **Task State**: Stored exclusively in JSON files
- **Documents**: Generated on-demand from JSON data
- **No Synchronization**: Eliminates bidirectional sync complexity
- **Performance**: Direct JSON access without parsing overhead
### Task JSON Schema
All task files use this 8-field schema:
```json
{
"id": "impl-1",
"title": "Build authentication module",
"status": "pending|active|completed|blocked|container",
"type": "feature|bugfix|refactor|test|docs",
"agent": "code-developer|planning-agent|test-agent|docs-agent",
"context": {
"requirements": ["JWT authentication", "OAuth2 support"],
"scope": ["src/auth/*", "tests/auth/*"],
"acceptance": ["Module handles JWT tokens", "OAuth2 flow implemented"],
"inherited_from": "WFS-user-auth"
},
"relations": {
"parent": null,
"subtasks": ["impl-1.1", "impl-1.2"],
"dependencies": ["impl-0"]
},
"execution": {
"attempts": 0,
"last_attempt": null
},
"meta": {
"created": "2025-09-05T10:30:00Z",
"updated": "2025-09-05T10:30:00Z"
}
}
```
### Hierarchical Task System
**Maximum Depth**: 3 levels (impl-N.M.P format)
```
impl-1 # Main task
impl-1.1 # Subtask of impl-1
impl-1.1.1 # Detailed subtask of impl-1.1
impl-1.2 # Another subtask of impl-1
impl-2 # Another main task
```
**Task Status Rules**:
- **Container tasks**: Parent tasks with subtasks (cannot be directly executed)
- **Leaf tasks**: Only these can be executed directly
- **Status inheritance**: Parent status derived from subtask completion
## File Structure
### Progressive Structure System
File structure scales with task complexity to minimize overhead for simple tasks while providing comprehensive organization for complex workflows.
#### Level 0: Minimal Structure (<5 tasks)
```
.workflow/WFS-[topic-slug]/
├── workflow-session.json # Session metadata and state
├── [.brainstorming/] # Optional brainstorming phase
├── [.chat/] # Gemini CLI interaction sessions
├── IMPL_PLAN.md # Combined planning document
├── .summaries/ # Task completion summaries
│ └── IMPL-*.md # Individual task summaries
└── .task/
└── impl-*.json # Task definitions
```
#### Level 1: Enhanced Structure (5-15 tasks)
```
.workflow/WFS-[topic-slug]/
├── workflow-session.json # Session metadata and state
├── [.brainstorming/] # Optional brainstorming phase
├── [.chat/] # Gemini CLI interaction sessions
├── IMPL_PLAN.md # Combined planning document
├── TODO_LIST.md # Auto-triggered progress tracking
├── .summaries/ # Task completion summaries
│ ├── IMPL-*.md # Main task summaries
│ └── IMPL-*.*.md # Subtask summaries
└── .task/
├── impl-*.json # Main task definitions
└── impl-*.*.json # Subtask definitions (up to 3 levels)
```
#### Level 2: Complete Structure (>15 tasks)
```
.workflow/WFS-[topic-slug]/
├── workflow-session.json # Session metadata and state
├── [.brainstorming/] # Optional brainstorming phase
├── [.chat/] # Gemini CLI interaction sessions
│ ├── chat-*.md # Saved chat sessions with timestamps
│ └── analysis-*.md # Comprehensive analysis results
├── IMPL_PLAN.md # Comprehensive planning document
├── TODO_LIST.md # Progress tracking and monitoring
├── .summaries/ # Task completion summaries
│ ├── IMPL-*.md # Main task summaries
│ ├── IMPL-*.*.md # Subtask summaries
│ └── IMPL-*.*.*.md # Detailed subtask summaries
└── .task/
├── impl-*.json # Task hierarchy (max 3 levels deep)
├── impl-*.*.json # Subtasks
└── impl-*.*.*.json # Detailed subtasks
```
### File Naming Conventions
#### Session Identifiers
**Format**: `WFS-[topic-slug]`
- Convert topic to lowercase with hyphens (e.g., "User Auth System" → `WFS-user-auth-system`)
- Add `-NNN` suffix only if conflicts exist (e.g., `WFS-payment-integration-002`)
#### Document Naming
- `workflow-session.json` - Session state (required)
- `IMPL_PLAN.md` - Planning document (required)
- `TODO_LIST.md` - Progress tracking (auto-generated when needed)
- Chat sessions: `chat-YYYYMMDD-HHMMSS.md`
- Task summaries: `IMPL-[task-id]-summary.md`
## Complexity Classification
### Unified Classification Rules
**Consistent thresholds across all workflow components:**
| Complexity | Task Count | Hierarchy Depth | Structure Level | Behavior |
|------------|------------|----------------|-----------------|----------|
| **Simple** | <5 tasks | 1 level (impl-N) | Level 0 - Minimal | Direct execution, basic docs |
| **Medium** | 5-15 tasks | 2 levels (impl-N.M) | Level 1 - Enhanced | Context coordination, TODO tracking |
| **Complex** | >15 tasks | 3 levels (impl-N.M.P) | Level 2 - Complete | Multi-agent orchestration, full docs |
### Simple Workflows
**Characteristics**: Direct implementation tasks with clear, limited scope
- **Examples**: Bug fixes, small feature additions, configuration changes
- **System Behavior**: Minimal structure, single-level tasks, basic planning only
- **Agent Coordination**: Direct execution without complex orchestration
### Medium Workflows
**Characteristics**: Feature implementation requiring task breakdown
- **Examples**: New features, API endpoints with integration, database schema changes
- **System Behavior**: Enhanced structure, two-level hierarchy, auto-triggered TODO_LIST.md
- **Auto-trigger Conditions**: Tasks >5 OR modules >3 OR effort >4h OR complex dependencies
### Complex Workflows
**Characteristics**: System-wide changes requiring detailed decomposition
- **Examples**: Major features, architecture refactoring, security implementations, multi-service deployments
- **System Behavior**: Complete structure, three-level hierarchy, comprehensive documentation
- **Agent Coordination**: Multi-agent orchestration with deep context analysis
### Automatic Assessment & Upgrades
- **During Creation**: System evaluates requirements and assigns complexity
- **During Execution**: Can upgrade (Simple→Medium→Complex) but never downgrade
- **Override Allowed**: Users can specify higher complexity manually
## Document Templates
### IMPL_PLAN.md Templates
#### Stage-Based Format (Simple Tasks)
```markdown
# Implementation Plan: [Task Name]
## Overview
[Brief description of the overall goal and approach]
## Requirements
[Functional and non-functional requirements]
## Stage 1: [Name]
**Goal**: [Specific deliverable]
**Success Criteria**:
- [Testable outcome 1]
**Tests**:
- [Specific test case 1]
**Dependencies**: [Previous stages or external requirements]
**Status**: [Not Started]
## Risk Mitigation
[Identified risks and mitigation strategies]
```
#### Hierarchical Format (Complex Tasks)
```markdown
# Implementation Plan: [Project Name]
## Overview
[Brief description and strategic approach]
## Requirements
[Functional and non-functional requirements]
## Task Hierarchy
### Main Task: [IMPL-001] [Primary Goal]
**Description**: [Detailed description]
**Complexity**: [High/Medium/Low]
**Status**: [Not Started]
#### Subtask: [IMPL-001.1] [Subtask Name]
**Description**: [Specific deliverable]
**Assigned Agent**: [code-developer/code-review-agent/general-purpose]
**Acceptance Criteria**:
- [Testable criteria 1]
**Status**: [Not Started]
##### Action Item: [IMPL-001.1.1] [Specific Action]
**Type**: [Code/Test/Documentation/Review]
**Description**: [Concrete action]
**Files Affected**: [List of files]
**Status**: [Not Started]
```
### TODO_LIST.md Template
```markdown
# Task Progress List: [Session Topic]
## Implementation Tasks
### Main Tasks
- [ ] **IMPL-001**: [Task Description] → [📋 Details](./.task/impl-001.json)
- [x] **IMPL-002**: [Completed Task] → [📋 Details](./.task/impl-002.json) | [✅ Summary](./.summaries/IMPL-002-summary.md)
### Subtasks (Auto-expanded when active)
- [ ] **IMPL-001.1**: [Subtask Description] → [📋 Details](./.task/impl-001.1.json)
```
## Agent Integration
### Agent Assignment
Based on task type and title keywords:
- **Planning tasks** → planning-agent
- **Implementation** → code-developer
- **Testing** → test-agent
- **Documentation** → docs-agent
- **Review** → review-agent
### Execution Context
Agents receive complete task JSON plus workflow context:
```json
{
"task": { /* complete task JSON */ },
"workflow": {
"session": "WFS-user-auth",
"phase": "IMPLEMENT"
}
}
```
## Data Operations
### Task Creation
```bash
echo '{"id":"impl-1","title":"New task",...}' > .task/impl-1.json
```
### Task Updates
```bash
jq '.status = "active"' .task/impl-1.json > temp && mv temp .task/impl-1.json
```
### Document Generation
```bash
# Generate TODO_LIST.md from current JSON state
generate_todo_list_from_json .task/
```
## Validation and Error Handling
### Task Integrity Rules
1. **ID Uniqueness**: All task IDs must be unique
2. **Hierarchical Format**: Must follow impl-N[.M[.P]] pattern
3. **Parent References**: All parent IDs must exist as JSON files
4. **Depth Limits**: Maximum 3 levels deep
5. **Status Consistency**: Status values from defined enumeration
6. **Required Fields**: All 8 core fields must be present
### Session Consistency Checks
```bash
# Validate active session integrity
active_marker=$(ls .workflow/.active-* 2>/dev/null | head -1)
if [ -n "$active_marker" ]; then
session_name=$(basename "$active_marker" | sed 's/^\.active-//')
session_dir=".workflow/$session_name"
if [ ! -d "$session_dir" ]; then
echo "⚠️ Orphaned active marker, removing..."
rm "$active_marker"
fi
fi
```
### Recovery Strategies
- **Missing Session Directory**: Remove orphaned active marker
- **Multiple Active Markers**: Keep newest, remove others
- **Corrupted Session File**: Recreate from template
- **Broken Task Hierarchy**: Reconstruct parent-child relationships
## Performance Benefits
### Marker File System
- **Session Detection**: Single `ls` command (< 1ms)
- **Session Switching**: Two file operations (delete + create)
- **Status Check**: File existence test (instant)
- **No Parsing Overhead**: Zero JSON/text processing
### JSON-Only Architecture
- **Direct Access**: No document parsing overhead
- **Atomic Updates**: Single file operations
- **No Sync Conflicts**: Eliminates coordination complexity
- **Fast Queries**: Direct JSON traversal
- **Scalability**: Handles hundreds of tasks efficiently
### On-Demand Generation
- **Memory Efficient**: Documents created only when needed
- **Always Fresh**: Generated views reflect current state
- **No Stale Data**: Eliminates sync lag issues
---
**System ensures**: Unified workflow architecture with ultra-fast session management, JSON-only data model, and progressive file structures that scale from simple tasks to complex system-wide implementations.