# Config manifest (/docs/config-manifest)



The config manifest records *which substrate ran*. A
[fingerprint](/docs/fingerprint) binds a turn's inputs to a hash;
the manifest binds the substrate that processed them — the plugin
set, the system prompts, the graph node bodies, the channel
definitions, the post-stage filters. One row per distinct
substrate, content-addressable, written to the config-manifest table.

Every [event-log](/docs/event-log) row carries a manifest hash
as a foreign reference to that row. So a full replay of any historical
session needs exactly two things: the event stream and the
manifest hash that was active when each event fired. That tuple is
self-contained — no live runtime, no ambient git HEAD, no
deploy-record lookup.

<StatusBadge status="in-flight">
  substrate contract locked · rolling out
</StatusBadge>

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

<Callout title="Rolling out additively">
  The config-manifest table and the
  manifest-hash column on the event log land as additive schema
  files. The column is nullable during rollout so rows written
  before the manifest substrate stay valid. Existing sessions keep
  working; new sessions stamp the reference. The cutover to a
  required column is a follow-up migration after every write path
  stamps the hash. See [Schema](/docs/schema) for the bundle file.
</Callout>

## Why it exists [#why-it-exists]

[Determinism](/docs/determinism) says a turn replays from its record
without drift against the same package version and the same input.
"Same package version" is the load-bearing phrase — but a
deployment's *effective* substrate is more than the npm version. It
includes the plugins you registered, the prompt templates you
shipped, the graph nodes your build composed, the channels and
filters in play. Two deployments on the same `@pleach/core`
version can run different substrates.

The fingerprint doesn't capture that. It binds the turn input. The
manifest captures the rest, so the replay contract becomes precise:
&#x2A;*same manifest, same input, same output.**

## The five surfaces [#the-five-surfaces]

The manifest is a snapshot of five substrate axes. Each is
content-hashed independently, then rolled up into one top-level
hash.

| Surface  | Snapshot field   | What it captures                                                   |
| -------- | ---------------- | ------------------------------------------------------------------ |
| Plugins  | Plugin snapshot  | The registered plugin set and the hooks each contributes           |
| Prompts  | Prompt snapshot  | The system-prompt facets and templates in effect                   |
| Nodes    | Node snapshot    | The graph node bodies (by content hash) and their stage assignment |
| Channels | Channel snapshot | The channel (state) definitions and their reducers                 |
| Filters  | Filter snapshot  | The post-stage filter declarations                                 |

Each surface gets its own child hash. Per-surface hashes are what make the manifest
dedup well: in a multi-tenant deployment most tenants load the
same plugin set, so the plugin snapshot is shared across
their manifest rows even when their prompts differ.

<Callout type="warn">
  **Current coverage is partial.** In the shipped cut, only the plugin
  surface carries real content. The prompt, channel, and filter builders
  return empty, and every node `bodyHash` is a 64-zero placeholder — so
  prompt/channel/filter/node drift is *not* hash-captured yet. The
  runtime warns once per process (`[ConfigManifest] Manifest content is
  partial`) when it writes a partial manifest. The table shape and write
  site are stable; the remaining surface content lands in a later slice.
  Treat manifest equality as "same plugin set," not "same substrate,"
  until then.
</Callout>

## The table [#the-table]

Manifests live in their own config-manifest table. Each row holds:

* the top-level manifest hash, which is the primary key (the Merkle roll-up);
* one child hash for each of the five surfaces;
* one full JSONB snapshot for each of the five surfaces, not a delta;
* a count of live event references;
* a creation timestamp and the tenant (default `default`).

The primary key is the content hash, so two sessions that ran the
same substrate write the same row — the insert is
`ON CONFLICT DO NOTHING`. Each per-surface hash gets its own index
for the cross-tenant query shapes below, plus a tenant index
for per-tenant scans.

