---
title: "Visualize Plan"
description: "Renders planned changes as ASCII visualizations with risk heat maps, execution order diagrams, dependency graphs, impact metrics, and before/after architecture comparisons. Stores visualizations in memory for cross-session reference. Use when reviewing implementation plans, comparing approaches, assessing risk, or analyzing change propagation."
---

<span className="badge badge-blue">Command</span> <span className="badge badge-yellow">medium</span>

```bash title="Invoke"
/ork:visualize-plan
```

<ContextualSkillSidebar slug="visualize-plan" />


# Plan Visualization

Render planned changes as structured ASCII visualizations with risk analysis, execution order, and impact metrics. Every section answers a specific reviewer question.

**Core principle:** Encode judgment into visualization, not decoration.

```bash
/ork:visualize-plan                          # Auto-detect from current branch
/ork:visualize-plan billing module redesign  # Describe the plan
/ork:visualize-plan #234                     # Pull from GitHub issue
```

## Argument Resolution

```python
PLAN_INPUT = "$ARGUMENTS"    # Full argument string
PLAN_TOKEN = "$ARGUMENTS[0]" # First token — could be issue "#234" or plan description
# If starts with "#", treat as GitHub issue number. Otherwise, plan description.
# $ARGUMENTS (full string) for multi-word descriptions (CC 2.1.59 indexed access)
```

---

## CRITICAL: Task Tracking

```python
# 1. Create main task IMMEDIATELY
TaskCreate(subject="Visualize plan: {PLAN_INPUT}", description="Plan visualization with ASCII rendering", activeForm="Analyzing plan context")

# 2. Create subtasks for each phase
TaskCreate(subject="Detect or clarify plan context", activeForm="Detecting plan context")          # id=2
TaskCreate(subject="Gather data and explore architecture", activeForm="Gathering plan data")       # id=3
TaskCreate(subject="Render tier 1 header", activeForm="Rendering header")                          # id=4
TaskCreate(subject="Render requested sections", activeForm="Rendering sections")                   # id=5
TaskCreate(subject="Offer actions and store in memory", activeForm="Finalizing visualization")     # id=6

# 3. Set dependencies for sequential phases
TaskUpdate(taskId="3", addBlockedBy=["2"])  # Data gathering needs context first
TaskUpdate(taskId="4", addBlockedBy=["3"])  # Header needs gathered data
TaskUpdate(taskId="5", addBlockedBy=["4"])  # Sections need header rendered
TaskUpdate(taskId="6", addBlockedBy=["5"])  # Actions need sections done

# 4. Before starting each task, verify it's unblocked
task = TaskGet(taskId="2")  # Verify blockedBy is empty

# 5. Update status as you progress
TaskUpdate(taskId="2", status="in_progress")  # When starting
TaskUpdate(taskId="2", status="completed")    # When done — repeat for each subtask
```

## STEP -1: Check Memory for Prior Plans

```python
# Search for related prior visualizations
mcp__memory__search_nodes(query="plan visualization {PLAN_INPUT}")
# If found, offer to compare with previous plan
```

## STEP 0: Detect or Clarify Plan Context

**First**, attempt auto-detection by running `scripts/detect-plan-context.sh`:

```bash
bash "$SKILL_DIR/scripts/detect-plan-context.sh"
```

This outputs branch name, issue number (if any), commit count, and file change summary.

**If auto-detection finds a clear plan** (branch with commits diverging from main, or issue number in args), proceed to Step 1.

**If ambiguous**, clarify with AskUserQuestion:

```python
AskUserQuestion(
  questions=[{
    "question": "What should I visualize?",
    "header": "Source",
    "options": [
      {"label": "Current branch changes (Recommended)", "description": "Auto-detect from git diff against main", "markdown": "```\nBranch Diff Analysis\n────────────────────\n$ git diff main...HEAD\n\n→ File change manifest (+A, M, -D)\n→ Execution swimlane by phase\n→ Risk dashboard + pre-mortems\n→ Impact summary (lines, tests, API)\n```"},
      {"label": "Describe the plan", "description": "I'll explain what I'm planning to change", "markdown": "```\nPlan Description\n────────────────\nYou describe → I visualize:\n\n→ Before/after architecture diagrams\n→ Execution order with dependencies\n→ Risk analysis per component\n→ Decision log (ADR-lite format)\n```"},
      {"label": "GitHub issue", "description": "Pull plan from a specific issue number", "markdown": "```\nGitHub Issue Source\n───────────────────\n$ gh issue view #N\n\n→ Extract requirements from body\n→ Map to file-level changes\n→ Generate execution phases\n→ Link back to issue for tracking\n```"},
      {"label": "Quick file diff only", "description": "Just show the change manifest, skip analysis", "markdown": "```\nQuick File Diff\n───────────────\n[A] src/new-file.ts        +120\n[M] src/existing.ts    +15  -8\n[D] src/old-file.ts        -45\n─────────────────────────────\nNET: +82 lines, 3 files\n\nNo risk analysis or swimlanes\n```"}
    ],
    "multiSelect": false
  }]
)
```

---

## STEP 1: Gather Data

Run `scripts/analyze-impact.sh` for precise counts:

```bash
bash "$SKILL_DIR/scripts/analyze-impact.sh"
```

This produces: files by action (add/modify/delete), line counts, test files affected, and dependency changes.

For architecture-level understanding, spawn an Explore agent on the affected directories:

```python
Agent(
  subagent_type="Explore",
  prompt="Explore the architecture of {affected_directories}. Return: component diagram, key data flows, health scores per module. Use the ascii-visualizer skill for diagrams.",
  model="haiku"
)
```

---

## STEP 2: Render Tier 1 Header (Always)

Use `assets/tier1-header.md` template. Load `Read("$\{CLAUDE_SKILL_DIR\}/references/visualization-tiers.md")` for field computation (risk level, confidence, reversibility).

```
PLAN: {plan_name} ({issue_ref})  |  {phase_count} phases  |  {file_count} files  |  +{added} -{removed} lines
Risk: {risk_level}  |  Confidence: {confidence}  |  Reversible until {last_safe_phase}
Branch: {branch} -> {base_branch}

