# THE CONSTITUTION

> **Generic by design.** This document hard-codes no project value; the reference implementation appears only as a labeled example. Claude binds every `<…>` placeholder and “per `CLAUDE.md`” reference from the project `CLAUDE.md` at read time — see `SPECIALIZE.md`.
### An engineering handbook for building enterprise solutions with Claude, Claude Code, and Claude Design
**Design-first · agent-orchestrated · scratch → deployment**

---

## 0. How to read this manual

This is the standing law for how we conceive, design, build, and ship large enterprise systems. It is **project-agnostic**: it describes a method, not one product. Throughout, a neutral reference implementation **Acme** (a .NET 10 Blazor Aspire modular monolith, ~30 modules, ~212 screens) is the **reference implementation** — wherever you see an Acme-specific value (a project name, a schema prefix, a component prefix), read it as an *instance* of a parameter you rebind for the next project — in any enterprise domain. The stack named here is the reference stack, itself a parameter (see `SPECIALIZE.md`).

Project parameters you rebind per project (set these once in the project's `CLAUDE.md`):

| Parameter             | Reference value (Acme)                                                                |
| --------------------- | ------------------------------------------------------------------------------------- |
| `<App>`               | `Acme`                                                                                |
| Composition root      | `<App>.Host`                                                                          |
| Design-system library | `<App>.DesignSystem` (RCL)                                                            |
| Shared primitives     | `<App>.SharedKernel`                                                                  |
| Cross-module channel  | `<App>.Contracts`                                                                     |
| Cross-cutting infra   | `<App>.Infrastructure`                                                                |
| Module project        | `<App>.<Module>`                                                                      |
| DS component prefix   | the design-system component + class prefix (`<ds-prefix>`)                            |
| Prototype location    | `Prototype/` + canonical entry HTML                                                   |
| Naming grammar        | `FR-<X>-NNN` · `BR-<X>-NNN` · `EVT-<X>-Name` · `PERM-<X>-Entity.Action` · `WF-<X>-NN` |

The three companions to this file:
- **`PROMPT_TEMPLATES.md`** — the system-prompt template and the per-phase / orchestration prompts, tuned for Claude Code.
- **`agents/*.md`** — the drop-in subagent definitions for `.claude/agents/`.
- **`commands/*.md`** — the orchestrator slash commands for `.claude/commands/`.

> **The one sentence that governs everything:** *Fidelity and quality are produced by architecture, not by vigilance.* We make drift and defects either mechanically impossible or automatically detected, so that neither a human nor an agent can quietly diverge — which is what lets agents do the heavy lifting while human attention stays bounded.

---

## 1. The twelve laws

These are non-negotiable. Every phase, agent, and gate below is in service of them. A project's `CLAUDE.md` may add laws; it may not weaken these.

1. **The rendered design is the contract.** The single source of truth for what a screen looks like and what information it carries is the *rendered* prototype (and, once reconstructed, the live UI in the repo). Precedence is **rendered prototype > reconciled spec > screenshot > draft md**. A prototype-vs-spec conflict is a **STOP-and-surface**, never a silent decision. **The prototype is the visual & UX contract, not the data-flow contract:** where it uses a single mock subject to stand in for "the selected one," or a stubbed action that only toasts, the *real* behaviour — carrying the chosen entity's identity through the seam, and producing the action's real effect — governs. Completing that is **expected forward-wiring, not a divergence**; only a *visual* deviation from the prototype is a STOP.

2. **Decouple through contracts.** A module never references another module. Cross-module needs are met only by subscribing to a **published event** or calling a **public query DTO** from the Contracts project. This is what makes parallel agent work safe: an agent needs only its own module plus the contracts it consumes/emits, and a broken contract is a compile error, not a 2 a.m. surprise.

3. **Single-writer orchestration.** Exactly one actor — the orchestrator (main thread) — writes shared trackers and closes cross-cutting seams. Worker agents touch **only their own new files** plus designated **append-only** shared files, and return a **structured report**. Integration is programmatic, never text-parsed.

4. **Stateless agents; context passed explicitly.** A subagent begins with a fresh context window; the only channel into it is the prompt string. Every delegation hands over the spec path(s), the design references, the relevant prior output, and the path to `CLAUDE.md`. The agent reads `CLAUDE.md` + its spec first.

5. **Isolated, bounded parallelism.** Workers run in parallel only when isolated — own build output dir, own browser/port, append-only to the one shared stylesheet. Concurrency is capped by a semaphore. Shared *declarations* are ordered by a **seed gate** (the first screen/slice of a new module lays the shared types alone before siblings fan out).

6. **Gates before "Done."** No agent self-attests completion. "Done" requires passing the gate for its phase: clean build, computed-style/visual assertions, value-not-literal checks, tests, contract tests, accessibility, and — for wiring — a reviewer PASS. A visible mismatch is a defect to root-cause and fix, never to explain away.

7. **Blast-radius limits.** An agent may freely change its own slice and the contracts it emits. Changes to the shared kernel, the Contracts surface, or another module's internals require a foundation-level gate (human or stricter review). The worst a runaway sweep can do is damage its own slice — which the gates catch.

8. **Append-only / self-registration over central edits.** Avoid hand-editing central files. Modules self-register (`Add<Module>()`); nav and routes come from a registry, not a hand-edited menu; the shared stylesheet is appended to, never rewritten. This removes the merge contention that otherwise forces serial work.

9. **Just-in-time spec reconciliation.** Specs are reconciled to the *current* design at the moment a slice is built, not perfected up front. Draft md files are **inputs, not truth**. Each slice carries a provenance header; the registries' Sync state tracks fresh/stale.

10. **Progressive completeness.** Build design-first and add capability as development reaches it. Feature-parity research informs the spec but never overrides the design; only the Must-haves a slice needs *now* are adopted, the rest go to a backlog.

11. **Capped autonomy with escalation.** Self-correction loops (reviewer→builder, test-fail→fixer) retry at most twice, then stop and file the case in an approval inbox. Never an infinite loop. Human supervision is **on the loop** (designed checkpoints + exception reports), not **in the loop** (every step).

12. **Institutional memory is mandatory.** Durable codebase facts go to `INSIGHTS.md`; corrections and self-caught mistakes go to `LESSONS.md` as *Mistake / Trigger / Rule*; status goes to `PROGRESS.md`. Read `PROGRESS` + `LESSONS` at session start. When a lesson proves stable, graduate it into a hard rule in `CLAUDE.md`. The system must get smarter every sweep.

---

## 2. The lifecycle — scratch to deployment

```mermaid
flowchart LR
  P0["0 · Conceive<br/>PRD.md in Claude"] --> P1["1 · Design<br/>Claude Design → prototype"]
  P1 --> P2["2 · Reconstruct<br/>prototype → Blazor UI"]
  P2 --> P3["3 · Specify<br/>MODULE/WORKFLOW/CLAUDE.md"]
  P3 --> P4["4 · Found<br/>kernel · contracts · infra"]
  P4 --> P5["5 · Build<br/>workflow sweeps wire backend"]
  P5 --> P6["6 · Harden & deploy<br/>perf · security · CI/CD"]
  P5 -. "new module / new design" .-> P2
```

| Phase                 | Goal                                                                                                   | Primary engine                                                                                | Gate to advance                                                                    |
| --------------------- | ------------------------------------------------------------------------------------------------------ | --------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------- |
| **0 Conceive**        | Turn an idea into a product spec                                                                       | Claude (chat) → `PRD.md`                                                                      | PRD covers modules, entities, FRs, workflows, business rules, events, integrations |
| **1 Design**          | Turn the PRD into a clickable, high-fidelity prototype on the design system                            | Claude Design (+ pre-built design system + PRD)                                               | ~90% of screens designed; **journey-continuity audit clean of S1 gaps on the golden journeys** (§K / `journey-continuity-audit`); designer sign-off |
| **2 Reconstruct**     | Reproduce the prototype 1:1 as the UI layer                                                            | `screen-reconstructor` agents under `reconstruct-sweep` (single-writer integration)           | Per-screen fidelity gate green; screen registry ✅                                  |
| **3 Specify**         | Capture behaviour, rules, and seams the design can't express                                           | Author `<X>_MODULE.md`, `<X>_WORKFLOW.md`, `<X>_DB_SCHEMA.md`, `CLAUDE.md` from the prototype | Specs exist with provenance headers; dependency graph drawn                        |
| **4 Found**           | Build the shared kernel, contract surface, infra, and design-system extraction — **human-in-the-loop** | Human + targeted agents                                                                       | Boundary tests pass; app shell + cross-cutting behaviours live                     |
| **5 Build**           | Wire real backend + processes behind the UI, **workflow by workflow**                                  | `build-workflow` sweep over the 9-agent pipeline                                              | Per-workflow Definition of Done met; reviewer PASS                                 |
| **6 Harden & deploy** | Performance, security, observability, release                                                          | Human + agents + CI/CD                                                                        | NFR targets met; release checklist green                                           |

The crucial mindset for phases 4–6: **a module is a unit of ownership; a workflow is a unit of delivery.** You do not finish a module in isolation and hope the seams line up later — that defers every integration bug to the end. You grow modules through the workflows that traverse them, so a module becomes complete as a *side effect* of all the workflows that have swept through it. Build the foundation by hand first; after that, every delivery is a workflow sweep.

**Two design lanes (the "new design" loop-back).** Phase 1 uses the design tool for the big bang; mid-flight, design-backlog screens route by one question — *does this screen need interactive human canvas iteration?* — because the design tool and the repo run the **same model**: the tool's marginal value is the canvas, never generation capability. **In-repo lane** (default): a scaffold-conforming row goes to the `design-builder` agent via `/design-build` — same brief, no console round-trip; the human still signs off on the rendered screenshot (on the loop, not couriering zips), and provenance + the contract sidecar are recorded **at birth**, so the screen never needs a drift sweep. **Console lane:** novel patterns, a new module's visual language, or wanted exploration go to the design tool, **batched per module-session**; the delivery is ingested atomically by `/promote-design` (place + wire + hash + registry + board flips in one scripted pass) — an *expected* delivery's delta is known at ingest, so it too never needs `design-sync`, which is reserved for genuinely unexpected prototype changes. The lane-routing rule is pinned per project in `CLAUDE.md §2`.

---

## 3. The architecture

A vertical-slice **modular monolith**, composed by a Host, orchestrated by .NET Aspire. Boundaries are enforced by architecture tests, not discipline.

```mermaid
flowchart TD
  W["Workflow slices<br/><i>delivery unit — one cut across several modules</i>"]
  M["Modules (vertical slices, ~30)<br/><i>ownership unit — Domain · Application · Infrastructure · UI · Add(Module)</i>"]
  C["Contracts<br/><i>the ONLY cross-module channel — append-only events + public DTOs</i>"]
  F["Foundation<br/><i>SharedKernel · DesignSystem (RCL) · Infrastructure · Host · Aspire AppHost</i>"]
  W --> M --> C --> F
```

**Canonical repository topology** (rebind `<App>`):

```
src/
  <App>.SharedKernel/    Frozen primitives: Entity, AggregateRoot, ValueObject, Result,
                         IDomainEvent, IIntegrationEvent, Permission, NavItem, INavRegistry, IModule. No app logic.
  <App>.Contracts/       Append-only integration events + public DTOs shared across modules.
  <App>.DesignSystem/    RCL: ported design system — Components/UI, Charts, Styles, Services, wwwroot (js/fonts/themes).
  <App>.Infrastructure/  MediatR behaviours (validation, authorization, audit), EF interceptors, Mongo, integration.
  <App>.Host/            Composition root: App/MainLayout/Sidebar, Program.cs (MediatR + nav registry + module loop).
                         Global InteractiveServer. References Aspire ServiceDefaults.
  Modules/
    <App>.<Module>/      ONE project per module: Domain/ Application/ Infrastructure/ UI/ <Module>Module.cs
tests/
  <App>.ArchitectureTests/   NetArchTest boundary rules (Domain has no EF/Infra; Contracts depend on no module).
  <App>.<Module>.Tests/      xUnit units + Playwright e2e (Category=e2e).
docs/                        modules/<m>/, cross-cutting/, design-system/, SCREEN_REGISTRY.md, PROGRESS/INSIGHTS/LESSONS.
```

**Boundary rules (Law 2 made concrete):**
- A module references only `SharedKernel`, `Contracts`, `DesignSystem` (+ `Infrastructure`) — **never another module's project**. Need another module's data? Subscribe to its event or call its public query DTO.
- **Self-registration:** each module exposes one `Add<Module>()` that registers its handlers, EF context, validators, nav item (into `INavRegistry`), and permissions. The Host calls them in a loop. No hand-edited menu, no central registration file (Law 8).
- **Per-module EF:** separate `DbContext` and schema per module (`reg.*`, `clin.*`, …) so migrations never collide — which is what lets migration work parallelize.
- **Append-only Contracts is enforced, not reviewed:** the Contracts public surface is snapshotted (`Contracts.approved.txt`, `approved ⊆ generated` asserted in ArchitectureTests via the `ContractsSurfaceTests` template) and diff-guarded at edit time (the `ContractsSurfaceRewrite` preflight detector). Deprecation is an *addition* (`[Obsolete]` + a V2 type); physical removal is a foundation-gated human event (Law 7) through the approval inbox — never an agent edit. Snapshot regeneration is single-writer (`tools/Update-ContractsSnapshot.ps1`, at integration/wave closure).

**Application-layer rules (codify before writing handlers):**
- Every MediatR request carries `[Permission("X.Entity.Action")]` or `[NoPermission]`; the `AuthorizationBehavior` is **fail-closed**.
- Every `BR-*` business rule is enforced in the **domain**, not just the UI.
- Publish domain/integration events through the **notification wrapper**, never raw.
- `Add<Module>()` must register the module's FluentValidation validators or `ValidationBehavior` silently no-ops.
- Mutations emit audit (SQL header + Mongo diff) and honour the config-console + identity-safety hooks.

**The persistence boundary** (which store owns what — decide per entity, not per module):
- **Relational (EF Core → SQL Server):** transactional, relational, ACID — core entities, transactions, orders, financials, audit *headers*.
- **Document (MongoDB):** free-text bodies, raw inbound payloads, audit *diffs*, large semi-structured blobs, AI prompts/outputs.
- **Cache / realtime (Redis):** cache-aside reads, session, the SignalR backplane for scale-out.
- **Search (a typo-tolerant search engine or equivalent):** fuzzy entity/code search with typo tolerance.
- **Large binaries:** files/blobs live in object or blob storage; SQL stores only metadata + a reference.

**Blazor Server reality (plan for it, don't discover it):** every user holds a server-side **SignalR circuit** carrying UI state, so at enterprise concurrency the bottlenecks are circuit memory and connection count, and every interaction round-trips to the server — latency-sensitive on poor networks. Mitigations are first-class, not afterthoughts: a **Redis backplane** + sticky sessions (or a managed SignalR service) for scale-out; `[SupplyParameterFromPersistentComponentState]` so state survives reconnects; a clear reconnection UX; and selective **Interactive Auto / WebAssembly** render modes for the most latency-sensitive or offline-tolerant surfaces.

---

## 4. Source of truth & just-in-time reconciliation

The draft `<X>_MODULE.md` / `<X>_WORKFLOW.md` you wrote early are **point-in-time drafts**, not the source of truth. The truth for visual/IA is the design as materialised in the repo (the reconstructed UI); the truth for behaviour is the spec *reconciled to that design at build time*. Reconciliation is therefore a step, not a document you keep eternally accurate.

**Precedence:** current design (rendered prototype → reconstructed UI) → reconciled spec (behaviour, states, seams) → draft md (input only) → research (advisory). When design and a draft disagree, design wins for anything visual; the md's behavioural content is reconciled, not obeyed and not discarded; genuine conflicts are flagged.

**Three mechanisms make this self-running:**
1. **Provenance header** on every spec — the design source it was derived from, a `last_synced` timestamp, and a hash of that source. Hash mismatch = stale.
2. **Sync state** — the registries' Sync chip (or a field in `PROGRESS.md`) tracking fresh / stale / unsynced per module and workflow.
3. **Reconciliation is the first job of `spec-architect` in every sweep:** read the current design for the slice, diff it against the draft md, rewrite the spec to match design while preserving still-valid behaviour, and emit a short **delta report** — which is exactly what the human reviews at checkpoint 1 (a focused diff, not a re-read). **Hard gate:** a sweep cannot pass the enrich phase unless the spec was reconciled against current design *this run*.

Because the design keeps evolving, a later design change to an already-built module is caught automatically by the **provenance hash going stale** and the **visual-regression baseline going red**, triggering a targeted re-sweep of just that slice.

**Provenance at birth.** A screen designed in-repo (`/design-build`) or ingested as an expected delivery (`/promote-design`) enters the registry with its source hash, brief id, and lane recorded **at creation** — its delta is known, so drift triage over it would only re-discover information the pipeline already had. `design-sync`'s scope is thereby what it should be: prototype sources a human changed *outside* the pipeline. Every screen born through the pipeline also carries its **contract sidecar** (see §5), so the contract is captured once, at the moment it is cheapest.

**Contract graduation (the dual-representation exit).** The prototype and the built UI are two living representations of the same screen; keeping them 1:1 forever makes the prototype an increasingly expensive dead twin once real wiring lands. So: **when a screen is wired and reviewer-PASSed, the live UI in the repo becomes its contract** (Law 1 already names it: "and, once reconstructed, the live UI in the repo"). The orchestrator marks the registry row `graduated`, freezes the prototype source (provenance archived), and removes it from drift-sweep scope. Consequences: cosmetic/structural changes to a graduated screen flow **forward-only** (edit the UI + refresh the UIMAP — no prototype round-trip); a genuine *redesign* of a graduated screen is a deliberate, briefed event — a new design-backlog row through either lane, applied with the reconstructor's re-sync mode and the **preserve-wiring** flag — never drift discovered after the fact. Drift-sweep scope thus shrinks monotonically as the build matures instead of growing with it. A project may opt out per screen family in `CLAUDE.md` where the prototype must stay live (e.g. an actively-designed module).

---

## 5. UI-driven contract extraction

The built UI is your most *reliable* specification of the contract surface, because it is concrete code with real bindings and mock data — more trustworthy than a week-old md. It is authoritative for the **interface** (shapes, operations, flow) and silent on the **logic** (rules, validation semantics, side effects). So extract from it systematically, and let the spec + research + human supply the logic.

`spec-architect` (or `module-wirer` at wiring time) reads each screen/component in the slice and writes a **wiring brief** (`docs/modules/<m>/<screen>_UIMAP.md`) mapping:

| From the screen                                                | To the backend                                 |
| -------------------------------------------------------------- | ---------------------------------------------- |
| **Screen subject** — which entity it presents                  | the **input key** it is parameterised by (route param / context bar) + the upstream that supplies it; an entity-scoped screen is never a singleton |
| Data displayed / bound                                         | a read model / query DTO                       |
| Forms & inputs (required markers, formats)                     | a command + FluentValidation rules             |
| Buttons, menu items, links                                     | operations / commands / navigations to support |
| Each action's **effect** (mutate · persist · navigate-with-context) | the command it dispatches — or, if not yet backed, a **marked stub + backlog item** (never a silent toast) |
| Lists & tables                                                 | pagination / sort / filter parameters          |
| Cross-screen references (record Y for entity X)                | cross-module **contracts**                     |
| Live / status elements                                         | SignalR channels                               |
| Role-gated controls                                            | `[Permission]` requirements                    |
| States present — and the loading/empty/error states **absent** | the gap list to build                          |

**Contract at birth (sidecar-first).** Deriving that table from rendered output is the expensive way — the contract is cheapest to capture when the generating model still holds it. Every screen born through the design pipeline therefore ships a **contract sidecar** (`<screen-file>.uimap.json`, per the `contract-sidecar` skill): the machine-readable twin of the rows above, emitted by `design-builder` in-repo and required of the design tool by the design-prompts Global preamble's output contract. Where a sidecar exists, `spec-architect` **validates it against the render and lifts it as the UIMAP's first draft** (adding what a sidecar can't carry — validation semantics, cross-module routing, the absent-states gap list), `screen-reconstructor` uses it as the fidelity gate's completeness checklist, and `design-sync` classifies contract-affecting drift by **sidecar diff** before any rendered-output archaeology. Law 1 is untouched: render disagrees with sidecar → the render wins and the sidecar is the defect. Legacy screens are backfilled on-demand (when a sweep touches them), never as a bulk pass.

**Highest-leverage tactic:** the mock data feeding each screen *is* a sample of the response the real backend must produce — lift it. The mock shapes become the first draft of DTOs, handlers are built to return that shape, and `seed-builder` reuses the same mock data as the basis for realistic seeds. Two honest cautions: inferred types need confirmation (a string might be an enum, a coded value, or a date — flag inferences), and mock data shows one happy case, so treat extracted contracts as a strong draft to confirm at the checkpoint.

---

## 6. The agent operating model

Agents are **single-purpose specialists** with scoped tools and a routed model. They are stateless (Law 4) and report in a structured shape (Law 3). The roster below covers the full lifecycle; the design-phase agent (`screen-reconstructor`) you already run, the seven build-phase agents and two understand-phase agents are defined in `agents/`.

Each agent is a **role**; the reusable **expertise** it applies lives in **skills** (`.claude/skills/`) that load on demand and are shared across agents — the subagent stays a thin role + report contract while the skill carries the how-to (the design-system contract, the reconstruction traps, schema design, the compliance rules). See `SKILLS.md` for the recommended public skills, the project-skill catalog, and the agent→skills map. Keep procedural depth in skills, not in `CLAUDE.md` (always loaded) or in the agent prompts (Law 12 — institutional memory, applied to capability).

```mermaid
flowchart TB
  subgraph U["Understand & enrich"]
    A1["spec-architect<br/><i>reconcile spec to design · UIMAP · delta report</i>"]
    A2["spec-researcher<br/><i>market-leader/standards parity · advisory</i>"]
  end
  subgraph B["Build the slice"]
    B1["backend-builder<br/><i>domain · MediatR · validators</i>"]
    B2["migration-engineer<br/><i>per-module EF migration (gated)</i>"]
    B3["seed-builder<br/><i>reference + realistic demo data</i>"]
    B4["crosscutting-weaver<br/><i>authz · audit · events · identity-safety · jobs</i>"]
    B5["module-wirer<br/><i>wire UI to handlers · keep design</i>"]
  end
  subgraph V["Verify & review"]
    V1["test-engineer<br/><i>xUnit · Playwright · NetArchTest · visual</i>"]
    V2["reviewer<br/><i>audit vs constitution · PASS/FAIL</i>"]
  end
  U --> B --> V
```

| Agent                  | Phase        | Job                                                                                          | Tools (scoped)                                      | Model   |
| ---------------------- | ------------ | -------------------------------------------------------------------------------------------- | --------------------------------------------------- | ------- |
| `screen-reconstructor` | 2            | Reproduce ONE screen 1:1 as the design-system classes Blazor                                 | Read, Grep, Glob, Edit, Write, Bash                 | inherit |
| `design-builder`       | 1 · backlog  | Author ONE net-new prototype screen in-repo from its design-prompts brief (scaffold-conforming rows); emits the screen file + contract sidecar + sign-off screenshot; never wires or flips | Read, Grep, Glob, Write, Edit, Bash | opus    |
| `journey-auditor`      | 1 gate · backlog | Trace ONE journey's continuity through the prototype (route/edge ledgers, role×journey walk, gap patterns); severity-ranked gap rows + continuity ledger; advisory (writes only its report) | Read, Grep, Glob, Bash, Write(report) | opus    |
| `edge-auditor`         | 1–2 · module | Inventory ONE module's prototype affordances by dead-handler tells; two-axis classification + exceptions-ledger re-verification; advisory (writes only its report) | Read, Grep, Glob, Bash, Write(report) | opus    |
| `design-sync`          | 2–5 · drift  | Detect + triage prototype drift; emit a routed re-sync plan; advisory (writes only its plan) | Read, Glob, Grep, Bash, Write(plan) + graph(read)   | opus    |
| `spec-architect`       | 3 / 5-enrich | Reconcile spec to current design; write UIMAP + delta report                                 | Read, Glob, Grep, Write(specs) + graph(read)        | opus    |
| `spec-researcher`      | 5-enrich · backlog | Feature-parity vs the market leader + domain/interop standards; advisory. Also dispatched in triage mode by `/design-help` for retrospective design-gap discovery over already-built workflows | Read, Glob, Grep, Write(specs), WebSearch, WebFetch + graph(read) | opus    |
| `backend-builder`      | 5-build      | Domain + application layer (MediatR records, validators, value objects, events)              | Read, Write, Edit, Grep, Glob, Bash + graph(read)   | opus    |
| `migration-engineer`   | 5-build      | Per-module EF migration; gated on destructive change                                         | Read, Edit, Bash                                    | sonnet  |
| `seed-builder`         | 5-build      | Idempotent reference + domain-plausible demo data                                            | Read, Write, Edit, Bash                             | sonnet  |
| `crosscutting-weaver`  | 5-build      | Pipeline behaviours + compliance hooks + events + SignalR + jobs                             | Read, Write, Edit, Bash + graph(read)               | sonnet  |
| `module-wirer`         | 5-build      | Wire reconstructed UI to handlers; add states; preserve design                               | Read, Edit, Grep, Glob, Bash + graph(read)          | sonnet  |
| `test-engineer`        | 5-verify     | xUnit + Playwright e2e + NetArchTest + visual regression                                     | Read, Write, Edit, Bash + graph(read)               | sonnet  |
| `interaction-auditor`  | 5-verify · backlog | Enumerate every affordance on touched (or all) screens; classify disposition + risk; reconcile vs UIMAP; emit the Interaction Ledger; read-only | Read, Glob, Grep, Bash + graph(read)    | opus    |
| `reviewer`             | 5-verify     | Read-only audit against this Constitution + `CLAUDE.md`                                      | Read, Glob, Grep + graph(read)                      | opus    |
| `wave-reviewer`        | 5-verify (wave) | Audit the combined union diff across a wave's branches for cross-sweep duplication / collision / seam interference; read-only | Read, Glob, Grep, Bash + graph(read) | opus |

**Model routing for cost/quality:** Opus for the judgment agents (`spec-architect`, `spec-researcher`, `reviewer`, `design-sync`, `interaction-auditor`, `journey-auditor`, `edge-auditor`, `wave-reviewer`) and for `design-builder` (design quality is judgment); Sonnet for the builders; the built-in **Explore** agent (Haiku, read-only) for fast codebase search between stages. Author agents via `/agents` (so they register immediately) and version-control the `.claude/` tree.

**Graph-first discovery (optional — `graph(read)` in the roster).** When the project indexes its code in a code-discovery graph MCP (per `CLAUDE.md §0` — `codebase-memory-mcp` is the reference; an optional capability, not a kit dependency), the audit/spec agents **and** the build agents get its **read** tools (`search_graph`/`trace_path`/`query_graph`/`get_code_snippet`/`get_architecture`/`detect_changes`/…) for structural questions a grep sweep answers expensively: who calls X, what a module exposes, which modules emit/consume an event, the cross-module contract surface, UI-affordance→handler matching, and boundary (Law 2) checks. They use it to **find** code, never to edit outside their slice — and treat it as read-only + possibly-stale (confirm load-bearing findings against the file). `migration-engineer`, `seed-builder`, and `screen-reconstructor` are excluded (narrow scope / visual fidelity needs no code discovery). **No subagent gets the index-mutating tools** (`index_repository`/`delete_project`): re-indexing is the orchestrator's **single-writer** duty (Law 3) — a **mandatory closure step** of every sweep/wave fold-in (`/build-workflow` step 7 · `/build-wave` Phase 5), plus after any large branch sync, so the graph never lags `main`. If no graph is configured, every agent falls back to Grep/Glob with no loss of behaviour.

**The session ledger (optional — multi-session coordination + the story that survives).** Concurrent Claude Code sessions on one checkout are the single-writer law's blind spot: each believes it is the only writer. When the session-ledger hooks are wired (`templates/SESSION_SETUP.md` — one cross-platform Node implementation, feature-detected, never breaks a session), every session carries a per-session `RUN_STATE` shard: its asks, mode, declared **write-claims**, heartbeat, turn ledger, and stage times. Sessions **see each other** — at `SessionStart` the orientation names every active session and its claims, and a new foreign claim is injected mid-session exactly once — so Law 3 becomes checkable: **before writing a shared board, confirm no active session claims it; two writers on one board is a STOP-and-coordinate, and a claim whose heartbeat has gone stale is expired, never blocking.** Closing work leaves a story in the dated **session journal**: the turn-end gate demands the narrative (`progress-reporting --kind session`: purpose · plan · done-with-evidence · pending · decisions-to-give) **at most once per session** (Law 11), and session end always appends a **mechanical envelope** (asks, diff, boards touched, HEAD movement) so the skeleton survives even a storyless close. `docs/STATUS.md` is regenerated at every turn end — **derived from rows, corpus, and git, stamped with the HEAD it was derived at, never hand-edited** (§10: derived state expires; rows do not). The journal and the shards join the memory set beside the trio, METRICS, and the dated report snapshots.

**Affordance closure (the screen-scope completeness check).** A sweep wires its *path*; a screen accumulates affordances from many paths and from visual-only reconstruction, so off-path and reconstruction-era buttons/links/CTAs/shortcuts become silent stubs that pass every per-path gate. `interaction-auditor` (read-only) closes that gap: at each workflow's interaction-closure step — and as a standalone backlog sweep over the whole built UI — it enumerates **every** interactive affordance, classifies each `Wired | Marked-stub | Unmarked-stub | Mis-wired | Dead-end | Design-gap`, reconciles them against the UIMAP's `action→effect`, and risk-tags every gap. It edits nothing; the orchestrator **rules the gate** — auto-remediating low-risk + trivially-constructable rows through the builders (or a visible "preview · not saved" marker) and **asking the human** (choices) on medium/high-risk rows — and is the single writer of the `INTERACTION_REGISTRY` board. This makes the `functional fidelity` invariant enforceable at **screen** scope, not just **path** scope.

**Journey-level continuity (the third audit layer).** Continuity is enforced at three scopes, by three actors, and the boundaries are strict: the **continuity invariants** (`CLAUDE.md §6`) are per-screen rules every builder honors; **`journey-auditor`** audits the **prototype** at journey scope — the gaps that live *between* screens (missing pick-before-work queues, dead/legacy/context-losing edges, absent handoff receivers, missing states/exceptions/artifacts) — dispatched per journey by **`/journey-audit`** (or run in the design tool via the `journey-continuity-audit` skill's `CONSOLE_PROMPT.md`); **`edge-auditor`** audits the **prototype** at affordance scope — every element that promises an action it doesn't perform (toast-only lifecycle/creation CTAs, placeholder handlers), dispatched per module by **`/edge-audit`** with the `dead-edge-audit` skill's two-axis taxonomy and its § Accepted toasts exceptions ledger; and **`interaction-auditor`** audits the **built UI** at affordance scope (sharing that taxonomy's remediation classes and ledger). The four cells are orthogonal — journey scope classifies destinations, affordance scope classifies handler behavior — and each audit cross-files findings that belong to a neighbor instead of absorbing them. The journey audit is also the **phase-1 exit gate** (zero S1 gaps on the golden journeys) and re-runs after every design batch, because filling gaps creates new seams. Its output routes through the design loop like any other demand: missing screens → the design backlog (→ `/design-build` or the console lane); unbuilt-source rewires → single-writer micro-edits with provenance refresh; deltas touching **built** screens → `design-sync` (drift by definition); **graduated** screens → forward-only remediation on the built side.

**Design-coverage gap discovery.** A sweep's `spec-researcher` runs in the full enrich context — benchmarking comprehensively and filing gaps through C1. The **`/design-help`** command runs `spec-researcher` in **triage mode** over any target (a workflow, a module, or `all` workflows in the project's registry — per `CLAUDE.md`) — **including already-built (✅) workflows** — to surface net-new screen requirements with no prototype coverage and file them to the project's design-backlog board (per `CLAUDE.md`), with a ready-to-send design-tool prompt per entry. It is the design-gap counterpart to the `interaction-auditor` standalone sweep: both are read-only + board-write retroactive audits that can run at any phase without touching build work.

**Closing the design loop (backlog → prototype without the courier).** A filed backlog row's brief (the `design-prompt-authoring` skill's output) is consumed by one of two lanes per `CLAUDE.md §2`'s routing rule. **`/design-build`** dispatches `design-builder` agents in-repo for scaffold-conforming rows — same brief, same model, no console round-trip; the orchestrator (single writer) assembles each row's **journey splice packet** (from the `/journey-audit` GAP or the workflow step chain) so the builder splices both edges — inbound CTA repointed, outbound CTA carrying the subject's context key — wires the entry point + resolver + the upstream repoint (a repoint into a **built** screen's source is drift → `design-sync`), records provenance-at-birth on the registry row, runs the **continuity delta check** (the audit's Phase-0 edge ledger over the affected journey — boards flip only on green), and may **fuse reconstruction** into the same sweep (the sidecar becomes the reconstructor's completeness checklist). **`/promote-design`** ingests a console-lane delivery in one atomic scripted pass (`workflows/promote-design.js`: classify NEW/IDENTICAL/OVERWRITE/UNEXPECTED, hash, sidecar-check, idempotent entry wiring) — an OVERWRITE in a delivery is *drift*, routed to `design-sync`, never silently applied. The division of labor is strict: `design-prompt-authoring` briefs sources that don't exist; `design-builder`/`/promote-design` create + ingest them with known deltas; **`design-sync` triages only what changed outside the pipeline** — and graduated screens (§4) are out of its scope entirely.

