# Schema (/docs/schema)



The schema bundle is the canonical persistence layer for the
Supabase and Postgres-backed adapters. It is split into tiers: a
**base** tier that every Postgres-backed runtime needs, and opt-in
**extension** tiers that each back one runtime option. Together they
produce a runtime schema with RLS policies, a shared
`updated_at` trigger, and indexes tuned for the access
patterns the adapters use.

Table and column names are documented with the first published release.

The base tier requires Postgres 15 or later, runs on bare Postgres
with no extensions, and applies by default. In-memory and IndexedDB
adapters need no SQL at all.

Files use `CREATE ... IF NOT EXISTS` and `DROP POLICY IF EXISTS`, so
re-applying is safe. Re-running a tier never drops a table or a
column and never deletes rows.

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

## Layout [#layout]

```
postgres/
├── base/                 ← applied by default
│   ├── manifest.json
│   └── 000_… 006_*.sql
└── extensions/           ← opt-in: --with <name>
    └── <tier>/
        ├── manifest.json
        └── 001_… *.sql
```

Each tier directory has a `manifest.json`:
`{ "description": string, "requires": string[], "after"?: string[] }`.
`requires` names other tiers that must be installed too (`base` is
implicit). `after` only affects order: when a listed tier is also
being installed, it is applied first.

List the tiers your installed version ships, with what each one
requires:

```bash
npx @pleach/core schema --list
```

The tier set grows between releases, so this command is the source of
truth, not this page.

## Applying the bundle [#applying-the-bundle]

```bash
npx @pleach/core schema                               # dry run: base only
npx @pleach/core schema --apply                       # copy base into your migrations dir
npx @pleach/core schema --apply --with team,outbox    # base plus two extensions
npx @pleach/core schema --apply --with all            # every core extension + first-party package schemas
```

* The target defaults to `./supabase/migrations/` if it exists,
  otherwise `./harness-migrations/`. Override it with `--target <dir>`.
* Files are written as `<rank>_<tier>__<original>.sql`. The rank is
  fixed per tier, so one flat directory sorts in apply order.
* Adding tiers later is incremental: run `--apply --with team` into
  the same directory and only the team files are written. A target
  file with identical content is skipped; one with the same name and
  different content is a clash, and `--apply` then exits 3 and writes
  nothing.
* `--with all` adds every core extension plus every first-party
  `@pleach/*` package that declares a schema, such as `@pleach/gateway`.
  It includes `vector-search`, which needs pgvector.
* `npx @pleach/core init` scaffolds the base tier only. Add extensions
  afterwards with `pleach schema --with`.

See [CLI](/docs/cli) for the flags. To apply by hand with `psql`, base
first:

```bash
for f in node_modules/@pleach/core/src/schema/postgres/base/*.sql \
         node_modules/@pleach/core/src/schema/postgres/extensions/team/*.sql; do
  psql "$DATABASE_URL" -v ON_ERROR_STOP=1 -1 -f "$f" || break
done
```

Apply each file inside a transaction. The files contain no `BEGIN` or
`COMMIT` of their own: `psql -1` runs each file as one transaction,
and runners that wrap each file (the Supabase CLI does) need nothing
extra. `-v ON_ERROR_STOP=1` plus `|| break` stops at the first failure
so later tiers never run on top of a failed one.

Everything installs into the `public` schema. The files use
unqualified names, so apply them with `public` first on the search
path.

## The base tier [#the-base-tier]

The base tier holds everything a Postgres-backed runtime needs. It
applies in numbered files, in order.

| Group                | What it holds                                                                                                                                                |
| -------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| Compatibility        | Roles and a stand-in for `auth.uid()`. A guarded no-op on Supabase. It lets the bundle apply on bare Postgres                                                |
| Sessions             | Core session state, a version counter and a message count                                                                                                    |
| Checkpoints          | Snapshot and restore points, one row per checkpoint. `SupabaseSaver` consumes them                                                                           |
| Event log            | The full observable event stream. Append-only and hash-chained per tenant and chain                                                                          |
| Event-log sequencing | The sequence allocator and chain-head functions both event-log writers use (`EventLogWriter`, and `createPgEventLogWriter` with `sequenceAllocator: "auto"`) |
| Call ledger          | The typed per-call audit ledger, with lineage and chain columns (chained by default) and an owner read view                                                  |
| Key/value store      | The store behind `SupabaseStore`                                                                                                                             |

## Extension tiers [#extension-tiers]

Pass the tier name to `--with`.

