# Audit ledger (/docs/audit-ledger)



This page covers the audit-ledger write side. For read-side
observability (OTel spans, lineage graph, Datadog and Honeycomb wiring),
see [Observability](/docs/observability).

## How the audit cluster pages relate [#how-the-audit-cluster-pages-relate]

Several pages cover the audit substrate at different grains.

| If you want to...                                      | Read                                                                                  |
| ------------------------------------------------------ | ------------------------------------------------------------------------------------- |
| Understand the write interface and register an adapter | **This page**                                                                         |
| See every field on a row and how to query it           | [The AuditableCall row](/docs/auditable-call-row)                                     |
| See the typed envelope every event flows through       | [Event log](/docs/event-log)                                                          |
| Build read-side projections off the event log          | [Event log projections](/docs/event-log-projections)                                  |
| Verify the hash chain or generate a proof              | [Hash chain](/docs/hash-chain)                                                        |
| Sign a turn corpus and emit an attestation bundle      | [Attestation](/docs/attestation)                                                      |
| Ship the OTel span side                                | [Observability](/docs/observability) + [OTel observability](/docs/otel-observability) |
| Gate writes with scrubbers for HIPAA, GDPR or PCI-DSS  | [Scrubbers](/docs/scrubbers) + [Compliance](/docs/compliance)                         |

Every LLM call goes through a **seam** and lands in **two separate
durable ledgers**. The **event log** records the session's observable
events (messages, tools, interrupts, content lifecycle) as an
append-only, per-chat sequence-numbered stream. The **AuditableCall**
ledger records the router's per-call decisions (which model, why, which
rung, what outcome). The write side stamps a **hash chain** entry on
event-log rows, optional **attestation** signs a corpus of rows, and
**scrubbers** redact PII at write time.

### Two ledgers, one compliance surface [#two-ledgers-one-compliance-surface]

The two streams are separate tables with different grains and keys, so
a query against one can't see the other. The split is a **doctrine**:

> **The event log is the single compliance-review and attestation
> boundary. The AuditableCall ledger is engineering telemetry (routing,
> cost and quality forensics) and is non-authoritative for compliance
> *by design*. Any fact a compliance review needs must have an
> event-log row.**

[Attestation](/docs/attestation) signs a merkle proof over **event-log
rows only**. `queryAudit` and `verifyAuditTrail` read the event log
alone. Each chat is its own hash chain, so a tenant-wide query grades
several chains. The compliance-relevant facts already have typed
event-log rows, including `llm.turn`, `cost.rollup`,
`interrupt.approved/rejected/edited/timeout`, `guard.decision`,
`synthesis.outcome` and `turn.started/completed/failed`. An auditor
reviews one ledger and makes one verification call: `verifyAuditTrail`.

|                          | Event log                                                                        | AuditableCall ledger                                                                                             |
| ------------------------ | -------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------- |
| **Grain**                | One row per observable session event                                             | One row per addressable LLM call                                                                                 |
| **Key**                  | `(chatId, sequenceNumber)`                                                       | `(sessionId, turnId, stageId, seqWithinTurn)`                                                                    |
| **Records**              | What the session experienced, including turn-boundary and decision-outcome rows  | How the router got there: selection reason, rung, fallback chain, latency, typed slots                           |
| **Role**                 | Compliance surface: attestation corpus, chain verification, `queryAudit`, replay | Engineering forensics: routing, cost attribution, model quality, SLA work                                        |
| **Contract**             | Append-only, hash-chained, tenant-scoped RLS                                     | Append-only typed row; per-session hash chain on by default in the durable ledgers; event-log anchors are opt-in |
| **State reconstruction** | [Projections](/docs/event-log-projections) fold rows into state                  | Analytics queries on typed slots and `stageId`; no fold semantics                                                |

When an outcome matters to a review but only the router can see it,
**project it into the event log** rather than sending the auditor to the
second ledger. Family exhaustion is the precedent: the AuditableCall
ledger keeps the routing detail, and the review-relevant outcome (the
user got no answer and a switch-model prompt) is projected as an
`error.code` row with `error_kind: "provider-exhausted"`.

If you find yourself joining the two ledgers to answer a compliance
question, a projection is missing. File it as a gap in the event-log
type union, not a query pattern to keep.

### Which AuditableCall facts the event log covers [#which-auditablecall-facts-the-event-log-covers]