**Prototype drift (mid-flight design changes).** When the prototype is updated after screens are built or specified — new screens, new designs, or nudges to existing ones — run **`/design-sync <scope>`** (manually after a re-export, or as a periodic drift sweep): it dispatches the `design-sync` agent and, as single writer, **executes the whole routed plan** end-to-end. The agent diffs the updated prototype against each screen's recorded provenance (`last_synced` + source hash), classifies every screen NEW / MODIFIED / REMOVED / UNCHANGED with its blast radius, and emits a routed re-sync plan the single writer executes — new screens through `reconstruct-sweep`, nudges through the reconstructor's **re-sync mode** (wiring preserved), and contract-affecting changes through `spec-architect` (which also re-enriches the dependent workflows). `design-sync` edits nothing itself; the orchestrator applies the plan and resets the affected registry rows to `◐ resync`. **Adoption ends with a continuity delta check:** the plan flags each drifted screen's journey membership (sidecar `journeys` lookup; inbound-edge counts on removals), and after executing the plan the orchestrator runs `/journey-audit <plan-file>` over the flagged journeys — a MODIFIED screen can silently flip an edge `OK → DEAD-END/WRONG`, a NEW screen can orphan, a removal severs inbound edges — so the drift is not adopted until those ledgers are green (the same gate `/design-build` 6b and `/promote-design` 4b apply to their batches).

