# PROMPT TEMPLATES

> **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`.
### System-prompt template + per-phase prompts, tuned for Claude, Claude Design, and Claude Code

These are the reusable prompts that drive the lifecycle in `CONSTITUTION.md`. Rebind the `<App>` / domain placeholders per project. Copy a block, fill the angle-bracket fields, paste.

---

## A. The system-prompt template (use as the project persona / `CLAUDE.md` preamble)

> Use this to set the operating contract for any Claude Code session on the project. It is short by design — the detail lives in `CONSTITUTION.md` and `CLAUDE.md`, which the session reads.

```
You are the engineering lead for <App>, a <domain> built as a <stack: e.g. .NET 10 Blazor Aspire modular monolith>. You operate under THE CONSTITUTION (CONSTITUTION.md) and this repo's CLAUDE.md — read both, plus PROGRESS.md and LESSONS.md, at the start of every session.

Operating contract (the twelve laws govern everything):
1. The rendered design is the contract. rendered prototype > reconciled spec > screenshot > draft md. A prototype-vs-spec conflict is STOP-and-surface, never a silent decision.
2. Decouple through contracts — a module never references another module; cross-module needs go through the Contracts project (events / public query DTOs).
3. Single-writer orchestration — the main thread is the only writer of shared trackers and seams; subagents return structured reports and touch only their own files + append-only shared files.
4. Stateless subagents — pass each one the spec path(s), design references, prior output, and the CLAUDE.md path explicitly.
5. Isolated, bounded parallelism — own output dir / browser-port per worker; semaphore cap; per-module seed gate.
6. Gates before Done — no self-attested completion; a visible mismatch is a defect to fix, never to explain away.
7. Blast-radius limits — change your own slice + the contracts you emit; kernel/Contracts/other-module changes need a foundation gate.
8. Self-registration over central edits — Add<Module>(); registry-driven nav; append-only shared stylesheet.
9. Just-in-time spec reconciliation — drafts are inputs; reconcile to the current design at build time; provenance header + the registries' Sync state.
10. Progressive completeness — design-first; research is advisory; adopt only what the slice needs now.
11. Capped autonomy — self-correction loops retry ≤2 then escalate to the approval inbox; human supervision is on the loop, not in it.
12. Institutional memory — record INSIGHTS / LESSONS (Mistake/Trigger/Rule) / PROGRESS; graduate stable lessons into CLAUDE.md rules.

Default to subagent-driven work: keep this main thread for planning, orchestration, integration, and verification. Plan non-trivial work before acting. Verify before "done."
```

---

## B. Phase 0 — Conceive (Claude chat → PRD.md)

```
Act as a product owner + domain expert for <domain>. From the idea below, produce a PRD.md for an enterprise solution.

Idea: <one paragraph>

The PRD must cover, per module: entities, functional requirements (FR-<X>-NNN), workflows (WF-<X>-NN) described step-by-step, business rules (BR-<X>-NNN), domain/integration events (EVT-<X>-Name), permissions (PERM-<X>-Entity.Action), integration points, and cross-cutting/compliance requirements. Mark the module list, the priority journeys to build first, and the non-functional targets (performance, accessibility, security, data residency). Flag every assumption as "> ASSUMPTION — confirm".
```

---

## C. Phase 1 — Design (Claude Design, with PRD + pre-built design system)

```
Using the attached PRD.md and our pre-built design system, design the clickable prototype for <App>.

Constraints: every screen uses ONLY design-system components and tokens — no off-system colours, no hand-rolled controls where a component exists. Match the design system's voice (sentence case, verb-led CTAs, numbers+units in status lines). Build the priority journeys end-to-end first as the continuity proof: <J-01 / J-02 / J-03>. Each screen must satisfy the continuity invariants — single primary CTA per state, guarded CTAs disabled-with-reason, no dead-ends or orphans, resumable drafts, every transition has a CTA + destination. Refine until ~90% of screens are designed, then we export the prototype.
```

---

## D. Phase 2 — Reconstruct (you already run this; included for completeness)

Reconstruction is driven by your existing `screen-reconstructor` agent under the `reconstruct-sweep` orchestrator (single-writer integration, 8-wide isolated parallel, seed-first per module, append-only CSS, isolated CDP browser). Dispatch:

```
/reconstruct <screen>        # one screen from the registry
/reconstruct                 # next ☐ from SCREEN_REGISTRY.md
```

Orchestrator (single writer) per batch: parse `SCREEN_REGISTRY.md` for ☐ rows → select a seed-safe batch (no two seedless screens share a module) → mark each ◐ → run the sweep → gate-review each report → ✅/◐, append `PROGRESS`, dedup the design-system classes in the stylesheet, graduate primitives, close seams.

---

## E. Phase 3 — Specify (author MODULE/WORKFLOW/CLAUDE from the prototype)

```
From the rendered prototype (the contract) and the reconstructed screens for <module/workflow>, author its spec.

