# CLAUDE.md

This file guides Claude Code in this repository. It is the **project-specific binding contract**; the cross-project method is `CONSTITUTION.md` (read it first — its twelve laws govern everything here). Fill every `<…>` placeholder and resolve every `<!-- fill -->` note for this project.

> **North star:** <!-- one sentence: what we are building and the fidelity bar. e.g. "An enterprise <domain> system that is a 1:1, pixel-faithful reproduction of the clickable prototype in `Prototype/` — every screen's layout, density, typography, color, copy, state, and interaction." --> The rendered prototype is the **contract**; when anything (a spec, a screenshot, this file) disagrees with it, **the rendered prototype wins** (Law 1).

---

## 0. Working cadence (Law 3, 4, 12)

- **Subagent-driven by default.** Delegate substantial separable build/research to subagents; keep the main thread for planning, orchestration, integration, and verification. Subagents are stateless — pass each one its spec path(s), design references, prior outputs, and this file's path.
- **Single writer.** Only the orchestrator (main thread) edits the trackers and closes cross-cutting seams. Subagents return structured reports and touch only their own files + append-only shared files.
- **Tracking trio — update on every verified step, never "later":** `docs/PROGRESS.md` (dated status log), `docs/INSIGHTS.md` (non-obvious facts + the why), `docs/LESSONS.md` (Mistake / Trigger / Rule). **Read `PROGRESS.md` + `LESSONS.md` at session start.** Boards: `docs/SCREEN_REGISTRY.md` (per-screen lifecycle), `docs/WORKFLOW_REGISTRY.md` (sweep board).
- When a lesson proves stable, **graduate it into a hard rule in this file.**
- **Quantitative memory (C1):** metrics shards at `docs/metrics/` (single-writer, append-only; schema `docs/METRICS_README.md`; read with `.claude/tools/Show-Metrics.ps1` or `progress.ps1 -Stats`). Retry-graduation threshold: an agent owning > `<40>` % of retries across `<3>` consecutive waves → LESSONS row + a trap entry in its skill. **Contracts surface (A3):** snapshot at `tests/<App>.ArchitectureTests/Contracts.approved.txt` (`.gitattributes eol=lf`); regeneration is orchestrator-only via `.claude/tools/Update-ContractsSnapshot.ps1`; removals are foundation-gated (approval inbox). **Framework governance:** installed kit version + file hashes live in `.claude/KIT_MANIFEST.json`; intentional local kit-file edits are declared in `.claude/KIT_OVERRIDES.txt`; check drift with `/kit-verify` or `.claude/tools/Verify-KitInstall.ps1`.
- **Code discovery is graph-first (optional — code-discovery graph MCP).** <!-- fill if this project indexes its code in a code-discovery graph (e.g. codebase-memory-mcp). DELETE this bullet if not. --> This repo is indexed as graph project **`<graph-project-id>`** <!-- the project id the MCP server assigns -->. For any *code* exploration, reach for the graph tools **before** Grep/Glob — a structural question (who calls X, what handlers a module exposes, which modules emit/consume an event) is far cheaper via the graph than a grep sweep.
  - **Orient → locate → read:** `get_architecture(aspects=['all'])` (its clusters surface the de-facto module seams) → `search_graph(label, name_pattern, file_pattern)` for exact qualified names → `get_code_snippet(qualified_name)` for source. Trace with `trace_path(direction="both")` (outbound-only misses cross-module callers); reserve `query_graph` for multi-hop / event traversal. Run `detect_changes()` to map the working-tree diff to affected symbols + blast radius before a cross-cutting seam edit or a wave fold-in.
  - **Scope + boundaries:** the graph covers `src/` + `tests/` only — the prototype tree and the kit source are excluded via [`.cbmignore`](.cbmignore), so searches stay scoped to real source. Always pass `project="<graph-project-id>"`. Graph tools are **read-only discovery**: they never replace the rendered-prototype fidelity check (Law 1) or the build gates, and Grep/Read stay correct for text, configs, and non-code files.
  - **Who may query (read-only graph tools):** the audit/spec subagents (`reviewer`, `interaction-auditor`, `wave-reviewer`, `spec-architect`, `design-sync`, `spec-researcher`) **and** the build subagents (`backend-builder`, `module-wirer`, `crosscutting-weaver`, `test-engineer`) are granted the **read** graph tools — for boundary/affordance/contract checks and UI→handler matching. Builders use the graph to **find** code, **never to edit outside their own slice** (Law 2/4), and treat it as pre-edit/possibly-stale for anything they just wrote (trust Read/build there). `migration-engineer`, `seed-builder`, and `screen-reconstructor` are intentionally excluded. **No subagent gets the index-mutating tools** (`index_repository`/`delete_project`).
  - **Freshness is an orchestrator-only duty (single-writer) — a mandatory closure step, not a background chore:** the index goes stale the moment code lands on the main branch (a sweep/wave fold-in, or a concurrent session advancing it under you) — **only the orchestrator** re-indexes (`index_repository(mode="full")`) as the **final step of every fold-in** (baked into the `/build-workflow` step 7 and `/build-wave` Phase 5 closure lists — run it there, never defer it) and again after any large branch sync. **Never declare a build "done" on a stale graph.** Subagents treat the graph as possibly-stale and confirm any load-bearing finding against the file.