[1] Changes  [2] Execution  [3] Risks  [4] Decisions  [5] Impact  [all]
```

---

## STEP 3: Ask Which Sections to Expand

```python
AskUserQuestion(
  questions=[{
    "question": "Which sections to render?",
    "header": "Sections",
    "options": [
      {"label": "All sections", "description": "Full visualization with all 5 core sections", "markdown": "```\n[1] Change Manifest   [A]/[M]/[D] file tree\n[2] Execution         Swimlane with phases\n[3] Risks             Dashboard + pre-mortems\n[4] Decisions         ADR-lite decision log\n[5] Impact            Lines, tests, API, deps\n```"},
      {"label": "Changes + Execution", "description": "File diff tree and execution swimlane", "markdown": "```\n[1] Change Manifest\n    [M] src/auth.ts         +45 -12\n    [A] src/oauth.ts        +89\n\n[2] Execution Swimlane\n    Phase 1 ====[auth]========▶\n    Phase 2 ----[blocked]--===▶\n```"},
      {"label": "Risks + Decisions", "description": "Risk dashboard and decision log", "markdown": "```\n[3] Risk Dashboard\n    MEDIUM ██░░ migration reversible\n    HIGH   ███░ API breaking change\n    Pre-mortem: \"What if auth fails?\"\n\n[4] Decision Log\n    D1: OAuth2 over JWT (security)\n    D2: Postgres over Redis (durability)\n```"},
      {"label": "Impact only", "description": "Just the numbers: files, lines, tests, API surface", "markdown": "```\n[5] Impact Summary\n    ┌──────────┬─────┬───────┐\n    │ Metric   │Count│ Delta │\n    ├──────────┼─────┼───────┤\n    │ Files    │  12 │  +3   │\n    │ Lines    │ 450 │ +127  │\n    │ Tests    │   8 │  +4   │\n    │ API sfc  │   3 │  +1   │\n    └──────────┴─────┴───────┘\n```"}
    ],
    "multiSelect": false
  }]
)
```

---

## STEP 4: Render Requested Sections

Render each requested section following `$\{CLAUDE_SKILL_DIR\}/rules/section-rendering.md` conventions. Use the corresponding reference for ASCII patterns:

| Section | Reference | Key Convention |
|---------|-----------|----------------|
| [1] Change Manifest | (load `$\{CLAUDE_SKILL_DIR\}/references/change-manifest-patterns.md`) | `[A]`/`[M]`/`[D]` + `+N -N` per file |
| [2] Execution Swimlane | (load `$\{CLAUDE_SKILL_DIR\}/references/execution-swimlane-patterns.md`) | `===` active, `---` blocked, `\|` deps |
| [3] Risk Dashboard | (load `$\{CLAUDE_SKILL_DIR\}/references/risk-dashboard-patterns.md`) | Reversibility timeline + 3 pre-mortems |
| [4] Decision Log | (load `$\{CLAUDE_SKILL_DIR\}/references/decision-log-patterns.md`) | ADR-lite: Context/Decision/Alternatives/Tradeoff |
| [5] Impact Summary | (load `$\{CLAUDE_SKILL_DIR\}/assets/impact-dashboard.md`) | Table: Added/Modified/Deleted/NET + tests/API/deps |

---

## STEP 5: Offer Actions

After rendering, offer next steps:

```python
AskUserQuestion(
  questions=[{
    "question": "What next?",
    "header": "Actions",
    "options": [
      {"label": "Write to designs/", "description": "Save as designs/{branch}.md for PR review", "markdown": "```\nSave to File\n────────────\ndesigns/\n  └── feat-billing-redesign.md\n      ├── Header + metadata\n      ├── All rendered sections\n      └── Ready for PR description\n```"},
      {"label": "Generate GitHub issues", "description": "Create issues from execution phases with labels and milestones", "markdown": "```\nGitHub Issues\n─────────────\n#101 [billing] Phase 1: Schema migration\n     labels: component:billing, risk:medium\n#102 [billing] Phase 2: API endpoints\n     labels: component:billing, risk:low\n     blocked-by: #101\n```"},
      {"label": "Drill deeper", "description": "Expand blast radius, cross-layer check, or migration checklist", "markdown": "```\nDeep Dive Options\n─────────────────\n[6] Blast Radius\n    direct → transitive → test impact\n[7] Cross-Layer Consistency\n    Frontend ↔ Backend endpoint gaps\n[8] Migration Checklist\n    Ordered runbook with time estimates\n```"},
      {"label": "Done", "description": "Plan visualization complete"}
    ],
    "multiSelect": false
  }]
)
```

**Write to file:** Save full report to `designs/\{branch-name\}.md` using `assets/plan-report.md` template.

**Generate issues:** For each execution phase, create a GitHub issue with title `[\{component\}] \{phase_description\}`, labels (component + `risk:\{level\}`), milestone, body from plan sections, and blocked-by references.

**Store in memory:** Save plan summary to knowledge graph for future comparison:

```python
mcp__memory__create_entities(entities=[{
  "name": "Plan: {plan_name}",
  "entityType": "plan-visualization",
  "observations": [
    "Branch: {branch}",
    "Risk: {risk_level}, Confidence: {confidence}",
    "Phases: {phase_count}, Files: {file_count}",
    "Key decisions: {decision_summary}"
  ]
}])
```

---

## Deep Dives (Tier 3, on request)

Available when user selects "Drill deeper". Load `Read("$\{CLAUDE_SKILL_DIR\}/references/deep-dives.md")` for cross-layer and migration patterns.

| Section | What It Shows | Reference |
|---------|--------------|-----------|
| [6] Blast Radius | Concentric rings of impact (direct -> transitive -> tests) | (load `$\{CLAUDE_SKILL_DIR\}/references/blast-radius-patterns.md`) |
| [7] Cross-Layer Consistency | Frontend/backend endpoint alignment with gap detection | (load `$\{CLAUDE_SKILL_DIR\}/references/deep-dives.md`) |
| [8] Migration Checklist | Ordered runbook with sequential/parallel blocks and time estimates | (load `$\{CLAUDE_SKILL_DIR\}/references/deep-dives.md`) |

---

## Key Principles

| Principle | Application |
|-----------|-------------|
| **Progressive disclosure** | Tier 1 header always, sections on request |
| **Judgment over decoration** | Every section answers a reviewer question |
| **Precise over estimated** | Use scripts for file/line counts |
| **Honest uncertainty** | Confidence levels, pre-mortems, tradeoff costs |
| **Actionable output** | Write to file, generate issues, drill deeper |
| **Anti-slop** | No generic transitions, no fake precision, no unused sections |

## Rules Quick Reference

| Rule | Impact | What It Covers |
|------|--------|----------------|
| section-rendering (load `$\{CLAUDE_SKILL_DIR\}/rules/section-rendering.md`) | HIGH | Rendering conventions for all 5 core sections |
| ASCII diagrams | MEDIUM | Via `ascii-visualizer` skill (box-drawing, file trees, workflows) |

## References

Load on demand with `Read("$\{CLAUDE_SKILL_DIR\}/references/&lt;file&gt;")`:
| File | Content |
|------|---------|
| `visualization-tiers.md` | Progressive disclosure tiers and header field computation |
| `change-manifest-patterns.md` | Change manifest ASCII patterns |
| `execution-swimlane-patterns.md` | Execution swimlane ASCII patterns |
| `risk-dashboard-patterns.md` | Risk dashboard ASCII patterns |
| `decision-log-patterns.md` | Decision log ASCII patterns |
| `blast-radius-patterns.md` | Blast radius ASCII patterns |
| `deep-dives.md` | Cross-layer consistency and migration checklist |

## Assets

Load on demand with `Read("$\{CLAUDE_SKILL_DIR\}/assets/&lt;file&gt;")`:
| File | Content |
|------|---------|
| `plan-report.md` | Full mustache-style report template |
| `impact-dashboard.md` | Impact table template |
| `tier1-header.md` | 5-line summary template |

## Related Skills

- `ork:implement` - Execute planned changes
- `ork:explore` - Understand current architecture
- `ork:assess` - Evaluate complexity and risks
- `ork:memory` - Search prior plan visualizations
- `ork:remember` - Store plan decisions for future reference


---

## Rules (1)

### Section Rendering Conventions — HIGH


# Section Rendering Conventions

Each visualize-plan section follows strict rendering rules to ensure consistency and reviewer utility.

## General Rules

1. **Every section answers ONE reviewer question** — if it doesn't answer a question, cut it
2. **Use scripts for precision** — run `analyze-impact.sh` for file/line counts, never estimate
3. **Annotations carry judgment** — `!!` for risk, `**` for new, `blocks` for dependencies
4. **Summary lines are mandatory** — every section ends with a one-line summary

**Incorrect:**
```
Files Changed:
- auth.py (modified)
- utils.py (new)
```

**Correct:**
```
[M] src/auth.py       +42 -8   !! security-critical
[A] src/utils.py      +65 -0   **new**
Summary: +107 -8 | 1 new | 1 modified | 0 deleted
```

## Section [1]: Change Manifest

- Use `[A]`/`[M]`/`[D]` prefix symbols (Terraform convention)
- Show `+N -N` line counts per file
- Flag high-risk files with `!!` and annotation
- Mark new files with `**`
- Always end with a summary line: `Summary: +N -N | X new | Y modified | Z deleted`

## Section [2]: Execution Swimlane

- `===` for active work, `---` for blocked/waiting
- Vertical `|` for dependencies with `blocks` annotations
- Identify and label the critical path
- Show parallel opportunities explicitly

## Section [3]: Risk Dashboard

- Part A: Reversibility timeline with `[====]` bars
- Always identify the point of no return with `--- POINT OF NO RETURN ---`
- Part B: Exactly 3 pre-mortem scenarios (most likely, most severe, most subtle)
- Each scenario needs a concrete mitigation, not generic advice

## Section [4]: Decision Log

- ADR-lite format: Context, Decision, Alternatives, Tradeoff
- Only document non-obvious decisions (skip "we need a database table")
- Always show at least one rejected alternative
- Tradeoffs must be honest — show the cost, not just the benefit

## Section [5]: Impact Summary

- Table format with Categories (Added, Modified, Deleted, NET)
- Include: Tests coverage delta, API surface changes, dependency changes
- Use `assets/impact-dashboard.md` template



---

## References (7)

### Blast Radius Patterns

# Blast Radius Patterns

Visualize the transitive impact of planned changes.

## Concentric Rings

The changed file at center, expanding rings for each degree of dependency:

```
                         Ring 3: Tests (8 files)
                    +-------------------------------+
                    |      Ring 2: Transitive (5)    |
                    |   +------------------------+   |
                    |   |   Ring 1: Direct (3)    |   |
                    |   |   +--------------+      |   |
                    |   |   | CHANGED FILE |      |   |
                    |   |   +--------------+      |   |
                    |   +------------------------+   |
                    +-------------------------------+

