# The AuditableCall row (/docs/auditable-call-row)



This page covers the audit-ledger row shape. For read-side
observability (OTel spans, lineage, Datadog patterns), see
[Observability](/docs/observability).

The row is one of three concepts in the audit-ledger cluster: the row
(this page), the [ProviderDecisionLedger](/docs/audit-ledger) write
interface, and the [hash chain](/docs/hash-chain) that detects
after-the-fact tampering. See [Audit ledger → the audit-ledger
cluster](/docs/audit-ledger#the-audit-ledger-cluster).

With an `AuditEmitter` registered, every request the runtime sends
through a built-in provider (`AiSdkProvider`, `AnthropicSdkProvider`,
`OpenAINativeProvider`) writes its own append-only row, retries and
sub-agents included. A provider that doesn't declare per-attempt
auditing (a custom `AgentProvider`, or `LangChainProvider` over a model
other than `ChatOpenAI`, `AzureChatOpenAI` or `ChatAnthropic`) keeps one
row per call. The provider SDK's own retries are turned off so none hide
inside it.

The row carries the tenant, turn, provider, model, status and latency as
structural columns, plus optional typed slots in a JSON payload
(`familyLock`, `tokenCost`, `toolSelection`, `synthesisQuality`,
`interruptDecision`, `pluginPayloads`, …). Replay, per-turn cost rollups
and "what did the agent do" queries read from it.

`@pleach/core` ships the typed row shape and the emit seam. The host
binds the principal, the per-turn sequence and the ledger that stores
the row. The default emitter is a no-op, so a deploy that registers no
emitter writes nothing. The quickstart and any production host wire one.

<Callout type="warn" title="Locked contract">
  The row shape is a cross-SKU contract. `@pleach/core` writes it,
  including the optional [call-row chain](#proving-rows-werent-edited)
  columns. `@pleach/gateway` reads `tenantId` for cost rollup,
  `@pleach/observe` joins on `turnId`, and `@pleach/eval` reads the row to
  replay. Changing the column set breaks every consumer, and no plugin
  path or config field alters the structural columns (tenant, turn, stage,
  provider, model, status). Token counts live in `payload.tokenCost`, not
  in columns. Schema changes are upstream contribution only.

  The **extension surface** lives in two places:

  * `principal.tenantId`, opaque to the row and scoped however your
    deployment wants (end customer, employee, team, cost center).
  * `pluginPayloads[]`, the typed, plugin-namespaced slot. Each entry
    carries `pluginId`, `subKind` and an opaque `data` payload the plugin
    owns.

  Everything else is fixed. See [Ownership boundaries →
  `@pleach/core`](/docs/ownership#pleachcore--the-substrate).
</Callout>

`tenantId` carries whichever attribution axis your deployment runs on:
an end-customer id for a SaaS, or an employee, team or cost-center id
when Pleach composes under an Anthropic Workspace or OpenAI Project on
an Enterprise contract. See [Migrating from Anthropic
Enterprise](/docs/migrating-from-anthropic-enterprise) and [Migrating
from OpenAI Enterprise](/docs/migrating-from-openai-enterprise).

Every call the runtime makes (synthesize, reasoning, converse, utility,
retries, fallbacks) writes one such row. Since v27, an emitter that
implements the optional `AuditEmitter.recordModelCall` also writes a
per-call row, carrying the `modelCall` slot, for every provider
dispatch, beside the decision rows that record why a model was picked.
See [Model resolution matrix → per-call
rows](/docs/model-resolution-matrix#per-call-rows).

**Subpath:** `@pleach/core/audit`

## Row shape [#row-shape]

The row spreads the identity columns inline (via
`extends AuditableCallIdentity`) and groups the rest into four required
nested sub-shapes (`principal`, `call`, `decision`, `outcome`) plus
optional typed payload slots. The structure is locked at
`AuditRecordVersion`. Bumps are recorded in
`AUDIT_RECORD_VERSION_HISTORY`.

### Identity [#identity]

<TypeTable
  type="{
  auditRecordVersion: { type: 'literal', description: 'Current wire-format version (50).' },
  recordId:           { type: 'ULID', description: 'Crockford-Base32, 26 chars, monotonic within ms.' },
  sessionId:          { type: 'string', description: 'Joins to the session record.' },
  turnId:             { type: 'string', description: 'Stable across retries within a turn.' },
  stageId:            { type: 'enum', description: 'One of anchor-plan / tool-loop / synthesize / post-turn. For a model call, the stage of the graph node that made it; outside a node, the stage the caller names, else the stage its call class maps to. Rows about one attempt, including provider-cascade rows, name the same stage.' },
  seqWithinTurn:      { type: 'number', description: 'Monotonic per turn, starts at 0.' },
  createdAt:          { type: 'ISO-8601', description: 'UTC timestamp.' },
  parentTurnId:       { type: 'string?', description: 'Sub-agent rows only: the spawning turn\'s key. On a sub-agent row `turnId` is the sub-agent\'s own sub-turn key. Omitted on root rows (additive V20→V21).' },
  subagentId:         { type: 'string?', description: 'Sub-agent rows only: the sub-agent\'s stable id (additive V20→V21).' },
  subagentDepth:      { type: 'number?', description: 'Sub-agent rows only: delegation depth, 1 or more (additive V20→V21).' },
  toolName:           { type: 'string?', description: 'The tool whose execution caused this call. On a sub-agent row, the tool that spawned the sub-agent. Omitted, never defaulted, when no tool did (additive V30→V31).' },
  parentRecordId:     { type: 'string?', description: 'Per-call (`modelCall`) rows only: the `recordId` of the decision row the same dispatch recorded earlier in the same turn. Omitted when there was none, never a guessed sibling (additive V26→V27).' },
  costOmitted:        { type: &#x22;'owned-per-call' | 'usage-unreported'?&#x22;, description: 'Only on a decision row with neither `modelCall` nor `tokenCost`, whose usage never arrived. `owned-per-call`: the dispatch\'s own per-call row owns the call and its unknown cost, so a cost-unknown count counts that row and skips this one (additive V26→V27). `usage-unreported`: this row is the call\'s only row (a quickstart sub-agent\'s inner call) and its stream reported no usage, only one of the input/output counts, or zero input and zero output tokens. The call is billed and its cost is unknown, never `$0`; a cost-unknown count counts this row (additive V27→V28).' },
}"
/>

### Principal [#principal]

`AuditableCallPrincipal` is replicated onto every row so SOC2
user-action queries don't need a session join.

<TypeTable
  type="{
  userId:            { type: 'string | null', description: 'Null for anonymous / guest.' },
  actorKind:         { type: 'enum', description: 'user / guest / scheduled / system.' },
  sessionAuthMethod: { type: 'enum', description: 'clerk / api-key / guest-token / internal.' },
}"
/>

### Call shape [#call-shape]

`AuditableCallShape` is post-routing: what actually ran, not what was
requested.

<TypeTable
  type="{
  callClass: { type: 'CallClass', description: 'Locked at session start.' },
  provider:  { type: 'ProviderFamily', description: 'The resolved provider family, populated with the real value the resolver picked.' },
  model:     { type: 'string', description: 'The resolved model id — a concrete model name, not a role/decision label. Falls back to the sentinel string &#x22;unresolved&#x22; when no model resolved (suppressed / empty / error terminal).' },
  transport: { type: 'enum', description: 'native / openrouter / byok-native / byok-openrouter.' },
}"
/>

### Decision [#decision]

`AuditableCallDecision` names the *policy* that picked the rung.

<TypeTable
  type="{
  requestedModel: { type: 'string | null', description: 'What the caller asked for.' },
  selectedReason: { type: 'enum', description: 'family-lock / fallback-rung / matrix-pick / user-explicit.' },
  rungOrdinal:    { type: 'number?', description: '0-based index of this rung in the model cascade; 0 = first-pick. Omitted when the emitter cannot measure it (optional since V25).' },
  fallbackChain:  { type: 'readonly string[]?', description: 'Prefix of models attempted before this one. Omitted when the emitter cannot see the chain; read an absent key as &#x22;not measured&#x22;, never as `[]` (optional since V24).' },
  lockedFamily:   { type: 'ProviderFamily?', description: 'The session\'s locked provider family at dispatch, recorded beside the family the call resolved to (`call.provider`). A disagreement between the two is the family-strict-cascade signal. Omitted when the lock was not observable, never defaulted (additive V21→V22).' },
}"
/>

### Outcome [#outcome]

`AuditableCallOutcome` carries the provider's coarse result.

<TypeTable
  type="{
  status:       { type: 'AuditableCallStatus', description: 'ok / degraded / provider-error / provider-exhausted / guard-rejected / timeout / user-aborted / unread / post-settle. `provider-exhausted` (V23) marks a family exhaustion; bucket it with `provider-error` when you group by failure class. `degraded` (V32) is a delivery verdict: something was served and billed, but it was a fallback, a notice or a repair, not the clean answer. It is counted as served, never as an error, and the optional `degradedReason` names why. `unread` and `post-settle` (V32) appear only on a per-call fallback-attempt row and are not provider failures (see [Fallback attempts](#fallback-attempts)).' },
  latencyMs:    { type: 'number', description: 'Provider-side latency.' },
  finishReason: { type: 'string | null', description: 'Unmodified provider string (e.g. &#x22;stop&#x22;, &#x22;tool_use&#x22;, &#x22;length&#x22;).' },
  httpStatus:   { type: 'number | null', description: 'Provider HTTP status when applicable.' },
  why:          { type: 'ProviderDegradationWhy | null', description: 'Provider-degradation diagnostics (&#x22;the WHY&#x22;) for a non-clean / empty outcome — raw native finish reason, serving provider, gateway attempt, optional post-hoc stats. Null/absent on a clean success (additive V18→V19).' },
}"
/>