<X>_MODULE.md: purpose; entities + persistence placement (SQL vs Mongo); data contracts; business rules (BR-<X>-NNN) enforced in the domain; UI states required (incl. loading/empty/error/permission-denied); dependencies; cross-cutting (roles/PERM, audited actions, cached reads, jobs, SignalR channels, AI steps); acceptance criteria; open questions. Add a provenance header (design source ref, last_synced, source hash). Use the naming grammar. Flag inferred items "> ASSUMPTION — confirm".

<X>_DB_SCHEMA.md: the module's database design of record — tables/collections per entity, columns + types, keys, indexes, constraints, relationships, SQL-vs-document-store placement, encryption-at-rest for sensitive columns, retention. Consistent with the MODULE spec's entities; it is the design migrations must match. Add the provenance header.

<X>_WORKFLOW.md: trigger + actors/roles; modules involved; step-by-step flow naming the module/handler each step hits; data crossing each boundary (→ contracts); failure/edge cases; acceptance criteria.
```

---

## F. Phase 4 — Found (human-in-the-loop foundation)

```
Build the foundation for <App>, human-in-the-loop. Do NOT build feature modules yet.

1. SharedKernel: freeze the primitives (Entity, AggregateRoot, ValueObject, Result, IDomainEvent, IIntegrationEvent, Permission, NavItem, INavRegistry, IModule).
2. Contracts: establish the append-only integration-event + public-DTO surface. Add the surface snapshot test from `templates/ContractsSurfaceTests.cs.template` (+ the PublicApiGenerator package) to ArchitectureTests, then commit the initial `Contracts.approved.txt` via `.claude/tools/Update-ContractsSnapshot.ps1` — on a green tree, before any feature module exists.
3. Infrastructure: the MediatR pipeline behaviours once — ValidationBehavior, fail-closed AuthorizationBehavior (reads [Permission]), AuditBehavior (SQL header + Mongo diff), caching (Redis), exception handling, OpenTelemetry; plus the compliance hooks (two-ID, break-the-glass, config-console, AI governance, irreversible-action safety).
4. DesignSystem extraction: confirm tokens, the component library, layout primitives, and the page scaffolds; stand up the visual-regression baseline.
5. Host: composition root, global InteractiveServer, the module-discovery loop, Aspire ServiceDefaults; wire backing services in AppHost as the first module needs them.
6. ArchitectureTests: NetArchTest boundary rules green.

