Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

Docs: free room under the TESTING.md, key-files and llms-full.txt size caps (GBRA-585) (#9599)

Garry Tanbf44f7e1ec3c
diff --git a/changelog.d/gbra585-docs-budget-room.md b/changelog.d/gbra585-docs-budget-room.md
new file mode 100644
index 0000000000..c26fc6cf97
--- /dev/null
+++ b/changelog.d/gbra585-docs-budget-room.md
@@ -0,0 +1,6 @@
+**Three agent-facing docs that had hit their size caps now have room again; no cap was raised.**
+
+### Documentation
+- The guard registry and self-test section moved out of `docs/TESTING.md` into its own page, `docs/ci-guards.md`. Links to its anchors, guard error messages and the guard baselines now point at the new page.
+- The key-files entries for page windows and large page writes moved from `core-services-2-continued.md` to a new `core-services-2-page-window.md`, and the entries from `src/core/sql-query.ts` through `src/core/utils.ts` moved from `core-utilities-2.md` to a new `core-utilities-2-continued.md`. Each full page links its continuation from its last line.
+- `llms-full.txt` links "Connect a hosted brain" (`docs/guides/hosted-harness-access.md`) instead of inlining it. It applies only once a brain runs on another machine, and the inlined AGENTS.md already routes those agents to it.
diff --git a/docs/TESTING.md b/docs/TESTING.md
index 727c57fc6f..40fe377f1b 100644
--- a/docs/TESTING.md
+++ b/docs/TESTING.md
@@ -831,236 +831,7 @@ Pinned by `test/scripts/build-schema.test.ts`; the end state by the E4 catalog g
### Guard registry and self-test
-The privacy and test-isolation guards use `scripts/lib/guard-candidates.sh` to
-scan fresh file contents in bounded batches before applying their detailed
-per-file rules. They do not cache passing results. Candidate scanner failures
-fail the guard, and matching files retain the same allowlists and diagnostics.
-
-`scripts/guards-manifest.tsv` is THE single registry of `scripts/check-*`
-guards, each classified `scanner` (greps/parses repo sources —
-must eventually carry fixtures), `buildfresh`, or `repostate` (build/freshness
-guards are exempt-with-reason, not fixture-tested).
-`scripts/guard-self-test.sh` (`bun run check:guard-self-test`, wired into
-`bun run verify`) proves every `selftest=yes` scanner CAN fail: it runs each
-one against known-bad (must exit non-zero) and known-good (must pass) fixture
-trees under `test/fixtures/guards/<guard>/{bad,good}/` via the
-`GBRAIN_GUARD_ROOT` env seam (guards run 4 at a time, `GUARD_SELF_TEST_JOBS`
-overrides; results print in manifest order; the whole pass must finish inside
-its 30 s budget), and enforces manifest completeness — a new
-`scripts/check-*` script that isn't registered in the manifest fails the
-build. A guard whose pattern rots into a permanently-green no-op fails CI
-instead of masquerading as coverage.
-
-A guard may carry extra known-bad trees named `bad-<variant>/`; each one must
-fail on its own. Refactor wave 1 adds one inside each split module location for
-every scanner that names a split file, listed in
-[`docs/designs/refactor-wave-1/path-consumers.md`](designs/refactor-wave-1/path-consumers.md).
-
-#### Layering guard
-
-`scripts/check-layering.ts` (`bun run check:layering`, in `bun run verify`)
-parses every file under `src/core/engine-sql/`, `src/core/schema-migrations/`
-and `src/core/persistence/` and fails on any import, type-only included, of an
-engine façade (`pglite-engine.ts`, `postgres-engine.ts`, `engine-factory.ts`)
-from engine-sql, of `src/core/migrate.ts` from schema-migrations, or of
-`src/core/ai/gateway.ts` from persistence. The first two directories are loaded
-by the engines and by `migrate.ts`, so an import back up is an ESM cycle that
-can fail with a temporal-dead-zone error at module load. Take the executor as a
-parameter and import types from `src/core/engine.ts`; migration helpers live in
-`schema-migrations/helpers.ts` and the `Migration` type in
-`schema-migrations/types.ts`; persistence embeds via `src/core/embedding.ts`.
-
-#### Write-path model guards
-
-`scripts/check-ai-sdk-importers.ts` (in `bun run verify`) fails when a file
-outside `scripts/ai-sdk-importers.allowlist` imports a provider SDK (`ai`,
-`@ai-sdk/*`, `@anthropic-ai/sdk`, `openai`) as a value, so every model call
-goes through `invokeAI`. Each mutating op has a write-inference class
-(`src/core/ops/write-inference.ts`). `test/write-path-zero-llm.serial.test.ts`
-asserts no generative call before commit and only attributed facts extraction
-after it; `test/write-path-no-egress.serial.test.ts`: keyless CLI writes open
-no connection. Helper: `test/helpers/ai-tripwire.ts`.
-
-#### Durable-flush guard
-
-`scripts/check-durable-flush.ts` (`bun run check:durable-flush`, in
-`bun run verify`) fails on an `fsyncSync(fd)` anywhere in `src/` outside
-`src/core/fs-durable.ts` whose `fd` is assigned from a read-only `openSync`
-(flags omitted, a flag string without `w`/`a`/`+`, or `O_RDONLY` without
-`O_WRONLY`/`O_RDWR`), file or directory, and on one whose flags it cannot
-read: Windows refuses fsync on a read-only handle and has no directory flush
-(EPERM; #5595, #5475). Fix: fsync the descriptor you wrote through before
-closing it (`fchmodSync(fd)` first for its final mode), or call `flushFile` /
-`flushDirectory(path, { bestEffort? })` from `src/core/fs-durable.ts`. A file
-that cannot migrate yet goes in the guard's `ALLOWLIST` with a reason; a stale
-entry fails. Fixtures: `test/fixtures/guards/check-durable-flush.ts/`. The
-#5595/#5475 regressions run natively on the `windows-latest` row of the
-test.yml `security-regressions` job; `test/helpers/win32-flush-semantics.ts`
-makes them discriminate on POSIX.
-
-#### Windows hidden-console guard
-
-`scripts/check-windows-hide.ts` (`bun run check:windows-hide`, in `verify`;
-#4992): a runtime `child_process` import or `Bun.spawn*` in `src/` outside
-`src/core/spawn.ts` fails unless the file is in `NOT_YET_MIGRATED` (a ratchet;
-a stale entry fails); `windowsHide: false` needs an `ALLOWLIST` reason.
-`test/windows-hidden-console.test.ts` is the native proof on the same row.
-
-#### Engine-sql ratchet
-
-`scripts/check-engine-sql-ratchet.ts` (`bun run check:engine-sql-ratchet`, in
-`bun run verify`) keeps each storage domain's SQL in one place,
-`src/core/engine-sql/<domain>.ts`, by stopping SQL from growing back into the
-engines. It parses `src/core/pglite-engine.ts`, `src/core/postgres-engine.ts`
-and every file under `src/core/pglite-engine/` and `src/core/postgres-engine/`,
-and names each class member (`PostgresEngine.getPage`), top-level function and
-top-level variable (`insertFact`). A unit is SQL-bearing when the literal text
-of a string, template, tagged template or `+` chain inside it has SQL
-structure: `SELECT ... FROM <x>`, `SELECT <fn>(`, `INSERT INTO <x>`,
-`UPDATE <x> [alias] SET`, `DELETE FROM <x>`, `WITH <x> AS (`,
-`CREATE|ALTER|DROP <object kind>`, `TRUNCATE <x>`, `SET LOCAL <x>`,
-`ON CONFLICT`, `WHERE ... ORDER BY|GROUP BY|LIMIT`, or a `$<n>::type` cast.
-Comments and identifiers never count. Keywords match in upper or lower case
-but never Title Case, and a lowercase match also needs a second SQL signal
-(`where`, `returning`, `$1`, `::`, `;`, `*` and similar), so "Select a file"
-or "could not delete from cache" is not SQL.
-
-`scripts/engine-sql-baseline.tsv` lists `migrated<TAB><domain>` rows (the
-domain's module must exist under `src/core/engine-sql/`) and
-`method<TAB><path><TAB><QualifiedName>` rows for the SQL-bearing members that
-remain. Rows only shrink. The guard fails on:
-
-- a new SQL-bearing member with no row: move the SQL into
- `src/core/engine-sql/<domain>.ts` and delegate, or mark the declaration (on
- its line or the line above) with `// engine-sql-ok: <reason>`; an empty
- reason fails;
-- a stale row, whose member is gone, no longer SQL-bearing or now marked:
- delete it, or run `bun scripts/check-engine-sql-ratchet.ts --prune`, which
- drops stale and duplicate rows and never adds one;
-- a duplicate or malformed row, or a `migrated` row with no module.
-
-When a domain moves, delete its members' rows and add its `migrated` row in
-the same commit.
-
-#### Page body readers
-
-`bun run check:page-body-readers` (in verify): every site that reads or writes
-a page body as one string has a row in `scripts/page-body-readers-baseline.tsv`
-naming what it must become; rows only shrink. Rules: the script's header.
-
-#### Engine-sql dynamic SQL
-
-`scripts/check-engine-sql-dynamic.ts` (`bun run check:engine-sql-dynamic`, in
-`bun run verify`) parses every file under `src/core/engine-sql/` except
-`fragment.ts`, the renderer, which writes `$n` and splices trusted text by
-design. In engine-sql every value reaches SQL as a bound parameter through
-`sqlFragment`, and only constant text is spliced. Trusted text is a string
-literal; a `const` in the same file initialized with trusted text or an
-`as const` object or array literal (members and element accesses included); a
-`CONSTANT_ALLOWLIST` name (`ENRICH_ORDER_SQL`); a call to a `VETTED_BUILDERS`
-entry (`pageReadFilter`, `buildRecencyComponentSql`,
-`privatePagesFilterFragment`, `currentCodeEdgeFilter`, `buildCJKKeywordSql`,
-`currentTextProjectionFilter`); a template or `+` chain whose parts are all
-trusted or are numbers the same function checked earlier with
-`Number.isFinite(<same expression>)`; or a conditional whose branches are both
-trusted. Both registries live in the script with a one-line reason each. The
-guard fails on:
-
-- `trustedSql(arg)` with an arg that is not trusted text: bind the value with
- `${value}` in `sqlFragment` instead, or register a new builder with its
- reason after review;
-- an untagged template or `+` concatenation, passed directly or through a
- local variable (`let` appends included) as the SQL of `.query(`,
- `.unsafe(`, `.executeRaw(` or `executeRawJsonb(`, with an untrusted part:
- compose with `sqlFragment` and run it with `executor.run(fragment)`;
-- a literal `$<digit>`, or a `$` right before a substitution, in a composed
- string (a template with substitutions, any `sqlFragment` template, any `+`
- operand): let `renderFragment` number the parameters. A static string passed
- as-is may carry `$1`;
-- an expanded list, `IN (` right before a substitution or a non-literal `+`
- operand: bind the array as one parameter, `= ANY(${ids}::text[])`, so
- prepared-statement caches stay bounded.
-
-Fixtures: `test/fixtures/guards/check-engine-sql-dynamic.ts/`; forms are
-driven in `test/scripts/engine-sql-dynamic.test.ts`.
-
-#### Engine-sql brands
-
-`scripts/check-engine-sql-brands.ts` (`bun run check:engine-sql-brands`, in
-`bun run verify`) keeps the RLS read brands in
-`src/core/engine-sql/brands.ts` unforgeable. `ScopedRead` records a read that
-ran inside `withScopedReadTransaction` on master and `LegacyUnscopedRead` one
-that ran unscoped on the pool (EO4), so a forged brand silently changes how a
-read is scoped. The guard fails on:
-
-- a brand key (any `__obtainVia...` name) in a text file under `src/`,
- `test/` or `scripts/` other than `brands.ts` and the guard's own script,
- fixtures and test: get a branded executor from `scopedRead(tx)` inside
- `withScopedReadTransaction`, or from `unscopedExecutor(executor, '<reason>')`;
-- in `src/`, a cast onto `ScopedRead` or `LegacyUnscopedRead` outside
- `brands.ts`, an `as unknown as T` where `T` names `SqlExecutor`,
- `ScopedRead` or `LegacyUnscopedRead`, or a double cast passed straight to
- `scopedRead(` or `unscopedExecutor(`. Driver-handle casts such as
- `tx as unknown as PgConn` in `dialect-postgres.ts` pass;
-- an import of `unscopedExecutor` or `LegacyUnscopedRead` (value, type,
- alias, re-export or `import('...').X` type) from outside engine-sql, the two
- engine façades, doctor (`src/commands/doctor.ts`, `src/commands/doctor/**`,
- `src/core/doctor*`), maintenance (`src/core/maintenance/**`), admin
- (`src/commands/admin*.ts`, `src/core/admin/**`), migrations
- (`src/core/migrate.ts`, `src/core/schema-migrations/**`,
- `src/commands/migrations/**`) and `test/`; an import of `scopedRead` from
- outside engine-sql, the façades and `test/`; or a namespace, dynamic or
- `require` import of `brands.ts` from outside that `scopedRead` list.
- `src/core/ops/**`, the MCP-facing surface, is always denied. Take the
- branded executor from the engine façade instead.
-
-The allowlists live in the script.
-
-#### Retired-phrase guard
-
-`scripts/check-retired-phrases.sh` (`bun run check:retired-phrases`, in
-`bun run verify`, under a second) keeps the instructions agents follow
-literally in step with refactor wave 1. It greps `CLAUDE.md`, `AGENTS.md`,
-`CONTRIBUTING.md`, `docs/` and `skills/` for the contributor-workflow phrases
-the wave retired: the old migrations-array wording and appending to it, the
-rule that every engine method is written twice, the CLI switch-case step, the
-migrate.ts region policy, and schema text listed as a hand-synced pair of
-`schema.sql` and the PGLite schema module. The patterns and the current
-instruction for each live in the script's `RETIRED` table. Historical records
-may quote them and are exempt: `docs/designs/`, `docs/test-audit/`,
-`docs/incidents/`, `docs/plans/`, `docs/proposals/`, `docs/research/`,
-`docs/issues/`, `docs/superpowers/`, `docs/migrations/`, `skills/migrations/`
-and the wave 1 porting kit (`docs/architecture/wave-1-*`); `CHANGELOG.md` is
-not scanned. Each hit prints `FAIL: <file:line> retired phrase "<match>"`,
-then `Why:`, `Fix:` with the current instruction, and `See:`. The fix is to
-rewrite the sentence to the current workflow, never to exempt the file. To
-retire another phrase, add a row to `RETIRED`. Fixtures:
-`test/fixtures/guards/check-retired-phrases.sh/` (one `bad-<location>` tree per
-scanned location); every pattern and the exemptions are driven in
-`test/scripts/check-retired-phrases.test.ts`.
-
-#### Bash 3.2 parse guard
-
-macOS ships GNU bash 3.2.57 as `/bin/bash`, and its parser rejects shapes
-bash 5 accepts. The one that broke every Mac (#5810) is a heredoc inside
-`$(...)` whose body holds an odd quote. `scripts/check-bash32.sh`
-(`bun run check:bash32`) runs the real 3.2 parser, `bash -n`, over every
-tracked `*.sh` except the guard fixtures under `test/fixtures/guards/`. It
-uses the first parser available: `GBRAIN_BASH32=<path>` (a bash 3.x binary),
-`/bin/bash` when it is bash 3.x (stock macOS), or the digest-pinned `bash:3.2`
-Docker image (`GBRAIN_BASH32=docker` forces the image). With none it prints
-one skip line and exits 0; `GBRAIN_TEST_BASH32_REQUIRE=1` makes that exit 2. Each
-failure prints `FAIL: <file:line>`, `Why:` (macOS `/bin/bash` is 3.2), `Fix:`
-(read heredoc text with `IFS= read -r -d '' VAR <<'EOF' || true`) and `See:`.
-To reproduce one file by hand:
-`docker run --rm -v "$PWD":/w -w /w bash:3.2 bash -n <file>`.
-
-The guard checks parsing only. It is not in `bun run verify`, which must not
-need Docker. The `test.yml` verify job runs it with `GBRAIN_TEST_BASH32_REQUIRE=1`
-together with `test/scripts/check-bash32.test.ts`, whose real-parser cases
-feed it the `test/fixtures/guards/check-bash32.sh/{bad,good}` trees. The
-macOS 26 job runs it under `/bin/bash` and then runs `bun run verify` there,
-which covers bash-4 runtime features the parser cannot see.
+The guard registry, its self-test and every source guard it runs (layering, write-path models, durable flush, Windows hidden console, engine-sql, page body readers, retired phrases, bash 3.2) are in [CI guards](ci-guards.md).
### Placeholder assertions
diff --git a/docs/architecture/key-files/core-persistence-continued.md b/docs/architecture/key-files/core-persistence-continued.md
index 401733e0cf..27cc72c2ea 100644
--- a/docs/architecture/key-files/core-persistence-continued.md
+++ b/docs/architecture/key-files/core-persistence-continued.md
@@ -44,5 +44,5 @@ The #6188 fence check and fence repair live in [fence repair](core-fence-repair.
- `src/core/links-fence.ts` + `src/core/links-fence-projection.ts` — the `## Links` fence (G5): the markdown form of authored (manual) edges, `<!--- gbrain:links:begin -->` / `end` around `| to | type | source | valid_from | valid_until | context |`, one row per (to, type, source), source defaulting to `manual`; a reconciliation-managed provenance (`MANAGED_LINK_SOURCES`, exported here and re-exported by `ops/links.ts`), a bad date or a duplicate key is a skipped row with a warning. `parseLinksFence` (state `absent` / `parsed` / `malformed`), the deterministic `renderLinksFence` (rows sorted by key), `upsertLinksFenceRow` (omitted context and dates keep the stored ones; identical row = unchanged body), `removeLinksFenceRows` (leaves an empty fence), `replaceOrInsertLinksFence` (a `## Links` section at the end of compiled_truth, above an unclosed code block) and `maskLinksFence`, which `extractBodyLinks` applies so the fence cells are never also extracted as markdown, wikilink or bare-slug edges. A rewrite of a fence that parses with warnings throws `LinksFenceRewriteRefusal`. Cells use `escapeFenceCell` plus the same one-level marker encoding for `gbrain:links:*`. `projectLinksFence(tx, page, rows)` reconciles only what the page's fence owns: edges with origin_page_id = the page and origin_field `links_fence` (deleted, context-updated, inserted by key) and `manual` transitions with origin_page_id = the page, compared per row by (to, type, link_source, kind, date) and written with the row's source in `link_source`, then refreshes the touched relationships; a row whose target is not a live page in the source yields no edge. `linksFenceProjectionRows` returns null for an absent or malformed fence, so such a body changes no edge (an absent fence retires nothing, as for facts; unlike facts no held generation is recorded, so after a hand deletion of the whole section the database keeps edges git no longer has until `remove_link` or the G3 indexer), and drops rows typed with a link type the active pack does not declare. Callers: `prepareCanonicalProjections` (every projected page publication, quarantined and segmented-unread bodies excepted), `prepareAutomaticLinks` (put_page auto-links and the managed links maintenance, so `extract --stale` restores a lost fence edge) and `persistence/manual-links.ts`. Database-only manual edges (origin_field NULL) are never touched by any of them. Pinned by `test/links-fence.test.ts` and `test/managed-links-fence.test.ts`.
- `src/core/persistence/source-lifecycle.ts` retire batches with `topology-transaction.ts` (#7702/#8905) — every `topologyTransaction` runs under `statement_timeout=5s` and `lock_timeout=1s` and maps SQLSTATE 57014/55P03 to `write_pending`, so a managed `remove` or `purge` first deletes the source's pages in batches of `SOURCE_RETIRE_BATCH_PAGES` (500; about 110 ms per batch with chunks and links on Postgres) under the native locks `withTopologyLocks` holds, each batch its own `topologyTransaction`. A batch re-checks the final transaction's preconditions (admin state, `lockTopologyRows`, the incarnation read before the locks, archived or `EXPIRED_ARCHIVE_SQL` due, no prior receipt other than this request's own admission, no `oauth_clients` reference, `assertTopologyRequestsSettled` from `topology-locks.ts`, `lockTopologyPrincipal`, and on the first batch `admitTopologyRetire` from `topology-receipts.ts`, which checks the receipt quotas at the largest receipt and records the admission) and, when one would refuse or replay, stops without deleting so the final transaction reports it, or throws that refusal before deleting; a batch that fails `write_pending` is retried at half the size (floor 1), so heavy pages still fit the bound; a refusal after some batches committed says how many pages that run already deleted; a dry run, a missing checkout, an unconfirmed operation and an admission-hooked call never batch. The final transaction's `sources` delete runs `removedSourceScrubCtes` (#9068: the source's retrieval and volunteer rows, and its slugs in eval candidates), so a run that stops after some batches leaves those rows until a retry commits. Each batch deletes inside `withCoordinatedWrite` with local-CLI attribution (the `pages` guard needs the source in `gbrain.write_sources`; only the final `sources` delete sets `gbrain.topology_change`). Committed batches are durable: a retry (same or new request_id) resumes, and the receipt's `pages_deleted` counts the pages deleted by the run that commits it. #8984: the first batch's transaction records the admission, a `persistence_topology_changes` row in state `recovering` with no recovery record, bound to the source incarnation it deletes from (`isRetireAdmission`); `recordTopologyChange` settles it `committed`, and a remove or purge that deletes that incarnation under another request, or any other lifecycle operation that commits a change to it (archive, restore, rebind, claim), settles it `failed` (`supersedeTopologyRetires`, which skips only the caller's own principal and request_id pair). A retry of the request_id against another incarnation (the source was removed and re-added) refuses `source_retire_superseded`, settles the admission `failed` and deletes nothing, also when a since-replaced CLI registration (another principal) admitted that request_id for a remove or purge, since idempotency is per principal; an admission bound to the current incarnation still resumes under the new registration; deactivation and graduation list an unsettled admission as a blocker that names its request_id and asks the user whether to finish it or keep what is left; an automatic expired-archive purge's admission (`expired_only` in its outcome) is left to the next automatic run with `needsUser: false`, and `sources writer status --json` lists the stopped and superseded requests (`topology_requests`). Tests: `test/source-retire-batched.test.ts` (PGLite), `test/e2e/source-retire-batched-postgres.test.ts` (60,000 pages), `test/source-retire-incarnation.test.ts` and `test/e2e/source-retire-incarnation-postgres.test.ts`.
- `src/core/persistence/label-edit.ts` + `src/core/repair/label-write.ts` (GST-2468) — the label-only page write of operator repairs (`repair visibility`, `repair private-labels`). `label-edit.ts`: `LABEL_KEYS` (visibility, access, confidentiality), `readLabelEdit` validates a `managed_maintenance_page` intent's `label_edit` (`set` plain-word values, `remove` keys), `spliceLabelLines` removes, replaces or appends label lines in a file's frontmatter text and declines (null) a block or multi-line value, a duplicate key or a file with no frontmatter block. `page-prepare.ts` `labelEditFile` uses it in `compareFileTarget` when the file matches the snapshot: the edited file (or its edited head over the write's body, for a fence row) must read back as the file the write would render, else the write refuses `label_edit_refused` (GST-2603; reason `file_differs` with the differing keys in `detail`, or `label_line`); the file is never re-rendered under a label edit. GST-2603: `labelEditFit` (also used by `writeLabelFile`) aligns the file with the stored page before comparing, and `align-stored.ts` `keepStoredOnlyStamps` (used by `alignWithStored` and sync's `keepStoredStamps`) keeps the stamps gbrain holds only in the database (the `validate: false` grandfather stamp and a stored `legacy_type` whose aligned type is the page's), so they never count as a difference; `fileSnapshotDifference` lists the differing keys (frontmatter keys, title, type, tags, body, timeline) for the raw and inferred reading and `fileMatchesSnapshot` is its empty case. `label-write.ts` `labelFileRefusal` is a write-free preflight (managed: `prepareFileTarget`, with the drift's keys from `error.localEdit` and `gbrain sources reconcile <id> <slug> --preview` as next step; unmanaged: `ownerRepairFile`, next step `gbrain sync --source <id>`; repo-less or no file: null); `visibility.ts` holds refusing pages in the preview (`details.held`, `residuals.held_file_drift` / `held_label_edit`, outside the hash and approved set) and `labelWrite` / `private-labels.ts` `prepareWrite` throw only its `label_edit_refused` before writing. `repair/core.ts` counts `label_edit_refused` as declined and never toward `item_failures_systemic`. Test: `test/label-repair-derived-stamps-gst2603.test.ts`. `label-write.ts`: `writeLabelPage` publishes through the maintenance door with `keep_trust` and the edit on a managed brain, else `importAtRevision` (maintenance transaction, page lock, `withTrustKeep`); `filesInCheckout` names the unmanaged pages whose checkout file would undo a database-only write; for those, `writeLabelFile` applies `labelEditFile` to the file's own bytes (it must still hold the page, `ownerRepairFile`), imports it under `withTrustKeep` and writes it back through `writePageThrough` (`fileText`, preimage checked) in one transaction; drift or a file edited mid-write throws `source_changed`, and a file it cannot write (`sync.write_through` off, `url_clone`, an unresolvable target, a write error) returns a held `file_backed` outcome with the import rolled back. `repair visibility` calls it directly; `private-labels` still holds those pages as `file_backed`; `repair/origin-carry.ts` (GST-2689) uses `writeLabelFile`, `importAtRevision` and `publishMaintenancePages` the same way to label derived pages private before their origin row goes, and parks the origin when one returns held or throws. GST-2476: `label-edit.ts` also edits `readable_by` (`READERS_KEY`, `EDIT_KEYS`; `set` takes a plain-word list, rendered `readable_by: [a, b]`), and `writeLabelPage` takes a maintenance `batch` (then `publishMaintenancePages([page], {batch})`). `src/core/repair/readers.ts` is `repair visibility --readers`: `checkedReaders` (members exist and are enabled, groups exist, else `access_member_invalid`; a list that leaves out the owner refuses unless `allowWithoutOwner`), `planReaders` (named pages or a `--slugs-file`, up to `READERS_MAX_PAGES`, approved set bound to each page's live readers) `readersWrite` (re-checks a page, holds a segmented one, renders the edit) and `applyReaders` (phase `READERS_PHASE`, one label-only write); `visibility.ts` `applyBatch` admits a managed source's run of readers items together through `publishMaintenancePages` under the run's batch (Postgres publishes them in groups of up to 8), so the Git effect commits a window's ready files together; `readersGitCounts` reports the run's Git effect states. `visibility.ts` `labelWrite` holds a managed page with no canonical file outside `storage.db_only` as `canonical_file_missing`. GST-2519, labels under `storage.db_only`: `sync-classify.ts` `gitVerdict` keeps a strict source's `db_ahead` path when `state.dbOnly` (a label repair on a page whose file Git still tracks there survives later syncs; a commit that moved still imports); `sync-prepare.ts` imports a db_only file over a live page through `withStoredLabels(text, stored, incoming)`, which adds each `EDIT_KEYS` label the row holds and the file does not state, so an import there never widens (a label the file states applies, wider included); `page-prepare.ts` `prepareFileTarget` lets a label repair of a strict page stamped `git_ignored`, with no recorded file and a path Git still ignores, write the database only instead of holding it `canonical_file_missing`. Tests: `test/db-only-labels-gst2519.test.ts`, `test/sync-classify-strict-g3.test.ts`.
+- `src/core/persistence/page-edit.ts` — `edit_page` (#5616): splits the canonical serialization into editable text and protected takes/facts segments whose remote view matches get_page's sanitized `content` byte for byte; `applyPageEdits` applies ordered exact-once replacements inside editable text only (typed `edit_no_match`/`edit_ambiguous_match`/`edit_protected_span`/`edit_invalid`), so canonical fences never move; `editDiff` caps the caller-view diff at 8 KB; `boundedUnifiedDiff` keeps its LCS table under `EDIT_PAGE_DIFF_CELL_BUDGET` (4M cells) by diffing only the window between common leading/trailing lines, and a window still over budget becomes one coarse hunk flagged `diff_coarse` (pinned by `test/large-pages/edit-diff-bounded.test.ts`). Called at submission (`page-mutations.ts`, before admission; skipped for a segmented page) and again on the locked snapshot in `page-prepare.ts`, which gives edit_page put_page's revision-bound `editing` timeline semantics. Pinned by `test/edit-page.test.ts`. `within` and the segmented path: [large page writes](core-services-2-page-window.md#large-page-writes).
- `src/core/repair/open-facts.ts` + `src/commands/repair-open-facts.ts` (#8194) — `gbrain repair open-facts`, the operator-only, explicit-only, preview-bound repair that opens facts stamped private before `facts.default_visibility world`. `openFactsReasonSql` is the one exclusion expression the preview, its reason counts and the locked apply share (expired, superseded, member page, withdrawn or purged at any visibility, any pending trust proposal or a rejected or undone widening, a holding, provenance or entity page that is `derivationPrivateSql` on any row with the slug, deleted or not, a missing or quarantined holding or provenance page, an unresolved provenance slug); `openFactClassSql` classes facts `fenced`, `unfenced` or `unpaged:<lane>` (no page or a transcript lane; opened only when named). Keyset windows (`--after`, `--limit`), the approved set binds the window and an apply refuses `preview_changed` when a new fact became eligible inside it. Writes lock the named pages FOR SHARE and each fact FOR UPDATE before the recheck: database-only rows change in place (managed: the `managed_maintenance_open_fact_visibility` intent, `prepareOpenFactsIntent`; else a maintenance transaction); fenced rows go through the label-only door with the cell set by `strikeFenceRow` (managed: `publishMaintenancePage` with `openFacts`, whose keep_trust publication `openFactsPublication` runs under `persistence/context.ts` `withOpenFacts`, the only setter of `gbrain.write_open_facts`, which `openedFactRowSql` reads in `trust/fence-guard.ts`, `generations/adapters/fact-rows.ts` and `canonical-projections.ts` so the row moves to world in place; unmanaged: the import, then the in-place update). The CLI keeps the write-ahead ledger (`repairLedger` in `repair-private-labels.ts`) and `--undo` re-privates what it opened. Refuses remote callers (`trusted_cli_required`) and `GBRAIN_ENFORCED_MEMBER` (`member_mode_refused`). Test: `test/repair-open-facts-8194.test.ts` (PGLite and Postgres, with a two-session race).
-- `src/core/persistence/page-edit.ts` — `edit_page` (#5616): splits the canonical serialization into editable text and protected takes/facts segments whose remote view matches get_page's sanitized `content` byte for byte; `applyPageEdits` applies ordered exact-once replacements inside editable text only (typed `edit_no_match`/`edit_ambiguous_match`/`edit_protected_span`/`edit_invalid`), so canonical fences never move; `editDiff` caps the caller-view diff at 8 KB; `boundedUnifiedDiff` keeps its LCS table under `EDIT_PAGE_DIFF_CELL_BUDGET` (4M cells) by diffing only the window between common leading/trailing lines, and a window still over budget becomes one coarse hunk flagged `diff_coarse` (pinned by `test/large-pages/edit-diff-bounded.test.ts`). Called at submission (`page-mutations.ts`, before admission; skipped for a segmented page) and again on the locked snapshot in `page-prepare.ts`, which gives edit_page put_page's revision-bound `editing` timeline semantics. Pinned by `test/edit-page.test.ts`. `within` and the segmented path: [large page writes](core-services-2-continued.md#large-page-writes).
diff --git a/docs/architecture/key-files/core-services-2-continued.md b/docs/architecture/key-files/core-services-2-continued.md
index c67dddb6fb..cc92eb106b 100644
--- a/docs/architecture/key-files/core-services-2-continued.md
+++ b/docs/architecture/key-files/core-services-2-continued.md
@@ -24,7 +24,7 @@ The page-state concurrency foundation under `src/core/page-state/` and the share
- `src/core/progressive-batch/` — shared ramp-up + cost-cap + verification primitive (trial 10 → ramp 100 → ramp 500 → full, with verification at each stage), with verifier+policy injection (callers describe HOW TO MEASURE SUCCESS, not WHEN TO WAIT FOR CTRL-C). Modules: `types.ts` (Stage, StageVerdict, AbortReason, discriminated `Verifier` union `OutputCountVerifier | IdempotentMutationVerifier | NoopVerifier`, Policy, StageReport), `orchestrator.ts` (`runProgressiveBatch(items, verifier, policy, runner)` — reads `getCurrentBudgetTracker()` ahead of `Policy.maxCostUsd` fail-closed; null both ways triggers `abort_cost_cap reason='no_budget_safety_net'`), `audit.ts` (ISO-week JSONL at `~/.gbrain/audit/progressive-batch-YYYY-Www.jsonl` via the shared `audit-writer` primitive), `stage-report.ts` (ASCII formatter for the default `Policy.onStageReport`). Env knobs: `GBRAIN_PROGRESSIVE_BATCH_DISABLED=1`, `GBRAIN_PROGRESSIVE_BATCH_AUTO=1` (skip Ctrl-C grace), `GBRAIN_PROGRESSIVE_BATCH_STAGES=10,100,500`. Sites that "jump straight to full" stay that way by default; ramp is opt-in per-site via `Policy.interactiveAbortMs > 0`. Pinned by `test/progressive-batch/orchestrator.test.ts` (35 cases, every verdict path).
-- `src/core/page-body/page-shape.ts` — Wave B PR 1 (spec 1.5): segmented page bodies are unreachable as strings. `guardSegmentedBody` (called by `rowToPage` for a row with `body_storage = 'segmented'`, so by every snapshot and `getPage` read) replaces `compiled_truth` / `timeline` with enumerable getters and setters that throw `page_body_segmented`, so property reads, spread, `JSON.stringify`, `structuredClone` and assignment all fail loud instead of seeing an empty body. `isSegmentedPage`, `assertInlineBody(page, site)` (explicit refusal where a writer would otherwise act before a getter fires, e.g. SQL-only writers; a read's `page_body_segmented` refusal fixes with `get_page body: 'auto'`; for a write that fix changes nothing, so `asSegmentedWriteRefusal` (called by MCP dispatch on a mutating op) swaps it for a report-only step naming `edit_page`, `append_page`, `add_tag` and `remove_tag`, and `readsPageInPieces(fix)` tells the two apart, which remember's unattributed-save fix in `persistence/verb-errors.ts` also uses), `pageBodyBytes(page)` (`body_bytes` for segmented pages), `pageBodySegmentedError` and `pageBodyOverCeilingError` (the refusal of a fence or timeline write through the put path on a page over 24 MiB; `wholeBodySnapshot` in `persistence/segmented-apply.ts` reads a page within it back as strings and refuses above it: semantic timeline writes, `takes-prepare.ts`, `facts-prepare.ts`, `reconcile-state.ts`, `gbrain core`). Tag writes on a segmented page never read the body: `prepareSegmentedTagMutation` (`persistence/page-prepare.ts`) flips them in metadata over the live manifest (`test/large-pages/segmented-semantic-writes.test.ts`). `bodyUnread(page)` says a segmented page's body was not read back as strings (over the single-string ceiling, see `materializedPage`); such a body was written by the streamed import, which holds fenced files, so `fenceBody(page)` reads it as empty for the fence merges and `withoutBody(page)` copies the page's other fields for a render whose body comes from the incoming write (a shrunk file rewrites such a page: `test/large-pages/segmented-shrink-below-ceiling.test.ts`). `Page` stays one shape (`body_storage?`, `body_bytes?`); the static half is `scripts/check-page-body-readers.ts` with `scripts/page-body-readers-baseline.tsv` (docs/TESTING.md#page-body-readers). Pinned by `test/large-pages/segmented-body-unreachable.test.ts`.
+- `src/core/page-body/page-shape.ts` — Wave B PR 1 (spec 1.5): segmented page bodies are unreachable as strings. `guardSegmentedBody` (called by `rowToPage` for a row with `body_storage = 'segmented'`, so by every snapshot and `getPage` read) replaces `compiled_truth` / `timeline` with enumerable getters and setters that throw `page_body_segmented`, so property reads, spread, `JSON.stringify`, `structuredClone` and assignment all fail loud instead of seeing an empty body. `isSegmentedPage`, `assertInlineBody(page, site)` (explicit refusal where a writer would otherwise act before a getter fires, e.g. SQL-only writers; a read's `page_body_segmented` refusal fixes with `get_page body: 'auto'`; for a write that fix changes nothing, so `asSegmentedWriteRefusal` (called by MCP dispatch on a mutating op) swaps it for a report-only step naming `edit_page`, `append_page`, `add_tag` and `remove_tag`, and `readsPageInPieces(fix)` tells the two apart, which remember's unattributed-save fix in `persistence/verb-errors.ts` also uses), `pageBodyBytes(page)` (`body_bytes` for segmented pages), `pageBodySegmentedError` and `pageBodyOverCeilingError` (the refusal of a fence or timeline write through the put path on a page over 24 MiB; `wholeBodySnapshot` in `persistence/segmented-apply.ts` reads a page within it back as strings and refuses above it: semantic timeline writes, `takes-prepare.ts`, `facts-prepare.ts`, `reconcile-state.ts`, `gbrain core`). Tag writes on a segmented page never read the body: `prepareSegmentedTagMutation` (`persistence/page-prepare.ts`) flips them in metadata over the live manifest (`test/large-pages/segmented-semantic-writes.test.ts`). `bodyUnread(page)` says a segmented page's body was not read back as strings (over the single-string ceiling, see `materializedPage`); such a body was written by the streamed import, which holds fenced files, so `fenceBody(page)` reads it as empty for the fence merges and `withoutBody(page)` copies the page's other fields for a render whose body comes from the incoming write (a shrunk file rewrites such a page: `test/large-pages/segmented-shrink-below-ceiling.test.ts`). `Page` stays one shape (`body_storage?`, `body_bytes?`); the static half is `scripts/check-page-body-readers.ts` with `scripts/page-body-readers-baseline.tsv` (docs/ci-guards.md#page-body-readers). Pinned by `test/large-pages/segmented-body-unreachable.test.ts`.
- `src/core/page-body/limits.ts` — Wave B size classes, ceilings, retention numbers and config keys in one place. `readPageBodyPolicy` is the single question every write asks: `segmented` is the effective `pages.segmented_storage` (unset means `SEGMENTED_STORAGE_DEFAULT`, `on`; `off` or an unrecognized value is off; held off while `segmentedWriterBlockers` finds a recent writer that blocks, and an unreadable gate counts as blocked), `maxBytes` the engine ceiling (256 MiB Postgres, 128 MiB PGLite, lowered by `pages.max_bytes`) while on and `PAGE_MAX_BYTES` while off. Config is read per call; only the writer gate is cached (`SEGMENTED_WRITER_GATE_TTL_MS`, `_resetSegmentedWriterGateForTests`). `chooseBodyStorage` applies the 1 MiB / 512 KiB hysteresis. The writer gate (`segmentedGateWriters` in `persistence/writer-versions.ts`) reads seven days of admitted requests in any state, committed publications, `ingest_log` rows and, on Postgres, `persistence_consumers` heartbeats; a row blocks when its version is below `SEGMENTED_WRITER_FLOOR` (`page-body/writer-floor.ts`: the `since` of the BEHAVIOR_CHANGES row with id `segmented_switch_on`, this build's VERSION while it is `TBD`, so the merge-slot stamp edits only that row) or unparsable, or when it lacks the segment-reader mark (migration v254: `admitter_segment_reader`, `consumer_segment_reader`, `persistence_consumers.segment_reader`, `ingest_log.writer_segment_reader`), because releases 0.60.252.0-0.60.262.0 have no segment readers and a version string cannot tell them apart. Not seen: an older binary's unmanaged single-page write, a run that dies before it logs, and read-only or export use. `pageRecoveryBytes` is the default `persistence.limits.worktree_recovery_bytes` (read by `persistence/limits.ts` `readJournalLimits` in its one config statement): twice the larger of the body the configured switch admits (`segmentedMaxBytes`, or `PAGE_MAX_BYTES` while off) and the largest page stored in segments (deleted pages included; one probe of `pages_segmented_body_bytes_idx`, v260, or the engine ceiling while that index is not valid, so a limit read never scans `pages`) plus `RECOVERY_FILE_HEADROOM_BYTES` per copy, never below 256 MiB, because a restore reserves its file twice; it ignores the writer gate, and turning the switch off or lowering `pages.max_bytes` never strands a stored page. `readPageBodyPolicy` treats a failed read of the switch or `pages.max_bytes` as off, never as unset. Doctor `segmented_storage` reports a hold left only by this host's pre-upgrade writes as information with its clear time when, for each, this build has since made the same kind of write (role and principal, `segmentedGateEvidence` `first_seen`) after it; otherwise (a cron or npx gbrain on the host) it warns. `PROJECTION_LOCK_HOLD_BYTES` (512 KiB of segments, an occurrence larger than that alone) and `PROJECTION_RETIRE_MAX_ROWS` (2,500 rows) bound what one projection transaction inserts or deletes while it holds the page's key lock (`page-body/ingest.ts` `stageOccurrenceChunks`, `page-body/projection.ts` `retireStaleChunks`), about a tenth of the 1 s `lock_timeout` a write to the page, or a source-exclusive write anywhere on the source (the lock's `page_write_guards` insert key-share locks the source row), waits under in its publication, so a write never waits out its bound behind a background build (`test/large-pages/projection-lock-hold.test.ts`). Tests: `test/large-pages/segmented-switch.test.ts`, `test/large-pages/recovery-budget-default.test.ts`, `test/large-pages/recovery-budget-ceiling.slow.test.ts`.
- `src/core/ops/page-upload.ts` — the five upload-session operations (`begin_page_upload`, `upload_page_part`, `get_page_upload`, `commit_page_upload`, `abort_page_upload`; write scope, client slug-fence allowlist). Begin routes the source and slug as put_page does, runs put_page's grant and visibility authorization before reading the page (a private page answers as a missing one), and reserves the declared bytes; every later call re-checks the binding (creating principal, write source inside the read scope, source incarnation, the page id or, for create, a still-absent slug) and answers any mismatch with an `upload_not_found` identical to an unknown id; abort needs only the creating principal, its source and the slug fences, so a session whose page or incarnation moved can still be freed. A refusal at commit (stale revision, sha mismatch) and a commit whose write ended without committing discard the session; only a write whose `body_ref` names the session is recorded as its commit, so a begin request_id another write already used attaches nothing. Commit claims the session with an atomic open-to-sealed `sealUpload` before hashing; a call that loses the claim, or finds a lapsed session another call already moved on (`settleLapse`), reads the session again and follows its real state (sealed or committing replays the commit, committed returns the first receipt), so `upload_expired` is answered only when this call expired it (`uploadCommitProbe` is the forced-race seam, `test/large-pages/upload-review.test.ts`). After the hash check commit submits an ordinary put_page carrying `body_ref` (`stagedBody`), so a second commit replays the first receipt; a replace re-checks `expected_revision` and the shrink guard. Append commits through `admitPageAppend` (persistence/page-append.ts) with the staged `body_ref`. Begin admits create and replace up to the page ceiling (`pages.max_bytes`, the engine ceiling by default) and an append up to PAGE_MAX_BYTES; over PAGE_MAX_BYTES a remote writer is refused `file_too_large` at begin where the write gate applies to an agent-written page.
- `src/core/persistence/page-upload.ts` — upload-session storage: `page_body_stagings` rows of kind `upload` and their raw `page_body_staging_parts`, `part_max_frame_bytes` from the transport's `ctx.inboundFrameBytes` (at most 4 MiB, minus a 4 KiB envelope), part UTF-8 and code-point checks, the staged-quota reservation (limits.ts `stagedCounterKeys`, recounted under the counter locks at begin) and its release on commit, abort or expiry (`transitionUploads` with `RELEASE_STAGED_CTE`, which deletes the parts in the same statement; the segment sweep expires lapsed sessions the same way). An open session expires past its idle or hard deadline, a sealed one only past its hard deadline, which sealing extends by one idle period; a lapsed session is never sealed, so the brain-wide sum at begin leaves out other principals' lapsed sessions; `expireIfLapsed` reports whether its update changed the row. A session takes at most `uploadPartLimit` parts (64 plus one per 64 KiB declared) unless the part completes it (`upload_too_many_parts`). `withStagedUpload` binds a put_page or append_page preparation to the sealed session and marks it committed in the publication transaction; `prepareStagedUpload` (from `preparePageMutation`) reads a body within PAGE_MAX_BYTES back as put_page content and hands a larger one to upload-streamed.ts. `stagedUploadWork` counts whole-body reads for the memory tests.
@@ -37,18 +37,5 @@ The page-state concurrency foundation under `src/core/page-state/` and the share
- `src/core/page-body/body-tiling.ts` (`untiledSegmentedPages`) + `schema.ts` (`liveTilingSql`, `untiledSql`) + `src/core/engine-sql/page-body.ts` — GST-1209: a live generation tiles its body when its manifest rows, as every reader selects them, cover `body_bytes` from byte 0 with no gap. `flipBodyGeneration` checks the generation it made live inside its transaction and refuses one that does not tile (`body_staging_expired`, detail reason `generation_incomplete`, nothing published). `setBodyStagingState` moves only a live staging (open, sealed, prepared): a move on to prepared or committed of a staging a fact purge aborted or a sweep expired (its staged rows deleted) refuses `body_staging_expired` instead of reviving it. `untiledSegmentedPages` lists live segmented pages of unarchived sources that do not tile (read-only, one aggregate per page), for doctor `segmented_tiling` (`src/commands/doctor/checks/segmented-tiling.ts`, BRAIN, host only, its own registry entry `segmentedTilingEntry` in `checks/graph-health.ts` so the wave checks' budget never hides it; the fix always names `--source`) and the repair (`survey` lists at most `PREVIEW_PAGE_LIMIT` pages and reports `truncated`). A sync hold naming `page_body_rows_unreadable` reads needs_human / repair and its `gitHoldFix` previews `gbrain repair segmented-tiling --source <id> --slug <slug>`.
- `src/core/repair/segmented-tiling.ts` — `gbrain repair segmented-tiling --source <id> [--slug <slug>]` (GST-1209), explicit-only, preview-bound, trusted local CLI on the owner host, `checks: ['segmented_tiling']`. The preview lists each untiled page with its file, HEAD's blob (oid, SHA-256, size) and sync hold under a hash; a page with no file, a file HEAD lacks or one over `pages.max_bytes`, a file another sync hold withholds (any but the unreadable-body `page_write_failed` one) or one `unreadPageImportScreen` (sync-screen.ts, the next sync's screen against the unread snapshot) refuses is listed held; a source with no Git checkout refuses `not_a_git_repo`. `--apply --expect` re-checks revision, generation and blob (`preview_changed`), then per page in one transaction under the key lock (coordinated maintenance on a managed brain) versions the damaged generation, stages the screened body after `preserveWithdrawnFenceRows` (purged claims stay out) through `prepareSegmentedBody` without reading the damaged body, flips with `applySegmentedBody` (title, type, frontmatter, tags and trust tier kept), clears the previewed hold, records the new revision as imported from the HEAD blob (`recordSyncImportProvenance`) when the file imports to the page's stored title, type, frontmatter and tags (so the next sync holds no `file_drift`), calls `requestGitHoldRetry` and writes an `op_checkpoints` receipt (`segmented-tiling-receipt`) and a `segmented-tiling` audit line. Tests: `test/large-pages/segmented-tiling-repair.test.ts`.
- `src/core/page-body/segment-facts.ts` + `segment-conversation.ts` — Wave B PR 2 lane 2e2 (spec 8, full-pass mode): the facts fence reconcile and conversation facts over a segmented body. `segmentedFactsFenceView` is `factsFenceView` (facts-fence.ts: each section's parsed fence, which sections hold one, and the #3625 timeline marker) read from the segments: one SQL query selects the live manifest rows that carry facts slots, a forced cut, or a begin/end marker (bytea `position`, nothing transferred), and `bodyBlocks`' `want` option reads only the runs holding them; the segmenter never cuts inside a fence, so a fence lies in one block (a longer one is a forced run, refused above `BLOCK_MAX_BYTES` with `page_body_segmented`), and joining one across blocks is a bounded fallback. `segmentedBodyMatchesFile` is `canonicalCacheState`'s stale-cache check for a segmented page: the canonical file streamed through `BodyScanner` against the stored regions, by length and SHA-256. `readSegmentedConversationInput` gives `readConversationInput` (conversation-parser/body.ts) the summary body through ranged reads: whole within `CONVERSATION_WINDOW_BYTES` (`PAGE_MAX_BYTES`), else the newest whole segments that fit (never starting inside a forced run) with the window's `fallbackDate` from its first segment's entry state; extract-conversation-facts parses that window, passes the date to the parse and the extractor, and writes a `tail_window` receipt (`window_rule: no_prior_facts`), but only on a page with no conversation facts: one that has any keeps them and is skipped (`skipped_too_large`, `window_rule: prior_facts_kept`), since the run clears every prior fact. Each loop counts its reads in `segmentedPassWork`. Consumers: `runExtractFacts` (`planFenceReconcile`, the stale-cache guard, the managed fence-facts request), the sweep's fence candidates (segmented pages with facts slots), `extract-conversation-facts`. Tests: `test/large-pages/segmented-facts-reconcile.test.ts`, `segmented-conversation-facts.test.ts`, `segmented-derived-linear.test.ts`.
-- `src/core/page-window/bounded-lead.ts` — leads, snippets and synopses read a bounded prefix, never the whole body: fan-out SQL selects `boundedBodyPrefixSql(alias)` (`left(coalesce(alias.compiled_truth, alias.truth_lead), 65536)`: a segmented page's NULL body falls back to its stored lead; the one COALESCE of body and lead the page body reader ratchet allows by name), `boundedRawPrefix` cuts a body at 64 KiB on a code point, and `overlaidBoundedRows` / `overlaidBoundedPrefix` replace a prefix holding a `gbrain:facts:begin` marker with the prefix of the withdrawal-overlaid body (one batched `readPageSnapshotsBatch` read; a page it no longer returns, or a failed read, gets an empty lead). A segmented page's row carries its stored `truth_lead`; when that lead holds a facts fence it is overlaid alone with the withdrawal ledger the snapshot read returns (`overlayCanonicalBodies`, then the same 64 KiB cut), never by reading segments. `pageLeadSource` gives getPage callers (exact-slug and alias snippets) a page's compiled truth, or a segmented page's `truth_lead` without touching its throwing body getters. `projectedLead` is that prefix through `boundedProjectedPrefix` (`document.ts`). Consumers: the exact-slug tier (`exact-lookup.ts`) and alias injection (`alias-hop.ts`) snippets, relational hydrate, the reflex pointer synopsis (`retrieval-reflex.ts` `safeSynopsis`: world-only reads take the projected prefix, the trusted entity-card widening the raw prefix through its own fence strip), the entity card's hit row and `entity names` leads, and think's anchor and window-floor rows (`think/gather.ts`: the raw overlaid prefix for the trusted local CLI, the projected prefix otherwise). Small pages render as before. Pinned by `test/bounded-lead.test.ts` and `test/large-pages/segmented-leads.test.ts`.
-- `src/core/page-window/document.ts` — the one read projection every remote window, outline and lead slices: `projectPageText` (fence overlay split, `sanitizeRemoteBody` + `credentialSafeProjection`, timeline after `TIMELINE_SEPARATOR`), `pageDocument` / `readPageDocument` (UTF-8 bytes + timeline byte offset, with the page's fence overlay), `chunkDocumentSpan` + `spanHoldsChunk` (a chunk's stored `projected_byte_*` span mapped into the document and verified), `boundedProjectedPrefix`, `locateChunksByStoredSpans` (byte spans to string offsets in one pass), `DEFAULT_INLINE_BODY_BYTES` (256 KB).
-- `src/core/page-window/window.ts` — byte/line window arithmetic on a UTF-8 buffer: windows snap to code points and line starts (`windowFrom`, `windowForLines`, `windowForBytes`, `windowAround`; a lone line longer than the window is cut on a code point as `forced_cut`), `pageOutline` (single pass: ATX headings outside code fences, or 64 KiB blocks for pages with fewer than two headings, with date ranges, paged by `from`/`limit`), and the opaque revision-bound cursor (`gpw1.`). `DocumentSlab` / `slabWindow` run the same arithmetic on a slice of a larger document and shift the result back to document coordinates.
-- `src/core/page-window/segmented.ts` — Wave B PR 2 (spec 7.2, 7.4): get_page over a segmented page in projected bytes, the same coordinates as an inline page. `SegmentedDocument` places units (segments from `projectedUnits` plus fixed text) by stored sums and reads only the units a window, line lookup or `around_chunk_id` touches (`slab` adds `EDGE` bytes so code-point and line snapping match the inline arithmetic). `segmentedReadDocument` is the read projection; `segmentedMarkdownDocument` the markdown view (`markdownHead`, then the projection for a remote caller, the overlaid stored body and `TIMELINE_SEPARATOR` for a trusted one). `page_view_digests` (migration v253) caches per page revision, view and audience the read view's line count and the markdown view's size and sha256, checked against the current total. `tailDigest` hashes the last `TAIL_BYTES` raw bytes of the last region, withheld from a remote caller when those rows hold a protected or facts region. `segmentedOutline` pages headings from stored metadata, reading at most `OUTLINE_READ_BYTES` of segments per page and carrying line counts forward between entries. `segmentedReadWork` (@internal) counts the units and segment bytes a read visits, for the read-cost bounds. `cli/page-render.ts` uses it for the local `gbrain get` stream (`streamSegmentedGet`); the thin client pages and verifies the markdown view (`printPagedPage`), and `--json` above `PAGE_MAX_BYTES` is refused on both paths. Pinned by `test/large-pages/segmented-get-page-parity.test.ts`, `read-cost.test.ts`, `remote-get-page-privacy.test.ts`, `segmented-get-cli.test.ts` and `segmented-get-over-ceiling.test.ts`.
-## Large page writes
-
-Writes that change part of a page in time proportional to the change (Wave B spec 6.1, 6.3): `append_page`, segmented `edit_page` and the splice engine both use. Tests: `test/large-pages/append-cost.test.ts`, `test/large-pages/append-concurrency.test.ts` and `test/large-pages/edit-segmented.test.ts`, PGLite and Postgres (helper `test/helpers/append-brain.ts`).
-
-- `src/core/page-body/splice.ts` + `tail-digest.ts` — byte-range splices of a segmented body. `spliceSegmentedBody` replaces stored byte ranges of the live generation (`BodyReplacement`) and stages the next one from the touched segments only: segmentation resumes at the last clean entry point before the first replaced byte and stops at the first old boundary whose entry state the new run reproduces, so later segments keep their bytes, text and chunks and only move (new manifest rows under the same occurrence; content_hash midstate recomputed). An append is an insertion at its region's end: it re-segments the old tail plus the text and moves nothing; an insertion at the truth/timeline boundary belongs to truth (`replacementRegion`), so exactly one row owns it. New segments equal to a replaced one keep its occurrence; the rest are chunked with vectors reused by chunk text. A change that flips a region's fence trust restages the whole body (`rescanned`). `splicePage` reads the page row a splice needs (generation, region sizes, cr tier, corpus generation, kind); `spliceWork` counts segments segmented, bytes read and manifest rows (the cost tests' work counters). `tail-digest.ts` is the append precondition's digest for inline pages, sha256 of a region's last min(4096, region bytes) raw stored bytes (`inlineTailDigest`; segmented pages use `page-window/segmented.ts` `tailDigest`); a tail holding facts or takes text is withheld from a remote caller, since a hash of hidden text is a guessing oracle. The cost test pins that a 10 KB append to a 4 MB and a 16 MB page segments only the tail plus the text, and a forced full-rewrite probe (`appendProbe.fullRewrite`) fails the bound.
-- `src/core/persistence/page-append.ts` — `append_page`: text added to the end of a region (`region` auto/truth/timeline, `separator` auto/none), idempotent by `request_id`. `admitPageAppend` (also the upload lane's `commit_page_upload` append entry, with a staged `body_ref`) journals the text or the reference, never the body; text is capped at `APPEND_TEXT_MAX_BYTES` (4 MiB), a facts or takes fence marker in it refuses `invalid_params` and a links fence marker `append_links_fence` (write links with `add_link`), and a missing or deleted page refuses `page_not_found`. `prepareAppendMutation` checks the optional preconditions on the locked snapshot (`expected_revision` gives `revision_changed`; `expected_tail_sha256` gives `tail_changed`, whose fix carries the current tail digest). A segmented page splices onto its region's tail through `prepareSegmentedSpliceMutation`, which segmented edit_page and append-mode upload commits share. It refuses a result over `pages.max_bytes` as a streamed import does (`file_too_large`, nothing written), and runs put_page's write gate over the new text only (title, frontmatter and the replacement bytes, O(text)): a flag verdict sets `content_flag` (`instruction_like`), records the page gate receipt and returns put_page's `gate` field; an allowed append never clears an existing flag, since the stored text was not re-read; it declines (null, whole-body path) for an always-loaded core page, an external_untrusted write the write gate scans whole, a change that creates or empties a region, or a file a withdrawal ledger rewrites. An inline page composes the new body on put_page's path, which promotes it past the segmented threshold. Chunks and embeddings of the appended text follow commit as for any segmented write. A remote append to the compiled truth records the bytes it added (`PreparedMutation.mentionRange`: stored truth offsets and their SHA-256, from the splice or, inline, the parsed appended bytes placed at the end of the stored truth after publication, so a Tier 1 fence normalization before them cannot shift the range) and queues a `links` effect carrying them (`data.range`, #7122; see `effect-links.ts`); timeline rows and fence projections of appended text wait for PR 4's incremental derivation. A file-backed segmented page's canonical file gains the appended bytes, its frontmatter rendered in stored key order as inline edit_page and append write-through render it.
-- `src/core/ops/page-append.ts` — the `append_page` operation (write scope, client slug-fence allowlist, `outputRedaction: 'no_stored_text'`): params `{slug, source_id?, text, request_id, expected_revision?, expected_tail_sha256?, region?, separator?}`, returns `{slug, revision, body_bytes, appended_bytes, chunks_new, size_state, receipt}`. get_page's `body: 'none'` returns `tail_sha256` and `tail_region` for inline and segmented pages, and its window reads return `edit_target: {revision, byte_start, byte_end}` in stored coordinates (`ops/get-page-body.ts` `editTarget`), withheld from a remote caller when hidden text precedes the window end (`read-range.ts` `hiddenBefore`).
-
-Segmented edit_page (`persistence/page-edit.ts`, entry in [Core Persistence](core-persistence.md)): optional `within: {byte_start, byte_end}` (stored coordinates, as `edit_target` returns them; `parseEditWithin`, `edit_invalid`) limits matching to one range, and a range the page no longer holds refuses `revision_conflict`. A remote caller's `within` refuses `edit_invalid` (one refusal for every range and edit, before any match or fence check) when hidden text starts before `byte_end`: on a segmented page the read projection's hidden units (`read-range.ts` `hiddenBefore`, the predicate `editTarget` withholds `edit_target` by), on an inline page a fence whose remote view differs from its stored text; such a range would measure the hidden text. A segmented page is never materialized: `prepareSegmentedEditMutation` (called first by `page-prepare.ts` `preparePageMutation`) finds each old_text by a streaming scan across segment boundaries (`locateSegmentedEdits`, with applyPageEdits' exactly-once, protected-span and remote-view rules; the scan keeps at most two matches per edit and refuses `edit_ambiguous_match` at the second, counted in `spliceWork.matches`) and splices the touched range; the receipt diff covers the touched range plus 2 KB of context, and only the first replacement past 256 KB (`diff_truncated`); its context never starts at or inside hidden facts or takes text, nor ends inside it, and its hunk lines count the caller's view (`viewNewlinesBefore`: row line counts plus, for a remote caller, each hidden run before the diff rendered as `sanitizeRemoteBody` renders it). With a withdrawal ledger that applies, the scan, the diff and those line counts read the page through its withdrawal overlay (`storedPieces` over `trustedSegments`, rows widened to whole fence blocks), on every path; a match into a block the overlay rewrote is never kept. A segmented page's remote edit view hides withdrawn rows as its remote windows do (`SEGMENTED_REMOTE_VIEW`, also on the whole-body path). A stored fence that does not compile refuses as applyPageEdits refuses it (typed `target_fence_malformed`, same location), at submission (`assertSegmentedEditFences`) and again at preparation: `scanCanonicalFences` runs over the stored fence text alone, each piece at its own line, so only segments holding fence text are read; with `within`, only the fences in the touched segments and those crossing into them. It declines to the whole-body path for an old_text naming the timeline sentinel or also found in the frontmatter head, or a miss without `within` on a page within the single-string ceiling.
-- `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 (a selector → window, setting aside body full/include_content/content_only beside it; else explicit body; include_content/content_only → full; the thin client and the local CLI → full; else auto). Several selectors read one window, `SELECTOR_ORDER` cursor > around_chunk_id > lines > bytes (GBRA-280); an around_chunk_id not on the page falls back to the next one (`fallbacks`, tried in order: a cursor for another page or view, or issued before the page changed, falls back too, and `view: markdown` drops around_chunk_id beside another selector), and the response's `window_selector {applied, ignored, note}` reports what was set aside. `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. `section`/`grep`: `ops/get-page-slice.ts` ([continued](core-services-2-continued.md)).
+Continued in [Core Services (2/3, page windows and large writes)](core-services-2-page-window.md).
diff --git a/docs/architecture/key-files/core-services-2-page-window.md b/docs/architecture/key-files/core-services-2-page-window.md
new file mode 100644
index 0000000000..4d1fd53beb
--- /dev/null
+++ b/docs/architecture/key-files/core-services-2-page-window.md
@@ -0,0 +1,21 @@
+# Key files: Core Services (2/3, page windows and large writes)
+
+[Subsystem index](../KEY_FILES.md) · [Previous entries](core-services-2-continued.md). Read only the entries relevant to your change.
+Current behavior and load-bearing invariants; history belongs in Git and CHANGELOG.
+Bounded page windows under `src/core/page-window/`, the large-page write paths (`append_page`, segmented edits) and get_page's body modes.
+
+- `src/core/page-window/bounded-lead.ts` — leads, snippets and synopses read a bounded prefix, never the whole body: fan-out SQL selects `boundedBodyPrefixSql(alias)` (`left(coalesce(alias.compiled_truth, alias.truth_lead), 65536)`: a segmented page's NULL body falls back to its stored lead; the one COALESCE of body and lead the page body reader ratchet allows by name), `boundedRawPrefix` cuts a body at 64 KiB on a code point, and `overlaidBoundedRows` / `overlaidBoundedPrefix` replace a prefix holding a `gbrain:facts:begin` marker with the prefix of the withdrawal-overlaid body (one batched `readPageSnapshotsBatch` read; a page it no longer returns, or a failed read, gets an empty lead). A segmented page's row carries its stored `truth_lead`; when that lead holds a facts fence it is overlaid alone with the withdrawal ledger the snapshot read returns (`overlayCanonicalBodies`, then the same 64 KiB cut), never by reading segments. `pageLeadSource` gives getPage callers (exact-slug and alias snippets) a page's compiled truth, or a segmented page's `truth_lead` without touching its throwing body getters. `projectedLead` is that prefix through `boundedProjectedPrefix` (`document.ts`). Consumers: the exact-slug tier (`exact-lookup.ts`) and alias injection (`alias-hop.ts`) snippets, relational hydrate, the reflex pointer synopsis (`retrieval-reflex.ts` `safeSynopsis`: world-only reads take the projected prefix, the trusted entity-card widening the raw prefix through its own fence strip), the entity card's hit row and `entity names` leads, and think's anchor and window-floor rows (`think/gather.ts`: the raw overlaid prefix for the trusted local CLI, the projected prefix otherwise). Small pages render as before. Pinned by `test/bounded-lead.test.ts` and `test/large-pages/segmented-leads.test.ts`.
+- `src/core/page-window/document.ts` — the one read projection every remote window, outline and lead slices: `projectPageText` (fence overlay split, `sanitizeRemoteBody` + `credentialSafeProjection`, timeline after `TIMELINE_SEPARATOR`), `pageDocument` / `readPageDocument` (UTF-8 bytes + timeline byte offset, with the page's fence overlay), `chunkDocumentSpan` + `spanHoldsChunk` (a chunk's stored `projected_byte_*` span mapped into the document and verified), `boundedProjectedPrefix`, `locateChunksByStoredSpans` (byte spans to string offsets in one pass), `DEFAULT_INLINE_BODY_BYTES` (256 KB).
+- `src/core/page-window/window.ts` — byte/line window arithmetic on a UTF-8 buffer: windows snap to code points and line starts (`windowFrom`, `windowForLines`, `windowForBytes`, `windowAround`; a lone line longer than the window is cut on a code point as `forced_cut`), `pageOutline` (single pass: ATX headings outside code fences, or 64 KiB blocks for pages with fewer than two headings, with date ranges, paged by `from`/`limit`), and the opaque revision-bound cursor (`gpw1.`). `DocumentSlab` / `slabWindow` run the same arithmetic on a slice of a larger document and shift the result back to document coordinates.
+- `src/core/page-window/segmented.ts` — Wave B PR 2 (spec 7.2, 7.4): get_page over a segmented page in projected bytes, the same coordinates as an inline page. `SegmentedDocument` places units (segments from `projectedUnits` plus fixed text) by stored sums and reads only the units a window, line lookup or `around_chunk_id` touches (`slab` adds `EDGE` bytes so code-point and line snapping match the inline arithmetic). `segmentedReadDocument` is the read projection; `segmentedMarkdownDocument` the markdown view (`markdownHead`, then the projection for a remote caller, the overlaid stored body and `TIMELINE_SEPARATOR` for a trusted one). `page_view_digests` (migration v253) caches per page revision, view and audience the read view's line count and the markdown view's size and sha256, checked against the current total. `tailDigest` hashes the last `TAIL_BYTES` raw bytes of the last region, withheld from a remote caller when those rows hold a protected or facts region. `segmentedOutline` pages headings from stored metadata, reading at most `OUTLINE_READ_BYTES` of segments per page and carrying line counts forward between entries. `segmentedReadWork` (@internal) counts the units and segment bytes a read visits, for the read-cost bounds. `cli/page-render.ts` uses it for the local `gbrain get` stream (`streamSegmentedGet`); the thin client pages and verifies the markdown view (`printPagedPage`), and `--json` above `PAGE_MAX_BYTES` is refused on both paths. Pinned by `test/large-pages/segmented-get-page-parity.test.ts`, `read-cost.test.ts`, `remote-get-page-privacy.test.ts`, `segmented-get-cli.test.ts` and `segmented-get-over-ceiling.test.ts`.
+
+## Large page writes
+
+Writes that change part of a page in time proportional to the change (Wave B spec 6.1, 6.3): `append_page`, segmented `edit_page` and the splice engine both use. Tests: `test/large-pages/append-cost.test.ts`, `test/large-pages/append-concurrency.test.ts` and `test/large-pages/edit-segmented.test.ts`, PGLite and Postgres (helper `test/helpers/append-brain.ts`).
+
+- `src/core/page-body/splice.ts` + `tail-digest.ts` — byte-range splices of a segmented body. `spliceSegmentedBody` replaces stored byte ranges of the live generation (`BodyReplacement`) and stages the next one from the touched segments only: segmentation resumes at the last clean entry point before the first replaced byte and stops at the first old boundary whose entry state the new run reproduces, so later segments keep their bytes, text and chunks and only move (new manifest rows under the same occurrence; content_hash midstate recomputed). An append is an insertion at its region's end: it re-segments the old tail plus the text and moves nothing; an insertion at the truth/timeline boundary belongs to truth (`replacementRegion`), so exactly one row owns it. New segments equal to a replaced one keep its occurrence; the rest are chunked with vectors reused by chunk text. A change that flips a region's fence trust restages the whole body (`rescanned`). `splicePage` reads the page row a splice needs (generation, region sizes, cr tier, corpus generation, kind); `spliceWork` counts segments segmented, bytes read and manifest rows (the cost tests' work counters). `tail-digest.ts` is the append precondition's digest for inline pages, sha256 of a region's last min(4096, region bytes) raw stored bytes (`inlineTailDigest`; segmented pages use `page-window/segmented.ts` `tailDigest`); a tail holding facts or takes text is withheld from a remote caller, since a hash of hidden text is a guessing oracle. The cost test pins that a 10 KB append to a 4 MB and a 16 MB page segments only the tail plus the text, and a forced full-rewrite probe (`appendProbe.fullRewrite`) fails the bound.
+- `src/core/persistence/page-append.ts` — `append_page`: text added to the end of a region (`region` auto/truth/timeline, `separator` auto/none), idempotent by `request_id`. `admitPageAppend` (also the upload lane's `commit_page_upload` append entry, with a staged `body_ref`) journals the text or the reference, never the body; text is capped at `APPEND_TEXT_MAX_BYTES` (4 MiB), a facts or takes fence marker in it refuses `invalid_params` and a links fence marker `append_links_fence` (write links with `add_link`), and a missing or deleted page refuses `page_not_found`. `prepareAppendMutation` checks the optional preconditions on the locked snapshot (`expected_revision` gives `revision_changed`; `expected_tail_sha256` gives `tail_changed`, whose fix carries the current tail digest). A segmented page splices onto its region's tail through `prepareSegmentedSpliceMutation`, which segmented edit_page and append-mode upload commits share. It refuses a result over `pages.max_bytes` as a streamed import does (`file_too_large`, nothing written), and runs put_page's write gate over the new text only (title, frontmatter and the replacement bytes, O(text)): a flag verdict sets `content_flag` (`instruction_like`), records the page gate receipt and returns put_page's `gate` field; an allowed append never clears an existing flag, since the stored text was not re-read; it declines (null, whole-body path) for an always-loaded core page, an external_untrusted write the write gate scans whole, a change that creates or empties a region, or a file a withdrawal ledger rewrites. An inline page composes the new body on put_page's path, which promotes it past the segmented threshold. Chunks and embeddings of the appended text follow commit as for any segmented write. A remote append to the compiled truth records the bytes it added (`PreparedMutation.mentionRange`: stored truth offsets and their SHA-256, from the splice or, inline, the parsed appended bytes placed at the end of the stored truth after publication, so a Tier 1 fence normalization before them cannot shift the range) and queues a `links` effect carrying them (`data.range`, #7122; see `effect-links.ts`); timeline rows and fence projections of appended text wait for PR 4's incremental derivation. A file-backed segmented page's canonical file gains the appended bytes, its frontmatter rendered in stored key order as inline edit_page and append write-through render it.
+- `src/core/ops/page-append.ts` — the `append_page` operation (write scope, client slug-fence allowlist, `outputRedaction: 'no_stored_text'`): params `{slug, source_id?, text, request_id, expected_revision?, expected_tail_sha256?, region?, separator?}`, returns `{slug, revision, body_bytes, appended_bytes, chunks_new, size_state, receipt}`. get_page's `body: 'none'` returns `tail_sha256` and `tail_region` for inline and segmented pages, and its window reads return `edit_target: {revision, byte_start, byte_end}` in stored coordinates (`ops/get-page-body.ts` `editTarget`), withheld from a remote caller when hidden text precedes the window end (`read-range.ts` `hiddenBefore`).
+
+Segmented edit_page (`persistence/page-edit.ts`, entry in [Core Persistence](core-persistence.md)): optional `within: {byte_start, byte_end}` (stored coordinates, as `edit_target` returns them; `parseEditWithin`, `edit_invalid`) limits matching to one range, and a range the page no longer holds refuses `revision_conflict`. A remote caller's `within` refuses `edit_invalid` (one refusal for every range and edit, before any match or fence check) when hidden text starts before `byte_end`: on a segmented page the read projection's hidden units (`read-range.ts` `hiddenBefore`, the predicate `editTarget` withholds `edit_target` by), on an inline page a fence whose remote view differs from its stored text; such a range would measure the hidden text. A segmented page is never materialized: `prepareSegmentedEditMutation` (called first by `page-prepare.ts` `preparePageMutation`) finds each old_text by a streaming scan across segment boundaries (`locateSegmentedEdits`, with applyPageEdits' exactly-once, protected-span and remote-view rules; the scan keeps at most two matches per edit and refuses `edit_ambiguous_match` at the second, counted in `spliceWork.matches`) and splices the touched range; the receipt diff covers the touched range plus 2 KB of context, and only the first replacement past 256 KB (`diff_truncated`); its context never starts at or inside hidden facts or takes text, nor ends inside it, and its hunk lines count the caller's view (`viewNewlinesBefore`: row line counts plus, for a remote caller, each hidden run before the diff rendered as `sanitizeRemoteBody` renders it). With a withdrawal ledger that applies, the scan, the diff and those line counts read the page through its withdrawal overlay (`storedPieces` over `trustedSegments`, rows widened to whole fence blocks), on every path; a match into a block the overlay rewrote is never kept. A segmented page's remote edit view hides withdrawn rows as its remote windows do (`SEGMENTED_REMOTE_VIEW`, also on the whole-body path). A stored fence that does not compile refuses as applyPageEdits refuses it (typed `target_fence_malformed`, same location), at submission (`assertSegmentedEditFences`) and again at preparation: `scanCanonicalFences` runs over the stored fence text alone, each piece at its own line, so only segments holding fence text are read; with `within`, only the fences in the touched segments and those crossing into them. It declines to the whole-body path for an old_text naming the timeline sentinel or also found in the frontmatter head, or a miss without `within` on a page within the single-string ceiling.
+- `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 (a selector → window, setting aside body full/include_content/content_only beside it; else explicit body; include_content/content_only → full; the thin client and the local CLI → full; else auto). Several selectors read one window, `SELECTOR_ORDER` cursor > around_chunk_id > lines > bytes (GBRA-280); an around_chunk_id not on the page falls back to the next one (`fallbacks`, tried in order: a cursor for another page or view, or issued before the page changed, falls back too, and `view: markdown` drops around_chunk_id beside another selector), and the response's `window_selector {applied, ignored, note}` reports what was set aside. `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. `section`/`grep`: `ops/get-page-slice.ts` ([continued](core-services-2-continued.md)).
diff --git a/docs/architecture/key-files/core-utilities-2-continued.md b/docs/architecture/key-files/core-utilities-2-continued.md
new file mode 100644
index 0000000000..e0c3bca99e
--- /dev/null
+++ b/docs/architecture/key-files/core-utilities-2-continued.md
@@ -0,0 +1,26 @@
+# Key files: Core Utilities (2/2, continued)
+
+[Subsystem index](../KEY_FILES.md) · [Previous entries](core-utilities-2.md). Read only the entries relevant to your change.
+Current behavior and load-bearing invariants; history belongs in Git and CHANGELOG.
+
+- `src/core/sql-query.ts` — engine-aware tagged-template SQL adapter for OAuth/admin/auth infrastructure. `sqlQueryForEngine(engine)` returns a `SqlQuery` (`(strings, ...values) => Promise<rows[]>`) that walks the template, builds `$N` positional SQL, asserts every value is a `SqlValue` (string | number | bigint | boolean | Date | null), and routes through `engine.executeRaw(sql, params)` (Postgres via postgres.js `unsafe(sql, params)`, PGLite via `db.query(sql, params)`). Deliberately narrower than postgres.js's `sql` tag: no nested fragments, `sql.json()`, `sql.unsafe()`, `sql.begin()`, or array binding — the narrow scalar-only surface is the feature (keeps it from drifting into a partial postgres.js clone). JSONB writes go through `executeRawJsonb(engine, sql, scalarParams, jsonbParams)` which composes positional `$N::jsonb` casts and passes JS **objects** through; an object reaches the wire with the correct type oid, so executeRawJsonb is safe (verified by `test/sql-query.test.ts` on PGLite, `test/e2e/auth-permissions.test.ts:67` on Postgres). Positional binding is NOT universally immune, though: binding a `JSON.stringify(x)` **string** to a bare `$N::jsonb` via `unsafe()` double-encodes it into a jsonb string scalar on real Postgres (PGLite hides it). Fixes: pass a raw object (executeRawJsonb / `sql.json`), or cast through `$N::text::jsonb`. `scripts/check-jsonb-pattern.sh` (template grep) doesn't fire on `executeRawJsonb(...)` because it passes objects; the positional `$N::jsonb` + `JSON.stringify` form is caught by `scripts/check-jsonb-params.mjs`. Also exports `FILES_METADATA_MERGE_SQL`, the one `ON CONFLICT (storage_path)` merge fragment every files upsert (`src/commands/files.ts` x4, `src/core/ops/files.ts` `file_upload`) interpolates: it resets a non-object `files.metadata` to `{}` before the jsonb `||` merge, because `||` array-wraps a non-object left operand and would turn a legacy string-scalar row into `["{}", {...}]` that `gbrain repair-jsonb` can no longer see (pinned by `test/file-upload-fail-closed.test.ts`). Consumed by `src/commands/auth.ts`, `src/commands/serve-http.ts`, `src/core/oauth-provider.ts`, `src/commands/files.ts`, `src/mcp/http-transport.ts` so all five work uniformly against PGLite and Postgres.
+- `src/core/raw-file-upload.ts` — `gbrain files upload-raw` (`src/commands/files.ts`) refuses `writer_coordinator_required` before writing into a managed worktree (raw files are unpublished): `managedRawUploadRefusal` (#5963) before a git-storage `mkdir` (fix: `gbrain files upload`), `managedPointerRefusal` (#7346) before an object-storage upload whose `.redirect.yaml` would land there (fix: `--no-pointer`). `rawUploadRefusedFor` stops `file_upload` (`src/core/ops/files.ts`) suggesting upload-raw there.
+
+- `src/core/storage-config.ts` — Storage tiering: `loadStorageConfig` reads `gbrain.yml` (warns once per unknown `storage:` key; an optional `keep_db` prefix list, present only when declared, is normalized like the tiers and matched by `isKeepDbSlug`, consumed by `repair/keep-db-policy.ts`), normalizes deprecated keys (`git_tracked`/`supabase_only`) to (`db_tracked`/`db_only`) with a once-per-process warning, and runs `normalizeAndValidateStorageConfig` (auto-fixes missing trailing `/`, throws `StorageConfigError` on tier overlap). Path-segment matcher: `media/x/` does NOT match `media/xerox/foo`. `isDeclaredDbOnlySlug` matches a lowercase page slug against the declared db_only dirs case-insensitively; managed persistence uses it to publish those pages database-only. `hasUnresolvedDbOnlyDeclaration` detects a db_only key line that resolved no directory (a multi-line flow list, a key outside `storage:`; one-line lists parse, `db_only: []` declares none, #8007); the sync baseline-commit guard refuses on it, and managed persistence turns a missing-file refusal into `storage_error`. Parses `gbrain.yml` itself (gray-matter breaks on delimiter-less YAML). Also carries `DERIVE_PHASE_DB_ONLY_DEFAULTS` (`life/events/`, `atoms/`, `extracts/`, `dream-cycle-summaries/`) + `effectiveDbOnlyDirs` — the engine's derive-phase output prefixes treated as implicitly-declared db_only by the `undeclared_db_only_pages` doctor check but deliberately NOT merged into `loadStorageConfig` (a global merge would auto-gitignore those dirs and silently kill ingestion for brains that file-back them) — and `findDbOnlyCollisions` (pure collector-output vs db_only overlap detector shared by the `db_only_collector_collision` doctor check and sync's `manageGitignore` warning). Pinned by `test/storage-config.test.ts` + `test/doctor-silent-death-checks.test.ts`.
+
+- `src/core/storage.ts` — Storage backends (S3, Supabase, local), `uploadFile` (#7427), `settingsStorage`, `hashStoredObject`; `prefixedStorage` refuses `.`/`..`/empty key segments and a leading `/`.
+
+- `src/core/stored-embedding-identity.ts` — reads the existing primary vector column's database type and width plus its recorded model before either engine initializes the schema or runs bootstrap DDL. Its fixed-name store inventory covers primary-space vectors in chunks, facts, query cache and takes; re-init refuses a model change when any is populated. Existing stores retain their identity instead of inheriting a fresh-install default; unknown column identity or missing model metadata refuses schema initialization with explicit migration guidance. This does not merge database model rows into the runtime gateway or rewrite stored vectors. Configless runtime access remains keyword-only until an embedding identity is explicitly configured. Approved model migrations invalidate companion vectors and clear the query cache atomically with their checkpoint and DB identity; same-target resume preserves already-regenerated companion vectors.
+
+- `src/core/surface-audit.ts` — `writeSurfaceChangeAudit(engine, audit)`: the surface-mutation audit trail. Every surface mutation (rescope CLI, `POST /admin/api/rescope-client`, `request_tools` persist) writes one typed `mcp_request_log` row — `operation='surface_change'`, params a RAW object `{actor, client_id, old, new, via}` via `executeRawJsonb` (never `JSON.stringify` into `::jsonb`). Zero new DDL; rides `idx_mcp_log_time_agent` + the retention TODO. Best-effort: a failed audit write warns to stderr, never fails the committed mutation (callers needing fail-closed semantics inspect the returned boolean). CLI-actor rows are written even though stdio ops don't otherwise log (documented exception — audit outranks the transport-logging convention). The usage reader excludes these rows from op-call stats.
+
+- `src/core/timeline-marker.ts` — the `<!-- gbrain:materialized v1 <12-hex> -->` marker that precedes a materialized timeline bullet: `timelineKey` (the one normalization for prior-set membership, dedup, stored-row matching and marker hashes), `timelineTupleHash`, `materializedMarker`, marker-line detection and `stripMaterializedMarkers`. Both timeline extractors skip marker lines (a marker never becomes bullet or header detail) and `sanitizeRemoteBody` drops them from chunk text unless `keepMaterializedMarkers` is set (remote `get_page`/`fetch` keep them so an edit round-trips). A marker whose hash no longer matches the bullet below it marks nothing.
+- `src/core/timeline-citations.ts` — `parseInlineCitationTimelineEntries`: inline `[Source: <source>, YYYY-MM-DD]` citations become timeline candidates whose summary is the citing paragraph without the citation; a page with no `[Source:` returns none before any paragraph is built. #6184: a comment-only line is a paragraph boundary and `stripHtmlComments` removes `<!-- … -->` spans (and dangling `<!--`/`-->`) before the summary is built, so section and materialized-row markers are never filed as entries. #6226: a citation files one entry per dated `source, date` segment (a `;` splits sources only after a date), summaries unwrap paired emphasis and keep inline code (#8893), and `supersededInlineCitationEntries` returns older readings' entries the current one drops; `timeline-extract.ts:supersededTimelineReadings` runs it with both extractors' bullet skips and `retractRemovedTimelineEntries` retracts those rows when their detail is extractor-written (`hasExtractorDetail`: empty or `Source: <source>`). The dated-bullet regexes (`TIMELINE_LINE_RE`, `_CN`, `isDatedTimelineLine`) live here and `link-extraction.ts` imports them.
+- `src/core/transcripts.ts` — `listRecentTranscripts(engine, opts)` library reused by both the `gbrain transcripts recent` CLI and the `get_recent_transcripts` MCP op. Reads `dream.synthesize.session_corpus_dir` + `dream.synthesize.meeting_transcripts_dir` config (same as `discoverTranscripts`); walks `.txt` files within `days`; applies the `isDreamOutput` guard from `transcript-discovery.ts` (skips dream-generated files); returns `{path, date, mtime, length, summary}[]` sorted newest-first. Summary mode (default true) = first non-empty line + ~250 trailing chars; full mode caps at 100KB/file. Missing/non-existent corpus dirs return `[]`, not error. Trust gate lives in the op handler, not here: the op throws `permission_denied` for `ctx.remote === true`; this is a trusted library function used by both the gated op and the local CLI.
+
+- `src/core/eligibility/fence-overlay.ts` + `src/core/trust/fence-append.ts` — the facts-fence eligibility overlay for chunks (#5575 ENG-1). `loadFenceChunkOverlay(engine, { sourceId, slug, compiled_truth, timeline })` reads, in one query and only when the body has world fence rows, which rows to omit (a `write_gate_holds` hold on the row's fingerprint, through the `registerFactHoldFingerprint` seam for the write gate's `holdFingerprint`; a `fact_purges` tombstone, the backstop to L3's import overlay) and which to demote (stored `facts.trust_tier` below the page tier, or a row a fence append is publishing, declared with `withPendingFenceRows`). `prepareMarkdownChunks(page, maxTokens, overlay)` (`markdown-chunks.ts`) drops both from the page's chunks and emits demoted rows as trailing chunks whose first line is `fenceTrustMarker(tier)` (a `compactTrustLabel` line with origin `facts-fence`); without overlay rows the output is byte-identical. The importer (`prepareFenceAwareMarkdownChunks`), projection rebuilds (`ProjectionSnapshot.fenceOverlay`), embed's chunkless rebuilds (`prepareProseChunks`) and evidence delivery's page document (`pageEvidenceText`) all cut through it; `healOversizedChunks` keeps the marker on every split piece. `fenceLowTierRows` / `renderFenceLowTier` give the demoted rows of one text for the segment reader's low-tier block. `eligibility/stamp.ts` labels a row carrying a marker min(page tier, marker tier) with origin `facts-fence` and applies floors at that tier; a marker can only lower. `withPageTierKept(tx, page, fn)` restores the page's prior `trust_tier`/`write_origin` after a fence append's page write (promotion capped at the prior tier when raising back), used by `fence-write.ts` (legacy mirror), `memory-prepare.ts` (remember) and `facts-prepare.ts` (managed entity facts). Tests: `test/fence-chunk-overlay.test.ts` (PGLite and Postgres via `test/e2e/fence-chunk-overlay-postgres.test.ts`).
+- `src/core/types.ts` extension + `src/core/operations.ts:search` + `src/core/import-file.ts` + `src/cli.ts` + `src/core/search/telemetry.ts` — the wiring layer for the retrieval-quality stack. `SearchResult` carries `evidence`, `create_safety`, `title_match_boost`, `alias_hit` (all optional; evidence/create_safety reference the union types in `evidence.ts`). The `search` MCP op uses a cheap-hybrid path by default and accepts a per-call `mode` (conservative|balanced|tokenmax) honored ONLY for trusted/local callers (`resolvePerCallMode(ctx, ...)` — remote callers use the configured mode so a remote provider can't force tokenmax spend); every search path stamps evidence fail-soft. `importFromContent` projects frontmatter `aliases:` into `page_aliases` via `normalizeAliasList` + `engine.setPageAliases` so new + changed pages register aliases at ingest. `src/cli.ts` carries the `gbrain search diagnose` dispatch (lazy import) and reconciles the `search` CLI path with the cheap-hybrid op. `src/core/search/telemetry.ts` carries in its rollup the rank-1 base_score drift signal (sum/count + 3 coarse buckets, aggregate not per-query), surfaced via `gbrain search stats`, backed by migration v111's `search_telemetry` columns. Tests: `test/cli-search-dispatch.test.ts`, `test/search/per-call-mode.test.ts`, `test/search/telemetry-rank1.test.ts`, `test/search/title-boost-stage.test.ts`, `test/search/alias-hop.test.ts`, `test/search/evidence.test.ts`, `test/search/searchvector-maxpool.test.ts`, `test/search/pre-migration-failopen.test.ts`.
+
+- `src/core/url-redact.ts` — Postgres-URL + free-text credential redaction, sibling of `redact-connection-info.ts`. `redactPgUrl(url)` strips userinfo from a single postgres/postgresql URL, preserving scheme/host/port/db/query (non-URL input collapses to `<redacted-url>`). `redactUrlsInText(text)` sweeps free text (error messages, log lines) for credential shapes of any word-character scheme (the pattern is `\w+://`, so scheme names containing `+`/`-`/`.` are not matched — postgres shapes are the target): the userinfo match is greedy up to the LAST `@` in the token so a raw `@` inside a password can't leak its tail (over-redacts toward safety), and libpq keyword/value forms (`password=` / `sslpassword=`, including quoted values with spaces) are masked too; text without a credential shape passes through untouched. `redactDeep(value)` recursively redacts postgres URLs inside structured payloads about to be stringified. Consumers: the upgrade-errors + connection-events audit JSONL sites, and cli.ts's doctor DB-fallback stderr note (layered with `redactConnectionInfo`). CI guard: `scripts/check-pg-url-redaction.sh` fails the build when a new code path emits an unredacted postgres URL. Pinned by `test/url-redact.test.ts`.
+
+- `src/core/utils.ts` — Shared SQL utilities used by both engines. Exports `parseEmbedding(value)` (throws on unknown input, used by migration + ingest paths where data integrity matters) and `tryParseEmbedding(value)` (returns `null` + warns once per process, used by search/rescore paths where availability matters more than strictness). `isUndefinedColumnError(err)` predicate — pattern-matches Postgres SQLSTATE 42703 / "column ... does not exist" with engine-driver shape variation tolerated; used by `oauth-provider.ts` so genuine errors (lock timeout, network blip, permission denied) propagate while column-missing falls through to the legacy fallback. `validateSourceId(id)` throws on anything outside `^[a-z0-9_-]+$`, used by the per-source disk-layout fix in patterns.ts/synthesize.ts before any `join(brainDir, '.sources', source_id, slug+'.md')` so source_id can't traverse out of brainDir. `rowToSearchResult` projects email `message_id` / `thread_id` metadata and exposes `source_subject` only when a non-empty Message-ID proves the page is an email, so generated page titles never become authoritative email subjects. `rowToPage` populates the required `Page.source_id` from the SELECT projection (`scripts/check-source-id-projection.sh` enforces every projection feeding `rowToPage` includes the column). `bigintToStringReplacer(key, value)` — the JSON replacer turning `bigint` into strings (the postgres.js int8 wire shape), shared by cli.ts's local-result normalizer (which re-exports it) and the commands that stringify results themselves (`gbrain call`, `extract --explain`); commands import it from here, never from the dispatcher. Its doc comment deliberately carries no double-dash flag literals — the flag-registry generator harvests them from every module a command transitively imports, and utils.ts is imported by nearly all.
diff --git a/docs/architecture/key-files/core-utilities-2.md b/docs/architecture/key-files/core-utilities-2.md
index 3da004c9b5..948670312f 100644
--- a/docs/architecture/key-files/core-utilities-2.md
+++ b/docs/architecture/key-files/core-utilities-2.md
@@ -34,25 +34,4 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
- `src/core/sort-newest-first.ts` — single source of truth for the descending-lex sort that `gbrain import` and `gbrain sync` both apply. Mutates in place (Array.prototype.sort semantics), returns the same array reference for fluent chaining. Empty/single-element inputs short-circuit. Future ordering changes flip one line here instead of touching two CLI commands. Pinned by `test/sort-newest-first.test.ts` (descending order, mixed prefixes, empty, single-element, in-place-mutation contract).
-- `src/core/sql-query.ts` — engine-aware tagged-template SQL adapter for OAuth/admin/auth infrastructure. `sqlQueryForEngine(engine)` returns a `SqlQuery` (`(strings, ...values) => Promise<rows[]>`) that walks the template, builds `$N` positional SQL, asserts every value is a `SqlValue` (string | number | bigint | boolean | Date | null), and routes through `engine.executeRaw(sql, params)` (Postgres via postgres.js `unsafe(sql, params)`, PGLite via `db.query(sql, params)`). Deliberately narrower than postgres.js's `sql` tag: no nested fragments, `sql.json()`, `sql.unsafe()`, `sql.begin()`, or array binding — the narrow scalar-only surface is the feature (keeps it from drifting into a partial postgres.js clone). JSONB writes go through `executeRawJsonb(engine, sql, scalarParams, jsonbParams)` which composes positional `$N::jsonb` casts and passes JS **objects** through; an object reaches the wire with the correct type oid, so executeRawJsonb is safe (verified by `test/sql-query.test.ts` on PGLite, `test/e2e/auth-permissions.test.ts:67` on Postgres). Positional binding is NOT universally immune, though: binding a `JSON.stringify(x)` **string** to a bare `$N::jsonb` via `unsafe()` double-encodes it into a jsonb string scalar on real Postgres (PGLite hides it). Fixes: pass a raw object (executeRawJsonb / `sql.json`), or cast through `$N::text::jsonb`. `scripts/check-jsonb-pattern.sh` (template grep) doesn't fire on `executeRawJsonb(...)` because it passes objects; the positional `$N::jsonb` + `JSON.stringify` form is caught by `scripts/check-jsonb-params.mjs`. Also exports `FILES_METADATA_MERGE_SQL`, the one `ON CONFLICT (storage_path)` merge fragment every files upsert (`src/commands/files.ts` x4, `src/core/ops/files.ts` `file_upload`) interpolates: it resets a non-object `files.metadata` to `{}` before the jsonb `||` merge, because `||` array-wraps a non-object left operand and would turn a legacy string-scalar row into `["{}", {...}]` that `gbrain repair-jsonb` can no longer see (pinned by `test/file-upload-fail-closed.test.ts`). Consumed by `src/commands/auth.ts`, `src/commands/serve-http.ts`, `src/core/oauth-provider.ts`, `src/commands/files.ts`, `src/mcp/http-transport.ts` so all five work uniformly against PGLite and Postgres.
-- `src/core/raw-file-upload.ts` — `gbrain files upload-raw` (`src/commands/files.ts`) refuses `writer_coordinator_required` before writing into a managed worktree (raw files are unpublished): `managedRawUploadRefusal` (#5963) before a git-storage `mkdir` (fix: `gbrain files upload`), `managedPointerRefusal` (#7346) before an object-storage upload whose `.redirect.yaml` would land there (fix: `--no-pointer`). `rawUploadRefusedFor` stops `file_upload` (`src/core/ops/files.ts`) suggesting upload-raw there.
-
-- `src/core/storage-config.ts` — Storage tiering: `loadStorageConfig` reads `gbrain.yml` (warns once per unknown `storage:` key; an optional `keep_db` prefix list, present only when declared, is normalized like the tiers and matched by `isKeepDbSlug`, consumed by `repair/keep-db-policy.ts`), normalizes deprecated keys (`git_tracked`/`supabase_only`) to (`db_tracked`/`db_only`) with a once-per-process warning, and runs `normalizeAndValidateStorageConfig` (auto-fixes missing trailing `/`, throws `StorageConfigError` on tier overlap). Path-segment matcher: `media/x/` does NOT match `media/xerox/foo`. `isDeclaredDbOnlySlug` matches a lowercase page slug against the declared db_only dirs case-insensitively; managed persistence uses it to publish those pages database-only. `hasUnresolvedDbOnlyDeclaration` detects a db_only key line that resolved no directory (a multi-line flow list, a key outside `storage:`; one-line lists parse, `db_only: []` declares none, #8007); the sync baseline-commit guard refuses on it, and managed persistence turns a missing-file refusal into `storage_error`. Parses `gbrain.yml` itself (gray-matter breaks on delimiter-less YAML). Also carries `DERIVE_PHASE_DB_ONLY_DEFAULTS` (`life/events/`, `atoms/`, `extracts/`, `dream-cycle-summaries/`) + `effectiveDbOnlyDirs` — the engine's derive-phase output prefixes treated as implicitly-declared db_only by the `undeclared_db_only_pages` doctor check but deliberately NOT merged into `loadStorageConfig` (a global merge would auto-gitignore those dirs and silently kill ingestion for brains that file-back them) — and `findDbOnlyCollisions` (pure collector-output vs db_only overlap detector shared by the `db_only_collector_collision` doctor check and sync's `manageGitignore` warning). Pinned by `test/storage-config.test.ts` + `test/doctor-silent-death-checks.test.ts`.
-
-- `src/core/storage.ts` — Storage backends (S3, Supabase, local), `uploadFile` (#7427), `settingsStorage`, `hashStoredObject`; `prefixedStorage` refuses `.`/`..`/empty key segments and a leading `/`.
-
-- `src/core/stored-embedding-identity.ts` — reads the existing primary vector column's database type and width plus its recorded model before either engine initializes the schema or runs bootstrap DDL. Its fixed-name store inventory covers primary-space vectors in chunks, facts, query cache and takes; re-init refuses a model change when any is populated. Existing stores retain their identity instead of inheriting a fresh-install default; unknown column identity or missing model metadata refuses schema initialization with explicit migration guidance. This does not merge database model rows into the runtime gateway or rewrite stored vectors. Configless runtime access remains keyword-only until an embedding identity is explicitly configured. Approved model migrations invalidate companion vectors and clear the query cache atomically with their checkpoint and DB identity; same-target resume preserves already-regenerated companion vectors.
-
-- `src/core/surface-audit.ts` — `writeSurfaceChangeAudit(engine, audit)`: the surface-mutation audit trail. Every surface mutation (rescope CLI, `POST /admin/api/rescope-client`, `request_tools` persist) writes one typed `mcp_request_log` row — `operation='surface_change'`, params a RAW object `{actor, client_id, old, new, via}` via `executeRawJsonb` (never `JSON.stringify` into `::jsonb`). Zero new DDL; rides `idx_mcp_log_time_agent` + the retention TODO. Best-effort: a failed audit write warns to stderr, never fails the committed mutation (callers needing fail-closed semantics inspect the returned boolean). CLI-actor rows are written even though stdio ops don't otherwise log (documented exception — audit outranks the transport-logging convention). The usage reader excludes these rows from op-call stats.
-
-- `src/core/timeline-marker.ts` — the `<!-- gbrain:materialized v1 <12-hex> -->` marker that precedes a materialized timeline bullet: `timelineKey` (the one normalization for prior-set membership, dedup, stored-row matching and marker hashes), `timelineTupleHash`, `materializedMarker`, marker-line detection and `stripMaterializedMarkers`. Both timeline extractors skip marker lines (a marker never becomes bullet or header detail) and `sanitizeRemoteBody` drops them from chunk text unless `keepMaterializedMarkers` is set (remote `get_page`/`fetch` keep them so an edit round-trips). A marker whose hash no longer matches the bullet below it marks nothing.
-- `src/core/timeline-citations.ts` — `parseInlineCitationTimelineEntries`: inline `[Source: <source>, YYYY-MM-DD]` citations become timeline candidates whose summary is the citing paragraph without the citation; a page with no `[Source:` returns none before any paragraph is built. #6184: a comment-only line is a paragraph boundary and `stripHtmlComments` removes `<!-- … -->` spans (and dangling `<!--`/`-->`) before the summary is built, so section and materialized-row markers are never filed as entries. #6226: a citation files one entry per dated `source, date` segment (a `;` splits sources only after a date), summaries unwrap paired emphasis and keep inline code (#8893), and `supersededInlineCitationEntries` returns older readings' entries the current one drops; `timeline-extract.ts:supersededTimelineReadings` runs it with both extractors' bullet skips and `retractRemovedTimelineEntries` retracts those rows when their detail is extractor-written (`hasExtractorDetail`: empty or `Source: <source>`). The dated-bullet regexes (`TIMELINE_LINE_RE`, `_CN`, `isDatedTimelineLine`) live here and `link-extraction.ts` imports them.
-- `src/core/transcripts.ts` — `listRecentTranscripts(engine, opts)` library reused by both the `gbrain transcripts recent` CLI and the `get_recent_transcripts` MCP op. Reads `dream.synthesize.session_corpus_dir` + `dream.synthesize.meeting_transcripts_dir` config (same as `discoverTranscripts`); walks `.txt` files within `days`; applies the `isDreamOutput` guard from `transcript-discovery.ts` (skips dream-generated files); returns `{path, date, mtime, length, summary}[]` sorted newest-first. Summary mode (default true) = first non-empty line + ~250 trailing chars; full mode caps at 100KB/file. Missing/non-existent corpus dirs return `[]`, not error. Trust gate lives in the op handler, not here: the op throws `permission_denied` for `ctx.remote === true`; this is a trusted library function used by both the gated op and the local CLI.
-
-- `src/core/eligibility/fence-overlay.ts` + `src/core/trust/fence-append.ts` — the facts-fence eligibility overlay for chunks (#5575 ENG-1). `loadFenceChunkOverlay(engine, { sourceId, slug, compiled_truth, timeline })` reads, in one query and only when the body has world fence rows, which rows to omit (a `write_gate_holds` hold on the row's fingerprint, through the `registerFactHoldFingerprint` seam for the write gate's `holdFingerprint`; a `fact_purges` tombstone, the backstop to L3's import overlay) and which to demote (stored `facts.trust_tier` below the page tier, or a row a fence append is publishing, declared with `withPendingFenceRows`). `prepareMarkdownChunks(page, maxTokens, overlay)` (`markdown-chunks.ts`) drops both from the page's chunks and emits demoted rows as trailing chunks whose first line is `fenceTrustMarker(tier)` (a `compactTrustLabel` line with origin `facts-fence`); without overlay rows the output is byte-identical. The importer (`prepareFenceAwareMarkdownChunks`), projection rebuilds (`ProjectionSnapshot.fenceOverlay`), embed's chunkless rebuilds (`prepareProseChunks`) and evidence delivery's page document (`pageEvidenceText`) all cut through it; `healOversizedChunks` keeps the marker on every split piece. `fenceLowTierRows` / `renderFenceLowTier` give the demoted rows of one text for the segment reader's low-tier block. `eligibility/stamp.ts` labels a row carrying a marker min(page tier, marker tier) with origin `facts-fence` and applies floors at that tier; a marker can only lower. `withPageTierKept(tx, page, fn)` restores the page's prior `trust_tier`/`write_origin` after a fence append's page write (promotion capped at the prior tier when raising back), used by `fence-write.ts` (legacy mirror), `memory-prepare.ts` (remember) and `facts-prepare.ts` (managed entity facts). Tests: `test/fence-chunk-overlay.test.ts` (PGLite and Postgres via `test/e2e/fence-chunk-overlay-postgres.test.ts`).
-- `src/core/types.ts` extension + `src/core/operations.ts:search` + `src/core/import-file.ts` + `src/cli.ts` + `src/core/search/telemetry.ts` — the wiring layer for the retrieval-quality stack. `SearchResult` carries `evidence`, `create_safety`, `title_match_boost`, `alias_hit` (all optional; evidence/create_safety reference the union types in `evidence.ts`). The `search` MCP op uses a cheap-hybrid path by default and accepts a per-call `mode` (conservative|balanced|tokenmax) honored ONLY for trusted/local callers (`resolvePerCallMode(ctx, ...)` — remote callers use the configured mode so a remote provider can't force tokenmax spend); every search path stamps evidence fail-soft. `importFromContent` projects frontmatter `aliases:` into `page_aliases` via `normalizeAliasList` + `engine.setPageAliases` so new + changed pages register aliases at ingest. `src/cli.ts` carries the `gbrain search diagnose` dispatch (lazy import) and reconciles the `search` CLI path with the cheap-hybrid op. `src/core/search/telemetry.ts` carries in its rollup the rank-1 base_score drift signal (sum/count + 3 coarse buckets, aggregate not per-query), surfaced via `gbrain search stats`, backed by migration v111's `search_telemetry` columns. Tests: `test/cli-search-dispatch.test.ts`, `test/search/per-call-mode.test.ts`, `test/search/telemetry-rank1.test.ts`, `test/search/title-boost-stage.test.ts`, `test/search/alias-hop.test.ts`, `test/search/evidence.test.ts`, `test/search/searchvector-maxpool.test.ts`, `test/search/pre-migration-failopen.test.ts`.
-
-- `src/core/url-redact.ts` — Postgres-URL + free-text credential redaction, sibling of `redact-connection-info.ts`. `redactPgUrl(url)` strips userinfo from a single postgres/postgresql URL, preserving scheme/host/port/db/query (non-URL input collapses to `<redacted-url>`). `redactUrlsInText(text)` sweeps free text (error messages, log lines) for credential shapes of any word-character scheme (the pattern is `\w+://`, so scheme names containing `+`/`-`/`.` are not matched — postgres shapes are the target): the userinfo match is greedy up to the LAST `@` in the token so a raw `@` inside a password can't leak its tail (over-redacts toward safety), and libpq keyword/value forms (`password=` / `sslpassword=`, including quoted values with spaces) are masked too; text without a credential shape passes through untouched. `redactDeep(value)` recursively redacts postgres URLs inside structured payloads about to be stringified. Consumers: the upgrade-errors + connection-events audit JSONL sites, and cli.ts's doctor DB-fallback stderr note (layered with `redactConnectionInfo`). CI guard: `scripts/check-pg-url-redaction.sh` fails the build when a new code path emits an unredacted postgres URL. Pinned by `test/url-redact.test.ts`.
-
-- `src/core/utils.ts` — Shared SQL utilities used by both engines. Exports `parseEmbedding(value)` (throws on unknown input, used by migration + ingest paths where data integrity matters) and `tryParseEmbedding(value)` (returns `null` + warns once per process, used by search/rescore paths where availability matters more than strictness). `isUndefinedColumnError(err)` predicate — pattern-matches Postgres SQLSTATE 42703 / "column ... does not exist" with engine-driver shape variation tolerated; used by `oauth-provider.ts` so genuine errors (lock timeout, network blip, permission denied) propagate while column-missing falls through to the legacy fallback. `validateSourceId(id)` throws on anything outside `^[a-z0-9_-]+$`, used by the per-source disk-layout fix in patterns.ts/synthesize.ts before any `join(brainDir, '.sources', source_id, slug+'.md')` so source_id can't traverse out of brainDir. `rowToSearchResult` projects email `message_id` / `thread_id` metadata and exposes `source_subject` only when a non-empty Message-ID proves the page is an email, so generated page titles never become authoritative email subjects. `rowToPage` populates the required `Page.source_id` from the SELECT projection (`scripts/check-source-id-projection.sh` enforces every projection feeding `rowToPage` includes the column). `bigintToStringReplacer(key, value)` — the JSON replacer turning `bigint` into strings (the postgres.js int8 wire shape), shared by cli.ts's local-result normalizer (which re-exports it) and the commands that stringify results themselves (`gbrain call`, `extract --explain`); commands import it from here, never from the dispatcher. Its doc comment deliberately carries no double-dash flag literals — the flag-registry generator harvests them from every module a command transitively imports, and utils.ts is imported by nearly all.
-
+Continued in [Core Utilities (2/2, continued)](core-utilities-2-continued.md).
diff --git a/docs/architecture/key-files/schema-mutation.md b/docs/architecture/key-files/schema-mutation.md
index ca34e29c98..b5061da97e 100644
--- a/docs/architecture/key-files/schema-mutation.md
+++ b/docs/architecture/key-files/schema-mutation.md
@@ -7,7 +7,7 @@ stats/sync data plane + CLI verbs + MCP ops + a first-class agent skill.
Key files:
- `src/core/persistence/staging.ts` — journaled same-directory staging descriptors reserve names, expected sizes and full hashes before any sink. Owner-locked recovery removes only known complete regular files; partial/unexpected bytes keep the root and recovery quota blocked, including committed receipt cleanup. Legacy records acquire durable staging descriptors before any new restoration. Final accounting requires verified absence and parent-directory durability. Stage digests are read in pieces (`large-file.ts` `hashDescriptor`). Wave B: a `before` stage (`.<sha256>.tmp.before-<uuid>`, a name older binaries refuse) holds the copy of a prior canonical file over 24 MiB; a live request's recovery keeps it (`cleanupRecoveryStaging(record, { keepBefore })`) until `restoreBeforeStage` renames it back over the file with its recorded mode or it is removed because the file already holds the prior bytes. A publication stage's stream still under its in-progress name (`<stage>.streaming`) is removed unread by `cleanupRecoveryStaging` and `discardStreamingStage` (never published; its bytes are produced again) and must be absent for final accounting; a partial file at the stage's own name still refuses. `publishStreamedStage` is the forward half of a version 2 withdrawal-mirror record (`effect-model.ts`): its verified publication stage, streamed from a segmented page's segments, is renamed over the canonical file; a missing stage refuses `unexpected_staging_bytes`. A regular-file ancestor proves an uncreated staging leaf is absent; recovery flushes the containing directory and settles the storage failure without deleting that ancestor or retaining a false recovery fence. Tests: `atomic-write.test.ts`, `atomic-long-staging.test.ts`, `persistence-staging.test.ts`, and eight-boundary process-crash harness.
-- `src/core/fs-durable.ts` — the shared durable-flush leaf (imports only `node:fs`). `flushFile(path)` fsyncs a file nobody holds open through `'r+'` on win32 (Windows `FlushFileBuffers` needs write access) and `'r'` elsewhere (a 0444 file stays flushable); a read-only file on win32 cannot be opened writable and is left to the OS. `flushDirectory(path, { bestEffort })` is strict by default: every error propagates except the win32 no-directory-flush codes (`EISDIR`/`EPERM`/`EINVAL`/`ENOTSUP`), a non-directory path fails `ENOTDIR`, and `bestEffort` swallows everything. `sameFileMode(actual, expected)` compares every permission bit on POSIX and only the owner write bit on win32, whose stat reports 0444/0666. A writer that still holds its descriptor sets the mode with `fchmodSync(fd)` and fsyncs that descriptor instead (atomic-write, skill-bundle staging). Callers: atomic-write, the persistence coordinator, identity, root registry, physical-root records, reconcile backups, recovery staging, topology checkouts (`flushTopologyDirectory` re-export, `flushTopologyTree`), skill bundles, agent-install state (`syncDirectory` re-export), `sources reconcile` previews and attendance-repair checkpoints. `scripts/check-durable-flush.ts` keeps new read-handle flushes out of `src/` (docs/TESTING.md#durable-flush-guard). Tests: `test/fs-durable.test.ts`, `test/persistence-windows-flush-5595.test.ts`, `test/bundle-files-windows-5475.test.ts`, `test/init-packaged-skills-native.test.ts`, run natively on windows-latest in the test.yml security-regressions job.
+- `src/core/fs-durable.ts` — the shared durable-flush leaf (imports only `node:fs`). `flushFile(path)` fsyncs a file nobody holds open through `'r+'` on win32 (Windows `FlushFileBuffers` needs write access) and `'r'` elsewhere (a 0444 file stays flushable); a read-only file on win32 cannot be opened writable and is left to the OS. `flushDirectory(path, { bestEffort })` is strict by default: every error propagates except the win32 no-directory-flush codes (`EISDIR`/`EPERM`/`EINVAL`/`ENOTSUP`), a non-directory path fails `ENOTDIR`, and `bestEffort` swallows everything. `sameFileMode(actual, expected)` compares every permission bit on POSIX and only the owner write bit on win32, whose stat reports 0444/0666. A writer that still holds its descriptor sets the mode with `fchmodSync(fd)` and fsyncs that descriptor instead (atomic-write, skill-bundle staging). Callers: atomic-write, the persistence coordinator, identity, root registry, physical-root records, reconcile backups, recovery staging, topology checkouts (`flushTopologyDirectory` re-export, `flushTopologyTree`), skill bundles, agent-install state (`syncDirectory` re-export), `sources reconcile` previews and attendance-repair checkpoints. `scripts/check-durable-flush.ts` keeps new read-handle flushes out of `src/` (docs/ci-guards.md#durable-flush-guard). Tests: `test/fs-durable.test.ts`, `test/persistence-windows-flush-5595.test.ts`, `test/bundle-files-windows-5475.test.ts`, `test/init-packaged-skills-native.test.ts`, run natively on windows-latest in the test.yml security-regressions job.
- `src/core/atomic-write.ts` — the shared atomic file writer for brain-repo markdown writers: unique short hidden tmp sibling from `atomicStagingPath` (`.<sha256(full target path)>.tmp.<uuid>`, so a valid basename near NAME_MAX still stages, #5861; `validateAtomicStagingPath` also accepts the historical `<target>.tmp.<uuid>` journal form, and recovery (`persistence/staging.ts` `upgradeRecoveryStaging`) durably swaps in a short stage only for a recorded historical leaf that returns ENAMETOOLONG; `timeline-write-through.ts` reuses the same allocator) → write loop until every byte lands (writeSync may legally short-write under disk pressure; a silent short write could atomically install truncated content) → fsync → close → synchronous staging boundary → optional `verify(onDiskBytes)` callback (throw = abort, tmp removed, target untouched) → atomic rename → parent-directory fsync through `fs-durable.ts` `flushDirectory` (rename durability; strict under `durable`, the journaled-publication flag, best-effort otherwise). The stage is opened with its final mode and `fchmod`-ed on the descriptor past the umask before any byte is written: `AtomicWriteOpts.mode` sets exact bits and reasserts them over an existing target's mode (a legacy 0644 file tightens on its next write); omitted, the target's existing mode is preserved, else 0644 & ~umask. `mkdirPrivate(dir, root = dir)` creates gbrain-private directories: a missing `root` gets default-permission ancestors and is itself made exactly 0700, each missing directory between `root` and `dir` is created 0700 (`O_NOFOLLOW` fchmod), and a directory that already exists, possibly one the user chose, is never chmod-ed; `dir` outside `root` throws. Consumers of the private modes: the Google connector (`google-source.ts`, `sources-ops.ts` Google add) and the persistence coordinator's Google publication. Consumed by `src/commands/backlinks.ts` (which verifies with `parseMarkdown({validate:true})` before the rename). Rename prevents torn writes, NOT lost updates — read-modify-write callers pair it with `withPageLock` (backlinks does). Unifying the per-module copies (skillopt/apply-edits, write-through, lint) is a filed TODO.
- `src/core/schema-pack/unify-types-handler.ts` + `src/core/onboard/checks.ts` (`checkPackUpgradeAvailable`) — pack-upgrade retype (`runUnifyTypes`, the `unify-types` job). #6196: on a managed brain apply runs the dry run first (`applyOnManagedBrain`): with nothing to retype, link or alias it only switches the active pack (`flipActivePack`, DB + file plane); otherwise it refuses `writer_coordinator_required` with the counts and a read-only `gbrain onboard --check --explain` fix before any lock or write, and the dry run warns that apply waits for coordinated retype. `pack_upgrade_available` on a managed brain is an info row (`readiness_state: degraded`) with that preview as its fix and no `unify-types` apply remediation it could not run. Coordinated retype (D2) is deferred.
- `src/core/onboard/checks.ts` (`checkTypeProliferation`) — doctor/onboard `type_proliferation` (#6289): one `SELECT DISTINCT source_id, type` read; each source resolves its own pack through `loadActivePackForLocalEngine(engine, { sourceId })` (per-source DB config included); sources sharing a pack pool their labels, an alias counts as its canonical type (`classifyStoredType`), and each pool is graded with the unchanged thresholds (warn above declared + 5, fail above declared × 2). The message names the worst pool's sources, pack and up to five undeclared labels. A source whose pack does not resolve, or a failed query, warns "not verified", never ok. Pinned by `test/onboard-pack-upgrade-checks.test.ts`.
diff --git a/docs/architecture/key-files/tooling-and-tests.md b/docs/architecture/key-files/tooling-and-tests.md
index b33fe2c457..f8abce2b0a 100644
--- a/docs/architecture/key-files/tooling-and-tests.md
+++ b/docs/architecture/key-files/tooling-and-tests.md
@@ -36,8 +36,8 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
- `scripts/check-progress-to-stdout.sh` — CI guard against regressing to `\r`-on-stdout progress. Wired into `bun run test` via `scripts/check-progress-to-stdout.sh && bun test` in package.json.
-- `scripts/check-retired-phrases.sh` — the retired-phrase guard (`bun run check:retired-phrases`, in `bun run verify`): greps `CLAUDE.md`, `AGENTS.md`, `CONTRIBUTING.md`, `docs/` and `skills/` for contributor-workflow phrases refactor wave 1 retired (the `RETIRED` table: pattern + the current instruction) and prints `FAIL: <file:line>` / `Why:` / `Fix:` / `See: docs/TESTING.md#retired-phrase-guard` per hit. Historical records (`docs/designs/`, `docs/test-audit/`, `docs/incidents/`, `docs/plans/`, `docs/proposals/`, `docs/research/`, `docs/issues/`, `docs/superpowers/`, `docs/migrations/`, `skills/migrations/`, the `docs/architecture/wave-1-*` porting kit) are exempt; `CHANGELOG.md` is not scanned. `GBRAIN_GUARD_ROOT` seam; fixtures `test/fixtures/guards/check-retired-phrases.sh/` (one `bad-<location>` tree per scanned location); pinned by `test/scripts/check-retired-phrases.test.ts`.
-- `scripts/check-bash32.sh` — the bash 3.2 parse guard (`bun run check:bash32`): runs the real GNU bash 3.2 parser (`bash -n`) over every tracked `*.sh` except `test/fixtures/guards/`, because macOS `/bin/bash` is 3.2 and rejects shapes bash 5 accepts (a heredoc inside `$(...)` with an odd quote). Parser order: `GBRAIN_BASH32` (a bash 3.x binary; `docker` forces the image), `/bin/bash` when it is 3.x, then the digest-pinned `bash:3.2` image. No parser prints one skip line and exits 0; `GBRAIN_TEST_BASH32_REQUIRE=1` makes it exit 2. Prints `FAIL: <file:line>` / `Why:` / `Fix:` / `See: docs/TESTING.md#bash-32-parse-guard`. Parse only, not in `bun run verify`; run by the `test.yml` verify job (image) and `macos-validation.yml` (`/bin/bash`, followed by `bun run verify`). `GBRAIN_GUARD_ROOT` seam; fixtures `test/fixtures/guards/check-bash32.sh/{bad,good}`; pinned by `test/scripts/check-bash32.test.ts`.
+- `scripts/check-retired-phrases.sh` — the retired-phrase guard (`bun run check:retired-phrases`, in `bun run verify`): greps `CLAUDE.md`, `AGENTS.md`, `CONTRIBUTING.md`, `docs/` and `skills/` for contributor-workflow phrases refactor wave 1 retired (the `RETIRED` table: pattern + the current instruction) and prints `FAIL: <file:line>` / `Why:` / `Fix:` / `See: docs/ci-guards.md#retired-phrase-guard` per hit. Historical records (`docs/designs/`, `docs/test-audit/`, `docs/incidents/`, `docs/plans/`, `docs/proposals/`, `docs/research/`, `docs/issues/`, `docs/superpowers/`, `docs/migrations/`, `skills/migrations/`, the `docs/architecture/wave-1-*` porting kit) are exempt; `CHANGELOG.md` is not scanned. `GBRAIN_GUARD_ROOT` seam; fixtures `test/fixtures/guards/check-retired-phrases.sh/` (one `bad-<location>` tree per scanned location); pinned by `test/scripts/check-retired-phrases.test.ts`.
+- `scripts/check-bash32.sh` — the bash 3.2 parse guard (`bun run check:bash32`): runs the real GNU bash 3.2 parser (`bash -n`) over every tracked `*.sh` except `test/fixtures/guards/`, because macOS `/bin/bash` is 3.2 and rejects shapes bash 5 accepts (a heredoc inside `$(...)` with an odd quote). Parser order: `GBRAIN_BASH32` (a bash 3.x binary; `docker` forces the image), `/bin/bash` when it is 3.x, then the digest-pinned `bash:3.2` image. No parser prints one skip line and exits 0; `GBRAIN_TEST_BASH32_REQUIRE=1` makes it exit 2. Prints `FAIL: <file:line>` / `Why:` / `Fix:` / `See: docs/ci-guards.md#bash-32-parse-guard`. Parse only, not in `bun run verify`; run by the `test.yml` verify job (image) and `macos-validation.yml` (`/bin/bash`, followed by `bun run verify`). `GBRAIN_GUARD_ROOT` seam; fixtures `test/fixtures/guards/check-bash32.sh/{bad,good}`; pinned by `test/scripts/check-bash32.test.ts`.
- `scripts/check-source-id-projection.sh` — CI grep guard for the multi-source bug class. Greps `src/core/postgres-engine.ts` + `src/core/pglite-engine.ts` for `SELECT.*FROM pages` projections matching the `rowToPage` feeder shape (id + slug + type + title) and fails if `source_id` is missing. `Page.source_id` is required at the type level; a projection dropping the column produces `Page` rows with `source_id: undefined` while TypeScript's `: string` lies about it. Wired into `bun run verify`.
diff --git a/docs/ci-guards.md b/docs/ci-guards.md
new file mode 100644
index 0000000000..faaff95c28
--- /dev/null
+++ b/docs/ci-guards.md
@@ -0,0 +1,236 @@
+# CI guards
+
+The guard registry, its self-test and the source guards it runs. Moved out of [TESTING.md](TESTING.md#guard-registry-and-self-test) to keep that file under its size cap.
+
+## Guard registry and self-test
+
+The privacy and test-isolation guards use `scripts/lib/guard-candidates.sh` to
+scan fresh file contents in bounded batches before applying their detailed
+per-file rules. They do not cache passing results. Candidate scanner failures
+fail the guard, and matching files retain the same allowlists and diagnostics.
+
+`scripts/guards-manifest.tsv` is THE single registry of `scripts/check-*`
+guards, each classified `scanner` (greps/parses repo sources —
+must eventually carry fixtures), `buildfresh`, or `repostate` (build/freshness
+guards are exempt-with-reason, not fixture-tested).
+`scripts/guard-self-test.sh` (`bun run check:guard-self-test`, wired into
+`bun run verify`) proves every `selftest=yes` scanner CAN fail: it runs each
+one against known-bad (must exit non-zero) and known-good (must pass) fixture
+trees under `test/fixtures/guards/<guard>/{bad,good}/` via the
+`GBRAIN_GUARD_ROOT` env seam (guards run 4 at a time, `GUARD_SELF_TEST_JOBS`
+overrides; results print in manifest order; the whole pass must finish inside
+its 30 s budget), and enforces manifest completeness — a new
+`scripts/check-*` script that isn't registered in the manifest fails the
+build. A guard whose pattern rots into a permanently-green no-op fails CI
+instead of masquerading as coverage.
+
+A guard may carry extra known-bad trees named `bad-<variant>/`; each one must
+fail on its own. Refactor wave 1 adds one inside each split module location for
+every scanner that names a split file, listed in
+[`docs/designs/refactor-wave-1/path-consumers.md`](designs/refactor-wave-1/path-consumers.md).
+
+### Layering guard
+
+`scripts/check-layering.ts` (`bun run check:layering`, in `bun run verify`)
+parses every file under `src/core/engine-sql/`, `src/core/schema-migrations/`
+and `src/core/persistence/` and fails on any import, type-only included, of an
+engine façade (`pglite-engine.ts`, `postgres-engine.ts`, `engine-factory.ts`)
+from engine-sql, of `src/core/migrate.ts` from schema-migrations, or of
+`src/core/ai/gateway.ts` from persistence. The first two directories are loaded
+by the engines and by `migrate.ts`, so an import back up is an ESM cycle that
+can fail with a temporal-dead-zone error at module load. Take the executor as a
+parameter and import types from `src/core/engine.ts`; migration helpers live in
+`schema-migrations/helpers.ts` and the `Migration` type in
+`schema-migrations/types.ts`; persistence embeds via `src/core/embedding.ts`.
+
+### Write-path model guards
+
+`scripts/check-ai-sdk-importers.ts` (in `bun run verify`) fails when a file
+outside `scripts/ai-sdk-importers.allowlist` imports a provider SDK (`ai`,
+`@ai-sdk/*`, `@anthropic-ai/sdk`, `openai`) as a value, so every model call
+goes through `invokeAI`. Each mutating op has a write-inference class
+(`src/core/ops/write-inference.ts`). `test/write-path-zero-llm.serial.test.ts`
+asserts no generative call before commit and only attributed facts extraction
+after it; `test/write-path-no-egress.serial.test.ts`: keyless CLI writes open
+no connection. Helper: `test/helpers/ai-tripwire.ts`.
+
+### Durable-flush guard
+
+`scripts/check-durable-flush.ts` (`bun run check:durable-flush`, in
+`bun run verify`) fails on an `fsyncSync(fd)` anywhere in `src/` outside
+`src/core/fs-durable.ts` whose `fd` is assigned from a read-only `openSync`
+(flags omitted, a flag string without `w`/`a`/`+`, or `O_RDONLY` without
+`O_WRONLY`/`O_RDWR`), file or directory, and on one whose flags it cannot
+read: Windows refuses fsync on a read-only handle and has no directory flush
+(EPERM; #5595, #5475). Fix: fsync the descriptor you wrote through before
+closing it (`fchmodSync(fd)` first for its final mode), or call `flushFile` /
+`flushDirectory(path, { bestEffort? })` from `src/core/fs-durable.ts`. A file
+that cannot migrate yet goes in the guard's `ALLOWLIST` with a reason; a stale
+entry fails. Fixtures: `test/fixtures/guards/check-durable-flush.ts/`. The
+#5595/#5475 regressions run natively on the `windows-latest` row of the
+test.yml `security-regressions` job; `test/helpers/win32-flush-semantics.ts`
+makes them discriminate on POSIX.
+
+### Windows hidden-console guard
+
+`scripts/check-windows-hide.ts` (`bun run check:windows-hide`, in `verify`;
+#4992): a runtime `child_process` import or `Bun.spawn*` in `src/` outside
+`src/core/spawn.ts` fails unless the file is in `NOT_YET_MIGRATED` (a ratchet;
+a stale entry fails); `windowsHide: false` needs an `ALLOWLIST` reason.
+`test/windows-hidden-console.test.ts` is the native proof on the same row.
+
+### Engine-sql ratchet
+
+`scripts/check-engine-sql-ratchet.ts` (`bun run check:engine-sql-ratchet`, in
+`bun run verify`) keeps each storage domain's SQL in one place,
+`src/core/engine-sql/<domain>.ts`, by stopping SQL from growing back into the
+engines. It parses `src/core/pglite-engine.ts`, `src/core/postgres-engine.ts`
+and every file under `src/core/pglite-engine/` and `src/core/postgres-engine/`,
+and names each class member (`PostgresEngine.getPage`), top-level function and
+top-level variable (`insertFact`). A unit is SQL-bearing when the literal text
+of a string, template, tagged template or `+` chain inside it has SQL
+structure: `SELECT ... FROM <x>`, `SELECT <fn>(`, `INSERT INTO <x>`,
+`UPDATE <x> [alias] SET`, `DELETE FROM <x>`, `WITH <x> AS (`,
+`CREATE|ALTER|DROP <object kind>`, `TRUNCATE <x>`, `SET LOCAL <x>`,
+`ON CONFLICT`, `WHERE ... ORDER BY|GROUP BY|LIMIT`, or a `$<n>::type` cast.
+Comments and identifiers never count. Keywords match in upper or lower case
+but never Title Case, and a lowercase match also needs a second SQL signal
+(`where`, `returning`, `$1`, `::`, `;`, `*` and similar), so "Select a file"
+or "could not delete from cache" is not SQL.
+
+`scripts/engine-sql-baseline.tsv` lists `migrated<TAB><domain>` rows (the
+domain's module must exist under `src/core/engine-sql/`) and
+`method<TAB><path><TAB><QualifiedName>` rows for the SQL-bearing members that
+remain. Rows only shrink. The guard fails on:
+
+- a new SQL-bearing member with no row: move the SQL into
+ `src/core/engine-sql/<domain>.ts` and delegate, or mark the declaration (on
+ its line or the line above) with `// engine-sql-ok: <reason>`; an empty
+ reason fails;
+- a stale row, whose member is gone, no longer SQL-bearing or now marked:
+ delete it, or run `bun scripts/check-engine-sql-ratchet.ts --prune`, which
+ drops stale and duplicate rows and never adds one;
+- a duplicate or malformed row, or a `migrated` row with no module.
+
+When a domain moves, delete its members' rows and add its `migrated` row in
+the same commit.
+
+### Page body readers
+
+`bun run check:page-body-readers` (in verify): every site that reads or writes
+a page body as one string has a row in `scripts/page-body-readers-baseline.tsv`
+naming what it must become; rows only shrink. Rules: the script's header.
+
+### Engine-sql dynamic SQL
+
+`scripts/check-engine-sql-dynamic.ts` (`bun run check:engine-sql-dynamic`, in
+`bun run verify`) parses every file under `src/core/engine-sql/` except
+`fragment.ts`, the renderer, which writes `$n` and splices trusted text by
+design. In engine-sql every value reaches SQL as a bound parameter through
+`sqlFragment`, and only constant text is spliced. Trusted text is a string
+literal; a `const` in the same file initialized with trusted text or an
+`as const` object or array literal (members and element accesses included); a
+`CONSTANT_ALLOWLIST` name (`ENRICH_ORDER_SQL`); a call to a `VETTED_BUILDERS`
+entry (`pageReadFilter`, `buildRecencyComponentSql`,
+`privatePagesFilterFragment`, `currentCodeEdgeFilter`, `buildCJKKeywordSql`,
+`currentTextProjectionFilter`); a template or `+` chain whose parts are all
+trusted or are numbers the same function checked earlier with
+`Number.isFinite(<same expression>)`; or a conditional whose branches are both
+trusted. Both registries live in the script with a one-line reason each. The
+guard fails on:
+
+- `trustedSql(arg)` with an arg that is not trusted text: bind the value with
+ `${value}` in `sqlFragment` instead, or register a new builder with its
+ reason after review;
+- an untagged template or `+` concatenation, passed directly or through a
+ local variable (`let` appends included) as the SQL of `.query(`,
+ `.unsafe(`, `.executeRaw(` or `executeRawJsonb(`, with an untrusted part:
+ compose with `sqlFragment` and run it with `executor.run(fragment)`;
+- a literal `$<digit>`, or a `$` right before a substitution, in a composed
+ string (a template with substitutions, any `sqlFragment` template, any `+`
+ operand): let `renderFragment` number the parameters. A static string passed
+ as-is may carry `$1`;
+- an expanded list, `IN (` right before a substitution or a non-literal `+`
+ operand: bind the array as one parameter, `= ANY(${ids}::text[])`, so
+ prepared-statement caches stay bounded.
+
+Fixtures: `test/fixtures/guards/check-engine-sql-dynamic.ts/`; forms are
+driven in `test/scripts/engine-sql-dynamic.test.ts`.
+
+### Engine-sql brands
+
+`scripts/check-engine-sql-brands.ts` (`bun run check:engine-sql-brands`, in
+`bun run verify`) keeps the RLS read brands in
+`src/core/engine-sql/brands.ts` unforgeable. `ScopedRead` records a read that
+ran inside `withScopedReadTransaction` on master and `LegacyUnscopedRead` one
+that ran unscoped on the pool (EO4), so a forged brand silently changes how a
+read is scoped. The guard fails on:
+
+- a brand key (any `__obtainVia...` name) in a text file under `src/`,
+ `test/` or `scripts/` other than `brands.ts` and the guard's own script,
+ fixtures and test: get a branded executor from `scopedRead(tx)` inside
+ `withScopedReadTransaction`, or from `unscopedExecutor(executor, '<reason>')`;
+- in `src/`, a cast onto `ScopedRead` or `LegacyUnscopedRead` outside
+ `brands.ts`, an `as unknown as T` where `T` names `SqlExecutor`,
+ `ScopedRead` or `LegacyUnscopedRead`, or a double cast passed straight to
+ `scopedRead(` or `unscopedExecutor(`. Driver-handle casts such as
+ `tx as unknown as PgConn` in `dialect-postgres.ts` pass;
+- an import of `unscopedExecutor` or `LegacyUnscopedRead` (value, type,
+ alias, re-export or `import('...').X` type) from outside engine-sql, the two
+ engine façades, doctor (`src/commands/doctor.ts`, `src/commands/doctor/**`,
+ `src/core/doctor*`), maintenance (`src/core/maintenance/**`), admin
+ (`src/commands/admin*.ts`, `src/core/admin/**`), migrations
+ (`src/core/migrate.ts`, `src/core/schema-migrations/**`,
+ `src/commands/migrations/**`) and `test/`; an import of `scopedRead` from
+ outside engine-sql, the façades and `test/`; or a namespace, dynamic or
+ `require` import of `brands.ts` from outside that `scopedRead` list.
+ `src/core/ops/**`, the MCP-facing surface, is always denied. Take the
+ branded executor from the engine façade instead.
+
+The allowlists live in the script.
+
+### Retired-phrase guard
+
+`scripts/check-retired-phrases.sh` (`bun run check:retired-phrases`, in
+`bun run verify`, under a second) keeps the instructions agents follow
+literally in step with refactor wave 1. It greps `CLAUDE.md`, `AGENTS.md`,
+`CONTRIBUTING.md`, `docs/` and `skills/` for the contributor-workflow phrases
+the wave retired: the old migrations-array wording and appending to it, the
+rule that every engine method is written twice, the CLI switch-case step, the
+migrate.ts region policy, and schema text listed as a hand-synced pair of
+`schema.sql` and the PGLite schema module. The patterns and the current
+instruction for each live in the script's `RETIRED` table. Historical records
+may quote them and are exempt: `docs/designs/`, `docs/test-audit/`,
+`docs/incidents/`, `docs/plans/`, `docs/proposals/`, `docs/research/`,
+`docs/issues/`, `docs/superpowers/`, `docs/migrations/`, `skills/migrations/`
+and the wave 1 porting kit (`docs/architecture/wave-1-*`); `CHANGELOG.md` is
+not scanned. Each hit prints `FAIL: <file:line> retired phrase "<match>"`,
+then `Why:`, `Fix:` with the current instruction, and `See:`. The fix is to
+rewrite the sentence to the current workflow, never to exempt the file. To
+retire another phrase, add a row to `RETIRED`. Fixtures:
+`test/fixtures/guards/check-retired-phrases.sh/` (one `bad-<location>` tree per
+scanned location); every pattern and the exemptions are driven in
+`test/scripts/check-retired-phrases.test.ts`.
+
+### Bash 3.2 parse guard
+
+macOS ships GNU bash 3.2.57 as `/bin/bash`, and its parser rejects shapes
+bash 5 accepts. The one that broke every Mac (#5810) is a heredoc inside
+`$(...)` whose body holds an odd quote. `scripts/check-bash32.sh`
+(`bun run check:bash32`) runs the real 3.2 parser, `bash -n`, over every
+tracked `*.sh` except the guard fixtures under `test/fixtures/guards/`. It
+uses the first parser available: `GBRAIN_BASH32=<path>` (a bash 3.x binary),
+`/bin/bash` when it is bash 3.x (stock macOS), or the digest-pinned `bash:3.2`
+Docker image (`GBRAIN_BASH32=docker` forces the image). With none it prints
+one skip line and exits 0; `GBRAIN_TEST_BASH32_REQUIRE=1` makes that exit 2. Each
+failure prints `FAIL: <file:line>`, `Why:` (macOS `/bin/bash` is 3.2), `Fix:`
+(read heredoc text with `IFS= read -r -d '' VAR <<'EOF' || true`) and `See:`.
+To reproduce one file by hand:
+`docker run --rm -v "$PWD":/w -w /w bash:3.2 bash -n <file>`.
+
+The guard checks parsing only. It is not in `bun run verify`, which must not
+need Docker. The `test.yml` verify job runs it with `GBRAIN_TEST_BASH32_REQUIRE=1`
+together with `test/scripts/check-bash32.test.ts`, whose real-parser cases
+feed it the `test/fixtures/guards/check-bash32.sh/{bad,good}` trees. The
+macOS 26 job runs it under `/bin/bash` and then runs `bun run verify` there,
+which covers bash-4 runtime features the parser cannot see.
diff --git a/docs/designs/refactor-wave-1/dx-primary.md b/docs/designs/refactor-wave-1/dx-primary.md
index f4c0f9aa38..749f96d929 100644
--- a/docs/designs/refactor-wave-1/dx-primary.md
+++ b/docs/designs/refactor-wave-1/dx-primary.md
@@ -336,7 +336,7 @@ branches ... fail loudly").
Fix: move the query to src/core/engine-sql/facts.ts and make both engine methods one-line delegations
(example: PGLiteEngine.listFacts). If the SQL is genuinely dialect-specific, add a row with a reason to
scripts/engine-sql-baseline.tsv.
- See: docs/TESTING.md#engine-sql-ratchet
+ See: docs/ci-guards.md#engine-sql-ratchet
```
**Path C: `/admin` route without `requireAdmin`** (existing test's message today names the route and the allowlist file,
diff --git a/llms-full.txt b/llms-full.txt
index 1fb32683ce..faed8c51cb 100644
--- a/llms-full.txt
+++ b/llms-full.txt
@@ -595,357 +595,6 @@ pre-mint before the service runs and pass `--token <value>`, or use the scoped
---
-## docs/guides/hosted-harness-access.md
-
-Source: https://raw.githubusercontent.com/garrytan/gbrain/master/docs/guides/hosted-harness-access.md
-
-# Connect your agent to an existing hosted GBrain
-
-Use this guide when your memory already lives on another machine. If you want to run GBrain inside your current agent instead, start with [Grok Bot](grok-bot.md), [Muse](muse.md), or the [coding-agent walkthrough](../tutorials/connect-coding-agent.md).
-
-The brain owner grants access on the running server; the connecting harness
-configures access in its own environment. Installing configuration on the host
-does not configure your laptop or Bot. First select the connection method:
-
-| Intended connection | Follow |
-| --- | --- |
-| Harness has native OAuth/PKCE settings | [Native OAuth path](#native-oauth-path) below |
-| Managed bearer configuration or a thin CLI adapter | The [machine handoff path](#1-grant-access-on-the-brain-host) below |
-| Open the dashboard, inspect clients, change permissions, or end access | [MCP administration](../mcp/ADMIN.md) |
-
-An endpoint URL, ordinary OAuth token, client secret, or MCP `admin` scope does
-not grant owner administration. The owner uses a separately protected bootstrap
-credential. Local stdio connections do not create an HTTP admin panel.
-
-## One setup prompt
-
-Paste this into the agent that should use the hosted brain:
-
-```text
-Connect this existing agent to my hosted GBrain. Follow:
-https://raw.githubusercontent.com/garrytan/gbrain/master/docs/guides/hosted-harness-access.md
-Keep my identity and unrelated configuration. Use memory-writer unless I explicitly
-request another capability. Select this harness's native OAuth/PKCE flow when
-available; otherwise have the owner provision a private machine handoff and
-install it here. Keep secrets out of chat, command arguments, and Git.
-Use the actual harness adapter, verify a unique memory round trip, and report
-server checks separately from observed recall in a new harness conversation.
-Explain that a new machine grant through mcp grant follows the brain's published
-skills by default; offer --skills memory-only. Preserve existing grants and publication opt-outs. Shared
-skills do not authorize scripts, additional tools, spending, or automatic capture.
-Do not claim that generated instructions or a job ID prove a working integration.
-```
-
-## Native OAuth path
-
-1. Obtain the intended harness's actual redirect URI and supported client
- authentication method from its settings/current guide. Public PKCE uses
- `none` and has no client secret; confidential PKCE uses its documented
- `client_secret_post` or `client_secret_basic` method.
-2. The owner follows [native registration](../mcp/ADMIN.md#native-oauth-with-pkce)
- with `gbrain mcp admin register NAME --redirect-uri URI`. Select the desired
- source and permissions explicitly; the native CLI default is read access.
- This creates authorization-code/refresh registration, not a machine token.
-3. The owner runs `gbrain mcp admin setup CLIENT_ID --harness ID --flow
- authorization-code` against that server. It returns live endpoint,
- registration, and setup instructions. Confidential delivery additionally
- requires `--credentials-out PRIVATE_FILE`. An `OAuthClientSetup` export is
- not the machine handoff accepted by `gbrain connect --credentials-file`.
-4. Enter the setup fields in the actual harness and start its OAuth connection.
- The native harness generates and retains the PKCE verifier. When the browser
- asks for owner approval, the authorized administrator issues a login link
- with `--oauth-request REQUEST_ID` from that browser URL. The owner can use
- the link in a fresh browser and return to the same consent request.
-5. Approve the displayed client, callback, scopes, and source access. Verify an
- authenticated call inside the actual harness, then perform the harmless
- cross-conversation memory check described below. Registration and downloaded
- instructions alone do not verify a native connection.
-
-If consent expires or the server restarts, start the connection again in the
-native harness. Enabling DCR is an owner choice, not a required repair: manual
-registration works with DCR disabled when the client supports entered client
-metadata. DCR never bypasses owner approval.
-
-The remaining numbered steps describe **machine handoffs**. Do not install one
-as a substitute when the native client requires OAuth/PKCE.
-
-## 1. Grant access on the brain host
-
-The owner needs a current GBrain runtime and an initialized brain. Stop older servers and workers while applying the grant migration; do not run mixed authorization implementations. Use your normal upgrade and maintenance procedure before restarting them.
-
-**Get the HTTPS endpoint.** Use the configured endpoint if the brain is already served over HTTPS; do not republish it. When the brain runs on the owner's own computer and needs publishing, `gbrain mcp expose` publishes `gbrain serve --http` on the owner's Tailscale tailnet with HTTPS, keeps it running as a user service, and writes the admin bootstrap token to `~/.gbrain/serve/admin-token`. Tailnet-only reach (the default) serves the owner's own devices; agents that run in a vendor's cloud — Grok Bot, Muse, ChatGPT, Claude.ai, Perplexity — need `gbrain mcp expose --funnel`. The printed MCP URL looks like `https://your-machine.your-tailnet.ts.net/mcp`. Steps, flags and troubleshooting: [Use your brain from anywhere over MCP](remote-mcp.md). Other HTTPS fronts (ngrok, a cloud host) come from your [server deployment](../mcp/DEPLOY.md); substitute the intended server's configured URL in every example below.
-
-**Say to your agent:** *"use my brain over mcp"* — *"connect grok bot to my brain"* — the `remote-mcp` skill publishes, then grants.
-
-For ordinary memory, choose `memory-writer`:
-
-```bash
-gbrain mcp grant agent-example --harness codex --profile memory-writer \
- --source default --url https://your-machine.your-tailnet.ts.net/mcp \
- --admin-token-file ~/.gbrain/serve/admin-token \
- --credentials-out /absolute/private/agent-example.json --json
-```
-
-Replace `codex` with the actual adapter identifier. The protected owner file
-provisions through the running server's authenticated admin API and existing
-database connection. `~/.gbrain/serve/admin-token` is the file `gbrain mcp
-expose` maintains; for another deployment, use the private file holding that
-server's configured owner credential. Without the flag,
-`GBRAIN_ADMIN_BOOTSTRAP_TOKEN` supplies the credential. An ordinary OAuth token
-or the endpoint URL cannot provision access. A local maintenance CLI can omit
-both owner credential mechanisms only when it can safely open the intended
-brain. Do not open the live PGLite database from a second process.
-
-Use `--dry-run` first to inspect a proposed grant without creating a client. Default output is redacted. The credential handoff is written with private permissions before any optional client installation or verification. Transfer it through a private file channel, then retain only the copies you need. Uploading credentials or backups is never automatic.
-
-New grants default to **`--skills follow`** within their approved read sources.
-Use **`--skills memory-only`** to opt out of enrollment; catalog reads can still
-be available. Following adds the explicit `skills_member_self` scope and
-catalog/membership operations, not `skill_editor` or `skill_publisher` authority.
-Fresh owned-root setup approves a limited prose-only follow policy for the
-packaged memory skills when publication is enabled. Existing brains still need
-owner approval of their source's follow/disclosure policy; migration and grant
-creation do not expand existing publication consent. Give each independent harness,
-including the parent, its own principal and private handoff. Shared credentials
-are one principal. See [shared brain skills](shared-brain-skills.md).
-
-| Profile | Access | Native MCP surface |
-| --- | --- | --- |
-| `memory-reader` | Read selected memory | Full, lists verbs |
-| `memory-writer` | Read and write selected memory | Full, lists verbs |
-| `coding-agent` | Isolated project writes and explicit project reads | Full, lists verbs |
-| `operator` | Read, write, and eligible brain administration operations | Full |
-| `delegating-agent` | Memory plus explicitly bound delegation | Starter |
-| `full` | All eligible remote capabilities at grant time, including bound delegation | Full |
-
-A **profile grants authority**. A **surface selects visible tools**. Full surface does not bypass a grant, and `admin` does not imply delegation, the named shared-skill scopes, or owner dashboard/client-management authority. Starter includes authorized skill discovery and membership; the exact seven-tool `verbs` surface is memory-only. `rescope-client <client_id> --surface full` lists every tool. Thin CLI adapters use the full surface while retaining their source, operation, and write restrictions. Direct local CLI access is trusted access to the local computer; OAuth profiles do not confine a local shell.
-
-Clients granted a memory profile before the full-surface default keep their stored `starter` surface; no migration or repair widens it, and only an explicit `--profile` application regrants it. New grants snapshot operation names and source access. A later server upgrade does not silently give a snapshot-bound client new operations. The connection's own `whoami` reports `grant_diagnosis`: which blocker applies (scope, operation snapshot, client pin or server ceiling) and how many operations it hides, without naming them; `gbrain doctor` on the host reports the same as `grant_new_ops_available` with the commands. The connection is also told once per session, in band, by the `grant_blocked_operations` notice (same blockers and counts, the owner's preview-then-apply command as `fix`, `next: tell_user_to_run`; once per grant revision for stateless HTTP calls), and a read that left out takes a hidden tool serves carries `hidden_tool_content` with the next step that connection can actually take ([connection notices](repair.md#connection-notices)). Neither notice changes what the connection can call. A grant written before snapshots recorded their operation catalog says "original intent unknown" rather than claiming it predates the operations. Explicitly regrant to include them: `gbrain auth rescope --client <client_id> --operations <op,...> --surface full --dry-run` (then without `--dry-run`; `--surface full` only when the stored surface also blocks) for OAuth clients, or `gbrain auth rescope-token <name> --refresh-operations` (preview) then `--add <op,...>` for legacy tokens ([grants that cannot reach new operations](../mcp/ADMIN.md#grants-that-cannot-reach-new-operations)). `gbrain auth rescope --client <client_id> --operations all` (alias: `gbrain auth rescope-client <client_id> --allowed-operations all`) stores no snapshot and clears the profile instead, so the scopes and the surface alone decide, including operations later upgrades add. `gbrain auth clients` marks su... (line truncated to 2000 chars)
-
-Snapshot-bound clients write through approved MCP operations such as `remember`, `capture`, or `put_page`. They cannot use the legacy `POST /ingest` webhook, whose queued writes do not yet enforce operation snapshots. Existing webhook clients with a `NULL` snapshot keep their legacy behavior.
-
-## 2. Install inside the intended harness
-
-Install GBrain there if needed, using the documented GitHub/Bun distribution. Then:
-
-```bash
-gbrain connect https://your-machine.your-tailnet.ts.net/mcp --harness codex \
- --credentials-file /absolute/private/agent-example.json --install
-```
-
-For Grok Bot, Muse, or another supported thin CLI adapter, also supply `--root /absolute/verified/persistent-root`. Grok Bot's recommended root is `/workspace/gbrain`. Discover and verify Muse's durable location before choosing a root. Use the generated **absolute launcher** for every later GBrain call; it pins routing and isolates inherited configuration.
-
-The installer preserves unrelated configuration and refuses an unowned or edited connection. Codex, Claude Code, and opencode receive private managed configuration (mode 0600) with the bearer token stored **inline** in that file: `~/.codex/config.toml`, Claude Code's user MCP config, or opencode's global config. The receipt names it with `token_storage: "inline"` and `config_path`, gives the `renew_command` that exchanges and writes a fresh token (`--install --fresh-token`), and lists `if_exposed`: preview and apply `gbrain mcp admin invalidate-tokens <client_id>` on the brain host ([invalidate tokens](../mcp/ADMIN.md#invalidate-tokens-revoke-or-delete)), run the renew command, which exchanges a new token instead of reusing the cached invalidated one (a handoff without a client secret needs a new handoff from the owner), then reload the harness. Neither the receipt nor the output prints the token. Treat that config file as a secret: when it sits in a Git working tree that does not ignore it, the receipt adds `token_warning`; add the file to the repository's `.gitignore` or move it, and follow `if_exposed` if it was already committed. Rotating the client secret does not invalidate issued access tokens. Generic adapters supply endpoint/authentication guidance; there is no universal configuration file. [Adapter reference](harness-adapters.md) lists supported mechanisms and reload steps.
-
-A configured server is only one step. Follow the adapter's reload instructions and enable the GBrain standing instruction through the harness's actual controls. Thin CLI installations write that instruction to `<ROOT>/GBRAIN-INSTRUCTIONS.md`. Grok Bot/Muse native skill activation remains a separate, visible step until observed in that harness. Generated files alone do not activate a skill.
-
-With an approved follow handoff, managed Claude Code, Codex, and opencode
-connections also install an owned, namespaced shared-brain router. Successful
-installation reports `restart_required` and `native: unverified`, not universal
-activation. Manual clients remain pending native registration. Read the
-`shared_skills` result and its `next_action`; a policy, grant, server-version,
-or ownership conflict can leave memory working while skill enrollment is pending.
-The router's freshness instruction is advisory, not a vendor-enforced hook.
-
-Inspect this connection's local skill receipt without credentials or a live
-host using `gbrain connect --harness codex --status --json`. Supply the actual
-adapter, connection `--name`, and the recorded `--root` for thin CLI adapters.
-It reports desired/installed/acknowledged views and pending cleanup, but keeps
-`current_authority: unprobed` and `native_use: unverified`; reconnect and test
-the native session separately.
-
-### Harnesses that only speak stdio
-
-A harness that can launch a command but cannot reach an HTTP MCP server uses
-a thin client's `gbrain serve`: install the CLI there, run `gbrain init
---mcp-only` with the client from step 1, then register
-`gbrain serve --surface starter --advertise verbs` (absolute path from
-`command -v gbrain`) as the harness's stdio server. It relays to the brain
-host with that client's grant and adds nothing to it
-([stdio bridge](../architecture/thin-client.md#stdio-bridge)). For a narrower
-harness, register its own client (`--scopes read` for read-only) and init it
-under a separate `GBRAIN_HOME`, set in the harness entry's env as well;
-`serve --access read-only` is refused on a thin client because only the
-host can enforce it.
-
-## 3. Prove a memory round trip
-
-Save durable facts and preferences, not local harness/configuration state. A
-remote `put_page` does not extract graph edges inline: stdio has best-effort
-startup/idle sweeps, but HTTP needs explicit host maintenance or authorized
-`add_link` calls. Configured providers can receive text, and Markdown export is
-not a full database backup. See [memory boundaries](memory-boundaries.md).
-
-Run the server verifier from the harness environment:
-
-```bash
-gbrain mcp verify --client CLIENT_ID --harness codex \
- --url https://your-machine.your-tailnet.ts.net/mcp \
- --credentials-file /absolute/private/agent-example.json --json
-```
-
-It checks transport, authentication, effective permissions, reading, a randomized write/readback, and cleanup separately. Memory profiles use `remember` and `recall`; isolated coding grants use pages inside their fence. The capabilities resource works even on the exact seven-tool surface.
-
-`server_status: "passed"` proves those server checks. Overall `status: "partial"` and exit code **2** mean actual harness evidence is still missing; exit **1** means a failed stage. A fluent response or an SDK probe is not proof that your Bot loaded its standing instructions.
-
-Now ask the actual agent to remember a unique harmless fact, with provenance, and note the observed GBrain call and returned ID. Start a new conversation and ask for it without repeating the fact. Observe `recall`. Correct it, read it back, then withdraw it and check active recall again. Keep the result in your private setup receipt. The harness must identify uncertainty if it cannot load the tool or retrieve the record.
-
-For native OAuth, make these calls through the harness's authenticated MCP
-connection; the private-handoff verifier above is for machine credentials.
-Inspect the advertised tool schemas before proposing arguments. Remote `recall`
-and `forget` operate on facts marked `visibility: "world"`, still restricted by
-the client's source grant. Use that explicit visibility only for the nonsensitive
-synthetic test fact and keep its returned ID for cleanup. A private test fact
-cannot be recalled or withdrawn through these remote operations. Never change
-real private facts' visibility to make verification pass. With read-only access,
-verify an authenticated capabilities/read call without adding write authority.
-
-`forget` withdraws a fact from active memory. History, source material, and backup copies may remain; it is not a promise of physical erasure. Verifier cleanup uses the same withdrawal semantics. Failed cleanup stays visible with the fixture identifier.
-
-## Delegation is a separate capability
-
-Only grant delegation when you want this client to start work on the brain host. Supply a nonempty set of tools from the running registry:
-
-```bash
-gbrain mcp grant research-example --harness grok-bot \
- --profile delegating-agent --source default \
- --bound-tools search,get_page --delegated-namespace job \
- --url https://brain.example.com/mcp \
- --admin-token-file /absolute/private/admin-token \
- --credentials-out /absolute/private/research-example.json --json
-```
-
-**New delegation has unlimited spending and concurrency 1.** Unlimited means no client spending cap; provider charges still apply, and usage remains attributed to the client. To impose a finite cap, explicitly add `--budget-usd-per-day 5`. Existing finite caps are preserved during repair and profile changes unless explicitly changed. A cap of `0` prevents paid work. Finite clients refuse paid calls whose maximum cost or pricing is unknown; unresolved liability stays reserved across midnight and reservation expiry until reconciled.
-
-The default job namespace isolates delegated writes per job. To use another allowed fence, supply `--delegated-slug-prefixes agents/research-example/`. Direct writes and delegated writes have separate fences. The delegated source must also belong to the parent's read grant, and bound tools must fit its operation snapshot. Local-only tools and cross-brain delegation are unsupported.
-
-Delegation verification first checks configuration with a dry run. Add `--delegate` to `mcp verify` only when you want a real worker challenge that may incur API charges. A queued job ID does not pass: the verifier requires terminal completion with the randomized result. An unavailable worker or failed cancellation remains visibly incomplete.
-
-Queued and running work stays restricted by both its submitted policy and the current grant. A changed source invalidates the original target; it does not move the job to another source. Revocation stops newly forbidden work at the next execution boundary and cannot undo an external operation already running.
-
-## Repair permissions without replacing credentials
-
-Inspect `whoami` or the authenticated `gbrain://capabilities` resource. It reports the effective profile, revision, scopes, source access, direct/delegated policies, spending mode, and repair reasons. Worker readiness is reported separately from grant validity.
-
-Preview an explicit profile update:
-
-```bash
-gbrain mcp grant agent-example --client CLIENT_ID --if-version REVISION \
- --harness codex --profile memory-reader --source default \
- --url https://brain.example.com/mcp \
- --admin-token-file /absolute/private/admin-token --dry-run --json
-```
-
-Get the current revision with `gbrain mcp admin client CLIENT_ID` using the
-same server URL and owner credential. Review the before/after grant, then repeat
-without `--dry-run`. `--if-version` rejects a stale edit. The client ID and secret
-remain unchanged. When updating a client, omit `--profile` to preserve its
-profile, scopes, operation snapshot, and bindings while changing only the fields
-you supply. An explicit profile selection regrants its eligible operations.
-Advanced local-maintenance repairs remain available through `gbrain auth
-rescope-client CLIENT_ID --help`; omitted restrictions are retained.
-
-Omitting `--skills` preserves the existing follow choice, including previously
-approved membership when reapplying a profile. Explicit custom scope/operation
-lists are respected instead of silently repaired. To explicitly
-enroll an old memory client, preview `mcp grant` with its client ID, current
-revision, and `--skills follow`, without `--profile`. Apply the reviewed change.
-For a machine client, recover its private handoff, issue a token carrying the
-added scope, and reconnect. For native OAuth, restart authorization in the
-harness to request the added scope. Exact follow and dedicated-editor examples are
-in [shared-skills permissions](shared-brain-skills.md#connect-each-installation).
-Do not grant editing merely because the client can write memory.
-
-Scope removals affect existing tokens immediately. Added scopes need a newly issued access token; refresh cannot expand its original scope grant. Source, operation, fence, binding, and surface changes apply on the next authenticated request. Repairing bindings benefits an existing token that already carries `agent`. TTL changes apply only to newly issued tokens. New renewable connections use one-hour access tokens; static-token adapters use 30 days. Check the receipt for the selected expiry.
-
-## Recover an interrupted handoff
-
-The host retains a private delivery journal before committing a new client. If the response or destination write is lost, recover the original handoff without duplicating the client:
-
-```bash
-gbrain mcp grant agent-example --client CLIENT_ID --resume --harness codex \
- --url https://brain.example.com/mcp \
- --admin-token-file /absolute/private/admin-token \
- --credentials-out /absolute/private/recovered-agent.json --json
-```
-
-Resume changes no permissions and rotates no secret. If the client ID was lost,
-use `gbrain mcp admin clients` with the same URL and owner credential and inspect
-the existing registration before retrying. A lost response can follow a
-committed mutation; it does not prove that creation failed.
-
-In the admin dashboard, use the existing client's setup/delivery action. New
-confidential clients use the same private host journal. If registration loses
-its response, inspect the existing client before recovery. Machine clients
-receive a machine handoff; native OAuth clients receive their distinct OAuth
-setup. Keep any secret-bearing download private and set its permissions to
-`0600` on the target computer. Recovery refuses a revoked client or a journal
-whose secret has since been rotated.
-
-An expired or lost machine **access token** can be reissued using the existing
-client secret. For native OAuth, reconnect in the harness. A lost **client
-secret** requires journal/handoff recovery or an explicit maintenance decision;
-see [legacy rotation limits](../mcp/ADMIN.md#recover-a-failed-step). The local
-`agent register --reissue` path supports confidential machine clients and leaves
-outstanding access tokens valid; it is not a general remote/native-PKCE recovery
-command. Protect or remove the host's `.gbrain/credential-deliveries` files
-deliberately after secure delivery; they contain credentials and are excluded
-from default backups.
-
-## Maintenance, removal, and troubleshooting
-
-Keep the host runtime and schema current together. Keep native instructions enabled for each harness, check token expiry for static adapters, and periodically repeat a harmless memory round trip. The host's normal maintenance schedule serves its connected clients; installing a remote connection does not silently create another server or paid routine.
-
-For a hosted thin CLI connection, a removed runtime is repaired by reinstalling
-GBrain in the harness, then repeating `gbrain connect ... --install` with the
-existing private handoff, endpoint, harness identifier, and root. The installer
-updates its owned launcher while preserving the host's memory and client
-identity. This connection has no local database backup or `bin/gbrain-setup`
-helper; complete backups belong on the brain host. If the handoff was lost,
-recover it through the host's delivery procedure first.
-
-Before applying the grant migration, stop old servers and workers and take a protected backup. Start only runtimes that enforce the migrated grants. If rollout fails, disable the affected entry points and restore a compatible runtime while preserving memory and the tightened grants; do not run an older authorization implementation against the migrated database. Local installations can be released independently of hosted delegation.
-
-Remove a managed configuration with the same private handoff and `gbrain connect
-... --remove`, or remove the native OAuth connection through its harness
-settings. Disable saved skills/routines through the harness controls. Use
-[token invalidation, revocation, or deletion](../mcp/ADMIN.md#invalidate-tokens-revoke-or-delete)
-when server authority should change. Removing configuration alone does not
-revoke access or delete memory.
-
-Managed removal also attempts to leave its shared-skills enrollment and removes
-only unchanged owned artifacts. `left_with_retained_files` requires review of
-the preserved edits and a native restart/disable step. A server-side
-`leave_brain` alone cannot remove files on the client. Offline or revoked access
-does not prevent local following from being disabled: inspect
-`remote_membership_pending` to distinguish local cleanup from host-acknowledged
-departure and retry the latter when possible. Back up operational DB
-state as well as canonical content; Git alone cannot restore memberships,
-policy history, revocations, or receipts. See
-[shared-skills recovery limits](shared-brain-skills.md#troubleshoot-leave-and-recover).
-
-<a id="hosted-harness-troubleshooting"></a>
-
-| Symptom | Next action | Who acts | Consent | Verify |
-| --- | --- | --- | --- | --- |
-| PGLite is busy | Use authenticated host administration (`--admin-token-file ~/.gbrain/serve/admin-token` against the running server) or wait for the current owner to close. Never remove a live lock. | brain host | none | `gbrain doctor --only connection --json` on the host |
-| Published URL unreachable from the agent | On the host, `gbrain mcp expose --status`. A cloud agent needs `--funnel`; tailnet-only reach serves only the owner's own devices. Certificate issuance can leave tailnet health `pending` for a minute. See the [remote MCP troubleshooting table](remote-mcp.md#troubleshooting). | brain host | `egress` when switching to `--funnel` | `gbrain mcp expose --status --json` |
-| Configuration conflict | Select a fresh connection name/root or inspect the changed entry; do not overwrite unrelated settings. | agent | none | re-read the harness's MCP configuration |
-| `grant_conflict` | Fetch the new revision and preview again. | agent, after the user agrees | none | preview the grant again |
-| Delegation missing | Inspect repair reasons and explicitly bind supported tools, an active source, path policy, and positive concurrency. | brain host | none | the harness's tool list |
-| Read works, writes fail | Check issued/current scopes, operation snapshot, source grant, and direct fence. Full surface alone adds no authority. | brain host | none | `whoami` (where callable) or `gbrain doctor --json` on the host |
-| Work queues but never finishes | Check the host worker and terminal job status; queue admission is not worker verification. | brain host | none | `gbrain jobs stats` on the host |
-| Finite cap blocks a call | Inspect unresolved reservations and provider pricing/bounds; do not treat unknown usage as zero. | user (sets or raises the cap) | `paid` | `gbrain doctor --json` on the host |
-| Server checks pass, new conversation fails | Verify native instruction activation, reload, absolute launcher, and observed GBrain calls inside that harness. | user (restarts or reloads the harness) | none | a `recall` from a new conversation |
-
-## Evidence and release gates
-
-As of **2026-09-09**, repository tests exercise private configuration writers, credential recovery, grant enforcement, owner consent, and server probes. Exact tests and observed results belong in the change's validation record. **Actual Grok Bot/Muse sessions have not been verified by these tests.** Native Grok Bot OAuth additionally requires confidential-client PKCE/resource checks, authenticated owner approval, and a successful real connector test. Muse personal-agent native MCP configuration remains unverified and is not an advertised installation path.
-
-[Validation evidence and actual-harness acceptance](harness-validation.md).
-
----
-
# Core entry points
## AGENTS.md
diff --git a/scripts/check-bash32.sh b/scripts/check-bash32.sh
index c832675ffc..308a6c38e8 100755
--- a/scripts/check-bash32.sh
+++ b/scripts/check-bash32.sh
@@ -116,7 +116,7 @@ while IFS= read -r line; do
done <<< "$out"
echo "Why: macOS /bin/bash is GNU bash 3.2; a script it cannot parse fails on every Mac (bun run verify included)." >&2
echo "Fix: read heredoc text with IFS= read -r -d '' VAR <<'EOF' || true instead of VAR=\$(cat <<'EOF' ... EOF), or rewrite the shape bash 3.2 rejects." >&2
-echo "See: docs/TESTING.md#bash-32-parse-guard" >&2
+echo "See: docs/ci-guards.md#bash-32-parse-guard" >&2
echo "" >&2
echo "✗ bash 3.2 parse: $errors error line(s) under $label" >&2
exit 1
diff --git a/scripts/check-durable-flush.ts b/scripts/check-durable-flush.ts
index 8631c93c00..2acff4dae6 100644
--- a/scripts/check-durable-flush.ts
+++ b/scripts/check-durable-flush.ts
@@ -1,6 +1,6 @@
#!/usr/bin/env bun
/**
- * Durable-flush guard (#5595, #5475; docs/TESTING.md#durable-flush-guard).
+ * Durable-flush guard (#5595, #5475; docs/ci-guards.md#durable-flush-guard).
*
* Windows `FlushFileBuffers` needs write access and Windows has no directory
* flush, so the POSIX idiom `fsyncSync(openSync(path, 'r'))` fails with EPERM
@@ -22,7 +22,7 @@ import { join, relative } from 'node:path';
import ts from 'typescript';
const ROOT = process.env.GBRAIN_GUARD_ROOT ?? join(import.meta.dir, '..');
-const ANCHOR = 'docs/TESTING.md#durable-flush-guard';
+const ANCHOR = 'docs/ci-guards.md#durable-flush-guard';
const HELPER = 'src/core/fs-durable.ts';
/** Files allowed to keep a read-only-handle flush until they migrate. Each entry names its reason; a stale entry fails. */
diff --git a/scripts/check-engine-sql-brands.ts b/scripts/check-engine-sql-brands.ts
index 1382faba00..e88825f399 100644
--- a/scripts/check-engine-sql-brands.ts
+++ b/scripts/check-engine-sql-brands.ts
@@ -1,7 +1,7 @@
#!/usr/bin/env bun
/**
* Engine-sql RLS brand guard (refactor wave 1, EO4 / AR2;
- * docs/TESTING.md#engine-sql-brands).
+ * docs/ci-guards.md#engine-sql-brands).
*
* src/core/engine-sql/brands.ts types each engine-sql read as `ScopedRead`
* (ran inside withScopedReadTransaction on master) or `LegacyUnscopedRead`
@@ -31,7 +31,7 @@ import { dirname, join, normalize, relative } from 'node:path';
import ts from 'typescript';
const ROOT = process.env.GBRAIN_GUARD_ROOT ?? join(import.meta.dir, '..');
-const ANCHOR = 'docs/TESTING.md#engine-sql-brands';
+const ANCHOR = 'docs/ci-guards.md#engine-sql-brands';
const BRANDS = 'src/core/engine-sql/brands.ts';
const BRAND_KEY = /__obtainVia\w*/;
const BRAND_TYPES = /\b(?:SqlExecutor|ScopedRead|LegacyUnscopedRead)\b/;
diff --git a/scripts/check-engine-sql-dynamic.ts b/scripts/check-engine-sql-dynamic.ts
index 626c7044cd..cb9487216b 100644
--- a/scripts/check-engine-sql-dynamic.ts
+++ b/scripts/check-engine-sql-dynamic.ts
@@ -1,7 +1,7 @@
#!/usr/bin/env bun
/**
* Engine-sql dynamic-SQL guard (refactor wave 1, A2b / CQ3 / EO8 / EO17;
- * docs/TESTING.md#engine-sql-dynamic-sql).
+ * docs/ci-guards.md#engine-sql-dynamic-sql).
*
* In src/core/engine-sql/** every value reaches SQL as a bound parameter
* (`sqlFragment`), and only constant text is spliced. This guard parses each
@@ -35,7 +35,7 @@ import ts from 'typescript';
const ROOT = process.env.GBRAIN_GUARD_ROOT ?? join(import.meta.dir, '..');
const SCAN_DIR = 'src/core/engine-sql';
-const ANCHOR = 'docs/TESTING.md#engine-sql-dynamic-sql';
+const ANCHOR = 'docs/ci-guards.md#engine-sql-dynamic-sql';
const EXEMPT_FILES: Record<string, string> = {
'fragment.ts': 'the renderer itself: it writes the $n placeholders and splices trustedSql text by design',
diff --git a/scripts/check-engine-sql-ratchet.ts b/scripts/check-engine-sql-ratchet.ts
index 5566bf3fe8..d43d480530 100644
--- a/scripts/check-engine-sql-ratchet.ts
+++ b/scripts/check-engine-sql-ratchet.ts
@@ -1,6 +1,6 @@
#!/usr/bin/env bun
/**
- * Engine-sql ratchet (refactor wave 1, goal (a); docs/TESTING.md#engine-sql-ratchet).
+ * Engine-sql ratchet (refactor wave 1, goal (a); docs/ci-guards.md#engine-sql-ratchet).
*
* Each storage domain's SQL lives once, in src/core/engine-sql/<domain>.ts,
* and both engines delegate to it. This guard keeps SQL from growing back
@@ -50,7 +50,7 @@ const tsInternal = ts as typeof ts & { getTokenAtPosition(sourceFile: ts.SourceF
const ROOT = process.env.GBRAIN_GUARD_ROOT ?? join(import.meta.dir, '..');
const BASELINE_REL = 'scripts/engine-sql-baseline.tsv';
-const ANCHOR = 'docs/TESTING.md#engine-sql-ratchet';
+const ANCHOR = 'docs/ci-guards.md#engine-sql-ratchet';
const FACADES = ['src/core/pglite-engine.ts', 'src/core/postgres-engine.ts'];
const MODULE_DIRS = ['src/core/pglite-engine', 'src/core/postgres-engine'];
const MARKER = 'engine-sql-ok';
diff --git a/scripts/check-layering.ts b/scripts/check-layering.ts
index 2b9cae11c2..4df3452259 100644
--- a/scripts/check-layering.ts
+++ b/scripts/check-layering.ts
@@ -1,6 +1,6 @@
#!/usr/bin/env bun
/**
- * Layering guard (refactor wave 1, EO10; docs/TESTING.md#layering-guard).
+ * Layering guard (refactor wave 1, EO10; docs/ci-guards.md#layering-guard).
*
* The wave's new directories sit BELOW the modules that load them, so an
* import back up would create an ESM cycle that can hit a temporal-dead-zone
@@ -25,7 +25,7 @@ import { dirname, join, normalize, relative } from 'node:path';
import ts from 'typescript';
const ROOT = process.env.GBRAIN_GUARD_ROOT ?? join(import.meta.dir, '..');
-const ANCHOR = 'docs/TESTING.md#layering-guard';
+const ANCHOR = 'docs/ci-guards.md#layering-guard';
interface Rule {
dir: string;
diff --git a/scripts/check-page-body-readers.ts b/scripts/check-page-body-readers.ts
index 630e30a4bc..19ee377c85 100644
--- a/scripts/check-page-body-readers.ts
+++ b/scripts/check-page-body-readers.ts
@@ -1,7 +1,7 @@
#!/usr/bin/env bun
/**
* Page body reader ratchet (Wave B segmented storage, spec 1.5 layer 4;
- * docs/TESTING.md#page-body-readers).
+ * docs/ci-guards.md#page-body-readers).
*
* A segmented page keeps its body in segments: `pages.compiled_truth` and
* `pages.timeline` are NULL, and `rowToPage` / the snapshot readers give the
@@ -57,7 +57,7 @@ import { isSqlText } from './check-engine-sql-ratchet.ts';
const ROOT = process.env.GBRAIN_GUARD_ROOT ?? join(import.meta.dir, '..');
const BASELINE_REL = 'scripts/page-body-readers-baseline.tsv';
-const ANCHOR = 'docs/TESTING.md#page-body-readers';
+const ANCHOR = 'docs/ci-guards.md#page-body-readers';
const BODY_FIELDS = new Set(['compiled_truth', 'timeline']);
const BODY_CALLS = new Set(['serializePageToMarkdown', 'serializeMarkdown', 'contentHash', 'prepareMarkdownChunks', 'pageDocument',
'refreshPageBody', 'putPage']);
diff --git a/scripts/check-retired-phrases.sh b/scripts/check-retired-phrases.sh
index ff0211037c..0dcc3b024e 100644
--- a/scripts/check-retired-phrases.sh
+++ b/scripts/check-retired-phrases.sh
@@ -69,7 +69,7 @@ while IFS=$'\t' read -r pattern fix; do
echo "FAIL: $file:$line retired phrase \"$match\"" >&2
echo "Why: refactor wave 1 retired this workflow; agents follow these docs literally and would edit the wrong file." >&2
echo "Fix: rewrite the sentence to the current instruction: $fix" >&2
- echo "See: docs/TESTING.md#retired-phrase-guard" >&2
+ echo "See: docs/ci-guards.md#retired-phrase-guard" >&2
done < <(grep -rnIE "$pattern" "${SCAN[@]}" 2>/dev/null || true)
done <<< "$RETIRED"
diff --git a/scripts/check-windows-hide.ts b/scripts/check-windows-hide.ts
index 74dd49d061..faa501b8d8 100644
--- a/scripts/check-windows-hide.ts
+++ b/scripts/check-windows-hide.ts
@@ -1,6 +1,6 @@
#!/usr/bin/env bun
/**
- * Windows hidden-console guard (#4992; docs/TESTING.md#windows-hidden-console-guard).
+ * Windows hidden-console guard (#4992; docs/ci-guards.md#windows-hidden-console-guard).
*
* On Windows a detached gbrain child has no console, so every console program
* it launches without `windowsHide` opens a visible console window that takes
@@ -26,7 +26,7 @@ import { join, relative } from 'node:path';
import ts from 'typescript';
const ROOT = process.env.GBRAIN_GUARD_ROOT ?? join(import.meta.dir, '..');
-const ANCHOR = 'docs/TESTING.md#windows-hidden-console-guard';
+const ANCHOR = 'docs/ci-guards.md#windows-hidden-console-guard';
const SEAM = 'src/core/spawn.ts';
const MODULES = new Set(['child_process', 'node:child_process']);
diff --git a/scripts/engine-sql-baseline.tsv b/scripts/engine-sql-baseline.tsv
index a5e54b6801..25c05fa525 100644
--- a/scripts/engine-sql-baseline.tsv
+++ b/scripts/engine-sql-baseline.tsv
@@ -7,7 +7,7 @@
# (`bun scripts/check-engine-sql-ratchet.ts --prune` drops stale rows). A new
# SQL-bearing engine member never gets a row: move the SQL, or mark it
# `// engine-sql-ok: <reason>`.
-# docs/TESTING.md#engine-sql-ratchet
+# docs/ci-guards.md#engine-sql-ratchet
migrated chunks
migrated cjk-search
migrated code-edges
diff --git a/scripts/llms-config.ts b/scripts/llms-config.ts
index ab27754e17..8ce212d8c8 100644
--- a/scripts/llms-config.ts
+++ b/scripts/llms-config.ts
@@ -50,7 +50,8 @@ export const SECTIONS: DocSection[] = [
{ title: "Memory boundaries", path: "docs/guides/memory-boundaries.md", description: "Durable shared preferences versus harness state; remote graph maintenance, provider text disclosure, authorization and full-backup limits; large pages (segmented storage up to 256 MiB on Postgres, append_page / gbrain append, upload sessions, windowed reads, limits per entry point).", includeInFull: false },
{ title: "Page history", path: "docs/guides/page-history.md", description: "Why a page changed: an optional reason on page writes, replaced_because in get_versions, the gbrain-reason commit trailer, remote visibility and repo-less brains.", includeInFull: false },
{ title: "Brain versus session memory", path: "docs/guides/brain-vs-memory.md", description: "Route durable facts and preferences to shared memory, configuration to the harness, and temporary work to session state.", includeInFull: false },
- { title: "Connect a hosted brain", path: "docs/guides/hosted-harness-access.md", description: "Getting the HTTPS endpoint (`gbrain mcp expose`, admin token file), host-side grants, private credential handoff, harness installation, profile repair, delegation limits and honest verification." },
+ // Linked, not inlined: it applies only once a brain already runs on another machine, and AGENTS.md (inlined) routes those agents to it; dropping it gave the bundle room under FULL_SIZE_BUDGET.
+ { title: "Connect a hosted brain", path: "docs/guides/hosted-harness-access.md", description: "Getting the HTTPS endpoint (`gbrain mcp expose`, admin token file), host-side grants, private credential handoff, harness installation, profile repair, delegation limits and honest verification.", includeInFull: false },
{ title: "Harness adapter reference", path: "docs/guides/harness-adapters.md", description: "Registry-generated transport, authentication lifetime and configuration facts.", includeInFull: false },
{ title: "Harness validation evidence", path: "docs/guides/harness-validation.md", description: "Local lifecycle and HTTP/worker proof, reproducible tests, and the remaining actual-harness acceptance checks.", includeInFull: false },
],
diff --git a/scripts/page-body-readers-baseline.tsv b/scripts/page-body-readers-baseline.tsv
index b16ed18506..5c74ab92e3 100644
--- a/scripts/page-body-readers-baseline.tsv
+++ b/scripts/page-body-readers-baseline.tsv
@@ -10,7 +10,7 @@
# its row (`bun scripts/check-page-body-readers.ts --prune` drops stale rows).
# A new whole-body reader never gets a row: use the segment reader, a bounded
# lead (boundedBodyPrefixSql), body_bytes or content_hash instead.
-# docs/TESTING.md#page-body-readers
+# docs/ci-guards.md#page-body-readers
src/cli/main.ts formatResult field STREAM renders a get_page result body; segmented bodies stream in PR 2
src/cli/page-render.ts asOfExitCode field NONE not the page body: tests whether a get_page as_of reply carries compiled_truth (a wire result, not a Page); a segmented edition replies with window, tested first
src/cli/page-render.ts formatGetPage call:serializeMarkdown SEGW
diff --git a/test/fixtures/guards/check-engine-sql-ratchet.ts/bad-duplicate/scripts/engine-sql-baseline.tsv b/test/fixtures/guards/check-engine-sql-ratchet.ts/bad-duplicate/scripts/engine-sql-baseline.tsv
index 810dfaee82..3b5d97b19d 100644
--- a/test/fixtures/guards/check-engine-sql-ratchet.ts/bad-duplicate/scripts/engine-sql-baseline.tsv
+++ b/test/fixtures/guards/check-engine-sql-ratchet.ts/bad-duplicate/scripts/engine-sql-baseline.tsv
@@ -1,3 +1,3 @@
-# Guard self-test fixture baseline (see docs/TESTING.md#engine-sql-ratchet).
+# Guard self-test fixture baseline (see docs/ci-guards.md#engine-sql-ratchet).
method src/core/postgres-engine.ts PostgresEngine.getPage
method src/core/postgres-engine.ts PostgresEngine.getPage
diff --git a/test/fixtures/guards/check-engine-sql-ratchet.ts/bad-empty-marker/scripts/engine-sql-baseline.tsv b/test/fixtures/guards/check-engine-sql-ratchet.ts/bad-empty-marker/scripts/engine-sql-baseline.tsv
index 31bd9b1a23..510d460734 100644
--- a/test/fixtures/guards/check-engine-sql-ratchet.ts/bad-empty-marker/scripts/engine-sql-baseline.tsv
+++ b/test/fixtures/guards/check-engine-sql-ratchet.ts/bad-empty-marker/scripts/engine-sql-baseline.tsv
@@ -1,2 +1,2 @@
-# Guard self-test fixture baseline (see docs/TESTING.md#engine-sql-ratchet).
+# Guard self-test fixture baseline (see docs/ci-guards.md#engine-sql-ratchet).
method src/core/postgres-engine.ts PostgresEngine.getPage
diff --git a/test/fixtures/guards/check-engine-sql-ratchet.ts/bad-migrated/scripts/engine-sql-baseline.tsv b/test/fixtures/guards/check-engine-sql-ratchet.ts/bad-migrated/scripts/engine-sql-baseline.tsv
index 1a20cf68f5..ffe7d357da 100644
--- a/test/fixtures/guards/check-engine-sql-ratchet.ts/bad-migrated/scripts/engine-sql-baseline.tsv
+++ b/test/fixtures/guards/check-engine-sql-ratchet.ts/bad-migrated/scripts/engine-sql-baseline.tsv
@@ -1,3 +1,3 @@
-# Guard self-test fixture baseline (see docs/TESTING.md#engine-sql-ratchet).
+# Guard self-test fixture baseline (see docs/ci-guards.md#engine-sql-ratchet).
migrated takes
method src/core/postgres-engine.ts PostgresEngine.getPage
diff --git a/test/fixtures/guards/check-engine-sql-ratchet.ts/bad-stale/scripts/engine-sql-baseline.tsv b/test/fixtures/guards/check-engine-sql-ratchet.ts/bad-stale/scripts/engine-sql-baseline.tsv
index e167944bb4..2108f758ba 100644
--- a/test/fixtures/guards/check-engine-sql-ratchet.ts/bad-stale/scripts/engine-sql-baseline.tsv
+++ b/test/fixtures/guards/check-engine-sql-ratchet.ts/bad-stale/scripts/engine-sql-baseline.tsv
@@ -1,3 +1,3 @@
-# Guard self-test fixture baseline (see docs/TESTING.md#engine-sql-ratchet).
+# Guard self-test fixture baseline (see docs/ci-guards.md#engine-sql-ratchet).
method src/core/postgres-engine.ts PostgresEngine.getPage
method src/core/postgres-engine.ts PostgresEngine.removedMethod
diff --git a/test/fixtures/guards/check-engine-sql-ratchet.ts/bad/scripts/engine-sql-baseline.tsv b/test/fixtures/guards/check-engine-sql-ratchet.ts/bad/scripts/engine-sql-baseline.tsv
index 47cda3389a..ec84b129ec 100644
--- a/test/fixtures/guards/check-engine-sql-ratchet.ts/bad/scripts/engine-sql-baseline.tsv
+++ b/test/fixtures/guards/check-engine-sql-ratchet.ts/bad/scripts/engine-sql-baseline.tsv
@@ -1,3 +1,3 @@
-# Guard self-test fixture baseline (see docs/TESTING.md#engine-sql-ratchet).
+# Guard self-test fixture baseline (see docs/ci-guards.md#engine-sql-ratchet).
migrated facts
method src/core/postgres-engine.ts PostgresEngine.getPage
diff --git a/test/fixtures/guards/check-engine-sql-ratchet.ts/good/scripts/engine-sql-baseline.tsv b/test/fixtures/guards/check-engine-sql-ratchet.ts/good/scripts/engine-sql-baseline.tsv
index 47cda3389a..ec84b129ec 100644
--- a/test/fixtures/guards/check-engine-sql-ratchet.ts/good/scripts/engine-sql-baseline.tsv
+++ b/test/fixtures/guards/check-engine-sql-ratchet.ts/good/scripts/engine-sql-baseline.tsv
@@ -1,3 +1,3 @@
-# Guard self-test fixture baseline (see docs/TESTING.md#engine-sql-ratchet).
+# Guard self-test fixture baseline (see docs/ci-guards.md#engine-sql-ratchet).
migrated facts
method src/core/postgres-engine.ts PostgresEngine.getPage
diff --git a/test/scripts/check-bash32.test.ts b/test/scripts/check-bash32.test.ts
index 0fac8acc7c..1d28a0e48d 100644
--- a/test/scripts/check-bash32.test.ts
+++ b/test/scripts/check-bash32.test.ts
@@ -79,7 +79,7 @@ describe('check-bash32.sh reporting (parser shim)', () => {
expect(r.stderr).not.toContain('also-bad.sh');
expect(r.stderr).toMatch(/^Why: {2}macOS \/bin\/bash is GNU bash 3\.2/m);
expect(r.stderr).toContain("Fix: read heredoc text with IFS= read -r -d '' VAR <<'EOF' || true");
- expect(r.stderr).toContain('See: docs/TESTING.md#bash-32-parse-guard');
+ expect(r.stderr).toContain('See: docs/ci-guards.md#bash-32-parse-guard');
});
it('refuses an explicit GBRAIN_BASH32 that is not bash 3.x', () => {
diff --git a/test/scripts/check-page-body-readers.test.ts b/test/scripts/check-page-body-readers.test.ts
index c1f43a2ee6..ee3fe9805b 100644
--- a/test/scripts/check-page-body-readers.test.ts
+++ b/test/scripts/check-page-body-readers.test.ts
@@ -97,7 +97,7 @@ describe('check-page-body-readers.ts: baseline rules', () => {
['src/core/reader.ts\treadBody\tfield\tINLINE\t']));
expect(r.code).toBe(1);
expect(r.out).toContain('src/core/new.ts:2 new page body reader in grow (field)');
- expect(r.out).toContain('See: docs/TESTING.md#page-body-readers');
+ expect(r.out).toContain('See: docs/ci-guards.md#page-body-readers');
});
test('a removed reader leaves a stale row that fails; --prune drops it and nothing else', () => {
diff --git a/test/scripts/check-retired-phrases.test.ts b/test/scripts/check-retired-phrases.test.ts
index 4b6f07fa00..738d1deb5b 100644
--- a/test/scripts/check-retired-phrases.test.ts
+++ b/test/scripts/check-retired-phrases.test.ts
@@ -66,7 +66,7 @@ describe('check-retired-phrases.sh', () => {
expect(r.stderr).toContain(`FAIL: docs/guides/x.md:3 retired phrase "${match}"`);
expect(r.stderr).toMatch(/^Why: {2}\S/m);
expect(r.stderr).toMatch(/^Fix: {2}rewrite the sentence to the current instruction: \S/m);
- expect(r.stderr).toContain('See: docs/TESTING.md#retired-phrase-guard');
+ expect(r.stderr).toContain('See: docs/ci-guards.md#retired-phrase-guard');
});
}
diff --git a/test/scripts/durable-flush-guard.test.ts b/test/scripts/durable-flush-guard.test.ts
index 67fe5c880d..d0e9339f20 100644
--- a/test/scripts/durable-flush-guard.test.ts
+++ b/test/scripts/durable-flush-guard.test.ts
@@ -40,7 +40,7 @@ describe('check-durable-flush.ts', () => {
expect(r.code).toBe(1);
expect(r.out).toContain('FAIL [durable_flush_read_handle]: src/core/persistence/writer.ts:');
expect(r.out).toContain('Fix: fsync the descriptor you wrote through before closing it, or call flushFile/flushDirectory from src/core/fs-durable.ts');
- expect(r.out).toContain('See: docs/TESTING.md#durable-flush-guard');
+ expect(r.out).toContain('See: docs/ci-guards.md#durable-flush-guard');
});
test('write-descriptor flushes, fs-durable itself and same-named descriptors in other functions pass', () => {
diff --git a/test/scripts/engine-sql-brands.test.ts b/test/scripts/engine-sql-brands.test.ts
index 1f4fef1bf7..150b0cdb56 100644
--- a/test/scripts/engine-sql-brands.test.ts
+++ b/test/scripts/engine-sql-brands.test.ts
@@ -35,7 +35,7 @@ function expectFail(files: Record<string, string>, where: string, what: string)
const r = run(files);
expect(r.code).toBe(1);
expect(r.out.split('\n').find((l) => l.startsWith(`FAIL: ${where} `))).toContain(what);
- for (const label of ['Fix:', 'Why:', 'See: docs/TESTING.md#engine-sql-brands']) expect(r.out).toContain(label);
+ for (const label of ['Fix:', 'Why:', 'See: docs/ci-guards.md#engine-sql-brands']) expect(r.out).toContain(label);
}
describe('check-engine-sql-brands.ts: brand keys', () => {
diff --git a/test/scripts/engine-sql-dynamic.test.ts b/test/scripts/engine-sql-dynamic.test.ts
index fd8e157a9e..1569248caf 100644
--- a/test/scripts/engine-sql-dynamic.test.ts
+++ b/test/scripts/engine-sql-dynamic.test.ts
@@ -65,7 +65,7 @@ describe('check-engine-sql-dynamic.ts: rejected forms', () => {
const lastLine = PRELUDE.split('\n').length + body.split('\n').length - 1;
const failLine = r.out.split('\n').find((l) => l.startsWith(`FAIL: src/core/engine-sql/domain.ts:${lastLine} `));
expect(failLine).toContain(what);
- for (const label of ['Fix:', 'Why:', 'See: docs/TESTING.md#engine-sql-dynamic-sql']) expect(r.out).toContain(label);
+ for (const label of ['Fix:', 'Why:', 'See: docs/ci-guards.md#engine-sql-dynamic-sql']) expect(r.out).toContain(label);
});
});
diff --git a/test/scripts/engine-sql-ratchet.test.ts b/test/scripts/engine-sql-ratchet.test.ts
index a4681396da..7323965dc0 100644
--- a/test/scripts/engine-sql-ratchet.test.ts
+++ b/test/scripts/engine-sql-ratchet.test.ts
@@ -73,7 +73,7 @@ describe('check-engine-sql-ratchet.ts: SQL structure detection', () => {
'truncate', 'updateAliasSet', 'withCte',
]);
expect(r.out).toContain('FAIL: src/core/pglite-engine/facts.ts:1 new SQL-bearing engine member selectAcrossPieces');
- for (const label of ['Fix: put the SQL in src/core/engine-sql/facts.ts and delegate', 'Why:', 'See: docs/TESTING.md#engine-sql-ratchet']) {
+ for (const label of ['Fix: put the SQL in src/core/engine-sql/facts.ts and delegate', 'Why:', 'See: docs/ci-guards.md#engine-sql-ratchet']) {
expect(r.out).toContain(label);
}
});
diff --git a/test/scripts/layering.test.ts b/test/scripts/layering.test.ts
index 6ad8605039..79ef61b95e 100644
--- a/test/scripts/layering.test.ts
+++ b/test/scripts/layering.test.ts
@@ -40,7 +40,7 @@ describe('check-layering.ts', () => {
const r = run({ 'src/core/engine-sql/facts.ts': line + '\n' });
expect(r.code).toBe(1);
expect(r.out).toContain('FAIL: src/core/engine-sql/facts.ts:1 imports src/core/');
- for (const label of ['Fix:', 'Why:', 'See: docs/TESTING.md#layering-guard']) expect(r.out).toContain(label);
+ for (const label of ['Fix:', 'Why:', 'See: docs/ci-guards.md#layering-guard']) expect(r.out).toContain(label);
});
test('schema-migrations: any import of migrate.ts fails, including from a nested dir', () => {
diff --git a/test/scripts/windows-hide-guard.test.ts b/test/scripts/windows-hide-guard.test.ts
index b226620f3e..2b5842480c 100644
--- a/test/scripts/windows-hide-guard.test.ts
+++ b/test/scripts/windows-hide-guard.test.ts
@@ -45,7 +45,7 @@ describe('check-windows-hide.ts', () => {
expect(r.out).toContain(`FAIL [windows_hide_direct_child_process]: src/commands/new-command.ts:`);
expect(r.out).toContain(what);
expect(r.out).toContain('Fix: import it from src/core/spawn.ts, which defaults windowsHide: true');
- expect(r.out).toContain('See: docs/TESTING.md#windows-hidden-console-guard');
+ expect(r.out).toContain('See: docs/ci-guards.md#windows-hidden-console-guard');
});
test.each([