# API reference

The HTTP API behind the app, the SDKs, the MCP server and the recorder. Every product route is under `/v1`; the base URL in production is `https://api.commitlayer.ai`. This page lists every endpoint by resource, with the request and response shapes as the server sends them. Shapes are written as types, not JSON: `{ id, name?: string, items: Thing[] }` means an object with `id`, an optional `name` and an array of `Thing`.

If you are starting out, the [quickstart](/docs) walks through the five calls that record an action, push the facts and read the verdict. The [action contracts](/docs/action-contracts) reference explains the YAML those calls are judged against.

## Authentication

Two credentials work on every route that needs one:

| Header | Who sends it | Where it comes from |
|---|---|---|
| `X-API-Key: <key>` | Agent runtimes, pipelines, scripts | Settings, API keys. Every plan. A key acts as an **analyst** when its scopes include `actions:record`, `facts:write` or `commitments:write` and as a **viewer** otherwise; the presets (`recorder`, `evidence`, `reader`, `approver`, `full`) are described under [Settings](#api-keys). Role is not the whole rule for a key: a route that records, pushes facts or changes what governs an action also asks for the scope (or, for the last, every scope), as each route says. |
| `Authorization: Bearer <token>` | The web app, the MCP server | A session JWT from `/v1/auth/*`, or an OAuth access token minted for an MCP client. |

An API key sent as `Authorization: Bearer spk_…` is refused with `401 api_key_wrong_header` (`details.supported_header: "X-API-Key"`); the key is never echoed. Routes for a signed-in person only (the guided setup and both samples, attestation and rotation, key management, notifications) answer an API key with `403 session_required` and say so.

The workspace (tenant) is derived from the credential. A write may also name `workspace_id` (and, where it has one, `environment`) to state what the caller believes it writes to: a value that is not the credential's is refused, `403 workspace_mismatch` / `403 environment_mismatch`, before anything is read or written, with the same answer whether or not the named workspace exists (RS-11). This holds on every write of the recording, evidence and approving sides, whether or not the route's body lists the fields (actions, facts, batches, commitments, execution reports, exception assignment, owner, notes, amendments, mappings, re-checks, product-access allocations, drafts, pricing definitions, the samples); it is checked after identity, side, role and scope and before the body is validated, so a body that is also invalid and names another workspace answers `403 workspace_mismatch`. `POST /v1/evidence/batches` and its preflight report the mismatch inside their structured `403 batch_rejected` / `preflight_failed` answer, with every other problem of the request and `written: false`. A key created with `environment` is bound to it; a write that names no environment is in the key's. Roles, lowest to highest: `counterparty`, `viewer`, `analyst`, `admin`, `owner`. Each endpoint below says the role it needs when it is not `viewer`.

## Conventions

- **Lists** accept `?limit=&cursor=` and return `{ items: [...], next_cursor: string | null }`. `next_cursor` is opaque; pass it back as `cursor`; `null` means the last page.
- **Dates** are ISO-8601 UTC strings. **Periods** are months, `YYYY-MM`. **Money** is `{ amount: number, currency: "USD" }`.
- **Verdicts** use one vocabulary everywhere: `VERIFIED | NOT_VERIFIED | UNVERIFIABLE`, under two lenses, `vendor | strict`. The action endpoints (`/v1/actions*`) present the same values with display labels, `PASS | FAIL | UNKNOWN` and `outcome | policy`, and return the raw value beside them as `raw_verdict`.
- **Idempotency.** Recording an action is idempotent on `action_id` (or, when the body has none, on its `Idempotency-Key` header); pushing facts is idempotent on `raw_ref` with `source_revision`. A retried write is safe: the same `action_id` with the same payload answers **`200`** with the stored action and its current verdict and writes nothing (`idempotent_replay: true`, header `Idempotent-Replay: true`); a different payload is `409 conflict` with `details.mismatched_fields`. The same `raw_ref` with the same content is a `duplicate` row (`rejection_reason: "duplicate_fact"`); with different content it is `409 raw_ref_conflict` and nothing of the request is written; a changed provider object is sent with its own `source_revision` and stored as a new observation. `Idempotency-Key` is honoured on `POST /v1/actions`, `POST /v1/settings/api-keys`, the key split and the creation of both samples (`POST /v1/onboarding/refund-sample-runs`, `POST /v1/onboarding/account-change-sample-runs`); elsewhere the natural identity above applies and the header is not read. See idempotency.md.
- **Rate-limit headers.** Every authenticated answer carries `X-RateLimit-Limit`, `X-RateLimit-Remaining`, `X-RateLimit-Reset` (seconds until the bucket is full again) and `X-RateLimit-Bucket` (`requests`, or `writes` on a write route), when limits are enforced.
- **Body limits.** 64 KiB on `/v1/public/*` and `/v1/auth/*`, 50 MiB for multipart uploads, 4 MiB otherwise; a larger body answers `413 payload_too_large` with `details.limit_bytes`.
- **Client address.** The address the edge sets in `X-Real-IP`, never `X-Forwarded-For`. `GET /v1/public/whoami` → `{ ip }` shows it.

## Errors

Every error is `{ error: { code: string, message: string, details?: any } }` with the matching HTTP status. The codes you will meet on any route:

| Status | Code | Meaning |
|---|---|---|
| 400 | `invalid_request`, `invalid_fact`, `disposable_email` and others named per endpoint | The request is malformed or refused; the message says what to change. |
| 401 | `unauthenticated`, `invalid_api_key` | No credential; an unknown or revoked API key (a revoked key gets the same answer as a wrong one). |
| 401 | `api_key_wrong_header` | An API key sent as `Authorization: Bearer`; send it as `X-API-Key`. The key is not echoed. |
| 401 | `invalid_session` | The bearer is not a live session token: revoked by a sign-out, not issued by us, or without a subject. |
| 402 | `entitlement_limit` | A plan limit on features, connections, seats or contracts; `details.upgrade_to` names the tier that lifts it. |
| 402 | `trial_expired` | The trial ended before a payment method was added. `upgrade_to` is the workspace's own plan: the message asks to pay for it or choose another, so do not render it as a demand for a higher tier. |
| 402 | `allowance_exceeded` | Developer only: the monthly allowance and the grace after it (72 hours or 250 actions past it, whichever first) are used up. A new action is not recorded until a plan is chosen; everything recorded keeps settling. Paid plans are never refused: past the allowance, actions run under the plan's per-action overage, reported in the response's `allowance` block and invoiced on the 2nd of the following month as one Stripe invoice item (audit `billing.overage_billed`). |
| 403 | `insufficient_scope`, `source_not_allowed`, `role_above_own`, `own_membership`, `mfa_required`, `blocked` | The credential may not do this. `blocked` is a bot-trap ban on the caller's address (24 hours; a request for a scanner path such as `/.env` sets one). |
| 403 | `session_required`, `person_required`, `performer_cannot_commit` | The operation is a signed-in person's (`session_required`), a named Owner's or Admin's decision no key can make, whatever it holds (`person_required`: accepting an exception), or the approving side's (`performer_cannot_commit`: a key that may record actions sends or assigns a commitment). |
| 403 | `workspace_mismatch`, `environment_mismatch` | The request names a workspace or environment that is not the credential's (RS-11). Nothing was written. |
| 403 | `sample_authorization_not_accepted` | The sample run's token (`X-CommitLayer-Sample-Token`) was sent on a write other than the sample's own action (`POST /v1/actions`) and records (`POST /v1/facts`): an approval, report, assignment, allocation, batch or any other write. It is refused, never ignored, so nothing sent in the sample's name becomes live. Nothing was written. |
| 403 | `separate_attestor_required` | The person who created an evidence key attests it; another Owner or Admin must (`details.handoff`: `ask_admin` or `invite_admin`). |
| 409 | `raw_ref_conflict`, `source_already_attested`, `creator_unknown`, `key_name_taken`, `already_split`, `idempotency_key_reused` | A record reuses a stored `raw_ref` with different content; a source already has a publisher (rotate it instead); a key's creator cannot be proven (replace the key); an active key already has that name; a key was split already; an `Idempotency-Key` was used for another request. |
| 422 | `required_param_missing`, `policy_fixed` | A limited parameter is absent or not a number where the contract does not keep the action unevaluable (`details.missing`); an attempt to switch off the no-self-attestation rule. |
| 404 | `not_found`, `unknown_contract` | No such object. |
| 409 | `conflict`, `already_exists`, `source_served_by_connector` | The write contradicts what is stored; nothing changed. |
| 413 | `payload_too_large` | See body limits above. |
| 422 | `validation_error` | Field errors as `details: [{ type, loc, msg }]`; the input is never echoed. |
| 429 | `rate_limited`, `fair_use_exceeded` | `rate_limited`: the workspace's requests a minute (`requests`: every authenticated call; `writes`: `POST /v1/actions`, `POST /v1/actions/verify`, `POST /v1/facts`, OTLP ingestion) are spent for its plan. `fair_use_exceeded`: a Developer workspace passed its daily cap on recorded actions or pushed facts. Both carry `Retry-After` and `details.retry_after`; nothing was applied. The figures are on `GET /v1/public/pricing` (`tiers[].rate_limits`, `tiers[].fair_use`). |
| 503 | `busy` | Overloaded; the request was **not applied**. `Retry-After: 1`. The write path (`POST /v1/actions`, `POST /v1/facts`, `POST /v1/actions/verify` unless it is a dry run, and the MCP `record_action` tool) admits at most `MAX_CONCURRENT_WRITES` requests at once per API process, and a writer that finds no slot within `WRITE_SLOT_TIMEOUT_SECONDS` gets this answer without touching the database. |
| 429 | `workspace_busy` | This workspace already has its share of the write slots taken on the API process that answered (`details.per_workspace`), by requests of its own that are being written or are waiting for the gate; the request was **not applied**. One workspace may hold every write slot but one, per API process (`MAX_CONCURRENT_WRITES_PER_WORKSPACE` sets another figure), so one workspace's burst always leaves one slot per API process for the other workspaces; their writes beyond that one can still wait and answer `busy`. A one-slot gate has no per-workspace share. Past its share, up to `MAX_WAITING_WRITES_PER_WORKSPACE` more of the workspace's writes per API process (twice `MAX_CONCURRENT_WRITES` unless set) wait for one of its own slots, each for at most `WRITE_SLOT_TIMEOUT_SECONDS`; a wait that runs out, or any write beyond those, gets this answer. `Retry-After: 1` is the soonest a retry is worth sending, not a forecast: while more of the workspace's clients keep writing than its share and its queue hold, a retry can be refused again. Send fewer writes at a time, or retry with a growing delay: a recorded action is idempotent on its `action_id`. |

### Error precedence

When several things are wrong with one request, the first of these answers, on every protected route (RD-44):

1. **Identity**: `401 unauthenticated`, `401 api_key_wrong_header`, `401 invalid_api_key`, `401 invalid_session`.
2. **Session-only operation reached with a key**: `403 session_required`.
3. **Side of the line**: `403 performer_cannot_commit` (a key that may record actions, on the approving side's routes), `403 person_required` (a key, on a person's decision).
4. **Role and scope**: `403 forbidden` (role), `403 insufficient_scope` (a missing scope).
5. **Workspace and environment binding**: `403 workspace_mismatch`, `403 environment_mismatch`.
6. **Payload validation**: `422 validation_error`, including a body that is not JSON at all, which is reported only after steps 1 to 4 passed.
7. **Business rules** of the route (`409`, `402`, `404`).

Authority by credential, enforced at the API whatever a page shows:

| Operation | approver key | recorder key | evidence key | person |
|---|---|---|---|---|
| Send a commitment; amend it; resolve its mapping; change its owner; assign its exception; re-check it | yes | `403 performer_cannot_commit` (re-check: `performer_cannot_recheck`) | `403 insufficient_scope` | Analyst+ (mapping: Admin+) |
| Create or change a commitment draft; publish a pricing definition | yes | `403 performer_cannot_commit` | `403 insufficient_scope` | Analyst+ |
| Approve a commitment draft | `403 person_required` | `403 person_required` | `403 person_required` | Analyst+ |
| Record an action or an execution report | `403 insufficient_scope` | yes | `403 insufficient_scope` | Analyst+ |
| Push records, links, checkpoints | `403 insufficient_scope` | `403 insufficient_scope` | yes | Analyst+ |
| Accept an exception | `403 person_required` | `403 person_required` | `403 person_required` | Admin+ |
| Attest, rotate or revoke trust; manage keys | `403 session_required` | `403 session_required` | `403 session_required` | Owner/Admin, never for a key they created |

## Metering

A **new** `action_id` on `POST /v1/actions`, an inline action on `POST /v1/actions/verify` that is not a dry run, or the MCP `record_action` tool counts one verified action against the month it is **recorded** in (UTC), whatever month its `requested_at` names: a backdated action never lands in a month already billed. An action marked `environment: "test"` is metered like any other. Re-recording an existing `action_id`, dry runs, verifying an already recorded action by id, the settlement re-checks and sandbox runs are never metered. Only agent actions are counted: a vendor's claims, uploaded or read by a connector or a reconciliation, are what gets checked and never count (`usage.outcomes_this_period`, `allowance.used` and Developer's daily cap alike). The MCP tool applies the same daily cap and allowance as REST, through the same function, and answers the same `fair_use_exceeded` and `allowance_exceeded` errors in its `error` block.

On a paid plan nothing is refused past the allowance. Metered responses carry:

```ts
allowance: {
  period, cap, used, over_by,
  mode: "within" | "unlimited" | "overage" | "grace" | "exceeded",
  grace_hours, grace_actions, grace_ends_at,
  overage_per_action, upgrade_to
}
```

`overage` is a paid plan past its allowance (billed per action); `grace` is Developer inside 72 hours of the first action past the allowance and at most 250 actions past it; `exceeded` is Developer after the grace, when a new action answers `402 allowance_exceeded` with the same object in `details`. The first action past the allowance is logged once as `allowance.exceeded`. `allowance` is `null` when the call re-records an existing action. The same object is on `GET /v1/auth/me` as `entitlements.allowance`.

**Plan changes and enrolled checks** (CL-0100 U-13). A trial ending, the allowance running out or a plan change can
stop *new* enrollment where the plan says so (Developer past its grace: `402 allowance_exceeded`); it never stops the
checks of an action or commitment already received. The reads their settlement asks for go ahead after a trial has
ended, and the reads a commitment's own re-checks and corrections ask for go ahead after a plan change too (a manual
"Sync now" still answers `trial_expired` / `source_not_on_plan`; an action recorded on a plan that never read a source
asks for no read of it); none is metered. Each commitment receipt carries `monitoring { state: "active" | "collection_stopped" | "ended" |
"not_started", window_ends_at, next_check_at, last_collected_at, stopped_sources, collection_stopped_after_seconds,
enrollment: { open, reason, plan, trial_expired }, terms, checks_on }`. When a system it reads has not reported for
48 hours inside the window, `state` is `collection_stopped` and `current_assessment.state` reads `undetermined`
(`reason: "collection_stopped"`) rather than `satisfied`; the original decision is unchanged.

A [commitment](#commitments) is one verified action: receiving a new (`commitment_ref`, `revision`) on `POST /v1/commitments` counts one, through the same function, with the same `allowance` block and the same `402` and `429` answers. The same commitment sent again, its execution reports, its re-checks (`POST /v1/commitments/{ref}/verify`) and the verification of its correction are never metered.

## Public (no auth)

### `GET /health`

**Response**

`{ status: "ok", version, engine_version, db: "ok", release_version, backend_git_sha, database_schema_version,
canonical_refund_contract_id, canonical_refund_contract_version, python_sdk_version, typescript_sdk_version,
deployed_at, build_id, build_created_at, code_schema_version, replica_started_at, build }`

**Build identity is not replica start** (CL-0100, U-26). `build_id` (`bld_…`) is derived only from what the build
carries (release, commit, engine, the schema the code migrates to, the SDK versions it pins, the canonical contract):
every replica and every restart of one build answer the same `build_id`; any change to those answers another.
`build_created_at` is when the image was built (`BUILD_CREATED_AT` build argument; null when the build does not say).
`replica_started_at` is when the answering process started and identifies only that replica's life.
`code_schema_version` is the newest migration the code knows; `database_schema_version` the newest applied (they
differ while a deferred migration is pending). `deployed_at` is kept for compatibility: `DEPLOYED_AT` when the deploy
sets it, else the replica's start (`deployed_at_source` on the provenance block says which), so it is not a build
identity. `scripts/rem3/provenance.py` pins these, with the site's `/version.json`, for a run and refuses to compare
results across builds.

`build` is the same build as Help / About shows it and "Copy diagnostics" copies it: `{ app_version, engine_version,
backend_sha, backend_sha_short, python_sdk_version, typescript_sdk_version, contract_id, contract_version,
schema_version, deployed_at, build_id, build_created_at, replica_started_at }`. Every value is this build's own metadata (the release constant, the deploy's commit,
the SDK versions the snippets pin, the canonical contract); a value the build does not carry is `null`, never a
target release written by hand. `GET /v1/diagnostics/build` (viewer, session or key) answers the same object. The
frontend's commit is the site's own `GET /version.json`.

The fields after `db` are the public subset of the deployment provenance (0.9.56): enough to tell one build from
another, nothing about configuration. `backend_git_sha` is `RAILWAY_GIT_COMMIT_SHA` or the image's `GIT_SHA` build
argument (null when neither is set); `deployed_at` is `DEPLOYED_AT` when set, else when the process started.

### `GET /v1/diagnostics/provenance` (viewer, session or key)

The full block a benchmark captures before every run and at the end: `{ release_version, engine_version,
backend_git_sha, frontend_git_sha, frontend_asset_hash, frontend_provenance: "configured"|"unknown",
frontend_version_url, database_schema_version, canonical_refund_contract_id, canonical_refund_contract_version,
python_sdk_version, typescript_sdk_version, active_feature_flags: {}, deployed_at, deployed_at_source, build_id,
build_created_at, code_schema_version, replica_started_at }`. The backend
cannot see which site build a browser runs: `frontend_git_sha` / `frontend_asset_hash` are what the deployment is
configured to pair with (`FRONTEND_GIT_SHA`, `FRONTEND_ASSET_HASH`); the site's own `GET /version.json` (`{ git_sha,
build_id }`, `build_id` naming the hashed `/_next/static/<build_id>/` asset directory) is the authority. If any value
changes during a benchmark, the run is invalid.

### `GET /v1/public/pricing`

**Response**

```ts
{
  trial_days,
  unit,
  allowance_policy,
  grace_hours,
  grace_actions,
  founding: {
    plan,
    price_monthly,
    months,
    seats,
    remaining,
    available,
    reason
  },
  included_everywhere: string[],
  compare: [{ group, label, note, values: { [tier]: boolean | string } }],
  tiers: [
    {
      id,
      name,
      for,
      support,
      price_monthly,
      price_placeholder,
      free,
      contact_sales,
      limits,
      overage_per_action,
      features,
      trial_days,
      rate_limits: { requests, writes } | null,
      fair_use: { actions_per_day, facts_per_day } | null
    }
  ]
}
```

`founding` is the Founding Builder offer read from Stripe's coupon (`remaining` seats from `times_redeemed`); it is `available: false` with a `reason` when Stripe is not configured or cannot be read, never guessed. `compare` is the pricing page's comparison table; a row true on every plan is in `included_everywhere` instead.

### `GET /v1/public/definitions`

**Response**

`{ items: Definition[] }`

```ts
Definition = {
  contract_id,
  version,
  kind: "outcome"|"action",
  lens_labels: { vendor: "vendor"|"outcome", strict: "strict"|"policy" },
  action_type: string|null,
  window: string|null,
  vendor,
  vendor_display,
  outcome_type,
  summary,
  source_citation: { url, retrieved, notes, title },
  unknown_fields: string[],
  lenses: {
    vendor: string[],
    strict: string[],
    preconditions?,
    limits?,
    expected_effects?,
    forbidden_effects?,
    window?: string[]
  },
  billing: { unit_price, currency },
  exclusions: any[]
}
```

Where  (plain-language rule lists; the extra `lenses` keys appear for `kind: action`)

### `GET /v1/public/definitions/{contract_id}`

**Response**

`Definition & { yaml: string }`

### `GET /v1/public/verify/{hash}`

**Response**

```ts
{
  found: boolean,
  kind?: "statement"|"verdict"|"dispute",
  statement?: {
    id,
    vendor,
    contract_id,
    contract_version,
    engine_version,
    period,
    generated_at,
    totals
  },
  verdict?: {...},
  chain_valid?: boolean,
  verdict_count?: number
}
```

A `verdict` match also covers action verdicts (`lens` is the engine name `vendor`/`strict`, `verdict` the raw vocabulary). `chain_valid` is present for statements and verdicts: for a verdict, every verdict of its run up to and including it re-hashes to the stored hash and links to the one before, from the run's genesis; a dispute package has no chain of its own and carries no `chain_valid`

### `GET /v1/public/connectors`

**Response**

`{ items: CatalogEntry[] }`, the same entries as `GET /v1/connections/catalog`

The connector catalog without auth, for the public Trust Center (`/security`): what each connector reads, the
scopes it asks for and the fields its connection form shows. It is the same for every workspace; nothing of a
workspace is in it.

### `GET /v1/public/sample-statement`

**Response**

`Statement`

Synthetic demo tenant, `synthetic: true`

### `GET /v1/public/sample-action`

**Response**

`ActionVerification & { synthetic: true }`

The public sample: the synthetic demo workspace's run of the onboarding sample's one scenario under the canonical refund contract (`scop_refund_order`, one-hour window) with the `onboarding_sample` provenance (FAIL: the Stripe refund and the Zendesk case observed, the Shopify cancellation missing). `404 not_found` until the demo tenant is seeded. Shape under **Actions** below; `action.is_sample` is true.

### `GET /v1/public/sample-commitment`

*(0.10.0.)* The public sample commitment, for the home page's receipt card: the synthetic demo workspace's finished
run of the guided [account-change sample](#account-change-sample) (received, judged incomplete, assigned,
corrected and verified), read from that commitment's own receipt. `404 not_found` until the demo workspace has
made the run (the boot after the first one does).

```ts
{
  sample: true,
  commitment_ref: string, revision: 1,
  workflow: "change_account_seats",
  summary: "Move Account A from 25 to 40 account seats, effective today",
  account: { account_ref: string },
  change: { seats_from: 25, seats_to: 40 },
  effective_at: string, due_at: string,
  executor: { kind: "automation" | "agent" | "person", name: string, reported: "completed" | "failed" },
  systems: [{ system: "billing" | "product_access", label: string,
              expected: string, observed: string,          // "40 seats", "25 seats"
              state: "match" | "mismatch" | "not_checked",
              reason: string }],                           // the receipt's own sentence for the system
  original_outcome: { state: "incomplete", decided_at: string, reason: string },
  exception: { owner: string,
               resolution_condition: string,               // a sentence: "Apply the approved access change."
               state: "corrected_verified" },
  correction: { verified_at: string, summary: string },
  status: "corrected"
}
```

`systems` is what each system showed when the original outcome was decided, so the corrected commitment still shows
the mismatch that made it incomplete. `exception.resolution_condition` is the required correction in a person's
words; the machine-checkable condition is on the receipt (`GET /v1/commitments/{ref}`). The reference and the times
are the run's own: the run happens in one go, so `decided_at` and `verified_at` are close together.
`scripts/export_public_sample_commitment.py --site <site checkout>` writes the same answer, from the same code run
against a throwaway database, as the site's built-in copy; `--check` says whether that copy is current.

### `POST /v1/public/leads`

**Request body**

```ts
{ name, email, company, message?, monthly_outcomes?, source? }
```

**Response**

`{ ok: true }`

### `POST /v1/public/gap-estimate`

**Request body**

```ts
{ monthly_outcomes: number, unit_price: number, strict_rate: number }
```

**Response**

```ts
{ low: number, high: number, mid: number, assumptions: string[] }
```

### `GET /v1/public/status`

Component health for the public status page; no sign-in. `{ components: [{ name, status, checked_at, detail?, ... }] }`
with `status` one of `operational`, `degraded`, `down`.

- **API** rates itself from what it answered in the last five minutes: `window_minutes`, `requests`, `errors` (5xx
  answers), `refused` (requests turned away because the process was full; also counted in `errors`), `error_rate`,
  `p50_ms`, `p95_ms` (time until the answer started, as the upper bound of a latency bucket). `degraded` at an
  error rate of 2% or a p95 of 3,000 ms; `down` at an error rate of 50%. Under 20 requests in the window it reads
  `operational` and `detail` says how few it saw. The figures are those of the API process that answered the
  request; with several processes each reports its own share. `/health` and this route are never refused and
  never counted.
- **Website** (production only, once measured) is one timed request from the API to the site's health route, at
  most every 30 seconds: `response_ms`; `degraded` at 1,500 ms or on one failure, `down` on two failures in a row.
  The status route returns the last measurement and never waits for one.
- **Verification engine** is `degraded` at ten or more dead engine jobs in 24 hours; **Job queue** at 500 or more
  queued jobs (`queued`).

## Auth

### `POST /v1/auth/dev-login`

**Request body**

`{ email, tenant_name?, name?, plan? }`

**Response**

`Session`

Only when `AUTH_MODE=dev`

Plan applies only when a new tenant is created; the first member is always `owner`

### `GET /v1/auth/workos/authorize?redirect=`

307 to WorkOS AuthKit (when configured). The `state` is signed and good for ten minutes, and the same value is set as a cookie on the API host, so the callback completes only in the browser that started it; a callback with a missing, foreign or expired state lands on `/login?error=auth_failed`. The callback redirects to the `redirect` it was started with (a `${WEB_URL}/auth/callback` URL; `next=` on it survives) plus `code=`, a one-time code good for sixty seconds.

`plan=` is the self-serve plan a new workspace is created on. `intent=trial` (or a `plan=` with no `intent`) opens AuthKit on its sign-up screen (`screen_hint=sign-up`); `intent=signin` or neither opens it on sign-in. A `tenant_slug=` with active SSO goes to that connection, which has no such screen, and gets no hint. `provider=google` or `provider=github` goes straight to that provider (WorkOS `provider=GoogleOAuth` or `GitHubOAuth`) instead of AuthKit's page, and gets no hint either; any other value is `400 unknown_provider`.

`POST /v1/auth/handoff { code }` → `{ token }`, once (`400 invalid_code` after); the web app's callback route makes that call server-side and sets the cookie, so the token never appears in a URL.

A **new account created with a password** (WorkOS `authentication_method: Password`) gets no session from the callback: the browser lands on `${WEB_URL}/login?notice=verify_email` and a link to `${WEB_URL}/verify-email?token=` is emailed (good once, for 24 hours; a new sign-in or a resend retires it; at most one a minute per address). `POST /v1/auth/verify-email { token }` → `Session` with the token, `mfa.method: "Password"`; `400 invalid_verification` when the link is unknown, used or expired (the address stays verified if a first click already landed, so signing in again works); `403 account_held` for a held workspace. `POST /v1/auth/verify-email/resend { email }` → `{ ok: true }` whatever the address. Google, GitHub, Microsoft, SSO, magic-link and passkey sign-ins arrive verified and never see the step; accounts that predate 0.9.4 are not asked.

`GET /v1/auth/providers` → `{ workos, dev_login }`, plus `email_code_signup: true` while the site's own sign-up screen is on (`REFUND_FIRST_SIGNUP` and WorkOS configured; refund-first onboarding, `docs/onboarding/refund/`).

### `POST /v1/auth/email-code/send` and `POST /v1/auth/email-code/verify`

The site's own sign-up screen, email code first. Both answer `404 not_found` unless `email_code_signup` is on. The API never takes a password: a body with any field other than those named is `422`.

`POST /v1/auth/email-code/send { email, plan? }` → `{ ok: true }`. WorkOS Magic Auth emails a six-digit code (`POST /user_management/magic_auth`); the code never passes through CommitLayer. A new address is screened as a hosted sign-up is: `400 disposable_email` or `no_mail_server`, `403` for the other refusals, before any code is sent. `429 rate_limited` when WorkOS limits the address, `503 email_code_unavailable` when WorkOS refuses (Magic Auth not enabled, for one). Event `email_code_requested` (`tier` only).

`POST /v1/auth/email-code/verify { email, code, plan?, redirect? }` (`code`: six digits) → `{ redirect }`: the code is traded with WorkOS (`grant_type=urn:workos:oauth:grant-type:magic-auth:code`), and the sign-in completes exactly as the hosted callback does: a new address gets a workspace of its own on `plan` as its owner, an invited one joins its workspace, the address counts as verified (`MagicAuth`). `redirect` is where the browser goes next: the `redirect` given when it is a `${WEB_URL}/auth/callback` URL, else `${WEB_URL}/auth/callback`, with `code=` (the one-time code `POST /v1/auth/handoff` trades), or `${WEB_URL}/login?error=…` for a refused or held account. `400 invalid_code` for a wrong, expired or used code; nothing is created then. Event `email_code_verified` (`tier` only).

### `POST /v1/auth/logout`

Revokes every session of the user: a token issued before the sign-out answers `401 invalid_session` from then on.

A bearer that is not a session token (another token the same key signs, or one without a subject) answers `401 invalid_session`.

`/v1/auth/*`, `/v1/public/*` and `/v1/oauth/*` are limited per client address (`ANON_RATE_PER_MINUTE`, default 60): `429 rate_limited` with `Retry-After`. `POST /v1/auth/email-code/send` and `/verify` are also limited per inbox and per client address, an hour's allowance each (`EMAIL_CODE_SENDS_PER_ADDRESS` 5, `EMAIL_CODE_SENDS_PER_IP` 20, `EMAIL_CODE_VERIFIES_PER_ADDRESS` 10, `EMAIL_CODE_VERIFIES_PER_IP` 30), with the same `429 rate_limited` whether or not the address has an account.

### `GET /v1/auth/me`

**Response**

```ts
Session = {
  token?: string,
  user: { id, email, name, mfa_enabled },
  tenant: { id, name, slug, plan, trial_ends_at, synthetic: boolean },
  membership: { role: "owner"|"admin"|"analyst"|"viewer"|"counterparty", role_label: string },
  capabilities: { [name: string]: boolean },   // e.g. can_manage_keys; see "Roles and capabilities"
  entitlements: Entitlements,
  is_platform_admin: boolean,
  impersonating?: boolean,
  mfa: { required: boolean, satisfied: boolean, method: string | null }
}
```

When `mfa.required` is true and `satisfied` is false, every product route answers `403` with code `mfa_required`; only `me`, `logout`, `switch-tenant` and the two enrolment endpoints work.

#### Roles and capabilities

`capabilities` says what the signed-in member may do: `can_view_actions`, `can_verify_actions`, `can_create_contracts`, `can_manage_connections`, `can_manage_keys`, `can_attest_sources`, `can_view_billing`, `can_manage_billing`, `can_view_members`, `can_manage_members` and the rest of the list in security/role-matrix.md. Each is read from the role checks of the routes that enforce it, so it is the same answer the route would give; a client offers a control when its capability is true and still handles the `403`. `tenants` lists the member's other workspaces (active memberships only). The four roles are Owner, Admin, Analyst and Viewer; "Editor" in older text means Analyst. The policy is in security/roles.md.

### `GET /v1/auth/invitations/{token}`

Any signed-in person. How they stand to an invitation (from Settings, Members or the engineer handoff): `{ matches, status: "pending"|"joined"|"cancelled"|"expired", signed_in_as, invitee, workspace, role_label, member, in_workspace, can_accept, tenant_id, destination }`. `matches` is whether the invitation was sent to this person; when it is false, `tenant_id` and `destination` are null and nothing can be accepted. Reading accepts nothing. `404` for a token that is not an invitation's.

### `POST /v1/auth/invitations/{token}/accept`

The invited person, signed in. Accepts a pending invitation at its invited role and answers a `Session` for the invited workspace (as `switch-tenant` does) with `destination`. Already accepted: the same answer, nothing changed. `403 wrong_account` for anyone else (audited in the inviting workspace as `security.denied`), `410 invitation_expired`, `410 invitation_revoked`, `404` for a token that is not an invitation's.

### `POST /v1/auth/logout`

**Response**

`{ ok: true, logout_url: string | null }`

The web app clears its cookie and, when `logout_url` is set (a session that came from the hosted sign-in), sends the browser there so the provider's session ends too and returns to the site; otherwise it goes to the home page. Never to the sign-in page, which would start a new hosted sign-in at once.

### `POST /v1/auth/mfa/enroll`

**Response**

`{ challenge_id, qr_code (data URI), secret, uri }`

For the signed-in user (hosted sign-in users only; `400 hosted_sign_in_only` otherwise). Shown once; nothing is stored until the first code verifies.

### `POST /v1/auth/mfa/verify`

**Request body**

`{ challenge_id, code }`

The `Session` with `mfa.satisfied: true` and `user.mfa_enabled: true`; `400 invalid_code` for a wrong code, `400 unknown_challenge` if enrolment was not started in this session.

### `POST /v1/auth/logout`

**Response**

`{ ok: true }`

### `POST /v1/auth/switch-tenant`

**Request body**

`{ tenant_id }`

**Response**

`Session`

```ts
Entitlements = {
  plan,
  limits: { connections, outcomes_per_month, contracts, seats },
  features: { [key: string]: boolean },
  usage: { connections, outcomes_this_period, contracts, seats },
  trial_ends_at: string|null
}
```

## Overview

### `GET /v1/overview?period=YYYY-MM`

**Response**

```ts
{
  period,
  vendors: VendorSummary[],
  onboarding: {
    connected: boolean,
    contract_selected: boolean,
    first_run: boolean,
    invoice_imported: boolean
  },
  verify_onboarding: {
    sample_action: boolean,            // the sample action was run
    api_key: boolean,                  // a key that is not revoked exists
    own_action: boolean,               // the workspace recorded an action of its own
    action_contract: boolean,          // an action contract is selected
    first_own_action_id: string|null,  // the first such action, by when it was recorded
    actions_recorded: number           // every stored action, sample and sandbox runs included
  }
}
```

An action "of its own" is a stored action that is not the sample, not an Agent sandbox run and not marked `environment: "test"` (see `POST /v1/actions`). An action a person records by hand in the app counts here. A sandbox run no longer sets `own_action`, and `first_own_action_id` is the first own action; it used to be the most recent.

```ts
VendorSummary = {
  vendor,
  vendor_display,
  contract_id,
  billed: { count, amount },
  verified_vendor: { count, amount },
  verified_strict: { count, amount },
  not_verified_strict: number,
  unverifiable_strict: number,
  definition_delta: { amount, count },
  open_disputes: number,
  trend: [{ period, billed, verified_vendor, verified_strict }],
  latest_statement_id: string|null
}
```

## Connections

### `GET /v1/connections/catalog`

**Response**

```ts
{
  items: [
    {
      source,
      display,
      kind: "claims"|"facts"|"both"|"internal",
      auth: "oauth"|"api_key"|"upload"|"otel",
      scopes: string[],
      fields_pulled: string[],
      docs_url
    }
  ]
}
```

Role: viewer. The same catalog without auth, for the public Trust Center (`/security`): `GET /v1/public/connectors`.

### `GET /v1/connections`

Query: `include_agent_api` (default `false`).

**Response**

`{ items: Connection[], evidence_sources: SourceHealth[], recorder: RecorderHealth, trust_levels: { [level]: label }, trust_classes: { [class]: label }, trust_level_classes: { [level]: { evidence_trust_class, trust_label } } }`

Health (RS-2, U-06) is computed from the data evaluation reads, never a separate monitor: the source checkpoints
settlement waits on, the records received, the checkpoint attempts the ingestion path logs, the keys bound to the
source and its attestations.

```ts
SourceHealth = { source_id, path: "evidence_pipeline"|"connector", last_successful_read_at, last_attempt_at,
  last_observation_at, coverage_through, lag_seconds: number|null, lag_threshold_seconds: 3600,
  state: "empty"|"active"|"lagging"|"unavailable"|"revoked"|"recovered",
  errors: [{ code, at }], next_retry_at: string|null }   // next_retry_at: a connector's next sync; null when pushed
RecorderHealth = { role: "recorder", authoritative: false, last_heard_at, last_action_recorded_at,
  state: "active"|"silent"|"never"|"revoked", live_keys, silent_after_seconds: 86400, note }
```

`empty`: no record and no checkpoint yet. `lagging`: coverage more than an hour behind now. `unavailable`: the
connector failed, or the latest checkpoint was refused (`checkpoint_not_permitted`). `revoked`: no live key may publish
the source. `recovered`: active again after an error. The recorder says what the agent tried and is never a business
source. In an action's `sources`, a source with no record on the action has `records: 0`, `evidence_trust_class: null`
and `trust_label: null` (RB-6): no provenance label comes from a connection's legacy rating (`trust`,
`trust_basis: "legacy_connection_rating"`).

`trust_classes` is the one trust vocabulary a reader is shown (`agent_reported` "Agent-reported", `backend_attested`
"Backend-attested", `commitlayer_read` "CommitLayer-read", `externally_verified` "Externally verified",
`sample_source` "Sample source"; `docs/trust-terminology.md`). `trust_levels` is the legacy three-level list that
`trust` and `source_trust` are set with, kept for clients written before classes. `trust_level_classes` says what
each legacy level reads as where nothing but a level is known (a pack's `min_trust`): it is **not** how to label a
connection or a source, whose own class is on the item (below).

The workspace's systems of record. The connection pushed actions and facts arrive on (source `agent_api`, "Agent
actions (API)") is not one: the first push creates it and it always reads healthy. It is left out of this list,
of the MCP `connector_health` tool and of the Overview's `onboarding.connected`, and Connections shows it as its two
sides, the runtime recorder and the evidence pipeline. `include_agent_api=true` lists it, for a client that reads
or sets its trust; `GET /v1/connections/{id}` and `PATCH /v1/connections/{id}` serve it by id as before.

```ts
Connection = {
  id,
  source,
  display_name,
  kind,
  status: "pending_auth"|"healthy"|"syncing"|"error"|"revoked",
  display_status: { code, label },   // what the app shows; see below
  trust: "independent"|"shared"|"self_reported",   // legacy level, as stored; the engine's `min_trust` gate reads it
  evidence_trust_class: "agent_reported"|"backend_attested"|"commitlayer_read"|"externally_verified",
  trust_label: string,       // "Agent-reported" | "Backend-attested" | "CommitLayer-read" | "Externally verified"
  legacy_rating: boolean,    // true: `trust` is a hand-set rating above self_reported, not an attestation
  sources: [{                // one per source pushed through this connection (the facts API's); [] otherwise
    source, trust, evidence_trust_class, trust_label, legacy_rating,
    attested: boolean        // a live evidence attestation exists for this source
  }],
  scopes: string[],
  last_sync_at,
  watermark,
  health: {
    ok: boolean, message?: string, lag_seconds?: number,
    records?: number,   // what the last read (or upload, or OpenTelemetry batch) returned: claims + facts
    hint?: string,      // after a connection test: advice that did not stop it (a Stripe secret key)
  },
  freshness: {
    watermark: string|null,      // the time the source is known complete up to
    age_seconds: number|null,    // now - watermark; null with no watermark yet
    stale: boolean,              // age_seconds > stale_after_seconds
    stale_after_seconds: number, // 172800 (two days)
    last_sync_at: string|null,   // when CommitLayer last read the source; shown, never used as freshness
    basis: "watermark"
  },
  config,
  created_at
}
```

Freshness has one definition everywhere it is reported (this response, `GET /v1/connections/{id}`, the MCP
`connector_health` tool, pack coverage `watermark_age_seconds`/`stale`, the guided setup's sources, the
operator's lag list): the age of the watermark, the same watermark settlement compares with the end of an
action's window. `health.lag_seconds` is that age, computed when the connection is read; it is no longer a value
stored at sync time (which was always 0 and read as "fresh" until the next daily sync, Board CL-128). A read that
finds nothing new still moves the watermark to its own start less `SYNC_SAFETY_LAG_SECONDS`, so a quiet source
that was read is current.

`display_status` says what has actually happened, so nothing reads "Healthy" before a first read has finished
(Board CL-150). `code` is one of `pending_auth` ("Waiting for credentials"), `error` ("Needs attention"),
`first_sync_running` ("First sync running"), `syncing` ("Syncing"), `first_sync_pending` ("Connected, first sync
pending": the credential passed one test call, or a source without credentials has received nothing, and
`last_sync_at` is null), `synced_empty` ("Synced, no records found": the last read returned 0 records) and `healthy`
("Healthy"). `status` keeps its meaning (`healthy` after a passing test) for clients that read it. A stale
watermark is `freshness.stale`, shown beside the status, never folded into it. A passing test's
`health.message` is "Connected, first sync pending" (or "Re-authenticated, first sync pending") until the first
read; a failing one is logged as a warning naming the connection, the source and the connector's message, never a
credential.

**Stripe.** Testing a Stripe connection reads the mode from the key's prefix (`rk_test_`/`sk_test_` or
`rk_live_`/`sk_live_`), checked against `livemode` on the records Stripe returns (a disagreement is an `error`,
`reauth: true`), and reads `GET /v1/account` for the account. It stores
`config: { stripe_mode: "test"|"live"|"unknown", account_id, account_name, key_type: "restricted"|"secret"|"unknown" }`;
`account_id` and `account_name` are `"unknown"` when a restricted key may not read the account, and the connection
works all the same. The key itself is only ever in the encrypted credential. A secret key (`sk_`) is accepted, with
`health.hint` recommending a restricted, read-only key. Every Stripe fact carries `attributes.livemode` from the
Stripe object it came from (null when Stripe did not say); an action judged on Stripe evidence of the other mode is
UNKNOWN with `evidence_mode_mismatch` (see `GET /v1/actions/{id}`).

**Salesforce.** `instance_url` is the org's own instance, `https://<your-domain>.my.salesforce.com`. A sign-in host
(`login.salesforce.com`, `test.salesforce.com`) or none answers `400 invalid_credentials` on create and on
re-authentication, and nothing is stored; API calls are never sent to a sign-in host. A rejected token's health
message keeps Salesforce's `errorCode` (for example `INVALID_SESSION_ID`) and says to reconnect with a fresh access
token.

**Trust on a connection (0.9.58).** `evidence_trust_class`, `trust_label` and `legacy_rating` are computed by the
same derivation that classes every record (`Evidence trust`, below), never stored and never set: a connector
CommitLayer reads with its own credential is `commitlayer_read`; a pushed source with a live attestation is
`backend_attested`; a pushed source nobody attested is `agent_reported`, and when `trust` / `source_trust` rates it
`shared` or `independent` by hand it stays `agent_reported` with `legacy_rating: true` (the engine still counts the
legacy rating for `min_trust` during the deprecation window, and it is not an attestation); OpenTelemetry is
`agent_reported`; an uploaded file is `agent_reported`, with `legacy_rating: true` while its legacy level is above
`self_reported`. Render `trust_label`; do not map `trust` to a class. The legacy fields are unchanged and are
returned beside the canonical ones on every answer under `/v1/connections` (list, get, create, patch, reauth).

### `PATCH /v1/connections/{id}`

Role: admin.

**Request body**

`{ trust?, source_trust?: { [source]: level } }`

**Response**

`Connection`

`trust` is how independent the connection's facts are from the party being verified (SECURITY.md §16); `source_trust` overrides it per pushed source on the facts-API connection. Audit: `connection.trust_changed`.

**Deprecated for the facts-API connection (`agent_api`).** Kept working through the deprecation window, it is no longer
offered in the app for that connection: a connection-wide level there rates every pushed source at once. Attest one
evidence key for one source instead (`POST /v1/evidence/attestations`). A source with a live attestation ignores
this setting for every pusher except the attested keys.

### `POST /v1/connections`

**Request body**

```ts
{
  source,
  display_name?,
  credentials?: { api_key?, subdomain?, access_token?, base_url?, ... },
  config?: {                         // non-secret; `role` and `kind` are the server's
    subdomain?,                      // zendesk
    ticket_binding?: { account_field, approval_ref_field, approval_revision_field, disposition_field?,
                       environment? },                       // zendesk: docs/connectors/zendesk.md
    approval_import?: { enabled, workflow, approved_stage, approvers: string[], environment?,
                        fields: { … } },                     // hubspot, salesforce: docs/connectors/hubspot.md
    portal_id?, org_id?              // the CRM instance's id, named in imported approvals' approval.source
  }
}
```

`source: "reference_app"` reads an application's enforcement state with its verifier-read credential
(`credentials: {base_url, access_token}`); an operator credential is refused. See
docs/connectors/reference_app.md and docs/connected-integration.md.

A connector read that could not collect a scope it must (a targeted read of an approved change's subscription,
invoices, ticket or tenant that failed) keeps the records it read but does not move the connection's checkpoint:
`health.complete: false`, `health.incomplete: [scope…]`, and `config.read_coverage` says per scope what the last read
covered.

**Response**

`Connection`

Plus `authorize_url` for OAuth sources

`400 invalid_credentials` when the connector refuses the credential before anything is stored (a Salesforce
sign-in host as the instance URL). A credential the provider rejects is stored and answers `200` with
`status: "error"` and the provider's message in `health`.

### `GET /v1/connections/{id}`

**Response**

```ts
Connection & {
  stats: { claims, facts, last_sync_duration_ms },
  recent_syncs: [
    { id, started_at, finished_at, status, rows_claims, rows_facts, error? }
  ]
}
```

### `POST /v1/connections/{id}/sync`

Role: analyst. Over MCP: the `sync_connection` tool, scope `connectors:sync` ([mcp.md](/docs/mcp)).

**Request body**

`{ backfill_days?: number }` (0 to 400; `400 backfill_too_large` above)

**Response**

`{ job_id, run_at, deduplicated: boolean, rate_limited: boolean }`

Queues a read of the connection. At most one read of a connection is queued: when one already is, this request
joins it (`deduplicated: true`, the same `job_id`) and brings it forward to now, and a larger `backfill_days` is
carried over. At most one runs: a read that finds another read of the same connection running waits a minute and
tries again, without counting an attempt. `400 not_syncable` for a pushed or uploaded source (`generic_csv`,
`otel`, the facts API's `agent_api`); `409 reauth_required` while the provider rejects the stored credential;
`402` (`source_not_on_plan`, `trial_expired`) when the plan does not read the source now. Audit:
`connection.sync_requested {backfill_days, deduplicated, via}`. The MCP tool also holds the read to
`CONNECTION_SYNC_MIN_INTERVAL` after the previous one started (`rate_limited: true` when it postponed it); the
Sync button does not wait.

**Reads on demand for actions.** Besides the daily sweep (03:00 UTC), a connection CommitLayer reads with a
stored credential is read for the actions whose contracts read it (`app/connectors/ondemand.py`, Board CL-120):
`ACTION_SYNC_DELAY` (1m) after the action is recorded, and, when the window has closed while the connection's
watermark is still before its end, `SYNC_SAFETY_LAG_SECONDS` after the end of the window (so the read's watermark
passes it). A read asked for by actions re-checks them as soon as it finishes, so a PASS the new facts complete
settles within minutes; a re-check that was waiting on the source comes forward as before. These reads go through
the same bounds (one queued, one running, `CONNECTION_SYNC_MIN_INTERVAL`, default 5m), skip a connection with no
credential, one waiting on re-authentication, a source the plan does not include and a workspace whose trial has
ended, and are queued in a savepoint after the verdict is stored: a failure to queue one is logged and never
fails or slows `POST /v1/actions`. `ACTION_SYNC_ENABLED=false` turns them off.

### `POST /v1/connections/{id}/reauth`

**Response**

`Connection`

Or `{ authorize_url }`

Tests the new credential as `POST /v1/connections` does (the same `400 invalid_credentials`, the same logging) and
queues a read when it passes.

### `DELETE /v1/connections/{id}`

**Response**

`{ ok: true }`

### `POST /v1/connections/upload`

**Request body**

```ts
{
  columns: { <canonical>: <csv header> },
  vendor?,
  contract_id? (claims; the library contract the rows belong to, default generic_outcome_csv),
  outcome_type?,
  subject_kind?,
  fact_type?,
  source? (facts),
  provides?: string[
    
  ] (facts; fact-source categories such as conversations/csat/refunds, used by missing_fact_source),
  keep_text?: boolean
}
```

**Response**

`{ connection_id, rows, job_id: null }`

Multipart form: `file`, `kind` (`claims`|`facts`), `mapping` (JSON string: ), `save_mapping_as?`, `connection_id?`

Uploads are ingested synchronously

A file of facts (`kind: facts`) is evidence like a pushed fact. Sent with an API key it needs `facts:write` (`403 insufficient_scope` otherwise, so a `recorder` key cannot upload the facts that judge its own action), and a key bound to sources uploads only for a source it is bound to (`403 source_not_allowed`; the source is the mapping's `source`, `generic_csv` when it names none). A signed-in analyst uploads as before.

### `POST /v1/connections/upload/preview`

**Response**

```ts
{ headers: string[], sample_rows: any[][], row_count, suggested_mapping }
```

Multipart form `file`, `kind`

### `GET /v1/connections/mappings`

Saved mappings

## Contracts

Contract YAML is parsed with a safe loader and refused with `400` above `MAX_CONTRACT_BYTES` (128 KiB), with more than 16 anchors or 32 aliases, deeper than 32 levels, or above 50,000 values.

### `GET /v1/contracts`

**Response**

`{ items: ContractSummary[] }`

```ts
ContractSummary = {
  id,
  version,
  vendor,
  outcome_type,
  status: "library"|"draft"|"active"|"archived",
  source_citation,
  selected: boolean,
  updated_at,
  owner: "library"|"tenant"
}
```

### `GET /v1/contracts/{id}?version=`

**Response**

```ts
Contract = ContractSummary & {
  yaml: string,
  description: string|null,       // the contract's description as served
  description_derived: boolean,   // true: `description` (and the one in `yaml`) is the current pack's sentence, see below
  compiled_sql: { vendor: string, strict: string },
  versions: [{ version, created_at, status, selected, owner: "tenant"|"library",
               change_note: string|null,        // why the product published this version; null for a person's
               corrects_version: number|null }] // the version whose description this one corrects
}
```

**A pack contract stored before 0.9.58 (RB-29).** Until 0.9.58 a configuration that took checks out of a pack's
contract left the pack's description as shipped, so a refund contract without a notification check still read "and
the customer told". Such a version is served with the description 0.9.58 writes for the same checks (the words of
each removed check taken out, and "Not checked in this configuration: …" added), in `yaml`, `description` and
`definition.summary`, with `description_derived: true`; the guided setup's contract summary reads the same
sentence. This applies only when the stored description is the pack's shipped one word for word and a check it
speaks of is absent: a description somebody edited is served as written (`description_derived: false`). Nothing
stored changes: the version's text, its diff (`GET /v1/contracts/{id}/diff`), statements and every verdict computed
under it keep the stored text and their hashes. Saving the served `yaml` as a new version stores the new sentence.

**The correction is then stored as a new version.** After the deploy, once per database, the worker publishes for
each such contract a new version whose only change is the description (and the `version` line every version
carries), with `change_note` "Description corrected: it no longer names a check this configuration does not run."
and `corrects_version`. It takes the place of the version it corrects: selected and `active` if that one was (which
then reads `archived`, as after any newly selected version), a `draft` if it was a draft. The pack installation's
version, its recorder mapping's `contract_version` and the guided setup's confirmed version move to it, so the
contract reads confirmed and active as before. From then on the contract page, `versions`, the setup's summary,
`GET /v1/contracts/{id}/diff` against the new version and anything issued later show the corrected text as
stored (`description_derived: false`); the diff between the two versions is the `version` line and the
description. Nothing already issued changes: the earlier version's text, statements, verdict bodies and hashes are
byte for byte what they were, and an action keeps the version it was recorded under, so a pending action settles
under that version with the verdict it would have had. The correction queues no re-verification and creates no
verdict version, snapshot, notification or webhook delivery; it writes one audit line,
`contract.description_corrected` (`from_version`, `version`, `note`). A description somebody edited is never
corrected. `POST /v1/actions` with `contract_version` set to a version whose description was corrected records
under the version that corrects it (the answer's `contract.version` says which) instead of answering
`409 contract_not_active`; a version archived for any other reason is refused as before.

### `POST /v1/contracts`

An analyst signed in, or an API key that holds every scope (the `full` preset, or a key that predates scopes). A key on one side of the line, a `recorder` or an `evidence` key, is refused with `403 insufficient_scope`: the agent's own key cannot save the contract it is judged by.

**Request body**

`{ yaml }`

**Response**

```ts
Contract & { warnings: Weakening[], compared_to: { version } | null }
```

```ts
Weakening = {
  severity: "warning",
  kind: "removed"|"loosened"|"changed",
  place,
  check,
  field?,
  from?,
  to?,
  message
}
```

(new version if id exists) — validates schema; `422` with `details.errors[]` on failure. `warnings` lists every way the new version accepts more than the one it replaces (a removed check, a raised `max`, an extended window, a shortened lookback on a negative check); saving with any emits `contract.weakened` and records the count in the audit entry.

### `POST /v1/contracts/validate`

**Request body**

`{ yaml }`

**Response**

```ts
{
  valid,
  errors: [{ path, message }],
  compiled_sql?,
  plain_language?,
  warnings: Weakening[],
  compared_to
}
```

### `POST /v1/contracts/draft`

Role: analyst.

**Request body**

```ts
{
  action_type?,
  contract_id?,
  lookback_days?: 30,
  lookahead?: "24h",
  min_share?: 0.8
}
```

**Response**

```ts
{
  yaml,
  contract: { id, version, window } | null,
  errors,
  warnings: string[],
  stats: {
    actions,
    effects: [{ source, type, share, max_per_action, included }],
    preconditions,
    params,
    window_p95_seconds
  }
}
```

A contract drafted from the recorded actions of one type and the facts observed on their subjects: effects seen after at least `min_share` of the actions become `expected_effects`, the p95 arrival of the last of them becomes the window, constant states before become preconditions, observed parameter maxima become limits. Nothing is saved. `400 nothing_to_draft` when no actions match.

### `POST /v1/contracts/{id}/select`

**Response**

`{ ok }`

Marks contract active for tenant; counts against entitlement

An analyst signed in, or an API key that holds every scope. A `recorder` or an `evidence` key is refused with `403 insufficient_scope`, as on `POST /v1/contracts`.

### `POST /v1/contracts/{id}/dry-run`

**Request body**

`{ period, version? }`

**Response**

```ts
{
  claims: number,
  vendor: Totals,
  strict: Totals,
  sample_reasons: { [code]: number }
}
```

### `GET /v1/contracts/{id}/diff?from_=1&to=2`

**Response**

`{ from, to, unified_diff: string }`

Note the query parameter is `from_`

### `GET /v1/contracts/primitives`

**Response**

```ts
{
  items: [
    {
      name,
      args: "none"|"duration"|"list"|"stage"|"status"|"label"|"sources",
      description,
      lenses_allowed: string[],
      fact_types: string[]
    }
  ],
  outcome_types: string[]
}
```

Dry-run response shape: `{ claims, available_sources: string[], vendor: { counts: { VERIFIED, NOT_VERIFIED, UNVERIFIABLE }, verified_amount, reasons: { [code]: number } }, strict: {...} }`

## Runs

### `GET /v1/runs`

**Response**

`{ items: Run[] }`

```ts
Run = {
  id,
  contract_id,
  contract_version,
  engine_version,
  period,
  status: "queued"|"running"|"succeeded"|"failed",
  started_at,
  finished_at,
  stats: {
    claims,
    facts,
    verified_vendor,
    verified_strict,
    not_verified_strict,
    unverifiable_strict,
    duration_ms,
    transcript_assist: { enabled, labeled, cost }
  },
  statement_id,
  error?
}
```

### `POST /v1/runs`

**Request body**

```ts
{ contract_id, period, version?, transcript_assist?: boolean }
```

**Response**

`Run`

### `GET /v1/runs/{id}`

**Response**

`Run & { logs: [{ ts, level, message }] }`

## Reconciliations

One vendor's claims for one period, checked against the tenant's facts. The object is keyed by (`contract_id`, `period`), the same key runs and statements use, so a run started here is an ordinary run and its statement an ordinary statement.

### `GET /v1/reconciliations?vendor=&period=`

**Response**

`{ items: Reconciliation[] }`

### `POST /v1/reconciliations`

**Request body**

`{ contract_id, period, version?, notes? }`

**Response**

`Reconciliation`

201; 409 `already_exists` with `details.id` when one exists for that contract and period; 400 `not_an_outcome_contract` for action contracts

### `GET /v1/reconciliations/{id}`

**Response**

`Reconciliation`

With `coverage`, `facts_connections`, `invoice?`, `disputes?`

### `PATCH /v1/reconciliations/{id}`

**Request body**

`{ invoice_id?, notes?, facts_connection_ids? }`

**Response**

`Reconciliation`

The invoice must be for the same vendor and period (400 `invoice_mismatch`); `""` detaches. `facts_connection_ids` names the fact connections this reconciliation relies on (step 2 of the wizard): each must exist and hold facts (404 / 400 `not_a_fact_source`); the run still uses every active connection's facts, the choice judges coverage and records what was checked.

### `POST /v1/reconciliations/{id}/claims/preview`

**Response**

```ts
{ headers, sample_rows, row_count, suggested_mapping, remembered }
```

Multipart form `file`

`remembered` is true when the vendor's last mapping fits the file's headers; `suggested_mapping` is then that mapping, otherwise a guess from the headers.

### `POST /v1/reconciliations/{id}/claims`

**Request body**

```ts
{
  columns: {
    subject_id,
    claimed_at,
    claim_id?,
    unit_price?,
    channel?,
    customer_email?,
    ...
  }
}
```

Multipart form `file`, `mapping?` (JSON ; omitted

The remembered mapping) → `Reconciliation & { upload: { rows, skipped, connection_id } }`. Rows are pinned to the reconciliation's contract, period, outcome type and subject kind; the mapping is remembered per vendor; 409 `already_run` once the reconciliation has been run.

### `POST /v1/reconciliations/{id}/facts/preview`

Multipart form `file`

As above for a facts file

### `POST /v1/reconciliations/{id}/facts`

**Response**

`Reconciliation & { upload }`

Multipart form `file`, `mapping` (JSON columns incl. `subject_id`, `occurred_at`, `fact_type?`), `source` (label, e.g. `helpdesk`), `provides` (comma-separated fact-source families, e.g. `conversations,csat`), `fact_type?` (default for rows without a column)

A one-off facts file for a system with no connector; it becomes a fact source for every later reconciliation.

### `POST /v1/reconciliations/{id}/run`

**Request body**

`{ transcript_assist? }`

**Response**

`Reconciliation`

(400 `no_claims` before any upload). Metered like `POST /v1/runs`.

### `DELETE /v1/reconciliations/{id}`

Role: admin.

**Response**

`{ ok, claims_removed }`

Removes the reconciliation and the claims uploaded into it; runs, statements and verdicts already produced stay in the hash chain.

```ts
Reconciliation = {
  id,
  vendor,
  vendor_display,
  contract_id,
  contract_version,
  outcome_type,
  subject_kind,
  period,
  status: "draft"|"ready"|"running"|"complete"|"failed",
  step: 2|4|5,
  claims: { count, amount, connection_id, file, mapping },
  facts_connection_ids,
  invoice_id,
  run_id,
  statement_id,
  notes,
  created_by,
  created_at,
  updated_at,
  run?: { id, status, started_at, finished_at, error },
  summary?: {
    billed,
    verified_vendor,
    verified_strict,
    not_verified: { vendor: Breakdown, strict: Breakdown },
    unverifiable,
    currency,
    delta,
    statement_hash,
    generated_at
  },
  exports?: { pdf, csv, json },
  coverage: {
    covered,
    selected,
    required: [
      {
        source,
        covered,
        connections: [
          { id, display_name, source, status, trust, evidence_trust_class, trust_label, legacy_rating, last_sync_at }
        ]
      }
    ],
    connections: [
      {
        id,
        display_name,
        source,
        kind,
        status,
        trust,                 // legacy level
        evidence_trust_class,  // with trust_label and legacy_rating: as on GET /v1/connections (0.9.58)
        trust_label,
        legacy_rating,
        last_sync_at,
        provides,
        covers,
        selected
      }
    ],
    available_sources,
    signal_gaps: [{ primitive, needs, description }]
  },
  facts_connections: [...],
  invoice?: { id, status, total, currency, source_ref, line_count },
  disputes?: [{ id, status, lens, contested_amount }]
}
```

`status` is derived: `draft` until claims exist, `ready` once they do, then the run's state. `step` is 2 until a fact source is chosen or imported, 3 until claims are uploaded, 4 until the run completes, then 5. Audit: `reconciliation.created|updated|claims_uploaded|facts_imported|run_started|deleted`.

## Statements

### `GET /v1/statements?vendor=&period=`

**Response**

`{ items: StatementSummary[] }`

```ts
StatementSummary = {
  id,
  run_id,
  vendor,
  vendor_display,
  contract_id,
  contract_version,
  engine_version,
  period,
  generated_at,
  statement_hash,
  billed,
  verified_vendor,
  verified_strict,
  delta: { amount, count },
  has_pdf,
  transcript_assist_used,
  shared_with
}
```

Flat; the full `totals` object is on the detail endpoint

### `GET /v1/statements/{id}`

**Response**

```ts
Statement = {
  id,
  run_id,
  vendor,
  vendor_display,
  contract_id,
  contract_version,
  engine_version,
  period,
  generated_at,
  statement_hash,
  synthetic,
  totals: {
    billed: { count, amount },
    verified_vendor: { count, amount },
    verified_strict: { count, amount },
    not_verified: { vendor: Breakdown, strict: Breakdown },
    unverifiable: { vendor: Breakdown, strict: Breakdown }
  },
  delta: {
    amount,
    count,
    alternatives: [{ label, description, count, amount }]
  },
  transcript_assist: null | {
    used: true,
    labeled,
    sample_rate,
    agreement_rate,
    samples_reviewed
  },
  methodology: { contract_yaml, sections: [{ n, title, body_md }] },
  exports: { pdf: string|null, csv, json },
  shared_with: [{ email, expires_at }],
  chain: { first_hash, last_hash, count }
}
```

```ts
Breakdown = { count, by_reason: [{ code, label, count, explanation }] }
```

### `GET /v1/statements/{id}/claims?lens=&verdict=&reason=&q=`

**Response**

`{ items: ClaimRow[] }`

```ts
ClaimRow = {
  claim_id,
  subject_id,
  outcome_type,
  claimed_at,
  unit_price,
  vendor_verdict,
  strict_verdict,
  primary_reason_vendor,
  primary_reason_strict,
  has_label
}
```

### `GET /v1/statements/{id}/export.pdf|csv|json`

File

### `POST /v1/statements/{id}/share`

**Request body**

`{ email, expires_at?, dispute_ids?: string[] }`

**Response**

`{ grant_id, counterparty_url }`

Enterprise

### `GET /v1/statements/{id}/delta-report`

**Response**

`{ period, lenses: {...}, alternatives: [...] , csv_url }`

## Evidence

### `GET /v1/claims/{claim_id}`

**Response**

```ts
{
  claim: Claim,
  subject_links: [...],
  facts: Fact[],
  verdicts: { vendor: Verdict, strict: Verdict },
  label: TranscriptLabel|null,
  explanations: { vendor: string, strict: string }
}
```

```ts
Claim = {
  claim_id,
  vendor,
  contract_id,
  subject_id,
  subject_kind,
  outcome_type,
  claimed_at,
  billing_period,
  unit_price,
  currency,
  raw_ref,
  connection_id
}
```

```ts
Fact = {
  fact_id,
  source,
  subject_id,
  subject_kind,
  fact_type,
  occurred_at,
  attributes,
  raw_ref
}
```

```ts
Verdict = {
  verdict,
  lens,
  reason_codes: string[],
  evidence: [
    { source, subject_id, fact_id, field, value, occurred_at, sha256 }
  ],
  contract_id,
  contract_version,
  engine_version,
  computed_at,
  verdict_hash,
  prev_hash
}
```

```ts
TranscriptLabel = {
  id,
  label,
  confidence,
  rationale,
  model_id,
  prompt_version,
  labeled_at,
  human_label,
  sampled
}
```

## Evidence trust

Trust determines whether evidence is eligible to satisfy a contract. Changing a source's attestation may change affected
verdicts and triggers reverification. Every record has an **evidence trust class**, computed from how it arrived and never
declared (`app/connectors/trust.py`):

| Shown to users | `evidence_trust_class` | When |
|---|---|---|
| Agent-reported | `agent_reported` | pushed by a key that can also record actions, by the agent's runtime, by an evidence key nobody attested, without a key, or uploaded |
| Backend-attested | `backend_attested` | pushed by an evidence-only key that an Owner or Admin attested for that source, of a type the attestation names |
| CommitLayer-read | `commitlayer_read` | read by a CommitLayer connector with its own read-only credential |
| Externally verified | `externally_verified` | reserved; nothing assigns it yet |
| Sample source | `sample_source` | generated by CommitLayer for one onboarding sample run; eligible for that sample only |

These five are the only trust classes (trust-terminology.md). `trust_label` (the words in the
first column) is returned beside every `evidence_trust_class`. Eligibility order: `agent_reported` <
`backend_attested` < `commitlayer_read` ≤ `externally_verified`. How a record arrived is a separate field,
`ingestion_path` (`customer_evidence_api`, `commitlayer_connector`, `file_import`, `agent_runtime`, `sample_run`)
with `ingestion_path_label`.

Replaced values: `commitlayer_connector` → `commitlayer_read`; `onboarding_sample` → `sample_source`;
`legacy_unattested` → `agent_reported` with `legacy_rating: true`; `ingestion_path: "facts_api"` →
`customer_evidence_api`. The legacy `trust` (`independent` / `shared` / `self_reported`) is still returned on records
and connections, deprecated, and is not a trust class.

### `GET /v1/evidence/sources` (viewer)

Each entry also carries `can_attest` and `attest_blocked { code, message, handoff: "invite_admin"|"ask_admin"|"replace_key", eligible_attestors }` (the site offers the control on `can_attest` and nothing else) and `health` (below); `runtime_recorder.health` and `evidence_pipeline.health` are described under [Connections](#get-v1connections). `runtime_recorder.keys[].last_used_at` is RFC 3339 UTC.

The facts-API connection as its two sides: `runtime_recorder { title: "Runtime recorder", keys: [{ id, name, side, last_used_at }], evidence_trust_class: "agent_reported", copy }` and `evidence_pipeline { title: "Evidence pipeline", entries: [{ source_id, evidence_key_id, evidence_key_name, evidence_key_prefix, key_side: "evidence"|"full", evidence_trust_class, basis, copy, attestation, attestable, contracts: [{ contract_id, effects }] }] }`, one entry per key and source it may push (`source_id: "*"` for a key with every scope). Each entry also has `rotation` (RD-16): `null`, or while a declared publisher rotation of its source runs `{ role: "outgoing"|"incoming", other_key_id, other_attestation_id, valid_until, checkpoint_authority }` on both keys' entries, so a reader that sees no key names (a key, a member below Admin) still tells the old publisher from the new one. `basis` of an evidence-only key that is not attested for the source now is `unattested_evidence_key`, `attestation_revoked` (an Owner or Admin withdrew it) or `attestation_rotated` (a rotation handed the source to another key), and its `copy` says why it is not eligible (RD-26), never the agent-key sentence of `agent_reported`. Also `mixed_keys` (live keys holding both `actions:record` and `facts:write`), `replacement` (admins, with a mixed key: the two `POST /v1/settings/api-keys` bodies that replace it, never one key with both sides), `classes`, `basis`, `statement { version, text }` and `confirmations [{ id, text }]`. Key ids, names and prefixes are `null` for anyone but an Owner or Admin. No key or hash.

**History** (CL-0100 remediation, RD-25 and RD-27): `history` lists every attestation ever made in the workspace, newest first, ended ones included: the attestation view plus `evidence_key_created_by` (from the key's own record or the audit event that created it, `evidence_key_created_by_source: "key_record" | "audit_log"`; when neither exists it is null with `creator_limitation: "historical_creator_unknown"` and `creator_limitation_text`, never a guessed name), `key_status` (`active`, `revoked`, `deleted`), `key_revoked_at`, `key_revoked_by`, `key_revoke_reason`, `ended_by` (`withdrawal`, `key_revocation`, `rotation` or null) and `validity: { from, until }`. `compromises` lists the compromise invalidations. Names, prefixes, display ids (`evidence_key_display_id`, the name and prefix together), creators and revokers are null for members below Admin.

### `GET /v1/evidence/attestations` (viewer)

`{ items: Attestation[] }`, newest first, revoked ones included.

```ts
Attestation = { id, evidence_key_id, evidence_key_name, evidence_key_prefix, evidence_key_display_id,
  evidence_key_status: "active"|"revoked", source_id, allowed_fact_types: string[],
  granted_level, attestation_version, attestation_statement, attested_by_user_id, attested_at,
  revoked_at, revoked_by_user_id, revoke_reason, audit_event_id, via: "attestation"|"evidence_trust_v0949"|"rotation",
  environment: "production"|"test"|null, reason: string|null, separation_declared: boolean|null,
  valid_until: string|null, rotated_to: string|null,
  status: "active"|"rotating"|"rotated"|"revoked" }
```

### `POST /v1/evidence/attestations/preview` (Owner or Admin, signed in)

`{ sources: string[], change?: "attest"|"change"|"revoke" }` → `{ sources, contracts: [{ contract_id, version }], potentially_affected_actions, more_than, affected_action_ids, affected_actions_total, affected_actions_truncated, settled_verdicts_unchanged: true }` (0.9.56: the impact list itself, newest first, at most 200 ids, never an ellipsis): the active contracts that read the sources and every action recorded under a contract that reads them and not yet settled (no cap since evidence trust slice 5; `more_than` is always `false` and kept for older clients). Stores nothing.

### `POST /v1/evidence/attestations` (Owner or Admin, signed in) → `201`

`{ evidence_key_id, source_id, allowed_fact_types?, confirmations: string[], confirm: true, environment: "production"|"test", reason: string (10..500), separation_declaration: true }` (RD-28: the environment, the reason and the declaration that the attesting person is separate from the key's creator and that the key is outside the agent's control are part of every attestation; `422` without them). **The person who created the key can never attest it** (`403 separate_attestor_required`, `details.handoff`: `ask_admin` when another Owner or Admin exists, `invite_admin` when none does), on this route and on the compatibility route; the creator is read from the key's `api_key.created` audit event, and a key with no such event (`409 creator_unknown`, `details.handoff: "replace_key"`) is replaced with `POST /v1/settings/api-keys/{id}/replace`, never attested. A source already published by another key is refused (`409 source_already_attested`, `details.current_key_display_id`, `details.remedy: "rotate_publisher"`): one key publishes a source, and a second comes in only through a rotation. Sample runs need no attestation. `confirmations` must hold the one id `GET /v1/evidence/sources` lists, `trusted_backend` (statement version 3), or, for existing clients, all five ids of version 2 (`422 confirmation_required` with `details.missing`). `allowed_fact_types` defaults to the types the workspace's action contracts read from the source and, for a source an approved account change's checks read (when the account-change workflow is installed or no contract reads the source), its approved-change record types too: `stripe` `billing.subscription_item`, `billing.invoice_line`; `product_access` `app.enforcement`; `identity_provider` `idp.sso_policy`; `ticketing` `ticket.state`; `notification_delivery` `notification.milestone`; `crm` `identity.relationship` (`422 fact_types_required` when there are none). The same definition is served as `entries[].attestable_fact_types` on `GET /v1/evidence/sources` and `evidence_fact_types` on `GET /v1/settings/api-keys`. An attestation covers a record received while it was in force: before its withdrawal and before the end of a declared rotation overlap (`valid_until`), whichever is first. Refused: `403 session_required` for any API key, whatever its scopes; `403 forbidden` below admin; `403 impersonation_read_only`; `404 key_not_found` (no live key); `409 not_an_evidence_key` (a key that can record actions, or predates scopes); `409 source_not_bound` (the key may not push the source); `409 source_served_by_connector`. A live attestation of the same key and source is revoked and replaced by the next `attestation_version`. Answers `{ attestation, reverification_queued }`: every unsettled action under a contract that reads the source is queued for a re-check (`verify_action`, payload `reason: "trust_changed"`, `cause: "trust_attested"`, idempotency key `verify_action:<claim>:trust:<audit event>`); the run records the cause. Settled verdicts are frozen and keep the configuration they were evaluated with. Audit: `evidence.attested` or `evidence.attestation_changed` (key id and prefix, source, types, level, versions, confirmations; never a key).

Effect: once a source has a live attestation, the engine counts a pushed record for it at the attested level only when an attested key pushed it and its type is allowed; every other pusher of that source name reads `self_reported`. A source without one evaluates as before.

### `POST /v1/evidence/rotations` (Owner or Admin, signed in, not the incoming key's creator) → `201`

`{ source_id, from_key_id, to_key_id, overlap_minutes: 0..1440, reason: string (10..500), environment?, confirm: true }`
moves a source's publisher deliberately (RD-36). The incoming key is attested now (the same rules as an attestation)
and holds **checkpoint authority** from now; the outgoing attestation runs out at `now + overlap_minutes`
(`status: "rotating"`, `valid_until`), when a job ends it (`status: "rotated"`, `rotated_to`). During the overlap both
keys' records count, so nothing in flight is lost, and only the incoming key's checkpoints move the source's coverage
(the outgoing key's are `checkpoint_not_permitted`). `0` hands over at once. Answers `{ attestation, outgoing,
checkpoint_authority, overlap_ends_at, reverification_queued }`. `409 not_current_publisher`, `422 same_key`,
`422 invalid_overlap`. Audit: `evidence.publisher_rotated`, then `evidence.attestation_rotated_out`.

### `GET /v1/evidence/rotations` (viewer)

`{ items: [{ source_id, outgoing: Attestation, incoming: Attestation, overlap_ends_at, state: "overlapping"|"completed" }], checkpoint_authority: { source: key_id } | null }`.

A revoked key authenticates nothing (`401`), so it can neither publish records nor move coverage. A record whose own
key's attestation for its source was revoked reads `attestation_status: "revoked"` (or `"rotated"` after a rotation)
and its ineligibility reason `attestation_revoked` / `publisher_rotated`, never `other_key_attested`.

### `POST /v1/evidence/attestations/{id}/revoke` (Owner or Admin, signed in)

`{ confirm: true, reason: string (3..500), source_id?: string }` (0.9.56: the reason is required, `422` without it;
`source_id`, when sent, must be the attestation's own source, `400 source_mismatch`, so the person confirms which
source loses eligibility). `409 already_revoked`. The answer adds `source_coverage` (the read model every page shows,
"2 of 3 eligible sources" after revoking one of three) and the attestation's `revoke_reason`. The audit event
`evidence.attestation_revoked` carries `reason`, `actor_user_id`, `actor_role`, `source_id`, `affected_contracts`,
`affected_unsettled_actions` and `settled_verdicts_unchanged: true`. When the last live attestation of a source is revoked, its per-source level is removed. Re-queues the affected unsettled actions as above (`cause: "trust_revoked"`). Audit: `evidence.attestation_revoked`.

**A withdrawal is prospective** (CL-0100 remediation, RD-33). An attestation covers the records received while it was in force: records the key sent before the withdrawal keep their class, for settled and unsettled actions alike, and records it sends afterwards are not eligible. Likewise an attestation covers records its key sent before it was made only for actions that have not settled yet (the action's first settlement is its trust cutoff); it never qualifies a record for a decision already made. Times are stored to the second; within one second the attestation, the record and the settlement are ordered by the milliseconds of their sortable ids, so an attestation made after the first settlement in the same second never reaches back, while one that caused the settlement still counts. A source that has ever had an attestation is governed by attestations alone: the legacy per-source rating no longer lifts any of its records. Three distinct trust actions exist, with three distinct effects:

| Action | Route | Effect on records already received | Effect from now on |
|---|---|---|---|
| Routine key revocation | `POST /v1/settings/api-keys/{id}/revoke` | none: they keep their class | the key cannot authenticate; its live attestations end now (`ended_by: key_revocation`) |
| Prospective attestation withdrawal | `POST /v1/evidence/attestations/{id}/revoke` | none | records the key sends for the source are not eligible |
| Explicit compromise invalidation | `POST /v1/evidence/compromises` | the records it covers are no longer evidence in any reading; affected commitments get a reassessment and an `unsafe_reliance` warning, and keep their original decision | the same, for records received inside its range |

### `POST /v1/evidence/compromises` (Owner or Admin, signed in)

`{ source, credential_id?, environment?: "production"|"test", from, to?, reason (10..1000), confirm: true }`. Records of `source` **received** at or after `from` and before `to` (open when omitted), through `credential_id` (an API key's or a connection's id; every credential when omitted), read for actions in `environment` (every one when omitted), are invalidated: their class reads `agent_reported` with basis `compromise_invalidated` and `attestation_status: "invalidated"`, and they satisfy no requirement. Answers `201 { invalidation: { id, source, credential_id, environment, from, to, reason, recorded_by, recorded_at, audit_event_id, applies_to, affected_commitments, affected_actions } }`: every decided commitment with a covered record on its accounts is queued for a re-check (an appended reassessment when its reading changes, and `trust_warnings` on its receipt), and every unsettled action reading the source is re-verified (`cause: "trust_invalidated"`). `400 reason_required` / `invalid_range`, `404 credential_not_found`, `422 invalid_timestamp`, `403 session_required` for any API key. Audit: `evidence.compromise_invalidated`. `GET /v1/evidence/compromises` (viewer) lists them, newest first.

Once a source has a live attestation, only an attested key speaks for it in two more ways: a declared watermark for it from any other pusher is not stored (`watermark_status: source_not_attested` on `POST /v1/facts`), and an identity link touching it counts in the engine's subject map only when its pusher is attested for that source (a link a connector made always counts). An attested key that sends a link another pusher sent first takes the link over.

`statement` is `{ version: 3, text, explanation }`: the founder's explanation ("Your Evidence pipeline key can send records from your backend. …"), the one confirmation (`confirmations: [{ id: "trusted_backend", text: "I confirm this Evidence pipeline key is stored only in a trusted backend and is not available to the agent being evaluated." }]`) and `details`, the statements shown behind "Review what this means". Version 2's five ids (`key_held_by_backend`, `agent_cannot_read_key`, `records_from_system_of_record`, `source_ids_accurate`, `understands_customer_attested`) are still accepted and recorded as version 2. A row keeps the text and version it was made with.

**Contracts state a minimum class.** An expected effect may carry `min_trust_class` (`backend_attested`, `commitlayer_connector` or `externally_verified`; `agent_reported` is refused). A record satisfies it when its class ranks at or above it. While a source has no attestation, the class of a pushed record follows its legacy rating (shown as `legacy_unattested` when the rating lifts it), so a workspace that has attested nothing evaluates as before. With both `min_trust` and `min_trust_class`, both must hold. Removing or lowering either is reported as a weakening.

## Invoices & disputes

### `GET /v1/invoices`

**Response**

`{ items: Invoice[] }`

```ts
Invoice = {
  id,
  vendor,
  period,
  source_ref,
  currency,
  total,
  parse_method: "csv"|"xlsx"|"pdf",
  status: "pending_review"|"accepted",
  line_count,
  created_at
}
```

### `POST /v1/invoices`

**Response**

`Invoice & { lines: InvoiceLine[], review_required: boolean }`

Multipart form `file`, `vendor`, `period`, `mapping?`

### `GET /v1/invoices/{id}`

**Response**

`Invoice & { lines: InvoiceLine[] }`

```ts
InvoiceLine = {
  id,
  sku,
  description,
  quantity,
  unit_price,
  amount,
  contract_id,
  matched_claim_count,
  accepted: boolean
}
```

### `POST /v1/invoices/{id}/accept`

**Request body**

```ts
{ lines: [{ id, sku?, quantity?, unit_price?, amount?, contract_id? }] }
```

**Response**

`Invoice`

### `GET /v1/invoices/{id}/reconciliation`

**Response**

```ts
{
  invoice_id,
  statement_id,
  rows: [
    {
      line_id,
      sku,
      contract_id,
      billed_qty,
      billed_amount,
      verified_vendor_qty,
      verified_strict_qty,
      exceptions: [{ claim_id, strict_verdict, reason }],
      variance_amount_vendor,
      variance_amount_strict
    }
  ]
}
```

### `POST /v1/invoices/{id}/disputes`

**Request body**

`{ line_ids: string[], lens: "vendor"|"strict", notes? }`

**Response**

`Dispute`

### `GET /v1/disputes`

**Response**

`{ items: Dispute[] }`

```ts
Dispute = {
  id,
  invoice_id,
  vendor,
  period,
  status: "draft"|"sent"|"credited"|"rejected"|"partial",
  lens,
  contested_amount,
  credited_amount,
  line_count,
  exception_count,
  package_hash,
  sent_at,
  resolved_at,
  notes,
  created_at
}
```

### `GET /v1/disputes/{id}`

**Response**

```ts
Dispute & {
  lines: [...],
  cover_letter_md: string,
  exports: { pdf, csv, json }
}
```

### `PATCH /v1/disputes/{id}`

**Request body**

`{ status?, credited_amount?, notes?, sent_at? }`

**Response**

`Dispute`

### `GET /v1/disputes/{id}/export.pdf|csv|json`

File

## Calibration (Scale+/Enterprise, transcript assist opt-in)

### `GET /v1/calibration/queue`

**Response**

```ts
{
  items: [
    {
      label_id,
      claim_id,
      label,
      confidence,
      rationale,
      excerpt_redacted: string[],
      labeled_at
    }
  ]
}
```

### `POST /v1/calibration/{label_id}`

**Request body**

```ts
{
  human_label: "customer_confirmed_resolved"|"customer_indicated_unresolved"|"abandoned"|"unclear"
}
```

**Response**

`{ ok }`

### `GET /v1/calibration/stats`

**Response**

```ts
{
  labeled,
  sampled,
  reviewed,
  pending,
  agreement_rate: number|null,
  sample_rate,
  by_label: { [label]: count },
  confusion: { [model_label]: { [human_label]: count } },
  spend_this_month,
  cost_cap
}
```

Queue items carry `excerpt_redacted: [{ role: "customer"|"agent", text }]` and `excerpt_purged: boolean`.

## Internal agents (OpenTelemetry)

### `GET /v1/otel/sources`

**Response**

```ts
{
  items: [
    {
      id,
      name,
      endpoint_url,
      endpoint_key_last4,
      mapping,
      last_seen_at,
      spans_received,
      claims_created
    }
  ]
}
```

### `POST /v1/otel/sources`

**Request body**

`{ name, mapping? }`

Source incl. one-time `endpoint_key`

### `PUT /v1/otel/sources/{id}/mapping`

**Request body**

`{ mapping }`

Source

### `POST /v1/otel/{endpoint_key}/v1/traces`

**Response**

`{ accepted: number, claims: number, facts: number }`: spans read, outcome claims and runtime-context facts made from them. A protobuf body answers `415`.

OTLP/HTTP JSON

Semantic convention documented in `docs/otel-convention.md`

## Verification state (0.9.56)

The canonical action-verification state (`app/engine/state.py`; the guide is verdict-states.md).
Every action view (`POST /v1/actions`, `POST /v1/actions/verify`, `GET /v1/actions/{id}`, `/wait`) carries these at
the top level and, with `copy`, `status_line`, `primary_reason` and `monitoring`, under `state`:

```ts
{
  action_id,
  processing_status: "RECORDED" | "PENDING" | "SETTLED",
  overall_verdict: "PASS" | "FAIL" | "UNKNOWN" | null,   // null while PENDING
  outcome_verdict: "PASS" | "FAIL" | "UNKNOWN",           // missing evidence is UNKNOWN while PENDING
  policy_verdict: "PASS" | "FAIL" | "UNKNOWN",            // while PENDING: FAIL for a violation no later record can undo, else UNKNOWN (never PASS)
  provisional_findings: [{ code, source, message, lens?, check?, detail? }],   // empty once SETTLED
  settlement_deadline, settled_at, observation_window_end, reversal_window_end,
  windows: { measured_from: "requested_at"|"due_at", settlement, observation, reversal },   // durations, e.g. "1h", "24h", "30d"
  verdict_version, snapshot_version, change_reason,
  headline, supporting_copy,                              // one text for the API and every page
  previous_state: {                                       // the version this one replaced, canonical values only
    verdict_version, processing_status, overall_verdict, outcome_verdict, policy_verdict,
    evaluated_at, change_reason, copy                     // copy: "Previous state: PENDING · Outcome UNKNOWN · Policy UNKNOWN"
  } | null,
  trust_summary: { fact_count_total, fact_count_by_trust, source_count_total, source_count_by_trust, source_trust, labels },
  sources: { [source]: { evidence_trust_class, trust_label, last_checkpoint, checkpoint_received, action_time,
                         covers_action, coverage_current, coverage_copy, coverage_explanation,
                         absence_basis: "checkpoint_confirmed"|"deadline_assumed"|null,
                         watermark, trust, connection_id } }
}
```

**`absence_basis` (0.9.58).** When a settled verdict fails the outcome because an expected effect has no eligible
record, the answer says on what basis that absence was concluded: `checkpoint_confirmed` when the source's last
checkpoint covers the settlement deadline, `deadline_assumed` when the source declared no checkpoint or one that
stops before the deadline. It is on the source (`sources.<id>.absence_basis`) and on the missing effect's row
(`checks.expected_effects[].absence_basis`); null wherever nothing is missing, while the action is PENDING, for an
UNKNOWN verdict and for the onboarding sample. The settlement rule is unchanged: a pushed source that never
declared a checkpoint is settled at the deadline, and a missing effect is then FAIL. With `deadline_assumed`,
`supporting_copy` ends with one sentence: "The source reported no checkpoint, so this result assumes its records
were complete at the deadline." (or, for a checkpoint that stops short: "The source's last checkpoint does not
cover the deadline, so this result assumes its records were complete at the deadline."). `headline` is unchanged. A
body settled before 0.9.58 keeps its stored `supporting_copy`; its `absence_basis` is derived when it is served.
Send `observed_through` for every source with each batch (the generated quickstart programs do) so a FAIL reads
`checkpoint_confirmed`.

`state` adds `headline`, `supporting_copy`, `policy_copy` (the pending policy line, e.g. "FAIL — Amount exceeds the
configured $250 limit."), `evaluated_at` and `verdict_change_reason` (= `change_reason`).

- `provisional_findings[].code`: `expected_effect_not_yet_observed`, `evidence_below_trust_requirement`,
  `source_watermark_behind`, `<param>_above_limit` (e.g. `amount_above_limit`: a limit on the action's own parameter,
  known when the action is recorded), `<param>_not_allowed`, `policy_violation_known`, `policy_failing_so_far`,
  `evidence_for_different_subject`, `identity_configuration_missing`. The last two are about records that are not
  the action's own: they are read when a pending action is served and never add a verdict version.
  `evidence_for_different_subject` (0.9.60, RB-41) is present only when a record *names this action* (see
  `identity.resolution.excluded_records`) and belongs to another subject. Its `message` is "Evidence for another
  order was excluded." and its `detail` "Eligible evidence for this order: 0." (with `excluded_count`,
  `eligible_count`). A record that merely arrived in the same workspace is never a finding on any action.
- `overall_verdict` once SETTLED: FAIL when either lens fails, else UNKNOWN when either is UNKNOWN, else PASS.
- `settled_at` is when this result actually settled (an early PASS settles before the deadline);
  `settlement_deadline` is requested_at + the contract's window, kept as context. `observation_window_end`: late
  expected or forbidden effects dated before it re-open a settled action (longest of the window, every forbidden
  effect's `within`, every aggregate limit's `over`, or the action block's `observation_window`).
  `reversal_window_end`: a reversal dated before it re-opens one (longest `reversed_by` `within`, default 30d, or
  `reversal_window`). `state.windows` (RS-8) gives the duration each of these instants is measured with, from
  `requested_at` (or from the action's own deadline when it carries one: `measured_from: "due_at"`, `settlement: null`):
  for `scop_refund_order` `{ settlement: "1h", observation: "24h", reversal: "30d" }`, so `observation_window_end` is
  the requested time plus 24 hours (the same clock time a day later, never the recording time).
  **Deadline-like fields, one meaning each:** `settlement_deadline` (= `settlement.settles_at`): when the contract's
  window closes and the action is judged once every source has caught up. `settlement.uncertainty_cutoff_at`:
  `settles_at` + `SETTLEMENT_MAX_LAG` (48 h), the moment a source still behind stops being waited for and the result
  settles on what arrived (the same name and meaning as a commitment's `evidence_health.uncertainty_cutoff_at`).
  `settlement.deadline` is the deprecated name of `uncertainty_cutoff_at` (same value; kept for clients that read it;
  it was never the settlement deadline). `observation_window_end` and `reversal_window_end`: until when later
  records re-open a settled action. `state.monitoring { active, until }` and `state.status_line` ("Settled PASS · monitoring for late
  changes until …") say whether the settled action is still watched.
- `change_reason`: `action_recorded`, `new_evidence`, `late_evidence`, `late_forbidden_effect`,
  `source_watermark_advanced`, `settlement_deadline_reached`, `settlement_recheck`, `trust_attested`, `trust_revoked`,
  `identity_link_added`, `connector_recovered`, `connector_synced`, `reversal_received`, `manual_reverify`.
- `identity.resolution { status: MATCHED|UNRELATED|AMBIGUOUS|CONFIGURATION_MISSING|NONE, matched_count,
  unrelated_count, unrelated_examples, ambiguous_count, configuration_missing_count, missing_link_types, next_step }`:
  the one identity answer both lenses and every page use. Since 0.9.60 (RB-41) it keeps three sets apart: what
  the workspace received (the Facts API), what is relevant to this action (its matched records, and
  `excluded_records`), and what is eligible to decide it (`eligible_count`). `excluded_count` and
  `excluded_records[] { fact_id, source, fact_type, subject_id, subject_kind, occurred_at, relationship,
  excluded_because: "belongs_to_another_subject", belongs_to }` are the records of a kind the contract expects, from
  the source it reads, inside the window, on another subject, that name this action by a supported reference
  (`relationship`): `action_reference` (the record's `attributes.action_id` / `action_ref` /
  `commitlayer_action_id` is this action), `order_reference` (the record's `attributes.order_id` is the action's
  subject), `payment_reference` (the action's `params.payment_id` / `payment_intent` / `charge_id` is the record's
  subject or payment), `support_case_reference` (the action's `params.support_case_id` / `ticket_id` is the record's
  subject) and `customer_reference` (both name the same `customer_id`). They are never attributed and never decide
  the action. `UNRELATED` now means exactly that such records exist and none is the action's own;
  `unrelated_count` / `unrelated_examples` are the earlier names of the same figures. Records with no such
  reference are not counted here at all: before 0.9.60 any record of an expected kind stored in the workspace
  inside the window made every pending action read `UNRELATED` with `evidence_for_different_subject`.
- `sources.<id>` (0.9.60, RB-43 and RB-44), each attribute its own:
  - provenance: `evidence_trust_class` and `trust_label` are the class of the records the source actually supplied
    to this action, and null when it supplied none. `provenance_state` is `evidence_received`,
    `no_record_through_checkpoint`, `configured_not_checked` or `evidence_not_received`, and `provenance_label` the
    words: the trust label, "No qualifying record observed through <checkpoint>", "Source configured — not yet
    checked" or "Evidence not received" (`provenance_checkpoint` carries the checkpoint). "CommitLayer-read" is only
    ever the class of a record a CommitLayer-managed connector retrieved. `trust` is the connection's legacy rating,
    kept for older clients: it is not a provenance and no label is to be derived from it.
  - connectivity: `configured` (a live connection provides the source, or a live key may publish for it),
    `connection_id`.
  - evidence sufficiency: `evidence_sufficiency` `complete` | `incomplete` | `not_applicable` (every effect the
    contract expects from this source was observed from eligible evidence).
  - absence coverage: `absence_coverage_required` (an expected effect of this source is missing) and
    `absence_coverage_sufficient` (its checkpoint covers the settlement deadline; null when not required);
    `absence_basis` as before.
  - `coverage_state` `verified_complete` | `not_required` | `current` | `behind` | `no_checkpoint`, with
    `coverage_copy` and `coverage_explanation`. A settled verdict whose effects from this source were all observed
    reads `verified_complete`, "Verified from complete eligible evidence.", whenever it settled; `coverage_current`
    is whether the coverage this action's verdict needs from the source is met (true there). Before 0.9.60 an
    early PASS read `coverage_current: false`, "Source coverage is behind this action."
  - monitoring freshness: `monitoring_active`, `monitoring_copy` ("Monitoring for later changes."), and
    `live_checkpoint`, what the source reports now, read when the answer is served. `last_checkpoint` stays the
    checkpoint the verdict was computed with and is never moved to match it.
- `coverage_summary { evidence_sufficiency, copy, settled_before_deadline, monitoring_active, monitoring_until,
  monitoring_copy }`: `copy` is "Verified from complete eligible evidence." on a settled PASS.
- `evaluation_inputs { mode: dry_run|recorded, evaluated_at, contract_id, contract_version, evidence_version,
  evidence_count, excluded_count, evidence_latest_at, source_checkpoints, trust_version, inputs_hash }`
  (0.9.60, RA-3): what this evaluation was computed from. A dry run (`POST /v1/actions/verify` with
  `dry_run: true`) and a recorded evaluation are one engine; with an equal `inputs_hash` their preconditions,
  expected and forbidden effects, eligibility, verdicts, explanation and source attribution are equal. Where two
  answers differ, `evaluated_at`, `evidence_version`, `evidence_count` and `evidence_latest_at` say what arrived
  between them. `facts[].recorded_at` is when each record was stored.
- `live.evidence_newer_than_snapshot` / `verdict.stale`: true only until a re-verification has looked at the newer
  record or trust change. One that changed nothing for the action stores no version and clears it (RB-41).
- `trust_summary { fact_count_total, fact_count_by_trust, source_count_total, source_count_by_trust, source_trust,
  labels }`: each record counted once under its one trust class, each source once under the best class among its
  records; each `*_by_trust` sums to its total. `summary.evidence_trust` (check rows, one record under two checks
  counted twice) is **removed**.
- `evidence_counts` adds `eligibility_scope` (`contract`, or `sample_only` for a sample action) and
  `eligibility_label` ("Eligible for this contract" / "Eligible for this sample only"); for a sample,
  `eligible_sources` and `records_eligible` count the run's own sample-source records.
- `version_history`: the versions as of this snapshot (`verdict_version`, `evaluated_at`, `change_reason`, the three
  verdicts, `processing_status`, `superseded_by`), so the history in an answer ends at the version its headline is.

**Deprecated, derived from the canonical fields** (they cannot disagree with them; verdict-states.md,
"Legacy fields"): `status` (`pending`/`settled`; use `processing_status`), `settles_at` and `settlement.settles_at`
(use `settlement_deadline`), `lenses.outcome.verdict` (= `outcome_verdict`), `lenses.policy.verdict`
(= `policy_verdict`), `action.latest.outcome/policy`, `previous` and `verdict.previous_verdict` (= `previous_state`),
`state.copy` (the judgement sentence on its own; read `headline` and `supporting_copy`), `/v1/actions/summary`. The stored, hashed lens is under
`lenses.<name>.stored { lens, verdict, reason_codes }` for audit; `raw_verdict`, `stored_verdict` and
`summary.evidence_trust` are no longer returned.

**Settlement.** A missing expected effect is FAIL at the deadline only when coverage is current: every source the
contract reads reported past the deadline (a pushed source's checkpoint, a connector's watermark). A source still behind
keeps the action PENDING (`source_watermark_behind`) until it catches up or `SETTLEMENT_MAX_LAG` (48h) ends the wait;
then it settles **UNKNOWN** with `source_stale:<source>` first, never FAIL. A subject with no record of its own whose
sources all reported past the deadline settles FAIL `expected_effect_missing_for_subject` (records of another subject
are never attached); `identity_unmatched` remains only for AMBIGUOUS and CONFIGURATION_MISSING. A worker sweep
(`requeue_overdue_settlements`) re-queues any pending action past its deadline whose re-check was lost.

**Reverification queue.** One queue (`app/engine/reverify.py`). Every accepted record, link and advanced checkpoint
passes through the impact resolver (`app/engine/impact.py`): pending actions a record is about are re-verified
(`ingestion_kind: new_evidence`), settled ones whose contract reads its source and type are re-opened when it is dated
inside their observation or reversal window (`ingestion_kind: late_evidence`), a record for another subject
re-verifies nothing, and a checkpoint re-verifies only the unsettled actions whose deadline it now covers. The answer's
`affected_actions` is exactly the set re-verified, with `affected_action_details[]` (`action_id`, `action_ref`,
`ingestion_kind`, `impact_kind`, `reasons[]`, `reverification_job_id`, `reverify_scheduled`). A re-verification that
changes nothing material stores no verdict version (idempotency.md). Job key: workspace, action, contract version,
evidence version, trust configuration version (`payload.job_key`). One queued job per action: further triggers join
it (`causes`, `triggers`), a running job is never joined. Debounce: `REVERIFY_DEBOUNCE_SECONDS` (default 0) and, for
trust changes, `REVERIFY_TRUST_DEBOUNCE_SECONDS` (default 30, capped at `REVERIFY_DEBOUNCE_MAX_SECONDS` 120), so
attesting three sources one after another produces one `trust_attested` version. `REVERIFY_MAX_ATTEMPTS` (5) attempts,
then the dead-letter state (`live.reverify_dead_letter`, admin metrics). Each run records `trigger`, `causes`,
`job_key` and `trigger_to_verdict_seconds`.

### `POST /v1/evidence/batches` — one atomic evidence batch (analyst, scope `facts:write`) → `201`

The route new code uses (0.9.58). [Publish evidence](/docs/evidence-pipeline) is the full guide, with the generated
programs, the source-binding model and the error table.

```ts
// request
{ workspace_id?: string,                 // checked against the key's workspace when given
  contract_id?: string,                  // when given, every record's source and type is checked against the contract
  action_id?: string,                    // the action the batch is evidence for, when known; it must exist
  links: LinkIn[],                       // the POST /v1/facts link schema
  facts: FactIn[],                       // the POST /v1/facts item schema
  observed_through: { [source_id]: RFC3339 } }   // the checkpoint of every source scanned
// response
{ status: "committed", written: true, workspace_id, contract: { contract_id, version, status } | null, action_id,
  links: [{ index, accepted: true, status: "created" | "exists", link_type, source, linked_source }],
  facts: (FactResult & { index, accepted: true, status: "stored" | "duplicate", duplicate: boolean })[],
  checkpoints: [{ source, observed_through, accepted: true, status: "advanced" | "unchanged" | "already_covered",
                  current_observed_through, affected_action_ids }],
  counts: { links, facts, facts_stored, facts_duplicate, checkpoints },
  affected_actions: string[], reverify_scheduled: boolean, snapshot_versions: { [action_id]: number | null },
  accepted_count, rejected_count: 0, reverification_jobs }
```

The whole request is validated before anything is written. If any link, record or checkpoint is invalid or not
permitted the answer is one error and nothing is stored: no identity link when a record is unauthorized, no record
when a link is invalid, no checkpoint when the batch fails, and no re-verification (a re-verification is a row of
the batch's own transaction). Otherwise the links, the records and the checkpoints are committed in one transaction.
The same batch sent again is accepted: a stored record is `duplicate`, a stored link `exists`, and a checkpoint a
later one already covers is `already_covered`.

```ts
// 403 (a permission is among the reasons) or 422
{ error: { code: "batch_rejected", message,
    details: { written: false, reason,                       // the first problem's code
      summary: string[],                                      // the error as lines to print
      errors: [{ kind: "request" | "fact" | "link" | "checkpoint", index, code, message, source?, fact_type?,
                 link_type?, linked_source?, allowed_sources?, allowed_fact_types?, observed_through? }],
      checks: [{ check, ok, errors }],
      invalid_sources: string[], allowed_sources: string[] | null,
      invalid_fact_types: [{ index, source, fact_type, allowed_fact_types }],
      failed_links: [{ index, code, link_type, source, linked_source, message }],
      failed_checkpoints: [{ code, source, observed_through, message }],
      received: { links, facts, checkpoints }, accepted: { links: 0, facts: 0, checkpoints: 0 } } } }
```

A rejected batch always answers `batch_rejected`; what was wrong is in `details`. `errors[].code` is one of
`workspace_mismatch`, `unknown_contract`, `not_an_action_contract`, `contract_not_active`,
`action_not_found`, `source_not_allowed`, `source_served_by_connector`, `source_not_in_contract`,
`fact_type_not_read`, `invalid_fact`, `invalid_timestamp`, `future_timestamp`, `invalid_link`, `link_not_permitted`,
`invalid_checkpoint`, `checkpoint_not_permitted` (each explained in [Publish evidence](/docs/evidence-pipeline#error-messages)).
Also `400 invalid_batch` with nothing to store, `403 insufficient_scope` for a recorder key and
`403 sample_authorization_not_accepted` with the sample run's token. A scoped evidence key may link only records of
sources the workspace configured, with at least one end in its own scope; a link end with no `source` is the
action's own subject. Audit: `evidence.batch_committed`.

### `POST /v1/evidence/batches/preflight` — check a batch, write nothing (analyst, scope `facts:write`) → `200`

The same body, validated exactly as the batch route validates it, with nothing written. An empty body checks the
key, the workspace and the contract alone.

```ts
{ ok: true, written: false, workspace_id, contract, action_id,
  key: { id, scopes, fact_sources }, allowed_sources: string[] | null,
  checks: [{ check: "workspace" | "contract" | "key_scopes" | "sources" | "fact_types" | "identity_links"
                    | "checkpoint_permissions", ok, errors }],
  received: { links, facts, checkpoints },
  source_bindings: SourceBinding[],     // the bindings this key publishes for
  checkpoint_sources: string[] }
```

A batch that would be rejected answers the same structured error with the code `preflight_failed`. The batch route
validates again by itself: the preflight is never a permission.

### `GET /v1/evidence/source-bindings` — the workspace's source-binding record (viewer)

```ts
{ record: null | {
    record_version: 1, workspace_id, contract: { contract_id, version, subject_kind },
    bindings: [{ role: "payment" | "order" | "support" | null,   // the role the source plays in the contract
                 provider: string | null,                        // what the workspace named: a system, "backend", "other"
                 source_id: string,                              // the exact id the contract reads; never a display name
                 path: "connector" | "facts_api_plan" | "facts_api",
                 pushed: boolean,                                // the workspace's backend sends it
                 required, subject_kind, subject_match: "action_subject" | "linked",
                 fact_types: string[], expected_effects: [{ code, fact_type, where }],
                 link: { link_type, source, subject_kind, linked_source, linked_subject_kind } | null,
                 evidence_key_scope: boolean, checkpoint: boolean }],
    source_ids: string[],
    evidence_key: { scopes: ["facts:write"], fact_sources: string[], evidence_class },
    checkpoint_sources: string[],
    links: [{ link_type, left: { source, subject_kind }, right: { source, subject_kind } }] } }
```

One record per workspace, derived on every read from the installed contract, the setup's answers and the
connections (`app/onboarding/bindings.py`). The evidence key's scope, the `source` of every fact and both ends of
every identity link in the generated programs and the per-source helpers, the checkpoint sources, the attestation
rows, the contract's coverage and the Connections page (`GET /v1/summaries/connections`
`evidence_pipeline.bindings` and `expected_sources`) all carry these source ids. `GET /v1/onboarding` `identity.links`
names them too, so a workspace whose backend sends its orders links a payment to `orders`, never to the pack's
default `shopify`.

### `POST /v1/evidence/batch` — publish evidence with source checkpoints (analyst, scope `facts:write`) → `201` — **deprecated**

Deprecated in 0.9.58 in favour of `POST /v1/evidence/batches`. The route is kept exactly as 0.9.56 shipped it, for
the client versions that call it (PyPI `commitlayer` 0.1.4 `publish_batch`, npm 0.1.5 `publishBatch`): same request,
same answer, same per-item results. It is not atomic across a refused checkpoint (the row says `accepted: false` and
the records sent with it stay), so a caller reads every `accepted`. Every answer carries `Deprecation: true` and
`Link: </v1/evidence/batches>; rel="successor-version"`, and the OpenAPI operation is marked deprecated.

```ts
// request
{ facts: FactIn[],                       // the POST /v1/facts item schema
  links?: LinkIn[],                      // optional, the POST /v1/facts link schema
  observed_through: { [source]: RFC3339 } }   // "this source was scanned through this moment"
// response
{ facts: FactResult[],                   // per record, exactly as POST /v1/facts answers
  checkpoints: [{ source, observed_through, accepted: boolean, status, affected_action_ids,
                  reason?: "source_not_attested" | "older_than_current_checkpoint", current_observed_through? }],
  affected_actions: string[],            // every action this batch changes (records and checkpoints)
  reverify_scheduled: boolean,
  snapshot_versions: { [action_id]: number | null },   // poll GET /v1/actions/{id} until snapshot_version passes it
  accepted_count, rejected_count, reverification_jobs }
```

A checkpoint for a source with zero records is valid. A checkpoint advances that source's watermark for the
workspace's evidence pipeline (what settlement waits on); once a source has a live attestation, only an attested key
moves it. `403 insufficient_scope` for a recorder key; `403 source_not_allowed` for a source the key is not bound to;
`409 source_served_by_connector`; `403 sample_authorization_not_accepted` with the sample run's token; `400
invalid_batch` with nothing to store. Publish checkpoints for every configured source on a schedule (every minute is
enough), not only when there are records: at the deadline a source counts as current only when its checkpoint is at or
after the deadline. Audit: `evidence.batch_published`.

`POST /v1/facts` answers the same per-record fields and, from 0.9.56, `affected_actions`, `reverify_scheduled`,
`identity_rechecks` and, per record, `affected_actions: [{ action_id, kind: new_evidence|late_evidence|
late_forbidden_effect|reversal_received|outside_windows, settled, scheduled }]` and `identity_status:
MATCHED|UNRELATED|CONFIGURATION_MISSING`. `affected_action_ids` now includes settled actions a record re-opens (before
0.9.56 a late duplicate refund answered `[]`).

### Canonical read models (viewer)

Every page reads these; nothing counts in the browser (`app/engine/read_models.py`).

- `GET /v1/summaries/verdicts` → `{ snapshot_version, generated_at, lens: "overall_settled", lens_label, scope: "real",
  counts: { total, pass, fail, unknown, pending }, lenses: { outcome: {pass, fail, unknown}, policy: {pass, fail,
  unknown} }, lens_labels, workflows: [{ contract_id, display, counts, lenses }], samples: {…counts}, excluded: {
  sandbox, test, sample }, definitions }`. Counts are settled overall verdicts plus PENDING, real activity only, read
  in one statement over every current snapshot; `snapshot_version` names that state.
- `GET /v1/summaries/refund-activity?show=real|sample|all&limit=50` → the refund workflow's `counts` and `lenses` (the
  same numbers as the summary's refund workflow, `counts_scope_label: "Real activity only"`, same `snapshot_version`),
  `samples`, `items` (each an action with `state`, `activity: "real"|"sample"` and `latest.snapshot_version`) and
  `coverage`.
- `GET /v1/summaries/source-coverage?contract_id=scop_refund_order` → `{ eligible, of, headline: "N of M eligible
  sources", sources: [{ source, path: managed_connector|evidence_pipeline, configured, credential_present, attested,
  connected, healthy, watermark, last_evidence_at, eligible, missing, revoked, state:
  eligible|revoked|missing|not_eligible, trust_class, trust_label }], trust_vocabulary }`.
- `GET /v1/summaries/connections` → `{ runtime_recorder: { credential_status, keys, last_action_at, health, scopes },
  evidence_pipeline: { credential_status, keys, last_fact_at, checkpoints, attestation, source_bindings, health,
  scopes }, managed_connectors: [{ id, source, connector_status, last_sync_at, watermark, scopes, health }],
  legacy_keys, source_coverage }`. Key names and prefixes for Owners and Admins only; never a key.
- `GET /v1/summaries/integration-health` → `{ status: healthy|attention, recorder, evidence_pipeline,
  managed_connectors, source_coverage, reverification: { queued, dead_letter }, issues: [{ source, issue }] }`.

The trust vocabulary is one set of names everywhere (trust-terminology.md): Agent-reported
(`agent_reported`), Backend-attested (`backend_attested`), CommitLayer-read (`commitlayer_read`), Externally verified
(`externally_verified`), Sample source (`sample_source`). The legacy ladder (`independent`, `shared`,
`self_reported`) is kept on connections and records, deprecated, and is never a trust class.

## Actions

Action verification against `kind: action` contracts (reference: [action-contracts.md](/docs/action-contracts)). Roles: `analyst` or higher (API keys qualify) for `POST /v1/actions`, `POST /v1/facts` and `POST /v1/actions/verify`; `viewer` for the `GET`s. Every request is tenant-scoped by the token. Verdict labels are `PASS | FAIL | UNKNOWN`, lenses `outcome | policy`.

Common errors: `404 unknown_contract` (no such contract id), `400 not_an_action_contract` (the id names an outcome contract), `409 contract_not_active` (a new action recorded against a workspace draft or an archived version; below), `404 not_found` (no such action), `400 invalid_request` (neither `action_id` nor `action` sent, or a malformed value), `400 invalid_fact` (bad `source`/`fact_type` identifier). On a paid plan there is no `402` on recording or verifying an action: past the monthly allowance every action is still recorded and verified, and the response's `allowance` block says whether it fell within the allowance or into overage (at the plan's per-action rate). On Developer the grace past the allowance is bounded (72 hours or 250 actions): inside it the block says `grace`; after it a new action, inline or recorded, answers `402 allowance_exceeded` and nothing is stored, while re-recording an existing `action_id`, verifying by id, dry runs and the settlement re-checks of recorded actions continue. `429 rate_limited` and `429 fair_use_exceeded` (Developer's daily caps) carry `Retry-After`. The three `POST` routes take a slot of the write gate and can answer `429 workspace_busy` or `503 busy` (see the error table above); a `dry_run` verification stores nothing and takes none. A **new** `action_id` counts one verified action against the month it is recorded in (see Metering); recording the same `action_id` again, `dry_run` verifications, verifying an already recorded action by id, and sandbox runs are never metered.

### Shapes

```
ActionIn = { action_id?: string(<=120), contract_id: string, contract_version?: number, workflow_id?: string, agent_id?: string,
             action_type?: string, subject_id: string, subject_kind?: string, requested_at?: ISO-8601, params?: object, channel?: string,
             compensates?: string,    // the earlier action this one corrects; see "Compensation" in docs/action-contracts.md
             environment?: "production"|"test" }   // production when omitted; see "Environment" under POST /v1/actions
FactIn   = { source: string, subject_id: string, subject_kind?: string, fact_type: string, occurred_at: ISO-8601, attributes?: object, raw_ref?: string(<=200) }
LinkIn   = { subject_id: string, source?: string, linked_subject_id: string, linked_source?: string, link_type?: string }   // two record ids that are the same case; link_type defaults to same_case

Action   = { id, action_id, contract_id, contract_version, workflow_id, agent_id, action_type, subject_id, subject_kind,
             requested_at, params: object, channel, environment: "production"|"test",
             recorded_via: "api_key"|"session"|"impersonation"|"mcp:api_key"|"mcp:oauth"|"mcp:session"|null,
             period: "YYYY-MM", compensates: string|null,
             resolution: { state: "compensating"|"compensated"|"compensation_failed", by, by_claim_id, at } | null,
             latest: null | { outcome: Verdict, policy: Verdict, status: "pending"|"settled", settles_at, computed_at } }

ActionVerification = {
  action: Action,
  contract: { id, version, display, window, kind: "action" },
  status: "pending"|"settled", settles_at,
  lenses: { outcome: LensResult, policy: LensResult },
  checks: { preconditions: Check[], limits: Check[], aggregate_limits: Check[], expected_effects: Check[], forbidden_effects: Check[], reversals: Check[] },
  summary: { expected: number, observed: number, headline: string },
  facts: Fact[],            // every stored fact for the action's subject id (oldest first, max 200; `text` attributes stripped)
  dry_run: boolean
}
LensResult = { verdict: "PASS"|"FAIL"|"UNKNOWN", raw_verdict: "VERIFIED"|"NOT_VERIFIED"|"UNVERIFIABLE", reason_codes: string[], reason_labels: string[],
               evidence: EvidencePointer[], verdict_hash, prev_hash, computed_at, explanation: string }
Check = { kind: "precondition"|"limit"|"aggregate"|"expected_effect"|"forbidden_effect"|"reversal", description, source: string|null, type: string|null,
          code: string, ok: boolean, observed: boolean, fact_id: string|null, occurred_at: string|null, value: any, message: string|null }
```

`Check.code` is the check's reason code: for expected effects it is `effect_observed:…` when `ok` and `expected_effect_missing:…` otherwise; for the other kinds it names the violation (`precondition_unmet:…`, `limit_exceeded:…`, `aggregate_exceeded:…`, `duplicate_effect:…`, `forbidden_effect_observed:…`, `effect_attr_mismatch:…`, `reversed:…`) whether or not it fired, so read `ok`. `value` is the parameter value for limits, the measured total for aggregates, `{expected, observed}` for an `effect_attr_differs` check that fired, and the matched fact's attributes for the other kinds. `ok` and `observed` differ: an observed forbidden effect is `observed: true, ok: false`; a precondition whose state record exists but does not match is `observed: true, ok: false`; a missing state record is `observed: false, ok: false`.

### `POST /v1/actions` — record an action (analyst, scope `actions:record`)

**A recorded action is immutable.** Sending an existing `action_id` again with the same action is a no-op that returns the action as recorded (safe to retry; optional fields may be left out). It is a different action, answered `409` with code `conflict` and changing nothing, when it names a different contract, subject, workflow, agent, type, channel or `compensates`; when it gives a different value for a parameter both records carry (or for `currency`), compared the way the checks read it, numbers as numbers, text without regard to case, and a yes or no as a boolean, its word or `1`/`0`; when it carries a parameter one of the contract's checks reads that the first record did not carry; or when its `requested_at` is after the action's window, or before the recorded one by more than `MAX_CLOCK_SKEW_SECONDS`. Everything else is the same action said again: a `requested_at` inside the window (a retry, or the second tool call of one action; two recorders' clocks may differ by the allowed skew), a recorder's own `mcp_tool` and `mcp_request_id`, a parameter the workspace's recorder mapping lists under `describes` for the tool (a reason two tools word differently), a parameter no check reads that only one of the two records carries. The first record stands and nothing a later one says is added to it. `params` may not carry `_units`, `_resolution` or `_compensates`, names the product keeps for what it records itself (`400 invalid_request`). For a different action, record it under its own id, or record a compensating action. `requested_at` further ahead than `MAX_CLOCK_SKEW_SECONDS` (15 minutes) answers `400 invalid_request`.

Idempotent on `action_id` (`raw_ref = agent_api:action:<action_id>`): a repeat of the same action answers `201` with the action as first recorded and its stored current verdict, `idempotent_replay: true` and the header `Idempotent-Replay: true`, and writes nothing (no action row, verdict version, usage, audit row or settlement job). The same `action_id` with a different payload answers `409 conflict` with `details: { action_id, mismatched_fields: ["params.amount", …] }` (idempotency.md). 

**Only a contract that governs records.** A new action is recorded against the version that governs: `contract_version` when given, else the workspace's selected version, else the library's. A workspace **draft** nobody selected (what a pack installation leaves until `POST /v1/contracts/{id}/select`) and an **archived** version (one superseded by a later selection) govern nothing, and recording a new action against either answers `409 contract_not_active` with `details: { contract_id, version, status: "draft" | "archived", active_version: number | null }`, in every environment, `test` included, and stores nothing. Select the version, or record against `active_version`. An unselected library contract is accepted, as before. A retry of an `action_id` recorded before its version was archived is the same action and answers `201`; the action stays pinned to that version and its verification and re-checks continue. The action view's `contract_status` (`library`, `active`, `draft` or `archived`) is the status of the version the action is pinned to now. The MCP tool `record_action` answers the same error with the same `details`. A `dry_run` verification (`POST /v1/actions/verify` with an inline action) stores nothing and may name a draft, so a contract can be tried before it is selected. Without `action_id` one is generated and every call creates a new action. An effect counts only at or after `requested_at`, so record before the tool runs or send the time it started. Recording does not verify. Audit: `action.recorded`.

```json
POST /v1/actions
{
  "action_id": "act_demo_refund_001",
  "contract_id": "refund_workflow",
  "workflow_id": "wf_cancel_and_refund",
  "agent_id": "whatsapp-support-agent",
  "action_type": "refund_order",
  "subject_id": "order_10231",
  "subject_kind": "order",
  "requested_at": "2026-09-28T10:42:00Z",
  "params": {"amount": 180.0, "currency": "USD", "reason": "customer_cancelled"},
  "channel": "whatsapp"
}

201
{
  "action": {
    "id": "act_01m3mggydp4h27rn5v9km2jw9s",
    "action_id": "act_demo_refund_001",
    "contract_id": "refund_workflow",
    "contract_version": 2,
    "workflow_id": "wf_cancel_and_refund",
    "agent_id": "whatsapp-support-agent",
    "action_type": "refund_order",
    "subject_id": "order_10231",
    "subject_kind": "order",
    "requested_at": "2026-09-28T10:42:00Z",
    "params": {"amount": 180.0, "currency": "USD", "reason": "customer_cancelled"},
    "channel": "whatsapp",
    "period": "2026-09",
    "latest": {"processing_status": "RECORDED", "status": "recorded", "overall_verdict": null, "outcome_verdict": "UNKNOWN", "policy_verdict": "UNKNOWN", "settlement_deadline": "2026-09-28T11:42:00Z", "snapshot_version": null, "headline": "Recorded · verification is starting", "...": "..."}
  }
}
```

`latest` is never `null` (RS-3). An action is stored before its verification (a verification that fails is retried by
a job), so a read in between finds it with nothing verified: its `latest` is then the RECORDED state
(`processing_status: "RECORDED"`, `status: "recorded"`, no overall verdict, `UNKNOWN` lenses, no snapshot or verdict
version, the contract's `settlement_deadline`). Lists (`GET /v1/actions`, `GET /v1/summaries/refund-activity`) serve
the same.

**Environment.** `environment` says which environment the action belongs to: `production` when omitted, `test` for an action from a test or staging run of your own. CommitLayer records what the caller says and cannot check it; in particular it cannot tell whether the systems of record behind an action hold test-mode data. An action marked `test` is recorded, verified and metered like any other. It is not the workspace's "own action" on the Overview card and never counts as a real action in the guided setup. Sending an existing `action_id` with another `environment` is a `409 conflict`; leaving the field out of a retry is not. `recorded_via` in the response is how the recording arrived (`api_key`, `session`, `mcp:api_key`, ...); it is null for actions recorded before the field existed. The MCP tool `record_action` takes the same `environment` argument. The published SDKs and recorders have no parameter for it, so their actions are `production`.

### Scoped checkpoints

*(CL-0100 remediation.)* A workspace-wide watermark claims that the whole source is complete up to a moment, for every environment and every account. A collector that reads one part of a source declares a **scoped checkpoint** instead, in `POST /v1/facts` (`checkpoints`) or on the product-access interface (`checkpoint_scope` beside `observed_through`):

```ts
CheckpointIn {
  source: string, observed_through: string,      // ISO with an offset
  environment: "production" | "test",
  source_instance?: string,                      // "default"
  collector_epoch?: string,                      // "1"; a restarted or replaced collector starts a new epoch
  partition?: string,                            // "*" (the whole source instance) unless named
  entities?: string[],                           // the subjects a named partition covers
  complete: boolean                              // only a complete successful collection moves it
}
```

Each answer carries `checkpoints: [{ environment, source, source_instance, collector_epoch, partition, entities, observed_through, status }]` with `status` `advanced`, `unchanged`, `incomplete_attempt` (recorded, nothing moved), `invalid_watermark` (earlier than the scope's current checkpoint) or `source_not_attested` (the source has an attestation and this key is not it). Settlement reads, for each source of an action, the workspace-wide watermark or the furthest scoped checkpoint of the action's environment whose partition is the whole source or names one of the action's accounts, whichever is further (`sources[].coverage_scope` names it). A checkpoint of another environment, partition or account never moves it, so a silent source stays silent for the actions it would cover. A connector publishes scoped checkpoints itself after a **complete** read of part of a source, with the connection as the credential: the reference application per instance (every source it serves, partition `*`, the instance's environment) and Stripe for the subscriptions approved changes name (partition `commitment_billing`, the key's mode); a read that could not collect a required scope publishes none. Only a source's checkpoint authority moves a scoped checkpoint (during a rotation, the incoming key).

### `POST /v1/facts` — push facts from systems of record (analyst, scope `facts:write`)

An API key needs the `facts:write` scope (`403 insufficient_scope` otherwise; a `recorder` key never has it) and may push only for the sources it is bound to (`403 source_not_allowed`). A source a live connector serves, by its own name or by what it provides, cannot be pushed through any key (`409 source_served_by_connector`): a pushed fact never stands in for what the connector reports. Inline `facts` on `POST /v1/actions/verify` follow the same rules outside a dry run.

A fact's `occurred_at`, and any declared watermark, further ahead than `MAX_CLOCK_SKEW_SECONDS` (15 minutes) answers `400 invalid_fact`; the request is not applied. The server's own ingestion time is stored apart from `occurred_at` and cannot be set by the caller.

The attribute `_collection` is reserved: it is the server's record of how a connector read a fact directly (source instance, object, revision, collection time; docs/connectors/reference_app.md). A pushed fact that carries it answers `400 invalid_fact` and nothing is stored, on `POST /v1/facts`, the evidence batches and `POST /v1/product-access/seat-allocations` alike. Every record in an action's view (`facts`, `facts_after_settlement`) carries `acquisition`: `{method: "direct_read", source_instance, environment, object_id, object_revision, source_event_at, collected_at, credential_role, …}` for a record a connector read, `{method: "pushed", credential_id}` for a pushed one whatever source it names, `{method: "imported"}` for an uploaded file and `{method: "sample"}` for the onboarding sample.

`{ facts?: FactIn[], links?: LinkIn[], watermarks?: { [source]: timestamp }, workspace_id?, environment? }`, up to 1000 facts per call (`FactIn` takes an optional `source_revision`); a push carries at least one fact, link or watermark (a source that caught up with nothing new sends its watermark alone). `watermarks` states that everything up to that time has been sent for a source; settlement waits on it instead of the clock (see `docs/action-contracts.md`, settlement), and advancing it brings forward any re-check waiting on the source. Idempotent on `raw_ref` and `source_revision` (RD-40): the same `raw_ref` (and revision) with the same source, type, subject and attributes is a `duplicate` and keeps the first observation's time; the same `raw_ref` with different content refuses the whole push, `409 raw_ref_conflict` with `details.conflicts: [{ index, raw_ref, source_revision, existing_fact_id }]`, and nothing is written; a changed provider object (a subscription, an invoice) is sent with its own `source_revision` and is stored as a new observation. When `raw_ref` is omitted the engine uses `agent_api:fact:<sha256 of [source, subject_id, fact_type, occurred_at, attributes]>`, so identical facts are skipped and changed ones become new facts. `source` and `fact_type` must be lowercase identifiers (`[a-z][a-z0-9_.:-]{0,63}`). Pushing a fact marks its `source` as available for `missing_fact_source`. A watermark only moves forward. Audit: `facts.pushed`.

The answer is per record (evidence trust slice 3), with the aggregate fields kept for existing clients:

```ts
{
  facts: [{
    index, fact_id, status: "stored" | "duplicate", raw_ref, source_revision,
    accepted: boolean, rejection_reason: null | "duplicate_fact",  // a record sent again is answered with the stored one
    source_id, fact_type, subject_id, observed_at,
    ingestion_path: "customer_evidence_api", ingestion_path_label,   // how it arrived; never a trust class
    ingestion_kind,                            // new_evidence | late_evidence | outside_windows | replay | null (about no action)
    credential: { id, name } | null,          // the key that sent it; its name only to that key; never the key
    origin,                                    // the stored provenance class (customer_backend, agent_self_report, ...)
    evidence_trust_class, trust_label,         // agent_reported | backend_attested | commitlayer_read | externally_verified | sample_source
    computed_trust_class, legacy_rating, basis, trust_copy,   // computed_trust_class: the same value, kept for existing clients
    attestation_status,                        // valid | fact_type_not_allowed | revoked | rotated | other_key_attested
                                               // | not_attested | not_attested_when_received | invalidated
                                               // | not_applicable
    eligible_contract_ids, ineligible_contract_ids,
    ineligibility_reasons: [{ contract_id, reason }],  // compromise_invalidated | credential_available_to_agent |
                                                       // fact_type_not_allowed | credential_not_attested_for_source |
                                                       // attestation_revoked | publisher_rotated | source_not_attested |
                                                       // no_evidence_credential | insufficient_trust
    affected_action_ids,                       // the actions this record re-verifies
    affected_actions: [{ action_id, ingestion_kind, impact_kind, matched_by, settled, scheduled, job_id, kind }],  // kind: deprecated name of ingestion_kind
    identity_link_status: "matched" | "unmatched",
    watermark_status: "current" | "behind" | "not_declared",
    reverify_scheduled: boolean,
  }],
  accepted_count, rejected_count,
  watermarks: [{ source_id, status: "advanced" | "unchanged" | "invalid_watermark" | "source_not_attested", watermark, affected_action_ids }],
  affected_actions: string[],                  // exactly the actions this push re-verifies; [] when it is about no action
  affected_action_details: [{ action_id, action_ref, settled, ingestion_kind, impact_kind,
                              reasons: [{ matched_by, check, source, fact_id?, fact_type?, subject_id? }],
                              reverification_job_id, reverify_scheduled }],
  reverify_scheduled: boolean,                 // false when affected_actions is empty
  reverification_jobs: string[],               // one per affected action, however many of its records arrived
  snapshot_versions: { [action_id]: number | null },
  settlement: { scheduled_action_ids, released_action_ids, completed_action_ids: [], asynchronous: true },
  links: [{ index, link_type, source, linked_source, accepted, status: "created" | "exists" | "rejected",
            reason: null | "link_not_permitted" | "source_not_allowed" | "invalid_link", message? }],
  links_rejected,
  ingested, linked,                            // linked: the links created by this push, never a rejected one
}
```

**Identity links have one authorization (RD-34)** on this route, `POST /v1/evidence/batch` and
`POST /v1/evidence/batches` (`app/engine/link_auth.py`), the engine's own rule: a link counts unless one of its sources
is attested for an evidence key and the pusher is not that key. A key bound to sources may link only when one end is
its own and both ends are sources of the workspace. A link that fails is refused where it arrives, never stored and
reported as linked: here as its own row (`status: "rejected"`, `reason`), the rest of the push going ahead; in the
atomic batch as `403 batch_rejected`. A link touching an approved change's identity refuses the whole request
(`403 commitment_identity_reserved`).

**Scheduled, not completed (RB-53).** `affected_actions` counts what this request scheduled: the re-verifications the
impact resolver queued and the waiting settlement re-checks a checkpoint brought forward
(`affected_action_details[].reasons[].check: "settlement_released"`). Settlement runs on the worker, so
`settlement.completed_action_ids` is always empty in the answer; poll each action until its snapshot version passes
`snapshot_versions`.

Eligibility is against the selected action contracts that read the record's source and type: an expected effect's
trust requirement, and none for a forbidden effect or a reversal. Refusals of the whole push carry
`details.reason`: `credential_not_authorized_for_source` (with `details.sources`) on `403 source_not_allowed`,
`source_served_by_connector` on `409`, and `future_timestamp` or `invalid_watermark` on `400 invalid_fact`.

**Reverification is event-driven** (`app/engine/reverify.py`). A new record, a link, a watermark that now covers an
action's time, an attestation, a revocation and a connector that recovers from an error each queue a re-verification
of the unsettled actions they concern, outside the request, through `verify_action`. Records, links, watermarks and
recoveries are debounced: while an action has one queued and not yet run, the next joins it (`payload.causes`). A
trust change always gets its own run. A settled verdict is never re-opened by any of them (reversals and late
evidence re-open one through their own jobs, as before). When every expected effect is satisfied the verdict settles at
once; the window is the longest the engine waits, not a delay.

Every stored fact carries a `trust_class` (`docs/packs/evidence-provenance.md`): `native_connector` for connector facts, `imported_batch` for uploads, `runtime_context` for OpenTelemetry, and for this endpoint the class of the key that pushed it: an evidence key's `evidence_class` (`customer_backend` by default, `provider_webhook`, `blockchain_confirmation`), or `agent_self_report` when the key also holds `actions:record`. `agent_self_report` and `runtime_context` rank as `self_reported` for `min_trust` whatever the operator declared for the source, so the party that recorded an action cannot also prove it. The pushing key's id is kept on the fact (`pushed_by`); both appear on every fact in a verification view.

`links` records that two ids are the same case, for example a support ticket and the order it is about. An effect observed on a linked subject counts for the action's subject (an agent that notifies the customer on the ticket has notified the customer about the order), and effects on linked subjects are never reported as orphans. Links are direction-free and idempotent; a `link_type` (`ticket_to_order`, `ticket_to_subscription`, `invoice_to_customer`, …) names what the link is and is what a pack's coverage counts; it defaults to `same_case`. `POST /v1/actions/verify` accepts the same `links` inline.

```json
POST /v1/facts
{
  "facts": [
    {"source": "shopify", "subject_id": "order_10231", "subject_kind": "order", "fact_type": "order_status",
     "occurred_at": "2026-09-28T10:41:30Z", "attributes": {"status": "open", "total": 180.0}},
    {"source": "stripe", "subject_id": "order_10231", "subject_kind": "order", "fact_type": "refund",
     "occurred_at": "2026-09-28T10:42:07Z", "attributes": {"amount": 180.0, "currency": "USD", "refund_id": "re_1Q2x"}},
    {"source": "crm", "subject_id": "order_10231", "subject_kind": "order", "fact_type": "note_added",
     "occurred_at": "2026-09-28T10:42:09Z", "attributes": {"author": "whatsapp-support-agent"}},
    {"source": "messaging", "subject_id": "order_10231", "subject_kind": "order", "fact_type": "customer_notified",
     "occurred_at": "2026-09-28T10:42:11Z", "attributes": {"channel": "whatsapp"}}
  ]
}

201  {"facts": [...one result per record...], "accepted_count": 4, "rejected_count": 0, "ingested": 4, "linked": 0, ...}
     // a second identical call: every record "accepted": false, "rejection_reason": "duplicate_fact", "ingested": 0
```

**The onboarding sample's terminal path.** With the header `X-CommitLayer-Sample-Token` (from
`POST /v1/onboarding/refund-sample-runs`), `POST /v1/actions` (recorder key) and `POST /v1/facts` (evidence key) store
the run's own fixed action and records and nothing else: every field must be the run's (`payloads` in the run's
answer), or the whole request is `403 sample_token_scope` and nothing is applied. The token must be the run's latest,
unexpired, for this workspace, and the key must have been created by the person who started the run
(`403 sample_token_invalid`, `sample_token_expired`, `sample_token_wrong_user`). Only then is the action stored with
`environment: "sample"` and the run's `sample_run_id`, and each record with the class `onboarding_sample`; a sample
action is never metered, and the sample's watermarks are the run's own, never the workspace's. Without the header no
request can produce either: `environment` accepts only `production` and `test`, `_sample_scenario` is a reserved
parameter, and no record field sets a class. The token is never logged or echoed.

### `POST /v1/actions/verify` — verify now (analyst)

`{ action_id?: string, action?: ActionIn, facts?: FactIn[], dry_run?: boolean }`. Send either `action_id` (a recorded action) or an inline `action` (recorded or updated first); inline `facts` are ingested before evaluation. Both lenses are evaluated synchronously against the action's own contract and the response is the full `ActionVerification`.

`dry_run` semantics: with `dry_run: true` the action, the facts and the verification are evaluated inside a savepoint that is rolled back — nothing is stored (no action, no facts, no run, no verdicts, no re-check job, no audit entry) and the response carries `dry_run: true`. For an already-recorded action, dry-run verdict hashes equal what a persisted verification over the same facts would produce; for an action first seen inline in a dry run, the internal `id` (which is part of the hash) is generated again when the action is really recorded. With `dry_run: false` (default) the action and facts are stored, a `Run` (`triggered_by: "action"`) with two chained verdicts is written, a `verify_action` job is queued at `settles_at` when the result is `pending`, and the audit log records `action.verified`.

The example is the repository's demo case (`tests/test_actions.py`): every effect happened except the Shopify cancellation. `facts` and the second lens are abbreviated.

```json
POST /v1/actions/verify
{
  "dry_run": true,
  "action": { ...ActionIn from POST /v1/actions above... },
  "facts": [ ...the four FactIn from POST /v1/facts above... ]
}

200
{
  "action": { "id": "act_01m3mggybvd8qj2hjzmb9m9j8b", "action_id": "act_demo_refund_001", "contract_id": "refund_workflow",
              "contract_version": 2, "workflow_id": "wf_cancel_and_refund", "agent_id": "whatsapp-support-agent",
              "action_type": "refund_order", "subject_id": "order_10231", "subject_kind": "order",
              "requested_at": "2026-09-28T10:42:00Z", "params": {"amount": 180.0, "currency": "USD", "reason": "customer_cancelled"},
              "channel": "whatsapp", "period": "2026-09",
              "latest": {"outcome": "FAIL", "policy": "FAIL", "status": "settled", "settles_at": "2026-09-28T10:57:00Z", "computed_at": "2026-09-28T17:20:41Z"} },
  "contract": {"id": "refund_workflow", "version": 2, "display": "Refund workflow (internal agent)", "window": "15m", "kind": "action"},
  "contract_status": "active",
  "status": "settled",
  "settles_at": "2026-09-28T10:57:00Z",
  "lenses": {
    "outcome": {
      "verdict": "FAIL", "raw_verdict": "NOT_VERIFIED",
      "reason_codes": ["verified_condition_not_met", "expected_effect_missing:shopify.order_cancelled"],
      "reason_labels": ["Verified condition not met", "Expected effect not observed: shopify order_cancelled"],
      "evidence": [
        {"source": "whatsapp-support-agent:claim", "subject_id": "order_10231", "fact_id": null, "field": "claimed_at",
         "value": "2026-09-28 10:42:00", "occurred_at": "2026-09-28 10:42:00", "sha256": "f8d788fa…"},
        {"source": "whatsapp-support-agent:claim", "subject_id": "order_10231", "fact_id": null, "field": "absence",
         "value": "no shopify.order_cancelled effect observed within the window", "occurred_at": "2026-09-28 10:42:00",
         "sha256": "750c42a1…", "primitive": "effect_observed"}
      ],
      "verdict_hash": "f8f3d619…", "prev_hash": "e3dc8f91…", "computed_at": "2026-09-28T17:20:41Z",
      "explanation": "FAIL: Verified condition not met"
    },
    "policy": { "verdict": "FAIL", "raw_verdict": "NOT_VERIFIED", "reason_codes": ["verified_condition_not_met", "expected_effect_missing:shopify.order_cancelled"], "...": "...", "prev_hash": "f8f3d619…" }
  },
  "checks": {
    "preconditions": [
      {"kind": "precondition", "description": "latest shopify.order_status before the action had status=open", "source": "shopify", "type": "order_status",
       "code": "precondition_unmet:shopify.order_status", "ok": true, "observed": true, "fact_id": "fct_01m3mggybd933grdyt85r1nk9w",
       "occurred_at": "2026-09-28T10:41:30Z", "value": {"status": "open", "total": 180.0},
       "message": "Order was not open for a refund at the time of the action"}
    ],
    "limits": [
      {"kind": "limit", "description": "amount above 250", "source": null, "type": null, "code": "limit_exceeded:amount",
       "ok": true, "observed": true, "fact_id": null, "occurred_at": null, "value": 180.0, "message": null}
    ],
    "expected_effects": [
      {"kind": "expected_effect", "description": "stripe.refund observed within 15m of the action", "source": "stripe", "type": "refund",
       "code": "effect_observed:stripe.refund", "ok": true, "observed": true, "fact_id": "fct_01m3mggybfa0fs6e5zy6bshs06",
       "occurred_at": "2026-09-28T10:42:07Z", "value": {"amount": 180.0, "currency": "USD", "refund_id": "re_1Q2x"}, "message": "Payment refund was not created"},
      {"kind": "expected_effect", "description": "shopify.order_cancelled observed within 15m of the action", "source": "shopify", "type": "order_cancelled",
       "code": "expected_effect_missing:shopify.order_cancelled", "ok": false, "observed": false, "fact_id": null,
       "occurred_at": null, "value": null, "message": "Shopify order remained active despite a successful payment refund"},
      {"kind": "expected_effect", "description": "crm.note_added observed within 15m of the action", "source": "crm", "type": "note_added",
       "code": "effect_observed:crm.note_added", "ok": true, "observed": true, "fact_id": "fct_01m3mggybg86zjv6bpmh85fnbw",
       "occurred_at": "2026-09-28T10:42:09Z", "value": {"author": "whatsapp-support-agent"}, "message": "No note was added to the customer record"},
      {"kind": "expected_effect", "description": "messaging.customer_notified observed within 15m of the action", "source": "messaging", "type": "customer_notified",
       "code": "effect_observed:messaging.customer_notified", "ok": true, "observed": true, "fact_id": "fct_01m3mggybgbr8swkwncfdakvnr",
       "occurred_at": "2026-09-28T10:42:11Z", "value": {"channel": "whatsapp"}, "message": "Customer was not notified"}
    ],
    "forbidden_effects": [
      {"kind": "forbidden_effect", "description": "more than 1 stripe.refund effect(s) observed within 15m", "source": "stripe", "type": "refund",
       "code": "duplicate_effect:stripe.refund", "ok": true, "observed": false, "fact_id": null, "occurred_at": null, "value": null, "message": null},
      {"kind": "forbidden_effect", "description": "stripe.refund observed with amount above 250", "source": "stripe", "type": "refund",
       "code": "forbidden_effect_observed:stripe.refund", "ok": true, "observed": false, "fact_id": null, "occurred_at": null, "value": null, "message": null}
    ]
  },
  "summary": {"expected": 4, "observed": 3, "headline": "FAIL — Shopify order remained active despite a successful payment refund"},
  "facts": [
    {"fact_id": "fct_01m3mggybd933grdyt85r1nk9w", "source": "shopify", "subject_id": "order_10231", "subject_kind": "order", "fact_type": "order_status",
     "occurred_at": "2026-09-28T10:41:30Z", "attributes": {"status": "open", "total": 180.0}, "raw_ref": "agent_api:fact:20c506db…"},
    "…3 more…"
  ],
  "dry_run": true
}
```

Other outcomes with the same contract (see `tests/test_actions.py`):

- Refund of 400 on an order whose latest status was `fulfilled`, refunded twice, all four effects present → `lenses.outcome.verdict = "PASS"` (reason codes `effect_observed:…` ×4), `lenses.policy.verdict = "FAIL"` with `reason_codes = ["precondition_unmet:shopify.order_status", "limit_exceeded:amount", "duplicate_effect:stripe.refund", "forbidden_effect_observed:stripe.refund"]`, `summary.headline = "FAIL — Order was not open for a refund at the time of the action"`; the duplicate check's `fact_id`/`value` point at the **second** refund.
- Subject with no fact at all → both lenses `UNKNOWN`, `reason_codes = ["identity_unmatched"]`, `headline = "UNKNOWN — Subject not found in fact sources"`.
- Action requested just now with only the state and the refund pushed → `status: "pending"`, `headline = "PENDING — 1 of 4 expected effects observed so far; window closes 2026-…"`, a `verify_action` job queued at `settles_at`.

### `GET /v1/actions` — list (viewer)

Query: `contract_id`, `workflow_id`, `verdict` (`PASS|FAIL|UNKNOWN`, case-insensitive; matches when **either** lens of the latest verification has that verdict), `period` (`YYYY-MM`, the action's `requested_at` month), `limit` (default 50, max 200), `cursor`. Items are `Action` objects, newest `requested_at` first; only actions under action contracts are listed. Pagination is offset-based: `next_cursor` is an opaque string to pass back as `cursor`, `null` on the last page. Without a `verdict` or `workflow_id` filter the page is cut in the database and only its actions are evaluated; with one, the listing considers the 2000 most recent matching actions.

```json
GET /v1/actions?verdict=FAIL&period=2026-09

200
{
  "items": [
    { "id": "act_01m3mggydp4h27rn5v9km2jw9s", "action_id": "act_demo_refund_001", "contract_id": "refund_workflow", "contract_version": 2,
      "workflow_id": "wf_cancel_and_refund", "agent_id": "whatsapp-support-agent", "action_type": "refund_order",
      "subject_id": "order_10231", "subject_kind": "order", "requested_at": "2026-09-28T10:42:00Z",
      "params": {"amount": 180.0, "currency": "USD", "reason": "customer_cancelled"}, "channel": "whatsapp", "period": "2026-09",
      "latest": {"outcome": "FAIL", "policy": "FAIL", "status": "settled", "settles_at": "2026-09-28T10:57:00Z", "computed_at": "2026-09-28T17:20:41Z"} }
  ],
  "next_cursor": null
}
```

### `GET /v1/actions/summary?period=YYYY-MM` — per-workflow counts (viewer) — **deprecated**

Deprecated in 0.9.56: these counts follow the strict lens of each action's latest verification with pending actions
counted under PASS/FAIL/UNKNOWN, which is how the Overview and Refund activity came to disagree (benchmark RB-17,
RB-18). The response now says so (`lens: "strict_latest"`, `deprecated: true`, `canonical_endpoint`). Every page reads
`GET /v1/summaries/verdicts`.

`period` defaults to the current month. One row per action contract that has actions; counts use the **policy** verdict of each action's latest verification (`pass + fail + unknown = total`; actions never verified count as `unknown`). `pending` is a **subset** of `total`, already counted under `pass`, `fail` or `unknown`: actions whose outcome is not PASS and whose window is still open or whose sources are behind; `settled` is `total - pending`. `compensated` is also a subset of `total`.

`total` and every count beside it are the workspace's own actions: Agent sandbox runs, actions recorded with `environment: "test"` the earlier sample refund (`act_demo_refund_001`) and the onboarding sample's runs (`environment: "sample"`) are reported apart, in `excluded: { sandbox, test, sample }`, and are in no other count. The response's `definitions` says the same per field.

```ts
{
  period,
  workflows: [{ contract_id, display, total, pass, fail, unknown, pending, settled, compensated,
                excluded: { sandbox, test, sample } }],
  definitions: { total, pending, settled, compensated, excluded }   // one sentence each
}
```

```json
GET /v1/actions/summary?period=2026-09

200
{ "period": "2026-09",
  "workflows": [ {"contract_id": "refund_workflow", "display": "Refund workflow (internal agent)", "total": 1, "pass": 0, "fail": 1, "unknown": 0, "pending": 0} ] }
```

### `GET /v1/actions/{action_ref}/wait?timeout=30` — the completion gate (viewer)
Holds the request until the action's verdict settles or `timeout` seconds pass (clamped to 0..60; the SDKs loop for longer waits). Response: the same `ActionVerification` as the GET below plus `timed_out: boolean` and `waited_seconds: number`. Each poll evaluates the evidence that has arrived; once it settles, that verification is stored once (like a scheduled re-check) and returned; audit `action.awaited {outcome, waited_seconds}`. A timeout returns the provisional view with `status: pending`. See the completion-gate section of [action-contracts.md](/docs/action-contracts).

### `GET /v1/actions/{action_ref}` — one action with its verification (viewer)

**0.9.56: one atomic snapshot.** The answer is the action's current snapshot, served whole: the canonical state, both
lenses, checks, counts, identity, sources, versions and timestamps were all written together when the verification
was stored (`snapshot: { snapshot_version, generated_at, etag }`, and the `ETag` header). Nothing is evaluated on
read, so a headline, lenses, counts and version history can never come from different verifications. When records,
links or a trust change are newer than the snapshot, the answer says so in `live: { evidence_newer_than_snapshot,
reverify_scheduled, reverify_dead_letter }` (and the legacy `verdict.stale`, `verdict.reverification_scheduled`); the
queued re-verification writes the next snapshot. `fresh_lenses` is no longer returned. Only `facts_after_settlement`
(records on the subject stored after the snapshot, listed apart) and `state.monitoring.active` (a matter of the clock)
are read live. See "Verification state" above for the canonical fields.

`action_ref` is the `action_id` or the internal `id`. Returns an `ActionVerification` with `dry_run: false`. `lenses` are the **stored** verdicts of the latest verification (same `verdict_hash` as the verify response).

**The evidence freeze.** Once an action has settled, `checks`, `summary`, `sources`, `facts`, `settlement`, `reversal` and `previous` are returned exactly as the engine saw them when the verdict settled: `evidence_frozen_at` carries that moment, and nothing is re-evaluated on read. Facts recorded on the action's subjects after that moment are listed apart in `facts_after_settlement` (same shape as `facts`) and never folded into the check table, so the table cannot say an effect was seen when the verdict says it was not there in time. The trust of each record and source is frozen too (evidence trust slice 3, B9): `sources[].trust`, `facts[].trust`, `facts[].evidence_trust_class` and `summary.evidence_trust` are the ones the verdict was judged with, whatever is attested or rated later. Only `resolution` (a later compensating action) stays live, and the headline names it.

While the action is **pending**, `evidence_frozen_at` is `null` and `checks`, `summary` and `facts` are rebuilt from the facts currently stored; `facts_after_settlement` is empty. When the stored verdict is older than the newest record, link or trust change it could depend on, `lenses` stay the stored verdict and `fresh_lenses` carries the evaluation of what is stored now, with `verdict.stale: true` (the re-verification that stores it is queued): a poll is never left with only a verdict older than its evidence, and the app shows `fresh_lenses`.

**Provisional FAIL** (board CL-148). While the action is pending and its policy lens already fails on a violation (a duplicate refund, a refund above the limit, an amount over the limit, a reversal), the view carries `provisional: { state, lens: "policy", code, label, message, checks: [{ kind, check, code, label, message, final, rule }] }`. `state` is `provisional_fail` when no record that can still arrive undoes the failure (every final check: the settled policy verdict will be FAIL), and `failing_so_far` when a later record could change it (a precondition, a sum, a comparison with a state record, or a contract whose `unverifiable_if` reads records). `rule` names the reason, per check type, as `docs/onboarding/refund/trust/verdict-state-model.md` ("Provisional FAIL") tabulates it. It is `null` when nothing fails and once settled; settlement itself is unchanged, and there is never a provisional PASS. In `GET /v1/actions` each pending item's `latest` carries the same block as `latest.provisional` only while one applies, and the onboarding verdict carries `provisional` (`state`, `code`, `label`, `message`). `contract_status` is the status of the version the action is pinned to (`library`, `active`, `draft`, `archived`; board CL-149).

Every view also carries:

- each record's `evidence_trust_class`, `basis`, `basis_text`, `trust_copy`, `attestation_status` and `credential_id` (in `facts`), and each check's `evidence_trust_class`;
- per expected effect, `evidence_state` (`not_received`, `received_ineligible`, `received_unmatched`, `pending_settlement`, `eligible_matched`, `eligible_not_satisfying`, `source_unavailable`), `evidence_required`, `evidence_observed` and `records`;
- `evidence_counts { sources, received_sources, eligible_sources, records_received, records_eligible, expected, satisfied }`, received, eligible and satisfied apart; a pending headline with records that are not eligible says "3 evidence records received. None currently meet this contract's trust requirement." and never "0 of 3 observed";
- `reason { category, code, label }`: the reason shown first, by one precedence (invalid action, evidence mode mismatch, identity unmatched, source unavailable, evidence not received, insufficient trust, settling, expected effect missing, forbidden effect, limit, pass; `app/engine/reasons.py`). `evidence_mode_mismatch` (category of the same name): a production action whose Stripe evidence is test mode, or a test action whose evidence is live mode, read from `attributes.livemode` on the Stripe records of the action's subject and the subjects linked to it, or, when the subject has none, from the connected Stripe key's mode (`config.stripe_mode`). Records that do not state a mode are never a mismatch. Both lenses are then UNKNOWN with this code first among their `reason_codes` (a failure of a limit or an allowed value on the action's own parameters, which reads no record, stays FAIL), and the lens's evidence carries `{ source: "system", field: "stripe_mode", value: { action_environment, evidence_modes, basis: "records"|"connection" } }`;
- `identity { status: matched|unmatched, subject_id, compared, unmatched_records, missing_link_types }`: one identity result for both lenses (an unmatched record is one of the effect's type in the window, on another kind of subject than the action's, that no action is or is linked to; another order's records never are). `evidence_counts`, `reason` and `identity` are frozen with a settled verdict;
- `verdict { verdict_id, verdict_version, evaluated_at, evidence_version, trust_configuration_version, contract_version, source_watermarks, previous_verdict, current_verdict, change_reason, changed, stale, reverification_scheduled }`. `change_reason` is the cause the run recorded: `recorded`, `new_evidence`, `watermark_advanced`, `identity_link_added`, `trust_attested`, `trust_revoked`, `connector_recovered`, `reversal_received`, `late_evidence`, `after_sync`, `settlement_check` or `manual_reverify`.

### `GET /v1/actions/{action_ref}/versions` — the verdict history (viewer)

`{ id, items: [{ verdict_version, verdict_id, prior_verdict_version, evaluated_at, processing_status, overall_verdict, outcome_verdict, policy_verdict, settled_at, settlement_deadline, change_reason, verdict_change_reason, trigger, changed, superseded_by, is_current, headline, canonical: true, canonical_source: "snapshot"|"derived_from_stored_lenses", snapshot_version, evidence_version, trust_configuration_version, identity_configuration_version, contract_version, source_watermarks, outcome, policy, status }], count }`, oldest first.

Every item carries the canonical verdict. A PENDING item has `overall_verdict: null`, an `outcome_verdict` that is UNKNOWN unless definitively known, and a `policy_verdict` of FAIL or UNKNOWN; it never reads FAIL for evidence that had not arrived. `outcome`, `policy` and `status` are deprecated names for `outcome_verdict`, `policy_verdict` and `processing_status` (lower-cased) and cannot differ from them. A version stored before snapshots (0.9.56) gets its canonical verdict from its stored lenses (`canonical_source: "derived_from_stored_lenses"`). A re-verification that changes nothing material adds no item; `changed` compares the canonical verdicts of consecutive items. `superseded_by` is the version that replaced it (null on the current one); the replaced row, its hashes and its frozen evidence stay as stored, and a re-verification that changes something appends a version and never rewrites one. Audit: `evidence.viewed` for a person; API-key reads are not audited.

### `GET /v1/actions/orphans?contract_id=&period=`

Builder plan and above (`402` with `details.upgrade_to: "builder"` below it). The sandbox reports its own run's orphans on every plan.

Effects of the kinds the contract expects or forbids, observed on subjects that have **no** recorded action under the
contract in the preceding window (the wrong-customer and injected-instruction cases). A subject linked to an action's
subject (see `links` under `POST /v1/facts`) is covered by that action and is not an orphan. Returns
`{ contract_id, window, period, count, items: [{ fact_id, source, subject_id, fact_type, occurred_at, attributes }] }`.
Reported only; never turned into a verdict. Role: viewer.

### Webhook events `action.verified`, `action.pending`, `contract.weakened`

`action.verified` is emitted whenever a persisted verification settles: immediately for actions verified after their window has closed with every source caught up (including `POST /v1/actions`, which verifies on record), from the `verify_action` job when a `pending` action settles, and again when a later reversal changes a settled verdict. `action.pending` is emitted once, for the first provisional verdict of an action. Dry runs never emit. Delivered with the standard envelope and signature (`{ id, event, created_at, data }`, headers `X-Event: <event>` and `X-Signature: t=<ts>,v1=<hex HMAC-SHA256 of "<ts>.<body>" under the webhook secret>`), and posted to Slack when configured. Both carry the same `data`:

```json
{
  "id": "wdl_…",
  "event": "action.verified",
  "created_at": "2026-09-28T10:57:02Z",
  "data": {
    "id": "act_01m3mggydp4h27rn5v9km2jw9s",
    "action_id": "act_demo_refund_001",
    "contract_id": "refund_workflow",
    "workflow_id": "wf_cancel_and_refund",
    "outcome": "FAIL",
    "policy": "FAIL",
    "status": "settled",
    "headline": "FAIL — Shopify order remained active despite a successful payment refund",
    "reasons": [{"code": "verified_condition_not_met", "label": "…"}, {"code": "expected_effect_missing:shopify.order_cancelled", "label": "…"}],
    "settlement": {"settles_at": "2026-09-28T10:57:00Z", "uncertainty_cutoff_at": "2026-09-30T10:57:00Z", "deadline": "2026-09-30T10:57:00Z", "status": "settled", "waiting_on": [], "stale_sources": [], "next_check_at": null},
    "reversal": null,
    "previous": {"outcome": "FAIL", "policy": "FAIL", "computed_at": "2026-09-28T10:42:03Z"},
    "changed": false,
    "verdict_hash": "f31939ee…"
  }
}
```

`data.settlement_deadline` and `data.settlement.settles_at` are the action's settlement deadline;
`data.settlement.uncertainty_cutoff_at` is the 48-hour cutoff after it, and `data.settlement.deadline` its deprecated
name with the same value (RS-8; see the deadline-like fields under the verdict state).

`reversal` is `{ fact_id, source, type, occurred_at, description, message }` when a record named in `reversed_by` undid the action; `previous` is the verdict pair this run replaced and `changed` says whether it differs. The Slack and email line says pending or settled, what the verdict waits on, what reversed it and what it was before. `verdict_hash` is the policy-lens verdict hash and can be checked at `GET /v1/public/verify/{hash}`.

`action.compensated` is emitted when a later action recorded with `compensates: "<action_id>"` settles PASS: `{ id, action_id, contract_id, workflow_id, outcome, policy, resolution: { state, by, by_claim_id, at }, compensated_by: { id, action_id, contract_id, outcome, policy, headline, verdict_hash } }`. The compensated action's own verdict and hash are unchanged; `action.verified` payloads carry `resolution` and `compensates` as well.

`contract.weakened` is emitted when a saved contract version accepts more than the one it replaces: `{ contract_id, version, previous_version, actor, warnings: Weakening[] }`.

All four are selectable events for customer webhooks (`GET /v1/settings/webhooks` lists them) and are posted to Slack when the Slack integration's `events` list includes them or is empty.

## Commitments

*(0.10.0.)* A **commitment** is one approved business change for one exact account, with its own effective time and deadline. It comes from the approving side (the system or person that approved the change), never from whoever performs the work. CommitLayer records the action that stands for it at once, so work that was promised and never started is still expected, settles, and fails at its deadline. It then reads the systems the change must reach, keeps an incomplete change open with an owner until it is corrected, and verifies the correction from the same systems.

The first workflow is `change_account_seats` (the [Commercial Account Changes pack](/docs/packs/commercial-account-changes), contract `cac_change_account_seats`): the approved number of seats must show on the account's Stripe subscription (**billing**) and on the account in your own application (**product access**, sent through the [product-access interface](/docs/product-access)). A billing record is never proof of product access.

Three things are kept apart on every commitment and never merged:

- `original_outcome` / `original_decision`: what was true at the deadline, **decided at the deadline and never before it**, and **stored once**, in the transaction that first settles the commitment's action, with its exact basis (`original_decision.basis`: the records each check read with their source event time, collection time and ingestion time, their trust class, credential and attestation; the records received and rejected; each source's checkpoint; the attestations in force; the approval and contract revisions). A unique index allows one per commitment, so concurrent workers and re-checks cannot store a second one. Nothing changes it afterwards: not a correction, a late record, a later attestation, a revocation, a key revocation, a compromise invalidation or a re-check (`frozen: true` from the moment it is decided).
- `reassessments`: a later reading of the same requirements at the same deadline that differs from the latest one is **appended**, dated, with its `reason` (`late_evidence`, `compromise_invalidation`, `trust_changed`, `evidence_corrected`, `migration_remediation`, `re_evaluation`) and its own basis. The latest reading is `assessed_outcome`; `status` follows it, the original decision does not.
- `current_assessment`: the present reading of the same requirements on the evidence as it stands now (the latest eligible record of each system), `provisional: true` before the deadline. It never replaces either of the above.
- `exception`: an incomplete change's owner, resolution condition and state (`open`, `assigned`, `corrected_verified`, `accepted`, `cleared`, `superseded`).
- `accepted_exception`: a named person's decision to live with an exception. It never reads as complete.

`status` is derived from them:

| `status` | `status_label` | Meaning |
|---|---|---|
| `scheduled` | Scheduled | Not effective yet (`effective_at` is ahead). Never late and never failing. |
| `pending` | Pending | Effective, and not decided yet: the deadline (`due_at`) is ahead, or it has passed and a system has not reported past it yet. A change that is already in place is still `pending` until its deadline. |
| `complete` | Complete | Every system showed the approved values at the deadline (the original decision, or a later reassessment from late evidence about that time). Decided at the deadline, never before. |
| `incomplete` | Incomplete | A system did not; an exception is `open` or `assigned`. Also a complete change, or a corrected one, that a system later showed undone. |
| `corrected` | Corrected and verified | The exception's resolution condition held on later evidence. `original_outcome` stays what it was at the deadline (a missed deadline stays missed) and is frozen from then on. |
| `exception_accepted` | Exception accepted | An Admin or Owner accepted the exception, with a reason. Counted apart; never complete. |
| `not_verifiable` | Not verifiable | A system could not be checked (`not_checked` says which and why). Never counted as failed. |
| `superseded` | Superseded | A later revision of the same `commitment_ref` replaced it, or a later approved change for the same exact account took effect before it was in place (`superseded_reason`). Not expected and never counted as failed, unless it had already missed its deadline or violated a requirement: a recorded miss stays a miss. |
| `needs_mapping` | Needs mapping | The approval named the account only partly and no single consistent authenticated relationship path gives its exact subscription, item or tenant yet (see [Approved-change obligation](#approved-change-obligation-and-its-checks)). Expected and never complete; it keeps its approved times. |

**Who may call what.** Reading takes a Viewer, or a key with `actions:read` (over MCP the three read-only commitment tools take `commitments:read`, a read scope the `reader` preset holds; [docs/mcp.md](/docs/mcp)). Sending a commitment takes a key with `commitments:write` (the `approver` preset: `commitments:write`, `actions:read`) or an Analyst signed in. **A key that holds `actions:record` cannot send a commitment or assign an exception**, whatever else it holds (`403 performer_cannot_commit`; this includes the `full` preset and keys that predate scopes): the side that performs the work never defines what was promised. Reporting execution takes `actions:record` (or a person). Re-checking and assigning take an Analyst; a key that holds `actions:record` cannot ask for a re-check either (`403 performer_cannot_recheck`). Accepting an exception takes an Admin or Owner signed in (`403 person_required` for any key). A platform admin impersonating a workspace reads commitments and cannot send one, assign an exception or accept one (`403 impersonation_read_only`). The session's capability model carries `can_view_commitments` (Viewer), `can_create_commitments` and `can_act_on_exceptions` (Analyst) and `can_accept_exceptions` (Admin).

**Metering.** One commitment is one verified action, counted when it is received, exactly as `POST /v1/actions` counts ([Metering](#metering)); the response carries the same `allowance` block. A later revision that changes something material (an amendment) is a new approved change and counts one. The same instruction sent again (under any delivery reference, after a key rotation, with a new source record revision, a note or another owner), a re-numbered revision that changes nothing material, execution reports, notes, owner changes, mapping resolution, re-checks, the settlement re-checks and the verification of a correction are never metered. A commitment waiting for mapping is metered when its action is recorded, once its references are exact.

### `POST /v1/commitments`

*Analyst; an API key needs `commitments:write` and must not hold `actions:record`.*

```ts
{
  commitment_ref: string,            // your reference; 1-80 characters, no spaces, no "@"
  revision?: number,                 // 1 when omitted; a higher revision supersedes the lower ones
  workflow: "change_account_seats",
  account: {
    account_ref: string,             // the account in your CRM (always required)
    billing_ref?: string,            // the Stripe subscription id (sub_…). May be left out: see intake below
    product_ref?: string,            // the account's tenant in your application. May be left out
    commercial_account_ref?: string, parent_subscription_ref?: string,
    billing_item_ref?: string,       // the exact subscription item (a child of a consolidated parent)
    time_zone?: string               // the account's IANA zone (UTC when omitted)
  },
  change: {
    seats_from?: number, seats_to: number, plan_from?: string, plan?: string, billing_price?: string,
    features?: { grant?: string[], remove?: string[] },
    sso?: { state: "disabled" | "enabled" | "required" }
  },
  terms?: {                          // commercial terms: when present the financial checks apply
    currency: string,                // ISO 4217; its own minor unit (JPY 0, EUR 2, KWD 3)
    unit_amount_minor?: number,      // an integer of minor units, or
    unit_amount?: string,            // an exact decimal ("45.00"; "12.5" JPY is 422 invalid_amount)
    billing_period?: { interval: "day" | "week" | "month" | "year", interval_count?: number, anchor: string },
    proration?: { rule: "prorate" | "none", basis?: "seconds" | "days", rounding?: "half_up" | "half_even" | "down" },
    pricing?: { definition_id: string, version: number, price_id?: string }   // a pinned pricing definition
  },
  ticket?: { ticket_ref?: string, required_status?: "open" | "pending" | "solved" | "closed",
             required_disposition?: string },
  notification?: { required_milestone: "created" | "queued" | "sent" | "delivered", message_ref?: string },
  approval?: { source?: string, external_change_id?: string, source_revision?: string,
               external_approver?: string },  // an approval source's own identity of the instruction
  approved_at?: string,              // now when omitted. Every time here is an ISO 8601 date and time WITH an
                                     // offset from UTC: "2026-12-01T17:00:00Z" or "…T17:00:00+01:00"
  approved_by?: string,              // a person approves as themselves (see below); a key may name the approver
                                     // its approval source recorded
  effective_at?: string,             // approved_at when omitted; or
  effective_local?: string,          // wall-clock time in account.time_zone ("2026-12-01T00:00")
  due_at?: string, due_local?: string,
  dst_resolution?: "earlier" | "later",            // only to resolve an ambiguous local time
  owner?: { team?: string, user_email?: string },   // who owns a gap; the exception opens assigned to them
  policy_defaults?: ("owner" | "due_at")[],         // apply the workspace's visible defaults instead
  note?: string,                                    // never material
  environment?: "production" | "test"               // production when omitted; test is never counted or announced
}
```

Returns `201 { commitment: Receipt, allowance, idempotent_replay: false }`.

- **Idempotent on the business instruction.** An instruction is identified by the workspace, the environment, the approval source (`approval.source`; `app` for a person) and its external change id (`approval.external_change_id`, the `commitment_ref` when omitted), never by the key that sent it, and by (`commitment_ref`, `revision`). The same instruction and revision with the same material content returns `200 { commitment, allowance: null, idempotent_replay: true }` with the header `Idempotent-Replay: true`, under whatever `commitment_ref` it is redelivered; a field left out of the retry is not compared. What is not material is recorded and creates nothing: a new owner (`owner_changed`), a new `approval.source_revision` (`source_revision_seen`), a note. Different material content under the same revision is `409 conflict` with `details: { commitment_id, commitment_ref, revision, mismatched_fields: string[] }` (for example `["account.product_ref", "change.seats_to"]`). A higher revision that changes nothing material returns the stored commitment (`revision_without_material_change`). An approved change is immutable: a change of mind is the next revision (an amendment, `POST /v1/commitments/{ref}/amend`). Concurrent deliveries of one instruction make one commitment.
- **The approver is authenticated, never text (RB-52).** A person signed in approves as themselves: `approved_by` must be absent or their own address (`422 approver_not_authenticated`). A key with `commitments:write` is an approval source: the approver it names is kept as that source's statement (`authority.external_approver`). `authority` on the receipt says which.
- **A reviewed deadline and an accountable owner (RB-52).** Without `due_at`/`due_local` or `owner`, the commitment is refused with `422 review_required` (`details.missing`) unless `policy_defaults` names the field: then the workflow window or the workspace's Owners apply and `obligation.defaults_applied` shows it. Drafts may be incomplete (`/v1/commitment-drafts`).
- **Local business time.** `effective_local`/`due_local` are resolved in `account.time_zone`: a time inside a daylight-saving gap is `422 nonexistent_local_time`; one inside an overlap is `422 ambiguous_local_time` (`details.candidates`) unless `dst_resolution` says which; `*_at` and `*_local` that disagree are `422 inconsistent_time`; an unknown zone is `422 invalid_time_zone`.
- **Partial references are accepted (FS-2).** `billing_ref`, `product_ref` and `billing_item_ref` may be left out. They are resolved from eligible `identity.relationship` records (section [Approved-change obligation](#approved-change-obligation-and-its-checks)); when that does not give each one exactly, the commitment is stored as `needs_mapping`.
- **Supersession.** A higher `revision` of a reference supersedes the lower ones (and a lower one that arrives late is superseded on arrival). The superseded commitment reads `superseded`; if its action had not settled it settles as UNKNOWN `superseded_by_revision`, never a FAIL at a deadline that no longer applies, and if it had settled its verdict is left exactly as it was and never evaluated again. The evidence that satisfies the later revision is therefore never read as a reversal of the earlier one.
- **Times are unambiguous or refused.** `approved_at`, `effective_at` and `due_at` (and `reported_at` on a report) must be an ISO 8601 date and time with an offset from UTC. A date alone, a time with no offset, `12/01/2026` and a bare number are `422 invalid_timestamp` with `details: { field, format }`: a deadline read as midnight UTC, or with day and month swapped, is a wrong deadline. `effective_local` and `due_local` are wall-clock times read in `account.time_zone` (an IANA name; `422 invalid_time_zone` otherwise): a time the clocks skip at a daylight-saving change is `422 nonexistent_local_time`; a time that happens twice is `422 ambiguous_local_time` (`details.candidates` lists both UTC moments) unless `dst_resolution` says which; a local time and an ISO time for the same field that disagree are `422 inconsistent_time`. The zone is kept on the commitment (`timeliness.time_zone`); machine times stay UTC (`Z`) and the receipt adds `*_local` blocks for people.
- **One environment per reference.** A revision is in its reference's environment: a `test` revision of a production reference (or the reverse) is `409 conflict` with `details: { commitment_ref, environment, mismatched_fields: ["environment"] }`. It would otherwise supersede the production commitment and take it out of every count.
- **A reference is the workspace's or a guided sample's, never both.** A reference a guided sample uses is `409 reference_reserved` with `details: { commitment_ref, reserved_for: "sample" }`, for any revision; choose another reference.
- **Other commitments for the same exact account** (another `commitment_ref` naming the same `billing_ref`, `billing_item_ref` and `product_ref`) are told apart by their references, never by their values. Two child accounts billed on one consolidated parent subscription are different accounts: neither affects the other. From the moment the later one **takes effect** (`effective_at`), the earlier one is no longer watched for later changes. When the later one takes effect before the earlier one's deadline, the two list each other in `overlaps_with`, and **the earlier one's obligation ends at the later one's effective time** (`original_outcome.judged_at`, `judged_early_because`): in place by then on every applicable check, it is `complete`; otherwise it reads `superseded` with `superseded_reason: "overlap"` (its action settles UNKNOWN `overtaken_by_later_commitment`), never a missed deadline, and no exception opens whose condition would undo the later change. A later change that is approved but not yet in effect ends nothing: the earlier change must hold until its own deadline, and is never decided at another change's approval (U-23). An earlier commitment whose exception is still open when a later change for the same account is approved is superseded and stays the recorded miss it was. `superseded_by_commitment` on the earlier one and `took_over_from` on the later one link the two.
- **Identity is exact, and it is CommitLayer's own.** The action of a commitment reads the records of `billing_ref` and `product_ref` and of nothing else. Records of another account are never read for it, however alike the accounts are. The two identity links of a commitment are made by CommitLayer from the approved change; no pushed, imported or connector-made link can add to them, take them over or stand beside them. A link that names the source `commitments`, or whose either end is a commitment's id, is refused on every evidence route (`403 commitment_identity_reserved` on `POST /v1/facts`, `POST /v1/evidence/batch` and `POST /v1/actions/verify`; a `link_not_permitted` error on `POST /v1/evidence/batches` and its preflight), whoever sends it, and the engine reads no other link for a commitment's action even if one were stored.
- **The action names are CommitLayer's.** A commitment's action is `commitment:<commitment_ref>:r<revision>`. `POST /v1/actions` refuses an `action_id` or a `compensates` that starts with `commitment:` (`400 reserved_action_id`), so the performing side can neither take a reference's name nor mark a commitment's action as compensated.
- `400 unknown_workflow`; `400 invalid_request` (`due_at` before `effective_at` or not after `approved_at`); `422 validation_error` for a malformed body; `422 invalid_timestamp`, `nonexistent_local_time`, `ambiguous_local_time`, `inconsistent_time`, `invalid_time_zone`, `invalid_amount`, `unknown_currency`, `review_required`, `approver_not_authenticated`; `403 insufficient_scope`, `403 performer_cannot_commit` or `403 impersonation_read_only` as above; `409 reference_reserved`; `409 workflow_not_ready` with `details: { pack_id, contract_id, readiness }` until the pack is installed and its contract selected; `402` and `429` as for any metered action. A refused commitment is not metered. Audit: `commitment.received`.

### `GET /v1/commitments`

`?status=&owner=&sample=&environment=&date_from=&date_to=&limit=&cursor=` → `{ items: CommitmentRow[], next_cursor, total, statuses: string[] }`, newest first. Filtered, counted and paged in the database: `total` is the number of matching commitments, `limit` is at most 200, and `next_cursor` (null on the last page) is passed back as `cursor`.

`status` is one of the eight statuses (`400 invalid_request` otherwise). `owner` is a team name, an address, or `unassigned` (exceptions nobody owns). `sample=true` returns the guided sample's commitments only, `sample=false` the workspace's own only; both when omitted. `environment` is `production` or `test` (`400` otherwise): the workspace's real activity is `sample=false&environment=production`. `date_from` and `date_to` bound the deadline (`due_at`) and are **both inclusive**: each is a day (`2026-11-30`, read in UTC; `date_to=2026-11-30` includes every deadline on that day) or an ISO 8601 date and time with an offset. Anything else is `422 invalid_timestamp`.

```ts
CommitmentRow {
  id, commitment_ref, revision, workflow, workflow_label,
  status, status_label,
  original_outcome: "pending" | "completed_on_time" | "missed_deadline" | "requirement_violated"
                  | "not_verifiable" | "not_judged",
  assessed_outcome: string,          // the latest reading at the deadline, which `status` follows (the original
                                     // decision unless a reassessment was appended)
  account: { account_ref, billing_ref, product_ref },   // billing_ref / product_ref null while not mapped
  change: { seats_from?, seats_to, plan?, billing_price? },
  approved_at, approved_by, effective_at, due_at,
  owner: { team?, user_email? } | null,          // the exception's owner once there is one, else the commitment's
  exception_state: "open" | "assigned" | "corrected_verified" | "accepted" | "cleared" | "superseded" | null,
  is_sample: boolean, sample_run_id: string | null, environment: "production" | "test" | "sample",
  superseded_by: string | null, action_id: string | null,   // null while it waits for mapping
  received_at, intake_state: "resolved" | "needs_mapping" | "resolved_by_person", billing_item_ref: string | null
}
```

### `GET /v1/commitments/{commitment_ref}`

`{commitment_ref}` is the commitment's `id` (`cmt_…`), its `commitment_ref` (the latest revision), or `commitment_ref@revision`. `404 not_found` otherwise. Returns the **receipt**: every field of `CommitmentRow` (with `original_outcome` as the object below) plus:

```ts
Receipt extends CommitmentRow {
  headline: string,                  // "Incomplete: billing reflects 40 account seats; product access remains
                                     //  at 25 account seats."
  revisions: [{ id, revision, status, change, approved_at, approved_by, effective_at, due_at,
                superseded_by, current: boolean }],
  supersedes: string | null, superseded_at: string | null,
  superseded_reason: "revision" | "overlap" | null,   // overlap: a later approved change for the same account
  superseded_by_commitment: { id, commitment_ref, revision } | null,
  took_over_from: [{ id, commitment_ref, revision }], // the commitments this one took over from (overlap)

  systems: SystemRow[],              // one per system the workflow reads, from the engine's own checks
  provisional: boolean,              // true until the outcome is decided: `systems` is what the systems show
                                     // so far, not the outcome
  systems_last_reported: [{ system, label, source, via, how: "read" | "reported",
                            reported_through: string | null,        // the system's checkpoint
                            last_record_at: string | null,          // the latest record for this account
                            last_record_received_at: string | null }],
  watch: { ends_at: string | null }, // until when the systems are watched after the deadline

  original_outcome: {
    state: "pending" | "completed_on_time" | "missed_deadline" | "not_verifiable" | "not_judged",
    label: string, deadline, effective_at, decided_at: string | null,
    decides_at: string, judged_at: string,   // the moment it is judged at: the deadline, or the approval of a
                                     // later change for the same account that took over first
    judged_early_because: { id, commitment_ref } | null,   // that later commitment
    verdict_version: number | null,  // the version of the action's verdict it was read from
    reason_codes: string[],          // the action's outcome reason codes
    changed_after: { system, label, source, observed, observed_at, evidence } | null,
                                     // a system that showed other values after the change was complete
    frozen: boolean                  // true once decided: the original decision is stored once and never
                                     // changes (later readings are `reassessments`)
  },

  original_decision: {               // null until decided
    state, label, decided_at, judged_at, deadline, verdict_version, reason_codes,
    approval: { commitment_id, commitment_ref, revision, approved_at, approved_by, contract_id,
                contract_version },
    basis: {                         // exactly what it rests on
      evaluated_at, judged_at, verdict_version, contract: { id, version }, approval,
      systems: SystemRow[],          // the rows at the deadline
      evidence: [{ system, source, record_type, fact_id, raw_ref, subject_id,
                   event_time,       // when it happened in the source
                   collected_at,     // when the collector read it (the record's observed_at), when known
                   ingested_at,      // when CommitLayer stored it
                   observed, trust_class, credential_id, connection_id, attestation_id, attestation_status,
                   invalidation_id, check, decisive }],
      records: { received, eligible, rejected: [{ fact_id, source, ingested_at, event_time, credential_id,
                                                  trust_class }] },
      source_checkpoints: { [source]: { watermark } },
      trust_decisions: [{ attestation_id, source, evidence_key_id, attested_at, revoked_at, granted_level }],
      trust_cutoff: string | null,   // the first settlement: attestations made from then on never reach back
      reason_codes, limitation?
    } | null,
    immutable: boolean,
    recorded: "decision" | "migration_recovered" | "migration_unrecoverable" | "awaiting_recovery",
    limitation: string | null
  } | null,
  assessed_outcome: { state, label, source: "original_decision" | "reassessment" | null },
  reassessments: [{ id, seq, at, reason, state, label, previous_state, reason_codes, basis, actor }],
  current_assessment: { state: "satisfied" | "not_satisfied" | "undetermined" | "not_applicable",
                        provisional: boolean, assessed_at, systems: SystemRow[], basis: string } | null,
  timeliness: { state: "pending" | "on_time" | "late" | "not_determined", effective_at, deadline,
                deadline_passed, effective_local, deadline_local, time_zone, decided_by },
                // *_local: { local: "2026-12-01 09:00", time_zone, utc_offset: "+01:00", iso, text }
  evidence_health: {
    state: "sufficient" | "waiting_on_sources" | "insufficient_terminal" | "not_supplied",
    counts: { received, eligible, rejected, missing, not_applicable }, count_basis,
    blocking_sources: [{ source, system, label, reason_code: "source_watermark_behind",
                         observed_state: "matches_provisionally" | "differs" | "no_record" | "not_eligible"
                                       | "not_checked",
                         coverage_through, behind_deadline_seconds, lag_seconds, explanation }],
    next_check_at, uncertainty_cutoff_at,     // the cutoff: the deadline plus SETTLEMENT_MAX_LAG (48 h)
    reason_codes: string[]
  } | null,
  approval_applicability: { state: "applicable" | "superseded" | "overtaken", revision, approved_at,
                            approved_by, superseded_by },
  trust_warnings: [{ code: "unsafe_reliance", invalidation_id, source, credential_id, environment, from, to,
                     reason, recorded_at, recorded_by, message }],

  execution_reports: Report[], execution_path: "agent" | "automation" | "person" | "mixed" | "unreported",

  exception: {
    state, kind: "missed_deadline" | "changed_after_completion" | "changed_after_correction",
    opened_at, deadline, account: { account_ref, billing_ref, product_ref },
    owner: { team?, user_email? } | null, assigned_at, assigned_by,   // "commitment" when it came with it
    expected: { [system]: { [attribute]: value } },
    observed: { [system]: { [attribute]: value } | null },            // the systems that did not match
    systems: SystemRow[],                                             // those systems' rows at the deadline
    evidence: string[],                                               // fact ids
    resolution_condition: {
      text: string,                  // "product_access account seats = 40": what has to change
      checks: [{ system, source, record_type, account, attribute, equals, min_trust_class, to_correct }],
      verified_by: string
    },
    last_checked_at: string | null, current: SystemRow[] | null,      // each system as last read
    closed_at?, closed_because?: "late_evidence_showed_on_time" | "superseded"
                               | "overtaken_by_later_commitment",
    history: [{ kind, at, actor, data }],
    earlier: [{ state, kind, opened_at, owner, expected, observed, systems, evidence, resolution_condition,
                correction, closed_at, closed_because }]   // exceptions it had before this one, oldest first
  } | null,

  correction: {
    verified_at, seconds_from_opened: number,
    evidence: [{ system, source, fact_id, trust_class, observed, observed_at }],
    summary: string                  // "Corrected and verified. The original change missed its deadline; …"
  } | null,
  accepted_exception: { accepted_by, accepted_at, reason } | null,

  not_checked: [{ system, label, source,
                  reason_code: "source_not_supplied" | "source_stale" | "no_record_for_account"
                             | "evidence_mode_mismatch",
                  reason: string }],
  overlaps_with: [{ id, commitment_ref }],
  action: { id, action_id, contract_id, contract_version, processing_status, overall_verdict,
            verdict_version, href },          // the engine action that stands for it: GET /v1/actions/{id}
  history: [{ kind, at, actor, data }],
  metering: { verified_actions: 0 | 1, rechecks_metered: false }
}

SystemRow {
  system: "billing" | "product_access", label: "Billing" | "Product access",
  source: "stripe" | "product_access", record_type: "subscription_configuration" | "seat_allocation",
  account: string,                   // billing_ref or product_ref
  expected: { [attribute]: value },  // billing: { quantity, price_id? }; product access: { seats, plan? }
  observed: { [attribute]: value } | null,   // what the record the check read shows
  observed_at: string | null,        // when that state took effect
  evidence: { fact_id, trust_class } | null,
  state: "matches" | "differs" | "no_record" | "not_eligible" | "not_checked",
  rejected_newer: [{ fact_id, observed, event_time, ingested_at, credential_id, trust_class,
                     reason_code, reason }],  // received records that do not count and are not older than the
                                     // one the check read (RB-54): reason_code is one of compromise_invalidated,
                                     // credential_available_to_agent, fact_type_not_allowed,
                                     // credential_not_attested_for_source, source_not_attested,
                                     // no_evidence_credential, insufficient_trust
  final: boolean,                    // true once the action settled: the state at the deadline
  reason: string                     // "Product access shows 25 account seats at the deadline; 40 account seats
                                     //  approved."
}
```

`state` in plain words: `matches` the system shows the approved values; `differs` it shows other values; `no_record` it holds no record of the account; `not_eligible` its only records came from a key that is not attested for the source (the performing side's own push, for example), which never count; `not_checked` it could not be read (see `not_checked`). While the commitment is `scheduled` or `pending`, `provisional` is true and `systems` says what each system shows so far (`final: false`): a system may already read `matches`, and that is not the outcome, which is decided at the deadline. Once the action settles, `systems` is what was true at the deadline and is not rewritten by a correction. A correction's evidence is under `correction.evidence` and `exception.current`. `correction` is the current exception's; the correction of an earlier exception is under `exception.earlier[]`.

`history[].kind` is one of `received`, `supersedes`, `superseded` (both with `data.reason`: `revision` or `overlap`), `overlap`, `judged_earlier`, `execution_report`, `checked`, `outcome_decided` (once, with `data.decision_id`), `reassessed` (`data: { state, previous, reason, verdict_version }`), `decision_recovered` (migration 0089), `exception_opened`, `exception_updated`, `exception_assigned`, `exception_accepted`, `exception_cleared`, `correction_verified`, `changed_after_correction`, `late_evidence_after_closure`.

The headline is built from the same reading as `status` (RB-51): after the decision, when what the systems show now differs from what they showed at the deadline (a change after completion, a correction under way), it says what they show now and names the original decision, for example `"Incomplete: changed after it was complete. Now: Billing shows 40 account seats, as approved; Product access now shows 25 account seats; 40 account seats approved. Original decision: completed on time."` The 40-seat observation at the deadline stays in `original_decision.basis`.

`evidence_health.blocking_sources` names only the sources whose coverage actually holds the decision: a source that has not reported past the deadline. A source can block even when its expected effect was already observed (`observed_state: "matches_provisionally"`): the change is judged as a state at its deadline, so a later record dated before the deadline could still change it; `explanation` says which case applies. `lag_seconds` is how far behind now the source's checkpoint is, `behind_deadline_seconds` how far behind the deadline. `uncertainty_cutoff_at` is when an unresolved wait ends as a terminal `not_verifiable` (`source_stale`).

### How a commitment is judged

- **Decided at the deadline, never before.** A commitment's action does not settle before `due_at`, even when every system already shows the approved values: what it checks is a state, and a state that is right an hour in can be undone before the deadline. Until then the commitment is `scheduled` or `pending` and the receipt shows what the systems show so far as provisional. A change that is in place after its effective time and before its deadline completes on time, at the deadline; a change that was in place and is undone before the deadline is a miss. **A scheduled change applied before its `effective_at` is a premature change**: a finding at once (`findings`), and at the deadline the outcome is `requirement_violated` even when the state is right then; it is corrected only by a transition into the approved state at or after the effective time (a restoration before it proves nothing), and the violation stays in the original outcome. "Settled" always means the action's current version is settled.
- **Each system is read as a state.** The latest eligible record of the system for the exact account, dated at or before `due_at`, must carry the approved values. An earlier record of the old state is not a finding; a change that was made and undone before the deadline is. A record counts only from a connector or from an evidence key attested for the source (`min_trust_class: backend_attested`).
- **A record's date is when the state took effect**, not when it arrived. A record that arrives after the decision and is dated inside the deadline re-verifies the action and appends a reassessment (`reason: "late_evidence"`): the latest reading says the change was on time (`status: complete`; an exception that had opened reads `cleared`), while `original_outcome` stays what was decided. It is late evidence about old work, never a correction. A record dated after the deadline never makes a late change on time: it can only correct it. For product access that date is `effective_at`, which is **the reporting application's own statement** (it only has to be at or before `observed_at`); for billing read by the connector it is Stripe's event time.
- **Trust changes after the decision.** A record counts if an attestation covered it when it was received: a withdrawal or a key revocation affects records received after it only, and an attestation made after the decision never qualifies a record received before it. So attesting a key after a miss and checking again, then revoking and checking again (the 0.10.0 AC6 sequence), changes neither the original decision nor the reading. Only an explicit compromise invalidation ([`POST /v1/evidence/compromises`](#post-v1evidencecompromises)) takes eligibility away from records already received: affected commitments get a reassessment (`compromise_invalidation`; a reading that would be a miss reads `not_verifiable` with `evidence_invalidated`, since what is left can establish neither) and a `trust_warnings` entry, and their original decision stays as it was made.
- **A closed exception stays closed.** After an exception is `corrected_verified` or `accepted`, a later reading that differs is appended as a reassessment and kept as a `late_evidence_after_closure` event (`data: { kept, evidence_now_reads }`); it reopens nothing. A correction therefore can never be turned into "completed on time" by a later, back-dated record.
- **An open exception follows the verdict.** When a new version of the action arrives while the exception is `open` or `assigned` (a record dated before the deadline came in, a source came to count), the exception's `expected`, `observed`, `systems`, `evidence` and `resolution_condition` are computed again from it (`exception_updated`); when it opened, its owner and its assignment stay.
- **At the deadline** the action waits for both systems to have reported past it (a connector's read, a pushed source's `observed_through`, or a scoped checkpoint of the commitment's environment and account, [scoped checkpoints](#scoped-checkpoints)), for at most `SETTLEMENT_MAX_LAG` (48 hours), also when the approved values were already observed: a state can still have changed before the deadline. Neither another commitment's deadline nor a checkpoint of another environment or partition settles it. A system that never reported past the deadline makes the commitment `not_verifiable` (`source_stale`) at `evidence_health.uncertainty_cutoff_at`, never failed and never complete on an unknown. A system nothing eligible supplies (no connection and no attested key) does the same (`source_not_supplied`). When both systems were current at the deadline and hold no record for the commitment's accounts, that is a miss, whatever else was received: a record of the same kind on some other subject, linked to nothing, never makes a commitment "not verifiable", because a commitment names its accounts itself and waits for no identity link.
- **A correction** is verified by evaluating the same contract on the evidence as it stands now: every system must show the approved values on its latest eligible record. It is checked whenever a record arrives for the account and on `POST /v1/commitments/{commitment_ref}/verify`. The exception then reads `corrected_verified` and the commitment `corrected`. The action's verdict is not re-evaluated, no verdict version is added, and `original_outcome` does not change. Asking for a re-check (any principal allowed to) never changes the original decision either; it can only append a reassessment when the records read differ.
- **After the deadline**, both systems are watched for 30 days (`watch.ends_at`; the watch ends earlier when a later approved change for the same exact account takes effect). A record that shows other values after a change was complete re-verifies the action (`reversed:<source>.<record_type>`): the commitment reads `incomplete` with an exception of kind `changed_after_completion`, and `original_outcome.state` stays `completed_on_time` with `changed_after` set. This also holds after an exception was `cleared`: the cleared one is kept under `exception.earlier` and a new one opens. After a **verified correction**, a system that shows other values again inside the watch opens a new exception of kind `changed_after_correction` (the commitment reads `incomplete` again, the corrected exception is kept under `exception.earlier` with its correction, and `original_outcome` does not change); a system that merely stops reporting is not a regression. After the watch has ended, a later change opens nothing.
- **Execution reports are never read by a check.** The same commitment gets the same result whoever reports, whatever they report, and whether anyone does.

### Approved-change obligation and its checks

*(L2a remediation.)* Every commitment is stored as an **obligation**: one immutable revision of what was approved
(`obligation` on the receipt): the account and its hierarchy, the change (seats, plan, feature grants and removals,
SSO state), the commercial terms in integer minor units, the effective time and deadline with the account's time
zone, the required ticket outcome and notification milestone, the owner, and the authenticated `authority`.
Every expected value comes from the approval or from a pinned [pricing definition](#pricing-definitions), never from
an execution report or from the system being checked; `obligation.expected_sources` names where each came from
(`approval.change.seats_to`, `pricing:fs-list@3:price_ent:EUR`). A commitment received before this release reads as
the seat change it was (`obligation.schema: "account_change.v1"`, `authority.kind: "legacy"` with its limitation).

**One registry of checks** (`GET /v1/commitments/checks`) defines what an approved change can require; the receipt's
`required_checks` lists all of them for that change, each with `applies` and the `reason` taken from the approval
(a check is not applicable only when the approval does not ask for it):

| Check | Reads | Applies when |
|---|---|---|
| `identity.bindings` | exact references, `identity.relationship` | always |
| `billing.quantity` | `billing.subscription_item` of the exact item, else the seat contract's `subscription_configuration` | `seats_to` |
| `billing.price` | same | `billing_price` (or a pricing pin's `price_id`) |
| `billing.terms` | `billing.subscription_item`: currency, `unit_amount_minor`, interval | `terms` |
| `billing.proration` | `billing.invoice_line` | `terms.proration.rule: prorate` and `seats_from` given |
| `billing.no_duplicate_charge` | `billing.invoice_line` | `terms` |
| `app.seats` | `app.enforcement.seat_capacity_enforced`, else `seat_allocation.seats` | `seats_to` |
| `app.plan` | `app.enforcement.plan`, else `seat_allocation.plan` | `plan` |
| `app.features` | `app.enforcement.features_enabled` | `features` |
| `idp.sso` | `idp.sso_policy` | `sso` |
| `ticket.disposition` | `ticket.state` for this account and approval revision | `ticket` |
| `notification.milestone` | `notification.milestone` for this account and approval revision | `notification` |
| `timing.not_before_effective` | every state record above | `effective_at` after `approved_at` |
| `continuity.no_unauthorized_reversal` | every state record above | always, after completion inside the watch |

Records count only when eligible by the engine's own trust rules (a connector's read, or an evidence key attested
for that source and record type; never a source's legacy rating), for the commitment's environment, and for the
exact bound object: the subscription item, the application tenant, the CRM account with the approval's
`external_change_id` and revision. A desired seat count, an active-user count, a queued SSO change or a pending void
request is never read as the effective state. The record types and their attributes are listed by
`GET /v1/commitments/checks` (`fact_types`); a record that does not match its schema is never read as a value and
shows as a task (`unsupported_schema`).

**Money.** Amounts are integers of the currency's minor unit (ISO 4217: JPY 0, EUR 2, KWD 3). Proration is computed
exactly from the approved unit amount (the terms, or the pinned pricing definition) over the pinned interval from
the effective time to the end of the billing period derived from `terms.billing_period`, with the stated basis and
rounding: a debit for `seats_to` and a credit for `seats_from`. The invoice is compared with that; it never defines
it. Distinct invoice lines billing the same charge of the change (same kind and interval of the bound item) are
duplicates; a redelivered line (the same `line_id`) and a debit with its proration credit are not, and one charge
billed under one `charge_id` is one charge. A duplicate is corrected only by its own void, or by a credit or refund
that offsets exactly that line (`offsets_line_id`, the opposite amount, in effect); one credit corrects one line.

**Two readings.** `checks.historical` is judged at the judgement point (the deadline, or the effective time of a
later change for the same exact account that ended the obligation) and is what `original_outcome` is built from,
kept with the decision (`outcome_detail.checks`); `checks.current` is the present corrective reading on fresh
evidence (sources that reported past the judgement point and past the record read), provisional before the
deadline. Each check is
`{ id, label, role, phase, state, final, expected, expected_refs, observed, evidence[], binding, findings[], reason,
task }` with `state` one of `satisfied`, `violated`, `pending`, `unknown`, `not_applicable`, `setup_required`.
`checks.waiting_on` names the sources a check (or the seat contract) waits on; `checks.decidable` says whether the
outcome can be decided now.

- `original_outcome.state`: `missed_deadline` when a required state was not in place by the deadline;
  `requirement_violated` when it was but another requirement was broken (premature change, duplicate charge, wrong
  proration); `not_verifiable` when a required check could not be established once the bounded wait ended
  (including a source nothing eligible supplies, a missing pricing definition, or an identity never mapped);
  `completed_on_time` only when every applicable check held. An exception of kind `missed_deadline` or
  `requirement_violated` opens; its `checks` list the failing checks and `resolution_condition.requirements` what must
  hold again. A correction is verified only when every applicable check holds on fresh eligible evidence
  (`correction.checks`); the original outcome never changes.
- `findings` lists every finding with its check, code and moment, including those found before the deadline
  (`premature_change`, `duplicate_charge`), which decide nothing until then: `premature_change`,
  `not_reached_by_deadline`, `wrong_value`, `wrong_currency`, `wrong_unit_amount`, `wrong_billing_period`,
  `proration_wrong_interval`, `proration_wrong_amount`, `duplicate_charge`, `feature_not_granted`,
  `feature_not_removed`, `sso_state_wrong`, `ticket_not_in_required_state`, `notification_milestone_missing`,
  `unauthorized_reversal`, `unsupported_schema`, `identity_ambiguous`, `binding_unresolved`,
  `pricing_definition_missing`, `source_not_covered`.
- `tasks` lists what has to be set up (`needs_mapping`, `setup_source`, `unsupported_schema`, `pricing_definition`);
  while any is open the commitment never reads `complete`.
- After completion, a record of a newer record type that shows other values inside the watch, or a duplicate billed
  after completion, opens `changed_after_completion` as the seat contract's own reversal does.
- `action.scope` is `seat_contract`: the engine action remains the metering and settlement record of the seat
  contract; the commitment's status and outcome are built from the checks.

New receipt fields: `obligation`, `authority`, `instruction { key, approval_source, external_change_id,
source_revisions[] }`, `amends`, `amended_by[]`, `required_checks[]`, `checks`, `findings[]`, `tasks[]`, `intake`;
`exception.checks`, `exception.current_checks`; `correction.checks`. New history kinds: `finding`, `intake_needs_mapping`,
`intake_resolved`, `mapping_resolved`, `owner_changed`, `note`, `source_revision_seen`,
`revision_without_material_change`, `approved_from_draft`, `contract_version_at_binding`.
`GET /v1/commitments/summary` adds `requirement_violated` and `needs_mapping`.

#### Intake and identity (FS-2)

An approval may name the account only partly. Each missing reference is bound only from eligible
`identity.relationship` records (kinds `crm_account->commercial_account`, `commercial_account->billing_subscription`,
`commercial_account->billing_item`, `commercial_account->app_tenant`, `crm_account->app_tenant`;
`billing_subscription->billing_item` lists a subscription's items and only checks consistency) of the commitment's
environment, valid at its approval (`valid_from <= approved_at < valid_to`), latest revision, and only when every
path gives the same single answer. A subscription with several items needs the account's own item. Otherwise the
commitment is stored as `needs_mapping` with `intake.unresolved[] { binding, reason: no_relationship | ambiguous |
conflicting_paths | expired_only, candidates[] { value, path[] } }`; it keeps its approval time, effective time and
deadline, stays in `expected`, and its action is recorded once its references are exact. A new eligible relationship
re-runs the resolution; at `due_at + SETTLEMENT_MAX_LAG` still unresolved, the outcome is `not_verifiable`
(`identity_unresolved`) and the task stays open. Names, emails, the first of several candidates and other accounts'
states never resolve anything. `intake.bindings[ref] { value, method: approval | relationship_path | person, path[] }`
keeps the path on the receipt.

- `GET /v1/commitments/intake?state=needs_mapping|resolved|resolved_by_person` (Viewer, `actions:read`): the queue.
- `POST /v1/commitments/{ref}/mapping` `{ bindings: { billing_ref?, billing_item_ref?, product_ref? }, reason }`:
  an Admin or Owner signed in, or the approval source's key (`commitments:write`); never a performer
  (`403 performer_cannot_commit`), an Analyst gets `403 forbidden`. Recorded with the actor, the reason and
  `chosen_from_candidates`. `409 not_waiting_for_mapping` when nothing waits.

#### Amendments, notes and owners

- `POST /v1/commitments/{ref}/amend` (Analyst, or `commitments:write`; never a performer): the material fields that
  change (`account` and `change` merge key by key; other fields replace); creates the next approval revision of the
  same instruction, linked (`amends` / `amended_by`, `supersedes` / `superseded_by`), metered once. A revision
  superseded before its deadline reads `not_judged`, and its rows say "Not judged: … before its deadline", never
  "at the deadline".
- `POST /v1/commitments/{ref}/notes` `{ note }` (Analyst) and `POST /v1/commitments/{ref}/owner` `{ owner, reason? }`
  (Analyst, or `commitments:write`): history only, `metered: false`.

#### Drafts

`POST /v1/commitment-drafts` `{ body }` (Analyst, or `commitments:write`; any subset of the commitment body;
`approved_at`/`approved_by` are dropped), `GET /v1/commitment-drafts`, `GET|PATCH /v1/commitment-drafts/{id}`
(`ready_to_approve`, `missing`, `required_checks`). `POST /v1/commitment-drafts/{id}/approve` takes a signed-in
Analyst, Admin or Owner (`403 person_required` for a key): the approval time is now, the approver is that person, the
effective time and deadline are fixed with it, and the commitment is enrolled and metered once; `422 review_required`
when the deadline or owner is missing; `409 already_approved` on a repeat.

#### Pricing definitions

`POST /v1/pricing-definitions` `{ definition_id, version, currency_prices: { price_id: { CUR: unit_amount_minor } },
interval?, interval_count?, proration?: { basis, rounding }, note? }` (Analyst, or `commitments:write`): immutable
per version (`201` with `idempotent_replay: true` for the same content, `409 conflict` for other content,
`422 unknown_currency` / `invalid_amount`). `GET /v1/pricing-definitions`, `GET /v1/pricing-definitions/{id}[@version]`.
An approval pins one version in `terms.pricing`; a pinned version that is not there is a `pricing_definition` task.

### `POST /v1/commitments/{commitment_ref}/reports`

*Analyst; an API key needs `actions:record`.* What the performing agent, automation or person says happened.

```ts
{ status: "completed" | "failed",
  executor: { kind: "agent" | "automation" | "person", name?: string },
  reported_at?: string, note?: string, report_ref?: string }
```

Returns `201 { report: Report, idempotent_replay: false, status }`; with a `report_ref` already stored for the commitment, `200` and `idempotent_replay: true`. `Report { id, status, executor, reported_at, received_at, note, report_ref, reported_by, counts_as_evidence: false }`. A report does not change the verdict or the status. Audit: `commitment.reported`.

### `POST /v1/commitments/{commitment_ref}/verify`

*Analyst; an API key needs `actions:read` and must not hold `actions:record` (`403 performer_cannot_recheck`: the side that performs the work does not drive the re-checks of its own work).* Checks the commitment again now, **against the latest records received**: a pending action is re-verified; a settled one gets a new verdict version only when a fresh evaluation differs from the stored one (a late record dated inside its windows, a source attested since); then the exception's resolution condition is evaluated, or, after a verified correction, whether it still holds. Nothing is read from a system by this call itself. When a connection reads billing, a read of it is queued (one per connection at a time, rate-limited as every on-demand read is) and the commitment is checked again when that read finishes. Product access is read the same way when a connector reads the application directly (`reference_app`); when your application pushes it, there is nothing to read.

```ts
{
  commitment: Receipt,
  metered: false,                    // never metered: it is the same commitment
  records_rechecked: boolean,        // the stored records were evaluated again (false for a superseded commitment)
  billing_read_queued: boolean,      // a read of the billing connection was queued
  billing_read: { queued: boolean,
                  reason: null | "no_billing_connection" | "sample" | "superseded" | "not_connected"
                        | "no_credential" | "reauth_required" | "trial_expired" | "source_not_on_plan"
                        | "not_queued",
                  run_at: string | null, connection_id: string | null },
  product_access_read: boolean,      // a read of the connection that reads product access directly was queued
  source_reads: [{ source: "product_access", queued: boolean,
                   reason: null | "pushed_not_read" | "sample" | "not_connected" | "no_credential"
                         | "reauth_required" | "trial_expired" | "source_not_on_plan" | "not_queued",
                   run_at: string | null, connection_id: string | null }],
  checked_against: "latest_records_received"
}
```

`no_billing_connection` means billing is sent by an attested evidence key: there is nothing to read. The receipt's `systems_last_reported` says, per system, how it arrives (`read` or `reported`), how far it has reported and when the latest record for the account was received. Audit: `commitment.checked` (with `billing_read_queued`).

### `POST /v1/commitments/{commitment_ref}/exception/assign`

*Analyst signed in, or a key with `commitments:write` that does not hold `actions:record`.* `{ owner: { team?, user_email? }, note? }` (one of the two is required) → `{ commitment: Receipt }`. `409 no_open_exception` (`details.exception_state`) unless the exception is `open` or `assigned`. `403 impersonation_read_only` for an impersonating platform admin. Audit: `commitment.exception_assigned`.

### `POST /v1/commitments/{commitment_ref}/exception/accept`

*Admin or Owner, signed in.* `{ reason: string }` (10 to 1000 characters; `422` without one) → `{ commitment: Receipt }`. The commitment reads `exception_accepted` from then on, whatever the systems show later. From then on `original_outcome` is frozen too. `403 person_required` for any API key; `403 impersonation_read_only` for an impersonating platform admin; `409 no_open_exception` as above. Audit: `commitment.exception_accepted`.

### `GET /v1/commitments/summary`

`?date_from=&date_to=` (on the deadline, both inclusive, as for the list; `422 invalid_timestamp` otherwise) → the leadership view. Every figure is a count beside its denominator; guided-sample and `environment: "test"` commitments are counted under `excluded` and in no other figure. Counted in the database.

```ts
{
  as_of, from, to,          // from / to as sent; `before` is the exclusive bound used for `to`
  before,
  expected,                 // the denominator, always present: received and not superseded, plus any commitment
                            // that had already missed its deadline when it was superseded
  superseded,               // replaced by a later revision, or overtaken by a later change for the same account
  superseded_after_miss,    // of those, the ones that had already missed their deadline (still in `expected`
                            // and in `missed_deadline`: supersession never erases a recorded miss)
  scheduled, pending,
  decided,                  // expected commitments whose deadline outcome is known (decided at the deadline)
  not_yet_decided,          // expected - decided
  verifiable,               // decided, and every system could be checked
  verifiable_share,         // verifiable / expected (0..1), null when expected is 0
  not_verifiable, not_verifiable_reasons: { [reason]: number },
                            // expected = verifiable + not_verifiable + not_yet_decided
  completed_on_time, missed_deadline,
  complete,                 // status complete now
  needed_correction,        // had an exception: open, assigned, corrected, accepted, or closed by supersession
  incomplete_open, unassigned,
  corrected_verified, accepted_exceptions,
  overdue,                  // past the deadline and neither complete, corrected nor accepted
  rates: {
    verifiable_of_expected:           { numerator, denominator, rate: number | null },
    verifiable_of_decided:            { numerator, denominator, rate },
    completed_on_time_of_verifiable:  { numerator, denominator, rate },
    completed_on_time_of_expected:    { numerator, denominator, rate }
  },
  time_to_ownership:            { count, median_seconds, mean_seconds, measured_from: "exception_opened",
                                  excluded: { opened_with_owner: number, cleared: number } },
  time_to_verified_correction:  { count, median_seconds, mean_seconds, measured_from: "exception_opened" },
  by_execution_path: { [path]: { expected, superseded, superseded_after_miss, scheduled, pending, decided,
                                 not_yet_decided, verifiable, verifiable_share, not_verifiable,
                                 completed_on_time, missed_deadline, complete, needed_correction, incomplete_open,
                                 corrected_verified, accepted_exceptions } },
  excluded: { sample: number, test: number },
  definitions: { [figure]: string }
}
```

`rate` is `null` when its denominator is zero. `by_execution_path` keys are `agent`, `automation`, `person`, `mixed` and `unreported`, from the execution reports each commitment has.

**Both times run from when the exception opened**, which is when CommitLayer decided the outcome (at the deadline, or up to 48 hours after it while a system had not reported), not from the deadline itself. `time_to_ownership` counts only exceptions that waited for an owner: an exception that opened already owned (the commitment named its owner) and an exception that a late record cleared are left out and counted under `excluded`. Each exception a commitment had counts on its own.

A change that is in place before its deadline is not in `completed_on_time` until the deadline has passed: it is `pending` (or `scheduled`) until then.

### `GET /v1/commitments/readiness`

What is connected, what can be checked and where evidence is missing for the workflow, with who does each missing step. Read-only.

```ts
{
  workflow, workflow_label,
  plan: { current, current_name, required, required_name, meets_requirement: boolean,
          upgrade_to: string | null,          // the plan to move to when the workspace's is below the pack's
          pack_status: "beta" | "ga", sample_on_every_plan: true,
          message: string | null },           // the plan requirement in a sentence, when it is not met
  warnings: [{ code: "billing_events_not_readable", system, summary, cost, fix, who }],
  pack: { id, installed, installed_version, contract_id, contract_active, active_version },
  ingestion: { approver_keys: number, people: string, refused: string },
  systems: [{ system, label, source, record_type, can_check: string[],
              supplied: boolean, via: "connector" | "attested_key" | null, attested_keys: number,
              records_received: boolean, watermark_age_seconds: number | null, stale: boolean,
              connection_status: string | null,
              how: "read" | "reported" | null,       // read by a connection, or reported by its own backend
              events_readable?: boolean | null,      // billing read by the Stripe connector only
              ready: boolean, missing: string | null }],
  identity: { method: "exact_id", how: string },
  steps: [{ step: "plan" | "install_pack" | "activate_contract" | "billing_source" | "product_access_source"
                | "approver_key", done: boolean, who: "owner" | "analyst" | "admin",
            summary: string,                    // what the step is, in plain words
            how: string }],                     // the technical instruction
  can_receive_commitments: boolean,    // the contract is selected
  can_verify: boolean,                 // and both systems are supplied
  ready: boolean,                      // every step done and every system has sent a current record
  limits: string[]
}
```

**The plan.** The account-change pack is on the Builder plan and above and is in beta; the guided sample runs on every plan. Below the pack's plan `plan.meets_requirement` is false, `plan.upgrade_to` names the plan to move to, `plan.message` says so in a sentence ("Verifying real account changes needs the Commercial Account Changes pack, which is on the Builder plan and above. This workspace is on Developer. The guided sample runs on every plan."), the `plan` step is not done, and `POST /v1/commitments` answers `409 workflow_not_ready`.

**Billing events.** When the Stripe key cannot read events (`Events: read`), `systems[].events_readable` is false for billing and `warnings` carries `billing_events_not_readable` with what it costs: a change of account seats or price is then dated at the read that first saw it, not when it was made, so a change made before its deadline and first read after it reads as late, and a change made and undone between two reads is not seen. Whatever the key can read, the subscriptions that open commitments name are read by id on every sync, so a change on an old subscription is never missed.

### `POST /v1/product-access/seat-allocations`

*Analyst; an API key needs `facts:write` and must be allowed to push for `product_access`.* The [product-access interface](/docs/product-access), version 1: what an account can use in your own application.

```ts
{
  allocations: [{ account_ref: string, seats: number,       // whole number >= 0
                  plan?: string,
                  observed_at: string,                      // when your application read it
                  effective_at?: string }],                 // when it took effect; observed_at when omitted.
                                                            // Your application's own statement.
  observed_through?: string                                 // "every change up to here has been sent"
}
```

Each allocation is stored as a `product_access.seat_allocation` record on the account (`subject_id` = `account_ref`, `subject_kind: "account"`), dated at `effective_at`, through the same path as `POST /v1/facts`, and the answer is that route's answer plus `interface: "product_access.v1"` and `record_type: "seat_allocation"`. `observed_through` is the source's watermark. Every time is an ISO 8601 date and time with an offset from UTC (`422 invalid_timestamp` otherwise, `details.field` naming it, for example `allocations[0].observed_at`). `400 invalid_request` with nothing to store; `400 invalid_fact` when `effective_at` is after `observed_at` or a timestamp is too far ahead; `403 source_not_allowed` for a key bound to other sources. A record counts for a commitment only when its key is an evidence key attested for `product_access`. Audit: `product_access.pushed`.

### Notifications

The exception's owner, when `user_email` is a member of the workspace (otherwise the workspace's Owners), gets an in-app notice, and the email the notification centre queues with it, of kind `commitment_exception_opened`, `commitment_exception_assigned` and `commitment_correction_verified`. Each carries `data: { commitment_id, workflow, status }` and `href: /app/commitments/{id}`, and never the account, the customer or a value. Sample and test commitments are never announced. A person named as owner who is not a member of the workspace, and a team name, are recorded as written; the notice then goes to the workspace's Owners. The wording follows the kind of exception: only a missed deadline is said to be missed; a change after completion says the change was complete at its deadline and changed afterwards.

### Webhook events `commitment.incomplete`, `commitment.corrected`, `commitment.exception_accepted`

Sent to the workspace's webhooks that subscribed to them (`POST /v1/settings/webhooks`, `events`), in the usual
envelope and with the usual signature, and to its Slack channel as one line:

- `commitment.incomplete`: an exception opened (the deadline was missed, a complete change was later undone, or a
  verified correction was later undone). `exception.kind` says which.
- `commitment.corrected`: the exception's resolution condition held on later evidence. `original_outcome` in the
  payload is what it was at the deadline: `missed_deadline` for a missed deadline, `completed_on_time` for a change
  that was complete and changed afterwards. The Slack line says "The original deadline stays missed." only for the
  first.
- `commitment.exception_accepted`: an Admin or Owner accepted the exception. Never sent as, or with, `corrected`.

Each is sent once, when it happens: checking a commitment again announces nothing new, and an exception that late
evidence clears, a commitment that completes on time and one that is superseded send none of them (the
commitment's action sends `action.verified` like any action). **Never sent for a guided sample or a commitment with
`environment: "test"`.** A channel that cannot be queued or reached never changes a commitment.

```ts
data: {
  id: "cmt_…", commitment_ref: string, revision: number, workflow: "change_account_seats",
  status: "incomplete" | "corrected" | "exception_accepted",
  original_outcome: "missed_deadline" | "completed_on_time",
  effective_at: string, due_at: string,
  exception: { state, kind, owner: { team?, user_email? } | null,
               systems: ("billing" | "product_access")[],      // the systems to correct
               resolution_condition: string,                   // e.g. "product_access account seats = 40"
               earlier_exceptions: number },                   // exceptions the commitment had before this one
  correction: { verified_at, summary } | null,
  accepted_exception: { accepted_by, accepted_at } | null,    // the reason is on the receipt only
  action_id: "act_…",                                         // the commitment's action
  href: "/v1/commitments/cmt_…"                               // the receipt: what each system showed
}
```

The values each system showed and the account's references in billing and in the product are not in the event;
they are on the receipt. Incident and review integrations (PagerDuty, Jira, GitHub Checks) raise nothing for these
events in this release.

### Account-change sample

*(0.10.0. Signed in only; an API key is `403 session_required` on every route here.)* The guided sample of the
commitments workflow, run in the person's own workspace: Account A is approved to go from 25 to 40 account seats, an
automation reports "completed", billing shows 40 and product access still shows 25. The commitment is incomplete;
the person assigns the exception, asks for a simulated correction, and reads it "Corrected and verified" with the
missed deadline kept.

It is the product's own path, not a mock of it: the approved change is received by the same function
`POST /v1/commitments` uses, its action is judged by the engine under the
[Commercial Account Changes pack](/docs/packs/commercial-account-changes)'s own contract (`cac_change_account_seats`,
with the pack's defaults), the exception is opened by the same rule, and the correction is verified by the same
contract on the later record. Only the evidence is the sample's.

**Nothing has to be set up.** The sample does not need the pack installed, a contract selected, a connection, a key
or an attestation, and it installs, selects and lists nothing. It works on every plan.

**Isolation** is the refund sample's (`POST /v1/onboarding/refund-sample-runs`, under Guided setup), by the same
mechanism:

- The sample's records carry the run's id and the evidence class `onboarding_sample` (shown as
  `trust_class: "sample_source"`). The engine reads only that run's records for the sample's commitment, so a sample
  record can never satisfy one of the workspace's commitments, and a record of the workspace (pushed or read by a
  connector, even for the same account reference) can never satisfy the sample.
- The sample's sources are the run's own declarations, never a connection or a key of the workspace.
- A sample commitment is **never metered** (`metering.verified_actions: 0`), **never in
  `GET /v1/commitments/summary`** (counted under `excluded.sample`), and **never announced**: no notice, email,
  webhook, Slack message or integration event.
- Its `commitment_ref` (`sample-account-change-<run>`) belongs to the sample: `POST /v1/commitments` with that
  reference is `409 conflict` (`details.reserved_for: "sample"`), so a real revision can never supersede it.

**The timeline is the scenario's own.** The run dates the change relative to the moment the run was started
(`run_at`): approved and effective two hours before, billing changed fifteen minutes after that, the automation's
report a minute later, product access observed still at 25 five minutes after that, and the deadline (`due_at`) five
minutes before `run_at`. Both sample sources are declared current at `run_at`, which is past the deadline, so the
commitment is judged by the ordinary rule the moment the first evidence is in: no clock is moved and nothing settles
early. The corrected record is dated when the person asks for it, which is after the deadline, so the correction is
late and `original_outcome` stays `missed_deadline`.

**One sample at a time.** A workspace has one run: starting again returns it, whoever asks and wherever it has got
to. `{ "rerun": true }` starts another, at most 10 a day per workspace (`429 sample_run_limit`); the refund sample's
ten a day are counted apart. Requests for one workspace are taken one after the other, so a double click makes one
run.

| Step (`step`) | How the person gets there | `next.action` |
|---|---|---|
| `created` | `POST /v1/onboarding/account-change-sample-runs` | `execute` |
| `incomplete` | `POST …/{run_id}/execute` | `assign` |
| `assigned` | `POST /v1/commitments/{id}/exception/assign` (the ordinary route) | `correct` |
| `corrected` | `POST …/{run_id}/correct` | `null` |

`step` is read from the commitment itself, so it is right however the exception was assigned. Assigning is not
required before the correction (`correct` works from `incomplete` too); the guided screen asks for it because the
journey is about ownership. If someone accepts the sample's exception through
`POST /v1/commitments/{id}/exception/accept`, `step` is `exception_accepted`, `next.action` is `null`, and `correct`
is `409 sample_not_incomplete`; `rerun` starts a fresh one.

#### `POST /v1/onboarding/account-change-sample-runs` (analyst, signed in)

Body optional: `{ "rerun"?: boolean }` (any other field is `422`). `201` with the run when a run was started, `200`
with the workspace's existing run otherwise. The approved change is received at once, so the answer already carries
the commitment. An `Idempotency-Key` header names the request: a retry with the same key (its answer was lost) answers
the run that request made or answered, `200` with `idempotent_replay: true` and header `Idempotent-Replay: true`, even
after another run was started; the same key for a different request (with or without `rerun`, or the other sample) is
`409 idempotency_key_reused`. Keys are per workspace.

```ts
{
  sample_run_id: "smp_…",
  is_sample: true,
  scenario: "account_change_missing_access",
  step: "created" | "incomplete" | "assigned" | "corrected" | "exception_accepted",
  status: string,                      // the same value as `step`
  steps: ["created", "incomplete", "assigned", "corrected"],
  next: { action: "execute" | "assign" | "correct" | null,
          hint: string,                // one sentence for the screen
          method: "POST" | null, path: string | null,   // the request that takes the next step
          body: object | null },       // for `assign`: { owner: { team: "Provisioning Operations" } }
  contract_id: "cac_change_account_seats", contract_version: 1,
  workflow: "change_account_seats",
  run_at: string,
  commitment: { id: "cmt_…", commitment_ref: "sample-account-change-…",
                status, original_outcome, exception_state,
                href: "/v1/commitments/cmt_…", app_href: "/app/commitments/cmt_…" },
  scenario_summary: {
    summary: "Move Account A from 25 to 40 account seats, effective today",
    account_label: "Account A",
    account: { account_ref: "sample-account-a", billing_ref: "sample-subscription-a",
               product_ref: "sample-product-account-a" },
    change: { seats_from: 25, seats_to: 40 },
    approved_by: "CommitLayer sample approver",
    executor: { kind: "automation", name: "Provisioning automation", reported: "completed" },
    suggested_owner: { team: "Provisioning Operations" },
    evidence_class: "onboarding_sample"
  },
  timeline: [{ key, label, done: boolean, at: string | null }],   // eight items, below
  receipt: { … }                       // the commitment's receipt, exactly GET /v1/commitments/{ref}
}
```

`timeline` keys, in order, each `done` by something the server recorded (never a timer): `commitment_received`,
`execution_reported`, `evidence_received:billing`, `evidence_received:product_access`, `outcome_decided`,
`exception_assigned`, `correction_received`, `correction_verified`.

At `created` the receipt reads `status: "pending"`, `original_outcome.state: "pending"`, `exception: null`, no
execution reports, and each of `systems` has `observed: null` and `final: false` (nothing has reported for the run
yet, so it waits although its deadline has passed).

#### `POST /v1/onboarding/account-change-sample-runs/{run_id}/execute` (analyst, signed in)

No body. Records the automation's report (`execution_reports[0]`: `status: "completed"`,
`executor: { kind: "automation", name: "Provisioning automation" }`, `counts_as_evidence: false`) and the first
evidence (billing at 40, product access at 25), then the engine judges. Answers the run (the shape above) with
`step: "incomplete"`:

- `receipt.status: "incomplete"`, `receipt.original_outcome.state: "missed_deadline"`;
- `receipt.systems`: billing `state: "matches"` (`observed: { quantity: 40 }`), product access `state: "differs"`
  (`expected: { seats: 40 }`, `observed: { seats: 25 }`);
- `receipt.headline`: `"Incomplete: billing reflects 40 seats; product access remains at 25 seats."`;
- `receipt.exception`: `state: "open"`, `kind: "missed_deadline"`, `owner: null`,
  `resolution_condition.text: "product_access seats = 40"`.

Idempotent per run: a run past this step is returned as it is. `404 not_found` for an id that is not an
account-change sample run of this workspace (a refund sample run's id included).

#### `POST /v1/onboarding/account-change-sample-runs/{run_id}/correct` (analyst, signed in)

No body. Pushes the simulated corrected product-access record (40 seats, dated now, the run's own) and reads the
commitment's evidence again, as `POST /v1/commitments/{ref}/verify` does. Answers the run with `step: "corrected"`:

- `receipt.status: "corrected"`, `receipt.status_label: "Corrected and verified"`;
- `receipt.original_outcome.state` still `"missed_deadline"`, with the same `decided_at` and `deadline`;
- `receipt.exception.state: "corrected_verified"`; `receipt.correction`: `verified_at`, `evidence` (the record of
  each system that showed it) and `summary`:
  `"Corrected and verified. The original change missed its deadline; product access was corrected later."`

`409 sample_not_incomplete` before `execute`, or when the exception was accepted (`details.step`). Idempotent per
run: a corrected run is returned as it is.

#### `GET /v1/onboarding/account-change-sample-runs/current` (viewer, signed in)

`200 {"run": {...}}` with the workspace's current run (its latest) in exactly the shape of the run by id, or
`200 {"run": null}` when the workspace has not started one: a workspace without a run is an ordinary state,
not an error. Read-only: it never starts a run.

#### `GET /v1/onboarding/account-change-sample-runs/{run_id}` (viewer, signed in)

The run, in the shape above, as it stands now.

#### The sample commitment through the ordinary routes

- `GET /v1/commitments/{ref}` (by id or by `commitment_ref`) returns its receipt with `is_sample: true`,
  `sample_run_id`, `environment: "sample"` and `metering.verified_actions: 0`.
- `GET /v1/commitments?sample=true` lists sample commitments only; `sample=false` the workspace's own only; without
  the filter both are listed, each marked by `is_sample`.
- `POST /v1/commitments/{ref}/exception/assign` and `…/exception/accept` work on it as on any commitment (no notice
  is sent). `POST /v1/commitments/{ref}/verify` re-reads the sample's own evidence. Execution reports can be added.
- Its action (`receipt.action.id`) is an ordinary action view with `is_sample: true` and
  `sample_scenario: "account_change_missing_access"`.

## Workflow packs

A pack is a versioned bundle of action contracts, evidence rules, identity links, recorder mappings, fixtures and benchmark scenarios for one kind of agent (`docs/packs/architecture.md`). Installing a pack creates **draft** contract versions and never activates anything; activation stays `POST /v1/contracts/{id}/select`, by a person with the analyst role. Reads take any member; configure and dry-run take an analyst and write nothing; install, upgrade and rollback take an analyst and `confirm: true`.

### `GET /v1/packs`

**Response** `{ items: PackSummary[], next_cursor: null }`

```ts
PackSummary = {
  id, name, version, status: "beta" | "ga" | "deprecated", description, minimum_plan: string | null, documentation_path,
  supported_action_types: string[], required_connectors: string[], optional_connectors: string[],
  workflows: [{ id, action_type, contract_id, contract_version, summary,
                minimum_plan: string | null,   // the workflow's own lowest plan, else the pack's minimum_plan
                consequential_tools: string[],
                parameters: [{ key, label, path, also: string[], type: "number" | "integer" | "duration" | "string" | "source" | "list" | "boolean", default, min?, max?, choices?,
                               removes: [{ check, path, without: string | null }] }],   // boolean only: the checks false takes out
                settlement, reversal, window, sources: string[], fixture_cases, scenarios }],
  evidence: [{ source, min_trust, accepted_classes: string[], note }],
  identity_links: [{ link_type, left: { source, subject_kind }, right: { source, subject_kind }, method, required_for: string[], how }],
  installed: { id, pack_version, status, installed_at, installed_by, configuration, contract_versions: { [contract_id]: version }, previous_version } | null,
  upgrade_available: boolean   // an installed pack whose installed version is older than the library's
}
```

Emits `pack_upgrade_available` for every installed pack with a newer release (also on `GET /v1/packs/{pack_id}`).

### `GET /v1/packs/{pack_id}`

`PackSummary` plus `contracts: { [contract_id]: yaml }`, `recorder_mapping`, `fixtures: { [workflow]: [{ id, title }] }`, `templates`, `readme`, `versions: string[]` and `requirements` (below). Emits the `pack_viewed` product event.

### `GET /v1/packs/{pack_id}/versions`

`{ items: [{ version, status, installed: boolean }] }`, oldest first. Every release the product ever seeded stays listed, which is what rollback uses.

### `POST /v1/packs/{pack_id}/configure`

**Request body** `{ configuration: { [workflow_id]: { [parameter_key]: value }, identity?: { [source]: { [setting]: value } } } }`

**Response** `{ pack_id, pack_version, contracts: { [contract_id]: yaml }, parameters: { [workflow_id]: { [key]: value_in_force } }, identity, warnings: Weakening[], dropped_checks: [{ workflow, check, parameter, text }], requirements }`. The values are validated against the parameter's type and bounds (`400 invalid_configuration`, `unknown_workflow`, `unknown_parameter`) and applied at the manifest's path (and every `also` path) in the contract; `warnings` lists every way a value makes a check weaker than the pack's default (a raised limit, a longer window, a check taken out). A `boolean` parameter (true or false only) keeps or takes out the checks it names under `removes`: false takes them out of the contract together, after every other value, and `dropped_checks` says in one plain sentence per check what CommitLayer can then not confirm ("Without an order system, CommitLayer cannot confirm the order was cancelled."). The Stripe pack's `refund_order` has three: `order_checks`, `case_checks`, `notification_check`. Every check left is the pack's own, unchanged. Nothing is written.

`identity` is how the connectors link the records of one case to the subject an action names (`app/connectors/linking.py`); it is accepted by a pack that declares identity links and is `null` in the answer of one that does not. The settings: `stripe.order_metadata_key` (the key of the charge's metadata that holds the order id; default `"order_id"`, `null` reads none), `shopify.payment_references` (link an order to the Stripe payments its transactions name; default `true`), `zendesk.order_field` (`"external_id"`, `"custom_field:<field id>"` or `null`, the default) and `intercom.order_attribute` (a conversation attribute name or `null`, the default). The answer's `identity` holds every setting in force, the defaults included. Any other source, setting or value is `400 invalid_identity`. The same `identity` is accepted by dry-run, install and upgrade, is stored with the installation and kept through an upgrade, and the Stripe, Shopify, Zendesk and Intercom connectors read the installed settings at their next sync. Links the connectors make carry `trust_class: "native_connector"`: `payment_to_order` (a Stripe payment and an order: from the Shopify order's transactions, or from the charge's metadata), `charge_to_payment` (a Stripe charge and its PaymentIntent) and `ticket_to_order` (a help-desk case and an order, from the configured field). The Stripe connector records each refund on the payment it refunds as well as on the customer. The refund's own metadata is never read, because the agent that refunds writes it.

`requirements = { plan: { current, minimum, lowest, ok, workflows: string[], upgrade_to }, connectors: [{ source, required, connected, allowed_on_plan }], evidence: [{ source, min_trust, min_evidence_trust_class, min_trust_label, covered, via, trust, evidence_trust_class, trust_label, legacy_rating, trust_ok, note }], missing_required_connectors: string[], ok }`. `evidence_trust_class`, `trust_label` and `legacy_rating` are the covering connection's or pushed source's, as `GET /v1/connections` states them (null when the source is not covered); `min_evidence_trust_class` and `min_trust_label` say the legacy `min_trust` in the same vocabulary (`shared` → `backend_attested` "Backend-attested", `independent` → `commitlayer_read` "CommitLayer-read", `self_reported` → `agent_reported`). `trust_ok` is decided on the legacy level, as the engine's `min_trust` gate decides it.

### `POST /v1/packs/{pack_id}/dry-run`

**Request body** `{ configuration?, workflow?: string }`

Runs every fixture case of the pack (or of one workflow) through the engine under the configuration (a case written for one combination of systems names its own `configuration`, laid over the request's): the case's facts arrive on temporary connections at the trust the case states, the action is recorded, verified, `later` facts are applied and it is verified again; everything happens in a savepoint that is rolled back, so the workspace keeps no claim, fact or connection from it.

**Response** `{ pack_id, pack_version, workflow, configuration, cases: [{ workflow, id, title, expected, observed: { outcome, policy, strict, codes, status, headline }, observed_after?, expected_after?, ok, note? }], summary: { total, ok, failed } }`. In `expected`, `observed` and their `_after` forms, `strict` is the scenario's strict result, **effects and policy together** (PASS only when every expected effect happened and no precondition, limit, prohibition or reversal failed). `policy` on this surface is a deprecated alias that always equals `strict`; it is **not** an action's `policy_verdict`, which judges the policy checks alone (a missing refund is `strict: FAIL` and `policy_verdict: PASS`). The published oracle values are unchanged. A case whose expectation was written for the pack's defaults may stop holding under a customer's configuration; `ok: false` with a `note` says so, which is what the dry run is for. Emits `pack_dry_run_started` and `pack_dry_run_completed`.

### `POST /v1/packs/{pack_id}/install`

Install, upgrade and rollback write contracts, so they take what saving a contract takes: an analyst signed in, or an API key that holds every scope. A `recorder` or an `evidence` key is refused with `403 insufficient_scope`.

**Request body** `{ configuration?, confirm: boolean }`

Validates the configuration, checks the plan, saves the configured contract of every workflow the plan may install as a **draft** at the next version the workspace has for that id, renders the recorder mapping with those versions pinned (rules for the contracts it wrote only), and records the installation. A workflow's plan is its own `minimum_plan`, else the pack's: on Developer the Stripe pack installs `refund_order` only, and an upgrade or reconfiguration on a higher plan adds the rest. `requirements.plan.workflows` lists the workflows the plan may install, `ok` is whether there is one, and `upgrade_to` names the plan that has them all. A plan that may install none is `402 plan_required` with `details.upgrade_to`. `400 confirmation_required` without `confirm: true`; `400 already_installed` for the version already installed (use upgrade). Audit: `pack.installed`. Emits `pack_installation_started` and `pack_installed`.

**Response** `{ install, contracts: [{ contract_id, version, status: "draft" }], warnings, recorder_mapping, activation: { steps: string[], how, note } }`

### `GET /v1/packs/{pack_id}/upgrade`

What moving the installation to the pack's current release would change: `{ pack_id, from_version, to_version, same_version, contracts: [{ contract_id, change: "added" | "removed" | "changed" | "unchanged", weakened?: Weakening[], strengthened?: Weakening[] }], parameters: { added, removed }, configuration, dropped_configuration, mapping: { kept, added, removed, changed: [{ tool, keys }], warnings }, warnings }`. `mapping` is what the upgrade does to the workspace's recorder mapping: the tools whose rule is added, removed or changed (`keys` names what changed in the rule), with a warning for every rule that goes and for every parameter whose `units` change, because a tool that keeps sending the amount the old way is recorded with another amount afterwards. `kept: true` says the workspace replaced its mapping and the upgrade keeps it as it is. `weakened` lists checks the new contract accepts more on, `strengthened` the ones it accepts less on, both computed against the workspace's installed draft with the customer's configuration re-applied. `404 not_installed`.

### `POST /v1/packs/{pack_id}/upgrade`

**Request body** `{ configuration?, confirm: boolean }`. New drafts for every contract of the current release, the configuration re-applied (or replaced when given), the previous release recorded. Active contracts are untouched. Audit: `pack.upgraded`. Emits `pack_upgraded`.

### `POST /v1/packs/{pack_id}/rollback`

**Request body** `{ confirm: boolean }`. Reinstalls the previous release's contracts as new drafts from the registry's stored copy, with the configuration that was in force then. `400 nothing_to_roll_back` when there is no previous release. Audit: `pack.rolled_back`.

### `GET /v1/packs/{pack_id}/coverage`

`{ pack_id, installed, sources: [{ source, required, covered, via: "connector" | "facts_api" | "generic_csv" | "otel" | null, trust, evidence_trust_class, trust_label, legacy_rating, min_trust, min_evidence_trust_class, min_trust_label, trust_ok, watermark_age_seconds, stale, status }], unmapped_consequential_tools: string[], observed_tools: [{ name, read_only, mapped, first_seen_at, last_seen_at }], mapping_customised_at, contracts: [{ workflow, contract_id, installed_version, activated, active_version, draft_versions, last_verified_pass_at }], identity_links: [{ link_type, required_for, links_seen }], identity: { settings: { [source]: { [setting]: value } }, links_made_by_connectors: { payment_to_order, charge_to_payment, ticket_to_order } } | null, collected_at }`

`identity` (null for a pack without identity links) is what the connectors sync with in this workspace (the installed configuration's `identity` over the defaults) and how many links of each kind they have made.

### `GET /v1/packs/{pack_id}/scenarios`

`{ items: [{ workflow, scenarios: [{ id, failure_mode, title, narrative?, agent_trace_says?, fixture_case, expected }], fixture_cases: string[] }] }`. `expected` is the deterministic oracle written with the scenario; the pack's tests fail when the engine disagrees with it. `expected = { outcome?, policy?, strict?, codes?, status? }`: `strict` is the scenario's strict result, **effects and policy together** (PASS only when every expected effect happened and no precondition, limit, prohibition or reversal failed). `policy` on this surface is a deprecated alias that always equals `strict`; it is **not** an action's `policy_verdict`, which judges the policy checks alone (a missing refund is `strict: FAIL` and `policy_verdict: PASS`). The published oracle values are unchanged. The MCP `get_pack_scenarios` tool answers the same.

### Product events

Pack events go through the product analytics pipeline (`app/ops/analytics.py`) with the workspace as the subject and
never carry a subject id, a parameter value or a credential: `pack_viewed` (get), `pack_connector_selected`
(configure, per source parameter), `pack_contract_drafted` (one per contract saved by install, upgrade or rollback;
properties `pack_id`, `pack_version`, `contract_id`, `contract_version`, `plan`, `connectors`, `via: rest | mcp`),
`pack_installation_started`, `pack_installed`, `pack_activated` (`POST /v1/contracts/{id}/select` on a contract an
installed pack owns), `pack_upgrade_available`, and per settled verdict under a pack's contract
`pack_verification_completed` (`pack_id`, `pack_version`, `workflow`, `outcome`, `policy`, `reason_codes`,
`test_or_production`, `plan`) with `pack_failure_detected`, `pack_unknown_returned` or `pack_reversal_detected` when
that is what the verdict is.

### `GET /v1/packs/{pack_id}/recorder-mapping`

The recorder mapping to give the MCP recorder or a framework integration: the workspace's own copy once the pack is installed, with `contract_version` pinned to the installed drafts, so a recorder configured from it records against those versions on purpose. Those versions are drafts until a person selects them: an action recorded against a draft is refused with `409 contract_not_active` until then (`POST /v1/actions`), so select the installed contract before pointing a recorder at the mapping. After an upgrade or a rollback the mapping pins the new drafts, and a recorder that fetches it again is refused until they are selected. Before an installation it is the pack's mapping as the default configuration renders it, with no versions. A rule the pack marks `when_source` is served only when the configured contract reads that source (a workspace whose help desk is HubSpot is served the HubSpot rule and not the Zendesk one).

The answer is the file for a recorder and holds the recorder's own keys only: `agent_id`, `workflow_id` and `tools` at the top, and `contract_id`, `contract_version`, `action_type`, `subject`, `subject_kind`, `params`, `action_id` and `compensates` in a rule. The TypeScript recorder refuses a file that holds any other key, so the keys only the API reads are left out of it. `GET /v1/packs/{pack_id}/recorder-mapping?annotated=true` is the workspace's whole document with those keys: `units`, `when_source` and `describes` in a rule, `consequential_tools` (the tools that must have a rule), `read_only_tools` (tools a person says change nothing) and `customised_at` at the top. Edit the annotated document and send it back with `PUT`; give a recorder the plain one. `recorder_mapping` in `GET /v1/packs/{pack_id}` and in the answer of an install is annotated too and is not a file for a recorder.

`unmapped_consequential_tools` in the coverage is every tool in the mapping's `consequential_tools`, and every tool reported through `observed-tools` that was not read-only when first reported and is not in the mapping's `read_only_tools`, for which the mapping has no rule. A rule is found the way a recorder finds it: the exact key, then the first key whose part after the last dot is the name. A tool nobody listed and nobody reported is not known to the API.

### `PUT /v1/packs/{pack_id}/recorder-mapping`

Body `{ mapping }`: the whole document, edited. Answers the stored document. The annotated document (`?annotated=true`) is the one to edit; the plain file a recorder is served can be edited and sent back too, because a rule that leaves out `units`, `when_source` or `describes` keeps what the stored rule of the same tool name has (for the parameters the rule still lists), and a document that leaves out `consequential_tools` keeps the stored list. A key is removed by sending it empty (`units: {}`, `describes: []`, `when_source: null`). A tool sent under a new name has no stored rule to take from: state its `units` on the rule, or its amounts are read in major units. Everything else is replaced as sent: rename a key to the name your MCP server gives the tool, change a path to your tool's argument, add a tool, and list your own `consequential_tools`. Analyst role; an API key needs every scope (a `recorder` key is refused with `403 insufficient_scope`). `404 not_installed` before an installation. `400 invalid_mapping` when a recorder could not use it: no `tools`, a rule without `contract_id` or `subject`, a `contract_id` that is not an action contract of the workspace, `units` or `describes` for a name that is not one of the rule's `params`, or a unit other than `major` or `minor`. `describes: [<param>]` on a rule lists the parameters that describe the call and are not part of what the action is; a second record of the same action may word them differently, and every other parameter both records carry has to agree. `read_only_tools: [<tool>]` at the top lists tools that change nothing; coverage does not warn for them. A rule for one of the pack's contracts that names no `contract_version` is pinned to the installed draft. The stored mapping carries `customised_at`; it is kept through an upgrade and a rollback, with the versions pinned again. One part of it follows the configuration all the same: a rule with `when_source` for a source the contracts as now configured do not read is left out, and the pack's rule for the source they read instead is added when the mapping has no rule of its own with that `when_source`, so a workspace that changes `helpdesk_source` is not left with the other help desk's rule. The `mapping` section of the upgrade preview names both. To go back to the pack's mapping, send `recorder_mapping` from `GET /v1/packs/{pack_id}`.

`units: { <param>: "minor" }` on a rule says the tool sends that parameter in the minor unit (`4000` for forty dollars, as the Stripe API does). When an action arrives from a recorder (`channel` is `mcp` and `params.mcp_tool` names the tool, the two things every recorder sends) under a contract of an installed pack, the intake converts the value by the action's `currency`, the same rule the Stripe connector applies to its facts, stores the result as the parameter, and returns what was sent under `action.units` (`{ amount: { unit: "minor", sent: 4000, currency: "usd", decimals: 2 } }`). The value is divided by 100, except for the currencies Stripe's currency page lists as zero-decimal (BIF, CLP, DJF, GNF, JPY, KMF, KRW, MGA, PYG, RWF, VND, VUV, XAF, XOF, XPF), which are taken as sent; ISK and UGX are divided by 100, as that page says they are written. An action that states no currency is read as hundredths, with `currency: null, decimals: 2` in `action.units`. Currencies with three decimals are not told apart (Stripe's list of them was not available when this was written) and are divided by 100 on both sides. An action that names no tool, one on another channel, or one whose tool the stored mapping has no rule for, is stored as sent. So is a value that is not a finite number (`nan`, `inf`).

### `POST /v1/packs/{pack_id}/observed-tools`

Body `{ tools: [{ name, read_only? }] }` (1 to 200 per call, 500 kept per pack): tool names seen in front of the agent, from the tool list of your MCP server or from a recorder that forwarded a call it had no rule for. `read_only` is the server's own statement about the tool (`annotations.readOnlyHint` in its `tools/list` answer); a tool reported without it is taken to change something. Needs `actions:record`, so the recorder's key can send it. Returns `{ recorded, unmapped_consequential_tools }` for the names in this call. `read_only` counts when a name is first reported. A tool once reported as changing something stays so through this route, whoever reports it again, so the key that records cannot quieten the warning about a tool it does not record; a later `read_only: false` does turn a read into a tool that must have a rule. To say a reported tool changes nothing, list it under `read_only_tools` in the mapping (`PUT`, a key with every scope). `404 not_installed` before an installation.

## Guided setup

The guided setup "Connect your first real workflow". Every route answers `404 not_found` unless the workspace has the rollout flag `real_workflow_onboarding_v1` (`entitlements.features` in `GET /v1/auth/me`; off by default; a platform admin sets it per workspace with `PATCH /v1/admin/tenants/{id}` and `{"features": {"real_workflow_onboarding_v1": true}}`, and `REAL_WORKFLOW_ONBOARDING_V1` is the deployment's default). The routes are for a signed-in person: an API key answers `403 session_required`. An impersonating platform admin can read and cannot write (`403 impersonation_read_only`). Request bodies take the fields listed and nothing else.

The setup stores what people chose and consented to and where each person is in the tour. It never stores that a step is done: every flag in `workspace_steps` is read from contracts, API keys and recorded actions when the state is requested, and no route accepts one from a client. Every write is idempotent and answers the whole state, the body of the read.

### `GET /v1/onboarding` (viewer; a counterparty receives the orientation with nothing of the workspace in it)

```ts
{
  version: 3, enabled: true,
  mode: "setup"|"orientation",
  status: "not_started"|"profiling"|"configuring"|"waiting_for_real_action"|"action_received"|"verdict_ready"|"evidence_not_independent"|"needs_configuration"|"completed",
  plan: { id, name, native_connectors: boolean, packs: boolean, slack: boolean, upgrade_to: string|null,
          connectors: { [system]: { allowed: boolean, requires_plan: string|null } } },
  workspace: { name, suggested_name, actions_this_month: number },   // real actions of the month with a settled verdict; suggested_name: the name refund-first's step 1 offers (a name given to the workspace is kept; a name made from a company address loses " workspace"; a personal address gives the person's name). Naming it is PATCH /v1/settings/tenant
  viewer: { role, can_configure: boolean, can_administer: boolean, invited: boolean, joined_configured: boolean,
            impersonating: boolean, orientation_reason: "role"|"invited_configured"|"completed"|null,
            show_welcome: boolean, show_orientation: boolean },
  profile: { goal: string|null, recording_methods: string[], evidence_systems: string[], workflow: string|null, completed: boolean },
  recommendation: null | { key: string|null, kind: "library_contract"|"pack_workflow"|"none", label, contract_id, pack_id, pack_name, workflow_id,
                           available: boolean, reason, closest: { key, kind, label }|null, candidates: Candidate[], alternatives: Candidate[],
                           recorder_method: string, notes: { code, ... }[] },
  workflow: null | { kind, key, label, contract_id, contract_version, pack_id, pack_name, workflow_id, installed: boolean|null,
                     exists: boolean, plan_ok: boolean, rules: Rules|null },
  refund: null | { answered: boolean,                // the refund workflow's questions; null for any other workflow
                   answers: { orders: "shopify"|"other"|"backend"|"none",
                              support: "zendesk"|"intercom"|"salesforce"|"hubspot"|"other"|"backend"|"none",
                              notification: "backend"|"none", max_refund: number, window: string,
                              payment?: "stripe"|"other"|"backend" },   // payment: once refund-first onboarding stored one
                   suggested: { ...the same, from question 3 },
                   options: { orders: string[], support: string[], notification: string[], windows: string[] },
                   configuration: { refund_order: { [parameter]: value } } | null,
                   rules: Rules|null,                   // the contract the answers make
                   dropped_checks: { check, text }[],  // the checks it leaves out, in plain words
                   warnings: string[],                 // values looser than the pack's (a larger refund, a longer window)
                   built: boolean,                     // the installed contract was built from these answers
                   roles?: RefundRole[] },             // refund-first onboarding only: one mapping line per role
  workspace_steps: { workflow_selected, contract_selected, contract_activated, recorder_method_selected, recorder_configured,
                     evidence_sources_selected, evidence_sources_connected, identity_mapping_configured,
                     checks_uncovered: number|null, checks_without_supplier: number|null,
                     first_real_action_id: string|null, real_evidence_received: boolean, first_real_verdict: "PASS"|"FAIL"|"UNKNOWN"|null,
                     first_real_verdict_reviewed: boolean, second_real_verification: boolean },
  steps: { key, n: 1..7, status: "done"|"current"|"waiting"|"todo", blocked: null|{ code: "role_required", role_required, upgrade_to } }[],
  contract: { confirmed: boolean, confirmed_by: string|null, confirmed_by_name: string|null, confirmed_at: string|null,
              confirmed_version: number|null, selected_now: boolean, governs_unselected: boolean,
              dropped_checks: { check, text }[],            // what the version a confirmation is for leaves out
              dropped_checks_confirmed: string[]|null },    // the check ids the recorded confirmation named
  action: null | { id, contract_id, contract_version: number|null, requested_at, recorded_at, environment, recorded_via, href,
                   before_setup: boolean, key_side: "recorder"|"full"|null, chosen: boolean,
                   subject_ref: string|null, status: "pending"|"settled"|null, settles_at: string|null },
  user_tour: { welcome_seen, profile_completed, current_step: string|null, dismissed_at: string|null, last_seen_at: string|null,
               resumed_count: number, orientation_completed },
  started_at: string|null, started_by: string|null, completed_at: string|null,
  sources: Source[], coverage: Coverage[],
  identity: { status: "not_required"|"required"|"seen"|"configured"|null, links: { link_type, left: { source, subject_kind }, right: { source, subject_kind }, method, how, links_seen: number, seen: boolean, links_trusted: number, trusted: boolean }[] },
  credentials: Credentials, recorder: Recorder, verdict: null | Verdict,
  candidates: { id, subject_ref, requested_at, recorded_at, status: "pending"|"settled", href }[],   // up to five other real actions
  last_real_action: null | { id, requested_at, recorded_at, status: "pending"|"settled", verdict: "PASS"|"FAIL"|"UNKNOWN"|null, href },
  second_verification: null | { id, contract_id, href },
  notifications: null | { email: boolean, email_recipient: boolean, slack: boolean, slack_available: boolean,
                          slack_plan: boolean, slack_configured: boolean, slack_upgrade_to: string|null,
                          notified_at: string|null },
  resume: null | { step: string|null, href: string|null }, // "/app/onboarding/refund" while that route has work left
  refund_first?: { enabled: true, landing: boolean, route: string }  // present only where refund-first onboarding
                                                                      // applies to the reader (docs/onboarding/refund/)
}
Credentials = { recorder_key: { exists: boolean, count: number, name: string|null, created_at: string|null, last_used_at: string|null },
                evidence_key: { needed: boolean, exists: boolean, count: number, name: string|null, fact_sources: string[],
                                needed_sources: string[], missing_sources: string[], last_used_at: string|null },
                full_access_keys: number, can_create: boolean,
                suggested: { recorder_name: string|null, evidence_name: string|null, evidence_sources: string[] } }
Recorder = { method: string|null, methods: string[], deployed_at: string|null, deployed_by: string|null,
             confirmed: boolean, key_used: boolean,
             last_recorder_heartbeat: string|null, heartbeat_window_days: 30, last_evidence_heartbeat: string|null,
             heartbeats: { recorder: { key_id: string|null, key_name: string|null, key_side: "recorder"|"full"|null, revoked: boolean,
                                       last_action_at, channel: string|null, method: string|null }[],
                           evidence: { source, via: "connector"|"facts_api"|"csv", last_at }[] },
             diagnostics: { not_counted: { reason, count: number, last_at }[] },
             waiting_since: string|null }
Source = { source, required: boolean, expected: boolean, selected: boolean, via: "connector"|"facts_api"|"csv"|"otel_context"|null, system: string|null,
           plan_required: string|null, suggested: { via: "connector"|"facts_api", system: string|null },
           status: "connected"|"syncing_first"|"error"|"receiving"|"key_ready"|"context_only"|"not_connected",
           supplied_by: "connector"|"facts_api"|"csv"|null,
           connector: null | { system, display, allowed_on_plan: boolean, requires_plan: string|null, scopes: string[], fields_pulled: string[],
                               docs_url, scopes_verified: false, contract_fact_types: string[], writes_contract_facts: boolean },
           connection_id: string|null,
           health: null | { status, system, ok: boolean, message: string|null, reauth: boolean, last_sync_at: string|null },
           watermark: string|null, watermark_age_seconds: number|null, stale: boolean, last_evidence_at: string|null,
           facts: null | { registered: boolean, evidence_key: boolean },
           trust: "independent"|"shared"|"self_reported"|null,
           evidence_trust_class: string|null, trust_label: string|null, legacy_rating: boolean|null,  // as on GET /v1/connections; null with `trust`
           trust_ok: boolean|null, effects: string[] }
Coverage = { effect, kind: "precondition"|"limit"|"expected"|"forbidden"|"reversal", source, type: string|null, text, min_trust: string|null,
             supplied_by: "connector"|"facts_api"|"csv"|null,
             status: "covered"|"missing_evidence"|"source_not_connected"|"source_stale"|"source_not_trusted"|"identity_link_required",
             reason: string|null }
Verdict = { status: "pending"|"settled",
            outcome, policy, verdict: "PASS"|"FAIL"|"UNKNOWN"|null,          // all three null while pending
            provisional: null | { state: "provisional_fail"|"failing_so_far", code, label, message },  // pending only (CL-148)
            counts: boolean, needs_configuration: boolean, legitimate: boolean,
            independence: "independent"|"self_supplied"|"unattributed"|"none",
            unknown_kind: "configuration"|"operational"|null,
            causes: { code, kind: "configuration"|"operational", source: string|null, step: string|null, fixed: boolean, param: string|null }[],
            reopens: string[], unsupplied_sources: string[],
            effects: (Entry & { effect, state: "observed"|"pending"|"missing"|"below_trust", freshness: Freshness|null })[],
            checks: (Entry & { kind: "precondition"|"limit"|"required_param"|"aggregate"|"forbidden_effect"|"reversal", param: string|null })[],
            sources: { source, freshness: Freshness, watermark: string|null, connection_id: string|null, via: "connector"|"pushed"|null }[],
            evidence: { received: boolean, sources: string[], trust_classes: string[] },
            reason_codes: string[], reasons: { code, label }[],              // empty while pending
            settles_at, settled_at: string|null, next_check_at: string|null, recheck_due: boolean, sync_queued: boolean,
            reviewed: boolean, reviewed_by: string|null, reviewed_by_name: string|null, reviewed_at: string|null, href }
Entry = { source: string|null, type: string|null, text, ok: boolean|null, code: string|null,
          observed: null | { param, value } | { attr, value } | { attr, expected, observed } | { required_trust, observed_trust },
          observed_at: string|null, reference: string|null, fact_ref: string|null, trust_class: string|null, evidence: boolean|null }
Freshness = "current"|"pending"|"stale"|"unavailable"|"key_ready"|"not_connected"
Candidate = { key, kind, label, contract_id, pack_id, pack_name, workflow_id, available: boolean, unavailable_reason: "plan_required"|null, requires_plan: string|null }
Rules = { summary, action_type, subject_kind, window, preconditions: string[], limits: string[], required_params: string[],
          expected_effects: { source, type, text }[], forbidden_effects: string[], required_sources: string[], other_sources: string[] }
```

Evidence trust (slices 3 to 5) adds, without changing `status`:

- `progress { state, verdict_version, sources }`: one status of the setup's first real action for every surface (the
  Overview, the refund route, Refund activity, the action page): `waiting_for_action`,
  `action_received_waiting_for_evidence`, `evidence_received_attestation_required`, `evidence_received_identity_required`,
  `evidence_received_settling`, `verification_scheduled`, `pass`, `fail`, `unknown`. A client compares `state` and
  `verdict_version` with what it showed to know something changed.
- `verdict.guidance { state, sources, action, missing_link_types?, requested_at?, watermarks?, next_check_at?, settles_at? }`:
  step 7's state (`waiting_for_evidence`, `trust_insufficient`, `identity_mapping_missing`, `source_settling`,
  `verification_scheduled`, `verdict_ready`) and its fix (`{ kind: "verify_evidence_sources", screen: "evidence",
  anchor: "verify-evidence" }`: the attestation is on the real-integration evidence screen, no longer step 4 or `{ kind: "review_identity_mapping", screen: "evidence", anchor: "identity-mapping" }`).
- `verdict.identity { status, compared, unmatched_sources, missing_link_types }` (identifiers by their last characters),
  `verdict.evidence_counts`, `verdict.reason`, `verdict.verdict_version`, and per effect `evidence_state`,
  `evidence_required`, `evidence_observed`, `records`. A record that arrived and that the contract cannot count for its
  trust adds the configuration cause `evidence_not_eligible` (step `configure_credentials`): such a verdict
  `needs_configuration` and cannot complete the setup.
- `refund.keys_saved { recorder_copied, evidence_copied, env_downloaded, saved_server_side, complete }`: step 4's
  record of how the new keys were kept (`POST /v1/onboarding/refund/keys-saved`), booleans only. A real action whose
  pushed sources are not attested opens `refund_first.screen: "evidence"` (it opened `credentials` until the
  attestation left step 4).
- `refund.attestation.rows[].effect_labels` ("Refund created", "Order cancelled", "Support case updated") and
  `refund.attestation.statement.explanation`; `workflow.rules.expected_effects[].accepted_classes`.

`notifications` is the notice of the workflow's first real action. When an API key records the workflow's earliest real action, the workspace's first owner and the person who began the setup are emailed once, each unless they turned it off (`email`); `email_recipient` says whether the caller is one of them. The email names the workflow and the workspace and links to `/app?setup=resume`; it carries nothing of the action. `slack` is true when a line will also be posted to the workspace's Slack channel: an admin asked for it, the plan has Slack alerts (`slack_plan`) and Slack is configured (`slack_configured`). `notified_at` is when the notice was queued; it is sent once per workspace, a restart included.

`resume` is where the setup opens for a person who comes back: `{ step: "review_verdict", href: "/app/actions/{id}" }` once the setup's real action exists, the current step before that, and both null once the setup is complete. A person who chose "Resume later" before that action arrived reads `user_tour.dismissed_at: null` from then on; dismissing again afterwards holds. `notifications` and `resume` are null for a counterparty.

`action` is the setup's real action: the earliest action an API key recorded in production under the chosen workflow's contract, or the one a person chose in its place (`chosen`). It carries `subject_ref` (the subject's last characters behind an ellipsis), `status`, `settles_at` and `contract_version` (the version the action was recorded and judged under, which a later selection does not change) beside the fields above, and never the subject id, a parameter or the caller's own action id. `last_real_action` is served once the setup is complete: the workflow's newest real action and the engine's latest verdict on it (`verdict` is null until that action has settled). A test-marked action, a sandbox run and an action a person recorded are never it.

`verdict` is the engine's verification of that action, laid out for the setup; nothing in it is computed a second time. While the action is `pending`, `outcome`, `policy`, `verdict` and `reason_codes` are empty, and an expected effect that has not been observed is `pending`, never `missing`: nothing is a finding before the engine settles. Settled means the engine has frozen a verification of the action: the verdicts it stored while the action was pending are not a verdict, also when a record that arrived since would change them. When every awaited record is in (or the window has closed) and the engine has not verified the action again, `recheck_due` is true, the one cause is `verification_due`, and the read queues the engine's own `verify_action` job once for the action. While pending, a forbidden effect, a reversal or an aggregate limit that has not been violated has `ok: null`, since a record can still arrive inside the window; a violation already observed is `ok: false`. `effects` has one entry per expected effect and `checks` one per precondition, limit, required parameter, aggregate limit, forbidden effect and reversal. `sources` gives the freshness of every source the checks read: `not_connected` (nothing supplies it), `key_ready` (a live evidence key is bound to it and no record has arrived, the word step 2 uses), `unavailable` (its connection is in error), `pending` (the verdict is waiting for it, or a connection is on its first read), `stale` (the verdict settled with it behind, or a connector's last read is older than two days), `current`.

What the block shows of a customer's records is limited by the server. `reference` is the record's own reference by its last characters, `fact_ref` the product's id of the fact, and `observed` is null except on a check that did not hold, where it carries the one value that explains it: the number a limit or a maximum was compared with, the two trust levels, a state the contract names, or the compared attribute (a number as it is, anything else by its last characters). Parameters, fact attributes, subject ids and whole references are on the action's own page and not here.

`independence` is read from the class the engine wrote on each fact under a check: `self_supplied` when one of them was pushed by a key that also records actions or observed by the agent's runtime, `unattributed` when one has no system behind it (typed in by a signed-in person, sent inline with a verification request), `independent` otherwise. When no check rests on a fact (a FAIL or an UNKNOWN on what was not there), the records the engine matched to the action's subject decide: one the recording side sent or a person typed gives the verdict that class, since without it the engine would not have known the subject, and only when all of them came from a system of record, or there is none, is the independence `none`. `counts` is a settled verdict whose independence is `independent` or `none`; `workspace_steps.first_real_verdict` is the verdict when it counts. For a settled UNKNOWN, `unknown_kind` says whether something is left to set up (`configuration`: a required source nothing supplies, a connection in error, a parameter the recorder left out, no record under the id the agent recorded) or the systems of record have not said enough (`operational`); `causes` lists each with the step that fixes it and `fixed` when the workspace no longer shows the problem. A settled FAIL whose failed checks are all expected effects on sources nothing supplied when it settled (`unsupplied_sources`, read from the frozen verification) is caused by the setup too: `causes` then lists each such source. `needs_configuration` is true for that FAIL and for a configuration UNKNOWN, and `legitimate` is a verdict that counts and does not need configuration: only such a verdict can be reviewed. The cause codes are `source_never_connected`, `source_sent_nothing` (an evidence key is bound to the source and it has sent nothing), `connection_in_error`, `identity_link_missing`, `evidence_after_verdict` (records on the subject arrived after the verdict settled; always `fixed`), `recorder_param_missing` (configuration) and `pending_settlement_window`, `source_not_yet_synced`, `awaiting_first_evidence` (with `source` when an evidence key is ready for a source that has sent nothing while the window is open, without when no record on the subject has arrived at all), `effect_in_waiting_state`, `verification_due` (operational). The status is `verdict_ready`, `evidence_not_independent` or `needs_configuration` accordingly, and with `needs_configuration` the steps in `reopens` read as not done.

`second_real_verification` is true, and `second_verification` names the action, once another real action of the workspace (under any action contract) has a settled verdict that counts by the same rule as the first (not on evidence the recorder supplied itself or a person typed), after the first verdict counted.

`credentials` is read from the workspace's API keys on every request, and no key, hash or prefix is in it. A recorder key is a live key that holds `actions:record` and not `facts:write`; an evidence key is a live key that holds `facts:write` and not `actions:record`. A key that holds both, or that predates scopes, is counted in `full_access_keys` and satisfies neither. `needed_sources` are the contract's sources the workspace sends through the Facts API (planned so, or suggested so where no plan was made; a source a native connection reads, a file supplies or a person planned as context needs no key): the sources the contract cannot decide without, the ones a person planned, and every source an expected effect reads (`sources[].expected`), since a PASS needs a record from each of those, and `missing_sources` those among them no live evidence key is bound to. The step `configure_credentials` is done when a recorder key exists and `missing_sources` is empty. A key's `name` is served to an admin or owner only; `suggested` holds names for the two keys and never a key.

`recorder.confirmed` is true when a real action for the chosen contract has arrived from an API key, and for no other reason: not a chosen method, not `deployed_at` (a person's statement), not a key that has only read (`key_used`). `last_recorder_heartbeat` is when the newest such action of the last `heartbeat_window_days` days arrived (null when the recorder has been silent for longer, which does not unconfirm it), and `heartbeats.recorder` the last one per key among the newest 200 of those days, with the channel the recorder wrote and the method that writes that channel (`null` for the SDKs and a plain REST call, which write none). `last_evidence_heartbeat` is the newest of `heartbeats.evidence`: per source of the contract, when its last record arrived from an evidence key or a file (`last_evidence_at`), or when its native connection last read. While no real action has arrived, `diagnostics.not_counted` says why the workspace's 20 most recent actions are not it: `not_recorded_with_api_key`, `environment_test`, `other_contract`, `sandbox_run`, `sample_action`, `sandbox_contract`, `synthetic_workspace`. `status` is `waiting_for_real_action` once steps 1, 3 and 4 are done, step 2 is done or waiting, a method is chosen and no real action exists; `waiting_since` is when a read first saw that. In a heartbeat, `key_id` and `key_name` are served to an admin or owner only, like the list of keys; everyone else reads `key_side` and the time. `action.before_setup` is true when the first real action arrived before the setup was begun (`started_at`), and `action.key_side` says which side of the line the key that recorded it is on: `full` is a key that can also push facts.

`sources` has one entry for each source the chosen workflow's contract reads, and `coverage` one for each of its checks that reads a system of record. Both are read from the workspace's connections, API keys and facts when the state is requested. A source is `connected` when a native connection is healthy and has finished a read, and `receiving` when a record has arrived for it that an evidence key pushed or a file imported; only those two make `evidence_sources_connected` true. A record with no key behind it (typed in by a signed-in person, written by a sandbox run, sent by a recorder beside its own action) is not evidence here. An expected effect or a precondition is `covered` by a pushed source once a record of that fact type has arrived; until then it reads `missing_evidence` with the reason `type_not_received`. Step 2 is `done` when every required source is connected and rated as the contract asks and every expected effect and precondition is covered; `workspace_steps.checks_uncovered` counts the ones that are not, and `checks_without_supplier` those among them that wait on nothing (no supplier, a supplier rated too low, a connector that does not write the fact). `connector.contract_fact_types` lists the fact types the contract reads from the source that the connector writes; an empty list means the connector supplies nothing to this contract. An identity link counts (`trusted`) when a connector read it or an evidence key pushed it; `identity.status` is `seen` when every link exists and at least one is of another or unknown origin, and `identity_mapping_configured` is then false. `last_evidence_at` is when the newest record of a fact type the contract reads arrived. `syncing_first` (tested, first read running) and `key_ready` (an evidence key is bound to the source, nothing received) are set up and not connected: step 2 then reads `waiting`. `error` carries the connection's own health message. `context_only` means the source has records from a key that also records actions, or from OpenTelemetry, and no evidence: context, never proof. `connector.scopes` and `connector.fields_pulled` are the connector's declared lists as `GET /v1/connections/catalog` serves them; `scopes_verified` is always false, because the product cannot check what a pasted key is allowed to do. `facts.registered` says whether the engine counts a pushed source as present, which the first record sent under that name does. `stale` is a native connection's watermark older than two days. `coverage[].reason` is one of `no_supplier`, `connection_error`, `nothing_received`, `first_sync_running`, `connector_does_not_write` (the connected system's connector does not record that fact type under that source name), `self_supplied`, `context_only`, `trust_below_minimum`, `watermark_old`, `link_not_seen`, or null when covered. `identity_mapping_configured` is null when the workflow needs no identity link. `first_real_action_id` is the first action recorded for the chosen workflow's contract with an API key, in `environment: "production"`, outside the sandbox and outside the synthetic demo workspace. `contract.governs_unselected` is true for a library contract: an action recorded under its id is judged by it whether or not it was selected, so for a library workflow a confirmation is a record of a decision and not a switch. It is false for a workspace's own contract (a pack workflow's drafts): a draft nobody selected governs no action (`409 contract_not_active` on `POST /v1/actions`), so for a pack workflow the confirmation, which selects the version, is what lets the agent record.

`mode` is `orientation` for a viewer or counterparty, for everyone once the setup is complete, and for a member whose invitation was sent after the workspace was configured (`viewer.joined_configured`): after the first read that showed steps 1, 3 and 4 done, step 2 done or waiting, and the real action arrived. A member invited before that, while the keys or the recording code are still to be done or the workspace is waiting for its action, gets `setup`. It is `setup` otherwise. A workflow `key` is a library contract id or `pack_id/workflow_id`.

### `PATCH /v1/onboarding/profile` (analyst)

The four answers; send the ones that changed. `goal`: `customer_operations`, `engineering_operations`, `access_it`, `payments_trading`, `paid_apis_x402`, `scheduling`, `other`. `recording_methods`: any of `mcp`, `langgraph`, `crewai`, `openai_agents`, `pydantic_ai`, `temporal`, `inngest`, `opentelemetry`, `python_sdk`, `typescript_sdk`, `rest`, `custom_service`, `not_sure`. `evidence_systems`: any of `stripe`, `shopify`, `salesforce`, `hubspot`, `zendesk`, `intercom`, `coinbase`, `github`, `ci_cd`, `monitoring`, `identity_provider`, `hr_system`, `internal_api`, `internal_database`, `webhook_events`, `other`. `workflow`: a key from `recommendation.candidates`, or `custom`. A value outside these lists is `422`; a workflow the product does not have is `400 unknown_workflow`. The answer to `recommendation` follows from the answers: it names one workflow that exists now and that the workspace's plan can use, and lists what the plan cannot use with the plan that has it.

### `POST /v1/onboarding/select-workflow` (analyst)

`{ "kind": "library_contract", "contract_id" }` or `{ "kind": "pack_workflow", "pack_id", "workflow_id" }`. Checked against the library, the packs on offer and the plan at the time of the request: `404 unknown_workflow`, `402 plan_required` with `details.upgrade_to`. Choosing selects no contract. A different choice clears a confirmation recorded for another contract. Audit: `onboarding.workflow_selected`.

### `POST /v1/onboarding/confirm-contract` (analyst)

`{ "contract_id", "version", "confirm": true, "dropped_checks"?: string[] }`. Selects the chosen workflow's contract for the workspace exactly as `POST /v1/contracts/{id}/select` does (the plan's limit on selected contracts, `402`, included) and records who confirmed which version and when. `400 confirmation_required` without `confirm: true`; `409 no_workflow_selected`; `409 contract_mismatch` for a contract other than the chosen workflow's; `409 version_mismatch` for a version the workspace does not have; `409 pack_not_installed` for a pack workflow whose pack is not installed. A version of a pack workflow's contract that leaves checks out (`contract.dropped_checks`, read from the configuration of the installation that wrote it) is confirmed with exactly those check ids in `dropped_checks`, which is the person's confirmation that CommitLayer will not check them: `409 dropped_checks_unconfirmed` otherwise, with `details.dropped_checks`. They are recorded with the confirmation (`contract.dropped_checks_confirmed`). For a pack workflow the version is the one the installation wrote, also while an earlier one stays selected. Confirming the same version again while it is still selected changes nothing. Audit: `onboarding.contract_confirmed` (with `dropped_checks`) and `contract.selected`.

### `PATCH /v1/onboarding/refund` (analyst)

`{ payment?, orders?, support?, notification?, max_refund?, window? }`: which system plays each role of the Stripe pack's refund workflow, the largest refund and the settlement window. `orders`: `shopify`, `other`, `backend` or `none`; `support`: `zendesk`, `intercom`, `salesforce`, `hubspot`, `other`, `backend` or `none`; `payment` (refund-first onboarding): `stripe`, `other` or `backend`; `notification`: `backend` (a system the workspace pushes notifications from) or `none`; `max_refund` a number from 1; `window` a duration such as `1h` or `24h`. The payment is Stripe and is not asked. A field left out keeps its earlier answer, or the suggestion from question 3 (Shopify when named, the first help desk named, `backend` when the workspace named a service of its own, the pack's limit and window). The answers are stored in full on the first save. `409 not_refund_workflow` when the chosen workflow, or before a choice the recommended one, is not `stripe_customer_operations/refund_order`; `422` for a value outside the lists; `400 invalid_answer` for one the pack refuses. Nothing is installed. Audit: `onboarding.refund_answers_saved`.

The answers make the workflow's configuration: `approved_limit` and `daily_limit_per_order` are the largest refund, `window` the window, `order_checks`, `case_checks` and `notification_check` are false for a role answered `none`, `order_source` and `helpdesk_source` name the system answered, and `case_resolved_status` is the status that help desk's connector records (`solved` for Zendesk, `closed` for Intercom and Salesforce, `4`, the default pipeline's Closed stage, for HubSpot). `refund.dropped_checks` lists, in plain words, every check a role answered `none` takes out.

`other` (a system CommitLayer has no connector for) and `backend` (the workspace's own backend sends it) keep the role's checks and read them from a source the workspace pushes through the Facts API under the role's own name: `order_source` `orders`, `helpdesk_source` `support` with `case_resolved_status` `resolved`. The refund has no such setting: the pack's contract reads it under `stripe` whatever the payment answer. Where refund-first onboarding applies to the reader, `refund.roles` has one line per role: `{ role: "payment"|"order"|"support", system, via: "connector"|"facts_api"|null, source, fixed_source, requires_plan, min_trust }` (`fixed_source` true when the contract reads a pushed payment under `stripe`; `min_trust` the trust the contract asks of that evidence, which a pushed record meets only once an admin rates its source).

### `POST /v1/onboarding/build-contract` (analyst)

`{ "confirm": true }`. Installs the Stripe Customer Operations pack with the stored answers' configuration, or saves new drafts of the installation that is there (its other workflows and identity settings kept), exactly as the pack's install and upgrade do: drafts only, the plan's workflows only (Developer: `refund_order`). Building again with answers the installation already has writes nothing. A new version clears a confirmation recorded for an earlier one. `400 confirmation_required`; `409 no_workflow_selected`; `409 not_refund_workflow`; `409 refund_answers_required` before the answers are saved; `402 plan_required`. Audit: `onboarding.contract_built` (with the version and the dropped check ids).

### `POST /v1/onboarding/select-evidence-sources` (analyst)

`{ "sources": [{ "source", "via": "connector"|"facts_api"|"csv"|"otel_context", "system"? }] }`. The plan for supplying each source the chosen contract reads; it replaces the plan stored before. `source` is the contract's own name for the source (`409 no_workflow_selected` before a workflow is chosen, `400 unknown_source` with `details.known` otherwise, `400 duplicate_source`). `system` names a native connector and defaults, for `connector`, to the connector the source is named after: `400 system_required` when there is none, `400 connector_does_not_provide` when that connector does not read the source. A connector the workspace's plan does not include is not refused: the source is stored as `facts_api` and its entry in `sources` carries `plan_required`. The route stores a plan and nothing more: it creates no connection, takes no credential (a body with any other field is `422`), calls no system, and no source reads as connected because of it. Connecting is `POST /v1/connections`, by an admin. Choosing another workflow clears the plan. Audit: `onboarding.evidence_sources_selected`.

### `POST /v1/onboarding/select-recorder` (analyst)

`{ "method" }`: one of `mcp_recorder`, `langgraph`, `crewai`, `openai_agents`, `pydantic_ai`, `temporal`, `inngest`, `python_sdk`, `typescript_sdk`, `rest` (`400 unknown_method` otherwise, with `details.methods`). `opentelemetry` answers `400 evidence_only`: a span cannot record an action under an action contract. The choice is stored and nothing else happens; choosing another method clears `deployed_at`. Where this is the first thing saved in the setup it sets `started_at`, as the first answer and the choice of a workflow do. Answers the state.

### `POST /v1/onboarding/evidence-trust` (admin; refund-first onboarding only)

`{ "sources": string[], "attest": true }`. The admin rates the sources the workspace's own backend sends through the Facts API as the source of record, at the trust the refund contract asks of each (`independent` for the refund and the order, `shared` for the support case), on the Facts API connection's per-source setting (`config.source_trust`, as `PATCH /v1/connections/{id}` sets it). `attest: true` is the admin's statement that the evidence key is held only by the backend that reads these records and that the agent cannot write through it; without it the body is `422`. `404` where refund-first onboarding does not apply to the caller; `403` for an analyst, an API key or an impersonating admin; `409 no_workflow_selected` before the refund workflow is chosen; `409 not_pushed` for a source the contract does not read through the Facts API or a connector serves; `409 evidence_key_required` for a source no live evidence key is bound to. It never lowers a rating and never changes the connection's own level; records a key holding `actions:record` pushes stay `self_reported` whatever is rated. Audit: `connection.trust_changed` with `via: guided_setup` and `attested`. Answers the state.

Since evidence attestation, it also stores an attestation (`via: evidence_trust_v0949`) of each live evidence key bound to each named source, as `POST /v1/evidence/attestations` would with every confirmation; a pair already attested is left as it is. It is the compatibility path for that route.

### `POST /v1/onboarding/refund-sample-runs` (analyst, signed in; the runnable refund sample)

Starts the workspace's onboarding sample run, or returns the one already running for the scenario (idempotent per
workspace and scenario; a fresh token is issued for a run still running and the earlier token stops working; none for a
run whose verdict is persisted). `{ "rerun": true }` starts another run (at most 10 a day per workspace,
`429 sample_run_limit`). An `Idempotency-Key` header names the request, as on the account-change sample: its retry
answers the run it made (`200`, `idempotent_replay: true`, a fresh token while the run still runs), never a second
run; the key reused for a different request is `409 idempotency_key_reused`. The run is under the canonical refund contract itself, whatever the workspace chose at step 2
and whether or not it has a contract yet: nothing is installed, selected or listed in the workspace. An API key is
`403 session_required`. Does not depend on the guided setup's flag (the Overview's "Run the sample" uses it too).

```
201 { "sample_run_id": "smp_…", "sample_token": "cls_smp_…" | null, "token_header": "X-CommitLayer-Sample-Token",
      "expires_at": "…" (30 minutes), "contract_id": "scop_refund_order", "contract_version": 1,
      "workflow_id": "refund_order", "window": "1h",
      "identifiers": {"action_id": "onboarding-sample-…", "order": "onboarding-order-001",
                      "customer": "onboarding-customer-001", "support_case": "onboarding-ticket-001",
                      "payment": "onboarding-payment-001"},
      "payloads": {"action": {…POST /v1/actions body…}, "facts": {…POST /v1/facts body…}},
      …the run's view (below)… }
```

The token is `cls_smp_<run>.<nonce>.<HMAC-SHA256>` over the run, workspace, person, contract and version, scenario,
expiry and nonce; the run keeps its SHA-256, never the token. It expires after 30 minutes or once the verdict is
persisted. The run's action is requested at the run's own moment (`requested_at` = `run_at`; never dated a
settlement window back) and its records carry that moment. The sample's evidence is a closed set: once every source
it reads has declared its checkpoint for the run, the verdict settles at once. `requested_at`, `settlement_deadline`
(`requested_at` + 1h) and `settled_at` are separate fields, and every list and detail shows the same run time.

### `POST /v1/onboarding/refund-sample-runs/dry-run` (viewer, signed in)

`{ "corrected"?: boolean }` → `{ persisted: false, scenario, contract_id, contract_version, verification }`.
Evaluates the workspace sample without storing it: the canonical contract and the sample's own scenario, through the
same ingestion and engine as a recorded run, inside a transaction that is rolled back. `verification` is the action
view a recorded sample shows (same checks, evidence, verdict, `headline`, `supporting_copy` and relative dates) with
`dry_run: true`. Nothing is written, counted or announced. An API key is `403 session_required`.

### `POST /v1/onboarding/refund-sample-runs/{id}/execute` (analyst, the run's person)

The one-click path: the server records the run's action (`record_action`) and its records, links and watermarks
(`ingest`, `ingest_links`), then `verify_action`. Idempotent per run. Answers the run's view.

### `GET /v1/onboarding/refund-sample-runs/{id}` (viewer, signed in)

`status` (`created`, `action_accepted`, `facts_accepted`, `verifying`, `verdict_ready`, `expired`, `failed`),
`action` (`state`, `id`, `href`), `facts` (`state`, `accepted`, `expected`, per source), `watermarks`,
`verification` (`state`, `verdict`, `verdict_id`, `verdict_version`, `reason_codes`, `explanation`,
`matches_scenario`), `timeline` (the seven step 6 items, each `done` by a server event, with its time), `events`,
`errors`, `run_at`, `requested_at`, `corrects_run_id`, `corrected_by`, `reviewed`.

### `POST /v1/onboarding/refund-sample-runs/{id}/review` (analyst)

"I reviewed this verdict" on the run's persisted verdict (`409 no_sample_verdict` before it). The first review stands.
It does not complete onboarding yet.

### `POST /v1/onboarding/refund-sample-runs/{id}/correct` (analyst)

"Run the corrected version": a second run of the corrected scenario (the Shopify cancellation added), linked by
`corrects_run_id`, executed at once; it passes. The first run's verdict never changes. Idempotent per run.

**Sample actions everywhere else.** Every action view carries `is_sample`, `sample_run_id`, `sample_scenario` and
`sample_contract_version`. A sample action is excluded from usage, the summary's totals (`excluded.sample`), the
workspace's own and real actions, webhooks, integrations, Slack and email, and pack telemetry; it counts toward the
workspace's first verdict (`first_verdict_received`) and sends `guided_sample_verdict_received` once. Its records have
`evidence_trust_class: "sample_source"` ("Sample source — generated by CommitLayer for this guided run") and are
read for their own run's action only; a production action never reads them, and a sample action never reads a
production record. `GET /v1/onboarding` carries `refund.sample` (the newest run's id and state, never a token).

### `POST /v1/onboarding/refund/keys-saved` (analyst; refund-first onboarding)

`{ recorder_copied?, evidence_copied?, env_downloaded?, recorder_env_downloaded?, evidence_env_downloaded?,
recorder_saved_server_side?, evidence_saved_server_side? }`, booleans only: any other field is `422`, so a key's value
cannot be sent here by mistake. Notes, once each, that a key was copied, that its environment file was downloaded (the
browser makes it; nothing is sent), and each key's own acknowledgement: "I stored the Runtime recorder key server-side"
(`recorder_saved_server_side`) and "I stored the Evidence pipeline key server-side" (`evidence_saved_server_side`). One
acknowledgement never covers both keys: the 0.9.56 field `saved_server_side` is no longer accepted (`422`). A field
sent `false` unsays nothing, and a restart clears them. `409 keys_missing` when the key being acknowledged does not
exist; `409 not_refund_workflow` outside refund-first onboarding's refund workflow; `403` for an API key. Audit:
`onboarding.refund_keys_saved` with the field names. Answers the state: `refund.keys_saved.recorder` and `.evidence`
(`exists`, `copied`, `env_downloaded`, `saved_server_side`, `acknowledged_at`, `acknowledged_by`, `statement`) and
`complete`, true when both keys were acknowledged. The flat fields of 0.9.56 are still returned, derived from that
record (deprecated). See docs/onboarding/refund/real-integration-checklist.md.

### The engineer handoff (admin; refund-first onboarding)

See docs/onboarding/refund/handoff-guide.md.

- `POST /v1/onboarding/handoff/preview { email, role?, note? }` → what will be sent: `recipient`, `workspace`,
  `workflow`, `systems`, `role`, `role_label`, `recommended_role`, `why_role`, `destination`, `note`,
  `already_completed`, `assigned`, `email { subject, text }`. Creates nothing.
- `POST /v1/onboarding/handoff { email, role?, note? }` → `201 { handoff, created, why_role, state }`. `role` is
  `admin` (default) or `owner`; `note` is plain text, at most 1,000 characters. Idempotent per address.
- `POST /v1/onboarding/handoff/{id}/resend` → the state. The same email again while nobody joined. `409
  already_joined`, `409 handoff_cancelled`, `429 resend_too_soon` (once a minute, five in all).
- `POST /v1/onboarding/handoff/{id}/cancel` → the state. Ends the handoff; a pending invitation's membership is
  removed. Cancelling twice changes nothing.
- `GET /v1/onboarding/handoff` (viewer) → `{ items, default_role, roles, why_role, subject }`.
- `GET /v1/public/handoff-invitations/{token}`, also `GET /v1/public/invitations/{token}` (no session) → the
  invitation for its own page, the same answer for the engineer handoff and for an invitation from Settings,
  Members: `product`, `kind` (`handoff`, `member`), `status` (`pending`, `joined`, `cancelled`, `expired`),
  `inviter`, `workspace`, `role`, `role_label`, `role_description`, `why_role`, `purpose`, `next_steps`,
  `destination`, `expires_at`, `workflow`, `systems`, `asked` (the last three empty for a member invitation),
  `sentence`, `note`, `invitee` (a hint, never the whole address), `accept_path`, `page_path`. `404` for any other
  token. The first read of a pending invitation is its "Opened". An invitation expires fourteen days after it was
  last sent.
- `GET /v1/public/invitations/{token}/address` (no session) → `{ email }`, the invited address, for filling the
  sign-up form in. Only while the invitation is pending; `404` otherwise. `GET /v1/auth/workos/authorize` takes
  `invite=<token>` and passes the same address to the hosted sign-in as `login_hint`.

Since CL-0100: a handoff names its `workflow` (`refund`, `account_change`; existing handoffs are `refund`) and
carries `progress` (`invited_not_started`, `joined_not_started`, `begun`) and `begun_at`: joining is not beginning.
The refund journey's `handoff.state` reads `in_progress` only once the engineer began (their own step or key, or
`POST /v1/onboarding/setup-tasks/refund/begin`), never because someone else did a step after they joined. The
public invitation page adds `workflow_key`; its `purpose`, `destination` and `accept_path` are the handoff's own
workflow's (`/app/commitments/setup?handoff=<token>` for the account-change setup).

### The account-change handoff (admin; CL-0100, RC-19, RC-20)

"Send setup to my engineer" from the account-change experience: the refund handoff's mechanism with the
account-change setup's subject ("Finish connecting the CommitLayer account-change workflow"), workflow, systems
(Billing: Stripe; Product access: your application), steps and destination (the account-change setup checklist).
Session only (`403 session_required` for an API key); writes need Admin, as the refund handoff's do.

- `POST /v1/onboarding/account-change/handoff/preview { email, role?, note? }` → as the refund preview, with
  `workflow_key: "account_change"`; `already_completed` names the pack turned on, the rules confirmed and the guided
  sample finished. The email also says that the setup page carries the workspace's engineering quickstart
  (`GET /v1/onboarding/account-change/quickstart`). Creates nothing.
- `POST /v1/onboarding/account-change/handoff { email, role?, note? }` → `201 { handoff, created, why_role,
  checklist }`. Idempotent per address and workflow (one address may hold a refund and an account-change handoff).
- `GET /v1/onboarding/account-change/handoff` (viewer) → `{ items, default_role, roles, why_role, subject }`.
- `POST /v1/onboarding/account-change/handoff/{id}/resend`, `.../{id}/cancel` → the checklist; the refund routes'
  rules (`409 already_joined`, `409 handoff_cancelled`, `429 resend_too_soon`; an Owner's invitation is resent or
  cancelled by an Owner). `404` for a handoff that is not the account-change setup's.

The engineer's joining notice names the workflow; their one reminder, a day later, is sent while the account-change
checklist is not complete.

### Setup checklists (CL-0100, RC-19, RC-20)

`GET /v1/onboarding/setup-tasks/{workflow}` (any signed-in member; `workflow`: `refund` or `account_change`) → the
one persisted checklist every participant reads:

```ts
{
  workflow, route,
  steps: [{ key, n, title, event, status: "done"|"current"|"todo"|"waiting"|"not_started", done, needs, note,
            started_at, completed_at, completed_by: Person|null, assigned_to: Person, href,
            reopened_at: string|null, persisted: true, result?: {...} }],
  done, total, complete, current,
  progress: "not_handed_off"|"invited_not_started"|"joined_not_started"|"in_progress"|"complete", progress_line,
  handoff: null | { ...the handoff, engineer, invited_by, state (= progress), state_line, opened_at, begun_at,
                    can_resend, can_cancel },
  viewer: { is_engineer, is_inviter, waiting_on_engineer, can_begin },
  etag, generated_at
}
```

`Person` is `{ kind: "user"|"system"|"role", user_id, name, email, via? }` (`via`: `approver_key`, `evidence_key`,
`attestation`, `connection`, `recorder_key`). Every step completes by a product event, never a click. A completion
is stored once (`onboarding_setup_tasks`) when it is first observed, with who and when; every later read, by either
person, in any tab, returns those values while the step stays complete. A step whose condition stops holding (its
key revoked) is reopened (`reopened_at`; the earlier completion is kept). `done` and `complete` are computed from the
same items, so an unchecked item never stands beside "n of n done". Before the engineer begins, every step still to
do reads `not_started` (account change) and `progress` says `invited_not_started` / `joined_not_started`.

`refund`: the seven steps of the real-integration checklist (as `GET /v1/onboarding`'s `journey.integration`, which
adds `progress` and `progress_line`); `409 not_refund_workflow` when the workspace's guided setup is not the refund
workflow's. `account_change` adds `prerequisites { pack_installed, contract_active }` and `first_result`, with five
steps:

| key | completes when | completed_by |
|---|---|---|
| `approver_key` | a live key with `commitments:write` and without `actions:record` exists | its creator |
| `evidence_keys` | every source the account-change rules read that no connection reads has a live evidence key bound to it (`note: "not_needed"` when connections read every source) | the last key's creator |
| `attest_sources` | each such source holds an attestation in force (by an Owner or Admin who did not create the key) | the attestor |
| `connect_sources` | every source is supplied (a connection or an attested key) and has sent a record | who made the connection, or the key's creator |
| `first_result` | the first production approved change (never a sample or a test-environment change) whose original decision read its connected systems (`completed_on_time`, `missed_deadline` or `requirement_violated`) | CommitLayer; `result { commitment_id, commitment_ref, state, decided_at, href }` |

`POST /v1/onboarding/setup-tasks/{workflow}/begin` (Admin, session) → the checklist. The invitee says they are
starting; `403 not_invitee` for anyone else. A second call changes nothing. Audit `onboarding.handoff_begun`.

**First connected result notice.** When an account-change commitment's original decision is stored, the writer that
stored it claims the workspace's milestone `first_connected_result:account_change` (one `verdict_milestones` row) for
the earliest connected decision, and only that writer writes the notice `first_connected_result` (in the app and by
email) to the evaluator (who sent the setup and the first Owner) and the engineer who joined, once per person:
`title "First connected account-change result: <commitment_ref>"`, `href /app/commitments/<id>`, `data {
notification_type, workflow: "account_change", commitment_id, commitment_ref, revision, original_decision,
decided_at, href }`. A recheck, a retry, a second worker, a later decision or a duplicate settlement sends nothing
more; a read of the checklist claims a milestone a failed writer left unclaimed and announces it while it is less
than a day old. Samples and test-environment changes never count, as no commitment of theirs is announced. The refund workflow's first real verdict notice (`first_real_verdict`) is
unchanged and separate.
- Only an Owner resends or cancels an invitation to be an Owner (`403 role_above_own`).

### `POST /v1/onboarding/recorder-deployed` (analyst)

No body. Records who said the recording code is deployed and when (`409 no_recorder_selected` before a method is chosen); the first statement stands. It completes no step. Answers the state.

### `GET /v1/onboarding/snippet` (viewer)

`?method=&language=`: the code that records an action under the chosen workflow's contract. `method` defaults to the chosen method, then `rest`; `language` to the method's first (`python` or `typescript` for `mcp_recorder`, `temporal` and `inngest`; `python` for `langgraph`, `crewai`, `openai_agents`, `pydantic_ai` and `python_sdk`; `typescript` for `typescript_sdk`; `curl` for `rest`). `409 no_workflow_selected` before a workflow is chosen; `409 pack_not_installed` for a pack workflow whose pack is not installed (its contract does not exist in the workspace yet, and an action recorded under it would be refused with `404 unknown_contract`); `400 unknown_method`, `400 evidence_only` (`opentelemetry`), `400 unknown_language` (with `details.languages`).

```ts
{ method, label, language, languages: string[],
  contract: { contract_id, version: number|null, action_type, subject_kind, subject, params: { name, type: "number"|"string" }[] },
  package: null | { registry: "pypi"|"npm", name, version, install },
  files: { name, language: "bash"|"json"|"python"|"typescript", code }[], code,
  env: ["COMMITLAYER_RECORDER_KEY"],
  placeholders: { name, stands_for }[],
  rules: string[], notes: { code, text }[] }
```

Every name in the code is the contract's own as it resolves at the request: its id, action type and subject kind, and the parameters its checks read (`contract.params`). No value is made up: what the caller's system knows is an argument of its own function, a path into its own tool call, or a `${NAME}` listed in `placeholders`. The key is read from the environment and is never in the answer: `env` names the variable. Every method reads the canonical `COMMITLAYER_RECORDER_KEY` (0.9.57; the published packages fall back to `COMMITLAYER_API_KEY`, deprecated, with a warning, when it is unset). `package` is the published version the code is written for (the SDK `commitlayer` at PyPI 0.1.5 and npm 0.1.6, which `/health` names as `python_sdk_version` and `typescript_sdk_version`; the recorder and integrations packages at PyPI 0.1.4 and npm 0.1.5); `notes` say what that version cannot do (it has no `environment` parameter, so its actions are stored as `production`) and name the later version where the workflow needs one. `code` is the file to show first (for `mcp_recorder`, the command; its mapping is the other file). For a pack workflow the MCP recorder's mapping is the pack's own rules for the contract, every one of them: the published recorders read a subject template such as `zendesk_ticket_{arguments.ticket_id}`. Where the mapping is written from the contract, its rule carries an `action_id` template built from an argument of the tool call, `${OPERATION_ID_ARGUMENT}`: the published recorder's own id is built from the MCP request number, which starts again with every session, so without the template a call in a later session is taken for an earlier one. Every listed placeholder is one the code itself uses. Reading a snippet stores and sends nothing.

### `GET /v1/onboarding/refund/quickstart` (viewer)

The refund workflow's quickstart, generated from the workspace's source-binding record: `env_files` (the two
environment files, each with its key line empty for the browser to fill), `languages.python|typescript|rest.files`
(`{ path, language, process: "recorder"|"evidence"|null, content, run }`: complete programs, and the exact command
that runs each), `sources` (the exact source ids the evidence programs publish and checkpoint: the evidence key's
scope), `managed_sources` (read by a CommitLayer connector; nothing is sent for them), `source_bindings`,
`evidence_key`, `links`, `endpoints` (`preflight`, `batches`), `arguments` (`["ORDER_ID", "AMOUNT"]`: every program
requires both and records or publishes nothing without them), `checkpoint_only` (the evidence programs' argument that
sends checkpoints alone) and `sdk` (the pinned versions). Before the refund workflow is chosen the canonical record
stands (`stripe`, `shopify`, `zendesk`). A workspace whose every source a connector reads has no evidence program,
and the TypeScript project then names none. No secret is in the answer. The certification job
(`scripts/certify_quickstart.py`) runs exactly these files.

Since 0.9.60 the answer also lists every integration artifact the product advertises, so a surface (and the
certification job) reads one list:

- `artifacts[] = { id, kind, process, language, label, program, files, env_file, install, run }`. `kind` is `recorder`
  (`recorder-python`, `recorder-typescript`, `recorder-rest`), `evidence_publisher` (`evidence-python`,
  `evidence-typescript`, `evidence-rest`, the last being the bash program on curl; absent where the workspace publishes
  no evidence), `env_template` (`env-recorder`, `env-evidence`), `source_bindings` and `install_instructions`. `files`
  names every file that makes the artifact whole (a TypeScript program with `package.json` and `tsconfig.json`), each
  served in this same answer.
- `source_bindings_file = { name: "commitlayer-source-bindings.json", content }`: the workspace's contract, source ids,
  evidence-key scope, bindings and links, as a file.
- `install_file = { name: "INSTALL.md", content }`: for each language the files, the pinned install and the two
  commands, the same `run` lines as above.

- `evidence_options = { reported: { flag: "--reported", sources }, record_id: { flag: "--record-id", needs } }`
  (`null` where the workspace publishes no evidence): what the three evidence programs take after `ORDER_ID AMOUNT`.
  `--reported SOURCE[,SOURCE]` publishes only the records those sources have for the order (the ids are the
  workspace's own; every checkpoint is still sent); `--reported SOURCE --record-id ID` publishes one more record of
  that source under the source's own id, so a second refund on an order is a second record and never a replay.
  Without either, a program sends every record once, as before, and a second run stores nothing twice.
- `situations[] = { key, title, when, steps[], result }`: what to run for what the workspace's systems report,
  with its own source ids. Each step is `{ process: "recorder" | "evidence", arguments, repeat? }` (the arguments go
  after the language's own command, in place of `ORDER_ID AMOUNT`) or `{ process: "product", text }`. The keys are
  `completed_refund`, `over_limit`, `missing_record`, `second_record`, `other_order` and `before_attestation`; the
  two about the payment system's records are absent where CommitLayer reads that system itself. The page shows them
  beside the programs, and `INSTALL.md` prints them as each language's commands
  (docs/evidence-pipeline.md, "Publish what your systems actually have").

The artifacts are the workspace's, derived on every read from its current configuration (answers changed and the
contract confirmed again: the programs follow). The read does not depend on the real-integration checklist's step and
is the same before the keys, at every step and after completion; it creates no key, no contract version and no action,
and never returns a key's value: each environment template has its key line empty, and the programs name environment
variables only. The site shows them on Connections ("Integration files"), which the checklist, the refund workflow's
page and the completed setup's summary link to (`journey.integration.artifacts`).

### `GET /v1/onboarding/account-change/quickstart` (viewer, signed in)

The account-change workflow's engineering quickstart (CL-0100): what "Send setup to my engineer" hands over on the
account-change experience. `env_files[] = { name, content, keys }` (`commitlayer-approver.env`,
`commitlayer-evidence.env`: the API address and the workspace id, every key line empty for the person to fill),
`languages.python|typescript|rest = { files: [{ path, language, content }], install, run: { approve, publish, read } }`
and `sdk` (the pinned versions). The programs: `approve` sends an approved change with the approver key
(`POST /v1/commitments`, arguments `CHANGE_REF ACCOUNT_REF BILLING_REF PRODUCT_REF SEATS_FROM SEATS_TO
DUE_IN_MINUTES`), `publish` sends what billing or product access holds with that source's evidence key
(`billing|product_access ACCOUNT_ID SEATS`), `read` reads the receipt (status, original decision, current assessment,
exception, monitoring). Every program refuses to run without its arguments, names its workspace (`workspace_id`), reads
keys from the environment only and never prints one. Served to any signed-in member whatever the guided setup's
rollout; an API key is `403 session_required`. No secret is in the answer and reading it creates nothing.
`scripts/rem3/quickstarts.py` runs exactly these files in clean environments.

### `PUT /v1/onboarding/refund/draft` (viewer; refund-first onboarding)

`{ screen, workspace_name?, payment?, orders?, support?, understood?, exit? }`: the refund route's form as the person
left it, whole, every time. `screen` is one of the route's screens; `payment`, `orders` and `support` are the same
keys `PATCH /v1/onboarding/refund` takes; `workspace_name` is at most 80 characters; any other field is `422`. It is
the one persisted onboarding draft (`onboarding_setup.draft`), replaced by each save. With `exit: true` the setup is
also put away for the caller (as `POST /v1/onboarding/dismiss` does), in the same transaction: both are stored, or
neither. "Save and exit" calls it and says "Answers saved." only after it answered `200`.

A draft is not an answer. Nothing is installed, built, confirmed, activated or marked done by it, and
`refund.answers` is unchanged: "Review the workflow" (`PATCH /v1/onboarding/refund`) is still what confirms the
choices, and it then takes them out of the draft. The answer is the state; `refund_first.draft` is
`{ screen, workspace_name, systems: { payment?, orders?, support? } | null, understood, saved_at, saved_by }` or
`null`. `workspace_name` is returned while the workspace was not renamed since the save. Before the contract is
confirmed, `refund_first.screen` is the draft's screen (`q1` or `q2`) for the person who saved there and has not
moved since, so the route reopens on the form with the draft's choices and never on a later screen built from older
answers. After the contract is confirmed the form no longer exists: a save keeps the position and the exit only.
The form's choices are the workspace's: they are stored for an Analyst, Admin or Owner; a Viewer's call stores their
position and the exit. `403` for an API key and an impersonating admin. Audit: `onboarding.draft_saved` with the
screen and the three choices (never the name), once per change. A restart clears the draft.

### `GET /v1/onboarding/evidence-snippet` (viewer)

One helper per source the workspace's backend sends, in REST, Python and TypeScript:
`sources[].files[] = { name, language, code, run }` (`run`: for the REST file, the commands that run it as it is, one
per record type and `checkpoint`). Each call is one atomic batch to `POST /v1/evidence/batches`: the record, the
identity link it needs (`subject.link`, whose `linked_source` is the workspace's configured order source) and the
source's checkpoint (`checkpoint: { field: "observed_through", source }`); each file also sends the checkpoint
alone. `placeholders` explains every `${NAME}` of the REST file, `OBSERVED_THROUGH` included. `packages` names the
published SDK version and the method the code calls (`request`). A source a live connector serves is under
`excluded`. `409 no_workflow_selected`. Reading it stores and sends nothing.

### `POST /v1/onboarding/step`, `/dismiss`, `/resume` (viewer)

The caller's own place in the tour. `step` takes `{ "current_step", "event"?: "viewed"|"completed"|"target_missing", "anchor"?, "route"? }`: `current_step` is one of the tour's step ids (`welcome`, `orientation`, `workflow.nav`, `workflow.recommended`, `workflow.rules`, `workflow.select`, `systems.nav`, `systems.sources`, `systems.add`, `systems.connector`, `systems.permissions`, `systems.connect`, `systems.health`, `systems.backend`, `systems.coverage`, `credentials.nav`, `credentials.new-key`, `credentials.recorder`, `credentials.evidence`, `credentials.shown-once`, `contract.configure`, `contract.coverage`, `contract.confirm`, `recorder.method`, `recorder.code`, `recorder.verify`, `recorder.waiting`, `verdict.open`, `verdict.intent`, `verdict.contract`, `verdict.sources`, `verdict.evidence`, `verdict.verdict`) and `anchor` one of the tour's anchors; anything else is `422`, so no string a client makes up is stored or sent with an event; `welcome` marks the welcome seen, and `orientation` with `event: "completed"` marks the orientation finished. No step id changes `workspace_steps`. `route` is a pattern such as `/app/contracts/[id]`; a concrete path is refused. `dismiss` hides the setup for the caller until `resume`, which takes an optional `{ "entry": "header"|"help"|"email_link"|"refund_route"|"dashboard_card" }` (`dashboard_card`: the refund dashboard's Resume setup card, after Setup options' "Save and exit"). Since 0.9.60 the refund route's "Save and exit" is `PUT /v1/onboarding/refund/draft` with `exit: true`, which stores the form with the exit; `dismiss` alone stores no choice.

### `POST /v1/onboarding/select-action` (analyst)

`{ "action_id" }`: the `id` of one of `candidates` (the action's own `action_id` is accepted too). Makes that action the one the setup is about, in place of the earliest. `409 no_workflow_selected`; `404 action_not_found`; `409 not_a_real_action` with `details.reason` (`not_recorded_with_api_key`, `environment_test`, `sandbox_run`, `sample_action`, `sandbox_contract`, `synthetic_workspace`, `other_contract`); `409 setup_completed` once the setup is complete. Audit: `onboarding.action_chosen`.

### `POST /v1/onboarding/review-verdict` (analyst)

`{ "action_id" }`. Records who reviewed the setup's first real verdict and when, and completes the setup (`completed_at`, status `completed`). The rule is applied by the server from what the product holds: `409 no_real_verdict` when the action is not the setup's real action or its verdict has not settled, `409 evidence_not_independent` when the verdict does not count, `409 needs_configuration` for a verdict that something left to set up caused (an UNKNOWN, or a FAIL whose failed checks all read sources nothing supplied). No field of any request can mark the setup complete. Reviewing again changes nothing: the first review stands. Audit: `onboarding.verdict_reviewed`.

### `POST /v1/onboarding/restart` (admin)

`{ "confirm": true }` (`400 confirmation_required` without it; `409 setup_completed` once the setup is complete, which stays complete). Clears the answers (the refund workflow's included), the chosen workflow and the confirmation with the checks it named. Contracts, connections, API keys, actions and verdicts are not touched, and a step that is still true reads as done again. The notes that an action's arrival, its evidence and its verdict were reported are kept, so choosing the same workflow again does not report them a second time. Audit: `onboarding.restarted`.

### `PATCH /v1/onboarding/notifications` (viewer; `slack` admin)

`{ "email"?: boolean, "slack"?: boolean }`, at least one (`422` otherwise). `email` is the caller's own switch for the email of the first real action. `slack` turns the workspace's Slack line on or off: below admin `403 forbidden`; `slack: true` answers `402 plan_required` with `details.upgrade_to` when the plan has no Slack alerts, and `409 slack_not_configured` when no Slack integration is active. Answers the state. Audit: `onboarding.notifications_changed` when a value changed.

Since 0.9.60 (RB-45) the body also takes `"unknown"?: boolean` (admin; `403` below): whether a real action
that settles UNKNOWN is announced. Off unless an admin turns it on. The state's `notifications.unknown` reads it.

### `GET /v1/notifications` (a signed-in person; their own notices)

`{ items: [{ id, kind, title, body, href, read, read_at, created_at, emailed, data }], unread }`. Verdict notices
(0.9.60, RB-45), by `kind`:

- `first_real_verdict`: once per workspace and workflow, for the real action whose verdict **settled first**, by the
  settlement events themselves (`action_snapshots` in order of `generated_at`, then `seq`). Not the first action
  recorded, the last one processed or the first that failed. The milestone is one unique row
  (`verdict_milestones`), so two workers that settle at the same moment cannot both announce it.
- `verdict_failed`: a real action settles FAIL for the first time.
- `verdict_pass_to_fail`, `late_forbidden_effect`, `verdict_reversal`: a settled PASS became FAIL (the second when a
  forbidden or duplicate effect arrived late, the third when the action's effect was reversed); `verdict_reversal`
  also when a settled FAIL became PASS.
- `verdict_unknown`: a real action settles UNKNOWN, only where the workspace turned `unknown` on.

`data { notification_type, action_id, workflow, verdict_version, new_state, previous_state, reason { code, text },
event_time, href }`: the action (CommitLayer's id), the workflow, the new and the previous canonical state, the
reason, when the verdict version was evaluated, and the link to the action. Each is written once per workspace,
action, verdict version, type and person, and its email once. Nothing is written for a sample, an idempotent
replay, a checkpoint or a re-check that changes nothing, a repeated read of an unchanged FAIL, or evidence that is
not the action's. A notice carries nothing of the customer (no subject, amount or parameter).

### `POST /v1/onboarding/notify-admin` (viewer)

Emails the workspace's first owner that the caller is waiting on a step their role cannot do. One email per member per day. `409 nothing_to_ask` when no step is waiting on another role.

## Agent sandbox

### `GET /v1/sandbox/scenarios`

Role: viewer.

**Response**

```ts
{
  items: [{ id, workflow, workflow_display, failure, description, recheck }],
  workflows,            // { key: display name }, one entry per workflow the sandbox offers
  systems               // names of the fake systems of record the scenarios run against
}
```

`workflows` and `systems` are the source for any page that states how many of each the sandbox has.

The 112 scripted scenarios from `docs/sandbox.md`.

### `POST /v1/sandbox/runs`

**Request body**

`{ scenario_id }`

**Response**

```ts
201 {
  run_id,
  scenario,
  agent: {
    agent_id,
    claimed_success,
    steps,
    notes,
    calls: [{ method, path, chaos }]
  },
  systems: { facts_ingested, unreachable },
  truth: { outcome, strict, policy, reasons },   // policy: deprecated alias of strict
  observed: { outcome, strict, policy },         // CommitLayer's answer in the truth's terms; `agrees` compares the two
  verification: ActionVerification,
  agrees,
  corrected_by_recheck,
  orphans,
  verify_ms
}
```

Analyst

`strict` is the scenario's strict result, **effects and policy together** (PASS only when every expected effect happened and no precondition, limit, prohibition or reversal failed). `policy` on this surface is a deprecated alias that always equals `strict`; it is **not** an action's `policy_verdict`, which judges the policy checks alone (a missing refund is `strict: FAIL` and `policy_verdict: PASS`). The published oracle values are unchanged. `verification` is an ordinary action view: read its `outcome_verdict`, `policy_verdict` and `overall_verdict` as on any action. The failure lab (`GET /v1/admin/benchmark/{run_id}`, platform admins) follows the same rule: each scenario row carries `truth_strict` beside `truth`, `commitlayer.strict` beside `commitlayer.policy` and `strict_match` beside `policy_match`, each pair always equal.

Runs one scenario inside the caller's workspace with the scripted agent: a fresh fake enterprise, the injected failure, facts extracted through it, the action recorded (`channel: sandbox`, subject ids prefixed with the run id so runs never share records) and verified. The eight sandbox contracts are copied into the workspace as unselected versions on first use. The agent id is `sandbox-agent:<run_id>`, so a per-agent aggregate sees only that run's actions. Sandbox runs are never metered. Audit: `sandbox.run`.

## Settings

Workspace settings. Reading needs `admin` unless stated; changing needs `admin`, and `owner` where stated.

### `GET /v1/settings/tenant`

**Response** the workspace: name, slug, plan, `retention_months`, `ip_allowlist`, the flags the plan sets, and `trust_policy: { separate_attestor_required: boolean }`.

### `PATCH /v1/settings/tenant`

**Request body** `{ name?, retention_months?, ip_allowlist?: string[], separate_attestor_required?: boolean }`. Send only the fields that change. `retention_months` other than 13 and `ip_allowlist` need Enterprise (`402`). `separate_attestor_required` is changed by an Owner only (`403 owner_required` for an Admin; audit `trust_policy.changed`): when true, the person who created an evidence key cannot attest it (`403 separate_attestor_required` from `POST /v1/evidence/attestations` and `POST /v1/onboarding/evidence-trust`).

### `GET /v1/settings/roles`

Role: viewer. The role vocabulary, the caller's authority and the seats, for every surface that names or offers a role.

```ts
{ roles: [{ role, label, description, takes_seat: boolean, assignable: boolean, capabilities: { [name]: boolean } }],
  aliases: [{ alias: "editor", label: "Editor", role: "analyst", role_label: "Analyst" }],
  assignable: string[],            // the roles the caller may invite or assign; never one above their own
  your_role, capabilities, requires: { [capability]: role },
  seats: { limit: number|null, active, pending, available: number|null, seat_roles, note },
  ownership_policy: string[] }
```

### `GET /v1/settings/members`

**Response**

```ts
{ items: [{ id, user_id, email, name, role, role_label, takes_seat, status, mfa_enabled, last_login_at, created_at,
            invitation: null | { kind: "member"|"handoff", status: "pending"|"expired", invited_at, expires_at, path, resendable },
            can_change_role: boolean, can_remove: boolean, assignable_roles: string[] }] }
```

`can_change_role`, `can_remove` and `assignable_roles` are what the caller may do to that member, by the rules below: an Admin gets `false` and `[]` on an Owner's row.

### `POST /v1/settings/members/invite`

**Request body** `{ email, role }`, `role` one of `owner`, `admin`, `analyst`, `viewer`. Creates a pending membership and its invitation, and emails the invitation's own link (`/invite/<token>`: the page says who invited, the workspace, the role and what it is for). Signing in with the invited address is the acceptance (audit `member.accepted`); only that address can accept, at the invited role. The invitation expires after fourteen days. `403 role_above_own` for a role above the caller's (an Admin cannot invite an Owner). `402` when the role takes a seat and none is free: nothing is created, and `details.seats` says where the workspace stands. `409 already_member`.

### `POST /v1/settings/members/{id}/resend`

Sends a pending member's invitation again and renews its fourteen days (once a minute, five in all: `429 resend_too_soon`). `409 already_accepted` once the member joined. An Owner's invitation is resent by an Owner.

### `PATCH /v1/settings/members/{id}`

**Request body** `{ role }`. Nobody assigns a role above their own (`403 role_above_own`: only an owner mints or demotes an owner), and nobody changes or removes their own membership (`403 own_membership`). `400 last_owner` when it would leave no Owner. `402` when the new role takes a seat the plan does not have. A pending member's invitation follows the new role.

### `DELETE /v1/settings/members/{id}`

Removes the membership; for a pending member, revokes the invitation (its link then says so; audit `member.invitation_revoked`). The same two rules as `PATCH` apply.

Every refusal on the member routes is written to the audit log as `security.denied` with `operation`, `reason`, `actor_role`, `target_role` and `requested_role` (security/roles.md).

### API keys

One credential, one side of the line: a `recorder` key records actions and cannot push facts; an `evidence` key pushes facts for the sources it is bound to and cannot record actions; a `reader` key reads; a `full` key does everything and is for a backend you control end to end. The key that records an action can never also supply the facts that verify it, by a push or by a file, and neither a `recorder` nor an `evidence` key can save or select a contract, install, upgrade or roll back a workflow pack, or replace its recorder mapping: those take a person signed in or a key with every scope. Over REST a `recorder` or `evidence` key otherwise reads what an analyst reads.

Key management is a signed-in Owner's or Admin's: an API key, whatever it holds, gets `403 session_required` on
every route below and never mints, splits, replaces or revokes a key (RB-49, RD-43).

### `GET /v1/settings/api-keys`

**Response**

```ts
{
  items: [{ id, name, prefix, display_id,            // display_id = "<name> · <prefix>", the same wherever a key is chosen
            status: "active"|"revoked", created_by, created_at, last_used_at, revoked_at, revoked_by, revoke_reason,
            scopes: string[], fact_sources: string[] | null, environment: "production"|"test"|null,
            side: "recorder"|"evidence"|"full"|null, legacy: boolean,   // legacy: a key that holds both sides
            migration: Migration | null, split_from: string | null, request_id: string | null }],
  scopes: [{ scope, description }],
  presets: { full, recorder, evidence, reader, approver },   // the one preset table onboarding and the split use too
  preset_descriptions, environments: ["production", "test"]
}
Migration = { state: "replacements_created"|"in_migration"|"replacements_revoked"|"retired", replacement_ids,
  replacements: [{ id, display_id, side, status, used }], created_at, first_replacement_used_at, retired_at,
  banner: boolean }   // banner: true until the legacy key itself is revoked
```

Every time is RFC 3339 UTC with `Z` (RS-9(c)). The presets (RD-19): `recorder` = `actions:record, actions:read`;
`evidence` = `facts:write, actions:read, connectors:read`; `approver` = `commitments:write, actions:read`; `reader`;
`full`. The guided setup's two keys are these presets.

### `POST /v1/settings/api-keys`

**Request body** `{ name, preset?: "full" | "recorder" | "evidence" | "reader" | "approver", scopes?: string[], fact_sources?: string[], evidence_class?: "customer_backend" | "provider_webhook" | "blockchain_confirmation", environment?: "production" | "test" }`. Every scope when neither `preset` nor `scopes` is given. `evidence_class` says what kind of party pushes through an evidence key and becomes the `trust_class` of the facts it pushes; it belongs only on a key that pushes facts and does not record actions. `environment` binds the key (RS-11).

Send `Idempotency-Key: <request id>` (the site always does). It is the creation's durable identity, stored on the key (RD-22, RD-23). A retry with the same identity and body whose first answer was lost revokes that never-used key and makes its replacement in one transaction (`replaces`); one creation, one live key. When the first key was already used, or the body differs, `409 idempotency_key_reused`.

**Response** the key view plus `key` (shown once, never again) and `replaces`.

`400 invalid_request` for an unknown preset or environment, an empty scope list, a key with `facts:write` that does not name its `fact_sources` unless it holds every scope, or an `evidence_class` on a key that records actions or pushes nothing. `409 key_name_taken` when an active key already has the name (case and spacing ignored; `details.existing_display_id`).

### `GET /v1/settings/api-keys/requests/{request_id}`

What a creation request made, by its `Idempotency-Key`: `{ request_id, key: KeyView | null, secret_available: false, recovery: { revoke_and_replace, explanation } | null }`. The way back after a lost answer: the metadata, never the secret.

### `POST /v1/settings/api-keys/{id}/replace`

`{ reason, confirm: true }` → revokes the key and creates its twin (same name, scopes, sources, class and environment) in one transaction; answers the new key view with `key` and `replaces`. Attestations do not move: the twin is attested anew by an Owner or Admin who did not create it. `409 key_revoked`.

### `POST /v1/settings/api-keys/{id}/split/preview` and `POST /v1/settings/api-keys/{id}/split`

The legacy dual-purpose key's split (RD-45, RD-46). The preview writes nothing and answers `{ legacy_key, recorder: { name, scopes, environment }, evidence: { name, scopes, fact_sources, evidence_class, environment } | null, sources, effects: string[], written: false }`. The split takes `{ confirm: true }` (`400 confirmation_required` otherwise; `Idempotency-Key` honoured) and answers `{ legacy_key, recorder: KeyView & { key }, evidence: KeyView & { key } | null, migration }`: both replacements created together, their secrets in this answer only. The original stays active, `legacy: true`, with its `migration`: `replacements_created`, then `in_migration` once a replacement is used, `retired` only when the legacy key itself is revoked. `409 already_split`, `409 not_a_legacy_key`, `409 key_revoked`. Audit: `api_key.split` and one `api_key.created` per replacement.

### `POST /v1/settings/api-keys/{id}/revoke` and `DELETE /v1/settings/api-keys/{id}?reason=`

Revokes the key at once, with a reason (`{ reason, confirm: true }`). Revoking a split legacy key retires its migration.

### Webhooks

Customer webhooks receive the events listed by `GET /v1/settings/webhooks` (`action.verified`, `action.pending`, `action.compensated`, `contract.weakened`, since 0.10.0 `commitment.incomplete`, `commitment.corrected` and `commitment.exception_accepted` (see [Commitments](#commitments)), and `test`). Every delivery carries the envelope `{ id, event, created_at, data }` and the headers `X-Event: <event>`, `X-Event-Id: <id>`, `X-Timestamp: <ts>` and `X-Signature: t=<ts>,v1=<hex HMAC-SHA256 of "<ts>.<body>" under the webhook secret>`. Nothing else is sent beyond
the HTTP client's own `Host`, `Accept`, `Accept-Encoding`, `Connection`, `User-Agent`, `Content-Length` and
`Content-Type`: no tracing or baggage headers (`sentry-trace`, `baggage`, `traceparent`), from a test delivery or a
real one (RS-5).

**Verifying a delivery.** Compute HMAC-SHA256 with the webhook secret over the bytes `<t>.` followed by the exact
request body as received (do not re-serialise it), and compare it in constant time with each `v1=` value; accept when
one matches. Refuse a `t` more than five minutes from your clock. **Event identity:** `id` (and `X-Event-Id`) is the
delivery's identity and is the same on every retry of it; keep the ids you processed and answer `2xx` to a repeat
without acting again (idempotent receipt). **Retries:** a failed delivery (no answer, or a status other than `2xx`) is
retried by the `deliver_webhook` job with backoff; `401` and `403` are not retried; twenty consecutive failures disable
the webhook (below). Each retry is signed afresh (new `t`, same `id`). **Rotation:** `rotate-secret` returns a new
secret; for the next 24 hours every delivery carries two signatures, `v1=<new>,v1=<old>`, so the receiver can switch
without dropping deliveries (`previous_secret_expires_at` on the webhook); after that only the new secret signs.

**Instants (0.9.58).** `created_at` and the signature's `<ts>` are the same ISO-8601 UTC instant with its zone
(`2026-09-28T10:57:02Z`); until 0.9.57 both were `2026-09-28 10:57:02` with no zone. Verify the signature over the
header's `<ts>` exactly as received; a receiver that parses either value must accept the ISO form. Every instant in
`data`, and in the payloads sent to chat and incident integrations, is ISO-8601 UTC as well. A sentence in an email
states an instant in the timezone its recipient saved (`PATCH /v1/auth/me/preferences`), with the zone's
abbreviation ("18 Nov 2026, 21:28 PST"), or in UTC, labelled "UTC", when none is saved.

### `GET /v1/settings/webhooks`

**Response**

```ts
{
  items: [{ id, url, events, status: "active" | "disabled", failure_count, last_error, last_response_code, last_attempt_at, last_delivered_at, disabled_at, created_at }],
  events: string[]
}
```

Use `events` as the selectable list; an unknown event name is rejected with `400`. `last_error` says what the receiver last did, in words that name the fix.

### `POST /v1/settings/webhooks`

**Request body** `{ url, events: string[] }`. At least one event, chosen by the admin: `400 events_required` for an
empty list (RS-7; the site ticks none in advance).

**Response** the webhook plus `secret`, shown once.

The URL must be https, carry no credentials, and name a public host that resolves only to publicly routable addresses: `localhost`, private and link-local addresses and `.internal`-style names answer `400 bad_url`. The same check runs at every delivery. Repeated slashes in the path are collapsed.

### `POST /v1/settings/webhooks/{id}/test`

**Response** `{ delivery: { id, status, response_code, last_error }, webhook }`. Delivers a `test` event now and reports the receiver's answer; a success re-enables a disabled webhook.

### `POST /v1/settings/webhooks/{id}/rotate-secret`

**Response** the webhook plus a new `secret`, shown once, and `previous_secret_expires_at`. The old secret keeps signing beside the new one for 24 hours, then stops; rotating again during the overlap ends the earlier secret at once. The failure count is reset.

### `POST /v1/settings/webhooks/{id}/enable`

**Response** the webhook, active, with failures forgiven.

### `GET /v1/settings/webhooks/{id}/deliveries`

**Response** `{ items: [{ id, event, status, response_code, attempts, last_error, created_at }] }`.

### `DELETE /v1/settings/webhooks/{id}`

Removes the webhook.

Twenty consecutive failures disable a webhook (audit `webhook.disabled`); while disabled, one delivery an hour is still tried and any success re-enables it (audit `webhook.recovered`). A receiver answering `401` or `403` fails that delivery once, without retries: the secret on its side does not match.

### Billing

### `GET /v1/settings/billing`

**Response**

```ts
{
  plan, status, stripe_customer: boolean, subscription: boolean,
  trial_ends_at, trial_used, trial_days, current_period_end,
  upgrade_options: Tier[],
  founding: { plan, price_monthly, months, seats, remaining, available, reason },
  stripe_configured: boolean,
  usage: { period: { label, start, end }, real_actions_used, real_actions_by_environment: { production, test },
           included_actions, samples_excluded, seats: { active, pending_invitations, limit, note } },
  // CL-0100 (RB-55):
  payment_method_on_file: boolean | null,
  payment_method: { on_file, state: "on_file"|"none"|"unknown", kind: "card"|...|null,
                    learnt_from: "no_customer"|"subscription"|"customer"|"payment_method"|"checkout"|"invoice"|"stripe_read"|null,
                    checked_at },
  trial: { active, expired, started_at, ends_at, days_total, days_left, card_required: false,
           payment_method_on_file, at_end: "first_charge"|"read_only_without_card", at_end_sentence },
  limits: { connections, outcomes_per_month, contracts, seats, ... },
  continuation: { plan, name, price_monthly, currency, interval, first_charge_on, needs_payment_method, sentence },
  workflow_packs: [{ id, name, entitled, workflows, required_plan, required_plan_name,
                     via: "trial"|"paid"|...|null, reason: null|"plan_does_not_include"|"trial_ended" }],
  navigation: { workflow_packs: { visible: true, href: "/app/packs", label, entitled: string[] } }
}
```

`usage.real_actions_used` counts the billable unit (a new action or a new commitment revision; docs "Metering") in the
period; `real_actions_by_environment` splits it into live and `test` (both metered); samples are never metered and are
counted apart in `samples_excluded`. Re-sending, polling, re-checks, corrections and reassessments are never counted.

`upgrade_options` is the public pricing tier list. `founding` is the same offer the public pricing endpoint carries, so the in-app upgrade cards show the price Checkout will charge.

`payment_method_on_file` is the billing provider's own state, never inferred from a customer existing: a no-card
trial has none. It is kept from the provider's events (`customer.subscription.created|updated` `default_payment_method`,
`customer.updated` `invoice_settings.default_payment_method`, `payment_method.attached|detached`,
`setup_intent.succeeded`, `checkout.session.completed` `payment_status`, `invoice.paid` with money on it); where
none was received for a workspace with a customer the read asks the provider once and keeps the answer; when it
cannot be learnt it is `null` (`state: "unknown"`). Only whether a method exists and its kind are kept. `trial`
reads the subscription's own trial start and end; `continuation` the plan's price and when it starts; an ended or
canceled trial includes no pack (`reason: "trial_ended"`) while `navigation.workflow_packs.visible` stays true, so
the place stays in every member's navigation through a checkout return, a trial start, its end and a paid plan.
`GET /v1/auth/me` carries the same `navigation` for every member.

### `GET /v1/settings/billing/preview?tier=`

**Response** `{ tier, name, price_monthly, current_plan, mode: "trial" | "paid" | "switch", trial_days, trial_ends_at, first_charge_on, trial_used }`.

`trial`: Checkout with the remaining trial days, first charge when it ends. `paid`: Checkout, charged today. `switch`: the existing subscription's price changes in place, prorated.

### `POST /v1/settings/billing/checkout`

**Request body** `{ tier }`.

**Response** `{ url, mode, founding: boolean }`: a Stripe Checkout URL, or for a switch the billing page with `?checkout=switched` and the plan already applied. A trial Checkout collects no card (`payment_method_collection: if_required`); a trial that ends without a card cancels the subscription rather than charging anyone. `founding: true` when the Founding Builder coupon was applied (Builder, while seats remain; Stripe's redemption cap decides, and a coupon Stripe refuses falls back to the list price in the same call).

Configuration problems answer `400 billing_error`; Stripe's refusals answer `502 stripe_error` with Stripe's message. `STRIPE_PRICE_<TIER>` may be a price id or a product id, resolved to its active monthly price.

### `POST /v1/settings/billing/portal`

**Response** `{ url }`: the Stripe billing portal for invoices, the card on file, downgrades and cancellation.

### Slack

### `GET /v1/settings/slack`, `POST /v1/settings/slack`, `DELETE /v1/settings/slack`

`POST` takes `{ webhook_url, events }`. Verdict events are posted to Slack when the integration's `events` list includes them or is empty.

### Incident, review and tracing channels (Growth and above)

### `GET /v1/settings/integrations`

**Response** `{ items: IntegrationItem[], available_events }`, one item per kind (`pagerduty`, `jira`, `github_checks`, `langfuse`, `langsmith`, `braintrust`):

```ts
IntegrationItem = {
  kind, display, description, secret_label,
  fields: [{ name, label, placeholder?, required }],
  default_events, configured, status: "active" | "disabled" | null,
  events, config, failure_count, last_error, last_delivery_at, open_items
}
```

### `POST /v1/settings/integrations/{kind}`

**Request body** `{ config?, secret?, events? }`. The secret is required the first time and never returned; saving re-enables a disabled integration.

### `POST /v1/settings/integrations/{kind}/test`

**Response** `{ ok, message }`; `502 integration_test_failed` with the provider's answer.

### `DELETE /v1/settings/integrations/{kind}`

Removes the integration.

Deliveries run through the `deliver_integration` job. The three tracing sinks write each settled verdict onto the trace the action names in its `trace_id` parameter (or the parameter configured): Langfuse as two scores on the trace (`commitlayer.outcome`, `commitlayer.policy`; 1 for PASS, 0 for FAIL, the word for UNKNOWN), LangSmith as feedback on the run (`commitlayer_outcome`, `commitlayer_policy`), Braintrust as scores merged onto the span row; an action without a trace id is skipped, a pending verdict never scored. PagerDuty opens an incident on FAIL (UNKNOWN as a warning) and resolves the same incident on PASS or `action.compensated`. Jira opens one issue per failing action, labelled `commitlayer` and `commitlayer-action-<id>`, and comments on later verdicts. GitHub Checks posts a check run on the commit named by the action's `commit_sha` parameter (`repo` parameter or the configured default repository): in progress while pending, `failure`, `success` or `neutral` once settled, updated in place on re-verification. Twenty consecutive failures disable an integration until it is saved again. Audit: `integration.configured`, `integration.tested`, `integration.removed`.

### Single sign-on (Enterprise)

### `GET /v1/settings/sso`

**Response** `{ enabled, connections: [{ id, workos_connection_id, domain, status }], login_url }`. `login_url` sends a browser straight to the workspace's identity provider.

### `POST /v1/settings/sso`

Role: owner. **Request body** `{ workos_connection_id, domain? }`. `403 sso_disabled` until CommitLayer has enabled SSO for the workspace (Enterprise provisioning).

### Audit log

### `GET /v1/settings/audit-log?limit=&cursor=&action=`

**Response** `{ items: [{ id, ts, actor, action, object_type, object_id, ip, metadata }], next_cursor }`.

### `GET /v1/settings/audit-log/export.csv`

The same rows as a file.

### Transcript assist

### `GET /v1/settings/transcript-assist`, `PATCH /v1/settings/transcript-assist`

**Response** `{ enabled, monthly_cost_cap, spend_this_month, sample_rate, message_window, provider_configured, entitled, available, waiting_for }`; `PATCH` takes the same fields.

`available` is false until the workspace's first invoice with money on it has cleared (`waiting_for: "first_invoice"`); until then `enabled: true` answers `402 payment_required` and nothing is labeled. The default cap is $5 a month.

### Data and jobs

### `POST /v1/settings/data-deletion`

Owner, signed in. **Request body** `{ confirm: "DELETE" }`. **Response** `{ request_id, receipt_at, state:
"requested", status_path: "/v1/account/data-deletion-requests/<request_id>", message }`.

What happens, in order (CL-0100 L7, RS-6; `app/core/deletion.py`):

1. **At once:** the request is recorded (receipt id `ddr_…`) and the workspace is closed. Every API key and every
   session of the workspace is refused from this moment (`403 tenant_unavailable`); a sign-in never opens it again.
   Audit `tenant.deletion_requested`.
2. **Within minutes:** the `tenant_deletion` job removes every row and stored object of the workspace (state
   `deleting`, audit `tenant.deletion_started`), then records the receipt (rows deleted per table, objects deleted;
   state `completed`, audit `tenant.deleted`) and emails it to the person who asked. Nothing waits for a contractual
   period; backups taken before the deletion still hold the data until they age out (35 days).
3. **Kept:** the request and its receipt, and the workspace's audit log, which ends with the deletion's own entries.
   The person who asked reads the request, its state, its receipt and the deletion's audit entries (below). The rest
   of the kept audit log is shown to nobody in the product.
4. **Afterwards:** the person's other workspaces are untouched. Signing in again opens one of them; with none, a new,
   empty workspace is created, and the session says why (`data_deletions` on `GET /v1/auth/me`).

### `GET /v1/account/data-deletion-requests`, `GET /v1/account/data-deletion-requests/{id}`

Any valid session of the person who asked, including the session of the workspace being deleted (every other route
refuses it). An API key gets `403 session_required`; another person's request answers `404`.

**Response** (one request; the list is `{ items: [...] }`, newest first):

```ts
{ id, workspace_id, workspace_name, state: "requested" | "deleting" | "completed", state_label,
  requested_at, started_at, completed_at, requested_by,                       // UTC "…Z"
  receipt: { request_id, tenant_id, completed_at, rows_deleted: { [table]: n }, objects_deleted } | null,
  audit: [{ id, action: "tenant.deletion_requested" | "tenant.deletion_started" | "tenant.deleted", at, actor }],
  kept, next }                                                                // sentences: what is kept, what next
```

`GET /v1/auth/me` (and every session answer) adds `data_deletions: [{ id, workspace_id, workspace_name, state,
state_label, requested_at, started_at, completed_at, requested_by }]`: the person's five newest requests.

### `GET /v1/jobs?status=`

**Response** `{ items: [{ id, type, status, attempts, run_at, last_error, created_at }] }`.

## MCP and OAuth

### `POST /mcp`

The MCP server (streamable HTTP, JSON responses). Bearer: an API key, an OAuth access token or a session JWT. Tools, resources, prompts, scopes and error shapes are in [the MCP reference](/docs/mcp). Every call is audited as `mcp.tool_called`.

### Authorization server

Served by the MCP SDK at the API root: `GET /.well-known/oauth-authorization-server`, `GET /.well-known/oauth-protected-resource/mcp`, `POST /register` (dynamic client registration), `GET /authorize` (PKCE S256; redirects to `${WEB_URL}/oauth/consent?req=`), `POST /token`, `POST /revoke`.

### `GET /v1/oauth/consent?req=`

Session bearer; any member but a counterparty.

**Response** `{ client: { id, name, uri, redirect_uri }, workspace: { id, name, role }, scopes: [{ scope, description, grantable }], expires_at }`. `400 invalid_consent_request` when the request is invalid or older than 10 minutes.

### `POST /v1/oauth/consent`

**Request body** `{ req, approve: boolean, scopes?: string[] }`.

**Response** `{ redirect_to }`: the client's redirect URI carrying `code` and `state`, or `error=access_denied`. Audit `oauth.approved`, `oauth.denied`.

## Counterparty

For users with the `counterparty` role: a vendor's people, who see only what was shared with them. Every view is audit-logged and every page is watermarked with `{ viewer_email, viewed_at }`.

### `GET /v1/counterparty/grants`

**Response**

```ts
{
  items: [{ id, tenant_name, expires_at, statements: [{ id, vendor, period, statement_hash }], disputes: [{ id, vendor, period, status, contested_amount }] }],
  watermark: { viewer_email, viewed_at }
}
```

### `GET /v1/counterparty/statements/{id}`

**Response** `Statement`, with the watermark.

### `GET /v1/counterparty/disputes/{id}`

**Response** the dispute view.

### `GET /v1/counterparty/statements/{id}/export.{pdf|csv|json}`, `GET /v1/counterparty/disputes/{id}/export.{pdf|csv|json}`

The same exports as the owning workspace sees.

## Admin

Platform administrators only (the addresses in `PLATFORM_ADMIN_EMAILS`).

### `GET /v1/admin/tenants`, `POST /v1/admin/tenants`, `PATCH /v1/admin/tenants/{id}`

`POST` takes `{ name, plan, owner_email, trial_days? }`. `PATCH` takes `{ plan?, limits?, features?, trial_ends_at?, sso_enabled?, counterparty_enabled?, name? }`.

### `POST /v1/admin/impersonate`

**Request body** `{ tenant_id, reason }`. **Response** a `Session` with a fresh token, audit-logged with the reason. `POST /v1/admin/stop-impersonation` returns a `Session` for the admin's home tenant.

### `GET /v1/admin/metrics`

Also accepts `Authorization: Bearer <METRICS_READ_TOKEN>` when that variable is set, for an external monitor; the token works on no other route.

**Response**

```ts
{
  collected_at,
  database: { bytes, wal_bytes } | null,
  queue: { [status]: n },
  dead_jobs: { engine_24h, delivery_24h, by_type: { [job_type]: n }, all_time },
  migrations: { pending: string[] },
  sync_lag_seconds: { max, avg, connections, excluded },
  stalest_connections: [{ tenant_id, tenant, connection_id, source, display_name, status, age_seconds }],
  runs_7d, error_rate_7d, pdf_missing, webhook_failures_24h,
  transcript_assist_spend_month, connections_in_error, active_tenants,
  cost: {...}, alerts: string[],
  write_gate: { slots, per_workspace, queue_per_workspace, in_progress, workspace_slots_taken,
                workspaces_writing, workspaces_waiting, refused_busy, refused_workspace_busy }
}
```

`write_gate` describes the API process that answered, not the fleet: `slots` is `MAX_CONCURRENT_WRITES`, `per_workspace` one workspace's share of them, `queue_per_workspace` how many of one workspace's writes may wait for one of its own slots, and the two `refused_*` counters are since that process started (`503 busy` and `429 workspace_busy`). `in_progress` is the writes admitted to the gate right now, with or without a workspace; it never passes `slots`. The next three count workspace slots, which a request takes before it waits for the gate, and stay at zero where no per-workspace limit applies: `workspace_slots_taken` is the slots taken across all workspaces (it passes `in_progress` while requests wait for the gate), `workspaces_writing` the workspaces with at least one slot taken, and `workspaces_waiting` the workspaces with at least one write waiting for one of its own slots. A `refused_workspace_busy` that keeps rising is one workspace sending more writes at once than its share and its queue hold; when `refused_busy` rises with it, the gate is full of other workspaces' writes and that workspace's share is taken by its own requests waiting for the gate. A rising `refused_busy` on its own is the whole gate being too small for the traffic.

`database.wal_bytes` is the SQLite write-ahead log; above 256 MB an alert names it, because a long-running reader is then holding the nightly checkpoint back and every commit pays for it.

`dead_jobs` splits the dead letters of the last 24 hours the way an incident has to read them: `engine_24h` counts job types that are ours to keep running (`verify_action`, `run_verification`, backups and the like), `delivery_24h` counts syncs, deliveries and notifications that die on someone else's system (`sync_connection`, `deliver_webhook`, `deliver_integration`, `send_alert`, `send_email`, `forward_feedback`), and `by_type` names each type. `queue.dead` and `all_time` stay the blended figure, which only ever grows because dead jobs are kept for inspection. A monitor pages on `engine_24h` and treats `delivery_24h` as an integrations finding; the public status page's "degraded" uses the same engine-only count.

`migrations.pending` names the performance-only migrations (index builds, `ANALYZE`) the last deploy left for the worker instead of running inside startup, so a deploy's health check never waits on an index build. They clear within minutes of a boot; the alert `deferred migrations waiting for the worker` means the worker is not running its queue.

`stalest_connections` are the connections behind `sync_lag_seconds.max`, stalest first, so an alert can name a tenant and a source. Connections with no stored credential, waiting on re-authentication, or without a watermark yet are not counted in the lag (`sync_lag_seconds.excluded` counts them) and are already in `connections_in_error`.

### `GET /v1/admin/connections`

**Response** `{ items: [{ connection_id, tenant_id, tenant, source, display_name, status, watermark, age_seconds, last_sync_at, has_credential, reauth, health_message, excluded }], counted }`: every live connection of a real workspace, stalest first. `excluded` (`no_credential`, `reauth`, `no_watermark`) says why a row is not counted in `sync_lag_seconds`.

### `GET /v1/admin/signup-refusals?status=&limit=`

**Response**

```ts
{
  items: [{ id, created_at, email, ip, country, reason, mode, detail, tenant_id, status, resolved_at, resolved_by }],
  held,
  guard: { country_policy, country_allow_domains, mx_check, reputation_check, reputation_min_confidence, geoip: { present, built_at, configured } }
}
```

`reason` is `disposable | no_mail_server | reputation | region_closed`; `status` is `refused` (nothing was created), `held` (the workspace exists, suspended), `approved` or `rejected`. `POST /v1/admin/signup-refusals/{id}/approve` opens a held workspace (active, owner emailed, audit `signup.approved`); `POST /v1/admin/signup-refusals/{id}/reject` keeps it closed (audit `signup.rejected`). Either on a row that is not held answers `409 not_held`.

The sign-in page can answer these refusal codes (`/login?error=` on the hosted flow, the error code on the development login): `disposable_email` (400), `no_mail_server` (400), `reputation` (403), `region_closed` (403, `details.country`), `account_held` (403, also from every product route while the workspace waits).

### `GET /v1/admin/jobs?status=&limit=&include_archived=false`, `POST /v1/admin/jobs/{id}/retry`

The queue. Dead engine jobs past thirty days carry `archived_at` and are listed only with `include_archived=true`; `retry` re-queues a job and clears `archived_at`.

### `GET /v1/admin/bans`, `DELETE /v1/admin/bans/{ip}`

`GET` → `{ items: [{ ip, reason, detail, created_at, expires_at, hits }] }`, unexpired bans newest first; `reason` is `scanner_path`, `robots_trap` or `form_honeypot`. `DELETE` → `{ ip, lifted }`; every API process honours it within `BAN_CACHE_SECONDS`. Audit `admin.ban_lifted`.

### `GET /v1/admin/leads`

The leads the public form collected.

### `POST /v1/admin/demo/seed`

Seeds the synthetic demo workspace.

## Billing webhooks

### `POST /v1/webhooks/stripe`

Signature-verified (the provider's scheme: HMAC-SHA256 over `"<t>.<exact body>"`, five-minute tolerance). Updates the
workspace's entitlements from subscription, invoice and checkout events, and keeps whether a payment method is on
file from those and from `customer.updated`, `payment_method.attached|detached` and `setup_intent.succeeded` (RB-55).

A refused delivery is `400 bad_signature` with a stable `details.reason` and the product's own remedy text, never a
library's message, a header, a body or a secret (RS-9(d)): `missing_signature`, `malformed_signature`,
`stale_timestamp` (older than five minutes, or ahead), `signature_mismatch`, `verification_unavailable` (no endpoint
secret configured; nothing processed). Diagnostics stay in the server log. **Replay:** an event id already processed
answers `200 { handled: true, duplicate: true, event_id }` and has no second effect (`inbound_webhook_events`); a
first delivery answers `{ handled, duplicate: false, event_id, ... }`. **Rotation:** `STRIPE_WEBHOOK_SECRET` may hold
several secrets separated by commas, newest first; a delivery signed with any of them is accepted.

## Development only

`POST /v1/auth/signup` answers `404` outside development; production accounts are created by the hosted sign-in. `POST /v1/auth/dev-login` exists only when `AUTH_MODE=dev`.