Stop at a foundation gate: boundary tests pass, app shell renders, behaviours apply uniformly.
```

---

## G. Phase 5 — Build (the workflow sweep)

```
/build-workflow <WorkflowName>
```

This runs the sweep in `commands/build-workflow.md`: spec-architect (reconcile + UIMAP, hard gate) → spec-researcher → **checkpoint 1** → per-module [backend-builder → migration-engineer (gate if destructive) → seed-builder → crosscutting-weaver → module-wirer] → test-engineer → reviewer (FAIL → route to owning agent, ≤2 retries → approval inbox) → **checkpoint 2** → single-writer integration.

Golden-workflow first: pick one workflow that exercises the full stack (real SQL + a Mongo document type + a SignalR update + an audited sensitive write) before scaling out. Then parallelise across workflows that touch **disjoint** module sets.

---

## H. Generic delegation template (how the orchestrator hands context to ANY subagent)

> Because subagents are stateless (Law 4), every delegation must be self-contained. Use this shape:

```
Use the <agent-name> subagent on <module/workflow> "<name>".
Read first: CLAUDE.md · <reconciled spec path> · <UIMAP/related paths>.
Prior outputs to build on: <paths to upstream agents' artifacts/reports>.
Scope: touch ONLY <your module's files> + append-only <shared stylesheet> ; do NOT edit siblings, central files, or trackers.
Parallel context: you are one of up to <N> isolated siblings — use an isolated output dir (obj/_v<slice>/) and an isolated headless Chromium over CDP; never the shared MCP browser; path-attribute a sibling-caused red build.
Return your structured report (Item/Status/Files changed/Contracts/Evidence/Insights/Lessons/Blockers).
```

---

## I. Maximising efficiency in Claude Code

- **Author agents via `/agents`** so they register immediately; version-control the whole `.claude/` tree (auditable history; refine prompts when a run misbehaves).
- **Route models:** Opus for `spec-architect`/`spec-researcher`/`reviewer`; Sonnet for builders; the built-in **Explore** agent (Haiku, read-only) for fast codebase search between stages.
- **Plan mode (Shift+Tab)** for any non-trivial step before files change; keep planning in the main thread (subagents start executing immediately).
- **Hooks** in `.claude/settings.json`: run `dotnet build` + lint + the test suite on stop and **block** completion on failure — guardrails fire even if an agent forgets.
- **Structured-report schemas** make integration programmatic — never text-parse agent output.
- **Single-writer pattern** keeps long autonomous runs safe: workers return reports; the main thread integrates. Pair with **isolated builds** (per-slice output dir), **append-only** shared files, and **path-attribution** for shared-tree red builds.
- **State in files, not chat:** `PROGRESS`/`INSIGHTS`/`LESSONS`/`SCREEN_REGISTRY`/`WORKFLOW_REGISTRY` + the approval inbox. A sweep is resumable and parallelisable because the filesystem is the shared memory.
- **Keep the main context lean:** delegate substantial separable work to subagents; reserve the main thread for planning, orchestration, integration, and verification.

---

## J. Design-backlog screen request (both design lanes)

> Use this template when a design-backlog row (per `CLAUDE.md`'s design-backlog path) is promoted to `◐ In Design`. The filled brief serves **both lanes** unchanged (routing per `CLAUDE.md §2`): the **in-repo lane** hands it to the `design-builder` agent via `/design-build` (scaffold-conforming rows — the default; no console round-trip, provenance + sidecar at birth); the **console lane** sends it to the design tool (Claude Design or equivalent — novel patterns / exploration; batch a module's briefs per session) and ingests the delivery with `/promote-design`. Expected output either way: a new prototype screen file in the project's prototype format **plus its contract sidecar**, then wired into the prototype's entry point and route resolver, and entered in the screen registry as a new `☐` row with born-provenance — ready for reconstruction.
>
> **Don't hand-fill this ad hoc — it is the successive output of every backlog row.** The **`design-prompt-authoring`** skill turns each `☐` design-backlog row into a filled brief in a **design-prompts companion board** (default `DESIGN_PROMPTS.md`, a sibling of the design-backlog board), with a **Global preamble** — the design-system law, page scaffolds, hard prohibitions, continuity invariants, and the output contract — authored once and prepended to every per-row block (so each block stays focused). The same skill fires from `/design-help`, from a sweep's Checkpoint 1 (`/build-workflow` · `/build-wave`), and as a standalone backfill — so the prompt below is emitted by whoever files the row, not produced one-off later.

```
Design new screen: [Screen Name]
App: <App> (<domain>) — <design system per CLAUDE.md>
Module: [module code per CLAUDE.md §module-map]
Scaffold: [scaffold type per CLAUDE.md §page-scaffolds]
Workflow: [WF-XX-NN] — step [N] of [M] in [workflow name]
Trigger: [what CTA / action on the upstream screen leads to this screen]
Purpose: [one sentence — what the user accomplishes here]
Entities shown: [primary data entities and key fields displayed]
Primary CTA: [name → destination screen]
Secondary CTAs: [save draft / cancel / defer / etc.]
Business rules enforced on this screen: [BR-XX-NNN list]
Continuity invariants to satisfy:
  - No dead-end: [which CTA advances the workflow; destination screen]
  - No orphan: [which upstream CTA / worklist row / context bar leads here]
  - Guarded CTAs: [condition → which CTA is visible-but-disabled-with-reason]
  - Draft resumable: [yes / no — where it re-surfaces if the user leaves mid-task]
Journey splice (fill when this screen inserts into a journey — lifted verbatim from the
  /journey-audit GAP row or the workflow step chain):
  - Journey: [J-id] · GAP: [GAP-nn, if audit-originated]
  - Inbound edge: [upstream file · CTA label · current state (dead-end/toast/missing)]
  - Outbound edge: [downstream route · context key the subject travels under]
  - Reuse anchor: [nearest existing screen/pattern named by the audit]
Reference screens (closest layout / scaffold match in existing prototype):
  [list the nearest existing prototype screen files]
Competitive analog (the equivalent screen in the market-leading reference product, per CLAUDE.md):
  [name if known]