**The universal report contract** every agent returns (so integration is programmatic, never text-parsed):

```
Item: <route|module|workflow> | <name>
Status: Done | Blocked
Files changed: [paths]            # own new files + append-only shared file only
Emitted/consumed contracts: [events, query DTOs]   # build agents
Evidence: build=<0 errors?> | tests=<pass?> | assertions=[…] | reference/screenshot=<paths>
Insights: [durable codebase facts → INSIGHTS.md]
Lessons: [correction → Mistake/Trigger/Rule → LESSONS.md]
Blockers: [anything that stopped Done, or design-vs-spec conflicts]
```

---

## 7. Orchestration — the workflow sweep

After the foundation is built by hand, all delivery is a **sweep**: one pass of the pipeline over a single workflow that may span many interdependent modules. The orchestrator is a **thin router** (Law 3) — it sequences, hands each agent explicit context (Law 4), enforces the gates, and is the **single writer** of trackers and cross-module seams.

```mermaid
flowchart TD
  I["Workflow spec + dependency graph"] --> E["Understand & enrich<br/>spec-architect · spec-researcher · UIMAP"]
  E --> H1{{"Human checkpoint 1<br/>approve reconciled spec · resolve design gaps"}}
  H1 --> BS["Build the slice<br/>backend → migration → seed → cross-cut → wire"]
  BS --> G["Automated quality gates<br/>xUnit · contract · Playwright · NetArchTest · visual · a11y"]
  G --> R["Reviewer agent<br/>audit vs constitution → PASS / FAIL"]
  R -- FAIL ×≤2 --> BS
  R -- PASS --> H2{{"Human checkpoint 2<br/>review digest · approve merge"}}
  H2 --> O["Single-writer integration<br/>seams closed · CSS deduped · primitives graduated · PROGRESS"]
```