## Postgres columns [#postgres-columns]

`PostgresProviderDecisionLedger` (`@pleach/core/audit`) writes one row
per call to the call-ledger table, whose schema ships with the package.
The wrapper columns map 1:1 off the row shape above, and everything else
rides in a JSON payload.

| Stored as                                                  | From                                                                                             |
| ---------------------------------------------------------- | ------------------------------------------------------------------------------------------------ |
| Record id (primary key)                                    | `recordId` (ULID)                                                                                |
| Audit record version                                       | `auditRecordVersion`                                                                             |
| Session id (UUID; deleting a session with rows is refused) | `sessionId`                                                                                      |
| Turn id, stage id, sequence within turn, creation time     | identity                                                                                         |
| Tenant, user, actor kind, session auth method              | `principal`                                                                                      |
| Call class, provider, model, transport                     | `call`                                                                                           |
| Status, latency, finish reason, HTTP status                | `outcome`                                                                                        |
| JSON payload                                               | `decision`, `outcome.why`, typed slots, lineage mirror                                           |
| Parent turn id                                             | `parentTurnId`; null on a root row                                                               |
| Root turn id                                               | Derived: own turn id on a root row, else the spawning user turn                                  |
| Sub-agent depth                                            | `subagentDepth`; 0 on a root row                                                                 |
| Tool name                                                  | `toolName`; null when no tool caused the call                                                    |
| Chain sequence, previous row's hash, row hash              | Call-row chain; stamped by default, null with `hashChain: false` or on an unchained fallback row |

### Lineage columns [#lineage-columns]

The four lineage columns let one SQL query see a whole sub-agent tree.
The root turn id is the depth-0 turn every row in the tree rolls up to,
so grouping by it covers any delegation depth.

To get one row per user turn, sub-agent calls included, group the
tenant's per-call rows by root turn id. For each group, count the calls,
take the deepest sub-agent depth, sum the known `costUsd`, and count the
calls whose cost was omitted. Per-call rows exist only when the emitter
implements `AuditEmitter.recordModelCall`. A missing `costUsd` is an
unknown cost, never `$0`, so count it apart.

On core's producers, the parent turn id holds the spawning **user**
turn's key (`turn:<userMsgId>`) at every depth, the same id family as a
root row's turn id. Matching the two joins a sub-agent row to its user
turn. It is not the event log's turn id, which is the bare runtime turn
id.

Two edges:

* A root emit site that can't derive the user turn records
  `turn:<assistantMessageId>`. Its rows don't join.
* Rows written before the columns existed have a null root turn id.
  Across mixed history, group by the first non-null of root turn id,
  parent turn id and turn id.

**Upgrading.** Re-applying the base tier adds the columns idempotently,
with sub-agent depth backfilled to 0. Until you re-apply, the ledger
still writes every row on the original 20-column insert, reports
`AUDIT_LEDGER_COLUMNS_DOWNGRADED` once through `onError`, and keeps the
lineage values in `payload`. Pass `lineageColumns: false` to use the
original column list from the start.