Ring 1 (direct):     auth.py, routes.py, middleware.py
Ring 2 (transitive): app.py, config.py, utils.py, cli.py, server.py
Ring 3 (tests):      test_auth.py, test_routes.py, ... (+6 more)
```

## Multi-File Blast Radius

When multiple files change, show overlapping impact:

```
BLAST RADIUS: 3 changed files

memory-writer.ts ─── Ring 1: 5 files ─── Ring 2: 12 files ─── Ring 3: 8 tests
                          |                    |
memory-health.ts ─── Ring 1: 3 files ────+    |
                          |               |    |
queue-processor.ts ── Ring 1: 2 files ──+─+───+

Overlap: 4 files appear in multiple blast radii
Unique impact: 18 files total (not 25 — overlap deduplicated)
```

## Fan-In / Fan-Out Analysis

```
Fan-In (what depends on changed files)    Fan-Out (what changed files depend on)
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━        ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
memory-writer.ts  [========] 8            graph-client     [======] 6
memory-health.ts  [====] 4                cc-native-writer [====] 4
queue-processor.ts [==] 2                 logger           [==] 2
decision-history.ts [===] 3              config            [=] 1

High fan-in = higher risk (more things break if this file breaks)
High fan-out = higher complexity (more things to understand)
```

## Dependency Tree (Detailed)

```
BLAST RADIUS: memory-writer.ts

