# Grid Blueprint Generator

**Version:** 1.0
**Status:** Implementation Guide
**Last Updated:** 2026-01-24

---

## Overview

This document describes how the Blueprint visualization system works:
1. How Planner outputs blueprint data in plan YAML
2. How MC calls the generator before execution
3. Mermaid and ASCII template specifications

---

## Planner Blueprint Output

### Plan YAML Structure

When Planner creates an execution plan, it MUST include a `blueprint` section in the YAML frontmatter. This enables visualization before execution begins.

```yaml
---
# Standard plan metadata
cluster: "my-project"
mission: "Build REST API with Auth"
mode: "AUTOPILOT"
complexity: "MEDIUM"
created_at: "2026-01-24T15:30:00Z"

# Blueprint data for visualization
blueprint:
  version: "1.0"
  layout:
    direction: "TB"  # TB (top-bottom) or LR (left-right)
    spacing:
      horizontal: 200
      vertical: 100
    node_width: 180
    node_height: 80

  # All nodes in the mission topology
  nodes:
    # Master Control (always present)
    - id: "mc"
      type: "master_control"
      label: "MASTER CONTROL"
      sublabel: "Orchestration"
      status: "pending"

    # Phases
    - id: "phase-01"
      type: "phase_coordinator"
      label: "PHASE 01"
      sublabel: "Foundation"
      parent_id: "mc"
      status: "pending"
      metadata:
        wave: 1

    # Blocks (task groups)
    - id: "block-01"
      type: "task_group"
      label: "BLOCK 01"
      sublabel: "Database Setup"
      parent_id: "phase-01"
      status: "pending"
      metadata:
        wave: 1
        autonomous: true
        files_modified:
          - "prisma/schema.prisma"
          - "src/lib/db.ts"

    # Agents
    - id: "exec-01"
      type: "agent"
      label: "EXECUTOR"
      sublabel: "Block 01"
      parent_id: "block-01"
      status: "pending"
      metadata:
        agent_type: "executor"

    - id: "recog-01"
      type: "agent"
      label: "RECOGNIZER"
      sublabel: "Verification"
      parent_id: "block-01"
      status: "pending"
      metadata:
        agent_type: "recognizer"

    # Checkpoints (if any)
    - id: "checkpoint-01"
      type: "checkpoint"
      label: "VERIFY"
      sublabel: "Human Check"
      parent_id: "block-02"
      status: "pending"
      metadata:
        checkpoint_type: "human-verify"

  # Edges (connections)
  edges:
    - source: "mc"
      target: "phase-01"
      type: "control_flow"

    - source: "phase-01"
      target: "block-01"
      type: "control_flow"

    - source: "block-01"
      target: "exec-01"
      type: "data_flow"
      label: "PLAN"
      data_type: "plan"

    - source: "exec-01"
      target: "recog-01"
      type: "verification"
      label: "SUMMARY"
      data_type: "summary"

    - source: "block-01"
      target: "block-02"
      type: "dependency"

# Rest of plan content...
phases:
  - name: "Foundation"
    blocks:
      # ... block definitions
---
```

### Node Types

| Type | Description | Visual Style |
|------|-------------|--------------|
| `master_control` | The MC orchestrator | Thick cyan border, special header |
| `phase_coordinator` | Phase grouping | Dashed border |
| `task_group` | Block of tasks | Standard green border |
| `agent` | Executor, Recognizer, Scout | Thin border, agent icon |
| `checkpoint` | Human intervention point | Orange dotted border |
| `data_store` | Files, databases | Data icon |

### Edge Types

| Type | Description | Visual Style |
|------|-------------|--------------|
| `control_flow` | Execution sequence | Solid arrow |
| `data_flow` | Data transfer | Solid with label |
| `dependency` | Must complete before | Dashed arrow |
| `verification` | Recognizer check | Double arrow |

### Status Values

| Status | Icon (ASCII) | Icon (Unicode) | Meaning |
|--------|--------------|----------------|---------|
| `pending` | `.` | `◌` | Not started |
| `running` | `o` | `◉` | In progress |
| `complete` | `*` | `●` | Finished |
| `failed` | `x` | `✕` | Error |

---

## MC Integration

### Calling the Generator

Master Control calls the blueprint generator before spawning any agents:

```python
# In MC execution flow
import subprocess
import json

def render_blueprint_before_execution(plan_path: str):
    """Render blueprint visualization before execution begins."""

    # 1. Generate visualizations
    result = subprocess.run([
        "python3",
        "~/.claude/tools/generate_blueprint.py",
        plan_path,
        "--output-dir", ".grid/",
        "--format", "both"  # mermaid and ascii
    ], capture_output=True, text=True)

    if result.returncode != 0:
        print(f"[MC] Blueprint generation failed: {result.stderr}")
        return

    # 2. Display ASCII to terminal
    with open(".grid/blueprint.txt", "r") as f:
        print(f.read())

    # 3. Save mermaid for documentation
    # .grid/blueprint.mmd is ready for rendering

    print("[MC] Blueprint rendered. Beginning execution...")
```