<a id="proving-rows-werent-edited-opt-in" />

## Proving rows weren't edited [#proving-rows-werent-edited]

With the call-row chain, you can prove that no row in a session was
edited in place, and that none was removed from the start or the middle.
It is **on by default**. `PostgresProviderDecisionLedger`,
`resolveDefaultProviderDecisionLedger` and the quickstart route's
durable ledger (`auditLedgerHashChain`) all stamp it unless you pass
`hashChain: false`. The verifier names the first row that doesn't match.
It catches an edit, a backfill or a deletion; it doesn't stop one, and
an unkeyed chain can be rewritten end to end by anyone with write
access. Pass an object to key it:

```typescript
import {
  PostgresProviderDecisionLedger,
  createPgAuditableCallChainReader,
  verifyAuditableCallChain,
} from "@pleach/core/audit";

const ledger = new PostgresProviderDecisionLedger({
  client: pool,
  // omitted = on, unkeyed SHA-256; false opts out
  hashChain: { signingKey, maxConflictRetries: 3 },
});

const verdict = await verifyAuditableCallChain({
  reader: createPgAuditableCallChainReader({ client: pool }),
  tenantId: "acme",
  sessionId,
  // key: the same signing key, resolved, when the chain is keyed
  // expectedHead: { chainSeq, rowHash } recorded elsewhere
});
// verdict.ok, verdict.head, verdict.rowCount, verdict.unchainedRowCount
```

There is one chain per tenant and session. Each row links to the
previous one, using SHA-256, or HMAC-SHA256 when `hashChain.signingKey`
is set. The hash covers every wrapper column, the four lineage columns
and the payload.

| Change to the table                    | What the verifier reports                                   |
| -------------------------------------- | ----------------------------------------------------------- |
| A row edited in place                  | The row's hash does not match the row content               |
| A row removed from the start or middle | A gap in the chain sequence and a broken previous-hash link |

What you provide for full-chain evidence:

* **An off-store head.** Record `verdict.head` somewhere the writer
  can't reach and pass it back as `expectedHead`. Removed tail rows
  aren't detected without it.
* **A signing key outside the database.** Set `hashChain.signingKey` so
  the hash is keyed rather than a public function of the row.

**Concurrency.** One ledger instance stamps one write per session at a
time. Across instances, a write that loses the race re-reads the head
and retries, up to `maxConflictRetries` (default 3).

**Fallback.** Audit completeness wins over chain coverage. After the
retries run out, or on any chain-side failure, the row is still written
with the chain columns `NULL`. Each such row reports
`AUDIT_LEDGER_ROW_UNCHAINED` through `onError`, and a table without the
chain columns reports `AUDIT_LEDGER_CHAIN_UNAVAILABLE` once. The
verifier counts these rows in `unchainedRowCount`. Without an `onError`,
the ledger reports degraded writes to `console.error`.

### When a row can't be stored [#when-a-row-cant-be-stored]

The Postgres ledger fails closed by
default (`ledgerWriteFailure: "fail"`). A transient driver error is
retried up to 3 times, 50 ms apart. If the row still isn't stored, the
write rejects with a `LedgerWriteError` (`code`
`AUDIT_LEDGER_WRITE_FAILED`, exported from `@pleach/core/audit`). Its
`reason` is `insert-failed`, `unreadable-result`, `redaction-dropped`,
`seal-dropped` or `write-timeout`. A caller that fires `recordCall`
without awaiting it must catch that rejection.

On `createPleachRoute`, a failed write ends the turn with an error frame
carrying that code, in place of `turn.completed`. The route waits up to
`auditLedgerWriteTimeoutMs` (default 30000) for the turn's writes, and a
write still pending then fails the same way. The route doesn't buffer
the answer, so text streamed before the error may already have reached
the client. `auditLedgerWriteFailure: "report"` on the route, or
`ledgerWriteFailure: "report"` on the ledger, keeps the older behaviour:
the failure goes to `onError` and the turn completes.

A `SessionRuntime` you build yourself fails closed the same way, for
the writes it can see. `AuditEmitter` methods return nothing, so an
emitter hands each ledger write to the turn with
`trackAuditLedgerWrite(ledger.recordCall(row))` from
`@pleach/core/audit`. Before `turn.completed`, the runtime waits up to
`auditLedgerWriteTimeoutMs` (default 30000) for those writes. A failed
or timed-out write ends the turn with an `error` event carrying
`AUDIT_LEDGER_WRITE_FAILED`, then `turn.completed` with
`outcome: "error"`. `auditLedgerWriteFailure: "report"` on the runtime
turns the wait off.

`trackAuditLedgerWrite` returns `false`, and nothing waits, outside a
turn: in a browser, in a runtime without `AsyncLocalStorage`, or after
the turn ends. Nothing waits on those writes, so a failed one can't fail
a turn: catch its rejection yourself. A ledger you register with
`setProviderDecisionLedgerFactory` gates a turn only when your emitter
tracks its writes.