memory-writer.ts (CHANGED)
├── stop/auto-remember-continuity.ts     (direct dependent)
│   ├── stop/unified-dispatcher.ts       (transitive)
│   │   └── hooks.json                   (config entry)
│   └── stop/session-patterns.ts         (transitive)
├── stop/session-profile-aggregator.ts   (direct dependent)
├── subagent-stop/unified-dispatcher.ts  (direct dependent)
├── skill/decision-processor.ts          (direct dependent)
│   └── skill/unified-dispatcher.ts      (transitive)
└── lifecycle/pre-compact-saver.ts       (direct dependent)

Direct: 5 files  |  Transitive: 3 files  |  Total: 8 files
```

## Impact by Layer

For full-stack changes, show blast radius per layer:

```
BLAST RADIUS BY LAYER

API Layer:
  Changed: routes.py, schemas.py
  Impact:  middleware.py, auth.py (2 dependents)
  Tests:   test_routes.py, test_auth.py (2 test files)

Service Layer:
  Changed: billing.py (new)
  Impact:  None (new file, no dependents yet)
  Tests:   test_billing.py (new, paired)

Model Layer:
  Changed: invoice.py (new)
  Impact:  billing.py depends on it (1 dependent)
  Tests:   test_models.py needs update (1 test file)

Frontend:
  Changed: InvoiceList.tsx, InvoiceDetail.tsx (new)
  Impact:  App.tsx (routing), Sidebar.tsx (navigation)
  Tests:   InvoiceList.test.tsx (new, paired)

Cross-Layer Dependencies:
  Frontend -> API: 2 new fetch calls (POST /invoices, GET /invoices)
  API -> Model: 1 new import (InvoiceModel)
