# BOOTSTRAP — day-zero setup

How to take the Constitution kit from a zip to a running, agent-orchestrated project. The installer scaffolds the **method layer** (the governing docs, the subagents, the orchestrator command, the boards, the memory files, a master `CLAUDE.md`, and the hooks). It does **not** create your code solution — scaffold that with your own stack's tooling (e.g. `dotnet new …`) either before or after.

## Prerequisites
- **Claude Code** installed and authenticated.
- Your stack's SDK/runtime for the build (e.g. the .NET SDK) — only needed once you wire the `verify` hook to real build/test commands.
- A shell: `bash` (macOS/Linux/WSL/git-bash) **or** PowerShell on Windows — either Windows PowerShell 5.1 (`powershell`) or PowerShell 7+ (`pwsh`); the kit's `.ps1` scripts are 5.1-safe.
- **Optional — a code-discovery graph MCP** (e.g. `codebase-memory-mcp`). The kit's audit/spec/build agents are pre-wired to use its **read** tools for cheap structural discovery (who calls X, the cross-module contract surface, UI→handler matching). It is **not required**: without it the agents fall back to Grep/Glob with no loss of behaviour. To enable, install the MCP server, index the repo, fill `<graph-project-id>` in `CLAUDE.md §0` (keep the graph-first bullet), and tune the seeded `.cbmignore`.
- **Optional — Node.js** (`node` on PATH) for the **session ledger** hooks: per-session `RUN_STATE` shards, mutual write-claim visibility across concurrent chat sessions (Law 3), the one-shot end-of-session story gate, journal envelopes, and a derived `docs/STATUS.md` — identical behavior on Windows, macOS, and Linux (see `templates/SESSION_SETUP.md`). Node is Claude Code's own runtime family so it is usually present; absent it the guard launchers exit 0 silently and the capability stays off.

## Install
Unzip the kit, then run the installer pointing at your repo (defaults to the current directory):

**bash**
```bash
cd constitution
./bootstrap.sh /path/to/your-repo        # add --force to overwrite (keeps .bak)
```

**PowerShell (Windows / cross-platform)**
```powershell
cd constitution
./bootstrap.ps1 C:\src\your-repo          # add -Force to overwrite (keeps .bak)
```

The installer is **non-destructive** — existing files are skipped, never clobbered. It is safe to run in a repo that already has a `CLAUDE.md`, a `screen-reconstructor.md`, or local edits; re-running is idempotent.

## What it creates

