BMAD workflow orchestration for AI-driven development

version
0.1.0

Install

/plugin install bmad-orchestrator@claude-devcontainer

Run it inside Claude Code after adding the marketplace with /plugin marketplace add zookanalytics/claude-devcontainer.

Contents

Discovered from source

Agents 6

AI-README.md

This file provides guidance to AI Agents (Claude Code, Gemini CLI) when working with code in this repository.

About This Project

BMAD Orchestrator is a Claude Code plugin that automates BMAD workflow orchestration. It provides:

  • Phase completion detection via Stop hooks
  • Story lifecycle management
  • Multi-instance dispatch coordination
  • Sprint status tracking

Project Structure

scripts/bmad/           # Core Python module
  cli.py                # CLI commands (menu, status, next, run-story, run-epic)
  status.py             # Sprint status parsing and priority logic
  executor.py           # Workflow execution with PTY and signal detection
hooks/scripts/          # Shell scripts for Claude Code hooks
  bmad-phase-complete.sh  # Stop hook for phase detection
docs/                   # Documentation
  research/             # Design documents and research
  implementation/       # Technical specifications

Key Concepts

Lock Files (.claude/.bmad-running/*.json)

Track actively running story work. Contains:

  • story_id: Which story is being worked on
  • starting_status: Status when phase began (for completion detection)
  • pid: Process ID of the running command

Signal File (.claude/.bmad-phase-signal.json)

Written by Stop hook when phase completes. Contains:

  • story_id: Which story
  • from_status / to_status: Status transition
  • timestamp: When detected

Dispatch File (.claude/.bmad-dispatched.json)

Tracks work sent to devcontainer instances. Used for:

  • Preventing duplicate dispatches
  • Detecting stale/dead work
  • Enabling restart functionality

Development Commands

This project uses only Python stdlib (no external dependencies).

# Run CLI directly
./scripts/bmad-cli status

# Run tests (when added)
python -m pytest tests/

Key Design Decisions

  1. No YAML Library: Uses simple custom parser to avoid dependencies
  2. PTY Execution: Full terminal transparency for interactive Claude sessions
  3. Signal-Based Termination: Stop hook + signal file for clean phase transitions
  4. Status-Based Detection: Compares status file changes rather than LLM output parsing

Files to Modify

TaskFiles
Add CLI commandscripts/bmad/cli.py
Change priority logicscripts/bmad/status.py
Modify execution flowscripts/bmad/executor.py
Update hook behaviorhooks/scripts/bmad-phase-complete.sh

Status File Locations

The orchestrator checks these locations for sprint-status.yaml:

  1. _bmad-output/implementation-artifacts/sprint-status.yaml
  2. docs/sprint-status.yaml

BMAD Orchestrator

A Claude Code plugin that automates BMAD (Breakthrough Method for Agile AI-Driven Development) workflow orchestration for AI-driven software development.

What It Does

  • Phase Detection: Automatically detects when Claude completes a workflow phase (story creation, development, code review)
  • Story Progression: Advances stories through the BMAD lifecycle (backlog → ready-for-dev → in-progress → review → done)
  • Multi-Instance Coordination: Dispatches work to devcontainer instances and tracks progress
  • Status Dashboard: Terminal-based view of sprint progress and next actions

Architecture

bmad-cli has two operating modes with different installation requirements:

CommandsRuns WherePurpose
next, restart, menu (dispatch)Host onlyOrchestrate work across multiple containers
run-story, run-epic, menu (execute)Container onlyExecute workflows inside devcontainer
status, auditEitherView status, check health

The orchestrator commands require Docker access to discover and dispatch to containers. The executor commands require being inside a devcontainer with Claude Code installed.

Installation

Host Installation (for orchestration)

Install globally on your host machine to dispatch work to containers:

npm install -g @zookanalytics/bmad-orchestrator

This provides the bmad-cli command with orchestration capabilities:

  • bmad-cli next - Dispatch next story to an available container
  • bmad-cli restart <id> - Resume a stale dispatch
  • bmad-cli menu - Interactive orchestration menu

Container Installation (for execution)

When using the claude-devcontainer Docker image, bmad-cli is pre-installed at /usr/local/bin/bmad-cli.

To enable the Stop hook for phase detection, add to your .devcontainer/devcontainer.json:

{
  "image": "ghcr.io/zookanalytics/claude-devcontainer:latest",
  "containerEnv": {
    "ENABLE_BMAD_ORCHESTRATOR": "true"
  }
}

This enables:

  • bmad-cli run-story <id> - Run a story through all phases
  • bmad-cli run-epic <id> - Run all stories in an epic
  • Phase completion detection via Stop hook

As a Claude Code Plugin (alternative)

If not using the devcontainer image, add to your project's .claude/settings.json:

{
  "enabledPlugins": {
    "bmad-orchestrator@claude-devcontainer": true
  },
  "extraKnownMarketplaces": {
    "claude-devcontainer": {
      "source": {
        "source": "directory",
        "path": "/path/to/claude-devcontainer"
      }
    }
  }
}

Usage

Interactive Menu (Recommended)

bmad-cli              # Opens interactive menu with smart defaults

The menu adapts based on environment:

  • On host: Shows orchestration options (dispatch, restart, audit)
  • In container: Shows execution options (run story, run epic)

Host Commands (Orchestration)

Run these on your host machine to manage work across containers:

bmad-cli              # Interactive orchestration menu
bmad-cli next         # Dispatch next story to an available container
bmad-cli restart ID   # Resume a stale/dead dispatch
bmad-cli audit        # Check for stale dispatches, optionally fix
bmad-cli status       # Show sprint status and next action

Container Commands (Execution)

Run these inside a devcontainer to execute workflows:

bmad-cli              # Interactive execution menu
bmad-cli run-story ID # Run a story through all phases to completion
bmad-cli run-epic ID  # Run all stories in an epic sequentially
bmad-cli status       # Show sprint status

How It Works

Phase Completion Detection

  1. When a BMAD workflow runs, the orchestrator creates a lock file tracking the story and starting status
  2. A Stop hook fires when Claude stops responding
  3. The hook compares the starting status against current sprint-status.yaml
  4. If status changed, a signal file is written
  5. The executor detects the signal and terminates Claude gracefully to proceed to the next phase

Story Lifecycle

backlog → ready-for-dev → in-progress → review → done

Each transition triggers the appropriate BMAD workflow:

  • backlog → ready-for-dev: create-story
  • ready-for-dev → in-progress: dev-story
  • in-progress → review: dev-story completion
  • review → done: code-review

Requirements

  • Python 3.10+
  • Claude Code CLI
  • BMAD Method installed in your project
  • jq for JSON parsing in hooks (fallback to grep if unavailable)

Project Structure

bmad-orchestrator/
├── plugin.json           # Claude Code plugin metadata
├── marketplace.json      # Plugin marketplace entry
├── hooks/
│   ├── hooks.json        # Hook definitions
│   └── scripts/
│       └── bmad-phase-complete.sh
├── scripts/
│   ├── bmad-cli          # CLI entry point
│   └── bmad/
│       ├── __init__.py
│       ├── cli.py        # Command implementations
│       ├── status.py     # Sprint status reader
│       └── executor.py   # Workflow execution
└── docs/
    ├── research/         # Design research and proposals
    └── implementation/   # Technical specifications

License

MIT

Tech Spec: BMAD Orchestrator

Overview

What We're Building

A lightweight CLI tool (bmad) that reads BMAD workflow state files and orchestrates development work across devcontainer instances. The tool provides:

  1. Status awareness - Always knows "where are we?" and "what's next?"
  2. Epic automation - Runs an entire epic through all stories with minimal intervention
  3. Clean audit trail - One commit per story completion or code review feedback
  4. Foundation for full automation - Structured to evolve into a dispatcher with parallel execution

Why It Matters

Currently, BMAD requires manual triggering of each phase and remembering which step comes next. This orchestrator eliminates that cognitive overhead while preserving human oversight at meaningful checkpoints.

Success Criteria

  • Single command shows current state and recommended next action
  • Can run an entire epic from start to finish with user involvement only at completion or critical questions
  • Each story produces clean, atomic commits
  • Works with existing claude-instance infrastructure
  • Terminal-only interface (no web UI)

Intervention Triggers

The orchestrator pauses automation and notifies the user when:

TriggerDetection MethodUser Action Required
Story blockedStatus set to blocked in YAMLReview blocked_reason, resolve issue
Test failuresBMAD workflow sets blocked with test outputFix tests or adjust acceptance criteria
Timeout exceededStory running > 30 min (configurable)Check instance, extend or abort
Merge conflictGit operation fails in workflowManual conflict resolution
Claude asks question(Future) Detected via instance output parsingAnswer question, resume
Epic completeAll stories in epic reach doneReview, merge PR, start next epic

Intervention Response Options:

[!] Story 1-3-protected-routes BLOCKED
    Reason: Test auth_redirect_test failing - expected 302, got 401

    Options:
    [r] Retry story (re-run dev-story)
    [s] Skip story (mark as blocked, continue epic)
    [f] Fix manually (pause automation, you take over)
    [a] Abort epic (stop all automation)

    Choice:

Context for Development

Existing Infrastructure

ComponentLocationPurpose
claude-instancescripts/claude-instanceManages devcontainer lifecycle, tmux integration
bmm-workflow-status.yaml_bmad-output/Tracks Phases 0-3 (Analysis → Solutioning)
sprint-status.yaml_bmad-output/implementation-artifacts/Tracks Phase 4 (epics, stories)
.claude-metadata.jsonworkspace rootPurpose tracking per instance
BMAD agents/workflows_bmad/21 agents, 50+ workflows

State File Structures

bmm-workflow-status.yaml (Phases 0-3):

workflow_status:
  - id: prd
    phase: 1
    status: "docs/prd.md"  # file path = complete
  - id: create-architecture
    phase: 2
    status: optional       # not started

sprint-status.yaml (Phase 4):

development_status:
  epic-1: in-progress
  1-1-project-setup: review
  1-2-user-registration: done
  1-3-protected-routes: backlog

Story Lifecycle

backlog → ready-for-dev → in-progress → review → done
  • backlog: Story exists only in epic file
  • ready-for-dev: Story file created via create-story workflow
  • in-progress: Developer actively implementing
  • review: Code review workflow running
  • done: Story completed with passing tests

Key Constraints

  1. Orchestration runs outside devcontainer - Host machine with visibility to all instances
  2. Work runs inside devcontainer - Claude instances execute in sandboxed environments
  3. One story at a time per epic - Sequential within epic, parallel across epics (future)
  4. Commits are atomic - One logical change per commit (story completion, review fix)
  5. No race conditions on state files - Sequential-by-epic model means only one instance modifies sprint-status.yaml at a time per epic. Future parallel execution will use epic-level locking or separate status files per epic.

Implementation Plan

Architecture

┌─────────────────────────────────────────────────────────────┐
│                      bmad CLI (host)                        │
│                                                             │
│  bmad status    - Read YAML, display status and next action │
│  bmad next      - Execute recommended action                │
│  bmad run-epic  - Automate entire epic through completion   │
│  bmad run-story - Automate single story through completion  │
└─────────────────────────────────────────────────────────────┘
         │                                    │
         │ reads directly                     │ dispatches work
         ▼                                    ▼
┌─────────────────────────┐         ┌─────────────────────────┐
│ sprint-status.yaml      │         │ claude-instance         │
│                         │         │                         │
│ Parsed by orchestrator  │         │ Runs BMAD workflows:    │
│ for status + next story │         │ • create-story          │
│                         │         │ • dev-story             │
│                         │         │ • code-review           │
└─────────────────────────┘         └─────────────────────────┘

Key insight: The orchestrator reads YAML directly for fast status checks, but invokes BMAD workflows (via claude-instance) for actual work execution. This avoids expensive Claude calls just to read a file.

File Structure

scripts/
├── claude-instance          # Existing - no changes needed
├── bmad                     # New - main CLI entry point (bash wrapper)
└── bmad/
    ├── __init__.py
    ├── cli.py               # Click-based CLI interface
    ├── status.py            # Reads sprint-status.yaml, computes next action
    └── executor.py          # Dispatches work to claude-instance

Core Components

1. Status Reader (status.py)

Reads sprint-status.yaml directly. Implements BMAD's priority logic (~20 lines).

@dataclass
class SprintStatus:
    """Parsed sprint status with computed metrics."""
    epics: dict[str, str]           # {"epic-1": "in-progress", ...}
    stories: dict[str, str]         # {"1-1-project-setup": "review", ...}
    counts: dict[str, int]          # {"backlog": 3, "done": 2, ...}

@dataclass
class Action:
    type: str           # "create-story", "dev-story", "code-review"
    story_id: str       # Target story
    skill: str          # Full BMAD skill path

def load_sprint_status(project_path: str) -> SprintStatus:
    """
    Read and parse sprint-status.yaml directly.

    Handles flat dict format:
        development_status:
          epic-1: in-progress
          1-1-project-setup: review
    """
    yaml_path = f"{project_path}/_bmad-output/implementation-artifacts/sprint-status.yaml"
    with open(yaml_path) as f:
        data = yaml.safe_load(f)

    dev_status = data.get("development_status", {})

    epics = {k: v for k, v in dev_status.items() if k.startswith("epic-")}
    stories = {k: v for k, v in dev_status.items()
               if not k.startswith("epic-") and not k.endswith("-retrospective")}

    counts = {"backlog": 0, "ready-for-dev": 0, "in-progress": 0, "review": 0, "done": 0}
    for status in stories.values():
        if status in counts:
            counts[status] += 1

    return SprintStatus(epics=epics, stories=stories, counts=counts)

def get_next_action(status: SprintStatus) -> Action | None:
    """
    Compute next action using BMAD's priority logic.

    Priority (from BMAD sprint-status Step 3):
    1. in-progress → continue with dev-story
    2. review → code-review
    3. ready-for-dev → dev-story
    4. backlog → create-story
    5. All done → None
    """
    # Sort stories by ID for consistent ordering
    sorted_stories = sorted(status.stories.items(), key=lambda x: x[0])

    for story_id, story_status in sorted_stories:
        if story_status == "in-progress":
            return Action("dev-story", story_id, "bmad:bmm:workflows:dev-story")

    for story_id, story_status in sorted_stories:
        if story_status == "review":
            return Action("code-review", story_id, "bmad:bmm:workflows:code-review")

    for story_id, story_status in sorted_stories:
        if story_status == "ready-for-dev":
            return Action("dev-story", story_id, "bmad:bmm:workflows:dev-story")

    for story_id, story_status in sorted_stories:
        if story_status == "backlog":
            return Action("create-story", story_id, "bmad:bmm:workflows:create-story")

    return None  # All complete
2. Executor (executor.py)
def dispatch_to_instance(
    action: Action,
    instance_name: str,
    wait_for_completion: bool = True
) -> ExecutionResult:
    """
    Dispatch action to a claude-instance.

    1. Render prompt template with action.context
    2. Call claude-instance with prompt
    3. Wait for completion (if requested)
    4. Parse result and return status
    """

def run_story_to_completion(story_id: str) -> StoryResult:
    """
    Run a single story through all phases until done.

    Loop:
      1. Load current state
      2. Get next action for this story
      3. If action is None, story is done
      4. Execute action
      5. Check for user intervention needs
      6. Repeat
    """

def run_epic_to_completion(epic_id: str) -> EpicResult:
    """
    Run all stories in an epic sequentially.

    For each story in epic:
      1. If backlog, create story first
      2. Run story to completion
      3. Advance to next story
    """
4. CLI Interface (cli.py)
@click.group()
def bmad():
    """BMAD Orchestrator - Workflow automation for AI-driven development."""

@bmad.command()
def status():
    """Show current workflow state and next recommended action."""
    state = load_state(".")
    display_status_table(state)
    action = get_next_action(state)
    display_recommendation(action)

@bmad.command()
@click.option("--yes", "-y", is_flag=True, help="Skip confirmation")
def next(yes: bool):
    """Execute the next recommended action."""
    state = load_state(".")
    action = get_next_action(state)

    if not yes:
        if not confirm_action(action):
            return

    result = dispatch_to_instance(action, instance_name=f"bmad-{action.context['story_id']}")
    display_result(result)

@bmad.command()
@click.argument("epic_id")
@click.option("--dry-run", is_flag=True)
def run_epic(epic_id: str, dry_run: bool):
    """Run an entire epic through all stories to completion."""
    if dry_run:
        display_epic_plan(epic_id)
        return

    result = run_epic_to_completion(epic_id)
    display_epic_result(result)

@bmad.command()
@click.argument("story_id")
def run_story(story_id: str):
    """Run a single story through to completion."""
    result = run_story_to_completion(story_id)
    display_story_result(result)

BMAD Integration

Division of Responsibility:

Orchestrator Does (Fast, Local)BMAD Does (Via Claude Instance)
Read sprint-status.yaml directlyExecute create-story workflow
Compute next action (priority logic)Execute dev-story workflow
Display status and countsExecute code-review workflow
Monitor for completionLoad agent personas
Set in-progress before dispatchUpdate status files after work
Detect blocked/timeoutCreate commits

Why This Split:

  • Status checking happens frequently → must be fast (no Claude calls)
  • Work execution is expensive anyway → BMAD workflows add value
  • Priority logic is ~20 lines → not worth a Claude call
  • Risk detection can be added later if needed

Dispatch Approach:

def dispatch_to_instance(
    action: Action,
    instance_name: str,
    timeout_minutes: int = 30
) -> ExecutionResult:
    """
    Launch claude-instance and invoke existing BMAD skill.

    Uses Popen with polling (not blocking subprocess.run) to:
    - Monitor progress via status file changes
    - Detect intervention triggers
    - Enforce timeout limits
    - Allow graceful interruption

    The BMAD workflow handles:
    - Agent persona loading
    - Reading relevant context files
    - Executing the workflow steps
    - Updating status files
    - Creating appropriate commits
    """
    skill = WORKFLOW_MAPPING[action.type]
    prompt = f"Run /{skill} for story {action.context['story_id']}"

    # Non-blocking launch
    process = subprocess.Popen(
        ["./scripts/claude-instance", "create", instance_name,
         "--prompt", prompt,
         "--branch", action.context.get("branch", "main")],
        stdout=subprocess.PIPE,
        stderr=subprocess.PIPE
    )

    # Polling loop
    start_time = time.time()
    while process.poll() is None:
        # Check timeout
        if time.time() - start_time > timeout_minutes * 60:
            process.terminate()
            return ExecutionResult(status="timeout", story_id=action.context['story_id'])

        # Check for intervention triggers (status file changes)
        current_status = load_story_status(action.context['story_id'])
        if current_status == "blocked":
            return ExecutionResult(status="intervention_needed", story_id=action.context['story_id'])

        time.sleep(5)  # Poll every 5 seconds

    exit_code = process.returncode
    return ExecutionResult(
        status="success" if exit_code == 0 else "failed",
        story_id=action.context['story_id'],
        exit_code=exit_code
    )

Status Transition Ownership:

TransitionWho Sets ItWhen
backlog → ready-for-devBMAD create-story workflowAfter story file created
ready-for-dev → in-progressOrchestratorBefore dispatching dev-story
in-progress → reviewBMAD dev-story workflowAfter implementation complete
review → doneBMAD code-review workflowAfter review passes
Any → blockedBMAD workflowWhen intervention needed

Critical: Orchestrator sets in-progress before dispatch to prevent race conditions where both sides assume the other will do it.

Code Review Fresh Instance Requirement:

The code-review action MUST spawn a new Claude instance (not continue in the same session). This ensures:

  • Fresh context without implementation bias
  • Independent evaluation of the code
  • BMAD principle: "reviewer should not be the implementer"
def dispatch_code_review(story_id: str) -> ExecutionResult:
    """
    Code review requires fresh instance - never reuse dev session.
    """
    instance_name = f"review-{story_id}-{int(time.time())}"  # Unique name
    return dispatch_to_instance(
        action=Action(type="code-review", ...),
        instance_name=instance_name
    )

Responsibility Split:

Orchestrator ResponsibilityBMAD Workflow Responsibility
Read state filesLoad agent persona
Compute "what's next"Read story/epic files
Select correct workflowExecute implementation steps
Launch claude-instanceUpdate sprint-status.yaml
Monitor for completionCreate commits
Advance to next stepHandle workflow-specific logic

Implementation Tasks

Phase 1: Status Reader (MVP) ✅ COMPLETE
  • Create scripts/bmad/status.py with load_sprint_status()
  • Parse sprint-status.yaml flat dict format (custom parser, no pyyaml)
  • Implement get_next_action() with BMAD priority logic
  • Implement bmad status command (display counts + next action)
  • Implement bmad run-epic --dry-run and bmad run-story --dry-run
  • Tests: YAML parsing, priority logic, edge cases (empty, all done)
Phase 2: Single Action Execution
  • Create scripts/bmad/executor.py with dispatch_to_instance() using Popen
  • Implement status transition (set in-progress before dispatch)
  • Integrate with claude-instance script
  • Implement bmad next command
  • Integration tests: Mock subprocess, exit code handling, timeout
Phase 3: Story Automation
  • Implement run_story_to_completion() with polling loop
  • Add intervention trigger detection (blocked, timeout, etc.)
  • Implement intervention response UI (retry/skip/fix/abort)
  • Implement bmad run-story command
  • Implement dispatch_code_review() with fresh instance requirement
  • Chaos tests: Mid-story exit, BMAD data mode failure
Phase 4: Epic Automation
  • Implement run_epic_to_completion()
  • Add epic-level progress display
  • Implement bmad run-epic command
  • Add --dry-run to show plan without executing
  • E2E tests: Full story lifecycle, full epic run-through
Phase 5: Polish & Documentation
  • Add rich terminal output with progress indicators
  • Add error handling and recovery guidance
  • Add logging for audit trail
  • Update AI-README.md with new commands
  • Document intervention triggers and response options

Dependencies

# Core (Python stdlib only - no external dependencies)
argparse          # CLI framework (stdlib)
dataclasses       # Data structures (stdlib)
pathlib           # Path handling (stdlib)

# Development/Testing
pytest>=7.0       # Testing framework
pytest-mock>=3.0  # Mocking utilities

Note: The orchestrator uses only Python stdlib to avoid dependency management issues. YAML parsing is done with a simple custom parser sufficient for sprint-status.yaml format.

Testing Strategy

Unit Tests (Required - Phase 1):

  • YAML parsing with various structures (empty, partial, complete)
  • Priority logic: in-progress beats review beats ready-for-dev beats backlog
  • Story ID sorting for consistent ordering
  • Edge cases: empty sprint, all done, no stories

Integration Tests (Required - Phase 2):

  • Mock claude-instance subprocess returning various exit codes
  • Timeout detection and process termination
  • Intervention trigger detection from status file changes

Chaos Scenario Tests (Required - Phase 3):

  • Instance exits mid-story (process killed)
  • Status file changes during polling (external edit)
  • Recovery from blocked status
  • Malformed YAML handling

E2E Tests (Phase 4):

  • Full story lifecycle with real Claude instance
  • Full epic run-through with multiple stories
  • Intervention flow (block, user response, resume)

Test Infrastructure:

# tests/conftest.py
@pytest.fixture
def sample_sprint_status(tmp_path):
    """Create sample sprint-status.yaml for testing."""
    yaml_content = """
development_status:
  epic-1: in-progress
  1-1-project-setup: done
  1-2-user-registration: review
  1-3-protected-routes: ready-for-dev
  epic-2: backlog
  2-1-document-model: backlog
"""
    status_file = tmp_path / "sprint-status.yaml"
    status_file.write_text(yaml_content)
    return status_file

@pytest.fixture
def mock_claude_instance(monkeypatch):
    """Mock subprocess calls to claude-instance."""

@pytest.fixture
def chaos_scenario(request):
    """Parameterized chaos scenarios for resilience testing."""

Risks and Mitigations

RiskMitigation
Claude instance hangsAdd timeout with status check, manual recovery instructions
State file corruptionValidate before write, backup before modify
Merge conflictsFail fast, provide manual resolution steps
Story fails testsKeep in review status, surface for human intervention

Open Questions

Resolved

  1. Language preference? → No preference, using Python (matches existing tooling patterns)
  2. Where does orchestration run? → Host machine, outside devcontainer
  3. Full automation now? → No, build foundation (Option A++) with path to full automation

Pragmatic Decision: Direct YAML Reading

After analysis, the orchestrator should read sprint-status.yaml directly rather than invoking BMAD data mode:

Why:

  • BMAD's priority logic is 5 simple if-statements - trivial to reimplement
  • Calling Claude just to parse a YAML file is expensive and slow
  • No reliable way to capture BMAD's template-output values
  • The orchestrator runs outside devcontainer, needs direct file access anyway

What we adopt from BMAD:

  • Priority logic: in-progress > review > ready-for-dev > backlog
  • Status values and lifecycle transitions
  • Story ID format conventions

What we skip (for now):

  • Risk detection (stale files, orphaned stories) - add later
  • Validation mode - orchestrator trusts the file format
  • Interactive prompts - orchestrator is automation-focused

This is a pragmatic tradeoff: we reimplement ~20 lines of simple logic to avoid complex output parsing and expensive Claude calls for status checks.

Future Enhancements (Out of Scope for Now)

  • Parallel epic execution (multiple devcontainers)
  • Web dashboard
  • Slack/webhook notifications
  • Automatic PR creation per epic
  • Cost tracking per story

Forward Compatibility for Full Dispatcher

The following design decisions enable future evolution to a full dispatcher with parallel execution:

Current DesignEnables Future
ExecutionResult dataclass with status/exit_codeDispatcher can aggregate results across instances
dispatch_to_instance() abstractionSwap subprocess for container orchestration API
Epic-level operations (run_epic)Natural unit for parallel execution
State files as source of truthMultiple instances can poll same files with locking
Skill mapping validationNew workflows register without code changes
Intervention trigger systemCentralized alert routing to user

Critical interfaces to preserve:

  1. Action dataclass structure - dispatcher will queue these
  2. ExecutionResult return type - dispatcher will aggregate these
  3. WORKFLOW_MAPPING dict - add workflows without modifying dispatch logic
  4. Status file format - add epic-level locks, not structural changes

Generated by create-tech-spec workflow Date: 2025-12-28

BMAD Pipeline Automation Proposal

Executive Summary

Build a lightweight dispatcher that orchestrates BMAD (Breakthrough Method for Agile AI-Driven Development) workflows across multiple parallel Claude instances. The dispatcher watches for ready features, assigns them to existing devcontainer infrastructure, and tracks each feature through a sequential story → development → testing pipeline.


Current State

What We Have

ComponentImplementationNotes
Parallel Claude executionclaude-instance scriptLaunches Claude in isolated devcontainers
SandboxingDocker containersAlready configured and working
Context/MemoryBMAD artifact filesPRD, architecture, stories, etc.
MonitoringtmuxFunctional but requires manual attention
BMAD methodInstalledAgents, workflows, templates in place

What We're Missing

  1. Trigger mechanism — No automated detection when a feature is ready for work
  2. Status tracking — No centralized view of which features are in which phase
  3. Workflow sequencing — No automation of the story → dev → test progression per feature
  4. Dashboard — No quick-glance visibility across all active work

Proposed Architecture

┌─────────────────────────────────────────────────────────────────┐
│                      BMAD Dispatcher                            │
│                                                                 │
│  • Watches: docs/sprint-status.yaml                             │
│  • Dispatches to: existing claude-instance infrastructure       │
│  • Tracks: feature phase progression                            │
│  • Reports: terminal dashboard                                  │
└─────────────────────────────────────────────────────────────────┘
         │                    │                    │
         ▼                    ▼                    ▼
   ┌───────────┐        ┌───────────┐        ┌───────────┐
   │ Container │        │ Container │        │ Container │
   │ feature-a │        │ feature-b │        │ feature-c │
   │           │        │           │        │           │
   │ Branch:   │        │ Branch:   │        │ Branch:   │
   │ feature/a │        │ feature/b │        │ feature/c │
   │           │        │           │        │           │
   │ Phase:    │        │ Phase:    │        │ Phase:    │
   │ dev       │        │ story     │        │ test      │
   └───────────┘        └───────────┘        └───────────┘

Data Flow

  1. User marks feature as ready-for-stories in sprint-status.yaml
  2. Dispatcher detects change, spawns container via claude-instance
  3. Container executes story creation, updates status to story-complete
  4. Dispatcher detects completion, advances to dev phase, re-dispatches
  5. Repeat for dev → test → complete
  6. Dashboard shows real-time status across all features

File Specifications

sprint-status.yaml (Enhanced)

# docs/sprint-status.yaml
current_sprint: 3
max_parallel_features: 4  # Limit concurrent work

features:
  - id: user-auth
    status: ready-for-stories  # Triggers pipeline
    prd_section: "2.1"
    priority: high
    branch: feature/user-auth
    
  - id: dashboard-widgets
    status: implementing  # Currently in dev phase
    prd_section: "3.2"
    priority: medium
    branch: feature/dashboard-widgets
    started_at: "2025-12-28T10:30:00Z"
    
  - id: notification-system
    status: complete
    prd_section: "2.4"
    priority: high
    branch: feature/notification-system
    completed_at: "2025-12-27T16:45:00Z"

# Valid status values (in order):
# - backlog
# - ready-for-stories  ← triggers dispatcher
# - creating-story
# - story-complete
# - implementing
# - dev-complete
# - testing
# - test-complete
# - complete
# - blocked (with blocked_reason field)

Dispatcher Configuration

# .bmad/dispatcher-config.yaml
polling_interval_seconds: 10
max_parallel_features: 4

claude_instance:
  script_path: ./scripts/claude-instance.sh
  default_args:
    - --dangerously-skip-permissions
    
phases:
  story:
    trigger_status: ready-for-stories
    working_status: creating-story
    complete_status: story-complete
    prompt_template: prompts/story-creation.md
    
  dev:
    trigger_status: story-complete
    working_status: implementing
    complete_status: dev-complete
    prompt_template: prompts/implementation.md
    
  test:
    trigger_status: dev-complete
    working_status: testing
    complete_status: complete
    prompt_template: prompts/testing.md

notifications:
  on_phase_complete: true
  on_error: true
  # Future: slack webhook, etc.

Component Specifications

1. Dispatcher (bmad_dispatcher.py)

Responsibilities:

  • Poll sprint-status.yaml for status changes
  • Maintain in-memory state of active features
  • Spawn containers via claude-instance script
  • Detect phase completion and advance workflow
  • Respect max_parallel_features limit
  • Handle errors gracefully (mark feature as blocked)

Key Functions:

def load_sprint_status() -> dict:
    """Load and parse sprint-status.yaml"""
    
def get_actionable_features(status: dict) -> list[Feature]:
    """Find features that need work started or advanced"""
    
def dispatch_feature(feature: Feature, phase: Phase) -> subprocess.Popen:
    """Launch claude-instance for a feature/phase combination"""
    
def check_phase_complete(feature: Feature) -> bool:
    """Check if feature's current phase is complete (via status file)"""
    
def advance_feature(feature: Feature) -> None:
    """Move feature to next phase and dispatch if not done"""
    
def main_loop() -> None:
    """Primary polling loop"""

Error Handling:

  • If a container exits non-zero, mark feature as blocked
  • Add blocked_reason field with error details
  • Continue processing other features
  • Log errors for later review

2. Prompt Templates

Each phase uses a template that gets feature-specific values interpolated:

prompts/story-creation.md:

You are the BMAD Scrum Master agent.

## Context
- Feature ID: {{feature_id}}
- PRD Section: {{prd_section}}
- Branch: {{branch}}

## Task
1. Read `docs/prd.md` section {{prd_section}}
2. Read `docs/architecture.md` for technical constraints
3. Create `docs/stories/{{feature_id}}-story.md` following the template in `docs/templates/story-template.md`

## Requirements
- Include clear acceptance criteria (testable)
- Include technical implementation notes
- List files that will be created/modified
- Note any dependencies on other features

## On Completion
1. Git add and commit: `feat(stories): create {{feature_id}} story`
2. Update `docs/sprint-status.yaml`: set {{feature_id}} status to `story-complete`
3. Git add and commit: `chore: mark {{feature_id}} story complete`

prompts/implementation.md:

You are the BMAD Developer agent.

## Context
- Feature ID: {{feature_id}}
- Story: `docs/stories/{{feature_id}}-story.md`
- Branch: {{branch}}

## Task
1. Read the story file completely
2. Read `docs/architecture/coding-standards.md`
3. Implement the feature per acceptance criteria

## Requirements
- Follow existing code patterns
- Add appropriate comments
- Do not modify files outside the story's scope
- Commit logical chunks with descriptive messages

## On Completion
1. Final commit with implementation
2. Update `docs/sprint-status.yaml`: set {{feature_id}} status to `dev-complete`
3. Git commit: `chore: mark {{feature_id}} implementation complete`

prompts/testing.md:

You are the BMAD QA agent.

## Context
- Feature ID: {{feature_id}}
- Story: `docs/stories/{{feature_id}}-story.md`
- Branch: {{branch}}

## Task
1. Read the story's acceptance criteria
2. Create test files in `tests/{{feature_id}}/`
3. Write tests that verify each acceptance criterion
4. Run the test suite

## Requirements
- Each acceptance criterion should have at least one test
- Tests should be independent and repeatable
- Include both positive and negative cases where appropriate

## On Completion
1. Commit test files: `test({{feature_id}}): add tests`
2. Update `docs/sprint-status.yaml`: set {{feature_id}} status to `complete`
3. Git commit: `chore: mark {{feature_id}} complete`

## If Tests Fail
- Document failures in `docs/stories/{{feature_id}}-test-failures.md`
- Set status to `blocked` with reason
- Do NOT attempt to fix implementation code

3. Status Dashboard (bmad_status.py)

Responsibilities:

  • Real-time terminal display of all feature statuses
  • Show phase, duration, branch for each feature
  • Highlight blocked features
  • Refresh automatically

Display Format:

╭─────────────────────────────────────────────────────────────╮
│                 BMAD Pipeline Status                        │
│                 Updated: 2025-12-28 14:32:05                │
├──────────────────┬────────────┬─────────────┬───────────────┤
│ Feature          │ Phase      │ Duration    │ Branch        │
├──────────────────┼────────────┼─────────────┼───────────────┤
│ user-auth        │ 🔨 Dev     │ 12m 34s     │ feature/...   │
│ dashboard        │ 📝 Story   │ 3m 21s      │ feature/...   │
│ notifications    │ 🧪 Test    │ 8m 02s      │ feature/...   │
│ settings         │ ✅ Done    │ —           │ feature/...   │
│ api-v2           │ 🚫 Blocked │ 45m 12s     │ feature/...   │
├──────────────────┴────────────┴─────────────┴───────────────┤
│ Active: 3/4 max │ Completed today: 2 │ Blocked: 1          │
╰─────────────────────────────────────────────────────────────╯

Dependencies:

  • rich for terminal formatting
  • pyyaml for status file parsing

4. Integration with claude-instance

The dispatcher calls the existing claude-instance script. Required interface:

./claude-instance.sh \
  --name <feature-id> \
  --branch <branch-name> \
  --prompt-file <path-to-prompt> \
  [--timeout <seconds>] \
  [additional args passed through]

Expected behavior:

  • Creates/attaches to a devcontainer named after the feature
  • Checks out the specified branch
  • Executes Claude with the provided prompt
  • Exits with 0 on success, non-zero on failure

If the current script interface differs, document the actual interface and we'll adapt the dispatcher.


Implementation Plan

Phase 1: Core Dispatcher (MVP)

  • Create bmad_dispatcher.py with basic polling loop
  • Implement feature detection from sprint-status.yaml
  • Integrate with claude-instance script
  • Implement phase advancement logic
  • Add basic logging

Phase 2: Status Dashboard

  • Create bmad_status.py with rich terminal UI
  • Add duration tracking
  • Add blocked feature highlighting
  • Test alongside dispatcher

Phase 3: Robustness

  • Add error handling and blocked status support
  • Add timeout handling for stuck features
  • Add graceful shutdown (SIGTERM handling)
  • Add configuration file support

Phase 4: Enhancements (Optional)

  • Web dashboard alternative (simple Flask/FastAPI)
  • Slack/webhook notifications
  • Metrics collection
  • Historical tracking

Directory Structure

project-root/
├── .bmad/
│   ├── dispatcher-config.yaml
│   └── prompts/
│       ├── story-creation.md
│       ├── implementation.md
│       └── testing.md
├── scripts/
│   ├── claude-instance.sh        # Existing
│   ├── bmad_dispatcher.py        # New
│   └── bmad_status.py            # New
├── docs/
│   ├── sprint-status.yaml        # Enhanced
│   ├── prd.md
│   ├── architecture.md
│   ├── stories/
│   │   └── {feature-id}-story.md
│   └── templates/
│       └── story-template.md
└── tests/
    └── {feature-id}/

Questions for Implementation

  1. What is the exact interface of claude-instance.sh?

    • What arguments does it accept?
    • How does it handle branch checkout?
    • How is the prompt passed (file, stdin, argument)?
  2. Where should the dispatcher run?

    • Same machine as devcontainers?
    • Separate orchestration container?
  3. How should we handle branch conflicts?

    • Auto-rebase from main before each phase?
    • Fail and mark blocked?
  4. Timeout policy?

    • How long should each phase be allowed to run?
    • Same timeout for all phases or phase-specific?
  5. Notification preferences?

    • Terminal only for MVP?
    • Future: Slack, email, etc.?

Success Criteria

  1. User can mark a feature as ready-for-stories and walk away
  2. Feature automatically progresses through story → dev → test
  3. Multiple features run in parallel (up to configured limit)
  4. Status is visible at a glance in terminal dashboard
  5. Failures are caught and surfaced, not silent
  6. Integrates with existing claude-instance infrastructure without modification

Non-Goals (Explicit Exclusions)

  • No new sandboxing — Use existing devcontainer setup
  • No conversation persistence — BMAD files are the memory
  • No external dependencies — Beyond Python stdlib + rich + pyyaml
  • No web UI for MVP — Terminal dashboard is sufficient
  • No GitHub Actions — This runs locally
  • No multi-user support — Single developer workflow

References


Document version: 1.0 Created: 2025-12-28 For: Claude instance with repository access

AI Agent Workflow Completion Detection Research

Date: 2025-12-30 Context: Research conducted to improve BMAD phase completion detection

Problem Statement

When running BMAD workflows, the system needs to detect when Claude has completed a phase (e.g., create-story, dev-story, code-review) so it can automatically proceed to the next phase without requiring the user to manually quit Claude.

Current Implementation

Our solution uses:

  1. Stop hook (.claude/hooks/bmad-phase-complete.sh) - Fires when Claude stops responding
  2. Status comparison - Compares starting_status in lock file against current sprint-status.yaml
  3. Signal file - When status changes, writes .claude/.bmad-phase-signal.json
  4. Custom PTY loop - _pty_spawn_with_signal() in executor.py watches for signal file and terminates Claude gracefully

Research Findings

1. CrewAI Approach: Callbacks & Guardrails

CrewAI uses a multi-layered approach:

  • Task callbacks - Fire after task completion with output context
  • Guardrails - Validation functions that can reject outputs and trigger rework
  • LLM-based guardrails - Use an LLM to evaluate if output meets criteria

Example guardrail pattern:

def validate_output(result: TaskOutput) -> GuardrailResult:
    if not meets_criteria(result):
        return GuardrailResult(success=False, error="Missing required sections")
    return GuardrailResult(success=True, result=result)

Relevance: Guardrails concept could enhance our Stop hook - instead of just detecting status change, we could validate phase output quality.

2. Claude-flow: Stream-JSON Chaining

The claude-flow project (GitHub) uses:

  • Structured JSON output between agents - Each agent outputs structured data
  • Dependency-based execution - Next task waits for specific outputs
  • Checkpointing - State saved between phases for recovery
  • Stream-based communication - Agents chain via stdout/stdin JSON streams

Relevance: Our sprint-status.yaml approach is similar to their structured output validation. Could enhance by adding explicit "phase complete" markers.

3. Agent Loop Termination Patterns

Research identified 4 common patterns for detecting agent completion:

PatternDescriptionReliabilityOur Usage
LLM says completeAgent explicitly signals "I'm done"Low (can hallucinate)Not used
Function/tool signalAgent calls a finish() toolHighNot yet implemented
Max steps reachedSafety limit on iterationsMedium (may cut off early)Yes (max_same_status_retries)
Specific info producedValidates expected output existsHighYes (status file change)

Relevance: Pattern #4 aligns with our approach. Could add Pattern #2 via /phase-complete skill.

4. State Machine Orchestration (LangGraph)

LangGraph uses:

  • StateGraph - Explicit state transitions with validation
  • Conditional edges - Routing based on output analysis
  • Self-reflection loops - Quality gates before proceeding
  • Interrupt/resume - Human-in-the-loop at defined points

Relevance: Our status-based transitions already implement a state machine:

backlog → ready-for-dev → in-progress → review → done

Adding validation at each edge would strengthen reliability.

5. Orchestrator Pattern (Multi-Agent)

From Claude Code orchestration research:

  • Orchestrator delegates, never implements - Prevents context pollution
  • Sub-agents get focused context - Only what they need for their task
  • Clear handoff points - Explicit signals between agents
  • Context management - Summarization between phases

Relevance: Our phase-based approach naturally segments context. Each Claude invocation starts fresh with focused task.

Industry Comparison

ApproachCrewAIClaude-flowLangGraphOur BMAD
State machine✅✅✅✅
Structured output✅✅✅✅
Safety limits✅✅✅✅
Checkpointing✅✅✅✅ (status file)
Explicit completion signal✅✅✅⚠️ Partial
Output guardrails✅❌✅❌
Human-in-loop✅❌✅✅

Recommendations

Short-term (Current Implementation is Solid)

Our Stop hook + signal file approach aligns with industry patterns:

  • Status-based detection = "specific info produced" pattern
  • Lock file tracking = checkpointing pattern
  • Max retries = safety limit pattern

No immediate changes needed - the current implementation is sound.

Medium-term Enhancements

  1. Add /phase-complete skill

    • Workflows explicitly call when done
    • Provides explicit signaling (Pattern #2)
    • Reduces reliance on status file timing
  2. Enhanced status markers

    • Add phase_completed_at timestamp to status
    • Include completed_by (which workflow)
    • Enables better debugging and audit trail

Long-term Enhancements

  1. Output guardrails

    • Before accepting phase complete, validate outputs exist
    • For dev-story: tests pass, code compiles, files created
    • For code-review: review comments addressed, no blockers
  2. LLM-based validation

    • Use lightweight model to verify phase output quality
    • "Does this code review output indicate approval or changes needed?"
  3. Structured phase output

    • Each workflow outputs JSON summary
    • Orchestrator validates expected fields present

Risk Analysis

RiskMitigation
False positive (Claude pauses mid-thought)Status change check prevents this
False negative (status not updated)Max retry limit catches stuck states
Race condition (status check vs file write)Signal file is atomic signal
Claude crashes mid-phaseLock file persists, can resume

Files Modified in Implementation

  • .claude/hooks/bmad-phase-complete.sh - Stop hook script
  • .claude/settings.json - Hook registration
  • scripts/bmad/executor.py - Custom PTY loop with signal watching
  • scripts/bmad/cli.py - Lock file starting_status tracking

References

  • CrewAI Documentation: Callbacks and Guardrails
  • Claude-flow GitHub Wiki: Workflow Orchestration
  • LangGraph: StateGraph patterns
  • Agent loop termination best practices (various sources)

BMAD Workflow Orchestration Implementation Brief

Executive Summary

This document captures research and decisions from a conversation about bringing structure to AI agent-driven software development at scale. The conclusion: BMAD Method is the right methodology, but we need a thin orchestration layer that eliminates the manual cognitive load of knowing "where am I?" and "what step is next?"


Problem Statement

We currently use BMAD (Breakthrough Method for Agile AI-Driven Development) manually. The methodology is solid—it provides:

  • Structured 4-phase lifecycle (Analysis → Planning → Solutioning → Implementation)
  • Specialized agents (PM, Architect, Developer, Scrum Master, etc.)
  • Artifact management (PRD, Architecture docs, Epic sharding, Stories)
  • Context preservation across handoffs

The friction point: Triggering each phase manually and knowing which step to trigger next is more complicated than desired. We want the system to know where we are and what comes next.


Research Summary: Alternatives Considered

Full Methodology Alternatives

FrameworkWhat It IsWhy We Didn't Choose It
GitHub Spec KitSpec-driven development (Spec → Plan → Tasks → Implement)Lighter weight, less opinionated about agent roles. Would require rebuilding process structure we already have.
MetaGPTSimulates software company with 5 roles (PM, Architect, Project Manager, Engineer, QA)More automated but less flexible. Roles are less customizable than BMAD.
CrewAIRole-based multi-agent orchestration frameworkBuilding blocks, not methodology. Would need to rebuild BMAD-like structure on top.
LangGraphGraph-based workflow orchestrationInfrastructure, not methodology. Same issue as CrewAI.

Orchestration-Specific Options

ApproachAssessment
State machine framework (LangGraph, etc.)Overkill. BMAD workflow is mostly linear, not complex branching. Would require maintaining two parallel state systems.
BMAD MCP Server (third-party)Worth evaluating. Claims "automatic workflow progression" but needs validation.
Roll our own on BMAD state fileRecommended. BMAD's bmm-workflow-status.yaml already IS the state. We just need a thin interpreter.

Decision: Build a Thin Orchestration Layer

Why This Approach

  1. BMAD's state file (bmm-workflow-status.yaml + sprint-status.yaml) already captures workflow state
  2. The workflow logic is simple—mostly linear with iteration on stories
  3. A state machine framework would require reimplementing BMAD's workflow graph in a second system
  4. Estimated effort: 50-100 lines of core logic

What the Orchestrator Does

  1. Reads current state from BMAD status files
  2. Computes next step based on track and completion status
  3. Returns the agent to load and workflow to run
  4. Optionally auto-triggers with confirmation prompt

BMAD Workflow Structure (For Implementation Reference)

Tracks (Determined by workflow-init)

  • Quick Flow (Level 0-1): Bug fixes, simple features. Skips Phase 3.
  • BMad Method (Level 2): Standard features. All phases.
  • Enterprise (Level 3+): Large scale. All phases with additional rigor.

Phase Progression

Phase 1: Analysis (Optional)
├── brainstorm-project (optional)
├── research (optional)
└── product-brief (recommended)

Phase 2: Planning (Required)
└── prd (REQUIRED) → generates PRD.md

Phase 3: Solutioning (Required for BMad Method + Enterprise, skip for Quick Flow)
├── create-architecture (required) → generates architecture.md
├── create-epics-and-stories (required) → generates epic files
└── implementation-readiness (gate check)

Phase 4: Implementation (Required)
├── sprint-planning (sets up sprint)
├── For each Epic:
│   ├── epic-tech-context (optional)
│   └── For each Story:
│       ├── create-story (SM generates story file)
│       ├── dev-story (Dev implements)
│       ├── code-review (review)
│       └── story-done (mark complete)
└── Repeat until all epics complete

Key Status Files

  • docs/bmm-workflow-status.yaml - Tracks Phases 1-3 completion
  • docs/sprint-status.yaml - Tracks Phase 4 (stories, epics, sprint progress)

Agent ↔ Workflow Mapping

WorkflowAgent
product-briefAnalyst
prdPM
create-architectureArchitect
create-epics-and-storiesPM
sprint-planningScrum Master
create-storyScrum Master
dev-storyDeveloper
code-review(Fresh LLM / separate reviewer)

Proposed Implementation

Core Logic (Pseudocode)

def get_next_step(project_path):
    """
    Reads BMAD state files and returns the next workflow to execute.
    
    Returns:
        {
            'phase': int,
            'agent': str,
            'workflow': str,
            'context': dict,  # Additional context like story_id, epic_id
            'status': 'pending' | 'complete'
        }
    """
    workflow_status = load_yaml(f"{project_path}/docs/bmm-workflow-status.yaml")
    track = workflow_status.get('track', 'bmad-method')
    
    # Phase 1: Analysis (all optional, skip to Phase 2 if not started)
    # User can manually invoke these, orchestrator focuses on required paths
    
    # Phase 2: Planning
    if not is_complete(workflow_status, 'phase_2', 'prd'):
        return {
            'phase': 2,
            'agent': 'pm',
            'workflow': 'prd',
            'context': {},
            'status': 'pending'
        }
    
    # Phase 3: Solutioning (skip for quick-flow)
    if track != 'quick-flow':
        if not is_complete(workflow_status, 'phase_3', 'architecture'):
            return {
                'phase': 3,
                'agent': 'architect',
                'workflow': 'create-architecture',
                'context': {},
                'status': 'pending'
            }
        
        if not is_complete(workflow_status, 'phase_3', 'epics'):
            return {
                'phase': 3,
                'agent': 'pm',
                'workflow': 'create-epics-and-stories',
                'context': {},
                'status': 'pending'
            }
        
        if not is_complete(workflow_status, 'phase_3', 'readiness'):
            return {
                'phase': 3,
                'agent': 'architect',  # or dedicated gate agent
                'workflow': 'implementation-readiness',
                'context': {},
                'status': 'pending'
            }
    
    # Phase 4: Implementation
    sprint_status = load_yaml(f"{project_path}/docs/sprint-status.yaml")
    
    if not sprint_status or not sprint_status.get('initialized'):
        return {
            'phase': 4,
            'agent': 'scrum-master',
            'workflow': 'sprint-planning',
            'context': {},
            'status': 'pending'
        }
    
    next_story = find_next_incomplete_story(sprint_status)
    if next_story:
        return {
            'phase': 4,
            'agent': 'dev',
            'workflow': 'dev-story',
            'context': {
                'epic_id': next_story['epic_id'],
                'story_id': next_story['story_id'],
                'story_file': next_story['file_path']
            },
            'status': 'pending'
        }
    
    # All complete
    return {'status': 'complete'}


def find_next_incomplete_story(sprint_status):
    """
    Iterates through epics and stories to find the next one to work on.
    
    Story states: not_started → in_progress → review → done
    """
    for epic in sprint_status.get('epics', []):
        for story in epic.get('stories', []):
            if story.get('state') not in ['done', 'review']:
                return {
                    'epic_id': epic['id'],
                    'story_id': story['id'],
                    'file_path': story.get('file'),
                    'state': story.get('state', 'not_started')
                }
    return None

Integration Options

Option A: Claude Code Custom Command

Create a custom slash command that:

  1. Calls the orchestrator logic
  2. Displays current status and recommended next step
  3. On confirmation, loads the appropriate agent and runs the workflow
User: /continue
Orchestrator: 
  Current: Phase 2 - Planning
  Status: PRD not started
  Next: Run 'prd' workflow with PM agent
  
  Continue? (y/n)
  
User: y
[Loads PM agent, executes *prd workflow]
Option B: MCP Tool

Expose as an MCP tool that can be called from any Claude interface:

  • bmad_status() - Returns current state
  • bmad_next() - Returns next step recommendation
  • bmad_continue() - Executes next step (with confirmation)
Option C: Wrapper Script (Simplest)

A script that outputs the next command to run:

$ ./bmad-next
Next step: Load PM agent, run *prd
Command: claude-code --agent pm --workflow prd

Implementation Considerations

Devcontainer Integration

When implementing, consider how this integrates with the existing devcontainer setup:

  • The orchestrator should work within the devcontainer environment
  • Access to project files (status yamls, story files) should use container paths
  • May want to expose orchestrator as a service or CLI tool within the container

State File Locations

Default BMAD v6 structure:

project/
├── bmad/
│   ├── config.yaml
│   └── _cfg/
│       └── agents/
├── docs/
│   ├── bmm-workflow-status.yaml  ← Primary state
│   ├── sprint-status.yaml         ← Implementation state
│   ├── prd.md
│   ├── architecture.md
│   └── stories/
│       ├── epic-1/
│       │   ├── story-1.md
│       │   └── story-2.md
│       └── epic-2/
│           └── ...

Error Handling

  • If status files don't exist, prompt to run workflow-init
  • If status is corrupted, provide recovery guidance
  • If a workflow fails mid-execution, state should remain at current step (not advance)

Human-in-the-Loop Gates

Preserve BMAD's existing approval gates:

  • PRD review before architecture
  • Architecture review before epic creation
  • Story review before marking complete

The orchestrator should recognize these gates and prompt for human confirmation before advancing.


Success Criteria

The implementation is successful when:

  1. Single command shows current state and next step
  2. Automatic progression (with confirmation) through the workflow
  3. No memorization required - system always knows what's next
  4. Preserves BMAD methodology - doesn't bypass steps or gates
  5. Works in existing devcontainer environment
  6. Minimal maintenance - tracks BMAD state files as source of truth

Next Steps for Implementation

  1. Review existing codebase - Understand devcontainer setup, existing Claude integration scripts
  2. Locate/create BMAD status files - Ensure we have examples to work with
  3. Implement core logic - The get_next_step() function
  4. Choose integration point - Claude Code command, MCP tool, or wrapper script
  5. Test with real project - Run through a full workflow cycle
  6. Iterate - Add edge case handling based on real usage

Appendix: BMAD Resources


Document Metadata

  • Created: December 2024
  • Purpose: Implementation brief for BMAD workflow orchestration
  • Context: To be loaded into Claude instance with repository access
  • Action: Implement thin orchestration layer based on this specification

Hooks 1

Sponsors

Details

Marketplace
zookanalytics/claude-devcontainer
Source
packages/bmad-orchestrator
Category
Community

More from zookanalytics/claude-devcontainer

All 3