**Sequence, gates, and human cost:** the amber checkpoints are the **only** two places human attention is required per workflow, and both are front-loaded. Everything else runs unattended. Within "Build the slice", the migration step has its own **gate** (any destructive change stops for approval). On reviewer FAIL, the orchestrator hands the specific finding to the one agent that owns it (a failing contract test → `backend-builder`; a visual diff → `module-wirer`; a missing acceptance criterion → `spec-architect`), capped at two retries, then files the case in the **approval inbox** (Law 11).

**Single-writer integration** (orchestrator only, after PASS): gate-review each structured report; close every cross-module seam the agents surfaced; dedup new design-system classes and **graduate** repeated patterns into primitives; update the registries' Sync state; append the `PROGRESS.md` line; harvest `INSIGHTS`/`LESSONS`.

**Parallelism after foundation — the wave.** A **wave** is a set of ≤N confirmed-disjoint sweeps drawn from the dependency-ordered schedule. One orchestrator session drives the wave through a six-phase lifecycle:

1. **Admission / span re-verify** (hard gate — no fan-out on stale disjointness assumptions): dispatch ≤N `spec-architect` agents concurrently to enrich their specs and emit each sweep's true span `{modules[], addedContractTypes[], touchesSharedKernel}`; run the project's wave-disjointness verifier against the emitted spans; a sweep that widened into conflict is dropped to a later wave and the surviving disjoint set proceeds.