| Tier               | Backs                                                                          | Holds                                                                                                             | Depends on                                                              |
| ------------------ | ------------------------------------------------------------------------------ | ----------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------- |
| `chat-links`       | A `ChatSessionLink` adapter                                                    | Links from a host chat to a session                                                                               | base                                                                    |
| `compliance`       | `SupabaseComplianceStorage` (deprecated), `SubjectKeyRegistry`                 | Generic audit records, signatures and per-subject keys                                                            | base                                                                    |
| `config-manifest`  | `ConfigManifestSupabaseStore`                                                  | Content-addressed runtime snapshots                                                                               | base                                                                    |
| `errors`           | `ErrorPropagator` and the ErrorChannel Supabase sink                           | Structured errors                                                                                                 | base                                                                    |
| `event-type-check` | A database-enforced event-type vocabulary on the event log                     | A check constraint on the event log                                                                               | base                                                                    |
| `model-registry`   | `refreshModelRegistry` with a Postgres store                                   | A model catalog and its refresh runs                                                                              | base                                                                    |
| `outbox`           | `SupabaseOutbox` (the SyncProtocol durable queue)                              | A durable queue of local changes waiting to sync                                                                  | base                                                                    |
| `permissions`      | The permission ledger (`@pleach/core/audit/permission-ledger`, `pleach audit`) | Workspaces, per-tenant and per-session chains, policies, approval nonces, approver identities, and two read views | base, Postgres 15 or later (`security_invoker` views). Server role only |
| `projections`      | Resumable event-log folds                                                      | Fold checkpoints                                                                                                  | base                                                                    |
| `response-tape`    | `createResponseTapeWriter` (deterministic-replay capture)                      | Captured provider responses                                                                                       | base                                                                    |
| `team`             | `TeamExtensionImpl` (sharing, comments)                                        | Session members and comments                                                                                      | base                                                                    |
| `vector-search`    | `SupabaseStore.search({ query })` with an embedder                             | An embedding column and a search function on the key/value store                                                  | base, pgvector 0.5.0 or later                                           |
| `worm`             | Append-only event log with hold-aware disposal                                 | Legal holds, plus protections on the event log                                                                    | base                                                                    |

Every shipped manifest has an empty `requires`, so no extension needs
another extension. Base applies first, then your chosen extensions in
the rank order the CLI assigns. Within a tier, files apply by number.
`worm` is opt-in (`--with worm`) and is not part of the default apply.

`event-type-check` is off by default. Leave it off if your host
writes its own bare event types: anything outside the core types,
`event.redacted` and `domain.<plugin>.<kind>` is refused with
SQLSTATE `23514`.

## What the tables hold [#what-the-tables-hold]

Table and column names are documented with the first published release. Until then,
this section describes what each group of storage answers.

**Sessions** answer "who owns this session and what state is it in".
Each row carries its owner, an optional organization, a title, a
version for optimistic concurrency, the full session state as JSON,
a message count for sidebar rendering, lifecycle timestamps and a
soft-delete marker. Indexes serve per-owner, per-organization and
recent-activity reads.

**Checkpoints** answer "what did the session look like at this step".
Each row is the whole session state at one step, with an integrity
hash, a pointer to its parent checkpoint and the event-log position
it corresponds to. A time-travel fork records where it came from.
There is no per-channel row, and the session id is text with no
foreign key to the sessions table, because subagent and fork thread
ids are not UUIDs. Pruning an ancestor clears the child's parent
pointer.

**The event log** answers "what happened, in what order". It is an
append-only stream. Order comes from a per-tenant, per-chain sequence
number that the allocator hands out, not from the row key. Each
chained row carries the previous row's hash and its own hash, so a
verifier can check the chain in order. A chat chain uses the chat id
as its chain id. Indexes serve in-order chain reads, per-chat reads,
per-session reads and filtered reads by event type.

**The outbox** answers "which local changes still need to sync". Each
row is one pending change with the local version it produced, the
server version it was made against, a body, an attempt count and the
last error. `append()` upserts on the caller-chosen id, `pending()`
reads in creation order, `markFailed()` bumps the attempts and records
the error, and `markSynced()` deletes the row. Owner access is granted
through the session row.

**Errors** answer "what failed, and where". They are persisted when
`enableErrorPropagation: true` is set on the runtime. A row has the
same shape as `HarnessError` (code, message, recovery hint, cause)
plus the session and turn it fired against. Use it for cross-session
error analytics.

**Chat links** answer "which session does this host chat belong to".
Set them through `SessionRuntimeConfig.chatId`. One chat binds to at
most one session at a time, and the last write wins. The link is
deliberately not a foreign key to the sessions table, so it can be
re-bound after a hard delete. Billing or product analytics can join
the ledger back to a customer-facing chat surface through it.