| AuditableCall fact                           | Event-log coverage                                                                                                                                                                                                                                         |
| -------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `interruptDecision`                          | `interrupt.approved/rejected/edited/timeout`, including the post-rewrite effective-args row                                                                                                                                                                |
| `tokenCost`                                  | Turn grain is covered by `llm.turn` and `cost.rollup`. The cache-hit split stays engineering                                                                                                                                                               |
| `toolSelection`                              | `tool_offer.snapshot` (offered), `tool.started/completed/failed` (ran) and `guard.decision` (refused). Elimination reasons are partly covered: schema-condensation refusals land durably too (see below). The router's ranking reasoning stays engineering |
| `planGeneration`                             | Plan *effects* are evidenced by `tool.*` and `turn.*`. Plan provenance is engineering-only (see [plans](/docs/plans))                                                                                                                                      |
| `synthesisQuality` and `delivery:*` outcomes | `synthesis.outcome` and the `content.reset/correction/finalized` ledger. `delivery:family-exhausted` also projects as `error.code`                                                                                                                         |

What remains AuditableCall-only is the router's internal reasoning.

Schema-condensation refusals are recorded. `tool_offer.snapshot` notes
which candidate schema condensation refused, under which gate and
ceiling. `condenseSchemas` returns `budgetDecisions`, and `AgentAdapter`
has an optional `getTurnCondensationDecisions()`. The types
`SchemaCondensationBudgetDecisions`, `SchemaCondensationDecline`,
`SchemaCondensationDeclineGate` and `SchemaCondensationDeclinePass`
export from `@pleach/core/strategies`.

With an `AuditEmitter` registered, every request the runtime sends
through a built-in provider (`AiSdkProvider`, `AnthropicSdkProvider`,
`OpenAINativeProvider`) writes its own `AuditableCall` row through a
`ProviderDecisionLedger`, 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 `tenantId`, `turnId`, `toolName`, `subagentDepth`,
`parentTurnId`, `model`, `provider` and `tokenCost`. `@pleach/core` ships
the write interface plus two reference implementations. The default
emitter is a no-op, so rows land only once the host registers an
emitter, which the quickstart and any production host do. Consumer code
registers adapters for Supabase, IndexedDB, S3 or any other store.

`tenantId` is the opaque rollup axis. In a multi-tenant SaaS it's your
end customer. In an internal deployment on an Anthropic or OpenAI
Enterprise contract it's typically the employee, team or cost center you
audit against. See [Migrating from Anthropic
Enterprise](/docs/migrating-from-anthropic-enterprise) or [Migrating from
OpenAI Enterprise](/docs/migrating-from-openai-enterprise).