- **Session ledger (optional — multi-session coordination).** <!-- fill if this project wires the session-ledger hooks (templates/SESSION_SETUP.md). DELETE this bullet if not. --> RUN_STATE shards: **`<docs/runs>`** · session journal: **`<docs/journal>`** · derived status: **`<docs/STATUS.md>`** (generated — never hand-edit) · heartbeat staleness: **`<30>`** min · claim scopes = the board names above. Overrides live in `.claude/session-ledger.config.json`. Before writing any shared board, check the orientation's active-claims list (Law 3); declare your own intent with `node .claude/hooks/session-ledger.js claim <board>`. End-of-session story: `progress-reporting --kind session` into the journal file the Stop gate names.

---

## 1. What this project is

**<App>** — <!-- fill: one paragraph. what it is, the breadth (≈N modules / ≈N screens), the through-line entity if any. -->

**Current state (read before assuming anything exists):** <!-- fill: what is scaffolded vs target. Keep this accurate as the build proceeds. -->

---

## 2. The prototype — visual & UX source of truth (Law 1)

<!-- fill: where the prototype lives and how to render it. -->
- **Location & entry point:** `<Prototype/…>` — <!-- the single authority for what a screen is. How to render it (build step / babel / click-to-navigate); first-load caveats. -->
- **Render it before building/wiring any screen.** Rendered prototype > reconciled spec > screenshot > draft md. A prototype-vs-spec conflict is a **STOP-and-surface**, never a silent decision.
- **Reference screenshots:** <!-- where captured reference shots go; the screenshot caveat (confirm overlaps with getBoundingClientRect, not from an image). -->
- **Companion docs (authoritative):** <!-- fill: the design/continuity brief, the PRD, the design-system README, the Rosetta-Stone reference page+commands pair. List each + what it gives you. -->
- **Design loop (mid-flight net-new screens — bindings for `/design-build` · `/promote-design` · `design-builder` · `design-prompt-authoring` · `contract-sidecar`):**
  - **Boards:** design-backlog `docs/DESIGN_BACKLOG.md` · design-prompts `docs/DESIGN_PROMPTS.md`. <!-- adjust paths if yours differ -->
  - **Prototype file pattern:** `<e.g. proto-screen-*.jsx — one no-build-step file per screen>` · **Entry-point wiring anchor:** <!-- fill: where include lines go, e.g. "the <script src> list in the entry HTML — insert after the last matching line" --> · **Route/step resolver:** <!-- fill: the file + structures a new route registers in (routes list, module map, breadcrumbs, step resolver…) — the orchestrator edits these; promote-design.js only proposes. -->
  - **Contract sidecar:** `<screen-file>.uimap.json` sibling per the `contract-sidecar` skill — required from BOTH lanes (the Global preamble's output contract carries it for the console).
  - **Lane routing rule:** default **in-repo** (`/design-build`) when the row conforms to a named page scaffold, its reference screens exist, and no exploratory iteration is requested; **console** (design tool + `/promote-design`, batched per module-session) for novel visual patterns, a new module's first screens, or wanted canvas iteration. <!-- tighten/loosen per project; the design tool and the repo run the same model — route by need for human canvas iteration, not by generation capability. -->
  - **Sign-off:** `/design-build` renders each screen to `docs/APPROVAL_INBOX/` for human approval before wiring. <!-- set the auto-accept policy here if any (green evidence only). -->
  - **Concurrency:** parallel dispatch cap for agent fan-out `<default 8>`.
  - **Dead-edge audit bindings:** the project's dead-handler tells (grep patterns for its toast/click idioms), the shared utility components, the context-carry navigation pattern, and the accepted-toast policy (who may accept a fire-and-forget; ledger lives in the interaction registry's § Accepted toasts — `docs/INTERACTION_REGISTRY.md` by default). <!-- fill -->
  - **Contract graduation (CONSTITUTION §4):** a wired + reviewer-PASSed screen's contract is the live UI; its prototype source is frozen (registry row `graduated`) and exits drift-sweep scope; changes flow forward-only, redesigns are briefed events with preserve-wiring. <!-- list any screen families opted OUT (prototype stays live). -->