### Output Files

The generator creates:

| File | Purpose |
|------|---------|
| `.grid/blueprint.txt` | ASCII diagram for terminal display |
| `.grid/blueprint.mmd` | Mermaid diagram for rendering |
| `.grid/blueprint.json` | Parsed blueprint data (for React Flow) |

---

## Mermaid Template

### Structure

```mermaid
%%{init: {'theme': 'dark', 'themeVariables': { 'primaryColor': '#00ff88', 'primaryBorderColor': '#00ff88', 'primaryTextColor': '#e0e0e0', 'lineColor': '#00ff88', 'secondaryColor': '#102030', 'tertiaryColor': '#0a1628'}}}%%

flowchart TB

%% Styling Classes
classDef mc fill:#102030,stroke:#00ccff,stroke-width:3px,color:#e0e0e0
classDef phase fill:#0a1628,stroke:#00ff88,stroke-width:2px,stroke-dasharray:5 5,color:#e0e0e0
classDef block fill:#0a1628,stroke:#00ff88,stroke-width:2px,color:#e0e0e0
classDef agent fill:#0a1628,stroke:#00ff88,stroke-width:1px,color:#e0e0e0
classDef checkpoint fill:#0a1628,stroke:#ff6600,stroke-width:2px,stroke-dasharray:3 3,color:#e0e0e0
classDef pending opacity:0.5
classDef running stroke-width:3px
classDef complete fill:#102030
classDef failed stroke:#ff3366

%% Master Control
MC["MASTER CONTROL<br/>Orchestration"]

%% Phase 1 Subgraph
subgraph phase01["PHASE 01: Foundation"]
direction TB

    %% Block 1 Subgraph
    subgraph block01["BLOCK 01: Database Setup"]
    exec01["EXECUTOR"]
    recog01["RECOGNIZER"]
    end

    %% Block 2 Subgraph
    subgraph block02["BLOCK 02: Auth Setup"]
    exec02["EXECUTOR"]
    recog02["RECOGNIZER"]
    end

end

%% Phase 2 Subgraph
subgraph phase02["PHASE 02: Features"]
direction TB

    subgraph block03["BLOCK 03: API Routes"]
    exec03["EXECUTOR"]
    recog03["RECOGNIZER"]
    end

end

%% Edges
MC --> phase01
phase01 --> block01
phase01 --> block02
block01 --> exec01
exec01 -->|SUMMARY| recog01
block02 --> exec02
exec02 -->|SUMMARY| recog02
phase01 -.->|depends| phase02
phase02 --> block03
block03 --> exec03
exec03 -->|SUMMARY| recog03

%% Apply Classes
class MC mc
class phase01,phase02 phase
class block01,block02,block03 block
class exec01,exec02,exec03,recog01,recog02,recog03 agent
```

### Template Variables

The generator replaces these placeholders:

| Variable | Description |
|----------|-------------|
| `{mission_name}` | Mission title |
| `{mode}` | AUTOPILOT, GUIDED, HANDS_ON |
| `{complexity}` | TRIVIAL to MASSIVE |
| `{phase_subgraphs}` | Generated phase blocks |
| `{edges}` | Generated edge definitions |
| `{class_assignments}` | Node class assignments |

---

## ASCII Template

### Structure

```
+========================================================================+
|                          GRID BLUEPRINT                                 |
|                       {mission_name}                                    |
|               Mode: {mode} | Complexity: {complexity}                   |
+========================================================================+
|                                                                         |
|                      +----------------------+                           |
|                      |   MASTER CONTROL     |                           |
|                      |    Orchestration     |                           |
|                      +----------+-----------+                           |
|                                 |                                       |
|         +-------------------+---+---+-------------------+               |
|         |                   |       |                   |               |
|         v                   v       v                   v               |
|  +-------------+     +-------------+     +-------------+                |
|  | PHASE 01    |     | PHASE 02    |     | PHASE 03    |                |
|  | Foundation  |     | Features    |     | Polish      |                |
|  +------+------+     +------+------+     +------+------+                |
|         |                   |                   |                       |
|  +------+------+     +------+------+     +------+------+                |
|  |* BLOCK 01   |     |. BLOCK 03   |     |. BLOCK 05   |                |
|  |  Database   |     |  API Routes |     |  Testing    |                |
|  | * EXECUTOR  |     | . EXECUTOR  |     | . EXECUTOR  |                |
|  | * RECOGNIZER|     | . RECOGNIZER|     | . RECOGNIZER|                |
|  +-------------+     +-------------+     +-------------+                |
|  |o BLOCK 02   |     |. BLOCK 04   |     +-------------+                |
|  |  Auth Setup |     |  Frontend   |                                    |
|  | o EXECUTOR  |     | . EXECUTOR  |                                    |
|  | . RECOGNIZER|     | . RECOGNIZER|                                    |
|  +-------------+     +-------------+                                    |
|                                                                         |
+=========================================================================+
| Progress: [########........................] 25%                        |
| Blocks: 2/8 complete | Agents: 4/16 | Est: 45min remaining              |
+=========================================================================+
| Legend:  . Pending   o Running   * Complete   x Failed                  |
| Agents:  # Executor  v Recognizer  @ Scout  ^ Planner                   |
+=========================================================================+
```