Output format: match the project's prototype file pattern per CLAUDE.md
  — the output must be addable to the prototype directory and wirable into the entry point
  and route resolver without a build step.
  Use only design-system tokens and components present in the existing prototype.
  Do not invent new tokens, class names, or component patterns not in the current prototype.
  ALSO deliver the contract sidecar <screen-file>.uimap.json (per the contract-sidecar skill):
  route, entities+fields, every CTA with guard/effect/destination, states, role gates,
  list params — describing exactly what the screen file renders. A delivery without its
  sidecar is incomplete.
```

**After the brief is filled:**
- **In-repo lane:** run `/design-build <DB-id>` — dispatch, sign-off checkpoint, wiring, provenance-at-birth registry row, and board flips are the command's job (optionally `--and-reconstruct` to fuse reconstruction into the same sweep).
- **Console lane:** send preamble + brief(s) to the design tool (batch per module-session); on delivery run `/promote-design <delivery-path> <DB-ids>` — placement, idempotent entry wiring, hashing, sidecar check/backfill, registry rows, and board flips are one atomic pass. Never hand-place files, and never run a drift sweep over an expected delivery.
- Reconstruct via the project's reconstruction command when the next sweep needs the screen; the board flips to `✅ Reconstructed` once the screen-registry row is ✅.

---

## K. Workflow-continuity audit (journey-level prototype audit)

> Screens designed one at a time accumulate gaps that live *between* them — missing queues/worklists (the pick-before-work rule), dead / legacy / context-losing edges, absent handoff receivers, missing states, exceptions, and artifact trails. This audit re-examines the whole prototype as end-to-end **role × journey** traces, reports a severity-ranked gap list, STOPs for approval, and only then fills approved gaps additively.
>
> **Single source:** the full fillable prompt ships with the kit as `.claude/skills/journey-continuity-audit/CONSOLE_PROMPT.md` (method + gap catalog + fill rules); the `journey-continuity-audit` skill carries the routing table. Two venues, one method:
> - **Console venue:** copy `CONSOLE_PROMPT.md`, fill its CONTEXT block (product, roles, journeys, design-language anchors, out-of-scope), paste into the Claude Design session. Ingest any resulting fills with `/promote-design` (an OVERWRITE inside the delivery is drift → `design-sync`).
> - **In-repo venue:** run `/journey-audit <J-id…|golden|all>` — one `journey-auditor` per journey in parallel; the orchestrator routes gaps per the skill's table (missing screens → design backlog → `/design-build` or console lane; unbuilt-source rewires → micro-edit + provenance refresh; BUILT-screen deltas → `design-sync`; graduated → forward-only).
>
> **Gap-row contract** (what every run emits): `GAP-nn | journey | role | from → to | missing/broken | S1–S4 | proposed fix | reuse anchor | touches (unbuilt / BUILT / graduated)`. Severity: S1 blocks the journey · S2 forces a workaround · S3 degrades · S4 polish.
>
> **Phase-1 exit gate:** the prototype is not "done" until the golden journeys audit clean of S1 gaps — a stronger criterion than a screen-count percentage. Re-run after every design batch: filling gaps creates new seams.

---

## L. Dead-edge audit (per-module affordance honesty, prototype side)

> Every interactive element that promises an action it doesn't perform — inventoried by mechanical tells (toast-only · no-handler · placeholder · disabled-without-reason · cross-screen dishonesty), classified on two axes (behavior disposition × remediation class: lifecycle step / creation entry / cross-nav / utility / accepted fire-and-forget), fixed additively, with a **§ Accepted toasts exceptions ledger** so re-runs verify instead of re-litigating. Fills the prototype-side affordance quadrant (`interaction-auditor` owns the built side; `journey-auditor` owns journey scope).
>
> **Single source:** `.claude/skills/dead-edge-audit/CONSOLE_PROMPT.md` (fillable console prompt) + the `dead-edge-audit` skill (taxonomy, fix grammar, routing). Venues: paste into the design tool per module, or run `/edge-audit <module|all>` in-repo.
>
> **The taxonomy law:** every run declares its buckets AND exclusions up front; every re-run includes the prior run's exclusions. A "closed" audit with silent exclusions is how "Add X" ships dead.
>
> **Prevention at birth:** `design-builder` + the design-prompts Global preamble forbid toast-only lifecycle/creation CTAs in new screens (deferral = Marked-stub or declared `notify-sim` in the sidecar) — the audit's steady state is verifying the ledger, not harvesting debt.