```

## Compact Blast Radius (small changes)

```
BLAST RADIUS: routes.py -> 3 direct, 5 transitive, 4 tests = 12 files
```


### Change Manifest Patterns

# Change Manifest Patterns

Terraform-style annotated file trees for visualizing planned changes.

## Symbol Convention

Borrowed from Terraform plan output for universal recognition:

```
[A]  Add       — New file being created
[M]  Modify    — Existing file being changed
[D]  Delete    — File being removed
[R]  Rename    — File being moved/renamed
[S]  Simplify  — File being reduced (lines removed, logic simplified)
```

## Annotation Convention

```
!!   Risk flag     — High-traffic path, complex logic, or fragile code
**   New file      — Freshly created, no existing behavior to break
~~   Deprecated    — Being replaced by another file
->   Moves to      — Content relocating to a different path
```

## Basic Change Tree

```
src/
├── api/
│   ├── routes.py          [M] +45 -12
│   └── schemas.py         [M] +20 -5
├── services/
│   └── billing.py         [A] +180       ** new file
├── models/
│   └── invoice.py         [A] +95        ** new file
└── tests/
    └── test_billing.py    [A] +120       ** new file

Legend: [A]dd [M]odify [D]elete  !! Risk  ** New
Summary: +460 -17  |  3 new  |  2 modified  |  0 deleted
```

## Annotated Change Tree (with risk flags)

```
src/
├── hooks/
│   ├── lifecycle/
│   │   ├── mem0-context-retrieval.ts   [D] -245    ~~ replaced by graph
│   │   ├── mem0-analytics-tracker.ts   [D] -180    ~~ no replacement needed
│   │   └── pre-compact-saver.ts        [S] -40     remove mem0 fallback
│   ├── stop/
│   │   ├── mem0-queue-sync.ts          [D] -320    ~~ queue system removed
│   │   └── auto-remember-continuity.ts [S] -25     !! touches session persistence
│   ├── lib/
│   │   ├── memory-writer.ts            [S] -350    !! core write path
│   │   ├── queue-processor.ts          [D] -280    ~~ queue system removed
│   │   └── memory-health.ts            [S] -60     remove mem0 health checks
│   └── setup/
│       ├── mem0-backup-setup.ts        [D] -150
│       ├── mem0-cleanup.ts             [D] -120
│       └── mem0-analytics-dashboard.ts [D] -200
├── skills/
│   ├── mem0-memory/                    [D] -4500   ~~ entire skill removed
│   ├── memory-fabric/SKILL.md          [S] -80     remove mem0 paths
│   └── remember/SKILL.md              [S] -45     remove --mem0 flag
└── tests/
    └── mem0/                           [D] -3200   ~~ 20 test files removed

Legend: [A]dd [M]odify [D]elete [S]implify  !! Risk  ** New  ~~ Deprecated
Summary: +0 -9,795  |  0 new  |  4 simplified  |  30 deleted
```

## Grouped by Action

For large changesets, group by action type:

```
DELETIONS (30 files, -9,195 lines):
  src/skills/mem0-memory/         [D] 42 files  -4,500 lines
  tests/mem0/                     [D] 20 files  -3,200 lines
  src/hooks/src/lifecycle/mem0-*  [D]  2 files    -425 lines
  src/hooks/src/stop/mem0-*       [D]  2 files    -520 lines
  src/hooks/src/setup/mem0-*      [D]  3 files    -470 lines
  bin/mem0-*.py                   [D]  2 files     -80 lines

SIMPLIFICATIONS (4 files, -600 lines):
  src/hooks/src/lib/memory-writer.ts    [S] -350 lines  !! core write path
  src/skills/memory-fabric/SKILL.md     [S]  -80 lines
  src/skills/remember/SKILL.md          [S]  -45 lines
  src/hooks/src/lib/memory-health.ts    [S]  -60 lines
  src/hooks/src/stop/auto-remember.ts   [S]  -25 lines  !! session persistence

NO CHANGES (185 files):
  All other skills, agents, hooks unchanged
```

## Compact Format (for small changes)

```
CHANGES: 3 files (+85 -12)
  [M] src/api/routes.py      +45 -12  !! hot path
  [A] src/api/schemas.py     +20
  [A] tests/test_routes.py   +20
```


### Decision Log Patterns

# Decision Log Patterns

ADR-lite format for documenting non-obvious choices in a plan.

## When to Document a Decision

Document when ANY of these apply:
- Multiple valid approaches exist and one was chosen over others
- The choice has a meaningful tradeoff (something is gained AND lost)
- Future developers would ask "why was it done this way?"
- The decision constrains future options

Do NOT document:
- Obvious choices ("we need a table for invoices")
- Implementation details ("use for loop vs map")
- Forced choices (only one option exists)

## Standard Decision Entry

```
#1: Use graph-only memory instead of dual-write
    Context:      Current system writes to 3 tiers (graph + .jsonl + mem0 cloud).
                  Only graph tier is used by 98% of queries.
    Decision:     Remove .jsonl and mem0 cloud tiers. Write only to graph + CC native.
    Alternatives: [a] Keep mem0 as optional   -> still 14K lines of code to maintain
                  [b] Abstract behind interface -> over-engineering for 2% usage
    Tradeoff:     + 14K lines removed, 39 Python scripts gone, zero external deps
                  - Lose cloud semantic search (affects cross-session pattern matching)
    Confidence:   HIGH (usage data confirms <2% mem0 queries)
