# Event log (/docs/event-log)



The event log records *observable events*: messages sent, tools dispatched, interrupts raised, subagents spawned, exports queued, and domain events from plugins. It records what the session experienced.

It's distinct from the [`AuditableCall` ledger](/docs/audit-ledger), which records the router's per-call decisions (which model fired and why). The two aren't peers for review. The event log is the single compliance-review and attestation boundary, with one hash chain and one verification call. The `AuditableCall` ledger is engineering telemetry, non-authoritative for compliance by design. Any router-side fact a review needs is projected into the event log as a typed row.

Application developers hydrate sessions from the event log, and replay and client-side `/events` folds consume it. See [Audit ledger → Two ledgers, one compliance surface](/docs/audit-ledger#two-ledgers-one-compliance-surface) for the side-by-side, and [Stream events](/docs/stream-events) for the shapes that become rows.

The event log is the persistence layer for the [runtime-lifecycle cluster](/docs/session-lifecycle#the-runtime-lifecycle-cluster). [Session lifecycle](/docs/session-lifecycle) mints and resumes against it, and [Turn lifecycle](/docs/turn-lifecycle) writes one row per observable event during `executeMessage`.

```typescript
import {
  EventLogWriter,
} from "@pleach/core";
import {
  ContentLedger,
  replayContentEvents,
  resolveDomainEventType,
} from "@pleach/core/eventLog";
import type {
  HarnessEvent,
  EventSeverity,
  ActorType,
} from "@pleach/core";
import type { DomainEventTypeConfig } from "@pleach/core/eventLog";
```

## Three layers [#three-layers]

| Layer         | Module              | Concern                                                                   |
| ------------- | ------------------- | ------------------------------------------------------------------------- |
| Write         | `EventLogWriter`    | Enqueue events; fire-and-forget at the call site                          |
| Durable flush | `durableFlush`      | Survive teardown via `waitUntil`; retry on transient failure              |
| Hydration     | `hydrateFromEvents` | Walk events and rebuild interrupt, subagent, export and user-card records |

## The durable type union [#the-durable-type-union]

The writer accepts the registered core event types plus plugin-namespaced `domain.<plugin>.<kind>` rows. The core union is the durable contract. Its runtime value is `HARNESS_EVENT_TYPES`, and the table below lists every member. A shape not listed here and not `domain.*`-namespaced is rejected at the storage constraint. Many high-frequency [stream events](/docs/stream-events) (deltas, progress ticks) are deliberately stream-only.

| Family               | Types                                                                                                                                                       | What it records                                                                                                                                                                     |
| -------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Session              | `session.created/resumed/ended/bound_chat`                                                                                                                  | Lifecycle boundaries and the session-to-chat binding                                                                                                                                |
| Turn / control plane | `turn.started/completed/failed/aborted/parked/continued` · `graph.completed` · `resume.held` · `route.slot_released` · `llm.turn` · `prompt.replay_witness` | One turn's boundaries, parking and continuation, and per-call facts                                                                                                                 |
| Messages / content   | `message.user/assistant` · `content.delta/reset/correction/finalized`                                                                                       | What the user sent and saw                                                                                                                                                          |
| Tools                | `tool.awaiting_approval` · `tool.started/completed/failed/schema_failure` · `tool_offer.snapshot`                                                           | Tool lifecycle and the offered set. A gated call's row is `tool.awaiting_approval` until a decision approves it                                                                     |
| Interrupts           | `interrupt.requested/approved/rejected/edited/timeout/dismissed/record_retired`                                                                             | Approval decisions; `interrupt.edited` writes two rows (operator, then effective arguments)                                                                                         |
| Subagents            | `subagent.spawned/tool_used/completed/failed`                                                                                                               | Delegated-work attribution                                                                                                                                                          |
| Remote jobs          | `job.dispatched/dispatch_failed/completed/failed/timeout`                                                                                                   | Remote job lifecycle                                                                                                                                                                |
| Sandbox              | `sandbox.created/terminated`                                                                                                                                | Sandbox lifecycle                                                                                                                                                                   |
| Checkpoints          | `checkpoint.created/forked/bulk_updated/branched`                                                                                                           | Durable-state lineage                                                                                                                                                               |
| Decisions / outcomes | `continuation.decision` · `guard.decision` · `intent.detected` · `synthesis.outcome` · `answer.sufficiency` · `hallucination.detected`                      | Turn control flow and the fabrication-detection verdict. A `guard.decision` row also records a refused truncated tool call (see [Tools](/docs/tools#truncated-tool-call-arguments)) |
| Safety               | `safety.blocked/flagged/high_risk_combination/precursor_detected`                                                                                           | Safety-policy verdicts                                                                                                                                                              |
| Errors / retries     | `error.propagated/recovered` · `error.code` · `retry.direct/orchestrator/stream_exhausted`                                                                  | Classified failure trail, including `provider-exhausted`                                                                                                                            |
| Cost / model         | `cost.rollup` · `cache.stream_hit` · `synthesize.tool_strip` · `model.reasoning_complete` · `model.upgraded` (deprecated, historical rows only)             | Per-turn cost and model facts                                                                                                                                                       |
| Skills / identity    | `skill.activated/used/created/promoted` · `identity.updated`                                                                                                | What the agent was armed with, used and authored                                                                                                                                    |
| Assets / canvas      | `asset.offloaded/exported/consumed` · `canvas.user_created`                                                                                                 | Artifact and canvas lifecycle                                                                                                                                                       |
| Actions              | `action.export/tool_run/search/window_open`                                                                                                                 | Action-rail interactions                                                                                                                                                            |
| Audit / clock        | `audit.recorded` · `clock.attested/drift_breached/attestation_failed`                                                                                       | The chained audit carrier and host clock attestation                                                                                                                                |

### `session.ended` — a close you can query for [#sessionended--a-close-you-can-query-for]

`session.ended` records a session closing, so a normal close is a positive fact. It's latched: at most one per runtime.

The payload carries the client id and the id of the session it closed, so you can name which leg ended without joining on timestamps.

<Callout type="warn" title="Absence is not evidence of a crash">
  A session whose process dies never writes `session.ended`. The row's
  presence proves a clean close; its absence proves nothing on its own.
  It could be a crash, a still-open session, or a host that never
  disposed the runtime.
</Callout>

### `HARNESS_EVENT_TYPES` — the union as a runtime value [#harness_event_types--the-union-as-a-runtime-value]

`@pleach/core/eventLog` exports the union as a real runtime value, so guards needn't scrape source text:

```typescript
import { HARNESS_EVENT_TYPES } from "@pleach/core/eventLog"
import type { HarnessEventType } from "@pleach/core/eventLog"

HARNESS_EVENT_TYPES.includes(candidate) // sorted, frozen
```

`tsc` rejects a union member missing from the tuple and a tuple key that isn't a union member.

<Callout type="warn" title="Membership means emittable, not persistable">
  A type in `HARNESS_EVENT_TYPES` can still be rejected at the storage
  constraint. A row survives only if its type is in the constraint's core
  list, or is rewritten to `domain.<ns>.<kind>`. Any other type fails the
  CHECK with Postgres `23514`, and the row is lost. The writers log the rejection
  rather than throw, and the pg writer counts it in `flush()`'s
  `checkViolations`.
</Callout>

### `answer.sufficiency` [#answersufficiency]

`answer.sufficiency` records the verdict on whether the delivered answer carried a substantive body. It writes one row per judged message, with the verdict, the judge's reason, the content length and the pending plan-step count. Write it through the exported producer:

```typescript
import {
  emitAnswerSufficiency,
  ANSWER_SUFFICIENCY_REASON_MAX_CHARS,
} from "@pleach/core/eventLog";
import type { AnswerSufficiencyLedger } from "@pleach/core/eventLog";
```

`emitAnswerSufficiency(ledger, verdict)` takes an `AnswerSufficiencyLedger` (`{ writer, chatId }`) and is a silent no-op when the ledger is unwired. The judge's `reason` is truncated to `ANSWER_SUFFICIENCY_REASON_MAX_CHARS` (160).

The model judge is opt-in (`answerSufficiencyJudge: true` on `SessionRuntimeConfig`, `createPleachRoute` or `createPleachAgent`). With it off, only the deterministic backstop applies.

With the judge on, it runs inside the tool loop, not after the turn. It reads a bounded evidence block of the turn's completed tool calls (the last 12, with capped arguments and results) and checks the draft answer against it. The synthesizer waits for the verdict. An insufficient verdict reopens the tool loop once per turn, so the turn still makes one synthesize call. A judge error, a timeout or a skip releases the wait without a verdict.

A resumed turn is judged too. Its verdict row is keyed on the resume's own message id, so a resume answer no longer writes a `no-user-message` skip row over it. A backstop `sufficient: false` still writes its verdict row and still defers the continuation gate's all-success stop by one pass. A pass that neither judge nor backstop ruled on writes no verdict row. The delivery boundary records the turn as a skip row with `skip_reason: "judge-not-enabled"` instead.

When the judge is on and the turn's abort signal fired before a verdict, the skip row carries `skip_reason: "turn-aborted"` and an `abort_reason` naming the abort class. A judge call that resolves after the abort writes no verdict. With the judge off, an aborted turn keeps its earlier reason.

### Engine-grading fields on `graph.completed` and `llm.turn` [#engine-grading-fields-on-graphcompleted-and-llmturn]

These payload fields answer "what did the engine do on this turn, and why" from durable rows alone. They're extensions of existing event types, so they need no storage-constraint change. Values are engine literals only: ids, counts and closed enums. They carry no user, model, tool-argument or provider text. A key is omitted when the engine didn't measure it, and a capped list carries `<list>_total` only when truncated.

| Field                                                                                                                              | What it answers                                                                                                                                                                                                                                                            |
| ---------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `graph_exit.conservation.dark_cause`                                                                                               | Why a node never ran: which subscribed channels were written, and the phase of the first write (`loop`, `latch` or `post-terminal`)                                                                                                                                        |
| `graph_exit.schedule_trace`                                                                                                        | Node dispatch order (capped)                                                                                                                                                                                                                                               |
| `graph_exit.route_arms`                                                                                                            | Each conditional-edge decision (capped)                                                                                                                                                                                                                                    |
| `turn_summary`                                                                                                                     | Model, synthesis and re-dispatch call counts inside the graph run; detached `post_graph` calls aren't counted                                                                                                                                                              |
| `turn_decisions`                                                                                                                   | Operational decisions by id and reason (capped at 20 entries)                                                                                                                                                                                                              |
| `turn_completeness`                                                                                                                | Whether the turn finished its plan, including unrecovered tool failures                                                                                                                                                                                                    |
| `plan_coverage`                                                                                                                    | Whether the plan named the tools the turn used; `plan_origin` is `async-hit`, `crash-fallback`, `in-node`, `other` or `none`                                                                                                                                               |
| `llm.turn` stream timing (`ttfb_ms`, `first_activity_ms`, `no_chunk_ms`, `load_shed_class`: `ttfb`, `midstream`, `both` or `none`) | Stream timing for the decision node's primary stream and the synthesizer stream only                                                                                                                                                                                       |
| `llm.turn` `rung`                                                                                                                  | Present only on a call re-dispatched after a failed call; `pivot_reason` is `garble-retry`, `cascade-in-family`, `cascade-non-matrix`, `cascade-loader-failure`, `guard-halt-hallucination`, `guard-halt-repetition`, `guard-halt-post-model-hook` or `zero-tool-recovery` |
| `llm.turn` `run.model_pivot`                                                                                                       | `"none"` when the runtime forbids model pivots; omitted otherwise                                                                                                                                                                                                          |
| `llm.turn` `post_graph`                                                                                                            | `true` on a model call the graph run doesn't await; omitted otherwise                                                                                                                                                                                                      |

Limits that apply to these fields:

* **`turn_completeness` and `plan_coverage`** are built without a model call. A tool name that isn't name-shaped, or that resolves nowhere, is dropped and counted in `names_dropped`. Every name array holds at most 32 names.
* **`turn_completeness` fields:** `plan_source`, `plan_steps_total`, `plan_steps_completed`, `uncovered_steps`, `awaiting_async` and `unrecovered_tool_failures` are always present. Optional fields include `terminal_arms`, `plan_id`, `plan_choice_timeouts`, `plan_choice_undeliverable`, `asks_count` and `names_dropped`.
* **`plan_coverage` fields:** `plan_source`, `plan_origin`, `planned`, `executed`, `unused_planned`, `unavailable_to_principal` and `known_names_basis` are always present. `plan_id`, `cold_start_outcome`, `requested_late`, `uncovered_planned`, `planned_not_offered` and `names_dropped` are optional. `requested_late` and `planned_not_offered` are absent when the turn-start tool offer wasn't captured, and rows written before `uncovered_planned` existed don't carry it. `asks_count` is written only when the host's `AgentAdapter` implements the optional `countUserAsks(userText)` hook.
* **Stream timing** isn't provider TTFB, and it runs on a different clock from `latency_ms`, so don't subtract one from the other.
* **`rung`** lands on the *next* call's row, never on the failed call's own row. The `cascade-non-matrix` reason appears only under the deprecated `legacyNonMatrixFallback` option, and `cascade-loader-failure` is no longer written.
* **`turn_decisions`** uses a closed vocabulary exported as `TURN_DECISION_VOCABULARY` (with `TURN_DECISION_IDS`, `TOOL_ARG_REPAIR_KINDS` and `PROMPT_BUDGET_COUNT_KEYS`). A host prompt builder reports its evictions through `recordPromptBudgetEviction`. A process without `AsyncLocalStorage` (a browser or edge worker) records a decision only when exactly one turn is in flight, so the list is a floor.
* **`resume-schedule-gate`** entries count gate evaluations, not node runs, so `admitted: 2` can mean the node ran once.
* **`post_graph`** is set by marking a fire-and-forget seam call with `metadata.detachedPostCommit: true` (`SeamInputMetadata`, from `@pleach/core/graph/seams`). Its row usually lands after `graph.completed`, but that isn't guaranteed. Marking a call the graph awaits removes it from `model_call_count`.

```typescript
import { recordPromptBudgetEviction } from "@pleach/core/eventLog";
```

**`resume.held`.** A resume that returns without the synthesizer being admitted writes no `graph.completed`. It writes one `resume.held` row with the message id, a `reason` (`plan-incomplete`, `no-plan` or `aborted`), and the same `turn_summary` and `turn_decisions` keys. A graph error or missing adapter writes neither row. An empty synthesis or a rejected credential writes `graph.completed`. `resume.held` is a new event type: if you install the optional event-type CHECK constraint, re-apply its migration on upgrade, or each `resume.held` row is refused while the rest of the batch lands.

**`route.slot_released`.** When a stopped turn's tool keeps running, an unscoped `createPleachRoute` holds its slot and the message claim until the tool settles, for at most `abandonedWorkSlotTimeoutMs` (default 600000). If that bound passes first, the route releases both and writes one `route.slot_released` row on the session's chat, with `reason: "abandoned-work-timeout"` and `heldMs`. The tool keeps running. A host database with its own event-type constraint must admit the type before the row can be stored.

**`turn.parked` and `turn.continued`.** A parked turn and the continuation that resumes it are durable rows, not only stream events. `turn.parked` records the message id, the segment, the reason (`deadline` or `host`), the next step and the segment's duration. `turn.continued` records the segment it resumed and the step it resumed from. Neither row carries the continuation token. Every segment writes under the same turn id, so these two rows are how you tell which segment a later row belongs to.

**`turn.started`.** The row carries a hash of the runtime configuration, so two turns that ran under different settings are distinguishable from the log alone. A continuation re-entry adds `is_continuation: true`; a fresh turn omits the key. A host that supplies a provenance bag gets it stored too, bounded to 16 keys with boolean, numeric or short string values. Entries that don't fit are dropped and counted.

**`turn.failed`.** The row records the serving provider, the finish reason of the last provider attempt, an error class and a message. Each label is checked before it's stored, and a malformed value is dropped and counted. The message is redacted for secrets and capped at 500 characters. The error class is dropped when redaction would change it, so a host name or key can't land there.

**`graph.completed` lattice violations.** `graph_exit.lattice_violations` lists the forbidden stage transitions the run took, as sorted `from->to` tokens. An empty list means the engine measured and found none. A sanctioned re-fire within a stage is never recorded.

**Context size on `llm.turn`.** `usage.inputTokens` stays the sum billed across every provider request in the call. `context_input_tokens` is the input size of the last request, which is how full the context was. It's omitted when the last request reported no input count.

**`clock.attestation_failed`.** The `reason` is one of `threw`, `rejected`, `timeout`, `invalid-result`, `imprecise` or `persistently-imprecise`. The last two carry the measured error bound and the tolerance it failed to fit. `persistently-imprecise` also carries the length of the imprecise run.

<Callout type="info" title="Not on the audit projection">
  These fields describe engine control flow, not audited decisions. The
  default audit projections don't include them.
</Callout>

### `domain.pleach.turn.stall` [#domainpleachturnstall]

A turn writes one durable `domain.pleach.turn.stall` row the first time it goes 15 seconds without progress. The row records the gap, the last event type, and the model calls and tools still open. A pending interrupt pauses the clock, so a human wait never writes the row. There's at most one row per turn, and an aborted turn never writes one.

## `EventLogWriter` [#eventlogwriter]

Per-runtime writer. Calls return synchronously; the write is enqueued and drained by the durable-flush pipeline.

```typescript
import { EventLogWriter } from "@pleach/core/eventLog";

const writer = new EventLogWriter(supabase);

writer.write({
  type: "message.user",
  chatId,
  actorId: userId,
  actorType: "user",
  payload: { content_preview: "Hello", token_count: 1 },
});
```

Every event needs a `chatId`. `actorId` and `actorType` (`"user"`, `"system"`, `"subagent"` or `"guest"`) sit at the top level of the event. You don't set severity: the writer stamps it from the event type.

### Sequence number stamping (always-on) [#sequence-number-stamping-always-on]

Every `chatId`-bearing row is stamped with a per-chat monotonic sequence number. The column ships in the base schema tier, and there's no opt-out. It carries the canonical ordering that `hydrateFromEvents`, `runtime.events.iterate({ fromSequenceNumber })` and the fold-vs-snapshot equivalence check depend on.

### `chat_id` is required for stamping [#chat_id-is-required-for-stamping]

A write without `event.chatId` skips stamping. The sequence number stays `NULL` and the row is excluded from per-chat folds, so `runtime.events.iterate({ chatId })` never sees it. Substrate writes always set `chatId`; legacy or out-of-band producers may not.

### Previous-row hash and row hash (hash chain) [#previous-row-hash-and-row-hash-hash-chain]

When chain stamping is on (default `true`), the writer stamps each row with the previous row's hash and its own hash. See [Hash chain](/docs/hash-chain) for the verifier surface and proof shape.

`verifyChainForChat` verifies one chat's chain in sequence order. `verifyChainById` verifies any chain by tenant, chain kind and chain id. Both ship in `@pleach/core/eventLog`, and a mismatch surfaces as a tamper-detection signal.

The reader to pass is the store's own `chainReader`. The SQLite `DurableStore` sets it, typed as the `HarnessEventReader` the verifiers take. The in-memory store leaves it `undefined` because its buffer keeps no row hashes, so check for it rather than casting another facet:

```typescript
import { createSqliteDurableStore } from "@pleach/core/store";
import { verifyChainForChat } from "@pleach/core/eventLog";

const store = createSqliteDurableStore("./agent.db");
if (!store.chainReader) throw new Error("this store keeps no hash chain");
const verdict = await verifyChainForChat({ reader: store.chainReader, tenantId: "default", chatId });
// verdict.ok, verdict.verifiedRowCount
```

### What a passing verdict leaves ungraded [#what-a-passing-verdict-leaves-ungraded]

`ok: true` means the links, the row hashes and every payload hash the walk could re-derive match. It doesn't mean every row was graded. Both verifiers report what they couldn't grade in three census fields. Each is absent when there were none, and carries `rowCount`, `firstSequenceNumber` and `lastSequenceNumber`:

| Field                       | `reason`                                            | Rows                                                                                 | Effect on `ok`                          |
| --------------------------- | --------------------------------------------------- | ------------------------------------------------------------------------------------ | --------------------------------------- |
| `notVerifiable`             | `CHAIN_NOT_VERIFIABLE_DIGEST_WIDTH`                 | A stored hash that isn't a 32-byte digest, excluded from the walk                    | None, but a non-zero count is a finding |
| `payloadNotVerifiable`      | `CHAIN_NOT_VERIFIABLE_PAYLOAD_HASH_ABSENT`          | Legacy (v1/v2) chained rows with no payload hash; the link is graded, the body isn't | None                                    |
| `payloadHashNotRederivable` | `CHAIN_NOT_VERIFIABLE_PAYLOAD_HASH_INSERTION_ORDER` | Legacy chained rows whose payload hash a `jsonb` read-back can't re-derive           | None                                    |

A v3 row with no payload hash is refused, not counted. The [permission-ledger reader](/docs/audit-ledger#what-ok-means) is stricter: it fails a chain with any `notVerifiable` rows.

To grade rows one at a time, call `chainRowPayloadDefect(row)`. It returns the reason a chained row's payload doesn't match its payload hash, or `null`. `null` doesn't mean the body was checked: a legacy row not labelled `sha256-jcs`, or read without its payload, also returns `null`.

### Config-manifest hash (config reference, rolling out) [#config-manifest-hash-config-reference-rolling-out]

Each row also carries a reference to the [config manifest](/docs/config-manifest) active when the event fired. Event stream plus manifest is what makes a session offline-replayable. The column is nullable during rollout, so rows written before the manifest substrate stay valid.

Every distinct config-manifest hash in the log should resolve to a manifest row, but no database foreign key enforces it. See [Config manifest](/docs/config-manifest) for the join shapes.

### `HarnessEvent` shape [#harnessevent-shape]

Every event extends a common base. Optional id fields let projections join on whichever entity the event is about.

```typescript
interface BaseEvent {
  chatId:       string;             // load-bearing — events are chat-scoped
  sessionId?:   string;
  actorId?:     string;
  actorType?:   ActorType;
  toolCallId?:  string;
  subagentId?:  string;
  jobId?:       string;
  checkpointId?: string;
  requestId?:   string;
  durationMs?:  number;
}

type HarnessEvent = BaseEvent & {
  type:     string;                 // dot-namespaced, e.g. "tool.completed"
  payload:  Record<string, unknown>;
};

type EventSeverity = "info" | "warning" | "error" | "audit";
type ActorType     = "user" | "system" | "subagent" | "guest";
```

Severity is stamped per event type: interrupts, retries, safety and action-rail events land at `"audit"`, tool and session lifecycle at `"info"`, and failures at `"error"`.

Events carry a client-generated ULID `id`. Durable flush is idempotent on it, so retries don't double-write.

### What a tool row holds [#what-a-tool-row-holds]

By default a `tool.started`, `tool.completed` or `tool.failed` row records the
tool's name, its duration and, on failure, the error. It holds no argument value
and no result.

Set `runtimeQuirks.enrichToolEventPreviewsForReplay: true` to add a bounded
preview. `tool.started` then carries a compact preview of the arguments, and
`tool.completed` carries up to 2,000 characters of the result. A truncation marker records how much was
kept, so a key missing from a cut preview isn't read as missing from the result.
Both previews pass through the scrubbers before they're stored.

The setting is off by default because arguments and results can carry personal
data. Turning it on is a storage and privacy decision. A review that has to show
what a tool returned needs it on before the call runs.

A `tool.failed` row also carries a `failure_class`, one of `fault`, `guard-refusal`, `not-started` or `unclassified`. `not-started` means the producer positively knows the tool was never dispatched, for example because the backend it needs was still starting. It isn't a refusal. A switch over `failure_class` must handle all four. `detectAnomalies` counts `not-started` as an error, so a backend outage stays in error totals. Only `guard-refusal` is excluded.

### Event type conventions [#event-type-conventions]

The runtime emits dot-namespaced types such as `session.created`, `tool.completed` and `interrupt.requested`. Plugins emit `domain.event` stream events, which `resolveDomainEventType` turns into typed rows. Use it so plugin events don't collide with the substrate's reserved type space.

```typescript
const config: DomainEventTypeConfig = {
  prefix: "compliance",
  kinds:  ["redaction.applied", "tamper.evidence.written"],
};

const resolved = resolveDomainEventType(config, "redaction.applied");
// → "compliance.redaction.applied"
```

### `asset.consumed` [#assetconsumed]

Pairs with `asset.offloaded` to make artifact consumption an event-log entry. It's emitted at the consumption call site, and the asset projection flips the matching artifact's `consumed` field to `true`.

```typescript
interface AssetConsumedEvent extends BaseEvent {
  type: "asset.consumed";
  payload: {
    s3_key:           string;   // join key against asset.offloaded
    consumed_at:      string;   // ISO-8601
    by_tool_call_id?: string;   // present when LLM-driven; absent for UI surfaces
    by_surface:
      | "tool-result-injection"
      | "ui-canvas-open"
      | "ui-export"
      | "manifest-recovery";
  };
}
```

`by_surface` records who consumed the asset: an LLM tool call, a user opening the canvas or exporting, or a server-driven manifest recovery. `by_tool_call_id` is the only PII-adjacent field and rides the compliance scrubber's allowlist.

### `asset.offloaded.payload.mime_type` [#assetoffloadedpayloadmime_type]

`AssetOffloadedEvent.payload.mime_type` is a required string, and producers populate it non-empty. An empty string is treated as a regression signal. Rows that predate the field get an extension-derived value at projection read time, with no database backfill.

## `durableFlush` [#durableflush]

Wraps the write queue with retry and `waitUntil`, so teardown on Fluid Compute or Lambda doesn't lose writes.

```typescript
import { setWaitUntilImpl } from "@pleach/core/eventLog";

// In your function handler:
setWaitUntilImpl(ctx.waitUntil.bind(ctx));
```

After registration, every write routes through `waitUntil`, and the platform keeps the function alive until it lands.

### Retry policy [#retry-policy]

* One attempt, then up to three retries with backoff of 100, 300 and 800 ms (four attempts in all).
* Idempotent on event `id`, so re-sends don't double-write.

When all retries fail, the event surfaces as an `error` stream event with code `4001`, and the runtime keeps running. Durable flush is observability, not control flow. The `error` payload includes the dropped event's `id`, so a recovery job can re-derive the row from the audit ledger (if it matches a `ProviderDecisionLedger` write) or from `hydrateFromEvents` against the surrounding slice.

### `flush()` reports durability [#flush-reports-durability]

On the provider-agnostic Postgres writer ([`createPgEventLogWriter`](/docs/storage#durable-event-log-writer)), `write()` never throws, and one row's failure never poisons the write tail. So `flush()` is the only place a caller learns whether events reached the table. It resolves to an `EventLogFlushResult` and never rejects. Check `.ok`:

```typescript
import type { EventLogFlushResult } from "@pleach/core/eventLog";

const result = await writer.flush();
if (!result.ok) {
  report(result.failed, result.errors);
}
```

| Field     | Meaning                                                                              |
| --------- | ------------------------------------------------------------------------------------ |
| `ok`      | `true` iff `failed === 0`. The field to branch on                                    |
| `flushed` | Rows durably inserted in this window                                                 |
| `failed`  | Events that didn't land, including events dropped by the fail-closed scrubber policy |
| `errors`  | The errors behind `failed`, capped at 100: a sample, never a census                  |

Counts cover the window since the previous `flush()` call, so one historical failure doesn't latch `ok` to `false`.

## `hydrateFromEvents` [#hydratefromevents]

Folds an event slice into interrupt, subagent, export and user-card records. It doesn't rebuild messages or job state. Use it to reconstruct what approvals, delegations and exports happened after a restart or from a checkpoint older than the latest event.

```typescript
import { hydrateFromEvents } from "@pleach/core/eventLog";

// rows: EventLogRow[] read from your event store, in sequence order
const state = hydrateFromEvents(rows);

// state.interrupts, state.subagents, state.exports,
// state.userCards, state.eventCount
```

`hydrateFromEvents(rows, options?)` returns `{ interrupts, subagents, exports, userCards, eventCount }`. Pass `options.fromSequenceNumber` to skip rows before a checkpoint's cursor. It applies rows in order, so the same slice gives the same result.

## `ContentLedger` + `replayContentEvents` [#contentledger--replaycontentevents]

For message content (streaming deltas, corrections, truncations), a content-shaped accumulator honors `content.correction` and `stream.truncated` events. It produces the same final message the user saw.

```typescript
import { ContentLedger, replayContentEvents } from "@pleach/core/eventLog";

// One-shot: rebuild the final user-visible content from a stored event slice.
const content = replayContentEvents(events);

// Or drive a ledger directly, then materialize the committed view.
const ledger = new ContentLedger();
const finalContent = ledger.materialize().content; // → final message content
```

Use it when a UI cache is out of sync with the event stream: re-derive instead of refetch.

## Projections [#projections]

A projection is a deterministic fold over an event slice. The package ships nine built-in projections plus a composite session-state reconstructor:

| Projection                | Returns                  | Use                                                                        |
| ------------------------- | ------------------------ | -------------------------------------------------------------------------- |
| `interruptProjection`     | `InterruptAccumulator`   | Outstanding approvals queue                                                |
| `subagentProjection`      | `SubagentAccumulator`    | Subagent tree per turn                                                     |
| `exportProjection`        | Export queue accumulator | Action-rail exports awaiting completion                                    |
| `userCardProjection`      | User-card accumulator    | `canvas.user_created` rows folded into canvas state                        |
| `configProjection`        | Per-chat config snapshot | Resolved session config at any point in the slice                          |
| `messageProjection`       | Final committed messages | Folds `content.delta`, correction and truncation rows                      |
| `toolCallProjection`      | Tool-call accumulator    | Pending and completed tool calls per turn                                  |
| `jobProjection`           | Job accumulator          | Async job lifecycle (`createJobProjection` factory for per-host resolvers) |
| `artifactProjection`      | Artifact accumulator     | `asset.offloaded` and `asset.consumed` folded into artifact state          |
| `reconstructSessionState` | Composite session state  | Single-call hydrator that runs all projections above                       |

```typescript
import {
  interruptProjection,
  toInterruptArray,
  subagentProjection,
  toSubagentArray,
} from "@pleach/core/eventLog";

const interruptAcc = events.reduce(interruptProjection.reduce, interruptProjection.initial());
const interrupts   = toInterruptArray(interruptProjection.finalize?.(interruptAcc) ?? interruptAcc);

const subagentAcc = events.reduce(subagentProjection.reduce, subagentProjection.initial());
const subagents   = toSubagentArray(subagentProjection.finalize?.(subagentAcc) ?? subagentAcc);
```

Projections are pure: the same input slice gives the same output. Build your own for domain views; the contract is `GraphProjection<T>`: `{ name, initial, reduce, finalize? }`.

`interruptProjection` is the canonical example. A requested interrupt becomes `pending`. Approved, rejected and edited rows set its `resolution` to that verdict. A timeout row sets it to `timeout`, or to `released` when a policy released the gate before any window expired (`client_detached`, `bridge_capacity_evicted`, `owner_unresolved`). A policy decision clears `resolvedBy`, because no person resolved it. `toInterruptArray(acc)` returns entries ordered by `requestedAt`, so the approval queue is safe to re-derive on every render.

## Reading events — the `runtime.events` facet [#reading-events--the-runtimeevents-facet]

Reads go through the `runtime.events` facet, backed by a `HarnessEventLogReader` the host supplies via `SessionRuntimeConfig.eventReader`. Both `DurableStore` bindings in `@pleach/core/store` supply one as their `eventReader` member. For any other store (Supabase, Postgres, an HTTP API), cast it into the `iterate` shape.

```typescript
import type { HarnessEventLogReader, EventLogRow } from "@pleach/core/eventLog";

// Walk rows for a chat, optionally from a sequence cursor.
async function recentRows(
  reader: HarnessEventLogReader,
  chatId: string,
): Promise<EventLogRow[]> {
  const rows: EventLogRow[] = [];
  for await (const row of reader.iterate({ chatId, fromSequenceNumber: 0 })) {
    rows.push(row);
  }
  return rows;
}
```

| Surface                                                         | Returns                      | Use                                                   |
| --------------------------------------------------------------- | ---------------------------- | ----------------------------------------------------- |
| `runtime.events.iterate(filter)`                                | `AsyncIterable<EventLogRow>` | Walk a chat's rows (server-side, service-role)        |
| `runtime.events.fold(projection, filter)`                       | `ProjectionResult<T>`        | Fold rows into typed state via a `GraphProjection<T>` |
| `queryHarnessEvents` / `getAllChatEvents` / `countEventsByType` | rows / counts                | Direct read helpers from `@pleach/core/eventLog`      |

## Projections — folding rows into state [#projections--folding-rows-into-state]

The canonical read surface is the `runtime.events` facet:

```typescript
for await (const row of runtime.events.iterate({ chatId, fromSequenceNumber: lastSeen })) {
  // ...
}

const result = await runtime.events.fold(interruptProjection, { chatId });
// result.state, result.rowsProcessed, result.projection (name)
```

`iterate` is a paginated async iterable, and `fold` applies a projection over it. Both are server-side only and require a Supabase service-role client. For a custom-projection write-up, see [Event log projections](/docs/event-log-projections).

## `EventLogRow` (read shape) [#eventlogrow-read-shape]

What `hydrateFromEvents` walks. Snake-cased, matching the column names you query.

```typescript
interface EventLogRow {
  id:             string;                       // ULID, primary key
  session_id:     string | null;
  event_type:     string;
  actor_id:       string | null;
  actor_type:     string;
  tool_call_id:   string | null;
  subagent_id:    string | null;
  job_id:         string | null;
  checkpoint_id:  string | null;
  request_id:     string | null;
  payload:        Record<string, unknown>;
  duration_ms:    number | null;
  severity:       string;
  created_at:     string;
  domain?:        string | null;                // plugin namespace, when domain.* row
  kind?:          string | null;                // plugin event kind, when domain.* row
}
```

Plugin-namespaced rows populate `domain` and `kind`; core rows leave both `null`. `hydrateFromEvents` flattens both shapes.

## Schema [#schema]

The event log persists to its own append-only table in the base schema bundle, ULID-keyed. RLS templates ship in the file, and production deployments using a service-role client bypass them. See [Schema](/docs/schema) for columns, indexes and RLS.

Durability is the storage adapter's job. On the quickstart path (`createPleachRoute`), the runtime writes the `message.user`, `message.assistant` and `tool.*` rows on turn finalization, so message and tool restoration work out of the box, **provided a durable storage adapter is configured**. The default in-memory adapter keeps these rows in the process heap only. They survive in-process resume but are lost on restart and absent on a fresh serverless instance. Wire a durable adapter (Supabase, Postgres or Redis) for the event log to outlive the process.

### `message.assistant` `payload.cost_rollup` [#messageassistant-payloadcost_rollup]

On the quickstart path, the `message.assistant` row also carries `payload.cost_rollup`, a snapshot of the turn's [cost rollup across sub-agents](/docs/subagents#cost-attribution) taken when the row is written.

```typescript
payload.cost_rollup = {
  // the root turn key, "turn:<userMsgId>", is the rollup's join key
  snapshot:      true,
  as_of:         "2026-10-06T12:00:00.000Z", // ISO time the snapshot was taken
  self:          TurnCostBucket,   // the root runtime's own calls
  descendants:   TurnCostBucket,   // every sub-agent call under the turn
  total:         TurnCostBucket,   // self + descendants
  partial:       boolean,          // any unpriced call, or truncated
  truncated:     boolean,          // rows before a release or eviction are missing
};
```

The root turn key isn't the row's turn id. The route stamps its own turn id on the row, so the rollup key is carried separately for joins to a sub-agent's `parentTurnId` and to `runtime.getTurnCostRollup()`.

The snapshot is a lower bound, valid as of `as_of`. A late `spawn()` child or a post-turn writer can record rows after it, so `partial: false` means only that nothing was unpriced or truncated at that moment. Re-read `getTurnCostRollup()` for a later figure. The field is omitted when no cost row was attributed to the turn, and it holds counts and ids only.

## `content.delta` streaming chunks [#contentdelta-streaming-chunks]

`content.delta` is the canonical streaming-chunk event type, with one row per token or chunk. A producer-side capture helper exists for hosts that want to record the chunk stream without wiring it by hand. `messageProjection` folds a turn's deltas into the final committed message. See [Stream events](/docs/stream-events) for the wire shape and [Event log projections](/docs/event-log-projections) for the fold.

## `InterruptManager` terminal writes and host-plugin job events [#interruptmanager-terminal-writes-and-host-plugin-job-events]

When the interrupt manager resolves an interrupt (approve, deny or edit), it writes a terminal event-log row. Replay tools use that row as the boundary for the interrupt.

Host plugins contribute job-lifecycle types under their own `domain.<plugin>.*` namespace, such as `domain.<plugin>.job.timeout` and `domain.<plugin>.job.completed`. Substrate code never writes under a host plugin's namespace. See [Interrupts](/docs/interrupts) and the [Plugin contract](/docs/plugin-contract).

## Authoring a custom projection [#authoring-a-custom-projection]

The bundled projections cover common reads. For domain reads (a per-tenant retry-rate dashboard, a citation-source histogram, a refund-event audit), author against `GraphProjection<T>`.

```typescript
import type { GraphProjection, EventLogRow } from "@pleach/core/eventLog"

interface RetryCount {
  total: number
  byTool: Record<string, number>
}

export const retryCountProjection: GraphProjection<RetryCount> = {
  name: "retry-count",
  initial: () => ({ total: 0, byTool: {} }),
  reduce: (acc, row: EventLogRow) => {
    if (row.event_type !== "tool.retried") return acc
    const toolName = row.payload?.toolName as string | undefined
    if (!toolName) return acc
    return {
      total: acc.total + 1,
      byTool: { ...acc.byTool, [toolName]: (acc.byTool[toolName] ?? 0) + 1 },
    }
  },
  // Optional finalize — runs once after all rows are consumed.
}
```

Every projection must be:

* **Pure.** Same rows, same output. No wall-clock reads, RNG or network calls. That's what makes projections replay-safe.
* **Order-preserving.** The reducer processes rows in the caller's order, by `chat_id` then sequence number, or `(created_at, id)`.
* **Total.** Unknown `event_type` values are no-ops, not throws, so projections don't break on rows from a newer schema version.

Return the same `acc` reference when no change applies. See the bundled `messageProjection`, `toolCallProjection` and `jobProjection` for full exemplars.

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

<Cards>
  <Card title="Schema" href="/docs/schema" description="What the event log table looks like — columns, indexes, RLS." />

  <Card title="Stream events" href="/docs/stream-events" description="The shapes the stream emits become event log entries." />

  <Card title="AuditableCall row" href="/docs/auditable-call-row" description="The other write stream — load-bearing decisions instead of observable events." />
</Cards>
