# The Constitution — handbook bundle

**Kit version:** see `KIT_VERSION` (release gate: `tools/Kit.Tests.ps1` must print `KIT GATE: PASS`).

Drop-in kit for design-first, agent-orchestrated enterprise builds with Claude, Claude Design, and Claude Code.

- `CONSTITUTION.md` — the master handbook: twelve laws, the scratch→deployment lifecycle, architecture, source-of-truth & reconciliation, UI-driven contract extraction, the agent model, orchestration, the feedback/governance model, quality gates, institutional memory, deployment, and the alignment through-line. Diagrams are inline (Mermaid).
- `PROMPT_TEMPLATES.md` — system-prompt template + per-phase and orchestration prompts + Claude Code efficiency.
- `SKILLS.md` — the expertise layer: recommended public skills + the project-skill catalog + agent map (`.claude/skills/`).
- `skills/` — ready-made project skills that ship with the kit (install to `.claude/skills/`): `spec-hardening` (pre-build spec-quality gate), `graduation` (duplicated markup → primitive), `design-prompt-authoring` (backlog row → ready-to-send brief, both lanes), `contract-sidecar` (the machine-readable UIMAP twin emitted at design time), `journey-continuity-audit` (journey-level prototype audit + the full console prompt), `dead-edge-audit` (per-module affordance honesty: tells, two-axis taxonomy, exceptions ledger + console prompt), **`completeness-sweep`** (built-vs-claimed falsification: eleven board-integrity checks — arithmetic, corpus-vs-registry, branch coverage, marker census, staleness, backlog charter, measured tests, corpus ground truth, graph freshness, metrics written, kit + contracts drift — plus the four-class gap taxonomy), `progress-reporting` (files the dated snapshot those findings survive in).
- `agents/` — sixteen drop-in subagent definitions for `.claude/agents/` (incl. `design-builder` — the in-repo design lane, `journey-auditor` — journey continuity, `edge-auditor` — prototype affordance honesty).
- `commands/` — the orchestrators for `.claude/commands/`: `build-workflow` · `build-wave` · `reconstruct` · `design-help` · **`design-build`** (in-repo design lane) · **`promote-design`** (console-lane delivery ingest) · **`journey-audit`** (in-repo continuity audit / phase-1 gate) · **`edge-audit`** (per-module dead-edge audit) · **`design-full-sweep`** (composite three-altitude audit) · **`design-sync`** (prototype-drift remediation / full executor) · `construct-help` (now re-derives the trackers' numbers before reporting them) · `construct-run`.
- `tools/progress.ps1` — live agent/sweep progress watcher (installs to `.claude/tools/`). Companions: `Show-Metrics.ps1` (the METRICS quartet reader — gate-failure Pareto, retry leaderboard; item C1) and `Update-ContractsSnapshot.ps1` (orchestrator-only Contracts public-surface snapshot regen; item A3 — the `ContractsSurfaceRewrite` preflight detector guards the snapshot at edit time). Templates: `METRICS_README.md` (event schema) · `ContractsSurfaceTests.cs.template` (the `approved ⊆ generated` ArchitectureTests gate).
- `workflows/` — `reconstruct-sweep.js` (generic parallel screen-reconstruction sweep) + `promote-design.js` (mechanical, idempotent ingest of an expected design-tool delivery; dry-run by default). Install to `.claude/workflows/`.
- **Session ledger** (opt-in, cross-platform) — `templates/session-ledger.js` behind Claude Code hooks, with guard launchers `session-hook.{sh,ps1}`: per-session `RUN_STATE` shards, ask capture, mutual write-claim visibility across concurrent sessions (Law 3), a one-shot end-of-session story gate (`progress-reporting --kind session`), mechanical journal envelopes at close, and a derived `docs/STATUS.md` stamped with the HEAD it was derived at. One Node implementation, identical on Windows/macOS/Linux; wiring in `templates/SESSION_SETUP.md`; self-test via `tools/SessionLedger.Tests.ps1`.
- `bootstrap.sh` / `bootstrap.ps1` — install the kit into a repo · `cleanup.sh` / `cleanup.ps1` — roll it back (safe, dry-run by default).


## Quick start (day-zero)
Unzip, then install into your repo (non-destructive — existing files are skipped):
```bash
cd constitution && ./bootstrap.sh /path/to/your-repo        # or: ./bootstrap.ps1 C:\src\your-repo
# roll back the install (dry run, then --apply):
cd constitution && ./cleanup.sh /path/to/your-repo --apply   # or: ./cleanup.ps1 C:\src\your-repo -Apply
```
Then fill `CLAUDE.md`, run `/agents`, wire `.claude/hooks/verify.*`, and follow `BOOTSTRAP.md` → the lifecycle in `CONSTITUTION.md §2`.

## Bootstrapping a brand-new solution — the zero-knowledge path

You have: a fresh repo containing only your **stack template** (solution/project scaffold) and a
**`Prototype/` folder** of design sources (`.md` exports, one file per screen or journey). You have
never used the kit. Five steps:

1. **Install the method layer.** From your repo root:
   `powershell -NoProfile -File <kit>\bootstrap.ps1` (or `<kit>/bootstrap.sh .`).
   Last line must read `PASS  KIT_MANIFEST.json written (...)` — that manifest is the install's
   birth certificate.
2. **Prove the machinery:** `powershell -NoProfile -File .claude\tools\Kit.Tests.ps1` →
   `KIT GATE: PASS`. Commit everything (`method layer: Constitution kit <KIT_VERSION>`).
3. **Open Claude Code** at the repo root and run `/agents` once so the installed agents register.
4. **Paste the alignment prompt below.** It binds the seeded `CLAUDE.md` to *your* solution and
   seeds the registries from *your* prototype — asking you only what it cannot infer.
5. **Review its batched questions, confirm, commit.** You are now at the start of the lifecycle
   (phase 1/2) with a fully bound method layer.

### The alignment prompt (copy-paste as your first message)

```text
You are the single-writer orchestrator for this repository. This is a brand-new solution:
it contains only a stack template and a Prototype/ folder of design sources. The Constitution
kit's bootstrap has already installed the method layer (.claude/*, CLAUDE.md, docs/ boards,
KIT_MANIFEST.json). Your job in this session is to BIND the method layer to this solution.
Method-layer setup only — write NO production code.

Step 0 — prove before trusting:
- Run: powershell -NoProfile -File .claude/tools/Verify-KitInstall.ps1   (expect all OK)
- Run: powershell -NoProfile -File .claude/tools/Kit.Tests.ps1           (expect KIT GATE: PASS)
- Paste both verdict lines. If either fails, STOP and report; do not bind on a broken install.

Step 1 — inventory (read-only):
- Detect the stack: solution/project files, target framework, test projects, and the EXACT
  build / test / run commands that work here.
- Scan Prototype/ recursively for design source files (.md and any .html exports). For each,
  record: path, screen title (first heading), module hint (folder or filename prefix), and
  outbound links/CTAs to other screens. Present the inventory as a table.
- Never edit .claude/KIT_MANIFEST.json, and do not modify kit machinery under .claude/ —
  it is hash-tracked; drift will be flagged by /kit-verify.

Step 2 — read the law, then bind:
- Read CONSTITUTION.md (twelve laws, phase model) and SPECIALIZE.md (what is rebindable).
- Fill EVERY <...> placeholder in CLAUDE.md: project name, stack + the exact commands from
  step 1, design source root = Prototype/, the module map derived from the inventory,
  design-system prefix, ports/worktree bindings.
- Where a binding cannot be inferred, do NOT guess silently: present ONE batched list of
  proposed values and open questions, wait for my confirmation, then write.

Step 3 — seed the boards from the inventory:
- Generate docs/SCREEN_REGISTRY.md rows (template columns; one row per screen, status "not
  reconstructed", source = its Prototype/ path, module from the map).
- Generate docs/WORKFLOW_REGISTRY.md candidate rows from the CTA/link graph — golden journeys
  first; mark uncertain rows with (?) for my review.
- Append a PROGRESS.md entry: what was bound, what was assumed, what remains open.

Step 4 — report and hand back:
- Output: bindings written, registry row counts, assumptions, open questions, and the
  recommended next step (usually /journey-audit over Prototype/, then the reconstruct sweep;
  foundation — phase 4, human-in-the-loop — before any /build-workflow).

Rules: single writer (only you touch CLAUDE.md and the boards this session); evidence over
claims (paste verdict lines, show diffs); stop-and-ask before anything destructive.
```

**Expected outcome:** two green verdict lines, a filled `CLAUDE.md` with zero `<...>` left, a
screen registry mirroring `Prototype/`, a candidate workflow registry, one PROGRESS entry — and a
short list of questions only a human can answer. If `Prototype/` is empty, say so in the first
line of the prompt and it will route you to phase 0/1 (PRD → design) instead of binding screens.

## Understanding the Constitution in 10 minutes

> The map, not the territory — the binding detail lives in `CONSTITUTION.md`.

**The one sentence that governs everything:** *fidelity and quality are produced by architecture,
not by vigilance* — drift and defects are made either mechanically impossible or automatically
detected, so agents do the heavy lifting while human attention stays bounded (five touchpoints,
on the loop, never in it). Since V2 that sentence applies to the kit itself: the framework is
versioned, self-gating, and its installations are manifest-verified.

### The end-to-end flow (idea → deployment)

```mermaid
flowchart LR
  P0["0 · Conceive<br/>PRD.md"] --> P1["1 · Design<br/>prototype + journey audit"]
  P1 --> P2["2 · Reconstruct<br/>prototype → UI 1:1"]
  P2 --> P3["3 · Specify<br/>MODULE / WORKFLOW / DB_SCHEMA"]
  P3 --> P4["4 · Found<br/>kernel · contracts · infra (by hand)<br/>+ initial Contracts snapshot"]
  P4 --> P5["5 · Build<br/>workflow sweeps wire the backend"]
  P5 --> P6["6 · Harden & deploy"]
  P5 -. "new module / new design" .-> P1
  P5 -. "drift re-sync" .-> P2
```

A module is a unit of *ownership*; a workflow is a unit of *delivery* — modules complete as a
side effect of the workflow sweeps that cross them. Phase gates: PRD coverage (0) → journey audit
clean of S1 on golden journeys (1) → per-screen fidelity gate (2) → provenance-headed specs (3) →
boundary tests + the committed contracts snapshot (4) → per-workflow Definition of Done +
reviewer PASS (5) → NFR targets + release checklist (6).

### The twelve laws (why the machine holds)

```
 1  Rendered design is the contract     rendered prototype > reconciled spec > screenshot > draft
 2  Decouple through contracts          modules touch only events / query DTOs — never each other
 3  Single-writer orchestration         one actor writes trackers, closes seams, appends METRICS
 4  Stateless agents                    fresh context; everything passed in the prompt (+ CLAUDE.md)
 5  Isolated, bounded parallelism       own worktree/port/output; semaphore cap; seed gate first
 6  Gates before "Done"                 no self-attestation — build/visual/tests/reviewer decide
                                        (V2: the kit gates ITSELF the same way — Kit.Tests.ps1)
 7  Blast-radius limits                 own slice + emitted contracts; shared kernel gated harder
 8  Append-only / self-registration    enforced by gates, not reviewed (contracts surface: the
                                        approved ⊆ generated snapshot; a rewrite is a HARD fail)
 9  Just-in-time reconciliation         specs reconciled to the CURRENT design at build time
10  Progressive completeness            design-first; research informs, never overrides
11  Capped autonomy + escalation        retries ≤2, then the approval inbox — never infinite
12  Institutional memory is mandatory   the memory QUARTET: INSIGHTS / LESSONS / PROGRESS +
                                        METRICS (docs/metrics/*.jsonl — gate-failure Pareto,
                                        retry leaderboard; >40% failure ×3 waves ⇒ graduation)
```

### The workflow sweep (phase 5 — one workflow across many modules)

```mermaid
flowchart TD
  I["Workflow spec + dependency graph"] --> E["Enrich<br/>spec-architect · spec-researcher"]
  E --> H1{{"■ Checkpoint 1 (human)<br/>approve reconciled spec · resolve design gaps"}}
  H1 --> BS["Build the slice<br/>backend → migration⟨gate⟩ → seed → cross-cut → wire"]
  BS --> G["Automated gates<br/>xUnit · contract tests · CONTRACTS SURFACE (approved ⊆ generated)<br/>Playwright · NetArchTest · a11y · visual · interaction-closure · preflight"]
  G --> R["reviewer → PASS / FAIL<br/>(a red contracts snapshot = automatic FAIL)"]
  R -- "FAIL ×≤2 → owning agent" --> BS
  R -- PASS --> H2{{"■ Checkpoint 2 (human)<br/>review digest · approve merge"}}
  H2 --> O["Single-writer closure<br/>seams · registries · memory quartet<br/>append METRICS lines · regen contracts snapshot (per wave)"]
```

Waves scale this to ≤N disjoint sweeps with **batched** checkpoints, kept safe by three
safeguards: span re-verify before fan-out, a per-fold integration gate (never fold onto a failing
tree), and the wave-reviewer's union-diff audit. On FAIL the orchestrator routes the *specific
finding* to the one agent that owns it, capped at two retries, then files it in the approval
inbox (Law 11).

### Framework governance (V2 — the kit obeys its own laws)

```mermaid
flowchart LR
  SRC["Kit source tree<br/>KIT_VERSION ⇄ CHANGELOG letter-locked<br/>(Governance.Tests asserts it)"] -->|"bootstrap<br/>(manifest written LAST)"| INST["Installed .claude/* + CLAUDE.md<br/>KIT_MANIFEST.json — normalized SHA-256<br/>per file · classes managed / seeded"]
  SRC --> GATE{{"tools/Kit.Tests.ps1<br/>every *.Tests.ps1 + preflight self-tests<br/>→ KIT GATE: PASS — the release bar"}}
  INST -->|"Verify-KitInstall.ps1 · /kit-verify"| CLS["OK · MODIFIED · OVERRIDE(declared) · MISSING<br/>STALE · CONFLICT · SEEDED(never flagged) · LOCAL(info)"]
  CLS -. "-Force re-bootstrap runs the drift check FIRST<br/>(evidence before overwrite)" .-> SRC
```

Same doctrine, one level down: a screen's truth lives in its hash and sidecar; an *installation's*
truth lives in its manifest, written at birth. Seeded files (`CLAUDE.md`, settings, verify hooks,
boards) are expected to diverge and are never flagged — the alarm-fatigue fix that keeps the tool
alive. Intentional local edits are declared in `.claude/KIT_OVERRIDES.txt` (every audit declares
its exclusions). `/housekeep` sweeps runtime debris under the same single-writer rules.

### Human attention — five points only (on the loop)

```
① Foundation sign-off (phase 4)          ④ Checkpoint 2 — approve the merge (batched per wave)
② Checkpoint 1 — reconciled spec + gaps  ⑤ Reviewer-FAIL escalations (approval inbox)
③ Destructive-migration approval
```

Watch a long sweep live: `pwsh .claude/tools/progress.ps1 -Watch` · quantitative memory:
`pwsh .claude/tools/Show-Metrics.ps1 -Pareto` (or `progress.ps1 -Stats`).

**The through-line:** an idea becomes a PRD; the PRD a journey-clean prototype; the prototype a
pixel-faithful UI under a single writer; UI + prototype become reconciled specs; the foundation
is laid by hand (and commits the first contracts snapshot); then every delivery is a sweep —
spec reconciled to the live design, contracts extracted sidecar-first, backend built behind the
UI without touching a pixel, quality proven by gates, seams closed by the single writer — while
the design loop feeds new screens through two lanes, four orthogonal audits keep continuity
honest, graduation retires prototype twins as wiring lands, the memory quartet makes every sweep
smarter (and now *measurably* smarter) than the last, and the framework itself stays versioned,
self-gating, and manifest-verified all the way down.


## Install into a repo (manual alternative)
1. Keep `CONSTITUTION.md` + `PROMPT_TEMPLATES.md` at the repo root (or `docs/`).
2. Copy `agents/*.md` into `.claude/agents/` (or re-create via `/agents` so they register immediately).
3. Copy `commands/build-workflow.md` into `.claude/commands/`.
4. Your existing `screen-reconstructor.md` + `reconstruct-sweep` and your project `CLAUDE.md` remain authoritative for project specifics; the Constitution generalises and extends them.

Reference example: an enterprise HMS (illustrative) (.NET 10 Blazor Aspire modular monolith).

## The design loop (mid-flight net-new screens)

Backlog rows (screens with no prototype source) flow through **one brief, two lanes** — route by whether the screen needs interactive human canvas iteration, never by generation capability (the design tool and the repo run the same model):

1. `/design-help` (or a sweep's Checkpoint 1) files the row; `design-prompt-authoring` emits its brief in `docs/DESIGN_PROMPTS.md`.
2. **In-repo lane (default for scaffold-conforming rows):** `/design-build <DB-id>` → the `design-builder` agent authors the prototype screen + its **contract sidecar** in-repo → human signs off on the rendered screenshot → the orchestrator wires + records **provenance at birth** → optional `--and-reconstruct` fuses reconstruction into the same sweep. No console round-trip, no drift sweep ever needed.
3. **Console lane (novel patterns / exploration):** send the briefs to the design tool **batched per module-session** → ingest the delivery with `/promote-design <zip|dir>` (one atomic pass: classify, hash, sidecar-check, idempotent entry wiring, registry + board flips). An expected delivery never needs `design-sync`; an OVERWRITE inside one is routed to it as genuine drift.
4. **Contract graduation:** once a screen is wired + reviewer-PASSed, the live UI becomes its contract; the prototype source freezes and exits drift-sweep scope (CONSTITUTION §4).

## Framework governance (the kit governs itself)

The kit applies its own laws to itself. **One tree, one version:** `KIT_VERSION` (`yyyy.MM.dd-<letter>`,
the letter matching the top `CHANGELOG.md` entry - asserted by `tools/Governance.Tests.ps1`); upgrades are
commit series against this tree, never side-car zips. **The kit gate (Law 6, recursively):** `tools/Kit.Tests.ps1`
runs every `*.Tests.ps1` suite in child processes plus the preflight harness self-tests (`preflight.ps1 -SelfTestOnly`)
and prints one verdict - no release, and no accepted upgrade delivery, without `KIT GATE: PASS`. **Provenance at
birth for installations:** bootstrap writes `.claude/KIT_MANIFEST.json` (normalized SHA-256 per installed file,
spec `text-crlf-bom-v1`, classes `managed`/`seeded`) as its LAST act; `tools/Verify-KitInstall.ps1` is design-sync
for installs - OK / MODIFIED / OVERRIDE (declared in `.claude/KIT_OVERRIDES.txt`) / MISSING / STALE / CONFLICT /
SEEDED-never-flagged / LOCAL-info. Report-only by default (Law 11); `-Strict` for CI. A `-Force` re-bootstrap runs
the drift check first so it never silently destroys the evidence it exists to find. `/kit-verify` wraps the tool
and appends the adhoc METRICS line (single-writer: the command, never the tool).