```

## Compact Decision Entry

For plans with many small decisions:

```
DECISIONS

#1  Graph-only memory (not dual-write)
    + 14K lines removed  - lose cloud search  | Confidence: HIGH

#2  Delete queue processor (not simplify)
    + no background jobs  - no retry on write failure  | Confidence: HIGH

#3  Keep decision-flow-tracker (not delete)
    + behavioral intelligence preserved  - 200 lines to maintain  | Confidence: MEDIUM
```

## Decision with Alternatives Matrix

When comparing 3+ options:

```
DECISION: Memory write strategy

+=================+===========+==========+========+==========+
| Option          | Lines     | Ext Deps | Speed  | Coverage |
+=================+===========+==========+========+==========+
| Graph-only  [X] | -14,100   | 0        | Fast   | 98%      |
| Dual-write      | -0        | 1 (mem0) | Medium | 100%     |
| Abstract layer  | +500      | 0        | Medium | 100%     |
+-----------------+-----------+----------+--------+----------+

[X] = Selected option
Rationale: 14K line reduction outweighs 2% coverage gap.
           Cloud search can be re-added later if needed (additive change).
```

## Decision Chain (dependent decisions)

When one decision forces subsequent decisions:

```
DECISION CHAIN

#1  Remove mem0 cloud tier
    |
    +-> #2  Delete 39 Python scripts (no longer needed)
    |
    +-> #3  Delete queue processor (only existed for mem0 retry)
    |
    +-> #4  Simplify memory-writer.ts (remove 3-tier fallback)
    |
    +-> #5  Remove MEM0_API_KEY from CI/CD (no longer used)

Root decision: #1
Cascade: 4 follow-on decisions, all lower risk than root
```

## Reversible vs Irreversible Decisions

Flag decisions by how hard they are to undo:

```
DECISION LOG

#1  [REVERSIBLE]   Use PostgreSQL for billing data
    Can migrate to another DB later. Schema is the contract, not the engine.

#2  [REVERSIBLE]   REST over GraphQL for billing API
    Can add GraphQL layer later without changing REST endpoints.

#3  [IRREVERSIBLE] Store amounts in cents (integer) not dollars (float)
    All downstream systems will depend on integer representation.
    Changing later requires data migration across all consumers.
```


### Deep Dive Patterns (Tier 3)


# Deep Dive Patterns

These are Tier 3 sections rendered only on explicit request after the core 5 sections.

## [7] Cross-Layer Consistency

Verify frontend/backend alignment by mapping endpoints to consumers:

```
CROSS-LAYER CONSISTENCY
Backend Endpoint          Frontend Consumer     Status
POST /invoices            createInvoice()       PLANNED
GET  /invoices/:id        useInvoice(id)        PLANNED
GET  /invoices            InvoiceList.tsx        MISSING  !!
```

### Rules
- List every backend endpoint the plan introduces or modifies
- Map each to its frontend consumer (component, hook, or API call)
- Flag `MISSING !!` for any unmatched endpoint — these are gaps in the plan
- Flag `ORPHANED !!` for frontend consumers calling endpoints not in the plan
- Include status: EXISTING, PLANNED, MISSING, ORPHANED

## [8] Migration Checklist

Generate an ordered runbook with explicit dependency constraints and time estimates:

```
MIGRATION CHECKLIST

Sequential Block A (database):
  1. [ ] Backup production database                    [~5 min]
  2. [ ] Run migration: 001_add_invoices.sql           [~30s]   <- blocks #4