■ **Checkpoint 1** (human): approve all ≤N reconciled specs and delta reports in one session; the single writer folds the approved specs.

2. **Provision worktrees**: create an isolated **git worktree** for each surviving sweep so every build chain operates on its own branch from this point forward.
3. **Staged fan-out** (the build): the orchestrator drives ≤N build chains **stage by stage** (backend → migration → seed → cross-cut → wire) — one stage-barrier at a time, each sweep in its own worktree; the slowest-of-N paces each stage. A sweep that fails or blocks is **parked** (filed to the approval inbox; the rest continue); failure is isolated, not propagated.
4. **Per-sweep automated gates** (concurrent, in each worktree): `test-engineer` + the project's preflight gate + `interaction-auditor` + `reviewer` → PASS per sweep; FAIL routes to the owning agent, capped at two retries, then parked (Law 11).
5. **Cross-sweep wave-review**: a fresh `wave-reviewer` opus agent audits the **combined union diff** across surviving branches — duplicate design-system classes (graduation candidates), Contracts append collisions, duplicated cross-cutting behaviours, and intra-wave seam interference. Read-only; structured findings feed the checkpoint 2 digest.

■ **Checkpoint 2** (human): review the wave digest (per-sweep evidence + wave-reviewer findings) and approve the merge in one session.

