Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
perf(cli): cold one-shot reads pay fewer round trips and skip the write path's modules (#7147 follow-up)
garrytane118508a7d5c
diff --git a/docs/architecture/key-files/core-persistence-graduation.md b/docs/architecture/key-files/core-persistence-graduation.mdindex 3445d29134..5824f39e32 100644--- a/docs/architecture/key-files/core-persistence-graduation.md+++ b/docs/architecture/key-files/core-persistence-graduation.md@@ -11,7 +11,7 @@ Verified engine graduation, PGLite to Postgres ([operator guide](../../guides/mo- `src/core/persistence/graduation-errors.ts` — one builder per graduation code (`sourceWriterHeldError` … `engineGraduatedError`) so the orchestrator, CLI, serve and doctor render each refusal one way: `why`, a filled `fix` with real argv (none only for `report`), a read-only verify (`gbrain migrate --status --json`, the `--plan` form, or doctor), `GRADUATION_DOCS` anchors, and the command helpers `planArgv`/`runArgv`/`resumeArgv`/`rollbackArgv`/`statusArgv`, which echo the user's `--to` spelling and name the URL only through `--url-env`. Test: `test/graduation-errors.test.ts` (table-driven over every code; each emitted argv names a real command with accepted flags and parses to its graduation mode).- `src/core/persistence/graduation-serve-guard.ts` — file reads only (marker, tombstone, config, manifest summary; never a lock attempt): `serveGraduationStartRefusal` (a serve launched while another live run owns the host brain exits 75 with `graduation_in_progress`, called from `connectCliOnlyEngine` in `src/cli.ts`), `graduationStatusReason` (a tombstoned path is status-only `engine_graduated`), `exitOnEngineIdentityChange` (status-only and degraded reconnect gates exit 75 for relaunch when the config names another engine, a tombstone appears or a run starts; a serve started with no config keeps recovering in place), `graduationHandoffRequested` (the resident stdio serve's 2 s marker poll in `installStdioLifecycle`), and `readGraduationManifestSummary` (the redacted view of the 0600 manifest). Test: `test/graduation-serve-guard.serial.test.ts` (includes a real `gbrain serve` child exiting 75 and `engine status --json`).- `src/core/persistence/engine-graduation.ts` — the orchestrator behind `gbrain migrate --to postgres`: `planGraduation` (zero mutations: probe-only source open, one read-only target session, refuses while a run is recorded non-terminal), `runGraduation` (needs `yes` plus `expectPlanHash`; a changed plan throws `preview_changed`), `resumeGraduation`, `rollbackGraduation`, `reconcileGraduation` and `graduationStatus` (files plus a read-only target-row read; split brain opens both datastores for counts). The kernel lock is held from step 1 to the routing flip: intent marker before the lock, autopilot pause marker, source open (waits up to 30 s for a resident serve's hand-off, else `graduation_source_writer_held`), in-process source doctor, route cross-check, drain and freeze, target fence, per-table copy with manifest checkpoints, deferred index build on the DDL route, verify (doctor child under `GBRAIN_GRADUATION_RUN`, plus `GBRAIN_GRADUATION_SOURCE_PERSISTENCE` naming the source's `persistence_brain.enabled`; #6331: `persistenceEnabledForHealth` in `ownership.ts` lets `sync_freshness` and `ownedContentFreshness` treat the fenced target as writer-owned only while its graduation row is this run's `verifying` target), then fence both and grant authority (source row `cutover`, lock-retaining close, move-aside, `O_EXCL` tombstone, one target transaction that sets `persistence_brain.enabled` and drops the fence) and flip routing (config, mounts). Every state change follows the transition tables and is mirrored into the 0600 manifest (`<GBRAIN_HOME>/.gbrain/graduation-manifest.json`, the only file holding target URLs) and the marker; each step announces its `graduationBoundary`. Resume continues from the recorded state with recorded identities; a resume after a lock gap recomputes source digests and re-drains and re-copies changed tables with their FK closure. Rollback before cutover abandons the target (fence kept); after cutover it requires the retained copy (checked before the fence and again under the kernel lock; gone refuses `not_found` via `retainedCopyMissingError` with nothing changed), fences first, takes the kernel lock, compares (`graduation-losses.ts`) and returns the target to authority on any refusal; `rollback_approved` onward only rolls forward. `--resume --yes` moves a stray datastore at the old path to `<path>.stray-<run_id>`. All refusals come from `graduation-errors.ts`. Tests: `test/graduation-state.test.ts`, `test/graduation-rollback.test.ts`, `test/e2e/graduation-*.test.ts`.-- `src/core/persistence/graduation-custody.ts` — filesystem custody and the open-path checks: the sibling intent marker (atomic replace, 0600, fsync), the `O_CREAT|O_EXCL` tombstone at the old data dir path, `inspectGraduationPath` (`none`, `in_progress`, `interrupted`, `graduated`, `split_brain`; marker liveness from pid, boot id, pid namespace and process start time; a recorded boot id or pid namespace this process cannot read for itself is `unknown`, never a match), `assertPgliteGraduationOpenable` (called by `PGLiteEngine` before `acquireLock`, so a tombstone refuses `engine_graduated` and a live run `graduation_in_progress` without touching the path, and again after the lock, refusing `graduation_interrupted` past cutover), `assertGraduationConnectAllowed` (every CLI connect: a non-authoritative target or a cut-over source refuses unless the session is the run's) and `assertGraduationAdmission` (writer admission). `moveAsideHeld` renames under the already-held kernel lock as a sanctioned filesystem publication (a managed brain's datastore is a managed root). Tests: `test/graduation-custody.test.ts`, `test/graduation-custody-probes.test.ts` (probe mocked in a child via `test/fixtures/graduation-liveness-probe.ts`).+- `src/core/persistence/graduation-custody.ts` — filesystem custody and the open-path checks: the sibling intent marker (atomic replace, 0600, fsync), the `O_CREAT|O_EXCL` tombstone at the old data dir path, `inspectGraduationPath` (`none`, `in_progress`, `interrupted`, `graduated`, `split_brain`; marker liveness from pid, boot id, pid namespace and process start time; a recorded boot id or pid namespace this process cannot read for itself is `unknown`, never a match), `assertPgliteGraduationOpenable` (called by `PGLiteEngine` before `acquireLock`, so a tombstone refuses `engine_graduated` and a live run `graduation_in_progress` without touching the path, and again after the lock, refusing `graduation_interrupted` past cutover), `assertGraduationConnectAllowed` (every CLI connect: a non-authoritative target or a cut-over source refuses unless the session is the run's; it reads the custody row in one statement through `readGraduationConnectRow`, where only an undefined table means no row) and `assertGraduationAdmission` (writer admission). `moveAsideHeld` renames under the already-held kernel lock as a sanctioned filesystem publication (a managed brain's datastore is a managed root). Tests: `test/graduation-custody.test.ts`, `test/graduation-custody-probes.test.ts` (probe mocked in a child via `test/fixtures/graduation-liveness-probe.ts`).- `src/core/persistence/graduation-schema.ts` + `src/core/schema-migrations/v201-persistence-graduation.ts` — the `persistence_graduation` singleton (each engine's own custody row; schema-owned, never copied) and `gbrain_graduation_fence()`. `installGraduationFence` puts a statement-level `ENABLE ALWAYS` trigger on every table that refuses writes unless `gbrain.graduation_run` equals the row's run id; `dropGraduationFence`, `setTargetState`/`setSourceState` (transition-table driven) and `withGraduationRun`.- `src/core/persistence/graduation-losses.ts` — rollback write detection: per carried table, the target digest against the verified receipt (`persistence_brain.enabled` through its transform), requests after the cutover sequence, and the security tables plus `fact_withdrawals` against the retained PGLite copy by identity and content (`last_used_at` ignored, expired OAuth tokens may disappear). Missing or changed security rows and new withdrawals are final.- `src/commands/migrate-graduation.ts` — the `gbrain migrate` graduation CLI, routed before connect from `routeEngineFreeSubcommands` in `src/cli.ts` when `routesToGraduation` holds (run-scoped verbs and `--plan` always; a bare `--to postgres|supabase` on a durable PGLite config unless `migrate.graduation` is false or the host is Windows). Without `--yes --expect` it plans and returns the `confirmation_required` payload (effects egress and destructive, what moves and what stays, `plan_hash`, the `--plan` preview; no stdin prompt); `--plan`/`--dry-run` prints the plan; the run reports the receipt, retained copy, target doctor, `gbrain mcp expose` and the MCP restart note. Exit codes 0/1/2/3, 11 for a progressing drain stop (1 when a blocker needs a person), 75 for `graduation_in_progress`, 130 after SIGINT (stops at the next batch boundary). `--json` prints one document; progress goes to stderr per table and batch. Test: `test/migrate-graduation-cli.serial.test.ts`.diff --git a/docs/architecture/key-files/core-services-2.md b/docs/architecture/key-files/core-services-2.mdindex 2576ab87b6..9775633cad 100644--- a/docs/architecture/key-files/core-services-2.md+++ b/docs/architecture/key-files/core-services-2.md@@ -42,7 +42,7 @@ Fact and page purge modules (`src/core/facts/purge*.ts`, `deletion-inventory.ts`- `src/core/ops/links.ts` — the link-domain op module (`add_link`, `remove_link`, `get_links`, `get_backlinks`, `list_link_sources`, `traverse_graph`); `get_backlinks`' `type`/`group`/`limit`/`cursor` live in `backlinks-paged.ts`. Three load-bearing behaviors. (1) Pack vocabulary at the write surface: an EXPLICIT `link_type` on `add_link` must be declared by the active schema pack when one resolves (`schema-pack/write-vocabulary.ts`; no resolvable pack = no enforcement; omitted/empty link_type is the untyped-edge default and stays unchecked; the check runs before the dry-run return so dry runs preview the rejection). (2) `traverse_graph` output shape: trusted local no-filter callers (`ctx.remote === false`, no `link_type`/`direction`) keep the legacy `GraphNode[]` shape that `gbrain graph` renders; remote callers default to `direction: 'both'` and always receive explicit `GraphPath[]` edges, so a page whose typed edges are all inbound does not read as edge absence. An explicit `direction` param wins for every caller. Depth: default 5 (`DEFAULT_TRAVERSE_DEPTH`), except a remote call that let direction default to `both` ALSO defaults depth to `REMOTE_BIDIRECTIONAL_DEFAULT_DEPTH` (2) — bidirectional path enumeration is combinatorial on entity hubs and this is the per-agent-turn path; a `link_type`-only remote call still takes both/2; an explicit depth is honored up to `TRAVERSE_DEPTH_CAP` (10, clamped with a warn). The edge walk runs through `engine.traversePathsDetailed`, and a hit on `TRAVERSE_PATH_ROW_CAP` (`engine-constants.ts`) surfaces as a stderr warn naming the cap (shallowest edges kept) — the `GraphPath[]` wire shape stays unchanged. Pinned by `test/traverse-graph-op-default.test.ts` + `test/traverse-paths-row-cap.test.ts`. (3) Link-read source scope: the three read ops take `source_id` (`parseSourceIdParam`, `__all__` admitted) and `all_sources` (equivalent to `__all__`; both together is `invalid_params`). `resolveLinkReadScope` composes `federatedSearchScope` (grant check, #5081 admission, unqualified no-grant widening to `localFederatedSourceIds`; a grant never widens), then `assertExplicitSourceLive` (so an archived source outside the caller's admission answers `permission_denied`, not `unknown_source`), then `linkReadScopeOpts` (remote scalar promoted to `sourceIds[]` for the engine's all-endpoints branch), then `readPolicyOpts`. A trusted local unqualified read that comes back as the federated `sourceIds[]` runs the scalar read once per federated source (set order, resolved source first) and merges de-duplicated on link identity, keeping the scalar branch's cross-source far endpoints; `traverse_graph` walks the federated set in one query because its scalar walk already scopes every node. A trusted local unqualified link read that returns nothing prints a stderr rerun hint naming sources outside the read that hold links for the slug (quiet under `json`, never for remote callers). CLI names: `links` (alias `get_links`), `backlinks`, `graph`. (4) Row paging (#6876): rows are keyset-paged by `ops/link-paging.ts` (cap after the source/identity merge; see its header). Pinned by `test/link-read-paging.test.ts`. Pinned by `test/federated-link-reads-5827.test.ts`, `test/link-reads-thin-client-5827.serial.test.ts` and `test/e2e/federated-link-reads-postgres.test.ts`. `traverse_graph` `hops` (1-3 `{link_type, toward}`) runs a typed chain through `runRelationalChain` under the op's read scope, returns `{anchor, answers, paths, diagnostics}` with evidence edges (remote context sanitized), refuses `hops` combined with `depth`/`link_type`/`direction` and bad hops as `invalid_params` naming the parameter path, and emits a `relational_chain` notice with the next call when the chain finds nothing. Pinned by `test/traverse-graph-hops.test.ts`.-- `src/core/ops/pages.ts` — page operations share source validation and the persistence coordinator. Replacements require `expected_revision` or explicit `force`; omitted preconditions permit creation only. The put_page description keeps `Keep a request_id UUID; retry with identical arguments` within its 1,460-character schema budget (pinned by `test/mcp-schema-budget.test.ts` minimum guidance; the description and the content param both keep the get_page include_content:true read that `test/mcp-tool-defs.test.ts` pins). `get_page` and `fetch` use `page-state/snapshot.ts` for exact/alias resolution, content, tags, revision and withdrawal overlays in one SQL snapshot; fuzzy fallback uses a short repeatable-read transaction with the same visibility and source ceilings. `get_page` `content_only` (`ops/get-page-projection.ts`) returns slug, source_id, type, title, revision, tags and content (keys pinned by `test/get-page-content-roundtrip-2225.test.ts`). A put_page `revision_conflict` (`ops/put-page-revision-source.ts`) whose expected_revision is the current revision of the same slug in another source the caller may read (grant via `federatedSearchScope`, private pages excluded for untrusted readers) names that source and gets a re-read fix; otherwise the refusal is unchanged. `get_page` adds `file_held` when sync holds the page's newer file (`persistence/held-reads.ts`; path for trusted local callers only). Missing migration dependencies and connection errors propagate. Capture freezes target/type/timestamp/provenance before admission and resolves same-ID replay first. `persistence/links-preparation.ts` prepares trusted automatic graph reconciliation outside locks, then installs it with canonical projections and the receipt; delayed oneshot reconciliation validates its originating revision. `persistence/page-advisories.ts` prepares bounded, content-free lint findings. Tests cover source/alias ownership, concurrent graph replacements, stale delayed reconciliation, private fences and durable retries. `list_pages` passes `listColumnsOnly` so `engine-sql/pages.ts:listPages` projects identity, type, title and dates without reading page bodies or frontmatter (`list-pages-columns-5154.test.ts`). `delete_page` accepts a strict boolean `purge` only from trusted local callers. Immediate purge uses the same durable journal, observed revision (or explicit `force`), stored/current authority and exact request-ID replay as other page mutations. Owner preparation resolves the recorded file from a coherent snapshot, including tombstones; file removal precedes hard deletion and receipt commitment in the guarded publication transaction. Failed publication preserves the prior active row or existing tombstone and never overwrites unexpected file bytes. The receipt reports the actual filesystem/database persistence outcome and warns that repository history, synced copies, exports and derived artifacts may retain content. The `gbrain delete <slug> --purge` flag derives from the operation contract. `list_pages` probes `limit + 1` rows: a local CLI caller gets a stderr truncation notice; every dispatched caller gets `_meta.pagination` (`truncated`, `limit`, `clamped_from?`, `next?`) and a remote caller whose page was truncated also gets the model-visible `listing_truncated` notice whose `fix.mcp` is the next-page call (`ops/list-pages-pagination.ts`; `next` is the `updated_asc` keyset or an offset). Test: `test/list-pages-truncation.test.ts`. An `updated_after` the database cannot cast (SQLSTATE 22007/22008, the shared `isDatetimeInputError` in `core/utils.ts` that the hybrid lexical arms also use) is `invalid_params` with a read-only list_pages fix, never echoing the value; other SQLSTATEs pass through (`test/list-pages-timestamp-input.test.ts`). put_page (dry runs included) refuses a new `.md`/`.mdx`-suffixed slug (`persistence/suffixed-slug.ts`). #6212: `delete_page` and `restore_page` (dry runs included) go through `persistence/page-mutations.ts:validateMutationSlug`, which admits a legacy stored slug (`ops/context.ts:isLegacyStoredPageSlug`: refused by today's grammar, still accepted by `validateSlug`) only when an existing row in the target source holds it; every other operation keeps `validatePageSlug`, and remote purge stays denied by `assertPurgeParams`. Large pages: `get_page` resolves its body mode first (`parseBodyRequest`, `src/core/ops/get-page-body.ts`) and returns `readPartialBody` for none/outline/window/auto-above-256 KB, `assertFullReadFits` guarding whole remote reads; `fetch` of a page over the inline size returns `fetchWindowResult` (window around the id's chunk anchor, `metadata.next_id`); remote `put_page` runs `assertLargePageAdmission` before queueing. A committed segmented write's outcome records `searchable` (`true`, `'pending'` when its projection runs after commit, `false` when quarantined); `persistence/searchable.ts:liveSearchable` re-reads a pending one whenever the receipt is served (the put_page reply in `page-mutations.ts`, `get_write_request`) and adds `searchable_retry_after_ms` and a `searchable_fix` that reads the receipt again (`test/large-pages/segmented-create-searchable.test.ts`).+- `src/core/ops/pages.ts` — page operations share source validation and the persistence coordinator. Replacements require `expected_revision` or explicit `force`; omitted preconditions permit creation only. The put_page description keeps `Keep a request_id UUID; retry with identical arguments` within its 1,460-character schema budget (pinned by `test/mcp-schema-budget.test.ts` minimum guidance; the description and the content param both keep the get_page include_content:true read that `test/mcp-tool-defs.test.ts` pins). `get_page` and `fetch` use `page-state/snapshot.ts` for exact/alias resolution, content, tags, revision and withdrawal overlays in one SQL snapshot; fuzzy fallback uses a short repeatable-read transaction with the same visibility and source ceilings. `get_page` `content_only` (`ops/get-page-projection.ts`) returns slug, source_id, type, title, revision, tags and content (keys pinned by `test/get-page-content-roundtrip-2225.test.ts`). A put_page `revision_conflict` (`ops/put-page-revision-source.ts`) whose expected_revision is the current revision of the same slug in another source the caller may read (grant via `federatedSearchScope`, private pages excluded for untrusted readers) names that source and gets a re-read fix; otherwise the refusal is unchanged. `get_page` adds `file_held` when sync holds the page's newer file (`persistence/held-reads.ts`; path for trusted local callers only). Missing migration dependencies and connection errors propagate. Capture freezes target/type/timestamp/provenance before admission and resolves same-ID replay first. `persistence/links-preparation.ts` prepares trusted automatic graph reconciliation outside locks, then installs it with canonical projections and the receipt; delayed oneshot reconciliation validates its originating revision. `persistence/page-advisories.ts` prepares bounded, content-free lint findings. Tests cover source/alias ownership, concurrent graph replacements, stale delayed reconciliation, private fences and durable retries. `list_pages` passes `listColumnsOnly` so `engine-sql/pages.ts:listPages` projects identity, type, title and dates without reading page bodies or frontmatter (`list-pages-columns-5154.test.ts`). `delete_page` accepts a strict boolean `purge` only from trusted local callers. Immediate purge uses the same durable journal, observed revision (or explicit `force`), stored/current authority and exact request-ID replay as other page mutations. Owner preparation resolves the recorded file from a coherent snapshot, including tombstones; file removal precedes hard deletion and receipt commitment in the guarded publication transaction. Failed publication preserves the prior active row or existing tombstone and never overwrites unexpected file bytes. The receipt reports the actual filesystem/database persistence outcome and warns that repository history, synced copies, exports and derived artifacts may retain content. The `gbrain delete <slug> --purge` flag derives from the operation contract. `list_pages` probes `limit + 1` rows: a local CLI caller gets a stderr truncation notice; every dispatched caller gets `_meta.pagination` (`truncated`, `limit`, `clamped_from?`, `next?`) and a remote caller whose page was truncated also gets the model-visible `listing_truncated` notice whose `fix.mcp` is the next-page call (`ops/list-pages-pagination.ts`; `next` is the `updated_asc` keyset or an offset). Test: `test/list-pages-truncation.test.ts`. An `updated_after` the database cannot cast (SQLSTATE 22007/22008, the shared `isDatetimeInputError` in `core/utils.ts` that the hybrid lexical arms also use) is `invalid_params` with a read-only list_pages fix, never echoing the value; other SQLSTATEs pass through (`test/list-pages-timestamp-input.test.ts`). put_page (dry runs included) refuses a new `.md`/`.mdx`-suffixed slug (`persistence/suffixed-slug.ts`). #6212: `delete_page` and `restore_page` (dry runs included) go through `persistence/page-mutations.ts:validateMutationSlug`, which admits a legacy stored slug (`ops/context.ts:isLegacyStoredPageSlug`: refused by today's grammar, still accepted by `validateSlug`) only when an existing row in the target source holds it; every other operation keeps `validatePageSlug`, and remote purge stays denied by `assertPurgeParams`. Large pages: `get_page` resolves its body mode first (`parseBodyRequest`, `src/core/ops/get-page-body.ts`) and returns `readPartialBody` for none/outline/window/auto-above-256 KB, `assertFullReadFits` guarding whole remote reads; `fetch` of a page over the inline size returns `fetchWindowResult` (window around the id's chunk anchor, `metadata.next_id`); remote `put_page` runs `assertLargePageAdmission` before queueing. A committed segmented write's outcome records `searchable` (`true`, `'pending'` when its projection runs after commit, `false` when quarantined); `persistence/searchable.ts:liveSearchable` re-reads a pending one whenever the receipt is served (the put_page reply in `page-mutations.ts`, `get_write_request`) and adds `searchable_retry_after_ms` and a `searchable_fix` that reads the receipt again (`test/large-pages/segmented-create-searchable.test.ts`). Write handlers import `page-mutations.ts` lazily (`test/cold-read-module-graph.test.ts`).- `src/core/ops/get-page-body.ts` — get_page's body modes (`auto|full|none|outline|window`, selectors `lines`/`bytes`/`around_chunk_id`/`cursor`, `view: read|markdown`). `parseBodyRequest` fixes precedence (explicit body; include_content/content_only → full; a selector → window; the thin client and the local CLI → full; else auto) and rejects conflicting selectors. `readPartialBody` never fills compiled_truth/timeline/content: it slices the read projection (`readPageDocument`) or, for `view: markdown`, the round-trip markdown with its sha256; a window is re-measured as the final encoded frame and shrunk until it fits `resultByteCap`. `around_chunk_id` uses the stored span (`anchor: stored_span`), a unique text match (`located`), or returns the chunk alone (`chunk_only`). Cursors are revision-bound; a stale one is `revision_changed` with a same-offset fix. `readFetchWindow` / `fetchWindowResult` serve fetch's windowed shape; `LARGE_PAGES_CAPABILITY` is advertised by `get_brain_identity`. A segmented page (Wave B PR 2, spec 7.2) is never read whole: `full` is `page_body_segmented` for local and MCP callers alike with `segmentedReadFix` (`body: 'auto'`, argv and mcp; local `gbrain get` with no `--body` streams it instead), and `page_too_large_for_inline` only for gbrain's thin client, its paging signal (`segmentedFullReadError`); `grammar_diagnostics` on it is `line_grammar: { state: 'skipped', reason: 'page_body_segmented' }` (`segmentedGrammarSkip`, line-grammar-report.ts); window byte offsets are coordinates of the view's `size.total_bytes`, never `body_bytes`, and an offset past the end is an empty window on both storages; `auto` is the outline plus the first window, and `segmentedWindows` cuts every window, outline page and `around_chunk_id` from `page-window/segmented.ts`. A segmented `around_chunk_id` resolves only from the chunk's live occurrence and segment-relative span (a retired occurrence is `revision_changed`; no text match), and `body: 'none'` reports stored sums plus the tail digest without chunk counts.- `src/core/persistence/large-page-guard.ts` — put_page against a page over 256 KB: `assertLargePageAdmission` (remote, before queueing) refuses `force` without `expected_revision` (`revision_required`) and content under half the stored body (`page_shrink_refused`) unless `allow_shrink`; `assertLargePageReplacement` re-checks the parsed body against the locked snapshot in preparation (`page-prepare.ts`).- `src/core/ops/page-edit.ts` — the `edit_page` operation (write scope, starter surface, client slug-fence allowlist): validates edits and the optional `within` range (full surface only), then submits through `submitPageMutation` like put_page; matching and the diff live in `persistence/page-edit.ts`.diff --git a/docs/architecture/key-files/entrypoints-and-docs.md b/docs/architecture/key-files/entrypoints-and-docs.mdindex 3a3520f3cb..30638eb171 100644--- a/docs/architecture/key-files/entrypoints-and-docs.md+++ b/docs/architecture/key-files/entrypoints-and-docs.md@@ -118,7 +118,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/cli.ts` — the entry point (`bun src/cli.ts`, the `gbrain` bin, the compiled binary): Bun floor, signal handlers and stdout delivery, then either the engine-free fast path (`cliFastPath`: `--version`, `version`, bare `gbrain`, `--help`, `-h`, after global-flag parsing and `runCliPreflight`) or a dynamic import of the dispatcher, `src/cli/main.ts` `runCli()`. Its static imports are paid by every invocation and stay light: the dispatcher's graph (every operation and command module) loads only for real commands, so `--version` and top-level help skip it. The top-level help text is `src/cli/top-help.ts`, shared by both paths. Pinned by `test/cli-fast-path.test.ts` (fast-path branches, output parity, and import-graph bounds for the entry and the dispatcher).- `src/cli/main.ts` — the dispatcher (moved out of `src/cli.ts`; tests import its helpers from here). It keeps three graphs off every command: `completeEngineStartup` asks `migrate-pending.ts` (generated latest version) before loading `migrate.ts` and its ~220 migration modules, `thin-client-upgrade-prompt.ts` takes `compareVersions` from `migration-ledger.ts` instead of the upgrade orchestrator registry, and `mcp-client.ts` loads the MCP HTTP client SDK on the first remote call. Generic thin-client mutation failures use the shared persistence reporter, retaining request IDs and typed JSON receipts while preserving SIGINT exit 130. `test/thin-client-write-errors.serial.test.ts` exercises real CLI timeout, cancellation, pending and conflict paths against a loopback MCP fixture. No-DB fallbacks announce themselves on stderr instead of degrading silently. `dream` dispatch binds the caught engine-connect error and emits `[dream] WARNING: could not connect to DB (...)` before falling through to filesystem-only phases; the `runDream(null, ...)` no-DB fallback is preserved (pinned by `test/cli-dream-engine-warn.test.ts`, 2 subprocess cases against good + bad DATABASE_URL). `doctor` dispatch does the same: when `connectEngine` OR the DB-backed `runDoctor` run throws, it emits `[doctor] DB-backed doctor run failed (...) — falling back to filesystem-only checks`, scrubbing the error message through BOTH `url-redact.ts:redactUrlsInText` and `redact-connection-info.ts:redactConnectionInfo` first, because doctor output is exactly what users paste into issues and CI logs (pinned by the fallback case in `test/doctor-minions-check.test.ts`: stderr note present, credentials absent, stdout stays parseable `--json`). `main()` opens with `await runCliPreflight()` (core/cli-preflight.ts: cwd-.env quarantine -> `~/.gbrain/.env` -> guardrails loader) before `parseGlobalFlags`; the former inline #3688 guardrails block lives in the preflight module. `get_page` output renders through `src/cli/page-render.ts`: a partial response prints only what it carries plus a stderr note, and a thin-client `gbrain get` refused with `page_too_large_for_inline` pages the round-trip markdown to its end (`readWholePageMarkdown`, size + sha256 checked, restarts if the page changes) before printing.- `connectEngine` is the thin-client backstop: on a config with `remote_mcp` and no `database_url` it refuses the dispatched command through `refuseThinClient` instead of building an engine, so a command without its own route never dies with "No database URL" or reads an empty in-memory PGLite. Handlers that already route over MCP (salience, anomalies, graph-query, whoknows, founder, and every recall form except an in-process `--query`/`--budget-tokens` call) run engine-free from `prepareConnectedDispatch`. Pinned by `test/thin-client-connect-engine-guard.test.ts`. A read-scope op connects with `oneShotRead`: startup reads the config table once (`withRequestConfigSnapshot`; pending migrations run outside it), skips the retired-marker cleanup only filesystem-guarded writes need, and the context build and the operation share a second snapshot; a transaction pooler's prepared-statements banner prints once per database (`src/core/pooler-notice.ts`). Pinned by `test/e2e/cli-read-startup-round-trips.test.ts` (statement counts from the wire trace). The host connect itself is `connectEngineForServe(hooks, {probeOnly, oneShotRead})` in `src/core/engine-connect.ts`: throw-only (`no_brain`, `requires_local_engine`, repair refusals), it records the engine's config through `ENGINE_CONNECT_HOOKS` and disconnects an engine whose startup fails after the connect; `connectEngine` wraps it with the CLI exits (`exitOnRepairFailed`), and the status-only serve call sites pass it directly (`test/engine-connect.test.ts`).+ `connectEngine` is the thin-client backstop: on a config with `remote_mcp` and no `database_url` it refuses the dispatched command through `refuseThinClient` instead of building an engine, so a command without its own route never dies with "No database URL" or reads an empty in-memory PGLite. Handlers that already route over MCP (salience, anomalies, graph-query, whoknows, founder, and every recall form except an in-process `--query`/`--budget-tokens` call) run engine-free from `prepareConnectedDispatch`. Pinned by `test/thin-client-connect-engine-guard.test.ts`. A read-scope op, `gbrain search`, `sources list` and a one-shot `recall` (not `--watch`) connect with `oneShotRead`: startup, the context build and the read share one config snapshot (`takeStartupConfigSnapshot` hands it over; pending migrations run outside it and drop its rows), the Postgres pool opens at most two connections (`ONE_SHOT_READ_POOL_MAX`; `GBRAIN_POOL_SIZE` still wins), and the retired-marker cleanup only filesystem-guarded writes need is skipped. Inside that snapshot source resolution reads the sources table once (`requestSnapshotRead` in `config-snapshot.ts`), and the search-statistics guard (`missingSearchStatistics`) is one statement (`test/cold-read-folded-statements.test.ts`); a transaction pooler's prepared-statements banner prints once per database (`src/core/pooler-notice.ts`). Pinned by `test/e2e/cli-read-startup-round-trips.test.ts` (statement counts from the wire trace). The host connect itself is `connectEngineForServe(hooks, {probeOnly, oneShotRead})` in `src/core/engine-connect.ts`: throw-only (`no_brain`, `requires_local_engine`, repair refusals), it records the engine's config through `ENGINE_CONNECT_HOOKS` and disconnects an engine whose startup fails after the connect; `connectEngine` wraps it with the CLI exits (`exitOnRepairFailed`), and the status-only serve call sites pass it directly (`test/engine-connect.test.ts`).Size ceiling (`src/cli/main.ts`): `scripts/module-size-limits.tsv` (per-change raise history: `git log -p` on that file). The ceiling covers `handleCliOnly`'s explicit ordered pipeline (`@cliPipelineStage` functions: thin-client guard, deferred-persistence routing, subcommand and help routes, read-only timeout path, sync watchdog and delegation, connectEngine terminator with degraded-serve recovery, teardown), thin-client routing and refusal, help and self-help text, strict flag parsing and process-exit teardown. Per-command dispatch (pre- and post-connect) lives in the command table (entry below), not in `src/cli/main.ts`.- `src/cli/remember-format.ts` — the `remember` human formatter (`formatRememberResult`: status, entity with `(inferred from mention)`, expiry, degraded dedup, a `note: private` line when the call passed `visibility: private` (#6606; read from the params, so it prints when the write ran on a serve owner too), `warnings` + `hint`), kept out of `src/cli.ts`; `--json` prints the raw envelope. Pinned by `test/remember-entity-inference.test.ts`.diff --git a/docs/architecture/key-files/files-and-sync-1.md b/docs/architecture/key-files/files-and-sync-1.mdindex edb936d38a..8c318c1e65 100644--- a/docs/architecture/key-files/files-and-sync-1.md+++ b/docs/architecture/key-files/files-and-sync-1.md@@ -49,7 +49,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/core/source-id.ts` — single canonical source_id validation, dependency-free by design (imported by both engines, cycle, source-resolver, sources-ops). `SOURCE_ID_RE` (strict: 1-32 lowercase alnum, interior hyphens only, no edge hyphens); `isValidSourceId` (boolean — for tiers that silently fall back: dotfile, brain_default) vs `assertValidSourceId` (throws — for tiers that must reject loudly: explicit `--source`, `GBRAIN_SOURCE`, `cycleLockIdFor`); `ALL_SOURCES = '__all__'` sentinel (deliberately NOT a valid id so it can never collide with a real source or leak into lock ids/path joins; `sourceScopeOpts` translates it to an unscoped read for trusted local callers and keeps it unsatisfiable for remote callers, fail-closed); `NO_SOURCES = '__none__'` is the explicit no-source legacy-token grant, refused rather than translated. `normalizeSourceInput`/`normalizeFederatedReadInput` normalize the `/admin/api/register-client` HTTP body, mirroring the CLI's `--source`/`--federated-read` flags: omitted `source` → `'default'`; omitted `federatedRead` → `undefined` so `registerClientManual` applies its own `[sourceId]` default; present-but-invalid values throw so the route returns a structured 400 (`invalid_source`) instead of failing at INSERT time. Pinned by `test/register-client-source-normalize.test.ts`.-- `src/core/source-resolver.ts` — 6-tier source resolution. `resolveSourceWithTier(engine, explicit, cwd)` returns `{ source_id, tier: SourceTier, detail? }` alongside `resolveSourceId()` (unchanged). `SOURCE_TIER_NAMES = ['flag', 'env', 'dotfile', 'local_path', 'sole_non_default', 'brain_default', 'seed_default']` (7 entries; order matches priority). Tier `sole_non_default` slots between `local_path` and `brain_default`: when NO `sources.default` config is set AND exactly one registered source has `local_path` AND isn't `'default'` AND the `'default'` source holds no active pages (the emptiness guard — the tier's charter is rescuing brains whose `'default'` is empty; when `'default'` carries an established corpus, auto-routing would hijack every bare write into the side-source, so the resolver falls through to `seed_default` and prints a one-line stderr notice naming both sides so the suppressed flip is diagnosable, same `GBRAIN_NO_SOLE_NON_DEFAULT_NUDGE=1` suppression knob as the routing nudge; a failed pages probe on an exotic/legacy schema keeps the auto-route), auto-route to it; archived sources excluded (try/catch for pre-v34 brains); private `pickSoleNonDefaultSource(engine)` shared by both resolver entry points so they cannot drift. Exported `formatSoleNonDefaultNudge(sourceId): string | null` builds the user-facing stderr nudge (null when `GBRAIN_NO_SOLE_NON_DEFAULT_NUDGE=1`). `resolveCliSyncSource` in `src/commands/sync/run.ts` calls `resolveSourceWithTier` unconditionally so the tier fires; `src/commands/import.ts:96-128` mirrors with the tier-gated nudge. Consumed by `gbrain sources current`, `import --source-id`, `extract --source-id`, and the `source_routing_health` doctor check. Pinned by `test/source-resolver-with-tier.test.ts` (`withEnv()` per test-isolation lint), `test/source-resolver-sole-non-default.test.ts` (20 cases incl. both-ways emptiness-guard + probe-failure fallback), `test/sync-sole-non-default-routing.test.ts` (3 PGLite cases driving real `runSync`), `test/pages-source-scoping-4329.test.ts` (real-engine both-ways guard coverage). Also exports `noGrantFederatedScope(engine, hasSourceGrant, sourceId)`, the widening decision transports share: returns `localFederatedSourceIds(..., 'seed_default')` ONLY when `hasSourceGrant === false` (the legacy-bearer no-grant floor), `undefined` for a granted token, for an OAuth client (flag `undefined` — a falsy gate here would widen every OAuth client), and when the resolver throws (best-effort; the scalar scope stands rather than failing the request). Called by `src/commands/serve-http.ts`; pinned by `test/no-grant-federated-scope.test.ts` (6 cases). `explicitReadBinding(engine, sourceId, tier)` (#5081) is the explicit-tier twin used by the stdio transport for `GBRAIN_SOURCE` (`env`) and `.gbrain-source` (`dotfile`) bindings: `{ sourceId, via, sourceIds, optedOut }`, where `sourceIds` is the same set `localFederatedSourceIds` computes (shared `federatedSetFor`, so an isolated anchor admits only itself) and `optedOut` lists `federated === false` sources for the denial hint; `undefined` for every other tier. Pinned by `test/explicit-read-admission-5081.test.ts`. Unscoped default-write guard family (the `seed_default` tier is the only one that actually lands a write in `'default'`): `assessDefaultWriteGuard(engine)` → `DefaultWriteAssessment { shouldGuard, defaultPages, nonDefaultPages, nonDefaultSources, failed? }` — an unindexed full-`pages` aggregate; `shouldGuard` when ≥1 non-default source holds pages AND non-default pages outnumber default's; a query failure returns the fail-open no-guard verdict stamped `failed: true`, which cachers/latchers must not treat as settled. `assessDefaultWriteGuardOnce(engine)` is the per-engine WeakMap memo (arms on the first SUCCESSFUL assessment whatever its verdict, forgets a failed attempt so the next caller retries, coalesces concurrent callers; `__resetDefaultWriteGuardMemo` is the test seam). `assessUnscopedDefaultWrite(engine, tier, mutating)` → `{ warning, assessed }` (`assessed: false` only when the aggregate failed); `formatDefaultWriteWarning(a, sourceFlag?)` / `formatDefaultWriteRefusal(cmd, a)` render the two surfaces; `defaultWriteAllowedByEnv()` is the `GBRAIN_ALLOW_DEFAULT_WRITE=1` escape hatch. Consumers: `sync` refuses (dry-run warns), `import` warns via the memo, MCP stdio's `createDefaultWriteAdvisory` prints once. Also exports `isResolverUserError(e)` — the ONE predicate for this module's user-facing throws (`Source "…" not found.` / `not found or is archived.`, `Invalid --source value`, `Invalid GBRAIN_SOURCE value`), consumed by dream.ts, agent.ts and code-scope.ts so a CLI command turns an unknown/archived source into a clean stderr line + exit 1 while anything else keeps propagating.+- `src/core/source-resolver.ts` — 6-tier source resolution. `resolveSourceWithTier(engine, explicit, cwd)` returns `{ source_id, tier: SourceTier, detail? }` alongside `resolveSourceId()` (unchanged). `SOURCE_TIER_NAMES = ['flag', 'env', 'dotfile', 'local_path', 'sole_non_default', 'brain_default', 'seed_default']` (7 entries; order matches priority). Tier `sole_non_default` slots between `local_path` and `brain_default`: when NO `sources.default` config is set AND exactly one registered source has `local_path` AND isn't `'default'` AND the `'default'` source holds no active pages (the emptiness guard — the tier's charter is rescuing brains whose `'default'` is empty; when `'default'` carries an established corpus, auto-routing would hijack every bare write into the side-source, so the resolver falls through to `seed_default` and prints a one-line stderr notice naming both sides so the suppressed flip is diagnosable, same `GBRAIN_NO_SOLE_NON_DEFAULT_NUDGE=1` suppression knob as the routing nudge; a failed pages probe on an exotic/legacy schema keeps the auto-route), auto-route to it; archived sources excluded (try/catch for pre-v34 brains); private `pickSoleNonDefaultSource(engine)` shared by both resolver entry points so they cannot drift. Exported `formatSoleNonDefaultNudge(sourceId): string | null` builds the user-facing stderr nudge (null when `GBRAIN_NO_SOLE_NON_DEFAULT_NUDGE=1`). `resolveCliSyncSource` in `src/commands/sync/run.ts` calls `resolveSourceWithTier` unconditionally so the tier fires; `src/commands/import.ts:96-128` mirrors with the tier-gated nudge. Consumed by `gbrain sources current`, `import --source-id`, `extract --source-id`, and the `source_routing_health` doctor check. Pinned by `test/source-resolver-with-tier.test.ts` (`withEnv()` per test-isolation lint), `test/source-resolver-sole-non-default.test.ts` (20 cases incl. both-ways emptiness-guard + probe-failure fallback), `test/sync-sole-non-default-routing.test.ts` (3 PGLite cases driving real `runSync`), `test/pages-source-scoping-4329.test.ts` (real-engine both-ways guard coverage). Also exports `noGrantFederatedScope(engine, hasSourceGrant, sourceId)`, the widening decision transports share: returns `localFederatedSourceIds(..., 'seed_default')` ONLY when `hasSourceGrant === false` (the legacy-bearer no-grant floor), `undefined` for a granted token, for an OAuth client (flag `undefined` — a falsy gate here would widen every OAuth client), and when the resolver throws (best-effort; the scalar scope stands rather than failing the request). Called by `src/commands/serve-http.ts`; pinned by `test/no-grant-federated-scope.test.ts` (6 cases). `explicitReadBinding(engine, sourceId, tier)` (#5081) is the explicit-tier twin used by the stdio transport for `GBRAIN_SOURCE` (`env`) and `.gbrain-source` (`dotfile`) bindings: `{ sourceId, via, sourceIds, optedOut }`, where `sourceIds` is the same set `localFederatedSourceIds` computes (shared `federatedSetFor`, so an isolated anchor admits only itself) and `optedOut` lists `federated === false` sources for the denial hint; `undefined` for every other tier. Pinned by `test/explicit-read-admission-5081.test.ts`. Unscoped default-write guard family (the `seed_default` tier is the only one that actually lands a write in `'default'`): `assessDefaultWriteGuard(engine)` → `DefaultWriteAssessment { shouldGuard, defaultPages, nonDefaultPages, nonDefaultSources, failed? }` — an unindexed full-`pages` aggregate; `shouldGuard` when ≥1 non-default source holds pages AND non-default pages outnumber default's; a query failure returns the fail-open no-guard verdict stamped `failed: true`, which cachers/latchers must not treat as settled. `assessDefaultWriteGuardOnce(engine)` is the per-engine WeakMap memo (arms on the first SUCCESSFUL assessment whatever its verdict, forgets a failed attempt so the next caller retries, coalesces concurrent callers; `__resetDefaultWriteGuardMemo` is the test seam). `assessUnscopedDefaultWrite(engine, tier, mutating)` → `{ warning, assessed }` (`assessed: false` only when the aggregate failed); `formatDefaultWriteWarning(a, sourceFlag?)` / `formatDefaultWriteRefusal(cmd, a)` render the two surfaces; `defaultWriteAllowedByEnv()` is the `GBRAIN_ALLOW_DEFAULT_WRITE=1` escape hatch. Consumers: `sync` refuses (dry-run warns), `import` warns via the memo, MCP stdio's `createDefaultWriteAdvisory` prints once. Also exports `isResolverUserError(e)` — the ONE predicate for this module's user-facing throws (`Source "…" not found.` / `not found or is archived.`, `Invalid --source value`, `Invalid GBRAIN_SOURCE value`), consumed by dream.ts, agent.ts and code-scope.ts so a CLI command turns an unknown/archived source into a clean stderr line + exit 1 while anything else keeps propagating. A request snapshot serves tiers 4, 5.5 and the federated set from one sources read.- `src/core/source-delete.ts` — `deleteSourceRow`: every unmanaged source delete (`sources remove`, `sources purge`, the `sources_remove` op, expired-archive purge) deletes the `sources` row and that incarnation's `persistence_source_bindings` row in one statement; bindings have no FK to `sources`. Bindings of other incarnations are left to `gbrain repair orphan-bindings` (`src/core/persistence/orphan-bindings.ts`, doctor `orphan_persistence_bindings`). The unmanaged claim check (`sync-authority.ts`) and doctor `unbound_source` count only a binding of the source's current incarnation. `EXPIRED_ARCHIVE_SQL` is the one purge-eligibility predicate (unmanaged sweep, its per-row DELETE and the managed `expiredOnly` purge): both archive timestamps must be later than the epoch and the expiry past; `UNVERIFIED_ARCHIVE_SQL` lists archived rows with a missing or epoch timestamp, which the sweep reports blocked with restore-then-archive guidance instead of purging.- `src/core/sources-ops.ts` — Multi-source registration + clone-lifecycle ops (`addSource`, `recloneIfMissing`, `defaultCloneDir`, `isOwnedClone`, `unownedHint`). **Reclone-ownership invariant (must-never-violate): gbrain may only delete/re-clone a clone it created, NEVER a user working tree.** `recloneIfMissing` deletes `local_path`, so it gates on `isOwnedClone(src)` and throws a `SourceOpError('unmanaged_path', ...)` BEFORE any filesystem op when ownership is unprovable — fail-closed. Ownership is proven by `config.managed_clone === true` (written by `addSource`'s `--url` path, covering default-location and `--clone-dir` clones) OR `local_path === defaultCloneDir(id)` (back-compat for pre-marker clones, via exact normalized-path equality, symlink-free). A row with `remote_url` + an unowned `local_path` (a user-registered working tree, e.g. `sources add --path`) is refused untouched; re-add with `--url` to regain auto-reclone. The reclone is EXDEV-safe: clone into a SIBLING temp of `local_path` (not the shared `clones/.tmp`, which may sit on a different mount than a `--clone-dir` target), then swap (move old aside → move new in → drop old) so `local_path` is never left missing-and-unrecoverable; on swap failure the original is restored, and if restore fails the error names the `aside` path so it's never reflexively deleted. A TOCTOU re-check re-confirms ownership immediately before the destructive move and rejects a symlink leaf swapped in after the entry check (`symlink_escape`). `unownedHint(src, state)` is the shared recovery message used by both the core error and the `gbrain sync --source` CLI error; `gbrain sources restore` special-cases `unmanaged_path` to print "DB row restored; gbrain syncs this path read-only" instead of the misleading "try sync to recover" guidance. `SourceOpErrorCode` includes `unmanaged_path`. Pinned by `test/sources-ops.test.ts`, `test/sources-resync-recovery.test.ts`. `assertNoOverlappingPath(engine, id, path)` is the ONE overlapping-path guard shared by every surface that binds a `local_path` (`addSource`, `gbrain sources set-path`): a path equal to, nested inside, or enclosing another source's `local_path` throws `SourceOpError('overlapping_path')` — overlapping trees make sync/write-through attribute files to the wrong source, so no add or repair path may skip it. The guard compares by spelling AND by realpath (both the candidate and each sibling `local_path` are `realpathSync`'d when they exist, fail-open to the spelling otherwise), so a symlink resolving into or over another source's tree cannot slip past it; the stored pointer and the error message keep the operator's spelling. #6946: `isOwnedClone`/`defaultCloneDir` live in `src/core/url-clone.ts`, re-exported here.diff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsvindex 36178cd537..3bd9ac3000 100644--- a/scripts/module-size-limits.tsv+++ b/scripts/module-size-limits.tsv@@ -3,7 +3,7 @@# Raising a ceiling is a conscious, reviewer-visible act. Lower ceilings in# the same commit as any peel (the guard fails on >50 lines of stale slack).# Columns: path max_lines policy note-src/cli/main.ts 3019 ratchet +1 W1 belief ledger: `gbrain beliefs --help` in SELF_HELP_WITHOUT_ENGINE; +1 Cat 41 run 4: recall's SELF_HELP_WITHOUT_ENGINE table entry (a dispatch table row cannot move); moved from src/cli.ts at 3214 (cold start: src/cli.ts is now the 66-line entry with the --version/help fast path; the top-level help text moved to cli/top-help.ts and the exit seam became runCli/exitOnFatalCliError); +2 #6340: the sync status / sync unblock preflight skip (logic in commands/sync/operator.ts); +3 agent operator gate fixes: repair-failed connect wrapper (logic in cli/cli-error.ts exitOnRepairFailed), transcripts recent through a live serve (logic in commands/transcripts.ts), pre-connect status reason (logic in commands/serve-status.ts); +23 merged from the collector (Lanes B/E/F: thin-client token reason, status-only serve hand-off, jobs/sync readiness wiring); +9 agent operator wave D3/D4: curated --help short-circuit (renderer in cli/help/render.ts), curated flag-value validation call (cli/help/validate.ts), table-dispatched SELF_HELP_WITHOUT_ENGINE entries for the selfHelp flips; +5 agent operator wave C10 (merged from the collector): serve --fail-fast in the connect-failure path; +31 #5950 (D6): connectEngine thin-client backstop, engine-free MCP-twin dispatch, recall/advisor/export refusal hints, refusal fix subcommand (lowered to 3131 by D1's renderCliError seam first); +2 agent operator wave A4: observational startup (probe-only connect for startup:observational commands; completeEngineStartup split out of connectEngine, exposed as ctx.completeStartup); +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5232: write-wait import, reporter-owned verdict in the op catch, thin-client writeWaitMs, ctx.writeWaitMs (logic in persistence/write-wait.ts); +1 #4768: serve --access help line; +4 #5433: list_pages TSV cell escaping in formatResult; +2 #lane-h pricing: help line + thin-client refusal hint for `gbrain pricing`; +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5433: list_pages TSV cell escaping in formatResult; +1 #5984: a strict run deadline when no progress window is set; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (3199 measured); +2 retrieval feedback: answer id line on stderr and additive answer_id on --json search/query rows (logic in feedback/record.ts); +1 feedback help line and its D3 table-dispatch entry (logic in commands/feedback.ts); 6 engine graduation (GBRA-50 G3): migrate pre-connect route (logic in commands/migrate-graduation.ts), serve start refusal and degraded-reconnect identity gate (logic in persistence/graduation-serve-guard.ts), usage line; +3 engine graduation (GBRA-50 G2a): connect-path graduation check on every engine (logic in persistence/graduation-custody.ts assertGraduationConnectAllowed); P3 x engine graduation composition: both deltas re-summed at the merge; 1 Foundations 2 Lane F: sources refresh pre-connect delegation to a resident PGLite owner (logic in commands/sources-refresh-delegate.ts); +3 agent operator gate fixes: repair-failed connect wrapper (logic in cli/cli-error.ts exitOnRepairFailed), transcripts recent through a live serve (logic in commands/transcripts.ts), pre-connect status reason (logic in commands/serve-status.ts); +23 merged from the collector (Lanes B/E/F: thin-client token reason, status-only serve hand-off, jobs/sync readiness wiring); +9 agent operator wave D3/D4: curated --help short-circuit (renderer in cli/help/render.ts), curated flag-value validation call (cli/help/validate.ts), table-dispatched SELF_HELP_WITHOUT_ENGINE entries for the selfHelp flips; +5 agent operator wave C10 (merged from the collector): serve --fail-fast in the connect-failure path; +31 #5950 (D6): connectEngine thin-client backstop, engine-free MCP-twin dispatch, recall/advisor/export refusal hints, refusal fix subcommand (lowered to 3131 by D1's renderCliError seam first); +2 agent operator wave A4: observational startup (probe-only connect for startup:observational commands; completeEngineStartup split out of connectEngine, exposed as ctx.completeStartup); +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5232: write-wait import, reporter-owned verdict in the op catch, thin-client writeWaitMs, ctx.writeWaitMs (logic in persistence/write-wait.ts); +1 #4768: serve --access help line; +4 #5433: list_pages TSV cell escaping in formatResult; +2 #lane-h pricing: help line + thin-client refusal hint for `gbrain pricing`; +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5433: list_pages TSV cell escaping in formatResult; +1 #5984: a strict run deadline when no progress window is set; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (3199 measured); +3 agent operator gate fixes: repair-failed connect wrapper (logic in cli/cli-error.ts exitOnRepairFailed), transcripts recent through a live serve (logic in commands/transcripts.ts), pre-connect status reason (logic in commands/serve-status.ts); +23 merged from the collector (Lanes B/E/F: thin-client token reason, status-only serve hand-off, jobs/sync readiness wiring); +9 agent operator wave D3/D4: curated --help short-circuit (renderer in cli/help/render.ts), curated flag-value validation call (cli/help/validate.ts), table-dispatched SELF_HELP_WITHOUT_ENGINE entries for the selfHelp flips; +5 agent operator wave C10 (merged from the collector): serve --fail-fast in the connect-failure path; +31 #5950 (D6): connectEngine thin-client backstop, engine-free MCP-twin dispatch, recall/advisor/export refusal hints, refusal fix subcommand (lowered to 3131 by D1's renderCliError seam first); +2 agent operator wave A4: observational startup (probe-only connect for startup:observational commands; completeEngineStartup split out of connectEngine, exposed as ctx.completeStartup); +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5232: write-wait import, reporter-owned verdict in the op catch, thin-client writeWaitMs, ctx.writeWaitMs (logic in persistence/write-wait.ts); +1 #4768: serve --access help line; +4 #5433: list_pages TSV cell escaping in formatResult; +2 #lane-h pricing: help line + thin-client refusal hint for `gbrain pricing`; +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5433: list_pages TSV cell escaping in formatResult; +1 #5984: a strict run deadline when no progress window is set; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (3199 measured); +6 engine graduation (GBRA-50 G3): migrate pre-connect route (logic in commands/migrate-graduation.ts), serve start refusal and degraded-reconnect identity gate (logic in persistence/graduation-serve-guard.ts), usage line; +3 engine graduation (GBRA-50 G2a): connect-path graduation check on every engine (logic in persistence/graduation-custody.ts assertGraduationConnectAllowed); P3 x foundations-2 composition: deltas re-summed at the merge; 1 Foundations 2 Lane F: sources refresh pre-connect delegation to a resident PGLite owner (logic in commands/sources-refresh-delegate.ts); +3 agent operator gate fixes: repair-failed connect wrapper (logic in cli/cli-error.ts exitOnRepairFailed), transcripts recent through a live serve (logic in commands/transcripts.ts), pre-connect status reason (logic in commands/serve-status.ts); +23 merged from the collector (Lanes B/E/F: thin-client token reason, status-only serve hand-off, jobs/sync readiness wiring); +9 agent operator wave D3/D4: curated --help short-circuit (renderer in cli/help/render.ts), curated flag-value validation call (cli/help/validate.ts), table-dispatched SELF_HELP_WITHOUT_ENGINE entries for the selfHelp flips; +5 agent operator wave C10 (merged from the collector): serve --fail-fast in the connect-failure path; +31 #5950 (D6): connectEngine thin-client backstop, engine-free MCP-twin dispatch, recall/advisor/export refusal hints, refusal fix subcommand (lowered to 3131 by D1's renderCliError seam first); +2 agent operator wave A4: observational startup (probe-only connect for startup:observational commands; completeEngineStartup split out of connectEngine, exposed as ctx.completeStartup); +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5232: write-wait import, reporter-owned verdict in the op catch, thin-client writeWaitMs, ctx.writeWaitMs (logic in persistence/write-wait.ts); +1 #4768: serve --access help line; +4 #5433: list_pages TSV cell escaping in formatResult; +2 #lane-h pricing: help line + thin-client refusal hint for `gbrain pricing`; +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5433: list_pages TSV cell escaping in formatResult; +1 #5984: a strict run deadline when no progress window is set; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (3199 measured); +3 agent operator gate fixes: repair-failed connect wrapper (logic in cli/cli-error.ts exitOnRepairFailed), transcripts recent through a live serve (logic in commands/transcripts.ts), pre-connect status reason (logic in commands/serve-status.ts); +23 merged from the collector (Lanes B/E/F: thin-client token reason, status-only serve hand-off, jobs/sync readiness wiring); +9 agent operator wave D3/D4: curated --help short-circuit (renderer in cli/help/render.ts), curated flag-value validation call (cli/help/validate.ts), table-dispatched SELF_HELP_WITHOUT_ENGINE entries for the selfHelp flips; +5 agent operator wave C10 (merged from the collector): serve --fail-fast in the connect-failure path; +31 #5950 (D6): connectEngine thin-client backstop, engine-free MCP-twin dispatch, recall/advisor/export refusal hints, refusal fix subcommand (lowered to 3131 by D1's renderCliError seam first); +2 agent operator wave A4: observational startup (probe-only connect for startup:observational commands; completeEngineStartup split out of connectEngine, exposed as ctx.completeStartup); +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5232: write-wait import, reporter-owned verdict in the op catch, thin-client writeWaitMs, ctx.writeWaitMs (logic in persistence/write-wait.ts); +1 #4768: serve --access help line; +4 #5433: list_pages TSV cell escaping in formatResult; +2 #lane-h pricing: help line + thin-client refusal hint for `gbrain pricing`; +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5433: list_pages TSV cell escaping in formatResult; +1 #5984: a strict run deadline when no progress window is set; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (3199 measured); +6 engine graduation (GBRA-50 G3): migrate pre-connect route (logic in commands/migrate-graduation.ts), serve start refusal and degraded-reconnect identity gate (logic in persistence/graduation-serve-guard.ts), usage line; +3 engine graduation (GBRA-50 G2a): connect-path graduation check on every engine (logic in persistence/graduation-custody.ts assertGraduationConnectAllowed); GBRA-49: edge-proposals answers --help without a brain (SELF_HELP_WITHOUT_ENGINE row); P3 x P1 (v0.60.57.0) composition: deltas re-summed at the merge; 1 Foundations 2 Lane F: sources refresh pre-connect delegation to a resident PGLite owner (logic in commands/sources-refresh-delegate.ts); +3 agent operator gate fixes: repair-failed connect wrapper (logic in cli/cli-error.ts exitOnRepairFailed), transcripts recent through a live serve (logic in commands/transcripts.ts), pre-connect status reason (logic in commands/serve-status.ts); +23 merged from the collector (Lanes B/E/F: thin-client token reason, status-only serve hand-off, jobs/sync readiness wiring); +9 agent operator wave D3/D4: curated --help short-circuit (renderer in cli/help/render.ts), curated flag-value validation call (cli/help/validate.ts), table-dispatched SELF_HELP_WITHOUT_ENGINE entries for the selfHelp flips; +5 agent operator wave C10 (merged from the collector): serve --fail-fast in the connect-failure path; +31 #5950 (D6): connectEngine thin-client backstop, engine-free MCP-twin dispatch, recall/advisor/export refusal hints, refusal fix subcommand (lowered to 3131 by D1's renderCliError seam first); +2 agent operator wave A4: observational startup (probe-only connect for startup:observational commands; completeEngineStartup split out of connectEngine, exposed as ctx.completeStartup); +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5232: write-wait import, reporter-owned verdict in the op catch, thin-client writeWaitMs, ctx.writeWaitMs (logic in persistence/write-wait.ts); +1 #4768: serve --access help line; +4 #5433: list_pages TSV cell escaping in formatResult; +2 #lane-h pricing: help line + thin-client refusal hint for `gbrain pricing`; +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5433: list_pages TSV cell escaping in formatResult; +1 #5984: a strict run deadline when no progress window is set; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (3199 measured); +3 agent operator gate fixes: repair-failed connect wrapper (logic in cli/cli-error.ts exitOnRepairFailed), transcripts recent through a live serve (logic in commands/transcripts.ts), pre-connect status reason (logic in commands/serve-status.ts); +23 merged from the collector (Lanes B/E/F: thin-client token reason, status-only serve hand-off, jobs/sync readiness wiring); +9 agent operator wave D3/D4: curated --help short-circuit (renderer in cli/help/render.ts), curated flag-value validation call (cli/help/validate.ts), table-dispatched SELF_HELP_WITHOUT_ENGINE entries for the selfHelp flips; +5 agent operator wave C10 (merged from the collector): serve --fail-fast in the connect-failure path; +31 #5950 (D6): connectEngine thin-client backstop, engine-free MCP-twin dispatch, recall/advisor/export refusal hints, refusal fix subcommand (lowered to 3131 by D1's renderCliError seam first); +2 agent operator wave A4: observational startup (probe-only connect for startup:observational commands; completeEngineStartup split out of connectEngine, exposed as ctx.completeStartup); +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5232: write-wait import, reporter-owned verdict in the op catch, thin-client writeWaitMs, ctx.writeWaitMs (logic in persistence/write-wait.ts); +1 #4768: serve --access help line; +4 #5433: list_pages TSV cell escaping in formatResult; +2 #lane-h pricing: help line + thin-client refusal hint for `gbrain pricing`; +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5433: list_pages TSV cell escaping in formatResult; +1 #5984: a strict run deadline when no progress window is set; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (3199 measured); +6 engine graduation (GBRA-50 G3): migrate pre-connect route (logic in commands/migrate-graduation.ts), serve start refusal and degraded-reconnect identity gate (logic in persistence/graduation-serve-guard.ts), usage line; +3 engine graduation (GBRA-50 G2a): connect-path graduation check on every engine (logic in persistence/graduation-custody.ts assertGraduationConnectAllowed); GBRA-49: edge-proposals answers --help without a brain (SELF_HELP_WITHOUT_ENGINE row); -25 agent-operator follow-up Item 3: the host connect moved to core/engine-connect.ts (throw-only connectEngineForServe, wrapped by connectEngine; the graduation connect gate moved with it); 1 Foundations 2 Lane F: sources refresh pre-connect delegation to a resident PGLite owner (logic in commands/sources-refresh-delegate.ts); +3 agent operator gate fixes: repair-failed connect wrapper (logic in cli/cli-error.ts exitOnRepairFailed), transcripts recent through a live serve (logic in commands/transcripts.ts), pre-connect status reason (logic in commands/serve-status.ts); +23 merged from the collector (Lanes B/E/F: thin-client token reason, status-only serve hand-off, jobs/sync readiness wiring); +9 agent operator wave D3/D4: curated --help short-circuit (renderer in cli/help/render.ts), curated flag-value validation call (cli/help/validate.ts), table-dispatched SELF_HELP_WITHOUT_ENGINE entries for the selfHelp flips; +5 agent operator wave C10 (merged from the collector): serve --fail-fast in the connect-failure path; +31 #5950 (D6): connectEngine thin-client backstop, engine-free MCP-twin dispatch, recall/advisor/export refusal hints, refusal fix subcommand (lowered to 3131 by D1's renderCliError seam first); +2 agent operator wave A4: observational startup (probe-only connect for startup:observational commands; completeEngineStartup split out of connectEngine, exposed as ctx.completeStartup); +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5232: write-wait import, reporter-owned verdict in the op catch, thin-client writeWaitMs, ctx.writeWaitMs (logic in persistence/write-wait.ts); +1 #4768: serve --access help line; +4 #5433: list_pages TSV cell escaping in formatResult; +2 #lane-h pricing: help line + thin-client refusal hint for `gbrain pricing`; +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5433: list_pages TSV cell escaping in formatResult; +1 #5984: a strict run deadline when no progress window is set; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (3199 measured); +3 agent operator gate fixes: repair-failed connect wrapper (logic in cli/cli-error.ts exitOnRepairFailed), transcripts recent through a live serve (logic in commands/transcripts.ts), pre-connect status reason (logic in commands/serve-status.ts); +23 merged from the collector (Lanes B/E/F: thin-client token reason, status-only serve hand-off, jobs/sync readiness wiring); +9 agent operator wave D3/D4: curated --help short-circuit (renderer in cli/help/render.ts), curated flag-value validation call (cli/help/validate.ts), table-dispatched SELF_HELP_WITHOUT_ENGINE entries for the selfHelp flips; +5 agent operator wave C10 (merged from the collector): serve --fail-fast in the connect-failure path; +31 #5950 (D6): connectEngine thin-client backstop, engine-free MCP-twin dispatch, recall/advisor/export refusal hints, refusal fix subcommand (lowered to 3131 by D1's renderCliError seam first); +2 agent operator wave A4: observational startup (probe-only connect for startup:observational commands; completeEngineStartup split out of connectEngine, exposed as ctx.completeStartup); +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5232: write-wait import, reporter-owned verdict in the op catch, thin-client writeWaitMs, ctx.writeWaitMs (logic in persistence/write-wait.ts); +1 #4768: serve --access help line; +4 #5433: list_pages TSV cell escaping in formatResult; +2 #lane-h pricing: help line + thin-client refusal hint for `gbrain pricing`; +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5433: list_pages TSV cell escaping in formatResult; +1 #5984: a strict run deadline when no progress window is set; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (3199 measured); +6 engine graduation (GBRA-50 G3): migrate pre-connect route (logic in commands/migrate-graduation.ts), serve start refusal and degraded-reconnect identity gate (logic in persistence/graduation-serve-guard.ts), usage line; +3 engine graduation (GBRA-50 G2a): connect-path graduation check on every engine (logic in persistence/graduation-custody.ts assertGraduationConnectAllowed); GBRA-49: edge-proposals answers --help without a brain (SELF_HELP_WITHOUT_ENGINE row); -25 agent-operator follow-up Item 3: the host connect moved to core/engine-connect.ts (throw-only connectEngineForServe, wrapped by connectEngine; the graduation connect gate moved with it); +2 entity recall: the human `gbrain entity` card prints referenced_by groups and a non-complete mention coverage; cat40 entity wave merge with v0.60.61.0 (3179 measured); +3 #4772 (W14 PR3): get_health text output says the entity ratios are n/a because the schema pack did not load (entity_types_status); +1 C4: gbrain questions CLI-only dispatch row (its help line is in cli/top-help.ts); +1 #6696 (A4): a local write captures the capacity notices (one call; logic in cli/op-notices.ts captureCapacityNotices); +1 large pages A6: the stdin cap reads PAGE_MAX_BYTES from core/page-size-policy.ts; +3 Wave B PR 2: local gbrain get of a segmented page streams on the page_body_segmented refusal (logic in cli/page-render.ts streamSegmentedGet); +1 #6712 PR 3 (L7): the sync_retry_failed_deprecated notice call (logic in commands/sync/args.ts noteRetryFailedDeprecated);+1 Cat 41 run 4: recall's SELF_HELP_WITHOUT_ENGINE table entry (a dispatch table row cannot move); +1 GBRA-133 PR 2a: sync trigger through a live PGLite serve (logic in commands/sync-delegate.ts maybeTriggerThroughServe); +1 GBRA-133 PR 2a merge: master and the sync trigger serve hand-off each added a dispatch row; +3 #7147: a one-shot read opens and closes its config snapshot around the context build and the operation (logic in core/config-snapshot.ts openRequestConfigSnapshot) and imports it+src/cli/main.ts 3024 ratchet +1 W1 belief ledger: `gbrain beliefs --help` in SELF_HELP_WITHOUT_ENGINE; +1 Cat 41 run 4: recall's SELF_HELP_WITHOUT_ENGINE table entry (a dispatch table row cannot move); moved from src/cli.ts at 3214 (cold start: src/cli.ts is now the 66-line entry with the --version/help fast path; the top-level help text moved to cli/top-help.ts and the exit seam became runCli/exitOnFatalCliError); +2 #6340: the sync status / sync unblock preflight skip (logic in commands/sync/operator.ts); +3 agent operator gate fixes: repair-failed connect wrapper (logic in cli/cli-error.ts exitOnRepairFailed), transcripts recent through a live serve (logic in commands/transcripts.ts), pre-connect status reason (logic in commands/serve-status.ts); +23 merged from the collector (Lanes B/E/F: thin-client token reason, status-only serve hand-off, jobs/sync readiness wiring); +9 agent operator wave D3/D4: curated --help short-circuit (renderer in cli/help/render.ts), curated flag-value validation call (cli/help/validate.ts), table-dispatched SELF_HELP_WITHOUT_ENGINE entries for the selfHelp flips; +5 agent operator wave C10 (merged from the collector): serve --fail-fast in the connect-failure path; +31 #5950 (D6): connectEngine thin-client backstop, engine-free MCP-twin dispatch, recall/advisor/export refusal hints, refusal fix subcommand (lowered to 3131 by D1's renderCliError seam first); +2 agent operator wave A4: observational startup (probe-only connect for startup:observational commands; completeEngineStartup split out of connectEngine, exposed as ctx.completeStartup); +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5232: write-wait import, reporter-owned verdict in the op catch, thin-client writeWaitMs, ctx.writeWaitMs (logic in persistence/write-wait.ts); +1 #4768: serve --access help line; +4 #5433: list_pages TSV cell escaping in formatResult; +2 #lane-h pricing: help line + thin-client refusal hint for `gbrain pricing`; +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5433: list_pages TSV cell escaping in formatResult; +1 #5984: a strict run deadline when no progress window is set; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (3199 measured); +2 retrieval feedback: answer id line on stderr and additive answer_id on --json search/query rows (logic in feedback/record.ts); +1 feedback help line and its D3 table-dispatch entry (logic in commands/feedback.ts); 6 engine graduation (GBRA-50 G3): migrate pre-connect route (logic in commands/migrate-graduation.ts), serve start refusal and degraded-reconnect identity gate (logic in persistence/graduation-serve-guard.ts), usage line; +3 engine graduation (GBRA-50 G2a): connect-path graduation check on every engine (logic in persistence/graduation-custody.ts assertGraduationConnectAllowed); P3 x engine graduation composition: both deltas re-summed at the merge; 1 Foundations 2 Lane F: sources refresh pre-connect delegation to a resident PGLite owner (logic in commands/sources-refresh-delegate.ts); +3 agent operator gate fixes: repair-failed connect wrapper (logic in cli/cli-error.ts exitOnRepairFailed), transcripts recent through a live serve (logic in commands/transcripts.ts), pre-connect status reason (logic in commands/serve-status.ts); +23 merged from the collector (Lanes B/E/F: thin-client token reason, status-only serve hand-off, jobs/sync readiness wiring); +9 agent operator wave D3/D4: curated --help short-circuit (renderer in cli/help/render.ts), curated flag-value validation call (cli/help/validate.ts), table-dispatched SELF_HELP_WITHOUT_ENGINE entries for the selfHelp flips; +5 agent operator wave C10 (merged from the collector): serve --fail-fast in the connect-failure path; +31 #5950 (D6): connectEngine thin-client backstop, engine-free MCP-twin dispatch, recall/advisor/export refusal hints, refusal fix subcommand (lowered to 3131 by D1's renderCliError seam first); +2 agent operator wave A4: observational startup (probe-only connect for startup:observational commands; completeEngineStartup split out of connectEngine, exposed as ctx.completeStartup); +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5232: write-wait import, reporter-owned verdict in the op catch, thin-client writeWaitMs, ctx.writeWaitMs (logic in persistence/write-wait.ts); +1 #4768: serve --access help line; +4 #5433: list_pages TSV cell escaping in formatResult; +2 #lane-h pricing: help line + thin-client refusal hint for `gbrain pricing`; +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5433: list_pages TSV cell escaping in formatResult; +1 #5984: a strict run deadline when no progress window is set; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (3199 measured); +3 agent operator gate fixes: repair-failed connect wrapper (logic in cli/cli-error.ts exitOnRepairFailed), transcripts recent through a live serve (logic in commands/transcripts.ts), pre-connect status reason (logic in commands/serve-status.ts); +23 merged from the collector (Lanes B/E/F: thin-client token reason, status-only serve hand-off, jobs/sync readiness wiring); +9 agent operator wave D3/D4: curated --help short-circuit (renderer in cli/help/render.ts), curated flag-value validation call (cli/help/validate.ts), table-dispatched SELF_HELP_WITHOUT_ENGINE entries for the selfHelp flips; +5 agent operator wave C10 (merged from the collector): serve --fail-fast in the connect-failure path; +31 #5950 (D6): connectEngine thin-client backstop, engine-free MCP-twin dispatch, recall/advisor/export refusal hints, refusal fix subcommand (lowered to 3131 by D1's renderCliError seam first); +2 agent operator wave A4: observational startup (probe-only connect for startup:observational commands; completeEngineStartup split out of connectEngine, exposed as ctx.completeStartup); +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5232: write-wait import, reporter-owned verdict in the op catch, thin-client writeWaitMs, ctx.writeWaitMs (logic in persistence/write-wait.ts); +1 #4768: serve --access help line; +4 #5433: list_pages TSV cell escaping in formatResult; +2 #lane-h pricing: help line + thin-client refusal hint for `gbrain pricing`; +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5433: list_pages TSV cell escaping in formatResult; +1 #5984: a strict run deadline when no progress window is set; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (3199 measured); +6 engine graduation (GBRA-50 G3): migrate pre-connect route (logic in commands/migrate-graduation.ts), serve start refusal and degraded-reconnect identity gate (logic in persistence/graduation-serve-guard.ts), usage line; +3 engine graduation (GBRA-50 G2a): connect-path graduation check on every engine (logic in persistence/graduation-custody.ts assertGraduationConnectAllowed); P3 x foundations-2 composition: deltas re-summed at the merge; 1 Foundations 2 Lane F: sources refresh pre-connect delegation to a resident PGLite owner (logic in commands/sources-refresh-delegate.ts); +3 agent operator gate fixes: repair-failed connect wrapper (logic in cli/cli-error.ts exitOnRepairFailed), transcripts recent through a live serve (logic in commands/transcripts.ts), pre-connect status reason (logic in commands/serve-status.ts); +23 merged from the collector (Lanes B/E/F: thin-client token reason, status-only serve hand-off, jobs/sync readiness wiring); +9 agent operator wave D3/D4: curated --help short-circuit (renderer in cli/help/render.ts), curated flag-value validation call (cli/help/validate.ts), table-dispatched SELF_HELP_WITHOUT_ENGINE entries for the selfHelp flips; +5 agent operator wave C10 (merged from the collector): serve --fail-fast in the connect-failure path; +31 #5950 (D6): connectEngine thin-client backstop, engine-free MCP-twin dispatch, recall/advisor/export refusal hints, refusal fix subcommand (lowered to 3131 by D1's renderCliError seam first); +2 agent operator wave A4: observational startup (probe-only connect for startup:observational commands; completeEngineStartup split out of connectEngine, exposed as ctx.completeStartup); +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5232: write-wait import, reporter-owned verdict in the op catch, thin-client writeWaitMs, ctx.writeWaitMs (logic in persistence/write-wait.ts); +1 #4768: serve --access help line; +4 #5433: list_pages TSV cell escaping in formatResult; +2 #lane-h pricing: help line + thin-client refusal hint for `gbrain pricing`; +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5433: list_pages TSV cell escaping in formatResult; +1 #5984: a strict run deadline when no progress window is set; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (3199 measured); +3 agent operator gate fixes: repair-failed connect wrapper (logic in cli/cli-error.ts exitOnRepairFailed), transcripts recent through a live serve (logic in commands/transcripts.ts), pre-connect status reason (logic in commands/serve-status.ts); +23 merged from the collector (Lanes B/E/F: thin-client token reason, status-only serve hand-off, jobs/sync readiness wiring); +9 agent operator wave D3/D4: curated --help short-circuit (renderer in cli/help/render.ts), curated flag-value validation call (cli/help/validate.ts), table-dispatched SELF_HELP_WITHOUT_ENGINE entries for the selfHelp flips; +5 agent operator wave C10 (merged from the collector): serve --fail-fast in the connect-failure path; +31 #5950 (D6): connectEngine thin-client backstop, engine-free MCP-twin dispatch, recall/advisor/export refusal hints, refusal fix subcommand (lowered to 3131 by D1's renderCliError seam first); +2 agent operator wave A4: observational startup (probe-only connect for startup:observational commands; completeEngineStartup split out of connectEngine, exposed as ctx.completeStartup); +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5232: write-wait import, reporter-owned verdict in the op catch, thin-client writeWaitMs, ctx.writeWaitMs (logic in persistence/write-wait.ts); +1 #4768: serve --access help line; +4 #5433: list_pages TSV cell escaping in formatResult; +2 #lane-h pricing: help line + thin-client refusal hint for `gbrain pricing`; +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5433: list_pages TSV cell escaping in formatResult; +1 #5984: a strict run deadline when no progress window is set; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (3199 measured); +6 engine graduation (GBRA-50 G3): migrate pre-connect route (logic in commands/migrate-graduation.ts), serve start refusal and degraded-reconnect identity gate (logic in persistence/graduation-serve-guard.ts), usage line; +3 engine graduation (GBRA-50 G2a): connect-path graduation check on every engine (logic in persistence/graduation-custody.ts assertGraduationConnectAllowed); GBRA-49: edge-proposals answers --help without a brain (SELF_HELP_WITHOUT_ENGINE row); P3 x P1 (v0.60.57.0) composition: deltas re-summed at the merge; 1 Foundations 2 Lane F: sources refresh pre-connect delegation to a resident PGLite owner (logic in commands/sources-refresh-delegate.ts); +3 agent operator gate fixes: repair-failed connect wrapper (logic in cli/cli-error.ts exitOnRepairFailed), transcripts recent through a live serve (logic in commands/transcripts.ts), pre-connect status reason (logic in commands/serve-status.ts); +23 merged from the collector (Lanes B/E/F: thin-client token reason, status-only serve hand-off, jobs/sync readiness wiring); +9 agent operator wave D3/D4: curated --help short-circuit (renderer in cli/help/render.ts), curated flag-value validation call (cli/help/validate.ts), table-dispatched SELF_HELP_WITHOUT_ENGINE entries for the selfHelp flips; +5 agent operator wave C10 (merged from the collector): serve --fail-fast in the connect-failure path; +31 #5950 (D6): connectEngine thin-client backstop, engine-free MCP-twin dispatch, recall/advisor/export refusal hints, refusal fix subcommand (lowered to 3131 by D1's renderCliError seam first); +2 agent operator wave A4: observational startup (probe-only connect for startup:observational commands; completeEngineStartup split out of connectEngine, exposed as ctx.completeStartup); +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5232: write-wait import, reporter-owned verdict in the op catch, thin-client writeWaitMs, ctx.writeWaitMs (logic in persistence/write-wait.ts); +1 #4768: serve --access help line; +4 #5433: list_pages TSV cell escaping in formatResult; +2 #lane-h pricing: help line + thin-client refusal hint for `gbrain pricing`; +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5433: list_pages TSV cell escaping in formatResult; +1 #5984: a strict run deadline when no progress window is set; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (3199 measured); +3 agent operator gate fixes: repair-failed connect wrapper (logic in cli/cli-error.ts exitOnRepairFailed), transcripts recent through a live serve (logic in commands/transcripts.ts), pre-connect status reason (logic in commands/serve-status.ts); +23 merged from the collector (Lanes B/E/F: thin-client token reason, status-only serve hand-off, jobs/sync readiness wiring); +9 agent operator wave D3/D4: curated --help short-circuit (renderer in cli/help/render.ts), curated flag-value validation call (cli/help/validate.ts), table-dispatched SELF_HELP_WITHOUT_ENGINE entries for the selfHelp flips; +5 agent operator wave C10 (merged from the collector): serve --fail-fast in the connect-failure path; +31 #5950 (D6): connectEngine thin-client backstop, engine-free MCP-twin dispatch, recall/advisor/export refusal hints, refusal fix subcommand (lowered to 3131 by D1's renderCliError seam first); +2 agent operator wave A4: observational startup (probe-only connect for startup:observational commands; completeEngineStartup split out of connectEngine, exposed as ctx.completeStartup); +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5232: write-wait import, reporter-owned verdict in the op catch, thin-client writeWaitMs, ctx.writeWaitMs (logic in persistence/write-wait.ts); +1 #4768: serve --access help line; +4 #5433: list_pages TSV cell escaping in formatResult; +2 #lane-h pricing: help line + thin-client refusal hint for `gbrain pricing`; +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5433: list_pages TSV cell escaping in formatResult; +1 #5984: a strict run deadline when no progress window is set; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (3199 measured); +6 engine graduation (GBRA-50 G3): migrate pre-connect route (logic in commands/migrate-graduation.ts), serve start refusal and degraded-reconnect identity gate (logic in persistence/graduation-serve-guard.ts), usage line; +3 engine graduation (GBRA-50 G2a): connect-path graduation check on every engine (logic in persistence/graduation-custody.ts assertGraduationConnectAllowed); GBRA-49: edge-proposals answers --help without a brain (SELF_HELP_WITHOUT_ENGINE row); -25 agent-operator follow-up Item 3: the host connect moved to core/engine-connect.ts (throw-only connectEngineForServe, wrapped by connectEngine; the graduation connect gate moved with it); 1 Foundations 2 Lane F: sources refresh pre-connect delegation to a resident PGLite owner (logic in commands/sources-refresh-delegate.ts); +3 agent operator gate fixes: repair-failed connect wrapper (logic in cli/cli-error.ts exitOnRepairFailed), transcripts recent through a live serve (logic in commands/transcripts.ts), pre-connect status reason (logic in commands/serve-status.ts); +23 merged from the collector (Lanes B/E/F: thin-client token reason, status-only serve hand-off, jobs/sync readiness wiring); +9 agent operator wave D3/D4: curated --help short-circuit (renderer in cli/help/render.ts), curated flag-value validation call (cli/help/validate.ts), table-dispatched SELF_HELP_WITHOUT_ENGINE entries for the selfHelp flips; +5 agent operator wave C10 (merged from the collector): serve --fail-fast in the connect-failure path; +31 #5950 (D6): connectEngine thin-client backstop, engine-free MCP-twin dispatch, recall/advisor/export refusal hints, refusal fix subcommand (lowered to 3131 by D1's renderCliError seam first); +2 agent operator wave A4: observational startup (probe-only connect for startup:observational commands; completeEngineStartup split out of connectEngine, exposed as ctx.completeStartup); +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5232: write-wait import, reporter-owned verdict in the op catch, thin-client writeWaitMs, ctx.writeWaitMs (logic in persistence/write-wait.ts); +1 #4768: serve --access help line; +4 #5433: list_pages TSV cell escaping in formatResult; +2 #lane-h pricing: help line + thin-client refusal hint for `gbrain pricing`; +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5433: list_pages TSV cell escaping in formatResult; +1 #5984: a strict run deadline when no progress window is set; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (3199 measured); +3 agent operator gate fixes: repair-failed connect wrapper (logic in cli/cli-error.ts exitOnRepairFailed), transcripts recent through a live serve (logic in commands/transcripts.ts), pre-connect status reason (logic in commands/serve-status.ts); +23 merged from the collector (Lanes B/E/F: thin-client token reason, status-only serve hand-off, jobs/sync readiness wiring); +9 agent operator wave D3/D4: curated --help short-circuit (renderer in cli/help/render.ts), curated flag-value validation call (cli/help/validate.ts), table-dispatched SELF_HELP_WITHOUT_ENGINE entries for the selfHelp flips; +5 agent operator wave C10 (merged from the collector): serve --fail-fast in the connect-failure path; +31 #5950 (D6): connectEngine thin-client backstop, engine-free MCP-twin dispatch, recall/advisor/export refusal hints, refusal fix subcommand (lowered to 3131 by D1's renderCliError seam first); +2 agent operator wave A4: observational startup (probe-only connect for startup:observational commands; completeEngineStartup split out of connectEngine, exposed as ctx.completeStartup); +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5232: write-wait import, reporter-owned verdict in the op catch, thin-client writeWaitMs, ctx.writeWaitMs (logic in persistence/write-wait.ts); +1 #4768: serve --access help line; +4 #5433: list_pages TSV cell escaping in formatResult; +2 #lane-h pricing: help line + thin-client refusal hint for `gbrain pricing`; +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5433: list_pages TSV cell escaping in formatResult; +1 #5984: a strict run deadline when no progress window is set; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (3199 measured); +6 engine graduation (GBRA-50 G3): migrate pre-connect route (logic in commands/migrate-graduation.ts), serve start refusal and degraded-reconnect identity gate (logic in persistence/graduation-serve-guard.ts), usage line; +3 engine graduation (GBRA-50 G2a): connect-path graduation check on every engine (logic in persistence/graduation-custody.ts assertGraduationConnectAllowed); GBRA-49: edge-proposals answers --help without a brain (SELF_HELP_WITHOUT_ENGINE row); -25 agent-operator follow-up Item 3: the host connect moved to core/engine-connect.ts (throw-only connectEngineForServe, wrapped by connectEngine; the graduation connect gate moved with it); +2 entity recall: the human `gbrain entity` card prints referenced_by groups and a non-complete mention coverage; cat40 entity wave merge with v0.60.61.0 (3179 measured); +3 #4772 (W14 PR3): get_health text output says the entity ratios are n/a because the schema pack did not load (entity_types_status); +1 C4: gbrain questions CLI-only dispatch row (its help line is in cli/top-help.ts); +1 #6696 (A4): a local write captures the capacity notices (one call; logic in cli/op-notices.ts captureCapacityNotices); +1 large pages A6: the stdin cap reads PAGE_MAX_BYTES from core/page-size-policy.ts; +3 Wave B PR 2: local gbrain get of a segmented page streams on the page_body_segmented refusal (logic in cli/page-render.ts streamSegmentedGet); +1 #6712 PR 3 (L7): the sync_retry_failed_deprecated notice call (logic in commands/sync/args.ts noteRetryFailedDeprecated);+1 Cat 41 run 4: recall's SELF_HELP_WITHOUT_ENGINE table entry (a dispatch table row cannot move); +1 GBRA-133 PR 2a: sync trigger through a live PGLite serve (logic in commands/sync-delegate.ts maybeTriggerThroughServe); +1 GBRA-133 PR 2a merge: master and the sync trigger serve hand-off each added a dispatch row; +3 #7147: a one-shot read opens and closes its config snapshot around the context build and the operation (logic in core/config-snapshot.ts openRequestConfigSnapshot) and imports it; +5 #7147 follow-up: a one-shot read hands its startup config snapshot to search, sources list and a one-shot recall (logic in core/engine-connect.ts takeStartupConfigSnapshot)src/commands/autopilot.ts 1662 ratchet refactor wave 1 split target (W4 autopilot, cut line); ceiling rationale: docs/architecture/key-files/commands-1.md entry for src/commands/autopilot.ts; +2 fix wave 5: nosemgrep justifications on the per-brain job launchctl/systemctl calls (#5195); +2 #5813: boot reconcile names attempted and running versions in log + audit; +2 #5855: Bun floor gate before the swap and the swap-refusal hold (logic in core/bun-floor.ts); +3 agent operator wave E9: --dry-run and the persistent_install consent gate before anything is written (logic in autopilot/install-consent.ts); +8 GBRA-130 C-6/A-10: the --retry-global mode row, help line and --phase value flag, and --status reading the brain-wide maintenance verdict into its JSON, text and exit code (logic in core/minions/global-maintenance-stall.ts and autopilot-retry-global.ts); +12 GBRA-133 #7003: --status grades from the daemon's heartbeat sidecar (two report fields and their doc line, the classifier's daemon input and threshold branch, the import and the showStatus read; logic in core/autopilot-heartbeat.ts)src/commands/doctor.ts 692 ratchet +2 Wave B decision #10: Check.skipped_segmented field (logic in doctor/check-fix.ts withSkippedSegmented); +19 #6696 doctor tiers: Check.elapsed_ms and DoctorReport tier/complete/unknown_sections/elapsed_ms/budget_ms fields, buildChecks/runDoctor deadline params (logic in doctor/budget.ts); +1 agent operator gate fixes: --probe consent gate (logic in doctor/probe-consent.ts); refactor wave 1 split target (W4 doctor); ceiling rationale: docs/architecture/key-files/commands-2.md entry for src/commands/doctor.ts; +4 #7142: DoctorReport.last_known_sections field and the buildChecks last-known/refresh scope params (logic in doctor/last-known.ts)src/commands/embed.ts 2304 ratchet +2 agent operator wave D2: --json failure envelope via writeCliError; lowered v0.46.26.0: embedBatchWithBackoff + retry cluster peeled to core/embed-retry.ts (core/commands layering fix); grown wave-g (#4530): per-model input-limit wiring; wave-k #3622 reimpl: --stale zero-progress failure quarantine; +29 #4668 (#4530): oversize-heal call sites in both --stale drains — kept low by peeling the healed-row remap to core/embed-oversize-heal.ts (shared with embed-stale.ts); +35 #4647 (refs #4599): per-tick timeout+abort on the single-flight lock heartbeat refresh (interval deliberately NOT unref'd); +122 refs #4599: stall-watchdog race around the drain + shared idempotent flushAndRelease + CLI stall exit mapping (watchdog machinery itself lives in core/embed-stall.ts); +12: adversarial-review hardening (healed_splits progress key + heal-tick comment); #5105: guarded derived projection preparation and read seals; #5105: conditional embedding installer wiring; archived eligibility: active-only dispatch with honest stranded-work reporting; explicit archived admission: live-source snapshots and honest refused-installation failures; +2 fw3: embed --stale --images dispatch (sweep lives in core/embed-stale-images.ts); +5 #5289: dry run reports restamp-only chunks apart from chunks to embed (count lives in core/embedding-invalidation.ts); +6 #4616: keep a partially refused batch in embedPageTexts and name the recovery command in failure samples (guard lives in core/ai/embedding-guard.ts); +5 #5226: embed summary counts distinct pages; +3 #5804: null projection snapshot counted as a failure with one batch summary in embed --stale; +18 wave 8 lane D1: #5527 mixed-space warning subtracts current-model chunks (+4), #5885 takes option/result fields and the stale-drain takes call (pass lives in core/embed-takes.ts); +9 Foundations 1 F4d: time-budget stop result fields, stdout verdict and stop recording in embed --stale (logic in core/embed-budget-stop.ts); +8 green-master lane A: chunkless install re-reads through retryProjectionConflict instead of recording an unavailable page (retry lives in core/page-state/projections.ts, failure line in core/agent-output.ts); +8 fix wave 13 P1.18: runEmbed consent parameter, cost-cap stop wiring and result fields, --slugs parsing to the next flag (cap, verdict and resume logic live in core/embed-cost-cap.ts); +28 large pages A9/T3/T16: --held listing and per-page cap metering on every embed path (logic in core/page-embedding-budget.ts meterPageBatch/spendGrant/heldEmbedArgv), approvedPageCapUsd from --max-usd on --slugs; +1 #6722: an explicit slug embed skips an embed_skip page (it keeps keyword chunks, never vectors); merge v0.60.240.0: large pages and master growth compose at 2265; +39 large pages Wave B lane 1e: segmented pages route to the keyset sweep on the slug, --all and --stale paths, with a dry-run count and provenance stamp (logic in core/page-body/segmented-embedding.ts)@@ -23,7 +23,7 @@ src/core/operations.ts 242 ratchet peel target: containment sprint C4-C7; grownsrc/core/pglite-engine.ts 3085 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)src/core/postgres-engine.ts 3107 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)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 2325 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)+src/core/types.ts 2327 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); +2 #7147 follow-up: EngineConfig.pool_max (interface field + doc)src/core/minions/queue.ts 2533 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)src/commands/init.ts 1884 ratchet +2 fix wave 9 lane F #5253: leaving deferred setup also clears the DB-plane embedding_disabled row (both init branches); grown v0.46.x keyless capability notices; grown db-availability loop: initPostgresCore typed-failure extraction + --prefer-postgres ladder hook + pgvector rethrow fix; +1 at megawave/wave-k merge; +master-merge true-up; wave-k: merge; #3753 --force re-init engine-preservation guard; +1 wave-k merge-union brace (--prefer-postgres close); +10 ambient-writeback WP8: runWritebackNudge consent ask in both engine epilogues (logic lives in core/onboard/writeback-nudge.ts); +4: v0.48.2 reranker readiness at init + test seam; +1: v0.48.2 provider normalization; +3: v0.48.2 review fixes; master integration: +2: preserve typed PGLite busy errors in schema-only init; shared-skills integration on company-ingestion base; retired provider integration removed; retain stored-vector identity on re-init; -14: first-run bundle + quickstart registration helpers live in init-first-run.ts (writeback/skills asks folded into the bundle); +5 agent operator follow-up Item 2: --surface flag (value flag, parse, help line, module-level registration surface, type import) for the printed harness registration; +2 fix wave lane B3: both engine paths stamp a database init created as a fresh install for the behavior_changes notice (core/behavior-change-notice.ts); +4 GBRA-81 item 1: --search-mode value flag, its parse line, module-level choice, help line (picker logic lives in init-mode-picker.ts); +2 D8 funnel: a fresh init counts one clean_install when the opt-in funnel is on (core/funnel.ts)src/commands/integrations.ts 1739 ratchet grown v0.46.26.0 megawave (#4039 connector compat) + 1 nosemgrep dataflow annotation (path-traversal audit); wave-k: exported heartbeatPath seam (#3900)@@ -40,7 +40,7 @@ src/core/config.ts 1992 ratchet +2 W5: search.page_rank_cut / page_rank_cut_factsrc/core/persistence/sync-run.ts 1681 ratchet new row: crossed the 1500 unlisted cap in #6643 (knock-on re-freeze, checkpoint revival, root cause and the truthful --retry-failed wait all drive the private cursor/gate machinery: holdUnderGate, freezeEntry, saveCursor); classification lives in sync-knock-on.ts, the checkpoint clause in checkpoint-validation.ts; peel the settle path (settleFailedRequest and its recoveries) into a sibling module next; +3 #6722: committed pages' size_state tallied into the cursor and the sync receipt size_states (logic in page-embedding-budget.ts addSizeState); merge v0.60.240.0: large pages and master growth compose at 1687; +2 #6694: the slug-mode checkpoint revival import and its doc line (predicate lives in persistence/sync-slug-mode.ts); +11 #6712 PR 3 (L7): a plain sync retries the recorded failure --retry-failed used to (retryRecordedFailure; the unchanged-refusal replay lives in persistence/sync-stop-class.ts replaysUnchangedRefusal), the moved-checkpoint and company content-refusal exceptions; #6712 PR 3 integration: lanes L7 (retryRecordedFailure, +19) and L8 (#6727 legacy-slug refusal line, #6735 timeout revival, +6) compose at 1762; +2 wave 18a integration: #6729 (lane 2, written against the 1745 ceiling) records identity downgrades in performManagedPass through noteIdentityDowngrades (logic in core/sync-identity-downgrades.ts), composed with master 1762; +14 Wave B PR 2: freezeEntry freezes a Markdown file over the read bound by reference (body_ref) and holdFailedFenceRequest holds a streamed refusal; both set freezeEntry/holdFailedFenceRequest locals (blob, oversize, rawHash) so they stay here, the hashing and preparation live in persistence/sync-streamed.ts and the hold in sync-screen.ts streamedRefusalHold; integrated at the master 4e29d0904 merge: master 1764 + Wave B PR 2 14 = 1778 measured; +4 #6948: freezeEntry holds an entry several live pages claim (hold in sync-screen.ts originConflictHold, verdict in persistence/origin-twins.ts)src/core/bootstrap/harness.ts 2592 ratchet +29 live-PGLite-serve lane: LIVE_SERVE refusal ahead of source resolution + unpinned --token hooks (CI e2e fix); +46 wave review: resolveHookSource dep (serve-parity resolver + federated grant), --source shape validation, loud SOURCE_UNRESOLVED instead of a silent 'default'; +10: #4574 parseCodexBlockBearer http_headers shape + legacy bearer_token fallback; +4 at megawave/wave-k merge; +codex hooks lane: step-7 codex hooks.json + config.toml trust pair, removeHarness arm; +234 ambient-writeback WP3: kind:'instructions' targets (plan/apply/converge-off/remove/status probes, OV-A4 override pre-check) — splice/render mechanics live in instructions-block.ts; +59 adversarial fix wave: registrar-mode block suppression, converge-failure receipt tracking, MCP-confirmed guard before block install; +26 round-3 fixes: codex-lane MCP-confirmed guard + smoke-rollback block strip; master: | merged v0.48.1.0 true-up; +41 #4897 resolveImplicitSource dep + defaultResolveImplicitSource: hooks/token/receipt bind to the serve's implicit default source when --source is omitted; +23 #4586 statusHarness live claude-code mcp verdict (URL mismatch or same-scope non-HTTP registration reads failed, receipt untouched); shared-skills integration on company-ingestion base; +18 #5671: logAmbientPostureNotes helper (registrar note moved out of applyHarness + pre-consent warning when an explicit private facts default meets the HTTP harness; text shared with doctor in facts/writeback-config.ts); +24 #5893: rotation grant carry wiring and its rotationCarry/withheldOperationsNote helpers (carry rules live in token-mint.ts carryLegacyGrant); +6 #5878: --refresh-skills flag and status epoch line (refresh logic lives in harness-skills.ts); +7 #4618 seat: HarnessFlags.seat field, --seat/--no-seat parse via hooks.ts parseSeatFlags, GBRAIN_SEAT in the hook env; -119 #6082: plugin-lane detectors moved to plugin-lanes.ts (re-exported); +18 #6092/#6171: hook ownership identity on write/remove/converge, permission ownership carry, --remove --dry-run and the --status hook census (logic in hooks.ts + harness-hooks.ts); +5 D8 Codex slice: the Codex SessionEnd capture hook obeys the recorded consent (wireCodexCapture: hooks on, capture accepted, never registrar mode) and is disclosed in the consent block; -31 #6743: cleanup gate moved to harness-cleanup.ts; +8 #6798: supersededEnrollments dep (interface field + default) and the --status epoch hint printed only for a superseded enrollment (the brain read lives in harness-skills.ts brainSupersededEnrollments)src/core/oauth-provider.ts 1236 ratchet new row: crossed the 1500 unlisted cap absorbing #3819 (DCR 400 invalid_client_metadata + scope filtering + custom-scheme redirect_uris + pseudo-scheme guard); merged v0.49: transactional grant enforcement shared with hosted grant policies; +1 #5222 resourceUrl option-src/core/ops/pages.ts 716 ratchet crossed the unlisted 1500 cap in the fix wave: pack-vocabulary enforcement on capture (#4721) + get_page alias follow (#4275) landed together; next growth should peel a pages-ops submodule; +3: alias hop reads the canonical in the owning source (ship-review); +5: explicit source_id liveness check in get_page/list_pages (#4620); +3: #4857 total-order slug sort + list_pages source_id parse; +5: #4620 explicit removed-source id fails loudly; master integration: +4: authenticated delegated private-write boundary and auto-link suppression; #5105: canonical page mutations peeled into persistence modules; +2 v0.50.5.0 purge parameter and shared preflight call; preparation composes through the persistence modules; +7: source-qualified deep-research fetch authorization and ambiguity refusal (codec lives in deep-research-id.ts); +1 #5567: remote get_page keeps materialized markers; +1 #5622: trusted local capture file parameter; +5 #5709: get_page include_timeline_entries (rows via get_timeline's read policy); +8 GBRA-36 security wave: required outputRedaction policy on each pages op; +1 #5154: list_pages passes listColumnsOnly; +17 #5641: list_pages exposes the updated_after_slug keyset cursor and updated_at_iso; +8 agent operator wave A2: every op declares mutating + idempotent (tags only); +7 F3b (#5954): list_pages pagination meta + listing_truncated notice for MCP callers (logic in ops/list-pages-pagination.ts); +4 #5988: get_page file_held (one indexed hold lookup; logic in persistence/held-reads.ts); +6 #6103: list_pages maps an unreadable updated_after (SQLSTATE 22007/22008) to invalid_params; wave 10 collector: #6103 (+6) and #4807 (+2) compose; +1 wave 11 W4.3 (#5969 D3): put_page drop_timeline param; +1 wave 11 security review: purge_deleted_pages yes param + trusted-CLI guard (consent logic in persistence/purge-deleted.ts); +1 Q2 parser gaps: get_page grammar_diagnostics param (report logic in core/line-grammar-report.ts); master v0.60.136.0 merge into #5575 memory trust (both sides kept); +21 large pages (Wave A): get_page body-mode dispatch, fetch window branch, put_page large-page admission and allow_shrink param, description text (logic in ops/get-page-body.ts and persistence/large-page-guard.ts); +1 D8 funnel: committed put_page records a save when the opt-in funnel is on; +1 #6609: restore_page detach param (logic in persistence/detached-pages.ts); +1 Wave B gem A: post-batch auto-link reads a segmented page materialized (helpers in persistence/segmented-apply.ts); merge v0.60.249.0: composes at 707; +4 Wave B PR 2: get_page refuses a segmented page whole and fetch windows one (logic in ops/get-page-body.ts and page-window/segmented.ts); +2 Wave B PR 2 lane F: get_page and fetch pin segmented reads to the authorized snapshot (pin logic in ops/get-page-body.ts authorizedReadPin); +3 W2 page-at-time: get_page known_as_of param and dispatch (logic in ops/known-as-of.ts and belief/page-at-time.ts)+src/core/ops/pages.ts 722 ratchet crossed the unlisted 1500 cap in the fix wave: pack-vocabulary enforcement on capture (#4721) + get_page alias follow (#4275) landed together; next growth should peel a pages-ops submodule; +3: alias hop reads the canonical in the owning source (ship-review); +5: explicit source_id liveness check in get_page/list_pages (#4620); +3: #4857 total-order slug sort + list_pages source_id parse; +5: #4620 explicit removed-source id fails loudly; master integration: +4: authenticated delegated private-write boundary and auto-link suppression; #5105: canonical page mutations peeled into persistence modules; +2 v0.50.5.0 purge parameter and shared preflight call; preparation composes through the persistence modules; +7: source-qualified deep-research fetch authorization and ambiguity refusal (codec lives in deep-research-id.ts); +1 #5567: remote get_page keeps materialized markers; +1 #5622: trusted local capture file parameter; +5 #5709: get_page include_timeline_entries (rows via get_timeline's read policy); +8 GBRA-36 security wave: required outputRedaction policy on each pages op; +1 #5154: list_pages passes listColumnsOnly; +17 #5641: list_pages exposes the updated_after_slug keyset cursor and updated_at_iso; +8 agent operator wave A2: every op declares mutating + idempotent (tags only); +7 F3b (#5954): list_pages pagination meta + listing_truncated notice for MCP callers (logic in ops/list-pages-pagination.ts); +4 #5988: get_page file_held (one indexed hold lookup; logic in persistence/held-reads.ts); +6 #6103: list_pages maps an unreadable updated_after (SQLSTATE 22007/22008) to invalid_params; wave 10 collector: #6103 (+6) and #4807 (+2) compose; +1 wave 11 W4.3 (#5969 D3): put_page drop_timeline param; +1 wave 11 security review: purge_deleted_pages yes param + trusted-CLI guard (consent logic in persistence/purge-deleted.ts); +1 Q2 parser gaps: get_page grammar_diagnostics param (report logic in core/line-grammar-report.ts); master v0.60.136.0 merge into #5575 memory trust (both sides kept); +21 large pages (Wave A): get_page body-mode dispatch, fetch window branch, put_page large-page admission and allow_shrink param, description text (logic in ops/get-page-body.ts and persistence/large-page-guard.ts); +1 D8 funnel: committed put_page records a save when the opt-in funnel is on; +1 #6609: restore_page detach param (logic in persistence/detached-pages.ts); +1 Wave B gem A: post-batch auto-link reads a segmented page materialized (helpers in persistence/segmented-apply.ts); merge v0.60.249.0: composes at 707; +4 Wave B PR 2: get_page refuses a segmented page whole and fetch windows one (logic in ops/get-page-body.ts and page-window/segmented.ts); +2 Wave B PR 2 lane F: get_page and fetch pin segmented reads to the authorized snapshot (pin logic in ops/get-page-body.ts authorizedReadPin); +3 W2 page-at-time: get_page known_as_of param and dispatch (logic in ops/known-as-of.ts and belief/page-at-time.ts); +6 #7147 follow-up: the write handlers load persistence/page-mutations.ts lazily (one loader line each), so a cold get_page skips the write pathsrc/core/search/mode.ts 1669 ratchet +53 W3 confidence-gated reranking: reranker_gate / reranker_gate_min_gap bundle fields, overrides, config parse and KNOB_CONFIG_KEY rows, knobsHash v=31 rrg=/rrgg=/ecf= parts (parse contracts in crag.ts); +10 System One v1: decide.* snapshot subset in loadSearchModeConfig, append-only dec= knobsHash part; +5 #3617 follow-up: v27 same-knobs behavioral-change note (relaxed-row fusion demotion rides the bump); new row: crossed the 1500 unlisted cap in the 2026-08 eval fix wave — KNOBS_HASH v=27 adaptive-return fold (ar/arem/arom/armk/ari parts + KnobsHashContext.adaptiveReturn field + contamination rationale comments) | merged v0.48.1.0 (+#4787) true-up; +master v0.48 merge true-up (reranker succession: no_key preflight, reranker_skipped stage, readiness); ranker wave v0.48.4.0: four knobs (expansion_variant_budget, relational_rerank_pin, keyword_arm_confidence_floor, metadata_boost_gate) + v29 hash parts + doc receipts (+218); #4781 loadSearchModeConfig reads the config table once via loadConfigSnapshot (+6); +4 #4359: update loadSearchModeConfig docstring — the cached path now reads config once (threaded snapshot), not twice; retired provider integration removed; +12 fw3-search: search.source_boosts + search.alias_token_hop read in the mode snapshot; +10 #5691: KnobsHashContext.queryPrefix and its append-only qp= part; P7 relational_planner / relational_orient_onehop knobs (interface docs, bundles, overrides, config parse, hash parts); +18 P7 relational_chain_slots knob (interface doc, bundles, override, config parse, rcs= hash part); +22 GBRA-60 S1 diverse_pool_depth knob (interface doc, bundles, overrides, pick, config parse, append-only dpd= hash part)src/commands/eval-longmemeval.ts 1544 ratchet new row: crossed the 1500 unlisted cap in fw3-search (#5092 benchmark-brain recycling: configureBrain split + recycler wiring + test seams; the recycler itself lives in src/eval/longmemeval/harness.ts); +1 P6: tokenmax synopsis-tier wiring (logic in eval/longmemeval/synopsis-tier.ts); +13 GBRA-81 lane A: --via-operation query|search (flags, per-call expansion pin, the run's expectExpansion, the op branch in runOneQuestion, row field, via_operation_summary and its FAIL line; logic in eval/longmemeval/via-operation.ts); +12 --call-plan FILE / --call-plan-gate CMD: two LME_FLAGS entries (CLI help lines), two ParsedArgs fields, the parseArgs pairing check and the header invariant (planner lives in eval/longmemeval/call-plan.ts; runEvalLongMemEval is one line shorter)src/commands/doctor/checks/extraction-sync.ts 1500 ratchet +7 GBRA-130 A-1: links_extraction_lag held bucket and its retry fix (logic in core/extraction-lag.ts heldExtractionReport); +1 undeclared_db_only_pages computes the source Git scope once per source (logic in core/markdown.ts sourceGitScope); new row: crossed the 1500 unlisted cap at the fix wave 9 merge: +7 lane W #5028 (extract_atoms freshness judged by the phase itself) and +3 lane F #5863 (extract_health dates a high halt rate by its last halt), each under the cap alone; +7 #5019: content_hash_duplicates fix pins the pairs' source (GBRAIN_SOURCE) and names a delete that runs; +1 fix wave 10 lane L1 #5556: links_extraction_lag denominator excludes quarantined pages (quarantineFilterFragment import); +11 fix wave 15 P2.8 (#5495): extract_health reads the 7-day halt reasons per kind (halt_reasons, top_halt_reason in details and the top reason in the warn line); the read, the unknown bucket and the ranking live in core/extract/rollup-writer.ts; +20 wave 18b lane 1: links_extraction_lag names the columns its pre-migration degrade reads (#6599 strict predicate), sync_freshness separates sync outcome from freshness for a source with no successful sync (#4960; verdict text, fixes and the attempt read live in doctor/sync-outcome.ts and core/sync-attempt.ts) and exempts read-only skill-pack catalogs (#6076; core/shared-skills/adopted-packs.ts); -51 #6803 (D1): links_extraction_lag reads its counts and verdict from core/extraction-lag.ts (shared with the sync nudge); +1 #7145: content_hash_duplicates reads one group past its list to report a floor ("at least 50")diff --git a/src/cli/main.ts b/src/cli/main.tsindex bc0548f581..90c57b281f 100755--- a/src/cli/main.ts+++ b/src/cli/main.ts@@ -641,7 +641,7 @@ async function runSharedOperation(command: string, subArgs: string[], cliOpts: C// timeout the abandoned handler may hold ref'd sockets — harmless here,// because the import.meta.main seam exits explicitly on every one-shot path.const READ_OP_TIMEOUT_MS = 180_000;- const configSnapshot = op.scope === 'read' ? openRequestConfigSnapshot(engine) : null;+ const configSnapshot = op.scope === 'read' ? takeStartupConfigSnapshot(engine) ?? openRequestConfigSnapshot(engine) : null;try {const { withTimeout, OperationTimeoutError } = await import('../core/timeout.ts');@@ -1994,9 +1994,11 @@ async function handleCliOnly(command: string, args: string[]) {if (!prepared) return;const engine = await connectCliOnlyEngine(command, prepared.args);if (!engine) return;+ const configSnapshot = takeStartupConfigSnapshot(engine);try {- await dispatchConnectedCommand(command, engine, prepared.args);+ await (configSnapshot ? configSnapshot.run(() => dispatchConnectedCommand(command, engine, prepared.args)) : dispatchConnectedCommand(command, engine, prepared.args));} finally {+ configSnapshot?.close();prepared.syncWatchdog?.dispose(); // #1633: tear down the hard-deadline watchdog on clean exit// #2084 — the CLI_ONLY fall-through teardown (drain every background-work// sink, THEN disconnect, under a computed-deadline backstop) lives in@@ -2404,8 +2406,9 @@ async function runReadOnlyTimeoutDispatch(command: string, args: string[]): Prom}throw e;}+ const configSnapshot = takeStartupConfigSnapshot(engine);try {- await withTimeout(dispatchReadOnlyCommand(engine, command, args), readOnlyTimeoutMs, label);+ await withTimeout(configSnapshot ? configSnapshot.run(() => dispatchReadOnlyCommand(engine, command, args)) : dispatchReadOnlyCommand(engine, command, args), readOnlyTimeoutMs, label);} catch (e) {if (e instanceof OperationTimeoutError) {const hint = userTimeoutMs ? '' : ` (default ${e.ms}ms; pass --timeout=Ns to override)`;@@ -2414,6 +2417,7 @@ async function runReadOnlyTimeoutDispatch(command: string, args: string[]): Prom}throw e;} finally {+ configSnapshot?.close();await finishCliTeardown({ engine });}return true;@@ -2619,7 +2623,8 @@ async function connectCliOnlyEngine(command: string, args: string[]): Promise<Br}try {// A4: an observational command connects probe-only and completes startup only after consent.- engine = await connectEngine({ probeOnly: findCliCommand(command)?.startup === 'observational' || (command === 'jobs' && args[0] === 'supervisor' && args[1] === 'status') });+ // A one-shot `recall` only reads the brain (its --since-last-run cursor is a file); --watch polls for minutes.+ engine = await connectEngine({ probeOnly: findCliCommand(command)?.startup === 'observational' || (command === 'jobs' && args[0] === 'supervisor' && args[1] === 'status'), oneShotRead: command === 'recall' && !args.includes('--watch') });} catch (serveConnectError) {if (command === 'jobs' && args[0] === 'child-readiness') {const { writeChildReadinessFailure } = await import('../core/minions/child-readiness.ts');@@ -2752,7 +2757,7 @@ async function dispatchReadOnlyCommand(engine: BrainEngine, command: string, arg// re-exported) so cli.ts's own connectEngine() call sites bind it locally.import { buildGatewayConfig } from '../core/ai/build-gateway-config.ts';export { buildGatewayConfig };-import { connectEngineForServe, noBrainError, type EngineConnectHooks, type EngineConnectOptions } from '../core/engine-connect.ts';+import { connectEngineForServe, noBrainError, takeStartupConfigSnapshot, type EngineConnectHooks, type EngineConnectOptions } from '../core/engine-connect.ts';/*** Which brain this process's engine targets. Set by connectEngine after braindiff --git a/src/core/config-snapshot.ts b/src/core/config-snapshot.tsindex 516a526334..8a36263e6f 100644--- a/src/core/config-snapshot.ts+++ b/src/core/config-snapshot.ts@@ -91,6 +91,8 @@ interface RequestSnapshot {engine: object;open: boolean;rows: Promise<Map<string, string> | null> | null;+ /** Other request-stable reads of the same engine (`requestSnapshotRead`), dropped with `rows`. */+ reads: Map<string, Promise<unknown>>;}const requestSnapshot = new AsyncLocalStorage<{ held: RequestSnapshot; live: boolean }>();@@ -119,8 +121,10 @@ export async function withRequestConfigSnapshot<T>(engine: BulkConfigReader, fn:* `withRequestConfigSnapshot` does, all from the same snapshot; `close()`* ends it, so later reads, and work a run left behind, read live.*/-export function openRequestConfigSnapshot(engine: BulkConfigReader): { run<T>(fn: () => Promise<T>): Promise<T>; close(): void } {- const held: RequestSnapshot = { engine, open: true, rows: null };+export interface RequestConfigSnapshot { run<T>(fn: () => Promise<T>): Promise<T>; close(): void }++export function openRequestConfigSnapshot(engine: BulkConfigReader): RequestConfigSnapshot {+ const held: RequestSnapshot = { engine, open: true, rows: null, reads: new Map() };return {run: fn => activeSnapshot(engine) ? fn() : requestSnapshot.run({ held, live: false }, fn),close: () => { held.open = false; },@@ -135,6 +139,7 @@ export async function withoutRequestConfigSnapshot<T>(fn: () => Promise<T>): Proreturn await requestSnapshot.run({ held: store.held, live: true }, fn);} finally {store.held.rows = null;+ store.held.reads.clear();}}@@ -176,3 +181,18 @@ export function noteRequestConfigWrite(engine: object, key: string, value: strinreturn next;});}++/**+ * `load()` once per request snapshot of `engine` under `key`, for a read that+ * stays fixed for one request the way the config table does (the sources+ * rows source resolution reads three ways, #7147). Undefined when no snapshot+ * applies; the caller then reads live. A write operation inside the request+ * drops it with the config rows, so a later read loads again.+ */+export function requestSnapshotRead<T>(engine: object, key: string, load: () => Promise<T>): Promise<T> | undefined {+ const held = activeSnapshot(engine);+ if (!held) return undefined;+ let read = held.reads.get(key) as Promise<T> | undefined;+ if (!read) held.reads.set(key, read = requestSnapshot.run({ held, live: true }, load));+ return read;+}diff --git a/src/core/db.ts b/src/core/db.tsindex 073e1687c6..2f8aac833a 100644--- a/src/core/db.ts+++ b/src/core/db.ts@@ -502,7 +502,7 @@ export async function connect(config: EngineConfig, hooks: PoolHealthHooks = {})const prepare = resolvePrepare(url);const timeouts = resolveSessionTimeouts();const opts: Record<string, unknown> = {- max: resolvePoolSize(),+ max: resolvePoolSize(config.pool_max),idle_timeout: 20,connect_timeout: resolveUrlConnectTimeout(url),// Explicit (matches the postgres.js implicit default; GBRAIN_POOL_MAX_LIFETIME_S overrides).diff --git a/src/core/engine-connect.ts b/src/core/engine-connect.tsindex b01d31fe89..e910445bda 100644--- a/src/core/engine-connect.ts+++ b/src/core/engine-connect.ts@@ -14,7 +14,7 @@ import type { BrainEngine } from './engine.ts';import { isThinClient, loadConfig, toEngineConfig, type GBrainConfig } from './config.ts';import { buildGatewayConfig } from './ai/build-gateway-config.ts';import { opError } from './ops/contract.ts';-import { withRequestConfigSnapshot } from './config-snapshot.ts';+import { openRequestConfigSnapshot, type RequestConfigSnapshot } from './config-snapshot.ts';/** The CLI-owned pieces the connect records into (cli.ts passes its dispatch context). */export interface EngineConnectHooks {@@ -33,6 +33,14 @@ export interface EngineConnectHooks {*/export const ONE_SHOT_READ_SHARED_BUFFERS = '32MB';+/**+ * Postgres connections for a process that runs one read operation and exits. Each connection a pool opens is a+ * TCP and auth handshake behind a remote pooler, and a cold `gbrain search` opened five with the default pool for+ * statements that mostly wait on one another. Two keep the read's parallel arms overlapping (the same wall clock as+ * ten at 40 ms RTT) for three fewer handshakes. GBRAIN_POOL_SIZE still sets it.+ */+export const ONE_SHOT_READ_POOL_MAX = 2;+export interface EngineConnectOptions {/** get_health, `upgrade --status`, doctor's migration_wedge check: never start or wait on migrations. */probeOnly?: boolean;@@ -41,7 +49,8 @@ export interface EngineConnectOptions {* config table once for the whole startup (each key read is a round trip behind a remote pooler, #7147;* pending migrations run outside the snapshot, reading and writing config live) and skips the* retired-marker cleanup, which only filesystem-guarded writes depend on. The CLI then builds the read's- * context and runs it under one more snapshot (`openRequestConfigSnapshot`), as MCP dispatch does.+ * context and runs it under the same snapshot (`takeStartupConfigSnapshot`): nothing between startup and the+ * read writes config, and a migration that ran drops the snapshot's rows, so the read takes fresh ones.*/oneShotRead?: boolean;}@@ -54,6 +63,16 @@ export function noBrainError() {});}+/** The config snapshot each one-shot read's startup ran under, until the CLI takes it for the read itself. */+const startupSnapshots = new WeakMap<BrainEngine, RequestConfigSnapshot>();++/** The snapshot a `oneShotRead` connect's startup read config through, handed over once; the taker closes it. */+export function takeStartupConfigSnapshot(engine: BrainEngine): RequestConfigSnapshot | undefined {+ const snapshot = startupSnapshots.get(engine);+ startupSnapshots.delete(engine);+ return snapshot;+}+export async function connectEngineForServe(hooks: EngineConnectHooks, opts: EngineConnectOptions = {}): Promise<BrainEngine> {const config = loadConfig();if (!config) throw noBrainError();@@ -65,9 +84,9 @@ export async function connectEngineForServe(hooks: EngineConnectHooks, opts: Engconst { configureGateway } = await import('./ai/gateway.ts');configureGateway(buildGatewayConfig(config));const { createEngine } = await import('./engine-factory.ts');- const engineConfig = opts.oneShotRead && config.engine === 'pglite'- ? { ...toEngineConfig(config), pglite_shared_buffers: ONE_SHOT_READ_SHARED_BUFFERS }- : toEngineConfig(config);+ const engineConfig = !opts.oneShotRead ? toEngineConfig(config)+ : config.engine === 'pglite' ? { ...toEngineConfig(config), pglite_shared_buffers: ONE_SHOT_READ_SHARED_BUFFERS }+ : { ...toEngineConfig(config), ...(process.env.GBRAIN_POOL_SIZE ? {} : { pool_max: ONE_SHOT_READ_POOL_MAX }) };const engine = await createEngine(engineConfig);hooks.SELECTED_CONFIG_BY_ENGINE.set(engine, config);const noRetry = process.argv.includes('--no-retry-connect') || process.env.GBRAIN_NO_RETRY_CONNECT === '1';@@ -76,10 +95,15 @@ export async function connectEngineForServe(hooks: EngineConnectHooks, opts: Engtry {// Engine graduation: a fenced target or a cut-over source refuses every connect but the run's own.await (await import('./persistence/graduation-custody.ts')).gateGraduationConnect(engine);- if (opts.probeOnly !== true) {- await (opts.oneShotRead ? withRequestConfigSnapshot(engine, () => hooks.completeStartup(engine, opts)) : hooks.completeStartup(engine, opts));+ if (opts.probeOnly !== true && opts.oneShotRead) {+ const snapshot = openRequestConfigSnapshot(engine);+ startupSnapshots.set(engine, snapshot);+ await snapshot.run(() => hooks.completeStartup(engine, opts));+ } else if (opts.probeOnly !== true) {+ await hooks.completeStartup(engine, opts);}} catch (e) {+ takeStartupConfigSnapshot(engine)?.close();await engine.disconnect().catch(() => {});throw e;}diff --git a/src/core/ops/pages.ts b/src/core/ops/pages.tsindex 741c9d2f17..d2222e2178 100644--- a/src/core/ops/pages.ts+++ b/src/core/ops/pages.ts@@ -1,4 +1,3 @@-import { pageMutationSource, submitPageMutation, validateMutationSlug } from '../persistence/page-mutations.ts';import { funnelPassThrough } from '../funnel.ts';import { suffixedSlugDryRun } from '../persistence/suffixed-slug.ts';import { AGENT_CONTENT_PARAMS, PAGE_MUTATION_PARAMS, CAPTURE_EVENT_PARAMS, CAPTURE_CLI_PROVENANCE_PARAMS, WRITE_WAIT_PARAM } from '../persistence/params.ts';@@ -48,6 +47,9 @@ import {validatePageSlug, pageNotFoundError,} from './context.ts';+/** The write path (journal, persistence service, sync), loaded by the mutating handlers only: a cold `gbrain get` never needs it (#7147). */+const pageMutations = () => import('../persistence/page-mutations.ts');+// --- Page CRUD ---/**@@ -352,6 +354,7 @@ const put_page: Operation = {mutating: true,scope: 'write',handler: async (ctx, p) => {+ const { pageMutationSource, submitPageMutation } = await pageMutations();const sourceId = pageMutationSource(ctx, p, 'put_page');if (ctx.dryRun) {if (typeof p.slug === 'string') {@@ -425,6 +428,7 @@ const delete_page: Operation = {mutating: true,scope: 'write',handler: async (ctx, p) => {+ const { pageMutationSource, submitPageMutation, validateMutationSlug } = await pageMutations();const sourceId = pageMutationSource(ctx, p, 'delete_page');assertPurgeParams(p, ctx.remote);if (ctx.dryRun) {@@ -454,6 +458,7 @@ const restore_page: Operation = {mutating: true,scope: 'write',handler: async (ctx, p) => {+ const { pageMutationSource, submitPageMutation, validateMutationSlug } = await pageMutations();const sourceId = pageMutationSource(ctx, p, 'restore_page');if (ctx.dryRun) {if (typeof p.slug === 'string') {@@ -694,6 +699,7 @@ const capture: Operation = {// hidden hint per the advisor pattern.cliHints: { name: 'capture', hidden: true },handler: async (ctx, p) => {+ const { pageMutationSource, submitPageMutation } = await pageMutations();pageMutationSource(ctx, p, 'capture');if (ctx.dryRun) {if (typeof p.slug === 'string') {diff --git a/src/core/persistence/graduation-custody.ts b/src/core/persistence/graduation-custody.tsindex 7003f9b737..ad7d00483d 100644--- a/src/core/persistence/graduation-custody.ts+++ b/src/core/persistence/graduation-custody.ts@@ -19,7 +19,7 @@ import { moveHeldPglite } from './maintenance.ts';import { withFilesystemPublication } from './filesystem-guard.ts';import { flushDirectory } from '../fs-durable.ts';import type { BrainEngine } from '../engine.ts';-import { GRADUATION_RUN_SETTING, graduationTablePresent, readGraduationRow } from './graduation-schema.ts';+import { GRADUATION_RUN_SETTING, graduationTablePresent, readGraduationConnectRow } from './graduation-schema.ts';import type { GraduationPathState, IntentMarker, ManifestState, TargetIdentity, Tombstone } from './engine-graduation.types.ts';@@ -334,7 +334,7 @@ function exemptRun(runId: string, env: NodeJS.ProcessEnv): boolean {* otherwise `graduation_interrupted`.*/export async function assertGraduationConnectAllowed(engine: BrainEngine, env: NodeJS.ProcessEnv = process.env): Promise<void> {- const row = await readGraduationRow(engine);+ const row = await readGraduationConnectRow(engine);if (!row || exemptRun(row.run_id, env)) return;if (row.role === 'target') {if (row.state === 'authoritative') return;diff --git a/src/core/persistence/graduation-schema.ts b/src/core/persistence/graduation-schema.tsindex 3e193d1a23..f0f99659c1 100644--- a/src/core/persistence/graduation-schema.ts+++ b/src/core/persistence/graduation-schema.ts@@ -118,6 +118,30 @@ export async function readGraduationRow(engine: BrainEngine, opts: { forUpdate?:};}+/**+ * The connect gate's read of the custody row in one statement (#7147): every CLI call pays this read before its+ * work, so it reads the row directly and treats only an undefined table (42P01, a brain before the migration) as "no+ * row" instead of probing for the table first. Outside a transaction only: a failed statement would abort one.+ */+export async function readGraduationConnectRow(engine: BrainEngine): Promise<Pick<GraduationRow, 'role' | 'run_id' | 'state' | 'source_data_dir'> | null> {+ let row: Record<string, unknown> | undefined;+ try {+ [row] = await engine.executeRaw<Record<string, unknown>>(+ `SELECT role, run_id::text AS run_id, state, source_data_dir FROM persistence_graduation WHERE singleton = 1`);+ } catch (error) {+ if ((error as { code?: unknown } | null)?.code === '42P01') return null;+ throw error;+ }+ tablePresent.add(rootEngine(engine));+ if (!row) return null;+ return {+ role: row.role as GraduationRow['role'],+ run_id: String(row.run_id),+ state: row.state as GraduationRow['state'],+ source_data_dir: (row.source_data_dir as string | null) ?? null,+ };+}+/** Run `fn` in one transaction that carries the run's identity, so the fence admits its writes. */export async function withGraduationRun<T>(engine: BrainEngine, runId: string, fn: (tx: BrainEngine) => Promise<T>): Promise<T> {return engine.transaction(async tx => {diff --git a/src/core/postgres-engine/keyword-statement-timeout.ts b/src/core/postgres-engine/keyword-statement-timeout.tsindex b15b5ed1ca..c92c20c55f 100644--- a/src/core/postgres-engine/keyword-statement-timeout.ts+++ b/src/core/postgres-engine/keyword-statement-timeout.ts@@ -22,6 +22,8 @@** Postgres only: PGLite runs these statements with no statement timeout.*/+import { requestConfigValue, type BulkConfigReader } from '../config-snapshot.ts';+export const KEYWORD_STATEMENT_TIMEOUT_KEY = 'search.keyword_statement_timeout_ms';export const KEYWORD_STATEMENT_TIMEOUT_DEFAULT_MS = 8000;export const KEYWORD_STATEMENT_TIMEOUT_MIN_MS = 1000;@@ -58,15 +60,19 @@ export const KEYWORD_STATEMENT_TIMEOUT_CONFIG_SQL = `SELECT value FROM config WH/*** The `statement_timeout` setting value (`<ms>ms`) for one engine connection:- * the file plane's value when set, else the DB plane's. A config table that- * cannot be read yet (a fresh brain before its schema) yields the default.+ * the file plane's value when set, else the DB plane's (from the request's+ * config snapshot when one is open, #7147). A config table that cannot be read+ * yet (a fresh brain before its schema) yields the default.*/export async function loadKeywordStatementTimeout(- reader: { executeRaw<T>(sql: string): Promise<T[]> },+ reader: { executeRaw<T>(sql: string): Promise<T[]> } & BulkConfigReader,fileValue: unknown,): Promise<string> {const fileMs = keywordStatementTimeoutMs(fileValue);if (fileMs !== undefined) return `${fileMs}ms`;- const rows = await reader.executeRaw<{ value: string }>(KEYWORD_STATEMENT_TIMEOUT_CONFIG_SQL).catch(() => []);- return `${resolveKeywordStatementTimeoutMs(undefined, rows[0]?.value)}ms`;+ const snapshotValue = await requestConfigValue(reader, KEYWORD_STATEMENT_TIMEOUT_KEY);+ const dbValue = snapshotValue !== undefined+ ? snapshotValue+ : (await reader.executeRaw<{ value: string }>(KEYWORD_STATEMENT_TIMEOUT_CONFIG_SQL).catch(() => []))[0]?.value;+ return `${resolveKeywordStatementTimeoutMs(undefined, dbValue)}ms`;}diff --git a/src/core/schema-pack/bundled.ts b/src/core/schema-pack/bundled.tsindex 1baa63c837..76b5ff4e81 100644--- a/src/core/schema-pack/bundled.ts+++ b/src/core/schema-pack/bundled.ts@@ -20,6 +20,11 @@ export const BUNDLED_PACK_NAMES = [export type BundledPackName = typeof BUNDLED_PACK_NAMES[number];+/** A pack name that is safe to join under the packs directory (mutate.ts and the active-pack loader share it). */+export function isValidPackName(name: string): boolean {+ return name.length > 0 && name.length <= 128 && /^[a-z0-9][a-z0-9._-]*$/.test(name);+}+export function isBundledPackName(name: string): name is BundledPackName {return (BUNDLED_PACK_NAMES as readonly string[]).includes(name);}diff --git a/src/core/schema-pack/load-active.ts b/src/core/schema-pack/load-active.tsindex 8e51850bca..cdcb81f542 100644--- a/src/core/schema-pack/load-active.ts+++ b/src/core/schema-pack/load-active.ts@@ -37,8 +37,7 @@ import {type ResolutionInput,type ResolutionResult,} from './registry.ts';-import { isBundledPackName } from './bundled.ts';-import { isValidPackName } from './mutate.ts';+import { isBundledPackName, isValidPackName } from './bundled.ts';import { bundledPackPath } from './bundled-assets.ts';/**diff --git a/src/core/schema-pack/mutate.ts b/src/core/schema-pack/mutate.tsindex 322aebe281..528ecbed99 100644--- a/src/core/schema-pack/mutate.ts+++ b/src/core/schema-pack/mutate.ts@@ -66,7 +66,7 @@ import { invalidateQueryCache } from './query-cache-invalidator.ts';import { logMutationFailure, logMutationSuccess, type MutationActor, type MutationOp } from './mutate-audit.ts';import { runFilePlaneLintRules } from './lint-rules.ts';import { withPackLock, type PackLockOpts } from './pack-lock.ts';-import { BUNDLED_PACK_NAMES as BUNDLED_PACK_NAME_LIST } from './bundled.ts';+import { BUNDLED_PACK_NAMES as BUNDLED_PACK_NAME_LIST, isValidPackName } from './bundled.ts';import type { BrainEngine } from '../engine.ts';export type PackFileFormat = 'json' | 'yaml';@@ -144,9 +144,7 @@ export interface MutateOpts extends PackLockOpts {* never validated names — so packs like 'my_pack' / 'notes.v2' exist legally* and refusing them here would permanently brick their mutation/lint.*/-export function isValidPackName(name: string): boolean {- return name.length > 0 && name.length <= 128 && /^[a-z0-9][a-z0-9._-]*$/.test(name);-}+export { isValidPackName };/*** Locate a user-mutable pack file. Bundled packs (gbrain-base,diff --git a/src/core/search/projection-statistics.ts b/src/core/search/projection-statistics.tsindex 6d2deb8e75..771096d620 100644--- a/src/core/search/projection-statistics.ts+++ b/src/core/search/projection-statistics.ts@@ -12,14 +12,16 @@ ANALYZE pages(text_projection_revision, knowledge_revision);type ProjectionStatisticsState = 'collected' | 'undefined' | 'uninspectable' | 'uncollected';-async function readProjectionStatistics(engine: Pick<BrainEngine, 'executeRaw'>): Promise<ProjectionStatisticsState> {- const rows = await engine.executeRaw<{- expression: string;- correct_table: boolean;- sampled_rows: number;- can_inspect: boolean;- collected: boolean;- }>(`SELECT pg_get_expr(e.stxexprs, e.stxrelid) AS expression,+interface ProjectionStatisticsRow {+ expression: string | null;+ correct_table: boolean | null;+ sampled_rows: number | null;+ can_inspect: boolean | null;+ collected: boolean | null;+}++/** The projection statistics' definition and collection state; `$${n}` binds PROJECTION_STATISTICS_NAME. */+const projectionStatisticsSql = (n: number) => `SELECT pg_get_expr(e.stxexprs, e.stxrelid) AS expression,e.stxrelid = 'pages'::regclass AS correct_table,p.reltuples AS sampled_rows,has_table_privilege(p.oid, 'SELECT') AND NOT row_security_active(p.oid) AS can_inspect,@@ -29,8 +31,14 @@ async function readProjectionStatistics(engine: Pick<BrainEngine, 'executeRaw'>)ON x.statistics_schemaname = (SELECT nspname FROM pg_namespace WHERE oid = e.stxnamespace)AND x.statistics_name = e.stxnameAND x.expr = pg_get_expr(e.stxexprs, e.stxrelid)- WHERE p.oid = 'pages'::regclass AND e.stxname = $1`, [PROJECTION_STATISTICS_NAME]);- const state = rows[0];+ WHERE p.oid = 'pages'::regclass AND e.stxname = $${n}`;++async function readProjectionStatistics(engine: Pick<BrainEngine, 'executeRaw'>): Promise<ProjectionStatisticsState> {+ const rows = await engine.executeRaw<ProjectionStatisticsRow>(projectionStatisticsSql(1), [PROJECTION_STATISTICS_NAME]);+ return projectionStatisticsState(rows[0]);+}++function projectionStatisticsState(state: ProjectionStatisticsRow | undefined): ProjectionStatisticsState {if (!state || !state.correct_table || state.expression !== '(text_projection_revision = knowledge_revision)') return 'undefined';if (!state.can_inspect) return 'uninspectable';if (Number(state.sampled_rows) < 0 || (Number(state.sampled_rows) > 0 && !state.collected)) return 'uncollected';@@ -177,6 +185,15 @@ const MISSING_SEARCH_STATISTICS_SQL = `SELECT r.tablename || '.' || r.attname ASAND NOT EXISTS (SELECT 1 FROM pg_stats s WHERE s.schemaname = current_schema() AND s.tablename = r.tablename AND s.attname = r.attname)ORDER BY r.position`;+/**+ * The three reads behind `missingSearchStatistics` in one statement (#7147: each is a round trip, and the search guard+ * runs it on every cold CLI search): the missing columns in order, pages' sampled rows, and the projection statistics'+ * state ($3), which only counts when pages holds SEARCH_STATISTICS_MIN_ROWS rows.+ */+const SEARCH_STATISTICS_STATE_SQL = `SELECT ARRAY(${MISSING_SEARCH_STATISTICS_SQL}) AS missing,+ (SELECT reltuples::float8 FROM pg_class WHERE oid = 'pages'::regclass) AS pages_rows, projection.*+ FROM (SELECT 1) AS one LEFT JOIN LATERAL (${projectionStatisticsSql(3)} LIMIT 1) AS projection ON true`;+/*** Postgres: the planner statistics search needs that are absent, as `table.column` (plus PROJECTION_STATISTICS_NAME* when the projection statistics are not collected on such a table). Empty when every one exists, the tables hold fewer@@ -189,10 +206,10 @@ const MISSING_SEARCH_STATISTICS_SQL = `SELECT r.tablename || '.' || r.attname ASexport async function missingSearchStatistics(engine: Pick<BrainEngine, 'executeRaw' | 'kind'>): Promise<string[]> {if (engine.kind !== 'postgres') return [];const pairs = Object.entries(SEARCH_STATISTICS_COLUMNS).flatMap(([table, columns]) => columns.map(column => [table, column] as const));- const rows = await engine.executeRaw<{ col: string }>(MISSING_SEARCH_STATISTICS_SQL, [pairs.map(p => p[0]), pairs.map(p => p[1])]);- const missing = rows.map(row => row.col);- const [pages] = await engine.executeRaw<{ reltuples: number }>(`SELECT reltuples::float8 AS reltuples FROM pg_class WHERE oid = 'pages'::regclass`);- if (Number(pages?.reltuples ?? -1) >= SEARCH_STATISTICS_MIN_ROWS && await readProjectionStatistics(engine) === 'uncollected') missing.push(PROJECTION_STATISTICS_NAME);+ const [state] = await engine.executeRaw<ProjectionStatisticsRow & { missing: string[] | null; pages_rows: number | null }>(+ SEARCH_STATISTICS_STATE_SQL, [pairs.map(p => p[0]), pairs.map(p => p[1]), PROJECTION_STATISTICS_NAME]);+ const missing = [...(state?.missing ?? [])];+ if (Number(state?.pages_rows ?? -1) >= SEARCH_STATISTICS_MIN_ROWS && projectionStatisticsState(state) === 'uncollected') missing.push(PROJECTION_STATISTICS_NAME);return missing;}diff --git a/src/core/source-resolver.ts b/src/core/source-resolver.tsindex b3b5c2a880..cfb5d0ec83 100644--- a/src/core/source-resolver.ts+++ b/src/core/source-resolver.ts@@ -16,6 +16,7 @@import { readFileSync, lstatSync, type Stats } from 'fs';import { join, dirname, resolve } from 'path';import type { BrainEngine } from './engine.ts';+import { requestSnapshotRead } from './config-snapshot.ts';import type { ExplicitReadBinding } from './ops/contract.ts';import { isSourceFederated, parseSourceConfig } from './sources-load.ts';import { SOURCE_ID_RE, isValidSourceId, ALL_SOURCES } from './source-id.ts';@@ -302,6 +303,9 @@ export function resolveSourceIdEngineFree(async function listRegisteredLocalPathSources(engine: BrainEngine,): Promise<Array<{ id: string; local_path: string; archived?: boolean }>> {+ const pending = requestSourceRows(engine);+ const request = pending && await pending;+ if (request) return request.filter(row => row.local_path !== null).map(({ id, local_path, archived }) => ({ id, local_path: local_path!, archived }));try {return await engine.executeRaw<{ id: string; local_path: string; archived?: boolean }>(`SELECT id, local_path, archived FROM sources WHERE local_path IS NOT NULL`,@@ -313,21 +317,39 @@ async function listRegisteredLocalPathSources(}}+/**+ * Every source row in one statement, once per request config snapshot (#7147): a CLI read or an MCP request resolves+ * its source through tier 4, tier 5.5 and the federated set, three reads of a table that does not change under one+ * read. Undefined without an open snapshot (no await, so a live read keeps its timing) and null on a brain older than+ * the `archived` column; the callers then read live.+ */+function requestSourceRows(+ engine: BrainEngine,+): Promise<Array<{ id: string; local_path: string | null; archived: boolean; config: unknown }> | null> | undefined {+ return requestSnapshotRead(engine, 'sources', () => engine.executeRaw<{ id: string; local_path: string | null; archived: boolean; config: unknown }>(+ `SELECT id, local_path, archived, config FROM sources ORDER BY id`,+ ).catch(() => null));+}+async function pickSoleNonDefaultSource(engine: BrainEngine,opts: { quiet?: boolean } = {},): Promise<string | null> {// archived column was added in v34 (v0.26.5). Older brains may not have// it — fall back to the un-archived query in that case via try/catch.- let rows: Array<{ id: string }>;- try {- rows = await engine.executeRaw<{ id: string }>(- `SELECT id FROM sources WHERE local_path IS NOT NULL AND id != 'default' AND archived = false`,- );- } catch {- rows = await engine.executeRaw<{ id: string }>(- `SELECT id FROM sources WHERE local_path IS NOT NULL AND id != 'default'`,- );+ const pending = requestSourceRows(engine);+ const request = pending && await pending;+ let rows: Array<{ id: string }> = request ? request.filter(row => row.local_path !== null && row.id !== 'default' && row.archived === false) : [];+ if (!request) {+ try {+ rows = await engine.executeRaw<{ id: string }>(+ `SELECT id FROM sources WHERE local_path IS NOT NULL AND id != 'default' AND archived = false`,+ );+ } catch {+ rows = await engine.executeRaw<{ id: string }>(+ `SELECT id FROM sources WHERE local_path IS NOT NULL AND id != 'default'`,+ );+ }}if (rows.length !== 1) return null;// #3070 emptiness guard: fire only when 'default' holds no active pages.@@ -936,6 +958,9 @@ export async function explicitReadBinding(}async function liveSourceRows(engine: BrainEngine): Promise<Array<{ id: string; config: unknown; archived?: boolean }>> {+ const pending = requestSourceRows(engine);+ const request = pending && await pending;+ if (request) return request.filter(row => row.archived === false).map(({ id, config, archived }) => ({ id, config, archived }));try {return await engine.executeRaw<{ id: string; config: unknown; archived?: boolean }>(`SELECT id, config, archived FROM sources WHERE archived = false ORDER BY id`,diff --git a/src/core/types.ts b/src/core/types.tsindex 7ccf11683d..b3e0f03235 100644--- a/src/core/types.ts+++ b/src/core/types.ts@@ -2309,6 +2309,8 @@ export interface EngineConfig {keyword_statement_timeout_ms?: number;/** PGLite `shared_buffers` for this open (e.g. '32MB'); unset keeps the data directory's setting. */pglite_shared_buffers?: string;+ /** Postgres: connections the module pool may open (a one-shot read: 2); unset keeps GBRAIN_POOL_SIZE or the default. */+ pool_max?: number;}// Errorsdiff --git a/test/cold-read-folded-statements.test.ts b/test/cold-read-folded-statements.test.tsnew file mode 100644index 0000000000..f3863edf6a--- /dev/null+++ b/test/cold-read-folded-statements.test.ts@@ -0,0 +1,129 @@+/**+ * #7147 follow-up: statements a cold one-shot read no longer pays.+ *+ * 1. Protects: inside one request snapshot, source resolution reads the sources+ * table once (tier 4, tier 5.5 and the federated set used to read it three+ * ways) and resolves exactly what live reads resolve; `requestSnapshotRead`+ * lives as long as its snapshot and a write operation drops it; the+ * graduation connect gate reads the custody row in one statement, treats a+ * missing table as no row and still throws every other error.+ * 2. Fails when: a resolver tier reads the sources table itself again inside a+ * snapshot, the memo outlives its snapshot or a write, the gate probes+ * to_regclass first again, or it swallows an error that is not 42P01.+ * 3. Existing coverage: test/config-request-snapshot.test.ts counts config+ * reads only; the source-resolver tests mock SQL text outside any snapshot;+ * test/graduation-state.test.ts checks the gate's refusals, not its+ * statements. test/e2e/cli-read-startup-round-trips.test.ts counts the same+ * statements through the CLI on Postgres.+ * 4. Seam: none. Statements are counted on the PGLite handle the engine uses.+ */+import { afterAll, beforeAll, beforeEach, describe, expect, test } from 'bun:test';+import { mkdirSync, mkdtempSync, rmSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { PGlite } from '@electric-sql/pglite';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import type { BrainEngine } from '../src/core/engine.ts';+import { requestSnapshotRead, withRequestConfigSnapshot, withoutRequestConfigSnapshot } from '../src/core/config-snapshot.ts';+import { localFederatedSourceIds, resolveSourceWithTier } from '../src/core/source-resolver.ts';+import { assertGraduationConnectAllowed } from '../src/core/persistence/graduation-custody.ts';+import { readGraduationConnectRow } from '../src/core/persistence/graduation-schema.ts';+import { resetPgliteState } from './helpers/reset-pglite.ts';+import { withEnv } from './helpers/with-env.ts';++let engine: PGLiteEngine;+let root: string;+const statements: string[] = [];++beforeAll(async () => {+ engine = new PGLiteEngine();+ await engine.connect({});+ await engine.initSchema();+ const db = engine.db as unknown as { query: (sql: string, ...rest: unknown[]) => Promise<unknown> };+ const query = db.query.bind(db);+ db.query = (sql: string, ...rest: unknown[]) => { statements.push(sql.replace(/\s+/g, ' ').trim()); return query(sql, ...rest); };+ root = mkdtempSync(join(tmpdir(), 'gbrain-cold-read-folded-'));+});++afterAll(async () => {+ await engine.disconnect();+ rmSync(root, { recursive: true, force: true });+});++beforeEach(async () => {+ await resetPgliteState(engine);+});++async function counted<T>(fn: () => Promise<T>): Promise<{ value: T; sql: string[] }> {+ statements.length = 0;+ const value = await fn();+ return { value, sql: [...statements] };+}++/** Whole-table reads of sources (an exact-id existence check is a separate statement). */+const sourceScans = (sql: string[]) => sql.filter(s => /\bFROM sources\b/.test(s) && !/\bid = \$1\b/.test(s));++describe('source resolution inside one request snapshot', () => {+ for (const shape of ['tier 4 (cwd inside a registered source)', 'tier 5.5 (one non-default source)'] as const) {+ test(`${shape}: one sources read, the same source and federated set as live reads`, async () => {+ const active = join(root, 'source-a-example');+ const archived = join(root, 'source-b-example');+ mkdirSync(active, { recursive: true });+ mkdirSync(archived, { recursive: true });+ await engine.executeRaw(`INSERT INTO sources (id, name, local_path, config, archived) VALUES+ ('source-a', 'source-a', $1, '{"federated": true}'::jsonb, false),+ ('source-b', 'source-b', $2, '{"federated": true}'::jsonb, true),+ ('source-c', 'source-c', NULL, '{"federated": true}'::jsonb, false)`, [active, archived]);+ const cwd = shape.startsWith('tier 4') ? active : root;+ const resolve = async () => {+ const resolved = await resolveSourceWithTier(engine, null, cwd);+ return { ...resolved, federated: await localFederatedSourceIds(engine, resolved.source_id, resolved.tier) };+ };+ await withEnv({ GBRAIN_SOURCE: undefined }, async () => {+ const live = await counted(resolve);+ const snapshot = await counted(() => withRequestConfigSnapshot(engine, resolve));+ expect(live.value.source_id).toBe('source-a');+ expect(snapshot.value).toEqual(live.value);+ expect(sourceScans(live.sql).length).toBeGreaterThan(1);+ expect(sourceScans(snapshot.sql)).toEqual(['SELECT id, local_path, archived, config FROM sources ORDER BY id']);+ });+ });+ }+});++describe('requestSnapshotRead', () => {+ test('loads once per snapshot, never outside one, and again after a write operation', async () => {+ let loads = 0;+ const load = async () => ++loads;+ expect(requestSnapshotRead(engine, 'k', load)).toBeUndefined();+ await withRequestConfigSnapshot(engine, async () => {+ expect(await requestSnapshotRead(engine, 'k', load)).toBe(1);+ expect(await requestSnapshotRead(engine, 'k', load)).toBe(1);+ expect(requestSnapshotRead({}, 'k', load)).toBeUndefined();+ await withoutRequestConfigSnapshot(async () => { expect(requestSnapshotRead(engine, 'k', load)).toBeUndefined(); });+ expect(await requestSnapshotRead(engine, 'k', load)).toBe(2);+ });+ expect(requestSnapshotRead(engine, 'k', load)).toBeUndefined();+ expect(loads).toBe(2);+ });+});++describe('the graduation connect gate', () => {+ test('reads the custody row in one statement, with no table probe', async () => {+ const { sql } = await counted(() => assertGraduationConnectAllowed(engine, {}));+ expect(sql).toEqual(['SELECT role, run_id::text AS run_id, state, source_data_dir FROM persistence_graduation WHERE singleton = 1']);+ });++ test('a database without the custody table has no row; any other failure still throws', async () => {+ const bare = new PGlite();+ try {+ const reader = { executeRaw: async (sql: string) => (await bare.query(sql)).rows } as unknown as BrainEngine;+ expect(await readGraduationConnectRow(reader)).toBeNull();+ await expect(assertGraduationConnectAllowed(reader, {})).resolves.toBeUndefined();+ const denied = { executeRaw: async () => { throw Object.assign(new Error('permission denied for table persistence_graduation'), { code: '42501' }); } } as unknown as BrainEngine;+ await expect(assertGraduationConnectAllowed(denied, {})).rejects.toThrow(/permission denied/);+ } finally {+ await bare.close();+ }+ });+});diff --git a/test/cold-read-module-graph.test.ts b/test/cold-read-module-graph.test.tsnew file mode 100644index 0000000000..ff1ccdc7c0--- /dev/null+++ b/test/cold-read-module-graph.test.ts@@ -0,0 +1,40 @@+/**+ * #7147 follow-up: what a cold read verb's module graph leaves out.+ *+ * 1. Protects: loading the module behind `gbrain get` (src/core/ops/pages.ts)+ * does not load the page write path (persistence/page-mutations.ts, which+ * pulled the journal, the persistence service, sync and PGLite WAL repair+ * into every cold read on a Postgres brain), and the active-pack loader+ * behind search and entity does not load the pack mutation module+ * (schema-pack/mutate.ts, the filesystem guard and the mutation audit).+ * 2. Fails when: ops/pages.ts imports page-mutations statically again, or+ * load-active.ts takes a helper from mutate.ts again.+ * 3. Existing coverage: test/cli-cold-start-registries.test.ts classifies+ * load-time registrations; nothing pinned the size of a read's graph.+ * 4. Seam: none. A child process loads each module into a fresh registry.+ */+import { describe, expect, test } from 'bun:test';+import { resolve } from 'node:path';++const REPO_ROOT = resolve(import.meta.dir, '..');++function loadedBy(entry: string): string[] {+ const script = `await import(${JSON.stringify(resolve(REPO_ROOT, entry))}); console.log(JSON.stringify(Object.keys(require.cache)));`;+ const r = Bun.spawnSync([process.execPath, '-e', script], { cwd: REPO_ROOT, stdout: 'pipe', stderr: 'pipe' });+ expect(r.exitCode, r.stderr.toString()).toBe(0);+ return (JSON.parse(r.stdout.toString().trim().split('\n').pop()!) as string[]).map(f => f.slice(REPO_ROOT.length + 1));+}++describe('a cold read loads no write path', () => {+ test('the get_page module loads neither the page write path nor PGLite WAL repair', () => {+ const loaded = loadedBy('src/core/ops/pages.ts');+ expect(loaded).toContain('src/core/ops/pages.ts');+ expect(loaded.filter(f => f === 'src/core/persistence/page-mutations.ts' || f === 'src/core/pglite-resetwal.ts' || f === 'src/core/persistence/journal.ts')).toEqual([]);+ }, 60_000);++ test('the active-pack loader does not load the pack mutation module', () => {+ const loaded = loadedBy('src/core/schema-pack/load-active.ts');+ expect(loaded).toContain('src/core/schema-pack/load-active.ts');+ expect(loaded.filter(f => f === 'src/core/schema-pack/mutate.ts' || f === 'src/core/schema-pack/mutate-audit.ts')).toEqual([]);+ }, 60_000);+});diff --git a/test/e2e/cli-read-startup-round-trips.test.ts b/test/e2e/cli-read-startup-round-trips.test.tsindex 29412e0cf3..0590ac1829 100644--- a/test/e2e/cli-read-startup-round-trips.test.ts+++ b/test/e2e/cli-read-startup-round-trips.test.ts@@ -12,7 +12,10 @@* once per database. Regressions it catches: a new per-key `getConfig` on the* read path outside a snapshot, the cleanup running for reads again, or the* banner printing on every call. Existing budget tests cover page writes and- * imports, not CLI read startup.+ * imports, not CLI read startup. The second half pins the statements the+ * follow-up folded: one config snapshot shared by startup and the read, one+ * sources read, the custody row without a table probe, the search-statistics+ * guard as one statement, and a two-connection pool for a one-shot read.*/import { afterAll, beforeAll, describe, expect, test } from 'bun:test';import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';@@ -74,4 +77,40 @@ describeDatabase('cold read verb startup through a transaction pooler (#7147)',expect(statements.filter(s => s.sql.includes('persistence_topology_changes'))).toEqual([]);}, 120_000);}++ /**+ * #7147 follow-up: each statement below was a round trip every cold read paid. A read shares one config snapshot+ * between startup and the operation (one bulk read, no per-key read), reads the sources table once for tier 4,+ * tier 5.5 and the federated set, reads the graduation custody row without a to_regclass probe first, and opens at+ * most two pooled connections. Each assertion fails on the base branch.+ */+ const sql = (s: StatementRecord) => s.sql.replace(/\s+/g, ' ').trim();+ const show = (rows: StatementRecord[]) => rows.map(sql).join('\n');+ for (const args of [['search', 'Acme'], ['query', 'who works at Acme'], ['get', 'people/alice-example'], ['entity', 'Alice Example'], ['recall', 'Alice Example']]) {+ test(`gbrain ${args[0]}: one config read, one sources read, one custody read, two connections`, async () => {+ const { statements } = await tracedRead(args, `folded-${args[0]}`);+ const config = configStatements(statements);+ expect(config.map(sql), show(config)).toEqual(['SELECT key, value FROM config']);+ const sources = statements.filter(s => /\bFROM\s+sources\b/i.test(s.sql) && !/\bJOIN\s+sources\b/i.test(s.sql) && /^\s*SELECT\s+id\b/i.test(s.sql));+ expect(sources.length, show(sources)).toBe(1);+ expect(statements.filter(s => s.sql.includes("to_regclass('persistence_graduation')"))).toEqual([]);+ expect(statements.filter(s => /\bFROM\s+persistence_graduation\b/.test(s.sql)).length).toBe(1);+ expect(statements.filter(s => s.sql.includes('persistence_topology_changes'))).toEqual([]);+ const connects = readSqlTrace(join(home, `folded-${args[0]}.ndjson`)).filter(s => s.kind === 'connect');+ expect(connects.length).toBeLessThanOrEqual(2);+ }, 120_000);+ }++ test('gbrain search: the search-statistics guard is one statement', async () => {+ const { statements } = await tracedRead(['search', 'Acme'], 'folded-statistics');+ const probes = statements.filter(s => s.sql.includes('pg_stats') || /reltuples::float8 AS reltuples FROM pg_class WHERE oid = 'pages'/.test(s.sql) || s.sql.includes('pg_statistic_ext'));+ expect(probes.length, show(probes)).toBe(1);+ }, 120_000);++ test('GBRAIN_POOL_SIZE still sizes a one-shot read pool', async () => {+ const trace = join(home, 'pool-size-1.ndjson');+ const r = await runCli(['search', 'Acme'], { home, cwd: home, timeoutMs: 90_000, env: { GBRAIN_SQL_TRACE: trace, GBRAIN_POOL_SIZE: '1' } });+ expect(r.exitCode, r.stderr).toBe(0);+ expect(readSqlTrace(trace).filter(s => s.kind === 'connect').length).toBe(1);+ }, 120_000);});diff --git a/test/engine-connect.test.ts b/test/engine-connect.test.tsindex 32c63e3831..21083bf6dd 100644--- a/test/engine-connect.test.ts+++ b/test/engine-connect.test.ts@@ -5,14 +5,17 @@* Protects: a config that vanished between a re-probe and the connect throws* the classified `no_brain` error (the CLI wrapper exits; a status daemon must* not), and an engine whose startup fails after the connect is disconnected,- * so the PGLite lock is free for the next attempt.+ * so the PGLite lock is free for the next attempt. A one-shot read keeps the+ * config snapshot its startup read through and hands it to the read once+ * (#7147: one bulk config read for the whole command).*/import { describe, test, expect } from 'bun:test';import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';import { tmpdir } from 'node:os';import { join } from 'node:path';-import { connectEngineForServe, ONE_SHOT_READ_SHARED_BUFFERS, type EngineConnectHooks, type EngineConnectOptions } from '../src/core/engine-connect.ts';+import { connectEngineForServe, ONE_SHOT_READ_SHARED_BUFFERS, takeStartupConfigSnapshot, type EngineConnectHooks, type EngineConnectOptions } from '../src/core/engine-connect.ts';import { runCall } from '../src/commands/call.ts';+import { withoutRequestConfigSnapshot } from '../src/core/config-snapshot.ts';import type { BrainEngine } from '../src/core/engine.ts';import type { GBrainConfig } from '../src/core/config.ts';import { withEnv } from './helpers/with-env.ts';@@ -77,6 +80,39 @@ describe('connectEngineForServe', () => {rmSync(home, { recursive: true, force: true });}}, 60_000);++ test('a one-shot read hands its startup config snapshot to the read, once; other connects keep none', async () => {+ const home = mkdtempSync(join(tmpdir(), 'gbrain-engine-connect-snapshot-'));+ try {+ mkdirSync(join(home, '.gbrain'), { recursive: true });+ writeFileSync(join(home, '.gbrain', 'config.json'), JSON.stringify({ engine: 'pglite', database_path: join(home, 'brain.pglite') }));+ await withEnv({ GBRAIN_HOME: home, DATABASE_URL: undefined, GBRAIN_DATABASE_URL: undefined }, async () => {+ const configReads: string[] = [];+ const startup = hooks(async e => {+ await withoutRequestConfigSnapshot(() => e.initSchema());+ const db = (e as unknown as { db: { query: (sql: string, ...rest: unknown[]) => Promise<unknown> } }).db;+ const query = db.query.bind(db);+ db.query = (sql: string, ...rest: unknown[]) => { if (/\bFROM config\b/i.test(sql)) configReads.push(sql); return query(sql, ...rest); };+ await e.getConfig('version');+ });+ const engine = await connectEngineForServe(startup, { oneShotRead: true });+ try {+ const snapshot = takeStartupConfigSnapshot(engine);+ expect(snapshot).toBeDefined();+ expect(takeStartupConfigSnapshot(engine)).toBeUndefined();+ await snapshot!.run(async () => { await engine.getConfig('version'); await engine.getConfig('embedding_model'); });+ snapshot!.close();+ expect(configReads.length).toBe(1);+ } finally {+ await engine.disconnect();+ }+ const plain = await connectEngineForServe(hooks());+ try { expect(takeStartupConfigSnapshot(plain)).toBeUndefined(); } finally { await plain.disconnect(); }+ });+ } finally {+ rmSync(home, { recursive: true, force: true });+ }+ }, 60_000);});describe('gbrain call sizes its connect by the operation scope', () => {