The gateway fails closed too. See [provenance
writes](/docs/gateway#when-the-provenance-row-cant-be-stored).

On the Postgres ledger, chained writes for one (tenant, session) queue
behind each other. A row waits at most `chainWaitTimeoutMs` (default
30000\) for the write ahead of it. Past that, only that row fails, with
`reason` `write-timeout`, and later rows read the chain head from the
table. If the stuck write commits later, the unique sequence index
makes it retry on the next free number, so the chain still verifies.

`hashChain` needs the lineage columns. An explicit `hashChain` with
`lineageColumns: false` throws a `TypeError` at construction, and with
`hashChain` omitted, `lineageColumns: false` leaves the chain off.
`tamperEvidenceCallRowChain({ key })` implements the
[`TamperEvidence`](/docs/audit-ledger#tamperevidence) plug-point over
the same hash.

To tie each row into the event log's chain as well, see [Anchoring call
rows in the event
log](/docs/audit-ledger#anchoring-call-rows-in-the-event-log).

### The KV ledger chain (`createPleachAgent`) [#the-kv-ledger-chain-createpleachagent]

`createPleachAgent` stores call rows in its durable store, and that
ledger is chained by default too, per session.
`auditLedgerHashChain: false` turns it off, and `{ signingKey }` keys it
with HMAC-SHA256.

Each chained row costs one extra put and one extra key. Per session, the
call rows (`["audit","calls",sessionId]`), the chain head record
(`["audit","call-chain-heads",sessionId]`) and the per-row sequence
markers (`["audit","call-chain-seqs",sessionId]`) are separate entries,
so purge or expire them together. After a restart or a failed
head write, the ledger recovers the head from the markers. Failures
never lose the row:

| Failure                     | What happens                                                |
| --------------------------- | ----------------------------------------------------------- |
| Head record write fails     | The row is stored; the next row retries the head            |
| Sequence marker write fails | The row is stored                                           |
| Head recovery gives up      | The row is written unchained; the next row resumes recovery |

Each case is reported through `onError`.

Verify a session with `verifyAuditLedgerStoreChain`:

```typescript
import {
  verifyAuditLedgerStoreChain,
  AUDIT_LEDGER_STORE_UNCHAINED_AFTER_CHAINED_REASON,
} from "@pleach/core/quickstart";

const verdict = await verifyAuditLedgerStoreChain({
  store,            // the agent's BaseStore
  tenantId: "acme",
  sessionId,
  // key: the same signingKey, when the chain is keyed
  // expectedHead: a head you hold outside the store
  // strict: true, to also fail unchained rows written after the first chained row
});
```

`expectedHead` fails a session whose rows are gone. For evidence, hold
the head outside the store and use a signing key.

`strict: true` is a hygiene check, and a rolling deploy can fail it
falsely. Its failure reason is
`AUDIT_LEDGER_STORE_UNCHAINED_AFTER_CHAINED_REASON`.

For time evidence, anchor call rows into the event log with
`withAuditRecordedAnchor` (`@pleach/core/audit`), and time-stamp the
event-log chain with RFC 3161 tokens from an authority you choose.

A fork is still possible when two writers share one session. The
verifier reports it with `CALL_ROW_CHAIN_FORK_REASON`
(`@pleach/core/audit`).

## What the ledger scrubs before storing [#what-the-ledger-scrubs-before-storing]

The durable ledgers scrub PII by default. `PostgresProviderDecisionLedger`,
the quickstart route (`auditLedgerRedactor`) and the `createPleachAgent`
KV ledger (`redactor`) run `createScrubberChainRedactor()` from
`@pleach/core/audit` once per row, before the row is stored and hashed.
The chain verifies over what is stored.

The default redacts emails, prefixed API keys, JWTs and phone numbers
(for example `[redacted:email]`), in exactly these fields:

* `interruptDecision.argsBefore`, `argsAfter`, `editPrompt`, `reason`, `approver`
* `planGeneration.intent`
* the `envelope` text fields

It does not scrub `pluginPayloads`, provider-cascade or tool-fallback
error text, `modelCall`, or any other field. If you put PII there, pass
your own redactor; it replaces the default.

```typescript
import {
  PostgresProviderDecisionLedger,
  createScrubberChainRedactor,
  piiRedactorNoop,
} from "@pleach/core/audit";

// verbatim rows: null or piiRedactorNoop()
new PostgresProviderDecisionLedger({ client: pool, redactor: piiRedactorNoop() });

// default is "fail-closed"; this policyId is
// "pleach.scrubber-chain.v1+on-error=fail-open"
new PostgresProviderDecisionLedger({
  client: pool,
  redactor: createScrubberChainRedactor({ onScrubberError: "fail-open" }),
});
```

**A failing redactor writes a WITHHELD row.** A redactor fails when it
throws, or when it changes an identity field (`recordId`, `sessionId`,
`turnId`, `stageId`, `seqWithinTurn`, `createdAt`, `auditRecordVersion`,
`principal.tenantId` or an `identity.*` coordinate). That includes a
redactor that edits the row in place, so redactors must be pure.

The raw row is never stored and never handed to `onError`. The ledger
keeps the identity, lineage, principal, call, decision, outcome, cost
and token scalars, and replaces every other slot (including
`pluginPayloads`, `interruptDecision`, `planGeneration` and `envelope`)
with `{ withheld: true, policyId, reason: "redactor-error" }`. Two
exceptions: `why.stats.note` is withheld, and `tokenCost` is kept minus
`priceSnapshot`.

A withheld row keeps its `costUsd` (or `costOmitted` reason) and token
counts, so the call is still billed, and it is chained like any other
row. Once stored, `onError` gets `AUDIT_LEDGER_ROW_WITHHELD` with the
row's coordinates. If even the withheld form can't be built, nothing is
written and `onError` gets `AUDIT_LEDGER_ROW_DROPPED` with the identity
scalars only.

## Typed payload slots [#typed-payload-slots]

The variable surface: what the ledger carries because no structural
invariant can derive it. Each slot is stage-correlated and optional. A
`tool-loop` row MAY carry `toolSelection`, and a `synthesize` row MAY
carry `synthesisQuality`. Narrow on `stageId`.

| Slot                | Wire shape                      | Where it fires                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      |
| ------------------- | ------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `familyLock`        | `FamilyLockPayload`             | Family-lock resolution boundary; carries `resolverPath`, `emitSite`, `requestedFamily`, `familyMismatch`, `byokActive`, `byokKeyId`, `resolvedViaAlias`, `legacyDefaultModel`                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       |
| `fallbackStep`      | `FallbackStepRecord`            | Post-attempt of every fallback rung; carries `originalFamily`/`originalModel`/`originalCallClass`, `attemptFamily`/`attemptModel`/`attemptCallClass`, `attemptIndex`, `reason` (`FallbackStepReason`), `inFamily`, `originalLadderStep`, `ladderStep`, `ladderRegression`                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           |
| `providerCascade`   | `ProviderCascadeRecord`         | Graph decision-node cascade pivots; carries `source` (`graph` / `imperative-carve-out`), `trigger` (`decision-throw` / `decision-retry` / `stream-error` / `max-retries` / `timeout` / `user-abort-confirmed`), `errorType`, `providerFrom`, `providerTo`, `attemptN`, `userAbortValid`                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                             |
| `cacheBreakpoint`   | `CacheBreakpointLog`            | Provider response boundary; carries `fingerprintComposite`, `cacheReadTokens`, `cacheCreationTokens`, `inputTokens`, `hitPct`                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       |
| `toolFallbackStep`  | `ToolFallbackStepRecord`        | Runtime tool-cascade pivot or class-exhaustion; carries `originalTool`, `cascadedTo`, `capabilityId`, `failureClass` (`ToolFallbackFailureClass`), `attemptIndex`, `triedToolCount`, `inClass`, `cascadeApplied`, optional `triggerSite`                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            |
| `tokenCost`         | `TokenCostRecord`               | Token and usage accounting, with the real counts the provider reported. From v49 it carries a required `reasoningTokensReported: boolean`: `true` when the provider reported a reasoning-token count (a reported `0` is `true`), `false` when it reported none, so `reasoningTokens: 0` then means unknown. Optional `costUsd` is a list-price estimate, omitted (never `0`) when unknown; `costOmitted` then says why (`unpriced`, `served-model-mismatch`, `priced-per-call`, `owned-per-call`). `priceSnapshot` names the snapshot `costUsd` came from (see [Price snapshot](#price-snapshot))                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   |
| `modelCall`         | `ModelCallRecord`               | Per-call rows only, one per provider dispatch (each retry gets its own, sub-agent retries included on the standard providers). Carries `site` (`seam` / `tool-loop`, plus `adapter` from v41), `attemptIndex`, `nodeId`, `servedModel`, `outcome` (`ok` / `error` / `aborted` / `abandoned`), `errorClass` (includes `unread` and `post-settle` from v32), `httpStatus`, `finishReason`, `inputTokens`, `outputTokens`, `cachedInputTokens`, `costUsd`, `costOmitted` (`served-model-mismatch` / `unpriced` / `usage-unreported`), `priceSnapshot`, `latencyMs`, `ttfbMs`. It also carries `costSource` / `estimatedInputTokens` / `generationId` (v39) and `priceBasis` / `servingProvider` (v40, [Price basis](#price-basis)); from v42 it adds `cacheWriteTokens` and `cacheWrite1hTokens` ([Cache writes](#cache-writes)), from v44 `attemptOrigin` and from v45 `dispatchId` ([Dispatch identity](#dispatch-identity)), from v46 `sameModelRetry` ([Same-model retries](#same-model-retries)), and from v47 `catalogCostUsd` / `catalogPriceBasis` / `catalogCostDrift` ([Catalog price and drift](#catalog-price-and-drift)). From v48, `usagePartial: true` marks a call cut off mid-stream: its token counts, and any `costUsd` priced from them, are a minimum of what was billed. It is never written as `false`, and a call read to its end doesn't carry it. From v50, `offNode: true` marks a call made outside any graph node with no named allowlist entry (see [Off-node calls](#off-node-calls)), and `offNodeAllowance` names the allowlist entry a call ran under; both are absent on every other row. No prompt or response content and no provider error text. A decision row never carries it |
| `synthesisQuality`  | `SynthesisQualityRecord`        | `synthesize` rows only                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                              |
| `toolSelection`     | `ToolSelectionTrace`            | `tool-loop` rows only                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               |
| `planGeneration`    | `PlanGenerationRecord`          | `anchor-plan` rows only                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                             |
| `interruptDecision` | `InterruptDecisionRecord`       | When a human-in-the-loop interrupt fires                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            |
| `pluginPayloads`    | `readonly PluginAuditPayload[]` | Plugin-namespaced extension slot (`auditRecordVersion: 8`). Each entry carries `pluginId`, `subKind` and an opaque `data` payload                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   |

`FallbackStepRecord.ladderRegression` shows the slot earning its keep.
A structural invariant says in-family fallback walks the ladder forward,
and the field says when one row went backwards.

## Joinability [#joinability]

* `sessionId` joins to the session record.
* `turnId` aggregates every row fired for one user message, the natural
  grain for cost reporting and replay.
* `(sessionId, turnId, stageId, seqWithinTurn)` is the idempotency key
  the ledger enforces on `recordCall`.

Rows are append-only. The interface ships no update or delete primitive,
and a row that needs to mutate bumps `auditRecordVersion`. Deletion runs
through the `GDPRSoftDelete` plug-point, which your host implements, or
through the [retention pass](#retention).

## Query patterns [#query-patterns]

The shipped Postgres ledger uses the columns in [Postgres
columns](#postgres-columns); a custom adapter picks its own. The
examples use the in-memory shape names.

```typescript
import { MemoryProviderDecisionLedger } from "@pleach/core/audit";

const ledger = new MemoryProviderDecisionLedger();

// every row for a turn, in seqWithinTurn order
const turn = await ledger.getTurn(sessionId, turnId);

// newest-first session window, ULID cursor pagination
const page = await ledger.getSession(sessionId, { limit: 100, before: cursor });

// streamed export by time range — yields chunks
for await (const chunk of ledger.streamByTimeRange({
  fromIso: "2026-06-01T00:00:00Z",
  toIso:   "2026-06-02T00:00:00Z",
  chunkSize: 500,
})) {
  // forward to SIEM
}
```

To reconstruct the fallback ladder, sort the turn's rows by
`seqWithinTurn`. For the tool-cascade chain, keep rows with `stageId`
`'tool-loop'` and a non-null `toolFallbackStep`, sorted the same way.

## Retention [#retention]

Default retention is indefinite. To remove whole call-row sessions past
a period you set, schedule `runCallLedgerRetentionPass` from
`@pleach/core/audit`. It has no default period, removes rows only
through the destroy function in the [WORM tier](/docs/worm), and skips
any session under a legal hold. You provide the period and the
scheduler. Per-subject deletion runs through the `GDPRSoftDelete`
plug-point.

## Why this lives in core, not a sibling [#why-this-lives-in-core-not-a-sibling]

Audit is what makes replay, eval and fallback-rate dashboards possible.
If it lived in a sibling, every consumer would choose whether to ship
audit at all, and the ecosystem couldn't assume a consistent floor.
`@pleach/core` ships the row, and siblings layer retention, redaction,
hash-chaining and replay on top.

## Typed record payloads [#typed-record-payloads]

Five record shapes were promoted from opaque JSON to typed,
stage-correlated slots: `InterruptDecisionRecord`, `TokenCostRecord`,
`ToolSelectionTrace`, `PlanGenerationRecord` and
`SynthesisQualityRecord`. Consumer code narrows by slot presence (`if
(call.toolSelection) { … }`) without `as` casts. For field shapes, see
[`/docs/typed-records`](/docs/typed-records).

`AUDIT_RECORD_VERSION_HISTORY` carries the bumps (v8 through v50, all
read-compatible). Older readers keep working, and newer readers get the
narrowed fields. Since v18 and v19 (resolved model, provider and token
usage; `decision.requestedModel`; `outcome.why`):

| Bump             | What changed                                                                                                                                                                                                                                                                                                                                                                  |
| ---------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| v20              | `outcome.why.stats.servingProvider`: the upstream that served the call.                                                                                                                                                                                                                                                                                                       |
| v21              | `parentTurnId`, `subagentId`, `subagentDepth`: a sub-agent's inner call writes its own row.                                                                                                                                                                                                                                                                                   |
| v22              | `decision.lockedFamily`: the session's locked family beside the resolved one.                                                                                                                                                                                                                                                                                                 |
| v23              | `outcome.status` gains `provider-exhausted`.                                                                                                                                                                                                                                                                                                                                  |
| v24              | `decision.fallbackChain` becomes optional: absent means not measured, never `[]`.                                                                                                                                                                                                                                                                                             |
| v25              | `decision.rungOrdinal` becomes optional.                                                                                                                                                                                                                                                                                                                                      |
| v26              | `interruptDecision.argsChanged` becomes optional; `tokenCost.costUsd` adds a list-price estimate, omitted for an unpriced model.                                                                                                                                                                                                                                              |
| v27              | `modelCall` (one per-call row per provider dispatch), `parentRecordId`, and `costOmitted` reasons on `modelCall`, `tokenCost` and the decision row.                                                                                                                                                                                                                           |
| v28              | `priceSnapshot` on `modelCall` and `tokenCost`. The decision row's `costOmitted` gains `usage-unreported`.                                                                                                                                                                                                                                                                    |
| v29              | `run`: the core version, and when known the git sha and config manifest hash, that recorded the row. Stamped only by the quickstart route.                                                                                                                                                                                                                                    |
| v30              | `modelCall.costOmitted` gains `usage-unreported` and is set whenever `modelCall.costUsd` is absent. See [Unreported usage](#unreported-usage).                                                                                                                                                                                                                                |
| v31 (Unreleased) | `toolName`, and the call-ledger schema gains parent turn id, root turn id, sub-agent depth and tool name columns. See [Lineage columns](#lineage-columns).                                                                                                                                                                                                                    |
| v32 (Unreleased) | `outcome.status` gains `degraded`, `unread` and `post-settle`; `outcome` gains optional `degradedReason`; `modelCall.errorClass` gains `unread` and `post-settle`. See [Fallback attempts](#fallback-attempts).                                                                                                                                                               |
| v33              | `outcome.degradedReason` gains `delivery.fabrication-replace`.                                                                                                                                                                                                                                                                                                                |
| v34              | `outcome.degradedReason` gains `delivery.fabrication-corrected`. A turn records at most one fabrication delivery-outcome row.                                                                                                                                                                                                                                                 |
| v35              | `synthesisQuality.synthesisPath` gains `delivery:fabrication-flagged:<subKind>`: flagged, body unchanged. Row-denominated failure rates are diluted from v35, so compare by turn.                                                                                                                                                                                             |
| v36              | `synthesisQuality.fabricationDeclaredBy` (optional): the plugins whose findings the row's arms acted on. On a client-recorded row (`recordedBy="client"`) the names are self-reported.                                                                                                                                                                                        |
| v37              | `synthesisQuality.synthesisPath` gains the withholding arm `streamed-draft-retracted`.                                                                                                                                                                                                                                                                                        |
| v38              | `dispatchGroupId` (optional): a decision row and every `modelCall` row of the same seam call share it.                                                                                                                                                                                                                                                                        |
| v39              | `modelCall.costSource`, `estimatedInputTokens`, `generationId` (optional): a dispatch whose usage never arrived may be priced by the provider's generation record (`generation-lookup`) or a prompt-token estimate (`input-estimate`, a floor). A model with no rate keeps `costOmitted: "usage-unreported"`.                                                                 |
| v40              | `modelCall.priceBasis` and `modelCall.servingProvider` (optional). See [Price basis](#price-basis).                                                                                                                                                                                                                                                                           |
| v41              | `modelCall.site` gains `adapter`: a row written by a framework adapter that observes a call it does not dispatch (e.g. a LangChain callback). One `adapter` row may cover several provider requests. Readers keyed on `seam` or `tool-loop` treat it as neither.                                                                                                              |
| v42              | `modelCall.cacheWriteTokens` (optional): prompt tokens written to the prompt cache, a subset of `inputTokens`. A priced write uses the rate source's cache-write rate; with no write rate the row stays `unpriced`. See [Cache writes](#cache-writes).                                                                                                                        |
| v43              | `modelCall.costSource` gains `partial-input-floor`: a dispatch that reported a headline count but no full usage is priced at its fresh input tokens (a floor) when the model's rate is known, plus cache reads at the cache-read rate; output tokens are not priced.                                                                                                          |
| v44              | `modelCall.attemptOrigin` (`provider-built` / `host-client`) and `modelCall.cacheWrite1hTokens` (optional). A priced cache write now uses the write rate of its lifetime; a write whose usage did not report the 1-hour/5-minute split, or has no rate for a lifetime it wrote, is `unpriced`. See [Dispatch identity](#dispatch-identity) and [Cache writes](#cache-writes). |
| v45              | `modelCall.dispatchId` (optional): a ULID minted per provider dispatch and handed to it, so a host can join its own records of that request back to the row. Correlation only, never an authorization or billing key.                                                                                                                                                         |
| v46              | `modelCall.sameModelRetry: true` (optional): one row per same-model retry claim the turn spent; counting marked rows gives a floor on the turn's re-streams. See [Same-model retries](#same-model-retries).                                                                                                                                                                   |
| v47              | `modelCall.catalogCostUsd`, `catalogPriceBasis` and `catalogCostDrift` (optional), beside `priceBasis: "provider-reported"` only: the catalog price of the same call, how it was priced, and whether the reported charge drifts from it by more than 5%. See [Catalog price and drift](#catalog-price-and-drift).                                                             |
| v48              | `modelCall.usagePartial: true` (optional): the call was cut off mid-stream, so its token counts, and any cost priced from them, are a minimum. Never written as `false`.                                                                                                                                                                                                      |
| v49              | `tokenCost.reasoningTokensReported` (required boolean): `true` only when the provider reported a reasoning-token count. A reader treats an absent key as unknown at any version.                                                                                                                                                                                              |
| v50              | `modelCall.offNode: true` and `modelCall.offNodeAllowance` (both optional), and a new `modelCall.errorClass` value `off-node-refused` with `outcome.status` `guard-rejected`. See [Off-node calls](#off-node-calls).                                                                                                                                                          |

v49 is the one required-field addition: a TypeScript producer that builds a `TokenCostRecord` by hand must now set `reasoningTokensReported`, or the build fails. Readers see an extra key and keep working.

Bumps from v24 on can omit a key an older writer always supplied, so a
reader that dereferences `decision.rungOrdinal`, `decision.fallbackChain`
or `interruptDecision.argsChanged` without a guard must add one. v28 and
v30 each add a value to a closed `costOmitted` set, so a decoder that
rejects unknown enum values must widen. v32 widens `outcome.status` and
`modelCall.errorClass`, so a consumer with an exhaustive `switch`, a
`Record` keyed on either, or a strict-enum decoder must add the new
values. v41 widens `modelCall.site` (`adapter`) and v43 widens
`modelCall.costSource` (`partial-input-floor`), so a validator or
`switch` over either must accept the new member. A reader that treats every status other than `ok` as a failure
should exclude them (see [Fallback attempts](#fallback-attempts)). Only
v31 touches the database. Its columns are optional, and an un-migrated
table keeps accepting rows (see [Lineage columns](#lineage-columns)).

### Unreported usage [#unreported-usage]

A billed call whose usage the provider didn't report has an unknown
cost, never `$0`. From v30, a per-call row omits `modelCall.costUsd` and
sets `costOmitted: "usage-unreported"` when the stream reported no
usage, only one of the input and output counts, or `0` for both.
`costOmitted` is set whenever `costUsd` is absent, with one exception: an
errored attempt that carried only error or terminal events and no token
count (a refusal) stays unmarked, even when it carries `usage: {}`.

A count the usage reader can't read is recorded as absent, not `0`. A
call that wrote to the prompt cache is priced where the rate source
publishes a cache-write rate, and `unpriced` otherwise. From v44 that
write is priced at the rate of its lifetime (1 hour or 5 minutes); a
usage that reports no lifetime split is `unpriced` rather than assumed
to be a 5-minute write. A call that read from the cache prices those reads at the
cache-read rate when the model has one; cached tokens with no cache-read
rate leave the row unpriced.

A streamed call that errors after the provider attached a usage object,
even an empty `usage: {}`, is `usage-unreported`. A dispatch refused
before any event, or one whose only events are error terminals, stays
unmarked.

For v29 and earlier rows, `modelCall.costUsd: 0` beside `0` input and
`0` output tokens is a silent zero, not a free call. Count it as a call
of unknown cost.

### Fallback attempts [#fallback-attempts]

A fallback implementation that declares `auditHooksEveryAttempt: true`
gets exactly one `modelCall` row for every attempt it creates through the
`auditModelCallAttempt` hook, read or not. Two kinds of attempt get their
own label, written to both `outcome.status` and `modelCall.errorClass`
(each appears on both fields or on neither):

| Value         | Meaning                                                                                                                          |
| ------------- | -------------------------------------------------------------------------------------------------------------------------------- |
| `unread`      | An attempt created before the call settled, with no read ever issued on it when the call settled.                                |
| `post-settle` | An attempt created after the call settled. It gets one row even if it is read later. A rising rate points at the implementation. |

Neither is a provider failure, because with a lazy source no request may
have been sent. Neither is in the provider-failure set (`provider-error`,
`provider-exhausted`), and the `audit.recorded` anchor tier is
`minor-failure`. The row keeps `outcome: "abandoned"` and omits `costUsd`
with `costOmitted: "usage-unreported"`: possibly billed, cost unknown,
never `$0`. An attempt that had a read issued and was then left keeps
`errorClass: "abandoned"` and `status: "provider-error"`. A
provider-dispatch audit stream closed before anything read it records
`unread`, and its cost stays omitted rather than priced by a prompt-token
estimate.

A stream cut by the content-repetition guard is billed at the usage its
provider reported, not at an `abandoned` input-only floor. After the cut,
the turn stops reading at once and the provider stream is drained in the
background until its usage arrives, so the turn's own stream never waits
on it. The drain stops early, and the call keeps the floor, when the
turn's abort signal has fired (a user Stop is reported as `user-stop`),
when it has run for 5 seconds or read 256 KiB, or at a tool-call chunk.

An emitter that sets `AuditEmitter.acceptsDrainedModelCall` receives the
call's row at the cut, with the drained reading pending as
`AuditDecisionInput.drainedModelCall`, and writes it once. The
quickstart emitter holds that row for up to 5 seconds, so a guard cut can
delay the end of the route's response stream by up to that long.

A runtime's `TurnReport` (the `harness` option's `onTurnReport`) includes
that row. An emitter that sets `acceptsDrainedModelCall` registers the
write of the row it is holding with
`SessionRuntime.holdTurnReportForAuditRow(offer)` (experimental). While
rows are held, the report fold waits for them to settle, for at most 5
seconds, so the report is complete when the turn's stream ends. The
caller's abort signal ends the wait at once. A runtime holds at most 256
rows, and a row past that bound is still written but the fold
doesn't wait for it.

`@pleach/core/audit` exports the pieces for an emitter of your own:
`settleDrainedModelCall(drained, cut, cutSettled, timeoutMs)`,
`trackPendingRowOffer(pending, offer, cap?)` and
`waitForPendingRowOffers(pending, boundMs)`. `settleDrainedModelCall` and `waitForPendingRowOffers` never reject.

`degraded` is a different kind of value. It marks a delivery that was
served and billed but was a fallback answer, a family-exhausted notice or
a graph-state repair. It is not an error, it owes no `httpStatus`, and
`outcome.degradedReason` is one of `delivery.empty-terminal-fallback`,
`delivery.family-exhausted-notice` or `delivery.graph-state-recovery`.

### Price basis [#price-basis]

From v40, `modelCall.priceBasis` says how a row's `costUsd` was priced.
The order per dispatch is:

1. `provider-reported`: the gateway's own charge for the call (OpenRouter
   `usage.cost`).
2. `served-provider`: the reported token counts at the published rates of
   the upstream that served the call. `modelCall.servingProvider` names
   that upstream when the stream reported one.
3. `list`: the model's list rates.

`priceSnapshot` is stamped only beside `priceBasis: "list"`, and an
unpriced row carries no basis. On a call served with the caller's own
provider key, the reported charge is the gateway fee plus the upstream
inference cost. Without the upstream figure no charge is reported, so the
row is priced from the served provider's rates.

The default OpenRouter request asks for usage accounting, and native
transports are unchanged. The standard loaders take a
`servedProviderRates` reader, `createPleachRoute` supplies one, and a
host's `costServedSources.endpoint` reader wins.

Not covered by `priceBasis`: decision rows' `tokenCost` stays
list-priced, and `modelCall` rows the route prices itself (generation
lookup or prompt estimate) carry no basis.

### Dispatch identity [#dispatch-identity]

From v44, `modelCall.attemptOrigin` says who built the client that sent
the attempt. `provider-built` means the provider built it from its
configured credentials; `host-client` means the caller passed its own
SDK client, whose endpoint, credentials and transport the provider does
not control. It is carried from `ProviderDispatchAttempt.origin`, so it
is present only when the provider reported its attempts.

From v45, `modelCall.dispatchId` is a ULID the core mints for each
provider dispatch before the request goes out, one per row and never
shared with a sibling attempt. The same value is handed to the dispatch
(`ModelCallDispatchIdentity`), so a host can stamp it on the request it
sends and join its own record of that request — a cost row, a gateway
log — back to the row. It is a correlation key only: never an
authorization, ownership or billing key.

### Same-model retries [#same-model-retries]

From v46, `modelCall.sameModelRetry: true` marks "one same-model retry
claim of this turn was spent here". Each claim the turn's same-model
retry budget grants stamps exactly one row: the first row recorded for a
dispatch that started at or after the claim. That is normally the
re-stream itself, but a dispatch interleaved between the claim and the
re-stream can carry the marker instead; the marker conserves the COUNT
per turn, it does not name the re-stream row.

A reader counts a turn's marked rows to learn how many same-model
re-streams the turn spent, and that count is a **floor**: a claim whose
re-stream crashed or was aborted before any row was recorded leaves no
marked row, and a dispatch outside a turn frame is never marked. Count in
the store, since a row cap can truncate a fetch. Every dispatch keeps its
row: the marker labels a billed call and never replaces or suppresses
one.

### Catalog price and drift [#catalog-price-and-drift]

From v47, a row priced `provider-reported` also records what the same
call would have cost from the rate catalog, so a gateway charge can be
audited without re-deriving prices:

| Field               | Meaning                                                                                                                                                                                                                                                                                           |
| ------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `catalogCostUsd`    | The reported counts at the serving upstream's published rates, else at the model's list rates. Omitted when the catalog cannot price the call — no rate, a served model the list rates are not for, or a cache token class with no rate — never `0` for want of a rate and never a fallback rate. |
| `catalogPriceBasis` | `served-provider` or `list`: which rates priced `catalogCostUsd`. Present exactly when `catalogCostUsd` is.                                                                                                                                                                                       |
| `catalogCostDrift`  | `true` when the reported charge and `catalogCostUsd` differ by more than `CATALOG_COST_DRIFT_TOLERANCE` (5%) of `catalogCostUsd`; absent otherwise and absent when `catalogCostUsd` is `0`, so an agreeing row and a pre-v47 row read alike.                                                      |

`costUsd` stays the reported charge: sum `costUsd`, never
`catalogCostUsd`. A row with no reported charge is byte-identical to
v46.

### Cache writes [#cache-writes]

From v42, `modelCall.cacheWriteTokens` records the prompt tokens the
call wrote to the provider's prompt cache, a subset of `inputTokens`
exactly as `cachedInputTokens` is. A priced call now reproduces from
fresh input + cache reads + cache writes + output.

From v44, `cacheWrite1hTokens` splits out the part written with a
1-hour cache lifetime; the rest were 5-minute writes. A write is priced
at the rate source's write rate for its lifetime
(`cacheWrite5mCostPer1M` / `cacheWrite1hCostPer1M`; the single
`cacheWriteCostPer1M` is deprecated and read only as a fallback for the
5-minute rate). A row whose usage did not report the 1-hour/5-minute
split (OpenRouter, a host done-chunk that forwards only the write
count), or which wrote a lifetime the rate source has no rate for, stays
`costOmitted: "unpriced"` — never at the input rate, never `0`.

### Off-node calls [#off-node-calls]

From v50, a model call made outside any graph node is visible on its row. The model-call node guard has three modes: `probe` (the default), `throw` and `off`.

In `probe` mode the call still runs and is billed as usual, and its row carries `modelCall.offNode: true`. In `throw` mode the call is refused before any request goes out, and the refused attempt's row carries `offNode: true`, `errorClass: "off-node-refused"` and `outcome.status` `guard-rejected`. That is one row, never a provider failure.

A call that runs under a named exception, built with `defineOffNodeAllowlist`, carries `modelCall.offNodeAllowance` set to the entry's name instead. `offNode` is never written as `false`. The browser and Edge, which carry no node frames, write neither field.

### Price snapshot [#price-snapshot]

`priceSnapshot` is written only beside `costUsd`, and only when the rate
source stamps one. An unpriced row never carries it. It names the shared
`/models` price snapshot the cost was computed from, so a cost can be
audited back to the catalog read behind it:

<TypeTable
  type="{
  id:         { type: 'string', description: 'Random per snapshot replacement, unique across processes.' },
  generation: { type: 'number', description: 'Process-local replacement counter; orders snapshots within one process.' },
  fetchedAt:  { type: 'ISO-8601', description: 'UTC time the snapshot landed.' },
}"
/>

It holds public catalog metadata only, with no tenant, session or
request data.

## Where to go next [#where-to-go-next]

<Cards>
  <Card title="Audit ledger" href="/docs/audit-ledger" description="The ProviderDecisionLedger interface and the persistence adapters that write these rows." />

  <Card title="Typed records" href="/docs/typed-records" description="The five typed record slots and the analytics each one unlocks." />

  <Card title="Tamper-evident hash chain" href="/docs/hash-chain" description="The previous row's hash plus the row hash: what protects this row's persistence." />

  <Card title="Observability" href="/docs/observability" description="Read-side wiring — OTel spans, Datadog, Honeycomb — that joins to rows on `turnId`." />

  <Card title="Scrubbers" href="/docs/scrubbers" description="The event-type allowlist and the four bundled scrubbers that gate event-log writes." />
</Cards>