Parallel Block B (after #2):
  3. [ ] Deploy API v2.1.0                             [~3 min]
  4. [ ] Update frontend bundle                        [~2 min]

Sequential Block C (verification):
  5. [ ] Smoke test                                    [~2 min]
  6. [ ] Monitor error rate 15 min                     [~15 min]
```

### Rules
- Group steps into sequential and parallel blocks
- Show `&lt;- blocks #N` for dependency constraints
- Include time estimates for each step
- Always start with a backup step for data-touching migrations
- Always end with verification (smoke test + monitoring)
- Use checkbox format `[ ]` for runbook usability


### Execution Swimlane Patterns

# Execution Swimlane Patterns

Temporal dependency diagrams showing parallel/sequential execution.

## Symbol Convention

```
===  Active work (this lane is executing)
---  Blocked / waiting for a dependency
|    Dependency line (vertical)
+    Junction (dependency meets lane)
>    Flow direction (lane endpoint)
[N]  Phase reference number
```

## Basic Swimlane (2 lanes)

```
Backend  ===[1: Schema]==[2: API]========================[4: Deploy]===>
                |            |                                ^
                |            +--------blocks---------+        |
                |                                    |        |
Frontend ------[Wait]--------[3: Components]=========[5: Integrate]+

=== Active   --- Waiting   | Dependency
Critical path: 1 -> 2 -> 4 (backend-bound)
```

## Multi-Lane Swimlane (3+ lanes)

```
Database ===[1: Migrate]=====================================>
                  |
                  +---blocks---+---blocks---+
                  |            |            |
Backend  --------[Wait]------[2: API]=====[4: Deploy]=======>
                               |               ^
                               +--blocks--+    |
                               |          |    |
Frontend --------[Wait]------[Wait]-----[3: UI]==[5: Int.]==>
                                                      |
Tests    --------[Wait]------[Wait]-----[Wait]---[6: E2E]===>

=== Active   --- Waiting   | Dependency
Critical path: 1 -> 2 -> 3 -> 5 (longest chain)
Parallel opportunity: Backend deploy (4) can run alongside Frontend UI (3)
```

## Phase Detail Blocks

Expand key phases with sub-steps:

```
Phase 2: API Endpoints [estimated: 2-3 hours]
+--------------------------------------------------+
| 2a. Define Pydantic schemas (InvoiceCreate, etc.) |
| 2b. Implement CRUD routes                         |
| 2c. Add auth middleware to new routes              |
| 2d. Write route tests                             |
+--------------------------------------------------+
  Blocks: Phase 3 (UI needs API contract)
  Blocked by: Phase 1 (needs DB tables)
```

## With Time Estimates

```
Timeline (estimated):
0h        1h        2h        3h        4h        5h        6h
|---------|---------|---------|---------|---------|---------|
Database  [##1##]
Backend            [####2####]          [##4##]
Frontend                      [####3####][##5##]
Tests                                          [##6##]
          ▲                                           ▲
          Start                                       Done

Estimated total: 6 hours (3.5h critical path + 2.5h parallel)
Without parallelism: 9.5 hours
Time saved by parallel execution: ~37%
```

## Dependency Graph (DAG style)

For complex dependency chains, use a directed acyclic graph:

```
EXECUTION ORDER (DAG)

    [1: Schema]
        |
    +---+---+
    |       |
[2: API] [3: Indexes]
    |       |
    +---+---+
        |
    [4: Deploy API]
        |
    +---+---+
    |       |
[5: UI]  [6: Cache]
    |       |
    +---+---+
        |
    [7: Integration]
        |
    [8: E2E Tests]

Parallelizable pairs: (2,3), (5,6)
Serial bottleneck: 4 (both UI and cache depend on API deploy)
```

## Conditional Execution

When phases have success/failure branches:

```
[1: Migrate] --success--> [2: API] --success--> [3: Deploy]
      |                      |
      +--failure-->          +--failure-->
      |                      |
[1R: Rollback DB]      [2R: Revert API]
      |                      |
      +-----> [ABORT] <------+
```


### Risk Dashboard Patterns

# Risk Dashboard Patterns

Reversibility timelines and pre-mortem scenarios.

## Reversibility Timeline

Shows each phase's undo capability. The point of no return is the most important signal.

### Standard Format

```
REVERSIBILITY TIMELINE

Phase 1  [================]  FULLY REVERSIBLE    (add column, nullable)
Phase 2  [================]  FULLY REVERSIBLE    (new endpoint, additive)
Phase 3  [============....]  PARTIALLY           (backfill data, can truncate)
              --- POINT OF NO RETURN ---
Phase 4  [........????????]  IRREVERSIBLE        (drop old column, data lost)
Phase 5  [================]  FULLY REVERSIBLE    (frontend toggle via flag)

Recommendation: Add backup step before Phase 4
```

### Fill Pattern Legend

```
[================]  FULLY REVERSIBLE    — Can undo completely, no data loss
[============....]  PARTIALLY           — Can undo, but some manual cleanup needed
[========........]  DIFFICULT           — Requires backup restore or significant effort
[....????????????]  IRREVERSIBLE        — Cannot undo, data permanently changed
```

### Compact Format (for simple plans)

```
Reversibility: Phase 1 [SAFE] -> Phase 2 [SAFE] -> Phase 3 [PARTIAL] -> Phase 4 [IRREVERSIBLE]
                                                                          ^
                                                               Point of no return
```

### With Rollback Instructions

```
REVERSIBILITY + ROLLBACK

Phase 1: Add users.billing_address column
  Reversibility: FULL
  Rollback: ALTER TABLE users DROP COLUMN billing_address;
  Time: <1 min  |  Data loss: NONE

Phase 2: Deploy billing API endpoints
  Reversibility: FULL
  Rollback: Revert deployment to previous version
  Time: ~3 min  |  Data loss: NONE

Phase 3: Backfill billing_address from legacy table
  Reversibility: PARTIAL
  Rollback: UPDATE users SET billing_address = NULL WHERE ...;
  Time: ~10 min  |  Data loss: backfilled data only

Phase 4: Drop legacy_billing table
  Reversibility: NONE
  Rollback: Restore from backup (Phase 0 snapshot required)
  Time: ~30 min  |  Data loss: ALL legacy billing if no backup
```

## Pre-Mortem Scenarios

Frame risks as "what already went wrong" narratives. More memorable than probability tables.

### Standard Format (3 scenarios)

```
PRE-MORTEM: This plan failed because...

1. MOST LIKELY: Cache served stale prices after Stripe webhook
   Probability: HIGH  |  Impact: HIGH
   Mitigation: Add cache invalidation hook on webhook receipt
   Rollback: Clear Redis cache (30s recovery)
   Detection: Monitor cache hit rate, alert on stale-age > 60s

2. MOST SEVERE: Migration ran on replica before primary
   Probability: LOW  |  Impact: CRITICAL
   Mitigation: Run migration with explicit --primary flag, verify replication lag
   Rollback: Cannot cleanly roll back (need full backup restore)
   Detection: Check pg_stat_replication before and after

3. MOST SUBTLE: Frontend shows billing tab to free-tier users
   Probability: MEDIUM  |  Impact: MEDIUM
   Mitigation: Add feature flag check in BillingTab component
   Rollback: Disable feature flag (instant)
   Detection: QA checklist for each user tier
```

### Tabular Format (for quick scanning)

```
PRE-MORTEM RISK TABLE
+======================+========+==========+========================+=============+
| Scenario             | Prob.  | Impact   | Mitigation             | Rollback    |
+======================+========+==========+========================+=============+
| Stale cache after    | HIGH   | HIGH     | Cache invalidation     | Clear Redis |
| webhook update       |        |          | on webhook receipt     | (30s)       |
+----------------------+--------+----------+------------------------+-------------+
| Migration on replica | LOW    | CRITICAL | --primary flag +       | Full backup |
| before primary       |        |          | check replication lag  | restore     |
+----------------------+--------+----------+------------------------+-------------+
| Billing tab shown    | MEDIUM | MEDIUM   | Feature flag in        | Disable     |
| to free-tier users   |        |          | BillingTab component   | flag (0s)   |
+----------------------+--------+----------+------------------------+-------------+
```

## Risk-Impact Quadrant

For plans with many risk factors, use a 2x2 grid:

```
                     HIGH IMPACT
                         |
    MONITOR CLOSELY      |      ACT NOW
                         |
    * API versioning     |  * schema migration
    * env config         |  * cache invalidation
                         |
   ──────────────────────+─────────────────── HIGH LIKELIHOOD
                         |
    ACCEPT               |      MITIGATE
                         |
    * docs update        |  * feature flag timing
    * logging format     |  * DNS propagation
                         |
                     LOW IMPACT

Priority: ACT NOW > MITIGATE > MONITOR > ACCEPT
```

## Cascading Failure Analysis

For distributed systems, show how one failure propagates:

```
FAILURE CASCADE: Database connection pool exhausted

[Pool exhausted] --> [API timeouts] --> [Frontend 504s] --> [User complaints]
       |                   |                  |
       v                   v                  v
  Detection:          Detection:          Detection:
  Connection          p95 latency         Error rate
  count alert         > 5s alert          > 1% alert
  (30s)               (2 min)             (5 min)

Total detection time: 30s (if pool alert configured)
Blast radius without alert: ~5 min until user-visible
```


### Visualization Tiers


# Visualization Tiers

Plan-viz uses three tiers of progressive disclosure. Tier 1 is always shown; Tier 2 sections are shown on request; Tier 3 deep dives are on-demand.

## Tier 1: Header (Always Rendered)

Use `assets/tier1-header.md` template. Fill from gathered data:

```
PLAN: {plan_name} ({issue_ref})  |  {phase_count} phases  |  {file_count} files  |  +{added} -{removed} lines
Risk: {risk_level}  |  Confidence: {confidence}  |  Reversible until {last_safe_phase}
Branch: {branch} -> {base_branch}

[1] Changes  [2] Execution  [3] Risks  [4] Decisions  [5] Impact  [all]
```

### Computing Header Fields

- **Risk level** = highest risk across all phases (LOW/MEDIUM/HIGH/CRITICAL)
- **Confidence** = LOW if >50% of changes are in untested code, MEDIUM if mixed, HIGH if well-tested paths
- **Reversible until** = last phase before an irreversible operation (DROP, DELETE data, breaking API change)

## Tier 2: Core Sections (On Request)

Five numbered sections, each answering a specific reviewer question:

| Section | Question Answered | Pattern Reference |
|---------|------------------|-------------------|
| [1] Change Manifest | What files change and how? | `change-manifest-patterns.md` |
| [2] Execution Swimlane | What runs in parallel? What blocks what? | `execution-swimlane-patterns.md` |
| [3] Risk Dashboard | What can go wrong? When is it irreversible? | `risk-dashboard-patterns.md` |
| [4] Decision Log | What non-obvious choices were made? | `decision-log-patterns.md` |
| [5] Impact Summary | What are the raw numbers? | `assets/impact-dashboard.md` |

## Tier 3: Deep Dives (On Demand)

| Section | Question Answered | Reference |
|---------|------------------|-----------|
| [6] Blast Radius | How far do changes ripple? | `blast-radius-patterns.md` |
| [7] Cross-Layer Consistency | Are frontend/backend aligned? | `deep-dives.md` |
| [8] Migration Checklist | What's the ordered runbook? | `deep-dives.md` |

