# /stories Command - Parallel Story Development

> ⚡ **Claude Code Only** - This command requires Claude's Task tool for parallel agent execution

## Usage

```
/stories [mode] [arguments]
```

## Description

Unified command for parallel development of user stories using Claude's Task tool with progressive sophistication and intelligent coordination. Automatically manages git worktrees, assigns innovation dimensions, and orchestrates multiple development agents working simultaneously.

## ULTRA-THINKING DIRECTIVE

Before beginning execution, engage in extended thinking about:

**Story Analysis & Evolution:**

- The deeper implications of each user story
- How to create meaningful progression across parallel implementations
- What makes each implementation valuable and unique
- How to balance consistency with innovation

**Parallel Strategy:**

- Optimal Sub-Agent distribution for the story count
- How to assign distinct innovation dimensions to maximize diversity
- Wave sizing and timing for complex projects
- Context management across multiple parallel agents

**Coordination Challenges:**

- How to prevent duplicate concepts across parallel streams
- Strategies for ensuring each agent produces genuinely unique output
- Managing git conflicts with concurrent development
- Quality control mechanisms for parallel outputs

**Progressive Sophistication:**

- Wave 1: Core functionality with clean implementation
- Wave 2: Enhanced features with optimizations
- Wave 3: Advanced integrations and scaling considerations
- Each wave builds on previous work with increasing complexity

## Modes

### `/stories` or `/stories:auto`

Auto-detect all user stories and launch parallel development with intelligent wave management.

**Usage:**

```
/stories
/stories:auto
```

**Options:**

- `--waves`: Execution strategy (e.g., `2,1` for 2 stories then 1)
- `--exclude`: Comma-separated list of story filenames to exclude
- `--pattern`: Custom glob pattern (default: `user-story-*.md`)
- `--sophistication`: Starting sophistication level (1-3, default: 1)
- `--quality-gates`: Enable quality checkpoints between waves
- `--context-optimize`: Enable aggressive context optimization for large projects

### `/stories:manual`

Manually specify stories and their worktrees for precise control.

**Usage:**

```
/stories:manual <story1_path> <worktree1> [<story2_path> <worktree2>] ...
```

**Example:**

```
/stories:manual docs/story1.md worktrees/feat1 docs/story2.md worktrees/feat2
```

### `/stories:analyze`

Analyze story dependencies without launching development.

**Usage:**

```
/stories:analyze [pattern]
```

**Output:**

- Dependency matrix
- Suggested execution waves
- Potential conflicts
- Worktree requirements

### `/stories:status`

Check the status of running story development.

**Usage:**

```
/stories:status
```

**Shows:**

- Active stories and their agents
- Progress for each story
- Worktree git status
- Completion estimates

### `/stories:merge`

Assist with merging completed stories.

**Usage:**

```
/stories:merge [story-name|all]
```

**Features:**

- Test verification
- Merge order suggestions
- Conflict detection
- Cleanup options

### `/stories:infinite`

Continuous story development mode with progressive waves.

**Usage:**

```
/stories:infinite [--wave-size N] [--max-waves N]
```

**Features:**

- Continuous wave generation
- Progressive sophistication
- Context capacity monitoring
- Graceful completion when approaching limits

### `/stories:pause`

Pause active parallel execution at next safe point.

**Usage:**

```
/stories:pause [--immediate] [--checkpoint]
```

**Options:**

- `--immediate`: Stop agents immediately (may lose progress)
- `--checkpoint`: Create checkpoint before pausing

**Creates:**

- Checkpoint file with current state
- Recovery plan for resume

### `/stories:resume`

Resume paused parallel execution from checkpoint.

**Usage:**

```
/stories:resume [--checkpoint-id ID] [--adjust-waves]
```

**Options:**

- `--checkpoint-id`: Specific checkpoint to resume from
- `--adjust-waves`: Recalculate waves based on remaining work

### `/stories:rollback`

Emergency rollback to previous known good state.

**Usage:**

```
/stories:rollback [--checkpoint-id ID] [--preserve-worktrees]
```

**Features:**

- Restores to last successful checkpoint
- Cleans up partial work
- Preserves diagnostic information
- Optional worktree preservation

## Implementation Details

### Enhanced Execution Strategy

**Wave-Based Distribution:**

- 1-3 stories: Launch all agents simultaneously
- 4-8 stories: Launch in waves of 3-4 agents
- 9+ stories: Progressive waves with sophistication levels
- Infinite mode: Continuous waves of 3-5 agents

**Innovation Dimension Assignment:**
Each agent receives a unique focus area:

- **Performance**: Optimization and efficiency
- **UX Enhancement**: User experience improvements
- **Architecture**: Clean code and patterns
- **Testing**: Comprehensive test coverage
- **Documentation**: Clear inline docs and examples
- **Security**: Input validation and safety
- **Accessibility**: Inclusive design patterns
- **Scalability**: Future-proofing implementations

### Auto Mode (`/stories` or `/stories:auto`)

1. **Discovery Phase**
   - Scan `docs/` for stories matching pattern
   - Extract story names and requirements
   - Assess complexity and dependencies

2. **Deep Analysis Phase**
   - Detect file dependencies and conflicts
   - Calculate optimal wave distribution
   - Assign innovation dimensions
   - Plan sophistication progression

3. **Setup Phase**
   - Create worktrees automatically
   - Name format: `worktrees/ck-[story-name]`
   - Branch format: `feature/[story-name]`
   - Initialize coordination files

4. **Parallel Execution Phase**
   - Deploy Task agents with structured prompts
   - Monitor progress and quality gates
   - Coordinate via status tracking
   - Handle failures with reassignment

### Manual Mode (`/stories:manual`)

1. **Validation**
   - Verify all story files exist
   - Check worktree availability
   - Ensure no conflicts

2. **Execution**
   - Launch specified stories in parallel
   - Use provided worktree paths
   - Same monitoring as auto mode

### Sub-Agent Task Specification

Each Task agent receives a structured prompt:

```
TASK: Implement user story [STORY_NAME] in worktree [WORKTREE_PATH]

You are Sub-Agent [N] with innovation dimension: [DIMENSION]

CONTEXT:
- Story specification: [Full story content]
- Existing implementations: [Summary of completed stories]
- Dependencies: [Files and components you'll modify]
- Your worktree: [WORKTREE_PATH]
- Assigned focus: [INNOVATION_DIMENSION] - [Description]

QUALITY STANDARDS:
1. Read and understand the story completely
2. Analyze existing code to ensure compatibility
3. Implement with focus on [INNOVATION_DIMENSION]
4. Write comprehensive tests (unit and integration)
5. Ensure all existing tests still pass
6. Update documentation as needed
7. Follow project coding standards

COORDINATION PROTOCOL:
- Update status every major milestone
- Report blockers immediately
- Check for updates from other agents
- Avoid modifying shared files without coordination

PROGRESS TRACKING:
- Create: /tmp/parallel-stories/[STORY_NAME]-status.md
- Update with: current task, progress %, blockers
- Mark complete when all tests pass

DELIVERABLE: Fully implemented story with tests, ready to merge
```

### BMAD-Enhanced Status Tracking

BMAD Method integrated status tracking:

```
/tmp/parallel-stories/
├── orchestrator.json        # Overall status and wave management
├── bmad-validation.json     # Story format validation results
├── [story]-tasks.json       # Task checkbox states from story
├── [story]-debug.json       # Debug log entries
├── [story]-dod.json         # DoD checklist results
├── [story]-blockers.json    # Blocking conditions encountered
├── [story]-dev-record.json  # Parsed Dev Agent Record
├── quality-gates.json       # Aggregated test/lint/coverage
├── sm-review.json           # SM validation status
└── completion-report.md     # Summary with BMAD compliance
```

## Examples

### Basic Parallel Development

```
# Auto-detect and run all stories
/stories

# With quality gates and optimization
/stories --quality-gates --context-optimize

# Starting at sophistication level 2
/stories --sophistication 2
```

### Custom Patterns

```
# Only frontend stories
/stories --pattern "user-story-frontend-*.md"

# Exclude draft stories
/stories --exclude "user-story-draft.md,user-story-wip.md"
```

### Wave Control

```
# Run 2 stories, then 2, then 1
/stories --waves 2,2,1

# Run all stories at once (max parallelism)
/stories --waves all
```

### Manual Control

```
# Run specific stories with specific worktrees
/stories:manual \
  docs/user-story-auth.md worktrees/auth-feature \
  docs/user-story-ui.md worktrees/ui-update
```

### Analysis and Planning

```
# See what would happen
/stories:analyze

# Analyze specific pattern
/stories:analyze "user-story-backend-*.md"
```

### Monitoring and Completion

```
# Check progress with quality metrics
/stories:status

# Merge all completed stories
/stories:merge all

# Merge specific story
/stories:merge auth-feature
```

### Infinite Mode

```
# Continuous development with waves of 4
/stories:infinite --wave-size 4

# Limited to 5 waves maximum
/stories:infinite --max-waves 5
```

### Advanced Sophistication

```
# Run with progressive sophistication
/stories --waves 3,3,2 --sophistication 1
# Wave 1: 3 stories at sophistication 1 (core)
# Wave 2: 3 stories at sophistication 2 (enhanced)
# Wave 3: 2 stories at sophistication 3 (advanced)
```

## Configuration

