Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
Fix lane N: doctor reports the segmented pages its whole-body checks skipped (decision #10)
garrytand065a1508113
diff --git a/docs/GBRAIN_VERIFY.md b/docs/GBRAIN_VERIFY.mdindex 7f29e7a25b..f2653f466d 100644--- a/docs/GBRAIN_VERIFY.md+++ b/docs/GBRAIN_VERIFY.md@@ -43,6 +43,11 @@ gbrain doctor --json- `schema_version`: current- `embeddings`: coverage percentage+A check that carries `skipped_segmented: N` (message ending in+`skipped (segmented): N`) did not read N pages stored in segments, so its+`ok` covers only the pages it read; see+[segmented page storage](guides/memory-boundaries.md#segmented-doctor-skips).+**If it fails:** The doctor output includes specific fix instructions for eachcheck. See `skills/setup/SKILL.md` Error Recovery table.diff --git a/docs/architecture/key-files/commands-2-continued.md b/docs/architecture/key-files/commands-2-continued.mdindex 0b984c4067..8751ddcbc1 100644--- a/docs/architecture/key-files/commands-2-continued.md+++ b/docs/architecture/key-files/commands-2-continued.md@@ -23,7 +23,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/commands/doctor/checks/search-eval.ts` — search, model, and AI-config health checks. `checkSearchMode` (`search_mode`) reports the resolved mode and its `search.*` overrides; when the only override is an explicit `search.reranker.model` row equal to the mode bundle's own default (a row an init may have written on Voyage installs) it is called redundant with the precise `gbrain config unset search.reranker.model` — never a `--reset`, which would also wipe every other tuned search knob.- `src/commands/doctor/checks/atom-holds.ts` — `extract_atoms_held_failed` (#6325, BRAIN, registered before `fence_integrity`). Lists `listHeldManagedAtoms` (`persistence/atom-maintenance.ts`): managed atom pages and transcripts held after `MAX_DETERMINISTIC_FAILURES` failed extractions of their current content (code `held_failed`) that no later run completed, each with its last request id, failure, `receipt_command` and `retry_command`. Warns with a paid `fix` (the reviewed `gbrain jobs submit extract-atoms-drain --params '{sourceId, retryRequestId}'` retry of the first item). Local doctor only; `run_doctor` does not include it. Tests: `test/managed-atoms-retry.test.ts`.- `src/commands/doctor/checks/extraction-input.ts` — `extraction_input_truncated` (large pages A7, BRAIN, registered after `fence_integrity`, before `search_mode`). Groups the live pages with an `input_truncated` receipt in `page_extraction_state` by pipeline and kind (`facts_backstop/head|tail_window`, `extract_atoms/head|tail_window`, `conversation_facts/skipped_too_large`) with three recent `source:slug` samples and a remedy each. Warns when an atoms or conversation-facts receipt exists; the atoms fix is `gbrain config set cycle.extract_atoms.max_input_chars <n>` (`ask_user`, consent `paid`), otherwise `fix_unavailable_reason: operator_judgement`. Facts-only receipts are `ok` with `severity: info`, `readiness_state: degraded` (no knob raises the facts cap; later appends are read incrementally). Reads the database only. Tests: `test/extraction-watermark-facts.test.ts`, `test/extraction-watermark-atoms.test.ts`, `test/conversation-facts-oversized-sidecar.test.ts`.-- `src/commands/doctor/checks/fence-integrity.ts` — `fence_integrity` (#6188, BRAIN, registered before `search_mode`). Each run advances the fence census within `GBRAIN_DOCTOR_FENCE_TIMEOUT_MS` (default 10 s), then reports per source the malformed facts/takes fences still waiting, each counted once (held file, stored page, unsynced file) and split by planned tier (deterministic, resolver, llm, manual), the oldest hold's age, the 7-day `fences_normalized` trend with top writers (warns at `FENCE_NORMALIZATION_WARN_7D` = 20), and the model-repair caps with today's ledger spend. `ok` only when nothing waits, every source's census is complete and no source reaches the trend threshold; a partial census warns with the resume command. The fix is the read-only `gbrain repair fences --source <id>` preview for holds, stored pages and files alike; a warn reads `readFenceAutoRepair` (details `auto_repair`): while a maintenance run is active and `fences.repair.enabled` is on, the non-manual fences are "repaired automatically by the next maintenance run", otherwise the fix's `then` is the apply. Model-tier fences say why they wait (`fences.repair.llm` off with the command that turns it on, or today's budget spent with the cap command), else the caps. `fenceIntegrityCheck(engine, sourceIds?)` is the `WAVE_CHECKS` entry (scoped for a remote caller). Location only. #6278: the check also counts `unrenderable_legacy_facts`: the active `row_num IS NULL` fact rows the fence step leaves unadopted because the fence codec would change their text (or their page already carries the claim), planned read-only per source within the census time budget (`planUnfencedFacts` + `auditUnadoptableFacts`) and listed by page, fact id and reason class, never the claim text. They stay active and searchable, so the finding says nothing is lost, never suggests `forget_fact`, and when it is the only finding its fix carries no command (`next: report`) with the doctor re-count as verify; an incomplete scan asks for a rerun. #6610: `unbound_legacy_facts` lists, from the same plan, unfenced rows of classic database-only pages that `persistence.unbound_write` keeps unfenced; when it is the only finding the fix is `gbrain config set persistence.unbound_write database_only` with `ask_user`. Test: `test/doctor-fence-integrity.test.ts`, `test/extract-facts-unfenced-rows.test.ts`.+- `src/commands/doctor/checks/fence-integrity.ts` — `fence_integrity` (#6188, BRAIN, registered before `search_mode`). Each run advances the fence census within `GBRAIN_DOCTOR_FENCE_TIMEOUT_MS` (default 10 s), then reports per source the malformed facts/takes fences still waiting, each counted once (held file, stored page, unsynced file) and split by planned tier (deterministic, resolver, llm, manual), the oldest hold's age, the 7-day `fences_normalized` trend with top writers (warns at `FENCE_NORMALIZATION_WARN_7D` = 20), and the model-repair caps with today's ledger spend. `ok` only when nothing waits, every source's census is complete and no source reaches the trend threshold; a partial census warns with the resume command. The fix is the read-only `gbrain repair fences --source <id>` preview for holds, stored pages and files alike; a warn reads `readFenceAutoRepair` (details `auto_repair`): while a maintenance run is active and `fences.repair.enabled` is on, the non-manual fences are "repaired automatically by the next maintenance run", otherwise the fix's `then` is the apply. Model-tier fences say why they wait (`fences.repair.llm` off with the command that turns it on, or today's budget spent with the cap command), else the caps. `fenceIntegrityCheck(engine, sourceIds?)` is the `WAVE_CHECKS` entry (scoped for a remote caller). Location only. #6278: the check also counts `unrenderable_legacy_facts`: the active `row_num IS NULL` fact rows the fence step leaves unadopted because the fence codec would change their text (or their page already carries the claim), planned read-only per source within the census time budget (`planUnfencedFacts` + `auditUnadoptableFacts`) and listed by page, fact id and reason class, never the claim text. They stay active and searchable, so the finding says nothing is lost, never suggests `forget_fact`, and when it is the only finding its fix carries no command (`next: report`) with the doctor re-count as verify; an incomplete scan asks for a rerun. #6610: `unbound_legacy_facts` lists, from the same plan, unfenced rows of classic database-only pages that `persistence.unbound_write` keeps unfenced; when it is the only finding the fix is `gbrain config set persistence.unbound_write database_only` with `ask_user`. Test: `test/doctor-fence-integrity.test.ts`, `test/extract-facts-unfenced-rows.test.ts`. Wave B decision #10: `withSkippedSegmented(check, n)` (`src/commands/doctor/check-fix.ts`) adds `Check.skipped_segmented: n` and a `skipped (segmented): n` message tail (unchanged at n = 0) to every check whose scan reads whole bodies: `oversized_pages`, `scraper_junk_pages`, `markdown_body_completeness`, `link_resolution_opportunity`, `fence_integrity` (segmented pages without a walked checkout file), `core_memory`, and `extract_health` via `readFactsReconcileBacklog`'s `skipped_segmented`; each count is one COUNT query that falls back to 0 on a schema without `body_storage`. Test: `test/large-pages/doctor-skipped-segmented.test.ts` (+ Postgres arm).- `src/commands/doctor/checks/git-convergence.ts` — `git_convergence` (#5063, brain category, after `sync_freshness`): for every non-archived filesystem source root plus `sync.repo_path` (connector sources skipped), `git status --porcelain -z` and `rev-list --left-right --count @{u}...HEAD` against the local upstream ref, never a fetch, each call bounded at 5 s and at most 50 roots. Commits not on the upstream warn after 6 h and fail after 24 h (oldest unpushed commit time); uncommitted changes warn once the oldest changed file is older than 6 h; behind is reported, not judged. Emits nothing when no probed root has an upstream. The same entry emits `tracked_ownership_marker` (#5186): `git ls-files --cached` on each of those checkouts, warn when a path `isPhysicalRootMetadata` recognizes is in the index, with a user-run `git -C <root> rm --cached <paths>` fix (an ignore rule never un-tracks a file; the push deny list is the backstop), ok otherwise, nothing without a checkout. `bootstrap-checks.ts` `bootstrap_push_health` also warns, instead of `ok`, when a recent successful push leaves the receipt workspace ahead of `origin/<branch>`. `scripts/smoke-test.sh` accepts a configured database URL (`engine status` `db_url_source`) and trusts doctor `embedding_provider` over raw OpenAI/Voyage keys. Tests: `doctor-git-convergence-5063.test.ts`, `doctor-ownership-marker.test.ts`, `bootstrap-doctor-checks.test.ts`, `smoke-test-worker.test.ts`.- `src/commands/doctor/checks/keyword-plan.ts` — `keyword_plan` (#6495, OPS, wave check with operator resolution; the keyword-side twin of `vector_plan` in commands-2.md). Postgres only: reads the commonest lexeme the planner knows for `content_chunks.search_vector` (`pg_stats.most_common_elems` with its frequency), EXPLAINs (no ANALYZE) the strict page-count statement for it (`buildKeywordCountStatement`, the builder the engine uses) and times the engine's own bounded `countKeywordPages(term, { timeoutMs: 2000 })`; warns `canary_timed_out` when that count hits its bound and `canary_slow` when it takes more than half of `search.keyword_statement_timeout_ms`, naming the knob with its range (1000-60000), the fail-open to the vector arm (`keyword_arm_failed`), that a longer bound buys time and not a cheaper statement, that one canary term is not workload coverage, and that a timed-out count is never "no matches". Skipped on PGLite, below 10,000 chunks (`pg_class.reltuples`) and without planner statistics (it names `ANALYZE content_chunks`); a failing probe reports unknown health. `engineKeywordPlanProbe(engine)` is the database side; `keywordPlanCheck(engine, probe?)` takes a fake for tests. Tested in `test/doctor-keyword-plan-6495.test.ts` (fake probe for every outcome; with DATABASE_URL the real probe on a seeded brain and a lock-forced timeout).diff --git a/docs/architecture/key-files/core-utilities-2.md b/docs/architecture/key-files/core-utilities-2.mdindex 23f536a29e..2a2ccf84d2 100644--- a/docs/architecture/key-files/core-utilities-2.md+++ b/docs/architecture/key-files/core-utilities-2.md@@ -18,7 +18,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/core/repair/fences.ts` — `gbrain repair fences` (#6188), preview-bound, `spends: 'llm'`, not explicit-only (no destructive consent). Candidates: the fence census (`listFenceCandidates` after a bounded `runFenceCensus`, `GBRAIN_FENCE_REPAIR_SCAN_MS`, default 10 s) filtered by `--only`/`--skip <path>` and `--slug <slug>`, plus files or pages the selection names that the census has not judged. Per candidate (`fence-repair/repair-io.ts` reads the current bytes): a host that may not write the source is skipped with the owner condition as its reason (`host_mismatch`, `transfer_in_progress`, `clone_in_progress`, `incarnation_changed`, `local_path_missing`, `coordination_path_missing`; `owner_unavailable` is the fallback; the skip's detail carries `why`, the read-only fix and `retryable`), a candidate a write in flight or an unfinished sync's frozen manifest still names is `sync_in_progress` (#6278: checked at plan, at apply and again at the write's admission in `file-repair.ts`; the rest of the source repairs while the sync runs, and a held path is not busy); `analyzeFences` (`repair-tiers.ts`) decides `proposal` (Tier 1 or Tier 2, validated, a fixed point, the exact diff), `llm` (only Tier 3 residuals: `fences.repair.llm`/`--no-llm` → `llm_disabled`, a page whose tags its file lacks → `canonical_overlay` before any spend, no measured model with a key and `models.fence_repair` unset → `no_measured_model`, an unpriced model under a user cap → `no_pricing`, under the default caps a warn-and-run notice naming `gbrain pricing set`, 0 caps or an estimate over `fences.repair.max_usd_per_page` → `budget_exhausted`, an attempt memo already rejected for these bytes → its stored verdict at $0) or `manual` with the exact location-only edit. The model is `resolveFenceRepairModel` (`fence-repair/model.ts`: `models.fence_repair`, else the first measured model with a key, else none). The preview saves the approved set (`previewHash` over sources, selection and each item's location, bytes hash, revision, tier and after-hash) and prints `apply_command` with `--expect`; `--apply --expect` replays it (`changed_since_preview` for moved bytes or revision), a bare `--apply` applies the current plan starting after the last candidate the previous bare run touched (`fence-repair-rotation`). Apply refuses a remote caller (`trusted_cli_required`) and runs Tier 3 through `runTier3` (ledger reservation, attempt claim, a corrective re-ask only after gate (a) or (e)); a daily-ledger refusal stops the run (`budget_exhausted`, D15: spent and cap, reset time, pages waiting, `gbrain config set fences.repair.max_usd_per_day <usd>` with consent `paid`). Outcomes `repaired` / `held` (FenceReason, also written to the hold with `recordFenceHoldRepair`) / `skipped`; `report` adds `repaired`, `remaining` by reason (an `--expect` apply re-checks the selection for what stays held) and `verification` (`FenceRepairVerification`: repaired per tier, held per reason, oldest hold, USD per Tier 3 repair). Tests: `test/repair-fences.test.ts` (PGLite and Postgres), `test/fence-repair-llm.test.ts`.- `src/core/repair/content-lane.ts` — the content-repair lane (#6377). `CONTENT_REPAIR_KINDS` is the ordered list of repair kinds that clear managed-sync content holds (today `fences`; the GBRA-72 integration appends `slug-conflicts`), read by `gbrain repair content` (`src/commands/repair-content.ts`), the `content_repair` cycle phase and `gbrain sync unblock --apply`, so a new kind plugs in with one entry. `CONTENT_REPAIR_HOLD_KINDS` maps a hold code to the kind that clears it (`invalid_fence` → `fences`; `frontmatter_slug_conflict` → `null` until Lane B's kind lands, which keeps the surfaces' refusal text). `runContentLane(engine, scope, { apply, kinds?, only, skip, expect?, noLlm, maxLlmUsd, deadline, registry? })` has no rule logic: it runs each kind through `repairRunner` in order, passing the run's paid allowance minus what earlier kinds spent (read from each result's `cost.llm_usd`; the daily ledger is `FENCE_REPAIR_LEDGER` for every kind) and one absolute deadline (a `time_budget` stop ends the pass; any other stop lets the next kind run), and returns per-kind results, each kind's own `preview_hash` (no combined hash: `--expect` is one hash per kind in lane order, `parseContentLaneExpect` refuses a wrong count with `invalid_params` before any kind runs), the lane's spend and remaining allowance, and `apply_command` (`contentLaneArgv`). A preview plans every kind before any mutation; `--apply --expect` binds each kind to its approved set; a bare apply runs each kind's own plan-and-apply (`changed_since_read` binding, held reasons recorded on the holds). `contentHoldDisposition(record, auto)` reads a hold's stored repair state (`fenceHoldStatus` for a fence hold; `meta.content_repair.action` for a slug-conflict hold, read loosely) and says whether an unattended surface may run the kind (`repair`), must list it (`listed`: `needs_human` for a manual reason or a recommended merge, `paid`, `owner`) or has no kind for it (`unsupported`). Output is counts, codes, hashes and paths only. Tests: `test/cycle-content-repair.test.ts` (stub kinds), `test/repair-content.test.ts` (the real `fences` kind through the CLI).- `src/core/repair/slug-conflicts.ts` — `gbrain repair slug-conflicts` (#6377, Lane B), the lane kind that clears `frontmatter_slug_conflict` holds: preview-bound, `spends: 'llm'`, `checks: []` (doctor keeps `git_held_files` on `frontmatter`), not explicit-only. Candidates are the source's slug-conflict holds (plus `--only <path>`); identity is resolved, not textual: the frontmatter slug is normalized the way the screen does and resolved through `slug_aliases` to a page id in the same source (a slug resolving to the held file's own page is exempt; a held file with no page yet is a normal candidate). Deterministic tier (`remove_slug`, confidence high): the named slug resolves to no page and names no other file, or to a page of a different type sharing no title token; the one-line edit publishes through the frontmatter repair's coordinated path (`prepareRepairPublication` / `submitManagedFileRepair`: bytes bound to the sha256 the preview read, import, hold clear and Git effect in one write). Every verdict uses managed sync's own screen (`sync-screen.ts` `loadSyncScreenRun` + `frozenImportScreenInput` + `screenFrozenContent`, on the file's bytes and on the edited bytes): a held file the screen now admits as it is (its line is clean, or names the file's own page as written) is planned as `import` and published unchanged through `submitManagedFileRepair` with an `import` receipt and `holdObservedAt` (the hold observation the plan read; a newer hold is kept and the hold records a `changed_since_read` retry); a file sync would hold whatever the lane writes (the page it is filed as carries another slug than its path, or the line reaches the own page only through an alias) is held `slug_page_mismatch` with both slugs (`named` on the hold). Everything else goes to the model tier (`src/core/content-repair/judgment.ts`): `remove_slug` applies the same way, `merge_into <canonical>` and `needs_human` are recorded on the hold as codes and slugs only (`recordContentHoldRepair`, `meta.content_repair`) and rendered by `sync status` as `needs_human` paragraphs; nothing merges pages. Caps and ledger are the fence repair's (`FENCE_REPAIR_LEDGER`, `fences.repair.max_usd_per_page` / `_per_day`, `fences.repair.llm`, `--no-llm`, `--max-usd`); the receipt is a `content_repair` receipt (action, tier, confidence, model, cost, before/after sha256) carried by the write and the commit trailer `gbrain-repair: <hold_code> <tier> <confidence>`. Tests: `test/repair-slug-conflicts.test.ts`, `test/repair-slug-conflicts-sync-screen.test.ts`.-- `src/core/repair/frontmatter.ts` — `gbrain repair frontmatter` (#5988), explicit-only, preview-bound, destructive consent (`--yes` with the hash, registry `consent`). #5966 (W14 P1.7): the slug rule itself is `slugStampedFrontmatter(slug, fm)` in `src/core/markdown.ts` (stamps `slug:` when the path cannot derive it, such as a doubled hyphen, and replaces a foreign `fm.slug`; used by `serializePageToMarkdown` and `commands/export.ts`, digest-neutral since `parseMarkdown` drops `fm.slug`); `slugStampCandidate` proposes a SAFE `slug:` stamp for a well-formed file at a page's recorded `source_path` whose path derives another slug and that declares none (a legacy render of a slug the path cannot derive), inserted as `serializeMarkdown` writes it; never normalizes or guesses. Scope: Git-visible `.md`/`.mdx` per source (managed owner root or legacy `local_path`) plus every Git hold row; database side, pages whose body begins with an embedded frontmatter block or whose title is the humanized slug while the file names one. `frontmatterCandidates` builds a safe rewrite (NUL strip, nested-quote swap, `repairRecoverableFrontmatter` quoting; parsed values must be unchanged) and an interpretive one (`autoFixFrontmatter` missing close / slug line, fold, dup, unclosed, `#` rescue); both must strict-parse with no hold. `prepareRepairPublication` binds each proposal to the page fields its import would store; a refusal or canonical overlay is `needs_review`. The hash covers sources, `include_ambiguous`, `--only`/`--skip`, and per file before/after sha256, page id/revision, result digest and `rename_from`; the approved set stores no frontmatter text. An `invalid_fence` hold is listed with a resolution that defers to `gbrain repair fences --source <id> --only <path>` (frontmatter repair never changes fences). Apply refuses while an unfinished managed sync cursor names a selected path, re-derives each change, then publishes through `managed_file_repair` (managed) or backup, write, `importFromFile`, hold clear and a printed commit step (legacy). Tests: `test/repair-frontmatter.test.ts`.+- `src/core/repair/frontmatter.ts` — `gbrain repair frontmatter` (#5988), explicit-only, preview-bound, destructive consent (`--yes` with the hash, registry `consent`). #5966 (W14 P1.7): the slug rule itself is `slugStampedFrontmatter(slug, fm)` in `src/core/markdown.ts` (stamps `slug:` when the path cannot derive it, such as a doubled hyphen, and replaces a foreign `fm.slug`; used by `serializePageToMarkdown` and `commands/export.ts`, digest-neutral since `parseMarkdown` drops `fm.slug`); `slugStampCandidate` proposes a SAFE `slug:` stamp for a well-formed file at a page's recorded `source_path` whose path derives another slug and that declares none (a legacy render of a slug the path cannot derive), inserted as `serializeMarkdown` writes it; never normalizes or guesses. Scope: Git-visible `.md`/`.mdx` per source (managed owner root or legacy `local_path`) plus every Git hold row; database side, pages whose body begins with an embedded frontmatter block or whose title is the humanized slug while the file names one. `frontmatterCandidates` builds a safe rewrite (NUL strip, nested-quote swap, `repairRecoverableFrontmatter` quoting; parsed values must be unchanged) and an interpretive one (`autoFixFrontmatter` missing close / slug line, fold, dup, unclosed, `#` rescue); both must strict-parse with no hold. `prepareRepairPublication` binds each proposal to the page fields its import would store; a refusal or canonical overlay is `needs_review`. The hash covers sources, `include_ambiguous`, `--only`/`--skip`, and per file before/after sha256, page id/revision, result digest and `rename_from`; the approved set stores no frontmatter text. An `invalid_fence` hold is listed with a resolution that defers to `gbrain repair fences --source <id> --only <path>` (frontmatter repair never changes fences). Apply refuses while an unfinished managed sync cursor names a selected path, re-derives each change, then publishes through `managed_file_repair` (managed) or backup, write, `importFromFile`, hold clear and a printed commit step (legacy). Tests: `test/repair-frontmatter.test.ts`. Wave B decision #10: the preview and the apply count the source's pages stored in segments (one COUNT; their stored head is NULL, so the embedded-block check skips them) as residual `skipped_segmented` plus a `skipped (segmented): N` warning, absent at 0 (`test/large-pages/doctor-skipped-segmented.test.ts`).- `src/core/persistence/mirror-read-only.ts` and `src/commands/sources-mirror.ts` — #5409 read-only mirror sources. `sourceMirrorReadOnly(engine, sourceId)` reads `sources.config.mirror_read_only` (default false). When true, `prepareFileTarget` (`page-prepare.ts`) returns no file for any coordinated page write into the source (receipt `write_through.skipped: 'mirror_read_only'`, `storage: 'database_only'`, set in `coordinator.ts`), and managed sync (`sync-prepare.ts`) imports an overlay (canonical form differs from the file bytes) database-only: no `file`, no newer-working-tree refusal, and `contentUnchanged` ignores the overlay. A page created that way with no recorded file is stamped `pages.database_only_reason='mirror_read_only'` (`classifyMirrorPage`, in the publication) and stays database-only after the flag is cleared; the coordinator refuses (`source_changed`) a file target prepared before the flag was set (rechecked under the publication with the source row `FOR SHARE`); `gitPage` (`effects.ts`) completes a mirror source's Git effects as skipped. `gbrain sources mirror-readonly|mirror-writable <id>` set and clear the key like `federate`/`unfederate`; `sources list --json` reports `mirror_read_only`.- `src/core/restore-target.ts` -- `resolveRestoreTarget(engine, source, repo)`: the source and repo `gbrain export --restore-only` restores, shared with `gbrain storage status` so its printed restore command restores exactly the files it lists. An explicit source (already resolved) wins; a repo without a source selects the one active source registered at that exact path, refuses a repo registered only to an archived source, else selects the only active source; neither selects the flagless resolver chain's source and its `local_path` (the legacy `sync.repo_path` answers for `default` only). `restoreFilePath(repo, slug, sourcePath, sourcePathBytes, slugRootMode)` is the file whose absence makes the restore write a page: the recorded `source_path` resolved in the repo in the source's slug-root mode (`scannerSlugRootMode`), else `<slug>.md`; an over-long or unsafe recorded path throws. Refusals throw `RestoreTargetError`; resolver and database errors propagate unchanged.diff --git a/docs/guides/memory-boundaries.md b/docs/guides/memory-boundaries.mdindex e0bf842187..cb24c007a5 100644--- a/docs/guides/memory-boundaries.md+++ b/docs/guides/memory-boundaries.md@@ -180,6 +180,19 @@ pages wait. A quarantined page says`searchable: false`. `gbrain import` waits for the build and reports`searchable` in its result the same way.+<a id="segmented-doctor-skips"></a>+**What doctor does not read on a segmented page.** Some doctor checks read a+page's whole body as one string, and a page stored in segments has none.+Those checks say how many such pages they passed by: `oversized_pages`,+`scraper_junk_pages`, `markdown_body_completeness`,+`link_resolution_opportunity`, `fence_integrity`, `core_memory` and+`extract_health` (its facts-backlog overlay) carry `skipped_segmented: N` in+`gbrain doctor --json` and end their message with `skipped (segmented): N`.+`gbrain repair frontmatter` reports the same count (residual+`skipped_segmented` and a warning) for the stored bodies it does not check;+it still checks their files. An `ok` from such a check covers only the pages+it read. The field is absent when no page is stored in segments.+While the switch is off (unset in this release, set to `off`, or held by anolder writer), new pages are stored inline up to 24 MiB as before.Pages already stored in segments stay readable and exportable; a write thatdiff --git a/docs/integrations/reliability-repair.md b/docs/integrations/reliability-repair.mdindex 5bed56f0d2..e76646cd8a 100644--- a/docs/integrations/reliability-repair.md+++ b/docs/integrations/reliability-repair.md@@ -33,7 +33,9 @@ Reports two checks:- `jsonb_integrity` — counts double-encoded rows per table and points youat `gbrain repair-jsonb`.- `markdown_body_completeness` — heuristic for pages whose `compiled_truth`- is suspiciously short compared to `raw_data.data ->> 'content'`.+ is suspiciously short compared to `raw_data.data ->> 'content'`. A page+ stored in segments has no `compiled_truth` column to compare, so it is not+ checked; the check reports how many with `skipped_segmented: N`.## Repairdiff --git a/llms-full.txt b/llms-full.txtindex 4f5b8eed16..50078a3af3 100644--- a/llms-full.txt+++ b/llms-full.txt@@ -10180,6 +10180,11 @@ gbrain doctor --json- `schema_version`: current- `embeddings`: coverage percentage+A check that carries `skipped_segmented: N` (message ending in+`skipped (segmented): N`) did not read N pages stored in segments, so its+`ok` covers only the pages it read; see+[segmented page storage](guides/memory-boundaries.md#segmented-doctor-skips).+**If it fails:** The doctor output includes specific fix instructions for eachcheck. See `skills/setup/SKILL.md` Error Recovery table.@@ -11794,7 +11799,9 @@ Reports two checks:- `jsonb_integrity` — counts double-encoded rows per table and points youat `gbrain repair-jsonb`.- `markdown_body_completeness` — heuristic for pages whose `compiled_truth`- is suspiciously short compared to `raw_data.data ->> 'content'`.+ is suspiciously short compared to `raw_data.data ->> 'content'`. A page+ stored in segments has no `compiled_truth` column to compare, so it is not+ checked; the check reports how many with `skipped_segmented: N`.## Repairdiff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsvindex d7d70a1418..81a0d9076a 100644--- a/scripts/module-size-limits.tsv+++ b/scripts/module-size-limits.tsv@@ -5,7 +5,7 @@# Columns: path max_lines policy notesrc/cli/main.ts 3012 ratchet +1 Cat 41 run 4: recall's SELF_HELP_WITHOUT_ENGINE table entry (a dispatch table row cannot move); moved from src/cli.ts at 3214 (cold start: src/cli.ts is now the 66-line entry with the --version/help fast path; the top-level help text moved to cli/top-help.ts and the exit seam became runCli/exitOnFatalCliError); +2 #6340: the sync status / sync unblock preflight skip (logic in commands/sync/operator.ts); +3 agent operator gate fixes: repair-failed connect wrapper (logic in cli/cli-error.ts exitOnRepairFailed), transcripts recent through a live serve (logic in commands/transcripts.ts), pre-connect status reason (logic in commands/serve-status.ts); +23 merged from the collector (Lanes B/E/F: thin-client token reason, status-only serve hand-off, jobs/sync readiness wiring); +9 agent operator wave D3/D4: curated --help short-circuit (renderer in cli/help/render.ts), curated flag-value validation call (cli/help/validate.ts), table-dispatched SELF_HELP_WITHOUT_ENGINE entries for the selfHelp flips; +5 agent operator wave C10 (merged from the collector): serve --fail-fast in the connect-failure path; +31 #5950 (D6): connectEngine thin-client backstop, engine-free MCP-twin dispatch, recall/advisor/export refusal hints, refusal fix subcommand (lowered to 3131 by D1's renderCliError seam first); +2 agent operator wave A4: observational startup (probe-only connect for startup:observational commands; completeEngineStartup split out of connectEngine, exposed as ctx.completeStartup); +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5232: write-wait import, reporter-owned verdict in the op catch, thin-client writeWaitMs, ctx.writeWaitMs (logic in persistence/write-wait.ts); +1 #4768: serve --access help line; +4 #5433: list_pages TSV cell escaping in formatResult; +2 #lane-h pricing: help line + thin-client refusal hint for `gbrain pricing`; +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5433: list_pages TSV cell escaping in formatResult; +1 #5984: a strict run deadline when no progress window is set; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (3199 measured); +2 retrieval feedback: answer id line on stderr and additive answer_id on --json search/query rows (logic in feedback/record.ts); +1 feedback help line and its D3 table-dispatch entry (logic in commands/feedback.ts); 6 engine graduation (GBRA-50 G3): migrate pre-connect route (logic in commands/migrate-graduation.ts), serve start refusal and degraded-reconnect identity gate (logic in persistence/graduation-serve-guard.ts), usage line; +3 engine graduation (GBRA-50 G2a): connect-path graduation check on every engine (logic in persistence/graduation-custody.ts assertGraduationConnectAllowed); P3 x engine graduation composition: both deltas re-summed at the merge; 1 Foundations 2 Lane F: sources refresh pre-connect delegation to a resident PGLite owner (logic in commands/sources-refresh-delegate.ts); +3 agent operator gate fixes: repair-failed connect wrapper (logic in cli/cli-error.ts exitOnRepairFailed), transcripts recent through a live serve (logic in commands/transcripts.ts), pre-connect status reason (logic in commands/serve-status.ts); +23 merged from the collector (Lanes B/E/F: thin-client token reason, status-only serve hand-off, jobs/sync readiness wiring); +9 agent operator wave D3/D4: curated --help short-circuit (renderer in cli/help/render.ts), curated flag-value validation call (cli/help/validate.ts), table-dispatched SELF_HELP_WITHOUT_ENGINE entries for the selfHelp flips; +5 agent operator wave C10 (merged from the collector): serve --fail-fast in the connect-failure path; +31 #5950 (D6): connectEngine thin-client backstop, engine-free MCP-twin dispatch, recall/advisor/export refusal hints, refusal fix subcommand (lowered to 3131 by D1's renderCliError seam first); +2 agent operator wave A4: observational startup (probe-only connect for startup:observational commands; completeEngineStartup split out of connectEngine, exposed as ctx.completeStartup); +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5232: write-wait import, reporter-owned verdict in the op catch, thin-client writeWaitMs, ctx.writeWaitMs (logic in persistence/write-wait.ts); +1 #4768: serve --access help line; +4 #5433: list_pages TSV cell escaping in formatResult; +2 #lane-h pricing: help line + thin-client refusal hint for `gbrain pricing`; +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5433: list_pages TSV cell escaping in formatResult; +1 #5984: a strict run deadline when no progress window is set; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (3199 measured); +3 agent operator gate fixes: repair-failed connect wrapper (logic in cli/cli-error.ts exitOnRepairFailed), transcripts recent through a live serve (logic in commands/transcripts.ts), pre-connect status reason (logic in commands/serve-status.ts); +23 merged from the collector (Lanes B/E/F: thin-client token reason, status-only serve hand-off, jobs/sync readiness wiring); +9 agent operator wave D3/D4: curated --help short-circuit (renderer in cli/help/render.ts), curated flag-value validation call (cli/help/validate.ts), table-dispatched SELF_HELP_WITHOUT_ENGINE entries for the selfHelp flips; +5 agent operator wave C10 (merged from the collector): serve --fail-fast in the connect-failure path; +31 #5950 (D6): connectEngine thin-client backstop, engine-free MCP-twin dispatch, recall/advisor/export refusal hints, refusal fix subcommand (lowered to 3131 by D1's renderCliError seam first); +2 agent operator wave A4: observational startup (probe-only connect for startup:observational commands; completeEngineStartup split out of connectEngine, exposed as ctx.completeStartup); +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5232: write-wait import, reporter-owned verdict in the op catch, thin-client writeWaitMs, ctx.writeWaitMs (logic in persistence/write-wait.ts); +1 #4768: serve --access help line; +4 #5433: list_pages TSV cell escaping in formatResult; +2 #lane-h pricing: help line + thin-client refusal hint for `gbrain pricing`; +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5433: list_pages TSV cell escaping in formatResult; +1 #5984: a strict run deadline when no progress window is set; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (3199 measured); +6 engine graduation (GBRA-50 G3): migrate pre-connect route (logic in commands/migrate-graduation.ts), serve start refusal and degraded-reconnect identity gate (logic in persistence/graduation-serve-guard.ts), usage line; +3 engine graduation (GBRA-50 G2a): connect-path graduation check on every engine (logic in persistence/graduation-custody.ts assertGraduationConnectAllowed); P3 x foundations-2 composition: deltas re-summed at the merge; 1 Foundations 2 Lane F: sources refresh pre-connect delegation to a resident PGLite owner (logic in commands/sources-refresh-delegate.ts); +3 agent operator gate fixes: repair-failed connect wrapper (logic in cli/cli-error.ts exitOnRepairFailed), transcripts recent through a live serve (logic in commands/transcripts.ts), pre-connect status reason (logic in commands/serve-status.ts); +23 merged from the collector (Lanes B/E/F: thin-client token reason, status-only serve hand-off, jobs/sync readiness wiring); +9 agent operator wave D3/D4: curated --help short-circuit (renderer in cli/help/render.ts), curated flag-value validation call (cli/help/validate.ts), table-dispatched SELF_HELP_WITHOUT_ENGINE entries for the selfHelp flips; +5 agent operator wave C10 (merged from the collector): serve --fail-fast in the connect-failure path; +31 #5950 (D6): connectEngine thin-client backstop, engine-free MCP-twin dispatch, recall/advisor/export refusal hints, refusal fix subcommand (lowered to 3131 by D1's renderCliError seam first); +2 agent operator wave A4: observational startup (probe-only connect for startup:observational commands; completeEngineStartup split out of connectEngine, exposed as ctx.completeStartup); +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5232: write-wait import, reporter-owned verdict in the op catch, thin-client writeWaitMs, ctx.writeWaitMs (logic in persistence/write-wait.ts); +1 #4768: serve --access help line; +4 #5433: list_pages TSV cell escaping in formatResult; +2 #lane-h pricing: help line + thin-client refusal hint for `gbrain pricing`; +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5433: list_pages TSV cell escaping in formatResult; +1 #5984: a strict run deadline when no progress window is set; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (3199 measured); +3 agent operator gate fixes: repair-failed connect wrapper (logic in cli/cli-error.ts exitOnRepairFailed), transcripts recent through a live serve (logic in commands/transcripts.ts), pre-connect status reason (logic in commands/serve-status.ts); +23 merged from the collector (Lanes B/E/F: thin-client token reason, status-only serve hand-off, jobs/sync readiness wiring); +9 agent operator wave D3/D4: curated --help short-circuit (renderer in cli/help/render.ts), curated flag-value validation call (cli/help/validate.ts), table-dispatched SELF_HELP_WITHOUT_ENGINE entries for the selfHelp flips; +5 agent operator wave C10 (merged from the collector): serve --fail-fast in the connect-failure path; +31 #5950 (D6): connectEngine thin-client backstop, engine-free MCP-twin dispatch, recall/advisor/export refusal hints, refusal fix subcommand (lowered to 3131 by D1's renderCliError seam first); +2 agent operator wave A4: observational startup (probe-only connect for startup:observational commands; completeEngineStartup split out of connectEngine, exposed as ctx.completeStartup); +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5232: write-wait import, reporter-owned verdict in the op catch, thin-client writeWaitMs, ctx.writeWaitMs (logic in persistence/write-wait.ts); +1 #4768: serve --access help line; +4 #5433: list_pages TSV cell escaping in formatResult; +2 #lane-h pricing: help line + thin-client refusal hint for `gbrain pricing`; +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5433: list_pages TSV cell escaping in formatResult; +1 #5984: a strict run deadline when no progress window is set; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (3199 measured); +6 engine graduation (GBRA-50 G3): migrate pre-connect route (logic in commands/migrate-graduation.ts), serve start refusal and degraded-reconnect identity gate (logic in persistence/graduation-serve-guard.ts), usage line; +3 engine graduation (GBRA-50 G2a): connect-path graduation check on every engine (logic in persistence/graduation-custody.ts assertGraduationConnectAllowed); GBRA-49: edge-proposals answers --help without a brain (SELF_HELP_WITHOUT_ENGINE row); P3 x P1 (v0.60.57.0) composition: deltas re-summed at the merge; 1 Foundations 2 Lane F: sources refresh pre-connect delegation to a resident PGLite owner (logic in commands/sources-refresh-delegate.ts); +3 agent operator gate fixes: repair-failed connect wrapper (logic in cli/cli-error.ts exitOnRepairFailed), transcripts recent through a live serve (logic in commands/transcripts.ts), pre-connect status reason (logic in commands/serve-status.ts); +23 merged from the collector (Lanes B/E/F: thin-client token reason, status-only serve hand-off, jobs/sync readiness wiring); +9 agent operator wave D3/D4: curated --help short-circuit (renderer in cli/help/render.ts), curated flag-value validation call (cli/help/validate.ts), table-dispatched SELF_HELP_WITHOUT_ENGINE entries for the selfHelp flips; +5 agent operator wave C10 (merged from the collector): serve --fail-fast in the connect-failure path; +31 #5950 (D6): connectEngine thin-client backstop, engine-free MCP-twin dispatch, recall/advisor/export refusal hints, refusal fix subcommand (lowered to 3131 by D1's renderCliError seam first); +2 agent operator wave A4: observational startup (probe-only connect for startup:observational commands; completeEngineStartup split out of connectEngine, exposed as ctx.completeStartup); +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5232: write-wait import, reporter-owned verdict in the op catch, thin-client writeWaitMs, ctx.writeWaitMs (logic in persistence/write-wait.ts); +1 #4768: serve --access help line; +4 #5433: list_pages TSV cell escaping in formatResult; +2 #lane-h pricing: help line + thin-client refusal hint for `gbrain pricing`; +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5433: list_pages TSV cell escaping in formatResult; +1 #5984: a strict run deadline when no progress window is set; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (3199 measured); +3 agent operator gate fixes: repair-failed connect wrapper (logic in cli/cli-error.ts exitOnRepairFailed), transcripts recent through a live serve (logic in commands/transcripts.ts), pre-connect status reason (logic in commands/serve-status.ts); +23 merged from the collector (Lanes B/E/F: thin-client token reason, status-only serve hand-off, jobs/sync readiness wiring); +9 agent operator wave D3/D4: curated --help short-circuit (renderer in cli/help/render.ts), curated flag-value validation call (cli/help/validate.ts), table-dispatched SELF_HELP_WITHOUT_ENGINE entries for the selfHelp flips; +5 agent operator wave C10 (merged from the collector): serve --fail-fast in the connect-failure path; +31 #5950 (D6): connectEngine thin-client backstop, engine-free MCP-twin dispatch, recall/advisor/export refusal hints, refusal fix subcommand (lowered to 3131 by D1's renderCliError seam first); +2 agent operator wave A4: observational startup (probe-only connect for startup:observational commands; completeEngineStartup split out of connectEngine, exposed as ctx.completeStartup); +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5232: write-wait import, reporter-owned verdict in the op catch, thin-client writeWaitMs, ctx.writeWaitMs (logic in persistence/write-wait.ts); +1 #4768: serve --access help line; +4 #5433: list_pages TSV cell escaping in formatResult; +2 #lane-h pricing: help line + thin-client refusal hint for `gbrain pricing`; +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5433: list_pages TSV cell escaping in formatResult; +1 #5984: a strict run deadline when no progress window is set; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (3199 measured); +6 engine graduation (GBRA-50 G3): migrate pre-connect route (logic in commands/migrate-graduation.ts), serve start refusal and degraded-reconnect identity gate (logic in persistence/graduation-serve-guard.ts), usage line; +3 engine graduation (GBRA-50 G2a): connect-path graduation check on every engine (logic in persistence/graduation-custody.ts assertGraduationConnectAllowed); GBRA-49: edge-proposals answers --help without a brain (SELF_HELP_WITHOUT_ENGINE row); -25 agent-operator follow-up Item 3: the host connect moved to core/engine-connect.ts (throw-only connectEngineForServe, wrapped by connectEngine; the graduation connect gate moved with it); 1 Foundations 2 Lane F: sources refresh pre-connect delegation to a resident PGLite owner (logic in commands/sources-refresh-delegate.ts); +3 agent operator gate fixes: repair-failed connect wrapper (logic in cli/cli-error.ts exitOnRepairFailed), transcripts recent through a live serve (logic in commands/transcripts.ts), pre-connect status reason (logic in commands/serve-status.ts); +23 merged from the collector (Lanes B/E/F: thin-client token reason, status-only serve hand-off, jobs/sync readiness wiring); +9 agent operator wave D3/D4: curated --help short-circuit (renderer in cli/help/render.ts), curated flag-value validation call (cli/help/validate.ts), table-dispatched SELF_HELP_WITHOUT_ENGINE entries for the selfHelp flips; +5 agent operator wave C10 (merged from the collector): serve --fail-fast in the connect-failure path; +31 #5950 (D6): connectEngine thin-client backstop, engine-free MCP-twin dispatch, recall/advisor/export refusal hints, refusal fix subcommand (lowered to 3131 by D1's renderCliError seam first); +2 agent operator wave A4: observational startup (probe-only connect for startup:observational commands; completeEngineStartup split out of connectEngine, exposed as ctx.completeStartup); +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5232: write-wait import, reporter-owned verdict in the op catch, thin-client writeWaitMs, ctx.writeWaitMs (logic in persistence/write-wait.ts); +1 #4768: serve --access help line; +4 #5433: list_pages TSV cell escaping in formatResult; +2 #lane-h pricing: help line + thin-client refusal hint for `gbrain pricing`; +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5433: list_pages TSV cell escaping in formatResult; +1 #5984: a strict run deadline when no progress window is set; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (3199 measured); +3 agent operator gate fixes: repair-failed connect wrapper (logic in cli/cli-error.ts exitOnRepairFailed), transcripts recent through a live serve (logic in commands/transcripts.ts), pre-connect status reason (logic in commands/serve-status.ts); +23 merged from the collector (Lanes B/E/F: thin-client token reason, status-only serve hand-off, jobs/sync readiness wiring); +9 agent operator wave D3/D4: curated --help short-circuit (renderer in cli/help/render.ts), curated flag-value validation call (cli/help/validate.ts), table-dispatched SELF_HELP_WITHOUT_ENGINE entries for the selfHelp flips; +5 agent operator wave C10 (merged from the collector): serve --fail-fast in the connect-failure path; +31 #5950 (D6): connectEngine thin-client backstop, engine-free MCP-twin dispatch, recall/advisor/export refusal hints, refusal fix subcommand (lowered to 3131 by D1's renderCliError seam first); +2 agent operator wave A4: observational startup (probe-only connect for startup:observational commands; completeEngineStartup split out of connectEngine, exposed as ctx.completeStartup); +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5232: write-wait import, reporter-owned verdict in the op catch, thin-client writeWaitMs, ctx.writeWaitMs (logic in persistence/write-wait.ts); +1 #4768: serve --access help line; +4 #5433: list_pages TSV cell escaping in formatResult; +2 #lane-h pricing: help line + thin-client refusal hint for `gbrain pricing`; +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5433: list_pages TSV cell escaping in formatResult; +1 #5984: a strict run deadline when no progress window is set; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (3199 measured); +6 engine graduation (GBRA-50 G3): migrate pre-connect route (logic in commands/migrate-graduation.ts), serve start refusal and degraded-reconnect identity gate (logic in persistence/graduation-serve-guard.ts), usage line; +3 engine graduation (GBRA-50 G2a): connect-path graduation check on every engine (logic in persistence/graduation-custody.ts assertGraduationConnectAllowed); GBRA-49: edge-proposals answers --help without a brain (SELF_HELP_WITHOUT_ENGINE row); -25 agent-operator follow-up Item 3: the host connect moved to core/engine-connect.ts (throw-only connectEngineForServe, wrapped by connectEngine; the graduation connect gate moved with it); +2 entity recall: the human `gbrain entity` card prints referenced_by groups and a non-complete mention coverage; cat40 entity wave merge with v0.60.61.0 (3179 measured); +3 #4772 (W14 PR3): get_health text output says the entity ratios are n/a because the schema pack did not load (entity_types_status); +1 C4: gbrain questions CLI-only dispatch row (its help line is in cli/top-help.ts); +1 #6696 (A4): a local write captures the capacity notices (one call; logic in cli/op-notices.ts captureCapacityNotices); +1 large pages A6: the stdin cap reads PAGE_MAX_BYTES from core/page-size-policy.ts; +3 Wave B PR 2: local gbrain get of a segmented page streams on the page_body_segmented refusal (logic in cli/page-render.ts streamSegmentedGet)src/commands/autopilot.ts 1642 ratchet refactor wave 1 split target (W4 autopilot, cut line); ceiling rationale: docs/architecture/key-files/commands-1.md entry for src/commands/autopilot.ts; +2 fix wave 5: nosemgrep justifications on the per-brain job launchctl/systemctl calls (#5195); +2 #5813: boot reconcile names attempted and running versions in log + audit; +2 #5855: Bun floor gate before the swap and the swap-refusal hold (logic in core/bun-floor.ts); +3 agent operator wave E9: --dry-run and the persistent_install consent gate before anything is written (logic in autopilot/install-consent.ts)-src/commands/doctor.ts 686 ratchet +19 #6696 doctor tiers: Check.elapsed_ms and DoctorReport tier/complete/unknown_sections/elapsed_ms/budget_ms fields, buildChecks/runDoctor deadline params (logic in doctor/budget.ts); +1 agent operator gate fixes: --probe consent gate (logic in doctor/probe-consent.ts); refactor wave 1 split target (W4 doctor); ceiling rationale: docs/architecture/key-files/commands-2.md entry for src/commands/doctor.ts+src/commands/doctor.ts 688 ratchet +2 Wave B decision #10: Check.skipped_segmented field (logic in doctor/check-fix.ts withSkippedSegmented); +19 #6696 doctor tiers: Check.elapsed_ms and DoctorReport tier/complete/unknown_sections/elapsed_ms/budget_ms fields, buildChecks/runDoctor deadline params (logic in doctor/budget.ts); +1 agent operator gate fixes: --probe consent gate (logic in doctor/probe-consent.ts); refactor wave 1 split target (W4 doctor); ceiling rationale: docs/architecture/key-files/commands-2.md entry for src/commands/doctor.tssrc/commands/embed.ts 2304 ratchet +2 agent operator wave D2: --json failure envelope via writeCliError; lowered v0.46.26.0: embedBatchWithBackoff + retry cluster peeled to core/embed-retry.ts (core/commands layering fix); grown wave-g (#4530): per-model input-limit wiring; wave-k #3622 reimpl: --stale zero-progress failure quarantine; +29 #4668 (#4530): oversize-heal call sites in both --stale drains — kept low by peeling the healed-row remap to core/embed-oversize-heal.ts (shared with embed-stale.ts); +35 #4647 (refs #4599): per-tick timeout+abort on the single-flight lock heartbeat refresh (interval deliberately NOT unref'd); +122 refs #4599: stall-watchdog race around the drain + shared idempotent flushAndRelease + CLI stall exit mapping (watchdog machinery itself lives in core/embed-stall.ts); +12: adversarial-review hardening (healed_splits progress key + heal-tick comment); #5105: guarded derived projection preparation and read seals; #5105: conditional embedding installer wiring; archived eligibility: active-only dispatch with honest stranded-work reporting; explicit archived admission: live-source snapshots and honest refused-installation failures; +2 fw3: embed --stale --images dispatch (sweep lives in core/embed-stale-images.ts); +5 #5289: dry run reports restamp-only chunks apart from chunks to embed (count lives in core/embedding-invalidation.ts); +6 #4616: keep a partially refused batch in embedPageTexts and name the recovery command in failure samples (guard lives in core/ai/embedding-guard.ts); +5 #5226: embed summary counts distinct pages; +3 #5804: null projection snapshot counted as a failure with one batch summary in embed --stale; +18 wave 8 lane D1: #5527 mixed-space warning subtracts current-model chunks (+4), #5885 takes option/result fields and the stale-drain takes call (pass lives in core/embed-takes.ts); +9 Foundations 1 F4d: time-budget stop result fields, stdout verdict and stop recording in embed --stale (logic in core/embed-budget-stop.ts); +8 green-master lane A: chunkless install re-reads through retryProjectionConflict instead of recording an unavailable page (retry lives in core/page-state/projections.ts, failure line in core/agent-output.ts); +8 fix wave 13 P1.18: runEmbed consent parameter, cost-cap stop wiring and result fields, --slugs parsing to the next flag (cap, verdict and resume logic live in core/embed-cost-cap.ts); +28 large pages A9/T3/T16: --held listing and per-page cap metering on every embed path (logic in core/page-embedding-budget.ts meterPageBatch/spendGrant/heldEmbedArgv), approvedPageCapUsd from --max-usd on --slugs; +1 #6722: an explicit slug embed skips an embed_skip page (it keeps keyword chunks, never vectors); merge v0.60.240.0: large pages and master growth compose at 2265; +39 large pages Wave B lane 1e: segmented pages route to the keyset sweep on the slug, --all and --stale paths, with a dry-run count and provenance stamp (logic in core/page-body/segmented-embedding.ts)src/commands/extract-conversation-facts.ts 2103 ratchet grown v0.46.x per-provider gateway-unavailable copy; grown wave-g (#4482): expected budget/deadline caps classified apart from error halts; wave-k: save-time resolution caller (#4052/#3729 — supersedes wave-g's per-row resolveEntitySlug mapper); +1: key-aware llm-fallback default (#3813); +1: pricingOverrides wiring into the owned BudgetTracker (#4633 adoption); +3: #4869 snapshot-mismatch counts as pages_failed; merged reliability/shared-skills source integration; +19: additive skip reasons and model-free dry-run (#5364); +21 #5757: managed extraction buffers a page's rows and replaces the prior batch in one coordinator transaction (replacement helper lives in core/persistence/derived-facts.ts); +18 #5823: result diagnostics, strict explicit-cap parsing and CLI recovery/help; default-cap decision lives in facts/conversation-budget.ts; +18 fix wave 7 (#5704, #5448): --json envelope on stdout (parser flag, help line, summary block gated behind the human-output branch); +2 fix wave 10 (#6037, issue #6033): explicit-slug page failures are contained per page through one bounded failure logger (recordPageFailure) shared with the pooled path; +4 fix wave 10 (#5120): facts.default_visibility resolved once per run (resolveDefaultVisibility) and applied to extracted rows only; 2 P2 segmentObservationDate + segmentValidFrom helpers (date-grounding observation time per segment; extractor event date wins over segment start); +4: ExtractConversationFactsResult.failed_pages (interface field) and the help text exit-status paragraph; partial-success logic lives in core/facts/conversation-run-status.ts; re-summed at the master 6ccf30c3e merge (2179 master lines + 20 integration lines over base); re-summed at the #6020 merge on actual lines (as rehearsed on capy/mpw-integration-p2); re-summed at the wave 10 merge on actual lines (+1 recordPageFailure fills failed_pages); lowered at the wave-9 follow-ups merge: the three zero-result literals became emptyExtractConversationFactsResult(); lowered to 2075 at wave 15 P2.5 (#6267): segment tunables, splitIntoSegments and renderSegmentForExtraction moved to core/facts/conversation-windows.ts, the message/segment types to core/facts/conversation-types.ts (re-exported here); +12 large pages T2: the oversized-sidecar snapshot and the durable size-skip receipt (skippedForSize; the cap and the bounded sidecar read live in core/conversation-parser/body.ts, the receipt in core/extraction-watermark.ts); merge v0.60.240.0: large pages and master growth compose at 2087; +7 large pages PR 2 lane 2e2: a segmented conversation over the window cap (snapshot.window, the tail_window receipt, the window fallback date; the window read lives in core/page-body/segment-conversation.ts); +9 lane 2e2 follow-up: the lossless window rule (a page over the window with conversation facts keeps them and is skipped, the receipt names the rule; the count lives in core/facts/conversation-publication.ts)src/commands/extract.ts 2640 ratchet grown v0.46.26.0 megawave: FS-walk stamp snapshot + legacy timeline repair wiring (#3957 D4) + PR#4486 rebase onto current master; grown wave-g (#4542): --from-meetings zero-match warning + default-pass note; +29: #3478 federated-only gate on the cross-source 'default' link fallback; +44: #3908 cross_source opt-in — counted drops + deterministic cross-source pick; +36: #4611 configured-sources.default fallback (resolveLinkFallbackDefault); +14: #4890 extractStaleFromDB quiet opt + extractForSlugs jsonMode batch_error stderr fallback; +5: #4855 stroke-letter fold in link extraction; +5: #4793 by-mention scan honours link_resolution.cross_source; +18: wave review — ExtractOpts.quiet threaded through the fs-walk extractors (stdout silence decoupled from jsonMode); +77: shared buildSlugPathIndex — every per-slug extractor resolves the real on-disk path, and the sync hooks report which slugs they actually read; +10 #4999: includeFrontmatter default-resolved inside extractLinksForSlugs + extractStaleFromDB (resolveIncludeFrontmatter), --stale flag absent -> configured knob; +20: pre-landing review of #4967 — resolveSlugRelPath: index miss falls back to the legacy slug+'.md' path so admitted _-prefixed / include_hidden pages keep their edges; T2: source-qualified inference and atomic origin-scoped derived links; standard DB extraction fences captured endpoint revisions; shared authoritative attendance/source reconciliation moved to the core module; +7 A2 preview-bound attendance repair import, help and authority dispatch; bounded incomplete-attendance diagnostics and consistent basename resolution; fail closed before graph mutation when active ontology is unavailable; +16 source-selected ontology cache, type-scoped preflight and non-starving failed stale drain; +7 write-path wave: per-slug extractors replace page links + retract removed timeline rows + rename-alias resolution; +5 fw3 derived-sync: timeline --prune-orphans CLI (#4649) and full-walk page link replacement; +13 fw3 A16/A15: sync link hook reads scoped page metadata and reports per-page extraction errors; +1 fw3 managed-lifecycle: extract --stale dispatches managed brains to the coordinator-safe path; +4 fw3 integration: managed brains refuse the direct timeline orphan prune; +26 #5609: managed extract --stale publishes links, canonical timeline and watermark per page in one coordinated transaction; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +4 at the merge; +6 fix wave 3 lane B: a managed brain routes the extract phase file walk through extractManagedStaleLinks instead of the refused raw timeline batch, keeping the extract.links_fs progress phase; +6 #5761: the unmanaged extract --stale sweep marks unresolved-attendance skips attendance-blocked; +2 eval-wave N9-3/N12-7: a page-type-bound pack attended rule defers to canonical attendance on the filesystem path (ownsAttendanceInference); lowered to 2528 #5904: the DB timeline walk moved to commands/extract-timeline-db.ts (coordinated publication on managed brains, honest refusal + non-zero exit); +13 entity mention index: extract --stale runs the mention pass after link work (half the budget reserved while mention-due pages exist), dry-run and JSON report mention counts, and the help documents the pass and `extract mentions --explain` (logic in core/mentions/); cat40 entity wave merge with v0.60.61.0 (2541 measured); +6 fix wave 10 lane L1 #5556: quarantined pages skipped by the file walks, slug lists and DB walks (slug lookup in quarantine.ts quarantinedSlugs); +3 #5556: the abort check stays its own statement in each quarantine-aware scan loop (cycle-abort coverage pin); 2 P5 wanted pages: both DB extract paths record unresolved authored refs with each page's links; +5 P5 line grammar: stated relation types on the filesystem link scan; +3 PGLite stale link drains refresh planner statistics before and during the drain (logic in planner-stats.ts plannerStatsForLinkDrain); +10 fix wave 12 W2.1 S4 (#6228): extract --stale flushes and stamps the pages a batch finished before an aborting page; +12 P5 wanted pages: both DB extract paths record unresolved authored refs with each page's links; +9 Q2 parser gaps: both DB extract paths read the line-grammar settings once, publish through replaceDerivedLinksUnlessSettingsChanged and report pages a mid-run settings change left stale; +25 GBRA-69: extract --source db reads snapshots and publishes derived links BATCH_SIZE pages at a time (readPageSnapshotsBatch in core/page-snapshot-batch.ts, replay in derived-links.ts replaceDerivedLinksBatchOrReplay); +2 GBRA-75 w7: the --source db links walk refreshes planner statistics (logic in planner-stats.ts plannerStatsForLinkDrain); +10 fix wave 13 P2.16 (#6272): both unmanaged DB link drains defer and count a page a concurrent writer moved (skipped_concurrent_write) instead of aborting the run (classifier and skip line in core/derived-links.ts); +3 fix wave 13 P2.18 (S4): extract all --source db stamps the pages both phases completed at one revision, in a finally (stampCompletedIntersection), instead of every links-phase page; +1 fix wave 13 P2.15 (#6273): --from-meetings exits non-zero while managed entity pages are still pending; +7 fix wave 13 PR2: extractFromDB split out of runExtract so runExtract stays under its function-size baseline; +3 PR 2 fix lane J1: extract --stale reads a segmented page block by block (extractSegmentedPageLinks, segmentedTimelineText) now that the stale list includes itdiff --git a/src/commands/doctor.ts b/src/commands/doctor.tsindex 8020d0806b..d27f8eca52 100644--- a/src/commands/doctor.ts+++ b/src/commands/doctor.ts@@ -177,6 +177,8 @@ export interface Check extends CheckAgentFields {category?: CheckCategory;/** #6696 B1: wall time of the registry entry that produced this check. */elapsed_ms?: number;+ /** Wave B decision #10: pages stored in segments this whole-body check did not read; only when > 0 (`withSkippedSegmented`). */+ skipped_segmented?: number;}/**diff --git a/src/commands/doctor/check-fix.ts b/src/commands/doctor/check-fix.tsindex c2215c2dfe..bc41956312 100644--- a/src/commands/doctor/check-fix.ts+++ b/src/commands/doctor/check-fix.ts@@ -120,6 +120,19 @@ export function checkError(name: string, what: string, err?: unknown, opts: { st};}+/**+ * Wave B decision #10: a check whose scan reads whole page bodies skips pages+ * stored in segments (their body columns are NULL). It reports how many with+ * `skipped_segmented: n` and a message ending in `skipped (segmented): n`,+ * so a segmented brain never looks healthier than it was checked to be.+ * n = 0 returns the check unchanged.+ */+export function withSkippedSegmented<T extends { status: Check['status']; message: string; skipped_segmented?: number }>(check: T, n: number): T {+ if (!n) return check;+ return { ...check, skipped_segmented: n,+ message: `${check.message} skipped (segmented): ${n} page(s) store their body in segments, and this check reads whole bodies, so it did not check them.` };+}+function isRendered(fix: Action | RenderedAction): fix is RenderedAction {return typeof (fix as RenderedAction).next === 'string';}diff --git a/src/commands/doctor/checks/calibration.ts b/src/commands/doctor/checks/calibration.tsindex 79009df3b6..3ab8f30b30 100644--- a/src/commands/doctor/checks/calibration.ts+++ b/src/commands/doctor/checks/calibration.ts@@ -21,7 +21,7 @@ import { resolveHardExcludes, DEFAULT_HARD_EXCLUDES } from '../../../core/searchimport { escapeLikePattern, buildVisibilityClause } from '../../../core/search/sql-ranking.ts';import { safeChunksFilter } from '../../../core/search/safe-chunks.ts';import type { Check } from '../../doctor.ts';-import { checkError, doctorVerify } from '../check-fix.ts';+import { checkError, doctorVerify, withSkippedSegmented } from '../check-fix.ts';import { pricingSetArgv } from '../../../core/budget/no-pricing.ts';// --- v0.36.1.0 calibration doctor checks (T12) ---@@ -266,6 +266,11 @@ export async function checkLinkResolutionOpportunity(const sampled = await engine.executeRaw<{ compiled_truth: string | null; timeline: string | null }>(`SELECT compiled_truth, timeline FROM pages WHERE deleted_at IS NULL ORDER BY id DESC LIMIT ${SAMPLE_LIMIT}`,);+ // Decision #10: a segmented page's body columns are NULL, so the sample scans it as an empty body.+ const [segmented] = await engine.executeRaw<{ n: number }>(+ `SELECT COUNT(*)::int AS n FROM (SELECT body_storage FROM pages WHERE deleted_at IS NULL ORDER BY id DESC LIMIT ${SAMPLE_LIMIT}) s WHERE s.body_storage = 'segmented'`,+ ).catch(() => []);+ const result = (check: Check) => withSkippedSegmented(check, Number(segmented?.n ?? 0));const totalPages = allSlugs.size;const sampledNote = totalPages > SAMPLE_LIMIT? ` (scanned the ${SAMPLE_LIMIT} most-recent of ${totalPages} pages)`@@ -294,33 +299,33 @@ export async function checkLinkResolutionOpportunity(}if (bareCount === 0) {- return { name, status: 'ok', message: 'No bare wikilinks found' };+ return result({ name, status: 'ok', message: 'No bare wikilinks found' });}if (wouldResolveCount === 0) {- return {+ return result({name,status: 'ok',message: `${bareCount} bare wikilink(s) found, but none have basename matches in the brain.`,- };+ });}const ratio = wouldResolveCount / bareCount;if (wouldResolveCount >= 5 && ratio >= 0.20) {const pct = Math.round(ratio * 100);- return {+ return result({name,status: 'warn',message:`${wouldResolveCount} of ${bareCount} bare wikilinks (${pct}%) would resolve to ` +`${distinctTargets.size} distinct page(s) under global_basename mode${sampledNote}. ` +`Enable with: gbrain config set link_resolution.global_basename true`,- };+ });}const pct = Math.round(ratio * 100);- return {+ return result({name,status: 'ok',message: `${wouldResolveCount}/${bareCount} bare wikilinks (${pct}%) would resolve — below the 20% / 5-link threshold for surfacing a hint${sampledNote}.`,- };+ });} catch (e) {return {name,diff --git a/src/commands/doctor/checks/content-quality.ts b/src/commands/doctor/checks/content-quality.tsindex 14c833edb8..a5a37be78f 100644--- a/src/commands/doctor/checks/content-quality.ts+++ b/src/commands/doctor/checks/content-quality.ts@@ -12,7 +12,7 @@ import { startHeartbeat } from '../../../core/progress.ts';import { checkUnverifiedExtractions } from './extraction-sync.ts';import type { Check } from '../../doctor.ts';import { connectedEngine, type DoctorContext, type DoctorEntry } from '../context.ts';-import { agentFix, checkError, doctorVerify } from '../check-fix.ts';+import { agentFix, checkError, doctorVerify, withSkippedSegmented } from '../check-fix.ts';async function runContentSanity(ctx: DoctorContext): Promise<Check[]> {const { args, progress } = ctx;@@ -70,8 +70,11 @@ async function runContentSanity(ctx: DoctorContext): Promise<Check[]> {WHERE p.deleted_at IS NULL AND p.frontmatter->'embed_skip'->>'reason' = 'oversized'AND (octet_length(p.compiled_truth) + octet_length(COALESCE(p.timeline, ''))) <= $1`, [bytesBlock]);const backfillable = Number(skipped?.n ?? 0);+ // Decision #10: a segmented page's body columns are NULL, so both size scans above pass it by.+ const [segmented] = await engine.executeRaw<{ n: number }>(`SELECT COUNT(*)::int AS n FROM pages p WHERE p.deleted_at IS NULL AND p.body_storage = 'segmented'`).catch(() => []);+ const oversizedCheck = (check: Check) => checks.push(withSkippedSegmented(check, Number(segmented?.n ?? 0)));if (backfillable > 0) {- checks.push({+ oversizedCheck({name: 'oversized_pages',status: 'warn',message: `${backfillable} page(s) were stored without chunks by an older gbrain because of their size, and now fit under the ${bytesBlock}-byte bytes_block. `@@ -80,7 +83,7 @@ async function runContentSanity(ctx: DoctorContext): Promise<Check[]> {'oversized_pages', { docs: 'docs/guides/memory-boundaries.md#large-pages-upgrade' }),});} else if (rows.length === 0) {- checks.push({+ oversizedCheck({name: 'oversized_pages',status: 'ok',message: `No pages exceed ${bytesBlock} bytes (excluding embed_skip pages, which already took the accepted non-embeddable remediation)`,@@ -90,7 +93,7 @@ async function runContentSanity(ctx: DoctorContext): Promise<Check[]> {const top = oversizeRows.slice(0, 3).map(r => `${r.slug} (${r.bytes}b, src=${r.source_id})`).join('; ');- checks.push({+ oversizedCheck({name: 'oversized_pages',status: 'warn',message: `${rows.length} page(s) exceed the ${bytesBlock}-byte content_sanity.bytes_block. Top: ${top}. A page over the block is stored without chunks on its next write. `@@ -163,6 +166,10 @@ async function runContentSanity(ctx: DoctorContext): Promise<Check[]> {);const hits: Array<{ slug: string; matched: string[] }> = [];const scanRows = rows as unknown as Array<{ slug: string; source_id: string; title: string; body_head: string; tl_head: string; frontmatter: Record<string, unknown> | null }>;+ // Decision #10: a segmented row's body heads are NULL, so only its title was assessed (LIMIT NULL is the full audit).+ const [segmentedRow] = await engine.executeRaw<{ n: number }>(`SELECT COUNT(*)::int AS n FROM (SELECT p.body_storage FROM pages p+ WHERE p.deleted_at IS NULL ORDER BY p.updated_at DESC LIMIT $1) s WHERE s.body_storage = 'segmented'`, [scanLimit]).catch(() => []);+ const segmentedScanned = Number(segmentedRow?.n ?? 0);for (const r of scanRows) {const sanity = assessContentSanity({compiled_truth: r.body_head ?? '',@@ -180,20 +187,20 @@ async function runContentSanity(ctx: DoctorContext): Promise<Check[]> {}}if (hits.length === 0) {- checks.push({+ checks.push(withSkippedSegmented({name: 'scraper_junk_pages',status: 'ok',message: scanLimit? `No junk-pattern hits in ${rows.length} recent page(s) (use --content-audit for full scan)`: `No junk-pattern hits in ${rows.length} page(s) (full audit)`,- });+ }, segmentedScanned));} else {const top = hits.slice(0, 3).map(h => `${h.slug} [${h.matched.join(',')}]`).join('; ');- checks.push({+ checks.push(withSkippedSegmented({name: 'scraper_junk_pages',status: 'warn',message: `${hits.length} page(s) match junk patterns. Top: ${top}. ${scanLimit ? '(scanned 1000 most-recent; rerun with --content-audit for full scan)' : '(full audit)'} New ingests with these shapes are now hard-blocked; existing inventory should be cleaned at source.`,- });+ }, segmentedScanned));}} catch (err) {const msg = err instanceof Error ? err.message : String(err);diff --git a/src/commands/doctor/checks/core-memory.ts b/src/commands/doctor/checks/core-memory.tsindex df983c5ac4..b5b0c8a750 100644--- a/src/commands/doctor/checks/core-memory.ts+++ b/src/commands/doctor/checks/core-memory.ts@@ -10,7 +10,7 @@import type { BrainEngine } from '../../../core/engine.ts';import type { Check } from '../../doctor.ts';import { connectedEngine, type DoctorContext, type DoctorEntry } from '../context.ts';-import { agentFix } from '../check-fix.ts';+import { agentFix, withSkippedSegmented } from '../check-fix.ts';import {CORE_CONFIG_KEYS, CORE_DOCS, coreUsage, loadCoreBlock, pendingCoreNotices, readCoreSettings, validateCoreConfigValue,} from '../../../core/core-memory.ts';@@ -24,6 +24,10 @@ const DELIVERY_WINDOW_MS = 7 * 24 * 60 * 60 * 1000;export async function coreMemoryCheck(engine: BrainEngine): Promise<Omit<Check, 'name'>> {const settings = await readCoreSettings(engine);const usage = await coreUsage(engine);+ // Decision #10: core usage reads each page's compiled_truth, which is NULL on a page stored in segments.+ const [segmented] = await engine.executeRaw<{ n: number }>(`SELECT COUNT(*)::int AS n FROM pages p+ WHERE p.deleted_at IS NULL AND p.frontmatter @> '{"always_load": true}'::jsonb AND p.body_storage = 'segmented'`).catch(() => []);+ const skipped = Number(segmented?.n ?? 0);const problems: string[] = [];const badConfig: string[] = [];for (const key of [...Object.values(CORE_CONFIG_KEYS), ...Object.values(PRESSURE_CONFIG_KEYS)]) {@@ -44,13 +48,13 @@ export async function coreMemoryCheck(engine: BrainEngine): Promise<Omit<Check,}if (usage.pages.length === 0) {const issues = [...badConfig, ...compiled];- return {+ return withSkippedSegmented({status: issues.length ? 'warn' : 'ok',message: issues.length ? `No core pages. ${issues.join('; ')}.`: settings.enabled ? 'No core pages. Start one with gbrain core init, then fill it in with the user.': 'Core memory is off (opt-in). If the user wants a profile loaded in every session: gbrain config set memory.core.enabled true, then gbrain core init.',details: { pages: 0, chars_used: 0, chars_limit: settings.maxChars, enabled: settings.enabled, bad_config: badConfig, compiled, docs: CORE_DOCS },- };+ }, skipped);}const block = await loadCoreBlock(engine, { excludePrivate: true, settings });const withheld = block.omitted.filter(o => o.reason === 'withheld');@@ -78,13 +82,13 @@ export async function coreMemoryCheck(engine: BrainEngine): Promise<Omit<Check,revision: block.revision, withheld, pending_notices: notices.length, delivered_last_7d: delivered, bad_config: badConfig, compiled, docs: CORE_DOCS,};if (!problems.length) {- return { status: 'ok', message: `Core memory ${settings.enabled ? 'on' : 'off'}: ${usage.pages.length} page(s), ${usage.chars}/${settings.maxChars} chars.`, details };+ return withSkippedSegmented({ status: 'ok', message: `Core memory ${settings.enabled ? 'on' : 'off'}: ${usage.pages.length} page(s), ${usage.chars}/${settings.maxChars} chars.`, details }, skipped);}- return {+ return withSkippedSegmented({status: 'warn', details,message: `Core memory: ${problems.join('; ')}.`,fix: agentFix(['gbrain', 'core', 'status', '--json'], 'Shows core usage, withheld pages and pending remote edits, read-only.', 'core_memory'),- };+ }, skipped);}async function runCoreMemory(ctx: DoctorContext): Promise<Check[]> {diff --git a/src/commands/doctor/checks/data-integrity.ts b/src/commands/doctor/checks/data-integrity.tsindex c157e0a961..d9879006c0 100644--- a/src/commands/doctor/checks/data-integrity.ts+++ b/src/commands/doctor/checks/data-integrity.ts@@ -18,6 +18,7 @@ import {} from './core-health.ts';import type { Check } from '../../doctor.ts';import { connectedEngine, type DoctorContext, type DoctorEntry } from '../context.ts';+import { withSkippedSegmented } from '../check-fix.ts';async function runIntegrity(ctx: DoctorContext): Promise<Check[]> {const { progress } = ctx;@@ -331,15 +332,26 @@ async function runMarkdownBody(ctx: DoctorContext): Promise<Check[]> {AND (rd.data ->> 'content') ~ '(^|\n)##+ 'LIMIT 100`,);+ // Decision #10: a segmented page's compiled_truth is NULL, so the length comparison above passes it by.+ const [segmented] = await engine.executeRaw<{ n: number }>(+ `SELECT COUNT(DISTINCT p.id)::int AS n+ FROM pages p+ JOIN raw_data rd ON rd.page_id = p.id+ WHERE p.body_storage = 'segmented'+ AND rd.data ? 'content'+ AND length(rd.data ->> 'content') > 1000+ AND (rd.data ->> 'content') ~ '(^|\n)##+ '`,+ ).catch(() => []);+ const skipped = Number(segmented?.n ?? 0);if (rows.length === 0) {- checks.push({ name: 'markdown_body_completeness', status: 'ok', message: 'No truncated bodies detected' });+ checks.push(withSkippedSegmented({ name: 'markdown_body_completeness', status: 'ok', message: 'No truncated bodies detected' }, skipped));} else {const sample = rows.slice(0, 3).map((r) => r.slug).join(', ');- checks.push({+ checks.push(withSkippedSegmented({name: 'markdown_body_completeness',status: 'warn',message: `${rows.length} page(s) appear truncated (sample: ${sample}). Re-import: edit each page body, then run gbrain sync (see docs/integrations/reliability-repair.md)`,- });+ }, skipped));}} catch {// pages_raw.raw_data may not exist on older schemas; best-effort.diff --git a/src/commands/doctor/checks/fence-integrity.ts b/src/commands/doctor/checks/fence-integrity.tsindex ee19f42ab7..2a63320413 100644--- a/src/commands/doctor/checks/fence-integrity.ts+++ b/src/commands/doctor/checks/fence-integrity.ts@@ -33,7 +33,7 @@*/import type { BrainEngine } from '../../../core/engine.ts';import type { Check } from '../../doctor.ts';-import { agentFix, doctorVerify } from '../check-fix.ts';+import { agentFix, doctorVerify, withSkippedSegmented } from '../check-fix.ts';import { auditUnadoptableFacts, planUnfencedFacts, unboundRefusedSentence, type UnadoptableFactRecord, type UnfencedFactsOutcome } from '../../../core/facts/unfenced-facts.ts';import { UNBOUND_SOURCE_DOCS, UNBOUND_WRITE_KEY } from '../../../core/persistence/unbound-source.ts';import { connectedEngine, type DoctorContext, type DoctorEntry } from '../context.ts';@@ -170,8 +170,15 @@ export async function fenceIntegrityResult(engine: BrainEngine, opts: { timeoutMunrenderable_legacy_facts: unrenderable,unbound_legacy_facts: { total: unbound.reduce((sum, page) => sum + page.rows, 0), pages: unbound },};+ // Decision #10: the census judges a stored page by its body columns, which are NULL on a page stored in segments;+ // only the checkout walk judges its file, so a segmented page without a walked file is skipped.+ const [segmented] = await engine.executeRaw<{ n: number }>(`SELECT COUNT(*)::int AS n FROM pages+ WHERE deleted_at IS NULL AND page_kind = 'markdown' AND body_storage = 'segmented' AND source_id = ANY($1::text[])+ AND (source_path IS NULL OR NOT (source_id = ANY($2::text[])))`,+ [census.map(c => c.source_id), runs.filter(run => run.files !== 'none').map(run => run.source_id)]).catch(() => []);+ const skipped = Number(segmented?.n ?? 0);if (!total && !partial.length && !noisy.length && !uncommitted.length && !unrenderable.total && unrenderable.complete && !unbound.length) {- return { status: 'ok', details, message: census.length ? `No malformed facts or takes fence is held, stored or waiting in a checkout (${census.length} source(s) scanned).` : 'No sources to scan.' };+ return withSkippedSegmented({ status: 'ok', details, message: census.length ? `No malformed facts or takes fence is held, stored or waiting in a checkout (${census.length} source(s) scanned).` : 'No sources to scan.' }, skipped);}const auto = await readFenceAutoRepair(engine, now());const at = now().getTime();@@ -215,7 +222,7 @@ export async function fenceIntegrityResult(engine: BrainEngine, opts: { timeoutM// No command to run: the rows stay as they are, so the fix is a report; verify re-counts them.: { consent: [], actor: 'agent' as const, requires_exclusive: false, docs: UNRENDERABLE_DOCS, verify: doctorVerify('fence_integrity'),why: `Nothing to run: ${unrenderable.total} legacy fact row(s) stay active and searchable because their text cannot be written into a facts fence unchanged. Tell the user which pages are listed under unrenderable_legacy_facts and report them with the gbrain version; the verify re-counts the rows.` };- return { status: 'warn', details: { ...details, auto_repair: auto }, fix, message: sentences.join(' ') };+ return withSkippedSegmented({ status: 'warn', details: { ...details, auto_repair: auto }, fix, message: sentences.join(' ') }, skipped);}/** The wave check (`WAVE_CHECKS`): the same verdict, scoped to `sourceIds` when a remote caller is. */diff --git a/src/commands/doctor/checks/local-audits.ts b/src/commands/doctor/checks/local-audits.tsindex 243c3929e0..b34ea8d117 100644--- a/src/commands/doctor/checks/local-audits.ts+++ b/src/commands/doctor/checks/local-audits.ts@@ -26,6 +26,7 @@ import {computeConversationParserProbeHealthCheck,} from './search-eval.ts';import type { Check } from '../../doctor.ts';+import { withSkippedSegmented } from '../check-fix.ts';import type { DoctorContext, DoctorEntry } from '../context.ts';async function runStubGuard(ctx: DoctorContext): Promise<Check[]> {@@ -208,11 +209,12 @@ async function runExtractionBacklogs(ctx: DoctorContext): Promise<Check[]> {applyExtractAtomsNoPricing(check, await readExtractAtomsNoPricing(engine).catch(() => []));// #5151: unmanaged brains reconcile fences in the cycle, so fence pages// behind their facts watermark are facts not indexed yet.+ let skippedSegmented = 0;if (!await managedPersistenceEnabled(engine).catch(() => true)) {const backlog = await readFactsReconcileBacklog(engine).catch(() => null);- if (backlog) applyFactsReconcileBacklog(check, backlog);+ if (backlog) { applyFactsReconcileBacklog(check, backlog); skippedSegmented = backlog.skipped_segmented ?? 0; }}- checks.push(check);+ checks.push(withSkippedSegmented(check, skippedSegmented));} catch {// Best-effort; rollup-table missing on pre-v106 brains is normal// and is already handled inside computeExtractHealthCheck.diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.tsindex f2c76e28d4..05d4b81ace 100644--- a/src/core/behavior-change-notice.ts+++ b/src/core/behavior-change-notice.ts@@ -732,6 +732,7 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText }{ since: 'TBD', text: 'Reads of a page stored in segments that follow an authorization (MCP `get_page` windows, outlines, sizes and its whole-body refusal, `fetch`, evidence windows and the `entity` card excerpt) now read the revision they authorized: a page edited, made private or dropped below the caller\'s `min_trust` mid-read refuses with `revision_changed` (or `page_not_found`) instead of returning the newer body, and evidence falls back to the hit chunk. A segmented page whose segment rows the reader cannot see, or that has a gap or a missing tail, refuses with the new `page_body_rows_unreadable` in every reader that produces its body (MCP reads, export, backup and restore file writes, body digests, fence rewrites) instead of reading as empty or short; an export with such a page fails. `purge_fact` now aborts a write in flight that staged a text holding the purged claim (its publish refuses `body_staging_expired`), segment maintenance keeps every text a live write staged, a page purge of an inline page no longer reports other pages\' segments as incomplete, and MCP `get_versions` reports a segmented version\'s readable size as `total_bytes` instead of its stored `body_bytes`.' },{ since: 'TBD', text: '`gbrain extract --stale`, the cycle\'s stale-extraction drain and the managed stale-links pass now extract a page stored in segments whose links or timeline are stale, reading its body block by block, and stamp it. Before, doctor `links_extraction_lag` and the sync report counted such a page as needing extraction while no extractor picked it up, so the count never reached 0.' },{ since: 'TBD', text: 'A large page held for embedding approval or stopped by `embed.max_usd_per_page` that is edited down to 1 MiB or under (inline, or still stored in segments) now embeds through the stale sweep and `gbrain embed --stale` like any page of its size, and no longer appears as held or capped in `gbrain embed --held`, doctor `partial_embedding` or write and sync receipts. Its budget row is kept: if the page grows past 1 MiB again, the hold or cap it had applies again.' },+ { since: 'TBD', text: 'Doctor checks that read whole page bodies now report the pages stored in segments they did not check, instead of passing them by silently: `oversized_pages`, `scraper_junk_pages`, `markdown_body_completeness`, `link_resolution_opportunity`, `fence_integrity`, `core_memory` and `extract_health` (its facts-backlog overlay) carry `skipped_segmented: N` in `gbrain doctor --json` and end their message with `skipped (segmented): N`. `gbrain repair frontmatter` reports the same count in its preview and apply (residual `skipped_segmented` and a warning). Nothing is added for a brain with no page stored in segments, so its doctor and repair output is unchanged.' },];/** The newest disclosed change's release: the notice id moves only when a release adds rows. */diff --git a/src/core/facts/reconcile-watermark.ts b/src/core/facts/reconcile-watermark.tsindex 483fcc034a..32b256ee55 100644--- a/src/core/facts/reconcile-watermark.ts+++ b/src/core/facts/reconcile-watermark.ts@@ -126,6 +126,8 @@ export interface FactsReconcileBacklog {pending: number;/** Pages whose current revision holds a malformed or misplaced fence. */invalid: Array<{ source_id: string; slug: string }>;+ /** Wave B decision #10: due pages stored in segments with no fence rows; the body match cannot read them, so whether they hold a fence is unknown. */+ skipped_segmented?: number;}/**@@ -146,9 +148,14 @@ export async function readFactsReconcileBacklog(engine: BrainEngine): Promise<FaORDER BY d.source_id, d.slug`,[`%${FACTS_FENCE_BEGIN}%`],);+ const [segmented] = await engine.executeRaw<{ n: number }>(+ `SELECT COUNT(*)::int AS n FROM pages p LEFT JOIN page_facts_reconcile r ON r.page_id = p.id+ WHERE p.deleted_at IS NULL AND ${DUE} AND p.body_storage = 'segmented' AND NOT ${OWNS_FENCE_ROWS}`,+ ).catch(() => []);return {pending: rows.filter(r => !r.invalid).length,invalid: rows.filter(r => r.invalid).map(r => ({ source_id: r.source_id, slug: r.slug })),+ ...(segmented?.n ? { skipped_segmented: Number(segmented.n) } : {}),};}diff --git a/src/core/repair/frontmatter.ts b/src/core/repair/frontmatter.tsindex fbddf4e110..14a0b50413 100644--- a/src/core/repair/frontmatter.ts+++ b/src/core/repair/frontmatter.ts@@ -228,6 +228,21 @@ async function pagesByOrigin(engine: BrainEngine, sourceId: string): Promise<Mapreturn new Map(rows.map(row => [row.source_path, { ...row, id: Number(row.id) }]));}+/**+ * Wave B decision #10: a page stored in segments has no stored head (its body+ * columns are NULL), so the database-side embedded-block check does not read+ * it. The preview and the apply report how many (`skipped_segmented`).+ */+async function reportSkippedSegmented(engine: BrainEngine, sourceIds: string[], residuals: Record<string, number>, warnings: string[]): Promise<void> {+ const [row] = await engine.executeRaw<{ n: number }>(`SELECT COUNT(*)::int AS n FROM pages+ WHERE source_id=ANY($1::text[]) AND deleted_at IS NULL AND source_path IS NOT NULL AND body_storage='segmented'`, [sourceIds]);+ const n = Number(row?.n ?? 0);+ if (!n) return;+ residuals.skipped_segmented = n;+ warnings.push(`skipped (segmented): ${n} page(s) store their body in segments, so the database-side check for a stored body that begins with its own frontmatter block `+ + 'did not read them; their files were checked.');+}+/** #4526: a body that begins with its own frontmatter block. */const EMBEDDED_BLOCK = /^\s*---[ \t]*\r?\n(?:[\s\S]*?\r?\n)?[A-Za-z_][\w-]*:[\s\S]*?\r?\n---[ \t]*(?:\r?\n|$)/;@@ -434,11 +449,15 @@ export const frontmatterRepair: RepairHandler = {why: `Finishes source ${sourceId}'s unfinished sync cursor, which would otherwise race the repair of a file it still names.` } });}const items = approved.items.map(({ selection: chosen, ...repair }, index) => item(repair, chosen, opts.expect!, index, index === approved.items.length - 1));- return { items: items.filter(entry => afterCursor(entry.cursor, after)), preview_hash: opts.expect, residuals: {} };+ const residuals: Record<string, number> = {};+ const warnings: string[] = [];+ await reportSkippedSegmented(engine, scope.source_ids, residuals, warnings);+ return { items: items.filter(entry => afterCursor(entry.cursor, after)), preview_hash: opts.expect, residuals, ...(warnings.length ? { warnings } : {}) };}const residuals: Record<string, number> = {};const warnings: string[] = [];const found = await scan(engine, scope, selection, residuals, warnings);+ await reportSkippedSegmented(engine, scope.source_ids, residuals, warnings);for (const path of found.unknownOnly) warnings.push(`--only ${path}: no such Markdown file or hold in scope; check the source-relative path.`);const sources = await engine.executeRaw<{ id: string; incarnation: string }>('SELECT id, incarnation::text AS incarnation FROM sources WHERE id=ANY($1::text[]) ORDER BY id', [scope.source_ids]);const approvedItems = found.prepared.map(entry => entry.approved);diff --git a/test/large-pages/doctor-skipped-segmented.test.ts b/test/large-pages/doctor-skipped-segmented.test.tsnew file mode 100644index 0000000000..26e1e6e01b--- /dev/null+++ b/test/large-pages/doctor-skipped-segmented.test.ts@@ -0,0 +1,171 @@+/**+ * Wave B PR 2 decision #10: doctor reports what it skipped.+ *+ * 1. Protects: every doctor check whose scan reads whole page bodies (their+ * SQL compares compiled_truth / timeline, which are NULL on a page stored+ * in segments) reports the segmented pages it passed by:+ * 'skipped_segmented: N' on the check object (doctor --json) and a message+ * ending in 'skipped (segmented): N' (the text line is 'name: message').+ * 'gbrain repair frontmatter' reports the same count in its preview and+ * apply (residual 'skipped_segmented', warning 'skipped (segmented): N').+ * A brain without segmented pages gets neither, so its output is unchanged.+ * 2. Fails when: a check drops the count (its segmented page is silently+ * passed by and the brain looks healthier than it was checked to be), or+ * reports a field on a brain that has no segmented page.+ * 3. Why existing coverage misses it: the doctor goldens and check tests run+ * on brains with inline pages only.+ * Seams: none. Counting is one COUNT query per check (no per-page loop).+ */+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { PGLiteEngine } from '../../src/core/pglite-engine.ts';+import type { BrainEngine } from '../../src/core/engine.ts';+import { importFromContent, importFromFile } from '../../src/core/import-file.ts';+import { createProgress } from '../../src/core/progress.ts';+import { disposePersistenceConsumer } from '../../src/core/persistence/service.ts';+import { resolveRepairScope } from '../../src/core/repair/core.ts';+import { repairRunner } from '../../src/core/repair/registry.ts';+import { renderRepairResult } from '../../src/commands/repair.ts';+import { computeDoctorReport, type Check } from '../../src/commands/doctor.ts';+import type { DoctorContext } from '../../src/commands/doctor/context.ts';+import { contentSanityEntry } from '../../src/commands/doctor/checks/content-quality.ts';+import { markdownBodyEntry } from '../../src/commands/doctor/checks/data-integrity.ts';+import { checkLinkResolutionOpportunity } from '../../src/commands/doctor/checks/calibration.ts';+import { fenceIntegrityCheck } from '../../src/commands/doctor/checks/fence-integrity.ts';+import { coreMemoryCheck } from '../../src/commands/doctor/checks/core-memory.ts';+import { extractionBacklogsEntry } from '../../src/commands/doctor/checks/local-audits.ts';+import { conversationBody } from '../helpers/conversation-page.ts';+import { isolatedPersistencePostgres } from '../helpers/persistence-postgres.ts';+import { withEnv } from '../helpers/with-env.ts';++const home = mkdtempSync(join(tmpdir(), 'gbrain-doctor-skipped-segmented-'));+const logger = { info() {}, warn() {}, error() {} };+const env = { GBRAIN_HOME: home, GBRAIN_SYNC_FAILURES_DIR: home, OPENAI_API_KEY: undefined, VOYAGE_API_KEY: undefined, ANTHROPIC_API_KEY: undefined };+/** The checks whose scans read whole bodies. */+const AFFECTED = ['core_memory', 'extract_health', 'fence_integrity', 'link_resolution_opportunity', 'markdown_body_completeness', 'oversized_pages', 'scraper_junk_pages'];++interface Brain { kind: string; mixed: BrainEngine; inline: BrainEngine }+const brains: Brain[] = [];+const closers: Array<() => Promise<void>> = [];++const page = (title: string, body: string) => `---\ntype: note\ntitle: ${title}\nalways_load: true\n---\n\n${body}\n\n## Notes\n\nSee [[missing-target]] for more.\n`;+const bigBody = () => conversationBody(1_200_000, { seed: 7 });++async function storage(engine: BrainEngine, sourceId: string, slug: string): Promise<string> {+ const [row] = await engine.executeRaw<{ body_storage: string }>('SELECT body_storage FROM pages WHERE source_id=$1 AND slug=$2', [sourceId, slug]);+ return row!.body_storage;+}++/** One page (segmented with the switch on when 'big') plus a raw_data sidecar with headings, so every affected check reaches it. */+async function seed(engine: BrainEngine, sourceId: string, slug: string, big: boolean): Promise<void> {+ expect(await importFromContent(engine, slug, page(slug, big ? bigBody() : 'A short page.'), { sourceId, noEmbed: true })).toMatchObject({ status: 'imported' });+ expect(await storage(engine, sourceId, slug)).toBe(big ? 'segmented' : 'inline');+ const [row] = await engine.executeRaw<{ id: number }>('SELECT id FROM pages WHERE source_id=$1 AND slug=$2', [sourceId, slug]);+ await engine.executeRaw(`INSERT INTO raw_data(page_id, source, data) VALUES($1, 'fixture', $2::text::jsonb)`,+ [row!.id, JSON.stringify({ content: `## One\n\n${'Original text. '.repeat(100)}\n\n## Two\n\nMore.` })]);+}++beforeAll(async () => {+ await withEnv(env, async () => {+ const all: Array<{ kind: string; engine: BrainEngine }> = [];+ for (let i = 0; i < 2; i++) {+ const lite = new PGLiteEngine(); await lite.connect({}); await lite.initSchema(); all.push({ kind: 'pglite', engine: lite });+ closers.push(async () => { await disposePersistenceConsumer(lite); await lite.disconnect(); });+ }+ for (let i = 0; process.env.DATABASE_URL && i < 2; i++) {+ const pg = await isolatedPersistencePostgres(process.env.DATABASE_URL);+ all.push({ kind: 'postgres', engine: pg.engine });+ closers.push(async () => { await disposePersistenceConsumer(pg.engine); await pg.close(); });+ }+ for (const { engine } of all) {+ await engine.setConfig('pages.segmented_storage', 'on');+ await engine.executeRaw("INSERT INTO sources(id,name,config) VALUES('seg-doctor','seg-doctor','{}') ON CONFLICT DO NOTHING");+ }+ for (let i = 0; i < all.length; i += 2) {+ const mixed = all[i]!.engine, inline = all[i + 1]!.engine;+ await seed(mixed, 'seg-doctor', 'notes/segmented', true);+ await seed(mixed, 'seg-doctor', 'notes/inline', false);+ await seed(inline, 'seg-doctor', 'notes/inline', false);+ await seed(inline, 'seg-doctor', 'notes/other-inline', false);+ // The facts backlog overlay on extract_health is read on unmanaged brains.+ for (const engine of [mixed, inline]) await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');+ brains.push({ kind: all[i]!.kind, mixed, inline });+ }+ });+}, 600_000);++afterAll(async () => {+ await withEnv(env, async () => { for (const close of closers) await close(); });+ rmSync(home, { recursive: true, force: true });+});++function ctx(engine: BrainEngine): DoctorContext {+ return { engine, args: [], jsonOutput: true, fastMode: false, doFix: false, dryRun: false, scope: 'brain', orphanRatioSourceId: undefined,+ progress: createProgress({ mode: 'quiet' }), skillsDirResolution: { dir: null, source: 'none' }, skillsDir: null, autoFixReport: null,+ schemaVersion: 0, connectionFailed: false, tier: 'standard' };+}++/** The affected checks, through the doctor's own JSON report (computeDoctorReport, then JSON). */+async function affectedChecks(engine: BrainEngine): Promise<Check[]> {+ const run = async (entry: { run(c: DoctorContext): Promise<unknown> }) => (await entry.run(ctx(engine))) as Check[];+ const checks: Check[] = [+ ...await run(contentSanityEntry),+ ...await run(markdownBodyEntry),+ await checkLinkResolutionOpportunity(engine),+ await fenceIntegrityCheck(engine),+ { name: 'core_memory', ...await coreMemoryCheck(engine) },+ ...(await run(extractionBacklogsEntry)).filter(c => c.name === 'extract_health'),+ ];+ const report = JSON.parse(JSON.stringify(computeDoctorReport(checks))) as { checks: Check[] };+ return report.checks.filter(c => AFFECTED.includes(c.name)).sort((a, b) => a.name.localeCompare(b.name));+}++describe('doctor reports the segmented pages its whole-body checks skipped', () => {+ test('one segmented page and one inline page: every affected check reports skipped_segmented: 1 in JSON and text', async () => withEnv(env, async () => {+ for (const brain of brains) {+ const checks = await affectedChecks(brain.mixed);+ expect(checks.map(c => [brain.kind, c.name, c.skipped_segmented])).toEqual(AFFECTED.map(name => [brain.kind, name, 1]));+ for (const check of checks) expect(check.message).toContain('skipped (segmented): 1 page(s) store their body in segments');+ }+ }), 600_000);++ test('a brain without segmented pages: no affected check carries the field or the text', async () => withEnv(env, async () => {+ for (const brain of brains) {+ const checks = await affectedChecks(brain.inline);+ expect(checks.map(c => [brain.kind, c.name, 'skipped_segmented' in c, c.message.includes('skipped (segmented)')]))+ .toEqual(AFFECTED.map(name => [brain.kind, name, false, false]));+ }+ }), 600_000);++ test('repair frontmatter: preview and apply report the segmented page the database-side check skipped', async () => withEnv(env, async () => {+ for (const brain of brains) {+ for (const [engine, segmented] of [[brain.mixed, 1], [brain.inline, 0]] as const) {+ const id = `fm-seg-${brain.kind}-${segmented}`, root = join(home, id);+ mkdirSync(join(root, 'notes'), { recursive: true });+ const files: Record<string, string> = {+ 'notes/big.md': `---\ntitle: Big notes\n---\n\n${segmented ? bigBody() : 'Small.'}\n`,+ 'notes/small.md': '---\ntitle: Small notes\n---\n\nA short page.\n',+ 'notes/roundup.md': '---\ntitle: Payments roundup\nauthor: alice-example (citing acme-example) (original: https://example.invalid/a)\n---\nA synthetic roundup.\n',+ };+ for (const [path, content] of Object.entries(files)) writeFileSync(join(root, path), content);+ await engine.executeRaw("INSERT INTO sources(id,name,local_path,config) VALUES($1,$1,$2,'{}')", [id, root]);+ for (const path of ['notes/big.md', 'notes/small.md']) await importFromFile(engine, join(root, path), path, { sourceId: id, noEmbed: true });+ expect(await storage(engine, id, 'notes/big')).toBe(segmented ? 'segmented' : 'inline');+ const scope = await resolveRepairScope(engine, id);+ const preview = await (await repairRunner(engine, { apply: false, noEmbed: true, logger })).run('frontmatter', scope, { explicit: true, sourceFlag: id });+ expect(preview.affected).toBe(1);+ const hash = preview.apply_command.split('--expect ')[1]!.split(' ')[0]!;+ const applied = await (await repairRunner(engine, { apply: true, noEmbed: true, logger })).run('frontmatter', scope, { explicit: true, sourceFlag: id, expect: hash });+ expect(applied.applied).toBe(1);+ for (const result of [preview, applied]) {+ const text = renderRepairResult(result);+ const seen: unknown[] = [brain.kind, result.mode, result.residuals.skipped_segmented, text.includes('skipped_segmented=1'),+ text.includes('WARNING: skipped (segmented): 1 page(s) store their body in segments')];+ expect(seen).toEqual(segmented ? [brain.kind, result.mode, 1, true, true] : [brain.kind, result.mode, undefined, false, false]);+ }+ }+ }+ }), 600_000);+});diff --git a/test/postgres-unit-arms.txt b/test/postgres-unit-arms.txtindex 4fbc0e19c1..e32483b371 100644--- a/test/postgres-unit-arms.txt+++ b/test/postgres-unit-arms.txt@@ -69,6 +69,7 @@ test/large-pages/chunk-retirement-plan.test.tstest/large-pages/chunk-visibility.test.tstest/large-pages/contextual-reembed-segmented.test.tstest/large-pages/credential-reseal-segments.test.ts+test/large-pages/doctor-skipped-segmented.test.tstest/large-pages/forget-reason-segmented.test.tstest/large-pages/forget-scope.test.tstest/large-pages/held-budget-shrink.test.ts