Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

Add the design plan for an optional Rust storage engine, with shadow mode, an opt-in swap and an engine benchmark (#9593)

Garry Tan538b872c95be
diff --git a/README.md b/README.md
index c305d4fd12..e2c1123728 100644
--- a/README.md
+++ b/README.md
@@ -390,6 +390,7 @@ Start with `gbrain doctor`. For database access failures, use `gbrain engine sta
- [MCP task guide](docs/mcp/README.md) — deployment and per-client setup (Claude Desktop, Code, Cursor, ChatGPT, Perplexity, Cowork)
- [MCP administration](docs/mcp/ADMIN.md) — owner dashboard access, client registration, OAuth, permissions, and token recovery
- [Evals](docs/eval/) and [research](docs/research/) — methods and results
+- [Rust engine plan](docs/designs/RUST_ENGINE.md) — proposed design for a third storage engine, not built yet; its [research maps](docs/designs/rust-engine/research/README.md) and [review record](docs/designs/rust-engine/review-record.md)
- [`docs/ethos/`](docs/ethos/) — philosophy (thin harness, fat skills, markdown as recipes, origin story)
- [`AGENTS.md`](AGENTS.md) — entry point for non-Claude agents
- [`CLAUDE.md`](CLAUDE.md) — entry point for Claude Code (deep operating context)
diff --git a/changelog.d/rust-engine-engine-plan.md b/changelog.d/rust-engine-engine-plan.md
new file mode 100644
index 0000000000..96e7f299be
--- /dev/null
+++ b/changelog.d/rust-engine-engine-plan.md
@@ -0,0 +1,5 @@
+**A design plan for an optional Rust storage engine is now in the docs; no code ships and nothing changes for any brain.**
+
+### Added
+- `docs/designs/RUST_ENGINE.md`: the plan for a third storage engine, written in Rust, behind the same engine contract as PGLite and Postgres. It covers the parity tests and gbrain-evals bake-off, a shadow mode that runs Rust beside an existing brain and generates a head-to-head report, an opt-in swap with a way back, and a public engine benchmark in gbrain-evals. It sets the bar that the Rust engine must be equal or better than both Postgres and PGLite on every measured axis, including concurrent writes, graph traversal, vector search and memory. The target is 10x better than Postgres and pgvector, and equal or better is the gate to ship. The Rust engine has no SQL dialect and serves typed engine methods only. It refuses raw SQL. It does not copy PGLite's locking. It has no whole-brain lock and no busy error, and a second process can always read and write. Each lock and queue call site becomes a typed engine operation with a stated guarantee and a concurrency test. The embedded engine comes first and is built so it can later serve many users. A full multi-user Rust server that replaces Postgres and pgvector is the end state. The new section "Path to a multi-user server" lists those later phases, and each one needs the maintainer's approval before it starts. Until that server passes the same bar, brains with writers on more than one machine stay on Postgres. Every switch it names ships off.
+- `docs/designs/rust-engine/research/`: twelve read-only maps of the current code that the plan cites, and `docs/designs/rust-engine/review-record.md`: the review record for the plan.
diff --git a/docs/designs/RUST_ENGINE.md b/docs/designs/RUST_ENGINE.md
new file mode 100644
index 0000000000..a4307787b7
--- /dev/null
+++ b/docs/designs/RUST_ENGINE.md
@@ -0,0 +1,777 @@
+# Rust engine: a third storage engine behind BrainEngine
+
+Status: design only, no production change. Every switch named here ships off, and nothing changes on upgrade. The maintainer approved this plan on 2026-11-16 by taking every recommendation at the final review gate; "Approval record" under the decisions lists what that covers. Each later PR that adds a setting, migration, error code, default or MCP operation still quotes the maintainer's yes for that item.
+Citation convention: repo-relative paths on master 9f1d54232d (v0.60.733.0). The research maps in [rust-engine/research/](rust-engine/research/README.md) were written against 36bd05806a, five commits earlier, and their line numbers refer to that commit. They are cited as `research/NN` (for example `research/01` is `docs/designs/rust-engine/research/01-engine-interface.md`). gbrain-evals paths are cited as `gbrain-evals:<path>` at 9ecc5b20.
+
+## Recommendation
+
+- Build a Rust storage engine as a third implementation of `BrainEngine` (`src/core/engine.ts:830`), beside `PGLiteEngine` and `PostgresEngine`, inside this repository. It loads in process as a napi-rs addon and is selected only when a user sets `engine: "rust"`.
+- Everything above the engine stays TypeScript: the CLI, MCP, operations, hybrid fusion, chunking, embedding, the persistence protocol, the error contract. They keep working unchanged and simply talk to a different engine.
+- A Rust engine cannot run Postgres SQL, and about 5,300 raw-SQL call-site lines sit outside the engines (re-measured at 9f1d54232d; see "Size"). The plan runs two tracks. Track 1: the Rust engine implements typed methods, refuses `executeRaw` with a typed error, and reports capabilities that gate subsystems not yet typed. Track 2: move raw SQL behind typed engine methods one subsystem at a time, for all engines, under a shrink-only ratchet. Track 2 is required work for the Rust engine, not optional (D18).
+- Existing brains move by shadow mode first (section "Shadow mode and swap"): Rust runs beside the current Postgres or PGLite engine as a follower, answers a sample of the same reads in the background, and a generated head-to-head report says `READY` or `NOT READY`. `gbrain engine swap --to rust` is allowed only on `READY`, keeps the old engine as a reverse shadow, and `gbrain engine swap --to postgres` (or `--to pglite`) is the way back.
+- The performance bar (decision D17): the Rust engine must be equal or better than TypeScript gbrain on Postgres and on PGLite on every axis in "Performance", including concurrent reads and writes, graph traversal, vector recall and latency, and memory. A loss on any axis is listed with its fix, never hidden. The maintainer's target is 10x better than Postgres and pgvector; equal or better on every axis is the gate to ship.
+- No SQL dialect in the Rust engine (D18): typed `BrainEngine` methods and the relation API only, raw SQL refused with a typed error, and every raw-SQL call site moved to typed methods as required Track 2 work.
+- Single machine first; a full multi-user Rust server that supersedes Postgres and pgvector is the target end state (D19). The embedded phases run one owner process per brain directory, but the storage core, the transaction API and the access checks are built to serve many users later (section "Path to a multi-user server"). Brains with writers on more than one machine stay on Postgres until that server passes the D17 bar.
+- No PGLite-style locking (D20). Concurrency is designed fresh for gbrain's workloads: no process-wide lock, no single-connection bottleneck, no `pglite_busy` equivalent, and no file lock that makes a second process fail or wait for the whole brain. Each lock and queue call site becomes a typed engine operation with a stated concurrency guarantee (section "Concurrency without PGLite-style locks").
+- PGLite deprecation gets a measurable entry gate (section "PGLite deprecation entry criteria"). Postgres deprecation is a separate decision after the multi-user server phases; shadow mode lets a single-writer Postgres brain move to Rust by choice, and nothing moves it by default.
+
+## Goal
+
+Give every PGLite user an embedded engine that does what PGLite does today (vector ANN including filtered search, full-text, trigram, JSON fields, trigger behavior as explicit writes, graph walks, locks, the job queue), with the same contract, the same answers on deterministic operations and equal or better retrieval quality on ranked ones, without the WASM heap cap, the planner statistics problem or per-statement protocol overhead. Let any existing single-writer brain, on PGLite or Postgres, prove Rust on its own workload in shadow mode, with tracked head-to-head metrics, and swap with one verified command when the numbers say so, with a way back. Then retire PGLite once the Rust engine reaches measured parity.
+
+Matching PGLite is not enough (D17). The Rust engine must be equal or better than TypeScript gbrain on Postgres (pgvector HNSW, local, same machine, same corpus, same run) and on PGLite, on every metric in "Performance": concurrent read and write throughput, latency, graph traversal, vector recall and speed, memory, cold open, import, index build and disk size. That is the gate to ship. The target beyond the gate is the maintainer's: 10x better than Postgres and pgvector (D17). The gbrain-evals preregistration fixes the margin on each axis; this plan sets no per-axis 10x number.
+
+The end state is a full multi-user Rust server that supersedes Postgres and pgvector (D19). The embedded engine comes first, and it is built server-ready from the start, so the server phases extend it instead of replacing it.
+
+The Rust engine does not copy PGLite's locking (D20). PGLite's locks come from running one WASM Postgres per process: one connection, one writer, and a file lock across processes. The Rust engine serves many readers, many writers and many processes on one machine, then many machines, with typed operations instead of lock primitives.
+
+## Why
+
+Measured pain, all recorded in this repository (collected in `research/12` A.1):
+
+| Symptom | Measured | Source | What an engine without SQL changes |
+|---|---|---|---|
+| A type or date filter disables the vector index walk | `searchVector` p50 462 ms filtered vs 56 ms unfiltered (Postgres, 20k pages); 195 vs 58 ms (PGLite, 10k) | `TODOS.md:50` | The filter is applied inside the vector scan, or an exact scan runs when the filter is selective |
+| Source-scoped vector search loses neighbours, then falls back | 4 to 8 s fallback when a source holds a few percent of a large brain | `CHANGELOG.md`, 0.60.131.0 entry | Same: per-source filter bitmaps, exact scan for small scopes |
+| PGLite HNSW build runs out of memory | OOM at 1 GB `maintenance_work_mem`, wedged at 1.5 GB, 663 s at 50k chunks; builds past about 300k chunks at 1,024 dims are refused with `pglite_vector_index_too_large` | `CHANGELOG.md` 0.60.146.0; `docs/ENGINES.md` "PGLite vector index ceiling" | No 2 GiB WASM heap; a build with a memory budget |
+| Stale planner statistics | a hot read took about 72 s, 21 ms after a full ANALYZE; PGLite has no autovacuum | `TODOS.md:556` | Access paths are coded, not planned |
+| Per-write overhead on PGLite | 113 to 30 ms owner wall time per write after tuning; 8.9 to 31.7 committed writes per second | `docs/research/pglite-persistence-throughput-2026-09-29.md` | No parse, plan and protocol round trip per statement |
+| Cold first query | budget 2,172 ms on PGLite vs 1,326 ms on Postgres (MCP path, 10k) | `scripts/scale/budgets.json` | No WASM boot or schema replay |
+| Vector phase stalls at 20k pages | 36 min before the WAL guard, 173 s after, RSS about 2.5 GiB | `TODOS.md:209` | No checkpoint inside one WASM statement |
+
+The engine seam exists but is not closed: `executeRaw(sql)` (`src/core/engine.ts:2714`) lets about 1,170 files bypass the typed methods (`research/01` section 9, re-measured at 9f1d54232d). That is why the plan has a Track 2.
+
+## Non-goals
+
+- No change to the Postgres engine's role in this plan's embedded phases. Postgres stays the engine for shared, hosted and multi-host brains until the multi-user Rust server passes the D17 bar (D19). Deprecating it is a later decision with its own plan. Shadow mode observes an engine from outside and changes neither engine's code; the only engine-side addition is the swap's write fence, which reuses graduation custody. A swap from Postgres is allowed only for a brain with one observed writer host.
+- No Rust rewrite of the CLI, MCP server, operations, hybrid fusion, chunkers, embedding, persistence coordinator or doctor. These stay TypeScript.
+- No separate repository, binary, command name or MCP server. No `gbrain-rust`.
+- No ranking or result change visible to callers unless an eval gate and the maintainer's yes allow it (decision D5).
+- No networked Rust server before the opt-in swap (D19). The server is a later phase (section "Path to a multi-user server"), and each of its phases starts only with the maintainer's yes. The embedded phases keep PGLite's process model, one owner process per brain directory, and refuse multi-host writers. The storage core must not depend on that model (see "Process model").
+- No PGLite-style locking (D20): no process-wide lock, no single-connection bottleneck, no `pglite_busy` equivalent, no file lock that makes a second process fail or wait for the whole brain, and no one-for-one copy of gbrain's lock primitives.
+- No SQL dialect and no query language in the Rust engine (D18). It serves typed `BrainEngine` methods and the relation API only.
+- No native reader for a PGLite data directory. Migration goes through the TypeScript copier.
+- No use of the Rust engine as an accelerator inside the PGLite or Postgres engines (option B below, deferred).
+
+## Constraints
+
+From the user (binding):
+
+- Third engine behind `BrainEngine`, in this repository. PGLite and Postgres stay fully supported.
+- gbrain-evals is part of the parity proof.
+- Work lands through the maintainers' merge process, which lands every change on master.
+
+From the merge process rules (binding):
+
+- Small PRs against `master`, each labeled `rust-engine`. Land by commenting `queue: #<n> <full head sha>`; no self-merge. Bring master in with merge commits; no rebase or force-push of a pushed branch.
+- No edits to `VERSION`, the `package.json` version, plugin manifests, `CHANGELOG.md` or release tooling. Each PR adds `changelog.d/<branch-slug>.md`; a PR that changes behavior for an existing user also adds `behavior-changes.d/<id>.md`.
+- `full-ci` label once the head is final. A changed or removed assertion, golden or baseline row gets a line in the PR body saying what it was, what it is and why.
+- All Rust sources, Cargo files and Rust build scripts live under one top-level directory. A PR that adds Rust code does not change how the existing engines behave.
+- The toolchain and CI PR goes first and alone, and states the CI time it adds.
+- Install and upgrade never need a Rust toolchain and never fail because a native binary is missing. A brain with no Rust engine available behaves exactly as today. Nothing uses the Rust engine unless a user asks.
+- the maintainer's explicit yes, quoted in the PR body, before: the engine-select config key or value, any default change, a schema migration, a new error code, a new MCP operation, anything that changes what a caller can read.
+- Same contract, same answers: the Rust engine passes the engine tests PGLite and Postgres pass. CLI and JSON output, MCP names and shapes, the markdown brain format, content hashes, fingerprints and deterministic operations stay byte-exact. Ranked search may return different results only when they are equal or better on the gbrain-evals retrieval metrics (D5, D17). Privacy and visibility match exactly; an engine that filters visibility differently is a blocker.
+- Git stays the parent: where a source has a checkout, content goes file, commit, then index. Brains without a repository stay fully supported, with the database as their record.
+- A `heads-up:` comment before changing shared files: `src/core/engine.ts`, `src/core/engine-sql/`, schema and migration files, `scripts/`, `.github/`, `test/postgres-unit-arms.txt`, goldens under `test/fixtures/goldens/`.
+- Public artifact rules from `CLAUDE.md`: placeholders only (`alice-example`, `acme-example`, `source-a`), security described functionally.
+
+## Architecture
+
+### What changes and what stays
+
+```
+CLI / MCP / operations / persistence coordinator / hybrid fusion / chunkers (TypeScript, unchanged)
+ | BrainEngine (typed methods only for Rust)
+ +-----------+------------+--------------------------+
+ PGLiteEngine PostgresEngine RustEngine (src/core/rust-engine.ts)
+ (WASM Postgres) (pgvector server) | process.dlopen
+ gbrain_engine.node (napi-rs, rust/)
+ |
+ record store + text index + vector index + graph
+```
+
+Because everything above the engine stays, the contract pieces the earlier full-rewrite plan had to rebuild come for free: operation names and schemas, the agent error envelope (`docs/protocol/AGENT_OPERATOR_v1.md`), degraded-result channels (`docs/protocol/MCP_META_CHANNELS.md`), write receipts and exit 10, memory-verb semantics (`docs/protocol/MEMORY_VERBS_v1.md`), the trusted-local versus remote split (`OperationContext.remote`, `src/core/ops/contract.ts:502`). The Rust engine only has to return the same rows for deterministic reads, and equal or better ranked results as D17 defines them.
+
+### Directory layout
+
+```
+rust/ all Rust sources, Cargo files, Rust build scripts
+ Cargo.toml Cargo.lock rust-toolchain.toml deny.toml
+ crates/gbrain-store/ record store, format header, relation catalog, outbox, counters
+ crates/gbrain-text/ Postgres-compatible text analysis, tsquery parser, ts_rank, CJK
+ crates/gbrain-trgm/ pg_trgm-compatible trigrams and similarity
+ crates/gbrain-vector/ VectorIndex trait, exact SIMD scan, ANN, filter bitmaps
+ crates/gbrain-graph/ adjacency lists, BFS walks with the engine row caps
+ crates/gbrain-domain/ typed domain methods, trigger equivalents, write invariants
+ crates/gbrain-napi/ napi-rs binding; the only crate that knows JavaScript
+ bench/ bake-off and performance harness
+ catalog/relations.json relation catalog generated from the PGLite schema
+ fixtures/ exactness fixtures generated from PGLite (ts_rank, pg_trgm, fingerprints, triggers)
+ scripts/ build, verify, catalog export, fixture export (TypeScript run with bun)
+src/core/rust-engine.ts RustEngine implements BrainEngine
+src/core/rust-engine/ loader, capability table, transaction wrapper, row mapping
+src/core/shadow/ shadow mode: engine wrapper, follower, reconcile, comparisons, ledger, report
+test/rust-unit-arms.txt test files whose Rust arm runs (grows only)
+.github/workflows/rust-engine.yml path-filtered CI lane
+```
+
+The TypeScript wrapper sits beside `pglite-engine.ts` and `postgres-engine.ts`, following "Adding a new engine" in `docs/ENGINES.md`.
+
+### Binding: napi-rs addon, in process
+
+- Chosen: an in-process Node-API addon built with napi-rs, loaded by the TypeScript wrapper. PGLite already runs in process, so the process model, the owner lock and the owner IPC socket carry over, with the owner protocol extended for the Rust engine (PR 18, D20). Vectors cross as typed arrays without a serialization step. The repository already ships and loads a native addon (`native/locks/`, loaded in `src/core/persistence/native-lock.ts:94`).
+- Rejected: a sidecar process over a socket. It adds a second process lifecycle and supervisor, serializes every row and vector, and makes `transaction(fn)` a cross-process protocol. Its one advantage is crash isolation, and in process that is only partly replaced. `catch_unwind` on every exported function, with `panic = "unwind"` in the release profile, turns a Rust panic into a typed error. It does not catch segfaults, aborts, allocation failures or faults inside native dependencies; those still end the process. The plan makes them rarer (no `unsafe` in gbrain crates without review, fuzzing at the binding boundary, `cargo deny` and `cargo audit`) and survivable (a store that recovers at the next open after any process death, proven by the crash robot), and accepts the residual risk for the preview. A sidecar is reconsidered if preview crash reports show native faults (see "Deferred").
+- Every call that touches disk or an index runs as an async task on a Rust worker pool, so the Bun event loop never blocks. PGLite runs queries on the main thread today (`TODOS.md:556`).
+- `transaction(fn)` keeps its shape: the wrapper opens a Rust write transaction handle and passes `fn` a transaction-bound clone of the engine, the same pattern `PostgresEngine` uses. Nested calls map to savepoints, an abort rolls back, `readOnly` refuses writes (`research/01` section 6). `AbortSignal` maps to a cancellation token checked between steps.
+- Writer admission is starvation free. A caller waits for a writer permit from a bounded writer pool (D17, D19) asynchronously, on the JavaScript side, before it uses any worker thread. An open write transaction runs its commands on its own transaction executor, so the worker pool size never decides whether the transaction that holds the writer can finish. The wait is bounded by the caller's `AbortSignal` or deadline and ends with the existing `cancelled` or `timeout` code; a cancelled waiter leaves no permit or queued task behind.
+- Re-entry is refused. A call on the outer engine from inside its own `transaction(fn)` would wait forever for the writer it already holds. The wrapper detects it and throws `internal_error` with reason `transaction_reentry` (added to decision D2) instead of hanging. `lockPageKeys` maps to the typed per-key single-flight operation (D20): it holds only the named keys, in sorted order, until the transaction ends, and never blocks other keys.
+- Lifecycle. `disconnect()` and the resident-consumer stop barrier stop admission, cancel queued tasks, wait a bounded time for running tasks, and then close the store. A task cancelled after it started reports what it committed through the receipt. PR 1 proves the Bun behavior this needs before any engine code: shutdown with pending tasks, cancellation after start, process exit with pending native work, and a threadsafe-function queue that is full or closing.
+- Loading (`src/core/rust-engine/loader.ts`), modeled on `loadBindingSync`: resolve the target (`linux-x64-glibc`, `darwin-arm64`, ...), then load with `process.dlopen` from `GBRAIN_RUST_ENGINE_ADDON` (absolute path; development and CI, decision D3) or from `<gbrain home>/engines/rust/<engine_build>/<target>.node`. A literal `require` is not used, so compiled release binaries do not grow for users who never select the engine. The addon exports `target`, `engine_abi` (an integer bumped when the binding surface changes), `engine_build` (a digest of the `rust/` tree it was built from), `catalog_version` and the store `format_versions` it reads and writes. Each release carries a generated manifest pinning the exact SHA-256 of the addon for each target. The loader refuses any other file and any `engine_abi`, `catalog_version` or format mismatch. Under `GBRAIN_RUST_ENGINE_ADDON` only the release digest pin is skipped; the `engine_abi`, catalog and format checks still apply, so a stale local build fails with its reason instead of opening the store. A release that leaves `rust/` unchanged carries the previous digests forward, so the installed addon stays valid.
+- The addon is loaded only by `constructEngine` when `engine` is `rust` (dynamic import, as PGLite's WASM is today). A missing or mismatched addon gives `engine_unavailable` (decision D2) with the fix for its reason ("Error contract for the Rust engine" below), and nothing else changes.
+
+### Storage replacement map
+
+| Postgres feature today | Used for | Rust replacement | Parity rule |
+|---|---|---|---|
+| Tables, rows, transactions, savepoints | every domain | `gbrain-store`: one table per relation in an embedded record store (redb or bundled SQLite used as a key-value store, picked by the bake-off); concurrent writers with snapshot isolation (per-relation or sharded writers with group commit, or an MVCC store, picked by the bake-off), concurrent snapshot readers; transactions and snapshots are bound to a connection, not to a thread or a process, so the same core serves many connections and processes (D17, D19) | PGLite semantics: nested is a savepoint, abort rolls back. `readOnly` refuses writes, as on Postgres; PGLite ignores the option today (`src/core/engine.ts:158`), so this is a deliberate, stronger behavior, listed in the parity matrix as a divergence |
+| pgvector `vector`, `halfvec`, HNSW, `<=>` | chunk, image and multimodal embeddings; facts; takes | vectors stored in records (f32, or f16 for `halfvec` columns); ANN index derived from them; exact SIMD scan always available | cosine equal to pgvector within 1e-6; ANN recall@10 against exact no lower than pgvector's on the same corpus |
+| Index walk, scope scan, iterative scan, escalations (`search/vector-statement.ts`, `vector-pool.ts`) | filtered vector search | roaring bitmaps per source, type, modality, page kind, date bucket, deleted and visibility class; exact scan below a filter-size threshold, filter-aware ANN above it, bounded escalation | keep the `vector_candidates_incomplete` reason; one row per page; ties `score DESC, page_id ASC, chunk_id ASC` |
+| `to_tsvector('english')`, `setweight`, GIN, `websearch_to_tsquery`, `phraseto_tsquery`, `ts_rank`, `ts_rank_cd` | keyword, title and facts arms | `gbrain-text`: the default-parser token rules gbrain's text hits, Snowball English stemmer, Postgres English stopwords, weights A to D with positions, websearch query grammar, `ts_rank` and `ts_rank_cd` formulas; postings in tantivy with a custom scorer or in the record store (bake-off) | decision D5 |
+| `gbrain_fts_input` (CJK spacing), CJK `LIKE` scan | title arm, CJK path | the function ported; an n-gram substring index for CJK | same matches as `search/cjk-keyword-sql.ts`; same ordering in the `ts_rank` compatibility mode, and equal or better retrieval quality with a better default ranker (D5, D17) |
+| `pg_trgm` (`similarity`, `%`, `word_similarity`, GIN) | find by name, resolver fuzzy arm, saved facts, takes search | `gbrain-trgm` reproducing pg_trgm's trigram extraction and similarity, thresholds 0.3 and 0.6 unless configured | scores equal to PGLite on a fixture set |
+| JSONB, GIN, `->`, `@>`, `jsonb_to_recordset`, jsonpath | frontmatter, payloads, job data, purge matching | JSON values in records; secondary indexes only for keys that are filtered on (frontmatter emails, `__param_hash`); purge matching in Rust code | stored once as a document; output key order matches jsonb |
+| Triggers (26 in `src/schema.sql`, more from migrations: `research/02` section 9) | generations, revisions, search vectors, projection queue, withdrawal and purge guards, trust stamping, access state | one Rust write hook per trigger in `gbrain-domain`, run inside the same write transaction | identical resulting rows, proven by a trigger parity matrix |
+| Sequences, `SERIAL` | ids, `page_generation_clock_seq`, `graph_generation_seq` | durable allocator reservations, made before a value is handed out and never rolled back by an abort (as Postgres and PGLite sequences behave; `graduation-copy.ts` keeps aborted values from being reissued) | monotonic across restarts and aborts; tests abort a transaction after allocating, restart, and check the value is never reissued |
+| `WITH RECURSIVE` | `traverse_graph`, retirement chains, `rank_entities` | `gbrain-graph`: BFS over forward and reverse adjacency per source | `TRAVERSE_WALK_ROW_CAP = 20000`, `TRAVERSE_PATH_ROW_CAP = 5000`, `(slug, id)` order, `truncated` flags |
+| Advisory locks, `FOR UPDATE`, `FOR KEY SHARE`, `SKIP LOCKED` | fact inserts per entity, queue and journal claims, leases | typed engine operations, one per call site (leased claims, compare-and-set writes, idempotent upserts, per-key single-flight), listed in "Concurrency without PGLite-style locks" (D20); never a process-wide lock | same claim order; fencing tokens checked in the transaction that writes; no lost update, no double claim, no deadlock under concurrent callers |
+| `LISTEN/NOTIFY` | minion wake on direct Postgres only | nothing: PGLite already polls | unchanged |
+| RLS, `set_config` GUCs (`gbrain.write_sources` and others) | defense in depth on Postgres; managed-writer guard | a typed write-scope argument on every mutating method; the invariants I1 to I15 in `research/09` section 12, enforced in `gbrain-domain`, never in `gbrain-napi` or the TypeScript wrapper, so they become the per-user access model a server enforces (D19) | per-operation authorization tests |
+| `NULLS NOT DISTINCT`, partial unique indexes, `CHECK`, FK cascade and restrict | link identity, timeline dedupe, idempotency keys, tokens | unique keys with a NULL sentinel; validated types; cascades and restricts in the same transaction | same refusals and error codes |
+| `md5()`, `sha256()`, `lower()`, `regexp_replace` inside SQL | `embedded_text_hash`, fact fingerprints | computed in TypeScript and passed in where Track 2 can move them; otherwise Rust code fuzzed against PGLite | byte-identical (see "Exactness hazards") |
+| `NUMERIC`, `DATEMULTIRANGE`, `TIMESTAMPTZ`, `BYTEA` | calibration, link validity ranges, times, segment texts and attachments | exact decimal type with Postgres rounding; interval sets; microsecond UTC integers; blobs | exact |
+| `pg_stat*`, `pg_class`, `EXPLAIN` gates, pools, PgBouncer | Postgres doctor checks, scale plan gates | not applicable, reported the way PGLite reports `opsPglite: 'not_applicable'` today | n/a |
+
+### Data on disk
+
+```
+~/.gbrain/brain.rust/ database_path (a directory)
+ FORMAT JSON: format_version, engine_abi, catalog_version,
+ schema_version (the TS config.version ledger it matches), created_by
+ records.<ext> record store: relations, secondary indexes, counters, outbox
+ text/ derived keyword index; records the outbox generation it reflects
+ vectors/<relation>.<column>/ derived ANN graph; records its generation
+ .gbrain-persistence.sock owner IPC socket (existing rule, src/core/context/resolve-ipc.ts)
+~/.gbrain/brain.rust.gbrain-owner.lock kernel lock sibling (existing rule, src/core/pglite-lock.ts); it decides
+ which process hosts the store, never a lock a caller waits on (D20)
+```
+
+- Record keys are order-preserving encodings of each relation's primary key. Values carry catalog column ids plus typed values, so adding a nullable column needs no rewrite.
+- `rust/catalog/relations.json` is generated from the live PGLite catalog at a pinned schema version (the same way `src/core/persistence/graduation-inventory.ts` reads the catalog): relation names, columns, types, keys, uniques and FKs, plus the secondary indexes the Rust engine keeps. Keeping Postgres relation names and columns lets the graduation inventory, digests and verification be reused through an engine-neutral adapter ("Migration and rollback"); the current helpers issue catalog and sequence SQL and cannot run on Rust unchanged.
+- One commit point. A write commits records and outbox entries in one store transaction (allocator reservations are durable separately and survive an abort, see the sequences row), then applies the outbox to the text and vector indexes, in generation order, before the call returns. A search issued after a write returns sees it, as today. If the process dies between commit and apply, the open catches the indexes up before serving reads.
+- Snapshot contract for search. Every search pins one record snapshot generation N. Text postings and vector entries carry the generation range in which they are valid, and the search uses only entries valid at N, so a reader at N never sees content, scores or permissions from N+1. Superseded entries are reclaimed only after the oldest open reader has passed their generation. As a backstop, each candidate's indexed revision is checked against the record at N, and deleted, withdrawn and visibility state is re-checked there before ranking; a mismatch drops the candidate and the search continues with the exact path for that arm, reporting the existing `vector_candidates_incomplete` reason when it cannot fill the page.
+- Failure after commit. If applying the outbox fails while the process stays alive (disk full, an index error, cancellation), the write is still committed: the call reports it as committed through its receipt and never as rolled back. The relation is marked behind at that generation; searches that touch it use the exact path for the affected arm until replay succeeds; replay retries in generation order and is idempotent; `gbrain engine status` and doctor report the lag.
+- The store refuses a newer `format_version` and backs up before upgrading an older one. `gbrain doctor --fix` rebuilds derived indexes from records without re-embedding and never writes records.
+
+### Process model
+
+- In the embedded phases the Rust engine keeps one owner process per brain directory, holding the kernel lock through the existing native lock addon, and other processes reach it through the existing owner IPC socket (`research/08` sections 2 and 3). This is a temporary limit of the embedded phases, not a lock design the core depends on (D19, D20). Unlike PGLite, a second process never fails or waits for the whole brain: it becomes a client of the owner for reads and writes, with no `pglite_busy` equivalent, and if the owner exits a client takes over hosting the store, retrying calls in flight by request id. The existing owner protocol cannot do this as it stands, so PR 18 extends it (see "Owner protocol for the Rust engine" below). The limit ends when the bake-off picks a store that several processes open directly without a process-wide writer lock, or at the server phase. The persistence consumer election already treats a one-process engine as "no other owner" (`src/core/persistence/consumer-election.ts`).
+- Those paths branch on `engine.kind === 'pglite'` today. Track 1 replaces those branches with one capability, `single_owner`, which PGLite and Rust report, so the Rust engine reuses the code instead of copying it. Some of these checks run on the config before any engine exists (`src/core/context/resolve-ipc.ts` keys the owner socket and secret on `cfg.engine === 'pglite'`; `src/core/persistence/graduation-serve-guard.ts` does the same), so a config-level helper, `engineIsSingleOwner(cfg.engine)`, answers the same question there, and both forms are covered by the kind-branch guard.
+- The owner process is a deployment choice for the embedded phases, not an assumption of the storage core (D19). The core has no global singletons and no per-process state that assumes one caller: every store handle, transaction, snapshot, writer permit and cache belongs to an engine instance, and every transaction belongs to a connection. Transactions and snapshots work across connections and processes, not only across threads in one process: IPC clients of the owner today and server clients later get the same isolation. A Rust test opens two engine instances on two stores in one process and runs concurrent transactions from several client processes through the owner IPC socket.
+- Owner protocol for the Rust engine (PR 18, D20). Today's owner protocol carries writes and a few reads only (`PERSISTENCE_IPC_OPERATIONS` in `src/core/persistence/ipc.ts`; no search and no transactions), refuses a request over 8 connections with `queue_capacity`, and makes a client wait for the engine lock when the lock holder is a command that serves no socket (`src/core/persistence/local-client.ts`). For a Rust brain: every owner publishes its socket, a one-shot CLI command included, so no holder makes a client wait for the lock; the protocol carries every `BrainEngine` method a client needs, search and connection-bound transactions included; a request over the connection limit queues inside its own deadline instead of failing at once, ends with `timeout` or `cancelled` only when that deadline passes or the caller cancels, and a cancel crosses the socket to the owner; at a handoff, a transaction still open on the old owner aborts and is reported as aborted, never as partly committed, and the client reruns it by request id, while a single call retries by request id against the write receipt. Doctor and `doctor --fix` on a Rust brain go through the running owner as an administration request, and take the owner role themselves only when no owner runs (see "Maintenance path"). A test runs each rule across processes: queueing over the limit, cancel, handoff during a transaction, and doctor beside a running owner.
+- Inside the owner, many writers run at once on the concurrent-writer store the bake-off picks (D17, D19); readers use snapshots and never block writers. The store must keep these guarantees: claim and lease exclusivity, per-entity fact ordering, fencing tokens checked in the writing transaction, the transactional invariants the parity matrix lists, and, on swap rollback or shutdown, fencing and draining every admitted writer before the store closes. The writer permit (see "Writer admission") comes from a bounded writer pool with the same starvation-free and cancellation rules.
+- Index-backed reads inside an open write transaction read committed index state. A guard test lists any call site that searches inside its own write transaction (expected: none); if one exists, it is fixed before that subsystem is allowed on the Rust engine.
+
+### Concurrency without PGLite-style locks
+
+The maintainer's principle (D20) is no PGLite-style locking. gbrain's TypeScript code today serializes work with lock primitives: named advisory locks, row locks, `SKIP LOCKED` queue claims, a lease table and PGLite's whole-brain owner lock with its `pglite_busy` error (`research/08` sections 3 to 6, `research/07`). The Rust engine does not copy them one for one. Each call site gets a typed engine operation with a stated guarantee. Track 2 moves each call site to its operation for all engines; on Postgres the operation may still take the Postgres lock inside its own SQL.
+
+| Call site today | Typed engine operation | Concurrency guarantee |
+|---|---|---|
+| Brain open: `pglite-lock.ts` kernel lock, `PgliteBusyError` (`pglite_busy`), `LiveServeLockError` | `open_brain`: the first process hosts the store, any other process becomes its client, and a client takes over hosting when the owner exits | a second process never fails or waits for the whole brain; calls in flight at a handoff retry by request id |
+| Schema init: `pg_advisory_lock(42)` (`postgres-engine/init-schema-lock.ts`, `db.ts`) | `upgrade_format`, a compare-and-set on `format_version` inside open | exactly one upgrade runs; every caller sees the old or the new format, never a partial one |
+| Write journal claims: `claimNextWrite` and batch claims with `FOR UPDATE ... SKIP LOCKED` (`persistence/journal.ts`, `persistence/consumer.ts`) | `claim_next_writes(lane, limit, lease)` | each request has one claimant at a time; the claim order and eligibility stay as today (`CLAIM_ORDER` and `claimableWriteSql` in `persistence/journal.ts`: with `foreground_priority` on, the default, a claimable foreground request goes before the sync rows it passes, then `sequence`; per-worktree and per-source heads, deferred rows and recovery blocks still gate a claim); the lease carries a fencing token; an expired lease is reclaimed |
+| Effect claims (`persistence/effect-journal.ts`, `persistence/embedding-noop-settle.ts`) | `claim_effects(kind, limit, lease)` | one claimant at a time, with a fenced execution token that the completion record must match; an expired or dead-owner claim is reclaimed, as `claimPersistenceEffect` does today, so an effect can run again after a crash between its external action and its recorded completion; each effect kind stays idempotent or keeps its own recovery step; `UNIQUE(request_id, kind)` stops duplicate journal rows only, not a second execution; a crash test kills the owner at that boundary on every engine |
+| Counters and caps: `persistence_counters` `FOR UPDATE` (`persistence/journal.ts`) | `reserve_capacity(key, delta, cap)`, an atomic compare-and-add | no over-admission and no lost update |
+| Minion job claim, stall, timeout and watchdog: `FOR UPDATE SKIP LOCKED LIMIT 1` (`minions/queue.ts`) | `claim_next_job(queue, worker, lease)`, `renew_job_lease`, `reclaim_stalled_jobs` | no double claim; completion and failure check the lease token |
+| Minion admission, quota and max-waiting advisory locks (`minions/queue.ts`) | `admit_job(spec)`: idempotency key, admission policy, quota and caps checked and the job inserted in one operation | the admission contract stays as today (`minions/queue.ts`): an idempotency key maps to one row; parameter coalescing applies only where the job's policy turns it on, the payload carries parameters, no idempotency key is given and the submit has no parent, and it uses the same job states and window; caps are never exceeded; the cases in `test/minions-admission.test.ts` stay, including the rerun of a running job, separate children and a submit after the window ends |
+| Parent row lock on child submit and roll-up (`minions/queue.ts`) | `submit_child_job(parent, spec)`, `roll_up_child(parent, child)` | exact child counts and roll-ups with concurrent children |
+| Budget meter and rate leases (`minions/budget-meter.ts`, `minions/rate-leases.ts`) | `reserve_budget(key, amount, cap)`, `acquire_rate_lease(key, ttl)` | no over-spend; a lease ends at its TTL |
+| Facts per entity: `pg_advisory_xact_lock` on source and entity (`engine-sql/facts.ts`) | `append_fact(entity, fact)`, with the per-entity sequence assigned at commit | one total, stable fact order per entity; no lost fact |
+| Page body chunks, writeback settings, mentions pass, chronicle reservation (`engine-sql/page-body.ts`, `facts/writeback-settings.ts`, `mentions/pass.ts`, `chronicle/ledger.ts`) | compare-and-set writes on the row revision, idempotent upserts on the natural key, `reserve_chronicle_range` | no lost update; a stale writer gets a typed conflict and re-reads |
+| Generation fence and publish (`generations/fence.ts`, `generations/publish.ts`) | `publish_generation(expected)`, a compare-and-set | generations stay monotonic; two publishers never win the same generation |
+| Derivation scope lock (`derivationScopeLockSql` in `page-body/schema.ts`, sweeps in `page-body/segment-derive.ts`): writers that bring rows into a sweep's scope hold it shared, and a sweep moves to its verify walk and ends only under it exclusively | `enter_derivation_scope(source)` in the writer's transaction, and `finish_derivation_sweep(source, sweep)`, which checks the writers that entered the scope since the sweep was recorded | a sweep ends only after every writer open when it was recorded has committed or aborted and the verify walk sees that writer's rows; a sweep never deletes a derivation row that a writer still open will bring back; the open-writer cases in `test/helpers/derivation-purge-cases.ts` run on every engine; writers in other sources never wait |
+| Cycle locks and the sync drain lease: `gbrain_cycle_locks`, `fenceLockRow` `FOR KEY SHARE` (`db-lock.ts`, `persistence/sync-lease.ts`) | `acquire_lease(id, ttl)`, `renew_lease(token)`, `assert_lease(token)` checked in the writing transaction | one holder; fenced work never blocks a renewal; a stale holder's write is refused |
+| Consumer election, heartbeat and worktree sweep (`persistence/consumer-election.ts`, `persistence/consumer-heartbeat.ts`) | `register_consumer`, `heartbeat`, `claim_sweep` | one full consumer per host; each sweep row is claimed once |
+| Grant moves, token backfill and OAuth client admission (`grants/legacy-token.ts`, `minions/delegated-admission.ts`) | `move_grant(expected_state)`, `claim_backfill_batch`, `admit_delegated(client, expected)` | no double grant; each backfill row is claimed once |
+| Links, withdrawals and purge row locks (`research/06`) | checks and compare-and-set on the target's state in the writing transaction | a withdrawn or purged target is never linked; restrict refusals are unchanged |
+| `lockPageKeys` | `single_flight(keys)` for one transaction | holds only the named keys, in sorted order; released at commit or abort |
+
+- No operation takes a process-wide or brain-wide lock on the hot path. Waits are bounded per call and per key, end with the existing `cancelled` or `timeout` code, and never block the whole brain.
+- Filesystem resource locks stay as they are, because they lock one file-system resource outside the store, not the brain, and do not depend on the engine. Each waits a bounded time for that resource only, or tries once without waiting; a busy resource refuses only the step that needs it, usually with a typed code and a retry with the same request id, and the Rust work keeps today's result for each one (a socket bind that finds the path taken returns no lock, and a setup step reports its own error). They are: Git checkout locks (`brain-commit.lock`, the push lock and the shell `flock` hook); worktree coordination and refresh locks (`persistence/ownership.ts`, `topology-locks.ts`, `topology-clone.ts`, `coordination-lock.ts`, `worktree-refresh.ts`, `head-blocker.ts`); the writer registration lock per lane (`persistence/identity.ts`); the reconciliation backup capacity lock (`persistence/reconcile-backup.ts`); socket bind locks (`cli-socket/server.ts`, `context/ipc-path.ts`); skills-directory and setup locks (`harness/native-router.ts`, `shared-skills/adapter.ts`, `shared-skills/migration-export.ts`, `setup/brain-first.ts`, `setup/hermes-turn-hook.ts`); and the probes in `persistence/activation.ts` and `persistence/administration.ts`, which take their lock only for a moment to test it and then release it. The migration orchestration lock (`migration-orchestration-lock.ts`) runs only during `apply-migrations`, never on the hot path; on a Rust brain the store side of an upgrade is `upgrade_format`. The PR 6 recount covers these files too.
+- Proof: each typed operation has a parity test against TypeScript gbrain on PGLite and Postgres that runs concurrent callers and checks the same observable outcome (no lost update, no double claim, no deadlock), and a stress test with many writers in many processes (see "Crash, property, concurrency and fuzz tests"). The call-site list is re-counted when PR 6's ratchet lands; a lock call site with no row here fails that check.
+
+### Engine selection
+
+- `~/.gbrain/config.json` gains the value `engine: "rust"` with a `database_path` (default `~/.gbrain/brain.rust`). `GBRAIN_DATABASE_URL` and `DATABASE_URL` keep implying Postgres (`src/core/config.ts:738`). Decision D1.
+- `constructEngine` (`src/core/engine-construct.ts`) gains a `rust` case and its unsupported-engine message names all three engines. `BrainEngine.kind` (`src/core/engine.ts:832`) gains `'rust'`, and so does every other `'postgres' | 'pglite'` engine union (the config type in `src/core/config.ts`, `targetEngine` in `src/commands/migrate-engine.ts`, the config shape in `src/core/context/resolve-ipc.ts`). The graduation inventory's `engines` record becomes `{ pglite, postgres, rust }` with no default for `rust`, so a row that does not say how Rust stores it fails to compile.
+- 268 direct `kind === / !==` comparisons exist in `src` today. A new guard, `check:engine-kind-branches`, baselines them and fails on new two-way branches. Before a subsystem is allowed on the Rust engine, its branches become capability questions or an exhaustive `byEngineKind({ pglite, postgres, rust })`, so a Rust brain never falls silently into a Postgres branch.
+- Users reach the engine only through `gbrain migrate --to rust` (and back with `--to pglite`), after the preview opens (decision D8). `openEngine` accepts kind `rust` for harnesses. `gbrain init` keeps its PGLite default.
+
+### Capability gating
+
+- `BrainEngine.capabilities` is a read-only set of named subsystem capabilities (`raw_sql`, `persistence_journal`, `minion_queue`, `access_control`, `belief_ledger`, `single_owner`, `postgres_admin`, ...). PGLite and Postgres report everything they have today. Rust reports what it implements.
+- One table, `src/core/engine-capabilities.ts`, records the capabilities each operation, CLI command record (`src/cli/command-table.ts`), cycle phase and minion handler needs. Anything not listed needs `raw_sql`, which Rust never has. The check runs at dispatch, before any work: the caller gets `engine_capability_missing` naming the capability, and nothing is written. Cycle phases and handlers without their capability are skipped with a degraded reason on the existing channel instead of failing the cycle.
+- `executeRaw`, `executeRawDirect`, `withReservedConnection` and any other raw-SQL entry point on the Rust engine throw `engine_capability_missing` with reason `raw_sql` (D18). The Rust engine has no SQL dialect to fall back on. This is a backstop for a missed path, not the gate; the Rust test arm proves each allowed operation never reaches it.
+- Every `BrainEngine` member is classified in `src/core/rust-engine/members.ts`, a table typed `satisfies Record<keyof BrainEngine, 'implemented' | Capability>`. A new interface member fails to compile until it is classified, so the list cannot drift by hand. A member not yet implemented throws `engine_capability_missing` naming its capability.
+- `check:rust-capability-coverage` prints the share of operations, commands, phases and handlers available on Rust. It is the progress number and the first PGLite-deprecation criterion. It is derived from the member table and the dispatch table, not kept as a separate list.
+- Postgres-only administration (pool diagnostics, `pg_stat` checks, RLS scope binding, Postgres graduation targets, PgBouncer handling) needs `postgres_admin` and stays unavailable on Rust by design.
+
+### Error contract for the Rust engine
+
+- Every new code and reason is a row in `src/core/error-registry.ts` (class, summary, why, reasons, suggestion, default read-only fix, docs anchor). `bun run build:error-codes` regenerates `docs/guides/error-codes.md`, and `gbrain errors <code>` answers offline. Errors use the existing envelope (`docs/protocol/AGENT_OPERATOR_v1.md`): stderr and a non-zero exit on the CLI, one `--json` document, `isError` over MCP.
+- Each envelope's `detail` carries caller-safe context: the gbrain version, the target, expected and found `engine_abi`, `engine_build`, `catalog_version` and store format, the names (never the values) of the environment variables that mattered, and home-relative paths only. Every refusal says whether anything was written.
+- One fix per reason:
+
+| Code and reason | Fix | Actor, `next` | Recovery |
+|---|---|---|---|
+| `engine_unavailable` `addon_missing` | `gbrain engine install rust`; verify with `gbrain engine status --json` | agent, `run` | nothing was touched; retry the failed call once after the install |
+| `engine_unavailable` `abi_mismatch`, `build_mismatch` | `gbrain engine install rust` (fetches the addon this release pins) | agent, `run` | as above; under `GBRAIN_RUST_ENGINE_ADDON` the fix says to rebuild with `bun run rust:build` instead |
+| `engine_unavailable` `unsupported_platform` | none to run: no addon exists for this target; open the brain on a supported preview host, or keep this brain on PGLite | user, `tell_user_to_run` | do not retry the install on this target |
+| `engine_unavailable` `load_failed` | `gbrain engine install rust` once; if it fails again, report with `detail.diagnostic_id` | agent, `run`, then `report` | one retry; the sanitized loader cause is in `detail` |
+| `engine_unavailable` `fetch_failed` | after connectivity returns, `gbrain engine install rust` once | agent, `run` | the staged download was discarded and the active addon is unchanged; one retry, then report |
+| `engine_unavailable` `verification_failed` | none; report it; there is never a bypass | user, `report` | the downloaded file is deleted and the active addon is unchanged |
+| `engine_capability_missing` before dispatch | none to run on this brain: tell the user the operation is not in the preview, with the capability list anchor; moving back is the user's choice, previewed read-only with `gbrain migrate --to pglite --plan` | user, `ask_user` | nothing ran |
+| `engine_capability_missing` `raw_sql` (backstop) | read the write receipt (`gbrain write-request -- <id>`) before any resubmission | agent, `run` (read only) | `detail.outcome` is `none` when the enclosing transaction rolled back, else `partial` or `unknown`; reconcile before retrying |
+| `engine_store_format_unsupported` `newer_format` | `gbrain upgrade` to at least the release named in `FORMAT` `created_by` | user, `tell_user_to_run` | the store is never downgraded or rewritten |
+| `engine_store_format_unsupported` `unreadable` | keep the directory as it is; restore from a verified backup (`gbrain backup restore`) | user, `ask_user` | nothing was written |
+| `engine_store_format_unsupported` `upgrade_failed` | none to run; the store stays at its old format and `detail` names the backup written before the upgrade | user, `report` | the old format remains readable by the previous release |
+
+- Caught panics: `gbrain-napi` installs its own panic hook, because the default hook prints the payload to stderr. The hook writes a sanitized trace (no row content, no argument values) to `<gbrain home>/engines/rust/diagnostics/<id>.txt` with mode 0600 and the call returns `internal_error` naming the operation, with `detail.diagnostic_id` and `detail.outcome`. A panic inside a write transaction aborts it; the wrapper then closes and reopens the store, which runs open-time recovery, before the next call. Over HTTP MCP only the diagnostic id is returned.
+- A cancellation that arrives after commit reports the write as committed through its receipt, never as cancelled.
+- Faults that end the process (segfaults, aborts) cannot be caught. The next open records that the previous owner ended without closing the store, and doctor `rust_engine_available` reports it with the `engine_build` and the recovery result.
+- Maintenance path: `gbrain doctor` and `doctor --fix` on a Rust brain send their work to the running owner as an administration request; when no owner runs, they take the owner role themselves. Either way they read `FORMAT` and the records without opening the derived indexes, so a corrupt index or a failed open-time replay can still be inspected and rebuilt. `--fix` rebuilds derived state only and never writes records.
+- Human output keeps the shared renderer (`Error [code]`, `Fix:`, `Why:`, `Docs:`); agents read `fix` from the `--json` document.
+- The reasons added here (`fetch_failed`, `verification_failed`, `newer_format`, `unreadable`, `upgrade_failed`) are part of decision D2.
+
+### Privacy and visibility
+
+- The source-scope ladder (`sourceScopeOpts`, `src/core/ops/context.ts:646`), trust checks and redaction stay in TypeScript and are unchanged. The engine receives scope and visibility arguments exactly as the other engines do.
+- Inside the engine, source scope, private pages, `readable_by`, hard excludes and soft-deletes apply inside each candidate set (vector, keyword, title, CJK, facts, relational), before ranking and before any text leaves the engine (`research/03`, "Must preserve exactly"). Malformed `readable_by` fails closed as `!nobody`; `restrictions_present` is maintained in the same write transaction (`research/09` I6 and I7).
+- Proof: the operations source-isolation matrix, `test/helpers/two-engine.ts` isolation cases, `test/memory-verbs-conformance.test.ts`, and gbrain-evals Cat 22 (0 leaks) all run on the Rust arm. Any difference in what a caller can read is a release blocker, not a tolerance.
+
+### Exactness hazards
+
+Each has a fixture generated from PGLite under `rust/fixtures/` and a test on the Rust arm.
+
+- Content hash and chunk boundaries: computed in TypeScript (`src/core/utils.ts` `contentHash`, `src/core/chunkers/`), so they do not change. The engine stores what it is given.
+- `embedded_text_hash = md5(chunk_text)`: computed in SQL today; Rust computes md5 over the same UTF-8 bytes.
+- Fact fingerprint: `gbrain_fact_fingerprint` is SQL (`src/core/facts/withdrawal-schema.ts:36`) using Postgres `lower()` and POSIX classes; withdrawals and purge tombstones key on it, so a different value silently un-forgets a fact. Migration carries stored fingerprints verbatim. PGLite and Postgres keep computing it in SQL, unchanged, because existing Postgres fingerprints depend on that host's `lower()` and whitespace classes. The Rust engine computes `gbrain_fact_fingerprint` and `gbrain_fact_fingerprint_v1` in its own code, fuzzed against PGLite's SQL on a corpus with non-ASCII text, mixed case and every whitespace class; before a Postgres swap, the same corpus runs against that host's SQL for both versions (see Fingerprints under shadow mode). Moving the computation out of SQL for all engines, or a versioned normalization, is a separate change that needs the maintainer's yes.
+- Page generation, the global generation clock, `knowledge_revision` and `text_projection_revision` rules (`src/schema.sql:182-205`, `:255-278`, `:1904-1961`): ported predicates plus a scenario matrix per column.
+- Belief ledger hashes (`event_key`, `state_hash`, `prior_hash`): carried verbatim; new events use the same byte encoding; the chain is verified after migration.
+- `NUMERIC` calibration bucketing: exact decimals with Postgres rounding; golden buckets at boundaries.
+- `now()` is the transaction start time in Postgres: the Rust write transaction carries one timestamp, at microsecond precision.
+- Text ordering and `lower()` follow PGLite's collation, which is the engine being replaced; the engine-graduation spike's mixed-case and accented key set (`docs/designs/engine-graduation-spike.md`, "Setup") is part of the fixture.
+- jsonb output: keys come back in jsonb order with duplicates collapsed; the Rust engine returns the same order.
+- Segmented page bodies (`page_segment_texts`, `page_body_manifest`) exist only in the database (`research/02` section 12): stored and migrated as user data, never treated as rebuildable.
+- Keyword ranking: decision D5.
+
+## The SQL problem and the chosen strategy
+
+### Size
+
+- At 36bd05806a (`research/01` section 9): about 4,890 `executeRaw` / `executeRawDirect` call-site lines in about 1,140 files outside the engine files, plus 186 tagged-template `sql` lines in 44 files, 20 `.unsafe(` and 29 `.query(` lines (`research/01` section 9).
+- Re-measured at 9f1d54232d with the pattern `executeRaw(Direct)?\s*[<(]` over `src`, excluding `pglite-engine.ts`, `postgres-engine.ts`, `engine.ts` and `src/core/engine-sql/`: 5,324 lines in 1,174 files. The raw-SQL ratchet baseline (PR 6) is generated from the tree at its own commit, never copied from this plan.
+- Only 15 storage domains live in `src/core/engine-sql/`; 54 engine members still own their SQL (`scripts/engine-sql-baseline.tsv`), including both keyword search methods and config.
+- The largest raw-SQL user is `src/core/persistence` (353 files, 83,862 lines, 1,487 raw-SQL lines at 9f1d54232d), then `src/commands` (614, of which `commands/doctor` 294), `core/repair` (334), `core/facts` (244), `core/minions` (204), `core/cycle` (167), `core/trust` (135), `core/shared-skills` (125), `core/page-state` (113), `core/belief` (109), `core/access` (108) and `core/search` (100) (`research/01`, `research/08`, re-counted with the pattern above). Persistence, page state and facts (1,844 lines together) gate Phase 7 and so the preview: their size sets the date of first user value.
+- The ratchet (`scripts/check-engine-sql-ratchet.ts`) sees only engine class members. It cannot see SQL in helpers that take `Pick<BrainEngine, 'executeRaw'>`, such as `src/core/feedback/store.ts:340`.
+- Tests: 790 of the 830 files that call `testBackends()` (re-measured at 9f1d54232d) also call `executeRaw` for setup or assertions.
+
+### Options considered
+
+**A. Typed engine plus a typed-methods track (chosen).** Track 1 builds the Rust engine against typed methods and gates the rest by capability. Track 2 moves raw SQL into typed engine methods subsystem by subsystem, for all engines.
+- Fixes the root causes (planner statistics, filtered ANN, WASM limits) because the Rust engine has no SQL planner at all.
+- Leaves PGLite and Postgres behavior unchanged: Track 2 moves SQL without changing it, and the same tests prove it.
+- Makes the seam real. `docs/ENGINES.md` already says "the interface assumes no SQL", while `executeRaw` says otherwise; Track 2 makes the first statement true.
+- Cost: Track 2 is most of the work. It is done as many small, behavior-preserving PRs that also give the Postgres engines typed, testable boundaries.
+
+**B. A Rust search and index accelerator first.** Rust would own vector and text indexes as a derived sidecar while PGLite or Postgres stays the record store.
+- Fixes the two largest latency pains (filtered ANN and FTS) and the PGLite HNSW out-of-memory quickly.
+- But it changes how the existing engines behave, which the merge process rules keep out of Rust PRs; it needs a second commit point kept consistent with Postgres across crashes (an outbox fed by triggers); Postgres hosts would need the native addon; it does nothing for planner statistics on other tables, per-statement overhead or the WASM data cap; and it does not move toward retiring PGLite.
+- Its useful parts (`gbrain-vector`, `gbrain-text`) are built in option A anyway. Kept as a possible later offer to Postgres users (open question 8).
+
+**C. An embedded Rust SQL engine that speaks enough Postgres, through a translation shim.**
+- gbrain's SQL uses plpgsql triggers, jsonpath, tsvector, `WITH RECURSIVE`, window functions, `DISTINCT ON`, `LATERAL`, `FOR UPDATE SKIP LOCKED`, advisory locks, `set_config` and catalog queries. Rust SQL libraries (sqlparser-rs, DataFusion, GlueSQL) cover parsing and analytics, not this dialect with OLTP semantics.
+- It would also bring back a planner, which is the source of the measured pain. Rejected.
+
+**C'. A native embedded Postgres binary in place of WASM.** Not Rust, but worth naming: it keeps all SQL working and removes the 2 GiB cap. It ships a database server and extension builds per platform, keeps the planner and filtered-ANN problems, and does not match the user's direction. Rejected for this plan.
+
+### Track 2 rules
+
+- One subsystem (or one file family) per PR. The SQL moves into `src/core/engine-sql/<domain>.ts` behind typed methods, and both Postgres-dialect engines delegate, following the "Storage method" row of `CONTRIBUTING.md` "Where does my change go?". No behavior change; changed assertions explained in the PR body.
+- Methods are named for what they mean (`journal.claimNext(...)`), not for the SQL they replace.
+- New methods are grouped as domain objects on the engine (`engine.journal`, `engine.queue`, `engine.access`, ...), each declared in its own module and referenced from `engine.ts` with one line, so `engine.ts` grows by one line per domain, not per method. This limits contention on a shared file and its `check:module-size` ceiling.
+- A new shrink-only ratchet, `check:engine-raw-sql-ratchet` with `scripts/engine-raw-sql-baseline.tsv`, counts raw-SQL call sites per file outside the engines, including helpers that take the engine or an executor. It runs in `verify`. A new raw-SQL call site outside an engine fails it. Decision D6.
+- Each Track 2 PR also moves the touched tests' setup and assertions off `executeRaw` onto typed helpers or the relation API (below), so those test files can join the Rust arm.
+- Order follows what an embedded brain reaches first: search arms and keyword methods; the 24 shared baseline method families (config, raw data, ingest log, ontology, dream verdicts, eval capture); the persistence journal, claims, counters, publication, recovery records and effects; page state, projections, generations and page bodies; facts (remember, forget, withdrawal, purge) and takes; the belief ledger; the minion queue, cycle locks and budget meter; access, trust, tokens and OAuth; mentions and entity identity; cycle phases and dream; repair; doctor checks; remaining commands.
+- Track 2 is required for the Rust engine, not optional (D18). Every raw-SQL call site a Rust brain can reach moves to typed methods or the relation API: migrations (as typed store-format steps on Rust, never SQL), doctor, the tests in the Rust arm, and the seven gbrain-evals files that run raw SQL against gbrain's schema (`cat18`, `cat19`, `cat22`, `cat24`, `cat27`, `cat28` and `longmemeval.ts`, `research/11`), which that repository's maintainers move under D11. Capability gating is a temporary state on the way, never the end state. Checkpoint C1 can still narrow or stop the Rust engine as a whole.
+- Postgres-only administration is never moved; it needs `postgres_admin`, which a Rust brain never reports, so the command refuses with the typed error.
+- Coordination with the merge process, per T-PR: a `heads-up:` comment naming the subsystem, the files and the baseline rows before the branch is pushed. If the merge process reports open PRs on the same files, the T-PR waits or is cut smaller instead of racing them. Churn on master in the 30 days before 9f1d54232d (first-parent commits): `src/core/engine.ts` 21, `src/core/engine-sql/` 59, `src/core/persistence/` 279, `scripts/module-size-limits.tsv` 215.
+- `src/core/engine.ts` is 2,890 lines, exactly its `check:module-size` ceiling (`scripts/module-size-limits.tsv:19`). Each domain object adds at most one line to it, its types live in their own module, and the ceiling row change with its reason rides in the same PR under the `scripts/` heads-up.
+- Track 2 is written by the Rust engine effort and landed and sequenced by the merge process, which does not write code. Before the first T-PR, a `question:` to the merge process asks whether other work it lands should follow the D6 ratchet the same way, so SQL moves in one direction only.
+
+### The relation API
+
+A small typed, non-SQL interface on every engine: `readRelation(name, { equals, range, orderBy, limit, after })`, `relationDigest(name)`, and, on the Rust engine only, `importRelation(name, rows)`. It is not a query language: equality and range filters on catalog columns only. It serves three users: tests that today inspect rows with `executeRaw`; the migration copier's target side; and the verification digest that both engines compute the same way.
+
+## Phases
+
+Track 2 starts in Phase 4 with the raw-SQL ratchet (PR 6), the search arms and the 24 shared baseline method families. The rest of Track 2 starts only after Checkpoint C1. Each phase lists entry and exit criteria.
+
+First value goes to PGLite users on darwin-arm64 or linux-x64-glibc who hit the measured pain above (filtered vector latency, the HNSW memory ceiling, stale planner statistics, write throughput). The preview (Phase 8) is built for them.
+
+**Phase 0: research map (done).** Twelve maps in `docs/designs/rust-engine/research/`, pinned to gbrain 36bd05806a and gbrain-evals 9ecc5b20:
+01 engine interface and raw-SQL bypass; 02 schema, triggers, RLS; 03 search pipeline; 04 ingest, chunking, embedding; 05 CLI and MCP surface; 06 graph and knowledge layer; 07 jobs, queue and cycles; 08 concurrency and persistence; 09 access and security invariants; 10 tests as an oracle; 11 gbrain-evals as an oracle; 12 performance and operations.
+
+**Phase 1: toolchain and CI.** Entry: this plan approved, and an effort budget through Checkpoint C1 recorded in this document by the maintainer (recorded: 8 calendar weeks or 25 merged PRs from PR 1, whichever comes first). Work: PR 1 alone. Exit: the CI lane is green; a trivial addon loads in Bun 1.4.4 and in a `bun build --compile` executable through `process.dlopen`; async tasks, typed arrays and panic-to-error work in Bun; shutdown with pending tasks, cancellation after start, process exit with pending native work and a full or closing threadsafe-function queue behave as the lifecycle rules above require; the added CI time is reported to the merge process.
+
+**Phase 2: storage, ANN and text bake-off.** Entry: Phase 1 landed. Work: compare record stores (redb, and bundled SQLite used only as a plain key-value record store; brain relations and their invariants are never built from SQLite tables, constraints or triggers, since the Rust engine has no SQL dialect, D18), ANN options (usearch with predicate filtering, LanceDB filtered ANN with its exact-scan fallback, an own HNSW, exact SIMD scan over roaring bitmaps) and text options (tantivy with a custom ts_rank scorer, an own postings table). Corpora at 10k, 200k and 1M chunks with real 1,024- and 1,536-dimension vectors (the scale fixture's 16 nonzero dimensions make HNSW look easy, `scripts/scale/fixture.ts:70`). Measure recall@10 against exact, p50 and p99 at filter selectivities 100, 50, 10, 1 and 0.1 percent, build time and peak RSS, disk size, crash recovery, addon size, and how exactly `ts_rank` is reproduced; PGLite and Postgres on the same machine as baselines. Per D17 it also measures concurrent read throughput at 1, 4, 16 and 64 clients, concurrent write throughput at 1, 4, 16 and 64 writers, graph traversal at depth 1 to 5 against Postgres `WITH RECURSIVE`, and peak and steady RSS per 100k chunks. Beating Postgres on the writer curve is a bake-off criterion. The record store must support concurrent writers (D17, D19): for example per-relation or sharded writers with group commit, or an MVCC store; a single writer with group commit is measured as a baseline only. Server-ready criteria join the bake-off (D19): transactions and snapshots work across processes and connections, not only threads in one process (measured with several client processes through the owner IPC socket); no global singletons or per-process state that assumes one caller; and a store format that can carry a commit log or snapshot stream a follower can consume, even though no follower is built yet (section "Path to a multi-user server"). Readers stay lock-free snapshots and use all cores, including parallel ANN and text arms. No PGLite-style locking joins the criteria (D20): no process-wide writer lock on the hot path; a second process opens the brain and reads and writes without busy errors; lock waits, conflict retries and p99 under contention are measured and reported for every option. The embedded phases still run one owner process per brain directory and refuse multi-host writers (D19), but no store option may depend on either. Before any Rust number exists, `bakeoff.md` names the target machines and the memory envelope (proposed: a 16 GB darwin-arm64 laptop and an 8 GB linux-x64-glibc VM, with a resident-memory budget at 200k chunks written there), and a memory budget per 100k chunks (f16 or quantized vectors and memory-mapped indexes allowed), measured against Postgres RSS as well as PGLite's. Exit: `docs/designs/rust-engine/bakeoff.md` names the choices with data, and they meet the performance targets and the D17 bar below on those machines, or `bakeoff.md` lists each loss with its planned fix for Checkpoint C1. `bakeoff.md` compares only SQL-free designs: every record-store option is judged as a key-value store behind the typed methods, on correctness burden, migration and maintenance as well as speed (D18). The idiomatic-SQLite slice the review record mentions was removed by D18. LanceDB is judged with its binary size counted. The simplest option that meets the targets and the server-ready criteria wins; an own HNSW only with a measured advantage.
+
+**Phase 3: parity oracle.** Entry: Phase 1 landed; runs beside Phase 2. Work: the in-tree harnesses (`src/commands/eval-longmemeval.ts` and `src/eval/`) take any `BrainEngine` instead of `PGLiteEngine`, which makes them the primary oracle with no driver protocol. In gbrain-evals, under that repository's terms (D11), its maintainers write and land the changes: one helper over gbrain's exported `engine-factory`, used only in the eval-gate runners (frozen and counted files stay untouched); setup-only SQL moves to typed calls where gbrain has them, while SQL that independently checks what gbrain stored moves to typed methods or the relation API too, as D18 requires; until a file moves, its SQL checks report `not_applicable` on the Rust arm and no gate that depends on them passes for Rust; one neutral embedding fixture keyed `(model, dims, side, sha256(text))`; and a LongMemEval warm-cache rebuild (about $2) only after the current LongMemEval work there is done, with a decision line and a cost cap, never committed. `research/11` maps an older gbrain-evals commit; the maintainers' count on current main is 91 engine-construction sites in 83 files and 184 raw-SQL calls in 67 files, the three runners `research/11` calls broken work, and the gbrain dependency is already pinned. gbrain's in-tree harness is the main parity check; gbrain-evals confirms it. Exit: two PGLite runs at the pinned release give identical results; the PGLite and Postgres baseline numbers are recorded (D17).
+
+**Phase 4: engine seam.** Entry: Phase 1 landed; D1, D2, D3 and D6 approved. Work: PRs 4 to 9. Exit: a Rust brain constructs, reports its capabilities and refuses everything else with typed errors; the Rust test arm runs; the raw-SQL and kind-branch ratchets run in `verify`; no change for any existing user.
+
+**Checkpoint C1: continue, narrow or stop.** Entry: Phases 2, 3 and 4 done. Inputs: `bakeoff.md`; a real-brain read benchmark (the maintainer exports their own brain with `rust/scripts/export-corpus.ts` and runs the bake-off harness against PGLite and Postgres on the same brain, whatever engine the brain uses; only aggregate numbers are published and no user is switched); a replay against an engine the brain does not use is labeled snapshot replay, not live shadow evidence; the Track 2 size per subsystem re-counted at that commit; effort spent against the Phase 1 budget. Outcomes, decided by the maintainer and recorded in `bakeoff.md`: continue (the rest of Track 2 starts); narrow (keep the ratchets, the capability set and the typed methods already landed, and pause Rust domain work); or stop (one PR removes `rust/`, the Rust test arm and the `rust` kind, and keeps the ratchets and typed methods, which help the existing engines).
+
+**Phase 5: core storage domains.** Entry: Phases 2 and 4 done; Checkpoint C1 decided continue. Work: PRs 10 to 14b implement the 15 migrated `engine-sql` domains, config, and the trigger equivalents. Exit: the domain tests, `test/e2e/engine-parity.test.ts` cases for those domains and the trigger parity matrix pass on the Rust arm; a small PGLite to Rust to PGLite roundtrip through the graduation adapter verifies exactly on the domains implemented so far, including consumed but unused sequence values, generated columns, withdrawals and database-only content.
+
+**Phase 6: search parity.** Entry: Phase 5 done; Track 2 search arms landed; the Phase 3 exit met, including the gbrain-evals changes landed and pinned (D11). Work: PRs 15 to 17. Exit: search tests pass on the Rust arm; eval gate E1; performance targets at 10k and 200k met, 1M reported.
+
+**Phase 7: write path and owner model.** Entry: Track 2 persistence, page-state and facts subsystems landed. Work: PRs 18 to 20 plus the Rust side of those Track 2 subsystems. Exit: `put_page`, `remember`, `forget`, `sync` and the minimum jobs (`sync`, `embed`, `extract`, `backlinks`) run through the persistence coordinator on Rust; the crash robot passes; memory-verb conformance 24/24; eval gate E2.
+
+**Phase 8: preview.** Entry: capability coverage of the core loop (ingest, sync, search, query, the seven memory verbs, the minimum jobs, doctor) is complete; `gbrain backup create` and `backup restore` work on Rust brains (PR 21b) and a full-store restore drill passes on both preview targets; the addon upgrade drill passes (stage, verify, switch, keep the previous addon; an upgrade with no network leaves the brain working or refusing with `engine_unavailable`, with no data touched); paired runs with confidence intervals show the Rust engine equal or better than Postgres and PGLite on every metric in "Performance" (D17); D4, D8 and D12 approved. Work: PRs 21, 21b, 22 and 23: `migrate --to rust` and back, backup and restore, store format and doctor checks, released addons with a staged upgrade. Exit: preview users can move a brain to Rust and back with verification; eval gate E3.
+
+**Phase S: shadow mode.** Entry: Phase 6 done (the follower needs `importRelation` and the graduation adapter from Phases 5 and 14b; read comparisons need search); D13 approved. Work: PRs S1 to S4, delivered so evidence arrives early: after S2 the supported read and search comparisons run with a provisional Markdown and JSON report, before write comparisons and full reconcile exist. Every partial report says `NOT READY`. Operations Rust cannot answer yet count as `capability_missing`, which makes the remaining Track 2 work visible on the real workload. The maintainer runs shadow mode on their own brain from S2 on; its reports feed the preview decision (D8) and PGLite deprecation criterion 9. Exit: 14 days of shadowing on the maintainer's brain with zero privacy divergences and a report that lists every remaining blocker.
+
+**Phase S-swap: swap and the way back.** Entry: Phase 8 entry criteria hold (backup and restore, staged addon upgrade); D14 and D15 approved. Work: PR S5. Exit: the swap, failback and recovery-point drills pass on both preview targets for a PGLite brain and a single-writer Postgres brain; the maintainer's brain reaches `READY` and is swapped with a reverse shadow kept for the recommended period. Shadow mode then becomes the recommended route into the preview, with `migrate --to rust` kept for PGLite users who choose the direct path.
+
+**Phase 9: full parity.** Work: the remaining Track 2 subsystems and their Rust side; more platforms (PR 24). Exit: every PGLite deprecation entry criterion below holds; eval gate E4.
+
+**Phase 10: PGLite deprecation.** A separate PR after the maintainer's yes (D9): the `gbrain init` default changes, a `deprecations.d/` record and notices ship, and PGLite stays loadable for `migrate --to rust` for a long, stated window.
+
+**Postgres deprecation: deferred.** It comes after the multi-user server phases below, as its own decision with its own plan covering hosted and multi-host brains, pooled concurrency and remote clients. Nothing in this plan removes or degrades the Postgres engine.
+
+## Path to a multi-user server
+
+The target end state (D19) is a full multi-user Rust server that supersedes Postgres and pgvector and is 10x better than them (D17). Phases 1 to 10 build the embedded engine. The phases below come after the opt-in swap (Phase S-swap). This plan approves none of them: each starts only after the maintainer's yes, recorded in this document, and each exit measures the D17 bar against Postgres in the same configuration. Until Phase M3 passes that bar, brains with writers on more than one machine stay on Postgres.
+
+**Phase M1: server mode and wire protocol.** Entry: the maintainer's yes; Phase S-swap done; the server-ready criteria in "Process model" hold. Work: a server mode in which one Rust engine process serves a brain to many clients; a wire protocol that carries the typed `BrainEngine` methods, so the MCP and CLI contract stays the same (operation names and schemas, the error envelope, write receipts and exit 10, the memory verbs). Exit: the engine tests and memory-verb conformance pass through the wire protocol; CLI, JSON and MCP goldens are identical against an embedded brain and a served brain; the latency the wire adds is measured and listed.
+
+**Phase M2: authentication and per-user access.** Entry: M1 done; the maintainer's yes. Work: per-user credentials on the server; the access checks in `gbrain-domain` (the typed write-scope argument, source scoping and the invariants I1 to I15) enforced per user and per connection, as the replacement for Postgres RLS. Exit: the per-operation authorization tests pass for each user; Rust equivalents of the RLS-role tests pass; gbrain-evals Cat 22 has zero leaks.
+
+**Phase M3: multi-process and multi-machine writers.** Entry: M2 done; the maintainer's yes. Work: writers on several hosts write through the server; claim and lease exclusivity, fencing tokens and per-entity fact ordering hold across connections and hosts; `multiple_writer_hosts` no longer refuses a brain the Rust server serves. Exit: concurrent write throughput at 1, 4, 16 and 64 writers from several hosts meets the D17 bar against Postgres with the same clients; the crash robot passes with writers on more than one machine; a multi-host Postgres brain moves to a served Rust brain through shadow mode and back.
+
+**Phase M4: replication, high availability and backups.** Entry: M3 done; the maintainer's yes. Work: a follower that consumes the store's commit log or snapshot stream; failover with fencing, so only one primary writes; online backup and point-in-time restore. Exit: failover and restore drills pass with no committed write lost outside the stated loss interval; backup and restore cover everything Postgres backups cover on the same brain.
+
+**Phase M5: Postgres deprecation, a separate decision.** Entry: M1 to M4 done, and the server meets the D17 bar on every axis, hosted and multi-host brains included. Work: its own plan and the maintainer's separate yes. Exit: the maintainer's decision on that plan is recorded in this document; this plan authorizes no deprecation. Nothing before then removes or degrades the Postgres engine.
+
+These server phases constrain choices in Phases 1 to 8:
+
+- Store bake-off (Phase 2): concurrent writers are required; transactions and snapshots must work across connections and processes; no option may depend on one owner process; the format must be able to carry a commit log or snapshot stream.
+- Transaction API (the interface in PR 8, Phase 4; its implementation in Phase 5): a transaction is bound to a connection handle, not to a thread or a process; `transaction(fn)` holds no state that a second connection could not hold; the writer permit comes from a bounded pool.
+- Access layer (Phases 5 and 7): the typed write-scope argument and the I1 to I15 checks live in `gbrain-domain`, never in `gbrain-napi` or the TypeScript wrapper, so a server enforces the same checks per user.
+- Store format (PR 19): the format note describes the replication and backup hooks; they are designed, not built.
+
+## PGLite deprecation entry criteria
+
+All must hold at one pinned commit, on every platform where PGLite would be deprecated:
+
+1. Capability coverage is complete: `check:rust-capability-coverage` reports no operation, command, phase or handler that a PGLite brain can run and a Rust brain refuses (Postgres-only administration excluded by name).
+2. The raw-SQL ratchet shows zero call sites reachable from those entries.
+3. Every file in the `testBackends()` set has a Rust arm listed in `test/rust-unit-arms.txt` and passing, except rows in a reviewed `test/rust-expected-divergence.tsv` limited to Postgres-dialect tests (SQL-text goldens, prepared-statement and RLS-role tests), each with a reason.
+4. CLI, agent-contract, catalog, decide and trust goldens are identical on a Rust brain; doctor goldens differ only in the listed engine-specific checks.
+5. Eval gates E1 to E4 pass.
+6. The Rust engine is no slower than PGLite on any `scripts/scale/budgets.json` entry, meets the targets below at 200k and 1M chunks, and meets the D17 bar: equal or better than Postgres and PGLite on every metric in "Performance".
+7. `migrate --to rust` and back verify exactly on the engine-graduation fixtures (1k, 10k, the embedding variants and the hand-made legacy brain) and preserve every database-only category.
+8. The crash robot and the concurrency suite pass on the Rust arm.
+9. At least four weeks of daily use on real brains with no data loss, no privacy difference and no open P1 bug against the engine. Dates, brain size bands and incidents are recorded in `docs/designs/rust-engine/preview-log.md`. Shadow reports from at least three real brains (the maintainer's included) reach `READY` on the deprecation commit, with their aggregates in `docs/designs/rust-engine/shadow-log.md`.
+10. Prebuilt addons exist for each platform being deprecated.
+11. Every PGLite-only user surface has a Rust path or a stated replacement: `backup create` and `backup restore` (`src/core/backup/snapshot.ts` refuses non-PGLite brains today), agent-install setup (`src/core/agent-install/setup.ts`), `init --pglite`, `pglite-repair` and `reinit-pglite`, and the eval harnesses that construct `PGLiteEngine`.
+12. An upgrade with no network access leaves every Rust brain either working on its pinned addon or refusing with `engine_unavailable` and the fix command, with no data touched; proven by a drill on each platform.
+
+## PR sequence
+
+Every PR targets `master`, carries the `rust-engine` label and a `changelog.d/` fragment, gets `full-ci` when its head is final, and lands through a `queue:` comment. "Heads-up" means a `heads-up:` comment before the change, kept in its own small PR. "Yes" names the decision whose quote goes in the PR body. No PR before Phase 8 changes anything for an existing user, so none adds a `behavior-changes.d/` entry until then.
+
+| # | Plain title | Main paths | Heads-up | Yes |
+|---|---|---|---|---|
+| 1 | Rust toolchain and CI lane for the engine (alone, first) | `rust/` workspace with a trivial `gbrain-napi` crate, `rust-toolchain.toml`, `Cargo.lock`, `deny.toml`; `rust/README.md` contributor quickstart (rustup is the only prerequisite; `bun run rust:build` builds the addon and prints its path and the `GBRAIN_RUST_ENGINE_ADDON` line; one `GBRAIN_TEST_BACKEND=rust bun test <file>` command; how to unset the override; the measured first-build time); a `rust:build` script entry in `package.json`; `.github/workflows/rust-engine.yml` (path-filtered to `rust/**`, `src/core/rust-engine*`, `src/core/engine.ts`, `src/core/engine-*.ts`, `src/core/engine-sql/**`, `src/schema.sql`, `src/core/migrate.ts`, `src/core/schema-migrations/**`, `src/core/persistence/graduation-*.ts`, `test/helpers/test-backends.ts`, `test/rust-unit-arms.txt`, `scripts/rust-unit-arms.ts` and the workflow itself; fmt, clippy, tests, cargo-deny, addon build on linux-x64 and darwin-arm64, Bun load smoke including a compiled executable) | `.github/` (full review; CI time stated) | none |
+| 2 | Bake-off harness | `rust/bench/`, `rust/scripts/export-corpus.ts` | none | none |
+| 3 | Bake-off report | `docs/designs/rust-engine/bakeoff.md` | none | none |
+| 4 | In-tree eval harnesses accept any engine | `src/commands/eval-longmemeval.ts`, `src/eval/**` (types widened from `PGLiteEngine` to `BrainEngine`) | none | none |
+| 5 | Engine capability set, reported in full by both engines | `src/core/engine.ts` (`capabilities`), both engines, `src/core/engine-capabilities.ts` | `engine.ts` | none |
+| 6 | Raw-SQL and engine-kind ratchets | `scripts/check-engine-raw-sql-ratchet.ts`, `scripts/engine-raw-sql-baseline.tsv`, `scripts/check-engine-kind-branches.ts` and baseline, `package.json` script entries, `verify` | `scripts/` | D6 |
+| 7 | Relation API on the Postgres-dialect engines | `src/core/engine-sql/relations.ts`, `engine.ts` | `engine.ts`, `engine-sql/` | none |
+| 8 | Rust engine shell, refusing everything with typed errors | `src/core/rust-engine.ts`, `src/core/rust-engine/` (including `members.ts`), `engine-construct.ts`, `kind` union and every other two-engine union, inventory `engines.rust` type, config value, `docs/ENGINES.md` "Adding a new engine" note that a non-SQL engine implements typed methods instead of a `SqlExecutor`, `openEngine` kind, `--engine` on in-tree eval commands, error registry, doctor check `rust_engine_available` (`not_applicable` unless selected) | `engine.ts`, doctor goldens | D1, D2, D3 |
+| 9 | Rust test arm | `test/helpers/test-backends.ts` (`GBRAIN_TEST_BACKEND=rust` selects the arm for files in `test/rust-unit-arms.txt`; never implicit), `scripts/rust-unit-arms.ts`, an exhaustive engine-for-backend test helper and the Rust-kind assertion, `rust-engine.yml` job, `.github/workflows/full-ci.yml` dispatching `rust-engine.yml` only when the same path filter matches (estimate: about 10 minutes per OS for a cold addon build and 3 minutes with the cache, on two OSes in parallel; PR 1 reports the measured time), a trigger-selection check | test harness, `.github/` | none |
+| 10 | Rust store core: sources, config, pages, tags, generation and revision rules | `rust/crates/gbrain-store`, `gbrain-domain`, `rust/catalog/`, wrapper methods | none | none |
+| 11 | Chunks, stored vectors, exact vector scan, files, code edges | `rust/crates/*`, wrapper | none | none |
+| 12 | Links, timeline and graph walks | `gbrain-graph`, `gbrain-domain` | none | none |
+| 13 | Facts and takes storage with withdrawal and purge guards | `gbrain-domain`, `rust/fixtures/` | none | none |
+| 14 | Segmented page bodies, salience, health, titles | `gbrain-domain` | none | none |
+| 14b | Engine-neutral graduation adapter and an early PGLite to Rust to PGLite roundtrip on the domains so far | `src/core/persistence/graduation-*.ts` (catalog inspection, canonical rows, counters, fencing and verification through the adapter), `src/core/rust-engine/` | `persistence/` | none |
+| 15 | Keyword, title and CJK search on Rust | `gbrain-text` | none | D5 |
+| 16 | Filtered vector search, facts arm, cosine rescore on Rust | `gbrain-vector` | none | none |
+| 17 | Trigram matching: find, resolver, saved facts on Rust | `gbrain-trgm` | none | none |
+| T1 to T14 | "Move <subsystem> SQL behind engine methods" (Track 2, one subsystem each, in the order listed above), each followed by an R-PR implementing it on Rust and adding test files to the Rust arm | `src/core/engine-sql/<domain>.ts`, the subsystem's files, its tests | `engine.ts`, `engine-sql/`, baseline rows | none |
+| 18 | Single-owner capability replaces PGLite kind checks in lock and IPC paths; a second process becomes an owner client for reads and writes, never `pglite_busy` (D20); the owner protocol extension in "Process model" | `src/core/pglite-lock.ts` callers, `resolve-ipc.ts`, `persistence/ipc.ts`, `persistence/local-client.ts`, consumer election | none | none |
+| 19 | Store format version, schema migration dispatch for Rust stores, index lag and rebuild checks | `gbrain-store`, `src/core/migrate.ts` and `src/core/schema-migrations/types.ts` (Rust disposition per migration), doctor checks | doctor goldens, `migrate.ts` | D2, D7 |
+| 20 | Crash robot, fuzz and scale cells for Rust | `scripts/persistence/`, `scale-tier.yml`, `rust-engine.yml` | `scripts/`, `.github/` | none |
+| 21 | `gbrain migrate --to rust` and back, PGLite brains only | the graduation adapter from PR 14b on both directions, inventory `engines.rust` rows, `src/commands/migrate-engine.ts` | none | D1 |
+| 21b | `gbrain backup create` and `backup restore` for Rust brains, with a full-store restore drill | `src/core/backup/` (a Rust snapshot taken under the owner lock at one committed generation, with derived indexes carried with their generation or rebuilt; the PGLite snapshot path unchanged), `src/commands/backup.ts` | none | D1 |
+| 22 | Released, attested engine addons with a pinned digest manifest, `gbrain engine install rust` (with `--from <file>` for offline import) and a staged upgrade | `release.yml`, `src/cli/commands/engine.ts` (the `engine` dispatcher, which routes only `status` today), a new `src/commands/engine-install.ts`, `src/core/binary-self-update.ts` staging, post-upgrade refresh, `engine status` fields | `.github/` (full review, install path) | D4 |
+| 23 | Rust engine preview documentation | `docs/ENGINES.md` (new section with a tested user quickstart: check the target, `gbrain backup create`, `gbrain engine install rust`, `gbrain migrate --to rust --plan`, then `--yes --expect <hash>`, one search, `gbrain engine status`, and the way back; expected output for each step; the capability list; a RustEngine column in the capability matrix), `docs/guides/troubleshooting.md` symptom rows for each new code and reason, `INSTALL_FOR_AGENTS.md` (an agent never moves a brain to Rust unless the user asks), `README.md` limits, how to report a preview problem (a GitHub issue titled `rust engine:` with `gbrain engine status --json` and `gbrain doctor --json` attached; no telemetry) | none | D8 |
+| S1 | Shadow mode core: supervised shadow child process, transaction-aware engine wrapper, mirror queue, metrics ledger and evidence manifest (off unless started) | `src/core/shadow/` (wrapper built with `registerEngineView` and extended to transaction-bound engines and group publication, invalidation collection with savepoint discard, bounded fail-open IPC, child supervisor, ledger writer), `src/core/engine-factory.ts` (wraps only when shadow is on), config keys | `engine-factory.ts` | D13 |
+| S2 | Read comparisons: pipeline observer, captured caller context and provider outputs, shadow execution mode without side effects, revision- and generation-aware classification, per-item privacy check, provisional report | `src/core/shadow/compare*.ts`, `src/core/shadow/observer.ts` (hooks in `src/core/search/hybrid/arms.ts` and the operation dispatcher), result normalizers, replay buffer, `rust/crates/gbrain-napi` read-only entry points | `src/core/search/` (heads-up) | D13 |
+| S3 | Seed, follow and reconcile, with the Postgres read-only source side and the `live-shadow` policy of the graduation adapter, allocator manifests, and rolled-back write comparisons on a copy-on-write snapshot | `src/core/persistence/graduation-*.ts` (one transaction-bound `REPEATABLE READ` export handle with a snapshot-age budget, shared-bound key intervals, `migration`/`live-shadow`/`reverse-shadow` policies, comparison inventory), `src/core/shadow/reconcile.ts`, `src/core/shadow/write-compare.ts` | `persistence/` (full review: stored data) | D13 |
+| S4 | `gbrain engine shadow` commands, the generated report and charts, doctor check `rust_shadow`, and the shadow quickstart | `src/cli/commands/engine.ts`, `src/commands/engine-shadow.ts`, `src/core/shadow/report*.ts` (decision brief, markdown, JSON, SVG), `bench`, daily rollup as an autopilot cycle step, doctor check and goldens; `docs/ENGINES.md` shadow quickstart with expected output, time to first report, resource and privacy notice, stop and delete; troubleshooting rows; `INSTALL_FOR_AGENTS.md` rule (agents read status and reports freely; starting a shadow needs the user's request) | doctor goldens | D13, D14 |
+| S5 | `gbrain engine swap` with durable writer observations, the pre-swap recovery checkpoint, the write fence, route verification, the reverse shadow, failback and recovery points, and the swap docs | `src/commands/engine-swap.ts` (persisted states, `--status`, `--resume`), writer-observation table and writers, the graduation adapter's Rust to Postgres and Rust to PGLite directions under `reverse-shadow`, error registry rows, `behavior-changes.d/`, `docs/ENGINES.md` swap and failback guide | schema and migrations (writer observations), `persistence/`, `engine-graduation.ts` (full review: stored data and auth) | D14, D15 |
+| 24 | More platforms: linux-arm64, darwin-x64, musl, Windows | `rust-engine.yml`, `release.yml` | `.github/` | none |
+| 25 | PGLite deprecation (later) | `gbrain init` default, `deprecations.d/`, notices, `behavior-changes.d/` | config defaults | D9 |
+
+S1 to S4 start after PR 17, with S2's provisional report first; S5 waits for PRs 21b and 22. PRs 2 to 4 can run in parallel after PR 1. T-PRs for the search arms and the 24 shared baseline families start after PR 6; the other T-PRs start after Checkpoint C1. Both run beside PRs 10 to 17.
+
+## Testing and proof
+
+### Engine test arm
+
+- `testBackends()` (`test/helpers/test-backends.ts:15`) gains a `rust` backend selected only by `GBRAIN_TEST_BACKEND=rust` and only for files listed in `test/rust-unit-arms.txt`. Default developer runs are unchanged and need no Rust toolchain. Selecting `rust` without a loadable addon fails loudly, as `requirePostgresTestDatabase` does for Postgres.
+- Most test files choose their engine with a two-way branch such as `backend === 'postgres' ? requirePostgresTestDatabase() : undefined`, which would build a PGLite brain under a `[rust]` label and pass. So the arm is selected by a runner, `scripts/rust-unit-arms.ts`, modeled on `scripts/postgres-unit-arms.ts`, which runs only the listed files with `GBRAIN_TEST_BACKEND=rust`; an exhaustive engine-for-backend helper replaces the two-way branch in a file before it is listed; and every engine opened under the Rust arm must report `kind === 'rust'`, or the file fails. A check refuses a listed file that still has a two-way backend branch.
+- The Rust CI lane builds the addon once and runs the listed files, sharded like the unit lane.
+- Divergences live in `test/rust-expected-divergence.tsv` and run as `test.failing`, the `EXPECTED_FAILURES` pattern of `test/helpers/two-engine.ts:308`, so an unexpected pass fails.
+- Targets beyond the unit files: `test/e2e/engine-parity.test.ts` with a Rust half; the two-engine isolation suite; `test/memory-verbs-conformance.test.ts`; the 81 black-box CLI files (`research/10` section 7) run against a temporary Rust brain.
+
+### Goldens
+
+- Engine-neutral goldens (`cli`, `catalog`, `decide`, `trust`, agent-contract fixtures) must be identical on a Rust brain.
+- Doctor goldens: identical except engine-specific checks, listed in the PR that adds them.
+- `test/fixtures/goldens/sql-text/` and `pglite-upgrade-replay` are Postgres-dialect artifacts and do not run on Rust.
+- Rust-only exactness fixtures (trigger results, `ts_rank`, `pg_trgm`, fingerprints, jsonb order, collation) live in `rust/fixtures/`, generated from PGLite by `rust/scripts/`, so they do not churn shared golden files.
+
+### Eval gates
+
+Rules: TypeScript on PGLite, TypeScript on Postgres and Rust run on the same machine, the same fixture and one pinned gbrain commit; thresholds are written before any Rust number exists and are not changed after; published numbers (LongMemEval from v0.28.8) are sanity checks only.
+
+| Gate | Phase | Benchmarks | Pass |
+|---|---|---|---|
+| E1 | 6 | In-tree LongMemEval `_s` retrieval only (500 questions, top-5, embedding fixture): keyword, vector, hybrid. gbrain-evals Cat 13, Cat 13b, Cat 10, Cat 12, Cat 7 | R@5 per adapter at least both the PGLite and the Postgres value, per-question top-5 differences listed; Cat 13 nDCG@5 and Cat 13b top-1 at least both values; Cat 10 133/133; Cat 12 50/50; Cat 7 reported |
+| E2 | 7 | BrainBench Cats 1+2 (graph on), Cat 3, Cat 4, type-accuracy (after its call-site fix), Cat 24, memory-verb conformance | P@5 and R@5 at least both the PGLite and the Postgres value; Cat 4 100%; Cat 24 5/5; conformance 24/24 |
+| E3 | 8 | Cat 22, Cat 19, Cat 27, Cat 23 (scored against PGLite's pg_trgm behavior) | Cat 22 zero leaks; others within 0.5 points or equal counts |
+| E4 | 9 | All of the above at the final pinned commit; minion durability and throughput (`test/e2e/bench-vs-openclaw/`); LLM-judged cats reported in bands set beforehand | all prior thresholds hold |
+
+The E1 and E2 retrieval thresholds are "equal or better", not "within N points", because a better ranker or a higher-recall vector index returns different results (D17). With the `ts_rank` compatibility ranker (D5), the keyword arm must also reproduce PGLite's fixture ordering exactly; that mode stays the regression baseline. E3 is an intentional exception to the D17 change: its thresholds stay as written, and Cat 22 stays at zero leaks.
+
+### Performance
+
+- Scales: 10k, 200k and 1M chunks with real 1,024- and 1,536-dimension vectors; filters on source, type and date at 100, 50, 10, 1 and 0.1 percent selectivity.
+- Bar (D17): the Rust engine must be equal or better than TypeScript gbrain on Postgres (pgvector HNSW, local, same machine, same corpus, same run) and on PGLite, on every metric below. The absolute targets further down are floors, not the bar.
+- Target (D17): 10x better than Postgres and pgvector, the maintainer's goal. The gate stays equal or better; the gbrain-evals preregistration fixes the margin on each axis, and this plan sets no per-axis 10x number.
+- Metrics, each a named step in `rust/bench/` and a card in the gbrain-evals `engine-bench` (D16):
+ - concurrent read throughput at 1, 4, 16 and 64 clients;
+ - concurrent write throughput at 1, 4, 16 and 64 writers: committed writes per second through `transaction(fn)`, outbox apply included;
+ - p50 and p99 for `get_page`, `put_page`, keyword, vector, hybrid and filtered search, single client and at fixed concurrency; end-to-end `query` with a precomputed query embedding (no expansion or rerank) and separately with them;
+ - graph traversal (`traverse_graph`, backlinks, `rank_entities`) at depth 1 to 5 against Postgres `WITH RECURSIVE`;
+ - vector search recall@10 against exact, and p50 and p99 against pgvector HNSW, at 200k and 1M chunks, 1,024 and 1,536 dimensions, filter selectivities 100 to 0.1 percent;
+ - peak and steady RSS, and RSS per 100k chunks;
+ - cold open to first `get`;
+ - import and sync throughput, index build time and disk size.
+- Gate: a Rust arm is not called ready for the opt-in swap (D14 criterion 8) or the preview (D8) unless it is equal or better than Postgres and PGLite on every metric, from paired runs with confidence intervals. A loss on any axis is listed in `bakeoff.md` and in the shadow report with its fix, never hidden.
+- Proposed targets, confirmed or corrected by the bake-off before Phase 5: vector arm p50 at most 20 ms and p99 at most 100 ms at 200k chunks with or without filters; no filtered query more than 2x its unfiltered time; cold engine open at most 50 ms; committed writes at least 3x PGLite; a bounded-memory build at 1M chunks (budget set by the bake-off). These are floors; the D17 bar applies on top of them.
+- Each target has a named step in `rust/bench/` that prints machine, engine, data size, N, p50 and p99, with PGLite and Postgres measured on the same machine in the same run. Write throughput is measured through `transaction(fn)` with the writer held across awaits and includes the outbox apply before return. Peak and steady resident memory at 200k and 1M chunks is reported against the memory envelope and the per-100k-chunk budget in `bakeoff.md`, beside Postgres RSS for the same corpus (f32 vectors at 1M chunks and 1,024 dimensions are about 3.8 GiB raw before any graph).
+- A Rust cell joins `scale-tier.yml`. Benchmarks report; CI gates on relative regressions.
+
+### Crash, property, concurrency and fuzz tests
+
+- Crash: SIGKILL between record commit and index apply, during import, during migration copy and during index rebuild; the open recovers, index lag returns to zero, and a deleted or withdrawn item is never returned.
+- Failure after commit without a crash: inject a failure after the record commit, after the text apply and before the vector apply while the owner stays alive; the receipt says committed, later reads are correct, replay brings the lag to zero, and a retried write is idempotent.
+- Snapshot isolation: pause a search across a concurrent content and permission update; the paused reader returns correct results for its snapshot and never newer restricted content.
+- Typed concurrency operations (D20): each operation in "Concurrency without PGLite-style locks" runs with concurrent callers on PGLite, Postgres and Rust and gives the same observable outcome: no lost update, no double claim, no deadlock. A stress cell runs 64 writers across 8 processes on one brain; a second process opening the brain never gets a busy error. The TLA+ properties in `spec/tla/` stay as tests.
+- Writer admission: start far more concurrent writers than worker threads while the first transaction awaits and then makes another engine call; all finish or time out within the bound, a cancelled waiter leaves nothing behind, re-entry gives `transaction_reentry`, and `disconnect()` finishes cleanly.
+- Fingerprints: create withdrawals and purges before a change, then insert equivalent non-ASCII and mixed-case claims on Rust after migration; they stay suppressed.
+- The crash robot (`scripts/persistence/README.md`: 1,000 seeded schedules, eight SIGKILL boundaries, 10,000 writes from four producers) gets a Rust cell.
+- Property tests (proptest): record encoding round trips, outbox idempotence, filtered search equal to exact search over the same bitmap, trigger hooks equal to the fixture.
+- Concurrency with pause points: a page update against an in-flight embedding job in both completion orders; the refresh-barrier safety properties (`spec/tla/refresh-barrier/`) as executable tests.
+- Fuzz (cargo-fuzz): the tsquery parser, the analyzer, row decoding and every binding entry point with malformed arguments; none may crash the process.
+- `cargo deny` and `cargo audit` in the Rust lane.
+- Drills on darwin-arm64 and linux-x64-glibc before the preview: full-store `backup create` and `backup restore` into an empty home with per-relation digests equal; addon upgrade online, offline and with an interrupted fetch, each ending with the brain working or refusing with `engine_unavailable` and no data touched.
+- Time-to-first-query drill on both preview targets, in a clean home with the 10k-page engine-graduation fixture: from `gbrain engine install rust` to the first search answered on Rust, following the PR 23 quickstart verbatim. Target: 5 minutes. The measured time is written in the preview docs. The PR 1 contributor quickstart is timed the same way (first build reported; edit, build and test loop under 1 minute).
+- Failure drills: a corrupt derived index and a failed open-time replay are repaired by `doctor --fix` through the maintenance path; a newer `FORMAT` gives `newer_format` with no write; an injected panic inside a write transaction returns `internal_error` with a diagnostic id, rolls back, and the next call succeeds; each `engine install` failure state leaves the active addon unchanged.
+- Error rows: one test per code and reason checks the registry row, the rendered `fix`, the `detail` context, and that no environment variable value and no absolute home path appears in the envelope or the diagnostic file.
+
+### Shadow mode tests
+
+- Off path: with shadow mode off, the engine factory returns the bare engine (`kind` and identity checked), no shadow module is imported on the hot path, and the persistence throughput harness shows no change against master.
+- Isolation: inject a slow, failing, panicking, aborting and hanging shadow child and a full IPC queue; every primary call returns the same result, nothing awaits the shadow, the child restarts, and the fault is recorded.
+- Commit capture: outer rollback, nested savepoint rollback, group publication and a committed write with a failed receipt each publish exactly the committed invalidations.
+- Reconcile: deletion, key change, insertion at an interval bound, an empty source relation and a delayed older batch arriving after a newer update all end with equal digests and no newer state overwritten.
+- Allocators: rollback-consumed ids, a deleted highest id and the first insert after each swap direction.
+- Classification: an index-only change, a membership change and an injected wrong Rust revision; a real Rust bug is never classified `stale`, and a repair never turns a mismatch into a match.
+- Privacy: an authorized item that moves into Rust's top 10 is a ranking difference; a wrong visibility rule in the shadow gives `privacy_diverged` on the first event, pauses read mirroring and raises the doctor error. Remote member and folder scope are covered.
+- No side effects: a mirrored search with cache hits and several vector arms makes zero provider calls, writes no telemetry, cache or retrieval timestamp, and nothing flushes later.
+- Write compare: create, conditional update, append, delete, no-op and multi-row writes; `write_uncomparable` when no equal preimage exists; the shadow's logical state is unchanged afterwards.
+- Policies: active jobs and running effects through seed, reconcile and both swap directions; no job or effect runs twice and no worker starts in a shadow store.
+- Overflow and missed writes: fill the queue past its bound; raw SQL, a second process and a second host write while shadow runs; reconcile repairs them and reports counts by relation.
+- Fence and eligibility: a stopped second host, two processes on one host, an already-open transaction and an old client writing after cutover are all refused or reported; unknown writer coverage refuses the swap.
+- Route: an environment `DATABASE_URL` override and an old serving process block the swap before authority changes; the probe confirms the effective engine after the switch.
+- Swap faults: kill, disk full and a failed digest at each persisted state; `--resume` continues, authority never points at an unverified engine, and the old primary is unchanged before the fence.
+- Failback and recovery drills on both preview targets for a PGLite brain and a single-writer Postgres brain: swap, write, fail back with every acknowledged write kept; make Rust unreadable and restore a recovery point with the loss interval stated; copy corruption into the reverse shadow and check that reverse following freezes.
+- Evidence: a change of Rust build or comparator starts a new epoch and resets readiness; an errored or stale attempt never counts as coverage; missing evidence gives `NOT READY`.
+- Report: the ledger and report contain no slug, title, query text or page content (a canary string scan); an expired `explain` sample is refused, never replaced.
+
+## Migration and rollback
+
+- `gbrain migrate --to rust` reuses the engine graduation machinery (`src/commands/migrate-graduation.ts`, `src/core/persistence/graduation-*.ts`), which already copies PGLite to Postgres from a deny-by-default inventory with carry, rebind, rebuild and discard classes (`docs/designs/engine-graduation-spike.md`).
+- The inventory gains an `engines.rust` column. A migration that adds a relation already fails `test/graduation-inventory.test.ts` until it has a row; after the preview it must also say how Rust stores it (decision D7).
+- Schema migrations on Rust stores. Each `Migration` (`src/core/schema-migrations/types.ts`) gains a Rust disposition: `catalog_only` (an additive change the catalog absorbs), `postgres_only` (an explicit no-op with its reason), or a Rust handler with its own verify through typed methods or the relation API. The runner in `src/core/migrate.ts` dispatches on it, since the SQL path and SQL-issuing handlers cannot run on Rust. Per migration, the catalog change, the data handler and the version ledger row commit in one store transaction; `FORMAT` is then rewritten by atomic rename, and an open that finds `FORMAT` behind the records repairs it from the records. A check fails a migration above the Rust baseline that has no disposition. Before PR 19, a catalog mismatch is refused by the loader and development stores are rebuilt.
+- The graduation helpers issue SQL on both sides today (catalog columns in `graduation-digest.ts`, sequence positions in `graduation-copy.ts`, metadata, counts and sequences in `graduation-verify.ts`). An engine-neutral graduation adapter keeps the custody state machine and replaces those assumptions: catalog inspection, canonical row export, counter and sequence transfer (never below a consumed value), fencing, import and verification, implemented for PGLite and Rust (PR 14b).
+- The preview moves PGLite brains to Rust and back. The target side writes through the Rust `importRelation` batch API in primary-key keyset order. Derived indexes build after the copy; embeddings are carried, never re-embedded. Postgres brains move only through shadow mode and `gbrain engine swap` (section "Shadow mode and swap"), which requires a single writer host and measures fingerprint agreement before the swap; `migrate --to rust` from Postgres stays deferred and refuses with a message that the brain stays on Postgres. The swap and the preview refuse a brain with writers on more than one machine, with a clear message that it stays on Postgres until the Rust server phase passes the D17 bar (D19).
+- Same safety as graduation: writers quiesced and the journal drained first; a plan hash confirmed with `--yes --expect <hash>`; refused while a live `gbrain serve` holds the source lock; refused before touching anything when the addon is unavailable.
+- `migrate --to rust`, and `migrate --to pglite` from a Rust brain, have the graduation modes and usage line: `--plan` (alias `--dry-run`, read-only), `--yes --expect <hash>`, `--status`, `--resume`, `--rollback-to-source`, and `--json` with progress on stderr. The plan lists the addon status and its install step, the disk space needed, the estimated copy time, blockers with their fix (for example a live `gbrain serve` and how to stop it), and the capability report: each operation, command, cycle phase and minion handler the brain would lose on Rust, with its reason.
+- The command never prompts. A missing addon is installed by the run only as a step listed in the plan. A caller without `--yes --expect <hash>` gets the plan and exit 3 with the fix.
+- The run report ends with one filtered vector search timed on the source before the copy and on the target after verification. It uses a stored chunk embedding as the query vector, so no provider is called, and prints both times and the result count only.
+- Verification: counts plus a per-relation content digest that both engines compute through `relationDigest` over a canonical row encoding. Config switches only after verification passes. The source directory is tombstoned, as graduation does, so older binaries refuse to write to it.
+- Preserved without exception: withdrawals and purge tombstones (fingerprints verbatim), belief events (chain verified after copy), tokens and OAuth rows (hashes only), access and policy state, segmented page bodies, page versions, journal and receipts, spend ledgers, calibration profiles, config rows except the engine-local keys.
+- Rollback path 1: if the Rust brain took no writes since migration (its write counter equals the migration mark), the switch back restores config and lifts the tombstone. Rollback path 2: `gbrain migrate --to pglite` copies the Rust brain back through the same copier and verification.
+- Neither rollback path is disaster recovery: both need a readable Rust store. Recovery from a damaged store uses `gbrain backup create` and `backup restore`, extended to Rust brains in PR 21b (today `src/core/backup/snapshot.ts` refuses non-PGLite brains), and a full-store restore drill is a preview entry criterion. The 8 GiB archive cap (`src/core/backup/archive.ts`) applies to Rust brains too; above it, the quiesced physical-copy runbook (`docs/guides/in-agent-setup.md`, "Large or non-standard brains") gains the Rust directory layout, and the restore drill covers one store above the cap by that path.
+- Fault injection at each stage (kill, disk full, blocked relation, corrupt index) checks that the reported target state matches reality and that the source is never modified.
+
+## Shadow mode and swap
+
+The safest way to move an existing brain, Postgres or PGLite, is to run Rust beside it first, measure both engines on the same live workload, and swap only when the numbers show Rust is clearly working. Shadow mode is that path. It is the recommended route for every existing brain; `migrate --to rust` stays as the direct path for PGLite brains.
+
+### What shadow mode does
+
+- The current engine stays the **primary**. It serves every read and write, and its answers are the only answers callers see. Rust is a **shadow**: a full local copy of the brain that follows the primary and answers the same reads in the background.
+- Shadow mode is opt-in per brain (`gbrain engine shadow start --plan`, then `--yes --expect <hash>`). When it is off, no shadow code is constructed: the engine factory returns the bare engine, and a test proves it.
+- **Crash isolation.** While another engine is primary, a supervised child process owns the shadow store and loads the Rust addon; the serving process never loads it. Mirror work crosses a bounded, fail-open IPC queue. A child exit, native abort, hang or resource exhaustion disables mirroring and is recorded; the primary keeps serving. The in-process binding stays the design for a Rust primary.
+- No foreground call awaits shadow work, and the shadow never fails a call. The shadow uses CPU, memory and disk on the same machine, so the claim is "no awaited work on the request path", not "zero impact"; the report shows the measured load. When the queue is full, the shadow sheds sampled reads first, then falls behind (reported as lag).
+- Shadow mode does not change the Postgres or PGLite engine code. It has two observation seams above `BrainEngine`: a transaction-aware engine wrapper for typed calls, and a scoped observer in the operation and search pipeline (`src/core/ops/contract.ts` `OperationContext`, the arm calls in `src/core/search/hybrid/arms.ts`) for the operation, the immutable caller-access context and the final output. The one exception is the swap fence (below), which reuses graduation custody.
+
+### How the shadow stays in step
+
+The shadow is an eventual-state copy, not a commit-log replica. Three mechanisms keep it in step:
+
+1. **Seed.** A full copy from the primary through the graduation adapter (PR 14b) under its `live-shadow` policy, read through one transaction-bound export handle inside one `REPEATABLE READ` read-only transaction on Postgres (one snapshot on PGLite), with a total snapshot-age budget as well as statement timeouts. The primary is not fenced and not tombstoned: a shadow is a copy, not a move.
+2. **Follow.** The wrapper wraps transaction-bound callback engines too (`transaction`, `transactionDirect`, the grouped publication runner in `src/core/persistence/group-publish.ts`). It collects the relation and key invalidations each write makes, drops those of rolled-back savepoints and transactions, and publishes them only after the outer commit succeeds, including commits whose operation receipt reports failure (`coordinator.ts:92`). The follower re-reads those keys from the primary and replaces them in Rust through `importRelation`, so stored ids and fingerprints stay identical. It never replays the call. Queue loss, a restart or an uncertain commit outcome invalidates the follower's coverage watermark until reconcile completes.
+3. **Reconcile.** Writes the wrapper cannot see (raw SQL, other processes, other hosts, cron) are caught by reconcile. Intervals are defined by shared primary-key bounds (composite keys, empty intervals and the unbounded tail included), never by independently numbered batches. A differing interval is replaced atomically in the shadow, including deletion of shadow-only keys and their dependent state. Snapshot installation is serialized with follower application, and an older generation never overwrites newer state. Reconcile is rate limited, read-only on the primary, runs continuously at low priority with a full pass at least nightly, and reports the rows it repaired by relation; rows the follower should have caught count as follower misses. Comparisons over an interval being repaired are suspended.
+
+- **Allocators.** Row imports keep stored ids; sequence and allocator state is copied separately as a manifest, including values consumed by rolled-back transactions (`graduation-copy.ts` sequence transfer), and verified with the sequence check in `graduation-verify.ts`.
+- **Policies.** The graduation adapter gets explicit `migration`, `live-shadow` and `reverse-shadow` policies. The migration-time transforms (jobs reset to waiting, running effects requeued, managed persistence disabled, caches discarded; `graduation-inventory.ts`) apply only at cutover. A shadow store never starts job, persistence-effect, sync or maintenance workers. A versioned comparison inventory separates carried data, runtime-only state, derived indexes and excluded caches, and every exclusion is reported.
+
+The shadow lives on one host, the **shadow host**: the machine that would own the brain after a swap. On Postgres brains with several hosts, the others keep writing to Postgres as today and reconcile picks their writes up.
+
+### What is compared
+
+- **Reads.** A sampled share of reads (`shadow.read_sample`, default 0.1 [proposed]; 1.0 for brains under 10k pages) is run again on the shadow with the captured caller-access context. Provider work is never repeated: the primary's resolved query vectors, expansion and rerank outputs and ranking settings are captured and passed to the shadow. A shadow execution mode suppresses telemetry buffers, cache writes, retrieval timestamps and feedback before they are scheduled.
+- **Classification.** Each comparison ends as `match`, `stale`, `inconclusive`, `diverged`, `privacy_diverged`, `rust_error` or `capability_missing`. `stale` needs evidence: a captured snapshot or generation showing an intervening primary change or unapplied follower work, for collections, missing rows and non-page relations as well as pages. Unequal revision strings alone are not enough. Without that evidence the result is `inconclusive`: the original mismatch is kept, and both engines are run again against a current stable generation. A later repair never turns an unexplained mismatch into a match.
+- **Deterministic operations** (`get_page`, list, backlinks, timeline, find, stats, facts reads, and the memory verbs except the ranked part of their results) must match exactly, including order. Where a memory verb ranks results (for example `recall`, which runs hybrid search), its deterministic fields, envelope and visibility filtering match exactly, and its ranked list is compared under "Ranked operations" below.
+- **Ranked operations** are compared per arm, correlated by request and role (cache hits, degraded paths and several vector arms included); fusion is TypeScript on both. The trigram arm must match exactly. Keyword and title arms must match exactly when Rust runs the `ts_rank` compatibility ranker (D5); with a better default ranker they report overlap@10 and rank correlation, and their quality is gated on the eval gates instead (D17). The vector arm reports overlap@10 against the primary, which is reported and not gated, and scores both engines' top 10 against the same exact scan; Rust's recall@10 must be at least the primary's (pgvector HNSW on Postgres). The fused top 10 reports overlap@10 and rank correlation.
+- **Privacy.** Every item in every mirrored Rust response is checked against the primary's read policy for the captured caller at a comparable policy generation (`src/core/search/private-visibility.ts`), at row and content level. An item the caller may not read is `privacy_diverged`; an authorized item that is simply outside the primary's top k is a ranking difference. One `privacy_diverged` event pauses read mirroring, raises a doctor error and resets the readiness window. The check is never sampled within a mirrored response; the report states that unsampled requests are unobserved.
+- **Writes.** A sampled share of typed writes (`shadow.write_sample`, default 0.05 [proposed]) runs against an isolated copy-on-write snapshot of the shadow that is validated to equal the primary's preimage, with the captured typed inputs, configuration, clock and randomness. The full mutation set is compared (deletes, dependent rows, allocator behavior, index effects) with explicit mappings for generated ids. When no equal preimage is available the result is `write_uncomparable` and does not count. The shadow's logical data, allocators and indexes are unchanged afterwards.
+- **Fingerprints.** Fact rows store no fingerprint: the primary computes it in SQL when asked (`src/core/engine-sql/facts.ts:458`), and the withdrawal guard matches a ledger row against both `gbrain_fact_fingerprint` and `gbrain_fact_fingerprint_v1` (`src/core/facts/withdrawal-schema.ts:73`). So for every fact row the follower imports, the follower asks the primary host to compute both values in its own SQL, Rust computes both in its own code, and the two pairs are compared; fingerprint agreement on a Postgres brain is a measured count. That count does not prove that withdrawals and purges keep matching: a purged claim keeps only its text-free hash (`src/core/facts/purge-schema.ts`), so no stored row shows a difference for it. Two more checks cover that. First, a probe corpus (non-ASCII text, mixed case, every whitespace class) runs through the primary host's own `gbrain_fact_fingerprint` and `gbrain_fact_fingerprint_v1` SQL and through Rust; a difference in either version refuses the swap (`engine_swap_refused`, reason `fingerprint_semantics_differ`) and is reported with the host's server version and collation settings. Second, a regression test withdraws and purges a claim on Postgres, removes its original text, swaps, then re-imports the same claim text, which must stay suppressed; the same test covers a legacy withdrawal recorded with only the `_v1` fingerprint whose original text is gone.
+- **Latency and resources.** Observed latencies (primary on the real call, shadow in the background) are reported as observed only and never support a speed claim. Speed claims come from `gbrain engine shadow bench`: buffered samples replayed on both engines back to back in alternating order on the shadow host. Bench never writes to the primary or to the live shadow store. Read samples replay against the live stores. Write samples (`putPage`, imports, chunk upserts) replay only against disposable copy-on-write snapshots of both engines, taken at the same generation, with workers, embedding calls, file writes and job enqueues disabled; the snapshots are deleted after the run, and bench refuses write samples when no equal pair of snapshots is available. For Postgres the primary time includes the network, which is the head-to-head a user feels. Peak RSS, store size, index lag, follower lag and the extra load on the primary are sampled every minute.
+
+### Evidence, tracking and the generated report
+
+- **Evidence epochs.** Each shadow run has a versioned evidence manifest: brain id, primary engine and version, Rust build digest, comparator and adapter versions, catalog, capability set and the approved readiness-policy hash. A change to any of them starts a new epoch; an unrelated release with identical relevant artifacts does not. Readiness counts only evidence from the epoch of the candidate being swapped.
+- **Metrics ledger.** Every comparison appends one row under `<gbrain home>/engines/rust/shadow/metrics/` (one JSONL file per day, mode 0600): an opaque sample id, time, epoch id, operation, both latencies, result counts, classification, reason code and keyed hashes of row ids (HMAC with a per-brain secret). No query text, page content or slugs, so an aggregate report can be shared.
+- **Replay buffer.** Separately, a bounded in-memory buffer in the owner process keeps the exact typed request, the captured embedding and the caller-access context of recent samples. It never enters the ledger or a report and is discarded on eviction or exit. `explain` and `bench` use only buffered samples; an expired sample gives a structured refusal and the command to collect fresh evidence. Durable replay storage is deferred.
+- A daily rollup (an autopilot cycle step on the owner, or `report` on demand) keeps 90 days of per-operation counts and percentiles.
+- `gbrain engine shadow status [--json]`: on or off, seed progress, time to first completed comparison, follower lag and coverage watermark, reconcile state, queue depth, sample rates, last privacy event, evidence collected so far, the estimated remaining time at the observed traffic rate, and the verdict.
+- `gbrain engine shadow report [--since 14d] [--json] [--out <dir>]` writes `shadow-report.md`, `shadow-report.json` (with a schema version) and two SVG charts. The report opens with a one-screen decision brief: `READY` or `NOT READY`, whether more evidence alone can fix it, the largest measured win, the largest regression, the top blockers and the next read-only command. Then a table of primary versus Rust p50 and p99 from paired bench samples (difference, N, confidence interval), and every D17 loss with its planned fix, then every readiness criterion with its value and threshold, coverage and exclusions per operation (attempted, completed, errored, stale, inconclusive, dropped, capability-missing), retrieval quality, write, fingerprint and privacy results, lag, primary load, RSS, disk and recovery evidence. `--since` changes the history shown, never the readiness window.
+- `gbrain engine shadow explain <sample-id>` reruns a buffered diverged sample locally, labels the current-state rerun separately from the original observation, and is the only command that shows content. It is local CLI only: the operation is `cliOnly`, because `localOnly` still admits stdio MCP (`src/core/ops/callable.ts:30`) and stdio callers are untrusted. The handler also refuses unless `ctx.remote === false`, and tests confirm that stdio MCP, HTTP MCP and the thin client are all refused. It reaches the owner process through the owner IPC socket, which is 0600 and accepts only the same OS user. The rerun uses the caller-access context recorded with the sample, never a wider one, and prints to the terminal only.
+- Doctor check `rust_shadow` (`not_applicable` when off) reports lag, a privacy event, a stalled follower or reconcile, a child fault and a full disk.
+- Aggregate numbers only from the maintainer's brain, and from preview users who explicitly export a sanitized report, go into `docs/designs/rust-engine/shadow-log.md`. Nothing is uploaded automatically.
+
+### Swap readiness
+
+`READY` needs every criterion below, from evidence in the current epoch (thresholds proposed in D14 and fixed before any candidate result is collected):
+
+1. At least 14 days of shadowing in the epoch; follower lag p99 under 60 s; three consecutive nightly reconcile passes that repaired nothing.
+2. Every operation class used in the window meets its minimum of successful comparisons (at least 10,000 reads in total). An errored, stale, inconclusive or dropped attempt is not successful coverage and never counts as a match. Missing evidence is `NOT READY`, never an omitted row. None was `capability_missing` in the last 7 days.
+3. Zero unresolved `rust_error` and zero unexplained `diverged` results on deterministic operations in the last 7 days.
+4. The trigram arm agrees exactly on every comparable sample. Keyword and title arms agree exactly when Rust runs the `ts_rank` compatibility ranker; with a better default ranker (D5), the release carries E1 and E2 results at least equal to both the PGLite and the Postgres values instead. The vector arm's recall@10 against exact is at least 0.98 and at least the primary's recall@10 against the same exact scan. Overlap@10 with the primary, for the vector arm and the fused top 10, is reported and not gated (D17).
+5. Zero unexplained differences on at least 1,000 comparable write comparisons.
+6. Zero `privacy_diverged` events in the window.
+7. Zero fingerprint mismatches and a passing allocator verification.
+8. In paired bench samples (at least 100 pairs each, with confidence intervals), Rust p50 and p99 are no worse than the primary's on every operation class, and better on filtered vector search by the margin D14 sets. The release's `bakeoff.md` and `engine-bench` results show Rust equal or better than both Postgres and PGLite on every metric in "Performance" (D17). Zero samples or an inconclusive result never means faster, and a loss on any axis is listed in the report with its fix.
+9. Zero panics and zero child faults in the shadow.
+10. A backup and restore drill on the shadow store passed; the release carries eval gates E1 to E3.
+11. Eligibility: durable writer observations (below) show one writer host for the last 7 days with no unknown writer path (a brain with writers on more than one machine stays on Postgres until the Rust server passes the D17 bar, D19); a personal brain, not a mounted team brain; the shadow host on a preview target.
+
+There is no readiness override in the preview. A `NOT READY` plan can be read but not run. Privacy, fingerprints, topology, platform, capabilities, recovery drills, caught-up following and final digest checks can never be waived; any later override for duration or sample counts needs its own approved policy.
+
+### Swap and the way back
+
+- **Writer observations.** Consumer heartbeats are diagnostics only (rows are purged after 90 seconds and deleted on clean shutdown, `consumer-heartbeat.ts`). S5 adds durable writer observations for the eligibility window. They are written only while a shadow is enabled for that brain, by every process that writes to it; a brain without a shadow gets the empty table from the migration and no extra write on any path. The eligibility window starts when the shadow starts. A write path with no observation makes eligibility unknown, which refuses the swap. S5 carries a `behavior-changes.d` row for the migration.
+- `gbrain engine swap --to rust --plan` is read only. It prints the verdict, eligibility, the capability report, disk space, the expected write pause, every environment variable, launcher and service definition known to select the current engine (names only, never values; `src/core/config.ts:738` lets `GBRAIN_DATABASE_URL` and `DATABASE_URL` override the file), and a plan hash.
+- `gbrain engine swap --to rust --yes --expect <hash>` runs these persisted states, each resumable with `--resume` and visible with `--status`:
+ 1. Write an immutable, verified pre-swap recovery checkpoint of the primary.
+ 2. Establish a durable, database-enforced write fence on the primary through graduation custody (`engine-graduation.ts`): ordinary clients are refused, already-admitted work is drained with the graduation drain, and only the reverse follower may write. The fence stays after cutover and across restarts.
+ 3. Drain the follower, run a final reconcile, advance Rust allocators to at least the primary's high-water marks, and compare full relation digests and sequence verification on both engines.
+ 4. Switch authority atomically, restart the owner, and have a fresh process resolve the normal caller route and confirm the brain identity and the effective engine. The run refuses before step 4 while an unresolved environment or service override or an old serving process remains. Success is reported only after the probe passes.
+- **Reverse shadow.** The old primary becomes the reverse shadow: the follower copies Rust's committed writes back under the `reverse-shadow` policy, and comparisons, the ledger and the report keep running in the other direction. Reverse following freezes on a detected integrity divergence.
+- **Failback.** `gbrain engine swap --to postgres` (or `--to pglite`) uses the same plan, fence, drain, verify and route-probe steps in reverse, needs no readiness verdict, and keeps every acknowledged write. Failback is for a readable, correct Rust store. It is not protection against corruption copied into the reverse shadow.
+- **Recovery.** Verified recovery points (the pre-swap checkpoint plus periodic ones during the reverse-shadow period) are kept separately from the reverse shadow. If Rust becomes unreadable or corrupt, recovery restores a chosen recovery point, states the interval of writes that would be lost, and needs explicit approval for that loss.
+- `gbrain engine shadow stop` is idempotent, keeps data and authority, and says whether it stopped a reverse follower. `stop --delete` has its own `--plan` and `--yes --expect <hash>`, previews the exact directory and says that the fast way back is lost; for a reverse shadow on Postgres it never drops the database. The recommended reverse-shadow period is 30 days [proposed].
+- All start, swap and delete commands follow the graduation contract (`src/commands/migrate-graduation.ts`): `--plan` (alias `--dry-run`) writes nothing; no approval gives `confirmation_required` and exit 3; `--json` prints one document on stdout with progress on stderr; recovery instructions never need a working engine connection.
+- For Postgres brains, the swap moves the brain from a server database to a store on the shadow host. Other hosts then use the thin client (remote MCP) against the shadow host; the plan lists each observed writer and the command that moves it. A host that read Postgres directly was a trusted local caller and would become a remote caller. An owner-bound credential (a token bound to the owner member, created by `gbrain auth` on the shadow host and handed over by the user) relaxes private pages and private facts, but it does not restore every trusted-local read: member and folder restrictions still apply to the owner (`src/core/access/caller.ts`, `src/core/search/private-visibility.ts`), and remote takes reads default to the `world` holder (`readHolders`, `src/core/ops/context.ts`). So the swap plan lists, per observed host, what that host reads today and what it would read through its planned credential: source grants, member and folder restrictions, private pages and facts, and takes holders. It refuses the swap (`engine_swap_refused`, reason `host_access_unbound`) until each listed host has a credential, and (reason `host_access_changed`) while any host's reads would differ. Accepting a listed difference is a separate user approval with its own plan hash (`--accept-access-change --expect <hash>`); it is never implied by the swap approval. The swap never widens or narrows what a caller can read without that step.
+
+### Errors
+
+`engine_swap_refused` (D15) has a recovery table before S4. Each reason (`not_ready`, `multiple_writer_hosts`, `writer_coverage_unknown`, `team_brain`, `follower_behind`, `digest_mismatch`, `route_override`, `host_access_unbound`, `host_access_changed`, `fingerprint_semantics_differ`) defines its registry class, exit code, the measured blocker, the authority state, side effects, a safe `fix.next`, a read-only `fix.verify`, a retry bound and a docs anchor. `not_ready` points to the report, never to an override. `multiple_writer_hosts`, `writer_coverage_unknown` and `team_brain` need a user topology decision; `multiple_writer_hosts` says plainly that a brain with writers on more than one machine stays on Postgres until the Rust server phase passes the D17 bar (D19, section "Path to a multi-user server"). `follower_behind` gives a bounded wait and a status check. `digest_mismatch` keeps diagnostics and leaves the old authority in place, and is not retried blindly. `route_override` names the variable or service, never its value. `host_access_changed` lists each host's differences and points to the separate access approval. `fingerprint_semantics_differ` keeps the old authority and is not retried until the engine or the source host changes. Interrupted runs carry the run id and a sanitized diagnostic id. CLI, doctor and `--resume` use the same builders.
+
+### Privacy, cost and agents
+
+- A shadow is a second full copy of the brain on the shadow host's disk, created only on the owner's request. The start plan states its size, the free space, the child process it will start and its resource bounds; the store directory is 0700.
+- Follower and reconcile reads use a dedicated connection with `statement_timeout`, a snapshot-age budget, a rate cap and read-only transactions, and pause under lock or load pressure. The report shows the extra load as queries per minute.
+- Shadow mode makes no provider call: embeddings are copied, never computed.
+- Agents may read `status`, `report` and every `--plan` without asking. Starting a shadow needs the user's request; a swap needs separate approval of the swap plan. `READY` is evidence, not permission. Start never enables general autopilot, paid maintenance or an upload.
+
+## Engine benchmark in gbrain-evals
+
+The maintainer asked for a public benchmark of the engines, built alongside the Rust engine, that shows which one is fastest, best, lowest latency and cheapest. It lives in gbrain-evals, not here, and it starts before any Rust code exists so the PGLite and Postgres baseline is on record first.
+
+- Name and base: `engine-bench` in gbrain-evals (not `engine-shootout`, which collides with that repository's counted `shootout-*` runners), built on its existing `perf.ts`, `scale-latency` and `graph-backend` runners. The gbrain-evals maintainers write and land it (D11); this repository asks for it and answers questions on a gbrain PR. The published report follows that repository's takeaways-first report shape.
+- Engines: PGLite (in-process) and Postgres with pgvector (a local container) from the first PR. The Rust arm joins when PR 17 lands search parity, through the same `BrainEngine` factory; it is never benchmarked before it passes the parity gates, so a fast wrong answer cannot win.
+- Same inputs on every engine: one committed corpus and query set, seeded vectors, fixed seeds, the same pinned `gbrain` release for every engine (D11), the same machine, and warm-up runs discarded. No provider calls, so a run costs nothing beyond the machine.
+- What it measures, per engine:
+ - Latency: p50, p95 and p99 per operation (`putPage`, `getPage`, keyword, vector and hybrid search, filtered search, backlinks, `listPages`, timeline), single client and at fixed concurrency.
+ - Throughput: bulk import pages per second and chunk upserts per second at 1k and 10k pages.
+ - Cold start: time from open to the first answered query.
+ - Footprint: peak resident memory and on-disk size after import.
+ - The D17 metrics in "Performance": concurrent read and write throughput at 1, 4, 16 and 64 clients or writers, graph traversal at depth 1 to 5, vector recall@10 against exact with p50 and p99 at 200k and 1M chunks, and RSS per 100k chunks. This repository asks for each card through the D11 channel.
+ - Quality: Recall@5 and nDCG@10 on the committed qrels, plus top-k agreement with the Postgres arm, so "best" means the same or better answers, not only speed.
+ - Cost: CPU seconds and memory per 1,000 queries, turned into dollars with a price model stated in the report (a list price per vCPU-hour and per GB-month, cited with its date). Hosted Postgres adds its published instance price as a separate line. The report shows the measured inputs, so a reader can apply their own prices.
+- Output: one JSON per run under `eval/reports/engine-bench/` and a head-to-head card per metric. The report names a winner per metric and says plainly where an engine loses.
+- Shared with shadow mode: `gbrain engine shadow bench` replays the same operation set on a user's own brain, reads against the live stores and writes only against disposable snapshots (see "Latency and resources"), so it never changes the user's brain. The public benchmark answers "which engine is better on a fixed corpus"; the shadow report answers "is Rust better on my brain".
+- Landing: by gbrain-evals' own maintainers (D11). The benchmark is its own experiment there: a preregistration that names the decision the result changes (which engine to pick for a brain size; later, whether PGLite can be deprecated in favor of Rust), uses seeded vectors, makes no provider calls, and says why no plain-prompt arm applies (no agent is in the loop); paired comparisons with confidence intervals, cost per operation, and runs at gbrain's newest release. At most two PRs per experiment: the preregistration with the runner, then the results. Public numbers get a claim check and gbrain's disclosure line before they merge. Compute stays inside the shared limits, and every VM is destroyed when its run ends. Experiment 1 compares PGLite and Postgres now. Each Rust arm is a new experiment, after PR 17, and is re-run before PGLite deprecation.
+
+## Distribution
+
+- Installs (`bun install -g github:garrytan/gbrain#stable`) never compile Rust and never download the addon. No postinstall script and no npm dependency is added; napi-rs is used through Cargo only.
+- The eight lock addons are committed (`native/locks/prebuilds/`, 16 to 70 KB each). The engine addon will be megabytes per target, so committing eight of them per change would grow the repository quickly. Recommended (decision D4): `release.yml` builds per-target addons on native runners and attaches them to the release with build attestations; `gbrain engine install rust` downloads the addon whose digest the running release's manifest pins for this target, verifies it the way `src/core/binary-self-update.ts` verifies the release binary (SHA-256 plus attestation pinned to this repository's release workflow), and stores it under `<gbrain home>/engines/rust/<engine_build>/`. `migrate --to rust` offers the same step. `gbrain engine install rust` is idempotent (an installed, verified addon exits 0) and has a `--json` form. `gbrain engine install rust --from <file>` imports an addon copied by hand and verifies it against the same pinned digest; it is the offline path, and `GBRAIN_RUST_ENGINE_ADDON` stays a development override. Each install failure state (interrupted fetch, attestation unavailable, digest mismatch, no disk space or permission, the new addon failing its first open) leaves the active addon unchanged and maps to a reason in the error contract. After the new addon has opened the brain, addons older than the previous one are removed.
+- Upgrades: a release that leaves `rust/` unchanged pins the same digest, so the installed addon keeps working. When the pinned digest changes and a Rust brain exists, `gbrain upgrade` and `self-upgrade` fetch and verify the new addon into its own `<engine_build>/` directory before switching, and keep the previous addon until the new one has opened the brain once. If that fetch fails, the binary upgrade still completes and the Rust brain reports `engine_unavailable` with the install command, as `post-upgrade` does; an upgrade never fails for want of the addon. A raw `bun install -g` upgrade has no staging step: `post-upgrade` fetches the addon, and if that fails the brain reports `engine_unavailable` with the install command and a doctor finding, with no data touched. `gbrain engine status` (and its `--json` document, as additive fields under `schema_version: 1`) reports the target and whether it is a preview target, the addon path (home-relative), its digest and the pinned digest, the store format, the index lag and the capability report. Brains on PGLite or Postgres never trigger a fetch.
+- Platforms: darwin-arm64 and linux-x64-glibc first (the two release binary targets, `.github/workflows/release.yml:128-132`), then linux-arm64-glibc, darwin-x64, musl and Windows, matching the lock addon's target list before PGLite is deprecated on each.
+- The addon size is measured in the bake-off. Embedding it in the compiled release binaries is reconsidered only if it is small enough that every user can carry it.
+
+## Decisions needing the maintainer's yes
+
+### Approval record
+
+On 2026-11-16 the maintainer answered the final review gate (revision 2) with "do it", which takes the recommended option on every gate item. Gate item ids are lowercase so they do not collide with the decision numbers below or the shadow PR names.
+
+| Gate item | Question | Approved option | Plan decision |
+|---|---|---|---|
+| d1 | How broad SQL rewrites start | Checkpoint C1 gates broad Track 2 | D6 |
+| d2 | Preview platforms | darwin-arm64 and linux-x64-glibc, backup and staged upgrade required | D12 |
+| d3 to d11 | Bake-off scope, migrate report, offline install, first-query target, `Fix:` placement, third-engine arrangement, search snapshots, graduation adapter, fact fingerprints | The recommendation in each, as written in the plan | plan text |
+| u1 | Who lands gbrain-evals changes | gbrain-evals' own maintainers write and land them; requests go through one channel, a `question:` or `heads-up:` line on a gbrain PR; no maintainer step | D11 |
+| u2 | Effort budget through Checkpoint C1 | 8 calendar weeks or 25 merged PRs from PR 1, whichever comes first | Phase 1 entry |
+| u3 | 1M-chunk benchmark corpus and spend | A permissively licensed public corpus, embedded once at 1,024 dimensions | D10 |
+| s1 | Shadow mode config, commands, first report | D13 as written; first report after PR S2 | D13 |
+| s2 | Swap readiness | The eleven criteria, no override in the preview | D14 |
+| s3 | Where the shadow runs | A supervised child process | D13 |
+| s4 | Postgres swap | In this plan, with the fence and one writer host | D15 |
+| s5 | Safety net after a swap | Reverse shadow plus recovery points | D14 |
+| s6 | Sharing shadow results | Local reports, manual sanitized export only | D13 |
+| p1 | The plan as a whole | Approved | all |
+
+D16 (the engine benchmark) comes from the maintainer's direction quoted in D16. D17 (the performance bar) comes from the maintainer's ruling quoted in D17. D18 (no SQL dialect) and D19 (single machine first, with a multi-user Rust server as the end state) come from the maintainer's answers quoted in each, including the 10:33 PM PST amendment quoted in D17 and D19. D20 (no PGLite-style locking) comes from the maintainer's principle quoted in D20. D1 to D5 and D7 to D10 are approved as directions here; the PR that adds each concrete key, code or default quotes the yes again, as the merge process requires.
+
+
+Each yes is quoted in the body of the PR that needs it.
+
+- **D1. Engine selection.** The config value `engine: "rust"` (with `database_path`, default `~/.gbrain/brain.rust`), `gbrain migrate --to rust` and back, kind `rust` in `openEngine`, and `--engine` on in-tree eval commands. Needed by PR 8 and PR 21.
+- **D2. New error codes.** `engine_unavailable` (reasons: `addon_missing`, `abi_mismatch`, `build_mismatch`, `unsupported_platform`, `load_failed`), `engine_capability_missing` (reasons: `raw_sql`, or the capability name), `engine_store_format_unsupported` (newer or unreadable store format). Needed by PRs 8 and 19. Review added the reasons `fetch_failed` and `verification_failed` (`engine_unavailable`, PR 22) and `newer_format`, `unreadable` and `upgrade_failed` (`engine_store_format_unsupported`). Eng review added the reason `transaction_reentry` on the existing `internal_error` code (PR 8).
+- **D3. Development override.** The environment variable `GBRAIN_RUST_ENGINE_ADDON` (absolute path to a locally built addon), for development and CI. Needed by PR 8.
+- **D4. Distribution.** Recommended: attested release assets fetched only on request (`gbrain engine install rust`, `migrate --to rust`) or, for an existing Rust brain, when an upgrade changes the pinned digest (staged by `gbrain upgrade` and `self-upgrade`, best effort in `post-upgrade`). Alternatives: commit prebuilds like the lock addon (simple, grows the repository by tens of megabytes per change); embed in compiled binaries (no fetch for binary installs, larger binary for everyone). Needed by PR 22.
+- **D5. Keyword ranking.** Changed by D17. The Rust keyword, title and facts arms reproduce `ts_rank` and `ts_rank_cd` with Postgres default weights and normalization as a compatibility mode, gated on fixture ordering; that mode is the regression baseline. A better ranker (BM25 or another) may be the default when it is equal or better than both Postgres and PGLite on the E1 and E2 retrieval metrics (R@5, nDCG@5, P@5, top-1). That default changes the result order callers see, so the PR that sets it quotes the yes. Needed by PR 15.
+- **D6. Track 2 for all contributors.** New SQL outside the engines fails a shrink-only ratchet; raw SQL moves behind typed engine methods grouped by domain; new two-way `kind` branches fail a guard. Needed by PR 6.
+- **D7. Schema change policy after the preview.** A migration that adds or changes a relation also adds its Rust catalog and inventory entries and its Rust disposition (`catalog_only`, `postgres_only` or a Rust handler with verify) in the same PR; the Rust arm in CI catches a miss. Needed before PR 23.
+- **D8. Opening the preview.** Users may run `migrate --to rust` once the Phase 8 entry criteria hold, including the D17 performance bar, with unsupported features refused by capability. Needed by PR 23.
+- **D9. PGLite deprecation.** Approval of the entry criteria in this plan now; the default change and notices later, in PR 25, with a separate yes.
+- **D10. Eval spend and pins.** About $2 to regenerate the LongMemEval embedding cache, the pinned gbrain commit for parity runs, and the E1 to E4 thresholds as written.
+- **D11. gbrain-evals landing.** Resolved, on that repository's final terms: its own maintainers write the gbrain-evals code and land it. This work opens no PRs there. It asks through one channel, a `question:` or `heads-up:` line on a gbrain PR, and the maintainer runs no step. The `gbrain` pin keeps following gbrain's newest release through `bun eval/runner/gbrain-pin.ts bump`, the only pin scheme; parity runs name the pinned release. A Rust build enters as a frozen `gbrain-rust` alias named in its preregistration, with the addon digest, the same way the existing frozen aliases are. Frozen or counted files there (preregistered experiments' counted files, sealed paths, receipts under `docs/benchmarks/*/counted/`) are never changed. Needed by the Phase 3 exit, and so by E1.
+- **D13. Shadow mode.** The commands `gbrain engine shadow start|stop|status|report|explain|bench`, the config keys `shadow.enabled`, `shadow.read_sample` (default 0.1, 1.0 under 10k pages), `shadow.write_sample` (default 0.05), `shadow.queue_max`, `shadow.cpu_share` and `shadow.ledger_retention_days` (default 90), the ledger and evidence manifest format, the supervised shadow child process, the doctor check `rust_shadow`, and shadow mode for Postgres primaries. Everything is off until a user starts it. The maintainer's request: "make it possible to run rust in shadow mode to existing postgres and make it easy to swap once it shows its clearly working (good metrics head to head, we should track it and generate it)". Needed by S1 to S4.
+- **D14. Swap readiness.** The eleven criteria in "Swap readiness" (criteria 4 and 8 as D17 changed them) with their numbers and the margin for "better on filtered vector search", fixed before candidate results exist; no readiness override in the preview; a 30-day recommended reverse-shadow period; recovery-point retention and the acceptable loss interval for disaster recovery. Needed by S4 and S5.
+- **D15. Swap fence and Postgres swaps.** A durable, database-enforced write fence on the old primary through graduation custody (the one engine-side addition), a writer-observation table (a schema migration), and Postgres swaps only with one observed writer host for 7 days; the brain is then served from the shadow host and other hosts move to the thin client. New error code `engine_swap_refused` with the reasons and recovery table in "Errors", including `host_access_unbound`, `host_access_changed` and `fingerprint_semantics_differ`. Other hosts of a swapped Postgres brain move to owner-bound credentials listed in the swap plan; the swap is refused while any host's reads would change, unless the user approves that difference separately. Needed by S5.
+- **D16. Engine benchmark.** A public engine benchmark in gbrain-evals (see "Engine benchmark in gbrain-evals"), PGLite and Postgres first, Rust after PR 17. The maintainer's words: "alongside this as you work on the rust engine you should probably also work on a garrytan/gbrain-evals benchmark of the different engines to show which one is fastest/best/lowest latency/cheapest". No change to this repository.
+- **D12. Preview contract.** The preview targets darwin-arm64 and linux-x64-glibc only. It opens only with verified backup and restore and the staged addon upgrade. Windows and the other platforms come before PGLite deprecation on each, not before the preview. Needed by PR 23.
+- **D17. Performance bar: better than Postgres on every axis.** The maintainer's ruling, 2026-11-16 at 10:11 PM PST: "oh i want this rust engine to be better than postgres multi-threaded and more performant and better at all the things: better graph traversal, faster. better pgvector / vector search. everything must be better. more multi-threaded and better memory management and faster." The maintainer added the target at 10:33 PM PST: "i think we should engineer it knowing we will want full multi-user rust that totally supercedes and is 10x better than using postgres and pgvector". 10x better than Postgres and pgvector is the target; equal or better on every axis stays the gate to ship. This plan sets no per-axis 10x number: the gbrain-evals preregistration fixes each margin before candidate results exist. The bar changes from "never slower than PGLite" to equal or better than TypeScript gbrain on Postgres (pgvector HNSW, local, same machine, same corpus, same run) and on PGLite, on every metric in "Performance"; the proposed absolute targets stay as floors. A Rust arm is not called ready for the swap (D14 criterion 8) or the preview (D8) without paired runs with confidence intervals on every metric, and a loss on any axis is listed in `bakeoff.md` and the shadow report with its fix. Better ranking or higher vector recall returns different results than Postgres, so ranked arms are gated on equal or better retrieval quality (E1 and E2: R@5, nDCG@5, P@5, top-1), not on identical results; vector overlap@10 with the primary is reported, not gated, and recall@10 against exact must be at least pgvector's. Everything else stays byte-exact: CLI and JSON output, MCP names and shapes, the markdown brain format, content hashes, fingerprints and deterministic operations, with zero privacy leaks. Multi-writer throughput, graph traversal and memory join the Phase 2 bake-off, with a concurrent-writer store required (D19), and a memory budget per 100k chunks set in `bakeoff.md` before any Rust number exists. Sections changed: Recommendation, Goal, Constraints, Architecture (the contract line), the storage replacement map (records, locks and CJK rows), the owner's write serialization, Phase 2, the Phase 3 exit, Checkpoint C1, the Phase 8 entry, PGLite deprecation criterion 6, Eval gates, Performance, the shadow's deterministic and ranked comparisons, the shadow report, swap readiness criteria 4 and 8, the engine benchmark, Risks, D5, D8 and D14. One owner process per brain directory and the refusal of multi-host writers hold for the embedded phases only; D19 makes a multi-user Rust server the end state.
+- **D18. No SQL dialect in the Rust engine.** The maintainer, "do it." (10:24 PM PST 2026-11-16), answering asks A1. The Rust engine has no SQL dialect and no query language: typed `BrainEngine` methods plus the relation API only. `executeRaw` and every other raw-SQL entry point are refused on Rust with a typed error (`engine_capability_missing`, reason `raw_sql`). The plain SQLite tables-and-triggers slice leaves the Phase 2 bake-off; SQLite may stay only as a plain key-value record store option. Every raw-SQL call site a Rust brain can reach (migrations, doctor, tests, and the seven gbrain-evals files) moves to typed methods; this is required Track 2 work, not optional. Sections changed: Recommendation, Non-goals, Capability gating, Track 2 rules, Phase 2, Phase 3 and the bake-off criteria.
+- **D19. Single machine first; a full multi-user Rust server that supersedes Postgres and pgvector is the target end state.** The maintainer, "do it." (10:24 PM PST 2026-11-16), answering asks B1, then amended on 2026-11-16 at 10:33 PM PST: "i think we should engineer it knowing we will want full multi-user rust that totally supercedes and is 10x better than using postgres and pgvector". The embedded phases run one owner process per brain directory, and brains with writers on more than one machine stay on Postgres until the Rust server passes the D17 bar. The engine is built for the server now: the storage core has no global singletons or per-process state that assumes one caller; transactions and snapshots work across connections and processes, not only threads in one process; the access checks (the typed write-scope argument and the invariants I1 to I15) live in the engine layer, `gbrain-domain`, as the RLS replacement a server enforces per user, never in the napi wrapper; and the store format considers replication and backup hooks (a commit log or snapshot stream a follower can consume), designed now and built later. The concurrent-writer store is required in the Phase 2 bake-off, and working across processes and connections is a bake-off criterion. The server phases are in "Path to a multi-user server"; each needs the maintainer's yes before it starts. The swap and the preview refuse a brain that has multi-host writers, with a clear message that it stays on Postgres until the Rust server phase passes the D17 bar (`multiple_writer_hosts`). Sections changed: Recommendation, Goal, Non-goals, the storage replacement map (records and access rows), Writer admission, Process model, Phase 2, Postgres deprecation, Path to a multi-user server (new), Performance, Migration and rollback, swap readiness criterion 11, Errors, the approval record, D17, open question 12, Risks and Deferred.
+- **D20. No PGLite-style locking.** The maintainer, 2026-11-16 at 10:39 PM PST: "the other thing about pglite - pglite sucks! there are so many locks and problems with it. the rust implementation we want it to be pristine and perfect for our cases." Concurrency is designed fresh for gbrain's workloads: many readers, many writers and many processes on one machine, then many machines (the D19 end state). There is no process-wide lock, no single-connection bottleneck, no busy error (no `pglite_busy` equivalent) and no cross-process file lock that makes a second process fail or wait for the whole brain. The Rust engine does not copy gbrain's lock primitives one for one (named transaction and advisory locks, row locks, `SKIP LOCKED` queue claims, `pglite_busy` handling): each lock and queue call site gets a typed engine operation with a stated guarantee, listed in "Concurrency without PGLite-style locks"; each has a parity test against TypeScript gbrain under concurrent callers and a stress test with many writers and many processes. The Phase 2 bake-off adds three criteria: no process-wide writer lock on the hot path, a second process reads and writes without busy errors, and contention measured and reported. One owner process per brain directory stays only as a temporary limit of the embedded phases, not a lock design the core depends on (D19). Sections changed: Recommendation, Goal, Non-goals, the storage replacement map (locks row), Binding (`lockPageKeys`), Data on disk, Process model (including the owner protocol), Errors (maintenance path), Concurrency without PGLite-style locks (new), Phase 2, Crash, property, concurrency and fuzz tests, PR 18, the approval record and Risks. Needed by PRs 2, 3, 6, 8, 18 and 20.
+
+## Open questions
+
+1. Who lands gbrain-evals changes? The merge process covers this repository only, and `research/11` describes an older, unpinned snapshot of the evals repository. Resolved in D11: that repository's own maintainers write and land them from requests on a gbrain PR, and the pin follows gbrain's newest release through its pin tool.
+2. If the bake-off picks bundled SQLite as the record store (as a plain key-value store only, D18), `constructEngine`'s message that SQLite is unsupported and `docs/ENGINES.md` need rewording, since SQLite would be an internal detail of the Rust engine. Acceptable?
+3. Which public 1M-vector corpus (license and dimensions) serves the 1M benchmark, or is a paid one-time embedding of a public corpus preferred?
+4. Does any caller search inside its own write transaction? The guard test answers it; a positive answer needs a design note before that subsystem moves.
+5. The keyword arm does not wrap the query in `gbrain_fts_input` (`research/03` section 9). The Rust engine copies current behavior; should a fix ship separately for all engines?
+6. Which collation and `lower()` behavior does PGLite use in practice? The fixtures pin the Rust engine to it, and the answer may show a PGLite and Postgres difference worth its own issue.
+7. When is Windows needed? Proposed in D12: after the preview, before PGLite deprecation on Windows. Confirm with D12.
+8. Is a Rust index accelerator for Postgres brains (option B) wanted later?
+9. Resolved: Rust brains get `backup create` and `backup restore` (PR 21b) before the preview. The existing commands refuse non-PGLite brains, and `migrate --to pglite` needs a readable store, so it is not recovery.
+10. Is four weeks of daily use the right dogfood length for criterion 9?
+11. Are the swap thresholds in D14 strict enough, or should the vector arm require exact equality with the primary when the brain is small enough for exact search on both?
+12. Settled by D19: in the embedded phases, brains with writers on more than one machine stay on Postgres; the multi-user Rust server that would serve them is a later phase (section "Path to a multi-user server"). Is the maintainer's own brain single-writer? C1 checks it before any swap timeline is given.
+13. Should preview users be invited to export and submit a sanitized aggregate report for `shadow-log.md` (never uploaded automatically), or only the maintainer's brain?
+14. For quiet brains, should readiness accept provider-free replay coverage, counted separately from live comparisons, to reach the per-operation minimums sooner?
+
+## Risks
+
+- **Track 2 dominates the schedule.** About 5,300 call-site lines across many subsystems, while master moves daily. Mitigation: the shrink-only ratchet stops growth from day one; subsystems are ordered by what an embedded brain reaches; each PR is small and independently useful to the Postgres engines.
+- **Contention on shared files.** `engine.ts` and `engine-sql/` change in many PRs. Mitigation: domain objects add one line to `engine.ts` per domain; heads-up comments; the merge process sequences the stack.
+- **Exactness drift.** `ts_rank`, `pg_trgm`, fingerprints, decimals, collation, jsonb order. Mitigation: PGLite-generated fixtures for each, eval gates, and verbatim carry of stored hashes.
+- **Silent Postgres branches.** A `kind` check that sends Rust down the Postgres path. Mitigation: the kind-branch guard and capability questions before a subsystem is allowed on Rust.
+- **A missed trigger is a silent loss of enforcement** (`research/09` risk 1). Mitigation: one Rust write chokepoint, the trigger parity matrix, and per-operation authorization tests.
+- **A native crash takes down the process.** Mitigation: `catch_unwind` on every export (panics only), fuzzed boundary, crash-safe store, no `unsafe` in gbrain crates without review. Segfaults, aborts and dependency faults remain a residual risk, accepted for the preview; a sidecar is reconsidered if crash reports show them.
+- **Memory.** An in-process ANN at 1M chunks and 1,024 dimensions is several GiB as f32 (`docs/ENGINES.md`, "Vector index sizing": about 7.6 GiB per million as `vector`). Mitigation: the bake-off measures f16 storage, memory-mapped vectors and quantization against recall.
+- **Better results look like different results.** A better ranker or a higher-recall vector index changes what callers see (D17). Mitigation: the `ts_rank` compatibility mode stays as the regression baseline, ranked arms are gated on eval quality at least equal to both existing engines, and overlap with the primary is reported in every shadow report.
+- **The D17 bar may not be reachable on every axis.** Postgres is a mature multi-writer server, and one axis, such as many concurrent writers, may resist an embedded design. Mitigation: the bake-off measures the writer curve before Phase 5, a concurrent-writer store is required, every loss is listed with its fix, and Checkpoint C1 decides continue, narrow or stop on that data.
+- **Building for a server slows the embedded preview.** The server-ready criteria (connection-bound transactions, no singletons, replication hooks in the format) add work before any server exists (D19). Mitigation: the criteria constrain choices but build nothing early; the bake-off picks the simplest option that meets them; each server phase starts only with the maintainer's yes.
+- **A server needs the access enforcement Postgres gets from RLS.** Mitigation: the access checks live in `gbrain-domain` from Phase 5, with per-operation authorization tests, so Phase M2 adds per-user credentials, not a new access model.
+- **A typed operation misses a guarantee a lock gave implicitly** (D20). A lock can protect more than its call site names. Mitigation: each operation's parity test runs concurrent callers against TypeScript gbrain on both engines, the stress cell runs many writers in many processes, and the TLA+ properties stay as tests.
+- **Bun and Node-API gaps.** napi-rs features may behave differently in Bun. Mitigation: PR 1 proves loading, async tasks and typed arrays in Bun 1.4.4 and in a compiled executable before any engine code.
+- **Downloaded native code.** Mitigation: attestation and hash verification pinned to this repository's release workflow, the same as the self-updating binary, plus the per-release digest manifest; fetch only on explicit request or for an existing Rust brain whose pinned digest changed.
+- **Schema drift after release.** New TypeScript migrations land several times a week. Mitigation: D7 plus the Rust arm in CI; additive changes need only a catalog entry.
+- **Split brain during migration.** Mitigation: quiesce, tombstone, verify before switching, and the two rollback paths.
+- **CI cost.** A Rust lane plus a growing Rust test arm. Mitigation: path filters, one addon build per run reused by shards, and the added time reported in PR 1 and PR 9.
+- **Time to first value.** The preview waits for Track 2 persistence, page state and facts (1,844 raw-SQL lines), so no user benefits for many PRs. Mitigation: Checkpoint C1 decides continue, narrow or stop with real-brain data and effort against budget; the named first cohort and two preview targets keep the preview small.
+- **A native crash in the shadow.** Mitigation: the shadow runs in a supervised child process while another engine is primary; the serving process never loads the addon.
+- **Corruption copied back.** A Rust bug could write bad data that the reverse shadow then copies. Mitigation: an immutable pre-swap recovery checkpoint, periodic recovery points, and reverse following that freezes on an integrity divergence.
+- **Shadow load on the primary.** The follower and reconcile read from Postgres or PGLite. Mitigation: read-only transactions with `statement_timeout`, a rate cap, a CPU share, pause under lock or load pressure, and the load shown in the report.
+- **A second full copy of private data.** Mitigation: opt-in per brain, a disk and privacy notice in the plan step, 0700 store, `shadow stop --delete`, and a ledger with keyed hashes only.
+- **False confidence from sampling.** A rare operation may be mirrored too few times. Mitigation: criterion 2 requires every operation used in the window to be mirrored, the privacy check is never sampled, and `report` shows per-operation counts beside each verdict.
+- **Shadow drift.** A missed write makes the shadow disagree and could block a good swap or hide a bad one. Mitigation: the follower copies rows instead of replaying calls, reconcile digests every range, `stale` is rechecked before it counts, and the swap compares full digests after the final reconcile.
+- **Addon drift on upgrade.** A same-ABI addon with older behavior could load, or an upgrade could leave a Rust brain without a usable addon. Mitigation: the pinned digest manifest, the staged upgrade that keeps the previous addon, and the offline upgrade drill (criterion 12).
+
+## Deferred
+
+- Option B, a Rust accelerator inside the PGLite or Postgres engines: it changes existing engine behavior, which Rust PRs may not do. Revisit after the preview (open question 8).
+- Platforms beyond darwin-arm64 and linux-x64-glibc before the preview: PR 24 still lands before PGLite deprecation on each platform (D12).
+- A sidecar process binding: revisit only if preview crash reports show native faults.
+- The `gbrain_fts_input` keyword-arm fix (open question 5): a separate change for all engines, never inside a Rust PR.
+- A stdio driver protocol and an `oracle-ts` shim for gbrain-evals: not needed while the in-tree `gbrain eval` harnesses and `engine-factory` cover the gates.
+- LLM-judged gbrain-evals categories as gates: they stay reported in bands set beforehand (E4).
+- Moving the `Fix:` line to the last line of the shared CLI error renderer (`src/core/agent-output.ts` prints it second): a change for every command, never inside a Rust PR. Agents read `fix` from `--json`.
+- A Rust preview issue template under `.github/ISSUE_TEMPLATE/`: the preview docs name the reporting route instead.
+- A `gbrain engine remove rust` command: removing an addon by hand is enough for the preview.
+- `gbrain migrate --to rust` from a Postgres brain. Single-writer Postgres brains use shadow mode and `engine swap`. Postgres brains with writers on several hosts stay on Postgres until the Rust server passes the D17 bar (D19).
+- The multi-user Rust server, Phases M1 to M5: designed for now, built later, each phase with the maintainer's yes (section "Path to a multi-user server").
+- Moving fact fingerprint computation out of SQL for all engines, or a versioned normalization: it can change Postgres behavior, so it needs its own change and the maintainer's yes.
+
+## Review record
+
+The accepted review requirements (binding on the PRs they name), the review record, the decision audit trail and the review scorecards are in [rust-engine/review-record.md](rust-engine/review-record.md).
diff --git a/docs/designs/rust-engine/research/01-engine-interface.md b/docs/designs/rust-engine/research/01-engine-interface.md
new file mode 100644
index 0000000000..e4564e1034
--- /dev/null
+++ b/docs/designs/rust-engine/research/01-engine-interface.md
@@ -0,0 +1,279 @@
+# 01. Storage engine seam: BrainEngine, engine-sql, and raw-SQL bypass
+
+Line numbers refer to gbrain 36bd05806a.
+
+Reference repo: `garrytan/gbrain` (v0.60.733.0, commit 36bd05806a). All paths below are relative to that root unless marked otherwise.
+
+Legend: **[V]** verified by reading the code. **[C]** counted with a ripgrep regex, so approximate (comments and docs can match). **[I]** inferred from the code, not executed.
+
+No tests were run. Nothing in the reference repos was modified.
+
+## 1. Bottom line
+
+- The seam exists and is well structured: one interface, `BrainEngine` (src/core/engine.ts:830), with 197 callable members (194 required, 3 optional), two engine classes, and a SQL-sharing layer `src/core/engine-sql/` for 15 storage domains. [V]
+- The seam is not closed. `BrainEngine` exposes `executeRaw(sql: string, params?)` (src/core/engine.ts:2714) and `executeRawDirect` (:2732). About 5,100 raw-SQL call-site lines sit outside the engine files, in about 1,140 files. [C]
+- Therefore the interface is a viable seam for a Rust core only for the typed domain methods. Every raw `executeRaw` caller needs a separate plan: port it to a typed method, or give the Rust core a SQL executor. [I]
+
+## 2. The BrainEngine interface (src/core/engine.ts:830-2890)
+
+The interface has a `readonly kind: 'postgres' | 'pglite'` discriminator (:832) and three optional members: `holdSchemaMigrationLock?` (:848), `findDuplicatePage?` (:922) and `findDuplicatePages?` (:926). The callable members, grouped by the section comments in the file:
+
+| Family (engine.ts lines) | Count | Representative members (signature, one-line purpose) |
+|---|---|---|
+| Lifecycle (834-859) | 9 | `connect(config)`, `disconnect()`, `reconnect(ctx?)` (recovers with the config captured at last connect, #2034), `initSchema()`, `transaction<T>(fn, opts?)` (:849), `transactionDirect<T>` (:851, control txn on the direct pool), `registerBeforeDisconnect(stop)` (:853, returns unregister), `withReservedConnection<T>(fn, opts?)` (:859) |
+| Pages CRUD (861-1196) | 24 | `getPage(slug, opts?)` (:869), `readPageSnapshot(s)`, `lockPageKeys(keys)`, `putPage(slug, page, opts?)` (:891), `deletePage(s)`, `softDeletePage(s)`, `restorePage`, `purgeDeletedPages`, `listPages`, `findPages`, `countPagesBy`, `resolveSlugs`, `getAllSlugs`, `listAllSources`, `updateSourceConfig`, `listCorpusSample` |
+| Search (1197-1239) | 6 | `searchKeyword(query, opts?)` (:1198), `countKeywordPages`, `searchKeywordPages`, `searchTitles`, `searchVector(embedding: Float32Array, opts?)` (:1224), `getEmbeddingsByChunkIds` |
+| Chunks + embedding state (1240-1423) | 15 | `upsertChunks(slug, chunks, opts?)` (:1269), `getChunks`, `getChunkPage`, `getChunkWindows`, `countStaleChunks`, `sumStaleChunkChars`, `setPageEmbeddingSignature`, `invalidateStaleSignatureEmbeddings`, `invalidateContentDriftEmbeddings`, `listStaleChunks`, `readEmbeddingStateCounts`, `listEmbeddingStateRows`, `deleteChunks` |
+| Extraction watermark (1424-1483) | 7 | `countStalePagesForExtraction`, `listStalePagesForExtraction`, `markPagesExtractedBatch`, `markPagesAttendanceBlocked`, `countStaleFrontmatterKeyPages`, `listStaleFrontmatterKeyPages`, `stripStaleFrontmatterKeys` |
+| Links / graph (1484-1841) | 23 | `addLink`, `addLinksBatch(links)` (:1521), `replaceDerivedLinks(origin, links)`, `removeLink`, `getLinks`, `getBacklinks`, `traverseGraph` (:1643), `traversePaths` (:1658), `traversePathsDetailed`, `relationalFanout`, `relationalChainHop`, `getBacklinkCounts`, `getAdjacencyBoosts`, `getSalienceScores`, `findOrphanPages` |
+| Tags (1842-1860) | 3 | `addTag`, `removeTag`, `getTags` |
+| Timeline + chronicle + ontology (1861-1935) | 12 | `addTimelineEntry(s)`, `getTimeline`, `getTimelineForDate`, `getSince`, `getOnThisDay`, `getLastSeen`, `upsertEventProjection`, `mergeOntologyFact`, `getOntology`, `discoverOntologyDimensions`, `findOntologyConflicts` |
+| Raw data + files (1936-1957) | 5 | `putRawData`, `getRawData`, `upsertFile(spec)`, `getFile(sourceId, storagePath)`, `listFilesForPage` |
+| Takes (1958-2074) | 14 | `addTakesBatch`, `updateTakeEmbeddings`, `listTakes`, `searchTakes`, `searchTakesVector`, `updateTake`, `supersedeTake`, `resolveTake`, `getScorecard`, `getCalibrationCurve`, `addSynthesisEvidence` |
+| Dream verdict cache (2075-2085) | 3 | `getDreamVerdict(filePath, contentHash)`, `putDreamVerdict`, `sweepDreamVerdicts` (TTL `DREAM_VERDICT_TTL_SECONDS = 30 * 86400`, :528) |
+| Contradiction probe (2086-2195) | 6 | `listActiveTakesForPages`, `writeContradictionsRun`, `loadContradictionsTrend`, `get/putContradictionCacheEntry`, `sweepContradictionCache` |
+| Facts (2196-2426) | 14 | `insertFact`, `insertFacts`, `deleteFactsForPage`, `expireFact`, `listFactsByEntity`, `listFactsSince`, `listFactsKeyset`, `listFactsBySession`, `listSupersessions`, `countUnconsolidatedFacts`, `findCandidateDuplicates`, `consolidateFact`, `findTrajectory`, `getFactsHealth` |
+| Segmented body (2427-2457) | 14 | `allocateBodyOccurrenceIds`, `stageSegmentTexts`, `readSegmentTexts`, `stageManifestRows`, `readManifest`, `stageSegmentChunks`, `createSegmentedPageShell`, `flipBodyGeneration`, `openBodyStaging`, `setBodyStagingState`, `sweepSegments`, segment derivation watermarks |
+| Versions (2458-2478) | 3 | `createVersion`, `getVersions<B>`, `revertToVersion` |
+| Stats + health (2479-2490) | 2 | `getStats`, `getHealth` |
+| Ingest log (2491-2498) | 2 | `logIngest`, `getIngestLog` |
+| Sync, slugs, aliases (2499-2655) | 9 | `updateSlug`, `rewriteLinks`, `resolveSlugWithAlias(Detailed)`, `resolveAliases`, `setPageAliases`, `refreshPageBody`, `updatePageContextualRetrievalState`, `migrateFactsToCanonical` |
+| Config (2656-2685) | 5 | `getConfig`, `setConfig`, `unsetConfig`, `listConfigKeys`, `getAllConfig` |
+| Migration + raw SQL (2686-2746) | 3 (+2) | `runMigration(version, sql)` (:2687), `getChunksWithEmbeddings`, `keywordBoundedRead(read)` (:2745). Plus `executeRaw` (:2714) and `executeRawDirect` (:2732) |
+| Code edges (2747-2805) | 6 | `addCodeEdges`, `deleteCodeEdgesForChunks`, `getCallersOf`, `getCalleesOf`, `getEdgesByChunk`, `searchKeywordChunks` (:2804) |
+| Eval capture (2806-2821) | 5 | `logEvalCandidate`, `listEvalCandidates`, `deleteEvalCandidatesBefore`, `logEvalCaptureFailure`, `listEvalCaptureFailures` |
+| Salience + enrich (2822-2889) | 5 | `batchLoadEmotionalInputs`, `setEmotionalWeightBatch`, `getRecentSalience`, `listEnrichCandidates`, `findAnomalies` |
+
+Total: 197 callable members, counted by a line regex that accepts optional (`name?(`) and generic (`name<T>(`) members: 194 required and 3 optional. The Lifecycle and Pages CRUD rows include the optional ones. [V] (counted by line range)
+
+Key shape facts [V]:
+- Public page operations take slugs, not numeric page IDs (docs/ENGINES.md:24-50 states this as a design choice). Some storage methods take a numeric `pageId`: `readManifest`, `stageSegmentChunks`, `readSegmentDerivations` and `retireSegmentDerivations` (src/core/engine.ts:2437-2456).
+- Two result envelopes: `SearchResult[]` for search (ranking happens above the engine in `src/core/search/hybrid.ts`), and `{ rows, affectedRows }` inside the SQL layer.
+- Limits are clamped by `clampSearchLimit` with `MAX_SEARCH_LIMIT = 100` (:821-828).
+- Engine-level constants that the Rust engine must match (src/core/engine-constants.ts): `DELETE_BATCH_SIZE = 500`, `TRAVERSE_PATH_ROW_CAP = 5000`, `TRAVERSE_WALK_ROW_CAP = 20000`, `LINK_READ_DEFAULT_LIMIT = 500`, `LINK_READ_MAX_LIMIT = 5000`, `LINK_READ_CONTEXT_MAX_CHARS = 2000`.
+
+### Escape hatches (engine.ts:2694-2745, 249-263)
+
+- `executeRaw<T>(sql, params?, opts?: { signal, timeoutMs, deadlineAt, jitOff, prepare })` (:2714). Takes arbitrary positional SQL text. The doc comment describes Postgres `statement_timeout`, PGLite cancellation, and JIT-off. [V]
+- `executeRawDirect` (:2732). Same, but routed to the session-mode pool when dual-pool is active. Used by the Minion lock heartbeat. [V]
+- `keywordBoundedRead(read)` (:2745). Runs `read` in one unscoped read transaction under `search.keyword_statement_timeout_ms`. [V]
+- `ReservedConnection` (:249-263) exposes only `executeRaw`, and is documented as unsafe to take inside `transaction()`. [V]
+
+## 3. Factory, open, connect
+
+- `createEngine(config)` (src/core/engine-factory.ts) calls `constructEngine`, registers a chat-usage sink, and wraps `disconnect` to deregister it. [V]
+- `constructEngine(config)` (src/core/engine-construct.ts) switches on `config.engine` (`'pglite'` or `'postgres'`, default `'postgres'`) and dynamically imports `PGLiteEngine` or `PostgresEngine`. Any other value throws; a `'sqlite'` value gets a specific error. [V]
+- `openEngine(settings)` (src/core/engine-open.ts, experimental) is the settings-only path. It requires `embedded_core: true`. It validates every key (unknown keys are rejected). It requires `host.id` as a UUID. It rejects `pool.max` outside 1-100. It reads no env vars, config file, or home dir. Default embedded pool is `DEFAULT_EMBEDDED_POOL_MAX = 4`. After `disconnect()` the engine is closed for good, and `connect()` throws `engine_closed`. [V]
+- `connectEngineForServe` (src/core/engine-connect.ts) is the CLI and serve path. Sequence: `loadConfig` → `configureGateway` → `createEngine` → `connectWithRetry` (db.ts) → `gateGraduationConnect` → `completeStartup` (migrations). One-shot read tuning: PGLite `shared_buffers = '32MB'` (`ONE_SHOT_READ_SHARED_BUFFERS`), Postgres `pool_max = 2` (`ONE_SHOT_READ_POOL_MAX`) unless `GBRAIN_POOL_SIZE` is set. [V]
+- `engineKey(engine)` (src/core/engine-key.ts) walks page-transaction clones and views back to the root engine, so per-engine caches (AI gateway, settings) key on the real engine. [V]
+- Engine scope (src/core/engine-scope.ts, engine-scope-store.ts) uses `AsyncLocalStorage`. A call with no scope in a process holding an open embedded engine is refused (`engine_scope_required`). [V]
+
+## 4. The SQL layer: src/core/engine-sql/
+
+Layout (33 `.ts` files, 8,718 lines total) [V]:
+
+- Migrated domains (15 files, about 7,040 lines), matching the `migrated` rows of `scripts/engine-sql-baseline.tsv`: `chunks` (1210 lines), `pages` (1225), `facts` (903), `links` (813), `takes` (712), `page-body` (552), `timeline` (269), `health` (273), `code-edges` (195), `cjk-search` (190), `titles` (145), `salience` (384), `sources` (81), `files` (54), `tags` (34).
+- Shared infrastructure, not domains: `bootstrap.ts` (756, forward-reference bootstrap run before the schema blob), `executor.ts` (113, `SqlExecutor` contract), `fragment.ts` (98, `sqlFragment` composition), `brands.ts` (52), `dialect-pglite.ts` (76), `dialect-postgres.ts` (94).
+- Helper modules that carry SQL but are not listed as domains in the baseline: `graph-rank.ts` (185 lines, about 20 SQL-keyword hits), `exact-identity.ts` (101, about 7), `page-lookup.ts` (109, about 4). `keyword-pages.ts` (54) and `normalize.ts` (40) had no literal SQL keywords in my check [C].
+
+Baseline (`scripts/engine-sql-baseline.tsv`, 79 lines) [V]:
+- 15 `migrated` rows (the domains above).
+- 54 `method` rows: 26 in `src/core/pglite-engine.ts`, 25 in `src/core/postgres-engine.ts`, plus 1 each in `pglite-engine/checkpoint-guard.ts`, `pglite-engine/code-edges.ts`, and `postgres-engine/init-schema-lock.ts`.
+- The 24 names shared by both engines are: `deleteEvalCandidatesBefore`, `discoverOntologyDimensions`, `findOntologyConflicts`, `getAllConfig`, `getConfig`, `getDreamVerdict`, `getIngestLog`, `getOntology`, `getRawData`, `getStats`, `listConfigKeys`, `listEvalCandidates`, `listEvalCaptureFailures`, `logEvalCaptureFailure`, `logIngest`, `mergeOntologyFact`, `migrateFactsToCanonical`, `putDreamVerdict`, `putRawData`, `searchKeyword`, `searchKeywordChunks`, `setConfig`, `sweepDreamVerdicts`, `unsetConfig`. That is 48 rows; the other 6 are engine-only (`_connectInternal`, `probePgliteScratchStore`, `issueProbe`, `getEdgesByChunk` on PGLite; `resolveFactsEmbeddingCast`, `acquireInitSchemaAdvisoryLock` on Postgres).
+
+Practical reading: the unmigrated families are config, dream verdicts, eval capture, ingest log, ontology, raw data, `getStats`, and the two keyword search methods. Keyword FTS on chunks (`searchKeywordChunks`) and pages (`searchKeyword`) is still implemented inside the engine classes, not in `engine-sql/`. [V]
+
+The ratchet is `scripts/check-engine-sql-ratchet.ts` (TypeScript compiler API). It only looks at class members of the two engine files and `pglite-engine/**`, `postgres-engine/**`. [V] It does not see SQL in helper functions that take the engine as an argument. One confirmed case: `insertEvalCandidate(engine: Pick<BrainEngine,'executeRaw'>, ...)` in src/core/feedback/store.ts:340 runs `INSERT INTO retrieval_events` through `engine.executeRaw`. `PostgresEngine.logEvalCandidate` (src/core/postgres-engine.ts:3101) is a one-line delegation to it, so that row is not in the baseline. [V]
+
+Guards that enforce the layer (scripts/): `check-engine-sql-ratchet.ts`, `check-engine-sql-brands.ts`, `check-engine-sql-dynamic.ts` (only constant text may be spliced), `check-layering.ts`, `check-engine-dynamic-import.ts`, `check-jsonb-pattern.sh`, `check-jsonb-params.mjs`. [V]
+
+## 5. Dialects and capabilities
+
+Two `SqlExecutor` adapters implement one contract (src/core/engine-sql/executor.ts). [V]
+
+| Aspect | PGLite (dialect-pglite.ts, pglite-engine.ts) | Postgres (dialect-postgres.ts, postgres-engine.ts) |
+|---|---|---|
+| Handle | one in-process `PGlite` (`db.query`), no pool | postgres.js pool (`this.sql`), plus optional direct pool |
+| Prepared statements | none | `prepare: true, simple: false` on the extended protocol (`query`) |
+| JSONB bind | `JSON.stringify(p.value)` (`bind()`) | `conn.json(p.value)` |
+| `maxBindParamsPerStatement` | 30,000 (`PGLITE_CAPABILITIES`) | `Infinity` (`POSTGRES_CAPABILITIES`) |
+| `transactionAdvisoryLocks` | false | true |
+| `probesEmbeddingCast` | false (always `::vector`) | true (`resolveFactsEmbeddingCast`, postgres-engine.ts:2271) |
+| Cancellation | pre-check, then race (no kernel cancel) | `query.cancel()` / driver `signal` |
+| `timeoutMs` in `executeRaw` | ignored | `SET LOCAL statement_timeout` in a BEGIN |
+| RLS scope binding | none (brand is identity) | `withScopedReadTransaction` (postgres-engine.ts:368) |
+| `withReservedConnection` | pass-through (pglite-engine.ts:1196) | `pool.reserve()` with a long-hold permit (postgres-engine.ts:763) |
+| Pool diagnostics | none | `getPoolDiagnostics` (:831) |
+
+Capabilities are three flags on the executor (`DialectCapabilities`), not on the engine. The engine-level `kind` is the only other discriminator. A regex count finds about 482 lines in 269 files that compare `engine`/`kind` to `'pglite'`/`'postgres'` [C]. Most look like config branches, not behavior branches. I did not classify them.
+
+The public capability matrix in docs/ENGINES.md:1598-1611 is a feature table (Full/Full), not a capability API. [V]
+
+## 6. Transactions
+
+- `transaction<T>(fn, opts?)` (engine.ts:849) runs `fn` with a cloned engine whose connection is the transaction handle. Nested calls use savepoints. [V]
+- `TransactionOptions` (engine.ts:142-160): `signal` (abort before BEGIN; on Postgres, abort during the transaction discards the connection and rolls back), `pipelineFirst` and `pipelineEarly` (transaction-pooler pipelining hints, both return a predicate over statement text), and `readOnly` (`BEGIN READ ONLY`). [V]
+- Postgres: `transactionOn` (postgres-engine.ts:726-760) builds a `txEngine` with `Object.create(this)` and `Object.defineProperty(txEngine, 'sql', { get: () => tx })`. It also sets `_pageTransaction`, `_heldPageKeys`, and `_commitChecks`. A checkout gauge tracks `'tx'`. [V]
+- PGLite: `transaction` (pglite-engine.ts:1209) uses `db.transaction`. Work is admitted through a checkpoint guard (`PgliteCheckpointGuard.runOutermost`). It cannot be interrupted after BEGIN. [V]
+- `transactionDirect` uses the direct pool when dual-pool is active (postgres-engine.ts:720). [V]
+- Usage: about 394 `.transaction(` call sites in 214 files outside the engines, and 10 `withReservedConnection(` sites in 8 files [C].
+- The pattern is JS-specific: `transaction(fn)` takes a callback, and the callee receives an engine object. A Rust port needs an explicit transaction handle or a batch API. [I]
+
+## 7. RLS read brands and scope binding
+
+Brands (src/core/engine-sql/brands.ts) [V]:
+- `ScopedRead` (`__obtainViaWithScopedReadTransaction`). Obtained only from `scopedRead(executor)` on the handle that `withScopedReadTransaction` yields. Means: the read ran in the RLS scope on master.
+- `LegacyUnscopedRead` (`__obtainViaUnscopedExecutor`). Obtained only via `unscopedExecutor(executor, reason)`. Means: the read ran on the pool with no scope transaction. Converting one to `ScopedRead` changes behavior, so it is a TODO, not a drive-by.
+- `check-engine-sql-brands.ts` rejects these keys anywhere else and rejects `as unknown as` next to executor types.
+
+Scope binding (src/core/postgres-engine.ts:331-409) [V]:
+- Opt-in by env var `GBRAIN_RLS_SCOPE_BINDING=1|true` (:363-364). Off by default.
+- When on, a source-scoped read runs in `readTransaction` and issues `set_config('app.scopes', <csv or '*'>, true)`. Precedence matches `sourceScopeOpts`: federated array > scalar > `'*'`.
+- The documented policy shape is `current_setting('app.scopes', true) = '*' OR source_id = ANY(string_to_array(current_setting('app.scopes', true), ','))` (:338-342).
+- The app layer (`sourceScopeOpts`) stays the mandatory first layer. RLS is defense in depth. The comment says only reads routed through `withScopedReadTransaction` are backstopped.
+- Schema: 33 policy/RLS lines in `src/schema.sql`; 166 policy/RLS regex hits across `src` [C]. Whether production runs with the flag on is not verified.
+
+## 8. Connection and pool lifecycle
+
+Postgres [V]:
+- `connect(config)` (postgres-engine.ts:433). With `config.poolSize`, it creates an instance pool: `max = min(config.poolSize, db.resolvePoolSize(...))`, `idle_timeout: 20`, `max_lifetime`, `connect_timeout`, `types: { bigint: BigInt }`, NOTICE silenced unless `GBRAIN_PG_NOTICES=1`, and `prepare` chosen by URL (PgBouncer transaction-mode detection). Session timeouts (`statement_timeout`, `idle_in_transaction_session_timeout`) come from db.ts.
+- Pool size: `DEFAULT_POOL_SIZE_FALLBACK = 10` (src/core/db.ts:62), overridden by `GBRAIN_POOL_SIZE` (db.ts:246-253).
+- `ConnectionManager` owns a read pool and an optional direct pool (dual-pool, for a session-mode URL alongside a transaction-mode pooler).
+- `disconnect()` (:516) → `disconnectInternal` (:526): runs `registerBeforeDisconnect` stops first, then tears down the direct pool, then the read pool.
+- `reconnect()` (:2859) reuses `_savedConfig`, guarded by `_reconnecting`.
+- `holdSchemaMigrationLock` (:687) and `acquireInitSchemaAdvisoryLock` (postgres-engine/init-schema-lock.ts) serialize schema init. 44 `pg_advisory*` occurrences across `src/core` [C].
+
+PGLite [V]:
+- `connect` (pglite-engine.ts:799) → `_connectWithRootRegistration` (:808) → `_connectInternal` (:887).
+- Data dir is `config.database_path`; undefined means in-memory.
+- Exclusive file lock via `acquireLock(dataDir)` (src/core/pglite-lock.ts:319). Failure message: "Could not acquire PGLite lock. Another gbrain process is using the database." `releaseLock` at pglite-lock.ts:410.
+- In-memory snapshot fast-restore only when `GBRAIN_PGLITE_SNAPSHOT` is set and the engine is not embedded (pglite-engine.ts:917).
+- WAL repair on `wasm-abort`, and a "repair failed" marker that blocks the open. Both are described in comments in `_connectInternal`.
+- Embedded WASM bundle with its own `vector` and `pg_trgm` extensions replaces the stock ones (pglite-engine.ts:33; src/core/pglite-embedded-assets.ts:267).
+- `disconnect()` (:1050) → `_closeInternal` (:1088): checkpoint, then close, then release the lock. A failed close retains the lock until process exit.
+
+## 9. How much SQL bypasses the engine
+
+These are regex counts over `src/` [C]. "Outside" means not in `src/core/engine*.ts`, `src/core/pglite-engine*`, `src/core/postgres-engine*`, or `src/core/engine-sql/`.
+
+| Pattern | Outside engines: call-site lines | Files |
+|---|---|---|
+| `.executeRaw(` / `.executeRawDirect(` (with optional generics) | about 4,890 | about 1,140 (1,144 total minus engine files) |
+| tagged template `` sql`...` `` | 186 | 44 |
+| `.query(` (mostly PGLite `db.query`) | 29 | 8 |
+| `.unsafe(` | 20 | 13 |
+| Combined | about 5,120 | |
+
+Inside the engine files: 180 matching lines across 22 files (postgres-engine.ts alone has 52 tagged templates). Note that `engine-sql` itself has only 5 `executeRaw` lines [C].
+
+About 1,014 `executeRaw` call sites in 440 files use a template literal with `${` interpolation (multi-line regex, approximate). I did not check whether any guard covers these. [C]
+
+Subsystem breakdown of outside-engine raw SQL (combined count): `core/persistence` 1,414; `commands` 603; `core/repair` 307; `core/facts` 234; `core/cycle` 157; `core/minions` 152; `core/trust` 118; `core/shared-skills` 117; `core/page-state` 109; `core/belief` 102; `core/access` 100; `core/search` 91; `core/page-body` 84; `core/generations` 79; `core/ops` 74. [C]
+
+Top 30 files by outside-engine raw SQL (combined count) [C]:
+
+| Lines | File |
+|---|---|
+| 65 | src/core/persistence/journal.ts |
+| 48 | src/core/minions/queue.ts |
+| 43 | src/core/page-state/projections.ts |
+| 37 | src/core/facts/purge.ts |
+| 35 | src/core/persistence/graduation-copy.ts |
+| 35 | src/core/mentions/pass.ts |
+| 34 | src/core/embedding-migration.ts |
+| 33 | src/core/persistence/source-lifecycle.ts |
+| 33 | src/core/page-body/segment-derive.ts |
+| 30 | src/core/persistence/worktree-refresh.ts |
+| 30 | src/core/persistence/sync-holds.ts |
+| 29 | src/core/persistence/page-purge.ts |
+| 28 | src/core/persistence/sync-run.ts |
+| 27 | src/core/shared-skills/restore.ts |
+| 26 | src/core/persistence/connector-sync.ts |
+| 26 | src/core/access/policy.ts |
+| 25 | src/core/persistence/ownership.ts |
+| 24 | src/core/repair/secret-spans.ts |
+| 24 | src/core/belief/purge-mirror.ts |
+| 23 | src/core/db-lock.ts |
+| 23 | src/core/access/members.ts |
+| 23 | src/commands/migrate-engine.ts |
+| 22 | src/core/persistence/effect-journal.ts |
+| 22 | src/core/oauth-provider.ts |
+| 22 | src/core/facts/purge-verify.ts |
+| 21 | src/core/persistence/atom-maintenance.ts |
+| 20 | src/core/persistence/topology-locks.ts |
+| 20 | src/core/persistence/deactivation.ts |
+| 20 | src/core/facts/conversation-publication.ts |
+| 20 | src/core/belief/purge.ts |
+
+Spot-checked [V]: `journal.ts:131` runs `tx.executeRaw` with an aggregate query on `persistence_requests`. `minions/queue.ts:384` runs `pg_advisory_xact_lock(hashtext(...))` through `tx.executeRaw`. `feedback/store.ts:340` runs `INSERT INTO retrieval_events` through a `Pick<BrainEngine,'executeRaw'>`.
+
+Two more facts that matter for the seam [C]: 132 `CREATE TABLE` statements in `src/schema.sql` (3,794 lines), and 317 files in `src/core/schema-migrations/`.
+
+Postgres-only feature usage across `src` (regex hits in `.ts` files, comments included) [C]:
+
+| Feature | Files | Hits | Notes |
+|---|---|---|---|
+| tsvector / ts_rank / websearch_to_tsquery | 44 | 148 | keyword FTS |
+| pgvector operators (`<=>`, halfvec) | 48 | 204 | vector search |
+| pg_trgm (`similarity`, `gin_trgm_ops`) | 29 | 74 | fuzzy slugs |
+| `WITH RECURSIVE` | 14 | 15 | graph walks |
+| advisory locks (`pg_advisory*`) | 32 | 57 | locks |
+| `SKIP LOCKED` | 15 | 31 | queues |
+| LISTEN / NOTIFY / pg_notify | 28 | 50 | notifications |
+| `FOR UPDATE` | 127 | 226 | row locks |
+| triggers / plpgsql | 49 | 337 | 70 hits in schema.sql |
+| RLS / CREATE POLICY | 49 | 143 | 33 hits in schema.sql |
+| JSONB (`::jsonb`) | 486 | 2,593 | |
+| `ON CONFLICT` | 249 | 473 | upserts |
+| `set_config(` | 57 | 148 | RLS and session settings |
+| `pg_stat*` / `pg_locks` / `pg_terminate` | 37 | 110 | diagnostics |
+
+## 10. Rust rewrite implications
+
+**Must preserve exactly**
+- The `BrainEngine` method semantics for slugs, soft-delete (`deleted_at`), source scoping (`sourceScopeOpts` precedence: federated array, then scalar, then `'*'`), and the limit clamp (`MAX_SEARCH_LIMIT = 100`).
+- The row-cap constants in section 2 (`TRAVERSE_*`, `LINK_READ_*`, `DELETE_BATCH_SIZE`). Callers depend on their truncation semantics.
+- Transaction semantics: nested means savepoint; abort rolls back; `readOnly` rejects writes.
+- JSON encoding: a JSONB value is stored as a document, not a double-encoded string. CLAUDE.md documents the Postgres double-encoding trap.
+- Error codes from `opError` (e.g. `engine_closed`, `engine_embedding_mismatch`, `engine_settings_invalid`), since callers branch on them.
+- Dream-verdict TTL (30 days) and the contradiction cache semantics.
+
+**Can be simplified**
+- Pool, prepared-statement, PgBouncer, and session-timeout logic (`postgres-engine.ts` connect path and `db.ts` pool helpers). A single-process embedded store needs none of it. I did not measure how much of the 3,182-line file this is.
+- RLS scope binding: replace with an app-layer filter that the Rust core always applies. Keep `ScopedRead` semantics as a type-level rule if wanted.
+- The PGLite/Postgres parity branches (capabilities, `kind`). One engine means no parity matrix.
+- Advisory locks and `SKIP LOCKED` become in-process mutexes and lease-based queues, with a file lock for the datastore.
+- LISTEN/NOTIFY becomes in-process channels.
+- Triggers, if any are behavior and not just maintenance, become explicit code in the write path. The 337 trigger/plpgsql hits need a per-trigger review.
+
+**Postgres feature each piece depends on (replacement candidates)**
+- Keyword search depends on tsvector/ts_rank and `websearch_to_tsquery`. A Rust replacement needs BM25-style ranking with the same query grammar. Ranking will differ.
+- Vector search depends on pgvector HNSW and the `halfvec` cast. The Rust core needs an ANN index plus an exact fallback. Recall parity needs measuring.
+- Fuzzy slug matching depends on pg_trgm. A trigram index covers it.
+- Graph traversal depends on `WITH RECURSIVE`. A BFS in Rust is simpler; the row caps must be kept.
+- JSONB depends on GIN indexes and the `->`/`@>` operators. A typed struct or serde_json with secondary indexes covers it.
+- RLS depends on `current_setting`. Replace with a scope filter in the Rust query layer.
+- Advisory locks depend on `pg_advisory_xact_lock`. Replace with a process-level lock table keyed by hashed IDs.
+
+**Risks**
+1. The raw-SQL escape hatch is the real seam. About 5,100 call-site lines in about 1,140 files bypass the interface. A Rust core that implements only the 194 typed methods will fail on the persistence, minions, repair, facts-purge, access, and cycle subsystems. This is the largest risk. [I]
+2. The ratchet cannot see SQL in helpers that take `Pick<BrainEngine,'executeRaw'>`. Any port that relies on the baseline to find SQL will under-count. [V]
+3. The 54 baseline method rows include the hot keyword-search paths (`searchKeyword`, `searchKeywordChunks`) and config. Those are not yet in `engine-sql/`, so they must be ported before any Rust engine can mirror them. [V]
+4. The schema is 3,794 lines, 132 tables, and 317 migration files, with RLS and triggers. A Rust port must decide whether to replay this schema or define a new one with a migration mapping. [V] [I]
+5. `openEngine` and `transaction(fn)` are JS-specific shapes. A napi binding would need to expose transactions as handles and map `AbortSignal` to cancellation tokens. [I]
+6. Parity tests are written against Postgres text goldens (`test/fixtures/goldens/sql-text/`, per src/core/engine-sql/fragment.ts header). If the Rust core does not run SQL, these goldens need a different oracle. [V] (the goldens are cited in code, not inspected)
+
+**Viability of the seam**
+- For the 15 migrated domains and lifecycle: the interface is viable for a Rust core via napi or an MCP/CLI process boundary. It is typed enough to bind.
+- For the other roughly 5,100 raw-SQL call sites: not viable without either (a) porting those domains into typed `BrainEngine` methods first (a multi-thousand-line job), or (b) embedding a SQL executor in Rust that accepts the same SQL text. Option (b) keeps Postgres-dialect SQL alive and is less clean.
+- Recommendation [I]: first, enumerate the 1,140 files by subsystem and decide per subsystem whether it is a typed domain (port) or an admin/maintenance path (can keep a narrow SQL shim). Treat `executeRaw` as a compatibility shim, not as the seam.
+
+## Open questions
+
+1. Which of the roughly 1,140 raw-SQL files are on the hot path (ingest, search, put_page, minions claim) and which are admin or maintenance (purge, repair, migrate-engine)? The port order depends on this.
+2. Where does the SQL for `Contradictions` (6 methods), `Versions` (3), and `keywordBoundedRead` callers live? Neither is a baseline row, and no `engine-sql` module is named for them. I did not trace the delegation.
+3. Does the ratchet need a helper-level scan (SQL inside functions that take `Pick<BrainEngine,'executeRaw'>`), or is the feedback store case the only one? I found one confirmed case.
+4. Is `GBRAIN_RLS_SCOPE_BINDING` enabled in any production deployment? The code paths are there; usage is not verified.
+5. How many of the 482 engine-kind branch sites are behavior branches versus config parsing? A regex cannot tell them apart.
+6. The doc at docs/ENGINES.md:1613 says "the interface assumes no SQL", but `BrainEngine` has `executeRaw(sql: string)`. Which statement the Rust design should follow is a product decision.
+7. Does the Rust core need to keep Postgres as a supported engine? If yes, the SQL seam must stay; if no, the escape hatch can be retired after porting.
diff --git a/docs/designs/rust-engine/research/02-schema.md b/docs/designs/rust-engine/research/02-schema.md
new file mode 100644
index 0000000000..7ae5405a51
--- /dev/null
+++ b/docs/designs/rust-engine/research/02-schema.md
@@ -0,0 +1,240 @@
+# 02 Schema map: `src/schema.sql`
+
+Line numbers refer to gbrain 36bd05806a.
+
+Reference: `garrytan/gbrain` v0.60.733.0, commit 36bd05806a (read-only). All 3,794 lines were read. "Verified" means read in the file or in code. "Inferred" means taken from a table name or comment. Line numbers refer to `src/schema.sql` unless a path is given.
+
+## 1. Shape of the file
+
+- Applied as one batch. `src/core/postgres-engine.ts:194-206` rewrites `vector(1536)`, the default embedding model, and the `embedding_dimensions` config row first. HNSW is skipped above 2,000 dimensions (`src/core/vector-index.ts:20-33`).
+- Extensions: `vector`, `pg_trgm`, `pgcrypto` (lines 3-6).
+- Grep counts (verified): 132 top-level `CREATE TABLE IF NOT EXISTS` (the phrase appears 134 times; two hits are comments at 1368 and 1376). 191 `CREATE [UNIQUE] INDEX`, including 2 HNSW, 8 GIN, 2 trigram. 26 literal `CREATE TRIGGER`, plus one dynamic loop. 22 functions. 3 sequences. 2 generated columns. 28 direct `ENABLE ROW LEVEL SECURITY` statements, plus three loops. Zero `CREATE POLICY` in `src/`.
+- About 46 more tables come from migrations (section 10).
+- 27 blocks are marked `BEGIN GENERATED from src/core/<module>.ts`. The TS module is the spec for each block.
+
+## 2. Classes, hot paths, conventions
+
+- **AUTH**: cannot be rebuilt from Markdown (`docs/architecture/system-of-record.md`, "DB-only by design").
+- **DER**: derived index or cache. Rebuildable from Markdown or by re-running work, which can cost money.
+- **LOG**: log or telemetry, droppable.
+- **COORD**: locks, queues, leases, state machines, request journals. Some must not be dropped.
+- **Hot**: R = search or read path; W = every write; blank = cold.
+- **GI** = loss kind from `src/core/persistence/graduation-inventory.ts`, a code-level classification. Compared in section 12.
+
+## 3. Core content
+
+| Tables (lines) | Keys, constraints, indexes | Class | Hot |
+|---|---|---|---|
+| `sources` (26-90, 1867-1879, 3559-3561) | PK `id`; UQ `name`, `incarnation` (UUID); `config` JSONB; `archived` + `archive_expires_at` (72h soft delete); partial IX on `config->>'github_repo'`. Seeds `default` (78-81). | AUTH | R |
+| `pages` (99-179, 1183-1234, 1880-1892) | PK `id` SERIAL; UQ `(source_id, slug)`; FK `source_id` CASCADE; CK `page_kind` markdown/code/image. Columns: `compiled_truth`, `timeline`, `frontmatter` JSONB, `content_hash`, `deleted_at`, `generation`, `knowledge_revision` UUID, `text_projection_revision`, `search_vector`, `links_extracted_at`, `database_only_reason`. Indexes include frontmatter GIN, title and slug trigram GIN, `search_vector` GIN, `(source_id, lower(title))`, `updated_at DESC`, and `COALESCE(effective_date, updated_at)`. | DER for file-backed rows; AUTH where `database_only_reason` is set | R+W |
+| `page_generation_clock` (242-248), seq `page_generation_clock_seq` (255-265) | Single row, CK `id = 1`; `value`. The sequence is the live clock. | COORD | W |
+| `page_retrievals` (308-311) | PK `page_id`, no FK on purpose (305). Written at most once per page per 5 min (298-307). | LOG | W (read) |
+| `content_chunks` (354-420, 432-458) | PK `id`; UQ `(page_id, chunk_index)`; FK CASCADE. `chunk_text`; `embedding vector(1536)` (rewritten at init); `embedding_image vector(1024)`; `embedding_multimodal vector(1024)`; `search_vector` TSVECTOR; `modality`; hashes; code columns (`symbol_name`, `symbol_name_qualified`, `parent_symbol_path` TEXT[], `doc_comment`, lines). IX: HNSW cosine on `embedding`; partial HNSW on `embedding_image`; GIN on `search_vector`; partial `WHERE embedding IS NULL`. | DER (GI user_data: paid embeddings) | R+W |
+| `code_edges_chunk` (472-495), `code_edges_symbol` (497-516) | Resolved edges UQ `(from_chunk_id, to_chunk_id, edge_type)`; unresolved refs UQ `(from_chunk_id, to_symbol_qualified, edge_type)`. FKs to chunks CASCADE; `source_id` FK. | DER | R |
+| `links` (549-590) | PK `id`; UQ NULLS NOT DISTINCT `(from, to, link_type, link_source, origin_page_id)` (582-583). CK `link_source` regex `^[a-z][a-z0-9]*(-[a-z0-9]+)*$`, ≤64 chars; CKs on `link_kind`, `resolution_type`, `assertion_tense`. `origin_page_id` FK SET NULL. Partial IX on `to_page_id` WHERE `link_type='supersedes'`. | DER for markdown, frontmatter, mention edges; AUTH for `manual` and CLI-added edges (inferred from 521-548) | R+W |
+| `wanted_links` (595-611) | BIGSERIAL; UQ `(origin_page_id, producer, ref_kind, target_source_id, target_ref)`. | DER | |
+| `tags` (616-626) | UQ `(page_id, tag)`; `tag_source` ('frontmatter', 'added', NULL). | DER; 'added' AUTH (inferred) | R+W |
+| `raw_data` (631-640) | UQ `(page_id, source)`; `data` JSONB sidecar. | AUTH (named DB-only in system-of-record.md) | |
+| `timeline_entries` (645-674) | FK `page_id`, `event_page_id` CASCADE. UQ expression `(page_id, date, md5(summary), source)` (670). Partial UQ `(event_page_id, date)` (674). | DER | R+W |
+| `page_versions` (679-690; cols 1893-1898, 1966) | FK CASCADE; `compiled_truth`, `frontmatter`, `snapshot_at`; added `knowledge_revision`, `timeline`, `title`, `type`, `tags`, `is_deleted`, `source_path`. Attribution columns come from migrations. | DER per doc; attribution not rebuildable | W |
+| `ingest_log` (700-715) | `source_type`, `source_ref`, `pages_updated` JSONB, `writer_version`, `writer_host_id`. | LOG | W |
+| `config` (720-730) | PK `key`; `value` TEXT. Seeds version, embedding model, dimensions, chunk strategy. | AUTH (some keys site-local) | R |
+| `files` (1136-1158), `file_migration_ledger` (1168-1178) | `files`: UQ `storage_path`; FKs source CASCADE, `page_id` SET NULL; `content_hash`, `metadata`. Ledger: PK `file_id`, CK status (5). | `files` AUTH (inferred); ledger COORD | |
+| `page_write_guards` (1899-1903) | PK `(source_incarnation, slug)`; FK incarnation CASCADE. | COORD (inferred) | W |
+| `page_projection_jobs` (2689-2696) | PK `(source_incarnation, slug)`; `revision`, `reason`. Filled by trigger. | COORD | W |
+| `page_embedding_budget` (2062-2074) | PK `page_id`; CK state open/held/capped; spend and reserve ≥0. | COORD | W |
+| `page_extraction_state` (2132-2143) | PK `(page_id, pipeline)`; watermark bytes and sha256; `input_truncated` JSONB. | COORD | W |
+| `page_view_digests` (2146-2156) | PK `(page_id, revision, view, audience)`; byte and line totals, sha256. | DER (GI rebuild) | R |
+| `page_segment_texts` (2162-2170) | PK `(source_id, sha256)`; `body` BYTEA; CK `byte_len` 1 to 1,048,576. | DER per doc; GI user_data | R |
+| `page_body_manifest` (2171-2202) | PK `(page_id, occurrence_id, gen_from, staging_key)`; `staging_key` GENERATED STORED (2195). FK `(source_id, sha256)`→segment texts. Partial UQ `(page_id, seq)` for live, unstaged rows. | DER manifest; staging rows COORD | R |
+| `page_body_stagings` (2203-2229), `_parts` (2230-2238), `_texts` (2239-2245) | Upload staging: states open, sealed, prepared, committed, aborted, expired; parts ≤4 MiB; hard-expiry partial IX. | COORD | |
+
+## 4. Auth, grants, withdrawal ledger
+
+| Tables (lines) | Keys, constraints | Class | Hot |
+|---|---|---|---|
+| `access_tokens` (735-745) | UUID PK; `token_hash` UQ (hash only); `scopes`; `revoked_at`; partial IX for unrevoked. | AUTH | R (inferred) |
+| `mcp_request_log` (750-760, 865-866) | SERIAL; `token_name`, `agent_name`, `operation`, `latency_ms`, `params` JSONB. Retention rollup is a migration table. | LOG | W |
+| `oauth_clients` (765-809) | PK `client_id`; `client_secret_hash`; `redirect_uris`; `federated_read` (GIN); FK `source_id` RESTRICT; budget, binding, `surface`, `grant_revision`; CK `source_grant` in ('none'). | AUTH | R (inferred) |
+| `oauth_tokens` (838-849), `oauth_codes` (851-862) | Token PK `token_hash`; code PK `code_hash` with PKCE fields; FK client CASCADE; `expires_at` BIGINT. | AUTH; GI discard for codes (243) | R (tokens) |
+| `oauth_grant_audit` (813-823) | BIGSERIAL; `before_grant`, `after_grant` JSONB; IX `(client_id, created_at)`. | LOG (GI security) | |
+| `fact_withdrawals` (828-835) | PK `(source_id, visibility, subject, fact_hash)`; CK visibility private/world; `subject` default `*`. | AUTH (withdrawal ledger, per doc) | R (inferred) |
+
+## 5. Operations, telemetry, per-domain state
+
+| Tables (lines) | Keys, constraints | Class | Hot |
+|---|---|---|---|
+| `op_checkpoints` (878-893), `op_checkpoint_paths` (900-908) | PK `(op, fingerprint)`; `completed_keys` JSONB array (CK); expression IX for sync holds. Paths PK `(op, fingerprint, path)`, FK CASCADE. | COORD (paths droppable after sync, per doc) | |
+| `context_volunteer_events` (915-930) | BIGSERIAL; slug, confidence, `match_arm`; 90-day prune. | LOG | W |
+| `retrieval_events` (936-942), `retrieval_event_pages` (943-951), `retrieval_event_links` (952-958) | Event TEXT PK; CK op (query, search, think, synthesize, recall). Pages PK `(event_id, source_id, slug)`, `rank`, `cited`. Links `edge_key`, `to_slug`. | LOG | W (inferred) |
+| `retrieval_feedback` (959-973) | PK `(event_id, signal, element_kind, source_id, element_key)`; rating 1-5; weight before and after. | LOG | |
+| `retrieval_weights` (974-983) | PK `(source_id, element_kind, element_key)`; weight REAL CK 0-1, default 0.5. | DER (learned; reset if feedback lost; inferred) | R (inferred) |
+| `session_context_state` (991-1006) | PK `(source_id, client_id, session_id)`; JSONB arrays; `facts_cursor_at`/`_id`; `degraded_wakes`. | COORD | R+W (inferred) |
+| `extract_atoms_transcript_state` (1036-1050), `extract_atoms_page_state` (1967-1981) | Transcript PK `(source_id, file_path, content_hash)`; page PK `(source_incarnation, page_id, content_hash)`. Failure streak, `tombstoned`. | COORD | |
+| `chat_usage_log` (1057-1072) | BIGSERIAL; token counts; `cost_usd` NULL when unpriced (1054). | LOG | W |
+| `open_loops` (1078-1109), `loop_suppressions` (1114-1121) | Loops: UQ `(source_id, dedup_key)`; CKs on `loop_type` (5), `status` (4), `detector`; `fact_id` with no FK. Suppressions UQ `(source_id, kind, value)`. Loops close, never delete (1076). | AUTH (inferred) | R (inferred) |
+| `migration_impact_log` (1377-1395) | BIGSERIAL; before and after metrics; `job_id` FK SET NULL. | LOG | |
+| `dream_verdicts` (1485-1505) | PK `(file_path, content_hash)`; `score`; JSONB `segments`, `entities`; `expires_at` default now()+30 days. | DER (paid triage cache; GI operational) | W |
+| `dream_synthesis_completions` (2124-2129), `chronicle_judge_reservations` (2115-2122) | Completions PK `(source_id, idempotency_key)`; reservations BIGSERIAL, no FK. | COORD | |
+| `chronicle_page_state` (2077-2114) | PK `(source_id, page_id, content_hash, extractor_version)`; CKs on state (4) and trigger; `attempts`, `next_attempt_at`, `cost_usd`, `event_slugs` TEXT[]. | COORD (GI user_data: "paid work done") | W |
+
+## 6. Queues, locks, request journal, persistence
+
+| Tables (lines) | Keys, constraints, indexes | Class | Hot |
+|---|---|---|---|
+| `minion_jobs` (1248-1321; triggers 1789-1825) | SERIAL; CK status (9 values, 1292); `claim_generation` BIGINT; `submission_authority` JSONB; `lock_token`, `lock_until`; `parent_job_id` FK SET NULL; `idempotency_key` partial UQ; CK `lock_duration_ms` 5,000-3,600,000. Claim IX partial WHERE waiting. | COORD | W |
+| `minion_inbox` (1324-1333), `minion_attachments` (1336-1351) | Inbox FK CASCADE. Attachments UQ `(job_id, filename)`; `content` BYTEA EXTERNAL; CK content or `storage_uri` present. | COORD (attachments droppable, per doc) | |
+| `subagent_messages` (1403-1425), `subagent_tool_executions` (1438-1463) | Messages UQ `(job_id, message_idx)`, `content_blocks` JSONB. Tool executions UQ `(job_id, message_idx, ordinal)`; CK status. | COORD (replay state) | |
+| `subagent_rate_leases` (1469-1476), `gbrain_cycle_locks` (1516-1532) | Leases FK job CASCADE, IX `(key, expires_at)`. Cycle lock PK `id`; `ttl_expires_at`; `acquisition_token` UUID. | COORD (GI discard) | |
+| `persistence_requests` (2450-2488) | UUID PK; UQ `(principal_kind, principal_id, request_id)`; UQ `sequence`; CK state (7); `digest`; JSONB `intent`, `authority`, `outcome`, `recovery`; CK `target_kind`, `protocol_version`. | COORD; idempotent replay identity, not droppable | W |
+| `persistence_effects` (2489-2499) | BIGSERIAL; FK request; UQ `(request_id, kind)`; CK state (4). Outbox. | COORD; not droppable | W |
+| `persistence_topology_changes` (2771-2791), `persistence_worktree_refreshes` (2795-2816) | Topology UQ `(principal_id, request_id)`; refresh partial UQ: one active per worktree. | COORD | |
+| `persistence_worktrees` (2409-2418), `_source_bindings` (2419-2425), `_host_bindings` (2426-2433), `_counters` (2442-2449), `_consumers` (2500-2521), `_writer_protocols` (2943-2950) | Worktree UUID PK; source binding PK `source_id`; host binding PK `(worktree_id, host_id)`; counters non-negative CKs; consumers PK `(host_id, pid, nonce)` (heartbeats); protocol PK `(worktree_id, host_id)`. | COORD (`consumers` GI discard) | W |
+| `persistence_local_writers` (2434-2441) | UUID PK; `credential_hash` UQ; `grant_ceiling` JSONB; `revoked_at`. | AUTH (credential) | |
+| `persistence_brain` (2402-2408; ALTERs 2939-2940) | singleton CK 1; `brain_id` UUID; `enabled`; `writer_protocol_floor` CK 1/2; `skill_bundles_enabled`. | AUTH (GI rebind) | R (guards) |
+| `git_canonical_brain` (2643-2646) | Singleton; `strict_sources` counter kept by three triggers on `sources` (2660-2671). | COORD | W |
+| `sync_wanted_markers` (3733-3744), `sync_notifier_leases` (3745-3753), `sync_notifier_sources` (3754-3777) | Markers PK `(source_id, intent)`; leases PK `host_id`, fence BIGINT; sources PK `source_id`, CK state (5). | COORD (leases and sources GI discard) | |
+| `needs_rederive` (3483-3496), `core_edit_notices` (3404-3421) | Rederive PK `(derived_table, derived_id)`. Notices BIGSERIAL, partial IX on unacked. | COORD | |
+
+## 7. Generations, derivations, purges
+
+| Tables (lines) | Keys, constraints | Class | Hot |
+|---|---|---|---|
+| `derived_generations` (1984-2013), `_items` (2014-2025), `_valve` (2026-2033), `_attempts` (2034-2043), `_activations` (2044-2058) | Generations: CK state (live, held, superseded), CK `held_reason` (8 values); partial UQs: one live and one held per `(source_id, kind, owner_key)` (2010-2011). Items PK `(generation_id, item_key)`. Valve PK `(source_id, kind, window_key)`. | COORD (GI user_data for generations) | |
+| `page_segment_derivations` (2250-2264) | PK `(page_id, pipeline, occurrence_id)`; CK pipeline (7); 32-byte `segment_sha256`, `context_hash`; CK state; JSONB `output`, `receipt`. Trigger refuses purged content (2345-2382). | DER watermarks (GI operational) | W |
+| `page_derivation_spend` (2265-2273) | PK `(page_id, family)`; family facts or synopsis; spend and reserve ≥0. | COORD | W |
+| `page_segment_derivation_purges` (2274-2292), `_purge_pages` (2293-2297) | Request PK `request_id`; `needles`, `patterns` TEXT[]; phase CK sweep/verify/recheck; cursors. | COORD | |
+| `derivation_inputs` (3468-3481) | PK `(derived_table, derived_id, input_table, input_id)`; IX on input. | DER (lineage) | |
+| `fact_purges` (3426-3436), `take_purges` (3442-3449), `page_purges` (3455-3462) | PKs `(source, visibility, subject, fact_hash)`, `(source, subject, claim_hash)`, `(source, content_hash)`. | AUTH (inferred: purge ledger) | R (inferred) |
+| `write_gate_receipts` (3506-3523), `write_gate_holds` (3524-3553) | Receipts UQ `(target_table, target_id, content_hash, detector_version)`. Holds UQ `(source_id, slug, fingerprint, detector_version)`; CKs on kind, status (held/released/dropped); `payload` JSONB. | Receipts LOG; holds AUTH (inferred: only copy until decided) | W |
+| `fact_relink_attempts` (3298-3315) | PK `(source_id, fact_id)`; `outcome`, `attempted_at`. | LOG | |
+
+## 8. Links, questions, decisions, eval, takes
+
+| Tables (lines) | Keys, constraints | Class | Hot |
+|---|---|---|---|
+| `link_transitions` (3320-3343) | BIGSERIAL; identity UQ NULLS NOT DISTINCT over 8 columns (3335-3336); CKs on kind and producer (includes `manual`). | DER (mixed: manual rows are DB-only) | |
+| `link_relationships` (3344-3370) | PK `(from, to, link_type, scope)`; `valid_ranges` DATEMULTIRANGE; CK `status_now` (6). | DER | |
+| `link_edge_proposals` (3372-3392), `graph_generation_seq` (3399) | UQ `(from, a_to, b_to, link_type, evidence_hash)`; CK status (10). | COORD | |
+| `pinned_questions` (3565-3598), `question_evidence` (3600-3615) | Questions UQ `(source_id, slug)`; definitions plus lease and spend columns. Evidence: `answer_revision`, page refs. | Questions AUTH (inferred); evidence DER | R (inferred) |
+| `belief_events` (3630-3669) | BIGSERIAL; `event_key` BYTEA UQ; CKs on `subject_kind` (6) and `origin` (5); `value`, `value_hash`, `prior_hash`, `state_hash`, `cause` JSONB. Append-only. | AUTH (history not rebuildable, per doc) | W |
+| `belief_page_lifetimes` (3671-3686), `belief_commit_marks` (3687-3690), `belief_retier_manifest` (3696-3709), `belief_redactions` (3710-3727) | Lifetimes PK UUID; partial UQ `(source_incarnation, slug)` while open. Commit marks PK `publication_id`. Retier PK `(summary_event, subject_kind, subject_key)`. Redactions BIGSERIAL. | AUTH | |
+| `decision_receipts` (3102-3137), `decide_spend` (3138-3151) | Receipts BIGSERIAL with `decision_id`, `slot`, `outcome`. Spend PK `request_id`, `cost_usd`. | LOG | W |
+| `decide_state` (3152-3156), `decide_proposals` (3207-3226), `decide_sweep_deferred` (3227-3236), `decide_review_queue` (3252-3263), `decide_review_proposals` (3264-3283) | State KV PK `key`. Proposals UQ `(sweep_id, pair_index)` and claim-pair UQ (3248), CK status. Deferred PK `(slot, source_id, fact_id)`. Review queue PK `(kind, source_id, a_ref, b_ref)`. | COORD | |
+| `decide_calibrations` (3173-3200) | BIGSERIAL; `threshold`, `metric`, `ece`, `qualification`, `retired_at`. | DER | |
+| `eval_candidates` (1543-1576), `eval_capture_failures` (1578-1583), `eval_contradictions_runs` (1631-1649), `think_ab_results` (1772-1785), `take_nudge_log` (1749-1768) | Candidates: CK query length ≤51,200; `retrieved_slugs` TEXT[]; `retrieved_chunk_ids` INTEGER[]. Nudge log XOR CK on take or proposal. | LOG | |
+| `eval_takes_quality_runs` (1591-1612) | UQ on four sha8 columns; CK verdict; `receipt_json`. Code comment calls these DB-authoritative (1585-1590). | LOG per name; comment disagrees | |
+| `eval_contradictions_cache` (1614-1626), `calibration_profiles` (1659-1686), `take_grade_cache` (1727-1747) | Cache PK on five columns with `expires_at`. Profiles FK CASCADE, GIN on `active_bias_tags`. Grade cache PK on four columns, CK verdict, `applied` default false. | DER | |
+| `take_proposals` (1690-1720) | UQ expression `(source_id, page_slug, content_hash, prompt_version, md5(claim_text))`; CK status (4); `acted_by`. | COORD | |
+
+## 9. Triggers, functions, RLS, GUCs
+
+**Triggers** (all in this file):
+
+| Trigger (table, timing) | Function (lines) | Effect |
+|---|---|---|
+| `bump_page_generation_trg` (pages, row, before I/U) | `bump_page_generation_fn` (182-205) | Insert: `generation` = max+1. Update: +1 when a content column changes (`compiled_truth`, `timeline`, `frontmatter`, `deleted_at`, `title`, `type`, `page_kind`, `content_hash`, others). |
+| `bump_page_generation_clock_trg` (pages, statement, after I/U/D) | `bump_page_generation_clock_fn` (267-278) | `nextval(page_generation_clock_seq)`. Global cache-bookmark clock. |
+| `pages_forget_retrievals` (pages, statement, after delete) | `gbrain_forget_page_retrievals` (313-334) | Deletes `page_retrievals` rows of deleted pages. |
+| `chunk_search_vector_trigger` (content_chunks, row, before I/U OF text, doc, qualified name) | `update_chunk_search_vector` (444-458) | `search_vector` = A(doc comment, qualified name) \|\| B(chunk text). |
+| `trg_pages_search_vector` (pages, row, before I/U OF title, timeline, timeline_lead) | `update_page_search_vector` (1196-1234; re-declared 2683-2688) | Title weight A; timeline text weight C. Body not indexed (1189-1192). |
+| `pages_knowledge_revision` (pages, row, before U) | `gbrain_advance_page_revision` (1904-1936) | New `knowledge_revision` UUID on identity or content change. Honours GUC `gbrain.materializing_revision` (1920-1925). |
+| `tags_knowledge_revision` (tags, row, after I/U/D) | `gbrain_advance_tag_revision` (1937-1961) | Bumps owning page's `knowledge_revision`. |
+| `pages_projection_queue` (pages, row, after I/U/D) | `gbrain_queue_page_projection` (2697-2766) | Upserts or deletes `page_projection_jobs`. |
+| `page_body_manifest_derivation_scope_retire` / `_delete`, `pages_derivation_scope_delete` | `gbrain_mark_derivation_scope_entry` (2298-2335) | Shared advisory lock on the source; copies in-flight purge requests into `_purge_pages`. |
+| `page_segment_derivations_refuse_purging` (before I/U OF output, receipt) | `gbrain_refuse_purging_derivation` (2345-2379) | Rejects writes containing purged needles (normalized text, `jsonb_path_query`). |
+| `minion_queue_protocol` (minion_jobs, row, before I/U) | `enforce_minion_queue_protocol` (1789-1810) | Claims must advance `claim_generation` by 1; old workers refused; spend tokens checked. |
+| `minion_job_notify` (minion_jobs, row, after I/U OF status) | `notify_minion_job_change` (1813-1825) | `pg_notify('minion_jobs', …)`. |
+| `managed_writer_guard` (created in loop, 2629-2638) | `gbrain_require_managed_writer` (2522-2627) | On pages, tags, slug_aliases, page_aliases, facts, takes, timeline_entries, sources, page_segment_texts, page_body_manifest: refuses writes outside GUC `gbrain.write_sources`; enforces git-canonical and topology gates. |
+| `git_canonical_sources_count_*` (sources, after I/U/D) | `gbrain_count_git_canonical_sources` (2647-2659) | Recounts strict sources. |
+| `gbrain_request_protocol`, `gbrain_effect_protocol` (persistence_requests, persistence_effects) | `gbrain_guard_request_protocol` (2957-2995), `gbrain_guard_effect_protocol` (2999-3007) | Protocol floor; skill-target and recovery-version checks. |
+| `gbrain_protocol_activation` (persistence_brain, before U) | `gbrain_guard_protocol_activation` (3011-3034) | Floor only rises; activation needs quiesced writers. |
+| `gbrain_skill_publication` (shared_skill_packs, _heads, _revisions) | `gbrain_guard_skill_publication` (3038-3054) | Requires a coordinated source capability. |
+| `shared_skill_delivery_lease` (shared_skill_delivery_batches, after I / U OF revisions) | `gbrain_lease_shared_skill_delivery` (3064-3081) | FOR KEY SHARE on each revision; inserts 24h leases. |
+
+Migration v035 adds an event trigger, `auto_rls_on_create_table`, that is not in this file.
+
+**Functions:** 22 in this file. Besides the 19 in the trigger table, there are `gbrain_try_jsonb` (64), `gbrain_fts_input` (432-436; spaces between CJK and ASCII runs), and `gbrain_require_persistence_protocol` (2951; raises 42501 unless GUC `gbrain.persistence_protocol` = '2'). Lines 3781-3793 reset `search_path` on 56 named functions, some created by migrations.
+
+**GUCs the guards read:** `gbrain.write_sources` (allowlist JSON), `gbrain.topology_change`, `gbrain.git_protocol`, `gbrain.persistence_protocol`, `gbrain.writer_quiesced`, `gbrain.materializing_revision`.
+
+**RLS (verified):** 28 direct `ENABLE ROW LEVEL SECURITY` statements, plus loops over 35 names (1846-1853), 10 page-body tables (2390-2394), and 10 shared-skill tables (3091-3094). All are conditional on the role having BYPASSRLS or superuser (1841-1861). No `CREATE POLICY` exists in `src/`, so any other role sees zero rows in these tables. Some guards raise `unreadable` errors when they cannot see a row they must check (2584, 2612).
+
+**Sequences:** `page_generation_clock_seq` (255), `page_body_occurrence_id_seq` (2161), `graph_generation_seq` (3399). About 47 lines declare SERIAL or BIGSERIAL (grep). **Generated columns:** `page_body_manifest.staging_key` (2195), `shared_skill_revisions.stored_bytes` (2889).
+
+## 10. Migration-only tables (outside this file)
+
+About 46 tables come from migrations and `schema-missing-tables.ts`. Groups: `facts` (v045, line 113) and `takes` (v037); `slug_aliases` (v105); `page_aliases` (v110); `query_cache` (v055) and `code_traversal_cache` (v059); `synthesis_evidence`; `access_*` (eight tables, v282-v299: members, groups, rules, policy state and revisions, pending coverage, migrations); `budget_*` and `mcp_spend_*`; `mcp_request_log_rollup`; `memory_proposals`; `page_mention_state`, `mention_index_status`, `mention_gazetteer_entries`; `drift_decisions`; `entity_identities`; `search_telemetry`; six `wake_*` tables; `reason_purge_tombstones`; `slug_rename_history`; `page_label_guards`; `take_domain_assignments`, `take_horizons`; `ingest_applied_captures`. Later drops: not verified. `facts` embedding is templated (`${vecType}(${embeddingDim})`, `src/core/engine-sql/facts.ts`). `takes` embedding was rebuilt to the config dimension in v142.
+
+## 11. Hot paths
+
+- **Search and read (R):** `sources` (filter on every search); `content_chunks` (keyword GIN and vector HNSW; 27 query sites in `engine-sql/chunks.ts`); `pages` (join, `deleted_at IS NULL`, `search_vector`, trigram); `links` (graph ranking; 15 FROM and 7 JOIN sites in `engine-sql/links.ts`); `tags` and `takes` (salience, `engine-sql/salience.ts`); `code_edges_*`; `facts`; segmented-page tables; Auth tables per request (inferred).
+- **Every page write (W):** `pages` (three triggers, guard, projection queue); `page_generation_clock`; `tags`; `content_chunks` (re-inserted on page change, 422-423); `page_versions` (snapshot per update); `ingest_log`; `persistence_requests` and `persistence_effects`; `page_projection_jobs`; `timeline_entries`.
+- **Per read (W, telemetry):** `page_retrievals`, throttled to once per 5 min (298-307). The comment explains the split: updating `pages` would fire triggers and advance the clock, expiring the query cache. Other per-read writes are inferred: `retrieval_events`, `mcp_request_log`, `access_tokens.last_used_at`.
+
+## 12. Where the code's classification differs from the doc
+
+The graduation inventory has 184 entries: 170 `carry` (78 user_data, 19 security, 73 operational), 2 `rebind` (persistence_brain, persistence_host_bindings), 3 `rebuild` (query_cache, code_traversal_cache, page_view_digests at 231-233), and 9 `discard` (the COORD tables marked GI discard in sections 5-6).
+
+Disagreements:
+- `content_chunks`: DER in the doc, GI user_data (58). Re-embedding is paid work.
+- `page_segment_texts` and `page_body_manifest`: DER in the doc, GI user_data (150, 133). Segmented bodies live in the DB.
+- `chronicle_page_state`: COORD here, GI user_data (52).
+- `page_segment_derivations` and `dream_verdicts`: DER in the doc, GI operational (147, 76).
+- `eval_takes_quality_runs`: the code comment says DB-authoritative (1585-1590); this map says LOG. Undecided.
+
+## Rust engine implications
+
+**Preserve exactly**
+- Page identity: integer page ids with UQ `(source_id, slug)`. Links, chunks, timeline, versions, and derivations all reference them.
+- Generation rules: the column predicate in `bump_page_generation_fn` (182-205) and the global clock (255-278). Layer-1 cache correctness depends on monotonic values.
+- Revision rules: `knowledge_revision` and `text_projection_revision` transitions (1904-1961). These gate caching and projection.
+- Search weights and tokenizer: A title, C timeline, A doc comment, B chunk text, English stemming, CJK spacing (432-436). Ranking drift moves the `gbrain-evals` baselines.
+- Timeline dedup key `(page_id, date, md5(summary), source)`; NULLS NOT DISTINCT uniqueness on links.
+- Append-only ledgers (withdrawal, purge, belief). If Rust must read existing brains, `event_key`, `state_hash`, `prior_hash` need byte-compatible hashing.
+- Request idempotency: `persistence_requests` UQ `(principal, request_id)` returns the stored outcome on replay.
+- Credentials stored as hashes only (`token_hash`, `code_hash`, `credential_hash`).
+
+**Can be simplified**
+- RLS (28 statements, 3 loops), BYPASSRLS checks, search-path hardening (3781-3793), and the auto-RLS event trigger exist because Postgres has roles. A single-process embedded engine has none of these.
+- The managed-writer guard and GUC allowlist (2522-2627) matter only with several writer processes. Keep them only if shared multi-host writes stay in scope.
+- LISTEN/NOTIFY becomes an in-process channel.
+- Triggers become one place in the write transaction; keep the semantics identical and test every write path.
+- About 46 migration-only tables and roughly 300 migration versions should not be replayed. Start from the final shape and use the graduation inventory as the carry list.
+- Most partial and expression indexes become application-maintained indexes. Keep the hot ones (claim, pending, generation, dedup).
+
+**Postgres features and their dependencies**
+
+| Feature | Used by | Rust substitute | Risk |
+|---|---|---|---|
+| pgvector HNSW, cosine | `content_chunks.embedding`, `embedding_image` (partial), facts, takes | ANN index plus exact fallback; dims from config; HNSW cap 2,000 (`vector-index.ts:20`) | recall and latency parity |
+| tsvector, GIN, English config | `pages.search_vector`, `content_chunks.search_vector` | tokenizer, stemmer, weights, CJK split | ranking drift |
+| pg_trgm GIN | `pages.title`, `pages.slug` (282, 286) | trigram index | fuzzy-match parity |
+| JSONB, GIN, jsonpath | `frontmatter`, payloads, purge matching (2367-2374) | serde_json plus field index | purge semantics |
+| Triggers | section 9 | in-transaction code | missed write paths |
+| LISTEN/NOTIFY | `minion_jobs` | in-process channel | cross-process workers |
+| FOR UPDATE SKIP LOCKED | `minions/queue.ts` (1511, 1585) | single-writer claim or lease row | double claim |
+| Advisory xact lock (2330), row locks | derivation scope, persistence | per-source mutex | deadlock |
+| Sequences | `page_generation_clock_seq` | atomic counter persisted with the row | monotonicity across restart |
+| NULLS NOT DISTINCT (PG15+) | links, link_transitions | sentinel-normalized unique keys | |
+| DATEMULTIRANGE | `link_relationships.valid_ranges` | interval-set type | low (no index) |
+| Partial unique indexes | one live and one held generation; open lifetime; claim pair; minion idempotency | enforced in transaction | |
+| BYTEA with EXTERNAL storage | segment texts, attachments | blob store | size |
+
+**Risks**
+- The schema is generated from TS modules. Port from those modules, not from this file, or drift follows.
+- The access-control tables (migrations v282-v299) are GI `security`. Dropping them silently changes who can read pages.
+- Segment bodies are DB-only per GI but DER per doc. Treating them as rebuildable from files that do not exist loses large-page bodies.
+- Telemetry must stay off the `pages` row, or triggers and cache invalidation storm.
+- Vector dimension is set at init; changing it rebuilds columns (see v142).
+- One failed statement aborts the whole batch (1368-1376). Do not replay the file as is.
+
+## Open questions
+
+1. Is Rust v1 single-process embedded only, or must it keep the multi-host persistence protocol (12 `persistence_*` tables) and the shared-skill tables?
+2. Are segmented page bodies the only copy of a body (GI user_data), or is the Markdown always the copy (doc)?
+3. Which of the ~46 migration-only tables are in v1 scope? Needs the full graduation list plus migration history.
+4. Must Rust read existing Postgres brains and verify belief and purge hashes, or start fresh?
+5. Is `eval_takes_quality_runs` authoritative (code comment) or a log (this map)?
+6. Are `session_context_state` and `retrieval_weights` per-client or per-brain state?
+7. Not checked: migration bodies (ALTER and DROP history) and triggers on migration-only tables.
diff --git a/docs/designs/rust-engine/research/03-search-pipeline.md b/docs/designs/rust-engine/research/03-search-pipeline.md
new file mode 100644
index 0000000000..697038ce11
--- /dev/null
+++ b/docs/designs/rust-engine/research/03-search-pipeline.md
@@ -0,0 +1,390 @@
+# 03. Search pipeline: retrieval and ranking, end to end
+
+Line numbers refer to gbrain 36bd05806a.
+
+Reference: gbrain TypeScript at `garrytan/gbrain`, commit `36bd05806a` (v0.60.733.0). Paths below are relative to `src/core/` unless they start with `docs/`. Line numbers are from reading the files at that commit.
+
+Provenance labels: **[code]** = read in the source; **[doc]** = quoted from `docs/architecture/RETRIEVAL.md` or `docs/guides/search-modes.md` and not re-measured; **[inferred]** = my reading of how pieces combine, not run.
+
+I did not execute the pipeline, the tests, or any benchmark. The eval repo (`gbrain-evals`, commit `9ecc5b20`) was only checked for layout. Benchmark figures below are doc quotes.
+
+## 1. Entry points
+
+| Op | File | Retrieval path | Expansion | Relational | Facts |
+|---|---|---|---|---|---|
+| `search` | `ops/search.ts:696` | `hybridSearchCached`, expansion pinned off (`:818`), `anyWordFill` | never | mode default | saved facts |
+| `search` `match: keyword` | `ops/search.ts` | page-grain keyword enumeration, no RRF | n/a | n/a | n/a |
+| `query` | `ops/search.ts:881` | `hybridSearchCached`; `expandFn` unless `expand:false` (`:1077`) | mode default (off) or `expand: true` | mode default or `relational` param | facts arm, facts block, temporal reserve, saved facts |
+| `recall` | `ops/facts.ts:298` | `hybridSearchCached`, expansion off (~`:1455`) | off | mode | facts |
+| `think` gather | `think/gather.ts:182-210` | bare `hybridSearch`, expansion off | off | mode | n/a |
+
+
+`query`'s `autocut` param text says "Default on", but the resolved default is off in every bundle (see section 9).
+
+## 2. Mode bundles (`search/mode.ts:488`, `MODE_BUNDLES`)
+
+| Knob | conservative | balanced (default) | tokenmax |
+|---|---|---|---|
+| `searchLimit` (default rows) | 10 | 25 | 50 |
+| `tokenBudget` | 4000 | 12000 | none |
+| reranker | off | `voyage:rerank-3-lite`, topNIn 25 | `voyage:rerank-3-lite`, topNIn 50 |
+| `expansion` | false | false | false |
+| `expansion_variant_budget` | null | null | null |
+| `intentWeighting` | true | true | true |
+| `keywordOrFallback` | true | true | true |
+| `relationalRetrieval` / `relational_planner` | false / false | true / true | true / true |
+| `relational_rerank_pin` | 3 | 3 | 3 |
+| `graph_signals` | false | true | true |
+| `collapse` / `rank_priors` | true / true | true / true | true / true |
+| `floor_ratio` | undefined (off) | undefined | undefined |
+| `metadata_boost_gate` | lexical | lexical | lexical |
+| `autocut` / `autocut_jump` / `autocut_min_top` / `autocut_min_keep` | false / 0.2 / 0.35 / 1 | same | same |
+| `cache_enabled` / threshold / TTL | true / 0.92 / 3600 | same | same |
+
+Resolution order is per-call `SearchOpts`, then per-key config, then `MODE_BUNDLES[search.mode]`, then `balanced` (`search/mode.ts`, header comment). The `cache_*` values (threshold 0.92, TTL 3600 s) are retained config only. The semantic cache is hard-disabled at `search/query-cache.ts:35` (`semanticResultCacheAvailable() { return false; }`), so every request runs retrieval fresh.
+
+## 3. Ordered stage diagram
+
+Default path for a text query with both embedding and keyword available (`hybridSearch`, `search/hybrid.ts:1086`). Pool sizes are for `balanced` and `conservative` with a default `limit`; `tokenmax` doubles them. The DB feature each stage uses is in the right-hand column.
+
+```
+[0] resolve request request.ts:109-250
+ limit = opts.limit || searchLimit (25 balanced)
+ pool = min(max(2*limit, 50, offset+limit), max(100, depth)) -> 50
+ intent = classifyQuery(regex, no LLM) query-intent.ts:513
+ detail: entity->'low' (soft), temporal/event->'high', else undefined
+ DB: none
+ |
+[1] embed query hybrid.ts:1058, timeout 6000ms (floor 2000ms)
+ prefix from config (query-prefix.ts)
+ DB: none (provider call)
+ |
+[2] expansion (off by default) arms.ts:228-258, expansion.ts
+ MIN_WORDS=3, MAX_QUERIES=3 (original + <=2 variants)
+ |
+[3] arms, run concurrently, Promise.allSettled-style fail-open
+ [3a] vector per query variant vector-statement.ts, postgres-engine.ts:1450
+ SQL candidate window innerLimit = offset + max(5*pool, 100) -> 250
+ ANN LIMIT = innerLimit (x2 when index walk)
+ HNSW cosine (<=>), hnsw.ef_search = clamp(window,40,1000)
+ best chunk per page, LIMIT pool
+ DB: pgvector HNSW vector_cosine_ops; hnsw.iterative_scan=relaxed_order;
+ hnsw.max_scan_tuples 20000; statement_timeout from 8000ms deadline
+ [3b] keyword postgres-engine.ts:1066, keyword-chunk-match.ts
+ websearch_to_tsquery('english') @@ chunk.search_vector
+ score = ts_rank(...) * phrase(1|2) * sourceFactorCase
+ ranked_chunks LIMIT min(3*pool, 300) -> 150; best per page; LIMIT pool
+ KEYWORD_RANK_CANDIDATES = 50,000 bound; work_mem 32MB
+ statement_timeout 8000ms (search.keyword_statement_timeout_ms)
+ DB: GIN(search_vector), tsvector, ts_rank, websearch_to_tsquery
+ fallback: if strict AND empty -> OR retry (keywordOrFallback), rarity-ranked
+ [3c] title title-statement.ts
+ pages.search_vector @@ websearch_to_tsquery(gbrain_fts_input(q))
+ exact_title DESC, ts_rank_cd * sourceFactor DESC; LIMIT pool
+ DB: GIN(pages.search_vector), ts_rank_cd
+ [3d] relational relational-recall.ts:376 (only if relational query)
+ typed-edge answers; bounded per-hop SQL; <= 50 frontier pages/hop
+ DB: links table, indexed lookups; recursive CTE only in graph walks
+ |
+[4] drop relaxed (OR) keyword/title rows if a text vector list is non-empty rank.ts:88-93
+ |
+[5] compose RRF lists (fusion-lists.ts composeFusionLists)
+ vector: k=vectorK (intent), keyword/title: k=keywordK, relational: k=60
+ expansion variant/clause: weight = budget/n (budget null -> 1)
+ |
+[6] RRF, page grain (rrf-page-fusion.ts, rrfFusionWeighted hybrid.ts:1467)
+ page vote = weight/(k+rank) at its best rank per list; lead chunk carries it
+ normalize by max; compiled-truth factor x2.0 (explicit low) or x1.2 (auto low)
+ DB: none (in-process)
+ |
+[7] cosine re-score (cosine-rescore.ts:121)
+ score = 0.7 * (rrf / maxRrf) + 0.3 * cosine; cosine = 1 - (embedding <=> q)
+ DB: pgvector <=> in SQL (engine-sql/chunks.ts:1121), dims check
+ |
+[8] post-fusion boosts (runPostFusionStages hybrid.ts:543), metadata group gated
+ backlink x(1+0.05*ln(1+n)); salience x(1+k*ln(1+s)), k=0.15|0.30
+ recency x(1+m*c*h/(h+days)); chronicle event/diary x1.15|1.25
+ graph adjacency x1.05 | cross-source x1.10 | session demote x0.95
+ alias-resolved x1.05; title-phrase x1.25 (not metadata-gated)
+ supersede x0.5
+ DB: GROUP BY counts on links, timeline/effective dates, page_aliases
+ |
+[9] identity boosts (request.ts:348)
+ generated-page demotion x0.5 (GENERATED_FACTOR)
+ exact-match x1.25 (entity intent) or title-mention x1.18 (general/temporal)
+ alias-mention x exactMatchBoost (entity intent only)
+ re-sort by score
+ |
+[10] dedup (dedup.ts:107): L1 top-3 chunks/page; L2 Jaccard>0.85 same page;
+ L3 type share <=0.6; L4 cap 2 per page (6 if segmented);
+ guarantee best compiled_truth chunk per page
+ collapse (collapse.ts; search.collapse=true): twins/redirects take one slot
+ DB: page reads
+ |
+[11] reranker (rerank.ts:127) top topNIn=25 rows, voyage, 5000ms, fail-open to RRF
+ tail keeps fused order; no-key -> reranker_skipped
+ |
+[12] feedback (feedback-boost.ts): bounded per-page weight, only if rated
+ relational re-pin (relational-rerank-pin.ts): <= 3 arm rows back on top,
+ only when reranker reordered
+ rank priors (rank-priors.ts): demote PERSON/OCR/UNDATED/... priors
+ |
+[13] alias hop (alias-hop.ts): exact alias match injects/boosts canonical page
+ exact-lookup tier (exact-lookup.ts): slug/exact-title identity -> rank 1
+ collapse again
+ DB: page_aliases, pages slug/title lookups (pg_trgm used by find_pages, not here)
+ |
+[14] evidence stamp (evidence.ts): alias_hit | exact_title_match |
+ high_vector_match (cosine >= 0.8) | keyword_exact | weak_semantic
+ autocut (off in all bundles), adaptive return (off by default)
+ relational evidence slot: pin one answer on page 1 (chain slots 10)
+ |
+[15] slice [offset, offset+limit) -> token budget (token-budget.ts; chars/4, CJK 1/char)
+ content flags stamp; meta emit
+ |
+[16] ops layer (after cache/capture): facts arm + facts block + temporal reserve (query only),
+ saved facts (search+query), evidence delivery (return_unit=auto, search/evidence-delivery.ts)
+```
+
+The hybrid flow is pinned in `hybridSearch` (`hybrid.ts:1086-1210`). Dedup runs before the reranker, so the reranker sees a diverse pool. The alias hop, exact-lookup tier and evidence stamp run after it.
+
+## 4. The SQL
+
+### 4.1 Vector arm (`search/vector-statement.ts`, `postgres-engine.ts:1450`)
+
+Chunk embeddings live in `content_chunks.embedding vector(1536)` with `CREATE INDEX idx_chunks_embedding ON content_chunks USING hnsw (embedding vector_cosine_ops)` (`schema.sql:360`, `:408`). No `WITH (m, ef_construction)` is set, so pgvector defaults apply [code]. Multimodal columns are `embedding_image` and `embedding_multimodal`, both `vector(1024)` (`schema.sql:400-415`).
+
+Key constants and shape:
+
+- `innerLimit = offset + max(limit*5, 100)` (`vector-statement.ts:315`). With pool 50 that is 250.
+- The ANN ordering is pure distance: `ORDER BY cc.embedding <=> $q LIMIT innerLimit` (`:404-412`). The source factor is a select-list expression, not in the ORDER BY, so the index stays usable (comment `:477-480`).
+- Score: `raw_score = 1 - (cc.embedding <=> $q)`, then `score = raw_score * sourceFactorCase` (`:408`, `:481`).
+- Freshness: `embedded_text_hash = md5(cc.chunk_text) OR embedded_text_hash IS NULL` (`:364`). On an indexed column the freshness predicate moves to a `scored` filter so the planner keeps the HNSW index (`:7-13`).
+- Per-page pool: `DISTINCT ON (COALESCE(source_id,'default'), slug) ORDER BY score DESC, page_id, chunk_id` (`sql-ranking.ts:263`), then `ORDER BY score DESC, page_id ASC, chunk_id ASC LIMIT pool OFFSET offset`.
+- Index walk (`:415-445`) and scope scan (`:447-475`): used only without type/date filters and for source shares of at least 0.04 (`:146`, `:354-361`). Scope scan covers small scopes (share < 0.3, chunks <= 120k; `:159-161`).
+
+Session settings (`vector-settings.ts:29-32`, `vector-pool.ts`):
+
+- `hnsw.ef_search = min(max(window, 40), 1000)` (`vector-index.ts:124-138`). The window is `innerLimit`, or `innerLimit * overfetch` for the walk.
+- `hnsw.iterative_scan`: default `relaxed_order` on pgvector 0.8+ (`search/hnsw-iterative-scan.ts:18`); `off` otherwise.
+- `hnsw.max_scan_tuples = 20000` (`POOL_MAX_SCAN_TUPLES`, `vector-pool.ts:85`).
+- Walk attempts: 2000 ms budget, `enable_sort=off`, up to 2 escalations of x4 (`INDEX_WALK_ESCALATIONS`, `vector-pool.ts:32`).
+- Pool loop: total deadline 8000 ms (`vector-pool.ts:103`), up to 3 escalations of x4 capped at `max(initialLimit, 20000)` (`:121-122`). On Postgres with an index and time left, one exact fallback with `+ 0` (`:125-127`). Shortfalls surface as `vector_candidates_incomplete`.
+
+### 4.2 Keyword arm (`postgres-engine.ts:1066`, `search/keyword-chunk-match.ts`, `search/keyword-statement.ts`)
+
+Non-CJK query:
+
+```
+candidates: content_chunks cc JOIN pages p JOIN sources s
+ WHERE cc.search_vector @@ websearch_to_tsquery('english', $1)
+ AND cc.modality = 'text' AND <type/date/source/hard-exclude/visibility filters>
+score = ts_rank(cc.search_vector, websearch_to_tsquery('english',$1))
+ * (CASE WHEN ... phraseto_tsquery ... THEN 2 ELSE 1 END) -- only if search.keyword_phrase
+ * sourceFactorCase(p.slug)
+ranked_chunks: row_number() OVER (PARTITION BY page_id ORDER BY score DESC, chunk_id) = 1,
+ LIMIT min(3*pool, 300) (innerLimit)
+best_per_page: DISTINCT ON (source_id, slug) ... LIMIT pool OFFSET offset
+```
+
+Facts from the code:
+
+- `KEYWORD_RANK_CANDIDATES = 50,000` (`keyword-chunk-match.ts:30`) bounds the rows ranked; over the bound the arm reports `keyword_candidates_incomplete`.
+- `KEYWORD_STATEMENT_SETTINGS = { work_mem: '32MB' }` (`:40`). Statement timeout comes from `search.keyword_statement_timeout_ms` (default 8000, `postgres-engine/keyword-statement-timeout.ts:28`). A cancelled statement fails open to the vector arm with `keyword_arm_failed`.
+- `ts_rank` is called with **default weights**, which are D=0.1, C=0.2, B=0.4, A=1.0, and default normalization 0. The code passes no weight array. Chunk `search_vector` weights are A = `doc_comment` and `symbol_name_qualified`, B = `chunk_text` (`schema.sql:444-458`). So a markdown chunk's text has weight 0.4 [code]. This is ts_rank, not BM25, despite the RETRIEVAL doc wording.
+- The query text is passed to `websearch_to_tsquery` raw, after `collapseWebsearchDashRuns` only (`postgres-engine.ts:1111`, `keyword-statement.ts:71`). It is **not** wrapped in `gbrain_fts_input`. Only the title arm wraps it (`title-statement.ts:64`). See section 9.
+- Relaxed OR retry (`keywordOrFallback`): if strict AND returns nothing, retry with `buildOrFallbackWebsearchQuery` (`sql-ranking.ts:363`). Narrowing caps at `OR_FALLBACK_MATCH_CAP = 20,000` (`keyword-or-narrow.ts:24`); rarity uses `RARE_TERM_CHUNK_CAP = 400` (`keyword-or-rarity.ts:36`).
+- Relaxed rows are dropped from RRF when a text vector list is non-empty (`hybrid/rank.ts:88-93`).
+
+### 4.3 Title arm (`search/title-statement.ts`)
+
+- Match: `p.search_vector @@ (websearch_to_tsquery('english', gbrain_fts_input($1)) || name-variant queries)` (`:64`). Name variants are given-name spellings (`titleNameVariants`, #7471).
+- Rank: `ts_rank_cd(p.search_vector, tsq) * sourceFactorCase` (`:68`). Page `search_vector` weights are A = title, C = timeline text (`schema.sql:1222-1224`).
+- Order: `exact_title DESC, score DESC, p.id ASC`, `LIMIT pool OFFSET offset` (`:125-126`). `exact_title = lower(btrim(title, ' "' || chr(160))) = normalizeAlias(query)`.
+- One row per page. A chunkless page gets a synthetic row (`chunk_id 0`, empty text), which the compiled-truth boost skips (`hybrid.ts:125-135`, #3695).
+
+### 4.4 CJK path (`search/cjk-keyword-sql.ts`, `search/cjk.ts`)
+
+- Trigger: `hasCJK(query)` (`cjk.ts:74`). `websearch_to_tsquery` cannot tokenize CJK under an ASCII config, so the tsvector path is skipped.
+- Terms: whitespace split, Korean particles stripped (`cjk.ts:207-250`). Match: AND of `LIKE/ILIKE '%term%'` per term.
+- Score: occurrence counts summed over terms, plus raw-phrase bonus and `1/POSITION` tiebreak; OR variant adds `MATCHED_TERM_WEIGHT = 1000` per matched term (`cjk-keyword-sql.ts:61`). Source factor multiplies.
+- Budget: `search.cjk_keyword_deadline_ms` default 3000, range 500-30000 (`cjk-keyword-deadline.ts:11-13`).
+- No tsvector, no GIN: an unindexed `LIKE` scan [code].
+
+### 4.5 Relational arm (`search/relational-recall.ts:376`, `relational-chain.ts`)
+
+- Built once before any return path (`hybrid/arms.ts:170-198`). Off unless `relationalRetrieval` is true (balanced and tokenmax).
+- Single hop: `parseRelationalQuery` (`relational-intent.ts:341`, fixed vocabulary regex). Planner (`relational_planner`): `parseRelationalPlan` (`relational-plan.ts:176`), at most `MAX_CHAIN_HOPS = 3` (`relational-chain.ts:363`). Per hop: 50 frontier pages, 100 edges per page, 10 paths per page [doc]. `CHAIN_HUB_HALF_DEGREE = 32` (`:126`), `UNCERTAIN_EDGE_WEIGHT = 0.5` (`:129`).
+- Fused at `k = baseRrfK = 60` only if the query is not image-modal and the list is non-empty (`fusion-lists.ts`).
+
+### 4.6 Facts arm and saved facts (query only, after retrieval)
+
+- Facts arm (`search/facts-arm.ts`): `MAX_FACT_ROWS = 3` (`:35`). Fact cosine floor `FACTS_ARM_COSINE_MIN = 0.6` (`fact-relevance.ts:75`), ordering by `facts.embedding <=> q` (vector or halfvec, `fact-relevance.ts:212-241`), lexical side `ts_rank_cd` over the facts FTS document (`idx_facts_fts`), term share `TERM_SHARE_MIN = 0.5` (`facts-arm.ts:39`). Facts take only spare row slots.
+- Facts block (default on, needs `token_budget`): up to 22% of the budget (`QUERY_FACTS_BLOCK_SHARE = 0.22`, `:52`), 40 rows (`:53`).
+- Temporal reserve (default off): 15% of budget (`:44`), 30% of rows (`:47`), up to 20 rows (`:45`).
+- Saved facts on `search` and `query`: up to 5 facts, three-quarters term share, capped at four required words [doc].
+
+## 4.7 Cosine SQL
+
+`engine-sql/chunks.ts:1121` returns `1 - (col <=> q)` with dims and zero-norm guards, only for chunks visible under the page visibility predicate. Unhydrated rows get cosine 0 (`cosine-rescore.ts:117`).
+
+## 5. Fusion
+
+### 5.1 RRF (`hybrid.ts:1467` `rrfFusionWeighted`, `search/rrf-page-fusion.ts`)
+
+- Vote identity is the page `(source_id, slug)`, not the chunk. Each list votes once per page at its best rank. The votes sum per page, and the page's lead chunk (largest own vote) carries the total. Other chunks keep their own votes (`rrf-page-fusion.ts:23-35`).
+- Vote = `weight / (k + rank)`, rank 0-based (`rrf-page-fusion.ts:80`).
+- Normalize by the maximum raw score so the top is 1.0 (`hybrid.ts:1480-1495`), then multiply by the compiled-truth factor (below).
+- Sort by `score DESC, own DESC`. Ties then follow the fusion's list order.
+- `RRF_K = 60` (`hybrid.ts:58`). Keyword-only and no-embedding paths use the same constant (`hybrid/keyword-only.ts:60,270`).
+
+### 5.2 Intent-based k (`search/intent-weights.ts:60-123`, `hybrid/rank.ts:55-65`)
+
+`effectiveRrfK(60, w) = 60 / w` (`:123`). Weights per intent (`:67-105`):
+
+| Intent | keyword weight -> keyword k | vector weight -> vector k | Notes |
+|---|---|---|---|
+| general | 1.0 -> 60 | 1.0 -> 60 | default |
+| entity | 1.15 -> 52.2 | 1.0 -> 60 | exact-match boost 1.25 |
+| temporal | 1.0 -> 60 | 1.0 -> 60 | recency suggested "on" |
+| event | 1.20 -> 50.0 | 0.95 -> 63.2 | recency "on", exact 1.10 |
+| concept | 0.9 -> 66.7 | 1.2 -> 50.0 | exact 1.0; title-mention boost off |
+
+Cross-modal "both" mode only: text k = 60/0.6 = 100, image k = 60/0.4 = 150 (`mode.ts` weights). Image-query refinement uses 60/0.4 and 60/0.6 (`by-image.ts:118-120`).
+
+Intent comes from `classifyQuery` (`query-intent.ts:513`), which is regex only and calls no LLM. Auto `detail` comes from `intentToDetail` (`query-intent.ts:607`): entity -> `low`, temporal/event -> `high`, concept/general -> undefined.
+
+### 5.3 Compiled-truth factor (`hybrid.ts:92-135`)
+
+- Applies only when `detail === 'low'`. Explicit `low` gives x2.0 (`COMPILED_TRUTH_BOOST`). Auto-`low` from entity intent gives x1.2 (`AUTO_LOW_COMPILED_TRUTH_TILT`, `:102`). Other details give 1.0.
+- Skipped for unverified auto-extracted stubs and synthetic chunkless title rows (#160, #3695).
+- The header comment at `hybrid.ts:1-10` still says "2.0x for compiled_truth chunks" with no mention of detail gating. That comment is stale.
+
+### 5.4 Cosine blend (`cosine-rescore.ts:121`)
+
+`blended = 0.7 * (score / maxScore_after_boost) + 0.3 * cosine`. The max is taken after the compiled-truth factor over the same nonnegative scores, so the normalized value is in [0,1]. Cosine is not clamped, so the blended score is in [-0.3, 1], not [0, 1]. Rows are re-sorted by blended score. This runs before post-fusion boosts (`rank.ts:156-165`).
+
+### 5.5 Source-aware factor (inside each arm's SQL)
+
+`buildSourceFactorCase` (`sql-ranking.ts:67`) is a longest-prefix `CASE`. Defaults (`search/source-boost.ts:18-45`): `originals/` 1.5, `writing/` 1.4, `concepts/` 1.3, `people/` `companies/` `deals/` 1.2, `meetings/` `media/articles/` `media/repos/` 1.1, `yc/` `civic/` 1.0, `daily/` 0.8, `media/x/` 0.7, `openclaw/chat/` `archive/` 0.5. Hard excludes (`:67`): `test/`, `attachments/`, `.raw/`. `detail: high` returns 1.0 (`sql-ranking.ts:73`). Because RRF uses ranks, this only changes order within an arm and which chunk represents a page.
+
+## 6. Post-fusion boosts (`runPostFusionStages`, `hybrid.ts:543`)
+
+All multiplicative on the score. `floor_ratio` is undefined in every bundle, so the floor gate is off (`computeFloorThreshold` returns -Infinity, `hybrid.ts:300`). Each stage stamps an explain field.
+
+| Stage | Constant | Gated by | Source |
+|---|---|---|---|
+| Backlink | `1 + 0.05 * ln(1 + inbound)` | metadata gate | `hybrid.ts:257` |
+| Salience | `1 + k * ln(1 + s)`, k = 0.15 (on) / 0.30 (strong) | metadata gate; `salience` opt | `hybrid.ts:327` |
+| Recency | `1 + m * c * h / (h + days)`; m = 1.0 / 1.5; per-prefix `(h, c)` | metadata gate; `recency != off` (intent-driven) | `hybrid.ts:359`, `recency-decay.ts:43-76` |
+| Chronicle type | event/diary x1.15 (on) / x1.25 (strong) | recency on | `hybrid.ts:448` |
+| Graph adjacency | x1.05 (>=2 hits in top-20), cross-source x1.10, session demote x0.95 | metadata gate + `graph_signals` | `graph-signals.ts:54-68` |
+| Alias-resolved | x1.05 | metadata gate | `hybrid/alias-resolved.ts:16` |
+| Title phrase | x1.25 (`title_boost`) | **not** gated | `hybrid.ts:416` |
+| Supersede | x0.5 | always (probe, 5-min TTL) | `hybrid.ts:779` |
+| Generated-page demotion | x0.5 | identity stage | `provenance-demotion.ts:28` |
+| Exact match | x1.25 (entity intent) | intent | `intent-weights.ts:141` |
+| Title mention | x1.18 (general/temporal, not concept, not relational) | intent | `intent-weights.ts:172` |
+
+Recency per prefix (`recency-decay.ts:43-76`): `daily/` 14 d / 1.5, `media/x/` and `chat/` 7 d / 1.5 and 1.0, `meetings/` 60 d / 1.0, `originals/` 180 d / 0.5, `writing/` 365 d / 0.4, `people/` and `companies/` 365 d / 0.3, `deals/` 180 d / 0.5, `concepts/` evergreen, fallback 90 d / 0.3.
+
+The metadata gate (`search/metadata-boost-gate.ts`, `lexical` in every bundle) skips the backlink, salience, recency, graph and alias stages when no strict keyword, title or relational row fused (relaxed OR rows do not count). Supersede, exact-match, title-phrase and compiled-truth stages still run. Doc receipt: conceptual nDCG@5 53.0 -> 57.8 [doc].
+
+## 7. Dedup, rerank, and the return tail
+
+### 7.1 Dedup (`search/dedup.ts`)
+
+Order (`dedupResults`, `:107-146`): L1 keep top 3 chunks per page (`dedupBySource`, `:151`); L2 drop same-page chunks with word-set Jaccard > 0.85 (`COSINE_DEDUP_THRESHOLD`, `:32`; whitespace-split, lowercased); L3 no type above `ceil(n * 0.6)` (`MAX_TYPE_RATIO`, `:33`); L4 cap 2 per page (`MAX_PER_PAGE`, `:34`; `MAX_PER_SEGMENTED_PAGE = 6`, `:36`); final pass adds the best pre-dedup compiled-truth chunk for any page lacking one, appended, not swapped (`guaranteeCompiledTruth`).
+
+### 7.2 Reranker (`search/rerank.ts:127`, `ai/defaults.ts:19`)
+
+- Reads `deduped.slice(0, topNIn)`; tail keeps fused order (`rerank.ts:137-138`). `topNIn` = 25 balanced, 50 tokenmax; conservative has it off.
+- Model `voyage:rerank-3-lite` unless `search.reranker.model` is set. Timeout 5000 ms. Fail-open: no key -> `reranker_skipped (no_key)`, timeout -> `rerank_failed`, pass-through -> `rerank_passthrough`, all stamped in degraded (`hybrid/rank.ts:286-347`).
+
+### 7.3 After rerank
+
+1. `applyFeedbackStage` (`feedback-boost.ts`): bounded multiplier from use-attributed ratings; no-op when nothing is rated.
+2. `pinRelationalRows` (`relational-rerank-pin.ts`): up to 3 arm rows back on top (max 10, `:73-75`). Only if the reranker reordered; not for image queries.
+3. `applyRankPriors` (`rank-priors.ts:127`): multiplicative priors (`PERSON 0.85`, `OCR 0.6`, `UNDATED 0.85`, `REDIRECT_STUB 0.5`, `ARCHIVE 0.8`; `:28-33`).
+4. Alias hop, exact-lookup tier (rank 1, supersession-filtered), then collapse again (`rank.ts:383-391`).
+
+### 7.4 Evidence, autocut, slot, budget (`rank.ts:370-545`)
+
+- Evidence labels (`evidence.ts`): `high_vector_match` needs real cosine >= 0.8 (`:64`); `keyword_exact` needs a strict keyword hit with base score >= 0.6 (`:53`). `HIGH_MATCH_FLOOR` 0.85 (`:51`) is legacy.
+- Adaptive return: opt-in, off. Autocut: off in every bundle. When on: cut at the largest rerank-score drop of at least 20%, keep at least 1, skip when top score < 0.35 (`autocut.ts:45-49`), page 1 only.
+- Relational evidence slot (`relational-recall.ts:280`): one arm answer guaranteed on page 1 (`relational_chain_slots = 10`).
+- Slice, then token budget: `balanced` 12000, `conservative` 4000, `tokenmax` none (`token-budget.ts:47`; CJK chars count 1 each).
+
+### 7.5 Evidence delivery
+
+`return_unit` defaults to `auto` (`search/evidence-delivery.ts:51`). `auto` expands only conversation hits to the whole page. Budgets: 6000 default, 24000 conversation, 32000 remote max (`:61-65`). Runs after cache and capture; neighbour chunks come from one batched, `page_id`-keyed, re-authorized read.
+
+## 8. Query cache and expansion
+
+- Query cache: disabled by `semanticResultCacheAvailable() = false` (`query-cache.ts:35`). Retained constants: threshold 0.92 (`:42`), TTL 3600 s (`:44`), text guard Dice 0.5 (`:102`). Degraded results use a 60 s TTL (`hybrid.ts:1382`). Cache keys include `evb=`, `mbg=`, `rrp=`, `rp=` in the knob hash [doc].
+- Expansion (`search/expansion.ts`): original + up to 2 LLM variants, skipped under 3 words (`MIN_WORDS`, `:17`) or 500 chars (`:18`). Variant weight is `budget / n` when `search.expansion_variant_budget` is set; default null = weight 1 (`fusion-lists.ts`). Doc: equal-weight expansion halved LongMemEval-S recall_all@5 (93.19% to 54.89%) [doc].
+
+## 9. Discrepancies between docs and code
+
+1. `query` param text says autocut is "Default on" (`ops/search.ts:943`). Resolved default is off in all three bundles (`mode.ts`), and `pagePlanHits` only forces off (`page-plan-hits.ts:10-14`). Code wins.
+2. RETRIEVAL.md calls the keyword arm "BM25". The code uses `ts_rank` with default weights and no normalization (`keyword-statement.ts:74`). Not BM25.
+3. The `hybrid.ts:1-10` header says the compiled-truth boost is always 2.0x. Code applies it only to explicit `detail: 'low'` (1.2x for auto), `hybrid.ts:92-108`.
+4. The keyword arm does not wrap the query in `gbrain_fts_input`; indexing and the title arm do. [inferred] An ASCII token that index-time splitting breaks (the doc's `Redis7` example) may miss on the keyword arm. Not run.
+
+## Rust engine implications
+
+**Must preserve exactly (contract, covered by tests or user-visible):**
+
+- Page-grain RRF: vote per page per list at its best rank, lead chunk carries the total, k = 60 base, intent k table (section 5.2), weights per list, max normalization before boosts.
+- Compiled-truth factor as explicit `low` 2.0x vs auto `low` 1.2x, skipped for unverified stubs and chunkless title rows.
+- Cosine blend 0.7 / 0.3 using the post-boost max, computed after RRF and before post-fusion boosts.
+- Stage order: dedup before rerank; alias hop, exact-lookup and evidence stamp after rerank; token budget last on the final slice.
+- Dedup layers L1-L4 with the constants above, plus the compiled-truth guarantee that appends rather than replaces.
+- Deterministic tie-breaks everywhere: `score DESC, page_id ASC, chunk_id ASC`.
+- Freshness: an embedding counts only if its `embedded_text_hash` matches the current text (or is NULL).
+- Visibility, private-page and hard-exclude filters must sit inside each candidate set, never be applied after ranking. Remote callers must not see private pages through any arm. Fail-closed on DB access errors: if both lexical arms fail with an access-class error, return an error, not an empty result (`hybrid/arms.ts:109-111`).
+- Relaxed OR keyword rows drop out of fusion whenever a text vector list is non-empty.
+- Source factor as a per-arm multiplier, longest prefix, `detail: high` bypass.
+
+**Can simplify:**
+
+- The index-walk, scope-scan, escalation and iterative-scan machinery (`vector-statement.ts`, `vector-pool.ts`) exists to work around pgvector filtered-HNSW planner behaviour. A Rust index that filters during search, or an exact scan on small scopes, can drop most of it. Keep only the contract: distinct pages, filters applied, bounded time.
+- The keyword OR fallback rarity machinery and CJK `LIKE` scan exist because Postgres ts_rank cannot tokenize CJK and cannot rank rare terms. An inverted index with real term statistics can replace them, but this changes scores. Decide whether to keep ts_rank-like scoring or move to BM25, and validate.
+- Semantic result cache: already disabled. Drop it; keep the knob names reserved.
+- `KEYWORD_RANK_CANDIDATES` (50k) and statement timeouts are Postgres guards. Keep the degraded-stage names (`keyword_candidates_incomplete`, `vector_candidates_incomplete`); they are user-visible.
+
+**Postgres features each stage depends on:**
+
+| Stage | Postgres feature | Rust replacement needed |
+|---|---|---|
+| Vector arm | pgvector `vector` type, HNSW `vector_cosine_ops`, `<=>`, `hnsw.ef_search`, `hnsw.iterative_scan`, `hnsw.max_scan_tuples`, `+0` index bypass | HNSW or flat vector index with filter-aware search; cosine |
+| Cosine rescore | `<=>` in SQL, `vector_dims`, `vector_norm` | in-process cosine on stored vectors |
+| Keyword arm | `tsvector`, GIN on `search_vector`, `websearch_to_tsquery('english')`, `ts_rank`, `phraseto_tsquery`, `setweight`, `ts_filter` | inverted index, query parser with websearch semantics, term stats |
+| Title arm | GIN on `pages.search_vector`, `ts_rank_cd`, `gbrain_fts_input()` (a SQL function) | title FTS index; port the CJK boundary split |
+| CJK path | `LIKE`/`ILIKE` with `ESCAPE` over `chunk_text` (unindexed) | substring or n-gram index |
+| Per-page pool | `DISTINCT ON`, window `row_number() OVER`, `count(*) OVER` | group-by with max, in process |
+| Index walk / scope scan | `MATERIALIZED` CTEs, `OFFSET 0` fences, `LATERAL` probes, `ANY(ARRAY(...))`, `hashint4` sampling | not needed if filters are applied in the index scan |
+| Filters and visibility | correlated `EXISTS` subplans, `NOT EXISTS`, `RLS` scope binding (`app.scopes`), `SET LOCAL` GUCs | row-level predicate in the engine, no RLS |
+| Freshness | `md5(chunk_text)` column compare | content hash in Rust |
+| Timeouts | `statement_timeout`, transaction-local `SET LOCAL` | time budget per arm in the engine |
+| Relational arm | indexed `links` reads, per-hop bounded SQL, recursive CTE for BFS | adjacency list in memory or a graph index |
+| Facts arm | `facts.embedding` halfvec, `ts_rank_cd` over `idx_facts_fts` | same as vector + keyword, over facts table |
+| Find-by-name (not ranked search) | `pg_trgm` GIN (`idx_pages_trgm`, `idx_pages_slug_trgm`) | trigram index if find_pages is kept |
+
+`LISTEN/NOTIFY`, advisory locks and `SKIP LOCKED` do not appear on the read path I traced.
+
+**Risks:**
+
+- Score parity: cosine should match; ts_rank will not. The gbrain-evals gates (BrainBench, NamedThingBench, LongMemEval) are the only parity check. Decide early between bit-compatible scores and ranking-level parity.
+- The keyword arm not normalizing query text (section 9.4) may be a live bug that a rewrite should not copy by accident.
+- The metadata gate, relational pin, feedback and rank priors all depend on the `lexical` decision. A reordering bug in one of them changes top-1 results more than a score change does.
+
+## Open questions
+
+1. Should the rewrite keep `ts_rank` default weights (D 0.1, C 0.2, B 0.4, A 1.0) and no normalization, or move to BM25 as the doc describes? This changes every keyword score and every boost that multiplies one.
+2. Is the keyword arm's missing `gbrain_fts_input` on the query side intentional? Confirm with a test on a CJK-adjacent ASCII token before porting.
+3. Which `query` default is authoritative for autocut: the param text ("Default on") or the bundles (off)?
+4. The facts arm, facts block and temporal reserve run only in `query` (RETRIEVAL.md). Confirm before porting the op surface.
+5. The HNSW walk/escalation machinery targets a 25k-chunk planner cliff. What is the target brain size for the Rust engine? That decides whether a flat scan is acceptable.
+6. Do the title-arm and CJK path need separate CJK title matching? The title arm uses `websearch_to_tsquery` and unlikely matches unspaced CJK titles [inferred, not run].
+7. Benchmark numbers are doc quotes. The Rust port needs the gbrain-evals harness re-run as its gate; I did not inspect those harness commands.
diff --git a/docs/designs/rust-engine/research/04-ingest-chunk-embed.md b/docs/designs/rust-engine/research/04-ingest-chunk-embed.md
new file mode 100644
index 0000000000..7eab2b9ab9
--- /dev/null
+++ b/docs/designs/rust-engine/research/04-ingest-chunk-embed.md
@@ -0,0 +1,315 @@
+# Write path: ingest, parse, chunk, embed, store
+
+Line numbers refer to gbrain 36bd05806a.
+
+Scope: the TypeScript gbrain write path, pinned to commit `36bd05806a` (v0.60.733.0) in `garrytan/gbrain`. Read-only reference; nothing there was edited.
+
+Evidence convention: plain statements were verified by reading the cited line. Statements marked **(inferred)** were not traced end to end.
+
+## 1. Entry points
+
+| Entry | Path | Notes |
+|---|---|---|
+| `gbrain import <dir>` | `src/commands/import.ts:267` `runImport`; per file calls `importFile` at `:749` | Concurrency clamped by `sync-concurrency.ts` (`clampWorkersForConnectionBudget`, `:488`). |
+| `gbrain sync` | `src/commands/sync.ts:444` `runSync` -> `runSyncInner`; `:517` `syncOneSource` | `--all` worker pool: `resolveParallelism` (`:477`), `DEFAULT_PARALLEL_SOURCES = 4` (`src/core/sync-concurrency.ts:47`). |
+| Sync pipeline | `src/commands/sync/incremental.ts:23` `performSyncInner` -> `preflight.ts:65` `preflightIncrementalSync` -> `preflight.ts:1005` `computeFilteredDelta` -> `imports.ts:57` `runImportsPhase` | Phase names (inferred from the module list in `src/commands/sync/`): preflight, delta, holds, imports, deletes/renames, embed pass, checkpoint. |
+| Per-file import in sync | `src/commands/sync/imports.ts:270` `importOnePath`; `:432` `drainImports` | Images go to `importImageFile` (`imports.ts:357`); text to `importFile`. |
+| `put_page` (MCP/CLI) | `src/core/ops/pages.ts:345` op; handler at `:368`-`:390` | Validates slug, runs slug fences and large-page admission (remote), then `submitPageMutation` (`src/core/persistence/page-mutations.ts:234`). |
+| `put_pages` (batch) | `src/core/ops/page-batch.ts` | Batch variant; `submitPageMutations` at `src/core/persistence/page-batch.ts:337`. |
+
+Verified: `imports.ts:68-74` says not to wrap the add/modify loop in `engine.transaction()`. Each file gets its own inner transaction. The comment states PGLite transactions are not reentrant (one mutex), so nesting hangs. Per-file atomicity is the chosen granularity.
+
+Inferred: the persistence coordinator reaches `importFromContent` through its `prepare` / `coordinated` seam (documented at `src/core/import-file.ts:259-265`). I did not trace the coordinator body.
+
+Checkpoint defaults (`src/commands/sync/checkpoint.ts:37-39, 72`): flush every 1000 files, at least every 10 s, abort after 3 consecutive checkpoint failures, yield to the event loop every 64 files.
+
+## 2. Change discovery (git)
+
+`src/core/sync-delta.ts`:
+- Committed range: `git diff --name-status -M from..to` (`:151`) and the NUL-safe form `git diff --raw -z -M from..to` (`:277`).
+- Working tree: `git diff --raw -z -M HEAD` (`:287`) plus `git ls-files -z --others --exclude-standard` (`:288`) for untracked files.
+- Output is read with a raised buffer because a 100K-file `--name-status` diff can exceed Node's 1 MiB default (`sync-delta.ts:46`; `sync-git.ts:303`).
+- Read-only git verbs are allowlisted (`sync-git.ts:288`).
+
+`sync-git.ts:264` `buildAutoEmbedArgs` and `:280` `resolveNoEmbed` are the sync-side embed switches (signatures verified; their exact decision rules were not traced).
+
+Verified: code-file allowlist `CODE_EXTENSIONS` in `src/core/sync.ts` (around `:87`) is derived from the chunker's language map, so only chunker-supported code files enter the code path.
+
+## 3. Parsing markdown (`src/core/markdown.ts`)
+
+Frontmatter:
+- `parseMarkdown` `:319`; `parseMarkdownHead` `:355`; `parsedMarkdownFields` `:449`; `frontmatterBodyOffset` `:137`.
+- Parse validation codes (`:16-24`): `MISSING_OPEN`, `MISSING_CLOSE`, `YAML_PARSE`, `SLUG_MISMATCH`, `NULL_BYTES`, `NESTED_QUOTES`, `NON_STRING_FIELD`, `EMPTY_FRONTMATTER`.
+- Warnings (`:37`): `FRONTMATTER_RECOVERED`, `FRONTMATTER_COMMENT_VALUE`.
+- Ambiguous unquoted lines are repaired by `quoteAmbiguousFrontmatterLine` (`:233`). I did not read its rules in full.
+- YAML alias budget: `MAX_FRONTMATTER_YAML_ALIASES = 16` (`:804`), checked by `yamlAliasesWithinLimit` (`:807`).
+- Reserved keys `type`, `title`, `tags`, `slug` (`:1304`).
+
+Holds (quarantine on import, not failure):
+- `HOLD_CODES` (`:510`): `invalid_frontmatter`, `frontmatter_slug_conflict`, `file_too_large`, `rename_held`, `parser_regression`, `tag_too_long`.
+- `INVALID_FRONTMATTER_REASONS` (`:512`): `yaml_parse`, `needs_interpretation`, `ambiguous_identity_key`, `ambiguous_protected_key`.
+- `contentSizeHold` (`:528`) and `classifyImportHold` (`:561`).
+- Intended refusal: `yaml_alias_limit` (`:515`).
+
+Timeline split (`splitBody` `:869`):
+1. `<!-- timeline -->` (preferred; also `<!--timeline-->`), or `--- timeline ---` (`timelineSentinelKind`, `:938`).
+2. A bare `---` counts only if content sits above it and the next non-blank line is a timeline heading (`isTimelineHeadingAfterDash`, `:944`).
+3. A sentinel inside a fenced code block does not split (`findLineOutsideFencedCode`, used by `findTimelineSplitIndex`, `:900`).
+4. Fallback: a timeline-shaped section (`findBareTimelineSection`) moves out of `compiled_truth`; later H2 sections stay.
+
+Output: `compiled_truth` is everything above the split; `timeline` is the rest. `serializeMarkdown` (`:1018`) writes `\n\n<!-- timeline -->\n\n` before a non-empty timeline and writes an empty sentinel when `needsEmptyTimelineSentinel` (`:1012`) says the body would otherwise be re-parsed wrongly.
+
+Size limits (`src/core/page-size-policy.ts`):
+
+| Constant | Value | Line |
+|---|---|---|
+| `PAGE_MAX_BYTES` | 24 MiB | `:16` |
+| `CODE_FILE_MAX_BYTES` | 5,000,000 | `:26` |
+| `PAGE_INLINE_MAX_BYTES` | 1 MiB | `:35` |
+| `isLargePageBytes` | predicate on the inline threshold | `:38` |
+| `MAX_FILE_SIZE` (import screen) | `= PAGE_MAX_BYTES` | `src/core/import-screen.ts:44` |
+
+Segmentation thresholds (`src/core/page-body/limits.ts`): promote to segmented above 1 MiB (`:28`); demote at or below 512 KiB (`:30`); segment min 64 KiB, target 256 KiB, rank-4 384 KiB, max 1 MiB (`:33-38`). Segmented pages store body regions separately (`src/core/page-body/`).
+
+## 4. Slug rules
+
+- `pathToSlug` `src/core/sync.ts:799`; `slugifyPath` `:775`; `slugifySegment` `:730`; `slugifyCodePath` `:786`.
+- Markdown: strip `.md`/`.mdx`; backslashes to `/`; drop leading `./`; slugify each segment.
+- Segment slugify: NFD, strip combining marks, strip Hebrew niqqud and cantillation (U+0591-U+05C7), NFC, strip variation selectors, lowercase, keep alnum, dot, space, `_`, `-`, and CJK; spaces to `-`; collapse hyphen runs and trim edge hyphens (`foldSegmentHyphens`).
+- Code: dots become hyphens and the path is flattened to one segment, so `src/core/chunkers/code.ts` becomes `src-core-chunkers-code-ts` (per the function's own doc comment).
+- A put that would change its slug under folding is refused (`hyphenFoldedSlug`, #7305).
+- Portability: `FILE_NAME_MAX_BYTES = 240` (`src/core/portable-slug.ts:18`); reserved device names (`:22`).
+- Op-level slug grammar: `OP_PAGE_SLUG_RE` (`src/core/page-slug-grammar.ts:25`); `validateSlug` (`src/core/utils.ts:39`).
+- Frontmatter slug conflict produces a hold, message from `slugConflictHoldMessage` (`src/core/import-file.ts:195`).
+
+## 5. Link extraction
+
+- Body: `extractPageLinks` `src/core/link-extraction.ts:844`; `extractBodyLinks` `:866`; `extractMarkdownLinks` `:1153`; `resolveMarkdownLinkSlug` `:655`.
+- Frontmatter: `frontmatterLinks` `:1083`.
+- Dedupe: `dedupeCandidates` `:1104`.
+- Code refs and entity refs: `extractCodeRefs` `:385`, `extractEntityRefs` `:409`.
+- Derived link storage lives in `src/core/derived-links.ts` **(not traced)**.
+
+## 6. Content hashing and change detection
+
+Page hash (`src/core/utils.ts:121`, `contentHash`):
+- `sha256(JSON.stringify({ title, type, compiled_truth, timeline: timeline || '', frontmatter, tags }))`, hex.
+- Frontmatter is a copy with `HASH_EPHEMERAL_FRONTMATTER_KEYS` and `tags` removed (`contentHashFrontmatterAndTags`, `:141`). Tags are the sorted `page.tags ?? frontmatter.tags`.
+- A streamed form (`src/core/page-body/content-hash-stream.ts`) must hash identical bytes.
+- Byte parity is pinned by `test/content-hash-parity-3694.test.ts` (named in a comment at `import-file.ts:510-516`).
+- Legacy formula: `contentHashLegacy` (`utils.ts:158`), used for compatibility (`import-file.ts:564`). Its full body was not read.
+
+Short-circuit: in `importFromContent` (`src/core/import-file.ts:254`), `hash` is computed at `:521`. When `existing.content_hash === hash` and the trust marker is unchanged (`:564-575`), the chunk-and-embed step is skipped. `forceRechunk` (opt, `:295`) bypasses it for `gbrain reindex --markdown`.
+
+Code files: `importCodeFile` (`import-file.ts:1241`) computes `sha256` at `:1287`; same short-circuit at `:1298`; `noEmbed` branch at `:1311`.
+
+Images: `importImageFile` (`:1877`) hashes the buffer at `:1916`; skip at `:1920`.
+
+Per-chunk provenance (`src/core/embedding-input-hash.ts`, #5553): `embeddingInputHash(ctx, tier, chunk)` (`:59`). It digests the vector column, model, dims, tier, and the exact input text. Tiers: `none`, `title`, `per_chunk_synopsis`. `content_chunks.embedded_text_hash` is `md5(chunk_text)` at embed time (`src/core/embed-stale.ts:178-183`, and the column comment in the schema).
+
+## 7. Chunking
+
+### 7a. Markdown: `src/core/chunkers/recursive.ts`
+
+Pipeline:
+1. `chunkText` (`:116`): `sanitizeRemoteBody` strips takes fences; `credentialSafeProjection`; world-visibility facts stay, private ones are removed.
+2. `chunkProjectedText` (`:134`): word count (CJK-aware, `src/core/cjk.ts`). If `wordCount <= chunkSize`, one chunk, then the char cap.
+3. Otherwise `recursiveSplit` -> `greedyMerge` -> `applyOverlap` -> `capByChars` (hard cap).
+
+Defaults (verified in code):
+
+| Option | Default | Where |
+|---|---|---|
+| `chunkSize` | 300 words | `recursive.ts:135` (`opts?.chunkSize \|\| 300`) |
+| `chunkOverlap` | 50 words | `:136` |
+| `maxChars` | 6000 chars | `:137` |
+| `maxTokens` | `DEFAULT_MAX_CHUNK_TOKENS` = 2000 (clamped down only) | `:138-141`; constant at `src/core/chunkers/token-estimate.ts:20` |
+| `boundaryCuts` | off (on for segmented pages only) | `ChunkOptions`, `recursive.ts:58-88` (doc comments) |
+| `headingsLead` | off (segmented only) | `ChunkOptions`, `recursive.ts:58-88` (doc comments) |
+| `CUT_LOOKBACK_CHARS` | 512 | `:353` |
+
+Delimiter hierarchy (`DELIMITERS`, `:50-56`): L0 `\n\n` paragraphs; L1 `\n` lines; L2 sentence ends including CJK full stops; L3 clauses `; `, `: `, `, `, CJK commas; L4 words (whitespace, or CJK char slice).
+
+Version constants (any boundary change must bump these to force reindex or re-embed):
+- `MARKDOWN_CHUNKER_VERSION` = `SAFE_FENCE_CHUNKER_VERSION` = 4 (`src/core/search/safe-chunks.ts:6`; re-exported at `recursive.ts:48`).
+- `SEGMENTED_CHUNKER_VERSION` = 5 (`src/core/page-body/segment-chunks.ts:47`).
+
+Token estimate: `estimateEmbedTokens` (`src/core/chunkers/token-estimate.ts:190`). `cl100kAvailable()` (`:48`) gates an exact tokenizer; the fallback when it is false is **(inferred: a heuristic)**. Whether the exact path runs depends on the host (see Rust risks).
+
+### 7b. Fenced code inside markdown: `src/core/markdown-chunks.ts`
+
+- Fence language tags map to pseudo paths (`FENCE_TAG_TO_PSEUDO_PATH`, `:10`), e.g. `ts`/`typescript` -> `fence.ts`, `py` -> `fence.py`, `rs` -> `fence.rs`. Unknown tags stay prose.
+- Per-fence tree-sitter parse timeout `GBRAIN_FENCE_PARSE_TIMEOUT_MS`, default 2000 ms (`:57`). Per-page budget `GBRAIN_FENCE_PARSE_BUDGET_MS`, default 5000 ms (`:59`).
+- Max fences per page: `GBRAIN_MAX_FENCES_PER_PAGE`, default 100 (`src/core/fence-scan.ts:27-29`).
+- `prepareMarkdownChunks` (`:179`): a quarantined page returns zero chunks. An `embed_skip` page keeps its chunks for keyword search but gets no vectors (#6722).
+- `prepareProseChunks` (`:191`) is the prose-only variant used by embed rebuilds.
+
+### 7c. Code: `src/core/chunkers/code.ts`
+
+- Tree-sitter WASM (`web-tree-sitter`), 36 grammars bundled as WASM assets (imports at `:48-113`).
+- `SupportedCodeLanguage` union (`:171-176`): 30 identifiers (typescript, tsx, javascript, python, ruby, go, rust, java, c_sharp, cpp, c, php, swift, kotlin, scala, lua, elixir, elm, ocaml, dart, zig, solidity, bash, css, html, vue, json, yaml, toml, sql), with a comment that all 36 grammars ship.
+- Extension detection: `detectCodeLanguage` (`:580`).
+- Entry points: `chunkCodeText` (`:629`); `chunkCodeTextFull` (`:723`, returns chunks and edges); `parseWithTimeout` (`:688`); `ChunkerTimeoutError` (`:657`).
+- Target size: `chunkSizeTokens` default 300 (`:788`); cap `maxChunkTokens` default 2000 (`:1080`).
+- Unsupported languages fall back to the recursive chunker with 300 words (`:1125`, `:1200`).
+- Versions: `CHUNKER_VERSION = 8` (`:146`); `GRAMMAR_REVISIONS` (`:157`): lua 1, typescript 2, tsx 2, javascript 2, python 2, ruby 2, elixir 1.
+- Edge extraction (symbols, calls, imports): `src/core/chunkers/edge-extractor.ts` (837 lines, **not traced**).
+
+## 8. Embedding
+
+### 8a. Defaults and dimensions
+
+- Default model `voyage:voyage-4`, 1024 dims, reranker `voyage:rerank-3-lite` (`src/core/ai/defaults.ts`, top-level constants).
+- Voyage recipe (`src/core/ai/recipes/voyage.ts`): OpenAI-compatible endpoint `https://api.voyageai.com/v1`; `max_batch_tokens: 120_000`; `chars_per_token: 1`; `safety_factor: 0.5`; `default_dims: 1024`; multimodal model `voyage-multimodal-3` only.
+- Voyage valid output dims: `[256, 512, 1024, 2048]` (`src/core/ai/dims.ts:56`). OpenAI text-embedding-3 max: small 1536, large 3072 (`dims.ts:73-74`).
+- Dims per provider are passed by `dimsProviderOptions` (`dims.ts:163`).
+
+Storage dims conflict (verified):
+- `src/schema.sql:360` declares `content_chunks.embedding vector(1536)` as a literal, and the column default model is `text-embedding-3-large` in `src/core/schema-embedded.generated.ts:365`.
+- The PGLite template uses `vector(__EMBEDDING_DIMS__)` (`scripts/build-schema.ts:410`) and replaces it at init (`:605`).
+- Runtime default is 1024. Dims mismatches are caught by `src/core/embedding-dim-check.ts`; the exact reconciliation flow was not traced **(inferred)**.
+- Image and multimodal columns are `vector(1024)` (`src/schema.sql:400` and `:403`).
+
+### 8b. Batching and truncation
+
+- Per-input char cap `EMBED_MAX_CHARS = 8000` (`src/core/ai/embed-batch-plan.ts:13`), applied by `truncateEmbedInputs` before any request.
+- Token-budget split: `splitByTokenBudget` (`:52`), `planEmbedRequests` (`:102`); default chars-per-token 4 (`:15`); default safety factor 0.8 (`:17`).
+- Item cap for recipes with no batch cap: `NO_BATCH_CAP_SUB_BATCH_ITEMS = 16` (`:33`).
+- Legacy wrapper `embedBatch` (`src/core/embedding.ts:80`) slices by `BATCH_SIZE = 100` (`:79`).
+- Gateway `embed` (`src/core/ai/gateway.ts:1625`): resolves recipe, truncates, drops empty inputs (`sendableEmbeddingInputs`), plans requests, honors `GBRAIN_EMBED_MAX_BATCH_TOKENS`, and records cost on the budget tracker.
+- Input-cap safety for strict models: `EMBED_INPUT_SAFETY = 0.6` (`src/core/embedding-input-limit.ts:34`); `resolveMaxChunkTokens` clamps to `[MIN, 2000]` (`:95`); `learnChunkCap` (`:75`) stores the cap learned from provider errors.
+- Batch-token overflow: recursive halving is the runtime net (per the voyage recipe comment).
+
+### 8c. Retries and refusal
+
+`src/core/embed-retry.ts`:
+
+| Constant | Value | Line |
+|---|---|---|
+| `MAX_RATE_LIMIT_RETRIES` | 5 | `:75` |
+| `RATE_LIMIT_FALLBACK_MS` | 60 000 | `:76` |
+| `RATE_LIMIT_PAD_MS` | 500 | `:77` |
+| `RATE_LIMIT_JITTER` | 0.3 | `:78` |
+| `RETRIABLE_GATEWAY_STATUSES` | 502, 503, 504 | `:103` |
+| `RATE_LIMIT_ATTEMPT_FLOOR_MS` | 1 s, 4 s, 10 s, 30 s, 75 s | `:151` |
+| `TRANSIENT_NET_BASE_MS` / `_MAX_MS` | 1 000 / 15 000 | `:291-292` |
+
+- SDK-level retries are disabled (`maxRetries: 0`, `:221`); this loop owns retries.
+- `embedBatchWithBackoff` (`:213`) retries rate limits and transient network errors.
+- `embedBatchKeepingUsable` (`:261`) keeps the usable vectors of a partly refused batch (null where refused). Refused chunks stay NULL for `embed --stale`.
+- Zero-norm and non-finite vectors are refused: `EMBEDDING_NORM_EPSILON = 1e-6` (`src/core/ai/embedding-guard.ts:21`); `degenerateEmbeddingReason` (`:25`); `screenEmbeddings` (`:92`); Matryoshka prefix fit (`fitMatryoshkaPrefix`, `:118`).
+
+### 8d. Write-time embedding inside import
+
+`src/core/import-file.ts:682-735`:
+- `noEmbed` is true when the caller passes it or the frontmatter has `embed_skip`.
+- `largePage = isLargePageBytes(bodyBytes) || segmented !== null`.
+- For a normal page, `embedChunks` runs before the DB transaction (`:688-735`). Pending chunks only (reused vectors skipped). Contextual-retrieval wrapper only in `title` mode.
+- On provider failure the text is still saved, chunks stay NULL, and the page is flagged deferred. The error is written to stderr (`:715-735`).
+- For a large or segmented page the write commits with NULL vectors and the stale sweep embeds later (`:683-684`, `postCommitEmbedding` at `:886` and `:924`).
+
+### 8e. Cost controls
+
+| Control | Default | Source |
+|---|---|---|
+| Sync inline cost gate | `sync.cost_gate_min_usd` = $0.50 | `src/core/sync-cost-gate.ts:340-348`, `runInlineCostGate` `:458` |
+| Per-page embed cap | `embed.max_usd_per_page` = $2; `tokenmax` posture makes it unlimited | `src/core/page-embedding-budget.ts:58-69` |
+| Spend posture | `spend.posture` config key; `tokenmax` disables caps | `src/core/config.ts:1700`; `src/core/page-spend.ts:7` |
+| Run cost cap | `embedCostCap` built from the authorization; aborts through an `AbortController` and sets a resume command | `src/core/embed-cost-cap.ts:39`, `:65` |
+| Image OCR per run | 200 images; est. $1.00; est. $0.002 per image; off unless `GBRAIN_EMBEDDING_IMAGE_OCR=true` | `src/core/import-file.ts:1734-1743`, `:1788` |
+
+Prices (`src/core/embedding-pricing.ts:31`): voyage-4 $0.06/MTok; voyage-4-large $0.12; voyage-4-lite $0.02; openai text-embedding-3-small $0.02; text-embedding-3-large $0.13. Unknown models fall back to $0.13 (`src/core/embedding.ts:137-145`). The legacy constant `EMBEDDING_COST_PER_1K_TOKENS = 0.00013` is `$0.13/MTok` (`:130`).
+
+### 8f. Stale detection and backfill
+
+- `embedStalePages` (`src/core/embed-stale.ts:292`) and `embedStaleForSource` (`:388`) are the drains. Stale means: `embedding IS NULL` (legacy) or the stored signature or `embedded_text_hash` does not match the current model, dims and chunk text (`:112`, `:178-183`).
+- CLI: `gbrain embed` flags (`src/commands/embed.ts`): `--stale`, `--slugs`, `--all`, `--batch-size` (capped at 10 000), `--pace`, `--priority`, `--catch-up`, `--dry-run`, `--yes`, `--images`, `--facts`, `--held`, `--force`, `--include-null-signature`, `--background`.
+- Background jobs: `submitEmbedBackfill` (`src/core/embed-backfill-submit.ts:177`); keyless path `keylessEmbedBackfill` (`:155`).
+- Sync embed pass: `resolveSyncEmbedBackfill` (`src/core/sync-embed-backfill.ts:149`).
+- Pass to a provider only what is missing: the reuse path (`import-chunk-reuse.ts`, `reuseStoredChunkVectors`) keeps identical rows and their vectors (import-file.ts ~`:770-800`).
+
+### 8g. Multimodal and images
+
+- Image import: `importImageFile` (`import-file.ts:1877`); supported extensions `png, jpg, jpeg, gif, webp, heic, heif, avif` (`:1512`); `MAX_IMAGE_BYTES = 20 MiB` (`:1515`).
+- Multimodal call: `embedMultimodal` (`src/core/ai/gateway.ts:1919`), gated by `multimodal_models` on the recipe; `multimodalEmbeddingModel` (`src/core/ai/multimodal-model.ts:14`).
+- Columns: `embedding_image vector(1024)`, `embedding_multimodal vector(1024)` (`src/schema.sql:400`, `:403`).
+- OCR text path (optional) produces chunk text from images when enabled.
+
+## 9. Storage and the DB dependencies on the write path
+
+Table `content_chunks` (`src/core/schema-embedded.generated.ts:358`; PGLite template `src/core/pglite-schema.generated.ts:180`): `id`, `page_id` (FK, cascade), `chunk_index`, `chunk_text`, `chunk_source` (default `compiled_truth`; the other source is `timeline`), `embedding`, `model`, `token_count`, `embedded_at`, `embedded_text_hash`, `embedding_input_hash`, `created_at`, `language`, `symbol_name`, `symbol_type`, plus later columns for segmented pages (`occurrence_id`, `local_ordinal`, `raw_byte_start/end`, `body_generation`), projection spans, and `embedding_pending_since`.
+
+Triggers and locks the write path depends on (verified by reading `src/schema.sql`):
+
+| Object | Event | Line | Effect |
+|---|---|---|---|
+| `bump_page_generation_trg` | BEFORE INSERT/UPDATE on `pages` | `:209` | Bumps page generation (cache gate). |
+| `trg_pages_search_vector` | BEFORE INSERT/UPDATE OF title, timeline on `pages` | `:1231` | Maintains `pages.search_vector` (tsvector). |
+| `chunk_search_vector_trigger` | BEFORE INSERT/UPDATE OF chunk_text, doc_comment, symbol_name_qualified on `content_chunks` | `:455` | Builds the chunk tsvector (`to_tsvector('english', ...)`, weights at `:444-447`). |
+| `pages_knowledge_revision` | BEFORE UPDATE on `pages` | `:1935` | Advances the revision counter. |
+| `tags_knowledge_revision` | AFTER INSERT/UPDATE/DELETE on `tags` | `:1960` | Revision on tag change; checks `pg_catalog.row_security_active`. |
+| `pages_projection_queue` | AFTER INSERT/UPDATE/DELETE on `pages` | `:2765` | Queues projection rebuilds. |
+| Derivation scope triggers | on `page_body_manifest`, `pages` (deleted_at) | `:2337-2343` | Retire derivations on page change. |
+| `managed_writer_guard` | BEFORE INSERT/UPDATE/DELETE on managed tables | `:2635` | Blocks non-managed writers. |
+| `facts_refuse_purged` | BEFORE INSERT/UPDATE on `facts` | `src/core/facts/purge-schema.ts:177` | Refuses purged facts. |
+| `minion_job_notify` | AFTER INSERT/UPDATE OF status on `minion_jobs` | `:1824` | NOTIFY for job wakeups (used by background embed jobs **(inferred)**). |
+
+Locks and transactions:
+- `importFromContent` opens one transaction covering version snapshot, `putPage`, tags, chunk replacement, and `beforeCommit` (`import-file.ts:242` doc; `:549-550`; `:744-884`).
+- Sources are locked `FOR SHARE` during embedding invalidation (`src/core/embedding-invalidation.ts:65-66`).
+- Chunk-vector index writes are budgeted: `CHUNK_VECTOR_WRITE_BUDGET = 5` (`src/core/page-state/chunk-moves.ts:24`); over budget, the import commits the page pending and finishes after commit.
+- Markdown read-modify-write uses file locks, not DB locks: `~/.gbrain/page-locks/<sha256-of-slug>.lock` (`src/core/page-lock.ts:7`). This is a separate mechanism from the DB.
+- Not verified: whether `pipelined(tx, ...)` (`import-file.ts:~790`) issues statements in parallel within one transaction.
+
+## Rust engine implications
+
+What must be preserved exactly:
+1. Content hash bytes. `contentHash` hashes a JSON string with a fixed key order and sorted tags after stripping ephemeral frontmatter keys. Any change in serialization, key order, or the ephemeral-key list makes every page look changed and triggers re-embed. Keep the parity fixture from `test/content-hash-parity-3694.test.ts` and port it.
+2. Chunk boundaries. Word counting (CJK-aware), the delimiter ladder, greedy merge, overlap of 50 words, and the 6000-char cap decide embedding inputs. Keep the same version integers (4 markdown, 5 segmented, 8 code) and bump them on any boundary change.
+3. `embedded_text_hash = md5(chunk_text)` and `embedding_input_hash` digests: stored values must still validate against vectors produced by the TS version if the Rust build reads the same data.
+4. Timeline sentinel rules (marker, `--- timeline ---`, bare `---` plus heading, fence-aware).
+5. Slug folding (NFD, niqqud strip, CJK keep, hyphen fold) so the same file yields the same page in both implementations.
+6. Hold codes and reasons (strings are part of `--json` output and the agent contract).
+7. Size thresholds: 24 MiB page max, 5,000,000 code max, 1 MiB inline, 512 KiB demote.
+
+What can be simplified:
+- Collapse the many per-engine variants (PGLite vs Postgres DDL, dims templating) into one schema generated from a single dim setting.
+- Replace `vector(1536)` literal vs 1024 default conflict with one source of truth.
+- Replace DB triggers with explicit application code in the same write transaction (FTS vectors, revision counters, projection queue, derivation retirement). The trigger set above is the complete list the write path relies on.
+- Drop RLS checks (`row_security_active`) in the embedded case **(inferred: no multi-tenant access inside one local process)**.
+- Replace `FOR SHARE` source locks with a single-writer lock on the brain file.
+- Replace LISTEN/NOTIFY wakeups (`minion_job_notify`) with an in-process channel.
+- Replace the per-page file locks with an in-process mutex plus a file lock only where the markdown file itself is written.
+
+Postgres feature dependencies on the write path:
+
+| Feature | Used for | Rust replacement |
+|---|---|---|
+| `vector(N)` + HNSW/IVFFlat | content_chunks.embedding, image, multimodal | sqlite-vec, usearch, or a flat f32 store with SIMD scan |
+| `tsvector` + `to_tsvector('english')` | search_vector on pages and chunks | FTS5 or tantivy, updated in the write transaction |
+| `md5()` | embedded_text_hash | any md5 crate, or switch to sha256 with a one-time backfill |
+| Triggers (listed above) | derived columns, revisions, queue | explicit writes in one transaction |
+| `FOR SHARE` / row locks | source locks during invalidation | serialized writer |
+| `SERIAL`, `TIMESTAMPTZ` | ids and timestamps | integer ids; RFC 3339 strings |
+| LISTEN/NOTIFY | job wakeup | channel |
+| `SKIP LOCKED` queues | background embed jobs **(inferred from minion queue design; not verified in this map)** | single-process queue |
+
+Risks:
+1. Host-dependent tokenization. `estimateEmbedTokens` switches on `cl100kAvailable()` (`token-estimate.ts:48`). If the Rust build cannot match the exact path, chunk token counts and therefore split points can differ between machines. Pin one estimator.
+2. Timing-dependent fence output. Per-fence (2 s) and per-page (5 s) parse budgets (`markdown-chunks.ts:57-59`) can change chunk output on a slow machine. Decide whether the Rust build uses a deterministic step budget instead.
+3. Provider-specific dims. Voyage accepts only 256/512/1024/2048; the schema must be sized from the chosen model at init, not a literal.
+4. Batch-token ceilings and retries: 120K tokens per Voyage batch, five rate-limit retries with fixed floors. Reimplementing this without the same floors changes behavior under load.
+5. Price table drift: the voyage recipe's display price ($0.12, labeled for voyage-4-large) and the pricing table ($0.06 for voyage-4) disagree. Keep one table.
+6. Keep provider calls outside the DB transaction. The TS small-page path embeds before the transaction (`import-file.ts:688-735`) and large pages embed after commit (`:886`, `:924`). A Rust port that embeds inside the write transaction would hold the write lock across network calls.
+
+## Open questions
+
+1. How the persistence coordinator (`src/core/persistence/page-mutations.ts:234`, `page-batch.ts:337`) drives `importFromContent` with `prepare` and `coordinated`. The full ordering of prepare, commit and read-back was not traced.
+2. `src/core/page-body/segment-chunks.ts` (`headingsLead`, `boundaryCuts`, segment windows) was referenced but not read. The Rust port needs it for segmented pages.
+3. `contentHashLegacy` (`src/core/utils.ts:158`): which stored rows still carry the legacy hash, and whether a Rust build must read or write it.
+4. `src/core/chunkers/edge-extractor.ts` (837 lines) and `symbol-resolver.ts` define code edges. Not traced.
+5. `src/core/embedding-dim-check.ts` reconciliation: how a 1536 literal in `schema.sql` becomes the configured width at Postgres init. Not traced.
+6. `cl100kAvailable` (`token-estimate.ts:48`): which path runs on a stock install, and whether the heuristic path is ever used in production.
+7. The `pipelined(tx, ...)` helper (`src/core/page-state/transactions.ts`): does it run statements concurrently inside one transaction?
+8. The embed pass in `sync` and the sync-lock interplay (`src/core/sync-lock.ts`) were not read.
+9. Video and audio ingestion (`src/core/transcription.ts`, 25 MB cap) is out of this map's scope; only images were traced.
diff --git a/docs/designs/rust-engine/research/05-cli-mcp-surface.md b/docs/designs/rust-engine/research/05-cli-mcp-surface.md
new file mode 100644
index 0000000000..aab2998fdf
--- /dev/null
+++ b/docs/designs/rust-engine/research/05-cli-mcp-surface.md
@@ -0,0 +1,262 @@
+# 05. Agent-facing surface: operations, CLI, MCP
+
+Line numbers refer to gbrain 36bd05806a.
+
+Reference: TypeScript gbrain v0.60.733.0 at `garrytan/gbrain` (commit 36bd05806a), read only. Eval repo at `garrytan/gbrain-evals` (commit 9ecc5b20).
+
+**Method.** The reference checkout has no `node_modules`, so `src/core/operations.ts` cannot be imported. The 204-entry manifest was instead read from a copy of the handler-free `src/core/operation-manifest.generated.ts` in /tmp and parsed with bun. The CLI command table was imported directly (its imports are type-only). Engine calls were mapped with a regex over `src/core/ops/*.ts` and `src/core/verbs.ts`: direct `engine.X(` calls inside each op's literal body. Helper-delegated calls are not followed, so some ops show no direct engine call. Items marked (inferred) were not confirmed by running code.
+
+## 1. Headline numbers (verified)
+
+| Item | Value | Where |
+|---|---|---|
+| Operations | 204 | `operation-manifest.generated.ts` |
+| Scope split: read / write / admin / agent / sources_admin | 92 / 60 / 48 / 2 / 2 | `scope` field |
+| Mutating / idempotent | 90 / 169 | |
+| `localOnly` / `cliOnly` / `verb` | 25 / 18 / 7 | |
+| Ops with `cliHints` / with a CLI name (`cliHints.name`) | 121 / 115 | |
+| Named params across all ops | 930 | |
+| Area groups | 30 (29 named, plus 5 ops with no area) | `operation-load.ts:30` OP_AREAS |
+| Output redaction | 112 `no_stored_text`, 53 `retrieval`, 39 object form (exempt or `localVerbatim`) | `ops/contract.ts:820` |
+| CLI command records | 132 (46 pre-connect, 12 pre-connect-own-engine, 74 post-connect) | `src/cli/command-table.ts:148` |
+| CLI records with thin-client refuse / route-then-refuse | 43 / 7 | `command-table.ts:483` |
+| CLI records with a `--json` document contract | 15 (plus `bench` and `eval export/replay/gate` as NDJSON) | `json` field |
+| Error registry entries | about 790 | `src/core/error-registry.ts` |
+| Memory verbs / protocol_version | 7 / 1 | `src/core/verbs.ts:35,41` |
+| Verb conformance fixture cases | 24 | `test/fixtures/memory-verbs/cases.json` |
+| Allowed OAuth scopes | 10 | `src/core/scope.ts:27` |
+
+## 2. The operation contract
+
+- Each op is a plain object of type `Operation` (`src/core/ops/contract.ts:826`) with `name`, `description`, `params` (a `ParamDef` map), `callShape`, `handler(ctx, params)`, `outputRedaction`, and optional `mutating`, `idempotent`, `scope`, `requiredScopes`, `localOnly`, `cliOnly: {argv}`, `publishGateKey`, `verb`, `area`, `agentCallable`, `annotations`, `cliHints`, `writeInference`.
+- `src/core/operations.ts:146` builds the canonical `operations` array by spreading per-domain arrays from `src/core/ops/*.ts` in a fixed order. The order is contractual because `docs/TOOL_CATALOG.md` is generated from it. `finalizeOperation` runs over the array at `:245`.
+- `operation-manifest.generated.ts` is the same list minus handlers, emitted by `scripts/build-operation-manifest.ts`. The CLI and stdio MCP read it so they never load the handler graph. `test/operation-manifest.test.ts` pins freshness and equality with the live registry.
+- Output redaction is applied at registration. `retrieval` ops get the canonical secret scanner over the whole response. `no_stored_text` ops return no page, chunk, fact, take or transcript text. `{exempt}` ops return stored text on purpose and must give a reason.
+
+## 3. Inventory by area (all 204)
+
+Legend after each name: scope `r` read, `w` write, `a` admin, `g` agent, `s` sources_admin. Flags: `L` localOnly, `C` cliOnly, `V` verb. Area names are not a contract (`contract.ts:892`, `operation-load.ts:22`), so a Rust port may regroup them.
+
+| Area (count) | Operations |
+|---|---|
+| pages (31) | get_page:r, put_page:w, delete_page:w, list_pages:r, restore_page:w, purge_deleted_pages:a+LC, capture:w, fetch:r, find_pages:r, edit_page:w, append_page:w, put_pages:w, begin_page_upload:w, upload_page_part:w, get_page_upload:w, commit_page_upload:w, abort_page_upload:w, get_write_request:w, list_write_requests:w, list_write_conflicts:r, cancel_write_request:w, get_versions:r, revert_version:w, promote_guest_note:w, put_raw_data:w, get_raw_data:r, resolve_slugs:r, get_chunks:r, whois:r, list_page_purges:a+C, unpurge_page:a+C |
+| jobs (20) | submit_job:a, get_job:a, wait_job:a, list_jobs:a, cancel_job:a, retry_job:a, get_job_progress:a, pause_job:a, resume_job:a, replay_job:a, send_job_message:a, submit_agent:g, get_agent_job:g, get_job_stats:a, watch_job:a, watch_write_request:w, watch_cron:a, accept_wakeshift_terms:w, list_watches:w, unwatch:w |
+| skills (15) | list_skills:r, get_skill:r, list_brain_skillpack:r, get_skill_asset:r, put_skill:w, delete_skill:w, set_skill_policy:a, get_skill_policy:a, get_skill_retention:a+LC, prune_skill_revisions:a+LC, retain_skill_revision:a+LC, import_skill_proposal:a+LC, join_brain:r, sync_brain_skills:r, leave_brain:r |
+| admin (13) | get_stats:a, get_health:a, run_doctor:a, get_brain_health:r, quarantine_list:a, get_write_attribution:a, get_status_snapshot:a, get_usage:a, code_traversal_cache_clear:a+L, migrate_embeddings:a+LC, run_onboard:a, run_skillopt:a, mute_notice:w |
+| takes (11) | takes_list:r, takes_search:r, think:r, takes_scorecard:r, takes_calibration:r, takes_add:w, takes_update:w, takes_resolve:w, takes_supersede:w, takes_remove:w+L, takes_rebuild:w+L |
+| search (10) | search:r, query:r, assemble_evidence:r, search_stats:a, search_modes:r, search_tune:a, cache_stats:a, search_exact:r, rate_answer:w, search_by_image:r |
+| links (9) | add_link:w, remove_link:w, get_links:r, get_backlinks:r, list_link_sources:r, traverse_graph:r, wanted_pages:r, find_orphans:r, rank_entities:r |
+| schema (9) | get_active_schema_pack:r, list_schema_packs:r, schema_stats:r, schema_lint:r, schema_graph:r, schema_explain_type:r, schema_review_orphans:r, schema_apply_mutations:a, reload_schema_pack:a |
+| insights (8) | get_calibration_profile:r, get_recent_salience:r, find_anomalies:r, get_recent_transcripts:r+LC, volunteer_context:r, find_contradictions:r, find_experts:r, find_trajectory:r |
+| memory-verbs (7) | remember:w+V, entity:r+V, synthesize:r+V, forget:w+V, recall:r+V, context_pack:r+V, delta:r+V |
+| memory (6) | confirm_memory:w, extract_facts:w, forget_fact:w, memory_recall:r, memory_write:w, memory_propose:w |
+| chronicle (6) | chronicle_day:r, chronicle_on_this_day:r, chronicle_since:r, chronicle_last_seen:r, volunteer_chronicle:r, chronicle_backfill:a+L |
+| entities (6) | extract_entities:w, extraction_pending:r, extraction_review:w+LC, entity_identity_link:w+L, entity_identity_unlink:w+L, entity_identity_list:r |
+| code (6) | code_callers:r, code_callees:r, code_def:r, code_refs:r, code_blast:r, code_flow:r |
+| files (5) | file_list:a+L, file_upload:a+L, file_url:a+L, file_register:a+LC, file_verify:a+LC |
+| (no area, 5) | storage_register:w+LC, storage_update:w+LC, sources_inspect:r+LC, connectors_status:r+LC, connector_sync:w+LC |
+| sources (5) | sources_add:s, sources_list:r, sources_remove:s, sources_status:r, sources_resolve_path:r |
+| questions (5) | questions_pin:w, questions_list:r, questions_status:r, questions_refresh:w, questions_unpin:w |
+| ontology (4) | ontology_get:r, ontology_propose:w, ontology_dimensions:r, ontology_conflicts:r |
+| loops (4) | open_loops:r, loops_close:w, loops_mute:w, loops_unmute:w |
+| tags (3) | add_tag:w, remove_tag:w, get_tags:r |
+| storage (3) | storage_find:r, storage_get:r, storage_list:r |
+| memory-settings (3) | get_memory_settings:r, set_memory_writeback:a, memory_conversation_mode:w |
+| timeline (2) | add_timeline_entry:w, get_timeline:r |
+| identity (2) | get_brain_identity:r, whoami:r |
+| ingest (2) | log_ingest:w, get_ingest_log:r |
+| single entries | advisor:r (advisor), sync_brain:a+L (sync), request_tools:r (discovery), purge_fact:a+C (facts) |
+
+Local-only ops (25): purge_deleted_pages, get_skill_retention, prune_skill_revisions, retain_skill_revision, import_skill_proposal, sync_brain, file_list, file_upload, file_url, file_register, file_verify, storage_register, storage_update, takes_remove, takes_rebuild, sources_inspect, get_recent_transcripts, connectors_status, connector_sync, chronicle_backfill, extraction_review, entity_identity_link, entity_identity_unlink, code_traversal_cache_clear, migrate_embeddings.
+
+CLI-only ops (18) have `cliOnly.argv`, for example `purge_deleted_pages` maps to `gbrain pages purge-deleted --dry-run --json`. Over MCP they return `trusted_local_only` (`cliOnlyRefusal`, `src/core/ops/callable.ts`).
+
+## 4. The roughly 30 most-used operations
+
+The repo has no usage histogram; the `derive-starter-ops.ts` script needs production `mcp_request_log` data. The ranking below is therefore inferred from the starter tier, which the code calls the daily-driver set (`src/mcp/surface.ts:93`). The starter set has 41 names by hand tally. The MEMORY_VERBS doc says 40. Dropping the skill-catalog and brain-membership ops leaves the 32 below.
+
+| Op | Scope | Engine path (direct calls, else delegate) |
+|---|---|---|
+| remember | w | `verbs.ts:229` `submitRememberMutation` then `persistence/memory-mutations.ts` then `persistence/journal.ts:289` `admitWrite` (inferred from the chain) |
+| entity | r | `verbs.ts:256`; name lookup helpers, no direct engine calls |
+| synthesize | r | `verbs.ts:348`; LLM call, cost block; no direct engine calls |
+| forget | w | `verbs.ts:484` then `submitForgetMutation` (`:381`); rewrites each page that carries the claim |
+| recall | r | `ops/facts.ts:298`: `listFactsSince`, `listFactsByEntity`, `listFactsBySession`, `listSupersessions`, `countUnconsolidatedFacts`; search arm reuses the search pipeline |
+| context_pack | r | `ops/facts.ts:714`; world-only facts unless trusted local |
+| delta | r | `ops/facts.ts:955` |
+| query | r | `ops/search.ts:881`: `getConfig`, `searchVector` (hybrid) |
+| search | r | `ops/search.ts:696`: `getConfig`, `searchKeyword` |
+| get_page | r | `ops/pages.ts:98`: `readPageSnapshot`, `transaction`, `getPage`, `getTimeline` |
+| list_pages | r | `ops/pages.ts:515`: `listPages` |
+| get_backlinks | r | `ops/links.ts:445` (helper) |
+| traverse_graph | r | `ops/links.ts:567`: `traverseGraph`, `traversePathsDetailed` |
+| list_link_sources | r | `ops/links.ts:473`: `listLinkSources` |
+| resolve_slugs | r | `ops/chunks.ts:21`: `resolveSlugs` |
+| get_ingest_log | r | `ops/ingest-log.ts:60`: `getIngestLog` |
+| put_page | w | `ops/pages.ts:345`: `readPageSnapshot`, `transaction`, plus the persistence write journal (inferred from imports) |
+| add_timeline_entry | w | `ops/timeline.ts:45` (helper) |
+| get_recent_salience | r | `ops/salience.ts:25`: `getRecentSalience` |
+| find_anomalies | r | `ops/salience.ts:69`: `findAnomalies` |
+| whoami | r | `ops/sources.ts:35`; reports identity per transport |
+| request_tools | r | `ops/request-tools.ts:159`: `executeRaw` (two calls); the only discovery meta-op, agent-callable |
+| capture | w | `ops/pages.ts:704` (hidden alias of a page write; starter list) |
+| edit_page | w | `ops/page-edit.ts:11` then `persistence/page-edit.ts`, `persistence/page-mutations.ts` |
+| submit_agent | g | `ops/jobs.ts:364`: `getConfig`; Minions queue |
+| get_agent_job | g | `ops/jobs.ts:539` |
+| cancel_job | a | `ops/jobs.ts:750` |
+| get_write_request | w | `ops/persistence.ts:229` |
+| list_write_requests | w | `ops/persistence.ts:258` |
+| cancel_write_request | w | `ops/persistence.ts:325` |
+| mute_notice | w | `ops/notices.ts:15` |
+| memory_conversation_mode | w | `ops/memory-settings.ts:204` |
+
+## 5. The seven memory verbs (MEMORY_VERBS v1)
+
+Source of truth: `docs/protocol/MEMORY_VERBS_v1.md` (1,311 lines), `src/core/verbs.ts`. The first four (`remember`, `entity`, `synthesize`, `forget`) are in `verbs.ts` and spread first into the operations array (`operations.ts:146`). `recall`, `context_pack` and `delta` are in `ops/facts.ts`.
+
+| Verb | Class | Params (* required) | Notes |
+|---|---|---|---|
+| recall | read | query, question (2,000 char cap), entity, budget_tokens, budget_policy (facts_first or query_first), source_id, source_ids, since, session_id, include_expired, supersessions, limit (per arm), grep, include_pending, return_unit, return_window, min_trust, max_chars | Facts arm plus search arm; `question` ranks facts by cosine plus term share; estimated tokens `ceil(len/4)` |
+| remember | write | fact, provenance (required, else `provenance_required`), ttl, entity, kind, visibility, valid_from, request_id, items (up to 20), content_origin, expected_revision, force, share, replaces | Returns a write receipt; `write_pending` maps to exit 10 |
+| entity | read | name or names (1 to 50), source_id, prefer_source_id, variants | Never errors on a miss (`found: false`); CI-gated p99 under 100 ms on 20K pages |
+| synthesize | read | question*, since, until | LLM call; `unavailable` error when no LLM is configured; quote check adds `QUOTE_NOT_IN_EVIDENCE` |
+| forget | write | id* (opaque fact_id string), reason, request_id, semantic_review | Idempotent (`expired: false` on repeat); `claim_linked` refusal when an unlinked fact shares a claim; facts expire, never delete |
+| context_pack | read | entities, budget_tokens, since, session_id, include_private, min_trust, include_quarantined, counterparty, intent, source_id, entity_refs, prefer_source_id | Zero LLM; fan-out capped at 8 entities; world-only for remote callers |
+| delta | read | since, since_slug, cursor, entities, budget_tokens, session_id, include_private, min_trust, beliefs | O(changes); session cursors expire after 7 idle days |
+
+Every verb response carries `protocol_version: 1` (`verbs.ts:230` and the others). `RESPONSE_SCHEMAS` (`verbs.ts:604`) and `ERROR_SCHEMA` (`verbs.ts:1105`) are the machine-readable shapes. Error envelope: `{error, code, message, suggestion, detail?, protocol_version}`. Frozen codes: `invalid_params`, `provenance_required`, `not_found`, `scope_denied`, `unavailable`, `budget_unsatisfiable` (reserved, never returned), `internal`. Versioning rule: names and semantics are frozen; new optional params and fields are additive; a breaking change means a new document.
+
+Read verbs redact credential-shaped text for remote callers (`ctx.remote !== false`). Remote callers see only `visibility = world` facts, except a caller bound to the brain owner, which also reads private facts (`worldOnlyFacts`, `src/core/search/private-visibility.ts`); source grants and member access still apply to both. The trusted local CLI sees stored text.
+
+## 6. Surface modes
+
+| Mode | Membership | Source |
+|---|---|---|
+| `verbs` | exactly ops with `verb === true` (7) | `surface.ts:242-247` |
+| `starter` | `STARTER_OPS` (41 by tally) | `surface.ts:93` |
+| `full` | all 204; default for bare `serve` | `surface.ts` header |
+
+Resolution for stdio: `GBRAIN_SURFACE` env, then `--surface` flag, then config `mcp_surface`, then `full` (`surface.ts:209-230`). `serve --http` ignores `GBRAIN_SURFACE` (`src/commands/serve.ts:294-305`). On HTTP the surface is a ceiling: each request resolves `min(ceiling, client row ?? default)`, recomputed per request (MEMORY_VERBS doc). Enforcement is fail-closed through one predicate, `isCallable` (`src/core/ops/callable.ts:25`), used by both tools/list and dispatch. A hidden op returns `unknown_tool`, so a guessed name does not leak.
+
+## 7. OperationContext and the trust boundary
+
+Key fields (`src/core/ops/contract.ts:477-826`):
+
+| Field | Meaning |
+|---|---|
+| `remote` | Required boolean (`:502`). Fail closed: only strict `false` is trusted. CLI sets `false` (`src/cli/main.ts:1456`); stdio and HTTP set `true` |
+| `transport` | `'stdio'` or `'http'`. Locality axis only; `localOnly` ops run on stdio and are denied on HTTP. Trust must not key off it |
+| `auth` | `AuthInfo`: `clientId`, `scopes`, `allowedSources`, `sourceId`, `boundTools`, `member`, `attest`, `readsUnscoped` |
+| `sourceId` | Required string; defaults to `'default'` |
+| `localFederatedSourceIds` | Federated read set; set only by trusted builders (CLI non-explicit tier, stdio without `GBRAIN_SOURCE`, legacy HTTP bearer with no grant) |
+| `explicitReadBinding` | Stdio `GBRAIN_SOURCE` or `.gbrain-source` pin; admits an explicit `source_id` only |
+| `surfaceCeiling`, `stdioSurface`, `isCallable` | Surface state for `request_tools` and `whoami` |
+| `takesHoldersAllowList` | Per-token holder filter on takes; default `['world']` for MCP tokens without a row |
+| `brainId`, `admissionOrigin`, `sessionId`, `writeWaitMs`, `deferEmbeds` | Routing, attribution, write wait; `deferEmbeds` is server-side only |
+
+`sourceScopeOpts` (`src/core/ops/context.ts:646-669`) is the one read-scope ladder: (1) non-empty `auth.allowedSources` gives `{sourceIds}`; (2) `sourceId === '__all__'` gives `{}` only for `remote === false`; (3) a scalar `sourceId` gives `{sourceId}`; (4) remote with a grant and no source throws `permission_denied`; (5) otherwise `{}`. Sentinels: `ALL_SOURCES = '__all__'` and `NO_SOURCES = '__none__'` (`src/core/source-id.ts:45,54`). The comment says not to simplify the `__all__` branch.
+
+Scope hierarchy (`src/core/scope.ts:162-173`): `admin` implies `write`, `read`, `sources_admin`, `users_admin`; `write` implies `read`; `agent`, `skill_editor`, `skill_publisher`, `skills_member_self`, `memory_confirm` stand alone. `operationScopesAllowed` (`:195`) also honours `agentCallable` for `request_tools`. Local CLI bypasses OAuth scope checks (`contract.ts:859`).
+
+Dispatch (`src/mcp/dispatch.ts:1007`, `dispatchToolCall`): normalise optional params, strip the room declaration, then for remote calls resolve the attested actor and audience, run the requester-scope gate (GST-363), resolve access, call `dispatchResolvedCall`, then shape the result and enforce the frame cap. `unknownToolEnvelope` is at `:639`, `errorResult` at `:883`.
+
+## 8. The write path
+
+Writes do not go straight to the engine. They are admitted as write-request rows by `admitWrite` (`src/core/persistence/journal.ts:289`), with states `queued`, `running`, `recovering`, `committed`, `conflict`, `failed`, `cancelled` (`persistence/types.ts:2-4`; `model.ts:7` adds `deferred` for `RequestState`). A receipt carries `request_id`, and the caller polls with `get_write_request`. Idempotency comes from `request_id` plus `expected_revision`. The journal's SQL includes `persistence_counters`, `SELECT ... FOR UPDATE` (`LOCK_COUNTERS_SQL`), `unnest($1::text[]) WITH ORDINALITY` and `ON CONFLICT` (`journal.ts:241-243`). The Rust port must reproduce these semantics, not the SQL.
+
+## 9. CLI
+
+- Entry: `src/cli.ts` answers `--help`, `--version` and the hook lanes without loading the dispatcher, then loads `src/cli/main.ts` (2,880 lines, `runCli`).
+- Command table: `CLI_COMMANDS` at `src/cli/command-table.ts:148`, 132 records. `CLI_ONLY` (`:459`) is every record name. `THIN_CLIENT_REFUSED_COMMANDS` (`:483`) has 47 entries. Phase tells the dispatcher whether to connect the engine first.
+- Ops reach the CLI through `cliHints.name` (115 ops; 121 ops carry a `cliHints` object) via `src/cli/op-manifest.ts`. Hidden ops are excluded from the CLI map.
+- `makeContext` (`src/cli/main.ts:1360`) builds the trusted local context: `remote: false`, `admissionOrigin: 'interactive'`.
+- JSON contract: a command with `json: 'document'` writes exactly one document to stdout; everything else goes to stderr (`src/cli/json-guard.ts`). Records with `jsonSubcommands` (eval) use NDJSON. A non-zero exit without a document gets a fallback `{error: "command_failed", code, message, suggestion, exit_code, contract_version: 1}`. A signal writes `error: "interrupted"`.
+- Errors: `writeCliError` (`src/cli/cli-error.ts:53`) and `renderCliError` (`src/core/agent-output.ts:868`). Human form is `Error [code]: message`, then `Fix:`, then `Why:`.
+
+Exit codes (`src/core/exit-codes.ts:18-112`, plus registry entries):
+
+| Exit | Meaning | Constant / source |
+|---|---|---|
+| 0 | ok | `OK_EXIT_CODE` |
+| 1 | failed; class and `retryable` in JSON | `FAILED_EXIT_CODE` |
+| 2 | usage or invalid input (`invalid_params`, `unknown_flag`) | `USAGE_EXIT_CODE` |
+| 3 | `confirmation_required`; nothing ran | `CONFIRMATION_REQUIRED_EXIT_CODE` |
+| 10 | write accepted, still pending (`write_pending`) | `PENDING_WRITE_EXIT_CODE` |
+| 11 | resumable budget stop | `BUDGET_STOP_EXIT_CODE` |
+| 12 | no results (opt-in via `GBRAIN_FAIL_ON_EMPTY=1`) | `NO_RESULTS_EXIT_CODE` |
+| 13 | harness wired, verify pending | `HARNESS_PENDING_VERIFY_EXIT_CODE` |
+| 14 | harness cleanup pending | `HARNESS_CLEANUP_PENDING_EXIT_CODE` |
+| 15 | no edition in force for `as_of` | `VALID_TIME_NOT_IN_FORCE_EXIT_CODE` |
+| 16 | host upgrade required | `HOST_UPGRADE_REQUIRED_EXIT_CODE` |
+| 17 / 18 | doctor alert: act / unknown | `DOCTOR_ALERT_ACT_EXIT_CODE`, `DOCTOR_ALERT_UNKNOWN_EXIT_CODE` |
+| 69 | serve exited unhealthy (opt-in) | `SERVE_UNHEALTHY_EXIT_CODE` |
+| 75 | migration lock held | `MIGRATIONS_RUNNING_EXIT_CODE` |
+| 124 | deadline elapsed | `TIMEOUT_EXIT_CODE` |
+| 130 | interrupted (SIGINT) | `INTERRUPTED_EXIT_CODE` |
+
+Registry codes default to exit 1 unless an entry sets `exit`. Of the 45 `consent`-class entries, 12 set exit 3 explicitly; the rest exit 1 unless they set another value, so exit 3 is not a class-wide rule. The contract's legacy exception: `mcp expose` and `google` still exit 2 for confirmation.
+
+Error envelope (`docs/protocol/AGENT_OPERATOR_v1.md:598-620`): `error` (frozen legacy value), `code` (canonical), optional `reason`, `message`, `suggestion`, `why`, `fix` (argv, command, mcp call, consent, actor, next, verify), `docs`, `docs_cmd`, `class` (`caller`, `consent`, `retryable`, `unavailable`, `server`, `host_only`), `retryable`, `notices`, `contract_version: 1`. `fix.next` is one of `run`, `ask_user`, `tell_user_to_run`, `wait`, `report`, decided by the table at `AGENT_OPERATOR_v1.md:713`.
+
+## 10. MCP server and transports
+
+- stdio: `startMcpServer` (`src/mcp/server.ts:339`) uses the MCP SDK's `ListTools` and `CallTool` handlers (`:443`, `:460`). Requests come in with `remote: true`, `transport: 'stdio'` (`:496-500`). Message cap is 64 MiB (`src/mcp/stdio-lifecycle.ts:26`). `request_tools` can widen the session surface.
+- Result shape: `ToolResult` (`src/mcp/dispatch.ts:163`) is `{content: [{type:'text', text}], isError?, _meta?, structuredContent?}`. Notices ride extra text blocks with a fixed prefix and `_meta.gbrain_notices`.
+- HTTP: `startHttpTransport` (`src/mcp/http-transport.ts:212`). Routes: `/health` (`:366`), `/mcp` (`:356` onward). Legacy bearer tokens are matched by SHA-256 hex digest (`:76-78`). Body cap is 1 MiB (`:69`, override `GBRAIN_HTTP_MAX_BODY_BYTES`). The OAuth path uses the SDK's 4 MiB limit.
+- Rate limits (`src/mcp/rate-limit.ts:148-155`): per-IP 30 per minute, per-token 60 per minute, LRU of 10,000 keys. Each is overridable by env.
+- OAuth 2.1 (`src/commands/serve-http-oauth.ts`, `src/core/oauth-provider.ts`): the SDK's `mcpAuthRouter` provides `/authorize`, `/token`, `/register`, `/revoke` (`:184`). Custom handlers add `client_credentials` before the router, `/.well-known/oauth-authorization-server` (`:190`), `/.well-known/oauth-protected-resource` (`:216`) and `/.well-known/gbrain` (`:223`). PKCE S256 is validated by the provider (`oauth-provider.ts:573`). Client auth methods are `client_secret_post`, `client_secret_basic`, `none`. Default access-token TTL is 3,600 s and refresh TTL 30 days (`oauth-provider.ts:232-235`). Hard cap `TOKEN_TTL_MAX_SECONDS = 7,776,000` (`src/core/grants/model.ts:20`). DCR TTL clamps to at least 300 s (`oauth-provider.ts:285`). `client_credentials` via DCR is refused unless the operator allows it (`:382`).
+- Serve flags: `--http`, `--port` (`src/commands/serve.ts:368`), `--token-ttl` (`:371`), `--surface`, `--advertise`, `--access read-only` (stdio only), `--stdio-member`.
+
+## 11. Contract guards and conformance oracles
+
+| Asset | What it pins | Reusable by Rust? |
+|---|---|---|
+| `test/operation-manifest.test.ts` | manifest freshness, equality with live registry, handler-free startup | Yes as data: export the manifest as JSON and diff it |
+| `test/operations-*.test.ts` (allow-list, trust-boundary, source-isolation matrix, coverage ledger, descriptions) | authorization and isolation per op | Yes, as black-box cases over the wire |
+| `test/mcp-tool-list-snapshot.test.ts`, `test/mcp-surface.test.ts` | tools/list per surface | Yes: byte or set compare |
+| `test/memory-verbs-conformance.test.ts` (896 lines) with `test/fixtures/memory-verbs/cases.json` (24 cases) | verb shape, enums, budget arithmetic, idempotent forget, private facts absent for remote | Yes, best oracle: run over HTTP with `gbrain protocol conformance --target` (`src/commands/protocol.ts:60`) |
+| `test/fixtures/agent-contract/v1/*.json` and `test/agent-contract-goldens.test.ts` | frozen wire envelopes; `next` is recomputed, never stored | Yes: the goldens are plain JSON |
+| `test/fixtures/goldens/cli/*.json`, `test/fixtures/cli-contract/help-baseline.json`, `test/cli-command-table.test.ts` | command table, help text, dispatch order | Partly; help text is useful, dispatch order is TS-specific |
+| `scripts/check-agent-contract.ts` (559 lines) with `scripts/agent-contract-baselines/*.tsv` (12 files, 129 rows) | 16 source rules; baselines are shrink-only; zero-baseline rules include `unregistered-code`, `code-naming`, `generic-suggestion`, `defaulted-suggestion` | No: it is a TypeScript AST scanner. Port the rule list and the registry-code check |
+| `test/fixtures/guards/check-agent-contract.ts` | fixture tree for the scanner (`GBRAIN_GUARD_ROOT` seam) | Only as a pattern |
+| `src/core/error-registry.ts` to `docs/guides/error-codes.md` (generated) | one row per code with class, exit, legacy value | Yes: generate a Rust table from the same source |
+| `eval/runner/mcp-contract.ts` (gbrain-evals, BrainBench cat 12) | trusted vs untrusted inputs across operations | No: imports `gbrain/operations` in-process over PGLite (`:20-23`). Needs an over-the-wire rewrite |
+
+## Rust engine implications
+
+**Must preserve exactly (wire contract)**
+- Operation names, scope, `localOnly`, `cliOnly`, `verb`, `mutating`, `idempotent`, param names, types and enums. These form the MCP tool schema and are read by agents.
+- The seven verb names, `protocol_version: 1`, the response field names, and the frozen legacy error values alongside canonical `code`.
+- Exit codes 0, 1, 2, 3, 10, 11, 12, 13, 14, 15, 16, 17, 18, 69, 75, 124, 130, and the envelope with `contract_version: 1`.
+- Fail-closed trust: `remote` is required; only strict `false` is trusted. Source ladder in `sourceScopeOpts`, including the `__all__` and `__none__` sentinels.
+- Scope implication table, PKCE S256, SHA-256 token storage, and the `request_id`/`expected_revision` idempotency rules.
+- The surface membership sets: `verbs` = the seven verbs; `starter` = the 41-name set. Monotonicity verbs ⊆ starter ⊆ full is pinned by tests.
+
+**Can simplify**
+- The 132-record CLI table is mostly routing. A Rust `clap`-style command tree with one generated op-to-command map covers it.
+- The lazy module loading, stdout interposer (`cli-force-exit.ts`) and Bun fast paths exist only for Bun's module graph. Rust writes stdout synchronously.
+- The express and SDK middleware order (`test/fixtures/goldens/serve-http/routes.json`) is TS-specific. Keep the routes, not the ordering.
+- The registry can become one generated static table.
+
+**Postgres features this surface depends on (engine-side, but reached from ops)**
+- Write journal: row locks (`FOR UPDATE`), `unnest ... WITH ORDINALITY`, `ON CONFLICT`, counter tables. Needs an embedded transactional store with single-writer or row-lock semantics.
+- Config as rows: `mcp_surface`, `mcp.strict_params`, `mcp.publish_*` are read from the engine config table with file fallback. Rust needs the same DB-over-file precedence.
+- Access tokens, OAuth clients and codes, and `mcp_request_log` are SQL tables. The legacy bearer path also runs raw SQL through `executeRaw` (in `request_tools` and wakeshift).
+- Facts and pages are source-scoped by `source_id` on every read; the ladder must be enforced in the storage layer's query builder, not only in ops.
+
+**Risks**
+- 930 params spread over 204 ops; most validation lives in per-op code plus `validate-params.ts` (322 lines). A Rust port that validates less will drift from the tools/list schema.
+- Description strings in the manifest are read by agents and drive behaviour. Treat them as data and copy them verbatim.
+- The write path has multi-step receipts, `write_pending`, and `--accept-pending`. Getting exit 10 and the receipt right matters more than the internal journal design.
+- `gbrain-evals` imports the TS library directly. Anything that breaks that import breaks the eval harness until it is rewritten over the wire.
+
+## Open questions
+
+1. Which ops are truly most used? The repo has no histogram. Who can supply production `mcp_request_log` counts so the starter set is re-derived?
+2. Starter tier size: the code tallies 41 names; the MEMORY_VERBS doc says 40. Which is the contract, and is the discrepancy intended?
+3. Should the Rust engine serve the full 204-op surface in v1, or only `verbs` plus `starter` with `full` later?
+4. Is the OAuth 2.1 server (DCR, PKCE, `/revoke`) required for v1, or is stdio plus legacy bearer enough for the first release?
+5. Which `cliOnly` commands (`purge_fact`, `file_verify`, `migrate_embeddings`, skill retention) must exist in v1 given they are owner-only?
+6. Per-op engine mapping is partial because helper-delegated calls were not followed. A second pass needs the TypeScript compiler, which is not installed in the reference checkout. Who installs it in a scratch copy?
+7. Does the Rust port keep write-request receipts and the `deferred` state, or can it admit writes synchronously in v1?
+8. Exit codes 2 versus 3 for `mcp expose` and `google` are documented as legacy. Should the Rust engine copy the legacy behaviour or the v1 table?
diff --git a/docs/designs/rust-engine/research/06-graph-and-knowledge.md b/docs/designs/rust-engine/research/06-graph-and-knowledge.md
new file mode 100644
index 0000000000..0105327acb
--- /dev/null
+++ b/docs/designs/rust-engine/research/06-graph-and-knowledge.md
@@ -0,0 +1,359 @@
+# Knowledge layer map: graph, entities, facts, takes, timeline
+
+Line numbers refer to gbrain 36bd05806a.
+
+Scope: the knowledge layer of gbrain v0.60.733.0 (commit 36bd05806a, read-only reference at garrytan/gbrain). Eval references are in garrytan/gbrain-evals (commit 9ecc5b20).
+
+Legend: unmarked claims were read in code and cite file:line. "[inferred]" marks conclusions drawn from comments, naming, or standard Postgres behavior that I did not run.
+
+## 1. Summary
+
+- The knowledge layer is one graph (`links`, with provenance columns), two entity-side tables (`page_aliases`, mention index), three fact-like stores (`facts`, `takes`, `timeline_entries`), and several DB-only ledgers (withdrawals, purge tombstones, belief events).
+- Markdown is canonical for file-backed knowledge. The `takes` and `facts` tables are derived indexes over fenced Markdown tables. Withdrawals, purge tombstones, belief events, and DB-only facts are not rebuildable from Markdown. (docs/architecture/system-of-record.md:44-100)
+- Postgres features in use: recursive CTEs (BFS with array visited sets), `pg_trgm`, `jsonb` containment, `jsonb_to_recordset` batch writes, `NULLS NOT DISTINCT` (PG15+), HNSW on `halfvec`/`vector`, `tsvector` GIN, advisory and row locks, and SQL triggers.
+- Search-time graph signals are multiplicative boosts from link counts (backlinks, adjacency, cross-source, session demotion), not embeddings.
+- Identity resolution is exact matches, then a same-name trigram check, then slugify. `whois` is exact-only.
+- Facts are fence-first, with a DB-only fallback. Forget is a DB withdrawal plus a Markdown strike. Purge is a separate owner-only tombstone operation.
+
+## 2. Authority: what can be rebuilt from Markdown
+
+| Store | Table(s) | Authority | Rebuild source / note |
+|---|---|---|---|
+| Page body, frontmatter | `pages`, `content_chunks` | FS canonical; DB-only pages exist | `sync` + `extract` (system-of-record.md:50-75) |
+| Markdown-derived links | `links` (origin_page_id set) | Derived | Re-extract from body and frontmatter |
+| Manual DB-only edges | `links` (origin NULL) | DB-only | Not in Markdown (link-temporal-schema.ts:6-8) |
+| Wanted links | `wanted_links` | Derived; page text is truth | wanted-links.ts:1-14 |
+| Temporal evidence | `link_transitions` | Derived from origin page | Replaced with origin's derived links (link-temporal-schema.ts:6-8) |
+| Temporal state cache | `link_relationships` | Derived cache | Rebuilt from transitions; `graph_generation_seq` invalidates query caches |
+| Edge contradiction proposals | `link_edge_proposals` | Operational state [inferred] | Apply/undo state, not Markdown |
+| Takes | `takes` (+ `synthesis_evidence`) | FS canonical via `## Takes` fence | takes-write.ts:1-12; takes-fence.ts:1-30 |
+| Facts | `facts` | FS canonical when file-backed; DB-only otherwise | system-of-record.md:138-143 |
+| Forget withdrawals | `fact_withdrawals` | DB-only, authoritative | withdrawal-schema.ts:84-93; system-of-record.md:378-400 |
+| Purge tombstones | `fact_purges`, `take_purges`, `page_purges` | DB-only, authoritative | purge-schema.ts:36-64 |
+| Belief events | `belief_events`, `belief_page_lifetimes`, `belief_commit_marks`, `belief_retier_manifest`, `belief_redactions` | DB-only by design | belief/schema.ts:17-93; system-of-record.md:98 |
+| Timeline rows | `timeline_entries` | Derived from Markdown | system-of-record.md:57-60 |
+| Tags | `tags` | Derived from frontmatter; `tag_source='added'` rows are DB-claimed | page-state/tags.ts:12-14 |
+| Page versions | `page_versions` | Audit history; "rebuildable in principle but not in practice" | system-of-record.md:72-74 |
+| Entity aliases | `page_aliases` | Derived from frontmatter/declared/subject | v110-page-aliases.ts:32-44; v206 |
+| Calibration profiles | `calibration_profiles` | Published snapshots [inferred: history not rebuildable] | v068-calibration-profiles-v0-36.ts:34-60 |
+
+Note: docs/architecture/system-of-record.md:98 lists the belief ledger as DB-only. The design doc (docs/designs/BELIEF_LEDGER.md) still says "Status: design, not built," but src/core/belief/ contains about 4,100 lines of implementation. The code is the more recent source. Treat the belief ledger as shipped but confirm with the owners.
+
+## 3. Links and the graph
+
+### 3.1 Schema
+
+`links` (src/schema.sql:549-584):
+- Columns: endpoints `from_page_id` and `to_page_id` (FK cascade), `link_type`, `context`, `link_source`, `link_kind`, `origin_page_id` (FK set null), `origin_field`, `resolution_type`, `assertion_tense`, `created_at`.
+- Unique key: `UNIQUE NULLS NOT DISTINCT (from_page_id, to_page_id, link_type, link_source, origin_page_id)`. The comment ties this to PG15+.
+- Indexes: `from_page_id`, `to_page_id`, `link_source`, `origin_page_id`, and a partial index on `to_page_id` where `link_type='supersedes'`.
+
+`wanted_links` (schema.sql:595-611): authored references whose target does not exist yet. Columns include `producer` (`body` | `frontmatter`), `ref_kind` (`slug` | `name`), `target_source_id`, `target_ref`, `checked_at`. Unique on `(origin_page_id, producer, ref_kind, target_source_id, target_ref)`. A live target updated after `checked_at` makes the origin stale for extraction (wanted-links.ts:1-14).
+
+`code_edges_chunk` and `code_edges_symbol` (schema.sql:472-515): call-graph edges between `content_chunks`. Unique on `(from_chunk_id, to_chunk_id, edge_type)` and `(from_chunk_id, to_symbol_qualified, edge_type)`. Writes use `ON CONFLICT DO NOTHING` (engine-sql/code-edges.ts:46-55). The PGLite path splits binds below 30,000 per statement because of a parameter-bridge limit (code-edges.ts header).
+
+### 3.2 Writes
+
+- `addLink` (engine-sql/links.ts:102-157) resolves both endpoints and upserts in one statement. Endpoint lookups take `FOR KEY SHARE` (links.ts:118-124) so a concurrent hard delete linearizes. A missing endpoint raises `PageMissingError`.
+- Batch writes (`addLinksBatch`, links.ts:216-256) pass one JSONB document and use `jsonb_to_recordset` with `ON CONFLICT ... DO NOTHING`.
+- `replaceDerivedLinks` (derived-links.ts:170) replaces all links owned by one origin page, plus its `wanted_links` rows, in one transaction. It checks origin revision and endpoint revisions and raises `DerivedLinkEndpointChangedError` on mismatch.
+- `link_source = 'mentions'` rows are body-text mentions. They feed orphan and traversal logic but are excluded from backlink counts and ranking (schema.sql:553-556; graph-rank.ts:116).
+
+### 3.3 Reads
+
+- `getLinks` / `getBacklinks` (links.ts:366, 437) are indexed point reads with privacy, source, and temporal filters.
+- Link types that do not count for ranking come from a code constant: `NON_RANKING_LINK_TYPES = ['amends']` (link-ranking-policy.ts:21). The SQL predicate is `link_type <> ALL(ARRAY['amends'])` (link-ranking-policy.ts:33-35).
+
+### 3.4 `traverse_graph`: the BFS walk
+
+`traverseGraph` (links.ts:659) and `traversePathsDetailed` (links.ts:711) share `bfsWalkCtes` (links.ts:609-648). This is a `WITH RECURSIVE` query over an array state, not a path enumeration:
+
+- Row 0 is the seed set, `array_agg(id ORDER BY slug, id)`.
+- Each step expands the frontier with `LATERAL`, dedupes neighbors with `NOT EXISTS (... unnest(visited))`, orders them by `(slug, id)`, and caps each layer with `LIMIT`.
+- `visited` grows as `bfs.visited || n.next`. The walk stops when `depth >= maxLayer`.
+- A window function `row_number() OVER (ORDER BY depth, ord)` gives each page a `pos`.
+
+Constants (engine-constants.ts):
+- `TRAVERSE_WALK_ROW_CAP = 20000` (line 48): total pages visited. `pos > cap` is dropped.
+- `TRAVERSE_PATH_ROW_CAP = 5000` (line 37): returned edges. Excess sets `truncated: true`.
+- Default `depth` 5 (links.ts:659). `frontierCap` bounds new pages per layer.
+
+Privacy and scope apply at the seed, at each step, and on both endpoints of every edge. This keeps graph reads inside the caller's source scope (comment at links.ts:672-674).
+
+### 3.5 `rank_entities`
+
+`rankEntitiesStatement` (graph-rank.ts:115-185) returns entities ordered by inbound, outbound, or both degree. Its structure:
+
+1. `readable` (MATERIALIZED): pages that the caller may read (live, unquarantined, unarchived source, optional private exclusion).
+2. `retired` (MATERIALIZED): pages with `canonical: false`, `superseded_by`, `merged_into`, or a status word `alias|redirect|redirected` (entities/resolve.ts:210-215).
+3. `chain` (`WITH RECURSIVE`): follows redirect targets up to `MAX_RETIREMENT_HOPS = 5` (resolve.ts:217).
+4. `fold` (MATERIALIZED, `DISTINCT ON`): the first live, readable target of each retired chain.
+5. `edges` (MATERIALIZED, `SELECT DISTINCT`): endpoints folded to targets, self-links dropped, non-ranking types dropped.
+6. `ends` / `d`: counts of in, out, and distinct neighbors per node, filtered by entity type.
+
+Ordering is `key DESC, slug COLLATE "C", source_id COLLATE "C"`. The doc comment (graph-rank.ts:20-30) gives a benchmark: about 3 s on Postgres 16 with 200k pages and 985k links, local and remote.
+
+### 3.6 Search boosts (not SQL-side)
+
+Two boost paths, both computed after fusion in `src/core/search/`:
+
+- Backlink boost (`applyBacklinkBoost`, hybrid.ts:257-300): counts distinct linking pages, excluding self-links and mention links. Factor `1 + 0.05 * ln(1 + count)`. Examples from the comment: 1 link gives about 1.035, 10 about 1.12, 100 about 1.23. Results below the floor threshold are skipped. Counts come from `readBacklinkCounts` (read-enrichment.ts:243-263), keyed by `page_id`.
+- Adjacency and cross-source boost (graph-signals.ts:54-68): among the top `DEFAULT_TOP_K = 20` results, a page linked from at least `ADJACENCY_MIN_HITS = 2` other top-K pages gets `ADJACENCY_BOOST = 1.05`. At least `CROSS_SOURCE_MIN_HITS = 2` distinct other sources gets `CROSS_SOURCE_BOOST = 1.10`. Session-prefix duplicates are demoted to `SESSION_DEMOTE = 0.95`. Fail-open: an error returns input unchanged. The SQL is `readAdjacencyBoosts` (read-enrichment.ts:265-287), with candidate ids inlined as integers to avoid a bad generic plan.
+- Hub dampening (search/hub-dampening.ts:11-14): `hubWeight(n, H) = 1 / (1 + ((max(n,1)-1)/H)^2)`. Call sites were not traced.
+
+BrainBench Cat 27 (gbrain-evals/eval/runner/cat27-graph-signals.ts:1-12) A/B-tests these signals on PGLite.
+
+### 3.7 Derived-link provenance
+
+Derived links carry `origin_page_id` and `origin_field`, so one page's re-extraction replaces only its own rows. Attendance and frontmatter-link rules are in docs/architecture/key-files/graph-and-facts.md.
+
+## 4. Entities and identity resolution
+
+### 4.1 Resolver ladder
+
+`resolveEntitySlug` (src/core/entities/resolve.ts:60-168) returns a slug or null. Its order, as read:
+
+1. Exact slug, when the input looks like a slug. A retired exact match follows its redirect (`followRetirement`).
+2. Exact own name: a live page whose slug basename equals the input wins over another page's alias (resolve.ts comment at 1.25).
+3. Organization directory variant (`orgDirVariants`) and `alias_exact` hits from `page_aliases` (resolve.ts:530-534).
+4. Same-name trigram candidate (only for multi-token inputs with `sameName`): `lower(title) % $2 OR slug ILIKE '%'||$3||'%'`, `ORDER BY GREATEST(similarity(title), similarity(slug)) DESC, slug`, `LIMIT 5` (resolve.ts:538-552). Accepted only if `isFactEntityPage` and `sameEntityName` both hold.
+5. Bare-name prefix expansion (`findPrefixCandidates`, resolve.ts:687). A single prefix candidate resolves. Several return `{miss: 'unverified'}`.
+6. Fallback to a deterministic `slugify` by the caller. It does not prefix a directory (resolve.ts:53 comment).
+
+`sameEntityName` (resolve.ts:195-199): both sides normalize to a sorted, de-duplicated token set, with accents folded, punctuation dropped, `NAME_NOISE_TOKENS` removed (resolve.ts:166). "Example, Alice" matches "Alice Example". "Alicia Example" does not. The token list is code state, so the Rust port must copy it exactly.
+
+### 4.2 Trigram use
+
+pg_trgm is required by schema (`CREATE EXTENSION IF NOT EXISTS pg_trgm`, schema.sql:4) and indexed:
+- `idx_pages_trgm` on `pages(title gin_trgm_ops)` (schema.sql:282).
+- `idx_pages_slug_trgm` on `pages(slug gin_trgm_ops)` (schema.sql:286).
+
+Uses:
+- `resolve.ts:544, 592, 883-891`: `%` plus `similarity()`.
+- `similar-pages.ts:58-59`: title `%` plus `similarity >= TITLE_SIMILARITY_FLOOR = 0.55` (similar-pages.ts:23).
+- `engine-sql/pages.ts:775-779`: fuzzy page lookup.
+- `engine-sql/takes.ts:343-371`: `query <% t.claim` with `word_similarity`. Ordered by score, then weight.
+- `resolve.ts:868-918`, `tryFuzzyMatch`. Two modes:
+ - Same-name mode (default): `LIMIT 5`, exactly one `isFactEntityPage` + `sameEntityName` candidate wins. Two namesakes are ambiguous and return null.
+ - Phantom-canonical mode: a winner needs score >= 0.7 and a margin of at least 0.1 over the runner-up (resolve.ts:868-918).
+- If pg_trgm is missing (`42883` or the operator error), the fuzzy arm is skipped and the resolver falls through to slugify (resolve.ts:920-925).
+
+[inferred] The `%` operator uses the pg_trgm default threshold 0.3, and `<%` uses `word_similarity_threshold` 0.6. No override was found in the repo, but I did not check the config table or extension defaults.
+
+### 4.3 `whois`: exact-match rule
+
+`whois` (src/core/ops/whois.ts:1-22) answers only on an exact match. It accepts an email address or a name, and matches the frontmatter `email`/`emails` value, the page title, or a declared alias. Folding: case, accents (NFKD minus marks, stroke letters folded), compatibility width forms, and surrounding whitespace or quotes. An email query compares whole addresses case-insensitively, with no accent folding. There is no nickname, typo, prefix, or semantic match, and no search fallback.
+
+Candidate SQL (engine-sql/exact-identity.ts:41-100) is a `UNION` of index-served equality probes, one per arm:
+- `lower(p.title) = ANY(keys)`: `idx_pages_source_title_lower`.
+- `regexp_replace(p.slug, '^.*/', '') = ANY(basenames)`: `idx_pages_slug_basename`.
+- `page_aliases.alias_norm = ANY(keys)`: `(source_id, alias_norm)` index.
+- `p.frontmatter @> {email: x}` and three other shapes: GIN `idx_pages_frontmatter`. Each address gets its own arm, because an `OR` plans worse.
+
+Limits: query at most 320 characters (`WHOIS_MAX_QUERY_CHARS`), at most 20 types, at most 100 candidates (`WHOIS_CANDIDATE_CAP`, whois.ts:24-27). Output includes `ambiguous: matches.length > 1`.
+
+### 4.4 Name variants and near-name index
+
+`name-variants.ts:23-28` classifies seven variant kinds; `typo` and `surname` are weak and need a single matching page overall. `near-name.ts` builds an in-process index (names 3-64 chars, at most 200,000 entities), not SQL.
+
+### 4.5 Retirement
+
+A retired page hands its identity to a target: `superseded_by` or `merged_into`, or `canonical: false`, or a status word. Chains stop at `MAX_RETIREMENT_HOPS = 5` and at cycles (resolve.ts:210-234). `rank_entities` folds retired edges onto the target. The redirect field is read from frontmatter with regex (graph-rank.ts:80-83).
+
+## 5. Facts
+
+### 5.1 Schema
+
+`facts` (created by migration v045, src/core/schema-migrations/v045-facts-hot-memory-v0-31.ts:113-160; later columns from v047, v051, v067, v089, v122, v166, v215, v273):
+
+- Identity: `id BIGSERIAL`, `source_id`, `entity_slug`, `fact`, `kind` (`event|preference|commitment|belief|fact|idea`), `visibility` (`private|world`), `notability`, `attributed_to`.
+- Validity and dedup: `valid_from`, `valid_until`, `expired_at`, `superseded_by`, `consolidated_at`, `consolidated_into`.
+- Provenance: `source`, `source_session`, `confidence REAL` (0..1), `row_num` and `source_markdown_slug` (fence round-trip), `source_window JSONB`.
+- Typed claim: `claim_metric`, `claim_value`, `claim_unit`, `claim_period`, `event_type`, `dimension`, `value`, `dim_status`.
+- Embedding: `halfvec(N)` or `vector(N)` (N default 1536, v045:32), with `embedding_model`, `embedded_at`, and `embedded_text_hash = md5(fact)` gating comparability.
+
+Indexes: partial `expired_at IS NULL` indexes on entity, session, and time; an unconsolidated index; a partial HNSW index on live embeddings, skipped if the dimension exceeds the pgvector limit for the type (v045:99-106); a keyword index `idx_facts_fts` (fts-index.ts:1-25); and a partial unique index on `(source_id, source_markdown_slug, row_num)`.
+
+halfvec requires pgvector >= 0.7. Migration v045 falls back to `vector` below that (v045:60-75). PGLite always uses halfvec (v045:89-91).
+
+### 5.2 `remember`: write path
+
+Verb (src/core/verbs.ts:67-120): requires `provenance` for a single fact (max 500 chars). `entity` is the subject. `ttl` is optional. Batch `items` are capped at 20.
+
+Implementation (src/core/facts/write-single.ts:1-20):
+1. Resolve the entity (section 4).
+2. Dedup via `decideSingleFact`: exact fingerprint first (always runs), then embedding cosine at the model's calibrated threshold.
+3. If the top candidate scores at or above threshold with the same `kind` but different text, the new fact supersedes it. Same text is a duplicate and returns the existing id.
+4. Fence-first write to Markdown. Legacy DB-only fallback for thin clients, unparented sources, or `sync.write_through` off (fence-write.ts:314-365).
+
+Thresholds (src/core/facts/supersession-threshold.ts:14-30): cosine supersession applies only to calibrated `provider:model@dims`. The one entry is `voyage:voyage-4@1024 = 0.95`. Uncalibrated models insert without superseding, and conflict review handles the pair. Operators can set `facts.supersession_thresholds`, or `off`.
+
+The fingerprint (withdrawal-schema.ts:27-40): `gbrain_fact_fingerprint` = sha256 hex of a normalized claim (lowercased, punctuation translated to spaces, whitespace collapsed, trimmed). `gbrain_fact_fingerprint_v1` trims, lowercases with the host's `lower()`, collapses whitespace and hashes; it does no punctuation folding. The fingerprint is stored in `fact_withdrawals` and `fact_purges`, so it must match byte-for-byte.
+
+Concurrency (engine-sql/facts.ts:88-170): when `entity_slug` is set, the insert takes `pg_advisory_xact_lock(hashtextextended(source_id || ':' || entity_slug, 0))`. The supersede path also updates the old row inside the same transaction. The comment in write-single.ts:14-17 says dedupe is sequential, so two identical submissions racing can both insert.
+
+### 5.3 `recall`
+
+`recall` (src/core/ops/facts.ts:298-330) reads facts by entity, `since`, or `session_id`. `query` also searches pages. Remote callers get world-visibility facts only, except a caller bound to the brain owner, which also reads private facts (`worldOnlyFacts`); source grants and member access still apply. Dedupe candidates for a write use `findCandidateDuplicates` (engine-sql/facts.ts:580-636): `k` clamped to `[1, 20]` (default 5), filtered by `source_id`, `entity_slug`, `expired_at IS NULL`, `valid_until` in the future, and `embedding <=> query` when comparable. The keyword arm (`findKeywordCandidates`, engine-sql/facts.ts:638-666) uses `plainto_tsquery`, `to_tsvector @@ q`, and `ts_rank_cd`.
+
+
+### 5.4 `forget`: withdrawal
+
+`forget` (src/core/verbs.ts:484-516) takes a fact id and an optional reason. It is idempotent. The result is `ok`, `path` (`fence` | `legacy_db` | `not_found` | `already_expired`), and a reason.
+
+The mechanism (forget.ts:1-15, withdrawal.ts:1-30, withdrawal-schema.ts:84-100):
+- Insert a row into `fact_withdrawals (source_id, visibility, subject, fact_hash, withdrawn_at)`, primary key on the four key columns. `subject='*'` means every entity.
+- Trigger `facts_preserve_withdrawal` (BEFORE INSERT OR UPDATE OF fact, source_id, visibility, entity_slug, expired_at) re-applies withdrawal to matching new rows.
+- Expire the row (`expired_at`, `valid_until`). Strike the Markdown row and append the reason. Withdrawal is DB-first and does not require a filesystem owner (system-of-record.md:378-392).
+- A forgotten claim without an entity is withdrawn for every entity. Remembering the same text again is refused with `fact_withdrawn` (withdrawal.ts:20).
+
+"Forget expires, never deletes" is the invariant (purge.ts:1-7).
+
+### 5.5 `purge_fact`: separate and destructive
+
+`purge_fact` (src/core/facts/purge.ts:1-30) runs only from the trusted local CLI. It is not a mode of `forget`. One transaction:
+- Write `fact_purges` (text-free tombstone), and `take_purges` for verbatim takes.
+- Hide and rederive derived rows (`derivation_inputs`, `needs_rederive`).
+- Delete the fact row and drop fence rows from stored page bodies and `page_versions` snapshots.
+- Redact carried request intents. Drop P8 review rows.
+- Post-commit: rewrite the Markdown file and commit `gbrain: purge fact <hash8>`.
+
+Refusal triggers (purge-schema.ts:124-187): `facts_refuse_purged` (BEFORE INSERT OR UPDATE OF fact, source_id, visibility, entity_slug), `takes_refuse_purged`, and `pages_refuse_purged` block reinsertion of purged content.
+
+### 5.6 Consolidation
+
+`consolidateFact` (engine-sql/facts.ts:668-670) sets `consolidated_at` and `consolidated_into` (a take id). The caller is the publication path in src/core/persistence/prepared-maintenance.ts:780-800: a consolidation request creates a take with `kind='fact'`, `holder='self'`, then marks each source fact as consolidated into that take, inside the same transaction. Consolidated facts are excluded by `idx_facts_unconsolidated`.
+
+### 5.7 Trajectory
+
+`find_trajectory` (ops/insights.ts:301) calls `findTrajectory` (engine-sql/facts.ts:672-740):
+- Filters: `entity_slug`, `source_id` or `source_ids`, `expired_at IS NULL`, world visibility for remote callers, `projectionEligibleSql` (quarantine and rederive gates), optional `claim_metric`, `kind` (`metric` or `event`), `since`/`until` on `valid_from`.
+- `ORDER BY valid_from DESC, id DESC LIMIT n`, then reversed to chronological. `clampSearchLimit(limit, 100, 500)`.
+- Embeddings returned only when `embedding_model` matches the config value and `embedded_text_hash = md5(fact)`.
+
+The math lives in TypeScript (src/core/trajectory.ts:1-25): a regression fires when a comparable pair (same metric, unit, period, strictly later) drops at least 10% (`GBRAIN_TRAJECTORY_REGRESSION_THRESHOLD`). Drift is `1 - mean(cosine(emb[i], emb[i-1]))`, clamped to [0,1], null with fewer than 3 embedded points.
+
+## 6. Takes, beliefs, calibration
+
+### 6.1 Takes
+
+`takes` (migration v037, src/core/schema-migrations/v037-takes-and-synthesis-evidence.ts:25-49; later changes v043, v048, v080, v094, v142, v251):
+- `id BIGSERIAL`, `page_id` (FK cascade), `row_num`, `UNIQUE (page_id, row_num)`.
+- `claim`, `kind` (`fact|take|bet|hunch`), `holder TEXT`, `weight REAL` in [0,1] (grid-rounded, v048), `since_date`, `until_date`, `source`, `superseded_by`, `active`.
+- Resolution: `resolved_at`, `resolved_outcome`, `resolved_value`, `resolved_unit`, `resolved_source`, `resolved_by`, `resolved_quality` (`correct|incorrect|partial|unresolvable`, v043).
+- `embedding VECTOR(N)`, with N matched to config (v142), HNSW partial on `active AND embedding IS NOT NULL`.
+
+Authority: markdown `## Takes` fence is canonical. The DB row is a mirror written through `addTakesBatch` (takes-write.ts:1-20). Writers that create DB-only takes are forbidden because the next sync clobbers them. Resolution columns are rendered into the fence when any row on the page has them (takes-fence.ts:85-93).
+
+### 6.2 Scorecard and calibration
+
+- `getScorecard` (engine-sql/takes.ts:599-648): Brier over resolved `correct`/`incorrect` bets as `AVG((weight - 1{correct})^2)`, plus counts `total_bets`, `resolved`, `correct`, `incorrect`, `partial`, `unresolvable_count`. Scoped by holder, domain prefix, since/until, sources, and privacy.
+- `getCalibrationCurve` (engine-sql/takes.ts:650-695): bins by `FLOOR(weight::numeric / bucket)`, `LEAST(..., max_idx)`. The comment (lines 678-681) explains that `NUMERIC` is required because float bucketing differs between Postgres and PGLite at boundaries (e.g. 0.7/0.1 = 6.999...). Rust must use exact decimal or integer arithmetic here.
+- Domain assignment: `take_domain_assignments` (v094), with aggregators in src/core/calibration/domain-aggregators.ts:1-20. The aggregator set is closed in code; domain names are open in pack manifests.
+- Profiles: `calibration_profiles` (v068:34-60), with `domain_scorecards JSONB`, `active_bias_tags TEXT[]` with GIN, a `published` flag, voice-gate fields, and `model_id`.
+- Contradiction runs and an expiring judge cache (engine-sql/takes.ts:141-292).
+
+### 6.3 Synthesis evidence
+
+`synthesis_evidence` (v037): a synthesis page cites `(take_page_id, take_row_num)` with a `citation_index`. Primary key `(synthesis_page_id, take_page_id, take_row_num)`. Derived from markdown by `extract takes` (system-of-record.md:73).
+
+### 6.4 Beliefs: the ledger
+
+"Beliefs" in gbrain names the belief ledger, not the takes. It records what the brain had recorded, and when (BELIEF_LEDGER.md section 1).
+
+`belief_events` (src/core/belief/schema.ts:17-52):
+- `event_key BYTEA UNIQUE`, `source_id`, `source_incarnation UUID`, `page_lifetime UUID`, `slug`, `subject_kind` in `page|fact|take|link|link_transition|coverage`, `subject_key`, `event_type`, `origin` in `live|unmanaged|baseline|backfill|reconcile`, `trust_tier`, `visibility`, `publication_id UUID`, `ord`, `recorded_at DEFAULT clock_timestamp()`, `valid_from`, `valid_until`, `value JSONB`, `value_hash`, `prior_hash`, `state_hash`, `cause JSONB`, `claim_fp`, `purged BOOLEAN`, `redacted_fields TEXT[]`.
+- Partial index on `claim_fp`; indexes on subject, page lifetime, and publication.
+
+Supporting tables: `belief_page_lifetimes` (partial unique on open lifetimes, schema.ts:54-64), `belief_commit_marks`, `belief_retier_manifest`, `belief_redactions`.
+
+Writes happen in `withBeliefBatch` (belief/ledger.ts:1-25): every committing transaction records one event per changed logical key, before the terminal receipt. Source rows are read under the held page keys.
+
+Purge and redaction are mirrored into the ledger (belief/purge-mirror.ts, belief/purge.ts).
+
+Withdrawal, purge, and redaction are compared in section 5.4-5.5. Forget keeps the expired row and the withdrawal. Purge keeps only text-free tombstones.
+
+## 7. Timeline
+
+`timeline_entries` (schema.sql:645-676):
+- `page_id`, `date DATE`, `source TEXT DEFAULT ''`, `summary`, `detail`, `event_page_id` (FK cascade, for Life Chronicle event projections), `created_at`.
+- Unique index `idx_timeline_dedup ON (page_id, date, md5(summary), source)`. The md5 key exists because a raw long summary overflowed the btree row limit (#3737, schema.sql:657-660).
+- Partial unique `idx_timeline_event_dedup ON (event_page_id, date) WHERE event_page_id IS NOT NULL`.
+
+Writes: `addTimelineEntry` and batch insert via `jsonb_to_recordset` with `ON CONFLICT (page_id, date, md5(summary), source) DO NOTHING` (engine-sql/timeline.ts:38-84).
+- `add_timeline_entry` is markdown-first (ops/timeline.ts:45-75). The Markdown Timeline section and inline `[Source: ..., YYYY-MM-DD]` citations are canonical (system-of-record.md:57-60).
+- Event projection `upsertEventProjection` (engine-sql/timeline.ts:255-268) writes rows with `event_page_id`. Reads hide rows whose event page is soft-deleted.
+- `last_seen` (engine-sql/timeline.ts:225-260): latest dated entry for an entity, considering both direct page matches and `event.who` entries in event frontmatter (`jsonb_array_elements_text`). Uses `date <= as-of`.
+
+## 8. Tags
+
+`tags` (schema.sql:616-628): `page_id` (FK cascade), `tag`, `tag_source` (`frontmatter` | `added` | NULL legacy), `UNIQUE(page_id, tag)`. Indexes on `tag` and `page_id`.
+
+- Frontmatter tags are import-owned: removing one from frontmatter deletes its `frontmatter` row (import-file.ts:828-835).
+- An explicit add claims the row as `added`, so import keeps it (page-state/tags.ts:12-14). Whether the add rewrites frontmatter was not traced.
+- `getTags` (engine-sql/tags.ts:12-33) is a `SELECT DISTINCT` over the page's rows.
+
+## 9. Page versions
+
+`page_versions` (schema.sql:679-690): `page_id`, `compiled_truth`, `frontmatter JSONB`, `snapshot_at`. Migrations add `timeline`, `knowledge_revision`, `title`, `type`, `tags`, `is_deleted`, `source_path`, `change_reason`, and segmented body references.
+
+- Written on each page write by `createPageVersion` (page-state/versions.ts:30-40).
+- Large pages (over `PAGE_INLINE_MAX_BYTES = 1 MiB`, page-size-policy.ts:35) keep only the newest `LARGE_PAGE_VERSIONS_KEPT = 5` (page-body/limits.ts:125). Older rows are deleted with `OFFSET`, and `markPrunedHistory` records the gap (versions.ts:35-40).
+
+
+## Rust engine implications
+
+What must be preserved exactly:
+- Fact fingerprint bytes: `gbrain_fact_fingerprint` normalization and sha256 hex. Withdrawal and purge tombstones key on it. A different normalizer silently un-withdraws facts on reimport.
+- Link identity: the five-part unique key with NULL-as-equal semantics, plus `link_source`, `origin_page_id`, and `origin_field`. Derived-link replacement is per origin.
+- Entity resolution order and token rule (`sameEntityName`, its noise-token list, the retirement chain of 5 hops, `followRetirement`). Ambiguous namesakes stay unresolved.
+- `whois` exact arms and caps (320 chars, 20 types, 100 candidates) and its ambiguity flag.
+- Traversal contract: BFS by layer, `(slug, id)` ordering, `TRAVERSE_WALK_ROW_CAP = 20000`, `TRAVERSE_PATH_ROW_CAP = 5000`, `truncated` flags, depth default 5.
+- Boost constants and formulas (backlink log factor, adjacency 1.05 with min 2 hits, cross-source 1.10, session demote 0.95, top-K 20), and the floor gate.
+- Calibration bucketing with exact decimal arithmetic.
+- Supersession thresholds, including "uncalibrated model never cosine-supersedes."
+- Timeline dedupe key `(page_id, date, summary-hash, source)`.
+- Fence formats for facts and takes, including strikethrough encodings (`superseded by #N`, `forgotten: <reason>`).
+
+What can be simplified:
+- Recursive CTEs become in-memory BFS over per-source adjacency maps (forward and reverse). Keep the caps and ordering, not the SQL.
+- `pg_advisory_xact_lock` on `source:entity` becomes a per-key mutex in the single writer. `FOR KEY SHARE` and `FOR UPDATE` become write-path serialization, since an embedded store with one writer does not need row locks.
+- Triggers (`facts_preserve_withdrawal`, `facts_refuse_purged`, `takes_refuse_purged`, `pages_refuse_purged`) become invariant checks inside the one write function. They must run in the same transaction as the write.
+- RLS (enabled on purge and belief tables when the role bypasses RLS) becomes application-level authorization.
+- Keep the `near-name` index in process, and keep `page_versions` retention as is.
+
+Postgres feature dependencies:
+
+| Feature | Used by | Rust replacement |
+|---|---|---|
+| WITH RECURSIVE, MATERIALIZED, DISTINCT ON | traverse, rank_entities, retirement chains | BFS and fold in code |
+| pg_trgm `%`, `similarity`, `word_similarity` | resolver fuzzy arm, similar-pages, takes search | Trigram sets computed in Rust; must reproduce pg_trgm scores |
+| GIN `jsonb @>` | whois email arms, frontmatter lookup | Hash index on normalized email and frontmatter keys |
+| `jsonb_to_recordset` | batch link, takes, timeline inserts | Native batch insert |
+| `NULLS NOT DISTINCT` | links unique key | Sentinel for absent origin |
+| partial unique indexes | timeline event dedupe, belief lifetimes, takes | Key-prefixed unique tables |
+| HNSW halfvec / vector | facts and takes semantic search | HNSW crate or equivalent, f16 or f32 storage |
+| tsvector GIN, ts_rank_cd | facts keyword arm, page FTS | Full-text index; ranking will differ |
+| advisory xact locks | facts insert, mentions, writeback | Single-writer or per-key locks |
+| FOR UPDATE / FOR KEY SHARE | links, withdrawals, purge | Serialized write path |
+| SQL triggers | withdrawal and purge guards | Checks in the write function |
+| clock_timestamp(), UUID, BYTEA | belief ledger | Native types |
+
+Risks:
+- Trigram scores must match pg_trgm closely, because resolver tie-breaks sort on `similarity DESC, slug ASC`. Without a reference implementation, add a golden test set from the TypeScript resolver.
+- `ts_rank_cd` ordering will not match BM25. The facts keyword dedupe arm is only a candidate source, so the risk is a different candidate set near the cutoff.
+- Calibration bucket boundaries: float arithmetic will misplace boundary weights.
+- Authoritative DB-only state (withdrawals, purges, belief events, DB-only facts) has no Markdown backup. The embedded store must be backed up and migrated as the system of record. system-of-record.md:398-440 says rebuild does not recover these.
+- The 3-second whole-graph `rank_entities` figure is from Postgres 16. In-memory Rust needs its own benchmark, and memory use for 985k edges must be measured.
+- Derived-link revision checks (`DerivedLinkEndpointChangedError`) depend on page revisions. Keep the revision field and check it on publish.
+
+## Open questions
+
+1. Is pg_trgm at default thresholds (0.3 for `%`, 0.6 for `<%`) in production, or is there a config override? The Rust port needs the exact value. [inferred defaults]
+2. How many facts are DB-only (no fence) in real brains? system-of-record.md says they are not recoverable from Markdown, and the port's backup plan depends on the count.
+3. Is the belief ledger enabled by default? BELIEF_LEDGER.md says "not built," but src/core/belief/ is about 4,100 lines. Owners must confirm before porting.
+4. Where is hub dampening (`hubWeight`) wired? No call site was traced.
+5. Are `timeline_entries` event-projection rows (`event_page_id`) fully derivable from event pages' frontmatter?
+6. Are `calibration_profiles` published snapshots authoritative history, or recomputable views?
+7. Does a tag add with `tag_source='added'` write back to frontmatter? page-state/tags.ts was only partly read.
+8. Which code-constant vocabularies must be copied exactly? At least NAME_NOISE_TOKENS (resolve.ts:166) and the correction cue lists in search/saved-facts-match.ts.
diff --git a/docs/designs/rust-engine/research/07-jobs-and-cycles.md b/docs/designs/rust-engine/research/07-jobs-and-cycles.md
new file mode 100644
index 0000000000..c4db2bf97e
--- /dev/null
+++ b/docs/designs/rust-engine/research/07-jobs-and-cycles.md
@@ -0,0 +1,503 @@
+# 07 Jobs, Minions queue, autopilot, and cycle phases
+
+Line numbers refer to gbrain 36bd05806a.
+
+Reference: `garrytan/gbrain` at commit `36bd05806a` (v0.60.733.0), read-only.
+Method: source reading only. I did not run the TypeScript code or its tests. Statements
+without an "(inferred)" tag were checked against the cited code. Line numbers are
+approximate to within a few lines where a function spans a block.
+
+## 1. Summary
+
+- The Minions queue is one Postgres table, `minion_jobs`, with a single claim statement
+ (`UPDATE ... WHERE id = (SELECT ... FOR UPDATE SKIP LOCKED LIMIT 1) RETURNING *`,
+ `src/core/minions/queue.ts:1463-1530`). Every state change after claim is fenced by
+ `lock_token`. Retries, stall recovery, timeouts, and parent/child roll-ups are all
+ set-based SQL in the same table.
+- Postgres features the queue depends on: `FOR UPDATE SKIP LOCKED`, `pg_notify` from a
+ row trigger, partial unique indexes, JSONB (`data->>'__param_hash'`), `pg_advisory_xact_lock`
+ (admission, quota, rate leases, budget), row locks on parents, and `now()` interval math.
+ The cycle lock is deliberately a row table, not an advisory lock (`src/core/db-lock.ts:8`,
+ because the cycle lease must outlive any one transaction: a session advisory lock would
+ break under PgBouncer transaction pooling, and a transaction-scoped `pg_advisory_xact_lock`
+ ends at commit).
+- The worker learns about new work from LISTEN/NOTIFY only for `sync` jobs and only on a
+ direct (non-pooler) Postgres session. Everywhere else it polls. A general job waits up to
+ 5 s (`pollInterval` default, `src/core/minions/worker.ts:310`); the sync-wake poll is 1 s.
+- Autopilot is a daemon that sleeps 300 s by default, dispatches per-source `sync` jobs and
+ a remediation plan on each tick, and supervises a `gbrain jobs work` child process.
+- The dream cycle (`runCycle`, `src/core/cycle.ts:1904`) has 32 phases. 14 are paid (chat or
+ embedding model calls), 10 are free, 6 need a git checkout, and 2 delete rows or files.
+- Of 42 handler names registered in `registerBuiltinHandlers` (`src/commands/jobs.ts:543-700`),
+ about 15 spend model money. A minimum useful brain needs only `sync`, `embed` (or
+ `embed-backfill`), `extract`, and `backlinks`. All four are deterministic except embedding.
+
+## 2. The queue: `src/core/minions/queue.ts`
+
+### 2.1 Table
+
+`minion_jobs` is at `src/schema.sql:1248-1302`. Key columns: `id SERIAL`, `name`, `queue`
+(default `'default'`), `status`, `priority INTEGER` (lower runs first), `submission_authority
+JSONB`, `claim_generation BIGINT`, `data JSONB`, retry fields (`max_attempts` default 3,
+`attempts_made`, `attempts_started`, `backoff_type` default `exponential`, `backoff_delay`
+1000 ms, `backoff_jitter` 0.2), stall fields (`stalled_counter`, `max_stalled` default **5**,
+`lock_token`, `lock_until`), `delay_until`, `parent_job_id`, `on_child_fail`, token counters,
+`depth`, `max_children`, `timeout_ms`, `timeout_at`, `lock_duration_ms`, `idempotency_key`,
+private-queue owner columns, `result`, `progress`, `error_text`, `stacktrace`, timestamps.
+
+Statuses (CHECK constraint): `waiting`, `active`, `completed`, `failed`, `delayed`, `dead`,
+`cancelled`, `waiting-children`, `paused`.
+
+Indexes: claim index `(queue, priority, created_at) WHERE status='waiting'`
+(`schema.sql:1304`); `lock_until WHERE status='active'` for stall sweeps; `timeout_at WHERE
+active`; `parent_id`; **unique** `uniq_minion_jobs_idempotency ON (idempotency_key) WHERE
+idempotency_key IS NOT NULL` (`schema.sql:1311`); a private-queue recovery index.
+
+Other tables: `minion_inbox` (`schema.sql:1324`, `job_id` FK with cascade, `sender`,
+`payload JSONB`, `read_at`), `minion_attachments` (`schema.sql:1336`, `content BYTEA` or
+`storage_uri`, `sha256`, unique `(job_id, filename)`), plus `subagent_messages`,
+`subagent_tool_executions`, `subagent_rate_leases`, `dream_verdicts`, and
+`dream_synthesis_completions` (`schema.sql:1403-1485`, `2124`).
+
+### 2.2 Claim (exact shape)
+
+`claim()` (`queue.ts:1463`) first calls `assertNoUnreviewedJobs`. Then it runs one `UPDATE`:
+
+- SET `status='active'`, `claim_generation = claim_generation + 1`, `lock_token = $1`
+ (worker-chosen token, the fence), `attempts_started = attempts_started + 1`,
+ `started_at = COALESCE(started_at, now())`, `updated_at = now()`.
+- `lock_duration_ms` resolves row value, then handler map (`$6`), then the worker default
+ (`$2`). Row and map values are clamped to [5000, 3600000] ms; the worker default is not
+ clamped. The result is stamped on the row. `lock_until = now() + that duration`.
+- `timeout_ms = COALESCE(timeout_ms, handler map)`; `timeout_at = now() + timeout_ms` when
+ set.
+- WHERE: `queue = $3 AND status = 'waiting' AND submission_authority IS NOT NULL AND
+ name = ANY($4)` plus optional watchdog and lane exclusions. The `submission_authority IS NOT
+ NULL` predicate means legacy rows without an authority are never claimed until a local
+ operator authorizes them.
+- ORDER BY `priority ASC, created_at ASC` (an overdue watchdog suspect can jump the queue).
+- `FOR UPDATE SKIP LOCKED LIMIT 1`.
+
+Every later write (`completeJob`, `failJob`, `renewLock`, `readInbox`) repeats the fence:
+`WHERE status='active' AND lock_token = $token`. A worker that lost its lease cannot write.
+
+Delayed rows are promoted by `promoteDelayed()` (`queue.ts:2153`): `status='delayed' AND
+delay_until <= now()` becomes `waiting`. The worker runs it at the top of every loop
+(`worker.ts:805-809`).
+
+### 2.3 Leases, renewal, and sweeps
+
+- Renewal: `renewLock` (`queue.ts:2096`) sets `lock_until = now() + ms` where
+ `lock_token` and `status='active'` match. The tick interval is `min(lockDuration/2, 60 s)`;
+ each call is capped at `min(lockDuration/3, 15 s)`; the safety margin is
+ `min(lockDuration/6, 30 s)` (`src/core/minions/lock-renewal-tick.ts:168-186`). A failed
+ renewal is verified before the job is evicted.
+- Stall sweep: `handleStalled` (`queue.ts:2166`) selects `status='active' AND lock_until <
+ now() - grace`. The grace is `GBRAIN_MINION_STALL_RECLAIM_GRACE_MS`, default 15 s
+ (`queue.ts:91`). If `stalled_counter + 1 < max_stalled` the row goes back to `waiting`. Otherwise
+ it goes to `dead` with `error_text='max stalled count exceeded'`. Parents are locked first,
+ sorted. A `SKIP LOCKED` subselect protects the update.
+- Timeouts: `handleTimeouts` (`queue.ts:1547`) marks `timeout_at < now()` active rows `dead` and
+ counts the attempt. `handleWallClockTimeouts` (`queue.ts:1687`) does the same for rows with no
+ `timeout_ms`, using `2 * lockDuration * max_stalled`.
+- Sweep order per worker tick: `handleStalled`, then `handleTimeouts`, then
+ `handleWallClockTimeouts` (`worker.ts:557-602`). The worker's `stalledInterval` default is
+ 30 s (`worker.ts:308`).
+- A lease beacon queue `gbrain-drain-lease` (`protected-names.ts:20`) holds drain-lease records
+ and is excluded from all sweeps.
+
+### 2.4 Retries and terminal states
+
+On handler error (`worker.ts:1728-1734`): if the error is unrecoverable or
+`attempts_made + 1 >= max_attempts`, the job goes `dead`. Otherwise it goes `delayed`.
+`failJob` (`queue.ts:1853`) increments `attempts_made` and sets `delay_until` for `delayed`.
+Backoff (`src/core/minions/backoff.ts:8-25`): `exponential` is `2^(attempts_made-1) * delay`,
+`fixed` is `delay`, with ±`jitter` multiplicative noise.
+
+Completion (`completeJob`, `queue.ts:1745`): status `completed`, `result` stored, and if
+`parent_job_id` is set, the parent gets a token roll-up and a `child_done` inbox row
+(sender `minions`, `outcome='complete'`). Failure also writes `child_done` with
+`outcome='failed'` or `'dead'` before the parent update (`failJob`, `queue.ts:1853`).
+
+`on_child_fail` on the child decides what the parent does: `fail_parent`, `remove_dep`,
+`ignore`, or `continue`.
+
+`retryJob` (`queue.ts:1227`), `cancelJob` (`queue.ts:782`), `pauseJob` (`queue.ts:2298`),
+and `prune` (`queue.ts:1247`) are the operator actions.
+
+### 2.5 Parent and child jobs
+
+- Submitting with `parent_job_id` locks the parent `FOR UPDATE` (comment at `queue.ts:219`)
+ and enforces `max_children`. The child inserts as `waiting` (or `delayed`). The parent moves
+ to `waiting-children`.
+- `maxSpawnDepth` defaults to 5 (`queue.ts:65`).
+- Aggregator pattern: when every child is terminal, `waiting-children` flips back to `waiting`.
+ The `subagent_aggregator` job then reads its `child_done` inbox rows
+ (`handlers/subagent-aggregator.ts` header).
+
+### 2.6 Inbox and attachments
+
+- `sendMessage` (`queue.ts:2325`) inserts into `minion_inbox`. `readInbox` (`queue.ts:2346`)
+ requires `lock_token` match and `status='active'`, then sets `read_at`.
+- `addAttachment` (`queue.ts:2455`) stores bytes or a URI with a sha256. Default cap
+ 5 MiB (`queue.ts:131`). Unique per `(job_id, filename)`.
+
+### 2.7 Idempotency
+
+- `add()` (`queue.ts:227`) fast path: `SELECT ... WHERE idempotency_key = $1` returns the existing
+ row (flagged `coalesced: true`).
+- Dead or cancelled rows release their key: the key is set to NULL and the old value is kept in
+ `data.__released_idempotency_key` (`src/core/minions/idempotency-coalesce.ts:37-47`). A
+ fresh insert then proceeds.
+- Insert: `ON CONFLICT (idempotency_key) WHERE idempotency_key IS NOT NULL DO NOTHING`
+ (`queue.ts:623`). A zero-row result is resolved by re-reading the winner.
+- Autopilot keys include the wall-clock slot (for example `autopilot-sync:<source>:<slot>`), so a
+ slow cycle cannot stack duplicates.
+
+### 2.8 Admission and quota (advisory locks)
+
+Order inside `add()`, in one transaction:
+
+1. Idempotency fast path (above).
+2. Param-coalescing (only when enabled per name, `admission.ts:45`, default only `subagent`).
+ Takes `pg_advisory_xact_lock(hashtext('minion_admission:'||name||':'||queue||':'||paramHash))`
+ (`queue.ts:385`), then returns the newest matching `waiting`, parentless row inside a TTL/2
+ window.
+3. Name-global quota (config only, no default): `pg_advisory_xact_lock(hashtext('minion_quota:'||name))`
+ (`queue.ts:431`), then count of `waiting` rows for that name across all queues. Over the cap
+ throws `QueueQuotaExceededError`.
+4. `maxWaiting` / `maxPending`: `pg_advisory_xact_lock(hashtext('minion_maxwaiting:'||name||':'||queue||':'||source))`
+ (`queue.ts:488`). Source scope is exact for `maxPending`.
+5. Insert with `ON CONFLICT` as above.
+
+Default waiting TTL: `subagent` 48 h (`admission.ts:50-52`). Expired waiting rows are cancelled with
+an auditable error text.
+
+Other advisory or row locks in the TS code: budget reservations `pg_advisory_xact_lock` on a
+hashed client id (`budget-meter.ts:99`, `255`, reservation TTL 10 min at `:28`); provider
+rate leases `pg_advisory_xact_lock($1::bigint)` (`rate-leases.ts:81`, lease TTL 120 s at
+`rate-leases.ts:54`); `SELECT ... FOR UPDATE` on `oauth_clients` (`delegated-admission.ts:40`).
+
+### 2.9 Wake and poll
+
+- Trigger `minion_job_notify`: `AFTER INSERT OR UPDATE OF status`, calls
+ `pg_notify('minion_jobs', json{id,status,name,queue,prev_status})` (`schema.sql:1812-1826`).
+ It fires on every status change, not only `waiting`.
+- `src/core/minions/sync-queue-wake.ts` LISTENs only when the connection is a direct session
+ (`chooseSyncQueueWake`, lines 37-47). It verifies with a probe NOTIFY within 3 s, else falls
+ back. A payload wakes the loop only if `name='sync' AND status='waiting' AND queue=<worker queue>`
+ (`isSyncWakePayload`, `sync-queue-wake.ts:56`).
+- Fallback poll: 1 s by default (`GBRAIN_WORKER_SYNC_WAKE_POLL_MS`, clamped to 250 ms-5 s), a
+ single indexed read for a waiting `sync` job (`sync-queue-wake.ts:24`, `:52`).
+- General idle wait: `IdleWaiter` (`idle-wait.ts`) waits `pollInterval` (default 5000 ms,
+ `worker.ts:310`; `jobs work` does not override it, `commands/jobs/work.ts:200`). A
+ `wake()` call ends the wait early.
+- Off on PGLite and when `GBRAIN_WORKER_SYNC_WAKE=0`. PGLite drains in the foreground instead
+ (`drainPgliteQueue`, `commands/jobs/work.ts:355`, 200 ms poll).
+
+## 3. Worker and supervisors
+
+- `MinionWorker` (`src/core/minions/worker.ts`, 1,792 lines). `start()` at `:506`; claim loop
+ at `:805`. Concurrency comes from `--concurrency` or `GBRAIN_WORKER_CONCURRENCY`, default 1
+ (`commands/jobs/shared.ts:91-92`).
+- Long-job lane (`lanes.ts`): default long names are `autopilot-cycle`,
+ `autopilot-global-maintenance`, `embed-backfill`, `connector-sync`, `extract`, `doctor-refresh`.
+ With concurrency ≥2, one slot is kept for short jobs by default
+ (`minions.short_job_reserved_slots`).
+- Job isolation: `jobIsolation: 'process'` runs each job in a SIGKILL-able child
+ (`job-isolation.ts`, kill grace 25 s). RSS watchdog and `maxRssMb` trigger graceful exit.
+- `ChildWorkerSupervisor` (`child-worker-supervisor.ts`, 845 lines) spawns `gbrain jobs work`.
+ Crash backoff is `min(1000·2^n, 60000) ms` plus 10% jitter (`supervisor.ts:245-249`).
+ Startup readiness timeout is 120 s (`WORKER_STARTUP_READY_TIMEOUT_MS`).
+- `MinionSupervisor` (`supervisor.ts`, 1,497 lines) is the standalone `gbrain jobs supervisor`.
+ It owns a PID lock, watches queue health, and restarts the child.
+
+## 4. Handlers
+
+### 4.1 Registration and protection
+
+`registerBuiltinHandlers` (`src/commands/jobs.ts:543-700`) registers **42 distinct names**.
+Some go through the `cycle-phase` wrapper (`handlers/cycle-phase.ts`), which calls
+`runCycle` for a single phase.
+
+Protected names (`src/core/minions/protected-names.ts`, 13 entries): `shell`, `subagent`,
+`subagent_aggregator`, `synthesize`, `patterns`, `consolidate`, `edge_contradictions`,
+`standing_questions`, `contextual_reindex_per_chunk`, `extract-takes-from-pages`, `unify-types`,
+`skillopt`, `extract-atoms-drain`. A protected name needs `allowProtectedSubmit` (CLI or trusted
+local caller). MCP and OAuth callers cannot submit them. `consolidate` is protected even
+though its phase is deterministic (see Open questions, item 3).
+
+### 4.2 Handler table
+
+"Paid" means a chat or embedding model call. "Free" means no model call, per the phase table
+or code reading. Items marked (inferred) come from names and imports, not a full read.
+
+| # | Job name | Source | What it does | Cost |
+|---|---|---|---|---|
+| 1 | `sync` | `handlers/sync.ts`, `commands/sync.ts` | Git/markdown sync into pages; submits embed-backfill | free |
+| 2 | `embed` | `handlers/embed.ts` → `commands/embed.ts` | `runEmbedCore` on stale chunks | paid (embed) |
+| 3 | `embed-backfill` | `handlers/embed-backfill.ts` (463 lines) | Per-source embedding, $10 budget per job, per-source lock | paid (embed) |
+| 4 | `embed-catch-up` | `handlers/embed-catch-up.ts` | `runEmbedCore` stale plus catch-up, onboarding | paid (embed) |
+| 5 | `lint` | `handlers/lint.ts` → `commands/lint.ts` | Lint pages | free |
+| 6 | `lint-fix` | `handlers/lint-fix.ts` | Lint with fixes | free |
+| 7 | `integrity` | `handlers/integrity.ts` → `commands/integrity.ts` | Integrity check | free (inferred) |
+| 8 | `integrity-auto` | `handlers/integrity-auto.ts` | `runIntegrity(['auto'])` | free (inferred) |
+| 9 | `sync-retry-failed` | `handlers/sync-retry-failed.ts` | Re-runs sync | free |
+| 10 | `import` | `handlers/import.ts` → `commands/import.ts` | Imports files; imports gateway (embeds?) | free (inferred) |
+| 11 | `extract` | `handlers/extract.ts` → `commands/extract.ts` | Links and timeline; stale mode chains a continuation | free |
+| 12 | `backlinks` | `handlers/backlinks.ts` → `commands/backlinks.ts` | `check` or `fix` back-links | free |
+| 13 | `extract-ner` | `handlers/extract-ner.ts` → `core/extract-ner.ts` | Regex NER links | free |
+| 14 | `extract-timeline-from-meetings` | `handlers/extract-timeline-from-meetings.ts` | Timeline rows from meeting pages | free (inferred) |
+| 15 | `extract-takes-from-pages` | `handlers/extract-takes-from-pages.ts` | LLM takes from pages | paid (chat) |
+| 16 | `extract-conversation-facts` | `handlers/extract-conversation-facts.ts` → `commands/extract-conversation-facts.ts` | LLM facts from conversations (`gateway.chat`) | paid (chat) |
+| 17 | `extract-atoms-drain` | `handlers/extract-atoms-drain.ts` → `core/cycle/extract-atoms-drain.ts` | Drains atom backlog, Haiku (~$0.30/source) | paid (chat) |
+| 18 | `loops_extract` | `handlers/loops-extract.ts` → `core/google/loops-extract.ts` | Open loops from Google sources | paid (chat, inferred) |
+| 19 | `chronicle_extract` | `handlers/chronicle-extract.ts` → `core/chronicle/job.ts` | Life Chronicle events | paid (chat) |
+| 20 | `facts-absorb` | `handlers/facts-absorb.ts` → `core/facts/backstop.ts` | LLM facts write-path, 10 min budget | paid (chat) |
+| 21 | `enrich` | `handlers/enrich.ts` → `commands/enrich.ts` | LLM enrichment of pages | paid (chat) |
+| 22 | `contextual_reindex_per_chunk` | `handlers/contextual-reindex-per-chunk.ts` (318 lines) | Haiku synopsis per chunk, then re-embed | paid (chat+embed) |
+| 23 | `reindex` | `handlers/reindex.ts` | Re-embed; paid only with a stored spend record | conditional |
+| 24 | `repair-jsonb` | `handlers/repair-jsonb.ts` | JSONB repair | free |
+| 25 | `orphans` | `handlers/orphans.ts` | Orphan report (`findOrphanPages`) | free |
+| 26 | `purge` | `handlers/purge.ts` | Hard-deletes expired pages, sources, checkpoints | deletes |
+| 27 | `doctor-refresh` | `commands/doctor/last-known.ts` | Refresh doctor snapshot | free (inferred) |
+| 28 | `ingest_capture` | `handlers/ingest-capture.ts` (465 lines) | Ingest event to inbox page via `importFromContent` | free (inferred) |
+| 29 | `connector-sync` | `handlers/connector-sync.ts` | Fetch chat-provider history when `auto_sync` is on | free; embed kick-off on PGLite |
+| 30 | `shell` | `handlers/shell.ts` (402 lines) | Runs a command as child process; guarded unless `--allow-shell-jobs` | free, protected |
+| 31 | `subagent` | `handlers/subagent.ts` (1,923 lines) | Anthropic tool-use loop; default `claude-sonnet-4-6`, 20 turns | paid (chat), protected |
+| 32 | `subagent_aggregator` | `handlers/subagent-aggregator.ts` | Deterministic roll-up of `child_done` rows | free, protected |
+| 33 | `synthesize` | `handlers/cycle-phase.ts` → `core/cycle/synthesize.ts` (3,244 lines) | Dream synthesis via subagents or one-shot | paid, protected |
+| 34 | `patterns` | `handlers/cycle-phase.ts` → `core/cycle/patterns.ts` (1,260 lines) | Cross-session pattern pages via subagents | paid, protected |
+| 35 | `consolidate` | `handlers/cycle-phase.ts` → `core/cycle/phases/consolidate.ts` | Facts to takes promotion; deterministic in v0.31 header | free, protected |
+| 36 | `extract_facts` | `handlers/cycle-phase.ts` → `core/cycle/extract-facts.ts` | `## Facts` fence reconcile | free |
+| 37 | `resolve_symbol_edges` | `handlers/cycle-phase.ts` | Code-edge resolution on chunks | free |
+| 38 | `recompute_emotional_weight` | `handlers/cycle-phase.ts` → `core/cycle/emotional-weight.ts` | Derived emotional-weight column | free |
+| 39 | `unify-types` | `handlers/unify-types.ts` | Pack upgrade: retypes 25K+ pages, manual | free (inferred), protected |
+| 40 | `skillopt` | `core/skillopt/job.ts` | Skill optimizer loop | paid, protected |
+| 41 | `autopilot-cycle` | `handlers/autopilot-cycle.ts` | `runCycle` for one source with the freshness subset | orchestrator |
+| 42 | `autopilot-global-maintenance` | `handlers/autopilot-global-maintenance.ts` (447 lines) | Runs `MAINTENANCE_PHASES` one by one, saves progress | orchestrator |
+
+Handler notes: `sync` hands embedding to `embed-backfill` after a change. The
+`autopilot-dispatch.ts` comment says the sync handler auto-enqueues it through
+`src/core/embed-backfill-submit.ts`; I did not trace that call (inferred).
+`extract` in stale mode chains a continuation job only while the stale count shrinks
+(`handlers/extract.ts:20-55`). `subagent` and `subagent_aggregator` have default lock
+leases of 5 min and timeouts of 30 min (`handler-timeouts.ts`).
+
+### 4.3 Minimum useful brain
+
+Needed:
+- `sync` (or `import`): brings pages in.
+- `embed` or `embed-backfill` (and `embed-catch-up` for onboarding): vectors for hybrid search.
+ Keyword search works without them.
+- `extract`: derived links and timeline rows from page content. Deterministic.
+- `backlinks`: finds and fixes missing back-links. Deterministic.
+
+Useful for autonomy: `autopilot-cycle` (per-source freshness), `purge` (soft-deleted pages
+reclaimed after 72 h), `orphans` (report only).
+
+Optional, and every paid LLM handler sits here: the subagent family, `synthesize`, `patterns`,
+`consolidate`, `extract-conversation-facts`, `facts-absorb`, `enrich`, `chronicle_extract`,
+`contextual_reindex_per_chunk`, `skillopt`, `extract-takes-from-pages`, `extract-atoms-drain`,
+`loops_extract`, `shell`, `connector-sync`, `ingest_capture`, `reindex`, `unify-types`,
+`integrity`, and the `*-repair` handlers.
+
+## 5. Autopilot
+
+Files: `src/commands/autopilot.ts` (1,658 lines; entry `runAutopilot` at `:629`, install
+functions `:901-1327`), `src/commands/autopilot-daemon.ts` (690 lines), `autopilot-dispatch.ts`
+(897 lines), `autopilot-remediation-policy.ts`, `autopilot-fanout.ts` (853 lines), `autopilot/jobs.ts`.
+
+Loop (`autopilot-daemon.ts`):
+1. Default `--interval 300` seconds (`:79`).
+2. `dispatchAutopilotTick` (`autopilot-dispatch.ts`):
+ - Per-source freshness syncs. Key `autopilot-sync:<source>:<slot>` where slot is
+ `floor(now / interval) * interval`. HEAD-driven syncs key on the HEAD sha instead.
+ - `extract_atoms` auto-drain.
+ - Remediation plan. Sleeps if score ≥ 95, plan empty, and last full cycle under 60 min
+ (`shouldSleepHealthyAutopilot`, `autopilot-remediation-policy.ts:45-55`).
+ - Targeted handler submits if plan ≤ 3 steps and under 300 s. Otherwise a full
+ `autopilot-cycle` fan-out per source (`fanoutMax`: 4 on Postgres, 1 on PGLite) and
+ `autopilot-global-maintenance`.
+ - A full cycle is forced every 60 min (`AUTOPILOT_FULL_CYCLE_FLOOR_MINUTES`).
+3. `adaptiveInterval` (`autopilot-daemon.ts:672-680`): score ≥ 90 doubles the interval;
+ score < 70 uses `max(base/2, 60 s)`; unknown score keeps the base.
+4. Sleep: `sleepWatchingHeads` watches git HEADs every 3 s
+ (`GBRAIN_AUTOPILOT_HEAD_PROBE_MS`, range 1-30 s), so a new commit can wake it early.
+
+Supervision: `ChildWorkerSupervisor` runs `gbrain jobs work`. After 5 consecutive crashes
+autopilot exits 1 (`autopilot-daemon.ts:419-423`). The daemon writes a heartbeat by touching
+its lock file. A foreign PID lock is taken over after 10 min
+(`AUTOPILOT_FOREIGN_PID_TAKEOVER_GRACE_MS`, `autopilot.ts:290`). Status calls the daemon stale
+after 6 intervals (`classifyAutopilotStatus`, `autopilot.ts:1514-1540`).
+
+PGLite: `installDaemon` refuses on PGLite unless `--force`, because a daemon would hold the
+single-writer lock (`autopilot.ts:901-910`). Fallback without minions (`minion_mode=off`,
+PGLite, `--inline`) runs sync, extract, and embed inline.
+
+Install targets (`detectInstallTarget`, `autopilot.ts:667-690`): `macos` (launchd plist),
+`linux-systemd` (user unit), `ephemeral-container`, `linux-cron` (crontab). The generated wrapper
+script sources a `GBRAIN_ENV_TEMPLATE` env file before exec (`writeWrapperScript`, `:783`).
+
+## 6. Cycle phases: `src/core/cycle.ts` and `src/core/cycle/`
+
+`ALL_PHASES` (`cycle.ts:130`) has 32 entries in this order. The dispatch in `runCycle` follows
+the same order (a test pins it, per the comment at `cycle.ts:219`). Scope comes from
+`cycle/phase-scope.ts`. Cost tier and managed class come from `cycle/phase-table.ts`
+(`MANAGED_PHASE_TABLE`, 32 entries). Tier counts: 14 paid, 10 free, 6 filesystem, 2 deletes.
+
+Source freshness subset (`phase-scope.ts`): `lint, backlinks, sync, extract, extract_facts,
+recompute_emotional_weight`. Connector sources run `extract, extract_facts,
+recompute_emotional_weight` only (`CONNECTOR_SOURCE_PHASES`). Explicit `--phase` lists are
+honored verbatim (`resolveCyclePhases`, `cycle.ts:289`).
+
+| # | Phase | Scope | Tier | Managed class | What it reads or writes (from phase-table reason unless inferred) |
+|---|---|---|---|---|---|
+| 1 | lint | source | filesystem | writes | Lint repairs, one page per repair, via coordinator |
+| 2 | backlinks | source | filesystem | no write | Counts missing back-links; audit only |
+| 3 | sync | source | filesystem | writes | Changed git files admitted through coordinator |
+| 4 | fence_repair | global | free | writes | Repairs held or malformed facts/takes fences |
+| 5 | content_repair | global | free | writes | Other content-repair kinds |
+| 6 | unindexed_files | global | filesystem | no write | Schedules files with no page for re-screen |
+| 7 | synthesize | mixed | filesystem | writes | Subagent synthesis from transcript corpus |
+| 8 | extract | source | free | writes | Derived links, timeline rows (DB) |
+| 9 | extract_facts | source | free | writes | Re-projects fence facts |
+| 10 | extract_atoms | source | paid | writes | Haiku atom pages (pack-gated) |
+| 11 | resolve_symbol_edges | global | free | no write | Code-edge metadata on chunks |
+| 12 | patterns | mixed | filesystem | writes | Pattern pages via subagents |
+| 13 | synthesize_concepts | global | paid | writes | Concept pages, Sonnet narratives (pack-gated) |
+| 14 | recompute_emotional_weight | source | free | no write | Derived `emotional_weight` column |
+| 15 | consolidate | source | free | writes | Facts to takes, deterministic |
+| 16 | propose_takes | source | paid | no write | Writes `take_proposals` review queue |
+| 17 | grade_takes | global | paid | no write | Caches verdicts in `take_grade_cache` |
+| 18 | calibration_profile | global | paid | no write | Writes `calibration_profiles` |
+| 19 | edge_contradictions | global | paid | writes | Proposals plus timeline lines (`add_timeline_entry`) |
+| 20 | claim_conflicts | global | free | no write | Writes `decide_proposals` |
+| 21 | drift | global | paid | writes | Drift report page (default off) |
+| 22 | standing_questions | global | paid | writes | Question pages; `pinned_questions` side tables |
+| 23 | chronicle | global | paid | writes | Life Chronicle event pages |
+| 24 | facts_drain | global | paid | writes | Runs queued facts-absorb jobs (PGLite) |
+| 25 | conversation_facts_backfill | source | paid | writes | Opt-in conversation facts |
+| 26 | enrich_thin | source | paid | writes | Opt-in stub-page development |
+| 27 | skillopt | global | paid | no write | Skill files outside the DB (default off) |
+| 28 | embed | global | paid | no write | Embeddings (`runEmbedCore`, stale) |
+| 29 | orphans | global | free | no write | Read-only orphan report |
+| 30 | schema-suggest | source | free | no write | Schema suggestions |
+| 31 | purge | global | deletes | writes | Purges soft-deleted pages past 72 h, one by one |
+| 32 | bookkeeping_gc | global | deletes | no write | Retention GC of bookkeeping rows and files |
+
+Phase notes:
+- `embed` runs with `stale: true`, quiet, and the cycle abort signal, then fails if a watchdog
+ aborted it (`cycle.ts:1688-1712`).
+- `orphans` warns only when more than half the corpus is orphaned (`cycle.ts:1839+`).
+- Per-phase budgets are in `src/core/cycle/budget-meter.ts` (named in the comment at
+ `cycle.ts:185`, not read in full).
+- Cycle lock: `gbrain-cycle` (`cycle/lock-set.ts:23`), a row in `gbrain_cycle_locks` with
+ `LOCK_TTL_MINUTES = 5` (`cycle.ts:684`). Per-source ids come from `cycleLockIdFor`.
+- Heavy phases yield to the event loop between phases, so lock renewal keeps running
+ (`handlers/autopilot-cycle.ts:17-19`).
+
+Per-source vs global: a per-source `autopilot-cycle` job is normalized to the freshness subset
+(`normalizeQueuedSourcePhases`, `cycle.ts:316`). Mixed and global phases run once in
+`autopilot-global-maintenance`, which walks `MAINTENANCE_PHASES` and records per-phase timeouts
+in progress (`handlers/autopilot-global-maintenance.ts:177-421`). It stamps
+`autopilot.last_global_at` on success (`cycle.ts:329`).
+
+## 7. Dream and subagent jobs
+
+`gbrain dream` (`src/commands/dream.ts`, 937 lines) is a thin alias over `runCycle`. Flags
+include `--phase`, `--source`, `--once`, `--drain` (atom backlog), `--pull`, `--dry-run`,
+`--reconcile-queue`, `--cancel-unmatched`, and `--json`.
+
+Dream-inline private queues: the cycle's fan-out phases mint a private queue per run,
+`dream-inline-<ms>-<uuid8>` (`queue.ts:66`). The lease for a private queue is 10 min
+(`DEFAULT_PRIVATE_QUEUE_LEASE_MS`, `queue.ts:67`). Children run through `runSubagentsInline`
+(`cycle/inline-drain.ts`), with `dream.synthesize.inline_concurrency` drain loops.
+
+Subagent jobs (`handlers/subagent.ts`):
+- A crash-resumable Anthropic Messages loop. Transcripts and tool executions live in
+ `subagent_messages` and `subagent_tool_executions`. Resume trusts `complete` or `failed` rows
+ and re-runs `pending` tools only if idempotent (header at `subagent.ts:1-22`).
+- Rate lease on `anthropic:messages`, TTL 120 s, max in-flight from
+ `GBRAIN_ANTHROPIC_MAX_INFLIGHT` (default 8). Table `subagent_rate_leases`.
+- Defaults: model `claude-sonnet-4-6` (`:86`), 20 turns (`:87`), 8192 output tokens (`:88`).
+ A `models.subagent` config can override.
+- Admission: param-coalescing on and 48 h waiting TTL (`admission.ts:45-52`).
+- One-shot mode (`handlers/subagent-oneshot.ts`, 721 lines): one tool-less completion, then
+ validated writes. Any validation failure falls back to the agentic loop. A retried job that
+ already wrote finalizes from the ledger instead of calling the model again.
+- The aggregator (`handlers/subagent-aggregator.ts`) does deterministic string concatenation of
+ `child_done` rows (v0.15 header). It does not call a model.
+
+## Rust engine implications
+
+Must preserve exactly:
+- Claim semantics: one atomic transition from `waiting` to `active` in priority then FIFO order,
+ with a worker-chosen fence token. Every later write must check the token. This is what makes
+ a dead worker's job recoverable without duplicate completion.
+- Lease math: `lock_until` versus stall grace (15 s), renewal at `min(lock/2, 60 s)`, the
+ [5 s, 1 h] clamp on row and map values, `max_stalled` default 5, and `attempts_started` ≥
+ `attempts_made`.
+- Idempotency: the unique key over non-null values, dead and cancelled rows releasing their key,
+ and the `coalesced` return.
+- Parent/child: `waiting-children` flip, `child_done` inbox messages, and the `on_child_fail`
+ policies.
+- Protected-name policy and the `submission_authority IS NOT NULL` claim gate. These decide who
+ can spend money.
+- Cycle phase order and scope. Freshness subset for per-source jobs.
+
+Can simplify:
+- LISTEN/NOTIFY and the `sync` special case: an in-process channel that wakes on any commit
+ that makes a job claimable. Keep a short poll as a backstop.
+- Advisory locks: one process owns the queue, so admission, quota, and budget can run under one
+ write lock. Only the keyed locks matter if multiple processes write.
+- Row-table cycle lock: an OS file lock or the same DB transaction plus TTL.
+- Dream-inline private queues: an in-process task set scoped to a phase run.
+- `minion_inbox` and `minion_attachments` as plain tables with BLOB content.
+
+Postgres feature to replace, and how:
+| Feature | Used for | Rust replacement |
+|---|---|---|
+| `FOR UPDATE SKIP LOCKED` | claim, stall, timeout, watchdog | `BEGIN IMMEDIATE` (SQLite) or single writer thread |
+| `pg_notify` trigger | wake | post-commit broadcast channel |
+| `pg_advisory_xact_lock` | admission, quota, rate, budget | per-key `Mutex` map, or the write transaction |
+| `ON CONFLICT ... WHERE` | idempotency | `INSERT ... ON CONFLICT` (SQLite upsert with partial index) |
+| JSONB `data->>` | param hash, source id | JSON1 functions or extracted columns |
+| `now() + interval` | leases, delays, TTL | integer epoch ms; compare with one clock source |
+| `FOR UPDATE` on parent | max_children, roll-up | serialized writes under the same transaction |
+| `SERIAL`, `BYTEA`, `TIMESTAMPTZ` | ids, attachments, times | `INTEGER PRIMARY KEY`, `BLOB`, integer ms |
+
+Risks:
+- Wall-clock leases. Clock skew between processes breaks stall and lock math. Use one clock owner
+ or allow one process only.
+- Multi-process workers. The TS design runs several `jobs work` children under a supervisor. Keep
+ that topology only if the Rust engine needs cross-process locking.
+- Long LLM calls hold leases for minutes. The renewal task must never block on the work it guards.
+- Test surface: about 7,800 lines of handler code plus the 2,574-line queue and 1,792-line worker
+ need equivalence tests. Several behaviors are pinned by tests in the reference repo, not by
+ types.
+- Stale comments in the reference repo (Open questions, item 6) could mislead a port.
+
+## Open questions
+
+1. Must the Rust queue support several worker processes at once? This decides whether the queue
+ needs cross-process locks and whether leases can use wall-clock time.
+2. Should v1 port all 42 handlers, or only the four minimum handlers plus the autopilot scheduler?
+ The 15 paid handlers need a chat and embedding provider layer that is a separate research thread.
+3. Keep `consolidate` as a protected name? Its phase is deterministic, and the protection may be
+ out of date.
+4. Keep `shell` at all? It is an arbitrary-command runner gated by an env flag.
+5. Keep the autopilot health-score interval rules (sections 5 and 6)? They are policy, and no
+ test pins them here.
+6. Stale or contradictory comments found in the reference, to confirm before porting:
+ - `handler-timeouts.ts` says the DB CHECK only enforces `> 0`. The schema enforces
+ `5000 <= lock_duration_ms <= 3600000` (`schema.sql:1301`).
+ - `cycle.ts:170` and `cycle.ts:2671` say `consolidate` uses a Sonnet rewrite. The phase is
+ deterministic in `phases/consolidate.ts:11-12`.
+ - `autopilot.ts:8` says restart with 10 s backoff. The code uses 1 s doubling to 60 s
+ (`supervisor.ts:245`).
+ - Worker option `maxStalledCount` (default 1, `types.ts:228`, `worker.ts:309`) is set but not
+ read anywhere in `src/core/minions`. The effective limit is the row column.
+7. Which handlers that import the gateway (`import`, `ingest_capture`, `loops_extract`,
+ `connector-sync`, `doctor-refresh`) make paid calls in practice? Verified only by names and
+ imports here.
diff --git a/docs/designs/rust-engine/research/08-concurrency-and-persistence.md b/docs/designs/rust-engine/research/08-concurrency-and-persistence.md
new file mode 100644
index 0000000000..8ffc9e9599
--- /dev/null
+++ b/docs/designs/rust-engine/research/08-concurrency-and-persistence.md
@@ -0,0 +1,230 @@
+# 08 Concurrency, persistence ownership and process model
+
+Line numbers refer to gbrain 36bd05806a.
+
+Reference: garrytan/gbrain v0.60.733.0 (read-only). All paths below are relative to that repo unless marked otherwise.
+
+Evidence tags: **[V]** verified by reading the code or spec named. **[D]** stated in a design or guide doc, not checked against code. **[I]** my inference.
+
+Path correction: the brief names `src/mcp/local-client.ts`. That file does not exist. The engine-free CLI router is `src/core/persistence/local-client.ts`, and the owner socket is `src/core/persistence/ipc.ts`. `src/mcp/` holds only server and transport code. [V]
+
+## 1. Why the persistence layer is so large
+
+The layer is not mainly about Postgres locking. It defends against a structural problem: **agent memory has two copies of record (Markdown files in a Git checkout and database rows), and many uncoordinated writers touch both.** [D] `docs/designs/DATABASE_CANONICAL_MEMORY.md` ("Why it matters") says each incident got a local fix (a guard, a hold kind, a provenance selector, a repair verb). The result was a hold vocabulary of 66 decision-table rows (`docs/guides/sync-unblock-runbook.md:121-189`), a writer census of about 300 rows (`docs/architecture/canonical-writers.tsv`, 306 lines [V]), and a managed sync that grew from 29 files and about 9,000 lines to 65 files and about 18,400 lines in one week in October. The Git-canonical design (`docs/designs/GIT_CANONICAL_MEMORY.md`, "Decision") chose git as the parent: the file is written, committed under the checkout's writer lock, and only then does the row commit. [D]
+
+The concrete failure modes the code defends against (each cited in the docs and mostly traceable in code):
+
+| Failure mode | Defense | Where |
+| --- | --- | --- |
+| A write meets a refresh and is lost or refused | Refresh write barrier: writes admitted during a refresh wait as `deferred` and replay after release | `src/core/persistence/refresh-barrier.ts:1-12`, `journal.ts:648-650`, `docs/designs/REFRESH_WRITE_BARRIER.md:14-18` [V/D] |
+| Process killed mid-write leaves a head claim that blocks the queue | Claim lease with `claim_expires_at`, `execution_token`, owner-death checks; head clears by itself | `claim-lease.ts`, `claim-phase.ts`, `docs/guides/troubleshooting.md:128` [V/D] |
+| Crash between file rename and DB commit | Durable file recovery record written before the rename; `recovering` state | `coordinator.ts:440-470` (`pageRecoveryRecord`), `coordinator.ts:486` (`publishMutation`) [V] |
+| Two processes drain the same source | Drain lease with fencing token; every fenced transaction checks the token | `sync-lease.ts:46-50`, `sync-lease.ts:88`, `db-lock.ts:225` [V] |
+| Owner host moved or restarted with a new identity | Writes queue for the owner; stale-owner diagnostic | `docs/guides/troubleshooting.md:219` [D] |
+| Stale grants replayed after waiting | Authority re-checked at publication and replay | `authority.ts`, `docs/architecture/key-files/core-persistence.md` [D/V] |
+| Admin or migration while writers run | Brain-level writer admin lock and activation flow | `admin-lock.ts`, `activation.ts`, `deactivation.ts` [D] |
+| Non-managed writers (cron, hooks, humans) bypass the writer lock | Trigger guard on ten tables when managed mode is on; `commit-push` takes the same lock | `schema.sql` (`gbrain_require_managed_writer`, around line 2620-2640) [V]; `src/commands/git.ts:36-41` [V] |
+
+Size by file family (line counts of `src/core/persistence/*.ts`, 353 files, 83,826 lines [V]):
+
+| Family | Files | Lines |
+| --- | --- | --- |
+| `sync-*` (managed sync passes, drain, holds, discovery, status) | 67 | 19,588 |
+| `graduation*` (engine graduation, migration custody) | 13 | 5,023 |
+| `effect*` (post-commit effect journal and runner) | 13 | 4,016 |
+| `git*` plus `effect-git.ts` (Git door, durability, push holds) | 9 | 3,961 |
+| `topology*` plus `worktree*` | 13 | 3,044 |
+| `connector*` | 13 | 2,620 |
+
+## 2. Process model
+
+There is one brain, many possible processes. The rules:
+
+- **Process kinds.** `src/core/direct-pool-profile.ts:3-7` defines three roles: `resident` (serve, jobs, autopilot, sync --watch keep the full pool), `short_lived` (a command that owns a consumer or takes a lease gets one connection), and `one_shot` (takes no lease). [V]
+- **One full consumer per host.** `src/core/persistence/consumer-election.ts:1-20` describes the election. A resident process checks whether a live full consumer already runs on this host. If so it becomes `waiter_only`: it claims nothing, writes no heartbeat, and its writes are published by the owner and reach it through receipt polls. Modes: `probing` to `full` or `waiter_only`, then `promoted`. Constants: `DRAIN_BACK_HEALTHY_TICKS = 3` (line 55), `PROBE_TIMEOUT_MISSES = 3` (line 57). The class is `WaiterOnlyConsumer` (line 107); the real consumer is `PersistenceConsumer` (`consumer.ts:166`). [V]
+- **Heartbeat table.** `persistence_consumers` (`src/schema.sql:2500`) has primary key `(host_id, pid, nonce)` and records `mode`, `pid_ns`, `boot_id`, `process_start`, `restart_required`, and the pool stats. Timings from `consumer-heartbeat.ts:41-49`: live within 30 s, lapsed at 60 s, purged at 90 s, renewed every 10 s, 5 s renewal deadline. A renewal also deletes this host's rows lapsed longer than 90 s. PGLite admits one process, so the probe reports "no owner" and nothing is written there. [V]
+- **Owner IPC socket.** `src/core/context/resolve-ipc.ts:402-408`: on PGLite the socket is `<dataDir>/.gbrain-persistence.sock`. On Postgres it is `<configDir>/run/persistence-<sha256(database_url)[0:12]>.sock`, so the URL's credentials never appear in the path. [V] The protocol (`ipc.ts`) is version 1, with a 32 MiB frame cap (`PERSISTENCE_IPC_MAX_BYTES`, line 20) and at most 8 connections (line 21). The operation set has 46 names (lines 22-37): puts, deletes, edits, capture, remember, forget, takes, skills, tags, links, and `get_write_request`/`list_write_requests`/`cancel_write_request`. Three owner-only operations (`purge_fact`, `list_page_purges`, `unpurge_page`, `LOCAL_CLI_OWNER_OPERATIONS`, line 39) run only for the verified local CLI registration. [V]
+- **CLI routing.** `local-client.ts` runs without an engine. It inspects the lock holder with `inspectLockHolder` (from `pglite-lock.ts`) and, if the holder publishes no persistence socket, refuses `owner_unavailable` and names the process. Nothing is sent to it (`local-client.ts:25`, `noDiscoveryPath`). [V]
+- **Exit codes.** `PENDING_WRITE_EXIT_CODE = 10` (`src/core/exit-codes.ts:42`) means "admitted, not yet committed; here is the request id". The CLI waits: `AGENT_WRITE_WAIT_MS = 5_000`, `CLI_WRITE_WAIT_MS = 30_000`, `MAX_WRITE_WAIT_MS = 600_000` (`write-wait.ts:17-20`), and the wire cap is `WIRE_WRITE_WAIT_MAX_MS = 30_000` (`params.ts:51`). [V]
+
+## 3. PGLite single-writer lock
+
+File: `src/core/pglite-lock.ts` (422 lines). PGLite is a single-connection embedded database; this file is the only thing stopping two processes from opening the same data directory. [V]
+
+- **Kernel lock.** `getPgliteKernelLockPath` (line 123) returns `<dataDir>.gbrain-owner.lock`, a stable sibling file that must never be unlinked. It is taken with `tryAcquireNativeLock` (native `flock`, see section 4). The kernel releases it when the process dies. [V]
+- **Metadata is diagnostic only.** The code says the legacy `.gbrain-lock/` directory "is never the ownership authority" (`pglite-lock.ts:58`). Its `lock` file records `pid`, `owner_token`, `protocol`, `pid_ns`, `boot_id`, `argv`, and a `refreshed_at` that a heartbeat rewrites every 30 s (`HEARTBEAT_INTERVAL_MS`, line 12). [V]
+- **Acquire loop.** `acquireLock` (line 319) defaults to a 30 s timeout and polls every 25 ms (`Math.min(25, ...)`, line 378). If a legacy directory exists and the owner cannot be proven dead (no PID, no matching `pid_ns` and `boot_id`, or an unreadable file), it raises `LegacyOwnerUnverifiedError`, which is not retryable. It is tolerated for 1 s (`LEGACY_UNVERIFIED_GRACE_MS`) to cover a legacy writer between `mkdir` and its metadata write. A live PID in the legacy directory raises `busy`. [V]
+- **Error classes.** `PgliteBusyError` (code `pglite_busy`, retryable), with subclasses `LiveServeLockError` and `LegacyOwnerUnverifiedError` (lines 19-55). [V]
+
+## 4. Native locks (`native/locks/`)
+
+- **What it is.** `locks.c` is a first-party C Node-API v3 addon. POSIX uses `flock`, Windows uses `LockFileEx`. The API is `openLock`, a nonblocking `tryLock`, and an idempotent `close`. The kernel releases ownership on process death. [V, `native/locks/README.md:1-9`]
+- **Rules the README sets.** Never unlink, rotate, copy over, or infer ownership from age or metadata of a lock file. Replacing a locked inode can allow two owners. Leaf symlinks, reparse points and nonregular files are refused. There is no TTL, PID or timestamp fallback. A close failure must stop publication. An unavailable addon or OS error yields `writer_lock_unavailable`. [V]
+- **Distribution.** Eight prebuilt addons are checked in, pinned to Zig 0.14.1 with a hash manifest. [V, README]
+- **Wrapper.** `src/core/persistence/native-lock.ts` (`acquireNativeLock` line 160, `tryAcquireNativeLock` line 250). Default deadline 5 s, polling 25 ms, cancellable with an `AbortSignal`. The addon loads only when a caller needs lock capability. [V]
+- **Call sites.** 23 files in `src/core` and `src/commands` call `acquire`/`tryAcquire` [V]. The persistence ones that matter most: per-worktree `binding.coordination_path` (`ownership.ts:218-219`, `:342`, `:402`, `:437`); `topology-locks.ts:48`; `head-blocker.ts:180` (refresh lock); `reconcile-backup.ts:62` (`.capacity.lock`); `identity.ts:221` (registration lock); `commit-push.ts:268-271` (commit and legacy lock). Git commit and push locks are `brain-commit.lock` and a separate push lock under the git dir. [V/D: `behavior-change-notice.ts:495`]
+- **Shell variant.** `src/core/brain-repo-durability.ts:341-343` generates a shell hook that uses `flock -w` on fd 8 and 9, with `GBRAIN_COMMIT_LOCK_WAIT_SECONDS` defaulting to 60 s. So there are two lock implementations for the same commit lock: the native one in TypeScript and the shell one in the installed hook. [V]
+
+## 5. Row locks and the `gbrain_cycle_locks` lease
+
+Table: `src/schema.sql:1516-1528`. Columns: `id TEXT PK`, `holder_pid`, `holder_host`, `acquired_at`, `ttl_expires_at`, `last_refreshed_at`, plus `acquisition_token` added by the lease schema (v152). Index `idx_cycle_locks_ttl`. [V]
+
+- **Generic lock.** `src/core/db-lock.ts` (1,131 lines). `tryAcquireDbLock` (line 229) inserts or takes over. Takeover needs an expired TTL and a `last_refreshed_at` older than the steal grace (`DEFAULT_STEAL_GRACE_SECONDS = 600`, line 95). A same-host dead PID is taken over after `HOLDER_TAKEOVER_GRACE_MS = 60_000` (line 82). Default TTL is 30 minutes (line 73). `withRefreshingLock` (line 972) renews the row. Every acquisition mints a fresh UUID token; refresh, release and cleanup match on `(id, holder_pid, acquisition_token)`. [V]
+- **Lock ids.** `syncLockId(sourceId)` (line 883) and `SYNC_LOCK_ID = syncLockId('default')` (line 891). `buildTenantLockId` (line 1119). The cycle lock is a separate id so the sync write window can nest under it. [V]
+- **Fence.** `fenceLockRow` (line 225) runs `SELECT 1 FROM gbrain_cycle_locks WHERE id=$1 AND acquisition_token=$2 AND ttl_expires_at > now() FOR KEY SHARE`. `FOR KEY SHARE` conflicts only with key writes and `DELETE`, so a renewal (which writes no key) still lands while a fenced transaction is open. The TLA+ README documents why `FOR SHARE` was wrong (#7442). [V]
+- **Drain lease for sync.** `src/core/persistence/sync-lease.ts`. `DRAIN_LEASE_TTL_MINUTES = 2` (line 46), `DRAIN_LEASE_REFRESH_MS = 20_000` (line 47), `FOLLOW_POLL_MS = 2_000` (line 49), `LEASE_RETRY_AFTER_MS = 60_000` (line 50), `HOLDER_STALL_MS = 5 min` (line 56), `FENCED_SLICE_MS = 5_000` (line 98). `withDrainLease` (line 270). `assertDrainLease` (line 88) runs inside every transaction that admits sync work or swaps the cursor. [V]
+
+## 6. Postgres advisory locks and row-lock clauses
+
+Counts over `src/**/*.ts` excluding generated files [V]:
+
+| Primitive | Call sites | Use |
+| --- | --- | --- |
+| `pg_advisory_xact_lock` | 37 | per-key serialization inside one transaction |
+| `pg_advisory_lock` (session) | 5 | schema init, `db.ts:600` and `init-schema-lock.ts` |
+| `pg_advisory_unlock` | 2 | pairs with the above |
+| `pg_advisory_xact_lock_shared` | 1 | derivation scope read lock (`page-body/schema.ts:279`) |
+
+Files: 27. Notable keys:
+
+- Schema init: `INIT_SCHEMA_LOCK_KEY = 42` (`src/core/postgres-engine/init-schema-lock.ts:29`). It is a session lock with a fallback when the pool has one connection (line 220). `db.ts:600` uses the same key as a session lock with a comment saying it is brain-global. [V]
+- Minion admission and quota: `queue.ts:385, 431, 460-488` (keys hashed from `minion_admission`, `minion_quota`, `minion_maxwaiting`). Budget meter: `budget-meter.ts:99, 255`. These belong to the jobs topic (r07). [V]
+- Facts per entity: `engine-sql/facts.ts:122, 151` (`hashtextextended(source_id||':'||entity)`). Page body chunks: `engine-sql/page-body.ts:197`. Generations: `generations/fence.ts:128`, `generations/publish.ts:71`. Chronicle reservation: `chronicle/ledger.ts:97`. Mentions: `mentions/pass.ts:481`. Writeback settings: `facts/writeback-settings.ts:122`. [V]
+- PGLite opt-out: `engine-sql/executor.ts:63-68` has a capability flag `transactionAdvisoryLocks`. PGLite "is a single-connection embedded database and never needed one". [V]
+
+Row-lock clauses: about 385 source lines match `FOR UPDATE`, `FOR KEY SHARE`, `FOR SHARE`, `FOR NO KEY UPDATE`, or `SKIP LOCKED` across `src` (including comments). In the persistence layer, `SKIP LOCKED` is used for the claim queue: `journal.ts:856` (`claimNextWrite`, `LIMIT 1 FOR UPDATE OF r SKIP LOCKED`), `journal.ts:909`, `consumer.ts:719` (100-row batch), `effect-journal.ts:167, 237, 276` (effect claims), `embedding-noop-settle.ts:77`, and `consumer-heartbeat.ts:297` (worktree sweep). [V]
+
+A comment in `src/core/db-lock.ts:8-9` says `pg_advisory_xact_lock` "is session-scoped" and that this is why the row lock is used. That is imprecise. Transaction-level advisory locks end with their transaction and do survive transaction-mode poolers; it is session-level `pg_advisory_lock` (used for schema init) that does not. [I]
+
+## 7. The write path: journal, claim, publish, effects
+
+Key tables (`src/schema.sql`, 14 `persistence_*` tables plus `op_checkpoints`, `gbrain_cycle_locks`, `page_generation_clock`) [V]:
+
+| Table (schema.sql line) | Role |
+| --- | --- |
+| `persistence_brain` (2402) | singleton: `enabled`, `brain_id`, `activated_at` |
+| `persistence_worktrees` (2409) | checkout: `owner_host_id`, `owner_epoch`, `topology_generation`, `state` (active, draining, recovering), `heartbeat_at` |
+| `persistence_source_bindings` (2419) | `source_id` to worktree and `relative_path` |
+| `persistence_host_bindings` (2426) | per host: `local_path`, `coordination_path`, `git_durability` |
+| `persistence_local_writers` (2434) | CLI and stdio credentials with `grant_ceiling` |
+| `persistence_counters` (2442) | outstanding counts and byte budgets, locked `FOR UPDATE` at `journal.ts:243` |
+| `persistence_requests` (2450) | the journal: `principal`, `request_id`, `sequence bigserial`, `state`, `execution_token`, `claim_expires_at`, `recovery`, `outcome`, `intent jsonb`, `UNIQUE(principal_kind, principal_id, request_id)` |
+| `persistence_effects` (2489) | post-commit effects: `kind`, `state` (queued, running, committed, failed), `UNIQUE(request_id, kind)` |
+| `persistence_consumers` (2500) | heartbeat rows |
+| `persistence_topology_changes` (2771), `persistence_worktree_refreshes` (2795), `persistence_writer_protocols` (2943) | topology, refresh barrier, protocol version |
+
+Request states: `queued, running, recovering, committed, conflict, failed, cancelled` (`schema.sql:2466`). [V]
+
+Admission: `admitWrite` (`journal.ts:289`) and `admitWriteInTransaction` (303). It locks the counters, checks caps, and inserts the row. Default caps (`src/core/persistence/model.ts:203-210`): 100 outstanding per principal, 1,000 per brain, 64 MiB intent bytes per principal, 256 MiB per brain, 1 GiB recovery bytes per brain, 256 MiB per worktree. Lifetime and terminal caps are off (`Infinity`) until configured. [V]
+
+Claim: `claimableWriteSql` (`journal.ts:751`) is a predicate: the row is `queued` or released from a refresh barrier, and its worktree is owned by this host and `active`. Ordering is `CLAIM_ORDER` (line 770): foreground priority first, then `sequence`. A claim sets `execution_token` and `claim_expires_at` (default lease 30 s, `claimNextWrite` line 840). Renewal is `claim-lease.ts:49` (`startClaimLease`). [V]
+
+Transient retries (`transient-retry.ts:33-35, 43`): statement cancel (57014), stale plan (0A000), or publication ceiling reached. Backoff 1 s, 2 s, 4 s, 8 s, then 15 s. Default maximum 5 retries (`persistence.max_transient_retries`). The retry does not count as a preparation attempt. [V/D]
+
+Preparation budgets (`preparation-budget.ts`, `DEFAULT_PREPARATION_POLICY`): sync 120 s, maintenance 120 s, ceiling 600 s, 2 attempts. [V]
+
+Publication (`coordinator.ts:486`, `publishMutation`): (1) a durable recovery record with the before and after hashes, (2) the file is staged and renamed into place, (3) one database transaction writes the row and the receipt, (4) effects are queued. `publishGroup` (`group-publish.ts:251`) does the same for batches. Every publication transaction opens with `declareDurablePersistence` (`protocol.ts:39`): `lock_timeout = 1s`, `statement_timeout = 5s` as transaction-local `set_config`, and `synchronous_commit = on`. A publication also sets `idle_in_transaction_session_timeout` to the publication ceiling (`publication-deadline.ts:27-31`: default 5 min, grace 30 s). [V]
+
+Git door: when `config.canonical = "git"`, `git-door.ts` commits the published files with plumbing (`hash-object -w`, `commit-tree`, `update-ref <branch> <new> <old>`), and the branch moves only if it still names the HEAD the commit was built on. [V]
+
+Effects: `EffectKind = 'git' | 'embedding' | 'withdrawal-mirror' | 'facts-backstop' | 'links'` (`effect-model.ts:6`). `PARK_AFTER_FAILURES = 5` (line 70). The runner is `runPersistenceEffects` (`effects.ts:813`). Git effects only push: they read the remote tip, scan `<tip>..HEAD`, and push fast-forward with a lease (`effect-git.ts`, `pushGitRoot`). [V]
+
+Database-side guards: when managed mode is on, `gbrain_require_managed_writer()` is a `BEFORE INSERT OR UPDATE OR DELETE` trigger on `pages`, `tags`, `slug_aliases`, `page_aliases`, `facts`, `takes`, `timeline_entries`, `sources`, `page_segment_texts`, `page_body_manifest` (`schema.sql` around 2620-2640). Missing state rows are treated as "unreadable", never as unmanaged. Protocol triggers: `gbrain_request_protocol` (2997), `gbrain_effect_protocol` (3009), `gbrain_protocol_activation` (3036). The file has 26 `CREATE TRIGGER` statements and 32 `ENABLE ROW LEVEL` or `CREATE POLICY` lines. [V]
+
+## 8. Thin client
+
+`docs/architecture/thin-client.md` [D, verified in parts]: a thin install (`gbrain init --mcp-only`) never opens a local PGLite file. All operations route to a remote `gbrain serve --http` through `src/core/mcp-client.ts` (`callRemoteTool`). The routing seam is `runThinClientRouted` in `src/cli.ts`, which runs before `connectEngine`. Local-only commands refuse with a hint table (`THIN_CLIENT_REFUSE_HINTS`). [V on names; D on behavior]
+
+A thin-client write is an ordinary remote journal request. For a `canonical: git` source, the owner commits to Git before the row. While the owner is down the call ends `write_pending` (exit 10) with its request id, and `gbrain write-request <id>` follows it. Nothing is written to the database first. [D]
+
+## 9. Postgres connection policy, PgBouncer, pools
+
+- **Prepared statements.** `resolvePrepare` (`src/core/db.ts:91-110`): `GBRAIN_PREPARE` env wins, then `?prepare=` on the URL, then auto-detect: port 6543 means `prepare: false`. Otherwise postgres.js default. [V]
+- **Pool size.** `resolvePoolSize` (`db.ts:246`) reads an explicit value, then `GBRAIN_POOL_SIZE`, then a fallback of 10. [V]
+- **Timeouts.** `statement_timeout` default `5min` (`GBRAIN_STATEMENT_TIMEOUT`), `idle_in_transaction_session_timeout` default `5min` (`GBRAIN_IDLE_TX_TIMEOUT`), both sent as connection startup parameters (`db.ts:346-347, 453-454`). [V]
+- **Transaction-mode poolers drop startup parameters.** The comment at `db.ts:319-340` and `troubleshooting.md:197` say PgBouncer and Supavisor drop them, so an autocommit statement has no server-side bound. Persistence works around this by setting transaction-local `set_config` values inside each transaction (`protocol.ts:39-46`), and the managed write preparation runs under a transaction-local `statement_timeout` (troubleshooting.md:197, #6278). [V/D]
+- **Dual pool.** `src/core/connection-manager.ts:1-40` (header comment): a read pool on the pooler URL and a direct pool for DDL and bulk work, with sizes and timeouts given in the comment. The direct URL is `GBRAIN_DIRECT_DATABASE_URL` or derived from a known Supabase pooler; `GBRAIN_DISABLE_DIRECT_POOL=1` is the kill switch. [D: the header comment, not re-checked in code]
+- **LISTEN/NOTIFY.** Used only by `src/core/minions/sync-queue-wake.ts`: `LISTEN` on the `minion_jobs` channel, and only on a detected direct session. Behind a transaction pooler it polls every 1 s instead. The persistence consumer does not use LISTEN; it uses heartbeat rows and short polls. [V]
+
+## 10. Brains, sources, mounts, and the shared checkout
+
+From `docs/architecture/brains-and-sources.md` [D] and code [V]:
+
+- **Brain** = one database (PGLite file or Postgres). Its lock is one data directory (PGLite) or one database URL (Postgres socket hash). Brains are enumerated by host config and `~/.gbrain/mounts.json` (`src/core/brain-registry.ts`, `mountsPath` line 48). `persistenceConfigForBrain` (`local-client.ts:33-52`) resolves `--brain` to a mounted engine before any host lock or socket is inspected. [V]
+- **Source** = a named repo (checkout) inside one brain. Rows: `sources`, `persistence_source_bindings`, `persistence_worktrees`. Slugs are unique per source. [V/D]
+- **Owner.** Each managed worktree has an owner host (`persistence_worktrees.owner_host_id`, `owner_epoch`). Host identity is `host.json` (`identity.ts`, `hostIdFor`). Only the owner publishes. A copy of the brain on another machine gets a new identity and its writes queue (`owner_unavailable`). [V/D]
+- **Git rules for a shared checkout.** `gbrain git commit-push` takes a short commit lock and a separate push lock per checkout. It does not rebase, stash or reset the working tree. Remote commits merge in memory. Push is fast-forward only (`src/commands/git.ts:36-41`). Writers outside gbrain (cron, scripts) must use this command or they become drift holds. [V/D]
+
+## 11. TLA+ models (`spec/tla/`)
+
+Two specs, checked with TLC, run by `bun run test:tla` (`spec/tla/README.md:1-30`). [V]
+
+| Spec | Files | What it models | Mutants |
+| --- | --- | --- | --- |
+| `drain-lease/DrainLease.tla` (344 lines) | 4 `.cfg` (main, safety with all adverse assumptions, stamp fence, nightly lanes) | one drainer per source; fencing token; renewal; crash; sleep | 14 (README table) |
+| `refresh-barrier/RefreshBarrier.tla` (884 lines) | 11 `.cfg` | one worktree, one page, writes, one refresh at a time, a foreign commit, a crash at any step, Postgres row-lock modes | about 22 entries in `mutants.json` (approximate: counted by key) |
+
+Safety properties include: `FencedTxnsMatchRow`, `OneDrainer`, `CursorMonotone`, `NoSpuriousLapse` (drain lease); `NoDeadlock`, `AppliedAtMostOnce`, `EveryEndNamed`, `DeferredWaitsForRelease`, `RefreshChangeNeverOverwritten`, `RecoveryOnlyByPolicy`, `NoApplyAfterRevoke`, `CommitsInAdmissionOrder` (refresh barrier). Liveness: `DeferredLeaves`, `EveryWriteEnds`. [V]
+
+Bugs the models found and the code fixed: #7442 (fenced transactions unbounded under the renewal timeout; fixed by `FOR KEY SHARE`), and GST-1853 (writes held behind an aborted refresh; fixed by running the owed managed sync on the way out). [D: README, verified in code by the cited symbols]
+
+Not modeled: PGLite (one connection), side effects outside the database, multiple worktrees or pages at once, older binaries that take no lock. [V/D]
+
+Crash robot: `scripts/persistence/README.md` describes a gate with 1,000 seeded schedules, eight SIGKILL boundaries, and 10,000 logical writes from four producer processes, on both engines. [V]
+
+## Rust engine implications
+
+**Must preserve exactly**
+
+- Single owner per brain data directory, with kernel-released ownership and no TTL takeover of the lock file itself. The lock file is never unlinked. Metadata is diagnostic only.
+- A durable journal row per write, with `(principal_kind, principal_id, request_id)` as the idempotency key and a monotone `sequence` (bigserial) that orders claims. Replays return the same outcome.
+- Recovery record written before any file rename; committed state reachable after SIGKILL at any boundary.
+- Fencing for any long-running work that could overlap a takeover: every commit checks token and expiry in the same transaction that writes.
+- Git ref updates are compare-and-swap on the old HEAD. A moved branch means re-read and rebuild, never force.
+- The exit-10 contract: an admitted write that has not committed returns a request id, and the request can be followed later.
+- Authority is rechecked at publication and at replay, not only at admission.
+- The refresh barrier semantics (defer, do not refuse; never overwrite a file the refresh changed). The TLA+ properties should be kept as tests.
+
+**Can be simplified**
+
+- In a single-process embedded Rust brain, the whole consumer election, waiter-only mode, heartbeat table, promotion and drain-back logic is needed only for multiple processes on one host. If the design is one owner process plus a local socket for CLI callers, most of `consumer-election.ts`, `consumer-heartbeat.ts`, `consumer-lane.ts`, and the `persistence_consumers` table go away.
+- The PGLite-versus-Postgres split disappears. One lock mechanism (`flock` or `LockFileEx`) covers the brain. The legacy `.gbrain-lock/` handling (`pglite-lock.ts`, 422 lines, plus `pglite-legacy-lock.ts` and the `pglite-repair` path) is not needed for a new format.
+- Advisory locks (42 call sites) become in-process mutexes or single-writer transactions. `FOR KEY SHARE` fencing is not needed if there is one writer. `SKIP LOCKED` queues become a single claim loop.
+- PgBouncer, dual pools, prepared-statement detection, `set_config` transaction-local timeouts, and LISTEN fallbacks all go away.
+- Statement and idle-transaction timeouts become per-operation deadlines in the process (the publication ceiling of 5 min, the preparation budgets of 120 s and 600 s, the 5 s renewal deadline).
+- The ten-table managed-writer trigger becomes a type-level or API-level rule: only the owner's write API can mutate page state.
+
+**Postgres feature each piece depends on (what Rust replaces it with)**
+
+| Piece | Postgres feature today | Rust substitute |
+| --- | --- | --- |
+| Write queue claim | `FOR UPDATE SKIP LOCKED`, `claim_expires_at` | single claim loop over an ordered table or log; lease in memory plus a durable claim record |
+| Counters and caps | `FOR UPDATE` on `persistence_counters` | in-process counters rebuilt from the journal at open |
+| Drain or sync lease | `gbrain_cycle_locks`, `FOR KEY SHARE`, `ON CONFLICT ... WHERE` | `flock` on the data directory plus a fenced write token if multi-process is kept |
+| Schema init lock | `pg_advisory_lock(42)` | file lock during open |
+| Per-key serialization | `pg_advisory_xact_lock(hashtext(...))` | per-key mutex map |
+| Post-commit effects | `persistence_effects` with `UNIQUE(request_id, kind)` | same table in the embedded store, same unique key |
+| Notifications | `LISTEN/NOTIFY` (minion queue only) | channel or condvar |
+| Timeouts | `set_config(..., true)`, `idle_in_transaction_session_timeout` | per-operation deadline objects |
+| Trigger guard | `gbrain_require_managed_writer` | Rust API visibility (only the owner module can call the mutating functions) |
+| Recovery records | JSON in `persistence_requests.recovery` | same, in the embedded store |
+
+**Risks**
+
+- Multi-process access is a real requirement today: `serve`, `jobs`, `sync --watch`, and CLI calls run at the same time against one brain. If the Rust engine keeps that, it needs the socket protocol and the owner election. Dropping it changes the operator model.
+- Network filesystems and `flock`: the native lock README says cross-process semantics are a host prerequisite. A Rust `fs2` or `flock` binding has the same limit; Windows `LockFileEx` behaves differently on abandoned handles.
+- PID reuse and stale-owner detection: the TypeScript code uses `pid_ns`, `boot_id`, and process start time. Rust needs the same, or accepts that a dead owner is found only by the kernel lock.
+- Git interop: external writers (cron, hooks, humans) still commit to the checkout. The Rust design must keep the commit-lock contract, or it reproduces drift holds.
+- Two copies of record: if the design is git-canonical, the file and row coordination (recovery records, git door, holds) remains the bulk of the code. If it is database-canonical, much of it goes away, but the export and import lanes take its place.
+- Compatibility: `write_pending` exit code 10, `owner_unavailable`, and the receipt schema are visible to agents and scripts. Changing them needs a mapping.
+
+## Open questions
+
+1. Does the Rust engine need several processes to write the same brain (CLI plus server), or is one owner process with a local socket enough? This decides whether sections 2, 5 and 7 shrink by most of their code.
+2. Is the Rust target git-canonical (files are truth, the database is an index) or database-canonical? The persistence layer's size mostly follows from this choice.
+3. Which of the 14 `persistence_*` tables and the 26 triggers are kept, and which become in-memory state rebuilt on open?
+4. Are the TLA+ specs ported as-is for the Rust protocol? They are language-neutral, and they are the best record of the race conditions.
+5. Is the thin-client remote MCP path in scope for the first Rust release? It is the largest source of the `write_pending` contract.
+6. Target platforms: does Windows need `LockFileEx` parity in v1, or is POSIX `flock` enough for the first milestone?
+7. Should `gbrain git commit-push` and the shell hook lock be replaced by one Rust implementation, and who owns the installed hook after migration?
+8. How many held-state kinds (the 66-row decision table) must the Rust engine reproduce, and which can be dropped because the single-owner model cannot produce them?
diff --git a/docs/designs/rust-engine/research/09-access-and-security.md b/docs/designs/rust-engine/research/09-access-and-security.md
new file mode 100644
index 0000000000..980fe3372c
--- /dev/null
+++ b/docs/designs/rust-engine/research/09-access-and-security.md
@@ -0,0 +1,236 @@
+# 09. Trust, auth and access control
+
+Line numbers refer to gbrain 36bd05806a.
+
+Map of how TypeScript gbrain (v0.60.733.0, commit 36bd05806a, `garrytan/gbrain`) decides who may read or write what, and which of those decisions Postgres enforces today. Paths are relative to the gbrain repo unless noted. Read-only research.
+
+Legend: **[V]** verified by reading the cited code. **[I]** inferred or only partly traced.
+
+## 1. Trust boundary: `OperationContext.remote`
+
+- **[V]** `remote: boolean` is required on `OperationContext` (`src/core/ops/contract.ts:477-502`). True for MCP and agent callers, false for the local CLI.
+- **[V]** Trusted callers set `remote: false`: CLI main (`src/cli/main.ts:1456`), the warm CLI socket (`src/core/cli-socket/execute.ts:67`), sweep (`src/core/sweep.ts:922`), oversized backfill (`src/core/oversized-backfill.ts:136`).
+- **[V]** Untrusted callers set `remote: true`: stdio MCP (`src/mcp/server.ts:423`, `:496`), HTTP transport (`src/mcp/http-transport.ts:568`), enforced-member mode (`src/cli/enforced-member.ts:321`).
+- **[V]** Fail-closed is by convention, not by type. Trusted-only sites test `ctx.remote === false`; untrust-unless-explicit sites test `ctx.remote !== false` (`src/core/verbs.ts:288`, `:304`, `:384`; `src/core/ops/files.ts:85`). `CLAUDE.md:55-57` says "Don't default it falsy."
+- **[V]** Transport is separate from trust. Stdio is `remote: true` even with no auth (`contract.ts:511-519`).
+
+## 2. Source isolation
+
+- **[V]** `sourceScopeOpts(ctx)` (`src/core/ops/context.ts:646-668`) is the one precedence ladder: `ctx.auth.allowedSources` (non-empty federated grant) > `ctx.sourceId` > nothing.
+- **[V]** An empty `allowedSources: []` does not widen. `__all__` spans every source only when `ctx.remote === false` (`context.ts:660-666`). For remote callers the literal matches nothing. A remote caller with no grant gets `permission_denied` (`context.ts:662-664`).
+- **[V]** `assertSourceInCallerScope` (`context.ts:681`) confines a named `source_id` to the same ladder for untrusted callers and answers `not_found` for out-of-scope ids. `assertSourceInCallerWriteScope` (`:712`) is stricter, for destructive ops.
+- **[V]** `CLAUDE.md:58-68` requires every read op to route through `sourceScopeOpts`. `scripts/check-getpage-scoped-write.mjs` guards the read-then-write pattern. This is a script check, not a DB constraint.
+- **[V]** `parseLegacyTokenScope` (`src/core/legacy-token-scope.ts`) maps a stored grant to `{sourceId, allowedSources}`. An empty array becomes the `NO_SOURCES` sentinel. Missing or malformed values fall back to `'default'`. It never widens.
+- **[V]** Search adds a second filter, `buildVisibilityClause` (`src/core/search/sql-ranking.ts:176`). The RLS scope binding (section 5.1) is opt-in and documented as "defense-in-depth layer 2"; the app filter is layer 1 and mandatory (`src/core/postgres-engine.ts:~335-340`).
+
+## 3. Credentials
+
+### 3.1 Legacy bearer tokens (`access_tokens`)
+
+- **[V]** `src/schema.sql:735-748`: `id UUID`, `name`, `token_hash TEXT UNIQUE`, `scopes TEXT[]`, `created_at`, `last_used_at`, `revoked_at`; partial index on `token_hash WHERE revoked_at IS NULL`. Later migrations add `member_id` and `may_act_for` (v282, `src/core/schema-migrations/v282-member-read-access.ts:29-30`), the unified grant columns and a `permissions` JSONB mirror (`src/core/token-mint.ts:1-20`), `attest_sources` (v293, per `docs/architecture/key-files/access.md`) and `reads_unscoped` (read in `src/core/access/token-binding.ts`).
+- **[V]** `generateToken(prefix)` = prefix + 32 random bytes hex (`src/core/utils.ts:22-24`). `hashToken` = plain SHA-256 hex, no salt or pepper (`utils.ts:15-17`). Plaintext is shown once (`SECURITY.md:430-435`).
+- **[V]** `Authorization: Bearer` is required on every request except `/health` (`src/mcp/http-transport.ts:292`).
+- **[V]** Revoke sets `revoked_at`. Rotation is mint first, then revoke the old token by id (`src/core/token-mint.ts:14-17`).
+- **[V]** Grant moves in `src/core/grants/legacy-token.ts` take row locks (`FOR UPDATE` at `:233-234`, `:338`) and `FOR UPDATE SKIP LOCKED` in the backfill (`:380`, `:402-405`).
+
+### 3.2 OAuth 2.1 (`oauth_clients`, `oauth_tokens`, `oauth_codes`)
+
+- **[V]** `oauth_clients` (`src/schema.sql:765-810`): `client_secret_hash`, `scope`, `source_id REFERENCES sources(id) ON DELETE RESTRICT`, `federated_read TEXT[]`, `member_id`, `may_act_for`, `token_ttl`, `deleted_at`, `source_grant CHECK (source_grant IN ('none'))`, `takes_holders`, `surface`, `allowed_operations`, `bound_*`, `budget_usd_per_day`.
+- **[V]** `oauth_tokens` (`:838-848`): PK `token_hash`, `client_id ... ON DELETE CASCADE`, `scopes`, `expires_at BIGINT`, `resource`. `oauth_codes` (`:851-862`): PK `code_hash`, `code_challenge`, `code_challenge_method DEFAULT 'S256'`, `redirect_uri`, `expires_at BIGINT NOT NULL`.
+- **[V]** `oauth_grant_audit` (`:813-823`) gets one row per grant revision with `before_grant` and `after_grant` JSONB. The code inserts; I did not check for an append-only guard.
+- **[V]** `verifyAccessToken` (`src/core/oauth-provider.ts:679`) joins `oauth_clients` in one query. It refuses revoked or missing clients (`:814`), and refuses a NULL or past `expires_at` (`:822-823`, fail-closed). It re-intersects issued scopes with the client's current scope on every request (`:816`), so a rescope applies at once.
+- **[V]** Client secrets are compared with `safeHexEqual(secret, hashToken(presented))` (`oauth-provider.ts:1017`, `src/core/timing-safe.ts`). The provider validates S256 PKCE before it consumes a code (`:573`, `:641-649`). Expired rows are swept (`:1035-1045`).
+- **[V]** `/authorize` never mints a code by itself. It records a pending request, which expires after 10 minutes, does not survive restart, and is capped server-wide and at 10 per client. Only the owner's approval in the admin dashboard mints a code (`SECURITY.md:394-415`). Admin routes are `requireAdmin`-gated (`src/commands/serve-http-access.ts:19-67`).
+
+### 3.3 Scopes
+
+- **[V]** `Scope` union (`src/core/scope.ts:25`): `read`, `write`, `admin`, `sources_admin`, `users_admin`, `agent`, `skill_editor`, `skill_publisher`, `skills_member_self`, `memory_confirm`.
+- **[V]** Implications (`scope.ts:163-168`): `admin` implies `sources_admin`, `users_admin`, `write`, `read`. `write` implies `read`. The rest imply only themselves. `agent` is never implied by `admin`.
+- **[V]** DCR ceilings: self-registration may hold `read write` (`DCR_REGISTRABLE_SCOPES`, `scope.ts:65`). DCR `client_credentials` is capped at `read` (`:72`). `memory_confirm` is local-CLI-only (`:82`). `agent` needs an operator grant with delegation bindings (`dcrScopeViolation`, `:98-100`). DCR is off by default (`SECURITY.md:258-265`).
+
+## 4. Per-page and per-member access
+
+### 4.1 Model
+
+- **[V]** Model C (`docs/tutorials/company-brain.md:114-160`): one source; tokens and OAuth clients bind to a member; pages name readers in frontmatter, e.g. `readable_by: [alice-example, group:team-a]`. Folder and page rules live in `gbrain access rule` (preview, then `--yes`) and in `.gbrain/access.yml` on git-backed sources.
+- **[V]** Tables from v282, v283, v286, v299, v309: `access_members` (id regex `^[a-z0-9][a-z0-9._-]{0,63}$`, `disabled_at`, `tombstoned_at`), `access_groups`, `access_group_members` (cascade), `access_rules`, `access_policy_state`, `access_policy_revisions`, `access_pending_coverage`, `access_policy_migrations`, `access_member_links`, `access_member_sources`. `pages` gains `page_readers TEXT[]`.
+- **[V]** Member ids are never reused. `removeMember` tombstones and `addMember` refuses a tombstoned id (`src/core/access/members.ts:9`). A credential bound to a disabled or tombstoned member is refused at verify.
+- **[V]** Requester scope (`src/core/access/requester-scope.ts`): on a brain with two or more enabled members, an unbound remote read is refused with `requester_scope_required`. Connections that predate multi-person serving get a 14-day grace. Reads are deny-by-default unless listed.
+- **[V]** Audience members (`kind: audience`, `members.ts:18`) get owner-like reads of their own derived pages. Only the trusted local operator sets the kind.
+
+### 4.2 Enforcement is app SQL, not RLS
+
+- **[V]** `readersAllowedSql` (`src/core/search/private-visibility.ts:171-178`) builds the predicate from `page_readers`, or from `gbrain_access_readers(frontmatter)` for snapshots. `folderRulesAllowedSql` (`:133`) covers folder rules. Identities are inlined as quoted literals after `validIdentity` (`src/core/access/principals.ts:64-66`), which accepts only `ACCESS_ID_RE` (`principals.ts:14`).
+- **[V]** `withCallerAccess` and `withoutCallerAccess` (`private-visibility.ts:392`, `:436`) carry the current caller's access in an `AsyncLocalStorage` store (`:23`, `:384`).
+- **[V]** A remote read of a page under a folder rule needs the member on every covering rule and on the page's own `readable_by`. Grants, hatches and `--as` do not relax it (`company-brain.md:147`).
+- **[V]** `visibility: private` pages are hidden from untrusted callers by `excludePrivate` in `buildVisibilityClause` (`sql-ranking.ts:176-188`).
+
+### 4.3 Malformed input fails closed (DB-side today)
+
+- **[V]** `gbrain_access_norm_readers` (`v282-member-read-access.ts:48-57`) lowercases, trims and accepts `member:<id>` and `group:<id>`. It never drops an invalid entry: if any entry fails to normalize, or nothing remains, the whole list becomes `['!nobody']` (`bool_and(n IS NOT NULL)` at `:50`; the same early return in `src/core/access/principals.ts:44`; mixed valid and invalid case in `test/access-principals.test.ts:86`). Dropping invalid entries instead would widen access.
+- **[V]** `gbrain_access_readers(fm)` (`:59-70`) returns NULL when `readable_by` is absent, and `['!nobody']` for a non-string, non-array value, an array longer than 256, or an array with non-string elements.
+- **[V]** `pages_access_derive_readers` (`:115-116`) is a BEFORE INSERT OR UPDATE OF frontmatter, page_readers trigger.
+- **[V]** `pages_access_mark_restricted` and `access_members_mark_restricted` set `config.access.restrictions_present = '1'` (`:97-106`, `:118-122`). This global flag gates the fast path. The v282 backfill sets it when any restricted page or member exists.
+
+## 5. Database-enforced controls
+
+### 5.1 RLS: enabled, no policies shipped
+
+- **[V]** `src/schema.sql:1828-1831` says enabling RLS with no policies means the anon key reads nothing; BYPASSRLS roles are unaffected. A grep for `CREATE POLICY` finds none in `src/schema.sql` or any migration.
+- **[V]** The DO block (`schema.sql:1832-1870`) enables RLS on 35 named tables covering content, graph and credential data. It is conditional on the role's privileges (`:1838-1841`). In total the file has 32 `ENABLE ROW LEVEL SECURITY` statements.
+- **[V]** `docs/guides/rls-and-you.md` describes the v35 `auto_rls_on_create_table` event trigger and a v275 backfill (event-trigger SQL at `src/core/persistence/graduation-target.ts:298`).
+- **[V]** `GBRAIN_RLS_SCOPE_BINDING=1` runs source-scoped reads inside `set_config('app.scopes', csv, true)` (`src/core/postgres-engine.ts:320-345`). The policy that would use it is an operator recipe (`docs/ENGINES.md:294-365`), not created by gbrain.
+- **[V]** PGLite has no RLS binding and no statement timeout (`src/core/postgres-engine/search-settings.ts` header).
+- **[V]** `test/guest-notes-scoped-role.test.ts` pins the failure mode: a role that neither owns nor bypasses RLS reads a table as empty. The guard must refuse, not treat empty as "no guest source".
+
+### 5.2 GUC write gate
+
+The app sets these with `set_config(..., true)` inside a transaction (`src/core/persistence/context.ts:65-68`). Triggers read them with `current_setting`.
+
+| GUC | Set by | Read by | Effect |
+|---|---|---|---|
+| `gbrain.write_sources` (JSON array) | `persistence/context.ts:68`; `belief/purge-mirror.ts:159`; `v191-alias-source-cascade.ts:34` | `gbrain_require_managed_writer` (`schema.sql:2556`, `:2598`); trust stamp (`trust/propagation.ts:29`); `gbrain_guard_skill_publication` (`:3038-3050`) | Writes outside the list are refused |
+| `gbrain.git_protocol` = '1' | `persistence/context.ts:68` | `schema.sql:2607` | Git-canonical sources refuse undeclared writers |
+| `gbrain.topology_change` = 'on' | `backup/snapshot.ts:283`; `persistence/topology-recovery.ts:176` | `schema.sql:2564` | Source topology changes only inside administration |
+| `gbrain.write_trust_tier`, `gbrain.write_origin` | `persistence/context.ts` | tier stamp (`trust/schema.ts:187`) | Writer trust; nests as min(outer, inner) |
+| `gbrain.write_principal_kind/id`, `gbrain.write_request` | `persistence/context.ts:65-68` | stamp function and attribution triggers | Attribution |
+| `gbrain.materializing_revision` | `page-body/rechunk.ts:166-181` | `schema.sql:1921` | Allows knowledge_revision change during rechunk |
+| `gbrain.persistence_protocol`, `gbrain.writer_quiesced` | persistence code | `schema.sql:2953`, `:3022` | Protocol floor, quiescence |
+
+- **[V]** `gbrain_require_managed_writer()` (`src/schema.sql:2522-2600`) is attached as `managed_writer_guard BEFORE INSERT OR UPDATE OR DELETE` to pages, tags, slug_aliases, page_aliases, facts, takes, timeline_entries, sources, page_segment_texts and page_body_manifest (a DO loop near `:2620-2640`). It refuses rows whose source, or on UPDATE the old source, is not in `write_sources`. It refuses an unreadable parent (`:2584-2593`). Errors are `P0001` with `writer_coordinator_required:` and constraint names such as `managed_writer_guard:allowlist`, `:topology`, `:checkpoint`, `:unreadable_state`, plus `git_canonical_fence:mutation`.
+- **[V]** Tier stamp (`src/core/trust/schema.ts:187-236`, triggers at `:309-312`). On INSERT it sets `trust_tier = COALESCE(writer, 'unknown')` and `write_origin`. On UPDATE it refuses a raise without owner confirmation and resets to OLD. A writer may not declare a tier above `operator_curated` (`OWNER_TIER_FLOOR`, `src/core/trust/tier.ts:40`) without promotion. Order (`tier.ts:19-21`): `user_confirmed` > `operator_curated` > `tool_observed` > `agent_written` > `unknown` > `external_untrusted`.
+- **[V]** Guest sources (`trust/schema.ts`, `guestGuard`, ~lines 150-186): a guest page is capped at the source ceiling, only listed writers may change it, it is written only as a guest note, and a guest source holds no facts, takes or timeline entries.
+
+### 5.3 Other DB-side invariants
+
+- **[V]** Purge tombstones (`src/core/facts/purge-schema.ts:157-186`): `pages_refuse_purged`, `facts_refuse_purged`, `takes_refuse_purged` refuse content whose hash or fact was purged for that source (`purged_content:`).
+- **[V]** `oauth_clients.source_id ON DELETE RESTRICT` is physical, so a soft-deleted client still blocks a source delete. `src/core/destructive-guard.ts` counts those referents (per `docs/architecture/key-files/security.md`).
+- **[V]** CHECKs: `access_members.id` regex (`v282:26`), `oauth_clients.source_grant IN ('none')` (`schema.sql:800`), `fact_withdrawals.visibility IN ('private','world')` (`~830-836`), `persistence_topology_changes.intent_bytes >= 0` (`src/core/persistence/topology-schema.ts:15`).
+- **[V]** Derived access state is kept by triggers: `pages_access_stamp_folder_rules` (v283, `:125`), `access_rules_mark_restricted` and `access_pending_coverage_mark_restricted` (v283, `:161-165`), `access_members_refresh_serves` and `config_serves_refresh` (v309, `:64-70`).
+- **[I]** Persistence protocol triggers (`schema.sql:2957-3060`) and the minion queue trigger (`:1789`) belong to other maps. They are DB-enforced, so they are listed for completeness.
+
+## 6. Grants
+
+- **[V]** Grant revisions (`oauth_clients.grant_profile`, `grant_revision`, `grant_repair_reasons`, `schema.sql:794-796`) and `oauth_grant_audit` (`:813-823`). Rescope is the trusted-operator path (`oauth-provider.ts:1233`, `src/core/grants/rescope.ts`).
+- **[V]** `assertScopeSourceGrant` is called from `src/core/grants/legacy-token.ts`, `src/core/grants/service.ts` and `src/core/token-mint.ts`. `key-files/access.md` names the inner writers `insertClientGrant`, `persistGrant`, `writeTokenGrant`, `insertUnifiedToken`; I did not open those bodies.
+
+## 7. `file_upload` confinement
+
+- **[V]** `src/core/ops/files.ts:58-86`: `scope: 'admin'`, `localOnly: true`. The path resolves against `hookSessionCwd()` and goes through `validateUploadPath` (`src/core/ops/context.ts:149-189`), which is stricter for untrusted callers (`strict = ctx.remote !== false`).
+- **[V]** `localOnly` is documented in `src/mcp/dispatch.ts:629-634` as hiding or refusing such ops over a network transport. [I] I did not trace dispatch to confirm the refusal end to end.
+- An open question about upload path confinement is tracked separately.
+
+## 8. Prompt-injection defenses
+
+- **[V]** Query expansion (`src/core/search/expansion.ts`). `sanitizeQueryForPrompt` (`:23-36`) caps at 500 chars, strips fenced code and HTML-like tags, and removes leading role words (`ignore`, `system`, `assistant`). `sanitizeExpansionOutput` (`:40-54`) strips control chars, caps at 500, dedupes, and keeps at most 2 alternatives. Expansion runs only for queries of 3+ words (`MIN_WORDS`, `:12`).
+- **[V]** The query-side sanitizer is a lightweight text strip scoped to query expansion.
+- **[V]** The stored-text defense is `src/core/write-gate.ts` (deterministic, model-free). Trust tier routes it. `external_untrusted` instruction-like text is flagged, quarantined, rejected or allowed per `write_gate.external_mode`, and a detector error quarantines. `agent_written` and `unknown` flag or allow, and a detector error allows. The gate never runs on `user_confirmed`, `operator_curated` or `tool_observed`. Patterns: `src/core/write-gate-patterns.ts`.
+- **[I]** The gate is application code. The DB stores tier and receipts, not the detector, so the Rust write path must call the gate itself.
+
+## 9. Egress and consent
+
+### 9.1 What text leaves the process
+
+- **[V]** Model calls go through `src/core/ai/gateway.ts`: `embed` (`:1859`, `:2066`, `:2215`), `expand` (`:2698`), `chat` (`:3906`). Provider keys are redacted from error text (`redactKeys`, `gateway.ts:155`, `src/core/ai/key-redact.ts`). Request bodies are sent as built by each caller.
+- **[V]** `secret-scan.ts` redaction runs at specific sites: fact embedding (`src/core/embed-facts.ts:9`), proactive brief (`context/proactive-brief.ts:26`), retrieval reflex (`context/retrieval-reflex.ts:41`), transcript render (`transcripts/render.ts:50`).
+- An open question about which page text may reach the embedding provider is tracked separately. The Rust embedder design depends on its answer.
+- **[V]** Expansion sends the sanitized query (`expansion.ts:64-70`).
+- **[V]** Egress budget (`src/core/egress-budget.ts:19-31`) caps each MCP frame: 4 MiB stdio, 1 MiB HTTP, configurable in [256 KiB, 9 MiB]. It protects the client, not the model provider. Trusted CLI calls have no cap.
+
+### 9.2 Consent gate
+
+- **[V]** `requireConsent` (`src/core/consent.ts:208`) runs only in trusted local CLI handlers. A `host_admin` action is never authorizable from MCP. Preapprovals live in `~/.gbrain/config.json`, not in the DB.
+- **[V]** The header says it plainly: "an agent can always pass `--yes`. This gate forces a stop and supplies relay text; it cannot prove a human agreed." The enforced rails are the spend cap and the plan-hash binding.
+- **[V]** Caps: `DEFAULT_PAID_CAP_USD = 5`, `DERIVED_CAP_MULTIPLIER = 1.5`, `DERIVED_CAP_FLOOR_USD = 0.25` (`consent.ts:84-87`).
+
+## 10. Credential vault (`src/core/creds/`, 1,118 lines)
+
+- **[V]** Custody (`vault.ts:9-16`): secrets live only in the vault or in env at connect time, never in the config DB or `sources.config`. Sources store a credential id. `list()` returns `redactEntry` output only (`vault.ts:110-131`).
+- **[V]** Interface (`vault.ts:87-103`): `get`, `put`, `list`, `delete`, `getClient`, `putClient`, `deleteClient`. Kinds: `oauth2`, `bearer`, `api_key`.
+- **[V]** `FileVaultBackend` (`vault.ts:214`): `~/.gbrain/credentials.json`, mode 0600 (pre-created before the atomic write). An unreadable file is refused, never overwritten. `openVault()` at `:302`.
+- **[V]** `EngineVaultBackend` (DB-backed, for hosted) exists only as a described interface; no implementation is in this repo.
+- **[V]** `src/schema.sql` has no credential table (grep `credential`, `secret`, `vault`).
+- **[V]** Encrypted bundle export (`creds/export.ts:23-30`): scrypt N=2^15, r=8, p=1; base64 salt and IV.
+
+## 11. SECURITY.md posture
+
+- **[V]** Remote MCP (`SECURITY.md:256-330`): DCR off by default; pre-register trusted clients with least-privilege grants; DCR ceilings and owner approval (`:367-415`); loopback bind, CORS, rate limits, proxy trust, body cap, audit log (`:440-616`).
+- **[V]** SECURITY.md does not mention the write gate, trust tiers or prompt injection (grep). Those are documented only in code headers (`src/core/write-gate.ts`, `src/core/trust/tier.ts`).
+
+## 12. Invariants the database enforces today (must move to Rust)
+
+These have no home in an embedded store: no RLS, no triggers, no policies. Each row says where the Rust check goes and how to test it.
+
+| # | Invariant | Enforced today by | Rust home | Test |
+|---|---|---|---|---|
+| I1 | Write only to sources in the caller's allowlist; old and new source both checked on UPDATE | `gbrain_require_managed_writer`, `schema.sql:2522-2600` | One write coordinator with `WriteScope { sources }`; check before every mutation | Foreign-source write: `writer_coordinator_required`. Cross-source move: refused. |
+| I2 | Source topology (incarnation, local_path, archived) changes only in administration | source branch, `schema.sql:2556-2570` | Topology capability type | Change `local_path` without capability: refused. Snapshot path still works. |
+| I3 | Git-canonical sources refuse writers without the protocol | `schema.sql:2607-2615`, `:2647-2670` | Protocol version on writer identity | Old-protocol writer to git source: refused. |
+| I4 | Tier from writer; no raise above `operator_curated` without promotion; origin stamped | `gbrain_stamp_trust_tier`, `trust/schema.ts:187-236` | Typed `TrustTier`; promotion is explicit | Matrix over (writer tier, old tier, promo, backfill). |
+| I5 | Guest ceiling, writer list, guest-note-only writes, no facts/takes/timeline in guest source | `trust/schema.ts` `guestGuard` | Guest policy before insert | Port `test/guest-notes-scoped-role.test.ts`. |
+| I6 | `readable_by` normalizes; malformed means `!nobody`; `page_readers` derived on every write | v282 functions and trigger | Normalize in writer; store derived column | Fuzz: non-string, >256 entries, uppercase, prefixes, empty, and a list mixing valid and invalid entries (must read as `!nobody`, never as the valid subset). |
+| I7 | `restrictions_present` set whenever a restriction exists | v282 mark-restricted triggers | Derive, or set in the same transaction | Restricted page read as unbound caller: filtered. |
+| I8 | Folder rule ids and serves recomputed on slug, source or member change | v283 stamp trigger; v309 serves triggers | Recompute in the same transaction | Move page into rule prefix; disable member; assert coverage and serves. |
+| I9 | Purged content never re-saved | `facts/purge-schema.ts:157-186` | Tombstone check in write path; index `(source_id, content_hash)` | Purge then `put` same content: `purged_content`. |
+| I10 | Source delete refused while any OAuth client (incl. soft-deleted) references it | `ON DELETE RESTRICT` | Referent check inside delete transaction | Soft-delete client, `sources remove`: refused, names client. |
+| I11 | Client delete cascades tokens and codes; source purge cascades withdrawals; group delete cascades members | FK `ON DELETE CASCADE` | Cascades in one Rust transaction | Delete client; no tokens or codes remain. |
+| I12 | Identifiers and enums valid (member id, `source_grant`, visibility) | CHECK constraints | Validated newtypes | Property test over invalid strings. |
+| I13 | Token and code hashes unique; lookup by hash, revoked excluded | UNIQUE, PK, partial index | Store hash only | Mint two tokens; revoked token refused. |
+| I14 | Non-BYPASSRLS roles read nothing from protected tables | RLS enable, no policy | Not needed; replace with per-op authz tests | Each read op with unbound or revoked credential returns no rows. |
+| I15 | Opt-in per-source read filter for an SQL role | `GBRAIN_RLS_SCOPE_BINDING` plus operator policy | Drop; `sourceScopeOpts`-equivalent is the only layer | Same per-op tests as I14. |
+
+## Rust engine implications
+
+**Preserve exactly**
+
+- Trust semantics. Trusted-only checks test "is trusted"; untrust-unless-explicit checks test "is not trusted". Use an enum with no default, so a missing caller is a compile error.
+- The `sourceScopeOpts` ladder, the `__all__` rule (trusted only), and "empty array is not all" (`context.ts:653-656`).
+- `readable_by` normalization and the `!nobody` fail-closed value, with the exact regex of `ACCESS_ID_RE`.
+- Scope names and implications (`scope.ts:25`, `:163-168`). `admin` does not imply `agent`.
+- DCR ceilings (`read write`; machine `read`; `memory_confirm` local-only).
+- Token format: prefix plus 32 random bytes hex, SHA-256 at rest, revoke by id.
+- Tier order, and no tier raise above `operator_curated` without promotion.
+- The `writer_coordinator_required` error family. Clients match on it.
+- Upload path confinement for remote callers (see section 7 for status).
+- Consent defaults: $5 cap, 1.5x derived multiplier, $0.25 floor.
+
+**Can simplify**
+
+- Drop RLS, `app.scopes`, the auto-RLS event trigger, the v275 backfill and the `RLS_EXEMPT` escape hatch. PGLite never had them, so the app layer was always authoritative.
+- Drop `EngineVaultBackend` until hosted needs it.
+- Make `restrictions_present` a computed or transactionally maintained value.
+- Bind identities as parameters instead of inlining literals in `readersAllowedSql`.
+- Replace the regex prompt sanitizer with a length cap and control-character strip, and rely on the write gate for stored text.
+
+**Postgres features each piece uses today**
+
+| Piece | Postgres feature |
+|---|---|
+| Write allowlist | Transaction-local GUC via `set_config(..., true)`; BEFORE triggers |
+| Trust stamping | BEFORE INSERT/UPDATE plpgsql triggers; jsonb |
+| Readers | Trigger-maintained `page_readers text[]`; IMMUTABLE SQL functions; jsonb `?` |
+| Access state | AFTER triggers; `ON CONFLICT`; FK RESTRICT and CASCADE; partial index |
+| Read isolation | RLS, BYPASSRLS, `row_security_active()` |
+| Tokens | `UUID`, `TEXT[]`, `BIGINT` epoch; `FOR UPDATE SKIP LOCKED`; partial index on `revoked_at IS NULL` |
+| Audit | `BIGSERIAL`; JSONB before and after |
+
+**Risks**
+
+1. A missed trigger is a silent loss of enforcement. I1, I4 and I7 hold only if the Rust write path applies them. Build one write chokepoint and test that nothing else mutates the store.
+2. `restrictions_present` is a global fast-path flag. The Rust engine must maintain it exactly. Test I7 first.
+3. RLS was never a real second layer for default configs. Per-op authz tests (I14) must replace it.
+4. Unsalted SHA-256 is fine for 256-bit random tokens and wrong for user-chosen secrets. Keep tokens random.
+5. Embedding egress: decide explicitly which pages are embedded and by which provider (see 9.1).
+6. Stored-text defense is the write gate. Port the gate patterns with their tests.
+7. The consent gate is advisory (`--yes` always works). Do not treat it as an authorization boundary.
+
+## Open questions
+
+1. Embedding egress policy (see 9.1): tracked separately.
+2. Is `GBRAIN_RLS_SCOPE_BINDING` used in any production brain? If yes, the port must match its observable behavior.
+3. Do any of the 32 RLS-enabled tables get read by a role other than the owner? If none, the RLS list can go.
+4. Is `engine-sql/` the only path reading `access_tokens` and `oauth_*`? A full grep is needed for the Rust read surface.
+5. Should `EngineVaultBackend` live in this repo or stay with the hosted product?
+6. Keep `sanitizeQueryForPrompt`, or drop it in favor of a length cap? Measure what the expansion model does with stripped input.
+7. How much of `requester-scope.ts` (14-day grace, stored timestamps) is needed in phase 1? A fresh Rust brain has no legacy connections.
+8. Which "working directory" does a Rust stdio server use for `file_upload` confinement? Match `hookSessionCwd()` semantics or define a new root.
diff --git a/docs/designs/rust-engine/research/10-tests.md b/docs/designs/rust-engine/research/10-tests.md
new file mode 100644
index 0000000000..82f48e2410
--- /dev/null
+++ b/docs/designs/rust-engine/research/10-tests.md
@@ -0,0 +1,148 @@
+# TypeScript test suites as a parity oracle
+
+Line numbers refer to gbrain 36bd05806a.
+
+Scope: gbrain v0.60.733.0 (commit 36bd05806a) at `garrytan/gbrain`, read only. Nothing was run; all counts come from `find`/`rg` over the checkout this session. "Verified" means read or counted in code or docs. "Inferred" means drawn from names, headers or docs without running the test.
+
+## 1. Headline numbers (verified)
+
+- 6,486 `*.test.ts` files under `test/` (6,489 repo-wide; the 3 extra sit outside `test/`).
+- About 53,100 `test(`/`it(` call sites by regex. Approximate: nested `describe` and `.each` expansion are not counted.
+- Disjoint tier buckets, by precedence (e2e directory, then `.serial`, `.slow`, `.live`, unit remainder): e2e 923, serial 476 (outside e2e; 502 total including e2e), slow 62, live 1 (2 more live files sit in `test/e2e`), unit 5,024. These sum to 6,486.
+- Only 81 test files spawn the CLI without importing `src/` directly or through a helper (see section 7). Roughly 500 test cases are that black-box set.
+
+## 2. Tier model
+
+Lanes are defined in `docs/TESTING.md` ("File taxonomy", l.1389; "Test command tiers", l.402) and the event matrix in `docs/ci-event-parity.md`.
+
+| Tier | Files | Selector / command | Database | CI cadence (from docs) |
+|---|---|---|---|---|
+| unit | 5,024 | `*.test.ts` outside `test/e2e`; `bun run test` (`scripts/run-unit-parallel.sh`) | PGLite; `DATABASE_URL` unset in the lane | every PR, 10 weighted shards |
+| serial | 476 (+26 in e2e) | `*.serial.test.ts`, listed in `scripts/serial-files.tsv` (476 rows); `bun run test:serial` | PGLite | 4 pooled workers, one Bun process per file |
+| slow | 62 | `*.slow.test.ts`; `bun run test:slow` | PGLite | named slow jobs or unit shards |
+| live | 3 | `*.live.test.ts`, `test/live/`; paid provider calls | real providers | never in PR CI |
+| e2e | 923 | `test/e2e/*.test.ts`; `bun run test:e2e` (`scripts/run-e2e.sh`) | real Postgres via `DATABASE_URL`; skipped when unset | PR gets a selected subset; full corpus on master, merge queue, nightly |
+| heavy | 9 `.sh` (2 are `_` helpers) + 3 `_*.ts` workloads in `tests/heavy/` | `bun run test:heavy` | Postgres | label-gated on PR; nightly `heavy-tests.yml` |
+| fuzz | 3 | `test/fuzz/*.test.ts` | none | in unit lane (about 3 s) |
+| admin | 29 files with `admin` in the name; 1 Playwright `admin/e2e/*.pw.ts` | `bun run test:admin` (PGLite in-memory, Chromium) | PGLite | required `admin-browser` job |
+| stress | harness `scripts/stress/` + 6 name matches | `bun run test:stress`; PR gate `stress-changed-tests` runs each touched file 10x | Postgres arms | PR (changed files), nightly race hunt |
+| scale | harness `scripts/scale/` + about 15 name matches | `bun run test:scale` (package.json l.103) | both | `scale-tier.yml`, nightly 10k-50k |
+| convergence | `test/sync-convergence.serial.test.ts` (+ helpers) | `bun run test:convergence` sets `GBRAIN_TEST_CONVERGENCE=1` (l.107) | PGLite | `convergence-nightly.yml`; PR cell in `persistence-validation.yml` |
+| busy-agent | `test/busy-agent-soak.serial.test.ts`, profile `test/fixtures/busy-agent-profile.json` | `bun run test:busy-agent` sets `GBRAIN_TEST_BUSY_AGENT=1` (l.108) | PGLite | dispatch-driven |
+| tla | `spec/tla/` (2 modules, 15 `.cfg`) | `bun run test:tla` (l.109) | none for TLC | `tla-spec.yml` nightly and on touching PRs |
+
+Per-directory split (verified; unit / serial / slow): root `test/*.test.ts` 4,168 / 418 / 46; `large-pages` 164 / 3 / 12; `scripts` 152 / 0 / 3; `pathological` 127 / 2 / 0; `search` 111 / 14 / 0; `ai` 80 / 4 / 0; `cycle` 36 / 2 / 0; `skillopt` 32 / 5 / 0; `decide` 15 / 22 / 0; `chunkers` 17; `ingestion` 12; `core` 10 / 3 / 1; `minions` 9 / 1 / 0; `audit` 9; `facts` 8; `conversation-parser` 8; `brainstorm` 8 / 2; `code-intel` 6; then 1 to 5 files each for `enrich`, `context`, `budget`, `bench`, `regressions`, `fuzz`, `extract`, `schema-pack`, `progressive-batch`, `fixtures`, `eval-contradictions`, `commands`, `eval`. `test/e2e` holds 923 files; `test/helpers` holds 12 `*.test.ts` plus about 200 helper modules.
+
+Note that `decide/` is serial-heavy (22 of 37 files), so its tests are process-isolated by design.
+
+## 3. Database requirements: PGLite versus `DATABASE_URL`
+
+- Unit, serial and slow lanes unset `DATABASE_URL` (docs/TESTING.md l.271). A file whose Postgres arm is gated on it runs that arm only where a Postgres lane names it: a workflow step, a `test/e2e/` wrapper (`registerPostgresTests`), a `tests/heavy` script, or a row in `scripts/e2e-backend-matrix.txt` (77 rows). `test/postgres-unit-arms.txt` (776 rows) lists unit files that run their Postgres arm in `persistence-validation.yml`.
+- `test/helpers/test-backends.ts`:
+ - `requirePostgresTestDatabase` (l.6) refuses to skip a Postgres arm silently.
+ - `testBackends()` (l.15) returns `['pglite','postgres']` when `DATABASE_URL` is set and `['pglite']` otherwise; `GBRAIN_TEST_BACKEND=postgres|postgres-direct|pgbouncer` forces the Postgres arm.
+ - `registerPostgresTests()` (l.24) wraps loaders with `GBRAIN_TEST_BACKEND=postgres`.
+- Counts (verified by `rg -l`): 831 files call `testBackends(`; 356 files mention `registerPostgresTests`; 284 of the `*-postgres.test.ts` wrappers call it; 1,022 files read `process.env.DATABASE_URL`.
+- `test/e2e/` files are gated: 399 mention `DATABASE_URL`; 181 have neither a gate nor a registration call (inferred: these run with `DATABASE_URL` set by the runner, or are skipped).
+- PGLite has a default-on schema snapshot (`test/fixtures/pglite-snapshot.tar`, generated by `scripts/build-pglite-snapshot.ts`; docs l.571). Every runner activates it, so the Rust port has no equivalent for the snapshot itself.
+
+## 4. Two-engine parity helpers
+
+- `test/helpers/two-engine.ts` (366 lines) runs two brains in one process with separate homes, AI keys, embedding models and fake OpenAI-compatible providers. `openTestBrain` (l.57) is the seam that later waves replace.
+ - `CASES` (l.114): 26 isolation cases.
+ - `EXPECTED_FAILURES` (l.308): 13 rows, each naming the wave that removes it (W2, W5, W6). These run as `test.failing`, so an unexpected pass fails the suite.
+ - `twoEngineIsolationSuite(kind, urls)` (l.324) is run from `test/two-engine-isolation.serial.test.ts` (PGLite) and `test/e2e/two-engine-isolation.test.ts` (Postgres).
+- `test/helpers/engine-sql-capability-cases.ts` pins three dialect capabilities, each with a boundary-size and a concurrent-write case: `maxBindParamsPerStatement` (PGLite splits code-edge inserts below 30,000 binds), `transactionAdvisoryLocks` (Postgres `pg_advisory_xact_lock` on same-entity fact inserts), and `probesEmbeddingCast` (`::vector` versus live column type). Registered from `test/engine-sql-capabilities.test.ts` and `test/e2e/engine-sql-capabilities-parity.test.ts`.
+- Other engine-sql parity files: `test/e2e/engine-sql-prepare-parity.test.ts` (`pg_prepared_statements`), `test/e2e/engine-sql-normalize-parity.test.ts` (column decode shapes), `test/e2e/engine-sql-rls-scope.test.ts` (non-owner `NOBYPASSRLS` role), `test/e2e/engine-sql-transaction-parity.test.ts`.
+- Name-level: 56 `*parity*.test.ts` files exist across the tree; 36 sit under `test/e2e`.
+- Executor-level: `test/executor-binding-matrix.test.ts` (PGLite arm) and `test/e2e/executor-binding-matrix.test.ts` (run twice: direct and PgBouncer, with `prepare=false`).
+- Shared scenario code across two engines is not treated as duplicate coverage (docs l.209). Engine-specific boundaries (JSONB, locks, pooler) are owned by the Postgres lane.
+
+## 5. Golden and contract tests
+
+- `test/helpers/golden.ts` is the golden harness. Goldens live under `test/fixtures/goldens/` (59 files: `doctor` 17, `sql-text` 14, `catalog` 10, `cli` 8, `pglite-upgrade-replay` 5, `decide` 3, `trust` 2). Each golden uses a named normalizer proven stable by capturing twice. Regenerate with `GBRAIN_TEST_UPDATE_GOLDENS=1`. 32 test files import the harness.
+- Most relevant to a Rust engine:
+ - `test/cli-goldens.test.ts`: `--help` text, `--version`, `--tools-json` bytes (sha256 pinned), unknown-command and unknown-flag exit codes and messages. Uses `runCliBatch` against the real `src/cli.ts` (`test/fixtures/goldens/cli/help-and-errors.json`, `tools-json.json`).
+ - `test/cli-json-commands.test.ts` and the agent-contract tests: under `--json`, stdout is exactly one document or NDJSON, and failures are envelopes with `code`, `suggestion`, `contract_version: 1`.
+ - `doctor` goldens (`test/helpers/doctor-json-golden.ts`).
+- `test/engine-sql-sql-text.test.ts` pins SQL text byte-for-byte. It is a conversion guard, not product behavior; it dies with the SQL layer.
+- Refactor-wave goldens pin output across rewrites; the docs say a golden is "a reviewer-visible diff" when regenerated (golden.ts header).
+
+## 6. TLA+ specs
+
+- `spec/tla/README.md` describes TLC checks plus mutants. `bun scripts/spec/mutants.ts` applies each mutant to a model copy (TLC must report a violation) and to the code (the named test must fail).
+- `spec/tla/drain-lease/DrainLease.tla` (344 lines): the managed-sync drain lease. One drainer per source. The lease is one row in `gbrain_cycle_locks`; the acquisition token is the fencing token. Fenced transactions take the row `FOR KEY SHARE` (#7442). The model is Postgres only; PGLite is one connection. Invariants: `OneDrainer`, `FencedTxnsMatchRow`, `NoSpuriousLapse`, `CursorMonotone`. Code: `src/core/persistence/sync-lease.ts`, `src/core/db-lock.ts`. 14 mutants (`mutants.json`). Configs: `DrainLease.cfg`, `DrainLeaseSafety.cfg`, `DrainLeaseStamp.cfg`, `DrainLeaseLanesNightly.cfg`.
+- `spec/tla/refresh-barrier/RefreshBarrier.tla` (884 lines): the refresh write barrier and deferred-write queue for one managed worktree and one page. Models Postgres's four row-lock modes, deadlock as a safety property (40P01), and crash-and-recover of the refreshing process (`MaxCrashes`). Code: `src/core/persistence/journal.ts`, `worktree-refresh.ts`, `refresh-barrier.ts`, `shared-skills/restore.ts`. 22 mutants. 11 `.cfg` files cover adoption, import holds, liveness and nightly variants.
+- Test linkage: `test/spec-drain-lease-constants.test.ts` checks the `.cfg` timing constants against the code (per the `DrainLease.tla` header, l.13).
+
+## 7. Black-box versus white-box
+
+Method: for every `*.test.ts` I classified (a) direct imports from `src/` (relative specifiers), (b) CLI spawn (`test/helpers/cli-spawn.ts` or a literal `src/cli.ts`), and (c) whether the helper modules the test imports reach `src/` at depth 1. Depth-1 is an upper bound, because transitive helper chains were not followed.
+
+| Class | Files | Test blocks (approx.) | Notes |
+|---|---|---|---|
+| Direct `src/` importers (white-box) | 5,545 | ~50,200 | Call functions and types from `src/`. Not portable. |
+| No direct `src/` import | 941 | ~2,900 | Mixed: see below. |
+| ...of which read source or doc text | 227 | | Structural guards (`test-reads-source-ok`, `structural-suites.tsv`, 488 rows). Not portable. |
+| ...of which spawn the CLI | 88 | | 7 reach `src/` via a helper (depth 1). |
+| Black-box candidates (spawn only, clean at depth 1) | 81 | ~496 | 64 root, 10 e2e, 7 `scripts/`. |
+
+The 81 black-box files include `cli-goldens.test.ts`, `cli-json-commands.test.ts`, `cli-help-discoverability.test.ts`, `doctor-cli-smoke.test.ts`, `export-help.test.ts`, `e2e/serve-http-oauth.test.ts`, `e2e/sources-remote-mcp.test.ts` and `e2e/zombie-reaping.test.ts`. Their assertions are on stdout bytes, JSON envelopes, exit codes and files written under a temp `HOME`. Two examples were read: `test/cli-json-commands.test.ts` (imports only `bun:test`, Node built-ins and `./helpers/cli-spawn.ts`) and `test/helpers/cli-spawn.ts`.
+
+The 941 non-importers are not uniformly portable. The 7 that reach `src/` through a helper (for example `test/e2e/agent-journey-postgres.test.ts`, `test/serve-stdio-bound-explicit-read.test.ts`) can become portable only after the helper is split into a protocol layer.
+
+Most `test/e2e` wrappers are white-box at the loader level: `registerPostgresTests` calls scenario modules that import `src/`. For example the 349 files using `registerPostgresTests` depend on `test/helpers/*-scenarios.ts`, which are white-box.
+
+Estimate of reuse:
+- Run unchanged with a binary seam: about 500 cases in 81 files.
+- Portable after helper refactoring: about 2,400 cases in roughly 860 non-importers, but most are scenario or source-text tests that need per-file review.
+- Not portable: about 50,000 cases in 5,545 direct importers, plus the source-text guards.
+
+Cases that a Rust engine can check beyond the 500 are only the ones that have a CLI or MCP surface and a DB-free fixture.
+
+## 8. Harness proposal (GBRAIN_BIN)
+
+1. The seam already exists. `test/helpers/cli-spawn.ts:63` hard-codes `CLI_PATH = src/cli.ts`; `:73` exports `_setSpawnTarget`; `:116` builds `[process.execPath, '--no-env-file', CLI_PATH]` unless overridden. Read `GBRAIN_BIN` there: if set, spawn `[GBRAIN_BIN]` and drop `--no-env-file`. Ten files across `test/`, `scripts/` and `tests/` already use `GBRAIN_BIN` (for example `test/plugin-turn-hook.test.ts` and `scripts/dx-explore.ts:834`), so the name is in use.
+2. The env contract the Rust engine must honor (already set by the helper): `HOME` and `GBRAIN_HOME` pinned to a temp dir; `DATABASE_URL`, `GBRAIN_DATABASE_URL`, `GBRAIN_REMOTE_CLIENT_SECRET` stripped; `GBRAIN_SKIP_STARTUP_HOOKS=1`.
+3. Run the 81 files from a TS checkout with `GBRAIN_BIN=<rust-engine CLI> bun test <files>`. Bun stays as the test driver, so the Rust team needs no new runner for the first pass.
+4. Track results in a ledger keyed by (file, test name), following the identity model in `scripts/ci-executed-counts.ts` (docs l.121). Mark each as pass, fail, or expected divergence, the last with a `test.failing`-style row like `EXPECTED_FAILURES`.
+5. Derive new Rust-native black-box cases from the goldens (`cli-help-v1`, `cli-tools-json-v1`) rather than from TS internals.
+
+## Rust engine implications
+
+Must preserve exactly (verified against the black-box set):
+- CLI surface: `--help` and `--version` text, `--tools-json` bytes, unknown-command and unknown-flag exit codes and messages (`cli-goldens`).
+- `--json` contract: one document per command, NDJSON where stated, error envelopes with `code`, `suggestion`, `contract_version: 1`.
+- Environment handling: `HOME`, `GBRAIN_HOME`, `GBRAIN_SKIP_STARTUP_HOOKS`, and stripped `DATABASE_URL`. The Rust engine must not read a `.env` the tests strip.
+- Doctor output shape (`doctor` goldens).
+
+Can be simplified or dropped:
+- Two-engine parity (`two-engine.ts`, `testBackends`, `registerPostgresTests`, the `*-parity` files, the PgBouncer backend matrix, `postgres-unit-arms.txt`). One engine means one arm.
+- PGLite schema snapshot and its CI cache machinery.
+- The isolation lint R1 to R9 (`scripts/check-test-isolation.sh`). These rules guard Bun's module registry and `process.env`. The lint's allowlist (63 lines) disappears with the TS code.
+- SQL-text goldens (`engine-sql-sql-text`) and the engine-sql capability cases, which describe Postgres dialect behavior.
+- Structural source-text guards (227 files), which check TS source shape, not product behavior.
+
+Postgres features each test depends on (what the Rust engine must replicate or replace):
+- `pg_advisory_xact_lock`: fact-insert serialization (`transactionAdvisoryLocks`).
+- Row locks and `FOR KEY SHARE`: the drain-lease fence (`DrainLease.tla`) and the refresh barrier (`RefreshBarrier.tla`, four lock modes, deadlock as a safety property).
+- `NOBYPASSRLS` and `FORCE RLS` roles: `engine-sql-rls-scope`, projection-statistics tests.
+- pgvector HNSW plan choice and `vector`/`halfvec` casts: `vector-candidate-safety-postgres`, `vector-plan-real-column-postgres`.
+- `pg_prepared_statements` and `prepare=false` behavior behind PgBouncer: `engine-sql-prepare-parity`, `backend-matrix`.
+- Inferred, not mapped: `LISTEN`/`NOTIFY` and `SKIP LOCKED` queues are presumably exercised by the minions and persistence suites.
+
+Risks:
+- Oracle narrowness: only about 500 cases are truly black-box. Most of the 6,486 files would need rewriting, not reuse. Plan a Rust-native suite from the goldens and the CLI contract, not a rerun of TS unit tests.
+- Helpers couple to `BrainEngine` internals (for example `engine.executeRaw`, `engineSqlExecutor`). Any Rust port of the helpers needs a new public seam.
+- Timing ceilings are tuned for Bun and WASM PGLite (per-file caps, 1536 MB per slot, 820 s crash-robot ceiling). Do not carry them over unchanged.
+- TLA+ models are Postgres-specific. If the Rust engine keeps a single process and in-process locks, `DrainLease` and `RefreshBarrier` need a new model, not a port.
+- Goldens are generated on TS master. A Rust output diff must be classified as intended or a bug, with a documented exception list (the `EXPECTED_FAILURES` pattern works).
+
+## Open questions
+
+1. Is the oracle the TS binary's behavior (goldens and CLI contract), or the TS test files themselves? The answer decides whether to port tests or write new black-box cases.
+2. Which goldens are contract-bearing and must stay byte-identical (`cli`, `tools-json`, `doctor`), and which are TS-formatting artifacts?
+3. Does the Rust engine keep multi-process writers? If not, `DrainLease` and the refresh barrier stop applying, and the crash-robot scheduling need not be ported.
+4. Who owns the `GBRAIN_BIN` seam in the TS test tree? The seam must be added either in a branch of gbrain or in a copied test tree.
+5. Should the 3 live provider files and the `evals` suite (21 files in `gbrain-evals/test/eval/`, mostly pure eval logic) run against the Rust engine? They depend on provider keys and a `gbrain` package import (one file imports `gbrain/engine`).
+6. Depth-1 import analysis may undercount black-box tests. Is a transitive pass worth the cost before committing to the 81-file estimate?
diff --git a/docs/designs/rust-engine/research/11-gbrain-evals.md b/docs/designs/rust-engine/research/11-gbrain-evals.md
new file mode 100644
index 0000000000..03c5d40b72
--- /dev/null
+++ b/docs/designs/rust-engine/research/11-gbrain-evals.md
@@ -0,0 +1,214 @@
+# gbrain-evals as the Rust parity oracle
+
+Line numbers refer to gbrain 36bd05806a.
+
+Research map for the Rust rewrite. Read-only inputs: gbrain-evals at `9ecc5b20`, gbrain (TypeScript) at `36bd05806a` (v0.60.733.0), and the installed copy `gbrain-evals/node_modules/gbrain` (v0.41.29.0, pinned in `bun.lock` to `041d89b`).
+
+Path conventions: `eval/...` is relative to `garrytan/gbrain-evals`. `ts:src/...` is relative to `garrytan/gbrain`.
+
+Legend: **[V]** verified this session by reading code or running a grep, `ls`, or a parse. **[D]** taken from a benchmark report in `docs/benchmarks/` and not re-run. **[I]** inferred.
+
+## 0. Summary
+
+- gbrain-evals is a consumer of gbrain. It imports 12 static `gbrain/*` subpaths (plus `transcription` and `package.json` dynamically), constructs `PGLiteEngine` in 26 places across 25 files, and makes 7 deep relative imports into `node_modules/gbrain` that bypass the exports map. **[V]**
+- Several runners write raw SQL into gbrain's Postgres schema (`pages`, `content_chunks`, `links`, `sources`, pgvector `::vector`). A Rust engine cannot run those without a SQL shim or a rewrite to ops. **[V]**
+- Three things are broken as checked out. `type-accuracy.ts` and `adversarial.ts` call `extractPageLinks` with a stale signature. `longmemeval.ts:55` imports a path that does not exist. The LongMemEval embed-cache fixture that the docs say ships is absent. **[V]**
+- The cheapest parity oracle is retrieval-only LongMemEval (500 questions, top-5). Without the cache fixture, the first run costs about $2 in OpenAI embeddings **[D]**.
+- Cats 14 and 15 never execute gbrain code. They test prompts copied into the runner. Do not gate Rust on them. **[V]**
+- gbrain's own TypeScript repo ships an in-tree LongMemEval harness (`gbrain eval longmemeval`, JSONL, judge, receipts, `--embed-cache`) at `ts:src/commands/eval-longmemeval.ts`. It is a better driver target than the evals runners. **[V]**
+
+## 1. Versions and pins
+
+| Item | Value | Source |
+|---|---|---|
+| gbrain-evals HEAD | `9ecc5b20` (v0.40.6.0 snapshot) | `git log` |
+| Declared gbrain dep | GitHub dependency on `garrytan/gbrain`, ref `master` (unpinned in this historical snapshot, not an install recommendation) | `package.json` at `9ecc5b20` |
+| Installed gbrain | 0.41.29.0, lock pin `041d89b` | `node_modules/gbrain/package.json`, `bun.lock` |
+| TS gbrain reference | `36bd05806a`, v0.60.733.0 | `ts:package.json` |
+| LongMemEval published numbers | gbrain v0.28.8 | `docs/benchmarks/2026-05-07-longmemeval-s.md:4` |
+| Snapshot | gbrain v0.40.6.0, commit `677142a6` | `docs/benchmarks/2026-05-23-v0.40.6.0-snapshot.md:3-4` |
+| BrainBench v0.20.0 baseline | gbrain `96852c0` | `docs/benchmarks/2026-04-23-brainbench-v0.20.0.md:6` |
+
+No single run reproduces every published number. Parity has to be measured against a TS run at one pinned commit, with published numbers used only as sanity checks.
+
+## 2. Benchmark inventory
+
+Paths are under `eval/runner/` unless noted. "Published" numbers are **[D]**. Cost and runtime come from the same reports and the snapshot.
+
+| Runner | Measures and data | Metric and published result | Cost, runtime | gbrain surface |
+|---|---|---|---|---|
+| `longmemeval.ts` (adapters `keyword`, `vector`, `hybrid`, `hybrid+expansion`) | Session retrieval over the `_s` split: 500 questions, about 50 sessions per haystack, 6 question types | Session R@5: keyword 19.80% (99/500), vector 97.40% (487/500), hybrid 97.60% (488/500), hybrid+expansion 97.60% (488/500) | Cold: about $2 embeddings plus about $1 Haiku. Warm: about $0. Hybrid p50 2.2 s | `PGLiteEngine`, `importFromContent`, `hybridSearch`, `expandQuery`, `loadConfig`, `configureGateway`, `embed`, `searchKeyword`, `searchVector`, raw `TRUNCATE` |
+| `multi-adapter.ts` (BrainBench Cats 1+2) | 240 rich-prose pages (`data/world-v1`), 145 auto-derived relational queries | P@5 49.1%, R@5 97.9%, 248/261 for gbrain. Vector-only 10.8/40.7 (v0.20.0 report) | About 3 min, $0 warm | `PGLiteEngine` (`putPage`, `traversePaths`), `runExtract` links and timeline |
+| `shootout-driver.ts` + `scripts/run-shootout-phase2.sh` | Same corpus, 90 queries, one hybrid cell per embedder | A0 P@5 18.0%, R@5 63.3% (81/184). Cat 13 subset R@5 94%. Phase 2 cells wedged on the rerank path | About $8 per cell, about 30 min per cell (script header) | `configureGateway`, `setConfig` for `search.mode` and reranker |
+| `cat13-conceptual.ts` (Cat 13) | 500 seeded paraphrase probes | nDCG@5: vector 49.1, gbrain 47.0, grep-only 46.2 | About 11 min, about $0.03 | `PGLiteEngine`, `runExtract`, `hybridSearch`, `importFromContent` |
+| `cat13b-source-swamp.ts` | 10 curated `originals/` plus 10 long chat pages, 30 queries | Top-1: gbrain 93.3%, vector-only 96.7%, grep-only 80% (vector wins here) | About 50 s, about $0 | same as Cat 13 |
+| `identity.ts` (Cat 3) | 100 entities times 8 alias types, 800 queries | Recall@10: documented aliases 100%, undocumented 31% (v1 report) | Hermetic | `putPage`, `searchKeyword`, `upsertChunks` |
+| `temporal.ts` (Cat 4) | 50 entities, 10 to 20 dated events | Point, range, recency, as-of all 100% (v1 report). As-of resolved in app code | Hermetic | `putPage`, `addTimelineEntry`, `getTimeline` |
+| `cat5-provenance.ts` (Cat 5) | Claim catalog, Haiku classifies supported, unsupported, over-generalized | No published number in repo | Anthropic only | No gbrain import **[V]** |
+| `cat6-prose-scale.ts` (Cat 6) | world-v1 pages times 6 injection kinds | Baseline only, no gate | Hermetic | `extractPageLinks` (correct 5-arg form, line 219) |
+| `perf.ts` (Cat 7) | Synthetic 1K and 10K pages | 10K P95: `get_page` 0.15 ms, `search_keyword` 0.59 ms, `traverse_paths` d=2 176.4 ms, bulk 5,848 pages/s. Gate `perf.ts:233`: search_keyword P95 at 10K under 200 ms | Minutes, hermetic | `putPage`, `addLink`, `get*`, `listPages`, `searchKeyword`, `traversePaths` |
+| `cat8-skill-compliance.ts` (Cat 8) | Sonnet agent drives gbrain tools; 4 iron-law metrics | Thresholds above 0.90, informational. No published number | About $2K estimated (v1 report) | `tool-bridge.ts`, `OPERATIONS` handlers |
+| `cat9-workflows.ts` (Cat 9) | About 50 scenarios across 5 workflows | More than 80% pass per workflow. No published number | About $1K estimated | same as Cat 8 |
+| `adversarial.ts` (Cat 10) | 22 edge cases times 6 ops = 133 attempts | 133/133 ops, 0 crashes, 0 silent corruption (v1 report) | Hermetic | `PGLiteEngine`, `getPage`, `putPage`, `searchKeyword`, `traversePaths`, `extractPageLinks` (stale, see Section 3) |
+| `cat11-multimodal.ts` (Cat 11) | 10 PDFs and 5 audio clips, fixtures not committed | Thresholds only. No published number | Needs OpenAI or Groq keys | `gbrain/transcription` (dynamic) |
+| `mcp-contract.ts` (Cat 12) | Trust boundary and input validation, 50 checks | 50/50 (v1 report) | Hermetic | `OPERATIONS`, `op.handler(ctx, params)` at line 61 |
+| `cat14-calibration.ts` | Calibrated vs baseline "think" on 8 probes | 75% win, 0% loss, 25% tie. About $0.15 | Under 5 min | **None.** Baseline prompt copied (line 126) |
+| `cat15-propose-takes.ts` | Predictions in prose: 8 pages, 48 labeled claims | F1 0.952 (train), 0.922 (unseen) | Under 5 min | **None.** Extract prompt copied (line 128). Corpus lives in gbrain test fixtures |
+| `cat18-embedding-providers.ts` | OpenAI, Voyage, ZeroEntropy on 164 pages, 21 queries | Cost $0.0009 to $0.0031 per 164 pages (snapshot) | About 10 min | `executeRaw` on `pg_attribute` and `content_chunks` (line 96) |
+| `cat18b-embedding-rerank-matrix.ts` | 6 cells, with and without rerank | R@10 12.2% to 53.7% (snapshot) | About 15 min | `setConfig` for `search.mode` and reranker |
+| `cat19-doctor-remediate.ts` | `doctor --remediate` end to end | Brain health 10 to 50 in 115 ms (snapshot) | Hermetic | `executeRaw` INSERT into `links`, UPDATE `embedding::vector`, `getHealth` |
+| `cat20-brainstorm.ts` | Novelty, usefulness, grounding, Haiku-judged | 6.3, 6.0, 7.7 out of 10 | About 3 min, about $2 | Deep import `runBrainstorm` (line 22) |
+| `cat21-code-retrieval.ts` | voyage-code-3 vs text-embedding-3-large, 12 probes | Top-1 2/12 for both (probe set too small) | About 10 min, about $0.30 | `hybridSearch`, `extractEntityRefs` |
+| `cat22-source-isolation.ts` | 3 sources, OAuth scoped to one | 0 leaks across 4 surfaces | Hermetic | `executeRaw` into `sources`, `listPages({sourceId, sourceIds})`, `getPage(slug,{sourceId})`, `hybridSearch({sourceId})` |
+| `cat23-phantom-redirect.ts` | 7 phantom slugs to canonical | 1/7 resolved, 2/7 ambiguous correct, 4/7 missed. Snapshot blames PGLite lacking pg_trgm | Hermetic | Deep import `resolvePhantomCanonical` (line 30) |
+| `cat24-capture-provenance.ts` | 5 ingest paths, provenance columns | 5/5 round-trip | Hermetic | `executeRaw` SELECT on `pages` provenance columns (line 105) |
+| `cat25-trajectory-routing.ts` | `think` with and without trajectory routing | Wave 10/10 vs baseline 9.5/10 | About 2 min, about $0.50 | Deep import `runThink` (line 29), `withTrajectory` flag |
+| `cat26-contextual-retrieval.ts` | none, title, synopsis modes | 100% R@10 on a micro corpus | About 3 min, about $0.10 | `setConfig('contextual_retrieval')`, `hybridSearch` |
+| `cat27-graph-signals.ts` | Adjacency, cross-source, session-demote signals | Multipliers too small to flip rank 1 | About 2 min | `executeRaw` INSERT into `links` with `ON CONFLICT` (line 265), `setConfig('search.graph_signals')` |
+| `cat28-federated-sync-latency.ts` | Serial vs parallel sync | Dominated by PGLite WASM cold start | Hermetic | `executeRaw` into `sources`, `importFromContent` |
+| `cat29-think-vs-search.ts` | `think` vs raw `search`, 5 questions, Haiku judge | Search 1.60/10, think 5.60/10 | About 8 min, about $3 | Deep import `runThink` (line 36) |
+| `type-accuracy.ts` (Cat 2 per-link type) | world-v1 `_facts` gold vs extracted links | No current result. Broken call (line 160) | Hermetic | `extractPageLinks` (stale) |
+| `smoke.ts` | Embedder preflight, 3 phases | Pass or fail only | Cheap | `configureGateway`, `embed` |
+| Docs only: Minions, tweet ingest | Job durability and throughput. Minions 10/10 vs sub-agents 0/10; p50 778 ms vs 8,086 ms | Reports in `docs/benchmarks/2026-04-18-*` | Harness lives in gbrain `test/e2e/bench-vs-openclaw/` **[V]**, not here | Out of scope for this repo |
+
+Two notes. The knowledge-runtime report points at `test/benchmark-put-page-latency.ts` in the gbrain repo. That file does not exist **[V]**. Also, the `_s` report describes the warm cache as "~150MB" in §8 and §12, while `eval/data/longmemeval/embed-cache/README.md` says "~700MB". Neither file exists in the checkout (see Section 4).
+
+## 3. Coupling inventory
+
+**Imports [V].** `gbrain/pglite-engine` in 25 import lines. `gbrain/ai/gateway` in 16. `gbrain/import-file` in 15. `gbrain/search/hybrid` in 9. `gbrain/types`, `gbrain/link-extraction`, `gbrain/operations`, `gbrain/extract`, and `gbrain/config` in 3 to 5 each. `gbrain/engine` and `gbrain/search/expansion` in 1 or 2 each. Dynamic: `gbrain/transcription` (Cat 11), `gbrain/embedding` (Cat 19), `gbrain/package.json` (13 runners).
+
+**Deep imports bypassing the exports map [V].** `longmemeval.ts:47,51,55` import `node_modules/gbrain/src/core/embedding.ts`, `.../ai/gateway.ts`, and `.../node_modules/ai/dist/index.mjs`. `cat20-brainstorm.ts:22`, `cat23-phantom-redirect.ts:30`, `cat25-trajectory-routing.ts:29`, and `cat29-think-vs-search.ts:36` import further internals.
+
+**`gbrain/package.json` does not resolve [V].** The exports map has no `./package.json`, so each of the 13 runners falls into its `catch` and records `gbrainVersion: 'unknown'` (for example `cat20-brainstorm.ts:150-154`). Scorecards therefore lose the version.
+
+**Engine surface used [V].** `connect`, `initSchema`, `disconnect`, `putPage`, `getPage`, `listPages`, `searchKeyword`, `searchVector`, `traversePaths`, `addLink`, `getLinks`, `getBacklinks`, `addTimelineEntry`, `getTimeline`, `upsertChunks`, `getStats`, `getHealth`, `setConfig`, `executeRaw`.
+
+**`setConfig` keys [V].** `search.mode` (`conservative`, `balanced`, `tokenmax`), `search.reranker.enabled`, `search.reranker.model`, `search.graph_signals`, `auto_link`, `contextual_retrieval`.
+
+**Options passed [V].** `hybridSearch` takes `limit`, `expansion`, `expandFn`, `sourceId`, `sourceIds`. `importFromContent` takes `noEmbed` and `sourceId`. The TS signatures exist at `ts:src/core/search/hybrid.ts:843,869,1086` and `ts:src/core/import-file.ts:254`.
+
+**Raw SQL against the gbrain schema [V].**
+- `cat19-doctor-remediate.ts:89-131`: counts on `pages(deleted_at)` and `content_chunks`; `INSERT INTO links (from_page_id, to_page_id, link_type, link_source) ... ON CONFLICT DO NOTHING RETURNING 1`.
+- `cat19-doctor-remediate.ts:211-213`: `UPDATE content_chunks SET embedding = $1::vector, embedded_at = now()`.
+- `cat18-embedding-providers.ts:96-99`: `pg_attribute` `atttypmod` on `content_chunks.embedding`.
+- `cat22-source-isolation.ts:60`, `cat28-federated-sync-latency.ts:62`, `cat27-graph-signals.ts:187`: `INSERT INTO sources (id, name, config) ... '{"federated": true}'::jsonb ON CONFLICT DO NOTHING`.
+- `cat24-capture-provenance.ts:78,105`: `source_kind, source_uri, ingested_via, ingested_at` on `pages`.
+- `longmemeval.ts:224-233`: `pg_tables` enumeration and `TRUNCATE ... RESTART IDENTITY CASCADE`, preserving `sources`, `config`, `gbrain_cycle_locks`, `subagent_rate_leases`.
+
+**Stale or broken call sites [V].**
+- `type-accuracy.ts:160` and `adversarial.ts:111` call `extractPageLinks(content, {}, type)`. The current signature is `async extractPageLinks(slug, content, frontmatter, pageType, resolver, opts?)` (`ts:src/core/link-extraction.ts:844`). The installed 0.41.29.0 has the same async six-argument form. The type-accuracy call is not awaited, so the `for...of` over a Promise fails. The adversarial call at line 186 is wrapped in `tryOp`, so the failure is recorded rather than thrown.
+- `longmemeval.ts:55` imports `node_modules/gbrain/node_modules/ai/dist/index.mjs`. That path is absent. `ai` is hoisted to `node_modules/ai/dist/index.mjs`. The LongMemEval runner therefore fails to resolve its import in this checkout. I did not execute it, so this is a file-existence finding.
+
+**Other drift [V].** `longmemeval.ts:101` and the TS CLI default (`ts:src/commands/eval-longmemeval.ts:414`) are both `topK: 8`. Published runs used 5. The evals runner reads a JSON array. The TS CLI reads JSONL (`eval-longmemeval.ts:463-469`). `CLAUDE.md` cites 314 tests in `test/eval`. A grep finds 278 `test(` or `it(` lines, so the count is approximate.
+
+## 4. Embedding-cache fixtures
+
+**What is in the checkout [V].** `eval/data/longmemeval/embed-cache/` contains only `README.md`. `git log --all` finds no committed `.sqlite` for that path. The docs describe a warm fixture (`eval/data/longmemeval/embed-cache/[email protected]`, "~150MB"). It is not in the repo. Treat the warm cache as lost until someone confirms otherwise.
+
+**evals cache format [V].** File `eval/reports/longmemeval/embed-cache/embed-cache-<model>@<dims>.sqlite` (gitignored). Table `embeddings(model TEXT, text_hash TEXT, vector BLOB, dims INTEGER, created_at INTEGER)` with primary key `(model, text_hash)`. The vector is float32 little-endian. Key is `sha256(text)`, with no side and no normalization. The `model` column stores `model@dims` (`eval/runner/longmemeval-cache.ts:46-54`, `:80-90`). WAL with a 10 s busy timeout. Both corpus chunks and query texts pass through the same cached transport (`longmemeval.ts:355-356`).
+
+**Default when config is missing [V].** `longmemeval.ts:347-348` default to `text-embedding-3-large` at 1536 dims. The snapshot says ZeroEntropy became gbrain's default embedder in v0.36.2 **[D]**. So an unpinned config changes the cache key and the OpenAI-based published numbers stop reproducing **[I]**.
+
+**TS cache format [V].** `ts:src/eval/shared/embed-cache.ts:107-115` defines `embed_cache(key TEXT PRIMARY KEY, model, dims, byte_len, vector BLOB) WITHOUT ROWID`. The key is derived from `(model, dims, text, side)` where side is `query` or `document` (`:132`). The two formats are not interchangeable.
+
+**Size estimate [I].** A 1536-dim float32 vector is 6,144 bytes. A 150 MB cache holds about 24,000 vectors.
+
+**Recommendation.** Define one neutral fixture: `(model_id, dims, side, sha256(text)) -> f32[]`. Generate it once from the TS engine through the test transport seam (`ts:src/core/ai/gateway.ts:797`, `__setEmbedTransportForTests`). Both the TS and Rust engines then read identical vectors. The report's own cold-cache estimate is about $2 for the full `_s` run **[D]**.
+
+## 5. Adapter design
+
+**Driver protocol.** Run one long-lived process per engine and talk to it over JSON-lines on stdio. Use MCP tool names wherever they exist, so the agent surface stays the same:
+
+- MCP-compatible ops: `put_page`, `get_page`, `list_pages`, `search`, `query`, `add_link`, `traverse_graph`, `get_timeline`, `add_timeline_entry`, `get_stats`. The 12 read tools and 3 dry-run tools in `eval/runner/tool-bridge.ts:41-62` already name them.
+- Harness-only ops: `reset`, `import_page` (with `noEmbed` and `sourceId`), `run_extract {links|timeline}`, `set_config {key, value}`, `load_embedding_fixture`, `version`.
+- Responses are `RankedDoc[]` shaped as in `eval/runner/types.ts:154-160`: `page_id`, `score`, `rank`, `snippet`.
+
+Why not the alternatives: a CLI `--json` process per call is fine for hermetic cats but too slow for 500 LongMemEval questions. HTTP adds a server with no benefit here.
+
+**Shim for the TypeScript side.** Write a thin `oracle-ts` process that implements the protocol over public `gbrain/*` exports (`PGLiteEngine`, `importFromContent`, `hybridSearch`, `operations`). Runners then never import gbrain. This removes the deep imports and the raw SQL from the runners. The shim is the only TS code that touches the schema.
+
+**Embeddings injected, never called [I].** In parity mode, the harness supplies vectors from the fixture (Section 4). Neither engine calls a provider. That isolates ranking and storage from embedding drift. Rust needs a `load_embedding_fixture` hook for this.
+
+**Which runners port trivially**
+- `grep-only.ts`: pure TypeScript, no gbrain import **[V]**. Use as the BM25 baseline unchanged.
+- `judge.ts` and the Anthropic-only runners (Cats 5, 8, 9, 14, 15, 20, 25, 29): harness-side, portable as-is.
+- `longmemeval-cache.ts`, `longmemeval-aggregate.ts`, `longmemeval-batch.sh`, `recorder.ts`: harness-side, reusable.
+- `types.ts` scorers, `multi-adapter.ts` scoring, and the six JSON schemas in `eval/schemas/`: portable contracts.
+- `mcp-contract.ts`: needs only op dispatch by name plus a `remote` flag. Works over MCP stdio.
+
+**Which need work**
+- `longmemeval.ts`: rewrite the ingest and search calls onto the protocol, fix the import, set top-K to 5, and accept JSONL.
+- Cats 3, 4, 7, 10: map onto ops. Mostly mechanical.
+- Cats 13, 13b, 22, 26, 27, 28: replace `setConfig` keys with explicit protocol knobs.
+- Cats 18, 18b, 21: switch from live providers to the fixture.
+- Cats 19, 22, 24, 27, 28: replace raw SQL with ops. These are the most Postgres-coupled.
+
+**Cannot apply without a prior change**
+- Cats 14 and 15 test copied prompts. First extract the think and extraction prompts into a shared module that both sides import.
+- Cats 20, 25, 29 depend on `runBrainstorm` and `runThink`, which exist only in TypeScript. Rust needs its own equivalents, validated by fixtures captured from the TS output.
+- Cat 11 needs transcription keys and fixtures that are not committed.
+- Cat 23 depends on `pg_trgm` semantics. Decide whether Rust must match that behavior before the cat can measure anything.
+- Cat 28 measures PGLite WASM cold start, which is not a product property. Drop or re-target it.
+
+## 6. Proposed phase gates
+
+Each gate compares Rust to a TS run at one pinned commit. Published numbers are sanity checks only.
+
+| Phase | Gate benchmarks | Pass criteria | Needs |
+|---|---|---|---|
+| P1 storage and search MVP | LongMemEval keyword, vector, hybrid (retrieval only, 500 q, top-5). Cat 13b. Cats 1+2 with graph off. Cat 10. Cat 12 | LongMemEval R@5 within 0.2 points of TS on the same fixture. Cat 12 50/50. Cat 10 133/133. Cat 13b top-1 within 1 point of TS | Fixture, `oracle-ts` shim, protocol |
+| P2 knowledge layer | Cats 1+2 full (graph on). Type-accuracy after the call-site fix. Cats 3, 4, 6 baseline, 19, 27 | Cats 1+2 P@5 and R@5 within tolerance of TS (49.1 and 97.9 published). Type-accuracy F1 per type matches TS | Links and timeline ops, `extract` equivalent |
+| P3 jobs and cycles | Minions and tweet-ingest (run in gbrain `test/e2e`). Cat 19 remediate | Durability and throughput match TS on the same harness | Harness outside this repo |
+| P4 multi-source isolation | Cat 22 (0 leaks). Cat 24 (5/5). Cat 23 only after the `pg_trgm` decision | 0 leaks across 4 surfaces | `sourceId` and `sourceIds` on ops |
+| P5 performance | Cat 7 at 1K and 10K. LongMemEval latency | search_keyword P95 at 10K under 200 ms. traverse_paths d=2 at 10K no worse than 176 ms | Ops and perf harness |
+| Later, LLM or provider gated | Cats 5, 8, 9, 14, 15, 20, 25, 29. LongMemEval hybrid+expansion. Cats 18, 18b, 21 | Judge-scored, so tolerance bands only | Judge budget, provider keys |
+
+## Rust engine implications
+
+**Preserve exactly**
+- Recall definition. The runner takes the top-K chunk results and then deduplicates to sessions (`longmemeval.ts:447-468`). Recall@5 is therefore over chunk hits, not over sessions. A Rust engine that returns the top five sessions will not reproduce the published numbers **[V]**.
+- Slug normalization. `putPage` lowercases, but `upsertChunks` does not. The runner lowercases at the boundary (`longmemeval.ts:439`). Decide whether Rust lowercases on write; that is simpler and the TS behavior is a quirk, not a feature **[I]**.
+- Chunking granularity (`splitBody`). The keyword 19.8% depends on it **[D]**.
+- Scoring constants from the reports: RRF k=60, final re-score `0.7 * rrf + 0.3 * cosine`, compiled-truth boost 2.0, and the source-boost map **[D]**.
+- The NDJSON row shape `{adapter, question_id, question_type, retrieved, ground_truth, hit_at_k, num_haystack, latency_ms, error?}` and the resume key `(adapter, question_id)` (`longmemeval.ts:124-138`, `:486`).
+- Sealed qrels. Adapters receive only `slug, type, title, compiled_truth, timeline` (`types.ts:56-61`).
+
+**Can simplify**
+- PGLite-specific machinery: engine recycling every 25 questions (`longmemeval.ts:317`), the 90 s per-question watchdog (`:394`), and the 3-worker, 10-minute batch wrapper. A Rust in-process index can reset in place.
+- Raw `TRUNCATE` by enumerating `pg_tables`. Replace with a `reset` op.
+- Two embedding-cache formats. Replace with one fixture.
+- Deep imports and `package.json` version capture. Record the binary's version and git SHA instead.
+
+**Postgres feature each piece depends on [V]**
+
+| Piece | Postgres feature | Location |
+|---|---|---|
+| Keyword search | tsvector and `ts_rank_cd` | Published description of `searchKeyword` (report §4) |
+| Vector search | pgvector `vector` type, `::vector` cast, HNSW | `cat19-doctor-remediate.ts:212`, report §4 |
+| Reset between questions | `pg_tables`, `TRUNCATE ... CASCADE` | `longmemeval.ts:224-233` |
+| Link writes | Unique constraint plus `ON CONFLICT DO NOTHING RETURNING` | `cat19:129`, `cat27:265` |
+| Sources | `jsonb` config, `ON CONFLICT` | `cat22:60`, `cat28:62` |
+| Provenance | `source_kind`, `source_uri`, `ingested_via`, `ingested_at` columns | `cat24:105` |
+| Dimension check | `pg_attribute.atttypmod` | `cat18:96-99` |
+| Soft delete | `pages.deleted_at` | `cat19:91,112` |
+| Embedded timestamp | `now()` | `cat19:212` |
+| Phantom resolution | `pg_trgm` (per snapshot) | `cat23` |
+
+**Risks**
+- Oracle drift. The published numbers come from v0.28.8, and the installed copy is 0.41.29.0. Reproduce at one pinned commit before trusting any tolerance.
+- Schema coupling. Any runner that touches a column breaks when Rust picks a different schema. Keep runners on ops only.
+- Non-determinism. `perf.ts` uses `Math.random()` for sampling (lines 176, 182). Haiku expansion drifts up to 0.2 points (report §11). `multi-adapter.ts` is seeded (`shuffleSeeded`).
+- Silent provider drift. An unpinned embedder changes the cache key and the published numbers.
+- Broken Cat 2 and misleading Cat 14. Type-accuracy does not run as checked out. Cat 14's win rate measures a copied prompt, not gbrain code.
+
+## Open questions
+
+1. Which gbrain commit is the parity target: the installed 0.41.29.0 (`041d89b`), TS master (`36bd05806a`), or the v0.28.8 published baseline? Parity needs one, pinned in the harness.
+2. Is the warm LongMemEval cache recoverable from another machine? If not, is a ~$2 regeneration acceptable?
+3. Should the parity driver be the TS repo's `gbrain eval longmemeval` (judge, receipts, `--embed-cache`, `--call-plan`) rather than `longmemeval.ts`? It already exists and is maintained with the engine.
+4. Should `eval brainbench` in the TS repo (know-to-ask, push, write-back, continuity; fixtures in `ts:evals/brainbench`) join this oracle? It shares the name "BrainBench" but is a different suite. The naming collision needs a rename or a note.
+5. Should Cats 14 and 15 wait until their prompts are moved into gbrain code, or be dropped from parity entirely?
+6. Who owns the shim that replaces deep imports, and does it live in the TS repo or in gbrain-evals?
+7. Do we require Rust to match `pg_trgm` phantom-redirect semantics (Cat 23), or accept a documented difference?
+8. Should the embedder default in the oracle stay OpenAI (matching published numbers) or move to the current ZeroEntropy default?
+9. Does the multimodal fixture set (Cat 11, `eval:fetch-multimodal`) exist anywhere? The script it names is not in `package.json` **[V]**.
diff --git a/docs/designs/rust-engine/research/12-perf-and-operations.md b/docs/designs/rust-engine/research/12-perf-and-operations.md
new file mode 100644
index 0000000000..5f47a11d4f
--- /dev/null
+++ b/docs/designs/rust-engine/research/12-perf-and-operations.md
@@ -0,0 +1,180 @@
+# 12. Performance, scale and operations map
+
+Line numbers refer to gbrain 36bd05806a.
+
+Reference: TypeScript gbrain v0.60.733.0 at garrytan/gbrain (read-only). Eval repo: garrytan/gbrain-evals (commit 9ecc5b20, read-only, only small-corpus latency checks found).
+
+Evidence labels used below:
+
+- [V] read in source or doc during this pass.
+- [R] a measurement recorded in a repo doc, CHANGELOG or TODO. Not re-run here.
+- [I] my inference.
+
+No benchmark or test was executed for this map. Counts come from rg or python over the source tree; where a count is a regex approximation, the text says so.
+
+## Part A: Performance
+
+### A.1 Measured pain points
+
+| Symptom | Measured number (scale) | Root cause | Citation | Does an embedded Rust store fix it? |
+|---|---|---|---|---|
+| Hot read plan falls into nested loops; `readAdjacencyBoosts` stalls | about 72 s, fixed to 21 ms by a full ANALYZE (reporter brain, size not stated) [R] | No planner statistics; PGLite has no autovacuum | TODOS.md:556 | Yes if access paths are hand-coded. No if SQL and its planner stay. |
+| Type or date filter disables the vector index walk, planner seq-scans and sorts `content_chunks` | 462 ms filtered vs 56 ms unfiltered (Postgres 20k); 195 vs 58 ms (PGLite 10k) [R] | `vector-statement.ts` marks filtered statements narrowed and skips the HNSW walk | TODOS.md:50 (open, P2) | Yes, if the ANN supports filtered search with a selectivity estimate. Needs design. |
+| Source-scoped vector search returns too few neighbours; fallback runs 4 to 8 s | 4 to 8 s fallback; source holds a few percent of a large brain [R] | HNSW walk runs over the whole brain, then filters | CHANGELOG.md:14686 (0.60.131.0) | Partly. Exact scan of up to about 25k chunks per source is cheap in memory; larger scopes need filtered ANN. |
+| Freshly imported 1M to 2M chunk brain: scoped search slow, half of broad searches fall back to keyword | 0.5 to 8 s; 8 to 75 ms p50 after refresh [R] | Stale statistics make the planner sort instead of walking HNSW | CHANGELOG.md:14572 (0.60.135.0) | Yes, if the store owns its statistics and refreshes them after bulk writes. |
+| Cold vector search after Postgres restart | vector stage 1.4 s median, 3.0 s p95; 41 ms median after prewarm (50 s to prewarm 11 GB) [R] | Index not in `shared_buffers` | CHANGELOG.md:6694 (0.60.449.0) | Partly. mmap plus explicit prewarm helps; an 11 GB index is still disk-bound. |
+| PGLite HNSW build out of memory, then wedged | OOM at 1 GB `maintenance_work_mem`; wedged at 1.5 GB; 663 s; chunk index 1.9 GB (PGLite 50k) [R] | pgvector builds the whole graph in memory inside a 2 GiB WASM heap; WAL checkpoint runs inside one statement | CHANGELOG.md:14285, 14294 (0.60.146.0); docs/ENGINES.md "PGLite vector index ceiling" | Yes. A bounded-memory builder with no WASM cap removes this. |
+| PGLite vector ceiling | a 248,802-chunk build takes about 11 min and makes a 1.9 GB index; graphs above 1.5 GiB (about 300k chunks at 1024 dims) are refused with `pglite_vector_index_too_large` [R] | WASM heap cap plus `maintenance_work_mem` sizing | docs/ENGINES.md "PGLite vector index ceiling" | Yes. |
+| Postgres HNSW build under-provisioned | 4.3x slower at 250k chunks with 256 MB; 1M-chunk build 103 s on 16 vCPU with 12 GB and 8 workers [R] | pgvector `maintenance_work_mem` and parallel workers | docs/ENGINES.md "Vector index sizing" | Yes, no DB knob. Build time becomes an implementation benchmark. |
+| Index size | about 7.6 GiB per million 1024-dim chunks as `vector` (9.8 GiB at 1.28M chunks); halfvec is one third of that [R] | Vector and graph links stored together | docs/ENGINES.md "Vector index sizing" | Partly. Quantised vectors (f16 or int8) are a design choice to make. |
+| PGLite 20k-page vector phase stalls | 36 min before the WAL guard; 173 s after; per-batch time still rises from 2.1 s to 6.3 s; RSS about 2.5 GiB [R] | Nested checkpoint inside WASM; superlinear per-batch cost | TODOS.md:209 (open, P2) | Yes for the WASM part. The superlinear growth is unexplained, so it is an open question for Rust too. |
+| Autovacuum never finishes on a 10M-chunk brain | millions of dead rows kept in every index [R] | gbrain's own ANALYZE took the table lock; Postgres cancels autovacuum after one second of waiting | CHANGELOG.md:9814 (0.60.318.0) | Yes, if the store has no MVCC bloat (in-place updates with compaction, or append-only with compaction). Compaction must be designed. |
+| Postgres stats wait for churn | autovacuum analyses only after about 10% of a table changes | Autovacuum threshold | TODOS.md:46 (open, P2) | Yes for embedded storage. No for remote Postgres mode. |
+| MCP search slow on Postgres between 10k and 20k pages | 615 ms at 20k (v0.60.53.0), now 33.7 to 74.1 ms; PGLite 27 ms [R] | Plan growth, since fixed | TODOS.md:378, 379 (closed) | Historical. Shows plan instability is a real risk. |
+| JIT compilation on a common title lookup | 17 ms execution, 504 ms JIT (40k pages, Postgres) [R] | `jit_above_cost` crossed by visibility subplans | TODOS.md:457 (open, P3) | Yes, no JIT. |
+| PGLite per-statement overhead | owner wall time per write 113 to 30 ms; WASM time 60.7 to 13.3 ms; 217 to 176 SQL statements; 473 relation-file opens per write (1,000 writes) [R] | Each `query()` parses, plans and describes over five protocol round trips | docs/research/pglite-persistence-throughput-2026-09-29.md | Yes. |
+| Committed write throughput | PGLite 8.9 to 31.7 writes/s; Postgres 11.2 to 13.5 writes/s (1,000 writes, standard-30 VM) [R] | Same as above | same doc | Yes for PGLite. |
+| Round trips to a pooled remote Postgres | `put` 4.5 s and 228 round trips to 4.1 s and 204 at 40 ms RTT; no-op sync 70 to 90 round trips to about 32 [R] | Network round trips per statement | CHANGELOG.md:8445 (0.60.375.0), 9275 (0.60.344.0) | Not applicable to embedded. Remote mode keeps the problem. |
+| Managed sync catch-up far from DB | about 150 pages/min; 10,000-file backlog 1.2 h, was 5.4 h [R] | Per-page round trips | CHANGELOG.md:16628 (0.60.73.0) | Same as above. |
+| Import cost drifts upward | last 10% of pages cost about 8x the first 10% (gate is 1.5x); 6.9 to 8.3 after a fix [R] | Not identified; the gate is partly report-only | TODOS.md:404; docs/fix-wave-notes/capy-fix-wave-8.md:18 to 24 | Unknown. Needs a benchmark before choosing a design. |
+| Doctor `purged_page_facts` slow | 6.7 to 7.0 s Postgres, 24 to 26 s PGLite, now about 1.0 s on both (1M active facts) [R] | Not stated in the entry (I: a scan over all facts) | CHANGELOG.md:80 (0.60.733.0) | Yes, if the store indexes the predicate. |
+| Quoted-marker screen quadratic | 12 to 18 s for 40,000 mentions, minutes for a 24 MiB page; now about 100 ms [R] | Re-reading the page for each mention (algorithmic, not a DB issue) | CHANGELOG.md:4826 (0.60.534.0) | No. The fix was algorithmic; Rust only helps the constant factor. |
+| Entity name batch slow on PGLite | about 2.4 s for 50 names at 55k pages [R] | Suffix `LIKE` with no index, scanned per name | TODOS.md:56 (open, P2) | Only with an index designed in. |
+| Saved-fact match on PGLite without trigram index | p50 19.6 to 3.4 ms at 10k facts; 94 to 12 ms at 50k; 167 to 23 ms at 100k [R] | Missing trigram index | TODOS.md:48 (P3, dropped by its gate) | Yes, if the store has a fuzzy index. |
+| Cold process first query | budget 2,172 ms PGLite, 1,326 ms Postgres (MCP path, 10k) [R]; snapshot ON 879 ms vs OFF 3,000 ms to connect and init schema (local, master v0.60.11.0) [R] | WASM boot and schema replay (I) | scripts/scale/budgets.json; docs/designs/refactor-wave-1/perf-baseline.md:149 to 152 | Yes. Removes WASM boot and replay (I). |
+| Connection exhaustion on Postgres | each read-only serve held a 3-connection pool; sessions ran out (`EMAXCONNSESSION`) [R] | Pool per process | CHANGELOG.md:6345 (0.60.464.0) | Remote mode only. |
+
+### A.2 Recurring root causes [V]
+
+1. Planner statistics. PGLite has no autovacuum (TODOS.md:556). Postgres autovacuum waits for about 10% churn (TODOS.md:46). gbrain's own ANALYZE blocked autovacuum (CHANGELOG.md:9814). Stale statistics flip vector search to a full sort (docs/ENGINES.md search section, "Without those statistics the vector candidate statement sorts every eligible chunk").
+2. Filters versus ANN. A filter disables the walk (TODOS.md:50), and a post-filter over a global walk loses neighbours (CHANGELOG.md:14686).
+3. WASM runtime. A 2 GiB heap cap (docs/ENGINES.md), per-statement protocol overhead (research doc), and an automatic WAL checkpoint that could spin at 100% CPU inside one statement (src/core/pglite-engine/checkpoint-guard.ts:1 to 12).
+4. Remote round trips. Every remote pooler statement costs a round trip. The fixes in CHANGELOG.md:8445, 8582, 9275 are pipelining and fewer statements.
+
+### A.3 Scales the Rust engine must handle
+
+| Dimension | Documented scale | Source |
+|---|---|---|
+| Pages | 600,000 (production-shaped soak, two hours, 2 ms and 65 ms network delays) | docs/STABILITY.md:49; CHANGELOG.md:8144 (0.60.387.0) |
+| Pages | 165,000 "production class"; 46k to 55k brains in reports | TODOS.md:5137; UPGRADING_DOWNSTREAM_AGENTS.md:400; TODOS.md:56 |
+| Chunks | 1M to 2M freshly imported; about 10M in a reporter's brain; 1.28M in the sizing example | CHANGELOG.md:14572, 9814; docs/ENGINES.md |
+| Facts | 1,000,000 active (doctor check); 100k with ranked recall of 51 ms p95 on Postgres | CHANGELOG.md:80; 13701 (0.60.169.0) |
+| Vector index | 11 GB HNSW on the 600k soak | CHANGELOG.md:6694 |
+| Dimensions | 1024 (Voyage default in CLI profile; image and multimodal columns); 1536 (base `content_chunks.embedding` in src/schema.sql:360); up to 8192 accepted by the embedding-column registry; a 2560-dim halfvec was used once | perf-baseline.md:63; CHANGELOG.md:40696, 40702 |
+| PGLite ceiling | about 300k chunks at 1024 dims before refusal | docs/ENGINES.md |
+| CI scale tier | 10k and 20k nightly; 50k gated on five nights of trend | scale-tier.yml:9, 30 to 35; scripts/scale/README.md. CHANGELOG.md:8144 describes the earlier tier as 300k pages. |
+
+The CI fixture is not a real embedding. `SCALE_VECTOR_DIMS = 16` in `scripts/scale/fixture.ts:70` places 16 nonzero dimensions in a column of width 1024 (fixture.ts:69 to 74). HNSW navigates such vectors far more easily than real ones, so scale-tier HNSW latencies are optimistic.
+
+### A.4 Measurement harness state [V]
+
+- `scripts/scale/budgets.json` holds p50 budgets at 3x the calibration run on Ubicloud standard-8. Postgres: `get_health` 597 ms, `search` (MCP path, remote) 151 ms, `query` hybrid 252 ms, `find_orphans` 86 ms, cold first query 1,326 ms. PGLite: `get_health` 463 ms, `search` (MCP path) 122 ms, `query` 74 ms, cold first query 2,172 ms. These are report-only until `trend.ts` reports stable ceilings.
+- `tests/heavy/rss-baseline.json` is an empty stub. No Linux peak-RSS baseline exists, so every RSS run is informational. A Rust port must create its own baseline.
+- `tests/heavy/read_latency_under_sync.sh` is informational unless `STRICT_LATENCY=1`.
+- `docs/eval-bench.md:256` sets the replay gate: mean latency within 50 ms of captured, and more than 2x anywhere is an alarm. The gbrain-evals repo has only small latency tables (for example 1.92 ms p50, docs/benchmarks/2026-04-19-knowledge-runtime-v0.13.md), so it is not a scale source.
+
+## Part B: Operations
+
+### B.1 Doctor [V unless marked]
+
+- Registry: `DOCTOR_CHECK_REGISTRY` is an array of about 165 entries (src/commands/doctor/registry.ts:206 to 385). Four tiers: `ops`, `quick`, `standard`, `deep` (context.ts:30). Non-interactive budget is 90 s (default-budget.ts:15).
+- Modules: 207 files in `checks/`; 118 export a `*Entry`. About 340 distinct check names appear in `emits:` arrays (regex count, approximate). Categories are brain, skill, ops and meta (src/core/doctor-categories.ts).
+- Engine-touching: 130 of 207 check files reference engine methods or SQL (regex, approximate).
+- Postgres-catalog checks (15 files): `postgres-tls.ts` (`pg_stat_ssl`), `planner-stats.ts` (`pg_stat_user_tables`), `vector-plan.ts` (`pg_class`, `pg_index`, `pg_am`, `pg_stats`), `keyword-plan.ts` (`pg_stats`), `core-health.ts` (`pg_extension`), `schema-health.ts` (`pg_roles`, `pg_class`), `function-search-path.ts` and `schema-function-bodies.ts` (`pg_proc`), `embedding-health.ts` (`pg_index`), `mcp-request-log.ts` (`pg_total_relation_size`), `persistence-requests.ts`, `queue-assets.ts`, `managed-guard.ts`, `graph-embedding.ts` (`information_schema`), `postgres-cancellation.ts`, `safe-index.ts`.
+- PGLite-only: `pglite-worker.ts` (312 lines); `pgliteDataDirEntry` in the registry. Twenty-two files branch on `engine.kind`. Three check files set `opsPglite: 'not_applicable'`, which skips them on PGLite under `--tier ops` (context.ts:50 to 56).
+- Rust mapping: engine-neutral checks (embedding coverage, page health, link integrity, facts and takes, skill routing, sync freshness) port by reading the Rust store. The Postgres-catalog checks and the pooler and connection checks (`session_lane_budget`, `pool_reap_health`, TLS) have no meaning in embedded mode and should be replaced by store checks: file lock, WAL or journal size, index age, statistics age, file-level integrity.
+
+### B.2 Schema migrations [V]
+
+- 313 migration files (v2 to v318). Versions 1, 17, 18, 19 and 100 have no file. 242 declare `idempotent: true`; 76 have a `handler:`; 31 use `sqlFor`; 40 set `transaction: false`. Types: src/core/schema-migrations/types.ts:20 to 32.
+- Ledger: no migrations table. The ledger is one row, `config.version`, seeded to `'1'` in src/schema.sql:726. `runMigrations` reads it (src/core/migrate.ts:381) and advances it after each migration succeeds (migrate.ts:513). Migrations must run in version order (migrate.ts:385 to 389).
+- Runner: `tryRunPendingMigrations` (migrate.ts:303) waits up to 5 s for a lock with a 250 ms poll. Each migration runs under `SET LOCAL statement_timeout` and `lock_timeout` (migrate.ts:214 to 242). Retries on SQLSTATE 57014 use 5 s, 15 s and 45 s backoff (migrate.ts:149 to 167).
+- Timeouts: migration statement timeout 600,000 ms (src/core/migration-timeout.ts:19); schema lock timeout default 60 s (src/core/postgres-engine/schema-lock-timeout.ts:46), set by `GBRAIN_SCHEMA_LOCK_TIMEOUT_SECONDS`.
+- Lock: Postgres holds advisory key 42 across connections (src/core/schema-migration-lock.ts:5 to 9; postgres-engine/init-schema-lock.ts). PGLite is serialised in-process only, because its kernel lock admits one process.
+- Fresh install: the schema blob seeds version 1, so a new brain replays every migration and prints one summary line (migrate.ts:470 to 486).
+- Schema shape (src/schema.sql, 3,794 lines): about 134 table definitions, 177 `CREATE INDEX`, 32 `ENABLE ROW LEVEL SECURITY`, 26 `CREATE TRIGGER`, 3 `CREATE EXTENSION`, 3 `NOTIFY`, 9 `tsvector`. `src/core/pglite-schema.generated.ts` is 3,030 lines.
+
+### B.3 Upgrade and engine switch [V]
+
+- `gbrain upgrade` (src/commands/upgrade.ts:51). Flags: `--channel stable|alpha`, `--dry-run`, `--stop-mcp`, `--no-restart`, `--swap-only`, `--restart-only`. Post-upgrade migrations run through `gbrain post-upgrade` (docs/UPGRADING_DOWNSTREAM_AGENTS.md:24); `apply-migrations --yes` is the explicit form.
+- Install methods: `bun`, `bun-link`, `binary`. `canSelfUpdate` returns true for bun and bun-link, and for binary only on darwin-arm64 and linux-x64 (src/core/self-upgrade.ts:302 to 313).
+- Binary swap (src/core/binary-self-update.ts:1 to 40): download to a sibling, verify SHA-256 against the SLSA attestation from the GitHub REST API (builder id pinned to this repo's release workflow on master, lines 53 to 58), smoke-test `--version`, check version against tag, then `rename`. Any failure leaves the old binary. The sigstore chain is not validated, and the header says so.
+- bun path: `bunReinstallCommand` runs `bun remove -g gbrain` then `bun add -g` the pinned tag, because an in-place tag swap corrupts the global package (src/commands/upgrade.ts:562 to 569).
+- Engine switch: `gbrain migrate --to postgres|supabase|pglite` (src/commands/migrate-engine.ts:6 to 8). PGLite to Postgres uses graduation (src/commands/migrate-graduation.ts), which needs a plan hash (`--yes --expect <hash>`) and refuses while a live `gbrain serve` holds the PGLite kernel lock (docs/ENGINES.md, "graduation-writer-held"). The legacy path re-creates pages through `putPage` and copies stored chunk embeddings with `upsertChunks` (src/commands/migrate-engine.ts:550), so it makes no embedding provider call.
+
+### B.4 Backups [V]
+
+- `gbrain backup status|check` (src/commands/backup.ts:1 to 20) is a coverage verdict, not a backup. It checks Git HEADs, remote readback, and the install receipt, and caches the verdict at `~/.gbrain/backup-status.json` (docs/operations/backup-check.md).
+- The DB file is deliberately gitignored. Git evidence covers committed files only. DB-only pages, facts and config need a separate drill. PGLite DB-only pages warn; Postgres DB-only pages are info.
+- Markdown export (`gbrain export --source <id> --dir ...`) is not a full database backup (CLAUDE.md:221).
+- Implication: the Rust store file is outside Git, so it needs its own backup story, or the design relies on re-sync from Markdown.
+
+### B.5 Spend controls [V]
+
+- `spend.posture`: `gated` (default) or `tokenmax`. `tokenmax` keeps the ledger and removes the ceiling, except that an explicit `--max-usd` always wins (docs/operations/spend-controls.md:16 to 35).
+- Key gates (docs/operations/spend-controls.md:140 to 161): backfill per source per 24 h $25 (`embed.backfill_max_usd_per_source_24h`); backfill per job $10 (`embed.backfill_max_usd`); `--yes` alone uses the estimate times 1.5 (floor $0.25) or a $5 default cap; atom auto-drain $2.00 per day; dream `extract_atoms` $0.30 per phase; fence repair $0.30 per page and $1.00 per day; Life Chronicle $0.25 per call and 200 calls per rolling 24 h; dream `synthesize` $5 per run.
+- Ledger tables: `page_embedding_budget`, `decide_spend`, `page_derivation_spend`, `chat_usage_log` (src/schema.sql:2062, 3138, 2265, 1057).
+- Implication: spend state is data in the store, so a Rust port must carry these tables or re-create their semantics.
+
+### B.6 Distribution [V]
+
+- Release binaries: `bun build --compile` on release.yml, targets `bun-darwin-arm64` (macos-26) and `bun-linux-x64` (ubuntu-latest) (.github/workflows/release.yml:125 to 131, 170). Bun is pinned to 1.4.4 (release.yml:109). No Windows or Intel macOS asset.
+- Installer: `bun install -g github:garrytan/gbrain#stable` (README.md:40, 65). The docs forbid `npm install -g gbrain` and `bun add -g gbrain`. `package.json` `engines.bun` is `>=1.4.4` (package.json:261 to 262).
+- Plugin lane: `.agents/gbrain-launcher` resolves the binary from `$GBRAIN_BIN`, then PATH, then `~/.bun/bin/gbrain` (lines 9 to 11). The Claude and Codex manifests start `serve --surface full --source-guard` through the launcher.
+- OpenClaw: `openclaw.plugin.json` names the plugin `gbrain-context-engine`, and its config schema (lines 8 to 16) asks for a `database_url` (a PostgreSQL URL, "Supabase recommended") and an OpenAI key. This is Postgres-specific and must change.
+- Version stamps: `VERSION`, `package.json`, `openclaw.plugin.json`, `.claude-plugin/plugin.json`, `.codex-plugin/plugin.json` all read 0.60.733.0 today. CLAUDE.md:329 calls this a five-file lockstep. CI fails when they drift.
+- Compiled binary embeds PGLite WASM; `scripts/check-pglite-embedded.sh` guards this (TODOS.md:8150 area). A Rust engine drops that lane.
+
+### B.7 What a Rust engine must replicate for users to switch [I]
+
+1. The command name `gbrain` on PATH and in `~/.bun/bin`, because the launcher and manifests hard-code it.
+2. The agent operator contract: `--json` envelopes, error codes (docs/guides/error-codes.md), exit codes (3 for confirmation required), and the `ask_user`-style fix objects. Harnesses parse these.
+3. The MCP tool names and parameter schemas, with the schema budget tests as a guard.
+4. Config keys and file locations (`~/.gbrain/config.json`, `~/.gbrain/brain.pglite` for the old store, `GBRAIN_*` env vars with env-over-config precedence).
+5. Spend gate defaults and the `spend.posture` switch.
+6. An upgrade path: `gbrain upgrade --channel stable|alpha`, a verified asset per platform, and a rollback.
+7. A reader for the old brain: either a dump from the TypeScript binary (graduation-style, with a plan hash) or a native PGLite data-dir reader. The data dir is Postgres on disk, so a Rust engine cannot read it without a Postgres-compatible reader [I].
+8. Doctor output shape (`checks[]` with `name`, `status`, `message`, `details.code`), since automation keys on check names.
+
+## Rust engine implications
+
+Must preserve exactly:
+- The one-writer rule. PGLite serves one process and hands off to `serve` (docs/ENGINES.md graduation section). The Rust store should keep one owner with a heartbeat (pglite-lock.ts:12 uses 30 s) and a documented handover.
+- Check names and status values that automation reads, and the `version` ledger semantics so the Rust engine can tell which TypeScript schema a brain last saw.
+- Spend gate defaults and the ledger rows (`page_embedding_budget`, `decide_spend`, `chat_usage_log`).
+- The release identity: the attestation builder id is pinned to this repo's `release.yml` on master (binary-self-update.ts:53 to 58). A Rust engine release needs a new workflow and a new expected id, or a different distribution channel.
+
+What can be simplified:
+- No migration ledger beyond a version number. Rust can use its own format and a single version key.
+- No advisory locks, LISTEN/NOTIFY, SKIP LOCKED or pooler handling in embedded mode. These account for about 15 to 30 source files each in TypeScript (regex counts: `pg_advisory` 30 files, `LISTEN` 15, `SKIP LOCKED` 15, `FOR UPDATE` 127).
+- No WASM boot, no snapshot cache, no checkpoint guard, no `maintenance_work_mem` sizing.
+- No `EXPLAIN`-based plan gates, because access paths are fixed. The scale-tier planner gates (Nested Loop inner-loop, planner stats) stop applying.
+- No binary download integrity code beyond the SHA-256 check if Rust ships signed artifacts.
+
+Postgres features each piece depends on, and their Rust replacement:
+- pgvector HNSW (62 TS files reference hnsw, 3 schema lines): replace with an in-process ANN with filtered search and a bounded-memory build.
+- tsvector and `ts_rank`, `pg_trgm`: replace with an inverted index and trigram or n-gram index.
+- JSONB (128 schema lines): typed columns or a document blob.
+- Triggers (26): explicit application-level writes in one transaction.
+- RLS (32 schema lines): application-level read policy (visibility, source grants).
+- Recursive CTEs (14 files): graph traversal in code.
+- Advisory and row locks, `FOR UPDATE`: single-writer lock plus application-level transactions.
+- `pg_stats`, autovacuum: owned statistics maintained by the store.
+
+Risks:
+- ANN filtered search. The TS code's biggest documented pain (filters, scope, freshly imported bulk) lives in ANN selectivity. Expect to benchmark and design this before writing code.
+- Build time and memory for a 1M to 10M-chunk HNSW. The TS numbers are the baseline to beat: 663 s at 50k (PGLite) and 103 s at 1M (Postgres, 12 GB).
+- Import ratio drift (8x last-to-first at 10k). Root cause unknown, so a Rust port may inherit it.
+- The CI fixture is 16-dim. Build the Rust benchmark on real 1024 and 1536-dim vectors.
+- Moving old brains. Without a reader for the PGLite data dir, users must export through the TypeScript binary first.
+
+## Open questions
+
+1. Which path migrates an existing PGLite brain: a native PGLite data-dir reader, or a dump written by the TypeScript binary (graduation style)?
+2. Is the migration statement timeout 600 s (code, src/core/migration-timeout.ts:19) or 30 minutes (CHANGELOG.md:8699, 0.60.365.0)? The code was used here; the discrepancy needs a human decision.
+3. Who owns the Linux RSS baseline? `tests/heavy/rss-baseline.json` is still empty, so the Rust port has no memory target from the TS side.
+4. What causes the superlinear per-batch growth in the PGLite vector phase (TODOS.md:209) and the 8x import drift (TODOS.md:404)? Both are open.
+5. Does the Rust engine keep the multi-process `serve` model (CLI, cron and harness all talking to one owner), or does it move to a single HTTP owner?
+6. Should the Rust engine read Postgres brains directly for remote mode, or only export from them? This decides whether the pooler and connection checks survive.
+7. Does the distribution go through a new GitHub release workflow with a new attestation identity, and which platforms (Windows is not published today)?
+8. The 50k scale tier and the 600k soak are not reproduced here. Does the Rust team need its own 600k-page fixture with real 1024-dim vectors?
diff --git a/docs/designs/rust-engine/research/README.md b/docs/designs/rust-engine/research/README.md
new file mode 100644
index 0000000000..c00bd14f77
--- /dev/null
+++ b/docs/designs/rust-engine/research/README.md
@@ -0,0 +1,31 @@
+# Rust engine research maps
+
+These twelve maps are research for a Rust third engine behind `BrainEngine`, next to PGLite and Postgres. The design they feed is in [`../../RUST_ENGINE.md`](../../RUST_ENGINE.md). Each map reads the TypeScript implementation and its tests and records what a Rust engine must match, what it can simplify, and which questions are still open.
+
+**Precedence.** The maps were written before the design was settled, and some of their implication sections explore a wider rewrite: one engine instead of a parity matrix (`01`), a Rust CLI and middleware (`05`), dropping the engine test matrix and TypeScript guards (`10`), a stdio `oracle-ts` route for gbrain-evals (`11`) and dropping the embedded PGLite lane (`12`). Those passages are kept as research history and do not bind. The approved [`../../RUST_ENGINE.md`](../../RUST_ENGINE.md) governs: it keeps the TypeScript surfaces, keeps PGLite and Postgres as engines, and defers the stdio route. Where a map and the plan disagree, the plan wins.
+
+## Pinned commits
+
+- gbrain: `36bd05806a` (v0.60.733.0). Line numbers in every map refer to this commit.
+- gbrain-evals: `9ecc5b20` (2026-05-24). That commit is about 3,500 commits behind gbrain-evals main as of 2026-11-16, so `11` is history for that repository: its counts, broken-runner notes and pin status are out of date, and the plan's D11 records the current terms.
+
+## Evidence tags
+
+Each map tags its claims as verified (code read), reported (doc quote) or inferred. The tag letters differ slightly per map (for example `[V]`, `[I]`, `[R]`, `[D]`, `[C]`, or "(inferred)"), and each map states its own legend near the top.
+
+## Maps
+
+| Map | Summary |
+|---|---|
+| [01-engine-interface.md](01-engine-interface.md) | The `BrainEngine` seam, `engine-sql`, and how much raw SQL bypasses the interface. |
+| [02-schema.md](02-schema.md) | `src/schema.sql` table by table: indexes, triggers, RLS, migration-created tables, and graduation inventory. |
+| [03-search-pipeline.md](03-search-pipeline.md) | Retrieval and ranking end to end: arms, fusion, boosts, filters, and the Postgres features each piece needs. |
+| [04-ingest-chunk-embed.md](04-ingest-chunk-embed.md) | The write path: parse, chunk, embed, store, plus the triggers that fire on write. |
+| [05-cli-mcp-surface.md](05-cli-mcp-surface.md) | The agent-facing surface: operations, CLI verbs, MCP surfaces, scopes, and exit codes. |
+| [06-graph-and-knowledge.md](06-graph-and-knowledge.md) | The knowledge layer: links and graph traversal, entities, facts, takes, timeline. |
+| [07-jobs-and-cycles.md](07-jobs-and-cycles.md) | The Minions job queue, autopilot, and the cycle phases. |
+| [08-concurrency-and-persistence.md](08-concurrency-and-persistence.md) | Locking, persistence ownership, and the multi-process model. |
+| [09-access-and-security.md](09-access-and-security.md) | Trust boundary, credentials, per-member access, and the invariants the database enforces today that must move into Rust code. |
+| [10-tests.md](10-tests.md) | The TypeScript test suites as a parity oracle, and a `GBRAIN_BIN` harness proposal. |
+| [11-gbrain-evals.md](11-gbrain-evals.md) | gbrain-evals as a parity oracle: runners, gates, and what a Rust engine must satisfy. |
+| [12-perf-and-operations.md](12-perf-and-operations.md) | Performance, scale, and operations: sizing, budgets, install and upgrade paths, and what users need to switch. |
diff --git a/docs/designs/rust-engine/review-record.md b/docs/designs/rust-engine/review-record.md
new file mode 100644
index 0000000000..3fc4587d75
--- /dev/null
+++ b/docs/designs/rust-engine/review-record.md
@@ -0,0 +1,1176 @@
+# Rust engine plan: review record
+
+Companion to [../RUST_ENGINE.md](../RUST_ENGINE.md). The plan was reviewed with gstack /autoplan (CEO, DX and Eng phases; design skipped, no UI), then the shadow-mode revision had a focused CEO, DX and Eng review. The "Review requirements" blocks are binding on the PRs they name.
+
+## Review requirements
+
+Requirements accepted in review. Each restates a change made in the sections above and names its check.
+
+<!-- autoplan-accepted:ceo -->
+- Addon identity: the addon exports `target`, `engine_abi`, `engine_build` (digest of the `rust/` tree), `catalog_version` and `format_versions`; each release pins the exact SHA-256 per target in a generated manifest; the loader refuses any other file or any mismatch except under `GBRAIN_RUST_ENGINE_ADDON`. Verify: loader unit tests for a wrong digest, a wrong `engine_abi`, a wrong catalog or format version, and the override path, each giving `engine_unavailable` with its reason and no file opened in the brain directory.
+- Addon path and upgrade: addons live at `<gbrain home>/engines/rust/<engine_build>/<target>.node`; `gbrain upgrade` and `self-upgrade` stage and verify the new addon before switching and keep the previous addon until the new one opens the brain; a raw `bun install -g` upgrade fetches in `post-upgrade` or reports `engine_unavailable` with the fix command and touches no data; `gbrain engine status` reports the addon digest, store format and index lag. Verify: the addon upgrade drill (online, offline, interrupted fetch) on darwin-arm64 and linux-x64-glibc before the preview.
+- Backup and restore: `gbrain backup create` and `backup restore` work on Rust brains (PR 21b, `src/core/backup/`, `src/commands/backup.ts`); a full-store restore drill passes on both preview targets before D8. Verify: restore into an empty home, then the verification digest equals the source digest for every relation.
+- Preview contract (D12): the preview is limited to darwin-arm64 and linux-x64-glibc, opens only with verified backup and restore and the staged upgrade, and Windows and other platforms come before PGLite deprecation on each.
+- PGLite deprecation criteria 11 and 12: every PGLite-only surface (backup create and restore, agent-install setup, `init --pglite`, `pglite-repair`, `reinit-pglite`, eval harnesses constructing `PGLiteEngine`) has a Rust path or a stated replacement; an offline upgrade drill passes on each platform being deprecated.
+- Checkpoint C1 after Phases 2, 3 and 4: inputs are `bakeoff.md`, a real-brain read benchmark run by the maintainer on their own exported brain against PGLite (aggregates only, no user switched), the Track 2 size per subsystem, and effort against the budget recorded at Phase 1 entry; outcomes continue, narrow or stop are recorded in `bakeoff.md`. Broad Track 2 (beyond the ratchet, search arms and the 24 shared baseline families) starts only after continue.
+- First-value cohort: PGLite users on darwin-arm64 or linux-x64-glibc who hit the measured pain; named in the Phases section.
+- Track 2 coordination: a `heads-up:` per T-PR naming files and baseline rows; wait or split when the merge process reports open PRs on the same files; `engine.ts` (2,890 lines, at its ceiling) grows by at most one line per domain with types in their own modules and the ceiling row change in the same PR; a `question:` to the merge process about other work following the D6 ratchet before the first T-PR.
+- Phase 6 entry requires the Phase 3 exit, including the gbrain-evals changes landed and pinned; D11 names who lands gbrain-evals changes.
+- Bake-off scope: add an idiomatic-SQLite slice (pages, chunks, links, one trigger family) judged on correctness burden, migration and maintenance as well as speed, and LanceDB filtered ANN with exact fallback with binary size counted; target machines and memory envelope are written in `bakeoff.md` before any Rust number.
+- Crash isolation is stated honestly: `catch_unwind` with `panic = "unwind"` covers panics only; segfaults, aborts and dependency faults are a residual risk accepted for the preview; a sidecar is deferred unless preview crash reports show native faults. Verify: a test that a panicking export returns a typed error and the process keeps serving.
+- Size numbers are re-measured at 9f1d54232d (5,324 raw-SQL lines in 1,174 files; persistence 1,487) and the PR 6 ratchet baseline is generated from the tree, never copied from the plan.
+- Deferred items live in the plan's `## Deferred` section: option B, platforms beyond the two preview targets before the preview, the sidecar, the `gbrain_fts_input` fix, the evals stdio protocol and `oracle-ts` shim, LLM-judged categories as gates.
+- Eval harness choice: the in-tree `gbrain eval` harnesses are the primary parity oracle; gbrain-evals runners through `engine-factory` are secondary for their categories.
+<!-- /autoplan-accepted:ceo -->
+
+<!-- autoplan-accepted:dx -->
+- Development override (revises the CEO addon-identity requirement): under `GBRAIN_RUST_ENGINE_ADDON` the loader skips only the release digest pin; the `engine_abi`, `catalog_version` and store format checks still apply. Verify: a loader test with the override pointing at a wrong-ABI build gives `engine_unavailable` reason `abi_mismatch`, a fix to rebuild with `bun run rust:build`, and no file opened in the brain directory.
+- Error contract: every Rust engine code and reason is a row in `src/core/error-registry.ts` with class, summary, why, reasons, suggestion, read-only default fix and docs anchor; `docs/guides/error-codes.md` is regenerated and `gbrain errors <code>` answers offline. Each envelope's `detail` carries the gbrain version, target, expected and found `engine_abi`, `engine_build`, `catalog_version` and store format, environment variable names without values, home-relative paths only, and whether anything was written. Verify: one test per code and reason checks the registry row, the rendered fix, the detail fields, and that no environment variable value or absolute home path appears.
+- Fix per reason: `addon_missing`, `abi_mismatch` and `build_mismatch` fix with `gbrain engine install rust` (rebuild under the override) and one retry; `unsupported_platform` has no install fix, tells the user to use a supported preview host or keep PGLite, and says not to retry; `load_failed` allows one install retry, then report with a diagnostic id; `fetch_failed` allows one retry after connectivity returns with the active addon unchanged; `verification_failed` is reported and never bypassed; `newer_format` fixes with `gbrain upgrade` to the release named in `FORMAT` `created_by` and never rewrites the store; `unreadable` keeps the directory and restores from a verified backup; `upgrade_failed` leaves the old format and names the backup written before the upgrade. These reasons are added to decision D2.
+- Capability refusals: a refusal at dispatch says nothing ran, names the operation, capability and engine, links the preview capability list, and leaves moving back to the user (`next: ask_user`, read-only preview `gbrain migrate --to pglite --plan`); an engine switch is never an automatic fix. The `raw_sql` backstop reports `detail.outcome` (`none` when the enclosing transaction rolled back, else `partial` or `unknown`) and its fix reads the write receipt before any resubmission.
+- Native failures: `gbrain-napi` installs its own panic hook; it writes a sanitized trace without row content or argument values to `<gbrain home>/engines/rust/diagnostics/<id>.txt` with mode 0600, and the call returns `internal_error` with `detail.diagnostic_id` and `detail.outcome`; a panic in a write transaction aborts it and the wrapper reopens the store before the next call; HTTP MCP callers get only the diagnostic id. A cancellation after commit is reported as committed. A process-ending fault is recorded at the next open and reported by doctor `rust_engine_available` with the `engine_build` and the recovery result. Verify: an injected panic inside a write transaction returns `internal_error` with an id, rolls back, and the next call succeeds.
+- Maintenance path: `gbrain doctor` and `doctor --fix` on a Rust brain take the owner lock and read `FORMAT` and records without opening derived indexes; `--fix` rebuilds derived state only and never writes records. Verify: drills where a corrupt derived index and a failed open-time replay are repaired by `doctor --fix`, and a newer `FORMAT` gives `newer_format` with no write.
+- Migration surface: `migrate --to rust` and `migrate --to pglite` from a Rust brain use the graduation modes and usage line (`--plan` alias `--dry-run`, `--yes --expect <hash>`, `--status`, `--resume`, `--rollback-to-source`, `--json`, progress on stderr). The read-only plan lists the addon status and install step, disk space, estimated copy time, blockers with their fix, and the capability report of operations, commands, cycle phases and minion handlers lost on Rust with reasons. The command never prompts; without `--yes --expect <hash>` a caller gets the plan and exit 3 with the fix. The run report ends with one filtered vector search timed on the source before the copy and on the target after verification, using a stored chunk embedding as the query vector, printing both times and the result count only. Verify: a test that the plan `--json` carries these fields and a non-interactive run without `--expect` exits 3 with nothing written.
+- Install and status: `gbrain engine install rust` is idempotent, has `--json`, and `--from <file>` imports a hand-copied addon verified against the same pinned digest (the offline path; the override stays development only). Each failure state (interrupted fetch, attestation unavailable, digest mismatch, no disk space or permission, first open of the new addon fails) leaves the active addon unchanged and maps to a reason above; addons older than the previous one are removed after the new one opens the brain. `gbrain engine status --json` adds, under `schema_version: 1`, the target and whether it is a preview target, the home-relative addon path, its digest and the pinned digest, store format, index lag and the capability report. Verify: an install failure drill per state.
+- Preview docs (PR 23): `docs/ENGINES.md` gets a tested user quickstart with expected output per step (check target, `gbrain backup create`, `gbrain engine install rust`, `migrate --to rust --plan`, the run with `--yes --expect <hash>`, one search, `gbrain engine status`, the way back), the capability list and a RustEngine column in the capability matrix; `docs/guides/troubleshooting.md` gets a symptom row per code and reason; `INSTALL_FOR_AGENTS.md` says an agent never moves a brain to Rust unless the user asks; `README.md` states the limits and the reporting route (a GitHub issue titled `rust engine:` with `gbrain engine status --json` and `gbrain doctor --json` attached; no telemetry).
+- Contributor quickstart (PR 1): `rust/README.md` names rustup as the only prerequisite, `bun run rust:build` (a `package.json` script entry) builds the addon and prints its path and the `GBRAIN_RUST_ENGINE_ADDON` line, shows one `GBRAIN_TEST_BACKEND=rust bun test <file>` command and how to unset the override, and records the measured first-build time.
+- Time to first query: a drill on darwin-arm64 and linux-x64-glibc in a clean home with the 10k-page engine-graduation fixture, from `gbrain engine install rust` to the first search answered on Rust, following the PR 23 quickstart verbatim; target 5 minutes, measured time written in the preview docs. The contributor quickstart is timed in PR 1, with an edit, build and test loop under 1 minute.
+- Large brains: the 8 GiB backup archive cap applies to Rust brains; above it the quiesced physical-copy runbook in `docs/guides/in-agent-setup.md` gains the Rust directory layout, and the restore drill covers one store above the cap by that path.
+- Dogfood record: PGLite deprecation criterion 9 records dates, brain size bands and incidents in `docs/designs/rust-engine/preview-log.md`.
+- Deferred, in the plan's `## Deferred` section: moving `Fix:` to the last line of the shared CLI renderer (repo-wide, never in a Rust PR), a preview issue template under `.github/ISSUE_TEMPLATE/`, and a `gbrain engine remove rust` command.
+<!-- /autoplan-accepted:dx -->
+
+<!-- autoplan-accepted:eng -->
+- Writer admission and re-entry: a caller waits for the single-writer permit asynchronously before it uses a worker thread; an open write transaction runs its commands on its own transaction executor; the wait is bounded by `AbortSignal` or deadline and ends with the existing `cancelled` or `timeout` code with no permit or task left behind; a call on the outer engine inside its own `transaction(fn)` throws `internal_error` reason `transaction_reentry` (added to D2); `lockPageKeys` is a per-key async mutex held until the transaction ends. Verify: start far more concurrent writers than worker threads while the first transaction awaits and then makes another engine call; all finish or time out within the bound, cancelled waiters leave nothing behind, re-entry gives `transaction_reentry`, and `disconnect()` finishes cleanly.
+- Lifecycle: `disconnect()` and the resident-consumer stop barrier stop admission, cancel queued tasks, wait a bounded time for running tasks and then close the store; a task cancelled after it started reports what it committed through the receipt. Verify: PR 1's Bun smoke covers shutdown with pending tasks, cancellation after start, process exit with pending native work, and a full or closing threadsafe-function queue, in Bun 1.4.4 and in a compiled executable.
+- Snapshot contract: every search pins one record snapshot generation; text postings and vector entries carry the generation range in which they are valid and the search uses only entries valid at its generation; superseded entries are reclaimed after the oldest reader passes them; each candidate's indexed revision and its deleted, withdrawn and visibility state are checked against the record snapshot, and a mismatch drops it and uses the exact path for that arm, keeping the `vector_candidates_incomplete` reason. Verify: pause a search across a concurrent content and permission update; the paused reader returns correct results for its snapshot and never newer restricted content.
+- Failure after commit: if the outbox apply fails while the process stays alive, the call reports the write as committed through its receipt, never as rolled back; the relation is marked behind; searches that touch it use the exact path until replay succeeds; replay runs in generation order and is idempotent; `gbrain engine status` and doctor report the lag. Verify: inject failures after the record commit, after the text apply and before the vector apply with the owner alive; check the receipt, later reads, replay to zero lag and an idempotent retry.
+- Graduation adapter (PR 14b): an engine-neutral adapter under the custody state machine provides catalog inspection, canonical row export, counter and sequence transfer never below a consumed value, fencing, import and verification for PGLite and Rust; `migrate --to rust` and back cover PGLite brains only; Postgres to Rust is deferred. Verify: a PGLite to Rust to PGLite roundtrip at the Phase 5 exit verifies exactly on the domains so far, including consumed but unused sequence values, generated columns, withdrawals and database-only content.
+- Schema migrations on Rust stores (PR 19, D7): each `Migration` carries a Rust disposition (`catalog_only`, `postgres_only` with a reason, or a Rust handler with its own verify); `src/core/migrate.ts` dispatches on it; per migration the catalog change, data handler and version ledger row commit in one store transaction, `FORMAT` is then rewritten by atomic rename and repaired from the records when behind; a check fails a migration above the Rust baseline with no disposition; before PR 19 the loader refuses a catalog mismatch. Verify: upgrade a previous-release Rust store containing legacy rows, interrupt each migration boundary, and check resumability, preserved data and truthful version markers.
+- Fingerprints: PGLite and Postgres keep computing `gbrain_fact_fingerprint` and `_v1` in SQL, unchanged; the Rust engine computes both in its own code fuzzed against PGLite's SQL on non-ASCII, mixed-case and whitespace-class input; a shared or versioned change is deferred and needs the maintainer's yes. Verify: create withdrawals and purges, migrate to Rust, insert equivalent non-ASCII and mixed-case claims; they stay suppressed.
+- Test arm: the Rust arm is selected by `scripts/rust-unit-arms.ts`, modeled on `scripts/postgres-unit-arms.ts`, running only files in `test/rust-unit-arms.txt` with `GBRAIN_TEST_BACKEND=rust`; an exhaustive engine-for-backend helper replaces two-way backend branches before a file is listed; every engine opened under the arm must report `kind === 'rust'`. Verify: a listed file that still has a two-way backend branch is refused by the listing check, and a file that opens an engine of another kind under the arm fails.
+- CI coverage: `rust-engine.yml` path filters include the Rust tree, the engine interface and engine-sql files, `src/schema.sql`, `src/core/migrate.ts`, `src/core/schema-migrations/`, the graduation helpers, the test-arm harness and list, and the workflow itself; `full-ci.yml` dispatches `rust-engine.yml` on the final head. Verify: a trigger-selection check shows that a schema-only change and a capability-only change select the Rust lane.
+- Member coverage: `src/core/rust-engine/members.ts` classifies every `BrainEngine` member with `satisfies Record<keyof BrainEngine, 'implemented' | Capability>`; an unimplemented member throws `engine_capability_missing` naming its capability; `check:rust-capability-coverage` derives from this table and the dispatch table. Verify: adding an interface member without a row fails `bun run typecheck`.
+- Engine unions: every `'postgres' | 'pglite'` engine union (kind, config type, `migrate-engine.ts` target, `resolve-ipc.ts` config shape) gains `rust`; the constructor's unsupported-engine message names all three; the inventory `engines` record is `{ pglite, postgres, rust }` with no default for `rust`. Verify: an inventory row without `rust` fails typecheck, and the constructor message test lists three engines.
+- Config-level owner check: `engineIsSingleOwner(cfg.engine)` answers the single-owner question where only config exists (owner socket and secret in `resolve-ipc.ts`, `graduation-serve-guard.ts`), and the kind-branch guard covers both forms. Verify: owner socket and secret paths resolve for a Rust config the same way as for PGLite.
+- Rust backup (PR 21b): the snapshot is taken under the owner lock at one committed generation, with derived indexes carried with their generation or rebuilt on restore; the PGLite snapshot path is unchanged. Verify: the full-store restore drill gives equal relation digests and zero index lag after restore.
+- Performance proof: each target has a named `rust/bench/` step printing machine, engine, data size, N, p50 and p99 beside PGLite on the same machine; write throughput is measured through `transaction(fn)` with the writer held across awaits and the outbox apply included; peak memory at 200k and 1M chunks is reported against the `bakeoff.md` envelope. Verify: the bake-off report shows each step's output for both preview targets.
+- Docs: `docs/ENGINES.md` "Adding a new engine" gains a note that a non-SQL engine implements typed methods instead of a `SqlExecutor` (PR 8). Verify: PR 8 review.
+- Numbers: the test count reads 790 of the 830 files that call `testBackends()`, re-measured at 9f1d54232d, and is re-measured again before the gate.
+- Deferred, in the plan's `## Deferred` section: Postgres to Rust migration, and moving fact fingerprint computation out of SQL for all engines.
+<!-- /autoplan-accepted:eng -->
+
+<!-- autoplan-accepted:shadow -->
+Cycle 2 (gate option D, the maintainer asked for shadow mode). Two focused review agents read the shadow-mode delta against the code: one with the CEO and DX lenses, one with the Eng lens. This was a focused delta review, not a full rerun of the interactive phases. All 21 findings were accepted and folded into "Shadow mode and swap", Phase S, PRs S1 to S5, "Shadow mode tests", D13 to D15, risks and open questions.
+- Cutover changes the effective route: environment and service overrides are listed (names only) and block the swap; a fresh process probe confirms the engine after the switch. Verify: the route test.
+- No readiness override in the preview; privacy, fingerprints, topology, platform, capabilities, recovery drills, caught-up following and final digests are never waived. Verify: a `NOT READY` plan cannot run.
+- Readiness counts successful comparisons per operation class; errored, stale, inconclusive and dropped attempts are not coverage; any unresolved `rust_error` blocks. Verify: the evidence test.
+- Evidence epochs bind readiness to the candidate build, comparator and policy. Verify: a build change resets readiness.
+- A bounded in-memory replay buffer, separate from the metrics ledger, feeds `explain` and `bench`; expired samples are refused. Verify: the report canary scan and the expired-sample test.
+- Start, swap, failback and delete follow the graduation `--plan` / `--yes --expect` / exit 3 / `--json` contract; swap has `--status` and `--resume`.
+- `engine_swap_refused` has a per-reason recovery table before S4.
+- The report opens with a decision brief; speed claims come only from paired bench samples with N and uncertainty.
+- Evidence arrives early: C1 replays the maintainer's export against Postgres too (labeled snapshot replay); S2 ships a provisional read and search report; status shows the estimated remaining time.
+- Shadow docs ship with S4 and swap docs with S5; agents may read status, reports and plans, but starting a shadow needs the user's request and a swap needs separate approval.
+- Writer eligibility comes from durable writer observations, not heartbeats; the swap sets a durable, database-enforced fence through graduation custody that stays after cutover. Verify: the fence and eligibility tests.
+- The shadow runs in a supervised child process while another engine is primary; the serving process never loads the addon. Verify: the isolation test with an aborting child.
+- Reverse shadow is failback for a healthy Rust store only; an immutable pre-swap checkpoint and periodic recovery points cover corruption, with the loss interval stated and approved. Verify: the recovery drills.
+- The wrapper is transaction-aware and publishes invalidations only after the outer commit, including committed writes with failed receipts. Verify: the commit capture test.
+- Reconcile uses shared key bounds, deletes shadow-only keys, and never lets an older snapshot overwrite newer state. Verify: the reconcile test.
+- Allocator state is copied and verified separately from rows. Verify: the allocator test.
+- `stale` needs snapshot or generation evidence; otherwise `inconclusive`, and repairs never turn a mismatch into a match. Verify: the classification test.
+- Privacy checks each returned item against the primary's read policy; an authorized top-k substitution is a ranking difference. Verify: the privacy test.
+- Write comparisons run on a copy-on-write snapshot validated against the primary's preimage, else `write_uncomparable`. Verify: the write-compare test.
+- Two observation seams (engine wrapper and pipeline observer); provider outputs are captured, and side effects are suppressed before they are scheduled. Verify: the no-side-effect test.
+- The graduation adapter has `migration`, `live-shadow` and `reverse-shadow` policies; shadow stores run no workers. Verify: the policies test.
+<!-- /autoplan-accepted:shadow -->
+## Review record
+
+<!-- autoplan-baseline-edits:ceo {"sourceSha256":"cc436571f82437799f94232b3796d788f322414c4138dff31d7670af019af7f7","replacements":[{"oldText":"A Rust engine cannot run Postgres SQL, and about 4,890 raw-SQL call-site lines sit outside the engines.","newText":"A Rust engine cannot run Postgres SQL, and about 5,300 raw-SQL call-site lines sit outside the engines (re-measured at 9f1d54232d; see \"Size\")."},{"oldText":"lets about 1,140 files bypass the typed methods (`research/01` section 9).","newText":"lets about 1,170 files bypass the typed methods (`research/01` section 9, re-measured at 9f1d54232d)."},{"oldText":"- About 4,890 `executeRaw` / `executeRawDirect` call-site lines in about 1,140 files outside the engine files, plus","newText":"- At 36bd05806a (`research/01` section 9): about 4,890 `executeRaw` / `executeRawDirect` call-site lines in about 1,140 files outside the engine files, plus"},{"oldText":"- Only 15 storage domains live in `src/core/engine-sql/`;","newText":"- Re-measured at 9f1d54232d with the pattern `executeRaw(Direct)?\\s*[<(]` over `src`, excluding `pglite-engine.ts`, `postgres-engine.ts`, `engine.ts` and `src/core/engine-sql/`: 5,324 lines in 1,174 files. The raw-SQL ratchet baseline (PR 6) is generated from the tree at its own commit, never copied from this plan.\n- Only 15 storage domains live in `src/core/engine-sql/`;"},{"oldText":"- The largest raw-SQL user is `src/core/persistence` (353 files, 83,826 lines, about 1,414 raw-SQL lines), then `commands`, `repair`, `facts`, `cycle`, `minions`, `trust`, `access` (`research/01`, `research/08`).","newText":"- The largest raw-SQL user is `src/core/persistence` (353 files, 83,862 lines, 1,487 raw-SQL lines at 9f1d54232d), then `src/commands` (614, of which `commands/doctor` 294), `core/repair` (334), `core/facts` (244), `core/minions` (204), `core/cycle` (167), `core/trust` (135), `core/shared-skills` (125), `core/page-state` (113), `core/belief` (109), `core/access` (108) and `core/search` (100) (`research/01`, `research/08`, re-counted with the pattern above). Persistence, page state and facts (1,844 lines together) gate Phase 7 and so the preview: their size sets the date of first user value."},{"oldText":"- Postgres-only administration is never moved; it needs `postgres_admin`.","newText":"- Postgres-only administration is never moved; it needs `postgres_admin`.\n- Coordination with the merge process, per T-PR: a `heads-up:` comment naming the subsystem, the files and the baseline rows before the branch is pushed. If the merge process reports open PRs on the same files, the T-PR waits or is cut smaller instead of racing them. Churn on master in the 30 days before 9f1d54232d (first-parent commits): `src/core/engine.ts` 21, `src/core/engine-sql/` 59, `src/core/persistence/` 279, `scripts/module-size-limits.tsv` 215.\n- `src/core/engine.ts` is 2,890 lines, exactly its `check:module-size` ceiling (`scripts/module-size-limits.tsv:19`). Each domain object adds at most one line to it, its types live in their own module, and the ceiling row change with its reason rides in the same PR under the `scripts/` heads-up.\n- Track 2 is written by the Rust engine effort and landed and sequenced by the merge process, which does not write code. Before the first T-PR, a `question:` to the merge process asks whether other work it lands should follow the D6 ratchet the same way, so SQL moves in one direction only."},{"oldText":"Track 2 runs in parallel from Phase 4 onward. Each phase lists entry and exit criteria.","newText":"Track 2 starts in Phase 4 with the raw-SQL ratchet (PR 6), the search arms and the 24 shared baseline method families. The rest of Track 2 starts only after Checkpoint C1. Each phase lists entry and exit criteria.\n\nFirst value goes to PGLite users on darwin-arm64 or linux-x64-glibc who hit the measured pain above (filtered vector latency, the HNSW memory ceiling, stale planner statistics, write throughput). The preview (Phase 8) is built for them."},{"oldText":"**Phase 1: toolchain and CI.** Entry: this plan approved.","newText":"**Phase 1: toolchain and CI.** Entry: this plan approved, and an effort budget through Checkpoint C1 recorded in this document by the maintainer (recorded: 8 calendar weeks or 25 merged PRs from PR 1, whichever comes first)."},{"oldText":"compare record stores (redb, bundled SQLite as a key-value store), ANN options (usearch with predicate filtering, an own HNSW, exact SIMD scan over roaring bitmaps)","newText":"compare record stores (redb, bundled SQLite as a key-value store, and a small idiomatic-SQLite slice: pages, chunks, links and one trigger family as real SQLite tables, constraints and triggers behind the same typed Rust methods), ANN options (usearch with predicate filtering, LanceDB filtered ANN with its exact-scan fallback, an own HNSW, exact SIMD scan over roaring bitmaps)"},{"oldText":"Exit: `docs/designs/rust-engine/bakeoff.md` names the choices with data, and they meet the performance targets below. The simplest option that meets them wins; an own HNSW only with a measured advantage.","newText":"Before any Rust number exists, `bakeoff.md` names the target machines and the memory envelope (proposed: a 16 GB darwin-arm64 laptop and an 8 GB linux-x64-glibc VM, with a resident-memory budget at 200k chunks written there). Exit: `docs/designs/rust-engine/bakeoff.md` names the choices with data, and they meet the performance targets below on those machines. The idiomatic-SQLite slice is judged on correctness burden (trigger and constraint parity), migration and maintenance as well as speed; adopting it changes the store design and is the maintainer's call (open question 2). LanceDB is judged with its binary size counted. The simplest option that meets the targets wins; an own HNSW only with a measured advantage."},{"oldText":"the raw-SQL and kind-branch ratchets run in `verify`; no change for any existing user.","newText":"the raw-SQL and kind-branch ratchets run in `verify`; no change for any existing user.\n\n**Checkpoint C1: continue, narrow or stop.** Entry: Phases 2, 3 and 4 done. Inputs: `bakeoff.md`; a real-brain read benchmark (the maintainer exports their own brain with `rust/scripts/export-corpus.ts` and runs the bake-off harness against PGLite on the same brain; only aggregate numbers are published and no user is switched); the Track 2 size per subsystem re-counted at that commit; effort spent against the Phase 1 budget. Outcomes, decided by the maintainer and recorded in `bakeoff.md`: continue (the rest of Track 2 starts); narrow (keep the ratchets, the capability set and the typed methods already landed, and pause Rust domain work); or stop (one PR removes `rust/`, the Rust test arm and the `rust` kind, and keeps the ratchets and typed methods, which help the existing engines)."},{"oldText":"**Phase 6: search parity.** Entry: Phase 5 done; Track 2 search arms landed.","newText":"**Phase 6: search parity.** Entry: Phase 5 done; Track 2 search arms landed; the Phase 3 exit met, including the gbrain-evals changes landed and pinned (D11)."},{"oldText":"the minimum jobs, doctor) is complete; D4 and D8 approved. Work: PRs 21 to 23: `migrate --to rust` and back, store format and doctor checks, released addons.","newText":"the minimum jobs, doctor) is complete; `gbrain backup create` and `backup restore` work on Rust brains (PR 21b) and a full-store restore drill passes on both preview targets; the addon upgrade drill passes (stage, verify, switch, keep the previous addon; an upgrade with no network leaves the brain working or refusing with `engine_unavailable`, with no data touched); D4, D8 and D12 approved. Work: PRs 21, 21b, 22 and 23: `migrate --to rust` and back, backup and restore, store format and doctor checks, released addons with a staged upgrade."},{"oldText":"10. Prebuilt addons exist for each platform being deprecated.","newText":"10. Prebuilt addons exist for each platform being deprecated.\n11. Every PGLite-only user surface has a Rust path or a stated replacement: `backup create` and `backup restore` (`src/core/backup/snapshot.ts` refuses non-PGLite brains today), agent-install setup (`src/core/agent-install/setup.ts`), `init --pglite`, `pglite-repair` and `reinit-pglite`, and the eval harnesses that construct `PGLiteEngine`.\n12. An upgrade with no network access leaves every Rust brain either working on its pinned addon or refusing with `engine_unavailable` and the fix command, with no data touched; proven by a drill on each platform."},{"oldText":"| 21 | `gbrain migrate --to rust` and back | graduation copier target side, inventory `engines.rust`, `src/commands/migrate-engine.ts` | none | D1 |","newText":"| 21 | `gbrain migrate --to rust` and back | graduation copier target side, inventory `engines.rust`, `src/commands/migrate-engine.ts` | none | D1 |\n| 21b | `gbrain backup create` and `backup restore` for Rust brains, with a full-store restore drill | `src/core/backup/`, `src/commands/backup.ts` | none | D1 |"},{"oldText":"| 22 | Released, attested engine addons and `gbrain engine install rust` | `release.yml`, `src/commands/engine*.ts`, post-upgrade refresh |","newText":"| 22 | Released, attested engine addons with a pinned digest manifest, `gbrain engine install rust` and a staged upgrade | `release.yml`, `src/cli/commands/engine.ts` (the `engine` dispatcher, which routes only `status` today), a new `src/commands/engine-install.ts`, `src/core/binary-self-update.ts` staging, post-upgrade refresh, `engine status` fields |"},{"oldText":"T-PRs start after PR 6 and run beside PRs 10 to 17.","newText":"T-PRs for the search arms and the 24 shared baseline families start after PR 6; the other T-PRs start after Checkpoint C1. Both run beside PRs 10 to 17."},{"oldText":"Its one advantage, crash isolation, is handled instead by: `catch_unwind` on every exported function (a panic becomes a typed error, never an abort), no `unsafe` outside vetted dependencies, fuzzing at the binding boundary, and a store that recovers at the next open after any process death.","newText":"Its one advantage is crash isolation, and in process that is only partly replaced. `catch_unwind` on every exported function, with `panic = \"unwind\"` in the release profile, turns a Rust panic into a typed error. It does not catch segfaults, aborts, allocation failures or faults inside native dependencies; those still end the process. The plan makes them rarer (no `unsafe` in gbrain crates without review, fuzzing at the binding boundary, `cargo deny` and `cargo audit`) and survivable (a store that recovers at the next open after any process death, proven by the crash robot), and accepts the residual risk for the preview. A sidecar is reconsidered if preview crash reports show native faults (see \"Deferred\")."},{"oldText":"or from `<gbrain home>/engines/rust/<engine_abi>/<target>.node`.","newText":"or from `<gbrain home>/engines/rust/<engine_build>/<target>.node`."},{"oldText":"The addon exports `target`, `engine_abi` (an integer bumped when the binding surface changes) and `build_commit`; a mismatch refuses the load.","newText":"The addon exports `target`, `engine_abi` (an integer bumped when the binding surface changes), `engine_build` (a digest of the `rust/` tree it was built from), `catalog_version` and the store `format_versions` it reads and writes. Each release carries a generated manifest pinning the exact SHA-256 of the addon for each target. The loader refuses any other file and any `engine_abi`, `catalog_version` or format mismatch, except under `GBRAIN_RUST_ENGINE_ADDON`. A release that leaves `rust/` unchanged carries the previous digests forward, so the installed addon stays valid."},{"oldText":"downloads the addon matching the running `engine_abi` and target","newText":"downloads the addon whose digest the running release's manifest pins for this target"},{"oldText":"stores it under `<gbrain home>/engines/rust/<engine_abi>/`.","newText":"stores it under `<gbrain home>/engines/rust/<engine_build>/`."},{"oldText":"- Upgrades: `engine_abi` changes only when the binding surface changes, so most upgrades keep using the installed addon. When a Rust brain needs a newer addon, `post-upgrade` fetches it before finishing; if the fetch fails, the upgrade still completes and the brain reports `engine_unavailable` with the install command and a doctor finding. Brains on PGLite or Postgres never trigger a fetch.","newText":"- Upgrades: a release that leaves `rust/` unchanged pins the same digest, so the installed addon keeps working. When the pinned digest changes and a Rust brain exists, `gbrain upgrade` and `self-upgrade` fetch and verify the new addon into its own `<engine_build>/` directory before switching, and keep the previous addon until the new one has opened the brain once. If that fetch fails, the binary upgrade still completes and the Rust brain reports `engine_unavailable` with the install command, as `post-upgrade` does; an upgrade never fails for want of the addon. A raw `bun install -g` upgrade has no staging step: `post-upgrade` fetches the addon, and if that fails the brain reports `engine_unavailable` with the install command and a doctor finding, with no data touched. `gbrain engine status` reports the addon digest, the store format and the index lag. Brains on PGLite or Postgres never trigger a fetch."},{"oldText":"Rollback path 2: `gbrain migrate --to pglite` copies the Rust brain back through the same copier and verification.","newText":"Rollback path 2: `gbrain migrate --to pglite` copies the Rust brain back through the same copier and verification.\n- Neither rollback path is disaster recovery: both need a readable Rust store. Recovery from a damaged store uses `gbrain backup create` and `backup restore`, extended to Rust brains in PR 21b (today `src/core/backup/snapshot.ts` refuses non-PGLite brains), and a full-store restore drill is a preview entry criterion."},{"oldText":"`abi_mismatch`, `unsupported_platform`","newText":"`abi_mismatch`, `build_mismatch`, `unsupported_platform`"},{"oldText":"- **D10. Eval spend and pins.** About $2 to regenerate the LongMemEval embedding cache, the pinned gbrain commit for parity runs, and the E1 to E4 thresholds as written.","newText":"- **D10. Eval spend and pins.** About $2 to regenerate the LongMemEval embedding cache, the pinned gbrain commit for parity runs, and the E1 to E4 thresholds as written.\n- **D11. gbrain-evals landing.** Who lands the Phase 3 gbrain-evals changes (the maintainer or a named lander), and pinning its `gbrain` dependency to one commit for parity runs. Needed by the Phase 3 exit, and so by E1.\n- **D12. Preview contract.** The preview targets darwin-arm64 and linux-x64-glibc only. It opens only with verified backup and restore and the staged addon upgrade. Windows and the other platforms come before PGLite deprecation on each, not before the preview. Needed by PR 23."},{"oldText":"1. Who lands gbrain-evals changes? The merge process covers this repository only, and the evals repository follows `gbrain#master` unpinned today.","newText":"1. Who lands gbrain-evals changes? The merge process covers this repository only, and the evals repository follows `gbrain#master` unpinned today. Proposed as D11: the maintainer lands them or names a lander, and parity runs pin gbrain to one commit; the Phase 3 exit, and so E1, waits for it."},{"oldText":"9. Should Rust brains get a user-facing `backup create` and `backup restore`, or is the existing `backup status|check` drill plus `migrate --to pglite` enough for the preview?","newText":"9. Resolved: Rust brains get `backup create` and `backup restore` (PR 21b) before the preview. The existing commands refuse non-PGLite brains, and `migrate --to pglite` needs a readable store, so it is not recovery."},{"oldText":"- **A native crash takes down the process.** Mitigation: `catch_unwind` on every export, fuzzed boundary, crash-safe store, no `unsafe` in gbrain crates without review.","newText":"- **A native crash takes down the process.** Mitigation: `catch_unwind` on every export (panics only), fuzzed boundary, crash-safe store, no `unsafe` in gbrain crates without review. Segfaults, aborts and dependency faults remain a residual risk, accepted for the preview; a sidecar is reconsidered if crash reports show them."},{"oldText":"- **Track 2 dominates the schedule.** About 4,890 call sites across many subsystems,","newText":"- **Track 2 dominates the schedule.** About 5,300 call-site lines across many subsystems,"},{"oldText":"- **CI cost.** A Rust lane plus a growing Rust test arm. Mitigation: path filters, one addon build per run reused by shards, and the added time reported in PR 1 and PR 9.","newText":"- **CI cost.** A Rust lane plus a growing Rust test arm. Mitigation: path filters, one addon build per run reused by shards, and the added time reported in PR 1 and PR 9.\n- **Time to first value.** The preview waits for Track 2 persistence, page state and facts (1,844 raw-SQL lines), so no user benefits for many PRs. Mitigation: Checkpoint C1 decides continue, narrow or stop with real-brain data and effort against budget; the named first cohort and two preview targets keep the preview small.\n- **Addon drift on upgrade.** A same-ABI addon with older behavior could load, or an upgrade could leave a Rust brain without a usable addon. Mitigation: the pinned digest manifest, the staged upgrade that keeps the previous addon, and the offline upgrade drill (criterion 12).\n\n## Deferred\n\n- Option B, a Rust accelerator inside the PGLite or Postgres engines: it changes existing engine behavior, which Rust PRs may not do. Revisit after the preview (open question 8).\n- Platforms beyond darwin-arm64 and linux-x64-glibc before the preview: PR 24 still lands before PGLite deprecation on each platform (D12).\n- A sidecar process binding: revisit only if preview crash reports show native faults.\n- The `gbrain_fts_input` keyword-arm fix (open question 5): a separate change for all engines, never inside a Rust PR.\n- A stdio driver protocol and an `oracle-ts` shim for gbrain-evals: not needed while the in-tree `gbrain eval` harnesses and `engine-factory` cover the gates.\n- LLM-judged gbrain-evals categories as gates: they stay reported in bands set beforehand (E4).\n\n## Review requirements\n\nRequirements accepted in review. Each restates a change made in the sections above and names its check."},{"oldText":"**Phase 5: core storage domains.** Entry: Phases 2 and 4 done.","newText":"**Phase 5: core storage domains.** Entry: Phases 2 and 4 done; Checkpoint C1 decided continue."},{"oldText":"7. When is Windows needed: before the preview or before PGLite deprecation on Windows?","newText":"7. When is Windows needed? Proposed in D12: after the preview, before PGLite deprecation on Windows. Confirm with D12."},{"oldText":"Recommended: attested release assets fetched only on request (`gbrain engine install rust`) plus a best-effort refresh in `post-upgrade` for Rust brains.","newText":"Recommended: attested release assets fetched only on request (`gbrain engine install rust`, `migrate --to rust`) or, for an existing Rust brain, when an upgrade changes the pinned digest (staged by `gbrain upgrade` and `self-upgrade`, best effort in `post-upgrade`)."},{"oldText":"Mitigation: attestation and hash verification pinned to this repository's release workflow, the same as the self-updating binary; fetch only on explicit request.","newText":"Mitigation: attestation and hash verification pinned to this repository's release workflow, the same as the self-updating binary, plus the per-release digest manifest; fetch only on explicit request or for an existing Rust brain whose pinned digest changed."},{"oldText":"- `cargo deny` and `cargo audit` in the Rust lane.","newText":"- `cargo deny` and `cargo audit` in the Rust lane.\n- Drills on darwin-arm64 and linux-x64-glibc before the preview: full-store `backup create` and `backup restore` into an empty home with per-relation digests equal; addon upgrade online, offline and with an interrupted fetch, each ending with the brain working or refusing with `engine_unavailable` and no data touched."}]} -->
+
+<!-- autoplan-accepted:ceo -->
+- Addon identity: the addon exports `target`, `engine_abi`, `engine_build` (digest of the `rust/` tree), `catalog_version` and `format_versions`; each release pins the exact SHA-256 per target in a generated manifest; the loader refuses any other file or any mismatch except under `GBRAIN_RUST_ENGINE_ADDON`. Verify: loader unit tests for a wrong digest, a wrong `engine_abi`, a wrong catalog or format version, and the override path, each giving `engine_unavailable` with its reason and no file opened in the brain directory.
+- Addon path and upgrade: addons live at `<gbrain home>/engines/rust/<engine_build>/<target>.node`; `gbrain upgrade` and `self-upgrade` stage and verify the new addon before switching and keep the previous addon until the new one opens the brain; a raw `bun install -g` upgrade fetches in `post-upgrade` or reports `engine_unavailable` with the fix command and touches no data; `gbrain engine status` reports the addon digest, store format and index lag. Verify: the addon upgrade drill (online, offline, interrupted fetch) on darwin-arm64 and linux-x64-glibc before the preview.
+- Backup and restore: `gbrain backup create` and `backup restore` work on Rust brains (PR 21b, `src/core/backup/`, `src/commands/backup.ts`); a full-store restore drill passes on both preview targets before D8. Verify: restore into an empty home, then the verification digest equals the source digest for every relation.
+- Preview contract (D12): the preview is limited to darwin-arm64 and linux-x64-glibc, opens only with verified backup and restore and the staged upgrade, and Windows and other platforms come before PGLite deprecation on each.
+- PGLite deprecation criteria 11 and 12: every PGLite-only surface (backup create and restore, agent-install setup, `init --pglite`, `pglite-repair`, `reinit-pglite`, eval harnesses constructing `PGLiteEngine`) has a Rust path or a stated replacement; an offline upgrade drill passes on each platform being deprecated.
+- Checkpoint C1 after Phases 2, 3 and 4: inputs are `bakeoff.md`, a real-brain read benchmark run by the maintainer on their own exported brain against PGLite (aggregates only, no user switched), the Track 2 size per subsystem, and effort against the budget recorded at Phase 1 entry; outcomes continue, narrow or stop are recorded in `bakeoff.md`. Broad Track 2 (beyond the ratchet, search arms and the 24 shared baseline families) starts only after continue.
+- First-value cohort: PGLite users on darwin-arm64 or linux-x64-glibc who hit the measured pain; named in the Phases section.
+- Track 2 coordination: a `heads-up:` per T-PR naming files and baseline rows; wait or split when the merge process reports open PRs on the same files; `engine.ts` (2,890 lines, at its ceiling) grows by at most one line per domain with types in their own modules and the ceiling row change in the same PR; a `question:` to the merge process about other work following the D6 ratchet before the first T-PR.
+- Phase 6 entry requires the Phase 3 exit, including the gbrain-evals changes landed and pinned; D11 names who lands gbrain-evals changes.
+- Bake-off scope: add an idiomatic-SQLite slice (pages, chunks, links, one trigger family) judged on correctness burden, migration and maintenance as well as speed, and LanceDB filtered ANN with exact fallback with binary size counted; target machines and memory envelope are written in `bakeoff.md` before any Rust number.
+- Crash isolation is stated honestly: `catch_unwind` with `panic = "unwind"` covers panics only; segfaults, aborts and dependency faults are a residual risk accepted for the preview; a sidecar is deferred unless preview crash reports show native faults. Verify: a test that a panicking export returns a typed error and the process keeps serving.
+- Size numbers are re-measured at 9f1d54232d (5,324 raw-SQL lines in 1,174 files; persistence 1,487) and the PR 6 ratchet baseline is generated from the tree, never copied from the plan.
+- Deferred items live in the plan's `## Deferred` section: option B, platforms beyond the two preview targets before the preview, the sidecar, the `gbrain_fts_input` fix, the evals stdio protocol and `oracle-ts` shim, LLM-judged categories as gates.
+- Eval harness choice: the in-tree `gbrain eval` harnesses are the primary parity oracle; gbrain-evals runners through `engine-factory` are secondary for their categories.
+<!-- /autoplan-accepted:ceo -->
+
+### CEO review (Phase 1)
+
+Run facts:
+- Run this plan's /autoplan run, autoplan run 2, Phase 1. Mode: SELECTIVE EXPANSION.
+- Plan base: origin/master 9f1d54232d (v0.60.733.0). Re-checked against origin/master f9377cabe4 for already-done work.
+- Reviewed snapshot: `.gstack/tmp/autoplan/autoplan-ceo-dZmy2e/ceo-implementation.md` (470 lines, sha 74d339f7...), read in full.
+- Host adaptations: no subagent launches and no user questions. The native CEO voice ran in host on the Step 0 snapshot (sha cc436571...). The outside voice (Codex) is not installed, so it is unavailable.
+- CEO scope summary: `ceo-plans/2026-11-16-rust-engine.md` in the local gstack project directory (status ACTIVE).
+
+System audit:
+- `BrainEngine` is one interface (`src/core/engine.ts:830`) with a `kind` union (`:832`), `transaction(fn)` (`:849`) and the open `executeRaw` seam (`:2714`). `engine.ts` is 2,890 lines, exactly its ceiling (`scripts/module-size-limits.tsv:19`).
+- Construction knows only `pglite` and `postgres` (`src/core/engine-construct.ts:12,16,23`). `DATABASE_URL` infers postgres (`src/core/config.ts:738-745`).
+- Raw SQL outside the engines: 5,324 lines in 1,174 files. Persistence alone: 353 files, 83,862 lines, 1,487 raw-SQL lines. 268 `kind ===`/`!==` branches. 831 test files use `testBackends`.
+- PGLite-only surfaces: backup (`src/core/backup/snapshot.ts:23,139`), agent-install setup (`src/core/agent-install/setup.ts:5,76`), `init --pglite` (`src/commands/init.ts:56`), `pglite-repair` (`src/cli/command-table.ts:175`), LongMemEval (`src/commands/eval-longmemeval.ts:143`).
+- Native addon prior art exists: the lock addon (`src/core/persistence/native-lock.ts:94`) with prebuilds for 8 targets. The release matrix is at `.github/workflows/release.yml:128-132`; binary self-update at `src/core/binary-self-update.ts:24-27`.
+- The `engine` command dispatcher (`src/cli/commands/engine.ts:11`) routes only `status` today.
+- No Rust work is on master: `git log origin/master --since=2026-11-10 -- rust src/core/rust-engine.ts` is empty.
+
+Landscape (web results, treated as untrusted input):
+- napi-rs support for Bun is best effort, and `bun build --compile` with addons is experimental. The plan already makes PR 1 prove `process.dlopen` in a compiled binary first.
+- LanceDB offers filtered ANN with an exact-scan fallback. usearch has no native metadata filter; tantivy is lexical only. LanceDB was added to the bake-off.
+
+#### 0A. Premises
+
+| # | Premise | Evidence | Status |
+|---|---|---|---|
+| 1 | A third engine fits behind one interface | `src/core/engine.ts:830` | verified |
+| 2 | Construction is a two-case switch that can take a third case | `src/core/engine-construct.ts:12` | verified |
+| 3 | Raw SQL outside the engines blocks a non-SQL engine | 5,324 lines measured; `src/core/engine.ts:2714` | verified (number corrected) |
+| 4 | A capability table already exists to gate subsystems | `src/core/engine-sql/executor.ts:53,81` | verified |
+| 5 | Measured PGLite pain is real | `TODOS.md:50`, `TODOS.md:209`, `TODOS.md:556` | verified |
+| 6 | Native addons already ship from this repo | `src/core/persistence/native-lock.ts:94` | verified |
+| 7 | Migration can reuse the graduation copier | `src/commands/migrate-graduation.ts:11-12,80` | verified |
+| 8 | `migrate --to` lacks a rust target today | `src/commands/migrate-engine.ts:44` | verified |
+| 9 | Backup works only for PGLite | `src/core/backup/snapshot.ts:139` | verified (plan amended, PR 21b) |
+| 10 | gbrain-evals follows gbrain master unpinned | `docs/designs/rust-engine/research/11-gbrain-evals.md:25` | verified (D11 added) |
+| 11 | Tests can grow a third backend arm | `test/helpers/test-backends.ts:4,15,20` | verified |
+| 12 | Bun version floor supports `process.dlopen` | `package.json:261-262` | verified |
+
+unverified=0
+
+Reality rows:
+
+REALITY: premise-table pass 12 premises checked against code, unverified=0; BrainEngine seam, kind union, executeRaw, PGLite-only backup all confirmed src/core/engine.ts:830
+REALITY: already-done pass git fetch to origin/master f9377cabe4; no rust/ tree, no rust-engine module, no Rust engine work landed src/core/engine-construct.ts:12
+REALITY: surface-check finding migrate --to accepts postgres, supabase, pglite only; engine dispatcher routes only status; backup create/restore exist but refuse non-PGLite brains; plan amended (PR 21b, PR 22 paths) src/cli/commands/engine.ts:11
+REALITY: binding-decisions pass gstack-decision-search returned none; user direction and the merge process guide recorded as binding constraints and applied docs/designs/RUST_ENGINE.md:47
+REALITY: numbers finding raw-SQL size re-measured [measured: rg over src] to 5,324 lines in 1,174 files versus the cited 4,890; engine.ts at its 2890 ceiling; plan amended and ratchet baseline regenerated at PR 6 [re-measure before gate] scripts/module-size-limits.tsv:19
+REALITY: deferred-asks pass no linked issue; deferred items listed with reasons in the plan Deferred section docs/designs/RUST_ENGINE.md:445
+REALITY: pr-count finding ship-policy has no pr_count so the default is one PR per wave; the merge process requires small PRs, so the plan splits into about 45 PRs and each extra PR costs one queue slot and a heads-up where shared files move .gstack/ship-policy.json:1
+REALITY: transaction-semantics pass no driver or pool change to existing engines; Rust transaction wrapper mirrors the existing transaction(fn) contract; crash robot gets a Rust cell src/core/engine.ts:849
+REALITY: units pass the only unit or accuracy change is vector storage (f32, or f16 for halfvec columns); its consumers, the 1e-6 cosine rule and recall@10 against exact, are stated beside it and the f16 and quantization choices are re-tuned in the bake-off docs/designs/RUST_ENGINE.md:122
+REALITY: perf-table finding targets had no named machine or memory envelope; amended so bakeoff.md names machines and envelope before any Rust number, with PGLite and Postgres baselines on the same machine scripts/scale/budgets.json:1
+REALITY: recall pass plan requires recall@10 against exact at filter selectivities 100 to 0.1 percent and per-source scope buckets docs/designs/RUST_ENGINE.md:259
+REALITY: prior-art pass napi-rs Bun support is best effort (diverge because PR 1 proves dlopen in a compiled exe first); LanceDB filtered ANN adopted into the bake-off src/core/persistence/native-lock.ts:94
+REALITY: contract-assumptions finding gbrain-evals depends on gbrain master unpinned; D11 pins one commit and names a lander before the Phase 3 exit docs/designs/rust-engine/research/11-gbrain-evals.md:25
+REALITY: dependency-fallback pass without the addon the engine reports engine_unavailable and nothing else changes; without D11 Phase 6 waits; without C1 continue broad Track 2 does not start src/core/engine-construct.ts:16
+REALITY: obligation-tiers pass must-ship for preview is PRs 1 to 23 with 21b; next is PR 24; deferred list in the plan; budget recorded at Phase 1 entry and checked at C1 docs/designs/RUST_ENGINE.md:265
+
+PLAN_REALITY: phase=ceo rows=15/15 missing=none unverified=0 verdict=complete
+
+#### 0B. Existing code leverage
+- Everything above the engine is reused unchanged: operations, MCP, fusion, chunkers, the persistence coordinator and the error contract.
+- Reused pieces: the capability table, the graduation copier, the native-lock addon build and prebuild pattern, binary self-update attestation, the `testBackends` matrix and the engine-sql baselines (`scripts/engine-sql-baseline.tsv`).
+
+#### 0C. Dream state
+- Today: two SQL engines; PGLite hits the WASM heap cap, planner statistics problems and per-statement overhead.
+- This plan: a third embedded engine with coded access paths and the same answers, and a closed engine seam that helps all engines.
+- 12-month ideal: Rust is the default embedded engine; PGLite is retired; the seam is fully typed.
+
+#### 0C-bis. Alternatives
+- Option A (typed engine plus Track 2): kept.
+- Option B (Rust accelerator inside existing engines): deferred. It changes existing engine behavior, which Rust PRs may not do.
+- Sidecar process: deferred; in process with honest crash text is simpler.
+- Idiomatic SQLite as the store: added as a bake-off slice; adoption is the maintainer's call (open question 2).
+
+#### 0D. Scope proposals (SELECTIVE EXPANSION)
+15 proposals: 12 accepted, 2 deferred, 1 skipped (handing Track 2 to other contributors changes the merge process's role). The full table is in the CEO scope summary.
+
+#### 0E. Mode
+SELECTIVE EXPANSION: hold the user's structure (third engine, this repository, PGLite deprecation after parity, gbrain-evals in the proof, landing through the merge process) and add only what completeness needs.
+
+#### 0F. Temporal interrogation
+- Hour 1: PR 1 proves the addon loads in a compiled binary on each target.
+- Week 1 to month 1: bake-off and Track 2 ratchets; C1 decides continue, narrow or stop.
+- Month 6: preview for the named cohort on two targets, with backup and staged upgrade.
+
+#### 0G. Spec pass (in host, not a subagent launch)
+- Dimensions: completeness, consistency, clarity, scope, feasibility. Score 8/10.
+- 4 issues found, 4 fixed: D4 and the "Downloaded native code" risk contradicted the staged upgrade fetch; Phase 5 entry lacked the C1 continue outcome; open question 7 was not reconciled with D12; testing lacked the restore and upgrade drills. Remaining: 0.
+
+#### 0H. Native CEO voice
+- Input matched `ceo cc436571...`. Verdict: direction sound; revise before approving the full program.
+- High: addon compatibility (same-ABI drift, offline upgrade). Accepted: digest manifest, `engine_build` path, staged upgrade.
+- High: recovery (backup refuses non-PGLite; rollback needs a readable store). Accepted: PR 21b and a restore drill.
+- High: time to value (no budget, no stop point, no cohort). Accepted: budget, Checkpoint C1, named cohort.
+- High: gbrain-evals has no lander, and Phase 6 did not require Phase 3. Accepted: D11 and the Phase 6 entry.
+- Medium: idiomatic SQLite missing from alternatives. Accepted: bake-off slice.
+- Medium: crash-isolation claim overstated. Accepted: corrected text.
+
+#### 0I. Consensus
+
+```
+CEO DUAL VOICES: CONSENSUS TABLE [subagent-only]
+ Dimension Claude Codex Consensus
+ 1. Premises valid? yes, numbers corrected N/A N/A
+ 2. Right problem to solve? yes N/A N/A
+ 3. Scope calibration correct? no until C1 and cohort N/A N/A
+ 4. Alternatives sufficiently explored? no until SQLite slice N/A N/A
+ 5. Competitive/market risks covered? partly, LanceDB added N/A N/A
+ 6. 6-month trajectory sound? yes after backup, upgrade N/A N/A
+Outside voice unavailable (not installed): six Consensus cells N/A, never CONFIRMED.
+```
+
+#### Review sections
+
+1. Architecture. One finding: addon identity was only `engine_abi`, so a same-ABI addon with older behavior could load. Fixed with `engine_build`, `catalog_version`, `format_versions` and the pinned manifest.
+
+```
+gbrain release -> manifest {target -> sha256}
+ loader: path <home>/engines/rust/<engine_build>/<target>.node
+ sha256 ok? abi ok? catalog ok? format ok? -> load
+ else -> engine_unavailable(reason) ; brain untouched
+```
+
+2. Errors and rescue. Mapped 9 paths; gaps on backup and upgrade, now closed (registry below).
+3. Security. One High finding: downloaded native code. Mitigated by attestation pinned to the release workflow, the digest manifest and fetch only on request or digest change. Visibility parity stays a blocker.
+4. Data and edge cases. Mapped: interrupted migration, offline upgrade, damaged store, empty brain, very large brain past the PGLite ceiling. Damaged store was unhandled; PR 21b closes it.
+5. Code quality. One finding: `engine.ts` is at its size ceiling. Fixed with the one-line-per-domain rule and the ceiling row in the same PR.
+6. Tests. Diagram below; one gap (restore and upgrade drills), fixed in Testing and proof.
+
+```
+engine tests x {pglite, postgres, rust} (rust arm grows only)
+exactness fixtures from PGLite -> rust crates
+gbrain eval (primary) + gbrain-evals via engine-factory (secondary, pinned D11)
+drills: restore digest equality; upgrade online/offline/interrupted
+```
+
+7. Performance. One finding: no named machines or memory envelope. Fixed in Phase 2.
+8. Observability. One gap: no way to see the addon in use. Fixed: `engine status` reports digest, store format and index lag.
+9. Deployment. Three risks: addon drift, Track 2 conflicts with other work on shared files, CI cost. Mitigations are in the plan.
+10. Future. Reversibility 4/5: the engine is opt-in and `migrate --to pglite` exists; C1 can stop the effort with one PR. Debt items: 2 (residual native crash risk, Track 2 size).
+11. Design. SKIPPED (no UI scope).
+
+#### NOT in scope
+- Option B accelerator: changes existing engines.
+- Platforms beyond two targets before the preview: PR 24 lands before deprecation on each.
+- Sidecar binding: only if crash reports show native faults.
+- `gbrain_fts_input` fix: separate change for all engines.
+- gbrain-evals stdio protocol and `oracle-ts` shim: not needed for the gates.
+- LLM-judged categories as gates: reported in bands only.
+- Postgres deprecation: a later plan.
+
+#### What already exists
+| Sub-problem | Existing code |
+|---|---|
+| Engine interface | `src/core/engine.ts:830` |
+| Capability gating | `src/core/engine-sql/executor.ts:53` |
+| Engine selection | `src/core/engine-construct.ts:12` |
+| Engine migration | `src/commands/migrate-engine.ts:44`, `src/commands/migrate-graduation.ts:11` |
+| Native addon build | `src/core/persistence/native-lock.ts:94` |
+| Release and attestation | `.github/workflows/release.yml:128`, `src/core/binary-self-update.ts:24` |
+| Backup | `src/core/backup/snapshot.ts:23` (PGLite only) |
+| Test matrix | `test/helpers/test-backends.ts:4` |
+
+#### Error and rescue registry
+| Error | Trigger | Rescue | Status |
+|---|---|---|---|
+| `engine_unavailable` (missing addon) | addon not installed | install command and doctor finding | planned |
+| `abi_mismatch` | binding surface changed | staged upgrade fetch | planned |
+| `build_mismatch` | digest not in manifest | refuse; reinstall | added |
+| `unsupported_platform` | no prebuild | stay on PGLite | planned |
+| Offline upgrade | no network on upgrade | previous addon kept or refuse, data untouched | added |
+| Damaged store | crash or disk fault | `backup restore` (PR 21b) | added |
+| Native panic | Rust panic | `catch_unwind` typed error | planned |
+| Native segfault | dependency fault | process ends; store recovers at next open | accepted risk |
+| `executeRaw` on Rust | untyped subsystem | typed error; capability gate | planned |
+
+0 critical gaps remaining.
+
+#### Failure modes registry
+| Failure | Impact | Mitigation | Critical gap |
+|---|---|---|---|
+| Same-ABI addon drift | wrong answers | digest manifest | no |
+| Upgrade without addon | brain unusable | staged upgrade, drill | no |
+| Store corruption | data loss | backup and restore drill | no |
+| Track 2 never ends | no user value | C1 with budget | no |
+| Evals unlanded | E1 blocked | D11 | no |
+| Native crash | process ends | recovery at open, crash robot | no |
+| Visibility differs | privacy breach | blocker in contract tests | no |
+
+7 total, 0 critical gaps.
+
+#### Dream state delta
+After this plan: a third opt-in engine on two platforms with backup, staged upgrade and the parity proof, and a partly typed seam. Left for the 12-month ideal: Windows and other platforms, PGLite retirement, the rest of Track 2, the Rust engine as default.
+
+#### Stale diagram audit
+The architecture and directory diagrams in the plan still match the amended text. 0 stale diagrams.
+
+#### Implementation tasks
+Carried by the plan's PR table (PRs 1 to 24 plus 21b and the T-PRs). No separate list.
+
+#### Completion summary
+
+```
+ +====================================================================+
+ | MEGA PLAN REVIEW: COMPLETION SUMMARY |
+ +====================================================================+
+ | Mode selected | SELECTIVE EXPANSION |
+ | System Audit | seam open (5,324 raw-SQL lines); backup and |
+ | | agent setup PGLite-only; engine.ts at cap |
+ | Step 0 | option A kept; C1, D11, D12, backup, addon |
+ | Section 1 (Arch) | 1 issue found |
+ | Section 2 (Errors) | 9 error paths mapped, 0 GAPS |
+ | Section 3 (Security)| 1 issue found, 1 High severity |
+ | Section 4 (Data/UX) | 5 edge cases mapped, 0 unhandled |
+ | Section 5 (Quality) | 1 issue found |
+ | Section 6 (Tests) | Diagram produced, 0 gaps |
+ | Section 7 (Perf) | 1 issue found |
+ | Section 8 (Observ) | 1 gap found (fixed) |
+ | Section 9 (Deploy) | 3 risks flagged |
+ | Section 10 (Future) | Reversibility: 4/5, debt items: 2 |
+ | Section 11 (Design) | SKIPPED (no UI scope) |
+ +--------------------------------------------------------------------+
+ | NOT in scope | written (7 items) |
+ | What already exists | written |
+ | Dream state delta | written |
+ | Error/rescue registry| 9 rows, 0 CRITICAL GAPS |
+ | Failure modes | 7 total, 0 CRITICAL GAPS |
+ | TODOS.md updates | 0 items proposed (plan Deferred section) |
+ | Scope proposals | 15 proposed, 12 accepted (SEL) |
+ | CEO plan | written |
+ | Outside voice | codex unavailable (not installed) |
+ | Lake Score | 12/14 recommendations chose complete option |
+ | Diagrams produced | 2 (addon load flow, test layers) |
+ | Stale diagrams found | 0 |
+ | Unresolved decisions | 0 |
+ | Reality rows | 15/15 rows (PLAN_REALITY), 0 unverified |
+ +====================================================================+
+```
+
+#### Taste decisions
+- Checkpoint C1 gates broad Track 2. Alternative: start all T-PRs after PR 6 as first written.
+- Preview contract D12: two targets, backup and staged upgrade required, Windows later. Alternative: a broader preview with more platforms.
+- Idiomatic-SQLite slice in the bake-off. Alternative: compare key-value stores only.
+
+USER CHALLENGES: None.
+
+Phase 2 (Design) skip: the UI-scope signal came only from a word-pair heuristic; the plan has no rendered surface and no visual files. DX scope: yes.
+
+<!-- autoplan-baseline-edits:dx {"sourceSha256":"36abed1fa568a039111f1ed1ff8c2c2e6111c0849f6266118c5d2da92bb6388c","replacements":[{"oldText":"The loader refuses any other file and any `engine_abi`, `catalog_version` or format mismatch, except under `GBRAIN_RUST_ENGINE_ADDON`.","newText":"The loader refuses any other file and any `engine_abi`, `catalog_version` or format mismatch. Under `GBRAIN_RUST_ENGINE_ADDON` only the release digest pin is skipped; the `engine_abi`, catalog and format checks still apply, so a stale local build fails with its reason instead of opening the store."},{"oldText":"gives `engine_unavailable` (decision D2) with the fix command, and nothing else changes.","newText":"gives `engine_unavailable` (decision D2) with the fix for its reason (\"Error contract for the Rust engine\" below), and nothing else changes."},{"oldText":"PgBouncer handling) needs `postgres_admin` and stays unavailable on Rust by design.","newText":"PgBouncer handling) needs `postgres_admin` and stays unavailable on Rust by design.\n\n### Error contract for the Rust engine\n\n- Every new code and reason is a row in `src/core/error-registry.ts` (class, summary, why, reasons, suggestion, default read-only fix, docs anchor). `bun run build:error-codes` regenerates `docs/guides/error-codes.md`, and `gbrain errors <code>` answers offline. Errors use the existing envelope (`docs/protocol/AGENT_OPERATOR_v1.md`): stderr and a non-zero exit on the CLI, one `--json` document, `isError` over MCP.\n- Each envelope's `detail` carries caller-safe context: the gbrain version, the target, expected and found `engine_abi`, `engine_build`, `catalog_version` and store format, the names (never the values) of the environment variables that mattered, and home-relative paths only. Every refusal says whether anything was written.\n- One fix per reason:\n\n| Code and reason | Fix | Actor, `next` | Recovery |\n|---|---|---|---|\n| `engine_unavailable` `addon_missing` | `gbrain engine install rust`; verify with `gbrain engine status --json` | agent, `run` | nothing was touched; retry the failed call once after the install |\n| `engine_unavailable` `abi_mismatch`, `build_mismatch` | `gbrain engine install rust` (fetches the addon this release pins) | agent, `run` | as above; under `GBRAIN_RUST_ENGINE_ADDON` the fix says to rebuild with `bun run rust:build` instead |\n| `engine_unavailable` `unsupported_platform` | none to run: no addon exists for this target; open the brain on a supported preview host, or keep this brain on PGLite | user, `tell_user_to_run` | do not retry the install on this target |\n| `engine_unavailable` `load_failed` | `gbrain engine install rust` once; if it fails again, report with `detail.diagnostic_id` | agent, `run`, then `report` | one retry; the sanitized loader cause is in `detail` |\n| `engine_unavailable` `fetch_failed` | after connectivity returns, `gbrain engine install rust` once | agent, `run` | the staged download was discarded and the active addon is unchanged; one retry, then report |\n| `engine_unavailable` `verification_failed` | none; report it; there is never a bypass | user, `report` | the downloaded file is deleted and the active addon is unchanged |\n| `engine_capability_missing` before dispatch | none to run on this brain: tell the user the operation is not in the preview, with the capability list anchor; moving back is the user's choice, previewed read-only with `gbrain migrate --to pglite --plan` | user, `ask_user` | nothing ran |\n| `engine_capability_missing` `raw_sql` (backstop) | read the write receipt (`gbrain write-request -- <id>`) before any resubmission | agent, `run` (read only) | `detail.outcome` is `none` when the enclosing transaction rolled back, else `partial` or `unknown`; reconcile before retrying |\n| `engine_store_format_unsupported` `newer_format` | `gbrain upgrade` to at least the release named in `FORMAT` `created_by` | user, `tell_user_to_run` | the store is never downgraded or rewritten |\n| `engine_store_format_unsupported` `unreadable` | keep the directory as it is; restore from a verified backup (`gbrain backup restore`) | user, `ask_user` | nothing was written |\n| `engine_store_format_unsupported` `upgrade_failed` | none to run; the store stays at its old format and `detail` names the backup written before the upgrade | user, `report` | the old format remains readable by the previous release |\n\n- Caught panics: `gbrain-napi` installs its own panic hook, because the default hook prints the payload to stderr. The hook writes a sanitized trace (no row content, no argument values) to `<gbrain home>/engines/rust/diagnostics/<id>.txt` with mode 0600 and the call returns `internal_error` naming the operation, with `detail.diagnostic_id` and `detail.outcome`. A panic inside a write transaction aborts it; the wrapper then closes and reopens the store, which runs open-time recovery, before the next call. Over HTTP MCP only the diagnostic id is returned.\n- A cancellation that arrives after commit reports the write as committed through its receipt, never as cancelled.\n- Faults that end the process (segfaults, aborts) cannot be caught. The next open records that the previous owner ended without closing the store, and doctor `rust_engine_available` reports it with the `engine_build` and the recovery result.\n- Maintenance path: `gbrain doctor` and `doctor --fix` on a Rust brain take the owner lock and read `FORMAT` and the records without opening the derived indexes, so a corrupt index or a failed open-time replay can still be inspected and rebuilt. `--fix` rebuilds derived state only and never writes records.\n- Human output keeps the shared renderer (`Error [code]`, `Fix:`, `Why:`, `Docs:`); agents read `fix` from the `--json` document.\n- The reasons added here (`fetch_failed`, `verification_failed`, `newer_format`, `unreadable`, `upgrade_failed`) are part of decision D2."},{"oldText":"refused before touching anything when the addon is unavailable.","newText":"refused before touching anything when the addon is unavailable.\n- `migrate --to rust`, and `migrate --to pglite` from a Rust brain, have the graduation modes and usage line: `--plan` (alias `--dry-run`, read-only), `--yes --expect <hash>`, `--status`, `--resume`, `--rollback-to-source`, and `--json` with progress on stderr. The plan lists the addon status and its install step, the disk space needed, the estimated copy time, blockers with their fix (for example a live `gbrain serve` and how to stop it), and the capability report: each operation, command, cycle phase and minion handler the brain would lose on Rust, with its reason.\n- The command never prompts. A missing addon is installed by the run only as a step listed in the plan. A caller without `--yes --expect <hash>` gets the plan and exit 3 with the fix.\n- The run report ends with one filtered vector search timed on the source before the copy and on the target after verification. It uses a stored chunk embedding as the query vector, so no provider is called, and prints both times and the result count only."},{"oldText":"`gbrain engine status` reports the addon digest, the store format and the index lag.","newText":"`gbrain engine status` (and its `--json` document, as additive fields under `schema_version: 1`) reports the target and whether it is a preview target, the addon path (home-relative), its digest and the pinned digest, the store format, the index lag and the capability report."},{"oldText":"`migrate --to rust` offers the same step.","newText":"`migrate --to rust` offers the same step. `gbrain engine install rust` is idempotent (an installed, verified addon exits 0) and has a `--json` form. `gbrain engine install rust --from <file>` imports an addon copied by hand and verifies it against the same pinned digest; it is the offline path, and `GBRAIN_RUST_ENGINE_ADDON` stays a development override. Each install failure state (interrupted fetch, attestation unavailable, digest mismatch, no disk space or permission, the new addon failing its first open) leaves the active addon unchanged and maps to a reason in the error contract. After the new addon has opened the brain, addons older than the previous one are removed."},{"oldText":"| 22 | Released, attested engine addons with a pinned digest manifest, `gbrain engine install rust` and a staged upgrade |","newText":"| 22 | Released, attested engine addons with a pinned digest manifest, `gbrain engine install rust` (with `--from <file>` for offline import) and a staged upgrade |"},{"oldText":"| 23 | Rust engine preview documentation | `docs/ENGINES.md` (new section, capability matrix row), `README.md` limits | none | D8 |","newText":"| 23 | Rust engine preview documentation | `docs/ENGINES.md` (new section with a tested user quickstart: check the target, `gbrain backup create`, `gbrain engine install rust`, `gbrain migrate --to rust --plan`, then `--yes --expect <hash>`, one search, `gbrain engine status`, and the way back; expected output for each step; the capability list; a RustEngine column in the capability matrix), `docs/guides/troubleshooting.md` symptom rows for each new code and reason, `INSTALL_FOR_AGENTS.md` (an agent never moves a brain to Rust unless the user asks), `README.md` limits, how to report a preview problem (a GitHub issue titled `rust engine:` with `gbrain engine status --json` and `gbrain doctor --json` attached; no telemetry) | none | D8 |"},{"oldText":"`rust-toolchain.toml`, `Cargo.lock`, `deny.toml`;","newText":"`rust-toolchain.toml`, `Cargo.lock`, `deny.toml`; `rust/README.md` contributor quickstart (rustup is the only prerequisite; `bun run rust:build` builds the addon and prints its path and the `GBRAIN_RUST_ENGINE_ADDON` line; one `GBRAIN_TEST_BACKEND=rust bun test <file>` command; how to unset the override; the measured first-build time); a `rust:build` script entry in `package.json`;"},{"oldText":"an interrupted fetch, each ending with the brain working or refusing with `engine_unavailable` and no data touched.","newText":"an interrupted fetch, each ending with the brain working or refusing with `engine_unavailable` and no data touched.\n- Time-to-first-query drill on both preview targets, in a clean home with the 10k-page engine-graduation fixture: from `gbrain engine install rust` to the first search answered on Rust, following the PR 23 quickstart verbatim. Target: 5 minutes. The measured time is written in the preview docs. The PR 1 contributor quickstart is timed the same way (first build reported; edit, build and test loop under 1 minute).\n- Failure drills: a corrupt derived index and a failed open-time replay are repaired by `doctor --fix` through the maintenance path; a newer `FORMAT` gives `newer_format` with no write; an injected panic inside a write transaction returns `internal_error` with a diagnostic id, rolls back, and the next call succeeds; each `engine install` failure state leaves the active addon unchanged.\n- Error rows: one test per code and reason checks the registry row, the rendered `fix`, the `detail` context, and that no environment variable value and no absolute home path appears in the envelope or the diagnostic file."},{"oldText":"a full-store restore drill is a preview entry criterion.","newText":"a full-store restore drill is a preview entry criterion. The 8 GiB archive cap (`src/core/backup/archive.ts`) applies to Rust brains too; above it, the quiesced physical-copy runbook (`docs/guides/in-agent-setup.md`, \"Large or non-standard brains\") gains the Rust directory layout, and the restore drill covers one store above the cap by that path."},{"oldText":"no open P1 bug against the engine.","newText":"no open P1 bug against the engine. Dates, brain size bands and incidents are recorded in `docs/designs/rust-engine/preview-log.md`."},{"oldText":"`engine_store_format_unsupported` (newer or unreadable store format). Needed by PRs 8 and 19.","newText":"`engine_store_format_unsupported` (newer or unreadable store format). Needed by PRs 8 and 19. Review added the reasons `fetch_failed` and `verification_failed` (`engine_unavailable`, PR 22) and `newer_format`, `unreadable` and `upgrade_failed` (`engine_store_format_unsupported`)."},{"oldText":"LLM-judged gbrain-evals categories as gates: they stay reported in bands set beforehand (E4).","newText":"LLM-judged gbrain-evals categories as gates: they stay reported in bands set beforehand (E4).\n- Moving the `Fix:` line to the last line of the shared CLI error renderer (`src/core/agent-output.ts` prints it second): a change for every command, never inside a Rust PR. Agents read `fix` from `--json`.\n- A Rust preview issue template under `.github/ISSUE_TEMPLATE/`: the preview docs name the reporting route instead.\n- A `gbrain engine remove rust` command: removing an addon by hand is enough for the preview."}]} -->
+
+<!-- autoplan-accepted:dx -->
+- Development override (revises the CEO addon-identity requirement): under `GBRAIN_RUST_ENGINE_ADDON` the loader skips only the release digest pin; the `engine_abi`, `catalog_version` and store format checks still apply. Verify: a loader test with the override pointing at a wrong-ABI build gives `engine_unavailable` reason `abi_mismatch`, a fix to rebuild with `bun run rust:build`, and no file opened in the brain directory.
+- Error contract: every Rust engine code and reason is a row in `src/core/error-registry.ts` with class, summary, why, reasons, suggestion, read-only default fix and docs anchor; `docs/guides/error-codes.md` is regenerated and `gbrain errors <code>` answers offline. Each envelope's `detail` carries the gbrain version, target, expected and found `engine_abi`, `engine_build`, `catalog_version` and store format, environment variable names without values, home-relative paths only, and whether anything was written. Verify: one test per code and reason checks the registry row, the rendered fix, the detail fields, and that no environment variable value or absolute home path appears.
+- Fix per reason: `addon_missing`, `abi_mismatch` and `build_mismatch` fix with `gbrain engine install rust` (rebuild under the override) and one retry; `unsupported_platform` has no install fix, tells the user to use a supported preview host or keep PGLite, and says not to retry; `load_failed` allows one install retry, then report with a diagnostic id; `fetch_failed` allows one retry after connectivity returns with the active addon unchanged; `verification_failed` is reported and never bypassed; `newer_format` fixes with `gbrain upgrade` to the release named in `FORMAT` `created_by` and never rewrites the store; `unreadable` keeps the directory and restores from a verified backup; `upgrade_failed` leaves the old format and names the backup written before the upgrade. These reasons are added to decision D2.
+- Capability refusals: a refusal at dispatch says nothing ran, names the operation, capability and engine, links the preview capability list, and leaves moving back to the user (`next: ask_user`, read-only preview `gbrain migrate --to pglite --plan`); an engine switch is never an automatic fix. The `raw_sql` backstop reports `detail.outcome` (`none` when the enclosing transaction rolled back, else `partial` or `unknown`) and its fix reads the write receipt before any resubmission.
+- Native failures: `gbrain-napi` installs its own panic hook; it writes a sanitized trace without row content or argument values to `<gbrain home>/engines/rust/diagnostics/<id>.txt` with mode 0600, and the call returns `internal_error` with `detail.diagnostic_id` and `detail.outcome`; a panic in a write transaction aborts it and the wrapper reopens the store before the next call; HTTP MCP callers get only the diagnostic id. A cancellation after commit is reported as committed. A process-ending fault is recorded at the next open and reported by doctor `rust_engine_available` with the `engine_build` and the recovery result. Verify: an injected panic inside a write transaction returns `internal_error` with an id, rolls back, and the next call succeeds.
+- Maintenance path: `gbrain doctor` and `doctor --fix` on a Rust brain take the owner lock and read `FORMAT` and records without opening derived indexes; `--fix` rebuilds derived state only and never writes records. Verify: drills where a corrupt derived index and a failed open-time replay are repaired by `doctor --fix`, and a newer `FORMAT` gives `newer_format` with no write.
+- Migration surface: `migrate --to rust` and `migrate --to pglite` from a Rust brain use the graduation modes and usage line (`--plan` alias `--dry-run`, `--yes --expect <hash>`, `--status`, `--resume`, `--rollback-to-source`, `--json`, progress on stderr). The read-only plan lists the addon status and install step, disk space, estimated copy time, blockers with their fix, and the capability report of operations, commands, cycle phases and minion handlers lost on Rust with reasons. The command never prompts; without `--yes --expect <hash>` a caller gets the plan and exit 3 with the fix. The run report ends with one filtered vector search timed on the source before the copy and on the target after verification, using a stored chunk embedding as the query vector, printing both times and the result count only. Verify: a test that the plan `--json` carries these fields and a non-interactive run without `--expect` exits 3 with nothing written.
+- Install and status: `gbrain engine install rust` is idempotent, has `--json`, and `--from <file>` imports a hand-copied addon verified against the same pinned digest (the offline path; the override stays development only). Each failure state (interrupted fetch, attestation unavailable, digest mismatch, no disk space or permission, first open of the new addon fails) leaves the active addon unchanged and maps to a reason above; addons older than the previous one are removed after the new one opens the brain. `gbrain engine status --json` adds, under `schema_version: 1`, the target and whether it is a preview target, the home-relative addon path, its digest and the pinned digest, store format, index lag and the capability report. Verify: an install failure drill per state.
+- Preview docs (PR 23): `docs/ENGINES.md` gets a tested user quickstart with expected output per step (check target, `gbrain backup create`, `gbrain engine install rust`, `migrate --to rust --plan`, the run with `--yes --expect <hash>`, one search, `gbrain engine status`, the way back), the capability list and a RustEngine column in the capability matrix; `docs/guides/troubleshooting.md` gets a symptom row per code and reason; `INSTALL_FOR_AGENTS.md` says an agent never moves a brain to Rust unless the user asks; `README.md` states the limits and the reporting route (a GitHub issue titled `rust engine:` with `gbrain engine status --json` and `gbrain doctor --json` attached; no telemetry).
+- Contributor quickstart (PR 1): `rust/README.md` names rustup as the only prerequisite, `bun run rust:build` (a `package.json` script entry) builds the addon and prints its path and the `GBRAIN_RUST_ENGINE_ADDON` line, shows one `GBRAIN_TEST_BACKEND=rust bun test <file>` command and how to unset the override, and records the measured first-build time.
+- Time to first query: a drill on darwin-arm64 and linux-x64-glibc in a clean home with the 10k-page engine-graduation fixture, from `gbrain engine install rust` to the first search answered on Rust, following the PR 23 quickstart verbatim; target 5 minutes, measured time written in the preview docs. The contributor quickstart is timed in PR 1, with an edit, build and test loop under 1 minute.
+- Large brains: the 8 GiB backup archive cap applies to Rust brains; above it the quiesced physical-copy runbook in `docs/guides/in-agent-setup.md` gains the Rust directory layout, and the restore drill covers one store above the cap by that path.
+- Dogfood record: PGLite deprecation criterion 9 records dates, brain size bands and incidents in `docs/designs/rust-engine/preview-log.md`.
+- Deferred, in the plan's `## Deferred` section: moving `Fix:` to the last line of the shared CLI renderer (repo-wide, never in a Rust PR), a preview issue template under `.github/ISSUE_TEMPLATE/`, and a `gbrain engine remove rust` command.
+<!-- /autoplan-accepted:dx -->
+
+### DX review (Phase 2.5)
+
+Run facts:
+- Run this plan's /autoplan run, autoplan run 2, Phase 2.5. Mode: DX POLISH. Rubric: `agent-ready-v1`.
+- Reviewed snapshot: `.gstack/tmp/autoplan/autoplan-dx-Ij2Ltz/dx-implementation.md` (sha 74d339f7...), read in full. Methodology read in full (1,870 lines).
+- Product type: developer tool. A CLI and an in-process storage engine (a native addon behind `BrainEngine`), used by people and by agents through `--json` and MCP.
+- Grounding read in the checkout: `README.md`, `docs/ENGINES.md` (engine status, adding an engine, capability matrix), `docs/protocol/AGENT_OPERATOR_v1.md` (error envelope, `Action`, exit codes), `docs/guides/troubleshooting.md` (symptom table), `src/core/error-registry.ts`, `src/core/agent-output.ts`, `src/cli/cli-error.ts`, `src/cli/commands/engine.ts`, `src/commands/migrate-engine.ts`, `src/commands/migrate-graduation.ts`, `src/commands/diag.ts`, `src/core/backup/archive.ts`, `CONTRIBUTING.md`, the gbrain-evals README.
+- Web research was unavailable in this host. Benchmarks for outside tools are reference knowledge, labeled as estimates (P1).
+- Voices: native DX subagent completed (INPUT matched `dx 74d339f7...`), 8 findings. Codex not installed: outside voice unavailable.
+
+#### Developer persona card
+
+```
+PERSONA: the PGLite power user who runs gbrain through an agent
+ Who: a developer or agent operator with a personal brain on PGLite,
+ darwin-arm64 or linux-x64-glibc, 10k to 200k chunks
+ Context: gbrain runs under an agent (MCP or CLI with --json) and a
+ `gbrain serve`; the user acts in a terminal when the agent asks
+ Pain: filtered vector search in hundreds of ms, the HNSW memory
+ ceiling, stale planner statistics, slow writes
+ Tolerance: will run 3 to 5 commands and wait a few minutes, once; will not
+ read source code or debug a native crash
+ Success: the same answers, visibly faster, and a sure way back
+SECOND PERSONA: the contributor building the engine (Rust and TypeScript),
+ who needs one build command and one test command
+```
+
+#### Empathy narrative
+
+I run my brain on PGLite and my agent talks to it all day. Search with a date filter got slow as the brain grew, and last week an index build ran out of memory. I read that gbrain has a Rust engine preview. I open the README and see a line about limits, then hunt through `docs/ENGINES.md` for the steps. I want to know before I start what I lose: will my nightly dream cycle still run? Nothing tells me. I run `gbrain migrate --to rust` and it refuses because `gbrain serve` holds the lock. Which process, and how do I bring my agent back afterwards? I stop it, try again, and get a plan hash. I am not sure whether the run will also download the engine or stop and ask me while my agent waits. The copy starts with no estimate. Twenty minutes later my first search returns, and I cannot tell if it is faster. The next day my agent reports `engine_capability_missing` with a capability name and nothing it can do. That is the moment I think about going back. After this review, the quickstart gives me each command with its expected output, the plan tells me the time, the blockers and every feature the brain would lose, the run never prompts, and it ends by timing the same filtered search on both engines.
+
+#### Competitive DX benchmark
+
+| Tool | Start → result | Time + evidence type | DX choice | Source |
+|---|---|---|---|---|
+| gbrain on PGLite (today) | `gbrain init --pglite --no-embedding` → working brain | 1 to 2 min, estimate from the documented steps | zero-config default | `README.md` install section (repo) |
+| gbrain PGLite → Postgres graduation | `migrate --to postgres --plan`, then `--yes --expect <hash>` → brain on Postgres | 10 to 30 min including database setup, estimate | read-only plan, plan hash, status, resume, rollback | `CONTRIBUTING.md` "Local graduation smoke" (repo) |
+| SQLite with sqlite-vec | load the extension, create a vector table, run a KNN query | 2 to 5 min, reference knowledge, not web-verified | one file, one extension | reference knowledge |
+| LanceDB (embedded) | install the package, connect to a directory, create a table, search | 2 to 5 min, reference knowledge, not web-verified | embedded directory store, filtered ANN | reference knowledge |
+| Chroma (embedded) | install the package, open a persistent client, add, query | 2 to 5 min, reference knowledge, not web-verified | in-process default, server optional | reference knowledge |
+| gbrain Rust engine, plan before review | read docs, install addon, migrate, first search | about 20 min, estimate (no binary exists) | opt-in move of an existing brain | this plan |
+| gbrain Rust engine, plan after review | quickstart, `engine install rust`, `migrate --to rust --plan`, run, search | target 5 min on the 10k-page fixture, to be measured by the drill | plan with time, blockers and capability report; timed search at the end | this plan, "Testing and proof" |
+
+The fair comparison is a move of an existing brain, not a fresh store, so the Rust engine is measured against graduation (10 to 30 min) and a fresh embedded store (2 to 5 min). Target tier: Competitive.
+
+#### Magical moment specification
+
+- Moment: the first search on Rust is visibly faster on the user's own brain.
+- Vehicle: the `migrate --to rust` run report. It ends with one filtered vector search timed on the source before the copy and on the target after verification, with a stored chunk embedding as the query vector (no provider call, no spend), printing both times and the result count only.
+- Uses existing parts: the graduation run report, the engine's vector search, the stored embeddings. No new command.
+- TASTE DECISION (see below). Alternative: the quickstart asks the user to run `gbrain diag --json` before and after.
+
+#### Developer journey map
+
+Preview user:
+
+| Stage | What the developer does | Friction before review | Resolution in the plan |
+|---|---|---|---|
+| Discover | reads `README.md` limits and `docs/ENGINES.md` | no quickstart, no list of what is missing on Rust, no agent rule | PR 23: tested quickstart with expected output, capability list, troubleshooting rows, `INSTALL_FOR_AGENTS.md` rule that an agent never moves a brain to Rust unless the user asks |
+| Install | `gbrain engine install rust` | failure states, offline install and idempotence unspecified | idempotent, `--json`, `--from <file>` offline import, one reason and fix per failure state, active addon unchanged on failure |
+| Hello world | `gbrain migrate --to rust` | modes unspecified, possible prompt, serve-lock refusal without a fix, no time estimate, no visible win | graduation modes, read-only plan with blockers and fixes, time, disk and capability report; never prompts (exit 3 with the fix); timed search at the end |
+| Real usage | daily queries, cycles, jobs | a refused operation names a capability and offers nothing | per-reason fixes; dispatch refusals say nothing ran; skipped phases listed in the plan and in `engine status` |
+| Debug | an error, a panic, a broken index | no trace for panics; doctor cannot reach a store that fails to open | panic hook with a private diagnostic file and id; maintenance path for doctor; failure drills |
+| Upgrade | `gbrain upgrade`, a downgrade, an offline machine | covered by CEO for success paths; failure states and downgrade vague | `fetch_failed`, `verification_failed`, `newer_format`, `upgrade_failed` with fixes; old addons pruned |
+
+Contributor:
+
+| Stage | Before review | Resolution in the plan |
+|---|---|---|
+| Discover | `CONTRIBUTING.md` has no Rust path | `rust/README.md` from PR 1 |
+| Install | toolchain pinned, prerequisites unstated | rustup is the only prerequisite; first-build time measured and written |
+| Hello world | no command that builds a loadable `.node` and runs one test | `bun run rust:build` prints the path and the `GBRAIN_RUST_ENGINE_ADDON` line; one `GBRAIN_TEST_BACKEND=rust bun test <file>` |
+| Real usage | test arm list exists | unchanged: add the file to `test/rust-unit-arms.txt` |
+| Debug | a stale local build could skip compatibility checks under the override | the override skips only the digest pin; a stale build fails with `abi_mismatch` and the fix says to rebuild |
+| Upgrade | `rust-toolchain.toml` pin | unchanged |
+
+#### First-time developer confusion report
+
+Preview user, following the plan as written before review:
+
+- T+0:00 Reads the README limits line. Where are the steps? Addressed: PR 23 quickstart.
+- T+0:03 Finds the `docs/ENGINES.md` section. What stops working on Rust? Addressed: capability list and the plan's capability report.
+- T+0:06 Runs `gbrain migrate --to rust`. Does it download the engine, and will it stop to ask while my agent waits? Addressed: install is a planned step; the command never prompts.
+- T+0:07 Refused: `gbrain serve` holds the lock. Which process, and how do I restart my agent? Addressed: blockers with their fix in the plan.
+- T+0:10 The copy runs with no estimate. Addressed: estimated time and disk space in the plan; progress on stderr.
+- T+0:20 First search returns. Is it faster? Addressed: timed search in the run report.
+- T+1 day: `engine_capability_missing` from the agent with nothing to do. Addressed: per-reason fix; nothing ran; moving back is the user's choice.
+- T+1 week: after `gbrain upgrade` the brain refuses with `engine_unavailable`. Which reason, and is it safe to retry? Addressed: reason table and retry bounds.
+
+Contributor:
+
+- T+0:00 Clones, looks for how to build the engine. Addressed: `rust/README.md`.
+- T+0:10 Builds with cargo, cannot find the `.node` or the variable to set. Addressed: `bun run rust:build` prints both.
+- T+0:15 A test fails oddly after pulling master; the local build is stale. Addressed: the override keeps the ABI and format checks.
+
+#### TTHW assessment
+
+- Preview user, before review: about 20 min, an estimate (no binary exists): finding the steps, the serve-lock refusal, the plan and run, an unestimated copy. Tier: Red Flag.
+- Target: 5 min from `gbrain engine install rust` to the first search answered on Rust, on the 10k-page engine-graduation fixture in a clean home on both preview targets, following the quickstart verbatim. Tier: Competitive. Measured by the time-to-first-query drill and written in the preview docs. Larger brains report their measured copy time instead of a target.
+- Contributor: before review, undetermined (no build-to-test path). Target: first build time measured and written in `rust/README.md`; edit, build and test loop under 1 min.
+- TASTE DECISION on the target (see below).
+
+#### Pass 1: Getting started (5 → 8)
+
+- Finding: no copy-paste path from an existing PGLite brain to a search on Rust, for users or contributors (native finding 6 agrees). Decision: PR 23 user quickstart with expected output per step; PR 1 contributor quickstart and `rust:build`. Mechanical, P1.
+- Finding: the migration's first run can surprise (serve lock, addon download, no estimate). Decision: graduation modes and a plan that lists blockers with fixes, time, disk and the capability report; never prompts. Mechanical, P5.
+- Not 10: the copy time for large brains is real and cannot be hidden; the 5-minute target holds only for the 10k-page fixture.
+
+#### Pass 2: API and CLI design (7 → 8)
+
+- Kept: `engine: "rust"`, `migrate --to rust`, `engine install rust`, `engine status`, `GBRAIN_TEST_BACKEND=rust` and `GBRAIN_RUST_ENGINE_ADDON` are consistent and guessable, and reuse existing verbs.
+- Finding: capability discovery is a contributor metric (`check:rust-capability-coverage`), not a user surface (native finding 7). Decision: a capability report in the migration plan and in `engine status --json`, as additive fields; no new MCP operation. Mechanical, P1.
+- Finding: `migrate --to rust` mode set was implicit; the legacy `migrate --to pglite` copier has no plan, status or resume. Decision: both directions for Rust brains use the graduation modes and usage line. Mechanical, P5.
+- Finding: `engine install rust` had no `--json`, idempotence or offline form. Decision: idempotent, `--json`, `--from <file>`. TASTE DECISION for `--from`.
+
+#### Pass 3: Error messages and debugging (5 → 7)
+
+```
+ERROR PATH MATRIX (agent-ready-v1), plan before review
+Path | Class | what | fix | recovery | code | context | trace | redaction | channel | Cap
+engine_unavailable at open (5 reasons) | unavailable | pass | fail | fail | pass | fail | N/A | pass | pass | CAP6:fix,recovery,context
+engine_capability_missing (dispatch | unavailable | pass | fail | fail | pass | fail | N/A | pass | pass | CAP6:fix,recovery
+ and raw_sql backstop)
+migrate --to rust refusal or failure | caller | pass | fail | pass | pass | fail | N/A | pass | pass | CAP6:fix,context
+engine_store_format_unsupported, and | unavailable | fail | fail | fail | pass | fail | fail | pass | pass | CAP6:fix,recovery,trace
+ doctor on a store that fails to open
+Unexpected: native panic or | server | fail | fail | fail | fail | fail | fail | fail | pass | CAP6:trace,recovery
+ process-ending fault
+```
+
+- N/A reasons: trace applies only to unexpected failures; the first three paths are expected refusals. Redaction for the panic path fails because the default Rust panic hook prints the payload to stderr before `catch_unwind` returns.
+- No CAP4: no secret leak, no failure reported as success, no unsafe fix and no terminal block were found. The migration has a non-interactive path (`--yes --expect`), and the plan now states the command never prompts.
+- What an agent saw before, for a dispatch refusal: `Error [engine_capability_missing]: this operation needs persistence_journal`, with no fix and no statement that nothing ran. After: `Fix:` names no command for the agent, `next: ask_user`, `user_message` says the operation is not in the preview and links the capability list, `detail.outcome: none`; moving back is previewed read-only with `gbrain migrate --to pglite --plan` only if the user chooses.
+- What an agent saw before, for a caught panic: a typed error with no code, id or outcome. After: `internal_error` naming the operation, `detail.diagnostic_id`, `detail.outcome`, a 0600 diagnostic file on the host, and the fix to read the write receipt before any resubmission.
+- Corrected unsupported-target line: `Fix: no Rust addon exists for linux-arm64-glibc; open this brain on a supported preview host or keep it on PGLite. Do not retry the install here.`
+- Decision: the "Error contract for the Rust engine" subsection, one fix per reason, `detail` context, panic hook, outcome on the backstop, maintenance path, cancellation after commit reported as committed, failure drills and a test per code and reason. Mechanical, P1. Native findings 1 to 5 agree and are folded in.
+- Permission and safety model: destructive steps keep `--yes --expect <hash>`; downloaded code is verified against the pinned digest and attestation with no bypass; the development override keeps the ABI and format checks. Debug aids: `GBRAIN_DEBUG=1`, `gbrain diag --json`, `gbrain doctor --json`, `gbrain errors <code>`.
+- Why 7, not 8: the shared renderer prints `Fix:` on the second line of four (`src/core/agent-output.ts`, verified), not first or last; changing it changes every command, so it is deferred and agents read `fix` from `--json` (TASTE DECISION). Process-ending native faults stay uncatchable; they get a next-open record, not a trace.
+
+DX TRIAGE: 5 CAP6 findings, 0 CAP4.
+
+#### Pass 4: Documentation and learning (4 → 8)
+
+- Finding: PR 23 named destinations only. Decision: the quickstart with expected output, the capability list, a RustEngine column in the capability matrix, troubleshooting symptom rows for each code and reason, the `INSTALL_FOR_AGENTS.md` rule, the reporting route. Error rows come from the registry, so `docs/guides/error-codes.md` and `gbrain errors <code>` stay in step. Mechanical, P1.
+- Not 10: docs are written in PR 23, late; earlier PRs rely on this design doc and `rust/README.md`.
+
+#### Pass 5: Upgrade and migration path (7 → 8)
+
+- Kept from CEO: pinned digests, staged upgrade, previous addon kept, offline drill, backup and restore.
+- Finding: install and upgrade failure states, downgrade to an older release and the 8 GiB backup cap for large Rust brains were unspecified (native findings 5 and 8; the cap verified at `src/core/backup/archive.ts:11`). Decision: reasons and fixes per state, `newer_format` naming the release to upgrade to, pruning addons older than the previous one, the physical-copy runbook for stores over the cap with a drill. Mechanical, P1.
+
+#### Pass 6: Developer environment and tooling (5 → 8)
+
+- Finding: no contributor command builds a loadable addon and runs one test; the override bypassed compatibility checks. Decision: `rust/README.md`, `bun run rust:build`, the override skips only the digest pin. Mechanical, P1 and P5. Default `bun test` and `bun run verify` still need no Rust toolchain (unchanged).
+
+#### Pass 7: Community and ecosystem (3 → 6)
+
+- Finding: "preview crash reports" drive the sidecar decision, but no route for them existed. Decision: PR 23 names the route (a GitHub issue titled `rust engine:` with `engine status --json` and `doctor --json` attached; no telemetry). Mechanical, P5.
+- Not higher: no issue template (deferred, it touches `.github/`), and the preview cohort is small by design (D12).
+
+#### Pass 8: DX measurement and feedback loops (5 → 7)
+
+- Finding: no TTHW measurement; criterion 9's dogfood had no record. Decision: the time-to-first-query drill on both targets; `docs/designs/rust-engine/preview-log.md` for dates, size bands and incidents. Mechanical, P1.
+- Not higher: no usage telemetry by design; feedback depends on issues and the maintainer's log.
+
+#### Native voice reconciliation
+
+All 8 native findings were accepted. Two claims were checked in the checkout first: the 8 GiB backup cap (`src/core/backup/archive.ts:11`, and `backup_too_large` in `src/core/error-registry.ts`) and the `Fix:` line placement (`src/core/agent-output.ts:874`, `src/cli/cli-error.ts:67`). Both hold. Finding 1's placement point is accepted as a finding with the fix deferred (repo-wide renderer). Findings 3 and 5 added reasons to D2. Finding 8's offline path became `engine install rust --from <file>`. The native voice's error-path rows that the plan now covers are in the error contract table; existing domain errors (constraints, authorization, read-only) are reused unchanged and were not re-graded.
+
+#### Consensus table
+
+```
+DX DUAL VOICES: CONSENSUS TABLE [subagent-only]
+Dimension | Claude subagent | Codex | Consensus
+1. Getting started under 5 min? | No: no walkthrough; TTHW undetermined | N/A | N/A
+2. API/CLI naming guessable? | Yes (7/10); capability discovery gap | N/A | N/A
+3. Error messages actionable? | No: 5 High CAP6 findings, no CAP4 | N/A | N/A
+4. Docs findable and complete? | No (5/10): examples, troubleshooting | N/A | N/A
+5. Upgrade path safe? | Partly: install and upgrade failures | N/A | N/A
+6. Dev environment friction-free? | No: no contributor build-to-test path | N/A | N/A
+```
+
+Codex is not installed, so every consensus cell is N/A (voice coverage missing). The subagent column agrees with this review on all six rows.
+
+#### NOT in scope
+
+- Moving `Fix:` to the last line in the shared CLI renderer: every command changes; never inside a Rust PR.
+- A preview issue template under `.github/ISSUE_TEMPLATE/`: the docs name the route.
+- `gbrain engine remove rust`: deleting the addon directory is enough for the preview.
+- Usage telemetry: gbrain has none; feedback comes from issues and the preview log.
+- A Champion-tier (under 2 min) TTHW: copying and indexing an existing brain cannot honestly meet it.
+- A new MCP operation for capabilities: `engine status --json` and the migration plan cover it.
+
+#### What already exists
+
+- The error envelope, `Action` with `actor` and `next`, exit codes and the `--json` fallback (`docs/protocol/AGENT_OPERATOR_v1.md`); the registry with generated docs and `gbrain errors <code>` (`src/core/error-registry.ts`, `src/core/error-docs.ts`).
+- Graduation modes: `--plan`, `--yes --expect`, `--status`, `--resume`, `--rollback-to-source`, `--json`, progress on stderr (`src/commands/migrate-graduation.ts`).
+- `gbrain engine status [--json] [--probe]` with `schema_version: 1` (`docs/ENGINES.md`).
+- `gbrain diag --json` with a timed search section (`src/commands/diag.ts`); `GBRAIN_DEBUG=1`.
+- The quiesced physical-copy runbook for brains over the backup cap (`docs/guides/in-agent-setup.md`).
+- The troubleshooting symptom table format (`docs/guides/troubleshooting.md`).
+- Binary self-update verification (SHA-256 plus attestation) in `src/core/binary-self-update.ts`.
+
+#### TODOS.md updates
+
+None proposed. Deferred DX items are in the plan's `## Deferred` section, as for the CEO phase (no user questions in this host).
+
+#### Implementation Tasks
+
+Synthesized from this review's findings. Effort assumes features at about 30x and docs at about 50x human to CC time.
+
+- [ ] **T1 (P1, human: ~2d / CC: ~1h)** Rust engine error contract: registry rows for every code and reason, `detail` context, per-reason fixes, a test per row
+ - Surfaced by: Pass 3, CAP6 on all five paths; native findings 1, 2, 5
+ - Files: `src/core/error-registry.ts`, `src/core/rust-engine/loader.ts`, `src/core/rust-engine.ts`, `docs/guides/error-codes.md`
+ - Verify: `bun test` for the per-code tests; `bun run build:error-codes` leaves no diff
+- [ ] **T2 (P1, human: ~1d / CC: ~30min)** Panic hook, diagnostic file and id, rollback and reopen after a caught panic
+ - Surfaced by: Pass 3 unexpected path; native finding 4
+ - Files: `rust/crates/gbrain-napi`, `src/core/rust-engine/`
+ - Verify: injected-panic drill returns `internal_error` with an id and the next call succeeds
+- [ ] **T3 (P1, human: ~1d / CC: ~30min)** Doctor maintenance path that works when normal open fails
+ - Surfaced by: native finding 3
+ - Files: `rust/crates/gbrain-store`, doctor checks, `src/core/rust-engine/`
+ - Verify: corrupt-index and failed-replay drills repaired by `doctor --fix`
+- [ ] **T4 (P1, human: ~1d / CC: ~30min)** `migrate --to rust` graduation modes, plan contents, capability report, never prompts, timed search at the end
+ - Surfaced by: Pass 1, Pass 2; native finding 7
+ - Files: `src/commands/migrate-graduation.ts`, `src/core/persistence/graduation-*.ts`
+ - Verify: plan `--json` lists blockers, time, disk and lost capabilities; a non-interactive run without `--expect` exits 3
+- [ ] **T5 (P1, human: ~1d / CC: ~30min)** `engine install rust` idempotence, `--json`, `--from <file>`, failure states, addon pruning; `engine status` fields
+ - Surfaced by: Pass 2, Pass 5; native findings 5, 8
+ - Files: `src/commands/engine-install.ts`, `src/commands/engine-status.ts`, `src/cli/commands/engine.ts`
+ - Verify: install failure drills leave the active addon unchanged
+- [ ] **T6 (P1, human: ~1d / CC: ~20min)** PR 23 preview docs with the tested quickstart, capability list, troubleshooting rows, agent rule, reporting route
+ - Surfaced by: Pass 1, Pass 4, Pass 7; native finding 6
+ - Files: `docs/ENGINES.md`, `docs/guides/troubleshooting.md`, `INSTALL_FOR_AGENTS.md`, `README.md`
+ - Verify: the time-to-first-query drill follows the quickstart verbatim
+- [ ] **T7 (P1, human: ~4h / CC: ~15min)** Contributor quickstart and `rust:build`; override keeps compatibility checks
+ - Surfaced by: Pass 6; native findings 6, 8
+ - Files: `rust/README.md`, `package.json` scripts, `src/core/rust-engine/loader.ts`
+ - Verify: timed in PR 1; loader test for a wrong-ABI build under the override
+- [ ] **T8 (P2, human: ~1d / CC: ~30min)** Rust layout in the physical-copy runbook and a restore drill above the 8 GiB cap
+ - Surfaced by: Pass 5; native finding 8
+ - Files: `docs/guides/in-agent-setup.md`, `src/core/backup/`
+ - Verify: restore drill digests equal
+- [ ] **T9 (P2, human: ~2h / CC: ~10min)** Time-to-first-query drill and `preview-log.md`
+ - Surfaced by: Pass 8
+ - Files: `scripts/` drill, `docs/designs/rust-engine/preview-log.md`
+ - Verify: measured time written in the preview docs
+
+#### DX Implementation Checklist
+
+```
+DX IMPLEMENTATION CHECKLIST
+============================
+[x] Time to hello world < 5 min (target, measured by the drill on the 10k fixture)
+[x] Installation is one command (gbrain engine install rust; installs of gbrain itself unchanged)
+[x] First run produces meaningful output (plan with time, blockers, capability report)
+[x] Magical moment delivered via the migrate run report's timed search
+[x] Every error message meets the agent-ready error contract (Pass 3), except Fix-line placement in human output (deferred, repo-wide)
+[x] API/CLI naming is guessable without docs
+[x] Every parameter has a sensible default (database_path, addon location)
+[x] Docs have copy-paste examples that actually work (quickstart run verbatim by the drill)
+[x] Examples show real use cases (a filtered search on the user's own brain)
+[x] Upgrade path documented with migration guide (staged upgrade, way back, reasons)
+[ ] Breaking changes have deprecation warnings + codemods: N/A until PR 25 (PGLite deprecation, deprecations.d)
+[x] TypeScript types included (BrainEngine, typed envelopes)
+[x] Works in CI/CD without special configuration (default runs need no Rust; the Rust lane is path-filtered)
+[x] Free tier available: N/A, open source, no account
+[x] Changelog exists and is maintained (changelog.d fragment per PR)
+[x] Search works in documentation: repo docs plus gbrain errors <code> offline
+[ ] Community channel exists and is monitored: GitHub issues only; no dedicated channel (deferred)
+```
+
+#### Taste decisions
+
+- Timed search in the migration run report (magical moment). Alternative: the quickstart tells users to run `gbrain diag --json` before and after.
+- Keep the shared renderer's `Fix:` placement; agents read `fix` from `--json`. Alternative: a Rust-only renderer that prints `Fix:` last, which would make Rust errors look different from every other code.
+- `engine install rust --from <file>` for offline machines. Alternative: document manual cache population only.
+- TTHW target 5 min on the 10k fixture (Competitive). Alternatives: under 2 min (not credible for a copy plus index build) or no number.
+
+USER CHALLENGES: None. Every accepted change stays inside the user's direction (third engine, opt-in, PGLite deprecation later).
+
+### Eng review (Phase 3)
+
+INPUT: eng ef6418b306cecfe1d77a2bcb368c2f2cc763c730e30edfacf3f9561aa5884e57 (amendment checkpoint `eng-implementation.md`, 520 lines). Methodology: plan-eng-review read 2108/2108 to EOF. Native subagent voice: completed, INPUT matched the snapshot. Outside voice (codex): unavailable, not installed. Scope signals: db, perf, search, dependency.
+
+Mode: FULL_REVIEW. Scope accepted as-is.
+
+#### Step 0. Scope challenge
+
+Premise table (every factual claim the plan's engineering rests on, checked at 9f1d54232d):
+
+| # | Premise | Claim | Receipt | Verdict |
+|---|---|---|---|---|
+| 1 | One engine seam | `BrainEngine` with `kind: 'postgres' \| 'pglite'` and `transaction<T>` | `src/core/engine.ts:832-849` | verified |
+| 2 | Raw SQL escape hatch is on the interface | `executeRaw` with signal, timeout, deadline, jitOff, prepare | `src/core/engine.ts:2714-2718` | verified |
+| 3 | `engine.ts` is at its size ceiling | 2,890 lines, ceiling 2890 | `scripts/module-size-limits.tsv:19` | verified |
+| 4 | engine-sql migration state | 15 migrated domains, 54 members still own SQL | `scripts/engine-sql-baseline.tsv:1` | verified |
+| 5 | Direct kind comparisons | 268 in `src` | `src/core/persistence/unbound-source.ts:119` | verified |
+| 6 | Engine construction is two-way | `config.engine \|\| 'postgres'`, pglite and postgres cases, "SQLite is not supported" | `src/core/engine-construct.ts:10-23` | verified |
+| 7 | Database URL forces Postgres | env var implies `'postgres'` | `src/core/config.ts:738-745` | verified |
+| 8 | Test matrix is two-way and env-selected | `TestBackend = 'pglite' \| 'postgres'`; unknown backends throw | `test/helpers/test-backends.ts:4-21` | verified |
+| 9 | Test files branch two ways on backend | `backend === 'postgres' ? url : undefined` builds PGLite otherwise | `test/trust-release-strict-home-gst2676.test.ts:69-70` | verified |
+| 10 | PGLite transaction holds keys across awaits | `withHeldPageKeys`, tx engine clone | `src/core/pglite-engine.ts:1209-1212` | verified |
+| 11 | Owner model keys on config, not only engine | `cfg.engine === 'pglite'` before an engine exists | `src/core/context/resolve-ipc.ts:404` | verified |
+| 12 | Graduation helpers are SQL on both sides | catalog columns, sequences, verify queries | `src/core/persistence/graduation-copy.ts:250` | verified |
+| 13 | Migration runner selects SQL per kind | `m.sqlFor?.[engine.kind] ?? m.sql`, then handler and verify | `src/core/migrate.ts:546-548` | verified |
+| 14 | Fingerprint is SQL with host `lower()` and POSIX classes | `gbrain_fact_fingerprint`, `_v1` | `src/core/facts/withdrawal-schema.ts:23-37` | verified |
+| 15 | full-ci dispatches two workflows only | `test.yml` and `e2e.yml` | `.github/workflows/full-ci.yml:46-47` | verified |
+| 16 | Backup is PGLite-only | refuses with `pglite_required`; 8 GiB archive cap | `src/core/backup/snapshot.ts:138-143` | verified |
+| 17 | Release targets | `bun-darwin-arm64`, `bun-linux-x64` | `.github/workflows/release.yml:160-170` | verified |
+| 18 | Native addon loader pattern exists | `loadBindingSync()` | `src/core/persistence/native-lock.ts:94` | verified |
+
+unverified=0
+
+What already solves each sub-problem:
+- Owner lock, owner IPC, consumer election: reused via the `single_owner` capability (`src/core/persistence/consumer-election.ts`).
+- Typed SQL boundary for Postgres-dialect engines: `src/core/engine-sql/` with `SqlExecutor` and `DialectCapabilities`; Track 2 extends it.
+- Runner-selected test arms: `scripts/postgres-unit-arms.ts` with `test/postgres-unit-arms.txt`; the Rust arm copies this pattern.
+- Expected divergence: `EXPECTED_FAILURES` with `test.failing` (`test/helpers/two-engine.ts:308`).
+- Graduation custody, inventory, digest and verify: `src/core/persistence/graduation-*.ts`; kept, with an engine-neutral adapter under it.
+- Native addon build, prebuild and load: `native/locks/` and `native-lock.ts`.
+- Attested download: `src/core/binary-self-update.ts`.
+- Crash robot and refresh-barrier spec: `scripts/persistence/README.md`, `spec/tla/refresh-barrier/`.
+
+Complexity check: the plan touches far more than 8 files and adds many modules and crates, so the gate trips. Auto-decided `plan-eng-review-structure`: "Original arrangement" (one engine, about 45 small PRs, two tracks, Checkpoint C1) over "Smaller arrangement" (Rust index accelerator only). The smaller shape is option B, which the plan already rejected for changing existing engines and the user direction rules out. Scope accepted as-is; the review adds PR 14b and amends existing rows.
+
+Reality rows:
+
+REALITY: premise-table pass 18 premises checked against code at 9f1d54232d, unverified=0; seam, unions, SQL escape hatch, test matrix, graduation SQL and migration dispatch confirmed src/core/engine.ts:830
+REALITY: already-done pass git fetch to origin/master a278ddf458; no rust/ tree; no rust-engine, napi or Rust engine commits since 2026-10-01 src/core/engine-construct.ts:10-23
+REALITY: surface-check finding GBRAIN_TEST_BACKEND=rust throws today; migrate --to accepts postgres, supabase, pglite only; full-ci dispatches only test.yml and e2e.yml, so a separate Rust workflow never runs under full-ci; plan amended (PR 9 runner, full-ci dispatch, trigger check) test/helpers/test-backends.ts:20
+REALITY: binding-decisions pass gstack-decision-search returned none; the user direction and the merge process guide stay binding; no overruled default is reintroduced docs/designs/RUST_ENGINE.md:45
+REALITY: numbers finding 268 kind comparisons [measured: rg over src]; 15 migrated and 54 method rows [measured: scripts/engine-sql-baseline.tsv]; 830 files call testBackends, not 831, and 790 of them call executeRaw [measured: rg over test]; 296 two-way backend ternaries in 258 files [measured: rg over test]; plan amended [re-measure before gate] scripts/engine-sql-baseline.tsv:1
+REALITY: deferred-asks pass no linked issue; the plan Deferred section gains Postgres to Rust migration and a shared fingerprint change, each with its reason docs/designs/RUST_ENGINE.md:478
+REALITY: pr-count finding ship-policy has no pr_count so the default is one PR per wave; the merge process requires small PRs; this review adds PR 14b, one more queue slot with a persistence heads-up .gstack/ship-policy.json:1
+REALITY: prior-art pass napi-rs on Bun is best effort and threadsafe-function shutdown, cancellation after start and exit with pending work need runtime tests (https://napi.rs/docs/more/troubleshooting); diverge because PR 1 proves each lifecycle case in Bun before engine code src/core/persistence/native-lock.ts:94
+REALITY: transaction-semantics finding PGLite holds page keys across awaits through a tx engine clone; a Rust writer held across awaits on a shared worker pool can starve and re-entry can deadlock; amended with async admission, a transaction executor and a re-entry refusal; crash robot keeps its Rust cell src/core/pglite-engine.ts:1209
+REALITY: contract-assumptions finding graduation copy and verify assume Postgres catalogs and sequences; the migration runner assumes SQL; fingerprint normalization depends on the host lower(); amended with a graduation adapter, a Rust migration disposition and unchanged SQL fingerprints on Postgres src/core/persistence/graduation-copy.ts:250
+REALITY: units pass vector storage units unchanged from the CEO phase; raw f32 at 1M chunks and 1,024 dimensions is about 3.8 GiB [estimated] beside the 7.6 GiB HNSW figure; cosine 1e-6 and recall@10 consumers unchanged docs/ENGINES.md:236-238
+REALITY: perf-table finding targets had no named bench step and writes were not measured with the writer held across awaits plus the outbox apply; amended with named rust/bench steps, same-machine PGLite, p50 and p99, and peak memory against the envelope scripts/scale/budgets.json:1
+REALITY: recall pass recall@10 against exact across selectivity and scope buckets stays; a behind index or a revision mismatch falls back to the exact path and keeps the vector_candidates_incomplete reason src/core/ops/search.ts:1022
+REALITY: dependency-fallback pass without the addon the engine reports engine_unavailable; without D11 Phase 6 waits; without PR 14b migrate --to rust does not ship; before PR 19 the loader refuses a catalog mismatch and dev stores are rebuilt src/core/engine-construct.ts:16
+REALITY: obligation-tiers pass must-ship for the preview is PRs 1 to 23 with 14b and 21b plus the accepted eng requirements; next is PR 24; deferred items in the plan; budget recorded at Phase 1 entry and checked at C1 src/core/backup/snapshot.ts:138
+
+PLAN_REALITY: phase=eng rows=15/15 missing=none unverified=0 verdict=complete
+
+#### Step 0.5. Dual voices
+
+ENG DUAL VOICES: CONSENSUS TABLE [subagent-only]
+
+| Dimension | Claude subagent | Codex | Consensus |
+|---|---|---|---|
+| Architecture sound | seam sound; snapshot, post-commit, graduation and migration contracts missing | N/A | N/A |
+| Test coverage sufficient | no; test arm can pass on PGLite; CI filters miss schema changes | N/A | N/A |
+| Performance risks named with a budget or bench | partly; no bench step per target, write path under held writer unmeasured | N/A | N/A |
+| Security threats covered | snapshot leak of newer restricted content was open | N/A | N/A |
+| Error paths handled | no post-commit failure contract; re-entry hangs | N/A | N/A |
+| Deployment risk manageable | yes, with full-ci wiring and the staged addon upgrade | N/A | N/A |
+
+Codex is not installed, so every consensus cell is N/A. Native voice verdict: rework before implementation; the rework is folded into the plan below.
+
+Native voice reconciliation (every cited file:line checked against the checkout):
+
+| # | Native finding | Check | Disposition |
+|---|---|---|---|
+| 1 | P1 records and derived indexes lack a shared snapshot contract | design gap, confirmed by the plan's "One commit point" text | accepted: generation-ranged index entries, revision backstop, exact fallback, isolation test |
+| 2 | P1 index apply failure after commit has no live-process contract | confirmed | accepted: committed receipt, relation marked behind, exact path until replay, fault injection test |
+| 3 | P1 relation API does not support the migration roundtrip | `graduation-digest.ts:87`, `graduation-copy.ts:250`, `graduation-verify.ts:67-135` all issue SQL, confirmed | accepted: engine-neutral graduation adapter, PR 14b early roundtrip, Postgres to Rust deferred |
+| 4 | P1 catalog versioning is not a migration strategy | `migrate.ts:546-605` selects SQL then runs handler and verify, confirmed | accepted: Rust disposition per migration, ordering of records, ledger and `FORMAT`, upgrade test |
+| 5 | P1 shared fingerprint function can change Postgres | `withdrawal-schema.ts:23-37` uses `pg_catalog.lower` and `[[:space:]]`, confirmed | accepted: Postgres and PGLite keep SQL; Rust fuzzed against PGLite; shared change deferred |
+| 6 | P1 async transaction scheduling can starve the writer | confirmed by the plan's worker-pool rule plus `transaction(fn)` held across awaits | accepted: async permit before any worker, transaction executor, bounded wait, test |
+| 7 | P2 Rust CI filters miss breaking changes | `full-ci.yml:46-47` dispatches only `test.yml` and `e2e.yml`, confirmed | accepted: widened filters, full-ci dispatch, trigger-selection check |
+| 8 | P2 approval inputs unresolved | C1 effort cap, corpus and spend, gbrain-evals owner | queued for the Phase 4 final gate with recommendations (Unresolved decisions below) |
+
+#### Section 1. Architecture
+
+```
+ CLI / MCP operations / cycle / minions (unchanged TypeScript)
+ |
+ dispatch capability check <-- engine-capabilities.ts
+ | members.ts (every BrainEngine member)
+ BrainEngine seam
+ +--------------------+---------------------+
+ | | |
+ PGLiteEngine PostgresEngine RustEngine (wrapper, TS)
+ | | | loader.ts (dlopen, digest, abi)
+ engine-sql/ (SqlExecutor, Postgres dialect) | admission: async writer permit
+ | | | transaction executor
+ PGLite WASM postgres.js v
+ gbrain-napi (async tasks, panic hook)
+ |
+ +-----------+-----------+--------+---------+------------+
+ | | | | |
+ gbrain-store gbrain-domain gbrain-text gbrain-vector gbrain-graph / gbrain-trgm
+ records, trigger hooks postings ANN + exact BFS, trigrams
+ counters, write scope (generation scan, bitmaps
+ outbox, FORMAT ranges) (generation ranges)
+
+ Migration: graduation custody state machine -> graduation adapter (PGLite | Rust)
+ Schema: migrate.ts -> sqlFor (PGLite, Postgres) | Rust disposition (catalog_only, postgres_only, handler+verify)
+```
+
+Findings:
+- A1 (P1, native 1). No snapshot contract between records and derived indexes; an older reader could see newer indexed content or permissions. Fix accepted: entries carry generation ranges, readers filter at their snapshot, reclamation after the oldest reader, revision backstop and exact fallback.
+- A2 (P1, native 2). No live-process contract for an index apply failure after commit. Fix accepted: committed receipt, relation marked behind, exact path until idempotent replay.
+- A3 (P1, native 3). Graduation reuse was overstated; helpers are SQL. Fix accepted: engine-neutral adapter (PR 14b), PGLite to Rust and back only; Postgres to Rust deferred.
+- A4 (P1, native 4). No schema and data migration strategy for Rust stores. Fix accepted: Rust disposition per `Migration`, one store transaction per migration, `FORMAT` repaired from records, a check for missing dispositions.
+- A5 (P1, native 6 plus this review). Writer held across awaits on a shared pool can starve; a call on the outer engine inside `transaction(fn)` deadlocks. Fix accepted: async permit, transaction executor, bounded wait with existing `cancelled` and `timeout`, `internal_error` reason `transaction_reentry` (added to D2).
+- A6 (P2). Worker pool lifecycle on `disconnect()` and the consumer stop barrier was unspecified, and Bun threadsafe-function lifecycle is best effort. Fix accepted: drain, cancel and close order; PR 1 smoke covers the four Bun cases.
+- A7 (P2). `single_owner` as a capability misses config-level checks in `resolve-ipc.ts:404,437` and `graduation-serve-guard.ts:33`. Fix accepted: `engineIsSingleOwner(cfg.engine)`.
+- A8 (P2). Backup for Rust cannot reuse the PGLite physical snapshot (`snapshot.ts:138-149`). Fix accepted: a snapshot under the owner lock at one committed generation.
+- A9 (P1, native 5). Moving the fingerprint into one PGLite-matched function would change future Postgres fingerprints. Fix accepted: SQL stays on both Postgres-dialect engines.
+
+Design twice:
+- Chosen: in-process napi engine implementing typed `BrainEngine` methods, with domain rules (triggers, guards) in Rust. One commit point, no SQL, owner model reused.
+- Second shape: Rust as a typed relation store under the existing TypeScript domain logic (a `SqlExecutor`-like boundary that takes relation reads and writes, with triggers kept in TypeScript). Smaller Rust surface and shared domain code, but every domain method becomes many boundary crossings, trigger semantics move to TypeScript for all engines (a behavior change for existing engines), and transaction-held-across-awaits costs grow per row. Kept the chosen shape; the relation API stays for tests, migration and digests.
+
+Red flags screen: (1) hidden shared state: index generations, addressed by A1; (2) two sources of truth: records and indexes, addressed by A1 and A2; (3) lock held across await: A5; (4) silent fallthrough to another engine: test arm (Section 3) and `byEngineKind`; (5) config and runtime disagree: A7; (6) dependency assumed from another repo: gbrain-evals pin (D11); (7) unbounded memory: generation ranges and 1M vectors (Section 4); (8) hand-synced list: capability coverage, addressed by the member table.
+
+Distribution: unchanged from CEO and DX (attested assets, pinned digest manifest, staged upgrade, `--from <file>`). No new install path.
+
+One realistic production failure per new path:
+
+| Path | Failure | Handled after review |
+|---|---|---|
+| Loader | stale local build under the override | refused by abi, catalog and format checks |
+| Writer admission | 50 writers queue while a transaction awaits | async permit, executor; bounded wait gives `timeout` |
+| Outbox apply | disk full after record commit | committed receipt; relation behind; exact path; replay |
+| Search | reader paused across a permission change | generation filter plus revision backstop |
+| Schema migration | handler interrupted mid-migration | one store transaction; ledger and `FORMAT` truthful |
+| Graduation | target sequence below a consumed source value | adapter transfers counters at or above the max consumed |
+| Backup | copy taken while the outbox is behind | snapshot at one committed generation, indexes rebuilt on restore |
+| Shutdown | process exit with pending native tasks | stop admission, cancel, bounded drain; PR 1 smoke |
+
+#### Section 2. Code quality
+
+- Q1 (P2). Capability coverage was a hand-synced list. Fix accepted: `src/core/rust-engine/members.ts` typed `satisfies Record<keyof BrainEngine, 'implemented' | Capability>`; coverage derived from it.
+- Q2 (P2). The two-engine unions live in several files (config, `migrate-engine.ts`, `resolve-ipc.ts:368`, the inventory `engines` record) and the constructor message names two engines. Fix accepted: all gain `rust`; the inventory has no default for `rust`.
+- Q3 (P3). `docs/ENGINES.md` "Adding a new engine" step 3 assumes a Postgres-dialect `SqlExecutor`. Fix accepted: PR 8 adds a non-SQL engine note.
+
+Shared-code rubric: the review reuses `scripts/postgres-unit-arms.ts`, `EXPECTED_FAILURES`, the graduation custody state machine and existing error codes (`cancelled`, `timeout`, `internal_error`) instead of adding parallel ones. One reason (`transaction_reentry`) is added under D2.
+
+#### Section 3. Tests
+
+Code path and user flow coverage (planned tests after this review):
+
+```
+CODE PATHS USER FLOWS
+constructEngine('rust') gbrain engine install rust
+ +- addon missing / abi / format [★★ TESTED] loader +- each failure state [★★ TESTED] drills
+ +- loaded, capabilities [★★ TESTED] PR 8 +- offline upgrade [→E2E] drill
+RustEngine.transaction(fn) gbrain migrate --to rust (PGLite)
+ +- nested savepoint / abort [★★★ TESTED] arm +- --plan json fields [★★ TESTED]
+ +- re-entry on outer engine [★★ TESTED] new +- no --expect, exit 3 [★★ TESTED]
+ +- writers > workers, cancel [★★★ TESTED] new +- roundtrip and back [→E2E] PR 14b, PR 21
+ +- disconnect with pending tasks [★★ TESTED] PR 1 +- from Postgres [GAP] deferred by design
+write commit -> outbox apply search on a Rust brain
+ +- SIGKILL between [★★★ TESTED] robot +- after own write [★★★ TESTED] arm
+ +- live failure after commit [★★★ TESTED] new +- paused reader, perm chg [★★★ TESTED] new
+ +- replay idempotent [★★ TESTED] new +- E1 parity [→EVAL] E1
+schema migration on Rust store backup create / restore (Rust)
+ +- disposition missing [★★ TESTED] check +- restore drill [→E2E] PR 21b
+ +- interrupted, resumable [★★★ TESTED] new +- above 8 GiB runbook [→E2E] drill
+fingerprint on Rust remember / forget / withdraw
+ +- fuzz vs PGLite SQL [★★★ TESTED] PR 13 +- suppressed after move [★★★ TESTED] new
+test arm selection CI
+ +- rust label opens PGLite [★★ TESTED] assert +- schema-only change runs Rust lane [★★ TESTED] check
+```
+
+COVERAGE: 26 paths, 25 planned with a test, 1 GAP (Postgres to Rust, deferred by design).
+QUALITY: 10 at ★★★ (behavior and edge cases), 11 at ★★, 5 routed to E2E or EVAL.
+
+Test gaps found (before amendment):
+- G1 (CRITICAL). Test arm false green: 296 `backend === 'postgres' ?` ternaries in 258 files build PGLite for any other backend. Fix: runner, helper, kind assertion, listing check.
+- G2. Rust CI path filters miss schema, interface and harness changes; full-ci does not dispatch the Rust workflow.
+- G3. No live failure-after-commit test.
+- G4. No snapshot isolation test across a permission change.
+- G5. No writer starvation, cancellation or re-entry test.
+- G6. No Rust store migration upgrade test.
+- G7. No fingerprint suppression test across migration with non-ASCII claims.
+- G8. No early migration roundtrip.
+
+Value cards:
+- Kind assertion. Value: protects=a Rust arm that cannot pass on PGLite; fails_when=any engine opened under the Rust arm has another kind; why_new=two-way branches fall through silently today; seam=none; no_claim=Rust correctness of the file's behavior.
+- Failure after commit. Value: protects=no resubmission of a committed write and no stale search; fails_when=receipt says rolled back or search uses a behind index; why_new=the plan only covered process death; seam=none; no_claim=disk-full handling in the record store itself.
+- Paused reader. Value: protects=callers never read newer restricted content; fails_when=a reader at N returns N+1 content or scores; why_new=indexes and records had no shared snapshot; seam=none; no_claim=Postgres or PGLite isolation.
+- Writer admission. Value: protects=bounded completion with more writers than workers; fails_when=any writer hangs past its bound or a permit leaks on cancel; why_new=transaction held across awaits on a shared pool; seam=none; no_claim=throughput targets.
+- Migration upgrade. Value: protects=existing Rust stores across releases; fails_when=data lost, step not resumable, or version markers ahead of data; why_new=catalog versioning had no data path; seam=none; no_claim=Postgres migrations.
+- Fingerprint suppression. Value: protects=forgotten facts stay forgotten; fails_when=an equivalent claim is accepted after a move; why_new=Rust computes the fingerprint outside SQL; seam=none; no_claim=cross-host Postgres equivalence.
+- Early roundtrip. Value: protects=graduation adapter correctness before the preview; fails_when=any relation digest differs or a sequence goes below a consumed value; why_new=helpers were SQL-only; seam=none; no_claim=Postgres to Rust.
+- Trigger-selection check. Value: protects=the Rust lane runs on changes that can break it; fails_when=a schema-only or capability-only diff skips the lane; why_new=filters were Rust-only; seam=none; no_claim=lane runtime.
+
+Tests made obsolete: none. No existing test is retired; `testBackends()` keeps its current behavior when `GBRAIN_TEST_BACKEND` is unset or names a Postgres arm.
+
+REGRESSION RULE: applied. Every change to shared files (`test-backends.ts`, `migrate.ts`, `schema-migrations/types.ts`, the graduation helpers, `full-ci.yml`, the engine unions) is gated by the existing PGLite and Postgres arms passing unchanged in the same PR, plus `test/graduation-inventory.test.ts` and `test/e2e/engine-parity.test.ts`.
+
+Test plan artifact: kept in the reviewer's local gstack project directory (`eng-review-test-plan-20261117-015207.md`); the test plan above is the committed copy.
+
+#### Section 4. Performance
+
+Scale: 10k, 200k and 1M chunks given by the plan; brain-level write rates for real users unknown until C1's real-brain benchmark.
+- P1. Write path: every write holds the single writer across awaits and applies the outbox before return, so the "committed writes at least 3x PGLite" target could fail on apply cost. Fix accepted: bench through `transaction(fn)` with the writer held, outbox apply included.
+- P2. Memory: raw f32 at 1M chunks and 1,024 dimensions is about 3.8 GiB [estimated] before any graph; generation-ranged entries add superseded entries until reclamation, and a long reader pins them. Fix accepted: peak memory reported against the `bakeoff.md` envelope at 200k and 1M; reclamation after the oldest reader.
+- P3. Targets had no named bench step. Fix accepted: one `rust/bench/` step per target printing machine, engine, size, N, p50 and p99 with PGLite on the same machine.
+- N+1: the relation API and graduation adapter page in primary-key keyset order; no per-row boundary crossing on the hot paths. Caching: none added; derived indexes are the cache and are rebuildable.
+
+#### NOT in scope
+
+- Postgres to Rust migration (deferred; needs multi-host fencing and per-host fingerprint equivalence).
+- A shared TypeScript fingerprint or versioned normalization for all engines (deferred; needs the maintainer's yes).
+- Any change to PGLite or Postgres behavior; Track 2 moves SQL without changing it.
+- A sidecar process binding (deferred by the CEO phase).
+
+#### What already exists
+
+Reused without change: the operation layer, MCP, fusion, chunkers, the persistence coordinator, the error envelope, the owner lock and IPC, `scripts/postgres-unit-arms.ts` as the runner pattern, `EXPECTED_FAILURES`, the graduation custody state machine and inventory, `binary-self-update.ts` verification, and the crash robot.
+
+#### Failure modes registry
+
+| Failure | Test | Handling | Silent? | Critical gap before review |
+|---|---|---|---|---|
+| Rust arm passes on PGLite | kind assertion | file fails | yes | CRITICAL |
+| Index apply fails after commit, process alive | fault injection | receipt committed, exact path, replay | yes | CRITICAL |
+| Older reader sees newer restricted content | paused reader | generation filter, backstop | yes | CRITICAL |
+| Fingerprint drift un-forgets a fact | suppression test | SQL unchanged on Postgres; Rust fuzzed | yes | CRITICAL |
+| Writer starvation | admission test | async permit, executor, timeout | no (hang) | gap |
+| Re-entry deadlock | re-entry test | `transaction_reentry` | no (hang) | gap |
+| Migration interrupted on Rust store | upgrade test | one transaction per migration | no | gap |
+| Sequence reissued after migration | roundtrip | adapter keeps max consumed | yes | gap |
+| Rust lane skipped on schema change | trigger check | widened filters, full-ci | yes | gap |
+
+Critical gaps flagged: 4, all closed by accepted requirements.
+
+#### Unresolved decisions
+
+Unresolved decisions that may bite you later (queued for the Phase 4 final gate; the plan already makes each a Phase 1 or Phase 3 entry input):
+- U1 (D11). Who lands and pins the gbrain-evals changes. Options: the maintainer lands them (least coordination); a named delegate (parallel work, needs confirmed access and ownership). Recommendation: the maintainer lands them unless a delegate is named.
+- U2 (Phase 1 entry, resolved at the final gate: 8 calendar weeks or 25 merged PRs). The effort budget through Checkpoint C1. Recommendation: 8 calendar weeks or 25 merged PRs from PR 1, whichever comes first, checked at C1 [estimated].
+- U3 (D10 and open question 3). The 1M benchmark corpus and spend. Recommendation: a permissively licensed public text corpus cut to 1M chunks and embedded once at 1,024 dimensions, kept as a fixture outside the repository, with a spend cap of $50 [estimated] beside the $2 LongMemEval cache.
+
+#### TODOS
+
+TODOS.md updates: none proposed. Per the merge process guide, deferrals go in the plan's `## Deferred` section instead of TODOS.md; this review adds two rows there.
+
+#### Implementation Tasks
+
+Synthesized from this review's findings. Effort assumes architecture and test work (ratios about 5x to 50x).
+
+- [ ] **T1 (P1, human: ~3d / CC: ~3h)** Test harness: Rust arm runner, engine-for-backend helper, kind assertion, listing check
+ - Surfaced by: Section 3, G1
+ - Files: `scripts/rust-unit-arms.ts`, `test/helpers/test-backends.ts`, `test/rust-unit-arms.txt`
+ - Verify: a listed file with a two-way branch is refused; an engine of another kind under the arm fails the file
+- [ ] **T2 (P1, human: ~1w / CC: ~1d)** Store and indexes: generation-ranged entries, revision backstop, exact fallback
+ - Surfaced by: Section 1, A1
+ - Files: `rust/crates/gbrain-text`, `rust/crates/gbrain-vector`, `rust/crates/gbrain-store`
+ - Verify: paused reader test across a content and permission update
+- [ ] **T3 (P1, human: ~4d / CC: ~4h)** Store: failure-after-commit state, behind marking, idempotent replay
+ - Surfaced by: Section 1, A2
+ - Files: `rust/crates/gbrain-store`, `src/core/rust-engine/`
+ - Verify: fault injection after commit, after text apply and before vector apply
+- [ ] **T4 (P1, human: ~3d / CC: ~3h)** Binding: async writer admission, transaction executor, re-entry refusal, lifecycle
+ - Surfaced by: Section 1, A5 and A6
+ - Files: `rust/crates/gbrain-napi`, `src/core/rust-engine.ts`, `src/core/error-registry.ts`
+ - Verify: writers far above worker count; re-entry gives `transaction_reentry`; PR 1 Bun lifecycle smoke
+- [ ] **T5 (P1, human: ~1w / CC: ~1d)** Graduation: engine-neutral adapter and early roundtrip
+ - Surfaced by: Section 1, A3
+ - Files: `src/core/persistence/graduation-digest.ts`, `graduation-copy.ts`, `graduation-verify.ts`, `src/core/rust-engine/`
+ - Verify: PGLite to Rust to PGLite roundtrip with consumed sequences, generated columns, withdrawals
+- [ ] **T6 (P1, human: ~4d / CC: ~4h)** Migrations: Rust disposition, dispatch, ordering, missing-disposition check
+ - Surfaced by: Section 1, A4
+ - Files: `src/core/schema-migrations/types.ts`, `src/core/migrate.ts`, `rust/crates/gbrain-store`
+ - Verify: upgrade a previous-release Rust store with legacy rows, interrupting each boundary
+- [ ] **T7 (P1, human: ~2d / CC: ~2h)** Facts: Rust fingerprint fuzzed against PGLite SQL; suppression test
+ - Surfaced by: Section 1, A9
+ - Files: `rust/crates/gbrain-domain`, `rust/fixtures/`
+ - Verify: withdrawals before a move suppress equivalent non-ASCII claims after it
+- [ ] **T8 (P2, human: ~1d / CC: ~1h)** Engine shell: `members.ts` table; coverage derived from it
+ - Surfaced by: Section 2, Q1
+ - Files: `src/core/rust-engine/members.ts`, `scripts/check-rust-capability-coverage.ts`
+ - Verify: adding an interface member fails `bun run typecheck` until classified
+- [ ] **T9 (P2, human: ~1d / CC: ~1h)** Engine unions and constructor message
+ - Surfaced by: Section 2, Q2
+ - Files: `src/core/engine.ts`, `src/core/engine-construct.ts`, `src/core/config.ts`, `src/commands/migrate-engine.ts`, `src/core/context/resolve-ipc.ts`, `src/core/persistence/graduation-inventory.ts`
+ - Verify: an inventory row without `rust` fails typecheck
+- [ ] **T10 (P2, human: ~1d / CC: ~1h)** Owner model: config-level `engineIsSingleOwner`
+ - Surfaced by: Section 1, A7
+ - Files: `src/core/context/resolve-ipc.ts`, `src/core/persistence/graduation-serve-guard.ts`
+ - Verify: owner socket and secret paths resolve for a Rust config
+- [ ] **T11 (P2, human: ~1d / CC: ~1h)** CI: widened filters, full-ci dispatch, trigger-selection check
+ - Surfaced by: Section 3, G2
+ - Files: `.github/workflows/rust-engine.yml`, `.github/workflows/full-ci.yml`
+ - Verify: a schema-only diff selects the Rust lane
+- [ ] **T12 (P2, human: ~2d / CC: ~2h)** Backup: Rust snapshot at one committed generation
+ - Surfaced by: Section 1, A8
+ - Files: `src/core/backup/`, `src/commands/backup.ts`
+ - Verify: full-store restore drill with equal relation digests
+- [ ] **T13 (P2, human: ~2d / CC: ~2h)** Bench: named step per target, held-writer write bench, memory against envelope
+ - Surfaced by: Section 4, P1 to P3
+ - Files: `rust/bench/`, `docs/designs/rust-engine/bakeoff.md`
+ - Verify: each step prints machine, engine, size, N, p50 and p99 beside PGLite
+- [ ] **T14 (P3, human: ~1h / CC: ~10min)** Docs: non-SQL note in "Adding a new engine"
+ - Surfaced by: Section 2, Q3
+ - Files: `docs/ENGINES.md`
+ - Verify: docs review in PR 8
+
+#### Worktree parallelization
+
+| Lane | Tasks | Modules | Depends on |
+|---|---|---|---|
+| A | T11 then T4 smoke | `.github/`, `rust/crates/gbrain-napi` | none (PR 1) |
+| B | T8, T9, T14 | `src/core/engine*`, `src/core/rust-engine/` | PR 1 |
+| C | T1 | `test/helpers/`, `scripts/` | Lane B |
+| D | T13 | `rust/bench/` | PR 1 |
+| E | T2, T3, T4 rest | `rust/crates/` | Phase 2 bake-off |
+| F | T5, T6 | `src/core/persistence/graduation-*`, `src/core/migrate.ts` | Lane E |
+| G | T7, T10, T12 | facts crate, `resolve-ipc.ts`, `src/core/backup/` | Lane E |
+
+Execution order: launch A alone (toolchain first). Then B and D in parallel. Then C. After the bake-off, E; then F and G in parallel. Conflict flags: `src/core/engine.ts` (B, F through domain objects), `src/core/rust-engine/` (B, E, F); sequence through the merge process with heads-up comments. 7 lanes, 4 parallel, 3 sequential.
+
+#### Completion summary
+
+- Step 0: Scope Challenge: scope accepted as-is
+- Reality rows: 15/15 applicable rows emitted (`PLAN_REALITY: phase=eng rows=15/15 missing=none unverified=0 verdict=complete`), 0 unverified premises
+- Architecture Review: 9 issues found
+- Code Quality Review: 3 issues found
+- Test Review: diagram produced, 8 gaps identified
+- Performance Review: 3 issues found
+- NOT in scope: written
+- What already exists: written
+- TODOS.md updates: 0 items proposed to user (deferrals in the plan's `## Deferred`)
+- Failure modes: 4 critical gaps flagged
+- Unresolved decisions: 3 in this review
+- Outside voice: codex, unavailable (not installed)
+- Parallelization: 7 lanes, 4 parallel / 3 sequential
+- Lake Score: 9/9 (every accepted fix chose the complete option)
+
+#### Taste decisions
+
+- Snapshot contract by generation-ranged index entries with a revision backstop. Alternative: validate candidates against records and retry only, which uses less memory but can miss items whose index entry was replaced.
+- Postgres to Rust migration deferred. Alternative: design multi-host source fencing now, which grows the preview for a cohort it does not target.
+- Re-entry refused as `internal_error` reason `transaction_reentry` under D2. Alternatives: route outer-engine calls into the open transaction (hides bugs), or a new top-level code (one more registry row and doc anchor).
+- Graduation adapter as its own PR 14b in Phase 5 with an early roundtrip. Alternative: build it inside PR 21, which finds adapter bugs only at the preview.
+- Fingerprints stay in SQL on PGLite and Postgres. Alternative: a versioned v2 normalization for all engines now, which needs legacy matching and the maintainer's yes.
+- Original arrangement kept at the complexity gate. Alternative: the smaller accelerator-only arrangement (option B).
+
+USER CHALLENGES: None. Every accepted change keeps the user's direction: a third engine, embedded Rust replacements, PGLite deprecation later, work in garrytan/gbrain with gbrain-evals in the plan.
+
+<!-- autoplan-baseline-edits:eng {"sourceSha256":"b73350256550439287bd9b01e84fb19f6d3e882f229405ad0f36a5cb745cb55e","replacements":[{"oldText":"- `transaction(fn)` keeps its shape: the wrapper opens a Rust write transaction handle and passes `fn` a transaction-bound clone of the engine, the same pattern `PostgresEngine` uses. Nested calls map to savepoints, an abort rolls back, `readOnly` refuses writes (`research/01` section 6). `AbortSignal` maps to a cancellation token checked between steps.","newText":"- `transaction(fn)` keeps its shape: the wrapper opens a Rust write transaction handle and passes `fn` a transaction-bound clone of the engine, the same pattern `PostgresEngine` uses. Nested calls map to savepoints, an abort rolls back, `readOnly` refuses writes (`research/01` section 6). `AbortSignal` maps to a cancellation token checked between steps.\n- Writer admission is starvation free. A caller waits for the single-writer permit asynchronously, on the JavaScript side, before it uses any worker thread. An open write transaction runs its commands on its own transaction executor, so the worker pool size never decides whether the transaction that holds the writer can finish. The wait is bounded by the caller's `AbortSignal` or deadline and ends with the existing `cancelled` or `timeout` code; a cancelled waiter leaves no permit or queued task behind.\n- Re-entry is refused. A call on the outer engine from inside its own `transaction(fn)` would wait forever for the writer it already holds. The wrapper detects it and throws `internal_error` with reason `transaction_reentry` (added to decision D2) instead of hanging. `lockPageKeys` maps to a per-key async mutex held until the transaction ends.\n- Lifecycle. `disconnect()` and the resident-consumer stop barrier stop admission, cancel queued tasks, wait a bounded time for running tasks, and then close the store. A task cancelled after it started reports what it committed through the receipt. PR 1 proves the Bun behavior this needs before any engine code: shutdown with pending tasks, cancellation after start, process exit with pending native work, and a threadsafe-function queue that is full or closing."},{"oldText":"- One commit point. A write commits records, counters and outbox entries in one store transaction, then applies the outbox to the text and vector indexes before the call returns. A search issued after a write returns sees it, as today. If the process dies between commit and apply, the open catches the indexes up before serving reads. Search re-checks deleted, withdrawn and visibility state against the record snapshot before returning.","newText":"- One commit point. A write commits records, counters and outbox entries in one store transaction, then applies the outbox to the text and vector indexes, in generation order, before the call returns. A search issued after a write returns sees it, as today. If the process dies between commit and apply, the open catches the indexes up before serving reads.\n- Snapshot contract for search. Every search pins one record snapshot generation N. Text postings and vector entries carry the generation range in which they are valid, and the search uses only entries valid at N, so a reader at N never sees content, scores or permissions from N+1. Superseded entries are reclaimed only after the oldest open reader has passed their generation. As a backstop, each candidate's indexed revision is checked against the record at N, and deleted, withdrawn and visibility state is re-checked there before ranking; a mismatch drops the candidate and the search continues with the exact path for that arm, reporting the existing `vector_candidates_incomplete` reason when it cannot fill the page.\n- Failure after commit. If applying the outbox fails while the process stays alive (disk full, an index error, cancellation), the write is still committed: the call reports it as committed through its receipt and never as rolled back. The relation is marked behind at that generation; searches that touch it use the exact path for the affected arm until replay succeeds; replay retries in generation order and is idempotent; `gbrain engine status` and doctor report the lag."},{"oldText":"Keeping Postgres relation names and columns makes the graduation inventory, digests and verification reusable as they are.","newText":"Keeping Postgres relation names and columns lets the graduation inventory, digests and verification be reused through an engine-neutral adapter (\"Migration and rollback\"); the current helpers issue catalog and sequence SQL and cannot run on Rust unchanged."},{"oldText":"- Those paths branch on `engine.kind === 'pglite'` today. Track 1 replaces those branches with one capability, `single_owner`, which PGLite and Rust report, so the Rust engine reuses the code instead of copying it.","newText":"- Those paths branch on `engine.kind === 'pglite'` today. Track 1 replaces those branches with one capability, `single_owner`, which PGLite and Rust report, so the Rust engine reuses the code instead of copying it. Some of these checks run on the config before any engine exists (`src/core/context/resolve-ipc.ts` keys the owner socket and secret on `cfg.engine === 'pglite'`; `src/core/persistence/graduation-serve-guard.ts` does the same), so a config-level helper, `engineIsSingleOwner(cfg.engine)`, answers the same question there, and both forms are covered by the kind-branch guard."},{"oldText":"`constructEngine` (`src/core/engine-construct.ts`) gains a `rust` case. `BrainEngine.kind` (`src/core/engine.ts:832`) gains `'rust'`.","newText":"`constructEngine` (`src/core/engine-construct.ts`) gains a `rust` case and its unsupported-engine message names all three engines. `BrainEngine.kind` (`src/core/engine.ts:832`) gains `'rust'`, and so does every other `'postgres' | 'pglite'` engine union (the config type in `src/core/config.ts`, `targetEngine` in `src/commands/migrate-engine.ts`, the config shape in `src/core/context/resolve-ipc.ts`). The graduation inventory's `engines` record becomes `{ pglite, postgres, rust }` with no default for `rust`, so a row that does not say how Rust stores it fails to compile."},{"oldText":"- `check:rust-capability-coverage` prints the share of operations, commands, phases and handlers available on Rust. It is the progress number and the first PGLite-deprecation criterion.","newText":"- Every `BrainEngine` member is classified in `src/core/rust-engine/members.ts`, a table typed `satisfies Record<keyof BrainEngine, 'implemented' | Capability>`. A new interface member fails to compile until it is classified, so the list cannot drift by hand. A member not yet implemented throws `engine_capability_missing` naming its capability.\n- `check:rust-capability-coverage` prints the share of operations, commands, phases and handlers available on Rust. It is the progress number and the first PGLite-deprecation criterion. It is derived from the member table and the dispatch table, not kept as a separate list."},{"oldText":"Migration carries stored fingerprints verbatim. Track 2 moves the computation into one TypeScript function proven equal to PGLite's SQL on a fuzz corpus that includes non-ASCII text, and every engine stores the passed value.","newText":"Migration carries stored fingerprints verbatim. PGLite and Postgres keep computing it in SQL, unchanged, because existing Postgres fingerprints depend on that host's `lower()` and whitespace classes. The Rust engine computes `gbrain_fact_fingerprint` and `gbrain_fact_fingerprint_v1` in its own code, fuzzed against PGLite's SQL on a corpus with non-ASCII text, mixed case and every whitespace class. Moving the computation out of SQL for all engines, or a versioned normalization, is a separate change that needs the maintainer's yes."},{"oldText":"790 of the 831 files that call `testBackends()`","newText":"790 of the 830 files that call `testBackends()` (re-measured at 9f1d54232d)"},{"oldText":"Exit: the CI lane is green; a trivial addon loads in Bun 1.4.4 and in a `bun build --compile` executable through `process.dlopen`; async tasks, typed arrays and panic-to-error work in Bun;","newText":"Exit: the CI lane is green; a trivial addon loads in Bun 1.4.4 and in a `bun build --compile` executable through `process.dlopen`; async tasks, typed arrays and panic-to-error work in Bun; shutdown with pending tasks, cancellation after start, process exit with pending native work and a full or closing threadsafe-function queue behave as the lifecycle rules above require;"},{"oldText":"Work: PRs 10 to 14 implement","newText":"Work: PRs 10 to 14b implement"},{"oldText":"Exit: the domain tests, `test/e2e/engine-parity.test.ts` cases for those domains and the trigger parity matrix pass on the Rust arm.","newText":"Exit: the domain tests, `test/e2e/engine-parity.test.ts` cases for those domains and the trigger parity matrix pass on the Rust arm; a small PGLite to Rust to PGLite roundtrip through the graduation adapter verifies exactly on the domains implemented so far, including consumed but unused sequence values, generated columns, withdrawals and database-only content."},{"oldText":"`.github/workflows/rust-engine.yml` (path-filtered to `rust/**` and `src/core/rust-engine*`;","newText":"`.github/workflows/rust-engine.yml` (path-filtered to `rust/**`, `src/core/rust-engine*`, `src/core/engine.ts`, `src/core/engine-*.ts`, `src/core/engine-sql/**`, `src/schema.sql`, `src/core/migrate.ts`, `src/core/schema-migrations/**`, `src/core/persistence/graduation-*.ts`, `test/helpers/test-backends.ts`, `test/rust-unit-arms.txt`, `scripts/rust-unit-arms.ts` and the workflow itself;"},{"oldText":"| 8 | Rust engine shell, refusing everything with typed errors | `src/core/rust-engine.ts`, `src/core/rust-engine/`, `engine-construct.ts`, `kind` union, config value,","newText":"| 8 | Rust engine shell, refusing everything with typed errors | `src/core/rust-engine.ts`, `src/core/rust-engine/` (including `members.ts`), `engine-construct.ts`, `kind` union and every other two-engine union, inventory `engines.rust` type, config value, `docs/ENGINES.md` \"Adding a new engine\" note that a non-SQL engine implements typed methods instead of a `SqlExecutor`,"},{"oldText":"| 9 | Rust test arm | `test/helpers/test-backends.ts` (`GBRAIN_TEST_BACKEND=rust` selects the arm for files in `test/rust-unit-arms.txt`; never implicit), `rust-engine.yml` job | test harness, `.github/` | none |","newText":"| 9 | Rust test arm | `test/helpers/test-backends.ts` (`GBRAIN_TEST_BACKEND=rust` selects the arm for files in `test/rust-unit-arms.txt`; never implicit), `scripts/rust-unit-arms.ts`, an exhaustive engine-for-backend test helper and the Rust-kind assertion, `rust-engine.yml` job, `.github/workflows/full-ci.yml` dispatching `rust-engine.yml` only when the same path filter matches (estimate: about 10 minutes per OS for a cold addon build and 3 minutes with the cache, on two OSes in parallel; PR 1 reports the measured time), a trigger-selection check | test harness, `.github/` | none |"},{"oldText":"| 14 | Segmented page bodies, salience, health, titles | `gbrain-domain` | none | none |","newText":"| 14 | Segmented page bodies, salience, health, titles | `gbrain-domain` | none | none |\n| 14b | Engine-neutral graduation adapter and an early PGLite to Rust to PGLite roundtrip on the domains so far | `src/core/persistence/graduation-*.ts` (catalog inspection, canonical rows, counters, fencing and verification through the adapter), `src/core/rust-engine/` | `persistence/` | none |"},{"oldText":"| 19 | Store format version, index lag and rebuild checks | `gbrain-store`, doctor checks | doctor goldens | D2 |","newText":"| 19 | Store format version, schema migration dispatch for Rust stores, index lag and rebuild checks | `gbrain-store`, `src/core/migrate.ts` and `src/core/schema-migrations/types.ts` (Rust disposition per migration), doctor checks | doctor goldens, `migrate.ts` | D2, D7 |"},{"oldText":"| 21 | `gbrain migrate --to rust` and back | graduation copier target side, inventory `engines.rust`, `src/commands/migrate-engine.ts` | none | D1 |","newText":"| 21 | `gbrain migrate --to rust` and back, PGLite brains only | the graduation adapter from PR 14b on both directions, inventory `engines.rust` rows, `src/commands/migrate-engine.ts` | none | D1 |"},{"oldText":"| 21b | `gbrain backup create` and `backup restore` for Rust brains, with a full-store restore drill | `src/core/backup/`, `src/commands/backup.ts` | none | D1 |","newText":"| 21b | `gbrain backup create` and `backup restore` for Rust brains, with a full-store restore drill | `src/core/backup/` (a Rust snapshot taken under the owner lock at one committed generation, with derived indexes carried with their generation or rebuilt; the PGLite snapshot path unchanged), `src/commands/backup.ts` | none | D1 |"},{"oldText":"- A Rust cell joins `scale-tier.yml`. Benchmarks report; CI gates on relative regressions.","newText":"- Each target has a named step in `rust/bench/` that prints machine, engine, data size, N, p50 and p99, with PGLite measured on the same machine in the same run. Write throughput is measured through `transaction(fn)` with the writer held across awaits and includes the outbox apply before return. Peak resident memory at 200k and 1M chunks is reported against the memory envelope in `bakeoff.md` (f32 vectors at 1M chunks and 1,024 dimensions are about 3.8 GiB raw before any graph).\n- A Rust cell joins `scale-tier.yml`. Benchmarks report; CI gates on relative regressions."},{"oldText":"- Crash: SIGKILL between record commit and index apply, during import, during migration copy and during index rebuild; the open recovers, index lag returns to zero, and a deleted or withdrawn item is never returned.","newText":"- Crash: SIGKILL between record commit and index apply, during import, during migration copy and during index rebuild; the open recovers, index lag returns to zero, and a deleted or withdrawn item is never returned.\n- Failure after commit without a crash: inject a failure after the record commit, after the text apply and before the vector apply while the owner stays alive; the receipt says committed, later reads are correct, replay brings the lag to zero, and a retried write is idempotent.\n- Snapshot isolation: pause a search across a concurrent content and permission update; the paused reader returns correct results for its snapshot and never newer restricted content.\n- Writer admission: start far more concurrent writers than worker threads while the first transaction awaits and then makes another engine call; all finish or time out within the bound, a cancelled waiter leaves nothing behind, re-entry gives `transaction_reentry`, and `disconnect()` finishes cleanly.\n- Fingerprints: create withdrawals and purges before a change, then insert equivalent non-ASCII and mixed-case claims on Rust after migration; they stay suppressed."},{"oldText":"- `testBackends()` (`test/helpers/test-backends.ts:15`) gains a `rust` backend selected only by `GBRAIN_TEST_BACKEND=rust` and only for files listed in `test/rust-unit-arms.txt`. Default developer runs are unchanged and need no Rust toolchain. Selecting `rust` without a loadable addon fails loudly, as `requirePostgresTestDatabase` does for Postgres.","newText":"- `testBackends()` (`test/helpers/test-backends.ts:15`) gains a `rust` backend selected only by `GBRAIN_TEST_BACKEND=rust` and only for files listed in `test/rust-unit-arms.txt`. Default developer runs are unchanged and need no Rust toolchain. Selecting `rust` without a loadable addon fails loudly, as `requirePostgresTestDatabase` does for Postgres.\n- Most test files choose their engine with a two-way branch such as `backend === 'postgres' ? requirePostgresTestDatabase() : undefined`, which would build a PGLite brain under a `[rust]` label and pass. So the arm is selected by a runner, `scripts/rust-unit-arms.ts`, modeled on `scripts/postgres-unit-arms.ts`, which runs only the listed files with `GBRAIN_TEST_BACKEND=rust`; an exhaustive engine-for-backend helper replaces the two-way branch in a file before it is listed; and every engine opened under the Rust arm must report `kind === 'rust'`, or the file fails. A check refuses a listed file that still has a two-way backend branch."},{"oldText":"- The source side reads through the existing engine, so PGLite and Postgres brains can both move. The target side writes through the Rust `importRelation` batch API in primary-key keyset order. Derived indexes build after the copy; embeddings are carried, never re-embedded.","newText":"- The graduation helpers issue SQL on both sides today (catalog columns in `graduation-digest.ts`, sequence positions in `graduation-copy.ts`, metadata, counts and sequences in `graduation-verify.ts`). An engine-neutral graduation adapter keeps the custody state machine and replaces those assumptions: catalog inspection, canonical row export, counter and sequence transfer (never below a consumed value), fencing, import and verification, implemented for PGLite and Rust (PR 14b).\n- The preview moves PGLite brains to Rust and back. The target side writes through the Rust `importRelation` batch API in primary-key keyset order. Derived indexes build after the copy; embeddings are carried, never re-embedded. Postgres to Rust is deferred until multi-host source fencing and per-host fingerprint equivalence are designed."},{"oldText":"- The inventory gains an `engines.rust` column. A migration that adds a relation already fails `test/graduation-inventory.test.ts` until it has a row; after the preview it must also say how Rust stores it (decision D7).","newText":"- The inventory gains an `engines.rust` column. A migration that adds a relation already fails `test/graduation-inventory.test.ts` until it has a row; after the preview it must also say how Rust stores it (decision D7).\n- Schema migrations on Rust stores. Each `Migration` (`src/core/schema-migrations/types.ts`) gains a Rust disposition: `catalog_only` (an additive change the catalog absorbs), `postgres_only` (an explicit no-op with its reason), or a Rust handler with its own verify through typed methods or the relation API. The runner in `src/core/migrate.ts` dispatches on it, since the SQL path and SQL-issuing handlers cannot run on Rust. Per migration, the catalog change, the data handler and the version ledger row commit in one store transaction; `FORMAT` is then rewritten by atomic rename, and an open that finds `FORMAT` behind the records repairs it from the records. A check fails a migration above the Rust baseline that has no disposition. Before PR 19, a catalog mismatch is refused by the loader and development stores are rebuilt."},{"oldText":"- **D7. Schema change policy after the preview.** A migration that adds or changes a relation also adds its Rust catalog and inventory entries in the same PR;","newText":"- **D7. Schema change policy after the preview.** A migration that adds or changes a relation also adds its Rust catalog and inventory entries and its Rust disposition (`catalog_only`, `postgres_only` or a Rust handler with verify) in the same PR;"},{"oldText":"- A `gbrain engine remove rust` command: removing an addon by hand is enough for the preview.","newText":"- A `gbrain engine remove rust` command: removing an addon by hand is enough for the preview.\n- `gbrain migrate --to rust` from a Postgres brain: it needs multi-host source fencing and per-host fingerprint equivalence; the preview cohort is PGLite users.\n- Moving fact fingerprint computation out of SQL for all engines, or a versioned normalization: it can change Postgres behavior, so it needs its own change and the maintainer's yes."},{"oldText":"and `newer_format`, `unreadable` and `upgrade_failed` (`engine_store_format_unsupported`).","newText":"and `newer_format`, `unreadable` and `upgrade_failed` (`engine_store_format_unsupported`). Eng review added the reason `transaction_reentry` on the existing `internal_error` code (PR 8)."}]} -->
+
+<!-- autoplan-accepted:eng -->
+- Writer admission and re-entry: a caller waits for the single-writer permit asynchronously before it uses a worker thread; an open write transaction runs its commands on its own transaction executor; the wait is bounded by `AbortSignal` or deadline and ends with the existing `cancelled` or `timeout` code with no permit or task left behind; a call on the outer engine inside its own `transaction(fn)` throws `internal_error` reason `transaction_reentry` (added to D2); `lockPageKeys` is a per-key async mutex held until the transaction ends. Verify: start far more concurrent writers than worker threads while the first transaction awaits and then makes another engine call; all finish or time out within the bound, cancelled waiters leave nothing behind, re-entry gives `transaction_reentry`, and `disconnect()` finishes cleanly.
+- Lifecycle: `disconnect()` and the resident-consumer stop barrier stop admission, cancel queued tasks, wait a bounded time for running tasks and then close the store; a task cancelled after it started reports what it committed through the receipt. Verify: PR 1's Bun smoke covers shutdown with pending tasks, cancellation after start, process exit with pending native work, and a full or closing threadsafe-function queue, in Bun 1.4.4 and in a compiled executable.
+- Snapshot contract: every search pins one record snapshot generation; text postings and vector entries carry the generation range in which they are valid and the search uses only entries valid at its generation; superseded entries are reclaimed after the oldest reader passes them; each candidate's indexed revision and its deleted, withdrawn and visibility state are checked against the record snapshot, and a mismatch drops it and uses the exact path for that arm, keeping the `vector_candidates_incomplete` reason. Verify: pause a search across a concurrent content and permission update; the paused reader returns correct results for its snapshot and never newer restricted content.
+- Failure after commit: if the outbox apply fails while the process stays alive, the call reports the write as committed through its receipt, never as rolled back; the relation is marked behind; searches that touch it use the exact path until replay succeeds; replay runs in generation order and is idempotent; `gbrain engine status` and doctor report the lag. Verify: inject failures after the record commit, after the text apply and before the vector apply with the owner alive; check the receipt, later reads, replay to zero lag and an idempotent retry.
+- Graduation adapter (PR 14b): an engine-neutral adapter under the custody state machine provides catalog inspection, canonical row export, counter and sequence transfer never below a consumed value, fencing, import and verification for PGLite and Rust; `migrate --to rust` and back cover PGLite brains only; Postgres to Rust is deferred. Verify: a PGLite to Rust to PGLite roundtrip at the Phase 5 exit verifies exactly on the domains so far, including consumed but unused sequence values, generated columns, withdrawals and database-only content.
+- Schema migrations on Rust stores (PR 19, D7): each `Migration` carries a Rust disposition (`catalog_only`, `postgres_only` with a reason, or a Rust handler with its own verify); `src/core/migrate.ts` dispatches on it; per migration the catalog change, data handler and version ledger row commit in one store transaction, `FORMAT` is then rewritten by atomic rename and repaired from the records when behind; a check fails a migration above the Rust baseline with no disposition; before PR 19 the loader refuses a catalog mismatch. Verify: upgrade a previous-release Rust store containing legacy rows, interrupt each migration boundary, and check resumability, preserved data and truthful version markers.
+- Fingerprints: PGLite and Postgres keep computing `gbrain_fact_fingerprint` and `_v1` in SQL, unchanged; the Rust engine computes both in its own code fuzzed against PGLite's SQL on non-ASCII, mixed-case and whitespace-class input; a shared or versioned change is deferred and needs the maintainer's yes. Verify: create withdrawals and purges, migrate to Rust, insert equivalent non-ASCII and mixed-case claims; they stay suppressed.
+- Test arm: the Rust arm is selected by `scripts/rust-unit-arms.ts`, modeled on `scripts/postgres-unit-arms.ts`, running only files in `test/rust-unit-arms.txt` with `GBRAIN_TEST_BACKEND=rust`; an exhaustive engine-for-backend helper replaces two-way backend branches before a file is listed; every engine opened under the arm must report `kind === 'rust'`. Verify: a listed file that still has a two-way backend branch is refused by the listing check, and a file that opens an engine of another kind under the arm fails.
+- CI coverage: `rust-engine.yml` path filters include the Rust tree, the engine interface and engine-sql files, `src/schema.sql`, `src/core/migrate.ts`, `src/core/schema-migrations/`, the graduation helpers, the test-arm harness and list, and the workflow itself; `full-ci.yml` dispatches `rust-engine.yml` on the final head. Verify: a trigger-selection check shows that a schema-only change and a capability-only change select the Rust lane.
+- Member coverage: `src/core/rust-engine/members.ts` classifies every `BrainEngine` member with `satisfies Record<keyof BrainEngine, 'implemented' | Capability>`; an unimplemented member throws `engine_capability_missing` naming its capability; `check:rust-capability-coverage` derives from this table and the dispatch table. Verify: adding an interface member without a row fails `bun run typecheck`.
+- Engine unions: every `'postgres' | 'pglite'` engine union (kind, config type, `migrate-engine.ts` target, `resolve-ipc.ts` config shape) gains `rust`; the constructor's unsupported-engine message names all three; the inventory `engines` record is `{ pglite, postgres, rust }` with no default for `rust`. Verify: an inventory row without `rust` fails typecheck, and the constructor message test lists three engines.
+- Config-level owner check: `engineIsSingleOwner(cfg.engine)` answers the single-owner question where only config exists (owner socket and secret in `resolve-ipc.ts`, `graduation-serve-guard.ts`), and the kind-branch guard covers both forms. Verify: owner socket and secret paths resolve for a Rust config the same way as for PGLite.
+- Rust backup (PR 21b): the snapshot is taken under the owner lock at one committed generation, with derived indexes carried with their generation or rebuilt on restore; the PGLite snapshot path is unchanged. Verify: the full-store restore drill gives equal relation digests and zero index lag after restore.
+- Performance proof: each target has a named `rust/bench/` step printing machine, engine, data size, N, p50 and p99 beside PGLite on the same machine; write throughput is measured through `transaction(fn)` with the writer held across awaits and the outbox apply included; peak memory at 200k and 1M chunks is reported against the `bakeoff.md` envelope. Verify: the bake-off report shows each step's output for both preview targets.
+- Docs: `docs/ENGINES.md` "Adding a new engine" gains a note that a non-SQL engine implements typed methods instead of a `SqlExecutor` (PR 8). Verify: PR 8 review.
+- Numbers: the test count reads 790 of the 830 files that call `testBackends()`, re-measured at 9f1d54232d, and is re-measured again before the gate.
+- Deferred, in the plan's `## Deferred` section: Postgres to Rust migration, and moving fact fingerprint computation out of SQL for all engines.
+<!-- /autoplan-accepted:eng -->
+
+## Decision Audit Trail
+
+<!-- AUTONOMOUS DECISION LOG -->
+
+| # | Phase | Decision | Class | Principle | Rationale | Rejected |
+|---|---|---|---|---|---|---|
+| 1 | CEO | Keep option A | Mechanical | P6 | Binding user direction; B changes existing engines | Option B first |
+| 2 | CEO | Addon identity, digest manifest, staged upgrade | Mechanical | P1 | Same-ABI drift and offline upgrade were unhandled | ABI-only check |
+| 3 | CEO | PR 21b backup and restore, restore drill | Mechanical | P1 | Backup refuses non-PGLite; rollback needs a readable store | Rely on `migrate --to pglite` |
+| 4 | CEO | Checkpoint C1 gates broad Track 2 | Taste | P3 | Time to value needs a stop point with data | T-PRs after PR 6 |
+| 5 | CEO | D12 preview on two targets | Taste | P3 | Smallest preview that is safe to recover | Broader preview |
+| 6 | CEO | D11 gbrain-evals landing and pin; Phase 6 needs Phase 3 | Mechanical | P1 | E1 depends on gbrain-evals | Leave owner open |
+| 7 | CEO | Idiomatic-SQLite slice in bake-off | Taste | P1 | Missing alternative | KV-only comparison |
+| 8 | CEO | LanceDB in bake-off | Mechanical | P2 | Off-the-shelf filtered ANN | usearch only |
+| 9 | CEO | Correct crash-isolation text | Mechanical | P5 | `catch_unwind` covers panics only | Keep claim |
+| 10 | CEO | Deprecation criteria 11 and 12 | Mechanical | P1 | PGLite-only surfaces exist | Criteria 1 to 10 only |
+| 11 | CEO | Track 2 coordination protocol | Mechanical | P1 | Shared-file churn and size ceiling | No protocol |
+| 12 | CEO | Re-measured numbers | Mechanical | P5 | Figures were from an older commit | Old figures |
+| 13 | CEO | In-tree `gbrain eval` primary, gbrain-evals secondary | Mechanical | P4 | Fewer moving parts for gates | stdio protocol now |
+| 14 | CEO | Do not hand Track 2 to other contributors | Mechanical | P6 | The merge process does not write code | Hand off |
+| 15 | CEO | Skip Phase 2 (Design) | Mechanical | P5 | Heuristic false positive; no UI | Run design review |
+| 16 | DX | Error contract subsection: fix per reason, detail context, registry rows, test per row | Mechanical | P1 | Five CAP6 paths had no actionable fix or context | Generic install fix for every reason |
+| 17 | DX | Panic hook, private diagnostic file and id, rollback and reopen | Mechanical | P1 | Default hook prints to stderr; no trace or outcome | `catch_unwind` alone |
+| 18 | DX | Doctor maintenance path when normal open fails | Mechanical | P1 | Doctor could not reach a broken store | Rely on restore only |
+| 19 | DX | Override skips only the digest pin | Mechanical | P5 | Stale local builds slipped past ABI and format checks (revises CEO text) | Override skips every check |
+| 20 | DX | `migrate --to rust` graduation modes, full plan contents, never prompts | Mechanical | P5 | First run had a lock refusal, possible prompt, no estimate | Implicit modes |
+| 21 | DX | Capability report in the plan and `engine status --json` | Mechanical | P1 | Capability discovery was contributor-only | New MCP operation |
+| 22 | DX | Timed search in the migrate run report | Taste | P1 | Shows the win on the user's own brain | Tell users to run `gbrain diag --json` |
+| 23 | DX | `engine install rust` idempotent, `--json`, failure states, pruning | Mechanical | P1 | Failure states and repeat runs unspecified | Leave to implementation |
+| 24 | DX | `engine install rust --from <file>` | Taste | P3 | Offline machines need a verified path | Manual cache population |
+| 25 | DX | PR 23 tested quickstart, capability list, troubleshooting rows, agent rule, reporting route | Mechanical | P1 | Docs listed destinations only | Write docs at the end without content rules |
+| 26 | DX | `rust/README.md` and `bun run rust:build` in PR 1 | Mechanical | P1 | No contributor build-to-test path | Cargo instructions only |
+| 27 | DX | TTHW target 5 min, measured by a drill | Taste | P3 | Competitive tier fits a copy plus index build | Under 2 min, or no number |
+| 28 | DX | Rust layout in the physical-copy runbook and a drill above 8 GiB | Mechanical | P1 | Backup cap is real (`archive.ts:11`) | Raise the cap |
+| 29 | DX | `preview-log.md` for criterion 9 | Mechanical | P5 | Dogfood had no record | Unrecorded dogfood |
+| 30 | DX | Keep the shared `Fix:` placement; defer the move | Taste | P5 | A move changes every command | Rust-only renderer |
+| 31 | DX | Defer issue template and `engine remove rust` | Mechanical | P3 | Touches `.github/`; deleting the directory suffices | Add in PR 23 |
+| 32 | Eng | Keep the original arrangement at the complexity gate | Taste | P6 | Smaller shape is option B, ruled out by the user direction | Accelerator-only arrangement |
+| 33 | Eng | Snapshot contract: generation-ranged index entries, revision backstop, exact fallback | Taste | P1 | Older readers could see newer restricted content | Validate and retry only |
+| 34 | Eng | Failure after commit: committed receipt, relation behind, exact path, idempotent replay | Mechanical | P1 | Live index failure had no contract | Report as a transaction failure |
+| 35 | Eng | Graduation adapter in PR 14b with an early roundtrip; PGLite brains only | Taste | P3 | Helpers issue catalog and sequence SQL | Build inside PR 21 |
+| 36 | Eng | Rust disposition per migration, one store transaction, FORMAT repaired from records | Mechanical | P1 | Catalog versioning had no data path | Catalog version only |
+| 37 | Eng | Fingerprints stay in SQL on PGLite and Postgres; Rust fuzzed against PGLite | Taste | P5 | A shared function could change Postgres | Shared TypeScript function now |
+| 38 | Eng | Async writer admission, transaction executor, `transaction_reentry` under D2 | Mechanical | P1 | Pool starvation and re-entry deadlock | Synchronous lock wait on workers |
+| 39 | Eng | Bun lifecycle cases in PR 1; drain order on disconnect | Mechanical | P1 | napi-rs on Bun is best effort | Prove later |
+| 40 | Eng | Config-level `engineIsSingleOwner` | Mechanical | P1 | Owner paths key on config before an engine exists | Engine capability only |
+| 41 | Eng | Rust backup at one committed generation under the owner lock | Mechanical | P1 | PGLite physical snapshot does not apply | Reuse snapshot.ts |
+| 42 | Eng | Runner-selected Rust arm, engine-for-backend helper, kind assertion, listing check | Mechanical | P1 | Two-way branches build PGLite under a rust label | Env value in testBackends only |
+| 43 | Eng | Widened Rust CI filters, full-ci dispatch, trigger-selection check | Mechanical | P1 | full-ci dispatches test.yml and e2e.yml only | Rust-only filters |
+| 44 | Eng | `members.ts` classifies every BrainEngine member; coverage derived | Mechanical | P5 | Hand-synced list drifts | Separate coverage list |
+| 45 | Eng | All engine unions gain rust; inventory rust key has no default | Mechanical | P5 | Several two-engine unions | Kind union only |
+| 46 | Eng | Named bench step per target; held-writer write bench; memory against envelope | Mechanical | P1 | Targets had no bench step | Targets without steps |
+| 47 | Eng | Non-SQL note in ENGINES.md "Adding a new engine" | Mechanical | P5 | Step 3 assumes a SqlExecutor | Leave the doc |
+| 48 | Eng | Queue gbrain-evals owner, C1 effort cap and corpus spend for the final gate | Mechanical | P6 | User decisions; not invented | Default them silently |
+| 49 | CEO | Shadow mode is the recommended route for existing brains; swap only on READY | User | P6 | The maintainer asked for it | Direct migrate only |
+| 50 | DX | Route-level cutover with override detection and a fresh-process probe | Mechanical | P1 | Env overrides beat config.json | Config-only switch |
+| 51 | CEO | No readiness override in the preview | Taste | P1 | Hard gates must not be waivable | Generic override |
+| 52 | CEO | Per-class successful-evidence counting; rust_error blocks | Mechanical | P1 | Errors escaped the gates | Count attempts |
+| 53 | CEO | Evidence epochs per candidate build and policy | Mechanical | P1 | Old builds polluted the window | One rolling window |
+| 54 | DX | In-memory replay buffer for explain and bench | Mechanical | P5 | Ledger cannot replay | Durable replay store |
+| 55 | DX | Graduation command contract for all shadow and swap mutations | Mechanical | P5 | Consistency | Ad hoc flags |
+| 56 | DX | Recovery table for engine_swap_refused | Mechanical | P1 | Reasons lacked fixes | Reasons only |
+| 57 | CEO | Decision brief at the top of the report; paired bench for speed | Mechanical | P1 | Report was an artifact list | Charts first |
+| 58 | CEO | Early evidence: C1 Postgres replay and a provisional S2 report | Taste | P3 | Value sooner | Wait for S1-S4 |
+| 59 | DX | Docs ship with S4 and S5; agent rules | Mechanical | P5 | Commands shipped before docs | S6 at the end |
+| 60 | Eng | Durable writer observations and a database-enforced swap fence | Taste | P1 | Heartbeats vanish; no fence means split brain | Heartbeat check |
+| 61 | Eng | Shadow in a supervised child process | Taste | P1 | Native faults would kill the primary | In-process shadow |
+| 62 | Eng | Recovery points beside the reverse shadow | Taste | P1 | Reverse shadow copies corruption | Reverse shadow only |
+| 63 | Eng | Transaction-aware wrapper; invalidations after outer commit | Mechanical | P1 | Proxy missed callback writes | Bounded-read Proxy |
+| 64 | Eng | Shared-bound reconcile intervals with deletes and ordering | Mechanical | P1 | Batches shift; upsert misses deletes | Per-side batches |
+| 65 | Eng | Allocator manifests verified separately | Mechanical | P1 | Rows do not carry sequence state | Row digests only |
+| 66 | Eng | stale needs generation evidence, else inconclusive | Mechanical | P1 | Revision strings excuse bugs | Revision compare |
+| 67 | Eng | Per-item authorization check for privacy | Mechanical | P1 | Top-k shifts are not leaks | Set difference |
+| 68 | Eng | Write compare on a preimage-validated copy-on-write snapshot | Mechanical | P1 | Replay after follow conflicts | Rollback on live shadow |
+| 69 | Eng | Two observation seams; captured provider outputs; suppressed side effects | Mechanical | P1 | Context and fusion live above the engine | Engine wrapper only |
+| 70 | Eng | Adapter policies migration, live-shadow, reverse-shadow | Mechanical | P1 | Migration transforms break live copies | One policy |
+
+## DX Review Scorecard
+
+```
++====================================================================+
+| DX PLAN REVIEW: SCORECARD |
++====================================================================+
+| Dimension | Score | Prior | Trend |
+|----------------------|--------|--------|--------|
+| Getting Started | 8/10 | 5/10 | up 3 |
+| API/CLI/SDK | 8/10 | 7/10 | up 1 |
+| Error Messages | 7/10 | 5/10 | up 2 |
+| Documentation | 8/10 | 4/10 | up 4 |
+| Upgrade Path | 8/10 | 7/10 | up 1 |
+| Dev Environment | 8/10 | 5/10 | up 3 |
+| Community | 6/10 | 3/10 | up 3 |
+| DX Measurement | 7/10 | 5/10 | up 2 |
++--------------------------------------------------------------------+
+| TTHW | 5 min target | about 20 min estimate (before) |
+| Competitive Rank | Competitive (target) |
+| Magical Moment | designed, via the migrate run report |
+| Product Type | developer tool: CLI plus in-process engine |
+| Mode | POLISH |
+| Overall DX | 7.5/10 | 5.1/10 | up 2.4 |
++====================================================================+
+| DX PRINCIPLE COVERAGE |
+| Zero Friction | covered (quickstart, one install command) |
+| Learn by Doing | covered (expected output per step) |
+| Fight Uncertainty | covered (plan with time, blockers, capability report) |
+| Opinionated + Escape Hatches | covered (defaults; --from, override, way back) |
+| Code in Context | covered (quickstart on the user's own brain) |
+| Magical Moments | covered (timed search) |
++====================================================================+
+```
+
+Errors stop at 7: the shared renderer's `Fix:` placement is deferred and process-ending native faults get a next-open record, not a trace. Community stops at 6: GitHub issues only, no template yet, a small preview cohort by design.
+
+## GSTACK REVIEW REPORT
+
+| Review | Trigger | Why | Runs | Status | Findings |
+|--------|---------|-----|------|--------|----------|
+| CEO Review | `/plan-ceo-review` (via autoplan) | Scope & strategy | 1 (not persisted) | CLEAR | 15 proposals, 12 accepted, 2 deferred |
+| Outside Review | codex, autoplan CEO, DX and Eng phases | Independent 2nd opinion | 0 | unavailable | codex not installed; no completed external review |
+| Eng Review | `/plan-eng-review` (via autoplan) | Architecture & tests (required) | 1 (not persisted) | CLEAR (PLAN) | 23 issues, 4 critical gaps, all folded into the plan; 3 decisions queued for the final gate |
+| Design Review | `/plan-design-review` | UI/UX gaps | 0 | skipped | no UI scope |
+| DX Review | `/plan-devex-review` (via autoplan) | Developer experience gaps | 1 (not persisted) | CLEAR (POLISH) | score: 5.1/10 → 7.5/10, TTHW: ~20 min → 5 min; 16 decisions, 3 deferred |
+
+- **OUTSIDE COVERAGE:** codex, CEO phase, unavailable (not installed), no completed external review. codex, DX phase, unavailable (not installed), no completed external review. codex, Eng phase, unavailable (not installed), no completed external review. Native in-host voices completed: CEO with 6 findings, DX with 8 findings, Eng with 8 findings (7 accepted, 1 queued as user decisions); native findings do not count as outside coverage.
+- **CYCLE 2 (shadow mode):** focused delta review by two review agents (CEO+DX lens, Eng lens), not a full interactive rerun; 21 findings, all accepted; 6 shadow decisions (S1-S6) added to the gate.
+- **VERDICT:** CEO + DX + ENG CLEARED for planning, cycle 2 included. The maintainer answered the final gate on 2026-11-16 with every recommendation (gate revision 2).
+
+**DECISIONS OPEN AT REVIEW TIME (since resolved):** these three were open when the review ended. The maintainer settled all three at the final gate; the "Approval record" in [`../RUST_ENGINE.md`](../RUST_ENGINE.md) records the outcome, and D11 now names the gbrain-evals maintainer agent as the lander.
+- U1 (D11): who lands and pins the gbrain-evals changes; recommended: the maintainer, unless a delegate is named.
+- U2 (Phase 1 entry): effort budget through Checkpoint C1; recommended: 8 calendar weeks or 25 merged PRs from PR 1, whichever comes first.
+- U3 (D10, open question 3): 1M benchmark corpus and spend; recommended: a permissively licensed public corpus embedded once at 1,024 dimensions, kept outside the repository, spend cap $50.
diff --git a/llms-full.txt b/llms-full.txt
index f6880b2e1c..d3f16c9e0d 100644
--- a/llms-full.txt
+++ b/llms-full.txt
@@ -4586,6 +4586,7 @@ Start with `gbrain doctor`. For database access failures, use `gbrain engine sta
- [MCP task guide](docs/mcp/README.md) — deployment and per-client setup (Claude Desktop, Code, Cursor, ChatGPT, Perplexity, Cowork)
- [MCP administration](docs/mcp/ADMIN.md) — owner dashboard access, client registration, OAuth, permissions, and token recovery
- [Evals](docs/eval/) and [research](docs/research/) — methods and results
+- [Rust engine plan](docs/designs/RUST_ENGINE.md) — proposed design for a third storage engine, not built yet; its [research maps](docs/designs/rust-engine/research/README.md) and [review record](docs/designs/rust-engine/review-record.md)
- [`docs/ethos/`](docs/ethos/) — philosophy (thin harness, fat skills, markdown as recipes, origin story)
- [`AGENTS.md`](AGENTS.md) — entry point for non-Claude agents
- [`CLAUDE.md`](CLAUDE.md) — entry point for Claude Code (deep operating context)