6. **Single-writer serial fold-in with integration gate**: fold surviving branches into the main branch **one at a time** (contract-emitters first); after each fold, re-run the project's preflight check on the combined tree — a non-zero exit means cross-sweep interference and is fixed-in-place (capped) or reverted-and-parked before the next fold; **never fold onto a failing tree**. After the last fold, run the project's migrate-all + seed-all integration test before closing the wave.

The per-stage primitives remain the proven width-1 mechanics: a **semaphore** caps total concurrency, a **per-module seed gate** orders shared-declaration creation, every worker is **isolated** (own worktree / own output dir), the shared stylesheet is **append-only**, and a shared-tree red build is attributed by **path-attribution** rather than touching siblings. At wave scale, the three safeguards — the span re-verify hard gate, the per-fold integration gate, and the `wave-reviewer` union-diff audit — make batched checkpoints mechanically safe. Width N is rebindable per project; the disjointness rule and the serial fold-in are invariant.

---

## 8. The feedback & governance model

Coordination across the three things that keep shifting — **requirements, design, and test feedback** — is what lets nine narrow agents behave like one team without a human refereeing every collision. Each is a shared store the agents orbit, with a two-way loop.

```mermaid
flowchart TB
  REQ["Requirements<br/><i>specs + acceptance</i>"]
  AG["Agents<br/><i>per workflow sweep</i>"]
  DES["Design<br/><i>reconstructed UI + design system</i>"]
  TST["Test &amp; review<br/><i>results + findings</i>"]
  REQ <-->|"conform · propose (advisory)"| AG
  AG <-->|"preserve fidelity"| DES
  AG <-->|"produce · loop back ×≤2"| TST
```

