# The 8-Phase Pipeline

MAPLE runs every feature through a fixed, phase-gated pipeline. No phase can be skipped. Three consecutive failures on any task escalate to a human.

Terminology: `spec-kit` in this repo means MAPLE's internal **Specification Knowledge & Integration Toolkit** stage/agent name. When state shows `awaiting_approval: "spec-kit"`, it refers to that local stage, not `github/spec-kit`.

```mermaid
flowchart LR
    P1["**Phase 1**\nDISCOVER\n@product-owner"]
    P2["**Phase 2**\nARCHITECT\n@architect"]
    P3["**Phase 3**\nPLAN\norchestrator"]
    P4["**Phase 4**\nINFRA\n@docker @k8s @terraform"]
    P5["**Phase 5**\nIMPLEMENT\nTDD loop"]
    P6["**Phase 6**\nVALIDATE\n@qa"]
    P7["**Phase 7**\nDOCUMENT\n@docs"]
    P8["**Phase 8**\nFINAL GATE\norchestrator"]

    P1 -->|"Human gate ✓"| P2
    P2 -->|"Human gate ✓"| P3
    P3 --> P4
    P4 --> P5
    P5 --> P6
    P6 -->|"100% pass"| P7
    P6 -->|"failure"| P5
    P7 --> P8
    P8 -->|"make test-all exits 0"| Done["✅ PR created"]
    P8 -->|"failure"| P5
```

---

## Phase Details

| # | Phase | Agent(s) | Human gate | Artifacts |
|---|---|---|---|---|
| 1 | **DISCOVER** | `@product-owner` | ✅ Yes | `stories.md`, `acceptance-criteria.md` |
| 2 | **ARCHITECT** | `@architect` | ✅ Yes | `architecture.md`, `adr.md`, `contracts/`, `threat-model.md` |
| 3 | **PLAN** | orchestrator | — | `plan.md`, `test-plan.md` |
| 4 | **INFRA** | `@docker`, `@kubernetes`, `@terraform`, `@postgresql` | — | `docker-compose.yml`, manifests, modules |
| 5 | **IMPLEMENT** | `@qa` + specialist agents | — | Source code, test files |
| 6 | **VALIDATE** | `@qa` | — | Validation report |
| 7 | **DOCUMENT** | `@docs` | — | Feature docs, CHANGELOG entry, runbooks |
| 8 | **FINAL GATE** | orchestrator | — | Completion summary, PR |

All artifacts land in `docs/specs/{feature-slug}/`. The orchestrator enforces order — specialists cannot jump phases.

---

## Spec-Kit Layer

Before the orchestrator allows Phase 5 to begin, the Spec-Kit must be complete:

```
Problem statement  →  Spec  →  Plan  →  Tasks
```

Each artifact requires human approval before the next is generated. The orchestrator refuses to issue implementation tasks until `plan.md` and `test-plan.md` exist in `docs/specs/{feature-slug}/`.

UI-bearing stories (`ui: true` in frontmatter) trigger additional design gates:
- ASCII/SVG wireframe — generated by `ux-researcher`
- W3C DTCG design tokens (`tokens.json`) — generated by `visual-identity-designer`
- High-fidelity mockup — stored in `docs/design/`
- Accessibility audit (WCAG 2.2 AA) — run by `a11y-auditor` before FINAL GATE

---

## The TDD Loop (Phase 5)

Each task goes through a strict RED → GREEN → REFACTOR cycle before the next task starts.

```mermaid
stateDiagram-v2
    direction LR
    [*] --> RED : QA writes failing test
    RED --> VerifyFail : run test suite
    VerifyFail --> RED : test passes — wrong test, rewrite
    VerifyFail --> GREEN : test fails ✓ — correct
    GREEN --> VerifyPass : specialist implements
    VerifyPass --> GREEN : test still fails — fix code
    VerifyPass --> REFACTOR : test passes ✓
    REFACTOR --> VerifyStill : clean up code
    VerifyStill --> REFACTOR : test broke — fix
    VerifyStill --> [*] : passes — next task
```

The QA agent writes the failing test **first**. A test that passes at the RED stage means it tested the wrong thing — QA rewrites it.

---

## Karpathy Principles: Code Quality Gate (Phase 5 → Phase 6)

MAPLE enforces Andrej Karpathy's 4 principles for reducing LLM coding mistakes at the **Phase 5 → Phase 6 transition**.

### The 4 Principles

