# Agent Quickstart

A 7-step copy-pasteable curl flow that takes an API agent from
`Bearer nabu_sk_…` + a vision paragraph to a generated screenplay.

Companion: [/llms.txt](https://app.nabu.page/llms.txt) for agent
discoverability; [api-errors.md](api-errors.md) for the error-code catalog.

## Prerequisites

1. Key creation is currently limited to platform admins. Each key acts as the
   account that minted it; workspace ownership alone cannot create keys.
2. An API key with the **`write` scope** plus the **`agent_mode`** and
   **`auto_advance`** capabilities for the full unattended flow.
   `agent_mode` is the one that gates `caller: 'agent'` — `validateAgentParams`
   silently CLAMPS `caller` to `'ui'` without it — and `auto_advance` gates
   `autoAdvance: true`. (`autonomous_write` is a THIRD, separate capability:
   it gates the direct-mutation tools like `update_scene` instead of the
   suggest-then-accept flow. This list used to name it here in place of
   `agent_mode`, which is why a key minted from these instructions could not
   actually run as an agent.) Keys without those caps can still chat AND
   still get through the wizard — since 2026-09-02 the SERVER owns the
   conversation binding and the mechanical PROCESSING chain, so an
   ordinary write-scoped key is no longer stranded. What those caps
   still buy is AUTONOMOUS DECISIONS: picking a pitch and a completion
   mode without asking. Without them the wizard reaches each decision and
   waits for your explicit `POST /wizard/pitch-select` /
   `POST /wizard/completion-mode`.
3. `BILLING_ENABLED=true` workspace OR a granted-credits override.
4. The existing **your own tooling** (`api_access`) entitlement applies to webhook creation
   (Studio, or the admin/alpha catalog override). API-key creation additionally requires the
   platform-admin user role, even for alpha or Studio workspace owners. A non-admin mint
   receives 403 `AUTH_INSUFFICIENT_PERMISSION` before anything is created.

## Step 1 — Create an API key

Keys default to **read-only** when `scopes` is omitted. The console, including the CLI
connection dialog, also starts with **Read only** selected. CLI login and ordinary
reads such as project listing work with that scope; admin reads still require admin
scope and the user role described below; project creation, wizard drive and other writes require an explicit
**Read & write** choice or `"scopes": ["read", "write"]`, as in this writing-agent example.
Existing keys retain their scopes. Scopes are cumulative: `admin` includes `write`
and `read`; `write` includes `read`. An existing admin-scoped key can authenticate
`POST /api/keys` instead of the cookie below, subject to the same workspace
admin/owner and `api_access` checks, plus the platform-admin **user** role.
Key creation is limited to platform admins until credential capture is available
. A key acts as the account that minted it; do not use another
person's key. Existing list/read/revoke access and the published capability enum
remain unchanged.

Capabilities default to `[]` when omitted. The CLI connection dialog preselects
`agent_mode` + `auto_advance`; these do not grant write scope. The
capability contract distinguishes **enforced**
`agent_mode` (`caller: 'agent'`), `auto_advance` (`autoAdvance: true`) and
`autonomous_write` (direct-mutation tools) from **declared but inert**
`dispatch_agents` and `admin`. Dispatch is governed by scope plus billing admission;
platform-admin endpoints require admin scope plus the user's DB role, not the
`admin` capability. Admin routes are not part of the public spec at
`/api/openapi.json`.

```bash
curl -X POST https://app.nabu.page/api/keys \
  -H "Cookie: <your-admin-session-cookie>" \
  -H "Content-Type: application/json" \
  -d '{
    "name": "Production agent",
    "scopes": ["read", "write"],
    "capabilities": ["agent_mode", "autonomous_write", "auto_advance"]
  }'
```

Response includes `plaintext: "nabu_sk_…"` — **shown ONCE only**.
Store it in your secrets manager. From this point on, every request
uses `Authorization: Bearer nabu_sk_…` instead of session cookies.

## Step 2 — Create a project

```bash
curl -X POST https://app.nabu.page/api/projects \
  -H "Authorization: Bearer $NABU_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "title": "Untitled Vision",
    "format": "feature"
  }'
```

Returns `{ id, title, slug, … }`. Save `id` for subsequent calls as
`$PROJECT_ID`.

## Step 3 — Discover project capabilities

```bash
curl https://app.nabu.page/api/projects/$PROJECT_ID/capabilities \
  -H "Authorization: Bearer $NABU_KEY"
```

Returns `capabilities` and `blocked` arrays for the eight existing actions,
plus wizard state/progress and artifact-presence information. `available: true`
means the inspected discovery checks passed; it does **not** reserve credits or
guarantee execution. Every action includes `admission.status: "not_assessed"`
and `uncheckedRequirements` naming what the actual handler still needs to check.
Discovery reads do not dispatch work or perform billing admission.

Each item has `action`, `endpoint`, `method`, `available` and `availability`.
`capabilities` contains `availability: "available"`; `blocked` contains both
`"blocked"` (known denial) and `"unknown"` (not verified), with `reason` and
`remedy`. A read-only key can see the export actions, whose real methods are
**POST** despite requiring only viewer/read access. It cannot gain write access
from discovery. Send a fresh authorized request to the advertised endpoint;
state, permission, body/model validation or admission can still refuse it.

Example excerpt for a read-only caller (representative entries):

```json
{
  "capabilities": [{
    "action": "export_fountain",
    "endpoint": "/api/projects/project_…/export/fountain",
    "method": "POST",
    "available": true,
    "availability": "available",
    "admission": {"status":"not_assessed","uncheckedRequirements":["request_validation","execution_time_checks"]}
  }],
  "blocked": [{
    "action": "chat",
    "endpoint": "/api/projects/project_…/ai/chat",
    "method": "POST",
    "available": false,
    "availability": "blocked",
    "reason": "Editor access with write scope is required",
    "remedy": "Use a credential with project editor access and write scope",
    "admission": {"status":"not_assessed","uncheckedRequirements":["request_validation","execution_time_checks","model_and_credit_admission","agent_parameters"]}
  }]
}
```

**Compatibility correction:** `wizardState` distinguishes `present`,
`absent` and `unreadable`. `currentStage`, `stageIndex`, `progress`, `isLocked`
and `agentAutoAdvance` can now be `null`; raw HTTP clients must handle unknown
state rather than assuming BONES, zero or false. `totalStages` follows the
canonical 14-stage order including `SYNOPSIS_COLLAB`. Artifact values are
`boolean | null`, based on inspected presence rather than completed-stage
history. `null` means unassessed or unreadable (the pitches reader also collapses
absence to null); it is not proof of absence. Presence does not establish semantic
validity. These nullable corrections are compatibility-impacting, not purely
additive. The current CLI does not consume this discovery response at runtime;
its generated API types describe the corrected shape.

## Step 4 — Start the wizard with a vision paragraph

```bash
curl -X POST https://app.nabu.page/api/projects/$PROJECT_ID/ai/chat \
  -H "Authorization: Bearer $NABU_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "message": "Two former best friends, now estranged, reunite in a small town to bury the third member of their childhood trio. The funeral becomes a reckoning. Themes: betrayal, forgiveness, the weight of unspoken truths.",
    "mode": "wizard",
    "caller": "agent",
    "autoAdvance": true
  }'
```

These flags request capability-gated agent behavior; they do not change the reply
into an agent envelope. Chat returns durable job/turn identity as JSON. Follow the
turn stream as described below.

### Optional: `selectionPolicy` for human-in-the-loop agents

By default (`selectionPolicy: "agent"`) the server's auto-advance
orchestrator makes autonomous decisions at three pipeline stages:
`DIRECTION_SELECTION` (auto-picks pitch #0), `TREATMENT_COLLAB`
(auto-finalizes), and `SCENE_GENERATION`/`TREATMENT_EXTRACTION`
(auto-picks completion mode). External fully-autonomous agents should
keep this default.

Send `"selectionPolicy": "human"` when the human is in the loop — e.g.
the `nabu-cli` REPL `/wizard` flow, where the user picks pitches via
the REPL after the orchestrator has dispatched extraction. With this
policy the orchestrator still **dispatches** jobs (extraction →
pitch-generation → direction-selection completes) but **defers
decisions** to explicit HTTP routes: `POST /wizard/pitch-select`,
`POST /wizard/synopsis/finalize`, etc. Added 2026-05-20.

At the Forge decision, read `GET /api/projects/$PROJECT_ID/wizard`. When it carries
`awaitingDecision.kind: "completion-mode"`, POST the chosen `mode` to
`/api/projects/$PROJECT_ID/wizard/completion-mode` with an `X-Idempotency-Key`. Replaying the
standing mode returns 200 without rewriting state. A different mode without `force` returns 409
and names `error.details.selectedCompletionMode`; adopt that winner. Send `force:true` only for a
deliberate restart with a different build scope. A post-commit queue outage returns a saved,
non-replayable 503: keep the same-key response as the receipt, then issue a fresh request/key to
resume the parked handoff. The server reuses its durable job identity, so this does not duplicate
the scene build.

## Step 5 — Follow the durable work

The chat POST returns HTTP 200 JSON, including when `stream: true` was sent.
A coordinator response looks like:

```json
{"jobId":"turn_…","turnId":"turn_…","conversationId":"conv_…","status":"queued","executionBackend":"coordinator","streamType":"turn"}
```

A supported legacy-job response contains `jobId`, `conversationId`,
`executionBackend: "legacy-job"` and `streamType: "turn"`; it does not require
`turnId` or `status`. Replayed coordinator work can report an existing turn's
status. Interaction-resolution responses can also include `responseText` and
`answerPersisted`. These identify admitted work, not a finished assistant reply.
Subscribe to
`GET /api/projects/{id}/ai/turn/{jobId}/stream` for content and terminal control
frames. Use the shared job/operation streams for other durable work.

**Chat returns dispatch identity, then a separate turn stream.** The unwired
server agent-envelope builder and schema are retired. Neither `agent_envelope`
nor `next_actions` is a server response field. The CLI retains its local
`AgentResponseEnvelope` result for compatibility, with empty metadata fields;
do not interpret them as server decisions or a completion signal.

**After the Forge:** a run the Forge completed opens the story MAP.
Read canonical wizard state: at `COMPLETE`, `storyMap` without `handedOffAt`
means the map is open. Read `GET /api/projects/{id}/wizard/story-map` for
sequences, scenes, beat markers, missing beats and Nisaba's ideas
(`?framework=<id>` previews another framework read-only). Use
`POST /api/projects/{id}/wizard/story-map/handoff`
with `{ mapCreatedAt }` from the map read — leave the map and start writing;
idempotent; an earlier map's identity is refused `409 STATE_STALE_CONTENT`. A project
without a map marker has no map to hand off. A `mode: 'wizard'` chat turn at COMPLETE
joins the TREATMENT thread (the map's conversation continues it — send
`treatmentConversationId` from `GET /wizard`, or no id); a different id is
refused `409 STATE_INVALID_TRANSITION` with `details.boundConversationId`.

## Step 6 — Drive the canonical wizard state

Follow [Driving the wizard end to end](#driving-the-wizard-end-to-end-no-browser)
and its `walkToCompletion` reference and stage table: read
`GET /api/projects/{id}/wizard`, apply the action for the current stage, observe
its durable work, then re-read state. Wizard stream events are invalidation hints;
re-fetch state when one arrives. The server dispatches background stages and can
auto-advance, so do not drive a fixed script or wait for `next_actions`.

**You do not have to send `conversationId` at all.** The server binds
the wizard's three chat threads to wizard state itself and returns them
on `GET /api/projects/{id}/wizard` (`conversationId`,
`synopsisConversationId`, `treatmentConversationId`). Sending the id
that state reports is fine; sending a DIFFERENT one is refused with
`409 STATE_INVALID_TRANSITION` and `details.boundConversationId` — the
id to use — rather than quietly forking the transcript. Before
2026-09-02 the binding existed only in the browser, so an API-driven
wizard could never advance past `CONVERSATION`.

## Step 7 — Compile the final screenplay

When canonical `GET /api/projects/{id}/wizard` reports `currentStage: "COMPLETE"`,
check readiness and any open map as described below, then fetch the screenplay:

```bash
curl https://app.nabu.page/api/projects/$PROJECT_ID/screenplay.fountain \
  -H "Authorization: Bearer $NABU_KEY"
```

Returns the compiled Fountain text. Convert to PDF via:

```bash
curl -X POST https://app.nabu.page/api/projects/$PROJECT_ID/pdf \
  -H "Authorization: Bearer $NABU_KEY"
```

## Operations

An **operation** is the durable billing/lifecycle object behind a unit of work
(aggregate fan-outs, single-job kinds). Its id equals the work's root job id —
and stays STABLE across retry attempts, where per-attempt job ids may not.
Three reasons an agent cares:

1. **Resolving an id after a deploy / long gap.** If you've persisted a work id
   and `GET /api/jobs/{id}` returns 404, the id may be an OPERATION id whose
   `jobs` row aged out. The jobs route now FALLS BACK to an operation lookup
   and returns a job-shaped envelope tagged `recordType:"operation"` — so the
   same poll resolves instead of disappearing. You can also read it directly:
   `GET /api/operations/{operationId}` → `{ operation, job, recordType }`.

2. **Cancelling work.** `POST /api/operations/{operationId}/cancel` requests
   cancellation (CAS `status → cancel_requested`). The id may be the canonical
   operation id or the root job id of exactly one live operation (never a run or turn id); the
   response's `operationId` names the canonical operation. Keep the
   same URL when replaying an idempotent request. It is idempotent — send an
   `X-Idempotency-Key` and a retry returns the cached response without
   re-running the CAS. **Kind gate:** cancelling here works only for an
   operation whose KIND is on operation authority. If it is not, you get a
   **409 `STATE_OPERATION_KIND_NOT_CANCELLABLE`** — a fail-loud signal, NOT a
   silent no-op — and you should cancel via the kind's existing surface (e.g.
   `PATCH /api/jobs/{id}`). The 409 tells you the kind failed that gate **now**;
   it is NOT a statement about any environment variable, and there is no single
   "migration" flag to wait on. Authority is decided per kind by the three-way
   `isKindOnOperationAuthority` gate
: a RETIRED kind is
   on operation authority permanently and unconditionally, a FLIPPED kind is
   while the operator has it enabled, and a kind still on legacy authority
   never is. Treat the 409 as "use the other surface for this kind", and
   re-probe rather than waiting on a flag.

3. **Streaming work that survives retries.**
   `GET /api/operations/{operationId}/stream` is the operation-keyed SSE
   sibling of `GET /api/jobs/{jobId}/stream`. The job stream is bound to ONE
   attempt's lifecycle; the operation stream stays open across retries on a
   single connection. Frames carry the same execution fields as job-stream
   frames (`status`/`progress`/`progressMessage`/`meta`/`error`/`result`) plus
   `operation: { id, kind, status }`, `attempt: { attemptNo, progressFloor, … }`,
   and — on the first frame after a retry — `attemptTransition:
   { fromAttemptNo, toAttemptNo }`. **Terminal semantics:** the stream closes
   ⟺ the OPERATION is terminal (`captured` → `completed`, `released`/`failed`
   → `failed`, `cancelled` → `cancelled`). An attempt's failure with retries
   remaining is NOT a terminal frame — do not treat a transient `failed` job
   status seen elsewhere as the operation's end; the operation stream (or
   `GET /api/operations/{operationId}`) is the durable answer. You may pass an
   execution id (job/run id) in the path; it resolves to the canonical
   operation.

## How scene writes land (commit-with-undo, no staging)

When an agent writes a scene through a committed-scene mode — a plain Nisaba `write_scene`, Try Hard, sequence, or the `scene-pipeline` job — **the write COMMITS to canon immediately**. There is no staged-draft holding pen you poll for approval: the content is canonical the instant the tool returns success (or returns `success:false, workLanded:true` when content committed but billing capture failed — that STILL means canon changed; never re-issue the write). The undo/version snapshot is the safety net, not a pending-approval gate. (The draft-SET modes — A/B, Workshop — instead present a compare-and-pick set and commit canon on the director's pick, or on your explicit accept call.)

- **Commit boundary.** Writes go through the semantic `createScene`/`updateScene` mutation boundary; agents never invent a separate "draft" table. A pre-write `nabu_versions` snapshot is taken before canonical bytes change (this is what "deny"/undo restores).
- **Commit evidence (writer-appropriate).** Recovery derives a writer's terminal from durable evidence appropriate to that writer — plain `write_scene` persists a `write_effects` commit-evidence row (`audit_recent_writes` reads this ledger); sequence carries its terminal on `sequence_runs`. A `cancelled:committed-scene` landing is derived only from an AUTHORITATIVE user cancel (`job.status='cancelled'`) plus committed evidence — a tab-close, deploy, or worker crash is NOT a user cancel (the work continues / requeues / redelivers server-side, and recovery settles it to whatever its real terminal is). Read the durable result back rather than assuming; a user-cancelled turn may still have committed the scene.
- **Landing.** The terminal descriptor + landing registry drive where the result surfaces (loud picker for draft SETS, quiet nudge for a single committed write, loud notice for an unrecorded failure). Recover a closed-tab outcome from the durable job/operation result, not from React state.

The "pick one of N" surfaces are the designed draft SETS — A/B and Workshop It (`present_scene_drafts` / `write_scene_ab`), which ride the jobs table, not staged_artifacts. **Accepting a draft-set pick commits canon.** Try Hard is NOT a draft set — it iterates internally and commits ONE canonical scene. Sequence is COMMIT-THEN-REVIEW: `write-scene-callback` commits each scene to canon as written (via `updateScene`) and THEN inserts a `sequence-scene` review marker (the only live staged_artifacts writer-producer post-RDEL) — so the per-scene ratify only APPROVES already-canonical content (deny = undo); it is NOT the commit point.

## Writing scene content

A content write to a scene must say which version of the scene it was based on. `PUT /api/projects/{id}/scenes/{sceneId}`
with `content` (Fountain) or `doc` (ProseMirror) **must** carry `expectedContentVersion`: the `contentVersion` from the
`GET` you applied your change to.

- **No version → refused, nothing written.** 409 `STATE_STALE_CONTENT` with `error.details.reason: "basis-required"`.
  It is never a last-writer-wins fallback.
- **The scene moved since you read it → refused, nothing written.** 409 `STATE_STALE_CONTENT` with
  `error.details { expectedContentVersion, currentContentVersion }`. Someone (the writer, Nisaba, an accepted draft)
  saved after your read; their words stand.
- **Recovery is a re-read, never a resend.** `GET` the scene again, apply your change to the text it returns, and send
  the new `contentVersion`. Copying `currentContentVersion` from the 409 onto the same body overwrites words you never
  read — the protocol cannot stop a client that does that, and the undo history will show it.
- **Each acknowledged save returns the scene's new `contentVersion`.** Use it as the basis of your next write to that
  scene.
- Metadata-only bodies (status, notes, heading, card colour, omitted) need no version.

## Error recovery

Every error response carries:

```json
{
  "error": {
    "code": "AUTH_INVALID_CREDENTIALS",
    "message": "API key revoked or expired",
    "category": "actionRequired",
    "retryable": false,
    "retryAfter": null
  }
}
```

- `category=transient` → retry with exponential backoff.
- `category=permanent` → bug or invariant violation; surface to operator.
- `category=actionRequired` → re-authenticate, get permissions, etc.

See [api-errors.md](api-errors.md) for the full catalog.

### Versioning typed-error recovery

The versioning subsystem throws 3 typed errors. AI agents catching these
should follow the per-class recovery contract:

| Class | nonRetryable | Recovery |
|---|---|---|
| `StaleVersionError` | `false` (recoverable) | Re-fetch latest via `readVersionByIdVia` or the matching scope helper. Recompute the change set against the new base. Retry the CAS write with a fresh `expectedBaseHash`. |
| `VersionContentMismatchError` | **`true`** (deterministic) | Caller's `idempotencyKey` already consumed by DIFFERENT content. Change the key (e.g., include a content fingerprint in construction), or accept the existing version + discard the new write. Retrying with same key + same new content cannot succeed. |
| `OutlineConcurrentModificationError` | `false` (recoverable) | Re-read via `getOutlineWithBaseHash`. Replay semantic intent against new base. Retry `replaceOutline` with the fresh `expectedBaseHash`. |

All 3 classes carry a `_is*` readonly duck-type marker for cross-realm
`instanceof` resilience: `_isStaleVersion`, `_isVersionContentMismatch`,
`_isOutlineConcurrentModification`. Use the marker when the error may
have crossed a Node.js vm or serialization boundary (NATS KV / SQLite
`jobs.error`).

## Rate limits

Each API key is limited per minute at its workspace plan's tier — or at Studio's
if the key's owner is in the alpha cohort.  429 responses carry `Retry-After` headers. The `BILLING_AGENT_BUDGET_EXCEEDED` error
 returns a `retryAfter` aligned to end-of-day UTC.

## Public authentication request sizes

Public JSON bodies have route-owned byte ceilings: `/api/auth/begin` and legacy
`/api/auth/register` **8 KiB**; `/api/auth/login`, `/api/auth/verify-code` and
`/api/invites/request` **4 KiB**; WebAuthn `/api/auth/verify` **16 KiB**. Overflow returns
the existing payload-too-large **413** envelope before JSON parsing. The first five also refuse
before their quota checks; WebAuthn keeps its existing origin/content-type/quota order before
reading. Ordinary request shapes and error codes are unchanged.

## Idempotency

Send `X-Idempotency-Key: <uuid>` on mutating requests. The raw UUID remains the globally
exclusive PostgreSQL key and the operator handle. A versioned hash binds the successful
authenticated user, method, substituted path and canonical body. Two users deliberately sending
the same retained UUID conflict; they do not receive independent namespaces or each other's
payloads. No mutable active-workspace field participates in the binding.

**Rolling deployment limits:** OLD and NEW contend on the same raw primary key.
A legacy hash is incompatible even for the same user's retry; NEW refuses it without adopting,
rewriting or refreshing the row. A simultaneous losing OLD request may answer 409. OLD/OLD
retains the pre-existing cross-user replay hole until OLD handlers retire. Normal NEW commits
also predicate on the reserved request hash, and CAS-loss replay checks the binding. This fences
a late NEW handler against a reclaimed different-hash row, but cannot amend OLD handler SQL
or solve same-hash ABA after operator intervention and expiry. No schema migration or fleet
hold is part of this change; fleet-wide isolation is not claimed during overlap.

Currently wired on:

- `POST /api/projects/{id}/coverage` (bodyless coverage dispatch,: same-key replay uses the existing answer without a second admission; different-key concurrent requests remain subject to the project-mutex-held one-hour dedup)
- `POST /api/jobs` (generic agent dispatch — incl. the scene-write pipeline via `agent: "scene-pipeline"` + `payload.sceneId`; the bespoke `POST …/scenes/{sceneId}/write` route was RETIRED, RS2S 2026-07-17)
- `POST /api/projects/{id}/scenes/batch` (bulk scene create)
- `POST /api/projects/{id}/scenes` (single scene create)
- `POST /api/operations/{operationId}/cancel`
- `POST /api/projects/{id}/ai/chat` (chat/wizard turn — E1. A retry with the same key replays the cached `{jobId, turnId}` instead of minting a second billable turn. The "NATS path only / the dev inline fallback path is unwrapped" caveat retired on 2026-08-20: there is no other path — `EVENT_BUS=nats` is required to boot and the inline fallback is deleted, so every turn on this route is idempotency-wrapped.)
- `POST /api/projects` (project create)
  **A TIMEOUT is an ambiguous failure, not a deterministic one:** the create is bounded (`fetchJsonWithBoundedSettle`, 15 s, covering the BODY read as well as the headers), and a deadline that elapses means the answer was LOST, not that the create was refused — the project may well exist. So a timeout takes the same road as a 5xx: `ambiguous` is set and no failure sentence is authored.
  **AN UNRESOLVED INTENT NEVER ROTATES.** A client key rotates on exactly three things, and "the director pressed again" is not one of them: the BODY changed (a different question), the write LANDED, or the outcome is PROVEN not-landed. An earlier cut armed one grace replay and then minted a fresh key, reasoning that a 5xx is terminal for its key under `cache-5xx` and replaying it forever is a dead end — but a fresh key on an operation whose outcome nobody knows is the duplicate the contract exists to prevent (a Chromium run recorded `K, K, K2`, and `K2` is a second project).

  **…AND A LISTING IS NOT THAT PROOF.** The first answer to that dead end was: read your own list, and rotate when nothing new is in it. That is unsound in exactly the case it is reached in. A create that has not COMMITTED yet reads as an empty list — nothing is there because nothing is there *so far* — so rotating on the emptiness sends a second write at an operation about to land. The reviewer drove it: hold the first POST before commit, expire the client deadline, answer the listing empty, press again → `K` then `K2`, both able to commit.

  **…AND NEITHER IS A STATUS CODE.** The second answer was: rotate once the ROUTE has answered — read from the HTTP status. That is unsound too, because a status does not say WHO answered. A gateway returns `502`/`503`/`504` on its own account, with an HTML body and no idea whether the request ever reached us. The reviewer drove exactly that: hold the create pending, expire the client deadline, answer the ASK with a plain gateway `503`, return an empty listing → `K, K, K2` again, both able to commit.

  **The proof has two halves, and a client only owns one.** FINALITY belongs to the thing that keeps the key — `executeWithIdempotency`'s record — and a client may only claim it from evidence THAT RECORD leaves. `readIdempotencyRecordAnswer` is that rule, written once for every client sender:

  | What the ANSWER carries | What it means for the key | What a client may do |
  |---|---|---|
  | `X-Idempotency-Record: recorded` | the record has a terminal cached answer for K (success, deterministic 4xx, or cached 5xx) | attribute; a recorded 5xx is final for K but is not success |
  | `X-Idempotency-Record: unreserved` | no visible reservation at read time; the original may still reserve later | keep K; confirmation never dispatches; a later explicit retry sends the same K |
  | `X-Idempotency-Record: retryable` | a matching transient row can be reserved again | keep K; a later explicit retry can contend on the existing guarded reservation |
  | legacy `X-Idempotency-Record: not-seen` | an older server observed absence or retryability | normalize to nonfinal `unreserved`; keep K |
  | `X-Idempotency-Record: in-progress` | K exists but is not terminal | keep K; say "still landing"; never rotate |
  | `X-Idempotent-Replay: true` without the newer header | compatibility evidence from an older wrapper that the terminal record answered | treat as `recorded` |
  | a 2xx, a Nabu error envelope, an auth 401, or any gateway/proxy response **without either record marker** | nobody who holds the record spoke; status and body authorship are not record evidence | keep K; ASK; never conclude, never rotate |
  | nothing at all (timeout, network) | the record says nothing | same |

  **Browser abort is not server cancellation.** A handler accepted before the deadline may still reserve after a read observes absence. Only `recorded` (or the legacy replay marker) establishes finality. New markers are conservatively unheard by the older parser; the updated parser treats old `not-seen` as nonfinal. An old client talking to an old server retains the old bug until replaced.

  **So the client ASKS through a read that cannot create.** It sends the same route, key and body with `X-Idempotency-Record-Read: true`. `executeWithIdempotency` inspects K and returns `recorded`, `in-progress`, `unreserved`, or `retryable`; the read never reserves K and never dispatches preflight or the handler. An existing row must match the request hash before any record answer is exposed. `useCreateProject.confirmOutcome(body)` is that ask, and `resolveNotLanded` REFUSES to rotate until the record has returned a final answer, so a surface cannot rotate (or tell a director "nothing was created") on its own guess. ATTRIBUTION stays the caller's half — `/onboarding` snapshots the project ids before the attempt, the dashboard compares its post-failure library re-read against the same snapshot — and it is only consulted once the record is finished. Where nothing can be established the words stay in front of the director and an EDIT is itself a new intent, because the key is bound to the body; server-side the record expires after 24 h.

**Single-scene save.** `PUT /api/projects/{id}/scenes/{sceneId}` accepts optional
`X-Idempotency-Key`: the authenticated principal, substituted path and body bind the key. A replay
returns the recorded response with `X-Idempotent-Replay: true` without another write, version check
or post-commit chain. A stale-version 409 is recorded: re-read the scene, then submit the corrected
edit with a new key. The mutating handler uses `cache-5xx`; only an exact pre-effect refusal marked
replay-safe by its existing producer is retryable. A stranded reservation needs operator recovery,
as above. The browser sends no key and keeps the existing CAS / `epochId` / `saveSeq` lineage path;
a complete exit-belt body still commits if its request signal aborts. Keyed aborted reads refuse
before reservation here (the two sheet routes below are the one exception), and unreadable or malformed
bodies never commit.

**Not wired, by design — full-screenplay editor save.**
`PUT /api/projects/{id}/screenplay` takes no `X-Idempotency-Key`. Its content CAS and optional
`saveSeq` (with `epochId` and the authenticated operator) record the save's lineage in the same
head UPDATE; a later save stands on the head its own earlier save wrote
. This domain recovery avoids a generic reservation
stranded by a deploy. Web-internal; no CLI field.

**Bounded create takeover.** `POST /api/projects` enforces
`PROJECT_CREATE_ACTIVATION_DEADLINE_MS` (120 seconds) at activation, after locking the
idempotency row. The server budget is independent of the browser's wait. Takeover becomes
eligible at that deadline plus the policy's 5-second replica-clock allowance (125 seconds).
Before that bound, a repeated keyed POST answers `409 STATE_ALREADY_IN_PROGRESS` with
`X-Idempotency-Record: in-progress` and `Retry-After` to the bound. A live 17-second create
therefore keeps its reservation and can land. An attempt that reaches activation after its
deadline rolls back and returns a replay-safe 503 (`X-Idempotency-Record: retryable`);
that same key may retry immediately only when replacements are enabled.
While OFF, a repeated POST returns the existing transient error without replacing the reservation.
Unkeyed creates enforce the same activation budget.

With `PROJECT_CREATE_TAKEOVER_ENABLED=1`, at or after the takeover bound, a normal same-key, same-body POST may replace an in-progress
reservation. Its guarded PG update locks the same row as the activation receipt: an activation
already holding that row may finish and the retry replays it; if takeover wins, the old
activation is refused. The persisted `started_at` fences every attempt's settlement. A killed
request can therefore recover with one active project, without a second journal.
`X-Idempotency-Record-Read: true` still only reads (503 after the bound), never takes over.
The clock allowance assumes replica skew below 5 seconds; greater skew affects the takeover
moment, but the row/attempt fence still excludes two activations. Terminal results and generic
`cache-5xx` are unchanged. Other routes retain the operator-only rule below. No new headers or
project response fields. New fenced reservations use `effect-v1:` plus the existing principal/request
hash in `request_hash`. Old binaries cannot match that binding, so their hash-only commits cannot
settle a new generation. A matching pre-upgrade create reservation may be taken over at the same bound by atomically
changing its binding and attempt fence. The old  binary's request-hash commit predicate
then fails and rolls back activation. Completed pre-upgrade answers still replay, and proven
transient failures may retry immediately when the flag is ON. This requires the  atomic activation/receipt
primitive on every overlapping binary; a build predating that primitive is unsupported.
That hash fence does NOT protect against the old operator resolver's key/status-only SQL.

**Resolver-first rollout and rollback floor.** Phase 1: deploy this correction with
`PROJECT_CREATE_TAKEOVER_ENABLED` unset or `0` (default OFF). Fresh creates, the 120-second
activation deadline, effect-v1 binding and all committed response replays remain active.
ALL replacement generations are temporarily blocked: stale in-progress takeover, failed-transient
retry and legacy-binding adoption. Stale in-progress requests require operator resolution
(503 at 125 seconds); a failed-transient POST returns its existing error (or a retry-unavailable
503), preserves the row and remains marked `retryable`. Confirmation reads remain unchanged.
The flag gates replacements, never the activation deadline or request binding. A stopped retry
can resume through the existing client same-key retry after flag activation; there is no automatic
recovery while OFF.
Every web instance and every in-flight resolver owner must be gone from the old code before phase 2.
The exact resolver floor is the `expectedStartedAt` guarded resolver in `ea1fcad9b5`:
`operatorResolvePg` predicates on key, in-progress status AND the inspected `started_at`.
Deploy the default-off correction everywhere; verify no old web instances OR in-flight resolver
owners remain; only THEN set `PROJECT_CREATE_TAKEOVER_ENABLED=1` to enable all replacements, including transient retries. No elapsed process-age
assumption substitutes for that verification. The parent owns deployment and the single activation.
To pause all replacements, unset/set `0` while retaining guarded resolver code. After any replacement
has been admitted, never roll back below the guarded-resolver floor, including while the flag is
OFF: an old resolver can still carry a stale inspection. Other PG/storage rollback floors remain.

### Guarded scene-note recovery

New keyed `suggest-the-move` requests use the existing request/attempt fence for billing admission and every queue/coordinator birth. The pending job and its actual queued 201 receipt co-commit; KV/publish follows commit. A lost answer is reconciled against that receipt or an actual exact job, never an empty listing. Confirmation reads still require project editor authorization and identical principal/method/path/body, but precede mutable scene/plan checks.

A queue-owned failure before any scheduling birth, combined with affirmative admission absence or the existing billing owner's committed/replayed release, may expose `retryable`. The writer retains the original key/body and submits explicitly within the existing 23-hour client reuse bound. Automatic stale takeover stays off. Omission, a5xx, an expired record and an unconfirmed release never permit a new key.

The authenticated operator command is documented in [API commands](admin-manual/operations/api-commands.md#guarded-scene-note-request-resolution--post-apiadminidempotencykeyresolve). It fences the inspected forward generation before compensation and derives its answer from the queue and billing owners. These forward records retain their fence through terminal closure and ordinary cache expiry. Legacy records, including expired ones, are never adopted or cleared by this door. Before deployment, the conductor must establish the exact  source/rollback floor and retirement of overlapping old producer/resolver/write owners; existing storage floors remain. A deployment timestamp alone cannot resolve already-issued legacy SQL. Positive jobs remain recoverable; unresolved legacy requests remain UNKNOWN.

### Caller mental model

For any (key, body-hash) pair the server holds the operation in ONE of
four states. Your retry behavior depends on which one you see:

| State | What it means | Your action |
|---|---|---|
| **terminal — recorded** (`2xx`/`4xx`/`5xx` with `X-Idempotency-Record: recorded`; a replay also carries `X-Idempotent-Replay: true`) | The server record produced and retained this answer. | Treat it as final for this key. A recorded 5xx is not success; only an explicit new-intent choice may rotate. |
| **terminal — expired** (after 24h) | Cached row was reclaimed. Same key + same body acts like a fresh request. | Re-execution is possible; expiry is not proof the original never committed. Reconcile an unresolved outcome first. |
| **active in-progress** (`409 STATE_ALREADY_IN_PROGRESS` + `X-Idempotency-Record: in-progress` + `Retry-After`) | Another concurrent request with the same key is running. | Wait the `Retry-After` interval, then retry with the same key. |
| **stuck in-progress** (`503 STATE_IDEMPOTENT_OPERATION_STATUS_UNKNOWN` + `X-Idempotency-Record: in-progress`) | Prior handler likely crashed mid-mutation. Server doesn't know if work committed. | Generic mutations require operator recovery below. A project-create confirmation may instead retry the same POST/key after its server takeover bound. **Rotating to a fresh key is UNSAFE** while the outcome is unresolved. |

### Specific outcomes (what the wrapper does with your response)

- **2xx** → cached as `completed` and answered with
  `X-Idempotency-Record: recorded`. Same key + same body retry returns the
  cached 2xx with that header plus `X-Idempotent-Replay: true`. Handler does NOT re-run.
- **4xx** → cached as `failed_deterministic` and answered with
  `X-Idempotency-Record: recorded`. Same key + same body retry returns the
  cached 4xx. Saves round-trips on validation errors + AI
  refusals.
- **5xx** → cached as `failed_deterministic` (Stripe-style invariant per
  lucent-scribing-quartz Slice -1 R1 absorption 2026-05-18). A 5xx from
  a mutating route can happen AFTER a side effect committed (scene
  written, billing captured, job dispatched). Auto-retrying would
  double-write. **Same key + same body retry returns the cached 5xx.**
  To attempt the operation again, rotate the key (fresh UUID) — but
  only through an explicit new-intent choice (or a director body edit), never
  merely because the cached response was a failure.

An exact replay-safe 503 marked by its producer is committed as `failed_transient`; after that
commit the wrapper returns `X-Idempotency-Record: retryable`. Keep the same key: the next submit
re-enters the handler. A JSON `retryable:true` alone is not this proof. Wizard operator-held waits
also require `error.details.operatorHeld` (operation id and the owning park’s fixed expiry), and
a response bearing `X-Idempotent-Replay: true` never grants a free wait. Existing CLI envelopes
already allow arbitrary `details`; no CLI command reads this browser-only wait marker or the
record header, and existing status/code/retry semantics remain unchanged.

### Reusing a key with different body

`422 STATE_IDEMPOTENCY_KEY_REUSED_WITH_DIFFERENT_BODY` — the retained request binding
conflicts (user, hash version, method, path or body). No record/replay marker, payload or prior
metadata is exposed. Reconcile the original outcome before starting a new write; an unresolved
operation must not blindly rotate its key. (Body hashing is canonical/property-order
insensitive, so `{a:1,b:2}` and `{b:2,a:1}` hash identically.)

### Stuck-in-progress recovery (`STATUS_UNKNOWN`)

After the 60s grace window, an in-progress row that hasn't been committed
surfaces as `503 STATE_IDEMPOTENT_OPERATION_STATUS_UNKNOWN`. The wrapper
does NOT auto-resolve generic mutations, no matter how long the row has been stuck — the
24h TTL applies only to TERMINAL records.

**Why (except the transaction-fenced create above)**: the server can't safely guess whether the original mutation
committed. Auto-resolving to `completed` could mask a real failure;
auto-resolving to `failed_*` could hide a successful write. So the only
safe path is operator inspection of the downstream system (database,
audit log, billing ledger).

**Rotating the key is UNSAFE in this state.** If the original mutation
committed, a fresh-key retry could double-write. If it didn't commit,
the original key was never the problem. Either way, the right path is:

1. Surface `STATUS_UNKNOWN` to your operator.
2. Operator inspects whether the work committed (e.g., does the scene
   exist? was billing captured?).
3. Operator calls `POST /api/admin/idempotency/{key}/resolve` with
   `{ expectedStartedAt, outcome, responseStatus, responseBody }`, using the `startedAt`
   of the inspected row, to terminal-commit that attempt. A takeover or completion since
   inspection returns 404; inspect the new attempt before trying to resolve it.
4. Your next retry against the same key gets the operator's resolved
   reply via the normal replay path.

### Response-header replay limitation

Replays return the cached body + status code with `Content-Type:
application/json`, `X-Idempotent-Replay: true` and `X-Idempotency-Record:
recorded` ONLY. The record marker also rides fresh terminal responses, so
it alone is not a replay marker; `X-Idempotent-Replay` is. Do NOT rely on
`Location`, `Retry-After`, or any other response header surviving a
replay; reconstruct route-specific headers from the body on each call.
(Corrected 2026-11-06, Rule 7: this paragraph said `Content-Type` +
`X-Idempotent-Replay` only; `executeWithIdempotency` stamps
`X-Idempotency-Record: recorded` on every replay )

### Header format

UUID format (v4/v7), with or without dashes. Malformed keys return 400.
Use a fresh UUID per logical operation; don't reuse keys across
unrelated mutations.

**Character and location sheet saves.** `PUT /api/projects/{id}/characters/{charId}` and
`PATCH /api/projects/{id}/locations/{locationId}` accept the optional key: the identity is the body AND the `If-Match`
it was sent against, `cache-5xx`. The browser's sheet editors send ONE request per save carrying every changed field,
with one key per request: a retry of that exact request replays the first answer and writes nothing; other
words under a used key are `422`. The field `basis` protocol still decides every
fresh request. An agent that edits a sheet keys each distinct edit the same way. **A complete keyed body is read even
when its transport already aborted** (these two routes only): the browser keys every field save, including the one a
closing page sends, and refusing its intact body would leave words that production could save only on one device.
It is safe because the key is in the record: the complete body runs once, and a later copy of the same key and body is
a replay that runs nothing, also after an Undo. A truncated or unreadable body is still refused 400 before the key is
reserved. A field save that meets an import is refused in the wrapper's pre-effect phase, so the same key runs again
once the import is over.

Routes NOT yet wired include these wizard POSTs:
`extract`, `pitch-select`, `path-select` and `complete`.
The bodyless `synopsis/finalize`, `synopsis/drift-check`, `pitch-generate`,
`sensitivity-scan` POST and `treatment/polish` routes replay keyed requests. Their route-level
prerequisite reads and polish quote reads run in preflight; admission, dispatch and writes
retain the default cached-error policy. A polish pricing outage can recover under the same key.
The pitch quote remains inside its mutating cycle owner; its phase split is tracked in.

`POST /wizard/treatment-extract` and `POST /wizard/spine-extract` are wired (over a parked
stage both resume through `/wizard/retry-stage` and answer `resumed: true`). Agents calling an unwired route get
the legacy non-idempotent behavior; retries may double-write.

`POST /api/projects/[id]/ai/plan-scene` accepts the same optional idempotency header
. Retain the key and identical body when recovering a lost response: a
replay returns the original queued job or inline preview without paid work repeating.
Unkeyed calls are separate planning intents. The ordinary binding, concurrent-attempt,
TTL and cached-error rules above apply.
A pricing-authority outage before admission remains retryable under that same key;
a failure after paid effects still follows the cached-error rules.

The cookie-only account exit `POST /api/user/data/workspaces/{id}/transfer` binds the key to the authenticated
owner, substituted workspace path and `{ successorUserId }`. Its role move, notice intent and 200 receipt commit together;
replay returns the original answer without cancelling a customer or moving ownership twice. API keys are refused.

`POST /wizard/synopsis/finalize`, `/wizard/synopsis/drift-check`, `/wizard/pitch-generate`, `/wizard/sensitivity-scan` and `/wizard/treatment/polish` also replay keyed requests. They accept no mutation payload; reuse one `X-Idempotency-Key` per press. A deliberate new run uses a new key.

## Dry-run

Scenes + characters create/update accept `X-Nabu-Dry-Run: true` (Slice
3d, coming). Returns the would-be body + 200 with zero side effects.

## CLI

[nabu-cli](https://github.com/Nabu-Screenwriting/nabu-cli) supports the commands in
its CI-enforced [command matrix](https://github.com/Nabu-Screenwriting/nabu-cli/blob/main/docs/commands.md):
auth/login, chat, projects list/create, wizard status, jobs, operations, admin and
doctor. It has no scene-update, notes or export command; use REST for those.
`wizard status` reads state; the full stage loop below requires REST calls.

---

## Driving the wizard end to end (no browser)

The wizard is fully drivable over HTTP. Everything below is a real route; there
is no browser-only step in the pipeline. The UI adds presentation (cinematics,
the primer overlay, the shimmer) — not authority.

### The loop, not a script

The wizard is a **state machine**, not a fixed sequence. A step can auto-advance
(Nisaba calling `trigger_pitch_round` moves CONVERSATION on by itself), a
processing step can sit for minutes, and one display step can render several
sub-screens. So drive a LOOP: read the current stage, apply that stage's
action, wait for the stage to change, repeat. Every action must be idempotent
with respect to its own stage reappearing.

| Stage | Drive it with | Await |
|---|---|---|
| BONES (FORMAT/SPARK/GENRE/INSTINCTS) | `PATCH /api/projects/{id}/wizard` with `bonesDraft`, then freeze | stage flips to CONVERSATION |
| CONVERSATION | `POST /api/projects/{id}/ai/chat` per message | the returned **job** reaches terminal |
| — advance | `POST /api/projects/{id}/wizard/extract` | gated on a conversation existing server-side |
| PITCH_GENERATION | dispatched for you | `GET /api/projects/{id}/wizard/pitches` |
| DIRECTION | `POST /api/projects/{id}/wizard/pitch-select` | DIRECTION_LOCKED |
| SYNOPSIS | `POST /api/projects/{id}/wizard/synopsis/finalize` | TREATMENT_PROCESSING |
| TREATMENT | `POST /api/projects/{id}/wizard/treatment/finalize` | TREATMENT_EXTRACTION |
| FORGING | `POST /api/projects/{id}/wizard/completion-mode` (`accelerated` / `one-shot` / `empty`) | COMPLETE |
| COMPLETE | `POST /api/projects/{id}/wizard/complete` | project leaves the wizard |

Canonical state is always `GET /api/projects/{id}/wizard`.

### Observe progress on the SHARED stream — never poll a new endpoint

`GET /api/projects/{id}/wizard/stream` is the canonical SSE channel
(`wizard.state.changed`), the same one the browser's `useWizardStateSync`
consumes. Its payload is an **invalidation hint, not state transport**: on a
frame, re-fetch `GET /api/projects/{id}/wizard` for the truth. Long-running
work returns a durable **jobId**; stream it with `GET /api/jobs/{id}/stream` or
the retry-stable `GET /api/operations/{id}/stream`. Adding a bespoke polling
endpoint for work that already has a job or turn violates the AGENT CONTRACT.

### Honour retryable transients

A 429 carrying `"retryable": true` and `retryAfter` is the server telling you to
wait, not a failure:

```json
{"error":{"code":"RATE_LIMIT_TOO_MANY_REQUESTS","category":"transient",
          "retryable":true,"retryAfter":6}}
```

Back off by at least `retryAfter` and retry. An agent that treats this as fatal
cannot distinguish a broken wizard from a busy one — and under any concurrency
this response is expected, not exceptional. Do **not** retry a 4xx that is not
marked retryable; that is a real answer.

### What the wizard owes you when it finishes

A completed wizard is a **setup step** for the rest of Nabu. Before treating a
project as ready, check `GET /api/projects/{id}/readiness` — `available` must
contain `logline`, `synopsis`, `treatment`, `characters`, `outline`, `spine`,
`dna`, `genre`, `bones` and `locked-direction` in **every** completion mode,
including Empty Canvas. Missing entries do not throw; they degrade silently
(an empty context layer, a `blocked` agent), which is exactly why they are
worth asserting.

Two reader traps: `GET /outline` never 404s (it returns `{acts: []}`), and
`GET /spine?optional=1` turns absence into `200 {spine: null}`. Use `/readiness`
for the first and the plain `/spine` for the second. `GET /setup-action` returns
`open-wizard` for a correct zero-scene project, so it is not a completeness
oracle.

### Settings POST retries

Preferences consolidation, filmography credit creation and cookie-authenticated email change
now accept the generic principal-bound K protocol with default cache-5xx. Retry the original
key/body after a lost response. A preferences `200 {success:false,summary:null}` is a recorded
operation with no generated summary, not a successful summary landing. Explicit record reads
remain non-dispatching; only a recorded answer permits deliberate new-operation rotation.

A client retaining a mounted account context may send BOTH optional headers
`X-Nabu-Expected-User-Id` and `X-Nabu-Expected-Workspace-Id` on its mutation and record reads.
The central request-aware session guards compare them to authenticated identity; they never
select credentials. Malformed tuples answer400, mismatches403, without record/replay markers.
Keep K/body on refusal and restore the original context; do not interpret403 as finality.
Headerless clients retain existing behavior. The tuple is not part of requestHash or the raw
UUID namespace, and old servers do not enforce it until upgraded. Independent local admin/page
guards are outside this adoption; exact coverage is in auth-billing.

Temporal Threads reconcile now uses the same optional identity tuple for its retained intent;
its route/schema and legacy headerless behavior are unchanged. Cookie mismatch holds K/body,
and returning to the original identity can replay the original operation. CLI clients retaining
an account context should send the existing tuple; CLI implementation remains tracked in TODO.

**Manual compaction retry.** Retain the exact key/body across uncertainty. An explicit existing record-read may separately discover a bound durable maintenance turn while preserving an earlier cached500 inside `mutation`; it never dispatches. Each explicit `/compact` request permits one same-key mutation after unreserved/retryable, while recorded/in-progress permits discovery only. Only a recorded known no-admission402 permits a subsequent explicit new intent. Scoped browser journal CAS preserves this distinction and prevents late acknowledgements from erasing newer intent.

## Initial framework

Every newly created project already has a framework selected by the deterministic genre/format scorer (Three-Act when nothing is known). An explicit framework change without a spine only changes this choice; it does not create scenes or placements. The existing structure GET exposes the choice and empty beats. Once a spine exists, the same change preserves placements and rebinds the beats. No extra bootstrap call is required to obtain a framework.

**Project-create recovery.** Creates retain the six shared backoff gaps and add one final ten-second gap. Even instant unanswered attempts reach the seventh automatic replay at 129 seconds, after the server activation deadline plus takeover margin (125 seconds). Every replay retains the same key and consumes the same persisted recovery budget; stopped records stay stopped across reloads. Other request surfaces keep their original schedule.

## Scoped note rulings and decision handles

`POST /api/projects/{id}/considerations/{family}/{memberId}/ruling` requires editor access.
`family` is `flag`, `finding` or `note`; the source must be a current machine note that participates
in the notes desk. Send `{"reason":"Intentional time jump. Leave it alone.","scope":{"kind":"claim"}}`.
The server derives the exact claim/passage scope; no client claim fingerprint or actor is accepted.
An explicit thread command uses `{"kind":"thread","threadId":"…","kindOfRuling":"intentional-complete"}`
as its scope. That declares writer intent, not a page payoff; the reason is preserved verbatim.
Optional `X-Idempotency-Key` replays the saved response without a second ruling or event.

`GET /api/projects/{id}/decisions/{handle}` requires viewer access and reads the owner record.
Handles are stable owner ids: `R·<ruling id>`, `D·<incident id>`, `D·suggestion:<id>`,
`P·feeder:<evidence id>`, and `P·<message id>` for the actual visible writer reply. Encode handles
as URL path segments. Each response carries date, source, action, verbatim text where the record
contains it, and recorded attribution; unknown authorship remains unknown. Feeder choices expose
only the recorded choice, never the unqualified thread-attribution hypothesis (Gate E still owns
ranking/advisory use). Suggestion proposal text is context, never quoted as the writer's words.
Bare note decisions are dated context only; only an explicit reasoned claim/thread ruling withholds
future matching notes. The current Notes buttons do not collect a reason. C2 owns `read_ledger` and
C3 owns the later prompt/index and UI wiring; this unit adds no new background work or paid call.