**Generic audit records** hold events that don't fit the typed
`AuditableCall` shape. `@pleach/compliance` and custom audit hooks
use them for cross-cutting records that don't map to a single LLM
call.

**Session members** answer "who else can see this session". Each row
ties a user to a session with a role (`owner`, `editor` or `viewer`).
`useTeam` presence and the shared-read policies consume it.

**Session comments** hold threaded comments on sessions: replies,
mentions and reactions. The surface is optional, and the runtime
itself doesn't consume it.

**The call ledger** answers "which provider call ran, under which
turn, at what cost". See [AuditableCall row](/docs/auditable-call-row)
for the field-by-field walk and the join patterns. The guarantees:

* Each row has a lexicographically sortable ULID key.
* Each row points at its session, and deleting a session that has audit history is refused. It takes an explicit retention decision.
* The pipeline stage and the actor kind are limited to fixed sets of values.
* A JSON payload carries typed slots such as cache hits and family-lock resolution.

Lineage fields, written by `PostgresProviderDecisionLedger` by
default, answer "which turn spawned this call":

* The spawning user turn of a sub-agent row. Empty on a root row.
* The root turn: a root row's own turn, otherwise the spawning user turn. Group by it to roll up any depth.
* The sub-agent depth: 0 on a root row, never negative.
* The tool whose execution caused the call. Empty when none did.

Chain fields, written on every row unless the ledger runs with
`hashChain: false` (they are empty then), answer "has this row been
altered":

* The position in the per-tenant, per-session chain, counted from 0.
* The predecessor's hash. Row 0 uses a genesis seed.
* The row's own hash: SHA-256, or HMAC-SHA256 when keyed, over the predecessor's hash and the canonical row bytes.

A constraint requires the three chain fields to be all empty or all
set. A unique position per tenant and session is the chain's fork
guard. Partial indexes serve lineage reads.