Three compliance plug-points (tamper evidence, PII redaction, GDPR
soft-delete) ride on top of the ledger. Tamper evidence and GDPR
soft-delete ship as reference-only no-ops. PII redaction runs by default
in the durable ledgers (`createScrubberChainRedactor()`, see
[`PIIRedactor`](#piiredactor)). `@pleach/compliance@0.1.0` ships the
four-scrubber bundle (`SSN-US`, `Luhn`, `US-DL`, `KeyedRegex`); see
[scrubbers](/docs/scrubbers). The chain verifier lives in
`@pleach/core/eventLog` (`verifyChainForChat`, `generateProof`), and
writer-side stamping is on by default. `@pleach/replay` consumes
`verifyChainForChat`. Subject-key-derived redaction wiring on
`PIIRedactor` and `GDPRSoftDelete` continues to land through the
`HarnessPlugin` contract; the plug-point shapes in `@pleach/core` are
the stable contract. See [compliance](/docs/compliance).

```typescript
import {
  MemoryProviderDecisionLedger,
  NoopProviderDecisionLedger,
  AUDIT_RECORD_VERSION_HISTORY,
  tamperEvidenceNoop,
  piiRedactorNoop,
  gdprSoftDeleteUnwired,
  NoopAuditEmitter,
} from "@pleach/core/audit";
import type {
  ProviderDecisionLedger,
  AuditableCallQuery,
  AuditableCall,
  PluginAuditPayload,
  TamperEvidence,
  PIIRedactor,
  GDPRSoftDelete,
  AuditDecisionInput,
  AuditEmitter,
} from "@pleach/core/audit";
```

See [AuditableCall row](/docs/auditable-call-row) for the row shape.

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

## The audit-ledger cluster [#the-audit-ledger-cluster]

The ledger is one of three concepts, with [the AuditableCall
row](/docs/auditable-call-row) (what gets written) and [the hash
chain](/docs/hash-chain) (after-the-fact tamper detection). The row is
the grain, the ledger is the write path, and the chain is the integrity
layer. The framing lives at [Concept clusters →
Audit-ledger](/docs/concept-clusters#audit-ledger-cluster).

## `ProviderDecisionLedger` [#providerdecisionledger]

The write interface. One method, fire-and-forget.

```typescript
interface ProviderDecisionLedger {
  recordCall(call: AuditableCall): Promise<void>;
}
```

Two contract rules:

1. **Append-only.** No update or delete primitive. A row that needs to
   mutate is a wire-format break: bump `auditRecordVersion` instead.
2. **Idempotent on `(sessionId, turnId, stageId, seqWithinTurn)`.**
   Re-emitting the same coordinates is a no-op, so retries on transient
   failure are safe.

Adapters that can batch SHOULD buffer at most 50 ms or 32 records
(whichever first) and flush at end-of-turn.

## `AuditableCallQuery` [#auditablecallquery]

The read interface. Write-only sinks (a SIEM forwarder, say) may omit
it. Adapters that consumers will query implement both.

```typescript
interface AuditableCallQuery {
  getTurn(
    sessionId: string,
    turnId: string,
  ): Promise<ReadonlyArray<AuditableCall>>;

  getSession(
    sessionId: string,
    opts?: { readonly limit?: number; readonly before?: string },
  ): Promise<ReadonlyArray<AuditableCall>>;

  streamByTimeRange(
    opts: StreamByTimeRangeOptions,
  ): AsyncIterable<ReadonlyArray<AuditableCall>>;
}

interface StreamByTimeRangeOptions {
  readonly fromIso: string; // inclusive, on createdAt
  readonly toIso: string; // exclusive
  readonly chunkSize?: number;
  readonly tenantId?: string; // matched against principal.tenantId
}
```

* `getTurn` returns rows in `seqWithinTurn` order, and an empty array
  (never an error) when the turn has none.
* `getSession` returns newest-first, with `limit` defaulting to 100.
  `before` is a `recordId` (ULID) cursor.
* `streamByTimeRange` yields chunks of at most `chunkSize` (default
  500\). Adapters that can't stream MAY emit a single chunk, so treat the
  iterable as the boundary, not the chunk.
* Always pass `tenantId` to `streamByTimeRange`. Omitting it streams
  every tenant; that form is deprecated, and the field becomes required
  at the next `auditRecordVersion` bump.

## Reference implementations [#reference-implementations]

| Implementation                   | Use case                                                  |
| -------------------------------- | --------------------------------------------------------- |
| `PostgresProviderDecisionLedger` | Durable rows in the call-row table on any Postgres driver |
| `MemoryProviderDecisionLedger`   | Tests, dev, in-process aggregation                        |
| `NoopProviderDecisionLedger`     | Audit isn't wired yet; calls write nowhere                |

All three ship in `@pleach/core/audit`. Other targets (IndexedDB, S3, a
SIEM) need a custom adapter; see [Writing your own
adapter](#writing-your-own-adapter).

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

const ledger = new MemoryProviderDecisionLedger();

// The ledger is bound to the runtime via the registry accessor
// (`setProviderDecisionLedgerFactory`, shown below) — it is NOT a
// `SessionRuntimeConfig` field. In tests you can also read the
// MemoryProviderDecisionLedger directly.
const runtime = new SessionRuntime({
  storage: memoryAdapter,
  userId: "test-user",
});

// drive a turn ...
const rows = await ledger.getSession(sessionId, { limit: 100 });
```

## `PostgresProviderDecisionLedger` [#postgresproviderdecisionledger]

The durable ledger. It takes any `{ query(sql, params) }` client
(node-postgres, Neon serverless, pglite) and sends one idempotent
parameterized insert per call. It has no update or delete method.

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

const ledger = new PostgresProviderDecisionLedger({
  client: pool,
  // hashChain and the redactor are on by default; pass
  // `hashChain: false` or `redactor: null` to opt out.
  onError: (err, call) => log.warn({ err, recordId: call.recordId }),
});
```

| Option                     | Default                                   | Effect                                                                                                                                                                                                                                                                         |
| -------------------------- | ----------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `client`                   | required                                  | The `PgClientLike` the ledger writes through                                                                                                                                                                                                                                   |
| `tableName` / `schemaName` | The bundle's call-row table / unqualified | Where rows go; each identifier is quoted                                                                                                                                                                                                                                       |
| `onError`                  | `console.error`                           | Breadcrumb for every swallowed failure and downgrade. A throwing callback is swallowed too                                                                                                                                                                                     |
| `lineageColumns`           | `true`                                    | Write the parent turn, root turn, sub-agent depth and tool name. `false` sends the original 20 columns                                                                                                                                                                         |
| `hashChain`                | on                                        | Stamps the [call-row chain](/docs/auditable-call-row#proving-rows-werent-edited), unkeyed SHA-256. `{ signingKey, maxConflictRetries }` keys it and sets the retry budget (default 3). `false` opts out. Chained writes are serialised per (tenant, session) within one ledger |
| `redactor`                 | `createScrubberChainRedactor()`           | Scrubs PII before anything is derived from the row, so the chain hashes what is stored. `null` or `piiRedactorNoop()` stores rows verbatim                                                                                                                                     |
| `ledgerWriteFailure`       | `"fail"`                                  | `"fail"` rejects a row that isn't stored with a `LedgerWriteError`. `"report"` sends the failure to `onError` and resolves                                                                                                                                                     |
| `chainWaitTimeoutMs`       | `30000`                                   | How long a chained row waits for the write ahead of it before failing with `reason` `write-timeout`. Must be a positive finite number, or construction throws a `RangeError`                                                                                                   |

By default `recordCall` rejects when the row isn't stored; see [When a
row can't be stored](/docs/auditable-call-row#when-a-row-cant-be-stored).
`recordCallOutcome(call)` does the same write and returns `"written"`,
`"duplicate"` or `"failed"`. A retried insert whose first attempt
committed but lost its reply reads `"written"`, not `"duplicate"`.

The ledger narrows its column set when the table is older than the
code. `columnTier` reads `"chain"`, `"lineage"` or `"base"`.

| Breadcrumb (`onError`)                | When                                                                                                                                                                                               |
| ------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `AUDIT_LEDGER_COLUMNS_DOWNGRADED`     | Once, when the table lacks the lineage columns. Re-apply the base tier                                                                                                                             |
| `AUDIT_LEDGER_CHAIN_UNAVAILABLE`      | Once, when `hashChain` is on and the table lacks the chain columns. Every row is still written, unchained                                                                                          |
| `AUDIT_LEDGER_ROW_UNCHAINED` (prefix) | Per row written with the chain columns empty, after a lost retry budget or a chain-side failure                                                                                                    |
| `AUDIT_LEDGER_ROW_WITHHELD`           | Per stored row the redactor refused. Identity, principal, call, decision, outcome and cost scalars are kept, and every other slot becomes `{ withheld: true, policyId, reason: "redactor-error" }` |
| `AUDIT_LEDGER_ROW_DROPPED`            | When even the withheld form can't be built; nothing is written                                                                                                                                     |

An explicit `hashChain` with `lineageColumns: false` throws a
`TypeError`. With `hashChain` omitted, `lineageColumns: false` leaves the
chain off. `resolveDefaultProviderDecisionLedger({ client,
lineageColumns, hashChain })` builds the same ledger when a client is
configured.

## Writing your own adapter [#writing-your-own-adapter]

A typical Supabase-backed adapter:

```typescript
// lib/audit/supabaseLedger.ts
import type { ProviderDecisionLedger, AuditableCall } from "@pleach/core/audit";
import type { SupabaseClient } from "@supabase/supabase-js";

const ledgerTable = "<your call ledger table>";
const dedupeKey = "<session, turn, stage and sequence columns>";

export class SupabaseProviderDecisionLedger implements ProviderDecisionLedger {
  constructor(private client: SupabaseClient) {}

  async recordCall(call: AuditableCall): Promise<void> {
    const { error } = await this.client
      .from(ledgerTable) // the call-row table from the schema bundle
      .upsert(this.toRow(call), {
        onConflict: dedupeKey,
        ignoreDuplicates: true,
      });

    if (error) {
      console.warn(`[audit-ledger] insert failed: ${error.message}`);
      // Soft-fail. Never throw.
    }
  }

  private toRow(call: AuditableCall) {
    return {
      // Map each AuditableCall field to its column per the schema bundle,
      // then keep the decision as the payload.
      payload: call.decision,
    };
  }
}
```

Register the factory with `setProviderDecisionLedgerFactory`. The
runtime calls it once at construction, passes its host-supplied Supabase
client to `fromSupabase`, and holds the returned ledger for its
lifetime:

```typescript
import { setProviderDecisionLedgerFactory } from "@pleach/core/runtime";

setProviderDecisionLedgerFactory({
  fromSupabase: (client) => new SupabaseProviderDecisionLedger(client),
});
```

## `AUDIT_RECORD_VERSION_HISTORY` [#audit_record_version_history]

The wire-format version log. Read it at runtime to render what changed
in a version:

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

for (const entry of AUDIT_RECORD_VERSION_HISTORY) {
  console.log(`v${entry.to} (${entry.landedAt}): ${entry.reason}`);
}
```

Pleach's CI checks each bump. Consumer adapters can check this constant
during migration to see which payload fields are new.

## The three compliance plug-points [#the-three-compliance-plug-points]

`TamperEvidence` and `GDPRSoftDelete` default to reference-only no-ops.
The durable ledgers default `PIIRedactor` to
`createScrubberChainRedactor()`; pass your own to replace it.
[`@pleach/compliance@0.1.0`](/docs/compliance) ships the four-scrubber
bundle. Chain verification ships in `@pleach/core/eventLog`
(`verifyChainForChat`, `verifyChainById`). Subject-key-derived
`GDPRSoftDelete` wiring stays host-side; the plug-point shapes below are
the stable contract.

### `TamperEvidence` [#tamperevidence]

Hash-chain over previous records.

```typescript
interface TamperEvidence {
  link(record: AuditableCall, prevAnchor: string | null): string | null;
  verifySequence(
    records: ReadonlyArray<AuditableCall>,
    initialAnchor: string | null,
  ): string | null;
  readonly schemeId: string;
}

import { tamperEvidenceNoop } from "@pleach/core/audit";
// No-op default — every link returns null, verification always passes.
```

`link` is deterministic and returns the anchor for `record` (`null` for
the first). `verifySequence` returns `null` if the sequence is intact,
or the `recordId` of the first record that breaks it. Both are
synchronous. `schemeId` is recorded in `payload.tamper.scheme` (default
`"none"`) so a verifier knows which implementation to load.

The live event-log implementation is in `@pleach/core/eventLog`
(`chainStep`, `computeRowHash`, `computeGenesisSeed`,
`PLEACH_C9_CANONICALIZATION_VERSION`), on by default
behind an `EventLogWriter` option, with `verifyChainForChat` and
`generateProof` for verification. Hosts that already route through that
chain leave this plug-point as the no-op default.

`tamperEvidenceCallRowChain({ key })` (`@pleach/core/audit`) is the live
implementation for the call-row table. For stored rows, prefer
`verifyAuditableCallChain`, which also checks chain position.

### `PIIRedactor` [#piiredactor]

Pattern-based redaction with an allowlist.

```typescript
interface PIIRedactor {
  redact(record: AuditableCall): AuditableCall;
  readonly policyId: string;
}

import { createScrubberChainRedactor, piiRedactorNoop } from "@pleach/core/audit";
// createScrubberChainRedactor() — the durable ledgers' default.
// piiRedactorNoop() — identity passthrough (policyId "none").
```

`redact` is pure, and adapters call it once per record before insert.
`policyId` names the policy that produced the stored shape.

**On by default in the durable ledgers.** `PostgresProviderDecisionLedger`
and the `createPleachAgent` KV ledger run `createScrubberChainRedactor()`
unless you pass another redactor, `null` or `piiRedactorNoop()`. It
scrubs exactly `interruptDecision.{argsBefore,argsAfter,editPrompt,reason,approver}`,
`planGeneration.intent` and the `envelope` text fields. It does not
scrub `pluginPayloads`, provider-cascade or tool-fallback error text, or
`modelCall`. Its `policyId` is `pleach.scrubber-chain.v1`, with
`+on-error=<mode>` or `+scrubbers=custom` appended for non-default
options. The SQLite event log scrubs by default as well;
`redaction: "off"` turns it off. `@pleach/compliance@0.1.0` ships the
row-level scrubber cohort on the event log via `contributeScrubbers`.

### `GDPRSoftDelete` [#gdprsoftdelete]

Subject-key-derived soft-delete.

```typescript
interface GDPRSoftDelete {
  softDelete(
    recordId: string,
    reason: RedactionReason,
    opts?: { readonly requestRef?: string | null },
  ): Promise<RedactedPayloadSentinel>;
}

import { gdprSoftDeleteUnwired } from "@pleach/core/audit";
// Throws on use — must be wired by the consumer.
```

`softDelete` replaces the named record's `payload` with a
`RedactedPayloadSentinel` and returns it for logging. It MUST be
idempotent: re-redacting returns the existing sentinel, and adapters
MUST NOT chain redactions. Identity fields and call shape are untouched.

**Host-wired.** You provide the wiring (tombstone table, subject-key
derivation, read short-circuit). The audit rows stay (append-only), and
the tombstone gates rendering. `@pleach/compliance` ships the
scrubber-side primitives.

## `AuditEmitter` [#auditemitter]

The seam side of the audit surface. Plugin code sees the emitter, and
the emitter writes to the ledger.

```typescript
interface AuditEmitter {
  recordFamilyLockDecision(
    input: AuditDecisionInput,
    overrides?: { readonly provider?: ProviderFamily },
  ): void;
  recordFallbackStepDecision(input: AuditDecisionInput): void;
  recordCacheHitDecision(input: AuditDecisionInput): void;
  recordProviderCascadeDecision(input: AuditDecisionInput): void;
  recordToolFallbackStepDecision(input: AuditDecisionInput): void;
  recordInterruptDecisionDecision(input: AuditDecisionInput): void;
  recordTokenCostDecision(input: AuditDecisionInput): void;
  recordToolSelectionDecision(input: AuditDecisionInput): void;
  recordPlanGenerationDecision(input: AuditDecisionInput): void;
  recordSynthesisQualityDecision(input: AuditDecisionInput): void;
}

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

There is one method per typed payload slot, ten in all. The default
implementation shares a single inner write across them.

All methods are sync fire-and-forget and return `void`. Implementations
MUST swallow exceptions internally, because a failure to record an
`AuditableCall` MUST NOT abort the turn.

`AuditDecisionInput` takes a `turnKey` (the orchestrator's messageId).
The seam fills in the session id, principal, per-turn sequence, record
id and timestamp, so emit sites supply only what they already know.

## Plugin-namespaced payloads [#plugin-namespaced-payloads]

`PluginAuditPayload` is the extension slot for a plugin that has typed
audit context but no matching core slot. It landed in
`auditRecordVersion: 8`.

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

interface PluginAuditPayload {
  readonly pluginId: string;   // e.g. "compliance-pharma"
  readonly subKind:  string;   // plugin-defined discriminator
  readonly data:     unknown;  // plugin-defined shape, plugin documents + casts
}
```

Entries land on `AuditableCall.pluginPayloads`. Core consumers switch
exhaustively on the named slots (`familyLock`, `tokenCost`, …). Plugin
consumers narrow on `pluginId`, then `subKind`, before reading `data`.
The plugin owns the shape and version policy of `data`.

## ULID record ids [#ulid-record-ids]

The `recordId` on every `AuditableCall` is a ULID: Crockford Base-32,
26 characters, lex-sortable. It encodes creation time in its high bits,
so cursor pagination via `recordId > cursor` needs no separate
timestamp index.

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

const id = ulid(); // → "01JC8XAEH..."
```

Use this helper for every record id. The lex-cursor reads depend on the
format.

## Tamper-evident hash chain [#tamper-evident-hash-chain]

Each event-log row carries two hash fields, the previous row's hash and
its own, that link it to its predecessor. The chain detects silent
backfill, reorder and removal after the fact, and the verifier reports
the first index where it breaks. `EventLogWriter` and
`createPgEventLogWriter` stamp the fields by default. The field
contract, verifier and back-compat path live on
[Hash chain](/docs/hash-chain).

## Anchoring call rows in the event log [#anchoring-call-rows-in-the-event-log]

The event log is the chained, attested ledger. The call ledger is not,
unless you opt in. `withAuditRecordedAnchor` wraps a ledger so each
newly written call row also writes one `audit.recorded` event into the
event log's hash chain. Nothing in core wraps a ledger by default.

```typescript
import { withAuditRecordedAnchor, verifyCallAnchors } from "@pleach/core/audit";

const anchored = withAuditRecordedAnchor(ledger, {
  eventLogWriter,                       // the session's event-log writer
  tenantId: "acme",                     // must match call.principal.tenantId
  resolveChatId: (call) => chatIdForSession(call.sessionId),
  isAdmitted: () => true,               // event_type CHECK admits audit.recorded
  // sourceId: "pleach-core" (default), onSkip: (reason, call) => …
});
```

The event names the row and carries a `sha256-jcs` call hash of the
`AuditableCall` record as passed to `recordCall`. It has no free-text
field.

Only a row the inner ledger reports as `"written"` is anchored, so a
duplicate or failed insert writes no anchor. A call that isn't anchored
is reported: a `[UXParity:audit-anchor:skipped:<reason>]` probe fires,
`onSkip` runs with the reason, and the verifier lists the row as
missing.

To anchor every call, you provide:

| Configuration                                                                       | `onSkip` reason when it's missing |
| ----------------------------------------------------------------------------------- | --------------------------------- |
| A `resolveChatId` that returns the call's chat id                                   | `no-chat`                         |
| A `tenantId` that matches the calls the ledger records                              | `tenant-mismatch`                 |
| An `event_type` CHECK that admits `audit.recorded`, reported through `isAdmitted()` | `not-admitted`                    |
| A runtime with SHA-256, and records with a JSON form                                | `hash-unavailable`                |
| A reachable event-log writer                                                        | `write-failed`                    |

`verifyCallAnchors({ calls, events, tenantId, chatId? })` cross-checks
rows against anchors:

| Field              | Meaning                                                                 |
| ------------------ | ----------------------------------------------------------------------- |
| `missing`          | A row with no anchor: a deleted anchor, or a call skipped at write time |
| `mismatched`       | A row changed after anchoring                                           |
| `orphans`          | An anchor with no row: the row was deleted                              |
| `duplicateAnchors` | A `record_id` anchored more than once                                   |
| `malformedAnchors` | Anchor events whose envelope can't be read                              |

`ok` is true only when every list is empty. The anchor check doesn't
verify the event-log chain itself, so also run `verifyChainForChat` over
the same events: the chain proves the anchors are intact, and this
proves the rows match them.

Two limits. Calls whose session has no resolvable chat are skipped, so
they show up as `missing`. And no Postgres reader that rebuilds
`AuditableCall` records from the call-row table ships yet, so `calls`
must be the records exactly as written, because an absent key and a
`null` hash differently.

## Verifiers [#verifiers]

| Function                   | Subpath                    | Checks                                                                                  |
| -------------------------- | -------------------------- | --------------------------------------------------------------------------------------- |
| `verifyAuditableCallChain` | `@pleach/core/audit`       | One session's call-row chain, with optional `expectedHead`                              |
| `verifyCallAnchors`        | `@pleach/core/audit`       | Call rows against their `audit.recorded` anchors                                        |
| `verifyChainForChat`       | `@pleach/core/eventLog`    | One chat's event-log chain; see [Hash chain](/docs/hash-chain#verifying-a-chain)        |
| `verifyAuditTrail`         | `@pleach/compliance/audit` | The whole event-log trail from genesis; see [below](#querying--exporting-the-audit-log) |

## Querying + exporting the audit log [#querying--exporting-the-audit-log]

`@pleach/compliance/audit` reads the event log through a duck-typed
`AuditStoreLike`, grades its hash chains, and renders the result to PDF
for an auditor. No ready-made `AuditStoreLike` adapter ships today: you
supply two methods over your own backend. `listRows(filter)` returns
event-log rows matching a filter, honouring its pagination fields, and
`verifyChain(rows, slice)` checks one contiguous run of a single chain.

`verifyAuditTrail` walks the whole trail from genesis and is the only
whole-trail verdict:

```typescript
import { verifyAuditTrail } from "@pleach/compliance/audit";

const trail = await verifyAuditTrail(store, {
  tenantId: "tenant-acme",
  chatId: "chat-123", // omit to walk every chain in the tenant
});

if (trail.chainStatus !== "valid") {
  throw new Error(`Audit trail ${trail.chainStatus}.`);
}
```

`queryAudit` reads one page on an opaque `cursor` and grades it `valid`,
`incomplete` or `tampered`:

```typescript
import { queryAudit } from "@pleach/compliance/audit";

const page = await queryAudit({
  store,
  tenantId: "tenant-acme",
  from: "2026-01-01T00:00:00Z",
  to: "2026-02-01T00:00:00Z",
  limit: 500,
});
// page.chainStatus: "valid" | "incomplete" | "tampered"
// page.chainStatuses: one verdict per chain, keyed by chatId
// page.cursor: pass back as `cursor` for the next page
```

* A page reads `valid` only when it has no cursor and no `from`, holds
  the chain's genesis row, and returns no next `cursor`. Every other
  page caps at `incomplete`.
* An empty result is `incomplete`. Zero rows prove nothing, and a fully
  deleted trail also returns zero rows.
* A tenant-wide page (no `chatId`) mixes several chains. Read
  `chainStatuses` for the per-chain verdict.
* `AuditRow` has `sequenceNumber`, `tenantId`, `chatId`, `eventType`,
  `recordedAt`, `payload`, `rowHash` and `prevRowHash`.

Grading rules, cursor format and known limits live on [Compliance:
proving the audit trail is
intact](/docs/compliance#proving-the-audit-trail-is-intact).

`exportAuditPdf` renders rows into a single PDF with a VALID /
INCOMPLETE / TAMPERED badge. It prints VALID only for a verdict carrying
`verifiedFrom: "genesis-walk"`, which only `verifyAuditTrail` returns:

```typescript
import { verifyAuditTrail, exportAuditPdf } from "@pleach/compliance/audit";

const trail = await verifyAuditTrail(store, { tenantId, chatId });
const pdfBytes = await exportAuditPdf({
  rows: trail.rows,
  metadata: {
    tenantId,
    framework: "soc2",
    chainValid: trail.chainValid,
    chainStatus: trail.chainStatus,
    verifiedFrom: trail.verifiedFrom,
  },
});
```

* `AuditPdfMetadata` requires `tenantId` and `chainValid`. `chainStatus`,
  `verifiedFrom`, `framework`, `title`, `from` / `to` and `notes` are
  optional. Without `chainStatus` and `verifiedFrom`, the badge never
  reads VALID.
* `pdfkit` is an optional peer. Without it, `exportAuditPdf` throws
  `MissingOptionalPeerError("pdfkit")`.
* The renderer is also importable at `@pleach/compliance/audit/exportPdf`.

## Permission ledger [#permission-ledger]

`@pleach/core/audit/permission-ledger` answers questions over permission
decisions: the `permission.granted`, `permission.escalated`,
`permission.denied` and `permission.revoked` rows of the event log. It
reads through two views (decisions and current grants) and issues no
writes. [`pleach audit`](/docs/cli#pleach-audit--read-the-permission-ledger)
is a CLI over this module, and the
[`@pleach/compliance/audit/stores`](/docs/compliance#ready-made-stores-sqlite-and-postgres)
audit stores read through it too.

```typescript
import {
  createPermissionLedger,
  createSqlitePermissionLedgerClient,
} from "@pleach/core/audit/permission-ledger";

const ledger = createPermissionLedger(createSqlitePermissionLedgerClient("./pleach.db"));
try {
  const report = await ledger.verify({ tenantId: "tenant-acme" });
  if (!report.ok) throw new Error("permission ledger failed verification");
} finally {
  await ledger.close();
}
```

| Client                                             | Opens                                                                                                                                                                         |
| -------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `createSqlitePermissionLedgerClient(pathOrHandle)` | A path read-only (`node:sqlite`, else the optional `better-sqlite3`). A handle you pass stays yours, in its own mode                                                          |
| `createPgPermissionLedgerClient(client, options?)` | A `pg` Pool runs each query in a read-only transaction. Any other client needs `ownsSession: true` or `readOnly: false`, or construction throws. Pass `key` for a keyed chain |

| Method                                         | Returns                                                                                                                              |
| ---------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------ |
| `currentGrants(filter?)`                       | Grants in force                                                                                                                      |
| `history(filter?)`                             | Every decision, oldest first. Adds `decisions`, `capability`, `since`, `until` and `limit` to the filter                             |
| `why(resolvedPath, filter?)`                   | `{ path, matches }`: the decisions whose scope covers the path, current grants first. Resolve the path with `resolveAuditPath` first |
| `policy(digestOrPrefix)`                       | One stored policy document, with `digestVerified`                                                                                    |
| `diffPolicy(a, b)`                             | A structured diff of two policy documents                                                                                            |
| `verify(filter?)`                              | A `VerifyReport`: one verdict per chain that carries a decision, plus signatures                                                     |
| `exportBundle(filter?, { includeChainRows? })` | `{ files, manifest, verification }`, the bundle `pleach audit export` writes                                                         |
| `close()`                                      | Closes a handle the client opened                                                                                                    |

Every filter takes `tenantId`, `chainKind`, `chainId` and
`workspaceRealpath`. A question the ledger can't answer throws
`PermissionLedgerError` with a `code`: `views-missing`,
`policy-not-found`, `policy-ambiguous`, `bad-input` or `key-material`.

### What `ok` means [#what-ok-means]

`ChainWalkResult.ok` is stricter than the core `VerifyResult.ok`. It
needs the core walk to pass **and** every chained row to be graded. A
walk that excluded rows (`notVerifiable`) is not `ok`, with
`LEDGER_CHAIN_ROWS_NOT_VERIFIABLE_REASON`. Rows whose payload couldn't
be checked (`payloadNotVerifiable`, `payloadHashNotRederivable`) and
Postgres rows with no sequence number (`unnumberedRowCount`) are
reported and leave `ok` as it is. `headChecked` is `false` on SQLite,
which keeps no committed head.

`verify` adds two rules. A chain with zero chained rows is not `ok`. The
report's `ok` is `false` when no chain matched the filter, when any
chain failed, or when any checked signature failed.

Row signatures are checked only through a `verifyRowSignature` hook in
`createPermissionLedger`'s options. Without one, `signatures.checked` is
`false` with a note and never reads as passed. With one, a change of
signer between two valid rows is a key boundary, not a failure.

### Approver references [#approver-references]

A signed permission row names its approver by an opaque reference
(`hmac-sha256:` plus a salted HMAC under the install's approver key),
not by id. The id is kept in an approver-identity table, which is not
chained. Erasing that row forgets who answered while every signed row
still verifies. Readers show an erased reference as `erased` and an
unreadable identity table as `unavailable`.

| Export                                                  | Does                                                                                                                                                                                                             |
| ------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `loadOrCreateApproverKey(dir, { create? })`             | Reads `<dir>/approver-key`, creating 32 random bytes at mode `0600` when absent. A file that isn't this user's regular file, or is readable by others, is `invalid`. `create: false` only reads                  |
| `createApproverReferencer({ key, identities?, warn? })` | `recorded(approver)` returns the approver with its `id` replaced by the kept reference. With no usable key (at least 32 bytes) it rejects with `ApproverKeyUnavailableError` (`PLEACH_APPROVER_KEY_UNAVAILABLE`) |
| `approverRefOf(key, id)`                                | A new salted reference; two calls never match                                                                                                                                                                    |
| `createPgApproverIdentityStore(client, { tenantId })`   | The approver-identity table on Postgres: `record`, `refFor`, `lookup`, `erase`                                                                                                                                   |
| `eraseApprover(...)`                                    | Erases an approver; see [GDPR erasure](/docs/compliance/gdpr-erasure#erasing-a-permission-approver)                                                                                                              |

Wrap the approver with `recorded()` before you build the grant, so the
row carries the reference. Rows written before a host referenced its
approvers name them in clear and are never rewritten.

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

<Cards>
  <Card title="AuditableCall row" href="/docs/auditable-call-row" description="The row shape this ledger persists — every field and typed payload slot." />

  <Card title="Tamper-evident hash chain" href="/docs/hash-chain" description="The per-row hash link and the verification path." />

  <Card title="Typed records" href="/docs/typed-records" description="The five discriminated payload kinds on the row." />

  <Card title="Observability" href="/docs/observability" description="Read-side wiring — OTel spans, Datadog, Honeycomb, Prometheus — that wraps this ledger." />

  <Card title="Fingerprint" href="/docs/fingerprint" description="The fingerprint that appears on every audit row." />
</Cards>