| Principle | What it enforces |
|-----------|-----------------|
| **Think Before Coding** | Assumptions stated explicitly. Ambiguities surfaced before implementation. No silent interpretations. |
| **Simplicity First** | Minimum viable code. No speculative features, abstractions, or over-engineering. If 200 lines could be 50, rewrite. |
| **Surgical Changes** | Only changes requested in the spec are made. No unrelated refactoring, cleanup, or style improvements. |
| **Goal-Driven Execution** | Tests written first. Success criteria explicit and verifiable. Every line of code traces to a requirement. |

### How the Gate Works

**After Phase 5 IMPLEMENT is complete:**

1. Orchestrator **auto-calls** `@karpathy-audit`
2. Audit analyzes the PR diff against:
   - Original spec (`docs/stories/{story}/Story.md`)
   - Actual code changes made
   - 4 principles above
3. Generates compliance report: `.claude/state/karpathy-report.json`

### Scoring & Gate Decision

| Overall Score | Decision | Action |
|---|---|---|
| ≥90 | 🟢 **PASS** | Auto-advance to Phase 6 VALIDATE |
| 70-89 | 🟡 **PASS_WITH_APPROVAL** | Pause. Display report. Require human approval (`[a]` key) to advance. |
| <70 | 🔴 **FAIL** | **BLOCK advancement.** Orchestrator HALTS. Require remediation + re-audit. |

### Violations Detected

- **Out-of-scope edits** — Files touched outside the story boundary
- **Scope creep** — Features added beyond what spec requires
- **Over-engineering** — Code complexity exceeds necessity
- **Unrelated refactoring** — Cleanup/improvements orthogonal to the spec
- **Hidden assumptions** — Requirements not surfaced or asked about

### Manual Invocation

Can be called at any phase (not just Phase 5→6):

```
/karpathy-audit
@karpathy-audit
```

### Orchestrator Hard Rule

```
NEVER proceed from Phase 5 to Phase 6 if Karpathy score < 70.
NEVER bypass the karpathy-audit gate.
If gate is genuinely wrong, escalate to human to modify the rule — do not silently bypass.
```

### Remediation Workflow

If audit fails (score <70):

1. Specialist re-assesses work against the violation
2. Removes out-of-scope code
3. Simplifies over-engineered logic
4. Surfaces hidden assumptions
5. Manually re-runs: `/karpathy-audit`
6. Once all 4 principles ≥70, human approves advancement

### Dashboard Integration

The TUI (`maple` dashboard) displays:
- Karpathy score badge in Phase 5 detail view
- Per-principle breakdown in `[P]` (Pipeline pane)
- Red blocking indicator if score <70 (prevents manual phase skip)
- Approval gate prompt if 70-89 (awaiting `[a]` key)

---

Every phase uses the same `make` targets. Agents, CI, and humans share one interface.

```bash
make build            # Build all artifacts
make test             # Unit tests
make test-integration # Integration tests (spins up containers automatically)
make test-e2e         # Playwright E2E tests
make test-contract    # Contract / schema tests
make test-all         # Full suite — the Phase 8 gate
make lint             # Lint
make security-scan    # Security scanning
make fmt              # Format code
make containers-up    # Start PostgreSQL + Redis test containers
make containers-down  # Stop and remove containers
make seed-test        # Seed test database
make migrate          # Run database migrations
```

The Makefile ships with stubs. Replace the recipe bodies with your stack's actual commands before running any feature.

The MAPLE-managed section (between `# ─── BEGIN MAPLE MANAGED` and `# ─── END MAPLE MANAGED`) is updated by `maple update` — your custom targets outside those markers are preserved.

---

## GitHub Integration

The `story-issue-sync` skill keeps local stories and GitHub Issues bidirectionally in sync:

- Every story file maps to a GitHub Issue via `issue_number` in frontmatter
- Phase transitions update the Issue label (e.g. `phase:implement`)
- The GitHub Project v2 board always reflects current status
- PRs are created and linked automatically at Phase 8

Bootstrap labels and the Project board from the dashboard command mode (`:labels`, `:project`) or CLI (`maple labels` / `maple project`).

---

## Escalation Policy

If a specialist agent fails the same task three consecutive times, the orchestrator:

1. Stops retrying
2. Writes a `BLOCKED.md` in `docs/specs/{feature-slug}/`
3. Prompts the human for intervention before resuming

This prevents infinite loops and surfaces genuinely hard problems early.