```
your-repo/
  CLAUDE.md                     <- master template (fill the <...> placeholders)   [skipped if present]
  .cbmignore                    <- optional: code-discovery graph ignore rules (delete if no graph MCP)
  CONSTITUTION.md               <- the governing method
  SPECIALIZE.md                 <- how Claude binds the generic kit from CLAUDE.md
  SKILLS.md                     <- the expertise layer (recommended + project skills)
  PROMPT_TEMPLATES.md           <- system + per-phase prompts
  .claude/
    agents/*.md                 <- build-phase subagents (your screen-reconstructor.md is preserved)
    skills/                     <- drop Anthropic's skills + your authored project skills here (SKILLS.md)
      spec-hardening/SKILL.md   <- shipped: pre-build spec-quality gate
      graduation/SKILL.md       <- shipped: extract duplicated UI markup into a reusable primitive
      design-prompt-authoring/SKILL.md <- shipped: backlog row -> ready-to-send design brief (both lanes)
      contract-sidecar/SKILL.md <- shipped: the machine-readable UIMAP twin emitted at design time
      journey-continuity-audit/  <- shipped: journey-level prototype audit (SKILL.md + CONSOLE_PROMPT.md)
      dead-edge-audit/          <- shipped: per-module affordance honesty (SKILL.md + CONSOLE_PROMPT.md)
    tools/
      progress.ps1              <- live agent/sweep progress watcher (pwsh ... -Watch)
      Show-Metrics.ps1          <- METRICS reader: Pareto / retry leaderboard / medians (item C1)
      Metrics.Tests.ps1 + metrics.fixture.jsonl <- reader self-tests (planted distribution)
      Update-ContractsSnapshot.ps1 <- orchestrator-only Contracts surface regen (item A3)
      ContractsSurface.Tests.ps1 <- detector self-tests (poison diff pair)
      Kit.Tests.ps1             <- THE KIT GATE: runs every *.Tests.ps1 suite + preflight self-tests
      New-KitManifest.ps1 / Verify-KitInstall.ps1 <- installation manifest writer + drift verifier
      Manifest.Tests.ps1 + manifest-fixture-*.txt <- hash-parity + classification drill
      Governance.Tests.ps1      <- version/changelog alignment + inventory + bootstrap completeness
      Compute-WaveSchedule.ps1  <- wave scheduler (graph-coloring; -Render writes WAVE_PLAN.md; status:done spans excluded)
      Verify-WaveDisjoint.ps1   <- pre-fan-out disjointness gate for /build-wave (-Verify; dot-sources the scheduler's rule)
      Schedule.Tests.ps1        <- scheduler self-tests (run standalone; expects PASS 3 waves)
      Verify-WaveDisjoint.Tests.ps1 <- verifier self-tests (reuses the fixture; asserts no rule drift)
      RenderFilter.Tests.ps1    <- status:done active/completed partition self-tests
      spans.fixture.json        <- 6-span test fixture for the scheduler + verifier tests
      PARALLELISM.md            <- how to mine spans.json, run the scheduler, and run the disjointness gate
    workflows/reconstruct-sweep.js <- generic parallel reconstruction sweep (phase 2)
    workflows/promote-design.js <- mechanical ingest of an expected design-tool delivery (dry-run default)
    commands/                   <- orchestrators: build-workflow (one sweep) · build-wave (<=N disjoint sweeps) ·
                                   reconstruct (phase-2 screens) · design-help (gap sweep) ·
                                   design-build (in-repo design lane) · promote-design (console-lane ingest) ·
                                   journey-audit (journey-continuity audit / phase-1 gate) ·
                                   edge-audit (per-module dead-edge audit) ·
                                   design-full-sweep (composite three-altitude audit) ·
                                   construct-help + construct-run (lifecycle)
    settings.json               <- Stop / SubagentStop verify hook
    settings.preflight.example.json <- opt-in: example settings with preflight hooks wired
    settings.session.example.json   <- opt-in: example settings with the session-ledger hooks wired
    hooks/
      verify.sh, verify.ps1     <- gate stubs (tune to your stack)
      oncodeedit.ps1            <- opt-in edit-time gate (PostToolUse hook)
      notify.ps1                <- opt-in turn-end notification hook
      session-ledger.js         <- opt-in session ledger (ONE cross-platform implementation)
      session-hook.sh, session-hook.ps1 <- guard launchers (exit 0 when node is absent)
      preflight/                <- preflight gate harness + generic detectors + optional dotnet-pack
        preflight.ps1           <- core harness (run with -Fast for quick mode)
        Detectors.psm1          <- generic detectors (NonHexGuid, StrayBuildDirs, TrackedCompressedAssets, IgnoreShadowsSource)
        selftests/              <- poison fixtures for generic detector self-tests
        dotnet-pack/            <- optional .NET/EF/Razor/CSS detector pack (auto-loaded when present)
  docs/
    SCREEN_REGISTRY.md          <- generic lifecycle ledger (Claude populates from CLAUDE.md)
    WORKFLOW_REGISTRY.md        <- generic sweep board
    INTERACTION_REGISTRY.md     <- generic affordance-closure board (interaction-auditor writes here)
    DESIGN_BACKLOG.md           <- net-new screens awaiting design (no prototype source)
    DESIGN_PROMPTS.md           <- companion briefs board (both lanes; Global preamble + per-row blocks)
    PROGRESS.md, INSIGHTS.md, LESSONS.md   <- the memory trio
    SESSION_SETUP.md            <- how to wire the session ledger (docs/runs + docs/journal + docs/STATUS.md appear at runtime)
    journal/                    <- dated session stories (narrative + mechanical envelope per session)
    METRICS_README.md + metrics/           <- the quantitative memory (quartet; single-writer JSONL shards)
    NOTIFY_SETUP.md             <- opt-in: how to configure the notification hook
    APPROVAL_INBOX/             <- parked decisions after capped retries
    design-system/              <- author as the build proceeds
```

> If you already have `PROGRESS.md`, `INSIGHTS.md`, `LESSONS.md`, or a registry at the **repo root**, bootstrap detects it and **skips seeding the `docs/` copy** (it prints `skip (root has …)`), so you never end up with duplicates — move the file into `docs/` if you want it tracked there.

## After install — the day-zero sequence
1. **Fill `CLAUDE.md`.** Resolve every `<…>` placeholder and `<!-- fill -->` note: the north star, the prototype location + companions, the pinned stack, the topology, the module map, the naming grammar, the design-system contract (be unambiguous — this is what the wiring + review agents enforce), compliance, and the page scaffolds. This is the single project-specific file the whole kit reads.
2. **Register the agents.** In Claude Code run `/agents` so the dropped-in agent files register immediately (no restart). Version-control the whole `.claude/` tree.
3. **Wire the `verify` hook.** Edit `.claude/hooks/verify.sh` (or `verify.ps1`) with your build + quick-test commands. On Windows-native shells, point the Stop hook command in `.claude/settings.json` at `pwsh -NoProfile -File "$env:CLAUDE_PROJECT_DIR/.claude/hooks/verify.ps1"`. The hook is **non-blocking** by default (feedback, not a trap — Law 11); real gating is the `reviewer` agent + CI. Use exit 2 only if you want a hard block.
4. **Run the lifecycle** (`CONSTITUTION.md §2`, prompts in `PROMPT_TEMPLATES.md`):
   - **Phase 0 Conceive** — produce `PRD.md` (template B).
   - **Phase 1 Design** — design the prototype in Claude Design from the PRD + design system (template C); refine to ~90%.
   - **Phase 2 Reconstruct** — reproduce the prototype 1:1 (your `screen-reconstructor` + reconstruction sweep).
   - **Phase 3 Specify** — author `<X>_MODULE.md` / `<X>_WORKFLOW.md` from the prototype (template E), then ask Claude to **generate `docs/SCREEN_REGISTRY.md` and `docs/WORKFLOW_REGISTRY.md` from `CLAUDE.md`** (it follows the generation contract at the top of each board).
   - **Phase 4 Found** — build the foundation human-in-the-loop (template F): SharedKernel, Contracts, Infrastructure behaviours, design-system extraction, Host, architecture tests.
   - **Phase 5 Build** — `/build-workflow <WorkflowName>`, golden workflow first, then fan out across disjoint module sets.
   - **Phase 6 Harden & deploy** — performance, security, observability, CI/CD behind the same gates.