### Project Configuration

Create `.claude/stories.json`:

```json
{
  "defaultWaveSize": 3,
  "autoCreateWorktrees": true,
  "worktreePrefix": "ck-",
  "branchPrefix": "feature/",
  "testCommand": "npm test",
  "excludePatterns": ["*-draft.md", "*-archived.md"],
  "sophisticationLevels": {
    "1": "Core functionality with clean code",
    "2": "Enhanced features with optimizations",
    "3": "Advanced integrations and scaling"
  },
  "innovationDimensions": [
    "performance",
    "ux",
    "architecture",
    "testing",
    "documentation",
    "security",
    "accessibility",
    "scalability"
  ],
  "qualityGates": {
    "testCoverage": 80,
    "lintErrors": 0,
    "typeErrors": 0
  }
}
```

### Global Configuration

Place in `~/.claude/stories.json` for user defaults.

## Best Practices

1. **Story Independence**
   - Best performance with independent stories
   - Dependent stories automatically sequenced
   - Use feature flags for shared components

2. **Innovation Dimensions**
   - Let the system assign dimensions automatically
   - Or specify focus areas for specific stories
   - Ensures diverse, high-quality implementations

3. **Wave Management**
   - Start with smaller waves to test coordination
   - Increase wave size as confidence grows
   - Use quality gates between waves

4. **Context Optimization**
   - Enable `--context-optimize` for large projects
   - Fresh agent instances per wave
   - Progressive summarization of completed work

5. **Regular Monitoring**
   - Check `/stories:status` periodically
   - Monitor quality metrics
   - Address blockers quickly

6. **Clean Merging**
   - Use `/stories:merge` for guided merging
   - Validates quality gates before merge
   - Removes worktrees after merge

## Troubleshooting

### "Story not found"

- Check file path and pattern
- Ensure story is in `docs/` directory

### "Worktree exists"

- Use different name or clean up old worktree
- Check with `git worktree list`

### "Conflicts detected"

- Review `/stories:analyze` output
- Adjust waves or story scope

### "Agent failed"

- Check `/tmp/parallel-stories/[story]-status.md`
- May need to run story individually

## Advanced Features

### Context Optimization Strategies

**Progressive Summarization:**

- Each wave receives condensed summary of previous work
- Maintains essential context while reducing token usage
- Strategic detail pruning for later waves

**Fresh Agent Instances:**

- Each Task agent starts with clean context
- Avoids accumulation of implementation details
- Orchestrator maintains lightweight state only

**Intelligent Batching:**

- Dynamic wave sizing based on context usage
- Smaller waves as context grows
- Graceful degradation to sequential if needed

### Coordination Protocols

**Duplicate Prevention:**

- Each agent assigned unique innovation dimension
- Cross-reference existing implementations
- Explicit uniqueness directives in prompts

**Quality Control:**

- Automated test execution per story
- Lint and type checking gates
- Coverage requirements enforcement
- Performance benchmarking for relevant stories

**Communication Channels:**

```
/tmp/parallel-stories/
├── broadcasts/          # Orchestrator → All agents
├── agent-reports/       # Agents → Orchestrator
├── cross-agent/         # Agent → Agent coordination
└── quality-metrics/     # Automated quality tracking
```

### Progressive Sophistication

**Level 1 - Core (MVP):**

- Basic functionality implementation
- Essential test coverage
- Clean, maintainable code

**Level 2 - Enhanced:**

- Performance optimizations
- Edge case handling
- Comprehensive testing
- Enhanced error handling

**Level 3 - Advanced:**

- Scalability considerations
- Advanced integrations
- Performance benchmarks
- Future-proofing

### Risk Mitigation

**Agent Failure Handling:**

- Automatic reassignment to new agent
- Partial progress recovery
- Failure analysis and reporting

**Conflict Resolution:**

- Pre-execution conflict detection
- Wave separation for conflicting stories
- Merge assistance with conflict guidance

**Quality Assurance:**

- Mandatory quality gates
- Automated rollback on test failure
- Performance regression detection

## Performance Notes

### Token Usage

- Parallel agents use ~15x tokens vs chat
- Saves significant wall-clock time
- Monitor usage in status reports

### Optimization Tips

- Group truly independent stories
- Keep stories focused and small
- Run analysis first for large sets

## Summary

The `/stories` command provides a sophisticated parallel story development system with:

- **Ultra-thinking** pre-execution analysis
- **Progressive sophistication** across waves
- **Innovation dimensions** for diverse implementations
- **Context optimization** for large projects
- **Quality gates** and coordination protocols
- **Infinite mode** for continuous development

This creates an intelligent, scalable, and elegant solution for parallel development that maximizes both speed and quality while maintaining code consistency and preventing conflicts.