- **Requirements** is both an input and something the agents improve: builders *conform* to the approved spec, while `spec-researcher`/`spec-architect` *propose* changes upward — kept advisory and human-gated, so the spec sharpens each sweep but never silently.
- **Design** is authoritative and effectively read-only to builders. `module-wirer` preserves it pixel-for-pixel; the enforcement is `test-engineer`'s **visual-regression baseline**, not trust. A genuinely new state the design never drew is **composed from existing design-system primitives and flagged for design review** — never invented freely.
- **Test & review feedback** is the loop that lets quality self-correct unattended: agents *produce* it, the orchestrator routes failures *back* to the owning agent, capped, then escalates.

**Supervision is on the loop, not in it.** The human spends attention at five high-leverage points only — foundation sign-off, each workflow's checkpoint 1 (reconciled spec + design gaps), destructive-migration approval, checkpoint 2 (merge), and reviewer-FAIL escalations. Everything mechanical is enforced by **hooks** (build + lint + tests on stop, blocking on failure) and the reviewer agent. That is the whole answer to "quality without losing nights": designed checkpoints + automated gates + capped autonomy + blast-radius limits + state-in-files. During a long sweep, `.claude/tools/progress.ps1 -Watch` gives a live read of every dispatched subagent (live/done/idle, by task) plus the registry roll-up — watching from the loop without stepping into it. At wave scale, the per-workflow checkpoints 1 and 2 are **batched per wave** — approve the wave's ≤N reconciled specs together at checkpoint 1, approve the wave merge together at checkpoint 2 — so human attention stays at two touchpoints per wave rather than two per sweep.

---

## 9. Quality gates & Definition of Done

Gates are the teeth behind Law 6. They compound across phases.

**Reconstruction gate (phase 2, per screen):** `dotnet build` 0 errors; the captured screen is the *rendered* screen (a browser-error/reconnect page is a FAIL, not evidence); the design-system CSS actually applied (`styleSheets[].cssRules.length > 0`); computed-style assertions match extracted prototype values (brand colour, key px, fonts, radii, active states); reference vs built read 1:1; every bound value renders its **value not the literal** (grep the served HTML); interactivity works over InteractiveServer; any action not yet backed renders a **visible stub marker** (a "preview · not saved" affordance), never a silent toast that implies a real effect. **State coverage — the clause a render check cannot supply:** the screen's design source is enumerated for **every conditional branch and the state key that drives it** (the design tool's conditional construct + its state flags), and the reconstruction reproduces **one branch per key** — or the report names the branch and why it is out of scope. **An unreproduced branch renders as a perfectly clean page**, so build-clean, stylesheet-applied, computed-style, values-not-literals and interactivity all pass on a screen that is missing an entire modal or alternate state; none of them can see an absence. The **branch ledger** (`state key → reproduced | out-of-scope(reason)`, each with its source `file:line`) is part of the reconstruction report, and it — not the screenshot — is what the orchestrator gates on before flipping a registry row to ✅.