## Rolling back
Changed your mind during setup? `cleanup.sh` / `cleanup.ps1` undo a bootstrap install. Run them from the kit, pointing at the repo — dry run first, then apply:

```bash
./cleanup.sh /path/to/your-repo            # dry run: shows what it would remove
./cleanup.sh /path/to/your-repo --apply    # performs the rollback
# PowerShell:  ./cleanup.ps1 C:\src\your-repo   (add -Apply to perform)
```

It is **safe**: it removes only files byte-identical to the kit's pristine output, so anything you've edited (a filled-in `CLAUDE.md`, edited registries, your own agents) is kept and reported. If a `--force` install left a `.bak`, the original is restored. Empty directories bootstrap created are removed; directories that still hold your files are left.

## Notes
- The two registries arrive **generic**; Claude fills them from `CLAUDE.md` and the specs — you don't hand-edit the templates between projects, only `CLAUDE.md` changes.
- The single-writer rule holds: only the orchestrator (main thread) edits the boards and memory files; subagents return structured reports.
- To reuse the kit on the next project: copy the `constitution/` folder, run the installer against the new repo, and write a new `CLAUDE.md`. Everything else is project-agnostic.

## Opt-in: preflight hooks (edit-time gate + turn-end gate)

The kit ships two additional hook sources that you can layer on top of the default `verify`-only wiring. They are **advisory by default** — exit 2 blocks only on unambiguous hard findings (e.g. a GUID literal with non-hex characters); Law 11 caps the feedback loop to at most two self-correction retries before a human sees it.

**What the hooks do:**

| Hook | File | Trigger | Blocks on |
|---|---|---|---|
| Edit-time gate | `oncodeedit.ps1` | `PostToolUse` (Edit/Write/MultiEdit) | `NonHexGuid` finding in any `.cs` or `.txt` file |
| Turn-end gate | `.claude/hooks/preflight/preflight.ps1 -Fast` | `Stop` / `SubagentStop` | configured hard detectors (see `.claude/hooks/preflight/`) |
| Session ledger | `session-ledger.js` via `session-hook.{ps1,sh}` | `SessionStart` / `UserPromptSubmit` / `PostToolUse` / `Stop` / `PreCompact` / `SessionEnd` | nothing except the **one-shot** end-of-session story gate (Law 11) — see `templates/SESSION_SETUP.md` + `.claude/settings.session.example.json` |

**To opt in:**

1. Bootstrap already copies `oncodeedit.ps1` into `.claude/hooks/oncodeedit.ps1` — no manual copy needed.
2. Replace (or merge) your `.claude/settings.json` with `templates/settings.preflight.example.json`. It keeps the existing `verify.sh` wiring and adds both preflight hooks.
3. If you use the optional .NET pack detectors (Razor / CSS), add the commented-out switch cases from the EXTENSION POINT block at the top of `oncodeedit.ps1`.

**Detectors-path resolution:** The hook resolves the detectors module automatically — `./preflight/Detectors.psm1` when installed (`.claude/hooks/`), falling back to `../scripts/preflight/Detectors.psm1` when run directly from the kit source during testing. If neither path exists the hook silently exits 0 (never blocks a missing detector install).

## Installation manifest & verify (framework governance)

Bootstrap writes `.claude/KIT_MANIFEST.json` as its **last** act (atomic; provenance at birth): kit version +
a normalized SHA-256 per installed kit file (spec `text-crlf-bom-v1`: BOM stripped, CR dropped for text - so
git `autocrlf` and PS 5.1 editors can never cause false drift). Files are classed `managed` (agents, commands,
skills, tools, hooks, root law docs - must match) or `seeded` (`CLAUDE.md`, `settings.json`, `verify` hooks,
`docs/` boards - copied once, expected to diverge, never flagged). `tools/Verify-KitInstall.ps1` diffs the
install against the manifest (add `-KitSource <kit>` for STALE/CONFLICT detection); intentional local edits are
declared one-per-line in `.claude/KIT_OVERRIDES.txt` and report as OVERRIDE. A `--force`/`-Force` re-install runs
the drift check first and STOPs on undeclared modifications (`-SkipDriftCheck` to override; `.bak` kept).
The housekeep hook installs to `.claude/hooks/housekeep.ps1` with `settings.housekeep.example.json` to merge.