---

## 3. Tech stack (pinned)

<!-- fill the table for this project. Keep it pinned and current. -->

| Layer | Choice |
|---|---|
| Orchestration | `<e.g. .NET Aspire>` |
| UI | `<e.g. Blazor Web App (.NET 10), global InteractiveServer>` |
| Design system | `<e.g. ported tokens, Tailwind v4, in an RCL>` |
| App / API | `<e.g. ASP.NET Core, MediatR (CQRS + in-process event bus), FluentValidation>` |
| Relational | `<e.g. EF Core → SQL Server, per-module schema>` |
| Document store | `<e.g. MongoDB — note bodies, audit diffs, blobs>` |
| Cache / realtime | `<e.g. Redis cache + SignalR backplane>` |
| Search | `<e.g. a typo-tolerant search engine>` |
| Identity | `<e.g. ASP.NET Core Identity, cookie/JWT, MFA>` |
| Integration | `<e.g. the external systems + standards this product integrates with>` |
| AI | `<one governed model service; CONFIG-gated; provenance-labelled; persisted; HITL-capped>` |
| Test | `<e.g. Playwright (.NET) + xUnit + NetArchTest>` |

**Build / run / test commands:** <!-- fill the exact commands for this project. -->

---

## 4. Target architecture (Law 2, 7, 8)

<!-- fill: describe the architecture (e.g. vertical-slice modular monolith composed by a Host). Then the topology — generalized form below; rebind <App>. -->

```
src/
  <App>.SharedKernel/    Frozen primitives. No application logic.
  <App>.Contracts/       Append-only integration events + public DTOs (the ONLY cross-module channel).
  <App>.DesignSystem/    The design-system library (components, styles, assets).
  <App>.Infrastructure/  MediatR behaviours (validation, authorization, audit), EF interceptors, integration.
  <App>.Host/            Composition root; module-discovery loop; global render mode.
  Modules/
    <App>.<Module>/      Vertical slice: Domain/ Application/ Infrastructure/ UI/ <Module>Module.cs (Add<Module>())
tests/
  <App>.ArchitectureTests/   Boundary rules.
  <App>.<Module>.Tests/      Units + e2e.
docs/                        SCREEN_REGISTRY / WORKFLOW_REGISTRY / PROGRESS / INSIGHTS / LESSONS / modules/ / cross-cutting/.
```

**Boundary rules (enforced by architecture tests):**
- A module references only SharedKernel, Contracts, DesignSystem (+ Infrastructure) — **never another module's project.** Cross-module = subscribe to its published **event** or call its public **query DTO**.
- **Self-registration:** each module exposes one `Add<Module>()` (handlers, EF, validators, nav into the registry, permissions); the Host calls them in a loop. No hand-edited central menu/registration.
- **Per-module EF:** separate `DbContext` / schema per module so migrations never collide.

**Application-layer rules:** every request carries `[Permission("<Module>.<Entity>.<Action>")]`/`[NoPermission]` (fail-closed authz); every business rule enforced in the **domain**; events publish through the **notification wrapper**; validators registered in `Add<Module>()`; mutations emit audit (SQL header + document diff).

### The module map

<!-- fill: the module list with codes and the build phases. -->

| Phase | Modules (code) |
|---|---|
| 0–1 Foundation & core | `<…>` |
| 2 … | `<…>` |

**Naming grammar:** <!-- fill: e.g. FR-<X>-NNN · BR-<X>-NNN · EVT-<X>-Name · PERM-<X>-Entity.Action · WF-<X>-NN -->

