Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

feat(core): openEngine(settings) behind embedded_core (GBRA-283 Wave B1)

garrytanf98c5d2acaa0
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 9b2f7c92fa..7a33c194ab 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -10,6 +10,18 @@ credits are retained; no result has been reassigned to another provider. Origina
identifiers and attribution are available in the pre-removal Git revision
`6040075c6cb95be5881cc2e1b76ef7d71f4e5d29` (retained on 2026-09-23).
+## [Unreleased]
+
+**An embedding host can open a brain from a settings value (experimental, off by default).** `openEngine(settings)` from `gbrain/engine-open` creates and connects an engine from one object: its database, its own pool, its direct URL, its persistence host identity, its local writer and its embedding identity. It reads no config file, environment variable or home directory for any of them, so two brains in one process never share a pool, a host id or a credential, and a stray `GBRAIN_DIRECT_DATABASE_URL` cannot send one brain's DDL somewhere else. It refuses unless the settings say `embedded_core: true`. The CLI, `gbrain serve` and mounts don't use it and behave exactly as before. Contributed by @bradgessler (#8455).
+
+### Itemized changes
+
+- `src/core/engine-open.ts` (new, exported as `./engine-open`): `openEngine`, refusing `embedded_core_required`, `engine_host_missing` and `engine_settings_invalid`. A connect never migrates; the host runs `initSchema()`. Documented in docs/ENGINES.md, "Opening an engine from settings".
+- `src/core/persistence/identity.ts`: `hostIdFor(engine)` and `setEngineHostId`, resolved through `engineKey`. Publication, admission, the consumer, worktree ownership, effects and the writer stamp use it; an unmarked engine still gets `localHostId()`. An embedded engine never reads or mints `host.json`, and its consumer heartbeat records `embedded:<host-id>`, which doctor and writer status read as an identity given at open. `registerLocalWriterValue` registers a writer the host holds as a value, and an embedded engine's writes use it instead of a `<brain>.<lane>.json` file.
+- `initSchema()` on an embedded engine seeds the embedding model and width from `settings.embedding` and refuses `engine_embedding_mismatch` on a database that records another one.
+- The decide spend cache is keyed by engine and held weakly, and a drained feedback queue no longer keeps its engine alive.
+- `test/engine-open.test.ts`, `test/engine-open-lifecycle.test.ts`, `test/e2e/engine-open-postgres.test.ts`.
+
## [0.60.556.0] - 2026-11-02
**Mounted brains stop sharing settings and search telemetry.** In a process that serves several brains, search telemetry for every brain was written into the first brain's database, and a handful of per-brain settings were read once from whichever brain asked first and then applied to all of them. Each of those caches now belongs to its engine, and each engine gets its own telemetry writer, which stops its timer when the engine disconnects and keeps its buffer for a reconnect. A process with one brain behaves exactly as before. Contributed by @bradgessler (#8454).
diff --git a/docs/ENGINES.md b/docs/ENGINES.md
index 85eb444de4..137938833f 100644
--- a/docs/ENGINES.md
+++ b/docs/ENGINES.md
@@ -722,6 +722,58 @@ the same reason and fix on its `connection` check.
`<data-dir>.gbrain-owner.json`, and starts the 10-minute WAL-repair
quarantine (`<data-dir>.lock-reap.json`). The next ordinary open succeeds.
+## Opening an engine from settings (experimental)
+
+`openEngine(settings)` (`src/core/engine-open.ts`, exported as `gbrain/engine-open`) creates and connects an engine
+from one value, for a host that embeds several brains in one process or keeps its settings somewhere other than
+`~/.gbrain`. It is off by default: it refuses unless `settings.embedded_core === true` (`embedded_core_required`).
+The CLI, `gbrain serve` and mounts never call it and behave exactly as before.
+
+```ts
+import { openEngine } from 'gbrain/engine-open';
+
+const engine = await openEngine({
+ embedded_core: true,
+ engine: 'postgres',
+ database: { url, directUrl }, // PGLite: { path }, or none for an in-memory brain
+ pool: { max: 4 }, // this engine's own pool (default 4), never the db.ts singleton
+ host: { id: hostId }, // required UUID: the persistence host identity
+ writer: { id, credential, lane: 'stdio' },
+ embedding: { model: 'voyage:voyage-4', dimensions: 1024 },
+});
+await engine.initSchema(); // a connect is not a migration: the host runs it
+// ...
+await engine.disconnect();
+```
+
+What the settings decide, with nothing read from a config file, an environment variable, the home directory or the
+working directory:
+
+- **Connection.** Postgres always connects on the instance-pool path. The direct (DDL/session) pool uses only
+ `database.directUrl`, or the route a known pooler URL derives; `GBRAIN_DIRECT_DATABASE_URL` is never consulted.
+ The statement-description cache stays in the process instead of `<home>/cache/pg-types`. PGLite skips the
+ `GBRAIN_PGLITE_SNAPSHOT` fast path.
+- **Host identity.** `hostIdFor(engine)` (`src/core/persistence/identity.ts`) answers `host.id` for the engine,
+ its page transactions and its read-through views; the consumer, publication, admission stamps and worktree
+ ownership use it. No `host.json` is read or minted, and an embedded engine without an id refuses
+ `engine_host_missing`. Its consumer heartbeat row records `embedded:<host-id>` in `host_json_path` and
+ `embedded` in `persistence_home`; doctor and writer status read that as "identity given at open", never as a path.
+ For every other engine `hostIdFor` is `localHostId()`.
+- **Writer.** An unauthenticated write uses `settings.writer` for its lane, registered in
+ `persistence_local_writers` on first use (`registerLocalWriterValue`: idempotent; another credential or lane under
+ the same id refuses `permission_denied`; a revoked registration is never replaced). No `<brain>.<lane>.json`
+ credential file is read or minted; without a writer for the lane the write refuses `writer_registration_required`.
+- **Embedding identity.** `initSchema()` seeds a fresh brain from `settings.embedding` (else the built-in default),
+ never from the process gateway, and refuses `engine_embedding_mismatch` on a database that records another model
+ or width; `gbrain migrate embeddings --status` previews a migration.
+- **Carried for later waves.** `storage`, `storagePrefix` and `ai` are held as given and read back with
+ `embeddedSettings(engine)` (the writer credential is left out). `disconnect()` drops them.
+
+Still process-wide: the AI gateway, `GBRAIN_*` tuning variables (pool lifetime, session timeouts), the
+connection-events audit log, and operation-level config reads (content-sanity screening, schema-pack resolution,
+the embedding switch on publication). A source with a git checkout keeps its native coordination lock under the
+process's persistence home.
+
## Canonical schema sources
Schema DDL text has one hand-edited copy. `bun run build:schema`
diff --git a/docs/guides/error-codes.md b/docs/guides/error-codes.md
index 55b53c736c..d316d195cf 100644
--- a/docs/guides/error-codes.md
+++ b/docs/guides/error-codes.md
@@ -1333,6 +1333,16 @@ More: [docs/operations/spend-controls.md#dream-paid-loop-breaker-dreambreakermax
More: [docs/guides/repair.md#embed-backfill-stalled](../../docs/guides/repair.md#embed-backfill-stalled)
+### embedded_core_required
+
+<a id="embedded_core_required"></a>
+
+| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable |
+|---|---|---|---|---|---|---|
+| openEngine (gbrain/engine-open) was called without embedded_core: true, so no engine was opened. | Opening an engine from settings alone is an experimental embedding surface that is off by default; a host opts in explicitly so no existing caller changes behavior. | Pass embedded_core: true in the settings; the CLI, gbrain serve and mounts open brains through their own connect path and need nothing. | agent | `repeat the read that failed` | 1 | no |
+
+More: [docs/ENGINES.md#opening-an-engine-from-settings-experimental](../../docs/ENGINES.md#opening-an-engine-from-settings-experimental)
+
### embedding_auth_failed
<a id="embedding_auth_failed"></a>
@@ -1443,6 +1453,16 @@ More: [docs/guides/troubleshooting.md#embedding-state](../../docs/guides/trouble
|---|---|---|---|---|---|---|
| The embedding model cannot produce the width of the brain's vector column; nothing was changed. | The request itself was wrong or no longer matches the brain; nothing was changed. | Correct the request using the message above, then retry. | agent | `repeat the read that failed` | 1 | no |
+### engine_embedding_mismatch
+
+<a id="engine_embedding_mismatch"></a>
+
+| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable |
+|---|---|---|---|---|---|---|
+| An engine opened from settings names an embedding model or width that differs from the one its database already records, so initSchema changed nothing. | The vector column has one width and the brain one embedding model; seeding another over it would make every stored and future embedding unreadable. Changing it is an explicit re-embed the user decides on. | Pass the database's recorded model and width in settings.embedding, or read the recorded identity with gbrain migrate embeddings --status on the brain host and preview a migration from there. Run: gbrain migrate embeddings --status --json | user | `gbrain doctor --json` | 1 | no |
+
+More: [docs/ENGINES.md#opening-an-engine-from-settings-experimental](../../docs/ENGINES.md#opening-an-engine-from-settings-experimental)
+
### engine_graduated
<a id="engine_graduated"></a>
@@ -1453,6 +1473,26 @@ More: [docs/guides/troubleshooting.md#embedding-state](../../docs/guides/trouble
More: [docs/guides/move-to-postgres.md#graduated-datastore](../../docs/guides/move-to-postgres.md#graduated-datastore)
+### engine_host_missing
+
+<a id="engine_host_missing"></a>
+
+| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable |
+|---|---|---|---|---|---|---|
+| An engine opened from settings has no host identity, so nothing that needs one ran and no host.json was created. | An embedded engine publishes and claims work under the host id its host gave at open; minting a host.json under the home directory instead would tie its writes to whatever process happens to share that directory. | Pass host: { id: <uuid> } to openEngine; keep the same id for the same host across restarts. | agent | `repeat the read that failed` | 1 | no |
+
+More: [docs/ENGINES.md#opening-an-engine-from-settings-experimental](../../docs/ENGINES.md#opening-an-engine-from-settings-experimental)
+
+### engine_settings_invalid
+
+<a id="engine_settings_invalid"></a>
+
+| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable |
+|---|---|---|---|---|---|---|
+| A setting passed to openEngine or registerLocalWriterValue is missing or malformed (engine kind, database url or path, pool size, host or writer id, writer credential or lane, embedding identity), so nothing was opened or registered. | The request itself was wrong or no longer matches the brain; nothing was changed. | Correct the setting the message names and call again. | agent | `repeat the read that failed` | 1 | no |
+
+More: [docs/ENGINES.md#opening-an-engine-from-settings-experimental](../../docs/ENGINES.md#opening-an-engine-from-settings-experimental)
+
### entity_types_unavailable
<a id="entity_types_unavailable"></a>
diff --git a/llms-full.txt b/llms-full.txt
index be60d11d32..058a01bb35 100644
--- a/llms-full.txt
+++ b/llms-full.txt
@@ -6138,6 +6138,58 @@ the same reason and fix on its `connection` check.
`<data-dir>.gbrain-owner.json`, and starts the 10-minute WAL-repair
quarantine (`<data-dir>.lock-reap.json`). The next ordinary open succeeds.
+## Opening an engine from settings (experimental)
+
+`openEngine(settings)` (`src/core/engine-open.ts`, exported as `gbrain/engine-open`) creates and connects an engine
+from one value, for a host that embeds several brains in one process or keeps its settings somewhere other than
+`~/.gbrain`. It is off by default: it refuses unless `settings.embedded_core === true` (`embedded_core_required`).
+The CLI, `gbrain serve` and mounts never call it and behave exactly as before.
+
+```ts
+import { openEngine } from 'gbrain/engine-open';
+
+const engine = await openEngine({
+ embedded_core: true,
+ engine: 'postgres',
+ database: { url, directUrl }, // PGLite: { path }, or none for an in-memory brain
+ pool: { max: 4 }, // this engine's own pool (default 4), never the db.ts singleton
+ host: { id: hostId }, // required UUID: the persistence host identity
+ writer: { id, credential, lane: 'stdio' },
+ embedding: { model: 'voyage:voyage-4', dimensions: 1024 },
+});
+await engine.initSchema(); // a connect is not a migration: the host runs it
+// ...
+await engine.disconnect();
+```
+
+What the settings decide, with nothing read from a config file, an environment variable, the home directory or the
+working directory:
+
+- **Connection.** Postgres always connects on the instance-pool path. The direct (DDL/session) pool uses only
+ `database.directUrl`, or the route a known pooler URL derives; `GBRAIN_DIRECT_DATABASE_URL` is never consulted.
+ The statement-description cache stays in the process instead of `<home>/cache/pg-types`. PGLite skips the
+ `GBRAIN_PGLITE_SNAPSHOT` fast path.
+- **Host identity.** `hostIdFor(engine)` (`src/core/persistence/identity.ts`) answers `host.id` for the engine,
+ its page transactions and its read-through views; the consumer, publication, admission stamps and worktree
+ ownership use it. No `host.json` is read or minted, and an embedded engine without an id refuses
+ `engine_host_missing`. Its consumer heartbeat row records `embedded:<host-id>` in `host_json_path` and
+ `embedded` in `persistence_home`; doctor and writer status read that as "identity given at open", never as a path.
+ For every other engine `hostIdFor` is `localHostId()`.
+- **Writer.** An unauthenticated write uses `settings.writer` for its lane, registered in
+ `persistence_local_writers` on first use (`registerLocalWriterValue`: idempotent; another credential or lane under
+ the same id refuses `permission_denied`; a revoked registration is never replaced). No `<brain>.<lane>.json`
+ credential file is read or minted; without a writer for the lane the write refuses `writer_registration_required`.
+- **Embedding identity.** `initSchema()` seeds a fresh brain from `settings.embedding` (else the built-in default),
+ never from the process gateway, and refuses `engine_embedding_mismatch` on a database that records another model
+ or width; `gbrain migrate embeddings --status` previews a migration.
+- **Carried for later waves.** `storage`, `storagePrefix` and `ai` are held as given and read back with
+ `embeddedSettings(engine)` (the writer credential is left out). `disconnect()` drops them.
+
+Still process-wide: the AI gateway, `GBRAIN_*` tuning variables (pool lifetime, session timeouts), the
+connection-events audit log, and operation-level config reads (content-sanity screening, schema-pack resolution,
+the embedding switch on publication). A source with a git checkout keeps its native coordination lock under the
+process's persistence home.
+
## Canonical schema sources
Schema DDL text has one hand-edited copy. `bun run build:schema`
diff --git a/package.json b/package.json
index d00fc1ba50..a8309c2ecb 100644
--- a/package.json
+++ b/package.json
@@ -20,6 +20,7 @@
"./operations": "./src/core/operations.ts",
"./minions": "./src/core/minions/index.ts",
"./engine-factory": "./src/core/engine-factory.ts",
+ "./engine-open": "./src/core/engine-open.ts",
"./pglite-engine": "./src/core/pglite-engine.ts",
"./link-extraction": "./src/core/link-extraction.ts",
"./import-file": "./src/core/import-file.ts",
diff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsv
index eca661562c..08eedaf929 100644
--- a/scripts/module-size-limits.tsv
+++ b/scripts/module-size-limits.tsv
@@ -20,8 +20,8 @@ src/core/engine.ts 2866 ratchet grown v0.46.26.0 megawave: relational/visibility
src/core/import-file.ts 2079 ratchet +2 #7880: importFromContent's holdNoncanonicalPrivate option (interface field; the hold is screenImportContent's); +2 #7848: importFromFile holds a non-canonical private request (predicate and hold in persistence/visibility-request.ts); +2 W1 belief ledger: the legacy import is an unmanaged projection point (logic in belief/projection-point.ts); +2: pre-publication withdrawal validation; grown v0.46.26.0 megawave: OCR budget + image import + embed-retry rewire (#3973 #3374); grown wave-g (#4530): per-model chunk-token cap wiring; +24 #4548: row-level visibility-aware fence merge on remote write-back (replaces the #2044 whole-block swap + #4553/#4555 warn-only paths); +7 #4546: merge extended to the timeline-embedded fence; +5 #4107: maybeOcr gates on the OCR model's provider; +3 #3893; +7: #4702 disabled_patterns pass-through to the sanity gate; composition true-up (fix-wave multi-train); +8 #4903: importCodeFile writes source_path so the full-sync reconcile can see code pages; -11: wave review — local fence append replaced by facts-fence.replaceOrInsertFactsFence (#4756 rule); security: durable queued authority and confined filesystem dispatch; master integration: grown v0.46.26.0 megawave: OCR budget + image import + embed-retry rewire (#3973 #3374); grown wave-g (#4530): per-model chunk-token cap wiring; +24 #4548: row-level visibility-aware fence merge on remote write-back (replaces the #2044 whole-block swap + #4553/#4555 warn-only paths); +7 #4546: merge extended to the timeline-embedded fence; +5 #4107: maybeOcr gates on the OCR model's provider; +3 #3893; +7: #4702 disabled_patterns pass-through to the sanity gate; composition true-up (fix-wave multi-train); +8 #4903: importCodeFile writes source_path so the full-sync reconcile can see code pages; -11: wave review — local fence append replaced by facts-fence.replaceOrInsertFactsFence (#4756 rule); harness support: boundary wiring to shared grants, isolated setup, withdrawal and delegated guards; merged v0.49: withdrawal preservation after data-only frontmatter parsing; #5105: small legacy writer/refusal and shared revision CAS delegates; #5105: +8 prepared contextual retrieval policy and retry boundary wiring; upstream integration: preserve independently reviewed master additions with branch facade extraction; #5252 wave: shared provider-free Markdown and code preparation; merged company ingestion/schema routing changes; master retrieval/projection integration with company ingestion; shared content: prepare managed image imports without bypassing canonical publication; +29 write-path wave: identity move/collision wiring (logic in import-identity.ts), deferred embedding on provider failure, image index completeness, file-time date anchor; +22 fw3 A13: markdown re-import reuses unchanged chunk vectors under the seal/wrapper/signature/protected-fence gate; +2 fw3 A12: importFromFile firstCommitAt option; +3 fw3 A14: managed imports keep add-only tags; +4 #5675: record the file origin move inference binds to (logic in import-identity.ts); fw3 integration: A12/A13/A14 (+27) and #5675 (+4) compose; +17 wave-2 W4: safe-chunk re-seal of unchanged legacy markdown/code pages (#5050 #5247) and embedding-input provenance on inline imports (#5553); -1 fix wave 2 (v0.60.5.0) integration: W4 delta re-summed over the merged master line count; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +16 at the merge; +11 #4616: markdown and code imports keep the usable vectors of a partially refused batch and leave refused chunks for embed --stale; lowered to 2230: #5621 contextual-mode resolution peeled to core/import-contextual-mode.ts (shared with gbrain repair contextual-mode); +2 wave 8 lane D1 #5158: key-order fallback equality call (comparison lives in page-state/import-guard.ts); +1 F1c: direct imports run in maintenanceTransaction (write attribution; helper in persistence/attribution.ts); lowered to 2178: #5988 content screen and content-sanity config peeled to core/import-screen.ts; +1 #6007: the prepared apply returns its page id and seal (PreparedImportApplied); +1 #5333: trusted imports drop a stale oversized embed_skip/content_flag the gate no longer sets, and an embed_skip transition defeats both unchanged fast paths; wave 10 collector: lane E (#5333) and the other lanes compose at 2183; grown #6188 (+17): fence options interface, result fields and the Tier 1 step call (logic in fence-repair/import-step.ts); +2 #5984 single-write fast path: the coordinated existingSnapshot option (interface field) composes with the lane apply diet at 2202; +1 GBRA-69: a coordinated apply defers its chunker seal to the caller (sealImportedPage in page-state/projections.ts); lowered to 2023: #5001 the edge-mapping loop moved to code-chunks.ts mapCodeEdges (shared with the prepared apply); W14 P3.13 (#5001) lowered 2049→2023 by moving the edge loop to mapCodeEdges; +2 W13 PR1 on top (2025 measured); +2 #6529: the unchanged-image skip path records source_path (refreshSourcePath, as #4588 does for Markdown); +4 large pages A6/T33: code files keep CODE_FILE_MAX_BYTES, a page over PAGE_INLINE_MAX_BYTES commits with NULL vectors for the metered stale sweep; +1 #6722: an embed_skip page is chunked and never embedded (noEmbed folds the marker); merge v0.60.240.0: large pages and master growth compose at 2032; +24 Wave B lane 1d: the segmented storage step (stage before publication, flip in the apply, seal and post-commit projection; logic in persistence/segmented-apply.ts and page-body/ingest.ts) and the streamed-import dispatch over the single-string ceiling (logic in page-body/streamed-import.ts); merge v0.60.248.0: Wave B PR 1 and master growth compose at 2056; +4 Wave B review: a rename re-preparation reuses the staged segmented body (reuseSegments option) and the remote fence merge reads an unread body as fence-free (fenceBody in page-body/page-shape.ts); +2 Wave B gem A: a coordinated demotion versions the segmented page before demoting it (createVersion order); lanes compose at 2062; +2 Wave B lane 2q: ImportResult.searchable (interface field; the value comes from SegmentedImport.afterCommit);+2: pre-publication withdrawal validation; +9 #7172: kept chunk rows move to their new index and a bounded managed publication defers its chunk replacement (logic in page-state/chunk-moves.ts and page-state/projections.ts continueDeferredProjection); merge v0.60.332.0: #7172 and master growth compose at 2075
src/core/migrate.ts 602 ratchet schema-migration runner only; migrations live in src/core/schema-migrations/ (W3); +3 #5216: resumable page revision backfill runs after every migration pass while pages.knowledge_revision is nullable
src/core/operations.ts 246 ratchet +1 #7168: graphRankOperations import (ops/graph-rank.ts; spread shares the orphans line); peel target: containment sprint C4-C7; grown v0.46.26.0 megawave op wiring; +chat-connectors wiring (master merge); +5 v0.47 gmail-loops: loopsOperations spread + OP_AREAS; #5105: receipt operation registry wiring; shared-skills integration on company-ingestion base; +2 security wave: withOutputRedaction applied at op registration; +1 #5616: pageEditOperations import (spread shares the pages line); +1 Foundations 1 F1b: attributionOperations import (spread shares the admin line); +1 agent operator wave A6: ops/notices.ts import (mute_notice); +2 agent operator closeout A1: registerOpRoutes import + call (routing logic in fix-routing.ts); +2 retrieval feedback: feedbackOperations import and spread (ops/feedback.ts); +1 #6007: pageBatchOperations import (spread shares the pages line); +1 P5: wanted_pages area row; lowered GBRA-75 W11 cold start: OP_AREAS + finalize step moved to operation-load.ts (shared with the CLI per-op loader); +1 C4 pinned questions: questionsOperations import and spread (ops/questions.ts; its areas live in operation-load.ts OP_AREAS); +1 Wave B append: pageAppendOperations import (spread shares the pages line); +1 Wave B upload sessions: pageUploadOperations import (spread shares the pages line); +1 #7191: search-exact import; +1 GBRA-156: whois import (ops/whois.ts; spread shares the chunks line); +1 GST-359 D: qmMemoryOperations import (ops/qm-memory.ts; spread shares the memory line)
-src/core/pglite-engine.ts 3099 ratchet +5 agent operator gate fixes: repair-failed marker gate before the lock and the marker record after a failed auto-repair (logic in pglite-repair.ts, refusal in pglite-repair-consent.ts); +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); E1 bootstrap moved to engine-sql/bootstrap.ts; ceiling rationale: docs/architecture/key-files/engines-1.md entry for src/core/pglite-engine.ts; evidence delivery: getChunkWindows delegate + type import (+3; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +12 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3213 #5824: searchVector SQL moved to search/vector-statement.ts (-166); lowered to 3117 #5889: searchTitles SQL moved to engine-sql/titles.ts (-108); lowered to 2915 F4a: getHealth SQL moved to engine-sql/health.ts (-202); +6 F4b: planner-sensitive reads call beforePlannerRead/plannerRead (logic in planner-stats.ts); +52 engine graduation (GBRA-50 G2a): marker/tombstone checks before and after the kernel lock (logic in persistence/graduation-custody.ts), lock-retaining close and held-lock open (engine lifecycle methods cannot move); 4 Foundations 2 Lane F: autocommit write statements take the WAL checkpoint guard (classifier writesWal in pglite-engine/checkpoint-guard.ts); +5 agent operator gate fixes: repair-failed marker gate before the lock and the marker record after a failed auto-repair (logic in pglite-repair.ts, refusal in pglite-repair-consent.ts); +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); E1 bootstrap moved to engine-sql/bootstrap.ts; ceiling rationale: docs/architecture/key-files/engines-1.md entry for src/core/pglite-engine.ts; evidence delivery: getChunkWindows delegate + type import (+3; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +12 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3213 #5824: searchVector SQL moved to search/vector-statement.ts (-166); lowered to 3117 #5889: searchTitles SQL moved to engine-sql/titles.ts (-108); lowered to 2915 F4a: getHealth SQL moved to engine-sql/health.ts (-202); +6 F4b: planner-sensitive reads call beforePlannerRead/plannerRead (logic in planner-stats.ts); +5 agent operator gate fixes: repair-failed marker gate before the lock and the marker record after a failed auto-repair (logic in pglite-repair.ts, refusal in pglite-repair-consent.ts); +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); E1 bootstrap moved to engine-sql/bootstrap.ts; ceiling rationale: docs/architecture/key-files/engines-1.md entry for src/core/pglite-engine.ts; evidence delivery: getChunkWindows delegate + type import (+3; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +12 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3213 #5824: searchVector SQL moved to search/vector-statement.ts (-166); lowered to 3117 #5889: searchTitles SQL moved to engine-sql/titles.ts (-108); lowered to 2915 F4a: getHealth SQL moved to engine-sql/health.ts (-202); +6 F4b: planner-sensitive reads call beforePlannerRead/plannerRead (logic in planner-stats.ts); +52 engine graduation (GBRA-50 G2a): marker/tombstone checks before and after the kernel lock (logic in persistence/graduation-custody.ts), lock-retaining close and held-lock open (engine lifecycle methods cannot move); 4 Foundations 2 Lane F: autocommit write statements take the WAL checkpoint guard (classifier writesWal in pglite-engine/checkpoint-guard.ts); +5 agent operator gate fixes: repair-failed marker gate before the lock and the marker record after a failed auto-repair (logic in pglite-repair.ts, refusal in pglite-repair-consent.ts); +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); E1 bootstrap moved to engine-sql/bootstrap.ts; ceiling rationale: docs/architecture/key-files/engines-1.md entry for src/core/pglite-engine.ts; evidence delivery: getChunkWindows delegate + type import (+3; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +12 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3213 #5824: searchVector SQL moved to search/vector-statement.ts (-166); lowered to 3117 #5889: searchTitles SQL moved to engine-sql/titles.ts (-108); lowered to 2915 F4a: getHealth SQL moved to engine-sql/health.ts (-202); +6 F4b: planner-sensitive reads call beforePlannerRead/plannerRead (logic in planner-stats.ts); +5 agent operator gate fixes: repair-failed marker gate before the lock and the marker record after a failed auto-repair (logic in pglite-repair.ts, refusal in pglite-repair-consent.ts); +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); E1 bootstrap moved to engine-sql/bootstrap.ts; ceiling rationale: docs/architecture/key-files/engines-1.md entry for src/core/pglite-engine.ts; evidence delivery: getChunkWindows delegate + type import (+3; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +12 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3213 #5824: searchVector SQL moved to search/vector-statement.ts (-166); lowered to 3117 #5889: searchTitles SQL moved to engine-sql/titles.ts (-108); lowered to 2915 F4a: getHealth SQL moved to engine-sql/health.ts (-202); +6 F4b: planner-sensitive reads call beforePlannerRead/plannerRead (logic in planner-stats.ts); +52 engine graduation (GBRA-50 G2a): marker/tombstone checks before and after the kernel lock (logic in persistence/graduation-custody.ts), lock-retaining close and held-lock open (engine lifecycle methods cannot move); +1 #5984: upsertChunks guards pass the per-transaction config memo (transactionMemo in page-state/transactions.ts); v0.60.58.0 merge: #5984 diet growth re-summed over v0.60.57.0 (2983 measured); 4 Foundations 2 Lane F: autocommit write statements take the WAL checkpoint guard (classifier writesWal in pglite-engine/checkpoint-guard.ts); +5 agent operator gate fixes: repair-failed marker gate before the lock and the marker record after a failed auto-repair (logic in pglite-repair.ts, refusal in pglite-repair-consent.ts); +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); E1 bootstrap moved to engine-sql/bootstrap.ts; ceiling rationale: docs/architecture/key-files/engines-1.md entry for src/core/pglite-engine.ts; evidence delivery: getChunkWindows delegate + type import (+3; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +12 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3213 #5824: searchVector SQL moved to search/vector-statement.ts (-166); lowered to 3117 #5889: searchTitles SQL moved to engine-sql/titles.ts (-108); lowered to 2915 F4a: getHealth SQL moved to engine-sql/health.ts (-202); +6 F4b: planner-sensitive reads call beforePlannerRead/plannerRead (logic in planner-stats.ts); +5 agent operator gate fixes: repair-failed marker gate before the lock and the marker record after a failed auto-repair (logic in pglite-repair.ts, refusal in pglite-repair-consent.ts); +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); E1 bootstrap moved to engine-sql/bootstrap.ts; ceiling rationale: docs/architecture/key-files/engines-1.md entry for src/core/pglite-engine.ts; evidence delivery: getChunkWindows delegate + type import (+3; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +12 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3213 #5824: searchVector SQL moved to search/vector-statement.ts (-166); lowered to 3117 #5889: searchTitles SQL moved to engine-sql/titles.ts (-108); lowered to 2915 F4a: getHealth SQL moved to engine-sql/health.ts (-202); +6 F4b: planner-sensitive reads call beforePlannerRead/plannerRead (logic in planner-stats.ts); +52 engine graduation (GBRA-50 G2a): marker/tombstone checks before and after the kernel lock (logic in persistence/graduation-custody.ts), lock-retaining close and held-lock open (engine lifecycle methods cannot move); +1 #5984: upsertChunks guards pass the per-transaction config memo (transactionMemo in page-state/transactions.ts); v0.60.58.0 merge: #5984 diet growth re-summed over v0.60.57.0 (2983 measured); +4 P7 relationalChainHop delegate; +8 contributor audit wave P0: listFactsKeyset delegate (SQL in engine-sql/facts.ts); +1 #5375: get_versions limit/include_body type import (GetVersionsOpts, PageVersionRows); +2 #5984 lane apply diet: putPage/setPageAliases write inline in the caller's page transaction (engine methods cannot move); +4 GBRA-69: replaceDerivedLinksBatch delegate (logic in derived-links.ts); +5 GBRA-67: readPageSnapshotsBatch delegate (batch logic in page-snapshot-batch.ts); +1 GBRA-75 wave 10: findDuplicatePages delegate (SQL in engine-sql/pages.ts); +2 GBRA-76: transaction/transactionDirect take TransactionOptions and refuse an already-aborted signal before BEGIN; +2 #4772 (W14 PR3): entityTypes HealthDeps delegate + import (policy in schema-pack/entity-types.ts, SQL in engine-sql/health.ts); +2 W14 P3.12 (#4772): entityTypes HealthDeps delegate + import on top of W13; +11 Cat 40 Hard fix wave F2 (#6271) on top: countKeywordPages/searchKeywordPages delegations (SQL in engine-sql/keyword-pages.ts) and the rankQuery score parameter (3023 measured); +3 W15 P1.2 (#6454): three one-line stale-frontmatter-key delegates (SQL in engine-sql/pages.ts); +6 large pages Wave A sub-a: getChunkPage delegate (SQL in engine-sql/chunks.ts); +11 #6696 B3: readEmbeddingStateCounts/listEmbeddingStateRows delegations + type import; +22 Wave B lane 1a: segmented page storage delegations (allocateBodyOccurrenceIds..sweepSegments, SQL in engine-sql/page-body.ts) and their imports; +7 LHF wave 2 item 5: request config snapshot delegate lines in getConfig/getAllConfig/setConfig/unsetConfig (logic in config-snapshot.ts); +3 PR2 fix lane B: logIngest stamps writer_version/writer_host_id/writer_segment_reader and getIngestLog names its columns (engine methods cannot move); integrated at the Wave B PR 2 master merge (v0.60.264.0): master 3072 + 3; +5 PR2 fix lane X: keywordBoundedRead runs the read on the engine itself (engine methods cannot move): 3075 + 5; +2 GBRA-130 B-6 (#6860): putDreamVerdict passes its payload through wellFormedJson (engine methods cannot move); +1 GBRA-130 A-1: held option on the stale-page list/count signatures (SQL in engine-sql/pages.ts); +1 GBRA-130 integration: the A-1 (links_extract_failure) and B-6 (wellFormedJson putDreamVerdict) engine hunks composed at the lane merge; +2 #6948: putPage runs assertOriginUnclaimed in its page transaction and restorePage runs assertRevivalUnclaimed (logic in persistence/origin-guard.ts; engine methods cannot move): 3080 + 2; GBRA-130 composed with #6948 at the master 0e0cd27b merge: re-summed to the merged line count (3085); +2 #7159: the frontmatter where clause in searchKeyword and its import (SQL in search/frontmatter-where.ts; engine methods cannot move); +2 GBRA-156 keyword OR rarity: the import and the searchKeyword OR retry through rankOrFallbackByRarity with an orFallback rank parameter like Postgres (logic in search/keyword-or-rarity.ts; engine methods cannot move); +5 agent operator gate fixes: repair-failed marker gate before the lock and the marker record after a failed auto-repair (logic in pglite-repair.ts, refusal in pglite-repair-consent.ts); re-summed at the Wave B PR 4 merge with v0.60.452.0 (3097 measured); +2 GBRA-283 Wave A (#8460): the ENGINE_ROOT import and field (engine identity for per-engine caches; class fields cannot move)
-src/core/postgres-engine.ts 3157 ratchet +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); ceiling rationale: docs/architecture/key-files/engines-2.md entry for src/core/postgres-engine.ts; evidence delivery: getChunkWindows scoped-read delegate + type import (+5; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +10 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3242 #5824: searchVector SQL moved to search/vector-statement.ts, +explainVectorSearch/runVectorAttempt (-156); +6 #5730: onpoisoned wiring on the instance/module/connection-manager pools + poisonedDiscards in getPoolDiagnostics (counter in pool-gauge.ts); +5 #5801: onCheckout observer seam (fires after reserve resolution / transaction-callback entry; listeners in pool-gauge.ts); lowered to 3119 #5889: searchTitles SQL moved to engine-sql/titles.ts (-133); lowered to 2914 F4a: getHealth SQL moved to engine-sql/health.ts (-216); +2 #5984: transactions track held page guards like PGLite (withHeldPageKeys), so repeated guards in one transaction cost no round trips; +1 #5984: traceSqlOptions import for the env-gated GBRAIN_SQL_TRACE bench hook (src/core/sql-trace.ts); v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (2917 measured); +2 engine graduation (GBRA-50 G2a): initSchema sizing parameter (the source embedding layout sizes a fresh target); +1 #5984: upsertChunks guards pass the per-transaction config memo (transactionMemo in page-state/transactions.ts); v0.60.58.0 merge: #5984 diet growth re-summed over v0.60.57.0 (2920 measured); +4 P7 relationalChainHop delegate; +8 contributor audit wave P0: listFactsKeyset delegate (SQL in engine-sql/facts.ts); +1 #5375: get_versions limit/include_body type import (GetVersionsOpts, PageVersionRows); 6 #6085: initSchema pins advisory lock 42, bootstrap, schema replay and unlock to one reserved backend when the DDL pool has more than one slot (gauge only, no long-hold permit), released in finally; wave 10 collector: lane E (#6085), lane G (#5375) and master compose at 2939; +2 #6110: search transactions pass jitOff to withScopedReadTransaction (SET LOCAL jit = off in postgres-engine/search-settings.ts); +2 #5984 lane apply diet: putPage/setPageAliases write inline in the caller's page transaction (engine methods cannot move); +1 #5984 single-write fast path composes with the lane apply diet at 2944; +2 #5984 shared parameter types: the instance pool passes shared_types and initSchema clears them after migrations (helpers in db.ts); +2 #6276: the remote alias-resolving readPageSnapshot runs with JIT off (withScopedReadTransaction jitOff); +5 #6278: executeRaw timeoutMs delegate (statement in postgres-engine/bounded-statement.ts); +23 #6278 PR 1.5: cancelSettleMs() and the settle timer in runUnsafe that discards a reserved connection whose cancel a transaction-mode pooler never completed; +3 #6317 lane 2: getPoolDiagnostics().pool from the vendored driver (postgres-engine/pool-stats.ts) and the prepare mark; +4 GBRA-69: replaceDerivedLinksBatch delegate (logic in derived-links.ts); +1 GBRA-69 extract batching: replaceDerivedLinksBatch delegate (batch logic in derived-links.ts); +9 GBRA-75: getBacklinkCounts and getHealth statements run JIT-off through the private jitOffRead transaction helper (engine methods cannot move); +3 GBRA-75 wave 7: searchKeyword and searchVector start the once-per-engine background search statistics guard (logic in search/projection-statistics.ts); +7 GBRA-67: readPageSnapshotsBatch scoped-read delegate (batch logic in page-snapshot-batch.ts); +1 GBRA-75 wave 10: findDuplicatePages scoped-read delegate (SQL in engine-sql/pages.ts); +7 #6383: poolIncidents hooks on the instance/module/connection-manager pools (counter and lines in pool-gauge.ts, budget in db.ts) and stuckDiscards/buildFailures in getPoolDiagnostics; +3 GBRA-76: transaction/transactionDirect take TransactionOptions; transactionOn attaches the begin handle to withTransactionAbort (logic in postgres-engine/transaction-abort.ts); +2 W14 P3.12 (#4772): entityTypes HealthDeps delegate + import on top of W13; +1 #5227: schema.sql replay under withSchemaLockTimeout (wave 14 PR1); +1 driver desync tripwire: desyncDiscards in getPoolDiagnostics (counter and line in pool-gauge.ts); +11 Cat 40 Hard fix wave F2 (#6271) on top: countKeywordPages/searchKeywordPages scoped-read delegations (SQL in engine-sql/keyword-pages.ts) and the rankQuery score parameter (3027 measured); +3 W15 P1.2 (#6454): three one-line stale-frontmatter-key delegates, reads scoped (SQL in engine-sql/pages.ts); +12 wave 16 G5.1 (#6495): keywordStatementTimeout memo field, its connect/disconnect resets and the keywordStatementTimeoutSetting accessor, plus one awaited setting per keyword/chunk/CJK transaction (resolver in postgres-engine/keyword-statement-timeout.ts); wave 16 G5.1 gate fix: keywordStatementTimeoutSetting resolves the knob once per connection on the first keyword statement from the saved connect config (connect issues no statement for it; 3042 measured); +7 large pages Wave A sub-a: getChunkPage scoped-read delegate (SQL in engine-sql/chunks.ts); +11 #6696 B3: readEmbeddingStateCounts/listEmbeddingStateRows delegations + type import; +22 Wave B lane 1a: segmented page storage delegations (allocateBodyOccurrenceIds..sweepSegments, SQL in engine-sql/page-body.ts) and their imports; +3 wave 18b lane 2 (#6495): keywordTimeouts negative-cache field and the searchKeyword runner wrap (logic in postgres-engine/keyword-timeout-cache.ts); integrated at wave 18b: master 3082 + 3; +3 PR2 fix lane B: logIngest stamps writer_version/writer_host_id/writer_segment_reader and getIngestLog names its columns (engine methods cannot move); integrated at the Wave B PR 2 master merge (v0.60.264.0): master 3085 + 3; +3 PR2 fix lane E (E1): getChunks/getChunkPage/getChunkWindows run the manifest privilege probe in their scoped transaction (chunkManifestReads in search/safe-chunks.ts); integrated at the lane E merge onto b75a69a6d: 3088 + 3; +6 PR2 fix lane X: searchVector, explainVectorSearch, the hasMore witness and runVectorAttempt pick the chunk-manifest statement form inside each bounded attempt transaction, so its statement_timeout bounds the probe (form memo vectorStatementForms in search/vector-statement.ts; engine methods cannot move): 3091 + 6; +5 PR2 fix lane X: keywordBoundedRead runs the read in withScopedReadTransaction under the keyword statement timeout setting (engine methods cannot move): 3097 + 5; +2 GBRA-130 B-6 (#6860): putDreamVerdict passes its payload through wellFormedJson (engine methods cannot move); +1 GBRA-130 A-1: held option on the stale-page list/count signatures (SQL in engine-sql/pages.ts); +1 GBRA-130 integration: the A-1 (links_extract_failure) and B-6 (wellFormedJson putDreamVerdict) engine hunks composed at the lane merge; +2 #6948: putPage runs assertOriginUnclaimed in its page transaction and restorePage runs assertRevivalUnclaimed (logic in persistence/origin-guard.ts; engine methods cannot move): 3102 + 2; GBRA-130 composed with #6948 at the master 0e0cd27b merge: re-summed to the merged line count (3107); +3 #7159: the frontmatter where clause in the two keyword typesClause sites and its import (SQL in search/frontmatter-where.ts; engine methods cannot move); GBRA-156 retrieval wave (#7201) composed with #7194 at the merge: re-summed (3114 measured); +2 warm CLI socket (#7218): connectedDatabaseUrl getter (the URL the engine connected with, bound into the socket identity), composed over the GBRA-156 retrieval wave (3116 measured); +1 GBRA-133 PR 2b: transactionOn hands the outermost transaction its commit checks (page-state/transactions.ts withCommitChecks), composed with the warm CLI socket at the merge (3117 measured); +18 GBRA-156: the private readTransaction helper behind withScopedReadTransaction and jitOffRead answers a top-level read before its COMMIT settles (engine methods cannot move; 3135 measured); +1 GBRA-156: transactionOn and runUnsafe hold a per-search connection slot (import of search/connection-budget.ts; 3136 measured); +2 GBRA-156: transactionOn passes TransactionOptions.pipelineFirst to the pool begin as { first } (driver gate in vendor/postgres index.js begin); an engine method cannot move; composed with the warm CLI socket and GBRA-133 PR 2b at the master v0.60.344.0 merge (3119 measured); GBRA-151 #7183/#7187/#7188 re-summed at the v0.60.402.0 merge (3135 measured); +2 #7183 (GBRA-151) at the v0.60.412.0 merge: read-write-transactions import and transactionOn wraps its connection in readWriteTransactions (logic in postgres-engine/read-write-transactions.ts; engine methods cannot move): 3135 + 2; +7 GBRA-156: transactionOn opens readOnly transactions as BEGIN READ ONLY and a top-level read inherits its request signal, runUnsafe refuses an aborted request (logic in request-signal.ts; engine methods cannot move): 3137 + 7; +3 GBRA-156 keyword OR rarity: the import and the searchKeyword OR retry through rankOrFallbackByRarity (logic in search/keyword-or-rarity.ts; engine methods cannot move); +2 wave-b PR 4 merged with #7218 (both sides added imports); re-summed at the Wave B PR 4 merge with v0.60.452.0 (3155 measured); +2 GBRA-283 Wave A (#8460): the ENGINE_ROOT import and field (engine identity for per-engine caches; class fields cannot move)
+src/core/pglite-engine.ts 3103 ratchet +4 GBRA-283 B1 (#8455): initSchema seeds an engine opened from settings with settings.embedding and refuses a mismatch, and its open skips the snapshot fast path (logic in embedded-engine.ts; engine methods cannot move); +5 agent operator gate fixes: repair-failed marker gate before the lock and the marker record after a failed auto-repair (logic in pglite-repair.ts, refusal in pglite-repair-consent.ts); +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); E1 bootstrap moved to engine-sql/bootstrap.ts; ceiling rationale: docs/architecture/key-files/engines-1.md entry for src/core/pglite-engine.ts; evidence delivery: getChunkWindows delegate + type import (+3; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +12 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3213 #5824: searchVector SQL moved to search/vector-statement.ts (-166); lowered to 3117 #5889: searchTitles SQL moved to engine-sql/titles.ts (-108); lowered to 2915 F4a: getHealth SQL moved to engine-sql/health.ts (-202); +6 F4b: planner-sensitive reads call beforePlannerRead/plannerRead (logic in planner-stats.ts); +52 engine graduation (GBRA-50 G2a): marker/tombstone checks before and after the kernel lock (logic in persistence/graduation-custody.ts), lock-retaining close and held-lock open (engine lifecycle methods cannot move); 4 Foundations 2 Lane F: autocommit write statements take the WAL checkpoint guard (classifier writesWal in pglite-engine/checkpoint-guard.ts); +5 agent operator gate fixes: repair-failed marker gate before the lock and the marker record after a failed auto-repair (logic in pglite-repair.ts, refusal in pglite-repair-consent.ts); +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); E1 bootstrap moved to engine-sql/bootstrap.ts; ceiling rationale: docs/architecture/key-files/engines-1.md entry for src/core/pglite-engine.ts; evidence delivery: getChunkWindows delegate + type import (+3; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +12 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3213 #5824: searchVector SQL moved to search/vector-statement.ts (-166); lowered to 3117 #5889: searchTitles SQL moved to engine-sql/titles.ts (-108); lowered to 2915 F4a: getHealth SQL moved to engine-sql/health.ts (-202); +6 F4b: planner-sensitive reads call beforePlannerRead/plannerRead (logic in planner-stats.ts); +5 agent operator gate fixes: repair-failed marker gate before the lock and the marker record after a failed auto-repair (logic in pglite-repair.ts, refusal in pglite-repair-consent.ts); +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); E1 bootstrap moved to engine-sql/bootstrap.ts; ceiling rationale: docs/architecture/key-files/engines-1.md entry for src/core/pglite-engine.ts; evidence delivery: getChunkWindows delegate + type import (+3; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +12 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3213 #5824: searchVector SQL moved to search/vector-statement.ts (-166); lowered to 3117 #5889: searchTitles SQL moved to engine-sql/titles.ts (-108); lowered to 2915 F4a: getHealth SQL moved to engine-sql/health.ts (-202); +6 F4b: planner-sensitive reads call beforePlannerRead/plannerRead (logic in planner-stats.ts); +52 engine graduation (GBRA-50 G2a): marker/tombstone checks before and after the kernel lock (logic in persistence/graduation-custody.ts), lock-retaining close and held-lock open (engine lifecycle methods cannot move); 4 Foundations 2 Lane F: autocommit write statements take the WAL checkpoint guard (classifier writesWal in pglite-engine/checkpoint-guard.ts); +5 agent operator gate fixes: repair-failed marker gate before the lock and the marker record after a failed auto-repair (logic in pglite-repair.ts, refusal in pglite-repair-consent.ts); +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); E1 bootstrap moved to engine-sql/bootstrap.ts; ceiling rationale: docs/architecture/key-files/engines-1.md entry for src/core/pglite-engine.ts; evidence delivery: getChunkWindows delegate + type import (+3; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +12 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3213 #5824: searchVector SQL moved to search/vector-statement.ts (-166); lowered to 3117 #5889: searchTitles SQL moved to engine-sql/titles.ts (-108); lowered to 2915 F4a: getHealth SQL moved to engine-sql/health.ts (-202); +6 F4b: planner-sensitive reads call beforePlannerRead/plannerRead (logic in planner-stats.ts); +5 agent operator gate fixes: repair-failed marker gate before the lock and the marker record after a failed auto-repair (logic in pglite-repair.ts, refusal in pglite-repair-consent.ts); +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); E1 bootstrap moved to engine-sql/bootstrap.ts; ceiling rationale: docs/architecture/key-files/engines-1.md entry for src/core/pglite-engine.ts; evidence delivery: getChunkWindows delegate + type import (+3; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +12 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3213 #5824: searchVector SQL moved to search/vector-statement.ts (-166); lowered to 3117 #5889: searchTitles SQL moved to engine-sql/titles.ts (-108); lowered to 2915 F4a: getHealth SQL moved to engine-sql/health.ts (-202); +6 F4b: planner-sensitive reads call beforePlannerRead/plannerRead (logic in planner-stats.ts); +52 engine graduation (GBRA-50 G2a): marker/tombstone checks before and after the kernel lock (logic in persistence/graduation-custody.ts), lock-retaining close and held-lock open (engine lifecycle methods cannot move); +1 #5984: upsertChunks guards pass the per-transaction config memo (transactionMemo in page-state/transactions.ts); v0.60.58.0 merge: #5984 diet growth re-summed over v0.60.57.0 (2983 measured); 4 Foundations 2 Lane F: autocommit write statements take the WAL checkpoint guard (classifier writesWal in pglite-engine/checkpoint-guard.ts); +5 agent operator gate fixes: repair-failed marker gate before the lock and the marker record after a failed auto-repair (logic in pglite-repair.ts, refusal in pglite-repair-consent.ts); +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); E1 bootstrap moved to engine-sql/bootstrap.ts; ceiling rationale: docs/architecture/key-files/engines-1.md entry for src/core/pglite-engine.ts; evidence delivery: getChunkWindows delegate + type import (+3; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +12 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3213 #5824: searchVector SQL moved to search/vector-statement.ts (-166); lowered to 3117 #5889: searchTitles SQL moved to engine-sql/titles.ts (-108); lowered to 2915 F4a: getHealth SQL moved to engine-sql/health.ts (-202); +6 F4b: planner-sensitive reads call beforePlannerRead/plannerRead (logic in planner-stats.ts); +5 agent operator gate fixes: repair-failed marker gate before the lock and the marker record after a failed auto-repair (logic in pglite-repair.ts, refusal in pglite-repair-consent.ts); +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); E1 bootstrap moved to engine-sql/bootstrap.ts; ceiling rationale: docs/architecture/key-files/engines-1.md entry for src/core/pglite-engine.ts; evidence delivery: getChunkWindows delegate + type import (+3; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +12 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3213 #5824: searchVector SQL moved to search/vector-statement.ts (-166); lowered to 3117 #5889: searchTitles SQL moved to engine-sql/titles.ts (-108); lowered to 2915 F4a: getHealth SQL moved to engine-sql/health.ts (-202); +6 F4b: planner-sensitive reads call beforePlannerRead/plannerRead (logic in planner-stats.ts); +52 engine graduation (GBRA-50 G2a): marker/tombstone checks before and after the kernel lock (logic in persistence/graduation-custody.ts), lock-retaining close and held-lock open (engine lifecycle methods cannot move); +1 #5984: upsertChunks guards pass the per-transaction config memo (transactionMemo in page-state/transactions.ts); v0.60.58.0 merge: #5984 diet growth re-summed over v0.60.57.0 (2983 measured); +4 P7 relationalChainHop delegate; +8 contributor audit wave P0: listFactsKeyset delegate (SQL in engine-sql/facts.ts); +1 #5375: get_versions limit/include_body type import (GetVersionsOpts, PageVersionRows); +2 #5984 lane apply diet: putPage/setPageAliases write inline in the caller's page transaction (engine methods cannot move); +4 GBRA-69: replaceDerivedLinksBatch delegate (logic in derived-links.ts); +5 GBRA-67: readPageSnapshotsBatch delegate (batch logic in page-snapshot-batch.ts); +1 GBRA-75 wave 10: findDuplicatePages delegate (SQL in engine-sql/pages.ts); +2 GBRA-76: transaction/transactionDirect take TransactionOptions and refuse an already-aborted signal before BEGIN; +2 #4772 (W14 PR3): entityTypes HealthDeps delegate + import (policy in schema-pack/entity-types.ts, SQL in engine-sql/health.ts); +2 W14 P3.12 (#4772): entityTypes HealthDeps delegate + import on top of W13; +11 Cat 40 Hard fix wave F2 (#6271) on top: countKeywordPages/searchKeywordPages delegations (SQL in engine-sql/keyword-pages.ts) and the rankQuery score parameter (3023 measured); +3 W15 P1.2 (#6454): three one-line stale-frontmatter-key delegates (SQL in engine-sql/pages.ts); +6 large pages Wave A sub-a: getChunkPage delegate (SQL in engine-sql/chunks.ts); +11 #6696 B3: readEmbeddingStateCounts/listEmbeddingStateRows delegations + type import; +22 Wave B lane 1a: segmented page storage delegations (allocateBodyOccurrenceIds..sweepSegments, SQL in engine-sql/page-body.ts) and their imports; +7 LHF wave 2 item 5: request config snapshot delegate lines in getConfig/getAllConfig/setConfig/unsetConfig (logic in config-snapshot.ts); +3 PR2 fix lane B: logIngest stamps writer_version/writer_host_id/writer_segment_reader and getIngestLog names its columns (engine methods cannot move); integrated at the Wave B PR 2 master merge (v0.60.264.0): master 3072 + 3; +5 PR2 fix lane X: keywordBoundedRead runs the read on the engine itself (engine methods cannot move): 3075 + 5; +2 GBRA-130 B-6 (#6860): putDreamVerdict passes its payload through wellFormedJson (engine methods cannot move); +1 GBRA-130 A-1: held option on the stale-page list/count signatures (SQL in engine-sql/pages.ts); +1 GBRA-130 integration: the A-1 (links_extract_failure) and B-6 (wellFormedJson putDreamVerdict) engine hunks composed at the lane merge; +2 #6948: putPage runs assertOriginUnclaimed in its page transaction and restorePage runs assertRevivalUnclaimed (logic in persistence/origin-guard.ts; engine methods cannot move): 3080 + 2; GBRA-130 composed with #6948 at the master 0e0cd27b merge: re-summed to the merged line count (3085); +2 #7159: the frontmatter where clause in searchKeyword and its import (SQL in search/frontmatter-where.ts; engine methods cannot move); +2 GBRA-156 keyword OR rarity: the import and the searchKeyword OR retry through rankOrFallbackByRarity with an orFallback rank parameter like Postgres (logic in search/keyword-or-rarity.ts; engine methods cannot move); +5 agent operator gate fixes: repair-failed marker gate before the lock and the marker record after a failed auto-repair (logic in pglite-repair.ts, refusal in pglite-repair-consent.ts); re-summed at the Wave B PR 4 merge with v0.60.452.0 (3097 measured); +2 GBRA-283 Wave A (#8460): the ENGINE_ROOT import and field (engine identity for per-engine caches; class fields cannot move)
+src/core/postgres-engine.ts 3163 ratchet +6 GBRA-283 B1 (#8455): an engine opened from settings routes its direct URL and statement-description cache from its settings, and initSchema seeds settings.embedding and refuses a mismatch (logic in embedded-engine.ts; engine methods cannot move); +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); ceiling rationale: docs/architecture/key-files/engines-2.md entry for src/core/postgres-engine.ts; evidence delivery: getChunkWindows scoped-read delegate + type import (+5; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +10 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3242 #5824: searchVector SQL moved to search/vector-statement.ts, +explainVectorSearch/runVectorAttempt (-156); +6 #5730: onpoisoned wiring on the instance/module/connection-manager pools + poisonedDiscards in getPoolDiagnostics (counter in pool-gauge.ts); +5 #5801: onCheckout observer seam (fires after reserve resolution / transaction-callback entry; listeners in pool-gauge.ts); lowered to 3119 #5889: searchTitles SQL moved to engine-sql/titles.ts (-133); lowered to 2914 F4a: getHealth SQL moved to engine-sql/health.ts (-216); +2 #5984: transactions track held page guards like PGLite (withHeldPageKeys), so repeated guards in one transaction cost no round trips; +1 #5984: traceSqlOptions import for the env-gated GBRAIN_SQL_TRACE bench hook (src/core/sql-trace.ts); v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (2917 measured); +2 engine graduation (GBRA-50 G2a): initSchema sizing parameter (the source embedding layout sizes a fresh target); +1 #5984: upsertChunks guards pass the per-transaction config memo (transactionMemo in page-state/transactions.ts); v0.60.58.0 merge: #5984 diet growth re-summed over v0.60.57.0 (2920 measured); +4 P7 relationalChainHop delegate; +8 contributor audit wave P0: listFactsKeyset delegate (SQL in engine-sql/facts.ts); +1 #5375: get_versions limit/include_body type import (GetVersionsOpts, PageVersionRows); 6 #6085: initSchema pins advisory lock 42, bootstrap, schema replay and unlock to one reserved backend when the DDL pool has more than one slot (gauge only, no long-hold permit), released in finally; wave 10 collector: lane E (#6085), lane G (#5375) and master compose at 2939; +2 #6110: search transactions pass jitOff to withScopedReadTransaction (SET LOCAL jit = off in postgres-engine/search-settings.ts); +2 #5984 lane apply diet: putPage/setPageAliases write inline in the caller's page transaction (engine methods cannot move); +1 #5984 single-write fast path composes with the lane apply diet at 2944; +2 #5984 shared parameter types: the instance pool passes shared_types and initSchema clears them after migrations (helpers in db.ts); +2 #6276: the remote alias-resolving readPageSnapshot runs with JIT off (withScopedReadTransaction jitOff); +5 #6278: executeRaw timeoutMs delegate (statement in postgres-engine/bounded-statement.ts); +23 #6278 PR 1.5: cancelSettleMs() and the settle timer in runUnsafe that discards a reserved connection whose cancel a transaction-mode pooler never completed; +3 #6317 lane 2: getPoolDiagnostics().pool from the vendored driver (postgres-engine/pool-stats.ts) and the prepare mark; +4 GBRA-69: replaceDerivedLinksBatch delegate (logic in derived-links.ts); +1 GBRA-69 extract batching: replaceDerivedLinksBatch delegate (batch logic in derived-links.ts); +9 GBRA-75: getBacklinkCounts and getHealth statements run JIT-off through the private jitOffRead transaction helper (engine methods cannot move); +3 GBRA-75 wave 7: searchKeyword and searchVector start the once-per-engine background search statistics guard (logic in search/projection-statistics.ts); +7 GBRA-67: readPageSnapshotsBatch scoped-read delegate (batch logic in page-snapshot-batch.ts); +1 GBRA-75 wave 10: findDuplicatePages scoped-read delegate (SQL in engine-sql/pages.ts); +7 #6383: poolIncidents hooks on the instance/module/connection-manager pools (counter and lines in pool-gauge.ts, budget in db.ts) and stuckDiscards/buildFailures in getPoolDiagnostics; +3 GBRA-76: transaction/transactionDirect take TransactionOptions; transactionOn attaches the begin handle to withTransactionAbort (logic in postgres-engine/transaction-abort.ts); +2 W14 P3.12 (#4772): entityTypes HealthDeps delegate + import on top of W13; +1 #5227: schema.sql replay under withSchemaLockTimeout (wave 14 PR1); +1 driver desync tripwire: desyncDiscards in getPoolDiagnostics (counter and line in pool-gauge.ts); +11 Cat 40 Hard fix wave F2 (#6271) on top: countKeywordPages/searchKeywordPages scoped-read delegations (SQL in engine-sql/keyword-pages.ts) and the rankQuery score parameter (3027 measured); +3 W15 P1.2 (#6454): three one-line stale-frontmatter-key delegates, reads scoped (SQL in engine-sql/pages.ts); +12 wave 16 G5.1 (#6495): keywordStatementTimeout memo field, its connect/disconnect resets and the keywordStatementTimeoutSetting accessor, plus one awaited setting per keyword/chunk/CJK transaction (resolver in postgres-engine/keyword-statement-timeout.ts); wave 16 G5.1 gate fix: keywordStatementTimeoutSetting resolves the knob once per connection on the first keyword statement from the saved connect config (connect issues no statement for it; 3042 measured); +7 large pages Wave A sub-a: getChunkPage scoped-read delegate (SQL in engine-sql/chunks.ts); +11 #6696 B3: readEmbeddingStateCounts/listEmbeddingStateRows delegations + type import; +22 Wave B lane 1a: segmented page storage delegations (allocateBodyOccurrenceIds..sweepSegments, SQL in engine-sql/page-body.ts) and their imports; +3 wave 18b lane 2 (#6495): keywordTimeouts negative-cache field and the searchKeyword runner wrap (logic in postgres-engine/keyword-timeout-cache.ts); integrated at wave 18b: master 3082 + 3; +3 PR2 fix lane B: logIngest stamps writer_version/writer_host_id/writer_segment_reader and getIngestLog names its columns (engine methods cannot move); integrated at the Wave B PR 2 master merge (v0.60.264.0): master 3085 + 3; +3 PR2 fix lane E (E1): getChunks/getChunkPage/getChunkWindows run the manifest privilege probe in their scoped transaction (chunkManifestReads in search/safe-chunks.ts); integrated at the lane E merge onto b75a69a6d: 3088 + 3; +6 PR2 fix lane X: searchVector, explainVectorSearch, the hasMore witness and runVectorAttempt pick the chunk-manifest statement form inside each bounded attempt transaction, so its statement_timeout bounds the probe (form memo vectorStatementForms in search/vector-statement.ts; engine methods cannot move): 3091 + 6; +5 PR2 fix lane X: keywordBoundedRead runs the read in withScopedReadTransaction under the keyword statement timeout setting (engine methods cannot move): 3097 + 5; +2 GBRA-130 B-6 (#6860): putDreamVerdict passes its payload through wellFormedJson (engine methods cannot move); +1 GBRA-130 A-1: held option on the stale-page list/count signatures (SQL in engine-sql/pages.ts); +1 GBRA-130 integration: the A-1 (links_extract_failure) and B-6 (wellFormedJson putDreamVerdict) engine hunks composed at the lane merge; +2 #6948: putPage runs assertOriginUnclaimed in its page transaction and restorePage runs assertRevivalUnclaimed (logic in persistence/origin-guard.ts; engine methods cannot move): 3102 + 2; GBRA-130 composed with #6948 at the master 0e0cd27b merge: re-summed to the merged line count (3107); +3 #7159: the frontmatter where clause in the two keyword typesClause sites and its import (SQL in search/frontmatter-where.ts; engine methods cannot move); GBRA-156 retrieval wave (#7201) composed with #7194 at the merge: re-summed (3114 measured); +2 warm CLI socket (#7218): connectedDatabaseUrl getter (the URL the engine connected with, bound into the socket identity), composed over the GBRA-156 retrieval wave (3116 measured); +1 GBRA-133 PR 2b: transactionOn hands the outermost transaction its commit checks (page-state/transactions.ts withCommitChecks), composed with the warm CLI socket at the merge (3117 measured); +18 GBRA-156: the private readTransaction helper behind withScopedReadTransaction and jitOffRead answers a top-level read before its COMMIT settles (engine methods cannot move; 3135 measured); +1 GBRA-156: transactionOn and runUnsafe hold a per-search connection slot (import of search/connection-budget.ts; 3136 measured); +2 GBRA-156: transactionOn passes TransactionOptions.pipelineFirst to the pool begin as { first } (driver gate in vendor/postgres index.js begin); an engine method cannot move; composed with the warm CLI socket and GBRA-133 PR 2b at the master v0.60.344.0 merge (3119 measured); GBRA-151 #7183/#7187/#7188 re-summed at the v0.60.402.0 merge (3135 measured); +2 #7183 (GBRA-151) at the v0.60.412.0 merge: read-write-transactions import and transactionOn wraps its connection in readWriteTransactions (logic in postgres-engine/read-write-transactions.ts; engine methods cannot move): 3135 + 2; +7 GBRA-156: transactionOn opens readOnly transactions as BEGIN READ ONLY and a top-level read inherits its request signal, runUnsafe refuses an aborted request (logic in request-signal.ts; engine methods cannot move): 3137 + 7; +3 GBRA-156 keyword OR rarity: the import and the searchKeyword OR retry through rankOrFallbackByRarity (logic in search/keyword-or-rarity.ts; engine methods cannot move); +2 wave-b PR 4 merged with #7218 (both sides added imports); re-summed at the Wave B PR 4 merge with v0.60.452.0 (3155 measured); +2 GBRA-283 Wave A (#8460): the ENGINE_ROOT import and field (engine identity for per-engine caches; class fields cannot move)
src/core/search/hybrid.ts 1562 ratchet +5 GBRA-81 item 5 per-stage search timings: HybridSearchOpts._timings (interface field) and the timer bindings and import in hybridSearch/hybridSearchCached (collector logic in search/stage-timings.ts); +2 W5 page-unit ranking cut: HybridSearchOpts.pageRankCut (logic in search/page-rank-cut.ts); +9 W3 confidence-gated reranking: HybridSearchOpts.rerankGate and the gate/lookup threading through rerankAndPin and sizeReturnPool (logic in search/hybrid/rerank-gate.ts, crag.ts gradePreRerank); re-summed at the W3 merge onto master v0.60.168.0 (1641 measured); +2 System One v1: HybridSearchOpts.decide (search/decide-stage.ts); refactor wave 1 split target (W4 hybrid, cut line); ceiling rationale: docs/architecture/key-files/core-search-1.md entry for src/core/search/hybrid.ts; +10 #5691: per-request embedding_query_prefix read once and threaded to the embeds and cache key; +5 green master wave (embedding opt-out): HybridSearchOpts._embeddingOptedOut (interface field) read once per request and threaded to the cache-lookup embed and the keyword-only gate; +24 P2 explain RRF attribution stamp in rrfFusionWeighted, backlink_count stamp, explain_target stage observations, explain/explainTarget opts; +14 fix wave 13 P4.8 #6400: lazyQueryEmbedDeadline (the query-embed deadline starts when the embed starts) and the _queryEmbedDeadline getter; +1 query facts arm: HybridSearchOpts.onQueryEmbedding (interface field; its one-line call is paid inside the ceiling) after the vector arms, so the facts arm reuses the query embedding without a second model call; re-summed at the master a08578ca5 merge (1591 master lines + 3 integration lines: the onQueryEmbedding hook); lowered to 1562: LHF wave 2 item 3 peeled cosineReScore into search/cosine-rescore.ts
src/core/types.ts 2352 ratchet +4 Wave B PR 1 (1c): Page.body_storage/body_bytes (interface fields; guard logic in page-body/page-shape.ts); +8 W3 confidence-gated reranking: HybridSearchMeta.rerank_gate (RerankGateMeta in search/hybrid/rerank-gate.ts); re-summed at the W3 merge onto master v0.60.168.0 (2279 measured); +7 fix wave 11 W6.2/W6.3 (#5989, #6132): SearchOpts.hnswIterativeScan and cjkKeyword, the keyword_candidates_incomplete stage and HybridSearchMeta.keyword_candidates (logic in engine-sql/cjk-search.ts); +5 System One v1 retrieval lane: SearchResult injection_p/injection_suspected, HybridSearchMeta answerability, egress_denied degraded reason; +4 System One v1: SearchResult rerank_score_kind/decide_evidence, HybridSearchMeta decide/rerank; +3 wave review: PAGE_SORT_SQL.updated_asc source_id + id tiebreakers (total order under federated scopes); +5 #4881: OntologyReadOpts extends PageReadScope doc; +3 #4857: PAGE_SORT_SQL.slug total-order tiebreaker comment; grown v0.46.26.0 megawave: EvidenceOpts, pacing/usage result fields, PageFilters growth (#4352 #4218); wave-k: +9 SalienceOpts/AnomaliesOpts source scope (#3867); +20 2026-09 adversarial batch 2: keyword_relaxed_carried stage + relaxed_dropped meta field docs; +16 2026-09 fix wave: SearchResult.keyword_relaxed field + full fusion-demotion doc; (#3867); +9: #4648 rerank_passthrough degraded stage + empty_result_set/malformed_shape reasons | merged v0.48.1.0 true-up; +master v0.48 merge true-up (reranker succession: no_key preflight, reranker_skipped stage, readiness); corrective release: shared internal PageReadScope and PageReadPolicy; ranker wave v0.48.4.0: HybridSearchMeta relational_rerank_pin / keyword_arm_confidence / metadata_boost_gate + SearchResult.relational_pinned (+48 over master's peel); +12: #4681 Page.updated_at_iso + keyset cursor precision docs; #5105: canonical page state shared module and transaction/snapshot delegates; #5105: public page revision fields; upstream integration: preserve independently reviewed master additions with branch facade extraction; #5252 wave: typed vector pool and readiness metadata; merged company ingestion/schema routing changes; retired provider integration removed; +1 write-path wave: 'created' effective-date source; +3 read-path wave: rerank_failed degraded stage + budget reason (closed vocabularies) and its recall classification note; +8 fw3-search: SearchOpts.source_boosts + keyword_arm_failed/title_arm_failed stages; +2 wave-2 W4: ChunkInput.embedding_input_hash (#5553); fix wave 3 x fix wave 2 (v0.60.5.0) composition: +2 at the merge; evidence delivery: optional SearchResult.delivered (+2; shape in search/evidence-delivery.ts); +2 eval wave N1-3: OntologyReadOpts.visibility (remote world-only ontology reads); +4 #5827: GraphNode.source_id and GraphPath from_source_id/to_source_id; +2 #5824: SearchOpts.vectorLegacyGuard rollback switch; +7 #5154: PageFilters.listColumnsOnly (interface field); +11 Foundations 1 F1b: WriteAttributionView + AttributedPageVersion (get_versions / get_write_attribution read shapes); +1 #5988: SearchResult.stale carries the held-file detail (interface field); +6 retrieval feedback: SearchResult feedback_boost/content_hash/relational_path_edges stamps and RelationalFanoutRow.path_edges (interface fields); +2 RelationalFanoutOpts.wide (interface field); 1 GBRA-49: temporal annotation field on link rows; 1 GBRA-49: temporal annotation field on link rows; 1 GBRA-49: temporal annotation field on link rows; +44 P7 ChainHopOpts/ChainHopEdge chain-hop contract types; P7 SearchResult.relational evidence + RelationalEvidence type + relational_plan meta + planner per-call overrides; +2 P7 SearchOpts.relationalChainSlots per-call override; +1 P7 ChainHopOpts.temporal (relationship-validity policy per hop); P3 x P7 (v0.60.60.0) composition: deltas re-summed at the merge; 1 GBRA-49: temporal annotation field on link rows; +44 P7 ChainHopOpts/ChainHopEdge chain-hop contract types; P7 SearchResult.relational evidence + RelationalEvidence type + relational_plan meta + planner per-call overrides; +2 P7 SearchOpts.relationalChainSlots per-call override; +1 P7 ChainHopOpts.temporal (relationship-validity policy per hop); +1 green master wave: embedding_disabled degraded reason (closed vocabulary); +2 #5951: Chunk.source_id (get_chunks names each row's source); 1 P2 SearchResult explain fields (rrf attribution, blend_norm_rrf, score_details, backlink_count) + RrfAttribution (interface fields); +11 #5575 (L1b): PageReadScope minTrust/suppressFlagged, SearchResult trust_tier/origin/unconfirmed, TimelineOpts eligibility (interface fields cannot move); +8 #4772 (W14 PR3): BrainHealth.entity_types_status field (interface fields cannot move); +1 C4: question page type row; +6 entity anchoring: optional SearchResult.entity_anchored row stamp (logic in search/entity-anchor.ts); +4 query facts arm: optional SearchResult.fact_row and superseded_claim row fields (logic in search/facts-arm.ts); +2 query facts arm: SearchResult result_type/fact_id/page_slug/follow_up (fact rows are never page-shaped); +9 Cat 40 Hard fix wave (#6271): SearchResult matched_alias/evidence_omitted/provenance, SearchOpts.rankQuery, keyword_count_unavailable stage and rerank_failed reasons; +12 fix wave 15 P2.1 (#6500): PageFilters.slugAfter (single-source slug keyset, interface field + doc) and the updated_desc tiebreaker comment (the keyset walk lives in facts/conversation-enumeration.ts); +2 wave 16 G5.1 (#6495): EngineConfig.keyword_statement_timeout_ms (interface field + doc); +2 GBRA-92: EngineConfig.pglite_shared_buffers (interface field + doc); +11 large pages (Wave A): Chunk/ChunkInput projected_byte_start/end interface fields (span logic in chunkers/recursive.ts, page-window/document.ts); +4 wave 18b lane 2 (#6495): SearchOpts.keywordTimeoutCache, the skipped_after_timeout degraded reason and the useCache doc line; integrated at wave 18b: master 2319 + 4; +2 LHF wave 2 item 3: retrieval meta cosine_rescore field (js_fallback disclosure; logic in search/cosine-rescore.ts); +14 GBRA-154 ranking wave (#4612 #7153 #7156 #7162 #7164): SearchResult collapsed/redirect_to/image_page/rank_prior/rank_score/fused_score stamps and HybridSearchMeta.collapse (interface fields; logic in search/collapse.ts, rank-priors.ts, score-contract.ts); GBRA-151 retrieval P0 x operability wave merge: both sides grew the file, re-summed (2343 measured); GBRA-156 retrieval wave (#7201) composed with #7194 at the merge: re-summed (2345 measured); GBRA-151 #7147 follow-up re-summed at the v0.60.338.0 merge (2347 measured); +2 GBRA-95 G7a follow-up: Page.withheld_source_path field; +2 #7600: SearchResult.quoted (interface field; logic in search/transcript-quote.ts); +1 #8377: ChronicleTimelineRow.trust_tier (interface field; chronicle reads quote rows by tier)
src/core/minions/queue.ts 2547 ratchet grown #4078 + megawave probe-liveness unlatch (#4310) + master private-queue lifecycle: recovery classifier + monotonic lease; security: durable queued authority and confined filesystem dispatch; master integration: grown #4078 + megawave probe-liveness unlatch (#4310) + master private-queue lifecycle: recovery classifier + monotonic lease; harness support: boundary wiring to shared grants, isolated setup, withdrawal and delegated guards; merged v0.49: durable authority and delegated admission both enforced; typed readiness, configuration-blocked lifecycle and bounded release; +9: prune archives completed dream synthesis keys; +18 Lane D: deferJob (a deferral returns a job to delayed with no attempt counted and no stacktrace growth); the ceiling had 17 lines of slack; +5 agent operator follow-up Item 5 merged over master: claim-time spend fence token and legacy_default stamp (logic in minions/spend-authorization.ts); +5 GBRA-130 A-30: claim excludeWatchdogSuspects option (signature, doc and the mark parameter), the releaseWatchdogClaim delegate, and the co-runner stall call site in handleStalled (logic in minions/watchdog-attribution.ts); +5 GBRA-158 #7239/#7240: failJob result parameter (the #7216 hunk), jsonbSafeJson import and its call in add (sanitizer in text-safe.ts); +2 #7242 lane reservation: claim excludeNames option (doc line and the bound array; policy in minions/lanes.ts); +1 #7241 submitter label import (job-insight.ts) + 1 queue-families type import; #7252 x #7249 merge: both sides grew the file, re-summed (2544 measured); +3 GBRA-133: the stall sweep deletes a drain-lease holder record whose lease lock is gone or expired
diff --git a/src/commands/doctor/checks/persistence-consumers.ts b/src/commands/doctor/checks/persistence-consumers.ts
index 2c6b224de1..2fc46aafab 100644
--- a/src/commands/doctor/checks/persistence-consumers.ts
+++ b/src/commands/doctor/checks/persistence-consumers.ts
@@ -31,7 +31,7 @@ import { compareWriterVersions } from '../../../core/persistence/writer-versions
import { serveServiceRestartArgv } from '../../../core/serve-service.ts';
import { VERSION } from '../../../version.ts';
import { consumerOverlap, hostIdentityMismatches, ownersWithoutHeartbeat, OVERLAP_MIN_AGE_MS } from '../../../core/persistence/consumer-diagnostics.ts';
-import { localHostIdentity } from '../../../core/persistence/identity.ts';
+import { isEmbeddedIdentityValue, localHostIdentity } from '../../../core/persistence/identity.ts';
import { agentFix, checkError, doctorVerify } from '../check-fix.ts';
import { connectedEngine, type DoctorContext, type DoctorEntry } from '../context.ts';
@@ -94,7 +94,7 @@ export async function hostIdentityMismatchCheck(engine: BrainEngine): Promise<Ch
return { name: 'host_identity_mismatch', status: 'warn', details: { ...details, minted_under: me.minted_under ?? 'unknown' },
message: `host_identity_mismatch: ${mismatches.length} managed worktree(s) on this filesystem belong to another host identity. `
+ `This process reads ${me.path} (host ${me.id}, ${minted(me.minted_under)}). `
- + ordered.slice(0, 3).map(m => `The binding for ${m.source_ids.join(', ') || m.worktree_id} at ${m.local_path} is owned by host ${m.owner_host_id} (${m.owner_host.host_json_path}, ${minted(m.owner_host.minted_under)})`
+ + ordered.slice(0, 3).map(m => `The binding for ${m.source_ids.join(', ') || m.worktree_id} at ${m.local_path} is owned by host ${m.owner_host_id} (${isEmbeddedIdentityValue(m.owner_host.host_json_path) ? 'identity given at open by an embedding host, no host.json' : `${m.owner_host.host_json_path}, ${minted(m.owner_host.minted_under)}`})`
+ `${m.reason === 'same_machine_id' ? ', minted on this same machine' : ', and this process\'s identity was minted after that binding under a different home'}.`).join(' ')
+ `${mismatches.length > 3 ? ` (first 3 of ${mismatches.length} shown.)` : ''} `
+ 'Every write from this process on those sources reports owner_unavailable (host_mismatch) and their maintenance never runs. '
diff --git a/src/core/ai/decide/store.ts b/src/core/ai/decide/store.ts
index 4c741255ca..a57c62a413 100644
--- a/src/core/ai/decide/store.ts
+++ b/src/core/ai/decide/store.ts
@@ -12,6 +12,7 @@
*/
import { createHmac, randomBytes } from 'node:crypto';
import type { BrainEngine } from '../../engine.ts';
+import { engineKey } from '../../engine-key.ts';
import { registerBackgroundWorkDrainer, type BackgroundWorkDrainMode } from '../../background-work.ts';
import { isValidOutcome } from './outcomes.ts';
import type { DecideLane, DecideSlot, QuestionKind } from './types.ts';
@@ -184,7 +185,7 @@ registerBackgroundWorkDrainer({ name: 'decide-receipts', order: 6, drain: drainD
export function __resetDecideStoreForTests(): void {
receipts.reset();
spend.reset();
- spendCache.clear();
+ spendCache = new WeakMap();
saltCache = new WeakMap();
}
@@ -245,11 +246,12 @@ export function pageSubject(sourceId: string | undefined, slug: string): string
interface SpendCacheEntry { day: string; at: number; total: number; remote: number }
const SPEND_CACHE_MS = 60_000;
-const spendCache = new Map<BrainEngine, SpendCacheEntry>();
+/** Keyed by engineKey: a transaction or view shares its engine's entry, and an engine dropped by its host takes its entry with it. */
+let spendCache = new WeakMap<object, SpendCacheEntry>();
const utcDay = (t = Date.now()) => new Date(t).toISOString().slice(0, 10);
function bumpSpendCache(engine: BrainEngine, row: SpendRow): void {
- const entry = spendCache.get(engine);
+ const entry = spendCache.get(engineKey(engine));
if (!entry || entry.day !== utcDay()) return;
entry.total += row.cost_usd;
if (row.remote) entry.remote += row.cost_usd;
@@ -257,7 +259,7 @@ function bumpSpendCache(engine: BrainEngine, row: SpendRow): void {
export async function dailySpend(engine: BrainEngine, now = Date.now()): Promise<{ total: number; remote: number }> {
const day = utcDay(now);
- const cached = spendCache.get(engine);
+ const cached = spendCache.get(engineKey(engine));
if (cached && cached.day === day && now - cached.at < SPEND_CACHE_MS) return { total: cached.total, remote: cached.remote };
const rows = await engine.executeRaw<{ total: number | string | null; remote: number | string | null }>(
`SELECT COALESCE(SUM(cost_usd), 0) AS total, COALESCE(SUM(CASE WHEN remote THEN cost_usd ELSE 0 END), 0) AS remote
@@ -265,7 +267,7 @@ export async function dailySpend(engine: BrainEngine, now = Date.now()): Promise
[`${day}T00:00:00Z`],
);
const entry = { day, at: now, total: Number(rows[0]?.total ?? 0), remote: Number(rows[0]?.remote ?? 0) };
- spendCache.set(engine, entry);
+ spendCache.set(engineKey(engine), entry);
return { total: entry.total, remote: entry.remote };
}
diff --git a/src/core/connection-manager.ts b/src/core/connection-manager.ts
index d91ecc633d..106a15c367 100644
--- a/src/core/connection-manager.ts
+++ b/src/core/connection-manager.ts
@@ -56,6 +56,11 @@ export interface ConnectionManagerOpts {
* Sourced from GBRAIN_DIRECT_DATABASE_URL or explicit caller config.
*/
directUrl?: string | null;
+ /**
+ * False for an engine opened from settings (engine-open.ts): the direct URL is `directUrl` alone (absent: none, or
+ * the route a known pooler URL derives) and GBRAIN_DIRECT_DATABASE_URL is never read.
+ */
+ directUrlFromEnv?: boolean;
/**
* Inherit pools + kill-switch state from a parent manager (worker engines,
* transaction clones). When set, this manager is a thin reference holder
@@ -196,7 +201,7 @@ export class ConnectionManager {
this._isSupabase = isSupabasePoolerUrl(opts.url);
// Direct URL: explicit override > env > derive > null. Pooler-shaped
// overrides are normalized to a real direct host (or dropped).
- const envOverride = process.env.GBRAIN_DIRECT_DATABASE_URL;
+ const envOverride = opts.directUrlFromEnv === false ? undefined : process.env.GBRAIN_DIRECT_DATABASE_URL;
const override = opts.directUrl ?? envOverride;
this._directUrl = normalizeDirectUrl(opts.url, override);
// #1915: an operator override is respected as-is — never second-guessed
diff --git a/src/core/db.ts b/src/core/db.ts
index 6f92b1b19b..cb2fd3b189 100644
--- a/src/core/db.ts
+++ b/src/core/db.ts
@@ -203,7 +203,8 @@ export function clearSharedTypes(...pools: unknown[]): void {
* it) in the same round trip and loads them; a database without a `config`
* table falls back to `SELECT 1`.
*/
-export async function checkPoolAndLoadSharedTypes(pool: ReturnType<typeof postgres>, url: string): Promise<void> {
+/** `persisted: false` (an engine opened from settings) keeps the shared descriptions in this process and reads no file under the home. */
+export async function checkPoolAndLoadSharedTypes(pool: ReturnType<typeof postgres>, url: string, opts: { persisted?: boolean } = {}): Promise<void> {
let rows: Array<{ server: string; schema: string | null; database: string | null }>;
try {
rows = await pool.unsafe(`SELECT current_setting('server_version_num') AS server, (SELECT value FROM config WHERE key='version') AS schema,
@@ -213,7 +214,7 @@ export async function checkPoolAndLoadSharedTypes(pool: ReturnType<typeof postgr
await pool`SELECT 1`;
return;
}
- loadSharedParameterTypes(url, String(rows[0]?.server ?? ''), rows[0]?.schema ?? null, rows[0]?.database ?? null);
+ if (opts.persisted !== false) loadSharedParameterTypes(url, String(rows[0]?.server ?? ''), rows[0]?.schema ?? null, rows[0]?.database ?? null);
}
/**
diff --git a/src/core/embedded-engine.ts b/src/core/embedded-engine.ts
new file mode 100644
index 0000000000..9a565f06a2
--- /dev/null
+++ b/src/core/embedded-engine.ts
@@ -0,0 +1,109 @@
+import { engineKey } from './engine-key.ts';
+import type { StorageConfig } from './storage.ts';
+import { DEFAULT_EMBEDDING_DIMENSIONS, DEFAULT_EMBEDDING_MODEL } from './ai/defaults.ts';
+import { opError } from './ops/contract.ts';
+
+/**
+ * The value an embedding host passes to `openEngine` (engine-open.ts). Nothing in it is read from a config file, an
+ * environment variable, the home directory or the working directory: a host that keeps those reads them itself and
+ * builds this object, one per brain.
+ */
+export interface EngineSettings {
+ /** Must be `true`. `openEngine` refuses every other value (`embedded_core_required`); the setting is off by default. */
+ embedded_core: boolean;
+ engine: 'postgres' | 'pglite';
+ /** Postgres: `url`, and `directUrl` for the direct (DDL/session) pool. PGLite: `path`, or none for an in-memory brain. */
+ database: { url?: string; directUrl?: string; path?: string };
+ /** Postgres only: this engine's own pool size (default 4). */
+ pool?: { max?: number };
+ /** The persistence host identity this engine claims and publishes under: a UUID. Required. */
+ host: { id: string };
+ /** The local writer the host holds as a value. Unauthenticated writes use it; no credential file is read. */
+ writer?: { id: string; credential: string; lane: 'cli' | 'stdio' };
+ /** The embedding identity `initSchema()` seeds a fresh brain with and checks an existing one against. */
+ embedding?: { model: string; dimensions: number };
+ /** The file storage backend and the host's object prefix, carried for the file operations. */
+ storage?: StorageConfig;
+ storagePrefix?: string;
+ /** `search.keyword_statement_timeout_ms` for this engine (Postgres). */
+ keyword_statement_timeout_ms?: number;
+ pglite?: { shared_buffers?: string };
+ /** AI provider settings for this engine; opaque here and recorded as given. */
+ ai?: Record<string, unknown>;
+}
+
+/** The settings `embeddedSettings` returns: everything the host passed except the writer credential. */
+export type EmbeddedSettingsView = Readonly<Omit<EngineSettings, 'writer'> & { writer?: { id: string; lane: 'cli' | 'stdio' } }>;
+
+interface EmbeddedRecord {
+ hostId: string | undefined;
+ settings: EngineSettings | null;
+}
+
+/** Keyed by `engineKey`, so a page-transaction clone, a view and every forwarding proxy over the engine share its record. */
+const records = new WeakMap<object, EmbeddedRecord>();
+let embeddedProcess = false;
+
+function recordOf(engine: object): EmbeddedRecord | undefined {
+ return records.get(engineKey(engine));
+}
+
+/** Marks `engine` as opened by `openEngine` with `settings`, and latches the process as one that holds embedded engines. */
+export function markEmbeddedEngine(engine: object, settings: EngineSettings): void {
+ const id = settings.host?.id;
+ const record: EmbeddedRecord = { hostId: typeof id === 'string' && id ? id.toLowerCase() : undefined, settings };
+ records.set(engineKey(engine), record);
+ embeddedProcess = true;
+}
+
+/** True for an engine `openEngine` opened, and for its page transactions and read-through views. */
+export function isEmbeddedEngine(engine: object): boolean {
+ return recordOf(engine) !== undefined;
+}
+
+/** True once any `openEngine` call in this process has marked an engine; it never resets. */
+export function processHasEmbeddedEngines(): boolean {
+ return embeddedProcess;
+}
+
+/** The host id an embedded engine was opened with; undefined for every other engine. */
+export function embeddedHostId(engine: object): string | undefined {
+ return recordOf(engine)?.hostId;
+}
+
+/** The settings an embedded engine holds until it disconnects, the writer credential included. */
+export function embeddedSettingsRecord(engine: object): EngineSettings | undefined {
+ return recordOf(engine)?.settings ?? undefined;
+}
+
+/** The settings an embedded engine was opened with, without the writer credential; undefined after disconnect. */
+export function embeddedSettings(engine: object): EmbeddedSettingsView | undefined {
+ const settings = embeddedSettingsRecord(engine);
+ if (!settings) return undefined;
+ const { writer, ...rest } = settings;
+ return Object.freeze({ ...rest, ...(writer ? { writer: { id: writer.id, lane: writer.lane } } : {}) });
+}
+
+/** Drops the settings (credentials, AI keys, storage) an embedded engine held; it stays marked embedded with its host id. */
+export function releaseEmbeddedEngine(engine: object): void {
+ const record = recordOf(engine);
+ if (record) record.settings = null;
+}
+
+/**
+ * The embedding identity `initSchema()` seeds an embedded engine's fresh brain with: `settings.embedding`, else the
+ * built-in defaults, never the process gateway or the config file. Undefined for every other engine.
+ */
+export function embeddedSchemaEmbedding(engine: object): { model: string; dimensions: number; given: boolean } | undefined {
+ if (!isEmbeddedEngine(engine)) return undefined;
+ const given = embeddedSettingsRecord(engine)?.embedding;
+ return given ? { model: given.model, dimensions: given.dimensions, given: true }
+ : { model: DEFAULT_EMBEDDING_MODEL, dimensions: DEFAULT_EMBEDDING_DIMENSIONS, given: false };
+}
+
+/** An existing database must record the embedding identity the settings name; `initSchema()` changes nothing otherwise. */
+export function assertEmbeddedEmbedding(want: { model: string; dimensions: number; given: boolean }, stored: { model: string | null; dimensions: number }): void {
+ if (!want.given || (stored.model === want.model && stored.dimensions === want.dimensions)) return;
+ throw opError('engine_embedding_mismatch', 'The database records another embedding model or width than settings.embedding.',
+ `This database's vector column is ${stored.dimensions} wide for ${stored.model ?? 'an unrecorded model'}, and the engine was opened with ${want.model} at ${want.dimensions}, so initSchema changed nothing. Pass the recorded model and width in settings.embedding, or read the recorded identity on the brain host with gbrain migrate embeddings --status --json and preview a migration from there. Changing the width is a re-embed the user decides on.`);
+}
diff --git a/src/core/engine-open.ts b/src/core/engine-open.ts
new file mode 100644
index 0000000000..32fa99002e
--- /dev/null
+++ b/src/core/engine-open.ts
@@ -0,0 +1,105 @@
+/**
+ * Experimental: open an engine from a settings value (`gbrain/engine-open`). Off by default; see
+ * docs/ENGINES.md "Opening an engine from settings".
+ */
+import type { BrainEngine } from './engine.ts';
+import type { EngineConfig } from './types.ts';
+import { opError } from './ops/contract.ts';
+import { createEngine } from './engine-factory.ts';
+import { markEmbeddedEngine, releaseEmbeddedEngine, type EngineSettings } from './embedded-engine.ts';
+import { assertLocalWriterValue, setEngineHostId } from './persistence/identity.ts';
+
+export type { EngineSettings, EmbeddedSettingsView } from './embedded-engine.ts';
+export { embeddedSettings, isEmbeddedEngine, processHasEmbeddedEngines } from './embedded-engine.ts';
+export { hostIdFor, registerLocalWriterValue } from './persistence/identity.ts';
+
+/** Connections a Postgres engine opened from settings may open when `pool.max` is not given. */
+export const DEFAULT_EMBEDDED_POOL_MAX = 4;
+
+const invalid = (setting: string, why: string) => opError('engine_settings_invalid', `The ${setting} setting is invalid.`, `${why} Nothing was opened.`);
+const text = (value: unknown) => typeof value === 'string' && value.length > 0;
+const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
+
+function checkSettings(settings: EngineSettings): void {
+ if (settings.engine !== 'postgres' && settings.engine !== 'pglite') throw invalid('engine', "engine is 'postgres' or 'pglite'.");
+ const database = settings.database;
+ if (!database || typeof database !== 'object') throw invalid('database', 'database is an object: { url, directUrl? } for Postgres, { path? } for PGLite.');
+ if (settings.engine === 'postgres') {
+ if (!text(database.url)) throw invalid('database.url', 'A Postgres engine needs database.url.');
+ if (database.path !== undefined) throw invalid('database.path', 'A Postgres engine takes database.url, not database.path.');
+ if (database.directUrl !== undefined && !text(database.directUrl)) throw invalid('database.directUrl', 'database.directUrl is a connection URL when given.');
+ } else {
+ if (database.url !== undefined || database.directUrl !== undefined) throw invalid('database.url', 'A PGLite engine takes database.path (or none for an in-memory brain), not a URL.');
+ if (database.path !== undefined && !text(database.path)) throw invalid('database.path', 'database.path is a data directory when given.');
+ }
+ const max = settings.pool?.max;
+ if (max !== undefined && !(Number.isInteger(max) && max > 0 && max <= 100)) throw invalid('pool.max', 'pool.max is a whole number from 1 to 100.');
+ if (!settings.host || settings.host.id === undefined || settings.host.id === '') {
+ throw opError('engine_host_missing', 'openEngine was called with no host identity.',
+ 'An engine opened from settings claims and publishes work only under the host id its host gives, and it never reads or mints host.json under the home directory, so nothing was opened. Pass host.id as a UUID and keep the same id for the same host across restarts.');
+ }
+ if (typeof settings.host.id !== 'string' || !UUID.test(settings.host.id)) throw invalid('host.id', 'The persistence tables store host ids as uuid, so host.id must be a UUID.');
+ if (settings.writer !== undefined) assertLocalWriterValue(settings.writer);
+ const embedding = settings.embedding;
+ if (embedding !== undefined && !(text(embedding.model) && Number.isInteger(embedding.dimensions) && embedding.dimensions > 0)) {
+ throw invalid('embedding', 'embedding is { model, dimensions } with a model name and a positive whole width.');
+ }
+}
+
+/**
+ * Creates and connects an engine from `settings` alone. It reads no config file, no environment variable, no home
+ * directory and no working directory for its database, pool, direct URL, host identity, writer or embedding identity.
+ * A Postgres engine always gets its own pool (never the module singleton in db.ts), and its direct pool is only
+ * `database.directUrl` (or the one a known pooler URL derives); `GBRAIN_DIRECT_DATABASE_URL` is never consulted.
+ *
+ * A connect is not a migration: the host runs `initSchema()` (or the migrations) itself. On an existing database
+ * `initSchema()` refuses `engine_embedding_mismatch` when `settings.embedding` names another model or width.
+ * `disconnect()` closes it for good and drops the settings it held.
+ */
+export async function openEngine(settings: EngineSettings): Promise<BrainEngine> {
+ if (settings?.embedded_core !== true) {
+ throw opError('embedded_core_required', 'openEngine requires embedded_core: true.',
+ 'Opening an engine from settings is an experimental embedding surface and is off by default, so nothing was opened. Pass embedded_core: true in the settings to opt in; the CLI, gbrain serve and mounts open brains through their own connect path.');
+ }
+ checkSettings(settings);
+ const held: EngineSettings = {
+ ...settings,
+ database: { ...settings.database },
+ host: { id: settings.host.id },
+ ...(settings.pool ? { pool: { ...settings.pool } } : {}),
+ ...(settings.writer ? { writer: { ...settings.writer } } : {}),
+ ...(settings.embedding ? { embedding: { ...settings.embedding } } : {}),
+ ...(settings.storage ? { storage: { ...settings.storage } } : {}),
+ ...(settings.pglite ? { pglite: { ...settings.pglite } } : {}),
+ };
+ const config: EngineConfig = {
+ engine: held.engine,
+ ...(held.database.url ? { database_url: held.database.url } : {}),
+ ...(held.database.path ? { database_path: held.database.path } : {}),
+ ...(held.keyword_statement_timeout_ms !== undefined ? { keyword_statement_timeout_ms: held.keyword_statement_timeout_ms } : {}),
+ ...(held.pglite?.shared_buffers ? { pglite_shared_buffers: held.pglite.shared_buffers } : {}),
+ };
+ const engine = await createEngine(config);
+ markEmbeddedEngine(engine, held);
+ setEngineHostId(engine, held.host.id);
+ let reconnecting = false;
+ const disconnect = engine.disconnect.bind(engine);
+ engine.disconnect = async (): Promise<void> => {
+ try { await disconnect(); }
+ finally { if (!reconnecting) releaseEmbeddedEngine(engine); }
+ };
+ const reconnect = engine.reconnect.bind(engine);
+ engine.reconnect = async (ctx?: { error?: unknown }): Promise<void> => {
+ reconnecting = true;
+ try { await reconnect(ctx); }
+ finally { reconnecting = false; }
+ };
+ try {
+ if (held.engine === 'postgres') await engine.connect({ ...config, poolSize: held.pool?.max ?? DEFAULT_EMBEDDED_POOL_MAX } as EngineConfig & { poolSize: number });
+ else await engine.connect(config);
+ } catch (error) {
+ await engine.disconnect().catch(() => {});
+ throw error;
+ }
+ return engine;
+}
diff --git a/src/core/error-registry.ts b/src/core/error-registry.ts
index 3bfd94f6ea..a018c454bd 100644
--- a/src/core/error-registry.ts
+++ b/src/core/error-registry.ts
@@ -300,6 +300,10 @@ export const CODES = {
embedding_unavailable: { class: 'unavailable', summary: "The provider returned an incomplete embedding batch." },
embedding_unconfigured: { class: 'host_only', summary: "The selected brain has no verifiable text embedding model and dimensions." },
embedding_width_mismatch: { class: 'caller', summary: "The embedding model cannot produce the width of the brain's vector column; nothing was changed." },
+ embedded_core_required: { class: 'caller', summary: "openEngine (gbrain/engine-open) was called without embedded_core: true, so no engine was opened.", why: 'Opening an engine from settings alone is an experimental embedding surface that is off by default; a host opts in explicitly so no existing caller changes behavior.', docs: 'docs/ENGINES.md#opening-an-engine-from-settings-experimental', suggestion: 'Pass embedded_core: true in the settings; the CLI, gbrain serve and mounts open brains through their own connect path and need nothing.' },
+ engine_embedding_mismatch: { class: 'host_only', actor: 'user', summary: "An engine opened from settings names an embedding model or width that differs from the one its database already records, so initSchema changed nothing.", why: 'The vector column has one width and the brain one embedding model; seeding another over it would make every stored and future embedding unreadable. Changing it is an explicit re-embed the user decides on.', docs: 'docs/ENGINES.md#opening-an-engine-from-settings-experimental', suggestion: "Pass the database's recorded model and width in settings.embedding, or read the recorded identity with gbrain migrate embeddings --status on the brain host and preview a migration from there.", fix: { argv: ['gbrain', 'migrate', 'embeddings', '--status', '--json'], consent: [], actor: 'agent', requires_exclusive: false, why: "Read-only: reports the brain's recorded embedding model and width and what a migration would change." } },
+ engine_host_missing: { class: 'caller', summary: "An engine opened from settings has no host identity, so nothing that needs one ran and no host.json was created.", why: 'An embedded engine publishes and claims work under the host id its host gave at open; minting a host.json under the home directory instead would tie its writes to whatever process happens to share that directory.', docs: 'docs/ENGINES.md#opening-an-engine-from-settings-experimental', suggestion: 'Pass host: { id: <uuid> } to openEngine; keep the same id for the same host across restarts.' },
+ engine_settings_invalid: { class: 'caller', summary: "A setting passed to openEngine or registerLocalWriterValue is missing or malformed (engine kind, database url or path, pool size, host or writer id, writer credential or lane, embedding identity), so nothing was opened or registered.", docs: 'docs/ENGINES.md#opening-an-engine-from-settings-experimental', suggestion: 'Correct the setting the message names and call again.' },
engine_graduated: { class: 'caller', summary: "A client opened a PGLite brain that moved to Postgres; its old path holds a tombstone.", docs: 'docs/guides/move-to-postgres.md#graduated-datastore' },
// wave 18b (GBRA-106) #4772: onboarding coverage checks read entity types from the active pack(s).
entity_types_unavailable: { class: 'unavailable', summary: "A schema pack in scope did not load, so the entity page types are unknown; onboarding's entity_link_coverage and timeline_coverage warn instead of grading the old hardcoded type list.",
diff --git a/src/core/feedback/record.ts b/src/core/feedback/record.ts
index d272207cd6..b03cc41327 100644
--- a/src/core/feedback/record.ts
+++ b/src/core/feedback/record.ts
@@ -145,6 +145,8 @@ async function runQueue(q: QueueState): Promise<void> {
}
} finally {
q.running = null;
+ // A drained queue holds nothing, so it does not keep its engine alive (a host may open an engine per request).
+ if (q.jobs.length === 0 && queues.get(q.engine) === q) queues.delete(q.engine);
}
}
diff --git a/src/core/persistence/applied-watermark.ts b/src/core/persistence/applied-watermark.ts
index b16243a291..48c4797c7d 100644
--- a/src/core/persistence/applied-watermark.ts
+++ b/src/core/persistence/applied-watermark.ts
@@ -107,7 +107,7 @@ export async function readAppliedWatermark(engine: BrainEngine, sourceId: string
const [source] = await engine.executeRaw<{ incarnation: string | null; root: string | null }>(`SELECT s.incarnation::text AS incarnation,
COALESCE((SELECT h.local_path FROM persistence_host_bindings h JOIN persistence_source_bindings b ON b.worktree_id=h.worktree_id
WHERE b.source_id=s.id AND h.host_id::text=$2 LIMIT 1), s.local_path) AS root FROM sources s WHERE s.id=$1`,
- [sourceId, (await import('./identity.ts')).existingLocalHostId()]);
+ [sourceId, (await import('./identity.ts')).existingHostIdFor(engine)]);
const commit = write.indexed_through.commit;
const root = !opts.remote && source?.root && commit ? source.root : null;
const lag = root ? await (opts.behind ?? readGitBehind)(root, commit!).catch(() => null) : null;
diff --git a/src/core/persistence/atom-maintenance.ts b/src/core/persistence/atom-maintenance.ts
index 324598932e..a4d395194f 100644
--- a/src/core/persistence/atom-maintenance.ts
+++ b/src/core/persistence/atom-maintenance.ts
@@ -8,7 +8,7 @@ import { OperationError, opError } from '../ops/contract.ts';
import { readFix } from '../ops/op-fix.ts';
import { currentSubmissionAuthority } from '../minions/submission-authority.ts';
import { authorizeStoredRequest, authorizeWrite, submissionAuthority } from './authority.ts';
-import { currentVerifiedLocalWriter, localHostId, registerLocalWriter } from './identity.ts';
+import { currentVerifiedLocalWriter, hostIdFor, registerLocalWriter } from './identity.ts';
import { admitWriteInTransaction, getWriteRequest, receiptFor } from './journal.ts';
import { digest, requireUuid, sha256 } from './digest.ts';
import { getWorktreeBinding, managedPersistenceEnabled, probeWorktreeWriter, type WorktreeBinding } from './ownership.ts';
@@ -106,7 +106,7 @@ async function atomOwnerTarget(engine: BrainEngine, sourceId: string, source: {
const writeThrough = !/^(false|0|off|no)$/i.test(await engine.getConfig('sync.write_through') ?? 'true');
const connectorDatabase = writeThrough && !binding && isConnectorSourceKind(source.kind);
const refusal = writeThrough && root && !binding && !connectorDatabase ? 'Atom maintenance requires the configured canonical owner.'
- : writeThrough && binding && (binding.owner_host_id !== localHostId() || binding.state !== 'active' || !binding.local_path)
+ : writeThrough && binding && (binding.owner_host_id !== hostIdFor(engine) || binding.state !== 'active' || !binding.local_path)
? 'The canonical atom owner is unavailable; no extraction was started.' : null;
return { binding, writeThrough, connectorDatabase, refusal };
}
diff --git a/src/core/persistence/attribution.ts b/src/core/persistence/attribution.ts
index 634a0e829d..d2292fdb62 100644
--- a/src/core/persistence/attribution.ts
+++ b/src/core/persistence/attribution.ts
@@ -1,4 +1,4 @@
-import { currentVerifiedLocalWriter, existingLocalHostId, readLocalWriter } from './identity.ts';
+import { currentVerifiedLocalWriter, existingHostIdFor, readLocalWriter } from './identity.ts';
import type { Principal, SqlEngine, WriteRequest } from './model.ts';
import type { BrainEngine } from '../engine.ts';
import { withWriteAttribution } from './context.ts';
@@ -59,7 +59,7 @@ export async function maintenanceAttribution(engine: SqlEngine): Promise<WriteAt
try { return principalAttribution({ kind: 'local_cli', id: await registration }); }
catch {
installationRegistration.delete(engine);
- return principalAttribution({ kind: 'application', id: `host:${existingLocalHostId() ?? 'unregistered'}` });
+ return principalAttribution({ kind: 'application', id: `host:${existingHostIdFor(engine) ?? 'unregistered'}` });
}
}
const installationRegistration = new WeakMap<SqlEngine, Promise<string>>();
diff --git a/src/core/persistence/consumer-diagnostics.ts b/src/core/persistence/consumer-diagnostics.ts
index 965ad967f4..b07dee7875 100644
--- a/src/core/persistence/consumer-diagnostics.ts
+++ b/src/core/persistence/consumer-diagnostics.ts
@@ -24,7 +24,7 @@ import { existsSync, statSync } from 'node:fs';
import { dirname } from 'node:path';
import type { BrainEngine } from '../engine.ts';
import { CONSUMER_LAPSED_MS, RESIDENT_CONSUMER_KINDS, listHostConsumers, type ListedConsumer } from './consumer-heartbeat.ts';
-import type { LocalHostIdentity } from './identity.ts';
+import { isEmbeddedIdentityValue, type LocalHostIdentity } from './identity.ts';
import { hasManagedRootMarker } from './root-registry.ts';
/** Both rows must be older than this before an overlap is a warning: two starters within one renewal are a known residual. */
@@ -85,6 +85,8 @@ type OwnerRow = { host_id: string; host_json_path: string; persistence_home: str
/** The `GBRAIN_HOME` parent value a supervisor sets so this process mints under the owner's home: the owner's `gbrain_home`, else its persistence home's grandparent (`<home>/.gbrain/persistence`). */
function fixEnv(owner: OwnerRow | undefined): string | null {
+ // An identity given at open (engine-open.ts) has no home to point a supervisor at.
+ if (isEmbeddedIdentityValue(owner?.host_json_path) || isEmbeddedIdentityValue(owner?.persistence_home)) return null;
const minted = owner ? parse(owner.minted_under) : null;
if (typeof minted?.gbrain_home === 'string' && minted.gbrain_home) return `GBRAIN_HOME=${minted.gbrain_home}`;
if (owner?.persistence_home) return `GBRAIN_HOME=${dirname(dirname(owner.persistence_home))}`;
diff --git a/src/core/persistence/consumer-heartbeat.ts b/src/core/persistence/consumer-heartbeat.ts
index 69e214be9f..ca2189502c 100644
--- a/src/core/persistence/consumer-heartbeat.ts
+++ b/src/core/persistence/consumer-heartbeat.ts
@@ -32,7 +32,7 @@ import { readlinkSync } from 'node:fs';
import type { BrainEngine } from '../engine.ts';
import { isProcessAlive, processStartTime, readBootId } from '../pglite-lock.ts';
import { VERSION } from '../../version.ts';
-import { localHostIdentity } from './identity.ts';
+import { hostIdentityPathsFor } from './identity.ts';
import type { SqlEngine } from './model.ts';
/** Kinds whose process stays resident: they defer to the first live full consumer of their host (`serve` always starts full). */
@@ -229,7 +229,7 @@ const RENEW_SQL = `WITH purged AS (
export function startConsumerHeartbeat(engine: DirectEngine, hostId: string, opts: ConsumerHeartbeatOpts): ConsumerHeartbeat {
if (engine.kind === 'pglite') return { renew: async () => {}, get failures() { return 0; }, stop: async () => {} };
const self = opts.identity ?? consumerIdentity();
- const paths = opts.paths ?? (() => { const id = localHostIdentity(); return { host_json_path: id.path, persistence_home: id.persistence_home, minted_under: id.minted_under }; })();
+ const paths = opts.paths ?? hostIdentityPathsFor(engine);
const execute = (sql: string, params: unknown[], signal: AbortSignal) =>
engine.executeRawDirect ? engine.executeRawDirect(sql, params, { signal }) : engine.executeRaw(sql, params, { signal });
const everyMs = opts.everyMs ?? CONSUMER_RENEWAL_MS;
diff --git a/src/core/persistence/consumer.ts b/src/core/persistence/consumer.ts
index 6af992e567..e99e13cc33 100644
--- a/src/core/persistence/consumer.ts
+++ b/src/core/persistence/consumer.ts
@@ -3,7 +3,7 @@ import { withoutCallerAccess } from '../search/private-visibility.ts';
import type { GBrainConfig } from '../config.ts';
import { claimableWriteSql, foregroundPrioritySql, claimGroupFollowers, claimNextLaneHead, claimNextWrite, publicationGroupKey, syncGroup, floorPreparationAttempts, hasClaimableWrite, getWriteRequestById, releaseUnpublishedClaim, renewWriteClaim, vacuumPersistenceQueues, independentGroup, sweepSegmentStorage, yieldToEventLoop } from './journal.ts';
import { connectionCapFailure, finishPreparationStalled, finishUnpublishedFailure, preparationAbortReason, recoverPublication, transientDatabaseFailure, type PreparedMutation } from './coordinator.ts';
-import { localHostId } from './identity.ts';
+import { hostIdFor } from './identity.ts';
import { executeClaimedGroup, PAGE_BATCH_GROUP_MAX, publishSingleWrite, singleWrite } from './group-publish.ts';
import { preparationConfigView } from './config-snapshot.ts';
import { CLAIM_LOST, DEFAULT_CLAIM_LEASE_TIMING, endLostLease, holdClaimForPublication, startClaimLease, type ClaimLeaseTiming } from './claim-lease.ts';
@@ -278,7 +278,7 @@ export class PersistenceConsumer implements PersistenceConsumerLike {
* interval across this host's processes (housekeeping-turn.ts).
*/
oneShot?: { waiting: () => boolean } } = {}) {
- this.hostId = opts.hostId ?? localHostId();
+ this.hostId = opts.hostId ?? hostIdFor(engine);
this.statements = consumerStatementEngine(engine);
}
private get checkoutObservable(): ((listener: () => void) => () => void) | undefined {
diff --git a/src/core/persistence/coordinator.ts b/src/core/persistence/coordinator.ts
index 3f9af171bb..b717a1cc75 100644
--- a/src/core/persistence/coordinator.ts
+++ b/src/core/persistence/coordinator.ts
@@ -11,7 +11,7 @@ import { flushDirectory } from '../fs-durable.ts';
import { isWriteTargetContained } from '../path-confine.ts';
import { sha256 } from './digest.ts';
import { authorizeStoredRequest } from './authority.ts';
-import { localHostId } from './identity.ts';
+import { hostIdFor } from './identity.ts';
import { acquireWorktree, getWorktreeBinding, guardOwnership, type WorktreeBinding } from './ownership.ts';
import { chargePreparationAttempt, clearResolvedRecovery, completeWrite, getWriteRequestById, lockCounters, markRecovering, prepareRecovery, releaseUnpublishedClaim } from './journal.ts';
import type { WaitingOn } from './claim-phase.ts';
@@ -334,7 +334,7 @@ export function preparationStalledFailure(row: WriteRequest, info: PreparationSt
*/
export async function finishPreparationStalled(engine: BrainEngine, row: WriteRequest, info: Omit<PreparationStallInfo, 'attempts'>, charge: boolean): Promise<WriteRequest> {
const attempts = charge ? await chargePreparationAttempt(engine, row) : row.preparation_attempts ?? info.limit;
- const failure = withAttempt(preparationStalledFailure(row, { ...info, attempts }), 'preparation');
+ const failure = withAttempt(preparationStalledFailure(row, { ...info, attempts }), 'preparation', engine);
return engine.transaction(tx => completeWrite(tx, row, 'failed', {}, failure));
}
@@ -352,7 +352,7 @@ export async function releaseChargedInterruption(engine: BrainEngine, row: Write
if (!charge) return null;
const done = await engine.transaction(async tx => {
const attempts = await chargeTransientInterruption(tx, row);
- if (attempts > charge.limit) return completeWrite(tx, row, 'failed', {}, withAttempt(writeInterruptedFailure(row, charge.interruption, attempts, charge.limit), stage));
+ if (attempts > charge.limit) return completeWrite(tx, row, 'failed', {}, withAttempt(writeInterruptedFailure(row, charge.interruption, attempts, charge.limit), stage, tx));
await releaseUnpublishedClaim(tx, row, reason);
return null;
}).then(outcome => ({ outcome }), () => null);
@@ -365,7 +365,7 @@ export async function finishUnpublishedFailure(engine: BrainEngine, row: WriteRe
stage: PublicationStage = 'publication'): Promise<WriteRequest> {
const charged = await releaseChargedInterruption(engine, row, error, stage);
if (charged) return charged;
- const failure = withAttempt(requestError(error), stage);
+ const failure = withAttempt(requestError(error), stage, engine);
if (mayReprepare(row, failure) || transientDatabaseFailure(error)) {
await releaseUnpublishedClaim(engine, row, transientDatabaseFailure(error) ? 'database_contention' : 'revision_changed_repreparing');
return (await getWriteRequestById(engine, row.id))!;
@@ -454,7 +454,7 @@ function largeRecoveryRecord(row: WriteRequest, file: PageMutationFile, binding:
}
export async function publishMutation(engine: BrainEngine, row: WriteRequest, prepared: PreparedMutation,
- hostId = localHostId(), callerHooks: PublicationHooks = {}): Promise<WriteRequest> {
+ hostId = hostIdFor(engine), callerHooks: PublicationHooks = {}): Promise<WriteRequest> {
const hooks = withFaultPoints(callerHooks);
let lock: NativeLockHandle | null = null;
let releaseCapacity: (() => void) | null = null;
@@ -657,7 +657,7 @@ export async function publishMutation(engine: BrainEngine, row: WriteRequest, pr
if (!transactionBodyCompleted && transientInterruption(error)) await faultPoint('persistence:recovery_interruption_charged', { requestId: row.request_id, writeId: row.id, sourceId: row.source_id, operation: row.operation, ...chargedInterruptionDetail(transientInterruption(error), error) });
const terminal = charged ? charged.failure
: !transactionBodyCompleted && !mayReprepare(row, requestError(error)) && !transientDatabaseFailure(error) ? requestError(error) : null;
- const failure = terminal ? withAttempt(terminal, published ? 'after_file_publication' : 'publication') : undefined;
+ const failure = terminal ? withAttempt(terminal, published ? 'after_file_publication' : 'publication', engine) : undefined;
try { await markRecovering(engine, row, failure ? 'publication_failed' : published ? 'commit_outcome_uncertain' : 'publication_not_started', failure); }
catch { /* database outage: durable recovery record remains discoverable */ }
if (lock) {
@@ -684,7 +684,7 @@ export async function publishMutation(engine: BrainEngine, row: WriteRequest, pr
}
}
-export async function recoverPublication(engine: BrainEngine, id: string, hostId = localHostId(), alreadyLocked = false,
+export async function recoverPublication(engine: BrainEngine, id: string, hostId = hostIdFor(engine), alreadyLocked = false,
terminalError?: PublicationFailure, capacityAlreadyHeld = false, hooks: PublicationHooks = {}): Promise<WriteRequest> {
let row = await getWriteRequestById(engine, id);
if (!row) throw opError('not_found', 'Write request not found.',
diff --git a/src/core/persistence/drift-conflicts.ts b/src/core/persistence/drift-conflicts.ts
index bc2a24f20b..a07bee7260 100644
--- a/src/core/persistence/drift-conflicts.ts
+++ b/src/core/persistence/drift-conflicts.ts
@@ -33,7 +33,7 @@ import { isValidSourceId } from '../source-id.ts';
import { validateSlug } from '../utils.ts';
import type { PageSnapshot } from '../page-state/types.ts';
import { sha256 } from './digest.ts';
-import { existingLocalHostId } from './identity.ts';
+import { existingHostIdFor } from './identity.ts';
import { getWorktreeBinding } from './ownership.ts';
import { staleMirrorPage } from './mirror-read-only.ts';
import { prepareFileTarget } from './page-prepare.ts';
@@ -77,7 +77,7 @@ export interface LiveDrift {
* page cannot drift).
*/
export async function liveFileDrift(engine: BrainEngine, sourceId: string, slug: string, snapshot?: PageSnapshot | null): Promise<LiveDrift> {
- const hostId = existingLocalHostId();
+ const hostId = existingHostIdFor(engine);
const binding = hostId ? await getWorktreeBinding(engine, sourceId, hostId) : null;
if (!binding?.local_path || binding.owner_host_id !== hostId || binding.state !== 'active') return { still_present: null, reason: 'not_owner_host' };
const page = snapshot === undefined ? await engine.readPageSnapshot(slug, { sourceId }) : snapshot;
@@ -272,7 +272,7 @@ export async function auditDriftConflicts(engine: BrainEngine, sourceId: string,
ORDER BY r.slug, r.sequence DESC`, [sourceId, slugs]) : [];
const recorded = access.trusted && slugs.length ? await engine.executeRaw<{ slug: string; source_path: string | null; source_uri: string | null }>(
'SELECT slug, source_path, source_uri FROM pages WHERE source_id=$1 AND slug=ANY($2::text[]) AND deleted_at IS NULL', [sourceId, slugs]) : [];
- const hostId = access.trusted ? existingLocalHostId() : null;
+ const hostId = access.trusted ? existingHostIdFor(engine) : null;
const binding = hostId ? await getWorktreeBinding(engine, sourceId, hostId) : null;
const owner = !!binding?.local_path && binding.owner_host_id === hostId && binding.state === 'active';
const root = owner ? join(binding!.local_path!, binding!.relative_path) : null;
diff --git a/src/core/persistence/effect-retry.ts b/src/core/persistence/effect-retry.ts
index 399e03481a..db9d56cfef 100644
--- a/src/core/persistence/effect-retry.ts
+++ b/src/core/persistence/effect-retry.ts
@@ -8,7 +8,7 @@ import { OperationError, opError, type OperationContext } from '../ops/contract.
import { readFix } from '../ops/op-fix.ts';
import type { Action } from '../agent-output.ts';
import { authorizeStoredRequest, authorizeWrite, submissionAuthority } from './authority.ts';
-import { existingLocalHostId } from './identity.ts';
+import { existingHostIdFor } from './identity.ts';
import { guardEffectSource } from './effect-recovery.ts';
import { assertEmbeddingEffectEnabled, readEmbeddingEffectProjection, selectedEffectPage } from './effects.ts';
import { PARK_AFTER_FAILURES, type PersistenceEffect } from './effect-model.ts';
@@ -141,7 +141,7 @@ export async function retryParkedEffects(engine: BrainEngine, sourceId: string,
OR (kind='git' AND state='failed' AND error_code=ANY($3::text[]))) ORDER BY kind`,
[request.id, options.parkedOnly === true, [...options.failedCodes ?? []]]);
if (!tracked.length) return null;
- const hostId = existingLocalHostId();
+ const hostId = existingHostIdFor(engine);
if (!hostId) throw unregisteredHost(sourceId, requestId);
return engine.transaction(async tx => {
const refusal = await storedAuthorityRefusal(tx, request, sourceId);
@@ -254,7 +254,7 @@ export async function retryEmbeddingEffect(engine: BrainEngine, sourceId: string
`Request ${requestId} in source ${sourceId} has no single embedding effect and no parked Git or withdrawal effect, so nothing was queued. Check that the request_id is the one from the write receipt and that ${sourceId} is the source it was written to.`,
{ fix: receiptFix(requestId) });
const request = requests[0];
- const hostId = existingLocalHostId();
+ const hostId = existingHostIdFor(engine);
if (!hostId) throw unregisteredHost(sourceId, requestId);
const config = await loadConfigWithEngine(engine, baseConfig);
const configuredSignature = config?.embedding_model && config.embedding_dimensions
diff --git a/src/core/persistence/effect-settle.ts b/src/core/persistence/effect-settle.ts
index 0c6886c115..19302388ee 100644
--- a/src/core/persistence/effect-settle.ts
+++ b/src/core/persistence/effect-settle.ts
@@ -35,7 +35,7 @@ import { computePlanHash } from '../consent.ts';
import { execFileBounded } from '../bounded-child-exec.ts';
import { gitChildEnv } from '../git-env.ts';
import { digest } from './digest.ts';
-import { existingLocalHostId } from './identity.ts';
+import { existingHostIdFor } from './identity.ts';
import { guardEffectSource } from './effect-recovery.ts';
import { storedAuthorityRefusal } from './effect-retry.ts';
import { getWorktreeBinding, type WorktreeBinding } from './ownership.ts';
@@ -168,7 +168,7 @@ export async function settleEffects(engine: BrainEngine, input: SettleEffectsInp
'A retired effect is un-settled like any other: preview --unsettle with the same selector, without --retire.', { fix: statusFix(sourceId) });
if (apply && !input.expect) throw opError('invalid_params', 'settle-effects --apply needs --expect <plan_hash> from its preview.',
'Run the preview (--dry-run), show the user the plan, and run the apply_command it prints after they agree.', { fix: statusFix(sourceId) });
- const hostId = existingLocalHostId();
+ const hostId = existingHostIdFor(engine);
if (!hostId) throw opError('permission_denied', 'Settling effects requires the registered local CLI host.',
`This machine has no registered gbrain host identity, so it cannot settle effects of source ${sourceId}; nothing changed. Run it on the brain host that owns ${sourceId}.`, { fix: statusFix(sourceId) });
const selector = requestId !== undefined ? ['--request-id', requestId] : ['--parked-code', parkedCode!];
diff --git a/src/core/persistence/facts-maintenance.ts b/src/core/persistence/facts-maintenance.ts
index 084e871cea..ad7bb918eb 100644
--- a/src/core/persistence/facts-maintenance.ts
+++ b/src/core/persistence/facts-maintenance.ts
@@ -21,7 +21,7 @@ import { authorizeStoredRequest, authorizeWrite, submissionAuthority } from './a
import { authorizePageVisibility } from './page-visibility.ts';
import { initializeLocalPersistence } from './page-mutations.ts';
import { prepareFileTarget } from './page-prepare.ts';
-import { currentVerifiedLocalWriter, localHostId } from './identity.ts';
+import { currentVerifiedLocalWriter, hostIdFor } from './identity.ts';
import { getWorktreeBinding, managedPersistenceEnabled, probeWorktreeWriter, type WorktreeBinding } from './ownership.ts';
import { authorizeFactsBackstop } from './effect-facts.ts';
import { admitWriteInTransaction, getWriteRequest, getWriteRequestById, receiptFor } from './journal.ts';
@@ -291,7 +291,7 @@ export async function prepareManagedFactsSession(ctx: FactsBackstopCtx,
if (binding.state !== 'active' || !binding.owner_host_id) throw opError('owner_unavailable', 'The canonical fact writer is unavailable; extraction has not started.',
`Source ${ctx.sourceId}'s canonical worktree is ${binding.state}, not active, so facts cannot be published yet. Check writer status and extract again once the owner is active.`,
{ fix: ownerStatusFix(ctx.sourceId) });
- if (binding.owner_host_id === localHostId()) {
+ if (binding.owner_host_id === hostIdFor(engine)) {
if (!await probeWorktreeWriter(binding, engine)) throw opError('writer_lock_unavailable', 'The canonical fact writer is busy; extraction has not started.',
`Another write holds source ${ctx.sourceId}'s canonical writer. Nothing was admitted, so run the extraction again once the writer is idle (the same request_id is safe).`,
{ fix: ownerStatusFix(ctx.sourceId) });
diff --git a/src/core/persistence/filesystem-guard.ts b/src/core/persistence/filesystem-guard.ts
index 63a4d368f6..0b3b98b3ff 100644
--- a/src/core/persistence/filesystem-guard.ts
+++ b/src/core/persistence/filesystem-guard.ts
@@ -1,4 +1,4 @@
-import { localHostId } from './identity.ts';
+import { hostIdFor } from './identity.ts';
import { AsyncLocalStorage } from 'node:async_hooks';
import { basename, dirname, isAbsolute, relative, resolve, sep } from 'node:path';
import { OperationError } from '../ops/contract.ts';
@@ -29,7 +29,7 @@ export async function refreshManagedFilesystemRoots(engine: SqlEngine, databaseP
// Rows are deduplicated by filesystem identity in recordManagedRoots, never by the stored spelling (#7203).
const rows = await engine.executeRaw<ManagedRootRecord>(`SELECT h.local_path,s.source_id,s.source_incarnation,s.worktree_id,s.topology_generation
FROM persistence_host_bindings h JOIN persistence_source_bindings s ON s.worktree_id=h.worktree_id WHERE h.host_id=$1::uuid
- UNION SELECT local_path,id,incarnation,NULL,NULL FROM sources WHERE local_path IS NOT NULL`, [localHostId()], { signal });
+ UNION SELECT local_path,id,incarnation,NULL,NULL FROM sources WHERE local_path IS NOT NULL`, [hostIdFor(engine)], { signal });
signal?.throwIfAborted();
// #7630: a relative local_path (a legacy ".") names whatever directory gbrain runs from; it is never a managed root.
const owned = rows.filter(row => isAbsolute(row.local_path));
diff --git a/src/core/persistence/group-publish.ts b/src/core/persistence/group-publish.ts
index 7f4eaeafd3..fd04fa0dad 100644
--- a/src/core/persistence/group-publish.ts
+++ b/src/core/persistence/group-publish.ts
@@ -37,7 +37,7 @@ import { relative, sep } from 'node:path';
import type { BrainEngine } from '../engine.ts';
import { OperationError } from '../ops/contract.ts';
import { authorizeStoredRequest, storedAuthorizationReads } from './authority.ts';
-import { localHostId } from './identity.ts';
+import { hostIdFor } from './identity.ts';
import { acquireWorktree, acquireWorktreeShared, getWorktreeBinding, guardOwnership, joinWorktreeLease, MANAGED_MODE_SQL } from './ownership.ts';
import { isLockOpenFailure, type NativeLockHandle } from './native-lock.ts';
import { awaitLaneBegin, awaitLaneTurn, LaneAbort, laneApplyBegin, laneClaimed, laneFinished, lanePolicy, stepDownLanes, type LaneState } from './sync-lanes.ts';
@@ -246,7 +246,7 @@ export type TransactionRunner = <T>(fn: (tx: BrainEngine) => Promise<T>) => Prom
/** #5984 Phase 4.5: foreground writes publishing beside this process's lane groups, until their recovery record is cleared. */
const publishingBeside = new Set<string>();
-export async function publishGroup(engine: BrainEngine, rows: WriteRequest[], prepared: PreparedMutation[], hostId = localHostId(),
+export async function publishGroup(engine: BrainEngine, rows: WriteRequest[], prepared: PreparedMutation[], hostId = hostIdFor(engine),
hooks: GroupHooks = {}, lane: LaneState | null = null, transaction: TransactionRunner = fn => publicationTransaction(engine, fn)): Promise<GroupPublication> {
const head = rows[0];
const none: GroupPublication = { done: null, requeued: [] };
@@ -462,7 +462,7 @@ export async function publishGroup(engine: BrainEngine, rows: WriteRequest[], pr
try {
const charged = await chargedInterruption(engine, row, error);
if (charged) await faultPoint('persistence:recovery_interruption_charged', { requestId: row.request_id, writeId: row.id, sourceId: row.source_id, operation: row.operation, ...chargedInterruptionDetail(transientInterruption(error), error) });
- const failure = charged?.failure ? withAttempt(charged.failure, 'publication') : undefined;
+ const failure = charged?.failure ? withAttempt(charged.failure, 'publication', engine) : undefined;
await markRecovering(engine, row, failure ? 'publication_failed' : 'publication_not_started', failure);
const recovered = await recoverPublication(engine, row.id, hostId, true, failure, true);
if (!charged && recovered.state === 'queued' && !recovered.recovery) requeued.push(row.id);
@@ -493,7 +493,7 @@ function seam(name: PublicationBoundary, row: WriteRequest): Promise<void> {
* released is taken back first; a request the group left recovering or that
* another worker now holds is returned as it stands.
*/
-export async function publishSingleWrite(engine: BrainEngine, row: WriteRequest, prepared: PreparedMutation, hostId = localHostId(), hooks: GroupHooks = {},
+export async function publishSingleWrite(engine: BrainEngine, row: WriteRequest, prepared: PreparedMutation, hostId = hostIdFor(engine), hooks: GroupHooks = {},
transaction?: TransactionRunner): Promise<WriteRequest> {
const single: PublicationHooks = hooks.projectionPending ? { projectionPending: hooks.projectionPending } : {};
if (engine.kind !== 'postgres' || !singleWrite(row) || !groupable(row, prepared) || !await writeSwitchOn(engine, 'single_write_group').catch(() => true)) {
@@ -594,7 +594,7 @@ async function settleCulprit(engine: BrainEngine, rows: WriteRequest[], culprit:
export async function completeGroup(tx: BrainEngine, rows: WriteRequest[], outcomes: Record<string, unknown>[]): Promise<WriteRequest[]> {
const ids = rows.map(row => row.id);
const keys = [...new Set(['brain', ...rows.map(row => principalKey(requestPrincipal(row))), `worktree:${rows[0]!.worktree_id}`])].sort();
- const stamp = writerStamp();
+ const stamp = writerStamp({ engine: tx });
const [, , completed] = await pipelined(tx, [
() => tx.executeRaw(ENSURE_COUNTERS_SQL, [keys]),
() => tx.executeRaw(LOCK_COUNTERS_SQL, [keys]),
diff --git a/src/core/persistence/head-blocker.ts b/src/core/persistence/head-blocker.ts
index 19c663e7a5..cc680bb65e 100644
--- a/src/core/persistence/head-blocker.ts
+++ b/src/core/persistence/head-blocker.ts
@@ -261,8 +261,8 @@ export async function describeHostConsumer(engine: BrainEngine, opts: { signal?:
const status = persistenceConsumerStatus(engine) as { state: string; consumer_election?: { mode: string } };
const mode = status.consumer_election?.mode ?? (status.state === 'open' ? 'full' : null);
if (mode === 'full' || mode === 'promoted') return `self(${mode})`;
- const { existingLocalHostId } = await import('./identity.ts');
- const host = existingLocalHostId();
+ const { existingHostIdFor } = await import('./identity.ts');
+ const host = existingHostIdFor(engine);
const { listHostConsumers } = await import('./consumer-heartbeat.ts');
const rows = host ? await listHostConsumers(engine, host, opts) : [];
const owner = rows.find(row => !row.self && (row.mode === 'full' || row.mode === 'promoted') && row.liveness === 'live');
diff --git a/src/core/persistence/identity.ts b/src/core/persistence/identity.ts
index 70803edb05..6c158d160f 100644
--- a/src/core/persistence/identity.ts
+++ b/src/core/persistence/identity.ts
@@ -11,6 +11,8 @@ import { readFix } from '../ops/op-fix.ts';
import { sha256 } from './digest.ts';
import type { Principal, SqlEngine } from './model.ts';
import { acquireNativeLock } from './native-lock.ts';
+import { engineKey } from '../engine-key.ts';
+import { embeddedHostId, embeddedSettingsRecord, isEmbeddedEngine } from '../embedded-engine.ts';
export interface LocalRegistration { id: string; credential: string; lane: 'cli' | 'stdio'; }
export interface LocalGrant { sourceIds: string[]; operations: string[] | null; scopes: string[]; slugPrefixes: string[] | null; }
@@ -115,6 +117,59 @@ export function localHostIdentity(): LocalHostIdentity {
export function existingLocalHostId(): string | null {
return readHostIdentity(join(persistenceHome(), 'host.json'), false)?.id ?? null;
}
+
+const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
+const settingsInvalid = (setting: string, why: string) => opError('engine_settings_invalid', `The ${setting} setting is invalid.`, `${why} Nothing was opened or registered.`);
+/** Host ids given for an engine (`openEngine`'s `host.id`), keyed by the engine behind a transaction or view. */
+const engineHostIds = new WeakMap<object, string>();
+/** Records the host id `engine` claims and publishes under; `hostIdFor` answers it from then on and no host.json is read or minted for it. */
+export function setEngineHostId(engine: object, id: string): void {
+ if (typeof id !== 'string' || !UUID.test(id)) throw settingsInvalid('host.id', 'The persistence tables store host ids as uuid, so host.id must be a UUID.');
+ engineHostIds.set(engineKey(engine), id.toLowerCase());
+}
+function givenHostId(engine: object): string | undefined {
+ return engineHostIds.get(engineKey(engine)) ?? embeddedHostId(engine);
+}
+function engineHostMissing(): OperationError {
+ return opError('engine_host_missing', 'This engine was opened from settings with no host identity.',
+ 'An engine opened with openEngine publishes and claims work only under the host id its host gave at open, and it never reads or mints host.json under the home directory, so nothing that needs a host identity ran. Reopen it with host.id set to a UUID.');
+}
+/**
+ * The host id `engine` claims, publishes and owns worktrees under: the id it was opened with (`openEngine`'s `host.id`,
+ * `setEngineHostId`), else this process's file identity `localHostId()`, exactly as before. An embedded engine with no
+ * id refuses `engine_host_missing` and never mints a host.json. With no engine, the file identity.
+ */
+export function hostIdFor(engine?: object): string {
+ if (!engine) return localHostId();
+ const given = givenHostId(engine);
+ if (given) return given;
+ if (isEmbeddedEngine(engine)) throw engineHostMissing();
+ return localHostId();
+}
+/** `hostIdFor` without minting: for an engine with no given id, the existing file identity or null (`existingLocalHostId()`). */
+export function existingHostIdFor(engine?: object): string | null {
+ if (!engine) return existingLocalHostId();
+ const given = givenHostId(engine);
+ if (given) return given;
+ if (isEmbeddedEngine(engine)) throw engineHostMissing();
+ return existingLocalHostId();
+}
+/** The `persistence_home` a consumer heartbeat row records for an identity given at open (no file behind it). */
+export const EMBEDDED_PERSISTENCE_HOME = 'embedded';
+/** True for a heartbeat `host_json_path` / `persistence_home` value that records an identity given at open, never a path. */
+export function isEmbeddedIdentityValue(value: unknown): boolean {
+ return typeof value === 'string' && value.startsWith('embedded');
+}
+/**
+ * The identity paths a consumer heartbeat row carries for `engine`: this process's host.json, its persistence home and
+ * where it was minted; for an engine whose identity was given at open, the sentinel `embedded:<host-id>` and
+ * `embedded` (no file exists, and none is minted).
+ */
+export function hostIdentityPathsFor(engine: object): { host_json_path: string; persistence_home: string; minted_under: Record<string, unknown> | null } {
+ if (givenHostId(engine) || isEmbeddedEngine(engine)) return { host_json_path: `embedded:${hostIdFor(engine)}`, persistence_home: EMBEDDED_PERSISTENCE_HOME, minted_under: null };
+ const id = localHostIdentity();
+ return { host_json_path: id.path, persistence_home: id.persistence_home, minted_under: id.minted_under };
+}
/**
* GBRA-156: one operation invocation (a CLI shared operation, an MCP tool call) reads the brain identity and verifies each
* local writer credential once for its pre-submission checks; `withRequestIdentityMemo` scopes those reads to that one
@@ -153,6 +208,13 @@ async function readBrainIdentity(engine: SqlEngine): Promise<string> {
return brain.brain_id;
}
export async function registerLocalWriter(engine: BrainEngine, lane: 'cli' | 'stdio', grant = defaultGrant(), replace = false): Promise<LocalRegistration> {
+ if (isEmbeddedEngine(engine)) {
+ if (replace) throw new OperationError('writer_registration_required', 'A writer given at open is not replaced here.',
+ 'This engine was opened from settings, so its local writer is the value its host passed (settings.writer); gbrain never mints or rotates a credential file for it. Revoke the registration and reopen the engine with a new writer id and credential.');
+ const local = embeddedLocalWriter(engine, lane);
+ await registerLocalWriterValue(engine, local, grant);
+ return local;
+ }
const brain = await brainIdentity(engine);
const path = join(persistenceHome(), `${brain}.${lane}.json`);
if (!replace) return ensureLocalWriter(engine, lane, grant, path);
@@ -173,17 +235,47 @@ async function ensureLocalWriter(engine: BrainEngine, lane: 'cli' | 'stdio', gra
async function ensureLocalWriterRow(engine: BrainEngine, lane: 'cli' | 'stdio', grant: LocalGrant, path: string): Promise<{ local: LocalRegistration; existing?: LocalWriterRow }> {
const local = privateJson<LocalRegistration>(path, () => ({ id: randomUUID(), credential: randomBytes(32).toString('hex'), lane }));
if (local.lane !== lane || typeof local.credential !== 'string' || typeof local.id !== 'string') throw invalidIdentityFile('Local writer registration is invalid.', path, `${lane} writer registration`);
+ const existing = await ensureRegistrationRow(engine, local, grant, () => credentialMismatch(path, local.id, lane));
+ return { local, ...(existing ? { existing } : {}) };
+}
+/** Inserts `local`'s row unless it exists; a revoked row, or one with another lane or credential, refuses. Returns the row it read. */
+async function ensureRegistrationRow(engine: SqlEngine, local: LocalRegistration, grant: LocalGrant, mismatch: () => OperationError): Promise<LocalWriterRow | undefined> {
const [existing] = await engine.executeRaw<LocalWriterRow>(
'SELECT revoked_at,credential_hash,lane,grant_ceiling FROM persistence_local_writers WHERE id=$1::uuid', [local.id]);
if (existing?.revoked_at != null) throw new OperationError('permission_denied', 'This local writer registration was revoked.', 'Explicitly register a new writer to authorize future work.');
- if (existing && (existing.lane !== lane || existing.credential_hash !== sha256(local.credential))) throw credentialMismatch(path, local.id, lane);
+ if (existing && (existing.lane !== local.lane || existing.credential_hash !== sha256(local.credential))) throw mismatch();
// A registered writer is left as it is (the insert would conflict and do nothing).
if (!existing) {
await engine.executeRaw(`INSERT INTO persistence_local_writers(id,lane,credential_hash,grant_ceiling)
- VALUES($1::uuid,$2,$3,$4::text::jsonb) ON CONFLICT(id) DO NOTHING`, [local.id, lane, sha256(local.credential), JSON.stringify(grant)]);
+ VALUES($1::uuid,$2,$3,$4::text::jsonb) ON CONFLICT(id) DO NOTHING`, [local.id, local.lane, sha256(local.credential), JSON.stringify(grant)]);
forgetRequestIdentity();
}
- return { local, ...(existing ? { existing } : {}) };
+ return existing;
+}
+/**
+ * Registers a local writer whose credential the host holds as a value: the row in `persistence_local_writers` and no
+ * file. Idempotent; a different credential or lane under the same id refuses `permission_denied`, and a revoked
+ * registration is never replaced. `openEngine` records `settings.writer` so that engine's writes use it; nothing an
+ * MCP or HTTP caller sends reaches this function.
+ */
+export async function registerLocalWriterValue(engine: SqlEngine, local: LocalRegistration, grant: LocalGrant = defaultGrant()): Promise<void> {
+ assertLocalWriterValue(local);
+ await ensureRegistrationRow(engine, local, grant, () => opError('permission_denied', 'Local writer credential does not match this registration.',
+ `Registration ${local.id} exists in this brain's database with another credential or lane, so nothing was registered. Pass that registration's own credential and lane, or register a new id.`,
+ { fix: registrationsFix() }));
+}
+/** A writer value is a UUID id, a credential of at least 32 characters and a lane, cli or stdio. */
+export function assertLocalWriterValue(local: LocalRegistration): void {
+ if (!local || typeof local.id !== 'string' || !UUID.test(local.id)) throw settingsInvalid('writer.id', 'A local writer id is a UUID.');
+ if (typeof local.credential !== 'string' || local.credential.length < 32) throw settingsInvalid('writer.credential', 'A local writer credential is a string of at least 32 characters.');
+ if (local.lane !== 'cli' && local.lane !== 'stdio') throw settingsInvalid('writer.lane', 'A local writer lane is cli or stdio.');
+}
+/** The writer an embedded engine was opened with, for `lane`; never a credential file. */
+function embeddedLocalWriter(engine: object, lane: 'cli' | 'stdio'): LocalRegistration {
+ const writer = embeddedSettingsRecord(engine)?.writer;
+ if (!writer || writer.lane !== lane) throw new OperationError('writer_registration_required', `This engine was opened from settings with no ${lane} writer.`,
+ `An engine opened with openEngine never reads a credential file from the home directory; its unauthenticated writes use the writer its host passed (settings.writer with lane ${lane}). Reopen it with that writer, or call with an authenticated principal.`);
+ return { id: writer.id, credential: writer.credential, lane: writer.lane };
}
/**
* #6712 PR 4b: `registerLocalWriter(engine, lane)` and `withVerifiedLocalRegistration` in one read of the registration:
@@ -191,6 +283,10 @@ async function ensureLocalWriterRow(engine: BrainEngine, lane: 'cli' | 'stdio',
* the persistence identity when the caller read it already.
*/
export async function withRegisteredLocalWriter<T>(engine: BrainEngine, lane: 'cli' | 'stdio', run: (writer: VerifiedLocalWriter) => Promise<T>, brainId?: string): Promise<T> {
+ if (isEmbeddedEngine(engine)) {
+ const local = await registerLocalWriter(engine, lane);
+ return withVerifiedLocalRegistration(engine, local, run);
+ }
const brain = brainId ?? await brainIdentity(engine);
const { local, existing } = await ensureLocalWriterRow(engine, lane, defaultGrant(), join(persistenceHome(), `${brain}.${lane}.json`));
const writer = existing ? verifiedFromRow(local, existing) : await verifyLocalWriter(engine, local);
@@ -243,6 +339,12 @@ async function rotateLocalWriter(engine: BrainEngine, lane: 'cli' | 'stdio', gra
}
}
export async function readLocalWriter(engine: SqlEngine, lane: 'cli' | 'stdio'): Promise<LocalRegistration> {
+ if (isEmbeddedEngine(engine)) {
+ const local = embeddedLocalWriter(engine, lane);
+ await registerLocalWriterValue(engine, local);
+ await verifyLocalWriter(engine, local);
+ return local;
+ }
const brain = await brainIdentity(engine);
const path = join(persistenceHome(), `${brain}.${lane}.json`);
if (!existsSync(path)) throw new OperationError('writer_registration_required', 'This installation has no local writer registration.', 'Register it locally, or use authenticated HTTP access.');
diff --git a/src/core/persistence/import-mutations.ts b/src/core/persistence/import-mutations.ts
index afd54b13d0..d4a4952317 100644
--- a/src/core/persistence/import-mutations.ts
+++ b/src/core/persistence/import-mutations.ts
@@ -6,7 +6,7 @@ import { isImageFilePath, type ImportResult } from '../import-file.ts';
import { loadConfig } from '../config.ts';
import { opError, OperationError, type OperationContext } from '../ops/contract.ts';
import { currentSubmissionAuthority } from '../minions/submission-authority.ts';
-import { currentVerifiedLocalWriter, localHostId } from './identity.ts';
+import { currentVerifiedLocalWriter, hostIdFor } from './identity.ts';
import { getWorktreeBinding } from './ownership.ts';
import { SCREENING_SHARED_READS, batchSharedReads, emitFenceNotice, initializeLocalPersistence, pendingAwareResponse, preparePageAdmission, requestPrincipalForContext, withBatchAdmission,
withLiveSearchable } from './page-mutations.ts';
@@ -101,7 +101,7 @@ export async function importManagedFiles(engine: BrainEngine, files: readonly Ma
const fail = (i: number, reason: unknown) => { settled[i] = { status: 'rejected', reason }; };
const sourceId = opts.sourceId ?? 'default';
const binding = await getWorktreeBinding(engine, sourceId);
- const unowned = !binding?.local_path || binding.owner_host_id !== localHostId() || binding.state !== 'active'
+ const unowned = !binding?.local_path || binding.owner_host_id !== hostIdFor(engine) || binding.state !== 'active'
? opError('owner_unavailable', 'Managed import must run on the active canonical owner for the selected source.',
`This host is not the active owner of source ${sourceId}, so nothing was imported. Run the import on the owner host that writer status names, or wait until its owner is active.`,
{ fix: readFix(`Shows source ${sourceId}'s owner host and state, read-only.`, { argv: ['gbrain', 'sources', 'writer', 'status', '--source', sourceId, '--json'] }) }) : null;
diff --git a/src/core/persistence/import-prepare.ts b/src/core/persistence/import-prepare.ts
index e03d188260..3b082a765e 100644
--- a/src/core/persistence/import-prepare.ts
+++ b/src/core/persistence/import-prepare.ts
@@ -25,7 +25,7 @@ import { FRONTMATTER_HEAD_MAX_BYTES, readPageBodyPolicy, type PageBodyPolicy } f
import { PAGE_MAX_BYTES } from '../page-size-policy.ts';
import { assertKnowledgePublicationAllowed } from '../shared-skills/knowledge-guard.ts';
import { getWorktreeBinding } from './ownership.ts';
-import { localHostId } from './identity.ts';
+import { hostIdFor } from './identity.ts';
import { sha256 } from './digest.ts';
import { screeningPath } from './screening-paths.ts';
import { isReservedSkillBundlePath } from '../skill-reserved-paths.ts';
@@ -168,7 +168,7 @@ export async function assertImportPaths(engine: BrainEngine, sourceId: string, r
const sources = await engine.executeRaw<{ id: string; local_path: string | null; worktree_path: string | null; relative_path: string | null }>(
`SELECT s.id,s.local_path,h.local_path AS worktree_path,b.relative_path FROM sources s
LEFT JOIN persistence_source_bindings b ON b.source_id=s.id AND b.source_incarnation=s.incarnation
- LEFT JOIN persistence_host_bindings h ON h.worktree_id=b.worktree_id AND h.host_id=$1::uuid WHERE NOT s.archived`, [localHostId()]);
+ LEFT JOIN persistence_host_bindings h ON h.worktree_id=b.worktree_id AND h.host_id=$1::uuid WHERE NOT s.archived`, [hostIdFor(engine)]);
for (const source of sources) {
if (source.id === sourceId) continue;
const roots = [source.local_path, source.worktree_path && source.relative_path !== null ? join(source.worktree_path, source.relative_path) : null];
diff --git a/src/core/persistence/journal.ts b/src/core/persistence/journal.ts
index 1a38e333bc..c59299e7fa 100644
--- a/src/core/persistence/journal.ts
+++ b/src/core/persistence/journal.ts
@@ -31,7 +31,7 @@ import { assertGraduationAdmission } from './graduation-custody.ts';
import { schemaAdmissionRefusal } from './schema-admission.ts';
import { CAPACITY_VERIFY } from './capacity-verify.ts';
import { readManagedMode } from './managed-mode.ts';
-import { localHostId } from './identity.ts';
+import { hostIdFor } from './identity.ts';
import { MANAGED_SYNC_PASS_OP } from './sync-pass-row.ts';
import { BACKOFF_ELAPSED } from './transient-retry.ts';
import { segmentWriteScope } from '../page-body/ingest.ts';
@@ -287,7 +287,7 @@ async function prepareAdmission(engine: BrainEngine, input: WriteAdmission, over
const bytes = jsonBytes(input.intent) + jsonBytes(input.authority);
const terminalBytes = Math.max(input.terminalReservation ?? 0, receiptReservation(input));
if (!Number.isSafeInteger(terminalBytes) || terminalBytes < 1024) throw new TypeError('Invalid terminal receipt reservation.');
- const stamp = writerStamp();
+ const stamp = writerStamp({ engine });
const origin = resolveAdmissionOrigin(input.origin);
// #6741 C: a declared background producer is refused before any receipt when the source's owner fails its verification.
if (input.worktreeId && declaredBackground(input.origin)) await assertBackgroundOwner(engine, input.sourceId, ownerStatusFix);
@@ -370,7 +370,7 @@ export async function admitWriteGroupInTransaction(tx: BrainEngine, inputs: Writ
|| input.operation !== first.operation || (input.targetKind ?? 'page') !== 'page' || (input.protocolVersion ?? 1) !== 1 || digest(input.authority) !== digest(first.authority))) {
throw new TypeError('A group admission requires one source, worktree, principal, operation and authority.');
}
- const stamp = writerStamp();
+ const stamp = writerStamp({ engine: tx });
const items = inputs.map(input => ({ input, requestId: requireUuid(input.requestId ?? randomUUID()), fingerprint: intentDigest(input),
bytes: jsonBytes(input.intent) + jsonBytes(input.authority), terminalBytes: Math.max(input.terminalReservation ?? 0, receiptReservation(input)) }));
assertMutationProtocol({ target_kind: 'page', protocol_version: 1 });
@@ -969,7 +969,7 @@ export async function completeWrite(tx: SqlEngine, row: WriteRequest, state: 'co
`Another owner pass claimed request ${row.request_id} in source ${row.source_id} before this pass recorded its outcome, so this pass's completion was discarded; the current claim records the final outcome. Inspect the request with the command in fix instead of resubmitting it.`,
{ fix: requestInspectFix(row) });
// Only publication stamps the consumer; failures, cancellations and conflicts leave it unset.
- const stamp = writerStamp();
+ const stamp = writerStamp({ engine: tx });
// #6007: one statement sizes the queued effects, checks the terminal reservation, completes the row and
// releases its outstanding counters; no row means the encoding exceeds the reservation and nothing changed.
const resultBytes = jsonBytes(outcome) + jsonBytes(current.authority) + 1024 + Buffer.byteLength(error?.message ?? '') + (error?.detail ? jsonBytes(error.detail) : 0);
@@ -1106,7 +1106,7 @@ export async function sweepSegmentStorage(engine: BrainEngine): Promise<void> {
if (!row?.present) return;
if (!await readManagedMode(engine)) { await engine.sweepSegments({ expireStagings: true }); return; }
const owned = await engine.executeRaw<{ source_id: string }>(`SELECT s.source_id FROM persistence_source_bindings s
- JOIN persistence_worktrees w ON w.id=s.worktree_id WHERE w.owner_host_id=$1::uuid AND w.state='active'`, [localHostId()]);
+ JOIN persistence_worktrees w ON w.id=s.worktree_id WHERE w.owner_host_id=$1::uuid AND w.state='active'`, [hostIdFor(engine)]);
for (const { source_id: sourceId } of owned) {
const writes = await segmentWriteScope(engine, sourceId);
await writes(exec => exec.sweepSegments({ sourceId, expireStagings: true }));
diff --git a/src/core/persistence/owner-activity.ts b/src/core/persistence/owner-activity.ts
index 7a96da597c..5b2f85ad02 100644
--- a/src/core/persistence/owner-activity.ts
+++ b/src/core/persistence/owner-activity.ts
@@ -22,7 +22,7 @@
*/
import type { BrainEngine } from '../engine.ts';
import { CONSUMER_LAPSED_MS } from './consumer-heartbeat.ts';
-import { existingLocalHostId } from './identity.ts';
+import { existingHostIdFor } from './identity.ts';
/** An owner with no live consumer and no activity for this long reads as stale. */
export const OWNER_STALE_MS = 24 * 60 * 60 * 1000;
@@ -57,7 +57,7 @@ export async function ownerActivity(engine: BrainEngine, worktreeIds: readonly s
FROM persistence_worktrees w
WHERE w.id::text = ANY($1::text[]) AND w.owner_host_id IS NOT NULL`, [ids, CONSUMER_LAPSED_MS],
{ signal: engine.kind === 'postgres' ? opts.signal : undefined });
- const local = existingLocalHostId();
+ const local = existingHostIdFor(engine);
for (const row of rows) {
const lastActive = row.last_active === null ? null : new Date(row.last_active).toISOString();
const self = local === row.owner_host_id;
diff --git a/src/core/persistence/owner-verification.ts b/src/core/persistence/owner-verification.ts
index c8958d7b75..2fbde41b8e 100644
--- a/src/core/persistence/owner-verification.ts
+++ b/src/core/persistence/owner-verification.ts
@@ -14,7 +14,7 @@
import type { Action } from '../agent-output.ts';
import { OperationError } from '../ops/contract.ts';
import type { SqlEngine } from './model.ts';
-import { existingLocalHostId } from './identity.ts';
+import { existingHostIdFor } from './identity.ts';
import { getWorktreeBinding, type WorktreeBinding } from './ownership.ts';
import { assertPhysicalRoot } from './physical-root.ts';
import { backgroundOwnerCheck, backgroundOwnerUnverified } from './admission-origin.ts';
@@ -41,7 +41,7 @@ export function verifyOwnerRoot(binding: Pick<WorktreeBinding, 'worktree_id' | '
/** Refuses a background admission for a source whose owner on this host fails the verification (cached per background run). */
export async function assertBackgroundOwner(engine: SqlEngine, sourceId: string, ownerStatusFix: (sourceId: string) => Action): Promise<void> {
const refusal = await backgroundOwnerCheck(sourceId, async () => {
- const host = existingLocalHostId();
+ const host = existingHostIdFor(engine);
const binding = await getWorktreeBinding(engine, sourceId, host);
if (!binding || binding.owner_host_id !== host) return null;
const failure = verifyOwnerRoot(binding);
diff --git a/src/core/persistence/ownership.ts b/src/core/persistence/ownership.ts
index 09913ad4fd..610a82ed13 100644
--- a/src/core/persistence/ownership.ts
+++ b/src/core/persistence/ownership.ts
@@ -11,7 +11,7 @@ import { discoverGitRoot } from '../sync-git.ts';
import { cliOptsToProgressOptions, getCliOptions } from '../cli-options.ts';
import type { ProgressOptions } from '../progress.ts';
import { detectManifestScope, storedManifestScope, worktreeManifest, type StoredWorktreeManifest, type WorktreeManifest } from './worktree-manifest.ts';
-import { localHostId } from './identity.ts';
+import { hostIdFor } from './identity.ts';
import { repairWedgedReservation, resolveCoordinationLock } from './coordination-lock.ts';
import type { SqlEngine, WriteRequest } from './model.ts';
import { acquireNativeLock, tryAcquireNativeLock, type NativeLockHandle } from './native-lock.ts';
@@ -82,15 +82,15 @@ export const WORKTREE_BINDING_SQL = `SELECT s.source_id,s.source_incarnation,s.w
JOIN persistence_worktrees w ON w.id=s.worktree_id
LEFT JOIN persistence_host_bindings h ON h.worktree_id=w.id AND h.host_id=$2::uuid
WHERE s.source_id=$1`;
-export async function getWorktreeBinding(engine: SqlEngine, sourceId: string, hostId: string | null = localHostId()): Promise<WorktreeBinding | null> {
+export async function getWorktreeBinding(engine: SqlEngine, sourceId: string, hostId: string | null = hostIdFor(engine)): Promise<WorktreeBinding | null> {
const [row] = await engine.executeRaw<WorktreeBinding>(WORKTREE_BINDING_SQL, [sourceId, hostId]);
return row ?? null;
}
/** `automatic` is only the ordinary first-write claim; the writer admin lock never blocks it. */
-export async function claimWorktree(engine: BrainEngine, sourceId: string, path: string, hostId = localHostId(), expectedAdminState?: string,
+export async function claimWorktree(engine: BrainEngine, sourceId: string, path: string, hostId = hostIdFor(engine), expectedAdminState?: string,
options: { automatic?: boolean } = {}): Promise<WorktreeBinding> {
if(await managedPersistenceEnabled(engine)) {
- if(hostId!==localHostId()) throw opError('permission_denied','A source can be claimed only by the local registered host.',
+ if(hostId!==hostIdFor(engine)) throw opError('permission_denied','A source can be claimed only by the local registered host.',
`Source ${sourceId} can only be claimed from the host that will own its checkout; nothing was claimed. Run the claim in a terminal on that host after reviewing writer status there.`,
{ fix: writerStatusFix(sourceId) });
const { runManagedSourceLifecycle }=await import('./source-lifecycle.ts');
@@ -237,7 +237,7 @@ async function lockWorktree(binding: WorktreeBinding, waitMs: number, signal: Ab
throw error;
}
if (!(error instanceof OperationError) || error.detail !== 'physical_root_device_changed') throw error;
- if (engine && await restampPhysicalRoot(engine, binding, localHostId())) { assertPhysicalRoot(binding.local_path, identity); return lock; }
+ if (engine && await restampPhysicalRoot(engine, binding, hostIdFor(engine))) { assertPhysicalRoot(binding.local_path, identity); return lock; }
const why = !engine ? 'this caller cannot verify database ownership'
: readPhysicalRootStamp(binding.local_path)?.birth === '0' ? 'this filesystem reports no birth time'
: 'database ownership of this checkout did not verify';
@@ -324,7 +324,7 @@ export interface WriterTransferOptions {
/** #5914: `--confirm-relocated-root`, a self-transfer of a directory recreated at the same path (inode/birth waived; everything else must agree). */
relocated?: boolean;
}
-export async function prepareWriterTransfer(engine: BrainEngine, sourceId: string, hostId = localHostId(), expectedAdminState?: string,
+export async function prepareWriterTransfer(engine: BrainEngine, sourceId: string, hostId = hostIdFor(engine), expectedAdminState?: string,
opts: WriterTransferOptions = {}): Promise<{ worktree_id: string; owner_epoch: string; manifest: StoredWorktreeManifest }> {
const binding = await getWorktreeBinding(engine, sourceId, hostId);
if (!binding || binding.owner_host_id !== hostId || !binding.local_path) throw opError('permission_denied', 'Only the current owner can prepare this transfer.',
@@ -376,7 +376,7 @@ export async function prepareWriterTransfer(engine: BrainEngine, sourceId: strin
* under the native coordination lock and the worktree row's FOR UPDATE. The epoch is kept, so an accept bound to it
* meets an active worktree and refuses `writer_transfer_conflict`; the owner may prepare again.
*/
-export async function cancelWriterTransfer(engine: BrainEngine, sourceId: string, expectedEpoch: string, hostId = localHostId(), expectedAdminState?: string,
+export async function cancelWriterTransfer(engine: BrainEngine, sourceId: string, expectedEpoch: string, hostId = hostIdFor(engine), expectedAdminState?: string,
opts: { dryRun?: boolean } = {}): Promise<{ worktree_id: string; owner_epoch: string; state: string; prepared_at: string | null; cancellable: boolean }> {
const binding = await getWorktreeBinding(engine, sourceId, hostId);
const notOwner = () => opError('permission_denied', 'Only the current owner can cancel this transfer.',
@@ -410,7 +410,7 @@ export async function cancelWriterTransfer(engine: BrainEngine, sourceId: string
});
} finally { await lock.release(); }
}
-export async function acceptWriterTransfer(engine: BrainEngine, sourceId: string, path: string, expectedEpoch: string, expectedManifest: string, hostId = localHostId(), expectedAdminState?: string,
+export async function acceptWriterTransfer(engine: BrainEngine, sourceId: string, path: string, expectedEpoch: string, expectedManifest: string, hostId = hostIdFor(engine), expectedAdminState?: string,
opts: WriterTransferOptions = {}): Promise<{ content_receipts: ContentReceiptRebind[] }> {
const root = realpathSync(resolve(path));
const binding = await getWorktreeBinding(engine, sourceId, hostId);
diff --git a/src/core/persistence/page-mutations.ts b/src/core/persistence/page-mutations.ts
index db14f3647f..b6b4a96601 100644
--- a/src/core/persistence/page-mutations.ts
+++ b/src/core/persistence/page-mutations.ts
@@ -27,7 +27,7 @@ import { dataFrontmatter, dumpFrontmatterYaml } from '../data-frontmatter.ts';
import { throwIfHeld } from '../trust/gate-outcomes.ts';
import { admitWrite, assertPageRequestIdentity, assertReplayIntent, getWriteRequest, intentDigest, type WriteAdmission } from './journal.ts';
import { submissionAuthority, authorizeStoredRequest } from './authority.ts';
-import { currentVerifiedLocalWriter, localHostId, readLocalWriter, registerLocalWriter, withVerifiedLocalRegistration } from './identity.ts';
+import { currentVerifiedLocalWriter, hostIdFor, readLocalWriter, registerLocalWriter, withVerifiedLocalRegistration } from './identity.ts';
import type { BrainEngine } from '../engine.ts';
import { claimWorktree, getWorktreeBinding } from './ownership.ts';
import { clientRequestIdOf, parseMutationPrecondition } from './preconditions.ts';
@@ -165,7 +165,7 @@ async function resolveCaptureFile(ctx: OperationContext, sourceId: string, p: Re
delete p.local_file;
const [source] = await ctx.engine.executeRaw<{ local_path: string | null }>('SELECT local_path FROM sources WHERE id=$1', [sourceId]);
const binding = await getWorktreeBinding(ctx.engine, sourceId);
- let root = binding ? binding.owner_host_id === localHostId() && binding.local_path ? join(binding.local_path, binding.relative_path) : null
+ let root = binding ? binding.owner_host_id === hostIdFor(ctx.engine) && binding.local_path ? join(binding.local_path, binding.relative_path) : null
: source?.local_path || (sourceId === 'default' ? await ctx.engine.getConfig('sync.repo_path') : null);
if (root && !isAbsolute(root)) root = null;
let origin: string | null = null;
@@ -498,7 +498,7 @@ export async function preparePageAdmission(ctx: OperationContext,
const root = configuredRoot && isAbsolute(configuredRoot) ? configuredRoot : null;
// Checkout paths belong to a host binding; sources.local_path may name
// another host's original checkout after a verified ownership transfer.
- const localRoot = binding ? binding.owner_host_id === localHostId() && binding.local_path
+ const localRoot = binding ? binding.owner_host_id === hostIdFor(ctx.engine) && binding.local_path
? join(binding.local_path, binding.relative_path) : null : root;
// #7324: a declared db_only page is canonical in the database, so its detach restore publishes database-only even
// where write-through would re-create its file (a managed checkout); assertRestoreOrigin still requires the file gone.
@@ -532,7 +532,7 @@ export async function preparePageAdmission(ctx: OperationContext,
// #5032: this host publishes the canonical file, and on Windows a ':' in its
// name cannot be stored; refuse before admission. Database-only writes pass,
// including read-only mirror sources and pages created while one (#5409).
- if (writeThrough && binding?.owner_host_id === localHostId() && binding.local_path && isWindowsColonTarget(snapshot?.page.source_path ?? `${slug}.md`)
+ if (writeThrough && binding?.owner_host_id === hostIdFor(ctx.engine) && binding.local_path && isWindowsColonTarget(snapshot?.page.source_path ?? `${slug}.md`)
&& !(snapshot && !snapshot.page.source_path && await isUnboundSourcePage(ctx.engine, sourceId, slug))
&& !await sourceMirrorReadOnly(ctx.engine, sourceId)
&& !(snapshot && !snapshot.page.source_path && await isMirrorOnlyPage(ctx.engine, sourceId, slug))
diff --git a/src/core/persistence/prepared-maintenance.ts b/src/core/persistence/prepared-maintenance.ts
index 7261994d51..de537161aa 100644
--- a/src/core/persistence/prepared-maintenance.ts
+++ b/src/core/persistence/prepared-maintenance.ts
@@ -13,7 +13,7 @@ import { fenceOperationError, scanCanonicalFences } from '../fence-repair/refusa
import { fenceCellReadBackProblem, formatFenceDate, parseFactsFence, renderFactsTable, replaceOrInsertFactsFence, type ParsedFact } from '../facts-fence.ts';
import { extractFactsFromFenceText } from '../facts/extract-from-fence.ts';
import { submissionAuthority, authorizeStoredRequest, authorizeWrite } from './authority.ts';
-import { currentVerifiedLocalWriter, localHostId, registerLocalWriter } from './identity.ts';
+import { currentVerifiedLocalWriter, hostIdFor, registerLocalWriter } from './identity.ts';
import { getWorktreeBinding, managedPersistenceEnabled, type WorktreeBinding } from './ownership.ts';
import { checkOwner, ownerUnavailableError } from './owner-refusal.ts';
import { admitWrite, admitWriteInTransaction, assertReplayIntent, getWriteRequest, intentDigest, type WriteAdmission } from './journal.ts';
@@ -111,7 +111,7 @@ export async function maintenancePreflight(engine: BrainEngine, sourceId: string
const writeThrough = !/^(false|0|off|no)$/i.test(await engine.getConfig('sync.write_through') ?? 'true');
const configuredRoot = source.local_path || (sourceId === 'default' ? await engine.getConfig('sync.repo_path') : null);
if (writeThrough && (root || configuredRoot || binding)) {
- const hostId = localHostId();
+ const hostId = hostIdFor(engine);
const owner = checkOwner(binding, source.incarnation, hostId);
if (owner.reason) throw ownerUnavailableError({ sourceId, reason: owner.reason, binding, incarnation: source.incarnation, hostId, remote: false, work: 'maintenance' });
if (root && realpathSync(root) !== realpathSync(join(owner.binding.local_path, owner.binding.relative_path))) {
diff --git a/src/core/persistence/publication-failure.ts b/src/core/persistence/publication-failure.ts
index ed0d755117..2258ada57a 100644
--- a/src/core/persistence/publication-failure.ts
+++ b/src/core/persistence/publication-failure.ts
@@ -358,9 +358,9 @@ export function ownerBuildMismatch(detail: unknown, cliVersion: string): { owner
}
/** Stamps which build, host and stage ran the failed attempt. */
-export function withAttempt(failure: PublicationFailure, stage: PublicationStage): PublicationFailure {
+export function withAttempt(failure: PublicationFailure, stage: PublicationStage, engine?: object): PublicationFailure {
if (!failure.detail) return failure;
- const stamp = writerStamp();
+ const stamp = writerStamp({ engine });
return { ...failure, detail: { ...failure.detail, stage, attempt: { consumer_version: stamp.version, consumer_host_id: stamp.hostId } } };
}
diff --git a/src/core/persistence/reconcile-audit.ts b/src/core/persistence/reconcile-audit.ts
index e248be1329..8daff58960 100644
--- a/src/core/persistence/reconcile-audit.ts
+++ b/src/core/persistence/reconcile-audit.ts
@@ -9,7 +9,7 @@ import { slugifyPath } from '../sync.ts';
import { recordedPathFromFileUri, scannerSlugRootMode } from '../write-through.ts';
import { isWriteTargetContained } from '../path-confine.ts';
import { submissionAuthority } from './authority.ts';
-import { currentVerifiedLocalWriter, existingLocalHostId, readLocalWriter, verifyLocalWriter } from './identity.ts';
+import { currentVerifiedLocalWriter, existingHostIdFor, readLocalWriter, verifyLocalWriter } from './identity.ts';
import { getWorktreeBinding } from './ownership.ts';
import { prepareFileTarget } from './page-prepare.ts';
import { readFix, trustedCliRequired } from '../ops/op-fix.ts';
@@ -49,7 +49,7 @@ export async function auditCanonicalSource(engine: BrainEngine, sourceId: string
"Pass --after exactly as the previous audit's next_after slug, or omit it to start from the first page.");
}
}
- const hostId = existingLocalHostId();
+ const hostId = existingHostIdFor(engine);
const binding = hostId ? await getWorktreeBinding(engine, sourceId, hostId) : null;
if (!binding?.local_path || binding.owner_host_id !== hostId || binding.state !== 'active') {
throw opError('owner_unavailable', 'Read-only drift auditing must run on the active canonical owner.',
diff --git a/src/core/persistence/recovery-resolve.ts b/src/core/persistence/recovery-resolve.ts
index 93cae0a3a8..e5decc8b62 100644
--- a/src/core/persistence/recovery-resolve.ts
+++ b/src/core/persistence/recovery-resolve.ts
@@ -67,7 +67,7 @@ import { flushDirectory } from '../fs-durable.ts';
import { isWriteTargetContained } from '../path-confine.ts';
import { unifiedDiff } from '../skillpack/diff-text.ts';
import { digest, sha256 } from './digest.ts';
-import { localHostId } from './identity.ts';
+import { hostIdFor } from './identity.ts';
import { acquireWorktree, containsPath, getWorktreeBinding, type WorktreeBinding } from './ownership.ts';
import { canonicalFilesystemPath } from './root-registry.ts';
import { completeWrite, getWriteRequestById } from './journal.ts';
@@ -452,7 +452,7 @@ function ownerBinding(binding: WorktreeBinding | null, sourceId: string, hostId:
* each file's private diff (a remote caller's preview never does).
*/
export async function scanStuckRecoveries(engine: BrainEngine, sourceIds: string[], opts: { requestId?: string; artifacts?: boolean; hostId?: string } = {}): Promise<StuckRecoveryScan> {
- const hostId = opts.hostId ?? localHostId();
+ const hostId = opts.hostId ?? hostIdFor(engine);
const scan: StuckRecoveryScan = { items: [], residuals: {}, refused: [], heads: [] };
const residual = (key: string) => { scan.residuals[key] = (scan.residuals[key] ?? 0) + 1; };
for (const sourceId of sourceIds) {
@@ -694,7 +694,7 @@ const changedAgain = (item: StuckRecovery, backupDir: string, command: string) =
export async function resolveStuckRecovery(engine: BrainEngine, item: StuckRecovery, opts: { keep: KeepChoice; previewHash: string; hostId?: string; lockWaitMs?: number }):
Promise<ResolutionResult & { replayed: boolean }> {
if (item.target === 'withdrawal_mirror') return resolveEffectRecovery(engine, item, opts);
- const hostId = opts.hostId ?? localHostId();
+ const hostId = opts.hostId ?? hostIdFor(engine);
const key = `${item.id}:${opts.previewHash}`;
const command = stuckRecoveryPreviewCommand([item.source_id], item.request_id);
let journal = await startedJournal(engine, key, item, opts, command);
@@ -779,7 +779,7 @@ Promise<ResolutionResult & { replayed: boolean }> {
*/
async function resolveEffectRecovery(engine: BrainEngine, item: StuckRecovery, opts: { keep: KeepChoice; previewHash: string; hostId?: string; lockWaitMs?: number }):
Promise<ResolutionResult & { replayed: boolean }> {
- const hostId = opts.hostId ?? localHostId();
+ const hostId = opts.hostId ?? hostIdFor(engine);
const key = `${item.id}:${opts.previewHash}`;
const command = stuckRecoveryPreviewCommand([item.source_id], item.request_id || undefined);
let journal = await startedJournal(engine, key, item, opts, command);
diff --git a/src/core/persistence/service.ts b/src/core/persistence/service.ts
index 01d6f92916..267b1229d9 100644
--- a/src/core/persistence/service.ts
+++ b/src/core/persistence/service.ts
@@ -15,7 +15,7 @@ import { OWNER_READ_BUDGET_MS, startOwnerRead, type OwnerActivity } from './owne
import { isTerminal, type WriteRequest } from './model.ts';
import { isWriteErrorCode, type WriteReceipt } from './types.ts';
import { registerPgliteReopen } from '../pglite-lifecycle.ts';
-import { localHostId } from './identity.ts';
+import { hostIdFor } from './identity.ts';
import { assertMutationProtocol } from './protocol.ts';
import { writeSwitchOn } from './switches.ts';
import { pendingWriteHint } from './health.ts';
@@ -136,7 +136,7 @@ export function startPersistenceConsumer(engine: BrainEngine, config: GBrainConf
const full = () => new PersistenceConsumer(engine, config, preparePersistedMutation,
{ drainNotice: kind === 'serve', oneShot, onSettled: row => { recordSettlement(engine); rememberSettled(engine, row.id); for (const listener of settledWaiters.get(engine)?.get(row.id) ?? []) listener(row); } });
const service: Service = kind !== 'serve' && RESIDENT_CONSUMER_KINDS.includes(kind) && engine.kind === 'postgres'
- ? { consumer: new WaiterOnlyConsumer(engine, config, full, { kind, hostId: localHostId(), pool: () => enginePoolStats(engine) }), stopping: false }
+ ? { consumer: new WaiterOnlyConsumer(engine, config, full, { kind, hostId: hostIdFor(engine), pool: () => enginePoolStats(engine) }), stopping: false }
: (() => { const consumer = full(); return { consumer, stopping: false, heartbeat: startConsumerHeartbeat(engine, consumer.hostId,
// #6317 (C1): the row's pool numbers come from the vendored driver's own queues (postgres-engine/pool-stats.ts).
{ kind, mode: 'full', report: () => ({ restart_required: consumer.restartRequired(), root_barrier_age_ms: consumer.oldestRootBarrierAgeMs(), pool: enginePoolStats(engine) }) }) }; })();
diff --git a/src/core/persistence/sync-pass-readers.ts b/src/core/persistence/sync-pass-readers.ts
index 2e50443c22..80becaa7e1 100644
--- a/src/core/persistence/sync-pass-readers.ts
+++ b/src/core/persistence/sync-pass-readers.ts
@@ -12,7 +12,7 @@ import { resolve } from 'node:path';
import type { BrainEngine } from '../engine.ts';
import { hardenedGitSync } from '../hardened-git.ts';
import { managedSyncResumeArgs } from '../sync-reconcile.ts';
-import { localHostId } from './identity.ts';
+import { hostIdFor } from './identity.ts';
import { passHealth, readLivePassRows, type PassHealth, type PassRow } from './sync-pass-row.ts';
export interface PassReading { source_id: string; row: PassRow; head: string | null; health: PassHealth }
@@ -23,7 +23,7 @@ export async function readCheckoutHeads(engine: Pick<BrainEngine, 'executeRaw'>,
if (!sourceIds.length) return heads;
const rows = await engine.executeRaw<{ source_id: string; local_path: string; relative_path: string }>(`SELECT b.source_id, h.local_path, b.relative_path
FROM persistence_source_bindings b JOIN persistence_host_bindings h ON h.worktree_id=b.worktree_id AND h.host_id=$2::uuid
- WHERE b.source_id=ANY($1::text[])`, [[...sourceIds], localHostId()]);
+ WHERE b.source_id=ANY($1::text[])`, [[...sourceIds], hostIdFor(engine)]);
for (const row of rows) {
const out = hardenedGitSync(resolve(row.local_path, row.relative_path), ['rev-parse', '--verify', '--quiet', 'HEAD^{commit}'], { timeoutMs: 10_000, maxBytes: 4096 });
heads.set(row.source_id, out.ok ? out.stdout.toString('utf8').trim() || null : null);
diff --git a/src/core/persistence/writer-versions.ts b/src/core/persistence/writer-versions.ts
index 06410cda95..0e815c61fa 100644
--- a/src/core/persistence/writer-versions.ts
+++ b/src/core/persistence/writer-versions.ts
@@ -1,6 +1,6 @@
/** Writer-version stamps on persistence_requests (migration 178): observation of older writers, not prevention. */
import { VERSION } from '../../version.ts';
-import { existingLocalHostId, localHostId } from './identity.ts';
+import { existingHostIdFor, hostIdFor } from './identity.ts';
import type { SqlEngine } from './model.ts';
/** Writers older than this may still delete database-only timeline rows during publication. */
@@ -33,9 +33,10 @@ export function writerVersionBelowFloor(version: string | null, floor = WRITER_V
* segmented pages write: a version string cannot tell a build with segment readers from a release of the same
* version without them.
*/
-export function writerStamp(opts: { mint?: boolean } = {}): { version: string; hostId: string | null } {
+export function writerStamp(opts: { mint?: boolean; engine?: object } = {}): { version: string; hostId: string | null } {
let hostId: string | null = null;
- try { hostId = opts.mint === false ? existingLocalHostId() : localHostId(); } catch { /* unwritable or invalid identity: stamp the version only */ }
+ // `engine`: the host id that engine was opened with (engine-open.ts), else this process's file identity.
+ try { hostId = opts.mint === false ? existingHostIdFor(opts.engine) : hostIdFor(opts.engine); } catch { /* unwritable or invalid identity: stamp the version only */ }
return { version: VERSION, hostId };
}
diff --git a/src/core/pglite-engine.ts b/src/core/pglite-engine.ts
index 4d4c0369e8..e3b7b4b57e 100644
--- a/src/core/pglite-engine.ts
+++ b/src/core/pglite-engine.ts
@@ -85,6 +85,7 @@ import { withVectorSettings } from './search/vector-settings.ts';
import { PGLITE_SCHEMA_SQL, getPGLiteSchema } from './pglite-schema.ts';
import { DEFAULT_EMBEDDING_MODEL, DEFAULT_EMBEDDING_DIMENSIONS } from './ai/defaults.ts';
import { readStoredEmbeddingIdentity } from './stored-embedding-identity.ts';
+import { assertEmbeddedEmbedding, embeddedSchemaEmbedding, isEmbeddedEngine } from './embedded-engine.ts';
import { DELETE_BATCH_SIZE, TRAVERSE_PATH_ROW_CAP, TRAVERSE_WALK_ROW_CAP } from './engine-constants.ts';
import { PageMissingError } from './engine-errors.ts';
import { SAFE_FENCE_CHUNKER_VERSION, bodyWriteChunkVersion, currentTextProjectionFilter, requiresSafeChunks, safeChunksFilter } from './search/safe-chunks.ts';
@@ -900,7 +901,7 @@ export class PGLiteEngine implements BrainEngine {
// hash, load the dump and skip the schema replay. Mismatch or missing
// file silently falls back to normal init.
let loadDataDir: Blob | undefined;
- if (!dataDir && process.env.GBRAIN_PGLITE_SNAPSHOT) {
+ if (!dataDir && process.env.GBRAIN_PGLITE_SNAPSHOT && !isEmbeddedEngine(this)) {
const snapshotResult = tryLoadSnapshot(process.env.GBRAIN_PGLITE_SNAPSHOT);
if (snapshotResult) {
loadDataDir = snapshotResult;
@@ -1139,7 +1140,9 @@ export class PGLiteEngine implements BrainEngine {
}
let dims: number = DEFAULT_EMBEDDING_DIMENSIONS;
let model: string = DEFAULT_EMBEDDING_MODEL;
- try {
+ const embedded = embeddedSchemaEmbedding(this); // settings.embedding, never the process gateway
+ if (embedded) ({ dimensions: dims, model } = embedded);
+ else try {
// Keep the gateway lazy: its static closure is large, and evaluation inside
// this try/catch preserves the unconfigured-gateway default fallback.
const gw = await import('./ai/gateway.ts'); // engine-dynamic-import-ok
@@ -1152,6 +1155,7 @@ export class PGLiteEngine implements BrainEngine {
const storedIdentity = await readStoredEmbeddingIdentity(this);
if (storedIdentity) {
if (!storedIdentity.model) throw new Error('Stored embedding model is unknown. Run gbrain migrate embeddings --status and explicitly migrate before schema initialization.');
+ if (embedded) assertEmbeddedEmbedding(embedded, storedIdentity);
dims = storedIdentity.dimensions;
model = storedIdentity.model;
}
@@ -2778,7 +2782,7 @@ export class PGLiteEngine implements BrainEngine {
// scope ingest_log queries. Default 'default' matches the column DEFAULT.
const sourceId = entry.source_id ?? 'default';
// v254: the writer's version, host and segment-reader mark (writer-versions.ts writerStamp).
- const stamp = writerStamp({ mint: false });
+ const stamp = writerStamp({ mint: false, engine: this });
await this.db.query(
`INSERT INTO ingest_log (source_id, source_type, source_ref, pages_updated, summary, writer_version, writer_host_id, writer_segment_reader)
VALUES ($1, $2, $3, $4::jsonb, $5, $6, $7::uuid, true)`,
diff --git a/src/core/postgres-engine.ts b/src/core/postgres-engine.ts
index 7e67836c2d..c53fa00209 100644
--- a/src/core/postgres-engine.ts
+++ b/src/core/postgres-engine.ts
@@ -124,6 +124,7 @@ import { buildKeywordChunkMatch, KEYWORD_RANK_CANDIDATES, KEYWORD_RANKED_ROWS_CT
import { privatePagesFilterFragment, privateSnapshotFilterFragment, privateLinkOriginFilterFragment, privateTimelineEventFilterFragment, privateProvenanceFilterFragment, privatePagesFilterForCaller } from './search/private-visibility.ts';
import { DEFAULT_EMBEDDING_MODEL, DEFAULT_EMBEDDING_DIMENSIONS } from './ai/defaults.ts';
import { readStoredEmbeddingIdentity } from './stored-embedding-identity.ts';
+import { assertEmbeddedEmbedding, embeddedSchemaEmbedding, embeddedSettingsRecord, isEmbeddedEngine } from './embedded-engine.ts';
import { DELETE_BATCH_SIZE, TRAVERSE_PATH_ROW_CAP, TRAVERSE_WALK_ROW_CAP } from './engine-constants.ts';
import { PageMissingError } from './engine-errors.ts';
import { EMBED_SKIP_FILTER_FRAGMENT } from './embed-skip.ts';
@@ -429,6 +430,7 @@ export class PostgresEngine implements BrainEngine {
const url = config.database_url;
if (!url) throw new GBrainError('No database URL', 'database_url is missing', 'Provide --url');
const size = Math.min(config.poolSize, db.resolvePoolSize(config.poolSize));
+ const embedded = isEmbeddedEngine(this);
// Honor PgBouncer transaction-mode detection on worker-instance pools too.
// Without this, `gbrain jobs work` against a Supabase pooler URL hits
// "prepared statement does not exist" under load just like the module
@@ -459,7 +461,7 @@ export class PostgresEngine implements BrainEngine {
opts.prepare = prepare;
}
this._sql = postgres(url, traceSqlOptions(opts, 'instance'));
- await db.checkPoolAndLoadSharedTypes(this._sql, url);
+ await db.checkPoolAndLoadSharedTypes(this._sql, url, { persisted: !embedded });
await db.setSessionDefaults(this._sql);
this._connectionStyle = 'instance';
@@ -472,6 +474,7 @@ export class PostgresEngine implements BrainEngine {
readPoolOwnedExternally: true, // we own _sql; manager just routes
onpoisoned: this.onPoisoned,
health: this.poolHealth,
+ ...(embedded ? { directUrl: embeddedSettingsRecord(this)?.database.directUrl ?? null, directUrlFromEnv: false } : {}),
});
this.connectionManager.setReadPool(this._sql);
} else {
@@ -569,7 +572,9 @@ export class PostgresEngine implements BrainEngine {
let dims: number = DEFAULT_EMBEDDING_DIMENSIONS;
let model: string = DEFAULT_EMBEDDING_MODEL;
- try {
+ const embedded = embeddedSchemaEmbedding(this); // settings.embedding, never the process gateway
+ if (embedded) ({ dimensions: dims, model } = embedded);
+ else try {
// Keep the gateway lazy: its static closure is large, and evaluation inside
// this try/catch preserves the unconfigured-gateway default fallback.
const gw = await import('./ai/gateway.ts'); // engine-dynamic-import-ok
@@ -583,6 +588,7 @@ export class PostgresEngine implements BrainEngine {
const storedIdentity = await readStoredEmbeddingIdentity(this);
if (storedIdentity) {
if (!storedIdentity.model) throw new Error('Stored embedding model is unknown. Run gbrain migrate embeddings --status and explicitly migrate before schema initialization.');
+ if (embedded) assertEmbeddedEmbedding(embedded, storedIdentity);
dims = storedIdentity.dimensions;
model = storedIdentity.model;
}
@@ -2621,7 +2627,7 @@ export class PostgresEngine implements BrainEngine {
// scope ingest_log queries. Default 'default' matches the column DEFAULT.
const sourceId = entry.source_id ?? 'default';
// v254: the writer's version, host and segment-reader mark (writer-versions.ts writerStamp).
- const stamp = writerStamp({ mint: false });
+ const stamp = writerStamp({ mint: false, engine: this });
await sql`
INSERT INTO ingest_log (source_id, source_type, source_ref, pages_updated, summary, writer_version, writer_host_id, writer_segment_reader)
VALUES (${sourceId}, ${entry.source_type}, ${entry.source_ref}, ${sql.json(entry.pages_updated)}, ${entry.summary}, ${stamp.version}, ${stamp.hostId}::uuid, true)
diff --git a/src/core/shared-skills/knowledge-guard.ts b/src/core/shared-skills/knowledge-guard.ts
index ad43c8f4a0..c66e3a4e11 100644
--- a/src/core/shared-skills/knowledge-guard.ts
+++ b/src/core/shared-skills/knowledge-guard.ts
@@ -4,7 +4,7 @@ import { fileURLToPath } from 'node:url';
import { OperationError } from '../ops/contract.ts';
import { isRelativeFileUri, resolveSourceLocalFilePath, sourceGitScope } from '../markdown.ts';
import { screeningPath } from '../persistence/screening-paths.ts';
-import { localHostId } from '../persistence/identity.ts';
+import { hostIdFor } from '../persistence/identity.ts';
import type { SqlEngine, WriteRequest } from '../persistence/model.ts';
import { canonicalFilesystemPath } from '../persistence/root-registry.ts';
@@ -92,7 +92,7 @@ function sharedPacks(engine: SqlEngine): Promise<PackRoot[]> {
h.local_path AS worktree_root,b.relative_path FROM shared_skill_packs p
JOIN sources s ON s.id=p.source_id AND s.incarnation=p.source_incarnation
LEFT JOIN persistence_source_bindings b ON b.source_id=p.source_id AND b.source_incarnation=p.source_incarnation
- LEFT JOIN persistence_host_bindings h ON h.worktree_id=b.worktree_id AND h.host_id=$1::uuid`, [localHostId()]);
+ LEFT JOIN persistence_host_bindings h ON h.worktree_id=b.worktree_id AND h.host_id=$1::uuid`, [hostIdFor(engine)]);
};
if ((engine as { _pageTransaction?: boolean })._pageTransaction !== true) return read();
let cached = packsInTransaction.get(engine);
diff --git a/test/e2e/engine-open-postgres.test.ts b/test/e2e/engine-open-postgres.test.ts
new file mode 100644
index 0000000000..4afd4b7239
--- /dev/null
+++ b/test/e2e/engine-open-postgres.test.ts
@@ -0,0 +1,162 @@
+/**
+ * openEngine(settings) on Postgres (Wave B1): each engine opened from settings gets its own pool of the size its
+ * settings name, connects only to its own database and direct URL, and records its host identity as given, while
+ * GBRAIN_DATABASE_URL, GBRAIN_DIRECT_DATABASE_URL, GBRAIN_POOL_SIZE, HOME and GBRAIN_HOME point elsewhere.
+ * Each case uses scratch databases on the DATABASE_URL server. Skips without DATABASE_URL.
+ */
+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
+import { randomBytes, randomUUID } from 'node:crypto';
+import { existsSync, mkdirSync, mkdtempSync, readdirSync, rmSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join, relative } from 'node:path';
+import postgres from '#postgres';
+import { assertSafeE2eDatabaseUrl } from '../helpers/db-guard.ts';
+import { withEnv } from '../helpers/with-env.ts';
+import { hostIdFor, openEngine, type EngineSettings } from '../../src/core/engine-open.ts';
+import { createEngine } from '../../src/core/engine-factory.ts';
+import { operationsByName, type OperationContext } from '../../src/core/operations.ts';
+import { startConsumerHeartbeat } from '../../src/core/persistence/consumer-heartbeat.ts';
+import { localHostId } from '../../src/core/persistence/identity.ts';
+import type { BrainEngine } from '../../src/core/engine.ts';
+import type { EngineConfig } from '../../src/core/types.ts';
+import { sharedParameterTypes, type SharedParameterTypes } from '../../src/core/pg-type-cache.ts';
+
+const DATABASE_URL = process.env.DATABASE_URL;
+const describeE2E = DATABASE_URL ? describe : describe.skip;
+if (!DATABASE_URL) console.log('Skipping E2E openEngine on Postgres (DATABASE_URL not set)');
+
+const scratch = mkdtempSync(join(tmpdir(), 'gbrain-engine-open-pg-'));
+const drops: Array<() => Promise<void>> = [];
+const urls: string[] = [];
+const dir = (name: string) => { const path = join(scratch, `${name}-${randomUUID().slice(0, 8)}`); mkdirSync(path, { recursive: true }); return path; };
+function filesUnder(root: string): string[] {
+ if (!existsSync(root)) return [];
+ return readdirSync(root, { recursive: true, withFileTypes: true }).filter(entry => !entry.isDirectory())
+ .map(entry => relative(root, join(entry.parentPath, entry.name))).sort();
+}
+const writerValue = () => ({ id: randomUUID(), credential: randomBytes(32).toString('hex'), lane: 'stdio' as const });
+const hostCtx = (engine: BrainEngine): OperationContext => ({
+ engine, config: {}, logger: { info: () => {}, warn: () => {}, error: () => {} }, dryRun: false, remote: true,
+} as unknown as OperationContext);
+const codeOf = async (work: Promise<unknown>) => { try { await work; return 'resolved'; } catch (error) { return (error as { code?: string }).code ?? String(error); } };
+const internals = (engine: BrainEngine) => engine as unknown as { _sql: { options: { max: number } } | null; _connectionStyle: string | null;
+ connectionManager: { resolveDirectUrl(): string | null } | null };
+const CANARY_URL = 'postgresql://canary:[email protected]:5432/canary';
+const CANARY_DIRECT = 'postgresql://canary:[email protected]:5432/canary-direct';
+
+beforeAll(async () => {
+ if (!DATABASE_URL) return;
+ assertSafeE2eDatabaseUrl(DATABASE_URL);
+ const admin = postgres(DATABASE_URL, { max: 1, prepare: false });
+ for (let i = 0; i < 2; i++) {
+ const name = `gbrain_test_engine_open_${randomUUID().replaceAll('-', '')}`;
+ await admin.unsafe(`CREATE DATABASE ${name}`);
+ const url = new URL(DATABASE_URL);
+ url.pathname = `/${name}`;
+ urls.push(url.toString());
+ drops.push(async () => { await admin.unsafe(`DROP DATABASE IF EXISTS ${name} WITH (FORCE)`); });
+ }
+ drops.push(() => admin.end());
+}, 60_000);
+
+afterAll(async () => {
+ for (const drop of drops) await drop().catch(() => {});
+ rmSync(scratch, { recursive: true, force: true });
+});
+
+describeE2E('openEngine on Postgres', () => {
+ const settingsA: Partial<EngineSettings> = {};
+ const settingsB: Partial<EngineSettings> = {};
+
+ test('two engines keep their own database, pool, direct URL and host identity; ambient settings never redirect a write', async () => {
+ const home = dir('canary-home');
+ const gbrainHome = dir('clean-gbrain-home');
+ const directB = urls[1]!;
+ Object.assign(settingsA, { embedded_core: true, engine: 'postgres', database: { url: urls[0]! }, pool: { max: 2 }, host: { id: randomUUID() }, writer: writerValue() });
+ Object.assign(settingsB, { embedded_core: true, engine: 'postgres', database: { url: urls[1]!, directUrl: directB }, pool: { max: 3 }, host: { id: randomUUID() }, writer: writerValue() });
+ await withEnv({ HOME: home, GBRAIN_HOME: gbrainHome, GBRAIN_DATABASE_URL: CANARY_URL, GBRAIN_DIRECT_DATABASE_URL: CANARY_DIRECT, GBRAIN_POOL_SIZE: '1' }, async () => {
+ const a = await openEngine(settingsA as EngineSettings);
+ const b = await openEngine(settingsB as EngineSettings);
+ try {
+ await a.initSchema();
+ await b.initSchema();
+ expect(internals(a)._connectionStyle).toBe('instance');
+ expect(internals(b)._connectionStyle).toBe('instance');
+ expect(internals(a)._sql?.options.max).toBe(2);
+ expect(internals(b)._sql?.options.max).toBe(3);
+ expect(internals(a).connectionManager?.resolveDirectUrl()).not.toBe(CANARY_DIRECT);
+ expect(internals(b).connectionManager?.resolveDirectUrl()).toBe(directB);
+ expect(hostIdFor(a)).toBe(settingsA.host!.id);
+ expect(hostIdFor(b)).toBe(settingsB.host!.id);
+ // The statement-description cache stays in this process: no file under the home is read or written for it.
+ expect((sharedParameterTypes(urls[0]) as SharedParameterTypes).file).toBeNull();
+ expect((sharedParameterTypes(urls[1]) as SharedParameterTypes).file).toBeNull();
+ await operationsByName.put_page.handler(hostCtx(a), { slug: 'notes/only-in-a', content: '---\ntitle: Only in A\n---\nWritten to database A.\n' });
+ await operationsByName.put_page.handler(hostCtx(b), { slug: 'notes/only-in-b', content: '---\ntitle: Only in B\n---\nWritten to database B.\n' });
+ expect((await a.getPage('notes/only-in-a'))?.compiled_truth).toContain('database A');
+ expect(await a.getPage('notes/only-in-b')).toBeNull();
+ expect((await b.getPage('notes/only-in-b'))?.compiled_truth).toContain('database B');
+ expect(await b.getPage('notes/only-in-a')).toBeNull();
+ const admitted = await a.executeRaw<{ admitter_host_id: string | null }>("SELECT admitter_host_id::text AS admitter_host_id FROM persistence_requests WHERE slug='notes/only-in-a'");
+ expect(admitted.map(row => row.admitter_host_id)).toEqual([settingsA.host!.id]);
+ } finally {
+ await Promise.all([a.disconnect(), b.disconnect()]);
+ }
+ const reopened = await openEngine({ ...settingsA, writer: { ...settingsA.writer! } } as EngineSettings);
+ try {
+ expect((await reopened.getPage('notes/only-in-a'))?.compiled_truth).toContain('database A');
+ } finally {
+ await reopened.disconnect();
+ }
+ });
+ // The connection-events audit log (connection-audit.ts) is a process-wide diagnostic sink, not an engine setting;
+ // nothing else, and no host.json or writer credential, lands under the home.
+ expect(filesUnder(gbrainHome).filter(path => !/^\.gbrain\/audit\/connection-events-\d{4}-W\d{2}\.jsonl$/.test(path))).toEqual([]);
+ expect(filesUnder(home)).toEqual([]);
+ }, 300_000);
+
+ test('the consumer heartbeat records the identity-given-at-open sentinel, not a host.json path', async () => {
+ const engine = await openEngine(settingsA as EngineSettings);
+ try {
+ const hostId = hostIdFor(engine);
+ const heartbeat = startConsumerHeartbeat(engine, hostId, { kind: 'cli', mode: 'full', everyMs: 60_000,
+ report: () => ({ restart_required: false, root_barrier_age_ms: null, pool: null }) });
+ try {
+ await heartbeat.renew();
+ const rows = await engine.executeRaw<{ host_json_path: string; persistence_home: string; minted_under: unknown }>(
+ 'SELECT host_json_path, persistence_home, minted_under FROM persistence_consumers WHERE host_id=$1::uuid', [hostId]);
+ expect(rows).toEqual([{ host_json_path: `embedded:${hostId}`, persistence_home: 'embedded', minted_under: null }]);
+ } finally {
+ await heartbeat.stop();
+ }
+ } finally {
+ await engine.disconnect();
+ }
+ }, 120_000);
+
+ test('initSchema refuses an existing database whose embedding width differs from settings.embedding', async () => {
+ const engine = await openEngine({ ...settingsA, embedding: { model: 'voyage:voyage-4', dimensions: 768 } } as EngineSettings);
+ try {
+ expect(await codeOf(engine.initSchema())).toBe('engine_embedding_mismatch');
+ } finally {
+ await engine.disconnect();
+ }
+ }, 120_000);
+
+ test('an unmarked engine keeps its instance pool, the ambient direct URL and the file identity (back-compat)', async () => {
+ const gbrainHome = dir('unmarked-home');
+ await withEnv({ GBRAIN_HOME: gbrainHome, GBRAIN_DIRECT_DATABASE_URL: CANARY_DIRECT, GBRAIN_POOL_SIZE: '1' }, async () => {
+ const config: EngineConfig = { engine: 'postgres', database_url: urls[0]! };
+ const engine = await createEngine(config);
+ await engine.connect({ ...config, poolSize: 3 } as EngineConfig & { poolSize: number });
+ try {
+ expect(internals(engine)._sql?.options.max).toBe(3);
+ expect(internals(engine).connectionManager?.resolveDirectUrl()).toBe(CANARY_DIRECT);
+ expect(hostIdFor(engine)).toBe(localHostId());
+ expect((sharedParameterTypes(urls[0]) as SharedParameterTypes).file?.startsWith(gbrainHome)).toBe(true);
+ } finally {
+ await engine.disconnect();
+ }
+ });
+ }, 120_000);
+});
diff --git a/test/engine-open-lifecycle.test.ts b/test/engine-open-lifecycle.test.ts
new file mode 100644
index 0000000000..2abc78a492
--- /dev/null
+++ b/test/engine-open-lifecycle.test.ts
@@ -0,0 +1,76 @@
+/**
+ * Per-engine state an embedding host that opens an engine per request must not leak or share (Wave B1 lifecycle),
+ * and the consumer-identity sentinel an engine opened from settings records. Every case here runs on master's
+ * modules, so each one is red before the change.
+ */
+import { afterEach, describe, expect, test } from 'bun:test';
+import { randomUUID } from 'node:crypto';
+import { dailySpend, __resetDecideStoreForTests } from '../src/core/ai/decide/store.ts';
+import { _resetFeedbackRecordingForTests, drainFeedbackQueue, recordAnswer } from '../src/core/feedback/record.ts';
+import { _resetFeedbackSettingsCacheForTests } from '../src/core/feedback/settings.ts';
+import { hostIdentityMismatches } from '../src/core/persistence/consumer-diagnostics.ts';
+import type { LocalHostIdentity } from '../src/core/persistence/identity.ts';
+import type { BrainEngine } from '../src/core/engine.ts';
+import type { OperationContext } from '../src/core/ops/contract.ts';
+
+afterEach(() => {
+ __resetDecideStoreForTests();
+ _resetFeedbackRecordingForTests();
+ _resetFeedbackSettingsCacheForTests();
+});
+
+/** A page transaction on `engine`, shaped as the engines build one (an own `_pageTransaction` on a prototype clone). */
+function transactionOn<T extends object>(engine: T): T {
+ const tx = Object.create(engine) as T;
+ Object.defineProperty(tx, '_pageTransaction', { value: true });
+ return tx;
+}
+
+describe('decide spend cache', () => {
+ test('a page transaction reads its engine\'s cached daily figure instead of querying again', async () => {
+ let reads = 0;
+ const engine = { executeRaw: async () => { reads++; return [{ total: 2, remote: 1 }]; } } as unknown as BrainEngine;
+ const now = Date.now();
+ expect(await dailySpend(engine, now)).toEqual({ total: 2, remote: 1 });
+ expect(await dailySpend(transactionOn(engine), now)).toEqual({ total: 2, remote: 1 });
+ expect(reads).toBe(1);
+ });
+});
+
+describe('feedback queue', () => {
+ test('a drained queue does not keep its engine alive', async () => {
+ const open = async (): Promise<WeakRef<object>> => {
+ const engine = {
+ kind: 'pglite',
+ getConfig: async (key: string) => (key === 'feedback.enabled' ? 'true' : null),
+ executeRaw: async () => [],
+ } as unknown as BrainEngine;
+ const ctx = { engine, config: {}, remote: false, logger: console } as unknown as OperationContext;
+ const meta = await recordAnswer(ctx, { op: 'query', pages: [{ source_id: 'default', slug: 'people/alice-example' }] });
+ expect(meta?.feedback.rateable).toBe(true);
+ expect(await drainFeedbackQueue(5000)).toEqual({ unfinished: 0 });
+ return new WeakRef(engine);
+ };
+ const held = await open();
+ // The settings cache keeps the last engine it read (one slot, by design); the queue is what this case measures.
+ _resetFeedbackSettingsCacheForTests();
+ for (let i = 0; i < 50 && held.deref(); i++) { Bun.gc(true); await Bun.sleep(20); }
+ expect(held.deref()).toBeUndefined();
+ });
+});
+
+describe('consumer identity sentinel', () => {
+ test('an owner whose heartbeat records an identity given at open gets no GBRAIN_HOME fix, never a path read from the sentinel', async () => {
+ const owner = randomUUID();
+ const me: LocalHostIdentity = { id: randomUUID(), path: '/home/alice-example/.gbrain/persistence/host.json', persistence_home: '/home/alice-example/.gbrain/persistence',
+ minted_under: { home: '/home/alice-example', gbrain_home: null, hostname: 'host-a', machine_id: null } };
+ const rows = [
+ [{ worktree_id: randomUUID(), owner_host_id: owner, local_path: '/srv/brain-example', created_at: '2026-01-01T00:00:00Z', source_ids: ['source-a'] }],
+ [{ host_id: owner, host_json_path: `embedded:${owner}`, persistence_home: 'embedded', minted_under: null, renewed_at: '2026-11-01T00:00:00Z' }],
+ ];
+ const engine = { kind: 'postgres', executeRaw: async () => rows.shift() ?? [] } as unknown as BrainEngine;
+ const [mismatch] = await hostIdentityMismatches(engine, me, { exists: () => true, marked: () => true, hostJsonMintedAt: Date.now() });
+ expect(mismatch?.owner_host).toMatchObject({ host_id: owner, host_json_path: `embedded:${owner}`, persistence_home: 'embedded' });
+ expect(mismatch?.fix_env).toBeNull();
+ });
+});
diff --git a/test/engine-open.test.ts b/test/engine-open.test.ts
new file mode 100644
index 0000000000..845482a1c4
--- /dev/null
+++ b/test/engine-open.test.ts
@@ -0,0 +1,386 @@
+/**
+ * openEngine(settings) (Wave B1): an engine opened from a settings value reads no config file, environment variable,
+ * home directory or working directory for its database, host identity, writer or embedding identity. PGLite here;
+ * test/e2e/engine-open-postgres.test.ts covers Postgres pools and connection routing.
+ */
+import { afterAll, describe, expect, test } from 'bun:test';
+import { existsSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join, relative } from 'node:path';
+import { randomBytes, randomUUID } from 'node:crypto';
+import { embeddedSettings, hostIdFor, isEmbeddedEngine, openEngine, processHasEmbeddedEngines, registerLocalWriterValue, type EngineSettings } from '../src/core/engine-open.ts';
+import { markEmbeddedEngine } from '../src/core/embedded-engine.ts';
+import { existingHostIdFor, existingLocalHostId, hostIdentityPathsFor, localHostId, localHostIdentity, revokeLocalWriter } from '../src/core/persistence/identity.ts';
+import { operationsByName, type OperationContext } from '../src/core/operations.ts';
+import { readStoredEmbeddingIdentity } from '../src/core/stored-embedding-identity.ts';
+import { ConnectionManager } from '../src/core/connection-manager.ts';
+import type { BrainEngine } from '../src/core/engine.ts';
+import { withEnv } from './helpers/with-env.ts';
+
+const scratch = mkdtempSync(join(tmpdir(), 'gbrain-engine-open-'));
+afterAll(() => { rmSync(scratch, { recursive: true, force: true }); });
+
+const dir = (name: string) => { const path = join(scratch, `${name}-${randomUUID().slice(0, 8)}`); mkdirSync(path, { recursive: true }); return path; };
+/** Every file under `root`, relative; an empty list means nothing was created there. */
+function filesUnder(root: string): string[] {
+ if (!existsSync(root)) return [];
+ return readdirSync(root, { recursive: true, withFileTypes: true }).filter(entry => !entry.isDirectory())
+ .map(entry => relative(root, join(entry.parentPath, entry.name))).sort();
+}
+const writerValue = (lane: 'cli' | 'stdio' = 'stdio') => ({ id: randomUUID(), credential: randomBytes(32).toString('hex'), lane });
+const settingsFor = (over: Partial<EngineSettings> = {}): EngineSettings => ({ embedded_core: true, engine: 'pglite', database: {}, host: { id: randomUUID() }, ...over });
+/** An operation call from an embedding host: a remote (stdio-lane) context with no authenticated principal. */
+const hostCtx = (engine: BrainEngine): OperationContext => ({
+ engine, config: {}, logger: { info: () => {}, warn: () => {}, error: () => {} }, dryRun: false, remote: true,
+} as unknown as OperationContext);
+const codeOf = async (work: Promise<unknown>) => { try { await work; return 'resolved'; } catch (error) { return (error as { code?: string }).code ?? String(error); } };
+/** Ambient settings that must never reach an embedded engine: a clean GBRAIN_HOME, a canary HOME and bogus database URLs. */
+function canaries() {
+ const home = dir('canary-home');
+ const gbrainHome = dir('clean-gbrain-home');
+ return { home, gbrainHome, env: {
+ HOME: home, GBRAIN_HOME: gbrainHome,
+ GBRAIN_DATABASE_URL: 'postgresql://canary:[email protected]:5432/canary',
+ GBRAIN_DIRECT_DATABASE_URL: 'postgresql://canary:[email protected]:5432/canary-direct',
+ } };
+}
+
+describe('openEngine refusals', () => {
+ test('refuses without embedded_core: true, and names the setting', async () => {
+ for (const embedded_core of [undefined, false, 'true', 1]) {
+ expect(await codeOf(openEngine({ ...settingsFor(), embedded_core } as unknown as EngineSettings))).toBe('embedded_core_required');
+ }
+ expect(await codeOf(openEngine(undefined as unknown as EngineSettings))).toBe('embedded_core_required');
+ });
+
+ test('refuses an absent host identity with engine_host_missing and malformed settings with engine_settings_invalid', async () => {
+ const { gbrainHome, env } = canaries();
+ await withEnv(env, async () => {
+ expect(await codeOf(openEngine({ ...settingsFor(), host: undefined } as unknown as EngineSettings))).toBe('engine_host_missing');
+ expect(await codeOf(openEngine(settingsFor({ host: { id: '' } })))).toBe('engine_host_missing');
+ expect(await codeOf(openEngine(settingsFor({ host: { id: 'worker-1' } })))).toBe('engine_settings_invalid');
+ expect(await codeOf(openEngine(settingsFor({ engine: 'postgres', database: {} })))).toBe('engine_settings_invalid');
+ expect(await codeOf(openEngine(settingsFor({ database: { url: 'postgresql://x/y' } })))).toBe('engine_settings_invalid');
+ expect(await codeOf(openEngine(settingsFor({ engine: 'sqlite' as 'pglite' })))).toBe('engine_settings_invalid');
+ expect(await codeOf(openEngine(settingsFor({ pool: { max: 0 } })))).toBe('engine_settings_invalid');
+ expect(await codeOf(openEngine(settingsFor({ writer: { ...writerValue(), credential: 'short' } })))).toBe('engine_settings_invalid');
+ expect(await codeOf(openEngine(settingsFor({ writer: { ...writerValue(), id: 'writer-1' } })))).toBe('engine_settings_invalid');
+ expect(await codeOf(openEngine(settingsFor({ embedding: { model: 'voyage:voyage-4', dimensions: 0 } })))).toBe('engine_settings_invalid');
+ });
+ expect(filesUnder(gbrainHome)).toEqual([]);
+ });
+});
+
+describe('openEngine on a clean home', () => {
+ test('writes a page on a no-root source, closes, reopens and reads it back; nothing is created under HOME or GBRAIN_HOME', async () => {
+ const { home, gbrainHome, env } = canaries();
+ const path = dir('brain');
+ const hostId = randomUUID();
+ const writer = writerValue('stdio');
+ const settings = settingsFor({ database: { path }, host: { id: hostId }, writer, embedding: { model: 'voyage:voyage-4-lite', dimensions: 512 },
+ storage: { backend: 'local', bucket: 'files-example', localPath: dir('objects') }, storagePrefix: 'tenant-a/', ai: { provider: 'opaque-example' } });
+ await withEnv(env, async () => {
+ const first = await openEngine(settings);
+ try {
+ await first.initSchema();
+ expect(isEmbeddedEngine(first)).toBe(true);
+ expect(processHasEmbeddedEngines()).toBe(true);
+ expect(hostIdFor(first)).toBe(hostId);
+ const held = embeddedSettings(first)!;
+ expect(held.storage).toEqual(settings.storage!);
+ expect(held.storagePrefix).toBe('tenant-a/');
+ expect(held.ai).toEqual({ provider: 'opaque-example' });
+ expect(held.writer).toEqual({ id: writer.id, lane: 'stdio' });
+ expect(JSON.stringify(held)).not.toContain(writer.credential);
+ const [source] = await first.executeRaw<{ local_path: string | null }>("SELECT local_path FROM sources WHERE id='default'");
+ expect(source?.local_path ?? null).toBeNull();
+ await operationsByName.put_page.handler(hostCtx(first), {
+ slug: 'notes/opened-from-settings', content: '---\ntitle: Opened from settings\n---\nEvery setting came in as a value.\n',
+ });
+ const got = await operationsByName.get_page.handler(hostCtx(first), { slug: 'notes/opened-from-settings' }) as { compiled_truth?: string };
+ expect(got.compiled_truth).toContain('Every setting came in as a value.');
+ } finally {
+ await first.disconnect();
+ }
+ expect(embeddedSettings(first)).toBeUndefined();
+
+ const second = await openEngine({ ...settings, writer: { ...writer } });
+ try {
+ await second.initSchema();
+ const got = await operationsByName.get_page.handler(hostCtx(second), { slug: 'notes/opened-from-settings' }) as { compiled_truth?: string };
+ expect(got.compiled_truth).toContain('Every setting came in as a value.');
+ const [registered] = await second.executeRaw<{ lane: string }>('SELECT lane FROM persistence_local_writers WHERE id=$1::uuid', [writer.id]);
+ expect(registered?.lane).toBe('stdio');
+ } finally {
+ await second.disconnect();
+ }
+ });
+ expect(filesUnder(gbrainHome)).toEqual([]);
+ expect(filesUnder(home)).toEqual([]);
+ }, 180_000);
+});
+
+describe('two engines in one process', () => {
+ test('keep their own datastore, host identity and writer', async () => {
+ const { gbrainHome, env } = canaries();
+ const a = settingsFor({ database: { path: dir('brain-a') }, writer: writerValue('stdio') });
+ const b = settingsFor({ database: { path: dir('brain-b') }, writer: writerValue('stdio') });
+ await withEnv(env, async () => {
+ const engineA = await openEngine(a);
+ const engineB = await openEngine(b);
+ try {
+ await engineA.initSchema();
+ await engineB.initSchema();
+ expect(hostIdFor(engineA)).toBe(a.host.id);
+ expect(hostIdFor(engineB)).toBe(b.host.id);
+ await engineA.transaction(async tx => { expect(hostIdFor(tx)).toBe(a.host.id); });
+ await operationsByName.put_page.handler(hostCtx(engineA), { slug: 'notes/only-in-a', content: '---\ntitle: Only in A\n---\nA.\n' });
+ await operationsByName.put_page.handler(hostCtx(engineB), { slug: 'notes/only-in-b', content: '---\ntitle: Only in B\n---\nB.\n' });
+ expect(await engineA.getPage('notes/only-in-a')).not.toBeNull();
+ expect(await engineA.getPage('notes/only-in-b')).toBeNull();
+ expect(await engineB.getPage('notes/only-in-b')).not.toBeNull();
+ expect(await engineB.getPage('notes/only-in-a')).toBeNull();
+ const writers = async (engine: BrainEngine) => (await engine.executeRaw<{ id: string }>('SELECT id::text AS id FROM persistence_local_writers')).map(row => row.id);
+ expect(await writers(engineA)).toEqual([a.writer!.id]);
+ expect(await writers(engineB)).toEqual([b.writer!.id]);
+ } finally {
+ await Promise.all([engineA.disconnect(), engineB.disconnect()]);
+ }
+ });
+ expect(filesUnder(gbrainHome)).toEqual([]);
+ }, 180_000);
+});
+
+describe('host identity', () => {
+ test('an embedded engine with no host id refuses engine_host_missing and never mints host.json', async () => {
+ const { gbrainHome, env } = canaries();
+ await withEnv(env, async () => {
+ const engine = {};
+ markEmbeddedEngine(engine, { ...settingsFor(), host: undefined } as unknown as EngineSettings);
+ expect(await codeOf(Promise.resolve().then(() => hostIdFor(engine)))).toBe('engine_host_missing');
+ expect(await codeOf(Promise.resolve().then(() => existingHostIdFor(engine)))).toBe('engine_host_missing');
+ expect(await codeOf(Promise.resolve().then(() => hostIdentityPathsFor(engine)))).toBe('engine_host_missing');
+ });
+ expect(filesUnder(gbrainHome)).toEqual([]);
+ });
+
+ test('an embedded engine records the identity-given-at-open sentinel, never a path', async () => {
+ const engine = {};
+ const id = randomUUID();
+ markEmbeddedEngine(engine, settingsFor({ host: { id } }));
+ expect(hostIdentityPathsFor(engine)).toEqual({ host_json_path: `embedded:${id}`, persistence_home: 'embedded', minted_under: null });
+ });
+
+ test('an unmarked engine keeps the file identity exactly as before (back-compat)', async () => {
+ const { gbrainHome, env } = canaries();
+ await withEnv(env, async () => {
+ const engine = {};
+ const transaction = Object.create(engine) as object;
+ Object.defineProperty(transaction, '_pageTransaction', { value: true });
+ expect(existingHostIdFor(engine)).toBeNull();
+ expect(hostIdFor(engine)).toBe(localHostId());
+ expect(hostIdFor(transaction)).toBe(localHostId());
+ expect(hostIdFor()).toBe(localHostId());
+ expect(existingHostIdFor(engine)).toBe(existingLocalHostId());
+ const identity = localHostIdentity();
+ expect(hostIdentityPathsFor(engine)).toEqual({ host_json_path: identity.path, persistence_home: identity.persistence_home, minted_under: identity.minted_under });
+ });
+ expect(filesUnder(gbrainHome)).toEqual(['.gbrain/persistence/host.json']);
+ });
+
+ test('a test double that answers every property is not an embedded engine (back-compat)', async () => {
+ const { env } = canaries();
+ await withEnv(env, async () => {
+ const double = new Proxy({}, { get: () => () => undefined });
+ expect(isEmbeddedEngine(double)).toBe(false);
+ expect(existingHostIdFor(double)).toBeNull();
+ });
+ });
+});
+
+describe('writer given as a value', () => {
+ test('registration is idempotent; another credential or lane under its id refuses; a revoked one is never replaced', async () => {
+ const engine = await openEngine(settingsFor());
+ try {
+ await engine.initSchema();
+ const writer = writerValue('stdio');
+ await registerLocalWriterValue(engine, writer);
+ await registerLocalWriterValue(engine, writer);
+ const rows = () => engine.executeRaw<{ lane: string; revoked: boolean }>('SELECT lane, revoked_at IS NOT NULL AS revoked FROM persistence_local_writers WHERE id=$1::uuid', [writer.id]);
+ expect(await rows()).toEqual([{ lane: 'stdio', revoked: false }]);
+ expect(await codeOf(registerLocalWriterValue(engine, { ...writer, credential: randomBytes(32).toString('hex') }))).toBe('permission_denied');
+ expect(await codeOf(registerLocalWriterValue(engine, { ...writer, lane: 'cli' }))).toBe('permission_denied');
+ expect(await codeOf(registerLocalWriterValue(engine, { ...writer, id: 'not-a-uuid' }))).toBe('engine_settings_invalid');
+ expect(await codeOf(registerLocalWriterValue(engine, { ...writer, credential: 'x'.repeat(31) }))).toBe('engine_settings_invalid');
+ expect(await codeOf(registerLocalWriterValue(engine, { ...writer, lane: 'http' as 'cli' }))).toBe('engine_settings_invalid');
+ expect(await revokeLocalWriter(engine, writer.id)).toBe(true);
+ expect(await codeOf(registerLocalWriterValue(engine, writer))).toBe('permission_denied');
+ expect(await rows()).toEqual([{ lane: 'stdio', revoked: true }]);
+ } finally {
+ await engine.disconnect();
+ }
+ }, 120_000);
+
+ test('the authority path uses the writer given at open; with none, a write refuses and no credential file is minted', async () => {
+ const { gbrainHome, env } = canaries();
+ const writer = writerValue('stdio');
+ await withEnv(env, async () => {
+ const none = await openEngine(settingsFor());
+ try {
+ await none.initSchema();
+ expect(await codeOf(operationsByName.put_page.handler(hostCtx(none), { slug: 'notes/refused', content: '---\ntitle: Refused\n---\nNo writer.\n' })))
+ .toBe('writer_registration_required');
+ expect(await none.getPage('notes/refused')).toBeNull();
+ } finally {
+ await none.disconnect();
+ }
+ const revoked = await openEngine(settingsFor({ writer }));
+ try {
+ await revoked.initSchema();
+ await registerLocalWriterValue(revoked, writer);
+ await revokeLocalWriter(revoked, writer.id);
+ expect(await codeOf(operationsByName.put_page.handler(hostCtx(revoked), { slug: 'notes/revoked', content: '---\ntitle: Revoked\n---\nRevoked writer.\n' })))
+ .toBe('permission_denied');
+ expect(await revoked.getPage('notes/revoked')).toBeNull();
+ } finally {
+ await revoked.disconnect();
+ }
+ });
+ expect(filesUnder(gbrainHome)).toEqual([]);
+ }, 180_000);
+});
+
+describe('embedding identity', () => {
+ test('initSchema seeds settings.embedding, not the process gateway, and an existing brain with another width refuses', async () => {
+ const path = dir('brain-embedding');
+ const first = await openEngine(settingsFor({ database: { path }, embedding: { model: 'voyage:voyage-4-lite', dimensions: 512 } }));
+ try {
+ await first.initSchema();
+ expect(await readStoredEmbeddingIdentity(first)).toEqual({ model: 'voyage:voyage-4-lite', dimensions: 512 });
+ } finally {
+ await first.disconnect();
+ }
+ const wider = await openEngine(settingsFor({ database: { path }, embedding: { model: 'voyage:voyage-4-lite', dimensions: 1024 } }));
+ try {
+ const refusal = await wider.initSchema().then(() => null, (error: unknown) => error as { code?: string; message?: string; suggestion?: string });
+ expect(refusal?.code).toBe('engine_embedding_mismatch');
+ expect(`${refusal?.message} ${refusal?.suggestion}`).toContain('gbrain migrate embeddings --status');
+ expect(await readStoredEmbeddingIdentity(wider)).toEqual({ model: 'voyage:voyage-4-lite', dimensions: 512 });
+ } finally {
+ await wider.disconnect();
+ }
+ const otherModel = await openEngine(settingsFor({ database: { path }, embedding: { model: 'openai:text-embedding-3-small', dimensions: 512 } }));
+ try {
+ expect(await codeOf(otherModel.initSchema())).toBe('engine_embedding_mismatch');
+ } finally {
+ await otherModel.disconnect();
+ }
+ const unstated = await openEngine(settingsFor({ database: { path } }));
+ try {
+ await unstated.initSchema();
+ expect(await readStoredEmbeddingIdentity(unstated)).toEqual({ model: 'voyage:voyage-4-lite', dimensions: 512 });
+ } finally {
+ await unstated.disconnect();
+ }
+ }, 240_000);
+});
+
+describe('connection routing', () => {
+ test('a settings-only manager ignores GBRAIN_DIRECT_DATABASE_URL; the default manager still reads it (back-compat)', async () => {
+ const url = 'postgresql://app:[email protected]:5432/brain_a';
+ const canary = 'postgresql://canary:[email protected]:5432/canary-direct';
+ await withEnv({ GBRAIN_DIRECT_DATABASE_URL: canary }, async () => {
+ expect(new ConnectionManager({ url }).resolveDirectUrl()).toBe(canary);
+ expect(new ConnectionManager({ url, directUrl: null, directUrlFromEnv: false }).resolveDirectUrl()).not.toBe(canary);
+ const direct = 'postgresql://app:[email protected]:5432/brain_a';
+ expect(new ConnectionManager({ url, directUrl: direct, directUrlFromEnv: false }).resolveDirectUrl()).toBe(direct);
+ });
+ });
+});
+
+describe('repo source', () => {
+ test('a write through an embedded engine on a source with a checkout lands in the file and the database, with no identity or credential file in the home', async () => {
+ const { gbrainHome, env } = canaries();
+ const root = dir('repo');
+ expect(Bun.spawnSync(['git', 'init', '--quiet', root]).exitCode).toBe(0);
+ const writer = writerValue('stdio');
+ await withEnv(env, async () => {
+ const engine = await openEngine(settingsFor({ database: { path: dir('brain-repo') }, writer }));
+ try {
+ await engine.initSchema();
+ await engine.executeRaw("UPDATE sources SET local_path=$1 WHERE id='default'", [root]);
+ await operationsByName.put_page.handler(hostCtx(engine), { slug: 'notes/in-the-repo', content: '---\ntitle: In the repo\n---\nWritten through.\n' });
+ expect((await engine.getPage('notes/in-the-repo'))?.compiled_truth).toContain('Written through.');
+ expect(filesUnder(root).filter(path => !path.startsWith('.git/'))).toContain('notes/in-the-repo.md');
+ const [owner] = await engine.executeRaw<{ owner_host_id: string }>("SELECT w.owner_host_id::text AS owner_host_id FROM persistence_source_bindings s JOIN persistence_worktrees w ON w.id=s.worktree_id WHERE s.source_id='default'");
+ expect(owner?.owner_host_id).toBe(hostIdFor(engine));
+ } finally {
+ await engine.disconnect();
+ }
+ });
+ // The checkout's native coordination lock still lives in the process's persistence home (coordination-lock.ts);
+ // no host.json and no writer credential file is created for the embedded engine.
+ expect(filesUnder(gbrainHome).filter(path => !/^\.gbrain\/persistence\/locks\/[0-9a-f-]{36}\.lock$/.test(path))).toEqual([]);
+ }, 180_000);
+});
+
+/**
+ * Persistence modules that still read this process's file identity directly. Each one runs only from a CLI command on
+ * the brain's own host, against a managed checkout that host owns (activation, claim, transfer, topology, checkout sync
+ * and repair). An engine opened from settings owns no managed checkout: activation and claims refuse any host but the
+ * owner, and `hostIdFor(engine)` answers every call an operation, publication or consumer effect makes for it.
+ */
+const FILE_IDENTITY_ALLOWLIST: Record<string, string> = {
+ 'activation.ts': 'gbrain activation mints the host identity on the brain host by design',
+ 'admin-lock.ts': 'writer admin lock, set by CLI administration on the brain host',
+ 'administration.ts': 'gbrain sources writer status/claim/register, local administration',
+ 'connector-sync.ts': 'connector checkout sync owned by the brain host',
+ 'coordination-lock.ts': 'fallback only when a caller passes no host id; claims pass hostIdFor(engine)',
+ 'deactivation.ts': 'gbrain deactivation on the brain host',
+ 'diagnostics.ts': 'local writer diagnostics for the CLI',
+ 'engine-graduation.ts': 'PGLite to Postgres graduation, a local CLI command',
+ 'file-repair.ts': 'checkout file repair on the owning host',
+ 'git-conversion.ts': 'repository conversion of a local checkout',
+ 'git-durability-administration.ts': 'git durability administration of a local checkout',
+ 'onboarding.ts': 'local onboarding preflight',
+ 'pre-activation-release.ts': 'pre-activation release on the brain host',
+ 'reconcile-state.ts': 'checkout reconcile on the owning host',
+ 'skill-activation.ts': 'shared skill activation, local administration',
+ 'source-lifecycle.ts': 'managed source add/move/rebind on the owning host',
+ 'sync-discovery.ts': 'checkout sync discovery on the owning host',
+ 'sync-drain.ts': 'gbrain sync drain on the owning host',
+ 'sync-freshness.ts': 'checkout sync freshness report on the owning host',
+ 'sync-movement.ts': 'checkout sync movement on the owning host',
+ 'topology-clone.ts': 'topology clone/reclone of a local checkout',
+ 'topology-locks.ts': 'topology locks of a local checkout',
+ 'topology-recovery.ts': 'topology recovery of a local checkout',
+ 'transfer-administration.ts': 'writer transfer administration between hosts',
+ 'worktree-refresh.ts': 'managed worktree refresh on the owning host',
+};
+
+describe('static guards', () => {
+ const root = join(import.meta.dir, '..');
+ const code = (path: string) => readFileSync(join(root, path), 'utf8').replace(/\/\*[\s\S]*?\*\//g, '').replace(/(^|[^:])\/\/.*$/gm, '$1');
+ const FILE_IDENTITY = /\b(localHostId|localHostIdentity|existingLocalHostId)\(/;
+
+ test('persistence code resolves the host id through hostIdFor(engine), except the justified allowlist', () => {
+ const dirPath = join(root, 'src/core/persistence');
+ const callers = readdirSync(dirPath, { recursive: true, withFileTypes: true })
+ .filter(entry => entry.isFile() && entry.name.endsWith('.ts'))
+ .map(entry => relative(dirPath, join(entry.parentPath, entry.name)))
+ .filter(name => name !== 'identity.ts' && FILE_IDENTITY.test(code(join('src/core/persistence', name))))
+ .sort();
+ expect(callers.filter(name => !(name in FILE_IDENTITY_ALLOWLIST))).toEqual([]);
+ // A row whose file stopped reading the file identity is stale: delete it.
+ expect(Object.keys(FILE_IDENTITY_ALLOWLIST).filter(name => !callers.includes(name))).toEqual([]);
+ expect(FILE_IDENTITY.test(code('src/core/shared-skills/knowledge-guard.ts'))).toBe(false);
+ });
+
+ test('no MCP or operation module reaches the value registrations', () => {
+ const scanned = ['src/mcp', 'src/core/ops'].flatMap(dirPath => readdirSync(join(root, dirPath), { recursive: true, withFileTypes: true })
+ .filter(entry => entry.isFile() && entry.name.endsWith('.ts')).map(entry => relative(root, join(entry.parentPath, entry.name))));
+ scanned.push('src/core/operations.ts');
+ const reach = scanned.filter(path => /\b(registerLocalWriterValue|setEngineHostId|markEmbeddedEngine|openEngine)\b/.test(code(path)));
+ expect(reach).toEqual([]);
+ });
+});
diff --git a/test/fixtures/export-consumer/consumer.ts b/test/fixtures/export-consumer/consumer.ts
index 5c375aa195..5f8c9af260 100644
--- a/test/fixtures/export-consumer/consumer.ts
+++ b/test/fixtures/export-consumer/consumer.ts
@@ -37,6 +37,7 @@ import { loadHeldOut as e25 } from 'gbrain/core/skillopt';
import { LiveServeLockError as e26 } from 'gbrain/pglite-lock';
import { assembleEvidenceForHits as e27 } from 'gbrain/search/evidence-delivery';
import { VERSION as e28 } from 'gbrain/version';
+import { openEngine as e29 } from 'gbrain/engine-open';
import type { BrainEngine } from 'gbrain/engine';
import type { PageInput, SearchResult } from 'gbrain/types';
import { PGLiteEngine } from 'gbrain/pglite-engine';
@@ -71,6 +72,7 @@ export const RUNTIME_IMPORTS: readonly unknown[] = [
e26,
e27,
e28,
+ e29,
];
export function makeEngine(): BrainEngine {
diff --git a/test/fixtures/goldens/exports/runtime.json b/test/fixtures/goldens/exports/runtime.json
index 043b876b15..2488324ed1 100644
--- a/test/fixtures/goldens/exports/runtime.json
+++ b/test/fixtures/goldens/exports/runtime.json
@@ -640,6 +640,15 @@
"./engine-factory": [
"createEngine"
],
+ "./engine-open": [
+ "DEFAULT_EMBEDDED_POOL_MAX",
+ "embeddedSettings",
+ "hostIdFor",
+ "isEmbeddedEngine",
+ "openEngine",
+ "processHasEmbeddedEngines",
+ "registerLocalWriterValue"
+ ],
"./eval/longmemeval/reader": [
"READER_MAX_SESSION_CHARS",
"READER_MAX_TOKENS",
diff --git a/test/fixtures/goldens/exports/types.json b/test/fixtures/goldens/exports/types.json
index 97a59e1c9c..be8e4f4cea 100644
--- a/test/fixtures/goldens/exports/types.json
+++ b/test/fixtures/goldens/exports/types.json
@@ -4421,6 +4421,82 @@
]
}
],
+ "./engine-open": [
+ {
+ "kind": "variable",
+ "name": "DEFAULT_EMBEDDED_POOL_MAX",
+ "signature": [
+ "4"
+ ]
+ },
+ {
+ "kind": "type",
+ "name": "EmbeddedSettingsView",
+ "signature": [
+ "{ readonly pglite?: { shared_buffers?: string; } | undefined; readonly host: { id: string; }; readonly database: { url?: string; directUrl?: string; path?: string; }; readonly embedding?: { model: string; dimensions: number; } | undefined; readonly embedded_core: boolean; readonly engine: \"postgres\" | \"pglite\"; readonly pool?: { max?: number; } | undefined; readonly storage?: StorageConfig | undefined; readonly storagePrefix?: string | undefined; readonly keyword_statement_timeout_ms?: number | undefined; readonly ai?: Record<string, unknown> | undefined; readonly writer?: { id: string; lane: \"cli\" | \"stdio\"; } | undefined; }"
+ ]
+ },
+ {
+ "kind": "interface",
+ "members": [
+ "ai?: Record<string, unknown> | undefined",
+ "database: { url?: string; directUrl?: string; path?: string; }",
+ "embedded_core: boolean",
+ "embedding?: { model: string; dimensions: number; } | undefined",
+ "engine: \"postgres\" | \"pglite\"",
+ "host: { id: string; }",
+ "keyword_statement_timeout_ms?: number | undefined",
+ "pglite?: { shared_buffers?: string; } | undefined",
+ "pool?: { max?: number; } | undefined",
+ "storage?: StorageConfig | undefined",
+ "storagePrefix?: string | undefined",
+ "writer?: { id: string; credential: string; lane: \"cli\" | \"stdio\"; } | undefined"
+ ],
+ "name": "EngineSettings"
+ },
+ {
+ "kind": "function",
+ "name": "embeddedSettings",
+ "signature": [
+ "(engine: object) => EmbeddedSettingsView | undefined"
+ ]
+ },
+ {
+ "kind": "function",
+ "name": "hostIdFor",
+ "signature": [
+ "(engine?: object) => string"
+ ]
+ },
+ {
+ "kind": "function",
+ "name": "isEmbeddedEngine",
+ "signature": [
+ "(engine: object) => boolean"
+ ]
+ },
+ {
+ "kind": "function",
+ "name": "openEngine",
+ "signature": [
+ "(settings: EngineSettings) => Promise<BrainEngine>"
+ ]
+ },
+ {
+ "kind": "function",
+ "name": "processHasEmbeddedEngines",
+ "signature": [
+ "() => boolean"
+ ]
+ },
+ {
+ "kind": "function",
+ "name": "registerLocalWriterValue",
+ "signature": [
+ "(engine: SqlEngine, local: LocalRegistration, grant?: LocalGrant) => Promise<void>"
+ ]
+ }
+ ],
"./eval/longmemeval/reader": [
{
"kind": "variable",
@@ -6712,7 +6788,7 @@
{
"kind": "class",
"members": [
- "canonical?: \"unknown\" | \"keyword_candidates_incomplete\" | \"projection_pending\" | \"timeout\" | \"rate_limited\" | \"embedding_disabled\" | \"writer_lock_unavailable\" | \"writer_pool_capacity\" | \"owner_unavailable\" | \"recovery_required\" | \"queue_capacity\" | \"write_quota_exhausted\" | \"write_quota_insufficient\" | \"write_capacity_backpressure\" | \"revision_required\" | \"revision_conflict\" | \"idempotency_conflict\" | \"source_changed\" | \"write_pending\" | \"storage_error\" | \"cancelled\" | \"permission_denied\" | \"scope_denied\" | \"invalid_params\" | \"not_found\" | \"page_not_found\" | \"page_identity_changed\" | \"write_claim_lost\" | \"request_too_large\" | \"response_too_large\" | \"writer_registration_required\" | \"writer_identity_invalid\" | \"writer_not_initialized\" | \"writer_coordinator_required\" | \"fact_already_expired\" | \"source_writeback_required\" | \"unsupported_mutation_protocol\" | \"writer_upgrade_required\" | \"writer_not_quiesced\" | \"skill_bundle_required\" | \"take_row_collision\" | \"invalid_source_uri\" | \"writer_admin_locked\" | \"connector_account_changed\" | \"connector_intent_outdated\" | \"checkpoint_validation_timeout\" | \"invalid_connector_text\" | \"connector_holds_exhausted\" | \"connector_fence_below_timeline\" | \"core_budget_exceeded\" | \"core_mark_owner_only\" | \"core_remote_edit_refused\" | \"core_delete_owner_only\" | \"timeline_rows_would_be_removed\" | \"purged_content\" | \"preparation_stalled\" | \"fence_unrenderable\" | \"page_body_segmented\" | \"revision_changed\" | \"tail_changed\" | \"write_outcome_unknown\" | \"write_interrupted\" | \"connection_inherited_read_only\" | \"owner_marker_missing\" | \"embedding_failed\" | \"bucket_not_found\" | \"database_error\" | \"unknown_transport\" | \"extraction_failed\" | \"fact_not_found\" | \"provenance_required\" | \"unavailable\" | \"budget_unsatisfiable\" | \"embedding_budget_below_worst_case\" | \"absent_from_worktree\" | \"access_command_failed\" | \"access_member_disabled\" | \"on_behalf_of_invalid_audience\" | \"on_behalf_of_unknown_member\" | \"on_behalf_of_not_permitted\" | \"actor_not_attested\" | \"actor_unlinked\" | \"on_behalf_of_in_arguments\" | \"access_policy_invalid\" | \"access_policy_pending\" | \"access_policy_widening_held\" | \"access_policy_store_mismatch\" | \"access_rule_invalid\" | \"access_member_id_retired\" | \"access_member_invalid\" | \"access_denied_test_user\" | \"access_env_missing\" | \"acknowledgment_unavailable\" | \"admin_policy_enforced\" | \"admission_paused\" | \"ambient_capture_off\" | \"ambiguous_id\" | \"ambiguous_ref\" | \"ambiguous_skill\" | \"answer_not_yours\" | \"answer_pending\" | \"answer_unavailable\" | \"api_not_enabled\" | \"approval_required\" | \"atom_drain_incomplete\" | \"atom_drain_no_progress\" | \"atom_drain_provider_failure\" | \"autopilot_job_owned_by_other_brain\" | \"body_staging_expired\" | \"budget_below_recent_runtime\" | \"backup_dump_failed\" | \"backup_too_large\" | \"belief_coverage_required\" | \"belief_stale_preparation\" | \"benchmark_duplicate_task_id\" | \"benchmark_empty\" | \"benchmark_exists\" | \"benchmark_judge_llm_no_rubric\" | \"benchmark_judge_qrels_no_expected\" | \"benchmark_judge_rule_no_checks\" | \"benchmark_judge_unknown_kind\" | \"benchmark_malformed\" | \"benchmark_missing_judge\" | \"benchmark_missing_task\" | \"benchmark_missing_task_id\" | \"benchmark_not_found\" | \"benchmark_rule_check_bad_arg\" | \"benchmark_rule_check_malformed\" | \"benchmark_rule_check_unknown_op\" | \"bootstrap_cleanup_pending\" | \"bootstrap_empty\" | \"bootstrap_pending_review\" | \"bridge_ownership_conflict\" | \"coverage_from\" | \"coverage_gap\" | \"clock_mismatch\" | \"extract_write_lost\" | \"item_failures_systemic\" | \"known_as_of_unproven\" | \"cache_quota_exceeded\" | \"calendar_unreadable\" | \"capacity_paused\" | \"catalog_capacity_exceeded\" | \"catalog_unavailable\" | \"changed_since_preview\" | \"chronicle_skipped\" | \"no_pricing\" | \"checkpoint_missing\" | \"claim_already_used\" | \"client_json_unreadable\" | \"client_json_wrong_type\" | \"client_not_found\" | \"client_shape_invalid\" | \"code_callees_requires_symbol\" | \"code_callers_requires_symbol\" | \"code_def_requires_symbol\" | \"code_refs_requires_symbol\" | \"code_reused\" | \"colon_slug_windows_write_through\" | \"command_failed\" | \"commit_lock_busy\" | \"commit_paths_invalid\" | \"commit_prestaged_paths\" | \"commit_outside_source_root\" | \"concurrent_write\" | \"config_error\" | \"confirmation_required\" | \"conflicting_source_scope\" | \"connection_lost\" | \"connector_access_denied\" | \"connector_auth_required\" | \"connector_binding_missing\" | \"connector_item_too_large\" | \"connector_response_too_large\" | \"connector_shape_drift\" | \"chunkless_pages_healable\" | \"consent_required\" | \"consent_timeout\" | \"consumers_without_heartbeat\" | \"content_repair_needs_human\" | \"content_null_bytes\" | \"content_rejected\" | \"continuation_unproven\" | \"corpus_chat_unavailable\" | \"corpus_window_backoff\" | \"corpus_window_dead_lettered\" | \"convergence_read_failed\" | \"cost_cap_exceeded\" | \"cost_preview_requires_yes\" | \"cursor_incarnation_retired\" | \"cycle_failed\" | \"d_sel_too_small\" | \"delta_cursor_upgrade_required\" | \"deleted_page_chunks_overdue\" | \"demo_graph_failed\" | \"demo_import_failed\" | \"demo_verification_failed\" | \"derived_cap_exhausted\" | \"destination_not_ready\" | \"drain_holder_stalled\" | \"drain_stalled\" | \"managed_sync_not_moving\" | \"dream_breaker_tripped\" | \"dirty_tree\" | \"doctor_tier_unavailable\" | \"effect_not_failed\" | \"embed_backfill_stalled\" | \"embedding_auth_failed\" | \"embedding_configuration\" | \"embedding_identity_unqualified\" | \"embedding_model_mismatch\" | \"embedding_plane_split\" | \"embedding_state_unknown\" | \"embedding_storage_unavailable\" | \"embedding_unavailable\" | \"embedding_unconfigured\" | \"embedding_width_mismatch\" | \"engine_graduated\" | \"entity_types_unavailable\" | \"eval_suite_unwired\" | \"explicit_tasks_conflict\" | \"export_limit\" | \"extractor_identity_mismatch\" | \"fact_withdrawn\" | \"fact_rows_collide\" | \"fence_row_changed\" | \"facts_absorb_write_refused\" | \"facts_backstop_skipped\" | \"facts_drain_deferred\" | \"facts_drain_job_failed\" | \"facts_payload_expired\" | \"feedback_disabled\" | \"feedback_not_authorized\" | \"fetch_failed\" | \"file_database_drift\" | \"fix_not_writable\" | \"file_drift\" | \"file_drift_mixed_selection\" | \"file_drift_state_required\" | \"file_removed_during_scan\" | \"file_unreadable\" | \"file_wins_rewrite\" | \"file_too_large\" | \"follow_approval_required\" | \"forget_requires_owner\" | \"reserved_frontmatter_key\" | \"generation_fenced\" | \"generation_held\" | \"generation_live_conflict\" | \"frontmatter_slug_conflict\" | \"full_resync_required\" | \"gate_failed\" | \"ghost_mass_delete_refused\" | \"notifier_stalled\" | \"origin_twin_mass_merge_refused\" | \"ghost_storage_unknown\" | \"git_branch_unborn\" | \"git_durability_not_enabled\" | \"git_checkout_required\" | \"git_worktree_link_broken\" | \"hosted_repo_refused\" | \"git_detached_head\" | \"git_index_conflict\" | \"git_index_locked\" | \"git_index_stale\" | \"git_target_pending\" | \"git_operation_in_progress\" | \"git_push_unavailable\" | \"git_target_changed\" | \"git_target_ignored\" | \"git_target_unsafe\" | \"git_unavailable\" | \"git_object_missing\" | \"git_conversion_blocked\" | \"git_conversion_incomplete\" | \"git_home_required\" | \"git_private_commit_refused\" | \"git_protocol_required\" | \"git_lfs_not_enabled\" | \"gitlink_not_followed\" | \"graduation_drain_timeout\" | \"graduation_embedding_dimension_mismatch\" | \"graduation_foreign_host_binding\" | \"graduation_in_progress\" | \"graduation_interrupted\" | \"graduation_rollback_writes_lost\" | \"graduation_source_writer_held\" | \"graduation_split_brain\" | \"graduation_target_auth_failed\" | \"graduation_target_ddl_unreachable\" | \"graduation_target_not_empty\" | \"graduation_target_unsupported\" | \"graduation_unclassified_table\" | \"graduation_unsupported_platform\" | \"graduation_verify_failed\" | \"grant_scope\" | \"graph_incomplete\" | \"host_identity_mismatch\" | \"harness_hook_duplicates\" | \"harness_hook_unowned\" | \"head_blocked\" | \"held_failed\" | \"held_out_overlaps_benchmark\" | \"held_out_required_for_bundled\" | \"independent_principal_required\" | \"insufficient_scope\" | \"integrate_conflict\" | \"internal\" | \"internal_error\" | \"interrupted\" | \"invalid_acknowledgment\" | \"invalid_client\" | \"invalid_fence\" | \"unclosed_ambiguous_tail\" | \"tail_exposure_approval\" | \"sync_in_progress\" | \"invalid_frontmatter\" | \"invalid_grant_clock_skew\" | \"invalid_grant_revoked\" | \"invalid_grant_testing_expiry\" | \"invalid_rating\" | \"invalid_receipt\" | \"invalid_receipt_transition\" | \"invalid_request\" | \"invalid_source\" | \"invalid_source_pin\" | \"invalid_token\" | \"invalid_write_wait\" | \"ipc_path_too_long\" | \"legacy_twin_mass_merge_refused\" | \"legacy_twins_storage_unknown\" | \"legacy_job_selection_invalid\" | \"legacy_jobs_active\" | \"legacy_lock_removal_refused\" | \"link_cursor_invalid\" | \"local_conflict\" | \"lock_busy\" | \"loops_extraction_skipped\" | \"maintenance_backpressure\" | \"maintenance_lock_busy\" | \"managed_failure_unsettled\" | \"managed_remedy_unavailable\" | \"merge_recommended\" | \"movement_unknown\" | \"managed_sync_flag_refused\" | \"managed_pull_skipped\" | \"manual_only_skipped\" | \"membership_inactive\" | \"membership_not_found\" | \"method_not_allowed\" | \"migration_lease_lost\" | \"migration_declined\" | \"migration_failed\" | \"migration_host_work_pending\" | \"migrations_pending\" | \"migrations_running\" | \"missing_source_scope\" | \"missing_source_value\" | \"models_strict_violation\" | \"no_context_ceiling\" | \"no_refresh_token\" | \"no_routing_eval\" | \"no_skill_md\" | \"no_worker\" | \"no_worker_surface\" | \"not_a_git_repo\" | \"not_converged\" | \"not_owner_host\" | \"not_connected\" | \"no_brain\" | \"overlapping_path\" | \"page_projection_conflict\" | \"page_body_rows_unreadable\" | \"page_projection_stale\" | \"page_shrink_refused\" | \"page_too_large_for_inline\" | \"parse_error\" | \"part_splits_code_point\" | \"part_too_large\" | \"frontmatter_alias_limit\" | \"parser_regression\" | \"pasted_wrong_url\" | \"payload_too_large\" | \"path_not_utf8\" | \"pattern_claims_pending\" | \"patterns_min_interval\" | \"pending_verify\" | \"pending_writes\" | \"persistence_restart_required\" | \"pool_inflight_over_budget\" | \"deep_health_probe_failed\" | \"refresh_required\" | \"serve_self_exit_suppressed\" | \"serve_unhealthy_exit\" | \"persistence_write_stall\" | \"push_unconfirmed\" | \"schema_lock_blocked\" | \"pg_connection_recovery_failed\" | \"pg_connection_stuck\" | \"pg_pool_stalled\" | \"pg_statement_build_failed\" | \"pglite_busy\" | \"pglite_vector_index_too_large\" | \"plan_output_failed\" | \"plan_stale\" | \"port_in_use\" | \"preview_changed\" | \"profile_incompatible\" | \"projection_owner_resident\" | \"knock_on_exhausted\" | \"keyword_skipped_after_timeout\" | \"publication_pending\" | \"pull_blocked_local_changes\" | \"purge_blocked_pending_recovery\" | \"purge_lookup_timeout\" | \"purge_mirror_unwritable\" | \"question_not_found\" | \"question_owner_only\" | \"rank_entities_timeout\" | \"read_budget_exhausted\" | \"receipt_conflict\" | \"receipt_fence_changed\" | \"receipt_fence_required\" | \"receipt_identity_mismatch\" | \"pat_file_unreadable\" | \"reconcile_host_required\" | \"reconcile_read_incomplete\" | \"recovery_prior_stage_unavailable\" | \"recovery_version_unsupported\" | \"redirect_uri_mismatch\" | \"ref_not_in_answer\" | \"refresh_dirty\" | \"refresh_diverged\" | \"refresh_drain_timeout\" | \"refresh_lock_timeout\" | \"refresh_no_upstream\" | \"refresh_not_managed\" | \"refresh_not_owner\" | \"refresh_source_changed\" | \"refresh_sync_timeout\" | \"relay_disabled\" | \"relay_session_expired\" | \"relay_unreachable\" | \"rename_held\" | \"rename_identity_unreadable\" | \"rename_reconcile_failed\" | \"request_already_submitted\" | \"requirements_changed\" | \"requires_local_engine\" | \"restart_refused\" | \"restart_unverified\" | \"runtime_build_skew\" | \"reset_upstream_refused\" | \"resume_spec_mismatch\" | \"result_too_large\" | \"revision_unavailable\" | \"schema_owner_required\" | \"scope_missing\" | \"search_cursor_requires_keyword\" | \"search_mode_local_only\" | \"scorecard_group_by_local_only\" | \"search_offset_over_cap\" | \"segmented_mirror_writer_gate\" | \"serve_build_drift\" | \"serve_port_in_use\" | \"serve_status_only\" | \"settle_mismatch\" | \"setup_harness_unsupported\" | \"setup_hosted_connection\" | \"setup_owner_conflict\" | \"hook_session_cwd\" | \"turn_hook_not_loaded\" | \"shared_skills_unavailable\" | \"shared_skills_unsupported\" | \"skill_asset_not_found\" | \"skill_candidate_invalid\" | \"skill_not_found\" | \"skill_retention_capacity\" | \"skill_unavailable\" | \"slug_page_mismatch\" | \"slug_root_mode_mismatch\" | \"source_binding_required\" | \"source_id_taken\" | \"source_mismatch\" | \"source_not_ready\" | \"source_profile_no_backfill\" | \"source_referenced\" | \"source_root_conflict\" | \"sources_not_readable\" | \"split_bad_ratio\" | \"split_unparseable\" | \"stable_channel_unresolved\" | \"stale_unavailable\" | \"state_mismatch\" | \"strict_requires_managed\" | \"sync_anchor_relative\" | \"sync_not_applicable\" | \"sync_admission_restricted\" | \"sync_deadline_stalled\" | \"sync_drain_lease_held\" | \"content_receipt_stale\" | \"sync_first_run_in_progress\" | \"sync_no_successful_sync\" | \"sync_cursor_replaced\" | \"sync_pass_superseded\" | \"sync_parser_regression\" | \"target_escape\" | \"timeline_comment_markup\" | \"readable_by_invalid\" | \"topology_change_required\" | \"transcript_secret_exposure\" | \"transcript_source_mismatch\" | \"triage_unreliable_backoff\" | \"trust_raise_refused\" | \"two_consumers_on_host\" | \"trusted_local_only\" | \"unexpected_file_bytes\" | \"unexpected_staging_bytes\" | \"unknown_command\" | \"unknown_flag\" | \"unknown_method\" | \"unknown_source\" | \"unknown_tool\" | \"unpriced_model\" | \"unmanaged_database_path\" | \"unmanaged_path\" | \"unsupported_export_data\" | \"unsupported_path\" | \"upload_expired\" | \"upload_not_found\" | \"upload_protected_content\" | \"upload_too_many_parts\" | \"upstream\" | \"upstream_diverged\" | \"upstream_rewritten\" | \"upstream_unknown\" | \"vector_prewarm_extension_missing\" | \"vector_prewarm_unsupported_engine\" | \"vector_prewarm_wont_fit\" | \"verification_failed\" | \"visibility_noncanonical\" | \"visibility_not_applied\" | \"withdrawal_capacity\" | \"withdrawal_mirror_failed\" | \"withdrawal_mirror_pending\" | \"withdrawal_provenance\" | \"write_capacity_low\" | \"write_gate_rejected\" | \"write_held\" | \"worktree_dirty\" | \"writer_admin_intent_required\" | \"writer_admin_state_changed\" | \"writer_busy\" | \"writer_identity_publish_failed\" | \"writer_manifest_mismatch\" | \"writer_manifest_rescope_required\" | \"writer_manifest_unsafe\" | \"writer_regrant_required\" | \"writer_transfer_conflict\" | \"writer_transfer_required\" | \"wrong_account_consented\" | \"schema_pack_too_large\" | \"schema_pack_emit_mismatch\" | undefined",
+ "canonical?: \"unknown\" | \"keyword_candidates_incomplete\" | \"projection_pending\" | \"timeout\" | \"rate_limited\" | \"embedding_disabled\" | \"writer_lock_unavailable\" | \"writer_pool_capacity\" | \"owner_unavailable\" | \"recovery_required\" | \"queue_capacity\" | \"write_quota_exhausted\" | \"write_quota_insufficient\" | \"write_capacity_backpressure\" | \"revision_required\" | \"revision_conflict\" | \"idempotency_conflict\" | \"source_changed\" | \"write_pending\" | \"storage_error\" | \"cancelled\" | \"permission_denied\" | \"scope_denied\" | \"invalid_params\" | \"not_found\" | \"page_not_found\" | \"page_identity_changed\" | \"write_claim_lost\" | \"request_too_large\" | \"response_too_large\" | \"writer_registration_required\" | \"writer_identity_invalid\" | \"writer_not_initialized\" | \"writer_coordinator_required\" | \"fact_already_expired\" | \"source_writeback_required\" | \"unsupported_mutation_protocol\" | \"writer_upgrade_required\" | \"writer_not_quiesced\" | \"skill_bundle_required\" | \"take_row_collision\" | \"invalid_source_uri\" | \"writer_admin_locked\" | \"connector_account_changed\" | \"connector_intent_outdated\" | \"checkpoint_validation_timeout\" | \"invalid_connector_text\" | \"connector_holds_exhausted\" | \"connector_fence_below_timeline\" | \"core_budget_exceeded\" | \"core_mark_owner_only\" | \"core_remote_edit_refused\" | \"core_delete_owner_only\" | \"timeline_rows_would_be_removed\" | \"purged_content\" | \"preparation_stalled\" | \"fence_unrenderable\" | \"page_body_segmented\" | \"revision_changed\" | \"tail_changed\" | \"write_outcome_unknown\" | \"write_interrupted\" | \"connection_inherited_read_only\" | \"owner_marker_missing\" | \"embedding_failed\" | \"bucket_not_found\" | \"database_error\" | \"unknown_transport\" | \"extraction_failed\" | \"fact_not_found\" | \"provenance_required\" | \"unavailable\" | \"budget_unsatisfiable\" | \"embedding_budget_below_worst_case\" | \"absent_from_worktree\" | \"access_command_failed\" | \"access_member_disabled\" | \"on_behalf_of_invalid_audience\" | \"on_behalf_of_unknown_member\" | \"on_behalf_of_not_permitted\" | \"actor_not_attested\" | \"actor_unlinked\" | \"on_behalf_of_in_arguments\" | \"access_policy_invalid\" | \"access_policy_pending\" | \"access_policy_widening_held\" | \"access_policy_store_mismatch\" | \"access_rule_invalid\" | \"access_member_id_retired\" | \"access_member_invalid\" | \"access_denied_test_user\" | \"access_env_missing\" | \"acknowledgment_unavailable\" | \"admin_policy_enforced\" | \"admission_paused\" | \"ambient_capture_off\" | \"ambiguous_id\" | \"ambiguous_ref\" | \"ambiguous_skill\" | \"answer_not_yours\" | \"answer_pending\" | \"answer_unavailable\" | \"api_not_enabled\" | \"approval_required\" | \"atom_drain_incomplete\" | \"atom_drain_no_progress\" | \"atom_drain_provider_failure\" | \"autopilot_job_owned_by_other_brain\" | \"body_staging_expired\" | \"budget_below_recent_runtime\" | \"backup_dump_failed\" | \"backup_too_large\" | \"belief_coverage_required\" | \"belief_stale_preparation\" | \"benchmark_duplicate_task_id\" | \"benchmark_empty\" | \"benchmark_exists\" | \"benchmark_judge_llm_no_rubric\" | \"benchmark_judge_qrels_no_expected\" | \"benchmark_judge_rule_no_checks\" | \"benchmark_judge_unknown_kind\" | \"benchmark_malformed\" | \"benchmark_missing_judge\" | \"benchmark_missing_task\" | \"benchmark_missing_task_id\" | \"benchmark_not_found\" | \"benchmark_rule_check_bad_arg\" | \"benchmark_rule_check_malformed\" | \"benchmark_rule_check_unknown_op\" | \"bootstrap_cleanup_pending\" | \"bootstrap_empty\" | \"bootstrap_pending_review\" | \"bridge_ownership_conflict\" | \"coverage_from\" | \"coverage_gap\" | \"clock_mismatch\" | \"extract_write_lost\" | \"item_failures_systemic\" | \"known_as_of_unproven\" | \"cache_quota_exceeded\" | \"calendar_unreadable\" | \"capacity_paused\" | \"catalog_capacity_exceeded\" | \"catalog_unavailable\" | \"changed_since_preview\" | \"chronicle_skipped\" | \"no_pricing\" | \"checkpoint_missing\" | \"claim_already_used\" | \"client_json_unreadable\" | \"client_json_wrong_type\" | \"client_not_found\" | \"client_shape_invalid\" | \"code_callees_requires_symbol\" | \"code_callers_requires_symbol\" | \"code_def_requires_symbol\" | \"code_refs_requires_symbol\" | \"code_reused\" | \"colon_slug_windows_write_through\" | \"command_failed\" | \"commit_lock_busy\" | \"commit_paths_invalid\" | \"commit_prestaged_paths\" | \"commit_outside_source_root\" | \"concurrent_write\" | \"config_error\" | \"confirmation_required\" | \"conflicting_source_scope\" | \"connection_lost\" | \"connector_access_denied\" | \"connector_auth_required\" | \"connector_binding_missing\" | \"connector_item_too_large\" | \"connector_response_too_large\" | \"connector_shape_drift\" | \"chunkless_pages_healable\" | \"consent_required\" | \"consent_timeout\" | \"consumers_without_heartbeat\" | \"content_repair_needs_human\" | \"content_null_bytes\" | \"content_rejected\" | \"continuation_unproven\" | \"corpus_chat_unavailable\" | \"corpus_window_backoff\" | \"corpus_window_dead_lettered\" | \"convergence_read_failed\" | \"cost_cap_exceeded\" | \"cost_preview_requires_yes\" | \"cursor_incarnation_retired\" | \"cycle_failed\" | \"d_sel_too_small\" | \"delta_cursor_upgrade_required\" | \"deleted_page_chunks_overdue\" | \"demo_graph_failed\" | \"demo_import_failed\" | \"demo_verification_failed\" | \"derived_cap_exhausted\" | \"destination_not_ready\" | \"drain_holder_stalled\" | \"drain_stalled\" | \"managed_sync_not_moving\" | \"dream_breaker_tripped\" | \"dirty_tree\" | \"doctor_tier_unavailable\" | \"effect_not_failed\" | \"embed_backfill_stalled\" | \"embedding_auth_failed\" | \"embedding_configuration\" | \"embedding_identity_unqualified\" | \"embedding_model_mismatch\" | \"embedding_plane_split\" | \"embedding_state_unknown\" | \"embedding_storage_unavailable\" | \"embedding_unavailable\" | \"embedding_unconfigured\" | \"embedding_width_mismatch\" | \"embedded_core_required\" | \"engine_embedding_mismatch\" | \"engine_host_missing\" | \"engine_settings_invalid\" | \"engine_graduated\" | \"entity_types_unavailable\" | \"eval_suite_unwired\" | \"explicit_tasks_conflict\" | \"export_limit\" | \"extractor_identity_mismatch\" | \"fact_withdrawn\" | \"fact_rows_collide\" | \"fence_row_changed\" | \"facts_absorb_write_refused\" | \"facts_backstop_skipped\" | \"facts_drain_deferred\" | \"facts_drain_job_failed\" | \"facts_payload_expired\" | \"feedback_disabled\" | \"feedback_not_authorized\" | \"fetch_failed\" | \"file_database_drift\" | \"fix_not_writable\" | \"file_drift\" | \"file_drift_mixed_selection\" | \"file_drift_state_required\" | \"file_removed_during_scan\" | \"file_unreadable\" | \"file_wins_rewrite\" | \"file_too_large\" | \"follow_approval_required\" | \"forget_requires_owner\" | \"reserved_frontmatter_key\" | \"generation_fenced\" | \"generation_held\" | \"generation_live_conflict\" | \"frontmatter_slug_conflict\" | \"full_resync_required\" | \"gate_failed\" | \"ghost_mass_delete_refused\" | \"notifier_stalled\" | \"origin_twin_mass_merge_refused\" | \"ghost_storage_unknown\" | \"git_branch_unborn\" | \"git_durability_not_enabled\" | \"git_checkout_required\" | \"git_worktree_link_broken\" | \"hosted_repo_refused\" | \"git_detached_head\" | \"git_index_conflict\" | \"git_index_locked\" | \"git_index_stale\" | \"git_target_pending\" | \"git_operation_in_progress\" | \"git_push_unavailable\" | \"git_target_changed\" | \"git_target_ignored\" | \"git_target_unsafe\" | \"git_unavailable\" | \"git_object_missing\" | \"git_conversion_blocked\" | \"git_conversion_incomplete\" | \"git_home_required\" | \"git_private_commit_refused\" | \"git_protocol_required\" | \"git_lfs_not_enabled\" | \"gitlink_not_followed\" | \"graduation_drain_timeout\" | \"graduation_embedding_dimension_mismatch\" | \"graduation_foreign_host_binding\" | \"graduation_in_progress\" | \"graduation_interrupted\" | \"graduation_rollback_writes_lost\" | \"graduation_source_writer_held\" | \"graduation_split_brain\" | \"graduation_target_auth_failed\" | \"graduation_target_ddl_unreachable\" | \"graduation_target_not_empty\" | \"graduation_target_unsupported\" | \"graduation_unclassified_table\" | \"graduation_unsupported_platform\" | \"graduation_verify_failed\" | \"grant_scope\" | \"graph_incomplete\" | \"host_identity_mismatch\" | \"harness_hook_duplicates\" | \"harness_hook_unowned\" | \"head_blocked\" | \"held_failed\" | \"held_out_overlaps_benchmark\" | \"held_out_required_for_bundled\" | \"independent_principal_required\" | \"insufficient_scope\" | \"integrate_conflict\" | \"internal\" | \"internal_error\" | \"interrupted\" | \"invalid_acknowledgment\" | \"invalid_client\" | \"invalid_fence\" | \"unclosed_ambiguous_tail\" | \"tail_exposure_approval\" | \"sync_in_progress\" | \"invalid_frontmatter\" | \"invalid_grant_clock_skew\" | \"invalid_grant_revoked\" | \"invalid_grant_testing_expiry\" | \"invalid_rating\" | \"invalid_receipt\" | \"invalid_receipt_transition\" | \"invalid_request\" | \"invalid_source\" | \"invalid_source_pin\" | \"invalid_token\" | \"invalid_write_wait\" | \"ipc_path_too_long\" | \"legacy_twin_mass_merge_refused\" | \"legacy_twins_storage_unknown\" | \"legacy_job_selection_invalid\" | \"legacy_jobs_active\" | \"legacy_lock_removal_refused\" | \"link_cursor_invalid\" | \"local_conflict\" | \"lock_busy\" | \"loops_extraction_skipped\" | \"maintenance_backpressure\" | \"maintenance_lock_busy\" | \"managed_failure_unsettled\" | \"managed_remedy_unavailable\" | \"merge_recommended\" | \"movement_unknown\" | \"managed_sync_flag_refused\" | \"managed_pull_skipped\" | \"manual_only_skipped\" | \"membership_inactive\" | \"membership_not_found\" | \"method_not_allowed\" | \"migration_lease_lost\" | \"migration_declined\" | \"migration_failed\" | \"migration_host_work_pending\" | \"migrations_pending\" | \"migrations_running\" | \"missing_source_scope\" | \"missing_source_value\" | \"models_strict_violation\" | \"no_context_ceiling\" | \"no_refresh_token\" | \"no_routing_eval\" | \"no_skill_md\" | \"no_worker\" | \"no_worker_surface\" | \"not_a_git_repo\" | \"not_converged\" | \"not_owner_host\" | \"not_connected\" | \"no_brain\" | \"overlapping_path\" | \"page_projection_conflict\" | \"page_body_rows_unreadable\" | \"page_projection_stale\" | \"page_shrink_refused\" | \"page_too_large_for_inline\" | \"parse_error\" | \"part_splits_code_point\" | \"part_too_large\" | \"frontmatter_alias_limit\" | \"parser_regression\" | \"pasted_wrong_url\" | \"payload_too_large\" | \"path_not_utf8\" | \"pattern_claims_pending\" | \"patterns_min_interval\" | \"pending_verify\" | \"pending_writes\" | \"persistence_restart_required\" | \"pool_inflight_over_budget\" | \"deep_health_probe_failed\" | \"refresh_required\" | \"serve_self_exit_suppressed\" | \"serve_unhealthy_exit\" | \"persistence_write_stall\" | \"push_unconfirmed\" | \"schema_lock_blocked\" | \"pg_connection_recovery_failed\" | \"pg_connection_stuck\" | \"pg_pool_stalled\" | \"pg_statement_build_failed\" | \"pglite_busy\" | \"pglite_vector_index_too_large\" | \"plan_output_failed\" | \"plan_stale\" | \"port_in_use\" | \"preview_changed\" | \"profile_incompatible\" | \"projection_owner_resident\" | \"knock_on_exhausted\" | \"keyword_skipped_after_timeout\" | \"publication_pending\" | \"pull_blocked_local_changes\" | \"purge_blocked_pending_recovery\" | \"purge_lookup_timeout\" | \"purge_mirror_unwritable\" | \"question_not_found\" | \"question_owner_only\" | \"rank_entities_timeout\" | \"read_budget_exhausted\" | \"receipt_conflict\" | \"receipt_fence_changed\" | \"receipt_fence_required\" | \"receipt_identity_mismatch\" | \"pat_file_unreadable\" | \"reconcile_host_required\" | \"reconcile_read_incomplete\" | \"recovery_prior_stage_unavailable\" | \"recovery_version_unsupported\" | \"redirect_uri_mismatch\" | \"ref_not_in_answer\" | \"refresh_dirty\" | \"refresh_diverged\" | \"refresh_drain_timeout\" | \"refresh_lock_timeout\" | \"refresh_no_upstream\" | \"refresh_not_managed\" | \"refresh_not_owner\" | \"refresh_source_changed\" | \"refresh_sync_timeout\" | \"relay_disabled\" | \"relay_session_expired\" | \"relay_unreachable\" | \"rename_held\" | \"rename_identity_unreadable\" | \"rename_reconcile_failed\" | \"request_already_submitted\" | \"requirements_changed\" | \"requires_local_engine\" | \"restart_refused\" | \"restart_unverified\" | \"runtime_build_skew\" | \"reset_upstream_refused\" | \"resume_spec_mismatch\" | \"result_too_large\" | \"revision_unavailable\" | \"schema_owner_required\" | \"scope_missing\" | \"search_cursor_requires_keyword\" | \"search_mode_local_only\" | \"scorecard_group_by_local_only\" | \"search_offset_over_cap\" | \"segmented_mirror_writer_gate\" | \"serve_build_drift\" | \"serve_port_in_use\" | \"serve_status_only\" | \"settle_mismatch\" | \"setup_harness_unsupported\" | \"setup_hosted_connection\" | \"setup_owner_conflict\" | \"hook_session_cwd\" | \"turn_hook_not_loaded\" | \"shared_skills_unavailable\" | \"shared_skills_unsupported\" | \"skill_asset_not_found\" | \"skill_candidate_invalid\" | \"skill_not_found\" | \"skill_retention_capacity\" | \"skill_unavailable\" | \"slug_page_mismatch\" | \"slug_root_mode_mismatch\" | \"source_binding_required\" | \"source_id_taken\" | \"source_mismatch\" | \"source_not_ready\" | \"source_profile_no_backfill\" | \"source_referenced\" | \"source_root_conflict\" | \"sources_not_readable\" | \"split_bad_ratio\" | \"split_unparseable\" | \"stable_channel_unresolved\" | \"stale_unavailable\" | \"state_mismatch\" | \"strict_requires_managed\" | \"sync_anchor_relative\" | \"sync_not_applicable\" | \"sync_admission_restricted\" | \"sync_deadline_stalled\" | \"sync_drain_lease_held\" | \"content_receipt_stale\" | \"sync_first_run_in_progress\" | \"sync_no_successful_sync\" | \"sync_cursor_replaced\" | \"sync_pass_superseded\" | \"sync_parser_regression\" | \"target_escape\" | \"timeline_comment_markup\" | \"readable_by_invalid\" | \"topology_change_required\" | \"transcript_secret_exposure\" | \"transcript_source_mismatch\" | \"triage_unreliable_backoff\" | \"trust_raise_refused\" | \"two_consumers_on_host\" | \"trusted_local_only\" | \"unexpected_file_bytes\" | \"unexpected_staging_bytes\" | \"unknown_command\" | \"unknown_flag\" | \"unknown_method\" | \"unknown_source\" | \"unknown_tool\" | \"unpriced_model\" | \"unmanaged_database_path\" | \"unmanaged_path\" | \"unsupported_export_data\" | \"unsupported_path\" | \"upload_expired\" | \"upload_not_found\" | \"upload_protected_content\" | \"upload_too_many_parts\" | \"upstream\" | \"upstream_diverged\" | \"upstream_rewritten\" | \"upstream_unknown\" | \"vector_prewarm_extension_missing\" | \"vector_prewarm_unsupported_engine\" | \"vector_prewarm_wont_fit\" | \"verification_failed\" | \"visibility_noncanonical\" | \"visibility_not_applied\" | \"withdrawal_capacity\" | \"withdrawal_mirror_failed\" | \"withdrawal_mirror_pending\" | \"withdrawal_provenance\" | \"write_capacity_low\" | \"write_gate_rejected\" | \"write_held\" | \"worktree_dirty\" | \"writer_admin_intent_required\" | \"writer_admin_state_changed\" | \"writer_busy\" | \"writer_identity_publish_failed\" | \"writer_manifest_mismatch\" | \"writer_manifest_rescope_required\" | \"writer_manifest_unsafe\" | \"writer_regrant_required\" | \"writer_transfer_conflict\" | \"writer_transfer_required\" | \"wrong_account_consented\" | \"schema_pack_too_large\" | \"schema_pack_emit_mismatch\" | undefined",
"canonicalCode: string",
"cause?: unknown",
"code: ErrorCode",
diff --git a/test/public-exports.test.ts b/test/public-exports.test.ts
index 7ef0eb9c97..ca6ef7b3ba 100644
--- a/test/public-exports.test.ts
+++ b/test/public-exports.test.ts
@@ -39,6 +39,7 @@ const EXPECTED_EXPORTS: ExpectedExport[] = [
{ subpath: 'gbrain/operations', canary: ['operations', 'OperationError'] },
{ subpath: 'gbrain/minions', canary: [] }, // barrel module; re-exports many names
{ subpath: 'gbrain/engine-factory', canary: [] }, // factory exports a default creator
+ { subpath: 'gbrain/engine-open', canary: ['openEngine', 'DEFAULT_EMBEDDED_POOL_MAX'] },
{ subpath: 'gbrain/pglite-engine', canary: ['PGLiteEngine'] },
{ subpath: 'gbrain/link-extraction', canary: ['extractEntityRefs', 'extractPageLinks'] },
{ subpath: 'gbrain/import-file', canary: ['importFromContent'] },
@@ -81,7 +82,8 @@ describe('public exports — package.json exports map', () => {
// breaking change going forward" — bump minor and update this count.
// 23→24 (2026-08 fix wave): ./core/skillopt (audit skillopt-cats-11).
// 28→29: ./version (gbrain-evals reads the installed version directly).
- expect(count).toBe(29);
+ // 29→30: ./engine-open (experimental openEngine(settings), GBRA-283 Wave B1).
+ expect(count).toBe(30);
});
test('EXPECTED_EXPORTS list matches the exports map exactly (no drift)', () => {