**Wiring gate (phase 5, per workflow):** all of the above for touched screens **plus** — handlers carry `[Permission]`; every `BR-*` enforced in the domain; FluentValidation validators registered and exercised; events published through the wrapper; per-module migration applied cleanly; integration tests against real SQL/Mongo/Redis (Testcontainers); a **contract test** for each event/DTO crossing a module boundary; Playwright e2e for the workflow procedure; every list→detail/edit seam opens the *selected* record (asserted: the destination shows the row's identity, not a fixed seed); every mutating CTA proves a **write-path round-trip with VALUE IDENTITY** — edit → save → reload → *the value read back is the value the user entered*, not merely that some value persisted — and the command's payload is asserted to carry the **captured input**, never a literal or a fixture; **no mutating command may be dispatched with a hard-coded fixture, placeholder literal, or freshly-minted identifier in a field the UI appears to capture** (a real write over invented data is strictly worse than an honest stub: it persists fiction into an audit-bearing record); the **affordance ledger** is complete for every touched screen — `interaction-auditor` has dispositioned **every** interactive affordance (button/link/CTA/shortcut/submit) as `wired | marked-stub | ticketed`, with **zero unmarked stubs and zero mis-wired seams** (off-path affordances are accounted for, not just the ones on this sweep's path); **and the ledger extends beyond controls to DISPLAYED VALUES** — every rendered value sourced from a mock/fixture namespace rather than a real read is dispositioned too, because a fabricated value with no control behind it is invisible to a ledger that enumerates only affordances (the recurring shape: one fabricated read-only panel sitting unmarked beside correctly-marked sibling panels on the same screen, seen by no gate at all); **NetArchTest** boundary tests green; axe accessibility clean; reviewer PASS.

**What a gate cannot see (the standing caveat on all of the above).** Every gate here is a *sample* of correctness, and each is blind to whatever it does not enumerate: a gate that samples the **default render** cannot see a branch that was never written; a gate that samples the **boards** cannot see a board that is wrong; a gate that iterates **registry rows** cannot see a surface that has no row. A passing gate is evidence, never proof. Two rules follow. **(1)** When a defect later surfaces *inside a passed gate's stated scope*, the defect is the **gate's** — amend the gate in the same pass that fixes the artifact (Law 6), and record the *mechanical* reason it was blind. **(2)** Completeness is proved against the **corpus**, never against the trackers — the `completeness-sweep` skill is the standing falsification (independently re-derive every number a board asserts; classify every incomplete affordance as reconstruction gap / wiring gap / data-seam / design gap before routing it). Run it at every phase gate and whenever a board claims a phase is complete.

**The gate's evidence outlives its session.** A gate that passes in conversation leaves nothing a later reader can audit, so a phase-exit gate files a **dated snapshot** (`/progress-report --kind gate`) as its evidence artifact: board integrity re-derived, findings classified and routed to their owning boards, and — mandatory on a gate report — the table naming each gate's blind spot and its amendment. Snapshots are **immutable once filed**; a correction files a new snapshot rather than editing an old one, so the record of what was believed *at the time* stays intact. A phase transition approved with no filed snapshot is a self-attestation (Law 6).

**Definition of Done (a workflow is shippable when):** spec reconciled to current design this sweep; all UI states present (loading/empty/error/permission-denied); real data wired through MediatR; cross-module interaction only via contracts; authz + audit enforced on every sensitive write; **the affordance ledger is complete for every touched screen (zero unmarked stubs / mis-wired seams; deferrals ticketed in `INTERACTION_REGISTRY`)**; the full gate green; reviewer PASS; `PROGRESS`/`INSIGHTS`/`LESSONS` updated; the registries' Sync state marked fresh.

**Compliance every module honours** (rebind to the domain; these are Acme's): identity-safety confirmation on sensitive writes; immutable audit (SQL header + Mongo diff, never updated/deleted); break-the-glass with logged, auto-expiring justification; RBAC `{Module}.{Entity}.{Action}`; config-console gating (test enabled *and* disabled states); AI governance (CONFIG-gated, provenance-labelled, persisted, human-in-the-loop capped); irreversible-action safety checks (a forbidden action never overridable, a high-risk one overridable only with logged justification); NFR targets (interactive load < 2 s, search < 500 ms, WCAG 2.1 AA, no sensitive data in logs, TLS 1.3, encryption-at-rest for sensitive columns, audit retention per policy).

**Continuity invariants** (the UI's connective tissue, enforced at wiring): no dead-end state; no orphan screen; a single primary CTA per state; a guarded CTA is **disabled-with-inline-reason**, never hidden or silently allowed; unfinished steps save a resumable draft; every step→step transition has a CTA + destination; **context-carrying seam** — a transition to an entity-scoped screen carries that entity's identity, and an entity-scoped detail/edit screen is **parameterised by its subject** (route param / context bar), never hard-coded to a singleton; **functional fidelity** — every interactive affordance either produces its real effect (mutate / persist / navigate-with-context) or is an **explicitly marked stub**, never a silent no-op.

---

## 10. Institutional memory (the learning loop)

The tracking trio is not bureaucracy — it is how the system compounds and how long autonomous runs stay safe.

- **`PROGRESS.md`** — durable build status + dated activity log (newest first). Written on every verified completion of a feature, screen, migration, or decision. Read at session start to orient.
- **`INSIGHTS.md`** — non-obvious codebase facts and gotchas, with the *why*. Read before working an unfamiliar area; appended whenever an agent discovers something that would save the next run an investigation.
- **`LESSONS.md`** — user corrections and self-caught mistakes as prevention rules, each as **Mistake / Trigger / Rule**. Appended immediately after any correction. Read at session start.
- **`SCREEN_REGISTRY.md`** — the per-route board (☐ → ◐ → ✅), the orchestrator's claim/integrate ledger.
- **`docs/metrics/*.jsonl`** — the **quantitative** memory (the trio's fourth companion — together, the quintet): one append-only JSONL line per sweep/wave/park/flake, written **only by the orchestrator** at integration from the reports it already holds, sharded per run so concurrent sessions never contend (schema: `docs/METRICS_README.md`; reader: `tools/Show-Metrics.ps1`). Qualitative memory says *what we learned*; METRICS says *what actually happens* — the gate-failure Pareto is the ranked prompt-refinement backlog, and Law 12 gains a quantitative graduation trigger: an owning agent holding >40% of retries across 3 consecutive waves earns its skill a trap entry (threshold rebindable per `CLAUDE.md`).
- **`<reports-dir>/YYYY-MM-DD-<kind>.md`** — **dated snapshots** (the fifth companion): the *evidence-level* memory, filed by `/progress-report` per the `progress-reporting` skill. Where the progress log says what happened and metrics say what actually happens, a snapshot says **what was true of the whole build on one date, at `file:line`** — the artifact a sweep's findings survive in once its session ends. **Immutable once filed.**

**Derived state expires; rows do not.** A board's roll-ups, totals, working set, and "next / blocked" prose are *derived* — the part no sweep has a reason to re-read, so they rot silently while the rows beside them stay correct. Recompute them **from the rows** at every integration rather than incrementing by hand, keep row edits and derived-section edits in one atomic write, and date-stamp status prose so its age is legible. The trackers are **evidence, not testimony**: `/construct-help` re-derives their numbers independently and reports any divergence as a **board-integrity finding** before it reports the numbers themselves.

When an insight or lesson proves stable and broadly useful, **graduate it into a hard rule** in `CLAUDE.md`. Worker agents never write the trackers (Law 3) — they return Insights/Lessons in their report, and the single-writer orchestrator records them.

---

## 11. Deployment & operations

- **Environments & migrations:** EF migrations are reviewed artifacts (Law 6 / `migration-engineer`); never auto-apply a destructive migration outside local dev; per-module schemas keep migrations independent. Aspire's AppHost provisions backing services as resources; add each when the first module needs it.
- **Blazor Server scale-out:** Redis backplane + sticky sessions (or a managed SignalR service); right-size circuit memory; load-test the SignalR path (k6/NBomber), not just request throughput; ship the reconnection UX.
- **Observability:** OpenTelemetry through Aspire ServiceDefaults — traces (including Blazor circuit activities), metrics, structured logs (no sensitive data). Health checks on every backing service.
- **Security:** fail-closed authorization; RBAC; immutable audit; break-the-glass; encryption-in-transit (TLS 1.3) and at-rest for sensitive columns; secrets out of source; data-residency honoured for the deployment region.
- **CI/CD:** the wiring gate runs in CI; merges gate on reviewer PASS + green suite + boundary tests; visual-regression baselines and a11y run on every PR; releases are promoted environment-to-environment behind the same gates.

---

## 12. How it all aligns (the through-line)

The reason this works as one system rather than six disconnected stages is that **the same orchestration DNA runs end to end.** Reconstruction (phase 2) and wiring (phase 5) look like different jobs, but they are the *same machine* pointed at different units of work:

| Invariant                    | In reconstruction (phase 2)                            | In wiring (phase 5)                                  |
| ---------------------------- | ------------------------------------------------------ | ---------------------------------------------------- |
| Unit of work                 | one screen                                             | one workflow slice                                   |
| Contract / source of truth   | rendered prototype                                     | current design + reconciled spec                     |
| Single writer                | orchestrator integrates reports                        | orchestrator closes seams + trackers                 |
| Isolated bounded parallelism | per-screen browser/obj dir, append-only CSS, seed gate | per-slice worktree, per-module EF, disjoint-set rule |
| Structured reports           | reconstructor report schema                            | universal report contract                            |
| Gate before Done             | fidelity gate                                          | wiring gate + reviewer                               |
| Blast-radius limit           | touch own screen + append CSS                          | touch own slice + emit contracts                     |
| Memory                       | INSIGHTS/LESSONS/PROGRESS                              | same trio + the registries' Sync state               |

So the flow is continuous: **an idea becomes a PRD; the PRD becomes a designed prototype; the prototype becomes a pixel-faithful UI via parallel reconstructor agents under a single writer; the UI and prototype become reconciled specs; the foundation is laid by hand; then each workflow is swept — its spec reconciled to the live design, its contracts extracted from the screens, its backend built behind the UI without touching a pixel, its quality proven by gates, its seams closed by the single writer — and the same trio of memory files makes every sweep smarter than the last, all the way to a gated deployment.** Human attention is spent only where judgment is irreplaceable; the architecture does the rest.

---

*Companions: `PROMPT_TEMPLATES.md` (system + phase prompts) · `agents/*.md` (drop-in subagents) · `commands/*.md` (orchestrator commands). Reference implementation: Acme.*
