Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(sync,doctor): untiled segmented holds point to the repair; sync status finds one hold; doctor reports segmented_tiling on its own budget

garrytan5d021eafc105
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 892596bbc4..f5b7fbc35b 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -10,6 +10,17 @@ credits are retained; no result has been reassigned to another provider. Origina
identifiers and attribution are available in the pre-removal Git revision
`6040075c6cb95be5881cc2e1b76ef7d71f4e5d29` (retained on 2026-09-23).
+## [Unreleased]
+
+**A sync hold on a page whose segment rows are missing now says to run the repair, and `gbrain sync status` finds one hold without paging.** A page stored in segments whose segment rows do not cover its body refuses every read, so a managed sync holds its file (`page_write_failed` naming `page_body_rows_unreadable`). That hold read retry with no person needed and pointed at `gbrain sources retry-held`, which can never clear it. It now reads needs_human with safe_actions repair, and its fix previews `gbrain repair segmented-tiling --source <id> --slug <slug>` (read-only; the apply needs the user's agreement and clears the hold). On a source with hundreds of holds the hold also sorted onto a late page of `sync status`, so a check reading the first page missed it.
+
+### Itemized changes
+
+- `src/core/persistence/sync-fault-class.ts`, `sync-holds.ts` (`gitHoldFix`), `sync-entry-fault.ts`: the `freeze_page_body_rows_unreadable` verdict, the hold's fix and its message name the segmented-tiling repair; when doctor `segmented_tiling` does not list the page, the fix says to grant the reading role access and run retry-held. `gbrain sync unblock` refuses the hold by name with that fix.
+- `gbrain sync status`: each `page_write_failed` hold names its `fault_code`, `holds_summary.by_fault_code` counts them, and `--slug <slug>` / `--code <code>` (a hold code or a fault code) list one hold; a filtered page's cursor and `next_command` keep the filter.
+- Doctor: `segmented_tiling` runs as its own entry with its own budget, so a default run reports it even when the wave checks of `timeline_history` run out of theirs; an entry's last known result recorded before a check was added no longer hides that check (it reports unknown, or is named in `doctor_last_known`).
+- #8504 items 6 and 8: `untiledSegmentedPages` (doctor and the repair) skips archived sources; doctor's fix always names a `--source` and lists the other damaged sources' commands; a repair preview over 1,000 pages reports `truncated` and says to preview again after the apply.
+
## [0.60.565.0] - 2026-11-03
**The per-file index describes how pages stored in segments are written and held.** The key-files entries for `write-through.ts` and `sync-entry-fault.ts` contradicted v0.60.560.0: the first said every page is rendered whole and `content` always holds the bytes written, and the second said a page-body fault at the freeze stops the run. They now describe the streamed write of a segmented page (measured at its snapshot's revision, checked against the scan cap before `source_path` binds, `inlineOnly` and `segmented_page`) and the `page_write_failed` hold that names `page_body_segmented` or `page_body_rows_unreadable`. The entries for full sync, `sync status`, the derived write-through and export also name `reexport_failures`, `last_error.request_id: null`, the `freeze_page_body_*` routing, the derived writer's `segmented_page` skip and the export's revision pin. Docs only.
diff --git a/docs/architecture/key-files/commands-2-continued.md b/docs/architecture/key-files/commands-2-continued.md
index 8b8acc9553..b2c2321d0c 100644
--- a/docs/architecture/key-files/commands-2-continued.md
+++ b/docs/architecture/key-files/commands-2-continued.md
@@ -34,7 +34,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
- `src/commands/doctor/checks/image-embedding-coverage.ts` — `image_embedding_coverage` (#6529, brain category, after `image_assets`). Counts live image pages (`page_kind = 'image'`), those with no `embedding_image` chunk, those with a NULL `source_path`, and the `managed_image_sync_unsupported` holds per source, and reads `isMultimodalEnabled()`. Ok when the brain has no image pages, when every image page has an image vector and a `source_path` and nothing is held, or when multimodal embedding is off (the counts are then informational: image search is not expected to work). On a multimodal install it warns with the counts (text coverage counts those pages as embedded while image search does not see them) and names `gbrain embed --stale --images` and `gbrain sync --no-pull --source <id>` for the holds. Read-only; no paid call. Test: `test/doctor-image-embedding-coverage.test.ts`.
- `src/commands/doctor/checks/provider-consent.ts` — `provider_consent` (OPS, engine-free filesystem lane right after `embedding_key_source`; not in `doctorReportRemote`): the provider-use decision `gbrain setup` recorded for this install (`localSetupRecords` in `src/core/setup/local-receipts.ts`). A decline (any live receipt; opt-outs win) is `ok` + info `disabled_by_choice`, "skipped by consent", naming the provider key variables present (names only) and carrying `providerConsentFix`: `gbrain setup <harness> --providers` (+ `--name`/`--scope project`), actor `user`, consent `paid`+`egress`, so `next: tell_user_to_run`. Accepted is plain `ok`; no receipt is info `not_applicable`. The same fix rides `embedding_provider`'s `--probe` skip (`checks/embedding-health.ts`), and `probe-consent.ts` authorizes nothing when a decline is recorded. Reads files only; sends nothing. Pinned by `test/doctor-provider-consent.serial.test.ts` (request counter: zero outbound under a decline, controls prove discovery and the probe are seen otherwise).
- `src/commands/doctor/budget.ts` + `checks/ops-sections.ts` + `checks/orphan-estimate.ts` — doctor tiers and budgets (#6696 B1). `parseDoctorTier` (`--tier ops|quick|standard|deep`, a bad value is `invalid_params`), `parseBudgetMs` (`--budget-ms`, default 4000 under ops, 10000 under quick, none otherwise) and `startDoctorDeadline` build the `DoctorDeadline` the CLI starts before connecting. `runDoctorRegistry` runs the entries tagged `tier: 'ops'` (persistence capacity, terminal failures, managed sync movement, persistence compaction, serve build drift, schema-pack consistency, embedding state) right after the connection lane; under `--tier ops` it runs only those (each `executeRaw` gets the absolute `deadlineAt`, so `SET LOCAL statement_timeout` is the time left after the pool wait: `postgres-engine/bounded-statement.ts`), reports an entry marked `opsPglite: 'not_applicable'` as an `ok` info row on PGLite, and stays complete. Every other tier bounds each entry by `doctor.entry_budget_ms` (default 15000). An entry past its budget, an unknown reported after the overall deadline, or a connect the deadline ended becomes `budgetUnknownCheck` (warn, `details.health: 'unknown'`, `reason: 'budget'`, `exact: false`, a rerun-alone fix), never a clear result; every check carries `elapsed_ms`, and the report adds `tier`/`complete`/`unknown_sections`/`elapsed_ms`/`budget_ms` only when `--tier` or `--budget-ms` was given (`doctorRunSummary`). `doctorHealth(ctx)` memoizes `getHealth` for one run. `orphan_ratio` estimates from a `TABLESAMPLE SYSTEM` sample above `doctor.orphan_ratio.full_scan_max_pages` (default 50000) unless `--tier deep`. Capacity and compaction freshness live in `checks/ops-sections.ts`. On every tier each entry runs inside its own `StatementDeadline` (`src/core/statement-deadline.ts`: an AsyncLocalStorage scope plus `deadlineBoundEngine`, one stable Proxy per real engine that refuses any engine call past the deadline, carries the deadline to the server on Postgres `executeRaw`, and marks the scope expired on a cancel even when the check catches it; `engineCacheKey` maps the wrapper to the real engine for engine-keyed caches; PGLite gets only the pre-statement refusal). The budget-config read is one bounded statement (2 s). `CHEAP_INCIDENT_CHECKS` (by check name: persistence capacity, managed sync movement, `text_projection_readiness`, `partial_embedding`, `links_extraction_lag`) run right after the ops sections, before any full scan. `scanDeadline` clips the frontmatter walk and the fence census to the entry deadline less 250 ms, so they report partial results. `--only` with an explicit `--budget-ms` gives the selected entries the whole overall budget; `budgetUnknownCheck` names the limiting budget (`details.limit`: `entry` or `overall`) and fixes with `--only <check> --budget-ms N` (N ten times that budget; actor agent while N fits `AGENT_TOOL_LIMIT_MS` less 10 s, else actor user). `--budget-ms 0` is no overall budget. `default-budget.ts`: a plain non-interactive CLI `doctor --json` (stderr not a TTY; no `--budget-ms`, `--tier`, `--fix`, `--remediate` or `--remediation-plan`) caps its check run at `doctor.default_budget_ms` (file plane, default 90000, 0 off), started by `startDeferredDeadline` when the registry starts (connect and migrations are outside it), with one stderr line; the report then carries the tier fields. `capacity-memo.ts` `doctorCapacityForecast`: one forecast per run (shared by `persistence_capacity` and `persistence_request_growth`) read under the run's overall deadline and dropped from the memo on a deadline failure, which makes the waiting check unknown instead of a counter-only verdict. `persistence_session_timeouts` reads `SHOW statement_timeout` outside the entry deadline. Tests: `test/doctor-tier-6696.test.ts`, `test/doctor-day-zero.test.ts` (`--tier ops`), `test/e2e/doctor-ops-tier-postgres.test.ts`, `test/doctor-entry-deadline-6803.test.ts` (+ `test/e2e/doctor-entry-deadline-postgres.test.ts`), `test/doctor-default-budget-6803.test.ts`; bench `scripts/bench/doctor-scale.ts`. #7276: `scoredChecks` keeps over-budget unknowns out of every score (`unknown_count`); `derived_visibility` is its own entry (`test/doctor-unknown-score-7276.test.ts`).
-- `src/commands/doctor/last-known.ts` — the quick tier's last known results (#7142). `--tier quick` (budget.ts: `QUICK_BUDGET_MS_DEFAULT` 10000, connect included; `entryRunsAt` orders ops ⊂ quick ⊂ standard ⊂ deep; `cheapTier` gives it the ops tier's round-trip connection check and counter-mode embedding state) runs the ops entries plus the entries tagged `tier: 'quick'` (schema version, the stub-guard entry with `sync_failures`, queue health, partial embeddings). `lastKnownMode` turns the store on only for a brain-wide local CLI run (`buildChecks(..., { lastKnown: 'cli' })` from `runDoctor`) or the refresh job, never under `--only`, `--source`, a remote scope, `--fix` or `--tier ops`. `runDoctorRegistry` records each entry's outcome (`done`, `expired` when it ran out of budget or emitted a budget unknown, `not_run` when the tier skipped a standard entry); `withLastKnown` writes the finished entries of a standard or deep run to `op_checkpoints` (op `doctor-last-known`, fingerprint = entry name, `completed_keys[0]` = `{ checks, measured_at, elapsed_ms }`, one bounded statement, best-effort) and `applyLastKnown` replaces an unfinished entry's checks with its last known ones when they are at most `LAST_KNOWN_MAX_AGE_MS` (24 h) old: same status, message prefixed `Last known, N ago (...)`, `details.last_known` `{ measured_at, age_ms, reason: not_in_tier | budget }`. The rest are named in one `doctor_last_known` warning (`details.health: 'unknown'`, `unknown_checks`), which `tierFields` expands into `unknown_sections`; served checks go to `last_known_sections` and make the report incomplete. An entry with no result younger than `REFRESH_AFTER_MS` (1 h) queues one `doctor-refresh` job on Postgres (idempotency key per hour, `maxWaiting: 1`, priority 10 so sync, the autopilot cycles, global maintenance, embed backfill and loops extract claim first, `timeout_ms` 15 min; none when DB config `doctor.background_refresh` is `false`, #7263); the handler (`runDoctorRefresh`, registered in `commands/jobs.ts`) runs `doctorRefreshRegistry()` (the connection lane plus every standard entry after the connection gate; filesystem entries are recorded only by CLI runs) with `REFRESH_ENTRY_BUDGET_MS` (600000) per entry inside the overall `REFRESH_BUDGET_MS` (10 min, passed as `--budget-ms`: past it no entry starts and the running one is cut, so the job completes with what it measured and the rest waits for the next slot) and queues nothing itself. `doctor-refresh` is in `DEFAULT_LONG_JOB_NAMES` (`minions/lanes.ts`). Tests: `test/doctor-refresh-7263.test.ts`, `test/doctor-quick-tier-7142.test.ts` (+ `test/e2e/doctor-quick-tier-7142-postgres.test.ts`).
+- `src/commands/doctor/last-known.ts` — the quick tier's last known results (#7142). `--tier quick` (budget.ts: `QUICK_BUDGET_MS_DEFAULT` 10000, connect included; `entryRunsAt` orders ops ⊂ quick ⊂ standard ⊂ deep; `cheapTier` gives it the ops tier's round-trip connection check and counter-mode embedding state) runs the ops entries plus the entries tagged `tier: 'quick'` (schema version, the stub-guard entry with `sync_failures`, queue health, partial embeddings). `lastKnownMode` turns the store on only for a brain-wide local CLI run (`buildChecks(..., { lastKnown: 'cli' })` from `runDoctor`) or the refresh job, never under `--only`, `--source`, a remote scope, `--fix` or `--tier ops`. `runDoctorRegistry` records each entry's outcome (`done`, `expired` when it ran out of budget or emitted a budget unknown, `not_run` when the tier skipped a standard entry); `withLastKnown` writes the finished entries of a standard or deep run to `op_checkpoints` (op `doctor-last-known`, fingerprint = entry name, `completed_keys[0]` = `{ checks, measured_at, elapsed_ms, emits }`, one bounded statement, best-effort) and `applyLastKnown` replaces an unfinished entry's checks with its last known ones when they are at most `LAST_KNOWN_MAX_AGE_MS` (24 h) old: same status, message prefixed `Last known, N ago (...)`, `details.last_known` `{ measured_at, age_ms, reason: not_in_tier | budget }`. The rest are named in one `doctor_last_known` warning (`details.health: 'unknown'`, `unknown_checks`), which `tierFields` expands into `unknown_sections`; served checks go to `last_known_sections` and make the report incomplete. An entry with no result younger than `REFRESH_AFTER_MS` (1 h) queues one `doctor-refresh` job on Postgres (idempotency key per hour, `maxWaiting: 1`, priority 10 so sync, the autopilot cycles, global maintenance, embed backfill and loops extract claim first, `timeout_ms` 15 min; none when DB config `doctor.background_refresh` is `false`, #7263); the handler (`runDoctorRefresh`, registered in `commands/jobs.ts`) runs `doctorRefreshRegistry()` (the connection lane plus every standard entry after the connection gate; filesystem entries are recorded only by CLI runs) with `REFRESH_ENTRY_BUDGET_MS` (600000) per entry inside the overall `REFRESH_BUDGET_MS` (10 min, passed as `--budget-ms`: past it no entry starts and the running one is cut, so the job completes with what it measured and the rest waits for the next slot) and queues nothing itself. `doctor-refresh` is in `DEFAULT_LONG_JOB_NAMES` (`minions/lanes.ts`). Tests: `test/doctor-refresh-7263.test.ts`, `test/doctor-quick-tier-7142.test.ts` (+ `test/e2e/doctor-quick-tier-7142-postgres.test.ts`).
- `src/commands/doctor/brain-health-bands.ts` + `remote-tier.ts` + `ops-snapshot.ts`, `src/core/doctor-remote-tier.ts`, `src/core/persistence/capacity-view.ts` — the ops tier for agents and remote clients (#6696 B2). `readCapacityView` (for `/admin/api/ops`) reads the counter rows, `capacityDiagnostics`, the light `readCapacityForecast` (null when unreadable: days unknown) and `readLastCompaction`; the bands read `cachedCapacitySnapshot`; `capacityVerify()` is the verify of every capacity fix (`gbrain doctor --only persistence_capacity --json` plus MCP `get_brain_health`). `readBrainHealthBands` backs the read-scope `get_brain_health` op: capacity band and days band, write failures and active blockers as count bands for the caller's readable sources, no slugs or exact counters, cached 60 s per engine and scope. `runRemoteDoctorTier` backs `run_doctor`'s `tier: "ops"` / `only` (admin). `runScopedRemoteDoctor` is the thin client's `gbrain doctor --tier ops` / `--only <registry check>`: it reads `tools/list` and uses `run_doctor` with the parameters, else the bands (`BAND_CHECKS`), else refuses `doctor_tier_unavailable`; it never runs the full remote report in their place. `cachedOpsSnapshot` serves `/admin/api/ops` from one ops run a minute. Tests: `test/doctor-ops-remote-6696.test.ts`.
- `src/commands/doctor/checks/rename-identity-downgrades.ts` — `rename_identity_downgrades` (#6729): warn while a downgraded rename record is open (`sync-identity-downgrades.ts`), naming up to 5 pairs with their facts and links; fix = the first pair's `gbrain repair rename-identity` apply (destructive, `ask_user`, `preview_argv`, `plan_hash`; `--close` on a managed brain), so unbound classic Postgres pairs get an actionable fix too; `gbrain restore <old-slug> --source-id <id> --force` is named as the alternative in its text only where `restore_available !== false`, and `restore_unavailable_sources` lists the rest.
diff --git a/docs/architecture/key-files/core-services-2-continued.md b/docs/architecture/key-files/core-services-2-continued.md
index 0c3cf76aa7..b22164b3a6 100644
--- a/docs/architecture/key-files/core-services-2-continued.md
+++ b/docs/architecture/key-files/core-services-2-continued.md
@@ -34,7 +34,7 @@ The page-state concurrency foundation under `src/core/page-state/` and the share
- `src/core/page-body/segment-blocks.ts` + `segment-links.ts` + `segment-takes.ts` — Wave B PR 2 (spec 8, full-pass mode): the derived passes over a segmented body, O(page) work and O(segment) memory, not yet incremental. `bodyBlocks(engine, page, { regions?, separator?, want? })` yields the trusted, withdrawal-overlaid joined body one block at a time (a segment, or a run joined across forced cuts, refused above `BLOCK_MAX_BYTES` (read-range.ts) with `page_body_segmented`; `want` skips a run unread), so each block starts where the parsers start fresh; `truthLead` reads a bounded lead; `readGarbageCollector` forces a collection every 4 MiB read; `detachedValue` copies a result kept past its block so it pins no segment text; `segmentedPassWork` counts the passes' work for the linearity test. `extractSegmentedPageLinks` runs `extractBodyLinks` over each block in a window (`bodyWindows`: the whole blocks before it, 4096 chars after, the headings still open), with the role phrases a first pass found (`segmentedRoleText`), and merges candidates in `extractPageLinks` order, plus the temporal inputs (`TemporalBody`). `parseTakesFenceBlocks` gives `parseTakesFence` of the joined body. Consumers: link preparation and the links effect, stale-links maintenance, source reconciliation, the sweep, `extract links|timeline|takes --source db`, `extract --stale` (the stale list includes segmented pages since PR 2 fix lane J1; test `test/large-pages/segmented-extraction-stale.test.ts`), the mention pass (`pageMentions`), the canonical prior view (`segmentedPriorView`), `segmentedTimelineText`, the chronicle judge and the facts planner (`planSegmentedExtraction`). Tests: `test/large-pages/segmented-derived-parity.test.ts`, `segmented-derived-passes.test.ts`, `segmented-derived-linear.test.ts`, `segmented-derived-memory.slow.test.ts`, `segmented-derived-work.test.ts`. `segment-lines.ts` serves the line-local maintenance scans: `bodyLines` yields the joined text's complete lines a block at a time (a line cut by a block boundary is carried, counted in `segmentedPassWork.carry`), consumed by `gbrain integrity` and `reconcile-links`; `segmentedRegionContains` searches one region for literal markers across block boundaries (repair `connector-fences`). Test: `test/large-pages/segmented-maintenance-commands.test.ts`.
- `src/core/persistence/large-file.ts` — Wave B PR 2 fix lane D: canonical files over 24 MiB (`LARGE_FILE_MIN_BYTES`) on the publication path, never one string or Buffer. `hashFile`/`hashDescriptor` (the persistence file hash, read in one-segment pieces), `FileBytes` (a file read on demand through one descriptor, the `ByteSource` the drift check's `fileBodyDigests` takes; `close` refuses `source_changed` when the file changed while read), `StreamedFileContent` (restore_page's file: export's serializer over the segments, measured once in preparation, produced again by `stageStreamedContent` into the reserved publication stage after the recovery record is durable and before the publication transaction: streamed into an in-progress sibling (`streamingStagePath`, `<stage>.streaming`), verified, fsynced and only then renamed to the stage's name, so a stream a crash cut short is never at that name and recovery removes it unread; a mismatch removes the stream and refuses `revision_conflict`; seam `large_file:stage_streaming` after each piece), and `stageBeforeCopy` (the prior file copied by the kernel into its `before` stage, hashed and fsynced; the recovery record names it by path and SHA-256 instead of embedding base64, and reserves the file once). `largeFileWork` (@internal) counts bytes read, written and copied and the largest piece. Coordinator: `pageRecoveryRecord` → `largeRecoveryRecord`, `stageLargeFiles`, `publishStagedContent`; a group publication never takes such a member (`groupable`). Flip lane A: the withdrawal mirror of a segmented page (`effects.ts` `mirrorPage`, any size) renders its file with `page-prepare.ts` `unreadPageFile` (a `StreamedFileContent`) and writes it with `stageStreamedContent` before its recovery transaction (`effect-recovery.ts` `stageStreamedMirror`); `existsAt` is the lstat-based leaf check it uses. `prepareFileTarget` reads the prior file through `FileBytes` at any size for a page stored in segments or a streamed target (never `readFileSync` whole), so its drift check reads in pieces of at most a segment. Test: `test/large-pages/segmented-withdrawal-mirror.test.ts`. Tests: `test/large-pages/segmented-delete-restore-file.slow.test.ts` (27 and 90 MiB round trips byte for byte, both engines), `test/large-pages/segmented-delete-crash.slow.test.ts` (SIGKILL between file removal and commit, and after the restoration rename).
- `src/core/page-body/body-digests.ts` — Wave B PR 2: the digests the drift check of a segmented page over the single-string ceiling compares (`page-prepare.ts` `segmentedFileMatches`). `fileBodyDigests(bytes, reading, filePath, opts)` runs the streamed importer's pass 1 (`BodyScanner`) over one reading of the file's bytes (an inferred-frontmatter prefix, then the bytes past a BOM), then SHA-256 over each region's byte ranges, and reports a facts fence marker; `storedBodyDigests(engine, pageId, ledger)` hashes each region of the trusted stored body (`readBodyRange`, one segment per read, `readGarbageCollector`). `bodyDigestWork` counts file and stored bytes and the largest piece handed to a scan or hash (at most a segment). `overlaidFileBodyDigests` overlays the file one complete fence block at a time; inside an open block a read stops at FENCE_MAX_BYTES plus `FENCE_READ_LOOKAHEAD` (4 bytes), so an over-bound fence refuses `page_body_segmented` without reading a further segment (`test/pathological/lp-g-file-digest-fence-bound.test.ts`). In `page-prepare.ts`, `prepareFileTarget` compares a page whose body was not read back through `segmentedFileMatches` (the raw reading, then the inferred one from `streamed-import.ts` `inferredHeadPrefix`; the same normalizations as `fileMatchesSnapshot` via `importedFileType`); a file body with a facts fence under a withdrawal ledger that applies refuses `page_body_segmented` instead of reading as drift. `restore_page` of such a page (`prepareUnreadRestore`) versions it, clears `deleted_at` and reseals (or leaves the projection queued when chunks are missing) without re-importing, and publishes `serializePageToMarkdown`'s bytes streamed from the segments by `segmentedExportMarkdown` into one buffer (under the 25 MiB pre-push scan cap); a core page and an external_untrusted writer refuse `page_body_segmented`, and an agent-tier writer's advisory write-gate scan is not re-run over the unchanged body. Tests: `test/large-pages/segmented-file-drift.test.ts`.
-- `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 that do not tile (read-only, one aggregate per page), for doctor `segmented_tiling` (`src/commands/doctor/checks/segmented-tiling.ts`, BRAIN, host only) and the repair.
+- `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, 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`.
diff --git a/docs/architecture/key-files/managed-sync-bookkeeping.md b/docs/architecture/key-files/managed-sync-bookkeeping.md
index c131fda3cf..24d712b3df 100644
--- a/docs/architecture/key-files/managed-sync-bookkeeping.md
+++ b/docs/architecture/key-files/managed-sync-bookkeeping.md
@@ -48,7 +48,7 @@ run, and the supersession of a checkpoint whose cursor another run replaced. The
- `src/commands/doctor/checks/managed-sync-movement.ts` + `src/core/persistence/sync-movement.ts` — #6317 (B4, I2): the movement reader and its doctor check. `readManagedSyncMovement` snapshots, per active managed source, the newest `completed_at` of committed `managed_sync_*` receipts in the current source incarnation (the watermark: one probe of the partial index `persistence_requests_sync_watermark`, v223; a count would shrink under compaction), the head claim's `step_since`, the `managed-sync` cursor (`index/total`, `held`) and `sources.last_sync_at`/`last_commit`, and whether a drain or full consumer is live on the owner host. `data_moving` is false when an unfinished cursor has had neither a committed receipt nor a head step advance for longer than `persistence.preparation_ceiling_ms` while a consumer is live; with none live the state is `parked` (informational). `sources status --json` and `writer status --json` print `data_moving`, `not_moving_since` and `movement_state` beside `sync_running`, and `sources status` prints the writer-status command beside `data_moving: false`; doctor `managed_sync_not_moving` (warn, scored for `not_moving` only) uses the same rule and command as its fix, and fails on a parked cursor whose admitted queue has no consumer past the ceiling (#6552; fix: the resume sync); `serve` prints one `[gbrain notice]` when a source flips. A failed backlog read is `unknown`, never `nothing_pending` (doctor warns). `/health` stays liveness-only.
- `src/commands/sources-writer-movement.ts` — #6317 (I2): `gbrain sources writer movement [<source>] [--wait <dur>] [--warn-only] [--json]`, the deploy gate `gbrain upgrade` and `post-upgrade` end by printing (bare, so it inherits the default window; neither runs it, because neither restarts the resident processes). The printed step is `MOVEMENT_SUPERVISOR_STEP` from the import-free leaf `src/commands/movement-step.ts` (re-exported here), so upgrade loads it before the swap (#6604). Same source selection as `writer status` (`persistence-admin.ts`). It snapshots through `sync-movement.ts`, waits `max(300 s, preparation budget + 60 s)` (printed as the effective budget; `--wait <dur>` takes sync's duration syntax) and judges each source: `moved` (a new committed publication; a cursor advanced only by holds or a `last_sync_at` touched by an up-to-date check is not movement) and `current` exit 0; `held` exits 0 with a warning and the hold kind's route (`gbrain repair fences --source <id>`; `preparation_stalled` → writer status, then `gbrain sources retry-held <id>`); `within_allowance` (the head's step advanced inside the window) exits 0 with `retry_after_ms`; `not_moving` exits 1 with `managed_sync_not_moving` (`reason: movement_check`, `fix.argv` the writer-status command, `fix.verify` this command); `unknown` (backlog unreadable) exits 1 with `movement_unknown`; other read failures keep their code. `--warn-only` prints the same envelopes and exits 0. `parseMovementArgs` refuses `--json` or `--warn-only` written with a value (`invalid_params`), except `--json=true`, which it reads as `--json` (#7619). Flags are regenerated into `src/core/cli-flag-registry.generated.ts` with `bun run build:flag-registry`.
- `src/core/serve-head-watcher.ts` + `src/core/persistence/sync-freshness.ts` + `src/commands/doctor/checks/managed-sync-latency.ts` — #6858 ask 6: on-commit sync and its latency metric. `startServeHeadWatcher` (two call sites: `installResidentTickers` in `src/commands/serve.ts`, stopped before `shutdownDelegatedSync`, and `runServeHttp` in `src/commands/serve-http.ts`, beside `startMovementWatch` and stopped on the same shutdown path) re-reads `sync.on_commit` every 30 s; while on it polls `git rev-parse HEAD` in each managed source checkout this host owns (`GBRAIN_SERVE_HEAD_POLL_MS`, default 3 s; an `fs.watch` on the git dir only nudges the poll), debounces 3 s (`GBRAIN_SERVE_HEAD_DEBOUNCE_MS`) and starts one managed sync through the unchanged `startDelegatedSync` with this host's `cli` registration. It never starts beside a running delegated sync or a held drain lease (the move stays pending and fires once after), skips a HEAD `sources.last_commit` already has, resumes a resumable stop up to `MAX_RESUMES`, and logs each distinct error once. `readSyncFreshness` samples committed `managed_sync_import` receipts of the last 24 h (not first syncs or working-tree entries): commit time is the git committer time of `intent.target`, searchable is `completed_at`, embedded is the page's newest `content_chunks.embedded_at` once every chunk has one, sampled only from a receipt no later committed write to the same page supersedes and only at or after its `completed_at`; p50/p95 in one aggregate over the `persistence_requests_sync_watermark` predicate. #7604: the supersede check reads the newest committed sequence per (source, slug) once, over the rows after the oldest sample (a materialized CTE), so the read stays linear in the samples after a killed pass leaves tens of thousands of receipts (a per-receipt subquery is quadratic and reaches the 300 s statement timeout). `gbrain sync status` (the `freshness` block) and `gbrain status` print it; doctor `managed_sync_latency` grades p95 against `sync.freshness_target_seconds` (default 300; fail over max(1 h, target)) only with `sync.on_commit` on or a target set. Tests: `test/serve-head-watcher.test.ts`, `test/serve-head-watcher-managed.serial.test.ts`, `test/serve-http-head-watcher.serial.test.ts`, `test/sync-freshness-6858.test.ts`. #7189: each `SourceFreshness` carries `behind` (`readGitBehind`, injectable `BehindReader`: `rev-list --count <last_commit>..HEAD` and the oldest of those commits' committer age; null without a checkout or a synced commit), printed by `formatSyncFreshness`.
-- `src/core/persistence/sync-status.ts` (status coherence) — GBRA-150: `state: blocked` means the source cannot advance (the drain outcome's meaning); a file hold that waits on a person while the source keeps syncing reads `synced` with reason `held_needs_human`, `needs_human` and `next` unchanged (`test/sync-status-blocked-definition.test.ts`); `detail` adds `landing` / `landing_read` (`landing-gaps.ts`). #7189: a `last_error` whose cursor failure row (`op_checkpoints` `managed-sync-failure`) is older than the source's newest committed managed-sync receipt carries `superseded` and sets neither `needs_human`, `state` nor `next` (`liveError`); `needs_human_from` names the hold or the error. #7243 (GBRA-133 PR 3a): every status carries `last_commit` (`sources.last_commit`) and `live` (the drain-lease holder still renewing it, from `readDrainLease`, read only when the source read's `gbrain_cycle_locks` probe finds a row, with `job_id` for a Minions sync job and `stalled` from `holderStalled` on the lease read's database clock (`db_now`); #7596: a holder that stopped renewing the lease (`readDrainLease`, `drainLeaseLive`) is not `live`, and an open pass with no live holder reads `pass_interrupted` (`passStatusState`) with an `interrupted` block (pass, last row write, the dead holder), which `sync-blocked.ts` also lists for doctor `managed_sync_blocked`; test `test/sync-pass-interrupted-7596.test.ts`; `live_job_id` also takes a job holder of a pass); `supersedingAttempt` marks a `last_error` `superseded` (`by`, `age_seconds`) when evidence newer than the failure row passed its phase (`resume` < `discovery` < `freeze`/`admission` < `receipt`/`checkpoint`; evidence: the pass row's `started_at` (pin), a level read (`timings_ms` set or an `up_to_date` idle tick), an uncommitted managed import or delete admitted later, a later commit). The CLI (`sync/operator.ts` `holdsListing`) bounds the holds: `holds_summary` (`topCounts` by code and by state: `needs_human`, `actionable`, `held`) over every hold, then `PLAIN_STATUS_HOLDS` (20) rows needs-human first, or with `--detail` a page of the shared listing contract (`bounded-listing.ts`, kind `sync_status_holds:<source>:<state>`, `--limit`/`--cursor`/`--all`, `--hold-state`), `holds_page` only when a page left rows out or took a cursor, the rows last. Test: `test/sync-status-truthful-7243.test.ts` (both engines). #7679: `worktree_refresh` is the active refresh of the source's worktree (read in the source statement, so no extra statement) with its holder, `liveness`/`orphaned` and fix; an orphaned one's `--resume` fix becomes `next` unless a person's decision comes first. GBRA-287: a `last_error` from a run that stopped before any write request was admitted (discovery, freeze, admission) carries `request_id: null` explicitly, since no receipt, root request or `write_error_detail` exists; `holdVerdict` classifies a `page_write_failed` freeze hold whose `write_failure.code` is a page-body code (`PAGE_BODY_FAULT_CODES`) by its `freeze_page_body_*` row.
+- `src/core/persistence/sync-status.ts` (status coherence) — GBRA-150: `state: blocked` means the source cannot advance (the drain outcome's meaning); a file hold that waits on a person while the source keeps syncing reads `synced` with reason `held_needs_human`, `needs_human` and `next` unchanged (`test/sync-status-blocked-definition.test.ts`); `detail` adds `landing` / `landing_read` (`landing-gaps.ts`). #7189: a `last_error` whose cursor failure row (`op_checkpoints` `managed-sync-failure`) is older than the source's newest committed managed-sync receipt carries `superseded` and sets neither `needs_human`, `state` nor `next` (`liveError`); `needs_human_from` names the hold or the error. #7243 (GBRA-133 PR 3a): every status carries `last_commit` (`sources.last_commit`) and `live` (the drain-lease holder still renewing it, from `readDrainLease`, read only when the source read's `gbrain_cycle_locks` probe finds a row, with `job_id` for a Minions sync job and `stalled` from `holderStalled` on the lease read's database clock (`db_now`); #7596: a holder that stopped renewing the lease (`readDrainLease`, `drainLeaseLive`) is not `live`, and an open pass with no live holder reads `pass_interrupted` (`passStatusState`) with an `interrupted` block (pass, last row write, the dead holder), which `sync-blocked.ts` also lists for doctor `managed_sync_blocked`; test `test/sync-pass-interrupted-7596.test.ts`; `live_job_id` also takes a job holder of a pass); `supersedingAttempt` marks a `last_error` `superseded` (`by`, `age_seconds`) when evidence newer than the failure row passed its phase (`resume` < `discovery` < `freeze`/`admission` < `receipt`/`checkpoint`; evidence: the pass row's `started_at` (pin), a level read (`timings_ms` set or an `up_to_date` idle tick), an uncommitted managed import or delete admitted later, a later commit). The CLI (`sync/operator.ts` `holdsListing`) bounds the holds: `holds_summary` (`topCounts` by code, by state: `needs_human`, `actionable`, `held`, and by `fault_code`, the `write_failure.code` a `page_write_failed` hold names) over every hold, then `PLAIN_STATUS_HOLDS` (20) rows needs-human first, or with `--detail` a page of the shared listing contract (`bounded-listing.ts`, kind `sync_status_holds:<source>:<state>:<filter>`, `--limit`/`--cursor`/`--all`, `--hold-state`), `holds_page` only when a page left rows out or took a cursor, the rows last. GST-1209 follow-up: `--slug <slug>` (slug or path) and `--code <code>` (hold code or `fault_code`) filter the rows before paging and echo as `holds_filter`; the summary stays over every hold. Tests: `test/sync-status-truthful-7243.test.ts` (both engines), `test/segmented-untiled-hold-gst1209.test.ts`. #7679: `worktree_refresh` is the active refresh of the source's worktree (read in the source statement, so no extra statement) with its holder, `liveness`/`orphaned` and fix; an orphaned one's `--resume` fix becomes `next` unless a person's decision comes first. GBRA-287: a `last_error` from a run that stopped before any write request was admitted (discovery, freeze, admission) carries `request_id: null` explicitly, since no receipt, root request or `write_error_detail` exists; `holdVerdict` classifies a `page_write_failed` freeze hold whose `write_failure.code` is a page-body code (`PAGE_BODY_FAULT_CODES`) by its `freeze_page_body_*` row.
- `src/core/persistence/resolve-paths.ts` — GBRA-150 `resolveSourcePaths`: what gbrain did with each file path of a source, by its own rules, so a landing check stops copying them. Per path: the sync slug (`resolveSlugForPath`), presence in the last synced commit and at HEAD (Git object reads), the skip reason (`unsyncableReason`, plus `typed_frontmatter` for a skipped metafile), the open hold, the live page by origin (`source_path`) and by slug (`slug_owner` when another file owns it, so a case-folded twin never reads as this file's page), a differing frontmatter `slug:`, chunk and embedding counts (`listEmbeddingStateRows` with its `slugs` filter), and one of `RESOLVE_PATH_STATES` with `searchable` (true / 'keyword' / false), `why` and an existing-command `fix`. Bounded: at most 200 paths, indexed lookups only, nothing written. A source whose `local_path` is relative refuses `sync_anchor_relative` (exit 3, an `ask_user` `gbrain sources set-path` fix). Tests: `test/sources-resolve-path.test.ts`.
- `src/core/page-searchability.ts` — #7190 `readPageSearchability`: each live page's state, `searchable: true | 'keyword' | false`, chunks, `unembedded` (visible chunks with a NULL active-column vector) and `embedding_hold`, folded from `listEmbeddingStateRows` and the budget-hold read. Shared by resolve-path and `get_write_request`'s `applied`; `gbrain pages status` (#7181) can compose it with its Git view.
- `src/core/persistence/applied-watermark.ts` — #7190 `readAppliedWatermark` (sources status, MCP `sources_status`, `sync --json`) and the cheap `readWriteWatermark` (`get_write_request`): `indexed_through` is `sources.last_commit` (only a finished pass moves it), `embedded_through` reads the oldest page with a NULL vector (held pages count), `committed_through_request` is one below the oldest unsettled request of the incarnation, `pending` adds requests, files behind HEAD, held files and withheld deletes, `writer_heartbeat` is the drain-lease holder and its last progress (redacted for remote callers).
diff --git a/docs/guides/repair.md b/docs/guides/repair.md
index c334b52dd2..5b92e7812f 100644
--- a/docs/guides/repair.md
+++ b/docs/guides/repair.md
@@ -423,14 +423,21 @@ write's staging (and deleted its staged rows) while the write prepared, and
the write's last preparation step moved the staging back to `prepared`. The
publish then passed its staging check, closed the page's old rows and
published none. Every read of such a page refuses `page_body_rows_unreadable`,
-and a managed sync holds its file `page_write_failed` on every retry.
+and a managed sync holds its file `page_write_failed` on every retry; that
+hold reads `needs_human` with `safe_actions: ["repair"]`, and its fix is this
+repair's preview for the page (`gbrain sync status --source <id> --code
+page_body_rows_unreadable --json` lists it).
Current versions refuse both steps with `body_staging_expired` (send the write
again), but upgrading rewrites nothing, so a page damaged earlier stays
unreadable until this repair runs.
Doctor `segmented_tiling` lists such pages: source, slug, live generation,
how many rows it has, the bytes they cover (or that they leave a gap) and the
-body size. It reads the manifest only and writes nothing.
+body size. It reads the manifest only and writes nothing. It skips archived
+sources, runs as its own doctor entry, and its fix names the first damaged
+source (`--source`) with the other sources' commands. A preview lists at most
+1,000 pages; one that finds more reports `truncated`, so preview again after
+the apply.
To republish them from Git, preview, then apply after the user agrees:
diff --git a/docs/guides/sync-unblock-runbook.md b/docs/guides/sync-unblock-runbook.md
index 1542615ed1..153eb06209 100644
--- a/docs/guides/sync-unblock-runbook.md
+++ b/docs/guides/sync-unblock-runbook.md
@@ -51,10 +51,13 @@ moving again; ask me only about the ones gbrain will not decide by itself."*
names the process holding its drain lease (a serve pass, a sync job, a CLI
sync), with its heartbeat, `progress` and `stalled`; null means nothing is
syncing it now. Holds are bounded: `holds_summary` counts every hold by
- code and by state (`needs_human`, `actionable`, `held`), and `holds` lists
- the first 20, needs-human first. When it leaves rows out, `holds_page`
- names `next_command`; `--detail` pages 100 at a time, `--hold-state
- needs_human` lists only the holds a person decides. A `last_error` with
+ code, by state (`needs_human`, `actionable`, `held`) and by `fault_code`
+ (the failure a `page_write_failed` hold recorded, which each such hold
+ also names), and `holds` lists the first 20, needs-human first. When it
+ leaves rows out, `holds_page` names `next_command`; `--detail` pages 100
+ at a time, `--hold-state needs_human` lists only the holds a person
+ decides, and `--slug <slug>` or `--code <code>` (a hold code or a
+ `fault_code`) lists the one hold you are looking for without paging. A `last_error` with
`superseded` (`by`, `age_seconds`) is history: a later attempt got past
the phase it failed in, so it drives neither `state` nor `next`.
2. If `needs_human` is false and nothing committed in the last ten minutes,
@@ -149,7 +152,7 @@ Every hold and error has three fields, from one table
| `legacy_slug_conflict` | page | none | yes | always: only a person decides which legacy page the file takes over |
| `settle_mismatch` | page | none | yes | always: the pass cannot tell why the path does not settle |
| `freeze_page_body_segmented` | page | upgrade | yes | always: a sync path read a page stored in segments whole |
-| `freeze_page_body_rows_unreadable` | page | retry | no | the page stays unreadable across syncs (a grant or row-level security policy hides its segment rows) |
+| `freeze_page_body_rows_unreadable` | page | repair | yes | always: the page's segment rows do not cover its stored body, so no sync can read it |
| `page_write_failed` | page | upgrade | yes | always: the writer cannot place the failure |
| `file_unreadable` | page | none | yes | always: only a change to the checkout makes the file readable |
| `visibility_noncanonical` | page | none | yes | always: only an edit to the file clears it |
diff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsv
index e030120414..979342b874 100644
--- a/scripts/module-size-limits.tsv
+++ b/scripts/module-size-limits.tsv
@@ -47,4 +47,4 @@ src/commands/doctor/checks/extraction-sync.ts 1500 ratchet +7 GBRA-130 A-1: link
src/core/search/evidence-delivery.ts 1759 ratchet +5 W5: EvidencePlan.rankCut resolved with the plan (logic in search/page-rank-cut.ts); +20 W5 whole_pages: wholeCost prices a block as delivery would emit it whole (needs the private Block/enrichBlock internals) and the cut is wired before allocate (cutWholePages lives in search/page-rank-cut.ts); new row: crossed the 1500 unlisted cap at the #6367 merge (master 1479, its explicit-budget cap) by the C1 date header threaded through every block path, cap included; pagePlanHits (search/page-plan-hits.ts) and the header loader (evidence-date.ts blockDateHeaders) were peeled first; peel candidate: allocateCapped; +8 at the #6396 merge: page evidence text cut through the fence-chunk trust overlay and the caller minTrust floor (re-summed: our 1504 + master +8); +119 Cat 40 next wave F2: the search.long_page_unit policy (withLongPagePolicy, selectLongPages size preflight with page/byte/deadline limits) and the long-page fetch and fallback in deliverEvidence, kept in the shared seam the plan names (gbrain-evals docs/plans/2026-10-11-cat40-next-wave, F2); +17 F2 rework to the frozen-comparison policy: search.long_page_min_chars (rendered-body characters, default 20,000) read in withLongPagePolicy, a character count in the preflight, the rendered-body confirmation in deliverEvidence, and the long-page row exemption in capDeliveredSnippets (re-summed at the 0.60.225.0 merge: master 1537 + F2 136); +39 Wave B PR 2 lane 2b: planSegmentedBlock joins the windows search/segmented-evidence.ts reads around a segmented page's hits into one run-marked document (needs the private Doc/Piece/buildDoc/locateAnchor internals), planBlock's unit cut split into blockFromDoc for both, sections bounded by their run, selectionCost counts a gap between runs, and the fetch skips the whole-body fence overlay for a segmented page; +4 segmented pages read at once before planning (segmentedReads; the read is search/segmented-evidence.ts, the statements page-body/read-range.ts); +17 GBRA-156: tail trim plan flag, DeliverOptions.query, DeliveryMeta.tail_trim, the trim call and the frozen-hit score/query library fields (logic in search/evidence-tail-trim.ts; interface fields cannot move); +7 GBRA-205: EvidencePlan.titleHeader and DeliveryMeta.title_header (interface fields cannot move) and the titles option on the header loader (logic in search/evidence-date.ts; the query budget key lives in search/evidence-packing.ts); +11 #7600: assemble_evidence quotes conversation rows and capEvidenceToBudget counts the quote fence (logic in search/transcript-quote.ts); +2 GBRA-156 /ship review: the cut-path admission and title room count the quote fence; +2 GBRA-156 /ship review pass 2: capEvidenceToBudget counts the fence only for the paths that fence (quote flag; recall counts the text as returned); +4 GST-687: page evidence and the extractive fallback quote below-owner-tier text for untrusted readers (untrusted flag; logic in search/transcript-quote.ts)
src/commands/config.ts 1524 ratchet new row: crossed the 1500 unlisted cap in wave 15 P7.4 #5461: set-time validation of think.pages_budget_chars / think.excerpt_ceiling_chars (range + parser live in core/think/pages-budget.ts), mirroring the cycle.consolidate.cluster_threshold hook; +1 wave 16 G5.1 (#6495): set-time refusal hook for search.keyword_statement_timeout_ms (check lives in commands/config/keyword-timeout-value.ts); +1 wave 18b lane 5 (#5012 item 6): search.contextual_retrieval prints the existing-pages hint after the write (text lives in commands/config/contextual-mode-hint.ts); +1 #6712 PR 2: retired/rollback sync key dispatch line (logic in core/sync-config-keys.ts handleSyncKeyConfig); +1 #6865: sync.slug_conflicts.auto_remove boolean validation at set time (refusal text in repair/slug-autoheal.ts); +1 #6948: sync.origin_twins.auto_resolve boolean validation at set time (refusal text in repair/origin-twins-heal.ts); +2 #6795: config set chat_model/expansion_model help line and the model-pin import (shadow report and file-pin unset live in commands/config/model-pin-shadow.ts); +1 #6712 PR 4b: sync.admission set-time hook (value logic in commands/config/sync-admission-value.ts); +4 #7130: set-time refusal hook for sync.max_deletes / sync.max_delete_ratio (and .source.<id>) / purge.retention_hours (check lives in core/sync-reconcile.ts deleteSafetyConfigRefusal); +1 GBRA-150: sync.metafile_pages set-time route (body in config/sync-metafile-pages-value.ts); re-summed at the v0.60.330.0 merge (1520 measured); +2 #7242 minions.terminal_hook file-plane key and its set branch (logic in minions/terminal-hook.ts); +1 GBRA-161: generations.* set-time route (refusal in commands/config/generations-values.ts); +1 GBRA-207 #7630: sync.repo_path set-time refusal hook (refusal in core/sync-config-keys.ts syncRepoPathRefusal)
src/commands/mcp-expose.ts 1519 ratchet hosted_option: Session carries the gbrain.io coaching notice on the first-receipt run and Tailscale/service friction exits (copy, refs and gating live in core/onboard/hosted-option.ts); +7 GBRA-199: --surface help lines, surfaceChosen option field and the advertise pass-through (registrationAdvertise in core/mcp-registration.ts)
-src/core/behavior-change-notice.ts 1618 ratchet +3 GBRA-200 comment, write-grant refusal and degraded-stamp rows (re-summed at the 0.60.562.0 merge: 1615 + 3); the BEHAVIOR_CHANGES table grows by one row per disclosed change: +4 the #7891 provenance-drift and #7917/#7918 maintenance-lowering rows and their comments (re-summed at the 0.60.495.0 merge: 1547 + 4); +2 GBRA-205 saved_facts_stems row and its comment (re-summed at the #7901 0.60.492.0 merge: 1541 + 2); +2 GBRA-205 search.query_facts_block default-on row and its approval comment (re-summed at the #7610 0.60.490.0 merge: 1539 + 2); +2 the #7900 content checkpoint host-move row (since TBD until the merge slot), +2 the #7897 private-hold sweep row (since TBD until the merge slot), +2 the #7880 ingest_capture and company-brain private-hold row (since TBD until the merge slot), +5 the frozen-source wave comment and four rows (#7868, #7850, #7869/#7870, #7871), +2 the #7848 visibility_noncanonical hold row (since TBD until the merge slot), +2 the #7846 extract_atoms session-source row (re-summed at the 0.60.481.0 merge: master 1524 + 2), +2 the #7805 synthesize session-source and #7841 visibility_not_applied rows (re-summed at the 0.60.480.0 merge: master 1522 + 2), +2 strict door planned-state row (#7705, re-summed at the 0.60.470.0 merge: master 1514 + 2), +2 Bun floor 1.4.4 row (#7644), the GBRA-95 RLS backfill row (+2), +3 rows for #7596 pass_interrupted, #7599 read-only serve and the --access=read-only ceiling, +1 G5 lane C trust_release row, +1 #7619 cli_flag_equals, +3 GBRA-207 #7630 relative-anchor and stalled-write rows, +2 the #7632 function search_path disclosure row and +2 the #7679 orphaned worktree refresh row (re-summed at the 0.60.471.0 merge: master 1516 + 2), +2 the #7814 retired v0.13.1 grandfather row, +2 the #7618 conversion withhold/progress/push row (master 1520 + 2); the behavior-change table split (#7607) retires this row; +4 GBRA-188 #7489: the wave comment and three rows (brain-first instructions, starter surface default, per-turn rule); +1 GBRA-188 plugin_turn_hook_gbra188 row; +1 GBRA-242 provider_key_rules_7959 row (#7959), +2 the GBRA-199 registration_lists_verbs row (since TBD until the merge slot); +2 GBRA-133 #7652: the #7611 pass_abandoned reader row and the lean read-only serve socket row (re-summed at the 0.60.503.0 merge: master 1555 + 2); +1 GBRA-243: the per-turn hook disclosure row (rows are data and cannot move); +4 GBRA-156 #7598 harness wave comment and rows (remote page cap, sources_not_readable refusal, sources add next step); +4 GBRA-156 #7601 search_quotes_transcript_rows comment and row; +1 GBRA-175 #7475 autopilot_restarts_serve_7475 row (re-summed at the #8012 merge: 1566 + 1); +3 #7997/#8014/#8015 rows (redaction markers, company db_only keep, ignored supabase_only scope); +2 #7199 (re-port of #7228) classic_drift_rescreen_7199 comment and row; +2 #7931 file_drift_agrees_7931 comment and row; +1 #7950 file_drift_slug_release_7950 row; +1 #7974 file_drift_followups_7974 row; +1 #8059 quoted_fence_marker_8059 row; +2 GBRA-247 #8009 provenance_repair_held_8009 and #7982 pass_transient_streak_7982 rows; +4 GBRA-247 #7973 plain_directory_sync_7973, #7988 managed_marker_own_directory_7988, #7985 former_binding_parked_group_7985 and settle_effects_retire_7985 rows Train S merge: 1570 base + 5 (master since the #8077 base) + 13 (#8077) = 1588.; +2 GST-687 remote_quotes_unverified_text_gst687 row and its comment (re-summed at the gate-ahead on train S 0.60.534.0: 1588 + 2); +2 #8377: the quote fence follow-ups row and its comment; +2 #8384: the quote fence follow-ups 2 row and its comment; +2 #8384 wave 3: the quote fence follow-ups 3 row and its comment; +5 GBRA-218 train M rows (A1 member_read_access_gbra218 and member_access_hatch_scope_gbra218, B shared_agent_audience_gbra231, A2 folder_access_rules_gbra218, folder_access_scoped_role_gbra218), re-summed at the train M merge of master v0.60.541.0: 1596 + 5 = 1601 measured; +3 GST-359 train C rows (C1 qm_attested_actor_gst359, C2 member_facts_gst359, D qm_memory_provider_gst359), re-summed at the train C merge of master v0.60.543.0: 1601 + 3 = 1604 measured; +2 #8424: hook_launcher_8424 row and its comment (rows are data and cannot move), re-summed at the #8418 v0.60.546.0 merge: 1604 + 2 = 1606 measured; +2 #8426: mcp_lane_launcher_8426 row and its comment (rows are data and cannot move); +2 GST-927: empty_nonstring_args_gst927 row and its comment, re-summed at the gate-ahead on master v0.60.550.0 plus #8420: 1610 measured; +2 GBRA-283 Wave A (#8460): engine_keyed_caches_gbra283 row and its comment (rows are data and cannot move); +2 GBRA-287: segmented_freeze_hold_gbra287 and segmented_reexport_gbra287 rows (rows are data and cannot move); +1 GST-1209: segmented_tiling_gst1209 row (rows are data and cannot move)
+src/core/behavior-change-notice.ts 1619 ratchet +3 GBRA-200 comment, write-grant refusal and degraded-stamp rows (re-summed at the 0.60.562.0 merge: 1615 + 3); the BEHAVIOR_CHANGES table grows by one row per disclosed change: +4 the #7891 provenance-drift and #7917/#7918 maintenance-lowering rows and their comments (re-summed at the 0.60.495.0 merge: 1547 + 4); +2 GBRA-205 saved_facts_stems row and its comment (re-summed at the #7901 0.60.492.0 merge: 1541 + 2); +2 GBRA-205 search.query_facts_block default-on row and its approval comment (re-summed at the #7610 0.60.490.0 merge: 1539 + 2); +2 the #7900 content checkpoint host-move row (since TBD until the merge slot), +2 the #7897 private-hold sweep row (since TBD until the merge slot), +2 the #7880 ingest_capture and company-brain private-hold row (since TBD until the merge slot), +5 the frozen-source wave comment and four rows (#7868, #7850, #7869/#7870, #7871), +2 the #7848 visibility_noncanonical hold row (since TBD until the merge slot), +2 the #7846 extract_atoms session-source row (re-summed at the 0.60.481.0 merge: master 1524 + 2), +2 the #7805 synthesize session-source and #7841 visibility_not_applied rows (re-summed at the 0.60.480.0 merge: master 1522 + 2), +2 strict door planned-state row (#7705, re-summed at the 0.60.470.0 merge: master 1514 + 2), +2 Bun floor 1.4.4 row (#7644), the GBRA-95 RLS backfill row (+2), +3 rows for #7596 pass_interrupted, #7599 read-only serve and the --access=read-only ceiling, +1 G5 lane C trust_release row, +1 #7619 cli_flag_equals, +3 GBRA-207 #7630 relative-anchor and stalled-write rows, +2 the #7632 function search_path disclosure row and +2 the #7679 orphaned worktree refresh row (re-summed at the 0.60.471.0 merge: master 1516 + 2), +2 the #7814 retired v0.13.1 grandfather row, +2 the #7618 conversion withhold/progress/push row (master 1520 + 2); the behavior-change table split (#7607) retires this row; +4 GBRA-188 #7489: the wave comment and three rows (brain-first instructions, starter surface default, per-turn rule); +1 GBRA-188 plugin_turn_hook_gbra188 row; +1 GBRA-242 provider_key_rules_7959 row (#7959), +2 the GBRA-199 registration_lists_verbs row (since TBD until the merge slot); +2 GBRA-133 #7652: the #7611 pass_abandoned reader row and the lean read-only serve socket row (re-summed at the 0.60.503.0 merge: master 1555 + 2); +1 GBRA-243: the per-turn hook disclosure row (rows are data and cannot move); +4 GBRA-156 #7598 harness wave comment and rows (remote page cap, sources_not_readable refusal, sources add next step); +4 GBRA-156 #7601 search_quotes_transcript_rows comment and row; +1 GBRA-175 #7475 autopilot_restarts_serve_7475 row (re-summed at the #8012 merge: 1566 + 1); +3 #7997/#8014/#8015 rows (redaction markers, company db_only keep, ignored supabase_only scope); +2 #7199 (re-port of #7228) classic_drift_rescreen_7199 comment and row; +2 #7931 file_drift_agrees_7931 comment and row; +1 #7950 file_drift_slug_release_7950 row; +1 #7974 file_drift_followups_7974 row; +1 #8059 quoted_fence_marker_8059 row; +2 GBRA-247 #8009 provenance_repair_held_8009 and #7982 pass_transient_streak_7982 rows; +4 GBRA-247 #7973 plain_directory_sync_7973, #7988 managed_marker_own_directory_7988, #7985 former_binding_parked_group_7985 and settle_effects_retire_7985 rows Train S merge: 1570 base + 5 (master since the #8077 base) + 13 (#8077) = 1588.; +2 GST-687 remote_quotes_unverified_text_gst687 row and its comment (re-summed at the gate-ahead on train S 0.60.534.0: 1588 + 2); +2 #8377: the quote fence follow-ups row and its comment; +2 #8384: the quote fence follow-ups 2 row and its comment; +2 #8384 wave 3: the quote fence follow-ups 3 row and its comment; +5 GBRA-218 train M rows (A1 member_read_access_gbra218 and member_access_hatch_scope_gbra218, B shared_agent_audience_gbra231, A2 folder_access_rules_gbra218, folder_access_scoped_role_gbra218), re-summed at the train M merge of master v0.60.541.0: 1596 + 5 = 1601 measured; +3 GST-359 train C rows (C1 qm_attested_actor_gst359, C2 member_facts_gst359, D qm_memory_provider_gst359), re-summed at the train C merge of master v0.60.543.0: 1601 + 3 = 1604 measured; +2 #8424: hook_launcher_8424 row and its comment (rows are data and cannot move), re-summed at the #8418 v0.60.546.0 merge: 1604 + 2 = 1606 measured; +2 #8426: mcp_lane_launcher_8426 row and its comment (rows are data and cannot move); +2 GST-927: empty_nonstring_args_gst927 row and its comment, re-summed at the gate-ahead on master v0.60.550.0 plus #8420: 1610 measured; +2 GBRA-283 Wave A (#8460): engine_keyed_caches_gbra283 row and its comment (rows are data and cannot move); +2 GBRA-287: segmented_freeze_hold_gbra287 and segmented_reexport_gbra287 rows (rows are data and cannot move); +1 GST-1209: segmented_tiling_gst1209 row (rows are data and cannot move); +1 GST-1209 follow-up: untiled_hold_repair_gst1209 row (rows are data and cannot move)
diff --git a/src/commands/doctor/checks/graph-health.ts b/src/commands/doctor/checks/graph-health.ts
index dba14a82a0..671901e904 100644
--- a/src/commands/doctor/checks/graph-health.ts
+++ b/src/commands/doctor/checks/graph-health.ts
@@ -340,6 +340,24 @@ export const derivedVisibilityEntry: DoctorEntry = {
run: runDerivedVisibility,
};
+/**
+ * GST-1209 follow-up: damaged segmented pages are their own entry with their own budget, so a default run reports the
+ * finding even when the wave checks of timeline_history run out of theirs (and never serves an older entry's last known result for it).
+ */
+async function runSegmentedTiling(ctx: DoctorContext): Promise<Check[]> {
+ ctx.progress.heartbeat('segmented_tiling');
+ const { segmentedTilingCheck } = await import('./segmented-tiling.ts');
+ const checks: Check[] = [];
+ checks.push(await segmentedTilingCheck(connectedEngine(ctx), ctx.orphanRatioSourceId ? [ctx.orphanRatioSourceId] : undefined));
+ return checks;
+}
+
+export const segmentedTilingEntry: DoctorEntry = {
+ name: 'segmented_tiling',
+ emits: ['segmented_tiling'],
+ run: runSegmentedTiling,
+};
+
export const timelineHistoryEntry: DoctorEntry = {
name: 'timeline_history',
emits: [
@@ -361,7 +379,6 @@ export const timelineHistoryEntry: DoctorEntry = {
'unbound_source',
'writer_version',
'segmented_storage',
- 'segmented_tiling',
'self_capture',
'vector_plan',
'keyword_plan',
diff --git a/src/commands/doctor/checks/segmented-tiling.ts b/src/commands/doctor/checks/segmented-tiling.ts
index 097a48f720..e23fea9b93 100644
--- a/src/commands/doctor/checks/segmented-tiling.ts
+++ b/src/commands/doctor/checks/segmented-tiling.ts
@@ -23,8 +23,10 @@ export async function segmentedTilingCheck(engine: BrainEngine, sourceIds?: read
return { name, status: 'fail', details: { pages, truncated: found.length > SAMPLE, sources, docs: DOCS },
message: `${found.length > SAMPLE ? `More than ${SAMPLE}` : found.length} live page(s) stored in segments have segment rows that do not cover their body, so every read of them refuses `
+ `(page_body_rows_unreadable) and a sync holds their file: ${listed.join('; ')}. Preview the repair; it republishes each page from its file at HEAD only when applied with the user's agreement.`,
- fix: agentFix(['gbrain', 'repair', 'segmented-tiling', ...(sources.length === 1 ? ['--source', sources[0]!] : [])],
- 'Previews republishing each listed page from its file at HEAD and writes nothing; applying it needs the user\'s agreement and the printed preview hash.', name, { docs: DOCS }) };
+ fix: agentFix(['gbrain', 'repair', 'segmented-tiling', '--source', sources[0]!],
+ 'Previews republishing each listed page of that source from its file at HEAD and writes nothing; applying it needs the user\'s agreement and the printed preview hash.'
+ + (sources.length > 1 ? ` The listed pages also span ${sources.slice(1).map(source => `gbrain repair segmented-tiling --source ${source}`).join(', ')}${found.length > SAMPLE ? ` (from the first ${SAMPLE} pages; run the check again after each repair)` : ''}.` : ''),
+ name, { docs: DOCS }) };
} catch (error) {
return checkError(name, 'read the segment rows of pages stored in segments', error);
}
diff --git a/src/commands/doctor/last-known.ts b/src/commands/doctor/last-known.ts
index 7d9b556aa2..7cac2fac4f 100644
--- a/src/commands/doctor/last-known.ts
+++ b/src/commands/doctor/last-known.ts
@@ -41,7 +41,11 @@ export const BACKGROUND_REFRESH_KEY = 'doctor.background_refresh';
/** Bound of the cache read and write (they run outside every entry's deadline). */
const IO_BOUND_MS = 3_000;
-export interface LastKnownEntry { checks: Check[]; measured_at: string; elapsed_ms: number }
+/**
+ * `emits`: the checks the entry emitted when it was recorded. A check the entry emits now and did not then (added by a later
+ * release, or a result recorded before `emits` was stored and not among its checks) has no last known result.
+ */
+export interface LastKnownEntry { checks: Check[]; measured_at: string; elapsed_ms: number; emits?: string[] }
/** What a run asks of the last known results: `serve` reports them for entries it did not finish; `record` stores the ones it did. */
export interface LastKnownMode { serve: boolean; record: boolean; refresh: boolean }
@@ -74,7 +78,8 @@ export async function readLastKnown(engine: BrainEngine): Promise<Map<string, La
/** Store the entries this run finished (best-effort: a read-only role or an old schema just keeps the previous results). */
export async function writeLastKnown(engine: BrainEngine, outcomes: readonly EntryOutcome[], now = Date.now()): Promise<void> {
const rows = outcomes.filter(o => o.state === 'done').map(o => ({ entry: o.entry.name,
- value: { checks: o.checks.filter(c => c.details?.last_known === undefined), measured_at: new Date(now).toISOString(), elapsed_ms: o.elapsed_ms } satisfies LastKnownEntry }));
+ value: { checks: o.checks.filter(c => c.details?.last_known === undefined), measured_at: new Date(now).toISOString(), elapsed_ms: o.elapsed_ms,
+ emits: [...o.entry.emits] } satisfies LastKnownEntry }));
if (!rows.length) return;
try {
await bounded(engine.executeRaw(
@@ -116,7 +121,11 @@ export function applyLastKnown(checks: Check[], outcomes: readonly EntryOutcome[
if (outcome.state === 'done') continue;
if (!last || !(age <= REFRESH_AFTER_MS)) refresh.push(outcome.entry.name);
if (last && age <= LAST_KNOWN_MAX_AGE_MS) {
- if (outcome.state === 'expired') for (const name of outcome.entry.emits) replaced.add(name);
+ // GST-1209 follow-up: a check the recorded result never covered keeps this run's unknown (expired) or is named unmeasured (not run).
+ const covered = new Set(last.emits ?? last.checks.map(c => c.name));
+ const uncovered = outcome.entry.emits.filter(name => !covered.has(name));
+ if (outcome.state === 'expired') for (const name of outcome.entry.emits) if (covered.has(name)) replaced.add(name);
+ if (outcome.state === 'not_run' && uncovered.length) stale.push({ ...outcome, entry: { ...outcome.entry, emits: uncovered } });
served.push(...last.checks.map(c => lastKnownCheck(c, last.measured_at, outcome.state === 'expired' ? 'budget' : 'not_in_tier', now)));
} else if (outcome.state === 'not_run') {
stale.push(outcome);
diff --git a/src/commands/doctor/registry.ts b/src/commands/doctor/registry.ts
index 0cac843d8d..68e826c79c 100644
--- a/src/commands/doctor/registry.ts
+++ b/src/commands/doctor/registry.ts
@@ -64,6 +64,7 @@ import {
derivedVisibilityEntry,
graphCoverageEntry,
orphanRatioEntry,
+ segmentedTilingEntry,
staleMentionsEntry,
timelineHistoryEntry,
} from './checks/graph-health.ts';
@@ -237,6 +238,7 @@ export const DOCTOR_CHECK_REGISTRY: readonly DoctorEntry[] = [
graphCoverageEntry,
orphanRatioEntry,
staleMentionsEntry,
+ segmentedTilingEntry,
timelineHistoryEntry,
extractionDateGroundingEntry,
integrityEntry,
diff --git a/src/commands/doctor/wave-checks.ts b/src/commands/doctor/wave-checks.ts
index 1b07f07e3a..2b5b335f82 100644
--- a/src/commands/doctor/wave-checks.ts
+++ b/src/commands/doctor/wave-checks.ts
@@ -259,7 +259,7 @@ export const WAVE_CHECKS: readonly WaveCheckSpec[] = [
run: async engine => (await import('./checks/segmented-storage.ts')).segmentedStorageCheck(engine),
},
{
- id: 'segmented_tiling', resolution: 'operator', registration: 'wave',
+ id: 'segmented_tiling', resolution: 'operator', registration: 'doctor.ts',
hostOnly: 'It lists page slugs, and the repair it names runs only from the trusted local CLI on the brain host.',
impact: 'Some pages stored in segments have segment rows that do not cover their body, so every read of them refuses and sync holds their files',
instruction: 'Preview `gbrain repair segmented-tiling --source <id>` (read-only), show the user the listing, and apply it with the printed --expect hash only after they agree; it republishes each page from its file at HEAD and never runs automatically.',
diff --git a/src/commands/sync/operator.ts b/src/commands/sync/operator.ts
index ef38d1a257..14bf326257 100644
--- a/src/commands/sync/operator.ts
+++ b/src/commands/sync/operator.ts
@@ -30,6 +30,7 @@ const SUPERSEDED_TEXT: Record<NonNullable<NonNullable<SyncStatus['last_error']>[
export function printSyncStatusHelp(): void {
console.log(`Usage: gbrain sync status --source <id> [--detail] [--json]
[--limit <n>] [--cursor <next_cursor>] [--all] [--hold-state <state>]
+ [--slug <slug>] [--code <code>]
Where a managed catch-up stands and what to do next, for an operator agent:
the newest sync pass (convergence: outcome, round, candidates, settled,
@@ -69,12 +70,15 @@ Every status names last_commit (the commit sync applied through) and live (the
process holding the drain lease, a serve pass included, with its heartbeat and
progress; null when nothing holds it).
-Holds are bounded: holds_summary counts every hold by code and by state
-(needs_human | actionable | held), then holds lists the first ${PLAIN_STATUS_HOLDS}
+Holds are bounded: holds_summary counts every hold by code, by state
+(needs_human | actionable | held) and by fault_code (the failure a
+page_write_failed hold recorded), then holds lists the first ${PLAIN_STATUS_HOLDS}
(needs_human first). With --detail the list pages (100 per page): holds_page
carries returned, limit, complete, next_cursor and next_command; --limit <n>
sets the page size, --cursor <next_cursor> prints the next page, --all prints
-every hold, and --hold-state <state> lists only that state.
+every hold, and --hold-state <state> lists only that state. --slug <slug>
+lists the hold on one slug (or path) and --code <code> the holds with that
+code or fault_code, so one hold is found without paging.
Decision table: docs/guides/sync-unblock-runbook.md
`);
@@ -165,18 +169,31 @@ const holdState = (hold: SyncStatusHold): HoldState => hold.needs_human ? 'needs
*/
function holdsListing(holds: readonly SyncStatusHold[], args: string[], sourceId: string) {
const { request, rest } = parseListingFlags(args, 'gbrain sync status');
- const stateAt = rest.indexOf('--hold-state');
- const state = stateAt >= 0 ? rest[stateAt + 1] : undefined;
- if (stateAt >= 0 && !HOLD_STATES.includes(state as HoldState)) {
- throw opError('invalid_params', `--hold-state must be one of ${HOLD_STATES.join(', ')} (got "${state ?? ''}").`, `Example: gbrain sync status --source ${sourceId} --detail --hold-state needs_human --json`);
+ const value = (flag: string, example: string) => {
+ const at = rest.indexOf(flag);
+ if (at < 0) return undefined;
+ const given = rest[at + 1];
+ if (given === undefined || given === '' || given.startsWith('--')) throw opError('invalid_params', `${flag} needs a value.`, `Example: gbrain sync status --source ${sourceId} ${flag} ${example} --json`);
+ return given;
+ };
+ const state = value('--hold-state', 'needs_human');
+ if (state !== undefined && !HOLD_STATES.includes(state as HoldState)) {
+ throw opError('invalid_params', `--hold-state must be one of ${HOLD_STATES.join(', ')} (got "${state}").`, `Example: gbrain sync status --source ${sourceId} --detail --hold-state needs_human --json`);
}
+ const slug = value('--slug', '<slug>');
+ const code = value('--code', 'page_write_failed');
+ const filter = { ...(slug ? { slug } : {}), ...(code ? { code } : {}) };
+ const listed = holds.filter(hold => (!state || holdState(hold) === state) && (!slug || hold.slug === slug || hold.path === slug)
+ && (!code || hold.code === code || hold.fault_code === code));
const sized = args.some(a => a === '--all' || a === '--limit' || a.startsWith('--limit='));
- const page = pageSortedRows(state ? holds.filter(hold => holdState(hold) === state) : holds, hold => [String(HOLD_STATES.indexOf(holdState(hold))), hold.path],
- args.includes('--detail') || sized ? request : { ...request, limit: PLAIN_STATUS_HOLDS }, `sync_status_holds:${sourceId}:${state ?? 'all'}`);
- const summary = { total: holds.length, by_code: topCounts(holds, hold => hold.code, 20), by_state: topCounts(holds, holdState, 20) };
+ const page = pageSortedRows(listed, hold => [String(HOLD_STATES.indexOf(holdState(hold))), hold.path],
+ args.includes('--detail') || sized ? request : { ...request, limit: PLAIN_STATUS_HOLDS }, `sync_status_holds:${sourceId}:${state ?? 'all'}:${JSON.stringify(filter)}`);
+ const faulted = holds.filter(hold => hold.fault_code);
+ const summary = { total: holds.length, by_code: topCounts(holds, hold => hold.code, 20), by_state: topCounts(holds, holdState, 20),
+ by_fault_code: topCounts(faulted, hold => hold.fault_code!, 20) };
const paging = page.complete && request.cursor === undefined ? null
: { returned: page.returned, limit: page.limit, complete: page.complete, next_cursor: page.next_cursor, next_command: nextListingCommand(['gbrain', 'sync', 'status', ...rest], page) };
- return { summary, paging, rows: page.rows };
+ return { summary, filter: Object.keys(filter).length ? filter : null, matched: listed.length, paging, rows: page.rows };
}
export async function runSyncStatus(engine: BrainEngine, args: string[]): Promise<void> {
@@ -206,7 +223,7 @@ export async function runSyncStatus(engine: BrainEngine, args: string[]): Promis
landing_read: read(status.landing_read), landing: status.landing?.status === 'ok' ? { ...status.landing, pages: status.landing.pages.map(page => ({ ...page, fix: page.fix ? renderAction(page.fix, ctx) : null })) } : status.landing,
capacity: { status: snapshot.status, pause_pct: snapshot.pause_pct, low: snapshot.low, paused: snapshot.paused }, freshness, notifier, ...(notices.length ? { notices } : {}),
// #7243: the holds come last, summary first, so a reader can stop before the rows.
- holds_summary: listing.summary, ...(listing.paging ? { holds_page: listing.paging } : {}), holds: listing.rows.map(hold => ({ ...hold, fix: renderAction(hold.fix, ctx) })) };
+ ...(listing.filter ? { holds_filter: listing.filter } : {}), holds_summary: listing.summary, ...(listing.paging ? { holds_page: listing.paging } : {}), holds: listing.rows.map(hold => ({ ...hold, fix: renderAction(hold.fix, ctx) })) };
if (args.includes('--json')) return writeJsonDocument(JSON.stringify(rendered, null, 2));
const c = status.cursor;
console.log(syncStatusHeadline(status));
@@ -227,10 +244,10 @@ export async function runSyncStatus(engine: BrainEngine, args: string[]): Promis
if (freshness) console.log(` freshness: ${formatSyncFreshness(freshness)}`);
if (notifierBlock) console.log(` ${formatNotifierBlock(sourceId, notifierBlock)}`);
console.log(` holds: ${status.holds.length}${status.holds.length ? ` (${status.holds.filter(h => h.needs_human).length} need a person)` : ''}; last error: ${status.last_error ? `${status.last_error.code} [${status.last_error.class}]` : 'none'}`);
- for (const hold of listing.rows) console.log(` ${hold.path}${hold.slug ? ` (${hold.slug})` : ''}: ${hold.code} [${hold.class}] safe: ${hold.safe_actions.join(',')}${hold.needs_human ? ` NEEDS HUMAN: ${hold.human_reason}` : ''}${hold.attempts > 1 ? ` (held ${hold.attempts} times)` : ''}`);
+ for (const hold of listing.rows) console.log(` ${hold.path}${hold.slug ? ` (${hold.slug})` : ''}: ${hold.code}${hold.fault_code ? ` (${hold.fault_code})` : ''} [${hold.class}] safe: ${hold.safe_actions.join(',')}${hold.needs_human ? ` NEEDS HUMAN: ${hold.human_reason}` : ''}${hold.attempts > 1 ? ` (held ${hold.attempts} times)` : ''}`);
if (listing.paging && !listing.paging.complete) {
const codes = Object.entries(listing.summary.by_code.counts).map(([code, n]) => `${code} ${n}`).join(', ');
- console.log(` ... ${status.holds.length - listing.rows.length} more not listed here (${codes}${listing.summary.by_code.other ? `, other ${listing.summary.by_code.other}` : ''}); `
+ console.log(` ... ${listing.matched - listing.rows.length} more not listed here (${codes}${listing.summary.by_code.other ? `, other ${listing.summary.by_code.other}` : ''}); `
+ `${listing.paging?.next_command ? listing.paging.next_command.join(' ') : `gbrain sync status --source ${sourceId} --detail --json`} lists them`);
}
const superseded = status.last_error?.superseded;
diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.ts
index 25f3b1b596..4005c66f0c 100644
--- a/src/core/behavior-change-notice.ts
+++ b/src/core/behavior-change-notice.ts
@@ -1417,6 +1417,7 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText;
{ since: '0.60.560.0', id: 'segmented_freeze_hold_gbra287', text: 'A managed sync whose freeze compares a Git-tracked page stored in segments with working-tree bytes that differ from the pinned commit now reads a page up to 24 MiB back whole, as its publication does, instead of refusing with `page_body_segmented` and stopping the source (`sync_blocked`) on every later sync. A page whose stored body cannot be read while it is frozen (`page_body_segmented` or `page_body_rows_unreadable`) is held `page_write_failed` with that code named, and the rest of the source syncs; `gbrain sync status` classifies such a hold by that code (`page_body_segmented`: upgrade, a person; `page_body_rows_unreadable`: retry, no person needed) instead of as an unplaced `page_write_failed`. A sync that stops before admitting any write request shows `last_error.request_id: null` in `gbrain sync status --json` instead of omitting it.' },
{ since: '0.60.560.0', id: 'segmented_reexport_gbra287', text: 'A full sync re-exports a DB-only page (#2426) stored in segments, streaming its file with the bytes `gbrain export` writes, instead of listing it as a `page_body_segmented` failure; a page whose re-export fails is returned in the result\'s `reexport_failures` and the run completes. Write-through of a page stored in segments keeps the existing file\'s mode, skips a file over the pre-push scan cap before binding `source_path`, and with frontmatter overrides returns an error result instead of a `page_body_segmented` one; the derived (generated-page) writer skips such a page (`segmented_page`). A segmented read whose page published a new body between its reads reads one generation (or the new live one) instead of refusing `page_body_rows_unreadable`.' },
{ since: '0.60.562.0', id: 'segmented_tiling_gst1209', text: 'A write to a page stored in segments whose staging a fact purge aborted or a sweep expired while the write prepared now refuses `body_staging_expired` (send the write again) and the page keeps its previous body, instead of publishing a generation with no segment rows, after which every read refused `page_body_rows_unreadable` and a managed sync held the file on every retry. A publish also refuses any generation whose rows do not cover the body it records. New doctor check `segmented_tiling` lists pages an older version left like this, and the explicit-only repair `gbrain repair segmented-tiling --source <id>` republishes each from its file at HEAD after a preview, with `--apply --expect <hash>`; a source without a Git checkout refuses it (`not_a_git_repo`).' },
+ { since: '0.60.565.0', id: 'untiled_hold_repair_gst1209', text: 'A managed-sync hold on a page stored in segments whose segment rows do not cover its body (`page_write_failed` naming `page_body_rows_unreadable`) now reads needs_human with safe_actions repair, and its fix previews `gbrain repair segmented-tiling --source <id> --slug <slug>` instead of `gbrain sources retry-held`, which could never clear it; `gbrain sync unblock` refuses it with that fix. `gbrain sync status` names each `page_write_failed` hold\'s `fault_code`, counts them in `holds_summary.by_fault_code`, and `--slug <slug>` / `--code <code>` list one hold without paging. Doctor `segmented_tiling` and the repair skip archived sources, doctor\'s fix always names a `--source`, and a repair preview over 1,000 pages says so.' },
// GBRA-200 (harness ask 6: stamp degraded replies). `since` is stamped at the merge slot.
{ since: '0.60.563.0', id: 'write_grant_refusal_gbra200', text: 'A `remember` naming a `source_id` outside the connection\'s write grant is still refused `scope_denied` (a page write: `permission_denied`), and the refusal now carries `writable_source_ids`: the sources the connection\'s own grant lets it write, never another source, identical whether the named source exists or not. On `remember` the `fix` repeats the call against that source once the user agrees (`next: ask_user`, naming both sources), so a harness can retry instead of giving up; `forget`, `forget_fact` and page writes carry no fix.' },
{ since: '0.60.563.0', id: 'degraded_stamp_gbra200', text: 'Every degraded or partial read result now carries one stamp naming why with stable codes: an MCP result gets `_meta.degraded: { reasons: [...] }` and one extra text block, `[gbrain degraded: <reasons>] ...`, after the others; a CLI `--json` object gets a `degraded` key, and other CLI output (human text, a bare `--json` array such as search results) gets that line on stderr. It covers search, query, recall, find_experts, context_pack, delta, entity, get_page (`file_held`), think and synthesize, search_exact, open_loops and rank_entities. recall and think no longer drop their page search\'s degraded stages (an embed timeout, a failed arm, the keyword rank bound): recall reports them in `_meta.retrieval.degraded` and its `degraded_recall` notice, think and synthesize as `GATHER_DEGRADED:<stage>` warnings, and a keyword-only search or recall on Postgres reports `keyword_candidates_incomplete` when the rank bound applies. A clean result carries no stamp, and no existing field changed.' },
diff --git a/src/core/page-body/body-tiling.ts b/src/core/page-body/body-tiling.ts
index c3fff40f69..f2e198541c 100644
--- a/src/core/page-body/body-tiling.ts
+++ b/src/core/page-body/body-tiling.ts
@@ -88,7 +88,7 @@ export interface UntiledPage {
}
/**
- * GST-1209: the live (not deleted) pages stored in segments whose live generation's rows do not cover body_bytes gapless
+ * GST-1209: the live (not deleted) pages of unarchived sources stored in segments whose live generation's rows do not cover body_bytes gapless
* from 0, so every read of them refuses page_body_rows_unreadable. One aggregate per page over its live rows, read-only;
* `sourceIds` and `slugs` narrow the scan, `limit` bounds the list (ordered by source and slug).
*/
@@ -97,7 +97,7 @@ export async function untiledSegmentedPages(engine: Pick<BrainEngine, 'executeRa
const rows = await engine.executeRaw<{ id: number; source_id: string; slug: string; revision: string; body_generation: unknown; body_bytes: unknown;
segment_count: number | null; source_path: string | null; n: unknown; covered: unknown; gapless: boolean }>(
`SELECT p.id, p.source_id, p.slug, p.knowledge_revision::text AS revision, p.body_generation, p.body_bytes, p.segment_count, p.source_path, t.n, t.covered, t.gapless
- FROM pages p CROSS JOIN LATERAL (${liveTilingSql('p')}) t
+ FROM pages p JOIN sources s ON s.id = p.source_id AND s.archived IS NOT TRUE CROSS JOIN LATERAL (${liveTilingSql('p')}) t
WHERE p.body_storage = 'segmented' AND p.deleted_at IS NULL AND ($1::text[] IS NULL OR p.source_id = ANY($1::text[]))
AND ($2::text[] IS NULL OR p.slug = ANY($2::text[])) AND ${untiledSql('p', 't')}
ORDER BY p.source_id, p.slug LIMIT $3`, [opts.sourceIds ? [...opts.sourceIds] : null, opts.slugs ? [...opts.slugs] : null, opts.limit ?? 1000]);
diff --git a/src/core/persistence/sync-entry-fault.ts b/src/core/persistence/sync-entry-fault.ts
index d934354a53..d6112e194b 100644
--- a/src/core/persistence/sync-entry-fault.ts
+++ b/src/core/persistence/sync-entry-fault.ts
@@ -125,7 +125,9 @@ export function freezeFaultHold(run: object, entry: HoldEntry, slug: string, pag
const text = (error instanceof Error ? error.message : String(error)).replace(/[\x00-\x1f\x7f]+/g, ' ').slice(0, 300);
return { path: entry.path, source_path: entry.sourcePath, slug, page_id: pageId, code: 'page_write_failed',
message: `${entry.path}: sync could not prepare its ${entry.action === 'delete' ? 'deletion' : 'import'} (${name}: ${text}), so it is held and the rest of the source synced. `
- + 'The next syncs re-test it; if it stays held, report it with the gbrain version or fix the file when the error names it, then gbrain sources retry-held.',
+ + ((error as OperationError | null)?.code === 'page_body_rows_unreadable' && pageBody
+ ? `The page's segment rows do not cover its body, so no retry clears it: preview gbrain repair segmented-tiling --source <source> --slug ${slug}.`
+ : 'The next syncs re-test it; if it stays held, report it with the gbrain version or fix the file when the error names it, then gbrain sources retry-held.'),
upstream_version: null,
meta: { ...meta, write_failure: { code: pageBody ? (error as OperationError).code : 'storage_error', origin: 'freeze', error_class: name, errno: typeof errno === 'string' ? errno.slice(0, 32) : null, request_id: null, attempts: 1, gbrain_version: VERSION } } };
}
diff --git a/src/core/persistence/sync-fault-class.ts b/src/core/persistence/sync-fault-class.ts
index e4a65decdb..160e127b58 100644
--- a/src/core/persistence/sync-fault-class.ts
+++ b/src/core/persistence/sync-fault-class.ts
@@ -101,8 +101,10 @@ export const SYNC_FAULT_TABLE: ReadonlyArray<SyncFaultRule> = [
// (rows that do not tile it). Keyed by detail codes no receipt carries, so a write receipt with the bare code keeps its class.
{ code: 'freeze_page_body_segmented', class: 'page', safe_actions: ['upgrade'], needs_human: true, escalate: 'always: a sync path read a page stored in segments whole',
human_reason: 'A sync path read this page stored in segments as one string, so its file is held and the rest of the source synced; upgrade gbrain, then run gbrain sources retry-held <source>, and report it with the gbrain version if it stays held.' },
- { code: 'freeze_page_body_rows_unreadable', class: 'page', safe_actions: ['retry'], needs_human: false, escalate: 'the page stays unreadable across syncs (a grant or row-level security policy hides its segment rows)',
- human_reason: 'Give the role that reads the brain the same access to page_body_manifest and page_segment_texts it has to pages, then run gbrain sources retry-held <source>.' },
+ { code: 'freeze_page_body_rows_unreadable', class: 'page', safe_actions: ['repair'], needs_human: true, escalate: 'always: the page\'s segment rows do not cover its stored body, so no sync can read it',
+ human_reason: 'The segment rows of this page stored in segments do not cover its body, so every read of it refuses and no retry clears the hold; preview gbrain repair segmented-tiling --source <source> --slug <slug> '
+ + '(read-only; doctor segmented_tiling lists the page) and apply it with the user\'s agreement. If doctor does not list the page, the rows exist but the role that reads the brain cannot see them: '
+ + 'give it the same access to page_body_manifest and page_segment_texts it has to pages, then run gbrain sources retry-held <source>.' },
{ code: 'page_write_failed', class: 'page', safe_actions: ['upgrade'], needs_human: true, escalate: 'always: the writer cannot place the failure',
human_reason: 'The write of this file keeps failing with an error gbrain cannot classify (an owner exception or an unplaced refusal); read its receipt (gbrain write-request <request_id>), report it with the gbrain version or fix the file when the error names its content, then run gbrain sources retry-held <source>.' },
// GBRA-130 A-7: the file is not a readable regular file inside the source root (a symlink, a non-regular file, a permission error).
diff --git a/src/core/persistence/sync-holds.ts b/src/core/persistence/sync-holds.ts
index 2add062899..f91d07ec9e 100644
--- a/src/core/persistence/sync-holds.ts
+++ b/src/core/persistence/sync-holds.ts
@@ -766,6 +766,15 @@ export function gitHoldFix(record: Pick<GitHoldRecord, 'source_id' | 'path' | 'c
case 'page_write_failed': {
const failure = record.meta.write_failure;
const verify = { argv: ['gbrain', 'sources', 'status', source, '--json'] };
+ // GST-1209: rows that do not cover the stored body fail every read, so a retry never clears the hold; the repair republishes the page from its file.
+ if (failure?.origin === 'freeze' && failure.code === 'page_body_rows_unreadable') {
+ return { argv: ['gbrain', 'repair', 'segmented-tiling', '--source', source, ...(record.slug ? ['--slug', record.slug] : [])], consent: [], actor: 'agent', requires_exclusive: false,
+ docs: 'docs/guides/repair.md#segmented-tiling',
+ why: `The segment rows of the page ${record.path} maps to do not cover its stored body, so every read of it refuses page_body_rows_unreadable and sync holds the file on every retry. `
+ + 'This previews republishing the page from its file at HEAD and writes nothing; applying it needs the user\'s agreement and the printed preview hash, and clears the hold. '
+ + `If doctor segmented_tiling does not list the page, the rows exist but the role that reads the brain cannot see them: give it access to page_body_manifest and page_segment_texts, then run gbrain sources retry-held ${source}.`,
+ verify: { argv: ['gbrain', 'doctor', '--only', 'segmented_tiling', '--json'] } };
+ }
// GBRA-133 S-63: a freeze fault threw before any request was admitted, so there is no receipt; the hold names the error.
if (failure?.origin === 'freeze') return { argv: ['gbrain', 'sources', 'retry-held', source], consent: [], actor: 'agent', requires_exclusive: false, docs: 'docs/guides/write-refusals.md#page_write_failed',
why: `Sync could not prepare ${record.path} (${failure.error_class ?? 'an unexpected error'}${failure.errno ? `, ${failure.errno}` : ''}; the hold message names it), so it held that file and the rest of the source kept syncing. `
diff --git a/src/core/persistence/sync-status.ts b/src/core/persistence/sync-status.ts
index 14d0d40e7a..b76864abcc 100644
--- a/src/core/persistence/sync-status.ts
+++ b/src/core/persistence/sync-status.ts
@@ -60,6 +60,8 @@ export interface SyncStatusHold extends SyncFaultVerdict {
public_category: PublicCategory;
slug: string | null;
path: string;
+ /** GST-1209: the failure code a `page_write_failed` hold recorded (`meta.write_failure.code`), so a listing names why it is held. */
+ fault_code?: string;
attempts: number;
held_since: string;
/** When the hold can be retried on its own: now (`null`), or never without the named step. */
@@ -330,7 +332,9 @@ function holdStatus(record: GitHoldRecord, auto?: FenceAutoRepair): SyncStatusHo
const terminal = classifyRecordedFault({ source_id: record.source_id, code: record.code, slug: record.slug });
const fix = gitHoldFix(record, auto);
// #6712 PR 2: an abandoned edit is the person's to commit or restore; unblock then finds the file clean and schedules it.
- return { code: record.code, category: terminal.category, public_category: terminal.public_category, slug: record.slug, path: record.path, attempts, held_since: record.held_at, ...verdict,
+ const faultCode = record.code === 'page_write_failed' ? record.meta.write_failure?.code : undefined;
+ return { code: record.code, category: terminal.category, public_category: terminal.public_category, slug: record.slug, path: record.path, ...(faultCode ? { fault_code: faultCode } : {}),
+ attempts, held_since: record.held_at, ...verdict,
retry_after: verdict.safe_actions[0] === 'retry' || verdict.safe_actions[0] === 'retry_when_clean' ? null : 'after the named step',
fix: verdict.needs_human && record.code === 'worktree_dirty' ? { ...fix, ask_user: true, user_message: verdict.human_reason } : fix };
}
diff --git a/src/core/repair/segmented-tiling.ts b/src/core/repair/segmented-tiling.ts
index dd15933dc1..ff27fb72b7 100644
--- a/src/core/repair/segmented-tiling.ts
+++ b/src/core/repair/segmented-tiling.ts
@@ -168,10 +168,15 @@ async function stageable(engine: BrainEngine, page: { source_id: string; slug: s
timeline: (await preserveWithdrawnFenceRows(engine, page.source_id, body.timeline ?? '', page.slug)).trim() };
}
-/** Every damaged page of the selection, as the preview lists it (republishable pages and held ones). */
-async function survey(engine: BrainEngine, selection: Selection): Promise<{ pages: HealPage[]; listing: RepairListing[]; held: number }> {
- const damaged = await untiledSegmentedPages(engine, { sourceIds: [selection.source_id], ...(selection.slugs.length ? { slugs: selection.slugs } : {}) });
- if (!damaged.length) return { pages: [], listing: [], held: 0 };
+/** The most damaged pages one preview lists; a preview that finds more says so (`truncated`), and the next preview after the apply lists the rest. */
+export const PREVIEW_PAGE_LIMIT = 1000;
+
+/** Every damaged page of the selection, as the preview lists it (republishable pages and held ones), up to `limit`. */
+export async function survey(engine: BrainEngine, selection: Selection, limit = PREVIEW_PAGE_LIMIT): Promise<{ pages: HealPage[]; listing: RepairListing[]; held: number; truncated: boolean }> {
+ const found = await untiledSegmentedPages(engine, { sourceIds: [selection.source_id], ...(selection.slugs.length ? { slugs: selection.slugs } : {}), limit: limit + 1 });
+ const truncated = found.length > limit;
+ const damaged = found.slice(0, limit);
+ if (!damaged.length) return { pages: [], listing: [], held: 0, truncated };
const checkout = await sourceCheckout(engine, selection.source_id);
const { maxBytes } = await readPageBodyPolicy(engine);
const pages: HealPage[] = [];
@@ -189,7 +194,7 @@ async function survey(engine: BrainEngine, selection: Selection): Promise<{ page
pages.push(heal);
listing.push({ item: label, class: 'republish', detail: describe(heal) });
}
- return { pages: pages.sort((a, b) => a.page_id - b.page_id), listing, held };
+ return { pages: pages.sort((a, b) => a.page_id - b.page_id), listing, held, truncated };
}
/**
@@ -246,11 +251,12 @@ export const segmentedTilingRepair: RepairHandler = {
const selection = selectionOf(scope, opts.slugs);
const command = previewCommand(selection);
if (!opts.apply) {
- const { pages, listing, held } = await survey(engine, selection);
+ const { pages, listing, held, truncated } = await survey(engine, selection);
const hash = hashOf(scope, selection, pages);
if (pages.length) await saveApprovedSet<HealPage & { selection: Selection }>(engine, { command: 'segmented-tiling', hash }, pages.map(page => ({ ...page, selection })));
return { items: pages.map((page, index) => item(page, hash, index === pages.length - 1)), preview_hash: hash, listing,
- residuals: { pages_to_republish: pages.length, held }, details: { pages } };
+ residuals: { pages_to_republish: pages.length, held, ...(truncated ? { more_pages_not_listed: 1 } : {}) },
+ details: { pages, ...(truncated ? { truncated: true, next: `More than ${PREVIEW_PAGE_LIMIT} damaged pages: apply this preview, then run ${command} again to list the rest.` } : {}) } };
}
if (!opts.expect) {
throw new OperationError('invalid_params', 'gbrain repair segmented-tiling --apply republishes only the set a preview printed.',
diff --git a/test/doctor-quick-tier-7142.test.ts b/test/doctor-quick-tier-7142.test.ts
index 13dee5d8fd..0acf7458bb 100644
--- a/test/doctor-quick-tier-7142.test.ts
+++ b/test/doctor-quick-tier-7142.test.ts
@@ -132,6 +132,31 @@ for (const kind of testBackends()) {
slowDelayMs = 0;
}, 60_000);
+ test('a check a later release added to an entry is never hidden behind that entry\'s older last known result', async () => {
+ await clear();
+ slowStatus = 'warn'; slowDelayMs = 0;
+ await runDoctorRegistry(ctxFor(engine, 'standard'), entries);
+ // The recorded result predates slow_new (an older release, which also stored no emits list).
+ await engine.executeRaw(`UPDATE op_checkpoints SET completed_keys = jsonb_build_array((completed_keys->0) - 'emits') WHERE op = $1 AND fingerprint = 'slow_a'`, [LAST_KNOWN_OP]);
+ const grown: DoctorEntry = { ...standardEntry, emits: [...standardEntry.emits, 'slow_new'] };
+ slowDelayMs = 800;
+ const checks = await runDoctorRegistry(ctxFor(engine, 'standard', { entryBudgetOverrideMs: 200 }), [opsEntry, quickEntry, grown]);
+ slowDelayMs = 0;
+ expect(byName(checks, 'slow_a')!.details?.last_known).toMatchObject({ reason: 'budget' });
+ expect(byName(checks, 'slow_new')).toMatchObject({ status: 'warn', details: { health: 'unknown', reason: 'budget' } });
+ expect(byName(checks, 'slow_b')).toMatchObject({ details: { health: 'unknown', reason: 'budget' } });
+
+ const quick = await runDoctorRegistry(ctxFor(engine, 'quick'), [opsEntry, quickEntry, grown]);
+ expect(byName(quick, 'slow_a')!.details?.last_known).toMatchObject({ reason: 'not_in_tier' });
+ expect(byName(quick, 'doctor_last_known')!.details).toMatchObject({ unknown_checks: ['slow_b', 'slow_new'] });
+
+ await runDoctorRegistry(ctxFor(engine, 'standard'), [opsEntry, quickEntry, grown]);
+ slowDelayMs = 800;
+ const recordedNow = await runDoctorRegistry(ctxFor(engine, 'standard', { entryBudgetOverrideMs: 200 }), [opsEntry, quickEntry, grown]);
+ slowDelayMs = 0;
+ expect(recordedNow.filter(c => c.name.startsWith('slow_')).map(c => c.name)).toEqual(['slow_a']);
+ }, 60_000);
+
test('--only and source-scoped runs neither read nor write last known results', async () => {
await clear();
await runDoctorRegistry(ctxFor(engine, 'standard', { only: new Set(['slow_a']) }), entries);
diff --git a/test/fixtures/goldens/doctor/content-pglite-human.json b/test/fixtures/goldens/doctor/content-pglite-human.json
index cf6662c67a..cb622607fc 100644
--- a/test/fixtures/goldens/doctor/content-pglite-human.json
+++ b/test/fixtures/goldens/doctor/content-pglite-human.json
@@ -110,6 +110,7 @@
" [OK] stale_mentions: No by-mention links in this brain.",
" [OK] timeline_orphans: No orphaned timeline rows across 4 page(s).",
" [OK] slug_collisions: No slug collisions across 2 source checkout(s).",
+ " [OK] segmented_tiling: Every live page stored in segments has segment rows that cover its whole body.",
" [OK] timeline_history: Every timeline row has a bullet in its page (4 page(s) inspected).",
" [OK] safe_index_pending: Every re-sealable page is at the safe-chunk index version.",
" [OK] credential_projection_pending: No page waits for the credential-safe re-chunk.",
@@ -128,7 +129,6 @@
" [OK] unbound_source: No page was written database-only to an unbound source.",
" [OK] writer_version: Every writer that admitted or published a request in the last 7 days is v0.60.5.0 or newer.",
" [OK] segmented_storage: Segmented page storage is on: pages over 1 MiB are stored in segments, up to 134217728 bytes on this PGLite brain.",
- " [OK] segmented_tiling: Every live page stored in segments has segment rows that cover its whole body.",
" [OK] self_capture: No session corpus is configured; nothing to classify.",
" [OK] vector_plan: Skipped: PGLite runs vector search in-process; the plan check applies to Postgres brains.",
" [OK] keyword_plan: Skipped: PGLite runs keyword search with no statement timeout; the canary applies to Postgres brains.",
diff --git a/test/fixtures/goldens/doctor/content-pglite-json.json b/test/fixtures/goldens/doctor/content-pglite-json.json
index 3dc28a60df..3968270507 100644
--- a/test/fixtures/goldens/doctor/content-pglite-json.json
+++ b/test/fixtures/goldens/doctor/content-pglite-json.json
@@ -1395,6 +1395,13 @@
"name": "slug_collisions",
"status": "ok"
},
+ {
+ "category": "brain",
+ "elapsed_ms": "<volatile>",
+ "message": "Every live page stored in segments has segment rows that cover its whole body.",
+ "name": "segmented_tiling",
+ "status": "ok"
+ },
{
"category": "brain",
"details": {
@@ -1708,13 +1715,6 @@
"name": "segmented_storage",
"status": "ok"
},
- {
- "category": "brain",
- "elapsed_ms": "<volatile>",
- "message": "Every live page stored in segments has segment rows that cover its whole body.",
- "name": "segmented_tiling",
- "status": "ok"
- },
{
"category": "brain",
"details": {
diff --git a/test/fixtures/goldens/doctor/hot-checks-pglite-json.json b/test/fixtures/goldens/doctor/hot-checks-pglite-json.json
index 423577ce69..781fa50b8c 100644
--- a/test/fixtures/goldens/doctor/hot-checks-pglite-json.json
+++ b/test/fixtures/goldens/doctor/hot-checks-pglite-json.json
@@ -1466,6 +1466,13 @@
"name": "slug_collisions",
"status": "ok"
},
+ {
+ "category": "brain",
+ "elapsed_ms": "<volatile>",
+ "message": "Every live page stored in segments has segment rows that cover its whole body.",
+ "name": "segmented_tiling",
+ "status": "ok"
+ },
{
"category": "brain",
"details": {
@@ -1887,13 +1894,6 @@
"name": "segmented_storage",
"status": "ok"
},
- {
- "category": "brain",
- "elapsed_ms": "<volatile>",
- "message": "Every live page stored in segments has segment rows that cover its whole body.",
- "name": "segmented_tiling",
- "status": "ok"
- },
{
"category": "brain",
"details": {
@@ -6437,6 +6437,13 @@
"name": "slug_collisions",
"status": "ok"
},
+ {
+ "category": "brain",
+ "elapsed_ms": "<volatile>",
+ "message": "Every live page stored in segments has segment rows that cover its whole body.",
+ "name": "segmented_tiling",
+ "status": "ok"
+ },
{
"category": "brain",
"details": {
@@ -6858,13 +6865,6 @@
"name": "segmented_storage",
"status": "ok"
},
- {
- "category": "brain",
- "elapsed_ms": "<volatile>",
- "message": "Every live page stored in segments has segment rows that cover its whole body.",
- "name": "segmented_tiling",
- "status": "ok"
- },
{
"category": "brain",
"details": {
diff --git a/test/fixtures/goldens/doctor/hot-checks-postgres-json.json b/test/fixtures/goldens/doctor/hot-checks-postgres-json.json
index 3303758190..f8cb2fe5b7 100644
--- a/test/fixtures/goldens/doctor/hot-checks-postgres-json.json
+++ b/test/fixtures/goldens/doctor/hot-checks-postgres-json.json
@@ -1458,6 +1458,13 @@
"name": "slug_collisions",
"status": "ok"
},
+ {
+ "category": "brain",
+ "elapsed_ms": "<volatile>",
+ "message": "Every live page stored in segments has segment rows that cover its whole body.",
+ "name": "segmented_tiling",
+ "status": "ok"
+ },
{
"category": "brain",
"details": {
@@ -1879,13 +1886,6 @@
"name": "segmented_storage",
"status": "ok"
},
- {
- "category": "brain",
- "elapsed_ms": "<volatile>",
- "message": "Every live page stored in segments has segment rows that cover its whole body.",
- "name": "segmented_tiling",
- "status": "ok"
- },
{
"category": "brain",
"details": {
@@ -6430,6 +6430,13 @@
"name": "slug_collisions",
"status": "ok"
},
+ {
+ "category": "brain",
+ "elapsed_ms": "<volatile>",
+ "message": "Every live page stored in segments has segment rows that cover its whole body.",
+ "name": "segmented_tiling",
+ "status": "ok"
+ },
{
"category": "brain",
"details": {
@@ -6851,13 +6858,6 @@
"name": "segmented_storage",
"status": "ok"
},
- {
- "category": "brain",
- "elapsed_ms": "<volatile>",
- "message": "Every live page stored in segments has segment rows that cover its whole body.",
- "name": "segmented_tiling",
- "status": "ok"
- },
{
"category": "brain",
"details": {
diff --git a/test/fixtures/goldens/doctor/json-pglite-degraded.json b/test/fixtures/goldens/doctor/json-pglite-degraded.json
index 20c729377f..4045febbf8 100644
--- a/test/fixtures/goldens/doctor/json-pglite-degraded.json
+++ b/test/fixtures/goldens/doctor/json-pglite-degraded.json
@@ -1272,6 +1272,13 @@
"name": "slug_collisions",
"status": "ok"
},
+ {
+ "category": "brain",
+ "elapsed_ms": "<volatile>",
+ "message": "Every live page stored in segments has segment rows that cover its whole body.",
+ "name": "segmented_tiling",
+ "status": "ok"
+ },
{
"category": "brain",
"details": {
@@ -1585,13 +1592,6 @@
"name": "segmented_storage",
"status": "ok"
},
- {
- "category": "brain",
- "elapsed_ms": "<volatile>",
- "message": "Every live page stored in segments has segment rows that cover its whole body.",
- "name": "segmented_tiling",
- "status": "ok"
- },
{
"category": "brain",
"details": {
diff --git a/test/fixtures/goldens/doctor/json-pglite-fresh.json b/test/fixtures/goldens/doctor/json-pglite-fresh.json
index ee62910248..ea05573d8d 100644
--- a/test/fixtures/goldens/doctor/json-pglite-fresh.json
+++ b/test/fixtures/goldens/doctor/json-pglite-fresh.json
@@ -1328,6 +1328,13 @@
"name": "slug_collisions",
"status": "ok"
},
+ {
+ "category": "brain",
+ "elapsed_ms": "<volatile>",
+ "message": "Every live page stored in segments has segment rows that cover its whole body.",
+ "name": "segmented_tiling",
+ "status": "ok"
+ },
{
"category": "brain",
"details": {
@@ -1641,13 +1648,6 @@
"name": "segmented_storage",
"status": "ok"
},
- {
- "category": "brain",
- "elapsed_ms": "<volatile>",
- "message": "Every live page stored in segments has segment rows that cover its whole body.",
- "name": "segmented_tiling",
- "status": "ok"
- },
{
"category": "brain",
"details": {
diff --git a/test/fixtures/goldens/doctor/json-postgres-fresh.json b/test/fixtures/goldens/doctor/json-postgres-fresh.json
index cac0b5a293..edaa86697b 100644
--- a/test/fixtures/goldens/doctor/json-postgres-fresh.json
+++ b/test/fixtures/goldens/doctor/json-postgres-fresh.json
@@ -1320,6 +1320,13 @@
"name": "slug_collisions",
"status": "ok"
},
+ {
+ "category": "brain",
+ "elapsed_ms": "<volatile>",
+ "message": "Every live page stored in segments has segment rows that cover its whole body.",
+ "name": "segmented_tiling",
+ "status": "ok"
+ },
{
"category": "brain",
"details": {
@@ -1633,13 +1640,6 @@
"name": "segmented_storage",
"status": "ok"
},
- {
- "category": "brain",
- "elapsed_ms": "<volatile>",
- "message": "Every live page stored in segments has segment rows that cover its whole body.",
- "name": "segmented_tiling",
- "status": "ok"
- },
{
"category": "brain",
"details": {
diff --git a/test/fixtures/goldens/doctor/registry-build-checks.json b/test/fixtures/goldens/doctor/registry-build-checks.json
index 96ccb84c1c..90d47f405a 100644
--- a/test/fixtures/goldens/doctor/registry-build-checks.json
+++ b/test/fixtures/goldens/doctor/registry-build-checks.json
@@ -485,6 +485,10 @@
"category": "brain",
"name": "slug_collisions"
},
+ {
+ "category": "brain",
+ "name": "segmented_tiling"
+ },
{
"category": "brain",
"name": "timeline_history"
@@ -557,10 +561,6 @@
"category": "ops",
"name": "segmented_storage"
},
- {
- "category": "brain",
- "name": "segmented_tiling"
- },
{
"category": "brain",
"name": "self_capture"
diff --git a/test/large-pages/managed-sync-segmented-freeze.test.ts b/test/large-pages/managed-sync-segmented-freeze.test.ts
index fd0b45aebe..ffc108f0ec 100644
--- a/test/large-pages/managed-sync-segmented-freeze.test.ts
+++ b/test/large-pages/managed-sync-segmented-freeze.test.ts
@@ -93,7 +93,7 @@ test('a segmented page whose rows do not tile its body is held at the freeze; th
expect((result.held ?? []).map(hold => [hold.path, hold.code])).toEqual([['people/person-example.md', 'page_write_failed']]);
expect(result.held![0]!.message).toContain('page_body_rows_unreadable');
expect((await readSyncStatus(engine, f.sourceId, { detail: false })).holds).toEqual([expect.objectContaining({ code: 'page_write_failed',
- path: 'people/person-example.md', needs_human: false, safe_actions: ['retry'] })]);
+ path: 'people/person-example.md', needs_human: true, safe_actions: ['repair'] })]);
const [other] = await engine.executeRaw<{ compiled_truth: string }>("SELECT compiled_truth FROM pages WHERE source_id=$1 AND slug='people/other-example'", [f.sourceId]);
expect(other!.compiled_truth).toContain('second');
expect(await engine.executeRaw('SELECT last_commit FROM sources WHERE id=$1', [f.sourceId])).toEqual([{ last_commit: git(f.root, 'rev-parse', 'HEAD') }]);
diff --git a/test/large-pages/segmented-tiling-repair.test.ts b/test/large-pages/segmented-tiling-repair.test.ts
index 9b09961b31..5355e89285 100644
--- a/test/large-pages/segmented-tiling-repair.test.ts
+++ b/test/large-pages/segmented-tiling-repair.test.ts
@@ -27,7 +27,8 @@ import { materializeSegmentedBody } from '../../src/core/page-body/ingest.ts';
import { untiledSegmentedPages } from '../../src/core/page-body/body-tiling.ts';
import { resolveRepairScope, runRepair } from '../../src/core/repair/core.ts';
import { AUTO_REPAIR_REGISTRY, repairRunner } from '../../src/core/repair/registry.ts';
-import { segmentedTilingRepair, SEGMENTED_TILING_RECEIPT_OP } from '../../src/core/repair/segmented-tiling.ts';
+import { segmentedTilingRepair, SEGMENTED_TILING_RECEIPT_OP, survey } from '../../src/core/repair/segmented-tiling.ts';
+import { readSyncStatus } from '../../src/core/persistence/sync-status.ts';
import { segmentedTilingCheck } from '../../src/commands/doctor/checks/segmented-tiling.ts';
import { withEnv } from '../helpers/with-env.ts';
import { withManagedFixtureWrite } from '../helpers/managed-e2e-fixture-write.ts';
@@ -88,7 +89,10 @@ test('doctor lists the damaged page read-only; the repair republishes it from HE
const held = await performManagedSync(engine, { sourceId: f.sourceId, noPull: true, noEmbed: true, noExtract: true });
expect((held.held ?? []).map(hold => [hold.path, hold.code])).toEqual([[FILE, 'page_write_failed']]);
const [source] = await engine.executeRaw<{ incarnation: string }>('SELECT incarnation::text AS incarnation FROM sources WHERE id=$1', [f.sourceId]);
- expect(await readGitHold(engine, f.sourceId, source!.incarnation, FILE)).not.toBeNull();
+ const hold = (await readGitHold(engine, f.sourceId, source!.incarnation, FILE))!;
+ expect(hold.message).toContain(`gbrain repair segmented-tiling --source <source> --slug ${SLUG}`);
+ expect((await readSyncStatus(engine, f.sourceId, { detail: false })).holds.find(h => h.path === FILE)).toMatchObject({ fault_code: 'page_body_rows_unreadable', needs_human: true,
+ safe_actions: ['repair'], fix: { argv: ['gbrain', 'repair', 'segmented-tiling', '--source', f.sourceId, '--slug', SLUG] } });
const before = await counts();
const check = await segmentedTilingCheck(engine, [f.sourceId]);
@@ -223,6 +227,37 @@ test('a claim the owner purged stays out: the apply republishes the file through
expect(await engine.executeRaw('SELECT count(*)::int AS n FROM content_chunks WHERE page_id=$1 AND chunk_text LIKE $2', [f.pageId, `%${PURGED}%`])).toEqual([{ n: 0 }]);
}), 300_000);
+test('#8504: an archived source is never listed, a multi-source fix names a source, a preview over its limit says so, an unknown source refuses', async () => withEnv(env, async () => {
+ const f = await managedFixture();
+ const second = 'people/other-example.md';
+ writeFileSync(join(f.root, second), person(1260 * 1024).replace(/Person Example/g, 'Other Example'));
+ commit(f.root);
+ await performManagedSync(engine, { sourceId: f.sourceId, noPull: true, noEmbed: true, noExtract: true });
+ const [other] = await engine.executeRaw<{ id: number }>('SELECT id FROM pages WHERE source_id=$1 AND slug=$2', [f.sourceId, 'people/other-example']);
+ const g = await managedFixture();
+ await damage(f.sourceId, f.pageId); await damage(f.sourceId, Number(other!.id)); await damage(g.sourceId, g.pageId);
+
+ const both = await segmentedTilingCheck(engine, [f.sourceId, g.sourceId]);
+ const [firstSource, otherSource] = [f.sourceId, g.sourceId].sort();
+ expect(both.fix?.argv).toEqual(['gbrain', 'repair', 'segmented-tiling', '--source', firstSource]);
+ expect(both.fix?.why).toContain(`gbrain repair segmented-tiling --source ${otherSource}`);
+
+ const limited = await survey(engine, { source_id: f.sourceId, slugs: [] }, 1);
+ expect([limited.pages.length + limited.held, limited.truncated]).toEqual([1, true]);
+ expect((await survey(engine, { source_id: f.sourceId, slugs: [] })).truncated).toBe(false);
+
+ await expect(resolveRepairScope(engine, 'missing-example')).rejects.toMatchObject({ code: 'invalid_params' });
+ const archive = (archived: boolean) => engine.transaction(async tx => {
+ await tx.executeRaw("SELECT set_config('gbrain.topology_change','on',true)");
+ await tx.executeRaw('UPDATE sources SET archived=$2 WHERE id=$1', [g.sourceId, archived]);
+ });
+ await archive(true);
+ expect(await untiledSegmentedPages(engine, { sourceIds: [g.sourceId] })).toEqual([]);
+ expect((await segmentedTilingCheck(engine, [f.sourceId, g.sourceId])).fix?.why).not.toContain(g.sourceId);
+ await expect(resolveRepairScope(engine, g.sourceId)).rejects.toMatchObject({ code: 'invalid_params' });
+ await archive(false);
+}), 300_000);
+
test('a source without a Git checkout refuses the preview: Git is the only copy it republishes', async () => withEnv(env, async () => {
await disposePersistenceConsumer(engine);
await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');
diff --git a/test/segmented-fault-classes-gbra287.test.ts b/test/segmented-fault-classes-gbra287.test.ts
index b7f9cbe4d0..4c778c1fcf 100644
--- a/test/segmented-fault-classes-gbra287.test.ts
+++ b/test/segmented-fault-classes-gbra287.test.ts
@@ -2,7 +2,7 @@
* GBRA-287: how the two stored-page-body fault codes are classified.
*
* 1. Protects: a managed-sync freeze hold naming `page_body_segmented` reads upgrade / a person, and one naming
- * `page_body_rows_unreadable` reads retry / no person (the `freeze_<code>` rows), while a write receipt carrying
+ * `page_body_rows_unreadable` reads repair / a person (GST-1209 follow-up: no retry clears it; the `freeze_<code>` rows), while a write receipt carrying
* either bare code keeps the class it had before (a caller refusal, a gbrain defect): the hold rows never leak into
* receipt diagnosis (`gbrain write-request`, writer failures, doctor).
* 2. Fails when: the hold rows are keyed by the bare codes (receipts turn into sync faults), or holdVerdict stops
@@ -26,7 +26,7 @@ describe('GBRA-287: page-body fault classes', () => {
test('a freeze hold is classified by the page-body code it names', () => {
expect(holdVerdict(freezeHold('page_body_segmented'), undefined)).toMatchObject({ safe_actions: ['upgrade'], needs_human: true });
- expect(holdVerdict(freezeHold('page_body_rows_unreadable'), undefined)).toMatchObject({ safe_actions: ['retry'], needs_human: false });
+ expect(holdVerdict(freezeHold('page_body_rows_unreadable'), undefined)).toMatchObject({ safe_actions: ['repair'], needs_human: true });
expect(holdVerdict(freezeHold('storage_error'), undefined).human_reason).toContain('gbrain write-request');
});
});
diff --git a/test/segmented-untiled-hold-gst1209.test.ts b/test/segmented-untiled-hold-gst1209.test.ts
new file mode 100644
index 0000000000..c134ab1004
--- /dev/null
+++ b/test/segmented-untiled-hold-gst1209.test.ts
@@ -0,0 +1,142 @@
+/**
+ * GST-1209 follow-up: a managed-sync hold on a page whose stored segment rows do not cover its body.
+ *
+ * 1. Protects: the freeze hold naming `page_body_rows_unreadable` (the page doctor `segmented_tiling` lists) reads
+ * needs_human with safe_actions repair and a fix that previews `gbrain repair segmented-tiling --source <id> --slug <slug>`,
+ * never a `sources retry-held` that cannot succeed; `gbrain sync unblock` refuses it by name with that fix; and
+ * `gbrain sync status --json` finds it among many holds without paging: `--slug` and `--code` (the hold code or the
+ * page-body fault code) filter the listing, each hold names its `fault_code`, and `holds_summary.by_fault_code` counts them.
+ * 2. Fails when: the hold reads retry / no person, its fix names retry-held, unblock reports it as "not something unblock
+ * performs", a filter is ignored or its cursor replays against the unfiltered list, or the fault code is missing.
+ * 3. PGLite, and Postgres when DATABASE_URL is set; holds are seeded with writeGitHold.
+ */
+import { afterAll, beforeAll, expect, test } from 'bun:test';
+import { randomUUID } from 'node:crypto';
+import { execFileSync } from 'node:child_process';
+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 { claimWorktree } from '../src/core/persistence/ownership.ts';
+import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';
+import { performManagedSync } from '../src/core/persistence/sync-run.ts';
+import { holdVerdict, readSyncStatus, unblockSync } from '../src/core/persistence/sync-status.ts';
+import { gitHoldFix, writeGitHold } from '../src/core/persistence/sync-holds.ts';
+import { runSyncStatus } from '../src/commands/sync/operator.ts';
+import { DOCTOR_CHECK_REGISTRY } from '../src/commands/doctor/registry.ts';
+import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';
+import { withEnv } from './helpers/with-env.ts';
+
+const home = mkdtempSync(join(tmpdir(), 'gbrain-untiled-hold-'));
+const engines: BrainEngine[] = [];
+let closePostgres: (() => Promise<void>) | undefined;
+const env = { GBRAIN_HOME: home, GBRAIN_SYNC_FAILURES_DIR: home, GBRAIN_SOURCE: undefined, OPENAI_API_KEY: undefined, VOYAGE_API_KEY: undefined, ANTHROPIC_API_KEY: undefined };
+const git = (root: string, ...args: string[]) => execFileSync('git', ['-C', root, ...args], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] }).trim();
+const SLUG = 'people/person-example';
+const FILE = `${SLUG}.md`;
+
+beforeAll(async () => {
+ const lite = new PGLiteEngine(); await lite.connect({}); await lite.initSchema(); engines.push(lite);
+ if (process.env.DATABASE_URL) { const pg = await isolatedPersistencePostgres(process.env.DATABASE_URL); engines.push(pg.engine); closePostgres = pg.close; }
+}, 120_000);
+afterAll(async () => {
+ await withEnv(env, async () => { for (const engine of engines) { await disposePersistenceConsumer(engine); await engine.disconnect(); } });
+ await closePostgres?.(); rmSync(home, { recursive: true, force: true });
+});
+
+const failure = (code: string) => ({ code, origin: 'freeze', error_class: code, errno: null, request_id: null, attempts: 1, gbrain_version: 'x' });
+const freezeHold = (code: string) => ({ source_id: 'source-a', path: FILE, slug: SLUG, code: 'page_write_failed', held_at: new Date().toISOString(),
+ meta: { attempts: 1, write_failure: failure(code) } }) as never;
+
+test('doctor runs segmented_tiling as its own entry, so a default run reports it even when the wave checks run out of budget', () => {
+ const owners = DOCTOR_CHECK_REGISTRY.filter(entry => entry.emits.includes('segmented_tiling'));
+ expect(owners.map(entry => [entry.name, entry.emits])).toEqual([['segmented_tiling', ['segmented_tiling']]]);
+ expect(owners[0]!.tier ?? 'standard').toBe('standard');
+});
+
+test('a freeze hold on a page whose segment rows do not cover its body points to the segmented-tiling repair', () => {
+ expect(holdVerdict(freezeHold('page_body_rows_unreadable'), undefined)).toMatchObject({ class: 'page', safe_actions: ['repair'], needs_human: true,
+ human_reason: expect.stringContaining('gbrain repair segmented-tiling') });
+ const fix = gitHoldFix(freezeHold('page_body_rows_unreadable'));
+ expect(fix.argv).toEqual(['gbrain', 'repair', 'segmented-tiling', '--source', 'source-a', '--slug', SLUG]);
+ expect(fix.verify?.argv).toEqual(['gbrain', 'doctor', '--only', 'segmented_tiling', '--json']);
+ expect(fix.then).toBeUndefined();
+ expect(fix.why).toContain('writes nothing');
+ expect(gitHoldFix(freezeHold('page_body_segmented')).argv).toEqual(['gbrain', 'sources', 'retry-held', 'source-a']);
+ expect(gitHoldFix(freezeHold('storage_error')).argv).toEqual(['gbrain', 'sources', 'retry-held', 'source-a']);
+});
+
+async function syncedSource(engine: BrainEngine) {
+ const id = `uh-${randomUUID().replace(/-/g, '').slice(0, 16)}`, root = join(home, id);
+ mkdirSync(root); git(root, 'init', '-q');
+ writeFileSync(join(root, 'alice-example.md'), '---\ntitle: Alice Example\n---\nAlice keeps the acme-example ledger.\n');
+ git(root, 'add', '.'); git(root, '-c', 'user.name=Example', '-c', '[email protected]', 'commit', '-qm', 'fixture');
+ await disposePersistenceConsumer(engine);
+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');
+ await engine.executeRaw("INSERT INTO sources(id,name,local_path,config) VALUES($1,$1,$2,'{}')", [id, root]);
+ await claimWorktree(engine, id, root);
+ await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1');
+ expect((await performManagedSync(engine, { sourceId: id, noPull: true, noEmbed: true, noExtract: true })).status).toBe('first_sync');
+ const [row] = await engine.executeRaw<{ incarnation: string }>('SELECT incarnation::text AS incarnation FROM sources WHERE id=$1', [id]);
+ return { id, incarnation: row!.incarnation };
+}
+
+async function printed(run: () => Promise<void>): Promise<string> {
+ const out: string[] = [];
+ const log = console.log;
+ console.log = (...parts: unknown[]) => { out.push(parts.join(' ')); };
+ try { await run(); } finally { console.log = log; }
+ return out.join('\n');
+}
+type Hold = { path: string; slug: string | null; code: string; fault_code?: string; needs_human: boolean; safe_actions: string[]; fix: { argv: string[] } };
+type StatusJson = { holds: Hold[]; holds_summary: { total: number; by_code: { counts: Record<string, number> }; by_fault_code: { counts: Record<string, number>; other: number } };
+ holds_filter?: Record<string, string>; holds_page?: { next_cursor: string | null; next_command: string[] | null } };
+const statusJson = async (engine: BrainEngine, args: string[]) => JSON.parse(await printed(() => runSyncStatus(engine, args))) as StatusJson;
+
+test('sync status finds the hold among many without paging; unblock refuses it with the repair', async () => withEnv(env, async () => {
+ for (const engine of engines) {
+ const s = await syncedSource(engine);
+ const now = new Date().toISOString();
+ const hold = (path: string, code: 'concurrent_write' | 'page_write_failed', meta: Record<string, unknown>) => writeGitHold(engine, { source_id: s.id, incarnation: s.incarnation, path,
+ source_path: path, slug: path.replace(/\.md$/, ''), page_id: null, code, message: `${path} is held (fixture).`, upstream_version: null, observed_at: now, run_id: null, mode: 'managed', meta: meta as never });
+ for (let i = 0; i < 130; i++) await hold(`aa/note-${String(i).padStart(4, '0')}.md`, 'concurrent_write', { recovery_version: 1 });
+ await hold('aa/storage-example.md', 'page_write_failed', { recovery_version: 1, write_failure: failure('storage_error') });
+ await hold(FILE, 'page_write_failed', { recovery_version: 1, write_failure: failure('page_body_rows_unreadable') });
+
+ const status = await readSyncStatus(engine, s.id, { detail: false });
+ const untiled = status.holds.find(h => h.path === FILE)!;
+ expect(untiled).toMatchObject({ code: 'page_write_failed', fault_code: 'page_body_rows_unreadable', needs_human: true, safe_actions: ['repair'] });
+ expect(untiled.fix.argv).toEqual(['gbrain', 'repair', 'segmented-tiling', '--source', s.id, '--slug', SLUG]);
+ expect(status.holds.find(h => h.path === 'aa/storage-example.md')).toMatchObject({ fault_code: 'storage_error' });
+ expect(status.holds.find(h => h.path === 'aa/note-0000.md')!.fault_code).toBeUndefined();
+
+ const plain = await statusJson(engine, ['--source', s.id, '--json']);
+ expect(plain.holds_summary.by_fault_code).toEqual({ counts: { page_body_rows_unreadable: 1, storage_error: 1 }, other: 0 });
+ expect(plain.holds_summary.total).toBe(132);
+
+ for (const args of [['--slug', SLUG], ['--code', 'page_body_rows_unreadable']]) {
+ const found = await statusJson(engine, ['--source', s.id, ...args, '--json']);
+ expect(found.holds.map(h => [h.path, h.fault_code, h.fix.argv[2]])).toEqual([[FILE, 'page_body_rows_unreadable', 'segmented-tiling']]);
+ expect(found.holds_summary.total).toBe(132);
+ expect(found.holds_filter).toEqual(args[0] === '--slug' ? { slug: SLUG } : { code: 'page_body_rows_unreadable' });
+ }
+ expect((await statusJson(engine, ['--source', s.id, '--code', 'page_write_failed', '--json'])).holds.map(h => h.path).sort()).toEqual(['aa/storage-example.md', FILE].sort());
+ expect((await statusJson(engine, ['--source', s.id, '--slug', 'aa/note-0007', '--json'])).holds.map(h => h.path)).toEqual(['aa/note-0007.md']);
+
+ const page = await statusJson(engine, ['--source', s.id, '--detail', '--code', 'concurrent_write', '--json']);
+ expect(page.holds.every(h => h.code === 'concurrent_write')).toBe(true);
+ expect(page.holds_page!.next_command).toEqual(expect.arrayContaining(['--code', 'concurrent_write']));
+ const next = await statusJson(engine, ['--source', s.id, '--detail', '--code', 'concurrent_write', '--cursor', page.holds_page!.next_cursor!, '--json']);
+ expect(next.holds.every(h => h.code === 'concurrent_write')).toBe(true);
+ expect(page.holds.length + next.holds.length).toBe(130);
+ await expect(printed(() => runSyncStatus(engine, ['--source', s.id, '--detail', '--cursor', page.holds_page!.next_cursor!, '--json']))).rejects.toMatchObject({ code: 'invalid_params' });
+ await expect(printed(() => runSyncStatus(engine, ['--source', s.id, '--slug']))).rejects.toMatchObject({ code: 'invalid_params' });
+ await expect(printed(() => runSyncStatus(engine, ['--source', s.id, '--code', '--json']))).rejects.toMatchObject({ code: 'invalid_params' });
+
+ const unblock = await unblockSync(engine, s.id, { apply: false });
+ const refused = unblock.refused.find(r => r.path === FILE)!;
+ expect(refused).toMatchObject({ needs_human: true, reason: expect.stringContaining('gbrain repair segmented-tiling') });
+ expect(refused.fix.argv).toEqual(['gbrain', 'repair', 'segmented-tiling', '--source', s.id, '--slug', SLUG]);
+ }
+}), 300_000);