Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

Fix lane P: core memory and frontmatter re-import read segmented pages whole up to 24 MiB (decision #1)

garrytan3cbc69cb458a
diff --git a/docs/architecture/key-files/core-memory.md b/docs/architecture/key-files/core-memory.md
index 21dc5dfd7b..3fb72b4c9f 100644
--- a/docs/architecture/key-files/core-memory.md
+++ b/docs/architecture/key-files/core-memory.md
@@ -9,7 +9,10 @@ notice). User guide: [core memory](../../guides/core-memory.md).
- `src/core/core-memory.ts`: marking and priority normalization, settings
(`memory.core.*`), page rendering and budget accounting, `listCorePages`
- (withdrawal-aware), `renderCoreBlock` (whole-page truncation, notice lines,
+ (withdrawal-aware; a page stored in segments is read back whole up to 24 MiB,
+ through `materializedSnapshot` when withdrawn, and a larger one is left out
+ unread and counted by doctor `core_memory` as `skipped_segmented`,
+ `test/large-pages/segmented-core-list.test.ts`), `renderCoreBlock` (whole-page truncation, notice lines,
withheld lines), `coreRevision`, the delivery sensitivity policy
(`applyCoreSensitivity`: credential-like hits withhold, contact details and
private paths redact) and `loadCoreBlock`, which every delivery lane uses.
diff --git a/docs/architecture/key-files/core-utilities-2.md b/docs/architecture/key-files/core-utilities-2.md
index 2a2ccf84d2..e02d2ec02b 100644
--- a/docs/architecture/key-files/core-utilities-2.md
+++ b/docs/architecture/key-files/core-utilities-2.md
@@ -18,7 +18,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
- `src/core/repair/fences.ts` — `gbrain repair fences` (#6188), preview-bound, `spends: 'llm'`, not explicit-only (no destructive consent). Candidates: the fence census (`listFenceCandidates` after a bounded `runFenceCensus`, `GBRAIN_FENCE_REPAIR_SCAN_MS`, default 10 s) filtered by `--only`/`--skip <path>` and `--slug <slug>`, plus files or pages the selection names that the census has not judged. Per candidate (`fence-repair/repair-io.ts` reads the current bytes): a host that may not write the source is skipped with the owner condition as its reason (`host_mismatch`, `transfer_in_progress`, `clone_in_progress`, `incarnation_changed`, `local_path_missing`, `coordination_path_missing`; `owner_unavailable` is the fallback; the skip's detail carries `why`, the read-only fix and `retryable`), a candidate a write in flight or an unfinished sync's frozen manifest still names is `sync_in_progress` (#6278: checked at plan, at apply and again at the write's admission in `file-repair.ts`; the rest of the source repairs while the sync runs, and a held path is not busy); `analyzeFences` (`repair-tiers.ts`) decides `proposal` (Tier 1 or Tier 2, validated, a fixed point, the exact diff), `llm` (only Tier 3 residuals: `fences.repair.llm`/`--no-llm` → `llm_disabled`, a page whose tags its file lacks → `canonical_overlay` before any spend, no measured model with a key and `models.fence_repair` unset → `no_measured_model`, an unpriced model under a user cap → `no_pricing`, under the default caps a warn-and-run notice naming `gbrain pricing set`, 0 caps or an estimate over `fences.repair.max_usd_per_page` → `budget_exhausted`, an attempt memo already rejected for these bytes → its stored verdict at $0) or `manual` with the exact location-only edit. The model is `resolveFenceRepairModel` (`fence-repair/model.ts`: `models.fence_repair`, else the first measured model with a key, else none). The preview saves the approved set (`previewHash` over sources, selection and each item's location, bytes hash, revision, tier and after-hash) and prints `apply_command` with `--expect`; `--apply --expect` replays it (`changed_since_preview` for moved bytes or revision), a bare `--apply` applies the current plan starting after the last candidate the previous bare run touched (`fence-repair-rotation`). Apply refuses a remote caller (`trusted_cli_required`) and runs Tier 3 through `runTier3` (ledger reservation, attempt claim, a corrective re-ask only after gate (a) or (e)); a daily-ledger refusal stops the run (`budget_exhausted`, D15: spent and cap, reset time, pages waiting, `gbrain config set fences.repair.max_usd_per_day <usd>` with consent `paid`). Outcomes `repaired` / `held` (FenceReason, also written to the hold with `recordFenceHoldRepair`) / `skipped`; `report` adds `repaired`, `remaining` by reason (an `--expect` apply re-checks the selection for what stays held) and `verification` (`FenceRepairVerification`: repaired per tier, held per reason, oldest hold, USD per Tier 3 repair). Tests: `test/repair-fences.test.ts` (PGLite and Postgres), `test/fence-repair-llm.test.ts`.
- `src/core/repair/content-lane.ts` — the content-repair lane (#6377). `CONTENT_REPAIR_KINDS` is the ordered list of repair kinds that clear managed-sync content holds (today `fences`; the GBRA-72 integration appends `slug-conflicts`), read by `gbrain repair content` (`src/commands/repair-content.ts`), the `content_repair` cycle phase and `gbrain sync unblock --apply`, so a new kind plugs in with one entry. `CONTENT_REPAIR_HOLD_KINDS` maps a hold code to the kind that clears it (`invalid_fence` → `fences`; `frontmatter_slug_conflict` → `null` until Lane B's kind lands, which keeps the surfaces' refusal text). `runContentLane(engine, scope, { apply, kinds?, only, skip, expect?, noLlm, maxLlmUsd, deadline, registry? })` has no rule logic: it runs each kind through `repairRunner` in order, passing the run's paid allowance minus what earlier kinds spent (read from each result's `cost.llm_usd`; the daily ledger is `FENCE_REPAIR_LEDGER` for every kind) and one absolute deadline (a `time_budget` stop ends the pass; any other stop lets the next kind run), and returns per-kind results, each kind's own `preview_hash` (no combined hash: `--expect` is one hash per kind in lane order, `parseContentLaneExpect` refuses a wrong count with `invalid_params` before any kind runs), the lane's spend and remaining allowance, and `apply_command` (`contentLaneArgv`). A preview plans every kind before any mutation; `--apply --expect` binds each kind to its approved set; a bare apply runs each kind's own plan-and-apply (`changed_since_read` binding, held reasons recorded on the holds). `contentHoldDisposition(record, auto)` reads a hold's stored repair state (`fenceHoldStatus` for a fence hold; `meta.content_repair.action` for a slug-conflict hold, read loosely) and says whether an unattended surface may run the kind (`repair`), must list it (`listed`: `needs_human` for a manual reason or a recommended merge, `paid`, `owner`) or has no kind for it (`unsupported`). Output is counts, codes, hashes and paths only. Tests: `test/cycle-content-repair.test.ts` (stub kinds), `test/repair-content.test.ts` (the real `fences` kind through the CLI).
- `src/core/repair/slug-conflicts.ts` — `gbrain repair slug-conflicts` (#6377, Lane B), the lane kind that clears `frontmatter_slug_conflict` holds: preview-bound, `spends: 'llm'`, `checks: []` (doctor keeps `git_held_files` on `frontmatter`), not explicit-only. Candidates are the source's slug-conflict holds (plus `--only <path>`); identity is resolved, not textual: the frontmatter slug is normalized the way the screen does and resolved through `slug_aliases` to a page id in the same source (a slug resolving to the held file's own page is exempt; a held file with no page yet is a normal candidate). Deterministic tier (`remove_slug`, confidence high): the named slug resolves to no page and names no other file, or to a page of a different type sharing no title token; the one-line edit publishes through the frontmatter repair's coordinated path (`prepareRepairPublication` / `submitManagedFileRepair`: bytes bound to the sha256 the preview read, import, hold clear and Git effect in one write). Every verdict uses managed sync's own screen (`sync-screen.ts` `loadSyncScreenRun` + `frozenImportScreenInput` + `screenFrozenContent`, on the file's bytes and on the edited bytes): a held file the screen now admits as it is (its line is clean, or names the file's own page as written) is planned as `import` and published unchanged through `submitManagedFileRepair` with an `import` receipt and `holdObservedAt` (the hold observation the plan read; a newer hold is kept and the hold records a `changed_since_read` retry); a file sync would hold whatever the lane writes (the page it is filed as carries another slug than its path, or the line reaches the own page only through an alias) is held `slug_page_mismatch` with both slugs (`named` on the hold). Everything else goes to the model tier (`src/core/content-repair/judgment.ts`): `remove_slug` applies the same way, `merge_into <canonical>` and `needs_human` are recorded on the hold as codes and slugs only (`recordContentHoldRepair`, `meta.content_repair`) and rendered by `sync status` as `needs_human` paragraphs; nothing merges pages. Caps and ledger are the fence repair's (`FENCE_REPAIR_LEDGER`, `fences.repair.max_usd_per_page` / `_per_day`, `fences.repair.llm`, `--no-llm`, `--max-usd`); the receipt is a `content_repair` receipt (action, tier, confidence, model, cost, before/after sha256) carried by the write and the commit trailer `gbrain-repair: <hold_code> <tier> <confidence>`. Tests: `test/repair-slug-conflicts.test.ts`, `test/repair-slug-conflicts-sync-screen.test.ts`.
-- `src/core/repair/frontmatter.ts` — `gbrain repair frontmatter` (#5988), explicit-only, preview-bound, destructive consent (`--yes` with the hash, registry `consent`). #5966 (W14 P1.7): the slug rule itself is `slugStampedFrontmatter(slug, fm)` in `src/core/markdown.ts` (stamps `slug:` when the path cannot derive it, such as a doubled hyphen, and replaces a foreign `fm.slug`; used by `serializePageToMarkdown` and `commands/export.ts`, digest-neutral since `parseMarkdown` drops `fm.slug`); `slugStampCandidate` proposes a SAFE `slug:` stamp for a well-formed file at a page's recorded `source_path` whose path derives another slug and that declares none (a legacy render of a slug the path cannot derive), inserted as `serializeMarkdown` writes it; never normalizes or guesses. Scope: Git-visible `.md`/`.mdx` per source (managed owner root or legacy `local_path`) plus every Git hold row; database side, pages whose body begins with an embedded frontmatter block or whose title is the humanized slug while the file names one. `frontmatterCandidates` builds a safe rewrite (NUL strip, nested-quote swap, `repairRecoverableFrontmatter` quoting; parsed values must be unchanged) and an interpretive one (`autoFixFrontmatter` missing close / slug line, fold, dup, unclosed, `#` rescue); both must strict-parse with no hold. `prepareRepairPublication` binds each proposal to the page fields its import would store; a refusal or canonical overlay is `needs_review`. The hash covers sources, `include_ambiguous`, `--only`/`--skip`, and per file before/after sha256, page id/revision, result digest and `rename_from`; the approved set stores no frontmatter text. An `invalid_fence` hold is listed with a resolution that defers to `gbrain repair fences --source <id> --only <path>` (frontmatter repair never changes fences). Apply refuses while an unfinished managed sync cursor names a selected path, re-derives each change, then publishes through `managed_file_repair` (managed) or backup, write, `importFromFile`, hold clear and a printed commit step (legacy). Tests: `test/repair-frontmatter.test.ts`. Wave B decision #10: the preview and the apply count the source's pages stored in segments (one COUNT; their stored head is NULL, so the embedded-block check skips them) as residual `skipped_segmented` plus a `skipped (segmented): N` warning, absent at 0 (`test/large-pages/doctor-skipped-segmented.test.ts`).
+- `src/core/repair/frontmatter.ts` — `gbrain repair frontmatter` (#5988), explicit-only, preview-bound, destructive consent (`--yes` with the hash, registry `consent`). #5966 (W14 P1.7): the slug rule itself is `slugStampedFrontmatter(slug, fm)` in `src/core/markdown.ts` (stamps `slug:` when the path cannot derive it, such as a doubled hyphen, and replaces a foreign `fm.slug`; used by `serializePageToMarkdown` and `commands/export.ts`, digest-neutral since `parseMarkdown` drops `fm.slug`); `slugStampCandidate` proposes a SAFE `slug:` stamp for a well-formed file at a page's recorded `source_path` whose path derives another slug and that declares none (a legacy render of a slug the path cannot derive), inserted as `serializeMarkdown` writes it; never normalizes or guesses. Scope: Git-visible `.md`/`.mdx` per source (managed owner root or legacy `local_path`) plus every Git hold row; database side, pages whose body begins with an embedded frontmatter block or whose title is the humanized slug while the file names one. `frontmatterCandidates` builds a safe rewrite (NUL strip, nested-quote swap, `repairRecoverableFrontmatter` quoting; parsed values must be unchanged) and an interpretive one (`autoFixFrontmatter` missing close / slug line, fold, dup, unclosed, `#` rescue); both must strict-parse with no hold. `prepareRepairPublication` binds each proposal to the page fields its import would store; a refusal or canonical overlay is `needs_review`. The hash covers sources, `include_ambiguous`, `--only`/`--skip`, and per file before/after sha256, page id/revision, result digest and `rename_from`; the approved set stores no frontmatter text. An `invalid_fence` hold is listed with a resolution that defers to `gbrain repair fences --source <id> --only <path>` (frontmatter repair never changes fences). Apply refuses while an unfinished managed sync cursor names a selected path, re-derives each change, then publishes through `managed_file_repair` (managed) or backup, write, `importFromFile`, hold clear and a printed commit step (legacy). Tests: `test/repair-frontmatter.test.ts`. Wave B decision #10: the preview and the apply count the source's pages stored in segments (one COUNT; their stored head is NULL, so the embedded-block check skips them) as residual `skipped_segmented` plus a `skipped (segmented): N` warning, absent at 0 (`test/large-pages/doctor-skipped-segmented.test.ts`). Decision #1: the re-import's already-matches check reads a page stored in segments back whole (`materializedSnapshot`) up to 24 MiB; over it the file is `needs_review` with `page_body_segmented` (`pageBodyOverCeilingError`) before its publication is prepared (`test/large-pages/segmented-frontmatter-reimport.test.ts`).
- `src/core/persistence/mirror-read-only.ts` and `src/commands/sources-mirror.ts` — #5409 read-only mirror sources. `sourceMirrorReadOnly(engine, sourceId)` reads `sources.config.mirror_read_only` (default false). When true, `prepareFileTarget` (`page-prepare.ts`) returns no file for any coordinated page write into the source (receipt `write_through.skipped: 'mirror_read_only'`, `storage: 'database_only'`, set in `coordinator.ts`), and managed sync (`sync-prepare.ts`) imports an overlay (canonical form differs from the file bytes) database-only: no `file`, no newer-working-tree refusal, and `contentUnchanged` ignores the overlay. A page created that way with no recorded file is stamped `pages.database_only_reason='mirror_read_only'` (`classifyMirrorPage`, in the publication) and stays database-only after the flag is cleared; the coordinator refuses (`source_changed`) a file target prepared before the flag was set (rechecked under the publication with the source row `FOR SHARE`); `gitPage` (`effects.ts`) completes a mirror source's Git effects as skipped. `gbrain sources mirror-readonly|mirror-writable <id>` set and clear the key like `federate`/`unfederate`; `sources list --json` reports `mirror_read_only`.
- `src/core/restore-target.ts` -- `resolveRestoreTarget(engine, source, repo)`: the source and repo `gbrain export --restore-only` restores, shared with `gbrain storage status` so its printed restore command restores exactly the files it lists. An explicit source (already resolved) wins; a repo without a source selects the one active source registered at that exact path, refuses a repo registered only to an archived source, else selects the only active source; neither selects the flagless resolver chain's source and its `local_path` (the legacy `sync.repo_path` answers for `default` only). `restoreFilePath(repo, slug, sourcePath, sourcePathBytes, slugRootMode)` is the file whose absence makes the restore write a page: the recorded `source_path` resolved in the repo in the source's slug-root mode (`scannerSlugRootMode`), else `<slug>.md`; an over-long or unsafe recorded path throws. Refusals throw `RestoreTargetError`; resolver and database errors propagate unchanged.
diff --git a/docs/architecture/key-files/google-and-loops-continued.md b/docs/architecture/key-files/google-and-loops-continued.md
index 93c88a0738..31cf03a2f0 100644
--- a/docs/architecture/key-files/google-and-loops-continued.md
+++ b/docs/architecture/key-files/google-and-loops-continued.md
@@ -17,7 +17,7 @@
- **`src/core/persistence/sync-lanes.ts`** + **`worktree-lease.ts`** — #5984 lanes. The drain opens a lane policy for its worktree (`openLanes`, keyed by a per-drain run id that lane groups carry as `intent.lane`; `closeLaneRun` at drain end stops new lane claims and waits up to 90 s for the lane tasks still running, counted from the head's claim by `laneTask`). While it is open, this process's consumer claims the next admitted lane group head out of FIFO order (`claimNextLaneHead` in journal.ts: every earlier request claimed, any unfinished one a running request of the same run) up to the effective lane count (`laneRoots`), and runs it as a lane (`executeClaimedGroup` with `lane`). Lane publications share the worktree's native lock in this process (`acquireWorktreeShared` / `worktree-lease.ts`; one lane acquires the lock while lanes arriving meanwhile wait and join, and a lease stays registered until its lock is released); every exclusive `acquireWorktree` first yields the lease (marks it draining and wounded, waits up to its budget), and a lease drains for new claims after `LEASE_TURN_MS` of continuous holding. Lane transactions begin in manifest order (`awaitLaneBegin`) and commit in manifest order (`awaitLaneTurn`, inside the transaction before the counters: the predecessor `intent.after` must have ended, committed or not (#6712); a requeued or unadmitted one releases it, a wounded lease or 60 s rolls it back). Publication validation accepts a lane group whose predecessor is still queued or running (`windowPredecessorAllows`). `laneFallback` in group-publish.ts releases or falls back to the single path (#6712: never cancels), and a lock or statement timeout steps the lane count down (`stepDownLanes`). Lane settings (`--lanes`/`--no-lanes` > `GBRAIN_SYNC_LANES` > `sync.lanes` > 6, clamped to the pool's long-hold capacity minus 3) resolve in `resolveBulkSettings` (sync-group.ts); with lanes the drain keeps twice the lane count of groups admitted ahead (`admitAhead`).
- **`src/core/persistence/sync-run.ts`** + **`sync-authority.ts`** — one immutable request at a time, bounded fairness and pinned-target resumption. A completed discovery that finds nothing to do (`up_to_date`) stamps only `sources.last_sync_at`, inside `withCoordinatedWrite` and guarded by source id and incarnation, so a quiet managed source stays fresh in doctor and a run that outlived a re-added source stamps nothing; dry runs and partial runs do not stamp. Cursors and requests freeze `noEmbed`, `noExtract` and `noSchemaPack`. #6712 PR 1: a resume inherits the cursor's processing opt-outs OR-wise (`adoptCursor`, one CAS that also stamps the resumer's validated authority) and reports a flag it overrode in `inherited_options`; nothing refuses over processing options, and `explicitProcessing` is gone. Admitted requests keep their own intent principal: they are read under it (`admittedBy`), and a writer change drops only unadmitted frozen entries. Every managed pass runs under the source's drain lease (`withDrainLease`, `src/core/persistence/sync-lease.ts`), whose token fences admission, the settled/held CAS, fan-in and the cursor CAS (`assertDrainLease`). Explicit idle ordinary-source retry creates fresh discovery/admission and retains terminal receipts, also when the run has a recorded failure and its pending write already committed before the cursor advanced; company consent retry retains its approved manifest/run. Active work blocks replacement. Claimed/inactive sync, including connector/company dispatch, remains refused: existing leases and native locks do not fence already-running engine-only legacy writers. No automatic activation or new transition protocol. `freezeEntry` checks a rename's source page (id, revision, origin) as well as its target slug, and a committed rename counts in `renamed`. #5522: a new-file entry (`pageId: null`) whose origin another cursor of the source has since imported is re-frozen against that page when it is live, holds exactly that origin at the entry's slug in the cursor's incarnation, and the sync preparer finds its content unchanged; otherwise the origin refusal stands, and the manifest is never rewritten. #5751: the working-tree screen passes the kernel waivers for working-tree entries and counts them into `legacySkips` (printed by `sync-diagnostics.ts` with `gbrain repair contextual-mode`). A terminal `checkpoint_validation_timeout` receipt gets its hint from `checkpoint-validation.ts`. Content holds (#5988, `sync-screen.ts`): `freezeEntry` screens each import (company-profile cursors and `sync.holds=fail` excepted); a refused file becomes a hold written in the same transaction as the cursor step (`saveCursor`'s `inTx`), with no request admitted, and an over-bound pinned blob is held by size before it is read. A cursor whose pending request failed with a content refusal (`isContentRefusal`, old message shapes included) converts in place with its stored options: held, or re-frozen once per distinct bytes (`converted`), so a refusal the screen misses stays blocked without minting receipts. #6188: a failed fence refusal (`fenceReceiptLocation`: the durable `error_detail.fence`, the message, or an older release's message) holds the same bytes even when the screen admits them (`prepareTimeFenceHold`, reason `prepare_time`); a compacted `invalid_params` / `take_row_collision` receipt converts only when the re-screen holds. A page request of the run that fails with a fence refusal is held in the same invocation at the terminal-failure branch (single path and a bulk group's failed member) after the source's other requests settle within the run's wait budget, else the run returns `partial`; it is converted once, gets no failure-ledger row and is logged as a conversion. `sync.holds=fail` and company-profile cursors keep blocking with the typed refusal. #6278: a `preparation_stalled` receipt (the owner gave up preparing a member) is converted the same way by both converters: an import holds by its bytes, a delete as a delete hold (`meta.deleted`, `upstream_version` null), the checkpoint never holds; `preparationStalledHold` (sync-screen.ts) records the receipt's step and the resume arguments. Both converters write their hold through `holdUnderGate`, the narrowed gate: the failed entry's admitted suffix (window, later group members, this run's queued lane rows) is cancelled first, then the hold waits only for active suffix descendants and unfinished requests naming the entry's page (`UNFINISHED_PAGE_REQUEST_SQL`, now matching path and origin too), evaluated inside the transaction that writes the hold under the page-key → cursor lock order; its doc comment states the invariant the old source-wide wait protected. The cursor's `breaker` counts the run's stalled receipts (identities and streak, saved with each CAS): `holdsEscalated`'s rule over the run's screened imports or `BREAKER_STREAK` (5) in a row trips it, the run stops `blocked_by_failures` with `SyncResult.breaker` (drain `preparation_systemic`), and the next run's `convertBlockedCursor` re-freezes the entry and schedules the run's stalled holds for a re-screen instead of holding; a committed page resets the streak. `sameContentAtOrigin` and the waiver screens race the sync preparer against `persistence.sync_preparation_ms` (`raceSyncBudget`, sync-waivers.ts) and fail open. Tests: `test/managed-sync-preparation-stalled-holds.test.ts`, `test/sync-waiver-budget.test.ts`. Results carry this run's holds, the outstanding total, escalation, `converted_from_failed` and `recovered_frontmatter` (`buildHoldReport`); dry runs list `would_hold` / `screen_skipped`. After the checkpoint commits the pass stamps drain step `finish` and emits `managed_sync.finish`; then (unless `noExtract`) the owner derives links for the source's stale pages through `links-maintenance.ts` under `FINISH_BUDGET_MS` (pages left over stay stale for `gbrain extract --stale`), so a PGLite-delegated sync and a Postgres sync take the same path; the result carries `links`, and an extraction failure leaves pages stale without failing the committed sync. #6278 (B7): when the checkpoint commits while `sources retry-held` re-screens are scheduled for the source (scheduled against a backlog, or while this cursor ran), the pass returns `partial` / `writer_yield` instead of `synced`, so the drain's next pass retires the finished cursor and discovers again, taking them; a `queue_capacity` refused for outstanding requests (`isWriteCapacityWait`) is left out of the failure ledger because the drain waits it out. #6696: the cursor key comes from `selectManagedCursor` (`sync-cursor-key.ts`), which every managed caller crosses: a run without `--strategy` and without a company plan keys a fresh cursor with the source's configured strategy, while an unfinished cursor under the raw key keeps resuming under it, so its admitted requests keep matching. `SyncOpts.embedDeferred` (the cost gate's auto-defer) is frozen on the intent and treated as `noEmbed` by preparation, never as a processing option a resume adopts or compares (`test/persistence-sync-cursor-strategy-6696.test.ts`).
- **`src/core/persistence/sync-holds.ts`** + **`sync-screen.ts`** + **`sync-blobs.ts`** — Git holds (#5988). One `op_checkpoints` row per held file (`sync-hold`, fingerprint `source:incarnation:path`) plus a per-source `sync-hold-summary` row (`count`, and `stale`: holds whose page exists); `writeGitHold` / `clearGitHold` lock the summary row and are conditional on the writing run's discovery time (`observed_at`), so an older run never replaces or clears a newer hold. Managed and legacy sync write the same rows; `readGitSourceHolds` (current incarnation only) feeds `retry-held` and legacy sync, and `readGitHoldListing` (count from the summary row, rows limited per source in SQL) feeds `sources status`, never `readAllSourceHolds`. `recordSyncConversion` logs each blocked request a managed run converted in place (`sync-conversions`, newest 20 per source, in the transaction that saves the converted cursor); `sources status` shows the newest 5. `gitHoldItem` gives every surface code, reason, key, line, location-only message, `fix` Action and `docs` anchor. #6188 `invalid_fence` holds carry `meta.fence` (reason, fence, section, rows, columns, section line), the file line of the first bad row (`meta.line`, from `fenceFileLine` when the screen holds it), `fence_version` and the last repair attempt (`fence_repair`); the summary row counts them (`fences`), and `holdRepairSteps` is the one router (D6) every surface prints: fence and slug-conflict holds (`HoldRepairRoute.fences` + `slug_conflicts`) preview the content-repair lane, `gbrain repair content --source <id>` (`contentRepairArgv`, #6377; the text says the next maintenance run repairs the fence and slug-conflict holds it can by itself when `FenceAutoRepair.active`), other holds preview `gbrain repair frontmatter`, a mixed source names both; one fence hold's own fix stays that file's `gbrain repair fences --only <path>` preview (`fenceHoldFix`). One fence hold's fix (`gitHoldFix` → `fence-repair/hold-fix.ts` `fenceHoldFix`) is that file's `--only <path>` preview with the step its state calls for, and `gitHoldItem` carries the D16 `fence` object (classes, tier, `auto_retry`, `next_attempt_after`); callers that can read the maintenance state pass it (`fenceAutoRepairFor`). `holdRescreenDue` is the one re-screen predicate managed discovery and legacy sync share (retry request, database-dependent codes, an older frontmatter reader or fence screen). Policy keys: `sync.holds` (`hold`/`fail`), `sync.hold_cap` (detail shown, default 500), `sync.hold_escalate_count` (50), `sync.hold_escalate_pct` (5, from 40 screened imports), `sync.parser_regression` (`stop`/`hold`). #6278: `preparation_stalled` holds carry `meta.stall` (request, step, `waiting_on`, attempts, the writing gbrain version, the sync's resume arguments) and count under `stalled` in the summary row and `HoldRepairRoute`; `gitHoldFix` routes them to `gbrain sources writer status --source <id> --json`, then `sources retry-held`, then the option-preserving sync (`stalledHoldSteps`), never to frontmatter repair, and `holdRescreenDue` re-screens them on a gbrain version change; `buildHoldReport` routes the escalation text by code. `sync-import-provenance` records (`recordSyncImportProvenance`, batched `recordSyncImportProvenances`) also carry `disk_sha256` / `disk_blob_oid` (the bytes the write left on disk), `revision` and `parser` (`syncImportParser`: `SYNC_IMPORT_PARSER_VERSION`, Markdown chunker, schema pack; never the release); records from before them, or from a repair, lack them and readers take them as unknown. `screenFrozenImport` builds its input with `frozenImportScreenInput` (rename base, the run's pack, sanity and purge tombstones) and screens it with `screenFrozenContent`, both shared with the slug-conflict repair so it judges a held file exactly as the next sync would; it admits a fence Tier 1 fixes (`fences.normalize`, read once per run only when needed; the dry run lists it in `would_normalize`), turns a refusal into a hold, or throws `sync_parser_regression` only when `sync-import-provenance` proves a validating gbrain imported the same bytes. `sync-blobs.ts` reads blob ids/sizes with chunked `ls-tree -l` and contents with `cat-file --batch`; `freezeEntry` reads each entry's pinned blob and content through `readPinnedBlob` / `readPinnedContent` (via `sync-screen.ts` `pinnedBlob` / `pinnedContent`): a miss lists that entry and up to 255 of the next committed imports in one `ls-tree` and loads their contents (8 MiB slices cut by window position, not read order; over-bound blobs excluded) in one `cat-file --batch`, kept per (Git root, full commit id) until the next window, so a managed first sync spawns a few Git processes per window instead of an `ls-tree` and a `git show` per page; a non-commit target, a window git refuses to list, or a blob the window cannot answer falls back to the per-entry read (`__setPinnedWindowForTests(0)` restores per-entry reads; `test/managed-sync-pinned-reads.test.ts` proves identical rows on PGLite and Postgres). `held-reads.ts` is the read side: `get_page.file_held`, `stale` on search/query hits and the `held_files` retrieval meta and notice, from one lookup by page id (`op_checkpoints_sync_hold_page_idx`, migration v200) and one summary read per call, cached per request; `stalled` coverage routes a `preparation_stalled` hold to the host operator's writer-status fix instead of a file repair; remote callers get codes and counts, never paths, and a fix addressed to the brain host operator (a held fence page gets `fenceHoldRelay`: the owner-host command and whether it clears by itself). Tests: `test/sync-holds-store.test.ts`, `test/persistence-sync-holds.test.ts`, `test/sync-all-hold-notes.test.ts`, `test/held-read-signals.test.ts`. #5493/#6529: managed discovery admits image imports whenever multimodal embedding is on (company plans refuse). Off, `freezeEntry` holds each image import as `managed_image_sync_unsupported` (`managedImageHold`, dry-run screen too) before any content read, whatever `sync.holds` says: the rest of the source imports, the hold is keyed by the pinned blob (or working bytes), and `holdRescreenDue` re-screens it on change, removal, multimodal on or `sources retry-held`. On, `freezeEntry` freezes the bytes as base64 (`pinnedImageBytes`, `frozenImageIntent`), an oversize image takes `oversizeHold`, identical bytes are a no-op by hash, and `sync-prepare.ts` routes the entry to `sync-image.ts`. The summary row counts `images`; those holds never count toward `holds_escalated` or `git_held_files`.
-- **`src/core/persistence/file-repair.ts`** — `managed_file_repair` (#5988), the owner-internal `put_page` kind `gbrain repair frontmatter --apply` submits (accepted only from the trusted local CLI with `managedFileImport`; MCP is refused by the reserved-field gate, remote authority by the preparer). `managedRepairRoot` resolves the owner through `checkOwner` (`owner-refusal.ts`) and refuses `owner_unavailable` with the condition as its reason; `submitManagedFileRepair` re-reads the source's `RepairBusySet` (`repair-busy.ts`) right before admission and refuses `sync_in_progress` when a write in flight or an unfinished sync's frozen manifest names the path, origin, slug or a rename endpoint (#6278: a sync can start while a fence repair waits on its model call). The preparer confines the path (`isWriteTargetContained` plus a component-wise `lstat` walk, no symlinks), requires the file's sha256 to equal the previewed `beforeHash` (`changed_since_preview` otherwise), recomputes `prepareRepairPublication` (the `screenSyncImport` + `importFromContent` preparation a managed sync import gets) and refuses a different result digest or a canonical overlay. It publishes the exact bytes as `file` (`expectedBeforeHash` = previewed hash; no `file_database_drift` check), applies the import (a held new file creates its page, a `renameFrom` moves the page with `updateSlug`), clears the Git hold (only while it is the `holdObservedAt` observation when the intent carries one, so a hold a newer sync wrote stays) and records `sync-import-provenance` in the same transaction; the file write queues the Git target effect. A fence repair (`gbrain repair fences`) passes its `FenceRepairReceipt` as `fenceRepair`: submission and the preparer refuse (`invalid_params`, nothing written) a receipt `parseFenceRepairReceipt` rejects or whose `before_sha256`/`after_sha256` are not the previewed and written bytes; the outcome carries it as `fence_repair`, the file target carries the commit note from `fenceRepairCommit` (`effect-model.ts`), and every refusal and fix names `gbrain repair fences --source <id>` instead of `gbrain repair frontmatter` (`FileRepairKind`, also taken by `confinedRepairTarget` and `managedRepairRoot`). Tests: `test/repair-frontmatter.test.ts`, `test/fence-repair-receipts.test.ts`.
+- **`src/core/persistence/file-repair.ts`** — `managed_file_repair` (#5988), the owner-internal `put_page` kind `gbrain repair frontmatter --apply` submits (accepted only from the trusted local CLI with `managedFileImport`; MCP is refused by the reserved-field gate, remote authority by the preparer). `managedRepairRoot` resolves the owner through `checkOwner` (`owner-refusal.ts`) and refuses `owner_unavailable` with the condition as its reason; `submitManagedFileRepair` re-reads the source's `RepairBusySet` (`repair-busy.ts`) right before admission and refuses `sync_in_progress` when a write in flight or an unfinished sync's frozen manifest names the path, origin, slug or a rename endpoint (#6278: a sync can start while a fence repair waits on its model call). The preparer confines the path (`isWriteTargetContained` plus a component-wise `lstat` walk, no symlinks), requires the file's sha256 to equal the previewed `beforeHash` (`changed_since_preview` otherwise), recomputes `prepareRepairPublication` (the `screenSyncImport` + `importFromContent` preparation a managed sync import gets) and refuses a different result digest or a canonical overlay. It publishes the exact bytes as `file` (`expectedBeforeHash` = previewed hash; no `file_database_drift` check), applies the import (a held new file creates its page, a `renameFrom` moves the page with `updateSlug`), clears the Git hold (only while it is the `holdObservedAt` observation when the intent carries one, so a hold a newer sync wrote stays) and records `sync-import-provenance` in the same transaction; the file write queues the Git target effect. An import of a segmented body seals itself, so the inline text seal is skipped and its `afterCommit` is forwarded. A fence repair (`gbrain repair fences`) passes its `FenceRepairReceipt` as `fenceRepair`: submission and the preparer refuse (`invalid_params`, nothing written) a receipt `parseFenceRepairReceipt` rejects or whose `before_sha256`/`after_sha256` are not the previewed and written bytes; the outcome carries it as `fence_repair`, the file target carries the commit note from `fenceRepairCommit` (`effect-model.ts`), and every refusal and fix names `gbrain repair fences --source <id>` instead of `gbrain repair frontmatter` (`FileRepairKind`, also taken by `confinedRepairTarget` and `managedRepairRoot`). Tests: `test/repair-frontmatter.test.ts`, `test/fence-repair-receipts.test.ts`.
- **`src/core/persistence/sync-prepare.ts`** — guarded raw fingerprint/revision, source root and active coordinator checks before preparation and at locked publication. A Markdown import's preparation carries `importProvenance` (`SyncPreparedMutation`); its publication writes it in the publish transaction with the page id, `revision` and the disk half (`syncDiskProvenance` over the canonical writeback, else `syncDiskBytes`), and a no-op waiver writes the same record instead. The checkpoint (`applyManagedSyncCheckpoint`) keeps a repository-root source's pinned slug mode (`sync-slug-mode.ts`). Old imports/checkpoints without durable processing consent refuse under their original IDs; old deletions require their immutable origin manifest and a still-matching page origin. `noEmbed` suppresses the effect itself; `noSchemaPack` bypasses pack loading; optional extraction stays disabled, but mandatory provider-free canonical projections remain. A filename-derived slug mismatch is accepted on every platform only when the page's stored canonical path is this file and the parsed slug is that page's slug; a different declared slug still refuses. CRLF equivalence never weakens raw CAS. No uncoordinated filesystem writes. The checkpoint validates receipts through `checkpoint-validation.ts` and, for a run whose entries another cursor imported (`overtaken`, #5522), also commits when that cursor already checkpointed the same target. Markdown imports pass `screenSyncImport` (the already-published working-tree exemption, then `screenImportContent` with the expected slug and recorded-origin exemption), the same screen the freeze-time hold screen runs, so a file is held exactly when publication would refuse it. Each import, deletion and no-op apply clears the path's Git hold (`holdObservedAt`), the checkpoint clears `releasedHolds` and ignores `supersededRequests` (failed content refusals the run converted in place), and every Markdown import records `sync-import-provenance` (raw sha256, blob, gbrain version, quoting recoveries) and reports `recovered_frontmatter` / `comment_value` in its outcome. Tests: `persistence-sync-origin-native.serial.test.ts`, `persistence-sync-options.serial.test.ts`, `persistence-sync-company.serial.test.ts`. A same-slug `renameFrom` accepts the page's recorded old origin. A different-slug rename prepares against the page where it stands, locks the old slug as an additional page key, and at publication moves the page with `updateSlug` (same id, inbound links and history, `old -> new` in `slug_aliases`, withdrawn claims follow), re-infers an implicit type from the new path, then re-prepares and applies the file content at the new slug, so the move never writes back to the file. Tests: `persistence-managed-lifecycle.test.ts`. `syncGitTopLevel` answers the checkout's `git rev-parse --show-toplevel` once per root and sync run, reading it again when the top level's `.git` entry is replaced or removed or a `.git` appears between it and the root. #6278: `prepareManagedSyncMutation` calls `enterClaimStep` at each await boundary (`managed_sync_active`, `authority`, `worktree_binding`, `configured_root`, `knowledge_publication`, `manifest_entry`, `git_rev_parse`, `origin_check`, `page_snapshot`, `import_screen`, `import_content`, `canonical_projections` and the rest, each naming `git`, `fs` or `db` where it knows), so a stall reports its step; the consumer's budget and the cancellation reaching those boundaries are in persistence-stalls.md. An intent with `embedDeferred` (#6696) prepares as `noEmbed` whatever the cursor's stored options say.
- **`src/core/persistence/links-maintenance.ts`** — `extractManagedStaleLinks` (then the mention pass unless `mentions: false`, which sync passes) derives links for pages whose extraction watermark is stale with `prepareAutomaticLinks` (put_page's replace contract; other producers' edges stay) and adds the coordinator's unrecorded canonical timeline tuples (insert-only) and each page's watermark in the same `withCoordinatedWrite` transaction, bound to the revision it read; an edited page or unresolved attendance stays stale. A page skipped for unresolved attendance is marked attendance-blocked at that revision (`pages.links_attendance_blocked_revision` / `_at`, written by `markPagesAttendanceBlocked` in `engine-sql/pages.ts` only while the revision still matches, cleared by `markPagesExtractedBatch` with the watermark); it is still reconsidered every run, and the `links_extraction_lag` doctor check counts it apart from lag while the marker equals the page's current revision. It is the one managed extraction path: managed sync, `extractStaleFromDB` on a managed brain, and the owner delegation all run it. `runManagedStaleExtraction` backs `gbrain extract --stale` on managed brains, locally or through the `writer_extract_stale` administration operation inside a PGLite owner (`src/commands/extract-stale-delegate.ts`, trusted CLI registration only). `links-preparation.ts` retargets a link written against a renamed page's old slug to the live canonical page through `slug_aliases`, as `get_page` does. Tests: `persistence-managed-lifecycle.test.ts`, `persistence-sync-stdio-owner.serial.test.ts`.
- **`src/core/persistence/sync-authority.ts`** — trusted CLI or original remote generic job authority; rejects stdio bulk privilege promotion and runtime option expansion, intersects original grants with current principal/source policy.
diff --git a/docs/guides/memory-boundaries.md b/docs/guides/memory-boundaries.md
index 64552c5cb6..4896a9a637 100644
--- a/docs/guides/memory-boundaries.md
+++ b/docs/guides/memory-boundaries.md
@@ -203,6 +203,12 @@ Those checks say how many such pages they passed by: `oversized_pages`,
`skipped_segmented` and a warning) for the stored bodies it does not check;
it still checks their files. An `ok` from such a check covers only the pages
it read. The field is absent when no page is stored in segments.
+Core memory reads a core page stored in segments back whole up to 24 MiB,
+as it reads an inline page, so `core_memory` counts only the core pages over
+24 MiB, which core leaves out of every session and of its budget. A
+frontmatter re-import of a page stored in segments works the same way up to
+24 MiB; over it the file is listed `needs_review` with `page_body_segmented`
+and nothing is written.
While the switch is off (unset in this release, set to `off`, or held by an
older writer), new pages are stored inline up to 24 MiB as before.
diff --git a/src/commands/doctor/checks/core-memory.ts b/src/commands/doctor/checks/core-memory.ts
index b5b0c8a750..4ce2abf0fe 100644
--- a/src/commands/doctor/checks/core-memory.ts
+++ b/src/commands/doctor/checks/core-memory.ts
@@ -17,6 +17,7 @@ import {
import { PRESSURE_CONFIG_KEYS, validatePressureConfigValue } from '../../../core/context/pressure.ts';
import { readHeartbeatTail } from '../../../core/context/hook-heartbeat.ts';
import { compiledCoreRevision, readCompiledCoreRecords } from '../../../core/context/compiled-core.ts';
+import { PAGE_MAX_BYTES } from '../../../core/page-size-policy.ts';
import { existsSync, readFileSync } from 'node:fs';
const DELIVERY_WINDOW_MS = 7 * 24 * 60 * 60 * 1000;
@@ -24,9 +25,9 @@ const DELIVERY_WINDOW_MS = 7 * 24 * 60 * 60 * 1000;
export async function coreMemoryCheck(engine: BrainEngine): Promise<Omit<Check, 'name'>> {
const settings = await readCoreSettings(engine);
const usage = await coreUsage(engine);
- // Decision #10: core usage reads each page's compiled_truth, which is NULL on a page stored in segments.
+ // Decision #10: listCorePages reads a page stored in segments back whole up to PAGE_MAX_BYTES (24 MiB) and leaves a larger one out.
const [segmented] = await engine.executeRaw<{ n: number }>(`SELECT COUNT(*)::int AS n FROM pages p
- WHERE p.deleted_at IS NULL AND p.frontmatter @> '{"always_load": true}'::jsonb AND p.body_storage = 'segmented'`).catch(() => []);
+ WHERE p.deleted_at IS NULL AND p.frontmatter @> '{"always_load": true}'::jsonb AND p.body_storage = 'segmented' AND p.body_bytes > $1`, [PAGE_MAX_BYTES]).catch(() => []);
const skipped = Number(segmented?.n ?? 0);
const problems: string[] = [];
const badConfig: string[] = [];
diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.ts
index 147a47f7c7..52ffafb9f7 100644
--- a/src/core/behavior-change-notice.ts
+++ b/src/core/behavior-change-notice.ts
@@ -735,6 +735,7 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText }
{ since: 'TBD', text: 'Doctor checks that read whole page bodies now report the pages stored in segments they did not check, instead of passing them by silently: `oversized_pages`, `scraper_junk_pages`, `markdown_body_completeness`, `link_resolution_opportunity`, `fence_integrity`, `core_memory` and `extract_health` (its facts-backlog overlay) carry `skipped_segmented: N` in `gbrain doctor --json` and end their message with `skipped (segmented): N`. `gbrain repair frontmatter` reports the same count in its preview and apply (residual `skipped_segmented` and a warning). Nothing is added for a brain with no page stored in segments, so its doctor and repair output is unchanged.' },
{ since: 'TBD', text: 'Semantic writes on a page stored in segments (`pages.segmented_storage` on): `add_tag` and `remove_tag` now work at any page size as a metadata change (the tag rows, `content_hash` and a version; no segment, chunk or embedding is rewritten), and a page backed by a file gets the new frontmatter in that file with its body unchanged; an `external_untrusted` writer, whose write gate scans the whole body, takes the put path below. `add_timeline_entry`, `takes_add` / `takes_update` / `takes_supersede` / `takes_resolve` / `takes_remove`, the facts fence write of `extract_facts`, `gbrain core add` / `remove` / `diff` and `gbrain sources reconcile` now read a segmented page up to 24 MiB back whole and write it as a normal put, with the result an inline page with the same body gets. Above 24 MiB they still refuse with `page_body_segmented` (wire error `invalid_params` for the memory verbs, not retryable), and the refusal now names the 24 MiB limit.' },
{ since: 'TBD', text: '`revert_version` of a page stored in segments, or to a version stored in segments, is refused with `page_body_segmented` (reason `segmented_revert`) before anything is written; it arrives with the segment writer in a later release. With `pages.segmented_storage` on, this includes pages between 1 MiB and 24 MiB that `revert_version` restores today. The versions stay readable: `get_versions` lists them, and a versioned `get_page` window reads one. Write the content you want back with `put_page`.' },
+ { since: 'TBD', text: 'Core memory and `gbrain repair frontmatter` on a page stored in segments (`pages.segmented_storage` on): a core page (`always_load: true`) stored in segments up to 24 MiB is now read back whole and rendered, budgeted and listed as its inline twin is; before, it counted as its title alone, and once a fact was withdrawn from it (or a `*` withdrawal existed in its source) session-start core, `context_pack`, `gbrain core status` and every core page write failed with `page_body_segmented`. A core page over 24 MiB is left out of core and doctor `core_memory` counts it (`skipped_segmented`), which now counts only those. `gbrain repair frontmatter --include-ambiguous` re-imports a page stored in segments up to 24 MiB whose title was derived from its slug, as it re-imports an inline page; over 24 MiB the file is listed `needs_review` with `page_body_segmented`, naming the 24 MiB limit, and nothing is written. Before, either case failed the whole preview.' },
];
/** The newest disclosed change's release: the notice id moves only when a release adds rows. */
diff --git a/src/core/cli-flag-registry.generated.ts b/src/core/cli-flag-registry.generated.ts
index 183ff54d13..b8c6087659 100644
--- a/src/core/cli-flag-registry.generated.ts
+++ b/src/core/cli-flag-registry.generated.ts
@@ -73,7 +73,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {
'graph-query': ['--brain', '--depth', '--direction', '--help', '--hop', '--include-foreign', '--json', '--mcp-only', '--source', '--type'],
'hook': ['--allow-unverified-remote', '--auto', '--batch-check', '--brain', '--branch', '--cached', '--count', '--diff-filter', '--enable', '--end-of-options', '--env', '--get', '--harness', '--help', '--jq', '--json', '--limit', '--name-only', '--others', '--pat-file', '--path', '--porcelain', '--pure', '--quiet', '--remove', '--seat', '--session', '--show-current', '--show-toplevel', '--since', '--source', '--yes'],
'import': ['--accept-pending', '--admin-intent', '--allow-empty', '--allow-noncanonical-root', '--apply', '--background', '--brain', '--cached', '--confirm-relocated-root', '--diff-filter', '--dim', '--embedding-dimensions', '--embedding-model', '--empty', '--exclude', '--exclude-standard', '--expected-epoch', '--expected-state', '--explain', '--follow', '--force', '--force-rechunk', '--format', '--fresh', '--help', '--include-gitignored', '--is-shallow-repository', '--json', '--log-noop', '--manifest', '--name-only', '--no-accept-pending', '--no-embed', '--no-embedding', '--no-gpg-sign', '--no-pull', '--no-renames', '--no-verify', '--only', '--others', '--path', '--probe', '--progress-interval', '--progress-json', '--quiet', '--self-transfer', '--show-toplevel', '--skip-failed', '--slugs', '--source', '--source-id', '--stale', '--status', '--supabase', '--timeout', '--to', '--url', '--verify', '--wait', '--workers'],
- 'init': ['--access', '--acknowledge-managed', '--adopt', '--aliases', '--all', '--allow-create-db', '--allow-docker', '--apply', '--assign-corpus', '--audit', '--auto', '--background', '--bound-slug-prefixes', '--brain', '--break-lock', '--budget-ms', '--budget-usd', '--chat-model', '--check', '--clear-never-installed', '--confirm-relocated-root', '--conflicts', '--content-root', '--db-only', '--dest', '--detach', '--dim', '--disable', '--drain', '--embedding-dimensions', '--embedding-model', '--enable', '--expand', '--expansion-model', '--expect', '--expect-remote', '--facts', '--fast', '--fix', '--force', '--force-retry', '--from-meetings', '--full', '--git', '--grant-types', '--group-by', '--harness', '--held', '--help', '--http', '--id', '--images', '--include-frontmatter', '--include-gitignored', '--issuer-url', '--json', '--keep', '--key', '--lanes', '--limit', '--list', '--local-postgres', '--markdown', '--max-usd', '--mcp-only', '--mcp-url', '--migrate-only', '--migration', '--model', '--no-autopilot-install', '--no-autostash', '--no-delegate', '--no-embed', '--no-embedding', '--no-expand', '--no-extract', '--no-git', '--no-llm', '--no-probe', '--no-pull', '--no-repair', '--no-schema-pack', '--non-interactive', '--oauth-client-id', '--oauth-client-secret', '--once', '--only', '--oversized', '--page', '--params', '--pat-file', '--path', '--pglite', '--phase', '--plan', '--prefer', '--prefer-postgres', '--preview', '--probe', '--profile', '--provenance', '--providers', '--pull', '--purge', '--push-only', '--query', '--question', '--quiet', '--rebase', '--reference-date', '--remediate', '--remove', '--repair-unknown-markers', '--reset', '--resolve', '--resume', '--retry-failed', '--save', '--schema-pack', '--scope', '--scopes', '--search-mode', '--section', '--self-transfer', '--semantic', '--show-toplevel', '--skip', '--skip-embed-check', '--skip-failed', '--slug', '--slugs', '--source', '--source-id', '--stale', '--state', '--status', '--supabase', '--surface', '--tier', '--timeout', '--to', '--token', '--touchpoint', '--url', '--url-env', '--user', '--version', '--wait', '--warn-only', '--workspace', '--yes'],
+ 'init': ['--access', '--acknowledge-managed', '--adopt', '--aliases', '--all', '--allow-create-db', '--allow-docker', '--apply', '--assign-corpus', '--audit', '--auto', '--background', '--bound-slug-prefixes', '--brain', '--break-lock', '--budget-ms', '--budget-usd', '--chat-model', '--check', '--clear-never-installed', '--confirm-relocated-root', '--conflicts', '--content-root', '--db-only', '--dest', '--detach', '--dim', '--disable', '--drain', '--embedding-dimensions', '--embedding-model', '--enable', '--expand', '--expansion-model', '--expect', '--expect-remote', '--facts', '--fast', '--fix', '--force', '--force-retry', '--from-meetings', '--full', '--git', '--grant-types', '--group-by', '--harness', '--held', '--help', '--http', '--id', '--images', '--include-ambiguous', '--include-frontmatter', '--include-gitignored', '--issuer-url', '--json', '--keep', '--key', '--lanes', '--limit', '--list', '--local-postgres', '--markdown', '--max-usd', '--mcp-only', '--mcp-url', '--migrate-only', '--migration', '--model', '--no-autopilot-install', '--no-autostash', '--no-delegate', '--no-embed', '--no-embedding', '--no-expand', '--no-extract', '--no-git', '--no-llm', '--no-probe', '--no-pull', '--no-repair', '--no-schema-pack', '--non-interactive', '--oauth-client-id', '--oauth-client-secret', '--once', '--only', '--oversized', '--page', '--params', '--pat-file', '--path', '--pglite', '--phase', '--plan', '--prefer', '--prefer-postgres', '--preview', '--probe', '--profile', '--provenance', '--providers', '--pull', '--purge', '--push-only', '--query', '--question', '--quiet', '--rebase', '--reference-date', '--remediate', '--remove', '--repair-unknown-markers', '--reset', '--resolve', '--resume', '--retry-failed', '--save', '--schema-pack', '--scope', '--scopes', '--search-mode', '--section', '--self-transfer', '--semantic', '--show-toplevel', '--skip', '--skip-embed-check', '--skip-failed', '--slug', '--slugs', '--source', '--source-id', '--stale', '--state', '--status', '--supabase', '--surface', '--tier', '--timeout', '--to', '--token', '--touchpoint', '--url', '--url-env', '--user', '--version', '--wait', '--warn-only', '--workspace', '--yes'],
'integrations': ['--auto', '--brain', '--dry-run', '--help', '--json', '--overwrite', '--refresh', '--source', '--target'],
'integrity': ['--accept-pending', '--auto', '--backend', '--background', '--body', '--brain', '--check', '--confidence', '--cost', '--dry-run', '--explain', '--follow', '--fresh', '--help', '--json', '--limit', '--no-accept-pending', '--progress-interval', '--progress-json', '--quiet', '--review-lower', '--skip-bare-tweet', '--skip-urls', '--source', '--timeout', '--type', '--wait'],
'jobs': ['--abbrev-ref', '--access', '--acknowledge-managed', '--add', '--aliases', '--all', '--allow-empty', '--allow-shell-jobs', '--allowed-operations', '--apply', '--asof', '--auto', '--background', '--backoff-delay', '--backoff-jitter', '--backoff-type', '--batch-size', '--body', '--bound-slug-prefixes', '--brain', '--break-lock', '--by-mention', '--cached', '--catch-up', '--check', '--cli-path', '--client', '--cluster-errors', '--concurrency', '--confidence', '--confirm-destructive', '--cost-estimate', '--date', '--dated-since', '--days', '--delay', '--detach', '--diff-filter', '--dir', '--drain', '--dry-run', '--embedding-dimensions', '--embedding-model', '--empty', '--entities', '--exclude', '--exclude-standard', '--expect', '--explain', '--facts', '--federated-read', '--filters', '--fix', '--follow', '--force', '--force-break-lock', '--format', '--fresh', '--from-index', '--from-meetings', '--full', '--full-history', '--fuzzy', '--grammar-diagnostics', '--group', '--hard-deadline', '--health-interval', '--held', '--help', '--http', '--id', '--idempotency-key', '--ids', '--images', '--include-deleted', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--include-null-signature', '--infer-dates', '--inject-bootstrap', '--inline', '--input', '--install', '--interval', '--is-ancestor', '--is-shallow-repository', '--job-id', '--job-isolation', '--json', '--kind', '--lanes', '--limit', '--lock-duration-ms', '--log-noop', '--markdown', '--max-age', '--max-attempts', '--max-cost', '--max-cost-usd', '--max-crashes', '--max-rss', '--max-sources', '--max-stalled', '--max-usd', '--max-waiting', '--mcp-only', '--min-context', '--missing-path', '--model', '--multimodal', '--name-only', '--ner', '--nice', '--no-auto-embed', '--no-autopilot-install', '--no-bulk', '--no-confirm', '--no-delegate', '--no-embed', '--no-extract', '--no-gpg-sign', '--no-hard-deadline', '--no-inject', '--no-lanes', '--no-llm', '--no-pull', '--no-renames', '--no-repair', '--no-schema-pack', '--no-verify', '--no-worker', '--non-interactive', '--now', '--older-than', '--once', '--only', '--order', '--others', '--output', '--override-disabled', '--oversized', '--pace', '--pace-max-concurrency', '--pack', '--page', '--parallel', '--params', '--path', '--pause', '--phase', '--pid-file', '--prefer', '--priority', '--probe', '--prune-orphans', '--purge', '--queue', '--queue-only', '--quiet', '--reason', '--rebuild', '--recent', '--redact-secrets', '--reenrich-after', '--refresh-ms', '--refresh-operations', '--repo', '--reset-checkpoint', '--resume', '--retry-failed', '--retry-held', '--review-lower', '--row', '--scopes', '--segment-limit', '--select', '--serial', '--session', '--show-toplevel', '--sigkill-rescue', '--since', '--skip-bare-tweet', '--skip-failed', '--skip-urls', '--sleep', '--slug', '--slugs', '--source', '--source-id', '--sources', '--src-subpath', '--stale', '--status', '--strategy', '--surface', '--swap-only', '--target', '--thin', '--thin-threshold', '--timeout', '--timeout-ms', '--to', '--trust', '--type', '--types', '--uninstall', '--updated-after', '--url', '--user', '--vectors', '--verbose', '--verify', '--version', '--watch', '--wedge-rescue', '--workers', '--working-tree', '--yes'],
diff --git a/src/core/core-memory.ts b/src/core/core-memory.ts
index 9ed7a138d9..55e0ab2df9 100644
--- a/src/core/core-memory.ts
+++ b/src/core/core-memory.ts
@@ -24,6 +24,7 @@ import type { ReadEligibility } from './eligibility/policy.ts';
import { proactiveEligibility } from './eligibility/registry.ts';
import { activationSuppressedSql, pageEligibleSql } from './eligibility/sql.ts';
import { compactTrustLabel, needsDataEnvelope, renderTrustedText, trustFields } from './eligibility/labels.ts';
+import { PAGE_MAX_BYTES } from './page-size-policy.ts';
export const CORE_DEFAULT_MAX_CHARS = 4000;
export const CORE_MIN_MAX_CHARS = 500;
@@ -215,7 +216,7 @@ export function renderCoreBlock(input: readonly CorePage[], opts: RenderCoreBloc
};
}
-type RawExec = Pick<BrainEngine, 'executeRaw' | 'readPageSnapshot'>;
+type RawExec = BrainEngine;
export interface ListCorePagesOpts {
/** Restrict to these sources; omitted = every source in the brain. */
@@ -232,7 +233,8 @@ export interface ListCorePagesOpts {
eligibility?: ReadEligibility;
}
-interface CoreRow { source_id: string; slug: string; title: string | null; compiled_truth: string | null; frontmatter: unknown; withdrawn: boolean;
+interface CoreRow { id: number | string; source_id: string; slug: string; title: string | null; compiled_truth: string | null; frontmatter: unknown; withdrawn: boolean;
+ body_storage: string | null; body_bytes: number | string | null;
trust_tier?: string; write_origin?: unknown; suppressed?: boolean }
/**
@@ -256,19 +258,27 @@ export async function listCorePages(exec: RawExec, opts: ListCorePagesOpts = {})
const trustCols = policy
? `p.trust_tier, p.write_origin, ${policy.suppressFlagged ? activationSuppressedSql('pages', 'p') : 'false'} AS suppressed,` : '';
const rows = await exec.executeRaw<CoreRow>(
- `SELECT p.source_id, p.slug, p.title, p.compiled_truth, p.frontmatter, ${trustCols}
+ `SELECT p.id, p.source_id, p.slug, p.title, p.compiled_truth, p.frontmatter, p.body_storage, p.body_bytes, ${trustCols}
EXISTS (SELECT 1 FROM fact_withdrawals w WHERE w.source_id = p.source_id AND (w.subject = '*' OR w.subject = p.slug)) AS withdrawn
FROM pages p WHERE ${where.join(' AND ')} ORDER BY p.source_id, p.slug LIMIT ${CORE_MAX_PAGES * 4}`, params);
const pages: Array<CorePage & { suppressed?: boolean }> = [];
for (const r of rows) {
if (r.suppressed === true) { pages.push({ ...toCorePage({ source_id: r.source_id, slug: r.slug, title: r.title ?? r.slug, compiled_truth: '' }), suppressed: true }); continue; }
+ const segmented = r.body_storage === 'segmented';
+ // Wave B decision #1: a body stored in segments is read back whole up to PAGE_MAX_BYTES (24 MiB); a larger one
+ // is left out of the list, never read, and doctor's core_memory check reports it (skipped_segmented).
+ if (segmented && Number(r.body_bytes ?? 0) > PAGE_MAX_BYTES) continue;
let compiled = r.compiled_truth ?? '';
// Withdrawn facts (forget) are applied by the canonical snapshot read,
// not by the stored body, so core never shows text get_page withholds.
if (r.withdrawn) {
const snap = await exec.readPageSnapshot(r.slug, { sourceId: r.source_id, ...(opts.excludePrivate ? { excludePrivate: true } : {}) });
if (!snap) continue;
- compiled = snap.page.compiled_truth ?? '';
+ compiled = segmented
+ ? (await (await import('./persistence/segmented-apply.ts')).materializedSnapshot(exec, snap))!.page.compiled_truth ?? ''
+ : snap.page.compiled_truth ?? '';
+ } else if (segmented) {
+ compiled = (await (await import('./page-body/ingest.ts')).materializeSegmentedBody(exec, Number(r.id), r.source_id)).compiled_truth;
}
pages.push(toCorePage({
source_id: r.source_id, slug: r.slug, title: r.title ?? r.slug, compiled_truth: compiled,
@@ -347,7 +357,7 @@ export function coreNoticeLine(n: { source_id: string; slug: string; revision: s
}
/** The block a session receives; empty text when core is disabled or empty. */
-export async function loadCoreBlock(engine: Pick<BrainEngine, 'executeRaw' | 'readPageSnapshot' | 'getConfig'>, opts: LoadCoreBlockOpts = {}): Promise<CoreBlock & { enabled: boolean; activation_withheld?: number }> {
+export async function loadCoreBlock(engine: BrainEngine, opts: LoadCoreBlockOpts = {}): Promise<CoreBlock & { enabled: boolean; activation_withheld?: number }> {
const settings = opts.settings ?? await readCoreSettings(engine);
if (!settings.enabled) {
return { text: '', chars_used: 0, chars_limit: settings.maxChars, pages: [], truncated: false, omitted: [], revision: 'disabled', enabled: false };
diff --git a/src/core/persistence/file-repair.ts b/src/core/persistence/file-repair.ts
index bba8598a41..b32ae80992 100644
--- a/src/core/persistence/file-repair.ts
+++ b/src/core/persistence/file-repair.ts
@@ -353,8 +353,11 @@ export async function prepareManagedFileRepairMutation(engine: BrainEngine, row:
const importContent = p.content.replace(/^\uFEFF/, '');
const overrideTier = (await ownerSourceGateInput(engine, row.source_id, parseMarkdown(importContent, `${row.slug}.md`, { activePack: screenConfig.activePack }).frontmatter)).tier;
const importOptions = { ...source, noEmbed: true, remote: false, preserveGateMarkers: true, overrideTier, activePack: screenConfig.activePack, filename: basename(p.sourcePath).replace(/\.mdx?$/i, ''), sourcePath: p.sourcePath, allowEmptyOverwrite: true };
+ // afterCommit follows the import that published (a page stored in segments chunks what its publication left unsealed).
+ let published = ready;
return { observedRevision: snapshot?.revision ?? null, noop: ready.noop && !fileChanges && !moved, contentUnchanged: ready.noop && !fileChanges && !moved,
trust: await ownerImportTrust(engine, row, ready.parsedPage.frontmatter, p.sourcePath), deferEmbedding: p.noEmbed, ...(moved ? { additionalPageKeys: [{ sourceId: row.source_id, slug: moved.slug }] } : {}),
+ ...(ready.afterCommit || moved ? { afterCommit: async (target: BrainEngine) => { await published.afterCommit?.(target); } } : {}),
...(fileChanges ? { file: { root, path: target, content: bytes, expectedBeforeHash: p.beforeHash,
...(fenceRepair ? { commit: fenceRepairCommit(p.path, fenceRepair.classes, fenceRepair.tier) } : contentRepair ? { commit: contentRepairCommit(p.path, contentRepair) } : {}) } } : {}),
validate: async tx => {
@@ -377,9 +380,11 @@ export async function prepareManagedFileRepairMutation(engine: BrainEngine, row:
await movedImport.validate(tx);
applied = movedImport;
}
- await applied.apply(tx);
+ published = applied;
+ const installed = await applied.apply(tx);
await tx.executeRaw('UPDATE pages SET source_path=$3 WHERE source_id=$1 AND slug=$2 AND source_path IS DISTINCT FROM $3', [row.source_id, row.slug, p.sourcePath]);
- if (!applied.noop) { await project(tx); await sealPageTextProjection(tx, row.slug, row.source_id); }
+ // A body stored in segments was sealed by its import's apply when complete (sealSegmentedPage); the inline text seal reads the whole timeline.
+ if (!applied.noop) { await project(tx); if (!installed?.segmented) await sealPageTextProjection(tx, row.slug, row.source_id); }
const holdCleared = await clearGitHold(tx, { sourceId: row.source_id, incarnation: row.source_incarnation, path: p.path, observedAt: p.holdObservedAt ?? new Date().toISOString() });
// #6712 PR 1: the record names what is on disk now (the approved bytes), the page revision they produced and the parser, so the next discovery prescreens the file.
const page = await tx.readPageSnapshot(row.slug, { ...source, includeDeleted: true });
diff --git a/src/core/repair/frontmatter.ts b/src/core/repair/frontmatter.ts
index 14a0b50413..c69aa4e826 100644
--- a/src/core/repair/frontmatter.ts
+++ b/src/core/repair/frontmatter.ts
@@ -59,6 +59,8 @@ import type { SyncRename } from '../persistence/sync-discovery.ts';
import { canonicalRepairFields, confinedRepairTarget, managedRepairRoot, prepareRepairPublication, repairScreenConfig, submitManagedFileRepair } from '../persistence/file-repair.ts';
import { clearApprovedSet, loadApprovedSet, previewChangedError, previewHash, saveApprovedSet } from '../persistence/preview-approval.ts';
import type { PageSnapshot } from '../page-state/types.ts';
+import { materializedSnapshot, segmentedOverCeiling } from '../persistence/segmented-apply.ts';
+import { pageBodyOverCeilingError } from '../page-body/page-shape.ts';
import { afterCursor, repairRequestId, type RepairHandler, type RepairItem, type RepairItemOutcome, type RepairListing, type RepairPlan, type RepairScope } from './core.ts';
import { gitChildEnv } from '../git-env.ts';
@@ -358,6 +360,11 @@ async function bindProposal(ctx: FileContext, path: string, hold: GitHoldRecord
const page = ctx.pages.get(sourcePath);
const slug = page?.slug ?? (proposal.rename_from ? resolveSlugForPath(sourcePath) : hold?.slug ?? resolveSlugForPath(sourcePath));
const snapshot = await engine.readPageSnapshot(slug, { sourceId: src.sourceId, includeDeleted: true });
+ // Wave B decision #1: the re-import compares the stored body whole, which a page stored in segments allows up to 24 MiB.
+ if (proposal.reimport && snapshot && segmentedOverCeiling(snapshot.page)) {
+ const refusal = pageBodyOverCeilingError(snapshot.page, `gbrain repair frontmatter (re-import of ${path})`);
+ return { source_id: src.sourceId, path, code: refusal.code, resolution: `${refusal.message} ${refusal.suggestion}` };
+ }
const base: PageSnapshot | null = proposal.rename_from ? await engine.readPageSnapshot(proposal.rename_from.slug, { sourceId: src.sourceId, includeDeleted: true }) : snapshot;
const publication = await prepareRepairPublication(engine, { sourceId: src.sourceId, slug, sourcePath, path, root: src.root, content: proposal.content,
snapshot, base, ...screenConfig });
@@ -365,7 +372,8 @@ async function bindProposal(ctx: FileContext, path: string, hold: GitHoldRecord
...(publication.refusal.line !== undefined ? { line: publication.refusal.line } : {}), resolution: resolution(publication.refusal, path, src.sourceId) };
if (publication.status === 'overlay') return { source_id: src.sourceId, path, code: 'canonical_overlay',
resolution: `Importing the repaired ${path} would keep page data the file does not carry (tags added outside the file, a withdrawal or sanitized text), so it is not written. Edit the file by hand to carry them (gbrain get --source ${src.sourceId} -- ${slug} shows the page), then preview again.` };
- if (proposal.reimport && snapshot && digest(canonicalRepairFields(snapshot.page, snapshot.tags)) === publication.digest) {
+ const stored = proposal.reimport ? await materializedSnapshot(engine, snapshot) : null;
+ if (stored && digest(canonicalRepairFields(stored.page, stored.tags)) === publication.digest) {
return { source_id: src.sourceId, path, code: 'embedded_frontmatter', resolution: `The page of ${path} already matches its file; nothing to re-import.` };
}
const original = readFileSync(join(src.root, path));
diff --git a/test/large-pages/doctor-skipped-segmented.test.ts b/test/large-pages/doctor-skipped-segmented.test.ts
index 26e1e6e01b..8d2c6d1518 100644
--- a/test/large-pages/doctor-skipped-segmented.test.ts
+++ b/test/large-pages/doctor-skipped-segmented.test.ts
@@ -126,8 +126,12 @@ describe('doctor reports the segmented pages its whole-body checks skipped', ()
test('one segmented page and one inline page: every affected check reports skipped_segmented: 1 in JSON and text', async () => withEnv(env, async () => {
for (const brain of brains) {
const checks = await affectedChecks(brain.mixed);
- expect(checks.map(c => [brain.kind, c.name, c.skipped_segmented])).toEqual(AFFECTED.map(name => [brain.kind, name, 1]));
- for (const check of checks) expect(check.message).toContain('skipped (segmented): 1 page(s) store their body in segments');
+ // Fix lane P: core memory reads a core page stored in segments whole up to 24 MiB, so core_memory checks this 1.2 MB
+ // page and reports nothing; its count of the core pages over 24 MiB is segmented-core-list.test.ts.
+ const skipping = AFFECTED.filter(name => name !== 'core_memory');
+ expect(checks.map(c => [brain.kind, c.name, c.skipped_segmented])).toEqual(AFFECTED.map(name => [brain.kind, name, skipping.includes(name) ? 1 : undefined]));
+ for (const check of checks.filter(c => skipping.includes(c.name))) expect(check.message).toContain('skipped (segmented): 1 page(s) store their body in segments');
+ expect(checks.find(c => c.name === 'core_memory')!.message).not.toContain('skipped (segmented)');
}
}), 600_000);
diff --git a/test/large-pages/segmented-core-list.test.ts b/test/large-pages/segmented-core-list.test.ts
new file mode 100644
index 0000000000..c6c61a422c
--- /dev/null
+++ b/test/large-pages/segmented-core-list.test.ts
@@ -0,0 +1,139 @@
+/**
+ * Wave B PR 2 fix lane P (decision #1): core memory lists a core page stored in segments.
+ *
+ * 1. Protects: listCorePages reads a core page (`always_load: true`) stored in segments just over 1 MiB back whole, as
+ * it reads its inline twin: the same compiled truth, rendered text, chars and priority, before a fact is withdrawn
+ * from it and after (the withdrawal overlay applies as on the inline page), so core usage, the session block and the
+ * write-path budget see the page as they see the inline one. A withdrawn core page over 24 MiB is left out of the
+ * list without reading a segment, the list, core usage and the session block still answer, doctor core_memory counts
+ * it (`skipped_segmented: 1`; the page within 24 MiB is not counted), and nothing stored changes.
+ * 2. Fails when: a segmented core page lists as its title alone (its NULL compiled_truth column), a withdrawn one
+ * throws page_body_segmented out of listCorePages (session-start core, context_pack, gbrain core status and the core
+ * budget check then fail for every page), or a page over 24 MiB is read whole.
+ * 3. PGLite always; PostgreSQL when DATABASE_URL is set (test/postgres-unit-arms.txt). Cost assertions are segment read
+ * counts, never time.
+ */
+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
+import { createHash } from 'node:crypto';
+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import type { BrainEngine } from '../../src/core/engine.ts';
+import { PGLiteEngine } from '../../src/core/pglite-engine.ts';
+import { importFromFile } from '../../src/core/import-file.ts';
+import { readPageBodyPolicy } from '../../src/core/page-body/limits.ts';
+import { PAGE_MAX_BYTES } from '../../src/core/page-size-policy.ts';
+import { coreUsage, listCorePages, loadCoreBlock } from '../../src/core/core-memory.ts';
+import { coreMemoryCheck } from '../../src/commands/doctor/checks/core-memory.ts';
+import { isolatedPersistencePostgres } from '../helpers/persistence-postgres.ts';
+import { testBackends } from '../helpers/test-backends.ts';
+import { withEnv } from '../helpers/with-env.ts';
+
+/** Twin slugs have equal lengths, so rendered text compares equal once the slug is replaced. */
+const INLINE = 'notes/ina-core';
+const SEGMENTED = 'notes/sei-core';
+const HUGE = 'notes/hugo-core';
+const HUGE_SOURCE = 'huge-core';
+
+const fence = `<!--- gbrain:facts:begin -->
+| # | claim | kind | confidence | visibility | notability | valid_from | valid_until | source | context |
+|---|-------|------|------------|------------|------------|------------|-------------|--------|---------|
+| 1 | Withdrawn world claim | fact | 1.0 | world | medium | 2026-01-01 | | chat | |
+| 2 | Kept world claim | fact | 1.0 | world | medium | 2026-01-01 | | chat | |
+<!--- gbrain:facts:end -->`;
+const line = (i: number) => '- ' + String(i).padStart(8, '0') + ' acme-example journal line with enough text to fill a segment quickly\n';
+const body = (bytes: number) => Array.from({ length: Math.ceil(bytes / line(0).length) }, (_, i) => line(i)).join('');
+/** A core page; the one over 24 MiB carries no facts fence (importing a fence needs the whole body as one string). */
+const corePage = (bytes: number, withFence: boolean) => '---\ntype: note\ntitle: Core Twin\nalways_load: true\n---\n\n# Core Twin\n\n'
+ + (withFence ? '## Facts\n\n' + fence + '\n\n' : '') + body(bytes);
+
+const home = mkdtempSync(join(tmpdir(), 'gbrain-segmented-core-list-'));
+const env = { GBRAIN_HOME: home, OPENAI_API_KEY: undefined, VOYAGE_API_KEY: undefined, ANTHROPIC_API_KEY: undefined };
+
+for (const kind of testBackends()) {
+ describe(kind + ': core memory lists a core page stored in segments', () => {
+ let engine: BrainEngine;
+ let close: () => Promise<void>;
+
+ const imported = async (sourceId: string, slug: string, bytes: number, segmented: boolean) => {
+ await engine.setConfig('pages.segmented_storage', segmented ? 'on' : 'off');
+ const root = join(home, kind, sourceId);
+ mkdirSync(join(root, 'notes'), { recursive: true });
+ writeFileSync(join(root, slug + '.md'), corePage(bytes, bytes <= PAGE_MAX_BYTES));
+ expect(await importFromFile(engine, join(root, slug + '.md'), slug + '.md', { sourceId, noEmbed: true, bodyPolicy: await readPageBodyPolicy(engine) }))
+ .toMatchObject({ status: 'imported' });
+ };
+ const withdraw = (sourceId: string, slug: string) => engine.executeRaw(
+ "INSERT INTO fact_withdrawals(source_id, visibility, subject, fact_hash) VALUES ($1, 'world', $2, gbrain_fact_fingerprint('Withdrawn world claim'))", [sourceId, slug]);
+ const sha = (text: string) => createHash('sha256').update(text).digest('hex');
+ /** Everything listCorePages gives a page (the texts as their head and digest), with the slug made neutral so twins compare equal. */
+ const listed = async () => Object.fromEntries((await listCorePages(engine, { sourceIds: ['default'] })).map(p => {
+ const rendered = p.rendered.split(p.slug).join('<slug>');
+ return [p.slug, { title: p.title, priority: p.priority, chars: p.chars, truth: sha(p.compiled_truth), rendered: sha(rendered), head: rendered.slice(0, 1200) }];
+ }));
+
+ beforeAll(async () => withEnv(env, async () => {
+ if (kind === 'postgres') { const pg = await isolatedPersistencePostgres(process.env.DATABASE_URL!); engine = pg.engine; close = pg.close; }
+ else { const lite = new PGLiteEngine(); await lite.connect({}); await lite.initSchema(); engine = lite; close = () => lite.disconnect(); }
+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');
+ await engine.executeRaw("INSERT INTO sources(id,name,config) VALUES($1,$1,'{}')", [HUGE_SOURCE]);
+ await imported('default', INLINE, 1_100_000, false);
+ await imported('default', SEGMENTED, 1_100_000, true);
+ await imported(HUGE_SOURCE, HUGE, PAGE_MAX_BYTES + 512 * 1024, true);
+ await engine.setConfig('memory.core.enabled', 'true');
+ const storage = await engine.executeRaw<{ slug: string; body_storage: string; body_bytes: string | null }>(
+ 'SELECT slug, body_storage, body_bytes::text AS body_bytes FROM pages ORDER BY slug');
+ expect(Object.fromEntries(storage.map(r => [r.slug, r.body_storage]))).toEqual({ [HUGE]: 'segmented', [INLINE]: 'inline', [SEGMENTED]: 'segmented' });
+ expect(Number(storage.find(r => r.slug === HUGE)!.body_bytes)).toBeGreaterThan(PAGE_MAX_BYTES);
+ }), 600_000);
+
+ afterAll(async () => { await close(); }, 120_000);
+
+ test('a segmented core page just over 1 MiB lists as its inline twin, before and after a fact is withdrawn from both', async () => withEnv(env, async () => {
+ const before = await listed();
+ expect(before[SEGMENTED]!.head).toContain('| 1 | Withdrawn world claim |');
+ expect(before[SEGMENTED]!.chars).toBeGreaterThan(1_100_000);
+ expect(before[SEGMENTED]).toEqual(before[INLINE]!);
+ await withdraw('default', INLINE);
+ await withdraw('default', SEGMENTED);
+ const after = await listed();
+ expect(after[SEGMENTED]!.head).not.toContain('Withdrawn world claim');
+ expect(after[SEGMENTED]!.head).toContain('| 2 | Kept world claim |');
+ expect(after[SEGMENTED]!.truth).not.toBe(before[SEGMENTED]!.truth);
+ expect(after[SEGMENTED]).toEqual(after[INLINE]!);
+ const block = await loadCoreBlock(engine, { sessionSourceId: 'default', excludePrivate: true });
+ expect(block.omitted.map(o => [o.slug, o.reason]).sort()).toEqual([[INLINE, 'budget'], [SEGMENTED, 'budget']]);
+ }), 600_000);
+
+ test('a withdrawn core page over 24 MiB is left out without a segment read; the list answers, doctor counts it and nothing changes', async () => withEnv(env, async () => {
+ const state = () => engine.executeRaw<Record<string, string>>(`SELECT p.slug, p.title, p.body_generation::text AS generation, p.body_bytes::text AS bytes, p.content_hash,
+ p.knowledge_revision::text AS revision, p.frontmatter::text AS frontmatter,
+ (SELECT count(*) FROM page_body_manifest m WHERE m.page_id=p.id)::text AS manifest,
+ (SELECT count(*) FROM page_segment_texts t WHERE t.source_id=p.source_id)::text AS texts,
+ (SELECT count(*) FROM page_versions v WHERE v.page_id=p.id)::text AS versions,
+ (SELECT count(*) FROM content_chunks c WHERE c.page_id=p.id)::text AS chunks
+ FROM pages p ORDER BY p.source_id, p.slug`);
+ await withdraw(HUGE_SOURCE, HUGE);
+ const before = await state();
+ const [huge] = await engine.executeRaw<{ id: number }>('SELECT id FROM pages WHERE source_id=$1 AND slug=$2', [HUGE_SOURCE, HUGE]);
+ const reads = { manifest: 0, texts: 0 };
+ const e = engine as unknown as Record<string, (...args: any[]) => Promise<unknown>>;
+ const originals = { manifest: e.readManifest!, texts: e.readSegmentTexts! };
+ e.readManifest = function (this: unknown, ...args: any[]) { if (Number(args[0]) === Number(huge!.id)) reads.manifest++; return originals.manifest.apply(this, args); };
+ e.readSegmentTexts = function (this: unknown, ...args: any[]) { if (args[0] === HUGE_SOURCE) reads.texts++; return originals.texts.apply(this, args); };
+ try {
+ expect((await listCorePages(engine)).map(p => p.slug).sort()).toEqual([INLINE, SEGMENTED]);
+ expect((await coreUsage(engine)).pages.map(p => p.slug).sort()).toEqual([INLINE, SEGMENTED]);
+ const block = await loadCoreBlock(engine, { sessionSourceId: HUGE_SOURCE, excludePrivate: true });
+ expect(block.omitted.map(o => o.slug).sort()).toEqual([INLINE, SEGMENTED]);
+ const check = await coreMemoryCheck(engine);
+ expect(check.skipped_segmented).toBe(1);
+ expect(check.message).toContain('skipped (segmented): 1 page(s) store their body in segments');
+ } finally { e.readManifest = originals.manifest; e.readSegmentTexts = originals.texts; }
+ expect(reads).toEqual({ manifest: 0, texts: 0 });
+ expect(await state()).toEqual(before);
+ }), 600_000);
+ });
+}
+
+afterAll(() => rmSync(home, { recursive: true, force: true }));
diff --git a/test/large-pages/segmented-frontmatter-reimport.test.ts b/test/large-pages/segmented-frontmatter-reimport.test.ts
new file mode 100644
index 0000000000..3138fa7c38
--- /dev/null
+++ b/test/large-pages/segmented-frontmatter-reimport.test.ts
@@ -0,0 +1,124 @@
+/**
+ * Wave B PR 2 fix lane P (decision #1): `gbrain repair frontmatter` re-imports a page stored in segments.
+ *
+ * 1. Protects: a page whose stored title was derived from its slug while its file names one is re-imported by
+ * `--include-ambiguous` when the page is stored in segments just over 1 MiB, with the inline twin's result: the
+ * same preview (diff, class, listing, residuals) and apply outcome, then the same page (title, body bytes,
+ * frontmatter, tags, content_hash, canonical file). A page over 24 MiB is listed needs_review with
+ * page_body_segmented, naming the 24 MiB limit; the rest of the preview still proposes its repairs, and the page,
+ * its segments, versions and file are unchanged.
+ * 2. Fails when: the re-import check reads the segmented page's body getters, so page_body_segmented fails the whole
+ * preview (every file of the source), or the segmented re-import differs from the inline one, or a page over 24 MiB
+ * is read whole or written.
+ * 3. PGLite always; PostgreSQL when DATABASE_URL is set (test/postgres-unit-arms.txt). Cost assertions are row counts.
+ */
+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
+import { createHash } from 'node:crypto';
+import { readFileSync, writeFileSync } from 'node:fs';
+import { join } from 'node:path';
+import { PAGE_MAX_BYTES } from '../../src/core/page-size-policy.ts';
+import { withVerifiedLocalRegistration } from '../../src/core/persistence/identity.ts';
+import { resolveRepairScope, type RepairResult } from '../../src/core/repair/core.ts';
+import { repairRunner } from '../../src/core/repair/registry.ts';
+import { openTwinBrain, twinPage, type TwinBrain } from '../helpers/segmented-twins.ts';
+import { testBackends } from '../helpers/test-backends.ts';
+import { withEnv } from '../helpers/with-env.ts';
+
+const INLINE = 'people/ina-example';
+/** Twin slugs have equal lengths, so outputs that print the slug compare equal once it is replaced. */
+const SEGMENTED = 'people/sei-example';
+const HUGE = 'people/hugo-example';
+const quiet = { info() {}, warn() {}, error() {} };
+
+for (const kind of testBackends()) {
+ describe(kind + ': repair frontmatter re-imports a page stored in segments', () => {
+ let brain: TwinBrain;
+
+ /** The title parseMarkdown derives from the slug, which an older import stored although the file names one. */
+ const damageTitle = async (slug: string) => {
+ const derived = slug.split('/').pop()!.replace(/-/g, ' ').replace(/\b\w/g, c => c.toUpperCase());
+ await brain.engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');
+ await brain.engine.executeRaw('UPDATE pages SET title=$3 WHERE source_id=$1 AND slug=$2', [brain.sourceId, slug, derived]);
+ await brain.engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1');
+ };
+ const run = (opts: { only?: string[]; apply?: boolean; expect?: string }) => withEnv(brain.env(), () => withVerifiedLocalRegistration(brain.engine, brain.cli, async () => {
+ const runner = await repairRunner(brain.engine, { apply: opts.apply === true, noEmbed: true, logger: quiet });
+ return runner.run('frontmatter', await resolveRepairScope(brain.engine, brain.sourceId),
+ { explicit: true, sourceFlag: brain.sourceId, includeAmbiguous: true, only: opts.only, expect: opts.expect });
+ }));
+ const hashOf = (result: RepairResult) => result.apply_command.split('--expect ')[1]!.split(' ')[0]!;
+ const title = async (slug: string) => (await brain.engine.executeRaw<{ title: string }>('SELECT title FROM pages WHERE source_id=$1 AND slug=$2', [brain.sourceId, slug]))[0]!.title;
+
+ beforeAll(async () => {
+ brain = await openTwinBrain(kind, [INLINE], async seed => {
+ await seed.setSwitch(false);
+ await seed.imported(INLINE, 1_100_000);
+ await seed.setSwitch(true);
+ await seed.imported(SEGMENTED, 1_100_000);
+ await seed.imported(HUGE, PAGE_MAX_BYTES + 512 * 1024);
+ });
+ const storage = await brain.engine.executeRaw<{ slug: string; body_storage: string; body_bytes: string | null }>(
+ 'SELECT slug, body_storage, body_bytes::text AS body_bytes FROM pages WHERE source_id=$1 ORDER BY slug', [brain.sourceId]);
+ expect(Object.fromEntries(storage.map(r => [r.slug, r.body_storage]))).toEqual({ [HUGE]: 'segmented', [INLINE]: 'inline', [SEGMENTED]: 'segmented' });
+ expect(Number(storage.find(r => r.slug === HUGE)!.body_bytes)).toBeGreaterThan(PAGE_MAX_BYTES);
+ for (const slug of [INLINE, SEGMENTED, HUGE]) await damageTitle(slug);
+ // The page over 24 MiB keeps its body; its file was edited down to one within the limit that names the title.
+ writeFileSync(join(brain.root, HUGE + '.md'), twinPage(1_100_000));
+ }, 600_000);
+
+ afterAll(() => brain.close(), 120_000);
+
+ test('over 24 MiB: the page is listed needs_review naming the limit, the other files are still proposed, and nothing changes', async () => {
+ const state = () => brain.engine.executeRaw<Record<string, string>>(`SELECT p.title, p.body_generation::text AS generation, p.body_bytes::text AS bytes,
+ p.content_hash, p.knowledge_revision::text AS revision,
+ (SELECT string_agg(m.occurrence_id::text || ':' || encode(m.sha256, 'hex'), ',' ORDER BY m.seq) FROM page_body_manifest m WHERE m.page_id=p.id AND m.gen_to IS NULL AND m.staging_id IS NULL) AS live,
+ (SELECT count(*) FROM page_versions v WHERE v.page_id=p.id)::text AS versions,
+ (SELECT count(*) FROM content_chunks c WHERE c.page_id=p.id)::text AS chunks
+ FROM pages p WHERE p.source_id=$1 AND p.slug=$2`, [brain.sourceId, HUGE]);
+ const file = () => createHash('sha256').update(readFileSync(join(brain.root, HUGE + '.md'))).digest('hex');
+ const before = { page: await state(), file: file() };
+ await brain.setSwitch(true);
+ const preview = await run({});
+ const listing = Object.fromEntries((preview.listing ?? []).map(entry => [entry.item, entry.class]));
+ expect(listing).toEqual({ [brain.sourceId + ':' + INLINE + '.md']: 'interpretive', [brain.sourceId + ':' + SEGMENTED + '.md']: 'interpretive',
+ [brain.sourceId + ':' + HUGE + '.md']: 'needs_review' });
+ const review = (preview.details as { needs_review: Array<{ path: string; code: string; resolution: string }> }).needs_review;
+ expect(review).toEqual([expect.objectContaining({ path: HUGE + '.md', code: 'page_body_segmented' })]);
+ expect(review[0]!.resolution).toContain('over the 24 MiB (' + PAGE_MAX_BYTES + '-byte) limit');
+ expect(review[0]!.resolution).toContain('Nothing was read or changed.');
+ expect(preview.residuals['needs_review:page_body_segmented']).toBe(1);
+ expect(preview.affected).toBe(2);
+ // A preview of that file alone approves nothing to apply.
+ const applied = await run({ only: [HUGE + '.md'] });
+ expect(applied.affected).toBe(0);
+ expect({ page: await state(), file: file() }).toEqual(before);
+ expect(before.page[0]!.title).toBe('Hugo Example');
+ }, 600_000);
+
+ test('just over 1 MiB: the segmented re-import previews, applies and stores what the inline twin does', async () => {
+ /** The preview hash binds the page's id and revision, which twins never share. */
+ const neutral = (slug: string, hash: string, value: unknown) => JSON.parse(JSON.stringify(value).split(slug).join('<slug>').split(hash).join('<hash>'));
+ const once = async (slug: string) => {
+ await brain.setSwitch(slug !== INLINE);
+ const preview = await run({ only: [slug + '.md'] });
+ const applied = await run({ only: [slug + '.md'], apply: true, expect: hashOf(preview) });
+ return neutral(slug, hashOf(preview), {
+ preview: { affected: preview.affected, residuals: preview.residuals, listing: preview.listing, details: preview.details },
+ applied: { applied: applied.applied, failed: applied.failed, outcomes: applied.outcomes,
+ outcome_items: applied.outcome_items?.map(({ detail, ...rest }) => ({ ...rest, detail: { ...detail, committed: undefined } })) },
+ });
+ };
+ const inline = await once(INLINE);
+ const segmented = await once(SEGMENTED);
+ expect(inline.preview.affected).toBe(1);
+ expect(inline.applied.applied).toBe(1);
+ expect(segmented).toEqual(inline);
+ expect([await title(INLINE), await title(SEGMENTED)]).toEqual(['Twin Example', 'Twin Example']);
+ expect(await brain.view(SEGMENTED)).toEqual(await brain.view(INLINE));
+ expect([await brain.storageOf(INLINE), await brain.storageOf(SEGMENTED)]).toEqual(['inline', 'segmented']);
+ const sealed = await brain.engine.executeRaw<{ slug: string; sealed: boolean }>(
+ 'SELECT slug, text_projection_revision = knowledge_revision AS sealed FROM pages WHERE source_id=$1 AND slug = ANY($2::text[]) ORDER BY slug', [brain.sourceId, [INLINE, SEGMENTED]]);
+ expect(sealed.map(r => [r.slug, r.sealed])).toEqual([[INLINE, true], [SEGMENTED, true]]);
+ }, 600_000);
+ });
+}
diff --git a/test/postgres-unit-arms.txt b/test/postgres-unit-arms.txt
index ef5d2acf4c..ccec75998e 100644
--- a/test/postgres-unit-arms.txt
+++ b/test/postgres-unit-arms.txt
@@ -104,6 +104,7 @@ test/large-pages/segmented-body-unreachable.test.ts
test/large-pages/segmented-bom.test.ts
test/large-pages/segmented-conversation-facts.test.ts
test/large-pages/segmented-conversation-sidecar-token.test.ts
+test/large-pages/segmented-core-list.test.ts
test/large-pages/segmented-create-searchable.test.ts
test/large-pages/segmented-delete-crash.slow.test.ts
test/large-pages/segmented-delete-restore-file.slow.test.ts
@@ -121,6 +122,7 @@ test/large-pages/segmented-facts-reconcile.test.ts
test/large-pages/segmented-file-drift-ledger.test.ts
test/large-pages/segmented-file-drift.test.ts
test/large-pages/segmented-forced-cuts.test.ts
+test/large-pages/segmented-frontmatter-reimport.test.ts
test/large-pages/segmented-get-cli.test.ts
test/large-pages/segmented-get-page-parity.test.ts
test/large-pages/segmented-leads.test.ts