---

## 5. Design system — the binding visual contract (Law 1)

<!-- fill: the design-system source, the token foundations (brand, neutrals, type, radii, shadows, icons), the voice, the page scaffolds, and the hard prohibitions. This section is the SINGLE answer the wiring + review agents enforce — make it unambiguous (e.g. resolve where UI components live: a design-system RCL vs a Host stylesheet). -->

- **Foundations:** `<brand / neutrals / semantic ramps>` · `<type family + weights>` · `<root scaling>` · `<radii / shadows>` · `<icon set>`.
- **Voice:** <!-- e.g. sentence case everywhere; verb-led CTAs; numbers + units in status lines; no emoji. -->
- **Page scaffolds:** <!-- the fixed set of layouts every page matches. -->
- **Hard prohibitions:** <!-- e.g. no native controls where a DS component exists; modals never dismiss on backdrop click; no inline style for layout; CSS-var syntax rule; reporting-lib-on-screen ban. -->

---

## 6. Continuity — connective tissue is a requirement, not a nicety

Every screen satisfies the continuity invariants: no dead-end state; no orphan screen; a single primary CTA per state; a guarded CTA is **disabled-with-inline-reason** (never hidden, never silently allowed); unfinished steps save a **resumable draft**; every step→step transition has a CTA + destination. <!-- fill: the keystone component (e.g. a persistent context bar) and the priority journeys (J-01/02/03) to build end-to-end first as the continuity proof — for each journey also list its ROLES and expected step chain (the /journey-audit dispatch packet); the golden journeys must audit clean of S1 continuity gaps at the phase-1 gate (PROMPT_TEMPLATES §K). -->

---

## 7. Compliance & cross-cutting (every module honors)

<!-- fill / rebind to the domain. The reference set: -->
- **Identity safety:** every sensitive write confirms two identifiers.
- **Audit:** immutable header (SQL, queryable) + old/new diff (document store); never updated or deleted.
- **Break-the-glass:** restricted records require a logged justification; access auto-expires.
- **RBAC:** `{Module}.{Entity}.{Action}`; effective permissions = union of roles; predefined + custom roles.
- **Config console:** a feature renders/runs only if enabled for the tenant; tests assert enabled AND disabled states.
- **AI governance:** every AI call CONFIG-gated, provenance-labelled, persisted, human-in-the-loop capped (AI never auto-commits a sensitive/irreversible action).
- **Domain safety:** <!-- e.g. mandatory checks before an irreversible action; contraindicated cannot be overridden. -->
- **NFR targets:** <!-- load/latency budgets; accessibility (WCAG 2.1 AA); no sensitive data in logs; TLS; encryption at rest; audit retention. -->

---

## 8. Working principles

1. **Render the prototype/screen first.** Build/wire to what you see; rendered > spec > screenshot. A conflict is STOP-and-surface.
2. **Plan non-trivial work** (3+ steps or architectural impact) before acting. Use the design-system components — never hand-roll one that exists.
3. **Verify before "done."** No self-attested completion; pass the phase gate (`CONSTITUTION.md §9`). A visible mismatch is a defect to fix, not to explain away.
4. **Full fidelity** — adopt the whole screen; an unbacked feature shows full-fidelity mock data + a visible "soon" marker, never silently omitted.
5. **Stay in your module folder;** reach other modules only via their events or public DTOs; register through `Add<Module>()`.
6. **<Domain> correctness outranks convenience.** If a rule here ever blocks correct behaviour, stop and raise it.

---

## Reference map

- **Constitution & kit:** `CONSTITUTION.md` · `SPECIALIZE.md` · `SKILLS.md` · `PROMPT_TEMPLATES.md` · `.claude/agents/*` · `.claude/commands/*` · `.claude/skills/*`.
- **Prototype (visual source of truth):** `<…>`.
- **Boards & memory:** `docs/SCREEN_REGISTRY.md` · `docs/WORKFLOW_REGISTRY.md` · `docs/PROGRESS.md` · `docs/INSIGHTS.md` · `docs/LESSONS.md`.
- **To author as the build proceeds:** `docs/modules/<m>/` (`<X>_MODULE.md`, `<X>_WORKFLOW.md`, `<X>_DB_SCHEMA.md`, `<screen>_UIMAP.md`) · `docs/cross-cutting/` · `docs/design-system/`.