Row-level security ships the same two-policy template as the rest
of the [schema bundle](/docs/schema#rls-template): a service-role
bypass for server-side adapters, and a tenant-isolation policy that matches the row's tenant to the current tenant for scoped clients.

### Foreign reference on the event log [#foreign-reference-on-the-event-log]

The event log gains a nullable manifest-hash column. It references the
config-manifest table, is indexed, and uses `ON DELETE SET NULL` and a
deferrable, initially deferred constraint.

The event log carries only the *top-level* manifest hash; the
per-surface child hashes live on the manifest row, reached by
joining. The column is a real foreign key, but two clauses keep it
cheap and rollout-safe:

* **`DEFERRABLE INITIALLY DEFERRED`** is load-bearing. A session
  writes its manifest fire-and-forget and writes its first event in
  the same transaction; deferring the constraint to commit time lets
  those two writes race without a transient FK violation.
* **`ON DELETE SET NULL`** means a retention GC that drops a manifest
  nulls the reference rather than cascading a delete into the audit
  trail — the event survives, it just loses its substrate pointer.

The constraint is nullable during rollout so rows written before the
manifest substrate stay valid.

## The hash [#the-hash]

Each surface is serialized to canonical JSON
([RFC 8785](https://www.rfc-editor.org/rfc/rfc8785) — sorted keys,
no insignificant whitespace) and hashed with SHA-256. The
top-level hash is a Merkle roll-up over the five child hashes,
ordered, with a versioned prefix:

```
manifestHash = sha256_hex(
  "pleach.manifest.v1" ␟
  "plugin:"  ␟ pluginHash  ␟
  "prompt:"  ␟ promptHash  ␟
  "node:"    ␟ nodeHash    ␟
  "channel:" ␟ channelHash ␟
  "filter:"  ␟ filterHash
)
```

`␟` is the ASCII unit separator (`0x1F`). This mirrors the
[hash chain](/docs/hash-chain)'s canonicalization —
same separator, same versioned-prefix discipline, same hex output
shape. The version prefix lets a future schema add a sixth surface
without colliding with `v1` manifests.

The manifest builder is a pure function of its inputs — no
`Date.now()`, no environment reads — so the same substrate always
produces the same hash. Each of the five child hashes is stable on
its own, so a change points at the surface that moved, not at
"something in the manifest moved."

## Reproducing and verifying a hash [#reproducing-and-verifying-a-hash]

The hash functions are exported from the `@pleach/core/manifest`
subpath, so a consumer can recompute a manifest hash independently —
read a persisted `ConfigManifest` back, revalidate its shape, and
recompute the roll-up to confirm the row wasn't tampered with.

```typescript
import {
  computeConfigManifestHash,   // the top-level Merkle roll-up
  computePluginManifestHash,   // the five per-surface child hashers
  computePromptManifestHash,
  computeNodeManifestHash,
  computeChannelManifestHash,
  computeFilterManifestHash,
  validateConfigManifestShape, // parse unknown → ConfigManifest (throws on drift)
  isConfigManifest,            // boolean predicate form
  ConfigManifestValidationError,
} from "@pleach/core/manifest";
```

The verify flow is: read the row as `unknown`, validate its shape, then
recompute — a mismatch means the stored hash and the stored surfaces
disagree.

```typescript
const row: unknown = await store.get(manifestHash);
const manifest = validateConfigManifestShape(row); // throws ConfigManifestValidationError on drift
const recomputed = computeConfigManifestHash(manifest);

if (recomputed !== manifest.manifestHash) {
  throw new Error("config manifest tampered — recomputed hash mismatch");
}
```

Each per-surface hasher recomputes one child hash in isolation, so a
mismatch localizes to the surface that moved (plugin, prompt, …) rather than the top-level roll-up alone.

`ConfigManifestMemoryStore` is the in-process store for tests and the
`pleach dev` harness — inject it via `SessionRuntimeConfig.configManifestStore`
to exercise the full provenance shape with no durable backend:

```typescript
import { ConfigManifestMemoryStore } from "@pleach/core/manifest";

const configManifestStore = new ConfigManifestMemoryStore();
const runtime = new SessionRuntime({ configManifestStore, userId });
```

<Callout type="info">
  The manifest **builder** functions (`buildConfigManifest` /
  `buildAndWriteConfigManifest`) that construct a manifest from a live
  substrate are not re-exported from a published subpath today — only the
  reproduce/verify helpers above are. The runtime writes the manifest for
  you at session construction; you recompute and verify it with the
  functions listed here.
</Callout>

## Querying [#querying]

The manifest turns three audit questions into index-backed
queries.

**Replay by config** — every event under the substrate active in a
session:

Ask the event log for every event with a given manifest hash.

**Cross-tenant audit by plugin set** — every event across all
sessions that ran with a given plugin set, regardless of prompt,
node, channel, or filter drift:

Join events to manifests and filter on the plugin child hash.

**Substrate reconstruction** — the full substrate behind a single
event, all five surfaces returned as JSONB:

Join one event to its manifest and read the five surface snapshots.

A manifest lookup is a primary-key hit, so JOIN cost is dominated
by the event-log scan, not the manifest cardinality. A typical
incident window of a thousand events references only a handful of
distinct manifests.

## Recording who approved a change [#recording-who-approved-a-change]

A change record links a manifest hash to the commit that produced it and to
the people who approved that commit. It is one `config.change_approved` row
on the tenant's audit chain, so an examiner can walk from any model call to
the approval:

```text
model-call row → configManifestHash → change record → commit → approvals
```

Print the hash your configuration produces, then record the change:

```bash
npx @pleach/core manifest hash --module ./pleach.runtime.config.mjs

npx @pleach/core audit record-change \
  --manifest-hash <hash> --commit <sha> \
  --approver <login>[=<iso time>] [--approver ...] \
  --source forge:github|forge:gitlab|native \
  [--approvals-digest sha256:<hex>] [--external system:id] \
  [--test-report-hash <sha256>] [--tenant <id>] [--db <pleach.db>]
```

* **`manifest hash`** builds the runtime from the module's default export and
  prints the hash every event row carries. It writes nothing. It also
  executes the module, so the module must have no side effects and need no
  secrets.
* **Approvers** are stored as erasable `hmac-sha256:` references, never
  logins. Erasing the mapping leaves the chained row verifiable.
* **A forge record needs `--approvals-digest`.** A native record is refused
  with it, since it carries no forge evidence.
* **The approvals digest** commits to the forge's approvals response as CI
  read it at merge. `npx @pleach/core audit digest <file>` computes it; keep
  the file as long as the record.
* **The PR or MR reference** sits outside the chain hash, so it can move
  after a forge migration. Its digest is chained.
  `npx @pleach/core audit relink-change --change-id <id> --external system:id`
  chains a `config.change_relinked` row for each move.
* **A change made outside a forge** uses the same command with
  `--source native` and the approvers given by hand.

Find the change behind any row with
`npx @pleach/core audit changes <manifest-hash> --tenant <id>`. Each result
reports whether its chain verified, and whether the stored reference still
matches the chained digest. A Postgres host calls `recordChangeApproval()`
from `@pleach/core/audit` with its own event-log writer. The CLI writes to
SQLite.

## Full snapshots, not deltas [#full-snapshots-not-deltas]

Each row stores the complete substrate, not a diff against a prior
manifest. The storage cost is small — content-addressing dedups
identical substrates, and per-surface hashes dedup the shared
parts — and the payoff is that replay reads one row. A delta
encoding would force the replay tool to walk a parent chain, which
breaks the moment retention drops a parent, and it would turn the
round-trip audit into a multi-step materialization. One row per
manifest keeps replay offline-able.

### The value is version-prefixed — parse it, never compare it [#the-value-is-version-prefixed--parse-it-never-compare-it]

`manifestHash` is `pleach.manifest.v<N>:<64-hex>` on the wire, not a
bare `<64-hex>`. The schema version is already an input to the roll-up
digest, so the same config hashes differently under different schema
versions, and a bare value gave a reader no way to tell which schema
produced it.

```typescript
import { parseConfigManifestHash } from "@pleach/core/manifest"

const { version, hex } = parseConfigManifestHash(manifest.manifestHash)
```

The schema is at **v4**. Don't hardcode a version in a matcher.

Without the prefix, the first schema bump would make every prior
recording compare unequal, and `detectReplayConfigManifestMismatch`
would report a config drift that never happened on every replay of a
pre-bump turn. It parses rather than string-compares, and treats
differing schema versions as **not comparable** rather than as drift.

It is self-migrating: a value with no prefix is unambiguously v1 — the
only version that ever shipped bare — and the `<hex>` half is unchanged
for a given config, so pre-prefix and post-prefix records of the same
config still compare equal once parsed.

<Callout type="warn" title="One accepted consequence across the upgrade">
  The manifest hash is the text primary key of the config-manifest table, so a
  single config can key two rows across the upgrade — the bare one written
  before, the prefixed one after — splitting the reference count between
  them. That is one duplicate row per distinct config, not a correctness
  break: retention GC deletes only when the reference count is zero, so the fork
  does not make the older row collectable.
</Callout>

## Retention [#retention]

Manifests are reference-counted against the event log: a manifest
survives as long as any event references it. The default floor is
**forever** — the compliance posture is "keep the audit trail,"
not "expire it." Cost-sensitive tenants can opt into a per-tenant
retention floor (planned) that drops manifests older than *N* days
*and* referenced by no surviving event.

This couples manifest retention to whatever event-log retention
you run, automatically:

| Event-log retention | Manifest retention                                            |
| ------------------- | ------------------------------------------------------------- |
| Forever             | Forever                                                       |
| *N*-day TTL         | Manifest drops within a GC pass of the last referencing event |
| Per-tenant policy   | Manifest follows per tenant                                   |

### `runRetentionGC` fails closed [#runretentiongc-fails-closed]

The reference count has been measured wrong in both directions — two
manifests holding 306 live event references sat at zero, and three with
counts of 11, 18, and 1 had none. Deleting a referenced manifest
destroys the config attribution of every event row pointing at it.

So `runRetentionGC` takes an optional `isReferenced` probe. Returning
`true` skips the row, and a probe that **throws** is also treated as
referenced: an unanswerable "is this still referenced?" must never
authorise an irreversible delete.

Two result fields report what happened:
`skippedStillReferencedCount` is a direct measurement of counter drift,
and `unverifiedRetiredCount` counts deletes made on the raw counter
alone — announced once rather than left implicit.

Existing callers are unchanged and still delete. The probe strictly
narrows what can be removed; it never widens it.

## One snapshot per session [#one-snapshot-per-session]

The manifest is captured once, at session construction — never
mid-stream. The content-addressable contract requires a stable
snapshot, so a config change mid-session is out of scope: the
session represents the substrate it started with. Mutating
manifest-relevant state mid-session is the kind of thing the
replayability contract is designed to forbid, not silently absorb.

## Where it sits in the replay story [#where-it-sits-in-the-replay-story]

**Two hashes, one row: inputs and substrate are bound separately.**

<Mermaid
  chart="flowchart LR
    Input([turn input]) --> FP[computeFingerprint]
    Substrate([plugins · prompts · nodes · channels · filters]) --> Manifest[manifest hash]
    FP --> Event[(event-log row)]
    Manifest --> Event
    Event --> Replay[offline replay]"
/>

The fingerprint binds the inputs; the manifest binds the
substrate; the event-log row carries both. Replay reads the
stream, dereferences each manifest hash, reconstructs the
substrate, and re-runs the events against it. Same manifest, same
input, same output.

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

<Cards>
  <Card title="Schema" href="/docs/schema" description="The schema bundle this table lands in, and the RLS template it shares." />

  <Card title="Event log" href="/docs/event-log" description="The stream whose rows carry the manifest hash reference." />

  <Card title="Determinism" href="/docs/determinism" description="The replay contract the manifest completes — same manifest, same input, same output." />

  <Card title="Fingerprint" href="/docs/fingerprint" description="The input-binding half; the manifest is the substrate-binding half." />
</Cards>