### Box Drawing Characters

For proper terminal rendering:

```
Corners:    + (ASCII) or ┌ ┐ └ ┘ (Unicode)
Horizontal: - (ASCII) or ─ (Unicode)
Vertical:   | (ASCII) or │ (Unicode)
T-joints:   + (ASCII) or ├ ┤ ┬ ┴ (Unicode)
Cross:      + (ASCII) or ┼ (Unicode)
Heavy:      = (ASCII) or ═ (Unicode)
```

### Status Icons

```python
STATUS_ICONS = {
    "pending":  {"ascii": ".", "unicode": "◌"},
    "running":  {"ascii": "o", "unicode": "◉"},
    "complete": {"ascii": "*", "unicode": "●"},
    "failed":   {"ascii": "x", "unicode": "✕"},
}

AGENT_ICONS = {
    "executor":   {"ascii": "#", "unicode": "⚡"},
    "recognizer": {"ascii": "v", "unicode": "✓"},
    "scout":      {"ascii": "@", "unicode": "★"},
    "planner":    {"ascii": "^", "unicode": "≡"},
}
```

---

## Usage Examples

### Command Line

```bash
# Generate both formats
python3 ~/.claude/tools/generate_blueprint.py plan.yaml

# Generate only ASCII
python3 ~/.claude/tools/generate_blueprint.py plan.yaml --format ascii

# Generate only Mermaid
python3 ~/.claude/tools/generate_blueprint.py plan.yaml --format mermaid

# Specify output directory
python3 ~/.claude/tools/generate_blueprint.py plan.yaml --output-dir .grid/

# Use Unicode characters (default is ASCII)
python3 ~/.claude/tools/generate_blueprint.py plan.yaml --unicode
```

### Programmatic

```python
from generate_blueprint import BlueprintGenerator

# Load plan
with open("plan.yaml", "r") as f:
    plan_data = yaml.safe_load(f)

# Generate
generator = BlueprintGenerator(plan_data)

# Get ASCII
ascii_diagram = generator.generate_ascii(use_unicode=True)
print(ascii_diagram)

# Get Mermaid
mermaid_diagram = generator.generate_mermaid()
print(mermaid_diagram)

# Save both
generator.save_all(".grid/")
```

---

## Live Updates

### Status Change Protocol

When MC receives status updates from agents, it updates the blueprint state:

```python
def update_blueprint_status(node_id: str, new_status: str):
    """Update node status in blueprint state."""

    # 1. Load current state
    with open(".grid/blueprint.json", "r") as f:
        blueprint = json.load(f)

    # 2. Find and update node
    for node in blueprint["nodes"]:
        if node["id"] == node_id:
            node["status"] = new_status
            break

    # 3. Update connected edges
    for edge in blueprint["edges"]:
        if edge["source"] == node_id and new_status == "complete":
            edge["status"] = "complete"
        elif edge["target"] == node_id and new_status == "running":
            edge["status"] = "active"

    # 4. Save updated state
    with open(".grid/blueprint.json", "w") as f:
        json.dump(blueprint, f, indent=2)

    # 5. Re-render ASCII for terminal
    generator = BlueprintGenerator(blueprint)
    ascii_output = generator.generate_ascii()
    print("\033[2J\033[H")  # Clear screen
    print(ascii_output)
```

### Progress Calculation

```python
def calculate_progress(blueprint: dict) -> dict:
    """Calculate overall mission progress."""

    nodes = blueprint["nodes"]

    # Count by type
    blocks = [n for n in nodes if n["type"] == "task_group"]
    agents = [n for n in nodes if n["type"] == "agent"]

    # Count by status
    blocks_complete = len([b for b in blocks if b["status"] == "complete"])
    agents_complete = len([a for a in agents if a["status"] == "complete"])

    # Calculate percentage (weight blocks more)
    total_weight = len(blocks) * 2 + len(agents)
    complete_weight = blocks_complete * 2 + agents_complete
    percent = int((complete_weight / total_weight) * 100) if total_weight > 0 else 0

    return {
        "blocks_complete": blocks_complete,
        "blocks_total": len(blocks),
        "agents_complete": agents_complete,
        "agents_total": len(agents),
        "percent": percent,
    }
```

---

## File Locations

| File | Path | Purpose |
|------|------|---------|
| This doc | `~/.claude/docs/GRID_BLUEPRINT_GENERATOR.md` | Implementation guide |
| Generator | `~/.claude/tools/generate_blueprint.py` | Python script |
| Output ASCII | `.grid/blueprint.txt` | Terminal display |
| Output Mermaid | `.grid/blueprint.mmd` | Renderable diagram |
| Output JSON | `.grid/blueprint.json` | State for updates |

---

*End of Blueprint Generator Documentation*