Every addition is an idempotent `ALTER TABLE … ADD COLUMN IF NOT EXISTS`
(constraints are guarded `DO` blocks), so re-applying the base tier
upgrades an existing install. Until you do, the ledger falls back to
the original column list on SQLSTATE `42703`. See
[AuditableCall row → Postgres columns](/docs/auditable-call-row#postgres-columns).

The owner read view of the call ledger is an allowlist, and none of
the lineage or chain fields are on it.

**Config manifests** are content-addressable snapshots of the runtime
substrate: the plugin set, system prompts, graph node bodies, channel
definitions and post-stage filters active in a session. The primary
key is the snapshot's content hash, so identical substrates share a
row. Event-log rows reference a snapshot through their manifest hash.
See [Config manifest](/docs/config-manifest) for the field walk, the
Merkle hash algorithm, retention, and the query shapes.

## RLS template [#rls-template]

Every table ships the same two-policy template. A service-role policy
gives full access to server-side adapters. Owner-scoped policies let
a signed-in client select, insert, update and delete only the rows it
owns, matched on the row's owner against `auth.uid()`.

Service-role clients bypass RLS by construction. Every owner policy
in the base schema and its extension tiers (errors, team,
compliance, outbox) is `TO authenticated`; the model-registry
catalog read is the only public policy. A client that reads or
writes its own rows must connect as a signed-in user
(`authenticated`) — passing `userId` on the runtime plus a
correctly signed user JWT is what threads the request through.
`anon` and any other role match no owner policy. On plain Postgres
with your own `auth.uid()`, run the per-user client as (or
`SET ROLE`) `authenticated`.

Signed-in users may insert their own session rows (the user-JWT
`SupabaseAdapter` setup relies on this), with any id except the
reserved quickstart audit session id. Mint session ids on the
server anyway, and never treat a client-proposed id as unclaimed.

### Identity columns are pinned after insert [#identity-columns-are-pinned-after-insert]

After INSERT, a client cannot change a session's id, owner or
organization. A `BEFORE UPDATE` trigger on the sessions table, in the
first base file, refuses the change with SQLSTATE `42501` for every
role that row-level security filters. Superusers, `BYPASSRLS` roles,
the table owner (RLS is not forced) and members that inherit
`service_role` are exempt. A host `BEFORE UPDATE` trigger whose name
sorts after it runs after the check, so it must not rewrite those
columns.

<Callout type="warn" title="The organization column is still client-chosen at insert">
  The trigger pins the value after insert. It does not make the value
  trustworthy: the client picks the organization id when it inserts the
  row. Don't use it in an org-scoped policy or an authorization check
  unless the insert path is pinned too, either with server-only session
  inserts or a `BEFORE INSERT` check of the value.
</Callout>

### The quickstart sentinel session [#the-quickstart-sentinel-session]

A reserved session id holds the quickstart's unowned audit rows. No
client can own it, and no owner policy that joins the sessions table
admits it, so a client that holds the row reads none of the rows
other principals filed under it, and writes no outbox, member or
comment row there. One residual remains: the self-select policies key
on the owner alone, so such a client can still read its own comments
and its own membership row under the sentinel.

### Upgrading an existing database [#upgrading-an-existing-database]

A database created from an earlier bundle keeps its old policies and
has no identity-pin trigger. Re-running the tiers picks up most
changes. The release also ships a proposed one-off upgrade SQL file
for the sentinel exclusion and the identity pin. Review it, then run
it in a quiet window: it takes `ACCESS EXCLUSIVE` locks on
the event log and several other tables until it commits.

<Callout type="warn" title="Breaking for clients on another role">
  Earlier bundles left some owner policies without a `TO` clause, so
  they also applied to `anon` and custom roles. A client that reached
  these tables as a role other than `authenticated` now matches no
  owner policy: connect it as `authenticated`. Databases created from
  an earlier bundle keep the old policies until you apply the upgrade
  SQL that ships with the release.
</Callout>

For shared sessions (per the session-members table), the owner
policy widens to "user is owner OR member is the current
user." The bundle ships the simple case; layer your own multi-user
policies on top.

### Multi-tenant policy keyed on the organization column [#multi-tenant-policy-keyed-on-the-organization-column]

When sessions belong to an org rather than a single user, gate
reads on the organization column and the JWT claim that
carries it. Write a select policy that matches the column against
that claim and excludes soft-deleted rows. The same shape works for
every table with an organization column.

Pair this with a JWT signer that stamps the organization id on
every token — Supabase Auth hooks or your own session issuer.

<Callout type="warn" title="Pin the insert path first">
  The organization id is chosen by the client when it inserts a session
  row, so this policy only holds if inserts are server-only or a
  `BEFORE INSERT` check validates the value. See
  [Identity columns are pinned after insert](#identity-columns-are-pinned-after-insert).
</Callout>

## The shared trigger function [#the-shared-trigger-function]

Every table that has an `updated_at` column uses one shared trigger
function that stamps the current time on each update. It is created
once, in the first base file, and reused everywhere. Don't redefine
it in your own migrations — the bundle's version is the one the
adapters expect.

## SQLite schema files [#sqlite-schema-files]

The SQLite store (`createSqliteDurableStore`) ships its DDL as plain SQL files. The `.sql` files are exported under `@pleach/core/schema/sqlite/*.sql`. Each tier directory also ships a `manifest.json`, in the same layout as the Postgres bundle:

```
sqlite/
├── base/                       001 … 004
└── extensions/
    ├── fts/                    001
    └── permissions/            001 … 009
```

| Tier          | Holds                                                                                                          |
| ------------- | -------------------------------------------------------------------------------------------------------------- |
| `base`        | Sessions, checkpoints, the hash-chained event log with its chain identity, and the key/value store             |
| `fts`         | The FTS5 index behind `searchEvents`                                                                           |
| `permissions` | The permission ledger read model, with the same object names and columns as the Postgres tier of the same name |

You do not apply these files yourself. `createSqliteDurableStore` applies `base`, then `fts`, then `permissions` on every open, each file in its own `BEGIN IMMEDIATE` transaction. Every file upgrades a `.db` written by an earlier build in place and never drops a table, a column or a row. `base` and `permissions` must apply. `fts` needs a SQLite build with FTS5; without it the store opens without full-text search.

Read the files when you want to inspect the schema or open the database from another tool.

## Custom columns [#custom-columns]

Adding columns is safe — the adapters serialize/deserialize the
`state` JSONB, not the row schema. To add fields the adapters
read directly (like a custom denormalized last-synced timestamp), use
an additive migration that lands after the bundle and update the
adapter via a custom subclass.

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

<Cards>
  <Card title="CLI" href="/docs/cli" description="`pleach init` for scaffolding the bundle into a target directory." />

  <Card title="Storage" href="/docs/storage" description="The adapters that consume this schema." />

  <Card title="AuditableCall row" href="/docs/auditable-call-row" description="The per-call audit ledger in detail — the field-by-field reference." />

  <Card title="Event log" href="/docs/event-log" description="The event log in detail — `EventLogWriter` and projections." />
</Cards>
