Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
Merge origin/capy/gbra93-a (PR A #6709 @5a08ef43) into capy/gbra93-bc
garrytanbe50cde68125
diff --cc CHANGELOG.mdindex 9e3e35773d,c59baf0799..026102e132--- a/CHANGELOG.md+++ b/CHANGELOG.md@@@ -12,57 -12,17 +12,69 @@@ identifiers and attribution are availab## [Unreleased]+**Sync, reconcile and repair loops that used to go round forever now end, or tell you exactly what ends them (#6696).** A sync handed to a running `gbrain serve` refused to resume an unfinished run unless you retyped its options, and flags a managed source can't honor failed late with an unrelated error. A run that had finished could still report itself blocked. A wedged migration printed "WEDGED" and then "All migrations up to date". Writes to a page whose file is gone were told to retry a sync that can never import that file. Hundreds of derived pages that disagreed with their files could only be reconciled one at a time. Each of these now finishes, or names the one command that finishes it. And `gbrain doctor --tier ops` now shows what is wrong in seconds on a brain of any size, with anything it could not finish reported as unknown instead of clear.++### How to use it++- Reconcile a whole folder of drifted pages in one preview: `gbrain repair file-drift --source <id> --all-drifted --only 'concepts/**' --prefer database`, then run the apply command it prints.+- Let the brain's own serve keep derived folders on the database copy: add `keep_db:` under `storage:` in the source's `gbrain.yml` (for example `keep_db: [concepts/]`). It is off until you add it.+- See whether serve runs an older build than your checkout: `gbrain doctor --only serve_build_drift --json`.+- Clear a wedged migration after fixing its cause: `gbrain apply-migrations --force-retry <version>`, then `gbrain apply-migrations --yes`.- - See what is wrong in seconds: `gbrain doctor --tier ops --json` (capacity, write failures, sync movement, receipt compaction, serve build, schema pack) under a 4 s deadline; `--budget-ms <n>` changes it, `--tier deep` runs the full scans.++- See what is wrong in seconds: `gbrain doctor --tier ops --json` (capacity and forecast, write failures, sync movement, receipt compaction, serve build, schema pack, embedding state) under a 4 s deadline; `--budget-ms <n>` changes it, `--tier deep` runs the full scans.+- List what search cannot fully see: `gbrain pages unsearchable --source <id> --json`.+- Find and remove pages whose file is gone: `gbrain pages ghosts --source <id>`, then preview `gbrain repair ghost-pages --source <id>` and run the printed apply after the user agrees.+- From an agent without admin scope: MCP `get_brain_health` returns the same health as bands; `gbrain doctor --tier ops` from a thin client uses it when the token is not admin.++### What you'd see++| Situation | Before | Now |+|---|---|---|+| `gbrain sync` delegated to serve, unfinished run stored `--no-embed` | refused `invalid_params` ("different or unknown processing options") | resumes with the stored options |+| `--skip-failed` on a managed source | `writer_coordinator_required` after the run started | `managed_sync_flag_refused`, naming the flag, before anything runs |+| a run whose checkpoint committed, then a long link tail | `blocked` / `no_admission`, "move to port 5432" | `synced` |+| a migration that ended partial 3+ times, nothing newer ran | "All migrations up to date", exit 0 | `migrations_pending` reason `wedged`, exit 1, fix asks the user |+| `remember` on a page with an extracted fact row past the fence | `storage_error` | commits at the next free row number |+| `gbrain doctor` on a large brain | every check ran to completion, minutes with no output | ops sections first; a check past `doctor.entry_budget_ms` (15 s) reports unknown (`reason: budget`) instead of holding the run |+| `orphan_ratio` above 50,000 pages | a full scan | a sampled estimate marked `estimated`; `--tier deep` scans fully |+| thin client `gbrain doctor --only persistence_capacity` with a read token | the thin-client connectivity checks, `--only` ignored | the `get_brain_health` capacity band, or `doctor_tier_unavailable` from an older serve |++### Itemized changes++- **Delegated sync options** (`src/commands/sync-delegate.ts`, `src/core/serve-sync-runner.ts`, `src/core/persistence/sync-administration.ts`, `src/core/persistence/sync-authority.ts`): both delegation builders send the list of processing flags you typed exactly as computed, so a flagless delegated resume adopts the unfinished run's stored options. A payload from an older CLI that omits the list counts only its true-valued `noEmbed` / `noExtract` / `noSchemaPack` as typed, so its `--no-embed` is honored; a supplied list is kept as sent, including on the resident-owner lane.+- **Embedding deferral holds** (`src/commands/sync/run.ts`, `src/core/persistence/sync-prepare.ts`): the cost gate's automatic embedding deferral is a runtime constraint of the run, never a stored option a resume adopts, so resuming a run that stored embedding on no longer embeds over it.+- **One cursor per source** (`src/core/persistence/sync-cursor-key.ts`): a source with a configured strategy keys its sync cursor the same way for `sync --all`, single-source sync, the cycle and delegated runs. An unfinished cursor under the older key finishes under it first.+- **Managed-forbidden flags** (`src/core/persistence/managed-sync-flags.ts`): `--skip-failed` and `--include-gitignored` on a managed source refuse with the new `managed_sync_flag_refused` at parse, before the serve socket and in jobs, MCP and the cycle; the fix is the same command without the flag.+- **Retry text for older failures** (`src/core/persistence/managed-retry-actions.ts`): `gbrain sync --retry-failed` names each failure held under another run's options as resumable (a replay of an unfinished run, or a fresh discovery), safely orphaned (the orphan repair retires it) or unresolved, each with the command that settles it, instead of "with the same options as the failed run (this receipt no longer records them)".+- **Finished runs end `synced`** (`src/core/persistence/sync-drain.ts`, `drain-step.ts`, `sync-run.ts`): after the checkpoint commits the run stamps drain step `finish` and emits `managed_sync.finish`; link extraction in the tail stops after 5 minutes (the rest stays for `gbrain extract --stale`), and a tail stuck past its own window stops `no_progress` at step `finish`. A run stuck in admission still stops `no_admission`.+- **Wedged migrations** (`src/commands/apply-migrations.ts`, `src/core/migration-ledger.ts`, `src/commands/upgrade.ts`): a migration with 3+ consecutive partial runs that no newer migration ran past fails `migrations_pending` with reason `wedged` (exit 1, `fix.next: ask_user`, `fix.argv: gbrain apply-migrations --force-retry <v>`, verify `--list --json`). `--list` names it with its clearing command, `--list --json` adds `wedged`, `post-upgrade` exits non-zero and `gbrain upgrade` prints `Migrations: wedged`. A wedge a newer migration already ran past is history, as doctor already treats it, and prints a nothing-to-do note.+- **Serve build drift** (`src/commands/doctor/checks/persistence-consumers.ts`): new doctor check `serve_build_drift` warns when a live serve or worker on this host runs an older build than this checkout, with the service restart command (`systemctl --user restart gbrain-serve.service` or `launchctl kickstart -k gui/<uid>/com.gbrain.serve`, else the pid) and a verify. It is ok on PGLite and on a fresh brain.+- **Bulk file drift** (`src/core/repair/file-drift.ts`, `src/core/repair/path-glob.ts`): `gbrain repair file-drift` takes repeatable `--only` / `--skip` over canonical file paths. A value without `*` is an exact path; on file-drift a value with `*` is a glob (`*` within a segment, `**` across). They narrow the selection before the mixed-class check, the bound and the preview, are bound into the preview hash and appear in the printed apply command. `--keep` on file-drift refuses and points at `--prefer database`.+- **`keep_db` policy** (`src/core/storage-config.ts`, `src/core/repair/keep-db-policy.ts`): an opt-in `storage.keep_db` prefix list. On the source's owner host, the resident serve, jobs or autopilot consumer reconciles drifted pages under those prefixes with the database copy, at most 10 requests every 10 minutes, below the write-quota stop line and never twice for one drift. Doctor `maintenance_write_drift` shows the policy, the pages it matches and their receipt cost. Unknown `storage:` keys now warn.+- **Slug-conflict repair agrees with sync** (`src/core/repair/slug-conflicts.ts`, `src/core/persistence/sync-screen.ts`, `src/core/persistence/file-repair.ts`): `gbrain repair content` judges a held `frontmatter_slug_conflict` file with the screen managed sync froze it with. A file sync would accept as it is imports unchanged and its hold clears, bound to the hold it read (a newer hold stays, with a retry); a source in a Git subfolder loses its stray `slug:` line; a file sync would hold whatever the repair writes is `slug_page_mismatch`, naming both slugs and the edit.+- **`remember` row numbers** (`src/core/persistence/memory-prepare.ts`): a remembered fact is numbered past both the page's fence rows and the facts rows recorded for the page, and a collision names the fact holding the row.+- **Terminal receipts** (`src/core/persistence/terminal-classify.ts`): a write refused because its page's file is missing is category `canonical_file_missing`, whose fix previews `gbrain repair ghost-pages --source <id>`. A `fence_unrenderable` adoption refusal is its own category, historical when written by a build older than 0.60.218.0. `docs/guides/write-refusals.md` tells SQL readers that `error_message` is the short form and that `gbrain sources writer failures` carries the exit.+- **Doctor tiers and budgets** (`src/commands/doctor/budget.ts`, `registry.ts`, `context.ts`, `src/cli/commands/doctor.ts`): `--tier ops|standard|deep` and `--budget-ms`. The ops sections run first in every tier; `--tier ops` runs only them under one deadline (default 4000 ms) that also bounds each Postgres statement (`executeRaw` `deadlineAt`, re-read after the pool wait). Other tiers bound each check by `doctor.entry_budget_ms` (default 15000). A check that did not finish is a warn with `details.health: "unknown"`, `reason: "budget"` and a rerun-alone fix; the report adds `tier`, `complete`, `unknown_sections`, `elapsed_ms` and `budget_ms` when a tier or budget is given, and every check carries `elapsed_ms`. On PGLite, ops sections that need a Postgres serve read `not_applicable` (info) and the report stays complete. `getHealth` runs once per doctor run.- - **Receipt compaction freshness** (`src/commands/doctor/checks/ops-sections.ts`): new ops check `receipt_compaction` warns when the last compaction (`persistence.maintenance.last_compaction`) is older than 24 hours while a persistence consumer is live. The local doctor now also runs `schema_pack_consistency` as an ops section; before, only the remote `run_doctor` report did.++- **Ops sections from the persistence checks** (`src/commands/doctor/checks/ops-sections.ts`): `persistence_capacity` (with its forecast) and `persistence_compaction` run as ops sections. The local doctor now also runs `schema_pack_consistency` as an ops section; before, only the remote `run_doctor` report did.+- **Sampled orphan ratio** (`src/commands/doctor/checks/orphan-estimate.ts`, `graph-health.ts`): above `doctor.orphan_ratio.full_scan_max_pages` (default 50000) `orphan_ratio` estimates from a `TABLESAMPLE` of about 2,000 pages and says so (`estimated: true`, `exact: false`); `--tier deep` scans fully.+- **Health for agents without admin** (`src/commands/doctor/brain-health-bands.ts`, `src/core/ops/admin.ts`): new read-scope MCP op `get_brain_health` returns capacity as `ok|low|critical` with a days band and write failures, unsearchable chunks and ghost pages as count bands for the caller's readable sources, with no slugs or exact counters, cached 60 s. It is the MCP verify of the capacity and `maintenance_backpressure` fixes (`src/core/persistence/capacity-view.ts`).+- **Ops tier over MCP and the thin client** (`src/commands/doctor/remote-tier.ts`, `src/core/doctor-remote-tier.ts`): `run_doctor` takes `tier: "ops"` and `only`. A thin client's `gbrain doctor --tier ops` or `--only <check>` uses them when the serve lists them, falls back to `get_brain_health` bands for a read token, and otherwise refuses with the new `doctor_tier_unavailable` (run doctor on the brain host); it never runs the full remote report instead. `/admin/api/ops` serves one ops run a minute (`ops-snapshot.ts`).+- **Embedding state** (`src/core/embedding-state.ts`, `src/core/engine-sql/chunks.ts`, `src/commands/doctor/checks/embedding-state.ts`): new doctor check `embedding_state` (ops section) counts where indexed text stands against the active embedding column: embedded, pending, keyword-only, quarantined, empty, chunks on deleted pages and chunkless pages. It warns only on chunks of pages soft-deleted more than 72 hours ago and, on a keyed brain, on chunkless pages with body text; on the ops tier it counts only index-backed states and reports `unknown` without a covering index instead of scanning. `get_brain_health` adds the unsearchable count as a band.+- **`gbrain pages unsearchable`** (`src/commands/pages-unsearchable.ts`): `--source <id> [--state] [--limit] [--json]` lists what search cannot fully see, one row per page and state with its fix; read-only.+- **Ghost pages** (`src/core/ghost-pages.ts`, `src/commands/doctor/checks/ghost-pages.ts`, `src/commands/pages-ghosts.ts`): one classifier for a live page whose canonical file is gone on the owner host (a stat pre-filter, then `liveFileDrift` reason `canonical_file_missing`). Doctor `ghost_pages` counts them with samples and a fix (ok off the owner host or with no bound source; unknown on unreadable storage); `gbrain pages ghosts --source <id> [--json]` lists them read-only; `get_brain_health` adds them as a band. A write refused for a removed canonical file now carries `detail: canonical_file_missing` (`page-prepare.ts`, `drift-conflicts.ts`).+- **`gbrain repair ghost-pages`** (`src/core/repair/ghost-pages.ts`): `--source <id>` previews the ghosts and prints the apply command; `--apply --expect <hash> --yes` soft-deletes exactly the previewed set through `delete_page` with the canonical file's absence rechecked in preparation and at publication (a file restored meanwhile is kept and reported `file_restored`). It refuses off the owner host (`not_owner_host`), on unreadable storage (`ghost_storage_unknown`) and past the mass-delete valve (`ghost_mass_delete_refused`), keeps declared `db_only` pages, and without consent exits 3 with nothing changed. `gbrain restore <slug> --force` undoes a removal within the 72-hour purge window.++ **Writes stop failing at the cumulative quota wall (#6696).** A brain running autopilot hit `queue_capacity` on every write once its receipt bytes reached the 1.5 GiB principal cap, because every receipt held a 16 KiB reservation it never gave back and nothing warned before the wall. Receipts are now charged for what they keep, the defaults cover a year at 5,000 writes a day, background work pauses before the wall so your own writes keep working, and doctor, notices and `/metrics` say how many days are left.++ ### Itemized changes++ - **Receipt true-up**: an admission reserves its request body plus 12 KiB (at least 16 KiB), so a 100 KB page reserves its 100 KB; once the last effect settles, `trueUpRequests` gives back what the receipt does not keep (in its own transaction after every settle path: the effect runner, embedding settle, the `embed --stale` bulk settle, effect retry and restore). Receipts compacted earlier give their excess back in one bounded pass.+ - **Defaults and forecast**: principal caps 2,000,000 request ids and 16 GiB receipt bytes (brain 8,000,000 and 64 GiB), from the growth model in `docs/guides/concurrent-writes.md#growth-model`. `persistence_capacity` forecasts days to exhaustion from the full 7-day aggregate on the principal index; warn at 80% or 30 days, fail at 95% or 7 days (`persistence.capacity.warn_days`, `fail_days`).+ - **Clear refusals**: a cumulative cap refuses `write_quota_exhausted` (reason `lifetime_ids` or `terminal_bytes`) with the host's `gbrain config set` raise; `queue_capacity` is only the outstanding-request cap. Background producers pause at `persistence.capacity.background_pause_pct` (80) with `write_capacity_backpressure`.+ - **Warnings**: `[gbrain notice write_capacity_low]` on write and sync receipts (hourly per scope, muteable), sync status and cycle output; `write_capacity_backpressure` notice when the pause starts; admin `/metrics` gauges `gbrain_write_capacity_{used,limit,days_to_exhaustion}` with a documented alert rule.+ - **Sync**: a capacity preflight refuses `write_quota_insufficient` before the first admission; a later cap refusal ends the drain `resumable` / `capacity_paused`.+ - **Compaction**: `gbrain repair receipt-compaction` (explicit-only, preview-bound) compacts on demand, floored at the configured retention unless `--force`; compaction skips open sync runs and the newest sync receipt per worktree; the consumer records each pass (`persistence.maintenance.last_compaction`); doctor adds `persistence_compaction` and `persistence_counter_drift`.+ - **Known-failing writes**: maintenance refuses a page whose canonical file is gone before admission (`canonical_file_missing`) and holds back a write refused three times in a day (`persistence.maintenance.refusal_breaker_threshold`); doctor `maintenance_write_drift` lists them.++## [0.60.230.0] - 2026-10-14**The entity-card latency test no longer fails on a busy CI machine while the card itself is fast (test and CI only, no product change).** The test checks that a card's p99 stays under 100 ms. On Ubicloud it failed at 107-125 ms whenever other memory-heavy tests shared its VM, or the hypervisor took CPU time from the guest, while the same calls took 36-41 ms run alone. It now measures the call's own thread CPU time, runs alone on its VM and re-times a call that hypervisor steal crossed. The 100 ms budget and every assertion are unchanged, and a 90 ms slowdown injected into the reference read still fails it.diff --cc docs/architecture/key-files/commands-2-continued.mdindex b5967d98e8,bbd8c861a9..a91d9210ec--- a/docs/architecture/key-files/commands-2-continued.md+++ b/docs/architecture/key-files/commands-2-continued.md@@@ -27,5 -23,3 +27,5 @@@ Current behavior and load-bearing invar- `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).- `src/commands/doctor/checks/image-embedding-coverage.ts` — `image_embedding_coverage` (#6529, brain category, after `image_assets`). Counts live image pages (`page_kind = 'image'`), those with no `embedding_image` chunk, those with a NULL `source_path`, and the `managed_image_sync_unsupported` holds per source, and reads `isMultimodalEnabled()`. Ok when the brain has no image pages, when every image page has an image vector and a `source_path` and nothing is held, or when multimodal embedding is off (the counts are then informational: image search is not expected to work). On a multimodal install it warns with the counts (text coverage counts those pages as embedded while image search does not see them) and names `gbrain embed --stale --images` and `gbrain sync --no-pull --source <id>` for the holds. Read-only; no paid call. Test: `test/doctor-image-embedding-coverage.test.ts`.- `src/commands/doctor/checks/provider-consent.ts` — `provider_consent` (OPS, engine-free filesystem lane right after `embedding_key_source`; not in `doctorReportRemote`): the provider-use decision `gbrain setup` recorded for this install (`localSetupRecords` in `src/core/setup/local-receipts.ts`). A decline (any live receipt; opt-outs win) is `ok` + info `disabled_by_choice`, "skipped by consent", naming the provider key variables present (names only) and carrying `providerConsentFix`: `gbrain setup <harness> --providers` (+ `--name`/`--scope project`), actor `user`, consent `paid`+`egress`, so `next: tell_user_to_run`. Accepted is plain `ok`; no receipt is info `not_applicable`. The same fix rides `embedding_provider`'s `--probe` skip (`checks/embedding-health.ts`), and `probe-consent.ts` authorizes nothing when a decline is recorded. Reads files only; sends nothing. Pinned by `test/doctor-provider-consent.serial.test.ts` (request counter: zero outbound under a decline, controls prove discovery and the probe are seen otherwise).- - `src/commands/doctor/budget.ts` + `checks/ops-sections.ts` + `checks/orphan-estimate.ts` — doctor tiers and budgets (#6696 B1). `parseDoctorTier` (`--tier ops|standard|deep`, a bad value is `invalid_params`), `parseBudgetMs` (`--budget-ms`, default 4000 under ops, none otherwise) and `startDoctorDeadline` build the `DoctorDeadline` the CLI starts before connecting. `runDoctorRegistry` runs the entries tagged `tier: 'ops'` (persistence capacity, terminal failures, managed sync movement, receipt compaction, serve build drift, schema-pack consistency) right after the connection lane; under `--tier ops` it runs only those, reads through `deadlineEngine` (each `executeRaw` gets the absolute `deadlineAt`, so `SET LOCAL statement_timeout` is the time left after the pool wait: `postgres-engine/bounded-statement.ts`), reports an entry marked `opsPglite: 'not_applicable'` as an `ok` info row on PGLite, and stays complete. Every other tier bounds each entry by `doctor.entry_budget_ms` (default 15000). An entry past its budget, an unknown reported after the overall deadline, or a connect the deadline ended becomes `budgetUnknownCheck` (warn, `details.health: 'unknown'`, `reason: 'budget'`, `exact: false`, a rerun-alone fix), never a clear result; every check carries `elapsed_ms`, and the report adds `tier`/`complete`/`unknown_sections`/`elapsed_ms`/`budget_ms` only when `--tier` or `--budget-ms` was given (`doctorRunSummary`). `doctorHealth(ctx)` memoizes `getHealth` for one run. `orphan_ratio` estimates from a `TABLESAMPLE SYSTEM` sample above `doctor.orphan_ratio.full_scan_max_pages` (default 50000) unless `--tier deep`. `receipt_compaction` warns when `persistence.maintenance.last_compaction` is older than 24 h while a consumer heartbeat is live. Tests: `test/doctor-tier-6696.test.ts`, `test/doctor-day-zero.test.ts` (`--tier ops`), `test/e2e/doctor-ops-tier-postgres.test.ts`.- - `src/commands/doctor/brain-health-bands.ts` + `remote-tier.ts` + `ops-snapshot.ts`, `src/core/doctor-remote-tier.ts`, `src/core/persistence/capacity-view.ts` — the ops tier for agents and remote clients (#6696 B2). `readCapacityView` is the one capacity read (counter rows, `capacityDiagnostics`, last compaction, and a `forecast` seam that is null until the forecast lands: null reads as days unknown); `capacityVerify()` is the verify of every capacity fix (`gbrain doctor --only persistence_capacity --json` plus MCP `get_brain_health`). `readBrainHealthBands` backs the read-scope `get_brain_health` op: capacity band and days band, write failures and active blockers as count bands for the caller's readable sources, no slugs or exact counters, cached 60 s per engine and scope. `runRemoteDoctorTier` backs `run_doctor`'s `tier: "ops"` / `only` (admin). `runScopedRemoteDoctor` is the thin client's `gbrain doctor --tier ops` / `--only <registry check>`: it reads `tools/list` and uses `run_doctor` with the parameters, else the bands (`BAND_CHECKS`), else refuses `doctor_tier_unavailable`; it never runs the full remote report in their place. `cachedOpsSnapshot` serves `/admin/api/ops` from one ops run a minute. Tests: `test/doctor-ops-remote-6696.test.ts`.++- `src/commands/doctor/budget.ts` + `checks/ops-sections.ts` + `checks/orphan-estimate.ts` — doctor tiers and budgets (#6696 B1). `parseDoctorTier` (`--tier ops|standard|deep`, a bad value is `invalid_params`), `parseBudgetMs` (`--budget-ms`, default 4000 under ops, none otherwise) and `startDoctorDeadline` build the `DoctorDeadline` the CLI starts before connecting. `runDoctorRegistry` runs the entries tagged `tier: 'ops'` (persistence capacity, terminal failures, managed sync movement, persistence compaction, serve build drift, schema-pack consistency, embedding state) right after the connection lane; under `--tier ops` it runs only those, reads through `deadlineEngine` (each `executeRaw` gets the absolute `deadlineAt`, so `SET LOCAL statement_timeout` is the time left after the pool wait: `postgres-engine/bounded-statement.ts`), reports an entry marked `opsPglite: 'not_applicable'` as an `ok` info row on PGLite, and stays complete. Every other tier bounds each entry by `doctor.entry_budget_ms` (default 15000). An entry past its budget, an unknown reported after the overall deadline, or a connect the deadline ended becomes `budgetUnknownCheck` (warn, `details.health: 'unknown'`, `reason: 'budget'`, `exact: false`, a rerun-alone fix), never a clear result; every check carries `elapsed_ms`, and the report adds `tier`/`complete`/`unknown_sections`/`elapsed_ms`/`budget_ms` only when `--tier` or `--budget-ms` was given (`doctorRunSummary`). `doctorHealth(ctx)` memoizes `getHealth` for one run. `orphan_ratio` estimates from a `TABLESAMPLE SYSTEM` sample above `doctor.orphan_ratio.full_scan_max_pages` (default 50000) unless `--tier deep`. Capacity (`persistence_capacity`, PR A's forecast) and compaction freshness (`persistence_compaction`) run as ops entries in `checks/ops-sections.ts`. Tests: `test/doctor-tier-6696.test.ts`, `test/doctor-day-zero.test.ts` (`--tier ops`), `test/e2e/doctor-ops-tier-postgres.test.ts`.++- `src/commands/doctor/brain-health-bands.ts` + `remote-tier.ts` + `ops-snapshot.ts`, `src/core/doctor-remote-tier.ts`, `src/core/persistence/capacity-view.ts` — the ops tier for agents and remote clients (#6696 B2). `readCapacityView` (for `/admin/api/ops`) reads the counter rows, `capacityDiagnostics`, the light `readCapacityForecast` (null when unreadable: days unknown) and `readLastCompaction`; the bands read `cachedCapacitySnapshot`; `capacityVerify()` is the verify of every capacity fix (`gbrain doctor --only persistence_capacity --json` plus MCP `get_brain_health`). `readBrainHealthBands` backs the read-scope `get_brain_health` op: capacity band and days band, write failures and active blockers as count bands for the caller's readable sources, no slugs or exact counters, cached 60 s per engine and scope. `runRemoteDoctorTier` backs `run_doctor`'s `tier: "ops"` / `only` (admin). `runScopedRemoteDoctor` is the thin client's `gbrain doctor --tier ops` / `--only <registry check>`: it reads `tools/list` and uses `run_doctor` with the parameters, else the bands (`BAND_CHECKS`), else refuses `doctor_tier_unavailable`; it never runs the full remote report in their place. `cachedOpsSnapshot` serves `/admin/api/ops` from one ops run a minute. Tests: `test/doctor-ops-remote-6696.test.ts`.diff --cc docs/guides/error-codes.mdindex 9f94227bb6,2b7b3094e0..01e4186e4e--- a/docs/guides/error-codes.md+++ b/docs/guides/error-codes.md@@@ -3373,6 -3281,26 +3385,26 @@@ More: [docs/guides/google-connect.md#trMore: [docs/guides/write-refusals.md#worktree_dirty](../../docs/guides/write-refusals.md#worktree_dirty)+ ### write_capacity_backpressure++ <a id="write_capacity_backpressure"></a>++ | Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable |+ |---|---|---|---|---|---|---|-| A background producer (maintenance, conversation facts, an autopilot phase or an autopilot catch-up sync) stopped admitting writes because a cumulative write cap is past `persistence.capacity.background_pause_pct` (default 80); interactive writes keep the rest. Nothing was submitted and no receipt was written. | Near a cumulative cap the remaining request ids and receipt bytes are kept for the user's own writes (remember, put_page, edit_page, operator sync, approved repair). Request ids are never freed, so past the line on ids only the brain host's config raise resumes background work; receipt bytes also free as receipts compact. | Only the brain host's operator can resolve this. Tell the user the message and run `gbrain doctor --json` on the brain host. Run: gbrain doctor --only persistence_capacity --json | agent | `gbrain doctor --json` | 12 | no |++| A background producer (maintenance, conversation facts, an autopilot phase or an autopilot catch-up sync) stopped admitting writes because a cumulative write cap is past `persistence.capacity.background_pause_pct` (default 80); interactive writes keep the rest. Nothing was submitted and no receipt was written. | Near a cumulative cap the remaining request ids and receipt bytes are kept for the user's own writes (remember, put_page, edit_page, operator sync, approved repair). Request ids are never freed, so past the line on ids only the brain host's config raise resumes background work; receipt bytes also free as receipts compact. | Only the brain host's operator can resolve this. Tell the user the message and run `gbrain doctor --json` on the brain host. Run: gbrain doctor --only persistence_capacity --json | agent | `gbrain doctor --only persistence_capacity --json` | 12 | no |++ More: [docs/guides/write-refusals.md#write_capacity_backpressure](../../docs/guides/write-refusals.md#write_capacity_backpressure)++ ### write_capacity_low++ <a id="write_capacity_low"></a>++ | Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable |+ |---|---|---|---|---|---|---|-| A cumulative write cap is at or past 80% or runs out within `persistence.capacity.warn_days` (30) days at its 7-day rate; writes still work. | Request ids are permanent and receipt bytes free only as receipts compact, so the cap is raised before admission refuses. | Only the brain host's operator can resolve this. Tell the user the message and run `gbrain doctor --json` on the brain host. Run: gbrain doctor --only persistence_capacity --json | agent | `gbrain doctor --json` | 1 | no |++| A cumulative write cap is at or past 80% or runs out within `persistence.capacity.warn_days` (30) days at its 7-day rate; writes still work. | Request ids are permanent and receipt bytes free only as receipts compact, so the cap is raised before admission refuses. | Only the brain host's operator can resolve this. Tell the user the message and run `gbrain doctor --json` on the brain host. Run: gbrain doctor --only persistence_capacity --json | agent | `gbrain doctor --only persistence_capacity --json` | 1 | no |++ More: [docs/guides/write-refusals.md#write_capacity_low](../../docs/guides/write-refusals.md#write_capacity_low)+### write_claim_lost<a id="write_claim_lost"></a>@@@ -3419,6 -3347,30 +3451,30 @@@ More: [docs/guides/write-refusals.md#wr|---|---|---|---|---|---|---|| The write was accepted and is still pending; it may commit later. | A temporary condition (a lock, a pending write, a rate limit); the same request can succeed later. | Wait briefly, then retry the same request (writes: reuse the same request_id). | agent | `repeat the read that failed` | 10 | yes |+ ### write_quota_exhausted++ <a id="write_quota_exhausted"></a>++ | Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable |+ |---|---|---|---|---|---|---|-| A cumulative write cap (permanent request ids or reserved receipt bytes, for the principal or the brain) is full, so the write was not admitted and nothing changed. | Request ids are permanent replay protection and a receipt keeps its bytes until it compacts, so waiting does not free the cap; the brain host raises it with gbrain config set (reversible). | Only the brain host's operator can resolve this. Tell the user the message and run `gbrain doctor --json` on the brain host. Run: gbrain doctor --only persistence_capacity --json | agent | `gbrain doctor --json` | 12 | no |++| A cumulative write cap (permanent request ids or reserved receipt bytes, for the principal or the brain) is full, so the write was not admitted and nothing changed. | Request ids are permanent replay protection and a receipt keeps its bytes until it compacts, so waiting does not free the cap; the brain host raises it with gbrain config set (reversible). | Only the brain host's operator can resolve this. Tell the user the message and run `gbrain doctor --json` on the brain host. Run: gbrain doctor --only persistence_capacity --json | agent | `gbrain doctor --only persistence_capacity --json` | 12 | no |++ Reasons: `lifetime_ids`, `terminal_bytes`.++ More: [docs/guides/write-refusals.md#write_quota_exhausted](../../docs/guides/write-refusals.md#write_quota_exhausted)++ ### write_quota_insufficient++ <a id="write_quota_insufficient"></a>++ | Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable |+ |---|---|---|---|---|---|---|-| A bulk run (managed sync catch-up, reclone or a repair) estimated more new receipts than the remaining write capacity allows before its producer's pause line, so it did not start; other writes still work. | Starting a run that the cap would stop part way leaves a long tail of pending pages; the preflight refuses up front with the config raise that covers the run. | Only the brain host's operator can resolve this. Tell the user the message and run `gbrain doctor --json` on the brain host. Run: gbrain doctor --only persistence_capacity --json | agent | `gbrain doctor --json` | 12 | no |++| A bulk run (managed sync catch-up, reclone or a repair) estimated more new receipts than the remaining write capacity allows before its producer's pause line, so it did not start; other writes still work. | Starting a run that the cap would stop part way leaves a long tail of pending pages; the preflight refuses up front with the config raise that covers the run. | Only the brain host's operator can resolve this. Tell the user the message and run `gbrain doctor --json` on the brain host. Run: gbrain doctor --only persistence_capacity --json | agent | `gbrain doctor --only persistence_capacity --json` | 12 | no |++ Reasons: `lifetime_ids`, `terminal_bytes`.++ More: [docs/guides/write-refusals.md#write_quota_insufficient](../../docs/guides/write-refusals.md#write_quota_insufficient)+### writer_admin_intent_required<a id="writer_admin_intent_required"></a>diff --cc docs/guides/repair.mdindex 0fb9b4261f,25d05476c7..9b5dd9dd73--- a/docs/guides/repair.md+++ b/docs/guides/repair.md@@@ -142,8 -142,8 +142,9 @@@ work behind exits 0, so scripts should| `orphan-children` | `child_table_orphans` (also a `storage_corrupt` error) | Explicit-only. Deletes rows of page child tables (chunks, versions, tags, takes, raw data, timeline, links) whose page row no longer exists, and clears dangling `links.origin_page_id` and `files.page_id` references, each in one statement that rechecks the orphan condition. See [orphan children](#orphan-children). | `torn_pages`: page rows whose stored body cannot be read (torn TOAST). The preview names them; the repair never changes them. || `planner-stats` | `planner_stats_stale` | Runs `ANALYZE` on the hot tables (pages, links, facts, takes, content_chunks, timeline_entries) whose planner statistics are stale, so search and graph reads stop planning as slow nested loops. PGLite also resets each table's pending row count; Postgres runs each `ANALYZE` with a 60 s statement timeout and a 2 s lock timeout. No journal admission, no user data changes, brain-wide. | none || `contextual-mode` | `contextual_retrieval_coverage` (pages with no recorded mode) | Stamps the contextual retrieval mode on markdown pages imported without one (for example by a large `--no-embed` sync, or by a connector source on an older gbrain), exactly as a fresh import of the page would: the page, source and brain settings decide, and the per-chunk synopsis tier lands at the free title tier. It rebuilds projections only: no page write, no new page version and no request ID. A page whose stored vectors already match the stamped convention keeps them and queues no re-embedding; a page whose embedding input changes has only those vectors cleared and is re-embedded once, unless you pass `--no-embed`. | `unsealed_projection`: pages whose chunks lag their text; `gbrain embed --stale` or `safe-chunks` seals them first, and the next run stamps them. `embed_skip`: pages marked to skip embedding keep their stored vectors and are not stamped. |-| `file-drift` | `maintenance_write_drift` | Explicit-only, preview-bound. Resolves pages whose canonical file differs from the database copy (`source_changed` / `file_database_drift`) through canonical reconciliation, preferring the file or the database copy within reconcile's protections. `--all-drifted` refuses mixed drift classes unless `--class` keeps one. See [file drift](#file-drift). | Protected metadata, the tag union and protected takes or private fact rows, listed per page as `exceptions`; pages changed after the preview (`changed_since_preview`). |+| `file-drift` | `maintenance_write_drift` | Explicit-only, preview-bound. Resolves pages whose canonical file differs from the database copy (`source_changed` / `file_database_drift`) through canonical reconciliation, preferring the file or the database copy within reconcile's protections. `--all-drifted` refuses mixed drift classes unless `--class` keeps one; `--only`/`--skip` narrow by canonical file path glob. Opt-in `storage.keep_db` lets the owner host's resident consumer resolve drift under declared prefixes with the database copy. See [file drift](#file-drift). | Protected metadata, the tag union and protected takes or private fact rows, listed per page as `exceptions`; pages changed after the preview (`changed_since_preview`). |+| `ghost-pages` | `ghost_pages` | Explicit-only, preview-bound, destructive consent. Soft-deletes live pages whose canonical file is missing on the owner host (ghost pages: every write refuses `canonical_file_missing` and no sync can import a file that is not there), through `delete_page` bound to the previewed owner, path and revision. `--apply --expect <hash> --yes`. See [ghost pages](#ghost-pages). | Declared db_only and never-filed derived pages (never listed); a page whose file came back before the apply (`file_restored`); pages changed after the preview (`changed_since_preview`). |+ | `receipt-compaction` | `persistence_capacity` (terminal bytes) | Explicit-only, preview-bound, destructive consent. Compacts terminal write receipts now instead of on the idle maintenance tick (#6696): the intent and error message are dropped, the outcome, error code and detail stay, and the unused reservation returns to the receipt-bytes counters. `--older-than <72h\|30d>` is floored at the configured retention unless `--force`; committed receipts only unless `--include-failures`. No admission, so it runs at a full cap. See [receipt compaction](#receipt-compaction). | `failures_kept`: failed, conflict and cancelled receipts left without `--include-failures`. Receipts of a run whose sync cursor is still open, and the newest sync receipt of each worktree, are never listed. |Timeline rows that an earlier version of a page produced and its current textno longer has are removals, not history, so `timeline` neither counts nordiff --cc docs/guides/troubleshooting.mdindex 46c1b9968a,1316fa02f0..5e51bd1e0d--- a/docs/guides/troubleshooting.md+++ b/docs/guides/troubleshooting.md@@@ -240,10 -232,6 +240,8 @@@ A running sync is not one of these: `gb<a id="write-capacity"></a>**Managed writes refused with `queue_capacity`, or doctor warns `persistence_capacity`?** A per-principal or per-brain write-journal limit (`persistence.limits.*`) is full (`queue_capacity`), or doctor sees lifetime request IDs or receipt bytes at 80% or more (`persistence_capacity`). For the cumulative limits (lifetime request IDs and receipt bytes), the warning and the refusal print a `gbrain config set persistence.limits.<limit> <value>` sized for about one more year; run it on the brain host, then retry with the same request ID. For outstanding-request or queued-byte limits, let outstanding writes finish and check `gbrain sources writer status`. Receipt compaction age is `persistence.receipt_retention_days` (default 30). Limits and defaults: [bounded admission and retention](concurrent-writes.md#bounded-admission-and-retention).- <a id="doctor-ops-tier"></a>**`gbrain doctor` is slow on a large brain, or you need to see what is wrong in seconds?** Run `gbrain doctor --tier ops --json`. It runs only the operator sections (write capacity, unresolved write failures, a managed sync cursor that stopped moving, receipt compaction age, a serve running an older build, schema-pack consistency, embedding state) under a 4000 ms deadline; `--budget-ms <n>` changes it. A section the deadline cut off is reported as unknown (`details.health: "unknown"`, `reason: "budget"`, `exact: false`), never as clear, and the report says `complete: false` with the section in `unknown_sections`; rerun it alone with `gbrain doctor --only <name> --json`. On PGLite, sections that need a Postgres serve (managed sync, terminal-failure receipts, schema packs) read `not_applicable` and the report stays complete. The default doctor runs the same sections first, bounds every other check by `doctor.entry_budget_ms` (default 15000), and estimates `orphan_ratio` from a sample above `doctor.orphan_ratio.full_scan_max_pages` pages (default 50000); `--tier deep` scans fully. From a thin client, `gbrain doctor --tier ops` (or `--only persistence_capacity`) asks the serve: an admin token gets the ops report, a read token gets the `get_brain_health` bands (capacity and write failures as bands, no raw counts), and a serve that predates the ops tier refuses `doctor_tier_unavailable`: run `gbrain doctor --tier ops --json` on the brain host or upgrade and restart its serve. Agents without a shell call MCP `get_brain_health` (read scope) or `run_doctor` with `tier: "ops"` (admin).-- <a id="receipt-compaction"></a>**Doctor warns `receipt_compaction` ("The last receipt compaction ran N h ago … while a persistence consumer is live")?** A live consumer compacts finished write receipts during maintenance and records the run in `persistence.maintenance.last_compaction`. When that record is older than 24 hours while a consumer has renewed its heartbeat, compaction is not running: retained receipts keep their reservation, so the cumulative [write capacity](#write-capacity) only grows. Run `gbrain sources writer status --json` (read-only) to see which consumer is live, its version and its last maintenance step; an older serve that predates the record needs an upgrade and restart (after the user agrees). With no live consumer, or before the first compaction, the check reads ok. Verify with `gbrain doctor --only receipt_compaction --json`.++<a id="doctor-ops-tier"></a>**`gbrain doctor` is slow on a large brain, or you need to see what is wrong in seconds?** Run `gbrain doctor --tier ops --json`. It runs only the operator sections (write capacity, unresolved write failures, a managed sync cursor that stopped moving, receipt compaction freshness (`persistence_compaction`, see [receipt compaction](repair.md#receipt-compaction)), a serve running an older build, schema-pack consistency, embedding state) under a 4000 ms deadline; `--budget-ms <n>` changes it. A section the deadline cut off is reported as unknown (`details.health: "unknown"`, `reason: "budget"`, `exact: false`), never as clear, and the report says `complete: false` with the section in `unknown_sections`; rerun it alone with `gbrain doctor --only <name> --json`. On PGLite, sections that need a Postgres serve (managed sync, terminal-failure receipts, schema packs) read `not_applicable` and the report stays complete. The default doctor runs the same sections first, bounds every other check by `doctor.entry_budget_ms` (default 15000), and estimates `orphan_ratio` from a sample above `doctor.orphan_ratio.full_scan_max_pages` pages (default 50000); `--tier deep` scans fully. From a thin client, `gbrain doctor --tier ops` (or `--only persistence_capacity`) asks the serve: an admin token gets the ops report, a read token gets the `get_brain_health` bands (capacity and write failures as bands, no raw counts), and a serve that predates the ops tier refuses `doctor_tier_unavailable`: run `gbrain doctor --tier ops --json` on the brain host or upgrade and restart its serve. Agents without a shell call MCP `get_brain_health` (read scope) or `run_doctor` with `tier: "ops"` (admin).+<a id="dream-paid-loop"></a>**Dream keeps skipping one transcript, or doctor warns `dream_paid_loop`?** A dream key died `dream.breaker.max_dead_submissions` times (default 3) in 24 hours and is refused so it stops billing you. Fix the cause, then `gbrain dream reset-key --list` and `gbrain dream reset-key '<key>'`. See [the paid-loop breaker](../operations/spend-controls.md#dream-paid-loop-breaker-dreambreakermax_dead_submissions).**Hourly cron sync keeps timing out on a federated brain?** Switch yourdiff --cc docs/guides/write-refusals.mdindex 1c08b428a9,fe9a79b8bc..ab405467d5--- a/docs/guides/write-refusals.md+++ b/docs/guides/write-refusals.md@@@ -52,7 -44,8 +52,8 @@@ of making a duplicate| Reason | Error code | What it means | Recovery || --- | --- | --- | --- || <a id="file_database_drift"></a>`file_database_drift` | `source_changed` | The page's canonical file and its database copy disagree, usually because the file was edited outside a coordinated write. Neither copy was overwritten. A file with no `type:` line keeps the stored type, and titles compare trimmed, so those alone do not cause this. | `gbrain sources reconcile <source> <slug> --brain <brain> --preview`, review the preview, resolve it, then `--apply <resolved-preview-file> --request-id <new uuid>`. Retry the original write with a **new** request ID. A page that records no file of its own (no `source_path`, typically written by an older release whose write-through also put `ingested_via` / `ingested_at` / `source_kind` in the file only) reconciles against the file at its slug path only when you add `--adopt-slug-path` to the preview; the refusal names the flag in that case, and apply records that file as the page's origin. See [repair a file/database disagreement](concurrent-writes.md#repair-a-filedatabase-disagreement). Many pages at once: `gbrain sources reconcile <source> --brain host --audit --conflicts` lists them and `gbrain repair file-drift` resolves them, preferring the file or the database copy ([file drift](repair.md#file-drift)). |- | <a id="canonical_file_missing"></a>`canonical_file_missing` | `source_changed` | The page's recorded canonical file is gone while its database page is still live (a ghost page: the file was moved or deleted outside gbrain and the deletion was never imported). A write to the page refuses with "The canonical file was removed outside coordinated publication." and nothing is written. A sync cannot import a file that is not there, so retrying the write or rerunning sync refuses the same way. `gbrain sources writer failures <source>` reports such receipts as category `canonical_file_missing`. | Decide which copy is right. If the file should exist, restore it at its recorded path and sync. If the page should go, preview the ghost-page repair with `gbrain repair ghost-pages --source <source>` (read-only; it prints the apply command with its hash) and apply it with `--apply --expect <hash> --yes` only after the user agrees; a soft-deleted page can be restored with `gbrain restore <slug> --force` until the autopilot purge 72 h later. `gbrain pages ghosts --source <source>` and doctor `ghost_pages` list them. See [ghost pages](repair.md#ghost-pages). Reconciliation does not restore missing files. |-| <a id="canonical_file_missing"></a>`canonical_file_missing` | `source_changed` (maintenance, before admission) | A maintenance write (fact-fence adoption, enrichment, `dream`) targets a page whose recorded canonical file is gone. Before this release each cycle admitted the write and settled a `conflict` receipt, so a few deleted files spent request ids and receipt bytes every cycle (#6696). Now maintenance refuses before admission: no request id, no receipt. Neither copy was changed. | Import the deletion with `gbrain sync --source <source>`, or restore the file and preview the page with `gbrain sources reconcile <source> <slug> --brain host --preview`. Doctor `maintenance_write_drift` lists the pages. |++| <a id="canonical_file_missing"></a>`canonical_file_missing` | `source_changed` (a caller write; maintenance refuses before admission) | The page's recorded canonical file is gone while its database page is still live (a ghost page: the file was moved or deleted outside gbrain). A caller write refuses with "The canonical file was removed outside coordinated publication." and nothing is written; retrying it refuses the same way. A maintenance write (fact-fence adoption, enrichment, `dream`) is refused before admission: no request id, no receipt (before #6696 each cycle settled a `conflict` receipt). `gbrain sources writer failures <source>` reports such receipts as category `canonical_file_missing`. Neither copy was changed. | Decide which copy is right. If the file should exist, restore it at its recorded path and preview the page with `gbrain sources reconcile <source> <slug> --brain host --preview`, or sync. If the page should go, preview the ghost-page repair with `gbrain repair ghost-pages --source <source>` (read-only; it prints the apply command with its hash) and apply it with `--apply --expect <hash> --yes` only after the user agrees; a soft-deleted page can be restored with `gbrain restore <slug> --force` until the autopilot purge 72 h later. `gbrain pages ghosts --source <source>` and doctor `ghost_pages` list them, doctor `maintenance_write_drift` lists held-back maintenance writes. See [ghost pages](repair.md#ghost-pages). |+ | <a id="refusal_breaker"></a>`refusal_breaker` | the code of the earlier refusals | The same maintenance write (same source, slug, page revision, planner and intent) was refused `persistence.maintenance.refusal_breaker_threshold` times (default 3; `0` turns it off) in the last 24 hours, so maintenance submits nothing for it instead of adding another receipt (#6696). It is tried again once the page, the planner or the write changes, or when the oldest refusal is 24 hours old. | Read the last refusal with `gbrain write-request -- <request_id>` (named in the message) and fix what it names. Doctor `maintenance_write_drift` lists every held-back write with its exit. || <a id="shared_origin"></a>`shared_origin` | `source_changed` (purge, or a delete whose survivor changed); a soft delete commits with `write_through.skipped: shared_origin` | Two live pages of one source recorded the same canonical file (a duplicate-origin twin: the shared file renders one of them, so a delete of either used to refuse `file_database_drift`, reconcile refused "Several pages claim the recorded canonical file" and every managed sync refused `page_identity_changed`). A soft delete (`gbrain delete <slug> --source-id <id> --expected-revision <rev>`) of a page whose file another live page records now keeps the file and publishes database-only: the selected database page is hidden; the file and the surviving page remain. This does not erase that file's contents. The receipt's `write_through.warning` says so and names the surviving slug to the trusted local owner, or to a remote writer whose grant and visibility cover that slug; other remote writers read a generic "another page of this source records the same file". Sync's census and both origin guards apply one rule: a live page wins over tombstones, several live pages refuse, a single tombstone may be reused, several tombstones stay ambiguous. A purge (`--purge`) of a shared-origin page refuses with this reason: a purge tombstones the content source-wide and a same-content survivor would refuse `purged_content` on its next import. A delete whose surviving claimant changed between preparation and publication (the file moved or removed, a survivor deleted or re-pointed) refuses and never removes the file as a fallback. | Delete the page that should not own the file; the kept file still holds whatever text it had, so edit it first if it holds the deleted page's text, then `gbrain sync --source <id> --no-pull --full` (or the next sync that imports the file) imports its current content into the surviving page. For a purge, soft-delete instead. After a `source_changed` on a changed survivor, submit the delete again with a new `request_id`; it re-reads the file's claimants. || <a id="writer-coordinator-required"></a>`database_guard` or `database_trigger` | `writer_coordinator_required` (or `storage_error` for another trigger) | A database trigger refused a row while a write was being prepared or published, so nothing was committed and any canonical file already replaced was restored. With `database_guard`, a gbrain process wrote a row its publication does not own (another source, an unresolvable source, or a source checkpoint/topology change outside owner administration). This is a gbrain defect or a version mismatch between gbrain processes sharing the database, not a content conflict. The receipt's `write_error_detail` names the table, operation, guard branch, source relationship and stage; it never contains page text or source names. For another trigger it also carries a closed `reason`: `attribution_unclassified_table` or `trust_unclassified_table` (a gbrain stamp trigger met a table it is not built for: a version mismatch), `graduation_in_progress` (the engine-graduation fence, SQLSTATE 55000, refuses writes until the move finishes: retry later), or `unknown` (an operator trigger gbrain does not know; its message text stays on the brain host). The same `reason`, raiser and table appear on the managed sync failure (`gbrain doctor`, the failure ledger) and in `gbrain sync status --json` `last_error.write_error_detail`. | On the brain host run `gbrain sources writer status --probe --json`. Its `recent_failures[].error_detail` adds the source ids and the gbrain build and host that ran the attempt (`attempt.consumer_version`). If that build differs from `gbrain --version`, upgrade or restart every gbrain process that shares the database (serve, autopilot, sync jobs), then retry with a **new** request ID. If the builds match, report `error_detail` on the gbrain issue tracker. Never force-write, edit SQL or disable the guard. || `ambiguous_source_path` | `page_identity_changed` | A source registered at a Git subfolder `<sub>` has a page whose stored path `<sub>/<file>` could mean either `<file>` in the source directory (the older Git-root spelling) or `<sub>/<file>` inside a folder of the source that repeats its name, and both files exist. Sync refuses instead of guessing. See [sources in a Git subfolder](multi-source-brains.md#sources-in-a-git-subfolder). | Rename or move one of the two files, commit, then `gbrain sync --source <source> --no-pull --retry-failed`. |diff --cc llms-full.txtindex 35de7154ee,7ded918672..2343be5eb5--- a/llms-full.txt+++ b/llms-full.txt@@@ -10418,10 -10405,6 +10422,8 @@@ A running sync is not one of these: `gb<a id="write-capacity"></a>**Managed writes refused with `queue_capacity`, or doctor warns `persistence_capacity`?** A per-principal or per-brain write-journal limit (`persistence.limits.*`) is full (`queue_capacity`), or doctor sees lifetime request IDs or receipt bytes at 80% or more (`persistence_capacity`). For the cumulative limits (lifetime request IDs and receipt bytes), the warning and the refusal print a `gbrain config set persistence.limits.<limit> <value>` sized for about one more year; run it on the brain host, then retry with the same request ID. For outstanding-request or queued-byte limits, let outstanding writes finish and check `gbrain sources writer status`. Receipt compaction age is `persistence.receipt_retention_days` (default 30). Limits and defaults: [bounded admission and retention](concurrent-writes.md#bounded-admission-and-retention).- <a id="doctor-ops-tier"></a>**`gbrain doctor` is slow on a large brain, or you need to see what is wrong in seconds?** Run `gbrain doctor --tier ops --json`. It runs only the operator sections (write capacity, unresolved write failures, a managed sync cursor that stopped moving, receipt compaction age, a serve running an older build, schema-pack consistency, embedding state) under a 4000 ms deadline; `--budget-ms <n>` changes it. A section the deadline cut off is reported as unknown (`details.health: "unknown"`, `reason: "budget"`, `exact: false`), never as clear, and the report says `complete: false` with the section in `unknown_sections`; rerun it alone with `gbrain doctor --only <name> --json`. On PGLite, sections that need a Postgres serve (managed sync, terminal-failure receipts, schema packs) read `not_applicable` and the report stays complete. The default doctor runs the same sections first, bounds every other check by `doctor.entry_budget_ms` (default 15000), and estimates `orphan_ratio` from a sample above `doctor.orphan_ratio.full_scan_max_pages` pages (default 50000); `--tier deep` scans fully. From a thin client, `gbrain doctor --tier ops` (or `--only persistence_capacity`) asks the serve: an admin token gets the ops report, a read token gets the `get_brain_health` bands (capacity and write failures as bands, no raw counts), and a serve that predates the ops tier refuses `doctor_tier_unavailable`: run `gbrain doctor --tier ops --json` on the brain host or upgrade and restart its serve. Agents without a shell call MCP `get_brain_health` (read scope) or `run_doctor` with `tier: "ops"` (admin).-- <a id="receipt-compaction"></a>**Doctor warns `receipt_compaction` ("The last receipt compaction ran N h ago … while a persistence consumer is live")?** A live consumer compacts finished write receipts during maintenance and records the run in `persistence.maintenance.last_compaction`. When that record is older than 24 hours while a consumer has renewed its heartbeat, compaction is not running: retained receipts keep their reservation, so the cumulative [write capacity](#write-capacity) only grows. Run `gbrain sources writer status --json` (read-only) to see which consumer is live, its version and its last maintenance step; an older serve that predates the record needs an upgrade and restart (after the user agrees). With no live consumer, or before the first compaction, the check reads ok. Verify with `gbrain doctor --only receipt_compaction --json`.++<a id="doctor-ops-tier"></a>**`gbrain doctor` is slow on a large brain, or you need to see what is wrong in seconds?** Run `gbrain doctor --tier ops --json`. It runs only the operator sections (write capacity, unresolved write failures, a managed sync cursor that stopped moving, receipt compaction freshness (`persistence_compaction`, see [receipt compaction](repair.md#receipt-compaction)), a serve running an older build, schema-pack consistency, embedding state) under a 4000 ms deadline; `--budget-ms <n>` changes it. A section the deadline cut off is reported as unknown (`details.health: "unknown"`, `reason: "budget"`, `exact: false`), never as clear, and the report says `complete: false` with the section in `unknown_sections`; rerun it alone with `gbrain doctor --only <name> --json`. On PGLite, sections that need a Postgres serve (managed sync, terminal-failure receipts, schema packs) read `not_applicable` and the report stays complete. The default doctor runs the same sections first, bounds every other check by `doctor.entry_budget_ms` (default 15000), and estimates `orphan_ratio` from a sample above `doctor.orphan_ratio.full_scan_max_pages` pages (default 50000); `--tier deep` scans fully. From a thin client, `gbrain doctor --tier ops` (or `--only persistence_capacity`) asks the serve: an admin token gets the ops report, a read token gets the `get_brain_health` bands (capacity and write failures as bands, no raw counts), and a serve that predates the ops tier refuses `doctor_tier_unavailable`: run `gbrain doctor --tier ops --json` on the brain host or upgrade and restart its serve. Agents without a shell call MCP `get_brain_health` (read scope) or `run_doctor` with `tier: "ops"` (admin).+<a id="dream-paid-loop"></a>**Dream keeps skipping one transcript, or doctor warns `dream_paid_loop`?** A dream key died `dream.breaker.max_dead_submissions` times (default 3) in 24 hours and is refused so it stops billing you. Fix the cause, then `gbrain dream reset-key --list` and `gbrain dream reset-key '<key>'`. See [the paid-loop breaker](../operations/spend-controls.md#dream-paid-loop-breaker-dreambreakermax_dead_submissions).**Hourly cron sync keeps timing out on a federated brain?** Switch yourdiff --cc scripts/module-size-limits.tsvindex 33b4d0ce8d,35469889c7..6dfc2e9c9f--- a/scripts/module-size-limits.tsv+++ b/scripts/module-size-limits.tsv@@@ -3,20 -3,20 +3,20 @@@# Raising a ceiling is a conscious, reviewer-visible act. Lower ceilings in# the same commit as any peel (the guard fails on >50 lines of stale slack).# Columns: path max_lines policy note- src/cli/main.ts 3008 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)+ src/cli/main.ts 3009 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)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 667 ratchet +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 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.tssrc/commands/embed.ts 2236 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)src/commands/extract-conversation-facts.ts 2075 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)src/commands/extract.ts 2637 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 baselinesrc/commands/jobs.ts 666 ratchet refactor wave 1 split target (W4 jobs, cut line); ceiling rationale: docs/architecture/key-files/commands-4.md entry for src/commands/jobs.ts; help lines: authorize-legacy --select (#5157 T3) and jobs cancel --select (DX-T2); submit --queue-only + PGLite work drain note (agent-first operator wave E5); +2 spend authorization: jobs submit --yes/--max-usd and jobs list --group help lines; +4 fix wave 9: supervisor stop help documents the 45 s wait, --queue and the verified-drain exit codessrc/commands/serve-http.ts 931 ratchet refactor wave 1 W4 split into serve-http-<area>.ts modules; ceiling rationale: docs/architecture/key-files/commands-5.md entry for src/commands/serve-http.ts; +2 agent operator wave A6: ServeHttpContext.noticeLedger (import + field; logic in core/notice-ledger.ts); +2 agent contract F1/F2: ServeHttpContext.readinessCache (probed readiness for initialize tails + gbrain://capabilities); +5 Lane D facts drain: serve --http starts the drain scheduler and stops it before the engine disconnect (logic in core/facts/drain-scheduler.ts); +2 agent-operator follow-up Item 3: ServeHttpOptions.adoptServer (status-only recovery hands its bound listener to listenOrRefuse; logic in serve-http-status.ts); +5 #6317: managed-sync movement watch start/stop (watch in persistence/sync-movement.ts)src/core/ai/gateway.ts 4523 ratchet +17 #6607: lazy OpenAI model discovery (discoverBeforeOpenAICall, once per reconfigure, at the chat/expand/embed entry points; it re-resolves through the gateway-internal resolveGatewayModels, so it cannot move); +18 W11 item 3: embedQuery query-embedding cache lookup/store + clear at every model-cache clear site and the test transport seam (cache lives in ai/query-embed-cache.ts); +7 fix wave 5 (#5137): provider-key redactor on every upstream error path and the first embedding 401/403 report (logic in ai/key-redact.ts, ai/key-warnings.ts); +20 System One v1: decide() delegating export + transport seam, RerankInput.onMeta/RerankMeta, TypeSafe reranker delegation to ai/decide/rerank-adapter.ts; +3 #5585: reconfigureGatewayWithEngine records expansion/chat model provenance (ai/gateway-model-sources.ts) + clears it with gateway state; lowered #5585: tracker record sites collapsed onto ai/budget-record.ts (recordOnTracker + failedCallUsage) while adding ledger fields (requested model, purpose, failed, estimated, countsAsCall); +20: schema-rejection fallback in chat() (retry once schemaless on a json_schema 4xx, remember the recipe for the process — mirrors expand()); re-summed after merging master v0.50.0.0 with the wave (structured-output + pricing hunks); +48: #4863 ChatOpts.responseSchema → tolerant json_schema Output on the chat() generateText call for openai-compatible recipes that declare structured outputs (facts extraction on Ollama); +74: #3657 post-sunset rerank short-circuit (effective-model check, once-per-process audit row + stderr, injected-clock seam); grown v0.46.26.0 megawave: config-plane probes + halt telemetry (#3387 #4312); +21 lines (OpenAI Responses API reasoning-item echo: ChatBlock 'reasoning' variant, chat()/toModelMessages() round-trip); wave-k absorbs: OCR routing seam (#4107 class), config-snapshot reader block (#3980); +21: #4107 OCR-model routing (getImageOcrModel); +10: keyless OPENAI_BASE_URL embedding override (#4385); wave-k #3622 reimpl: GBRAIN_EMBED_MAX_BATCH_TOKENS env cap for no_batch_cap recipes; +9: DeepSeek judge thinking pin plumbed through chat opts (#4069); +master v0.48 merge true-up (reranker succession: no_key preflight, reranker_skipped stage, readiness); ranker wave v0.48.4.0: ChatOpts.temperature threaded to the transport (+15); +24: #4172 recipe-declared thinking headroom on the chat()/toolLoop() default — shared isThinkingModel predicate (Claude-5 regex || recipe thinking_by_default, fail-closed), also consumed by the subagent handler; +20: #4861 claude-cli expansion routed to the schemaless viaText path (the CLI adapter ignores responseFormat, so the native generateObject branch had no fallback); retired provider integration removed; safety wave: migration reranker input ceilings; lowered by fix wave 3 #5680 (embed request planning peeled to ai/embed-batch-plan.ts); +5 #4616: empty inputs skip the provider and every text/multimodal result is screened for zero-norm/NaN/Inf vectors (logic lives in ai/embedding-guard.ts); fix wave 3 integration: #4616 empty-input filtering feeds the shared #5680 batch planner; +3 #5691: embedQuery takes a per-request queryPrefix (no gateway state); +26 fix wave 7 (#5642): embed spend records bank provider-reported usage.tokens (all sub-batches reported → measured; chars-per-token estimate stays the fallback and the failure charge); +2 #5892: import + load-time call of installAiSdkWarningWriter (writer lives in ai/sdk-warnings.ts); +12 #5490: chat() delegation to ai/chat-fallback.ts when chat_fallback_chain is set (attempt loop lives there), ChatOpts.allowFallback + ToolLoopOpts.allowFallback fields and the toolLoop forward; +2 #5490 review: ChatResult.fallbackFrom (the call model a chat_fallback_chain answer replaced); +1 fix wave lane B3: configureGateway keeps chat_fallback_on_refusal (the refusal switch lives in ai/chat-fallback.ts); +18 fix wave 9 lane B: ChatOpts.thinking (#5331, per-route mapping lives in ai/thinking-off.ts), ChatOpts.timeoutMs + ToolLoopOpts.turnTimeoutMs and the turn forward (#4921); interface fields and their docs cannot move; +2 P8: GBRAIN_AI_CALL_LOG observer install in configureGateway (logic in ai/call-log.ts); +2 W9F item 5: thinkingOffOutputCap export shared by chat() and the judge preflight estimates (capability table lives in ai/thinking-off.ts); +3 A1 (wave 0): ChatResult.usage.reasoning_tokens (interface field + doc) and the chat() reasoning-subset read beside the cache counts; the ai-sdk importer allowlist is shrink-only, so the seam stays here); +9 GOOGLE_GENERATIVE_AI_BASE_URL: resolveNativeBaseUrl('google') + the three native-google construction sites (eval metering proxy); re-summed at the master 6ccf30c3e merge (4417 integration + 4423 master - 4408 base); lowered -5: the expand() prompt template peeled to ai/expansion-prompt.ts (buildExpansionPrompt) so the longmemeval call planner measures the same text- src/commands/sync.ts 525 ratchet refactor wave 1 split target (W4 sync); ceiling rationale: docs/architecture/key-files/commands-6.md entry for src/commands/sync.ts; +2 for the #5751 SyncResult.legacySkips interface field (fix wave 4); +2 fix wave 4 lane B: SyncResult.connectorHolds interface field (held counts for the sync summary); +1 fix wave 5 (#5032): SyncResult.fileRefusals interface field (named per-file Windows colon refusals); +13 #5984: SyncResult.drain / managedCursor and SyncOpts.drain / drainStartedAt interface fields (drain loop lives in persistence/sync-drain.ts); +1 #5984: SyncOpts.noBulk / bulk interface fields; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (510 measured); +2 #5984 lanes: SyncOpts.lanes field and the lanes progress-event field; +2 #6278: SyncResult.breaker interface field (the preparation-stall breaker verdict); +1 fix wave 13 P4.3 #6386: the JSON-output comment names writeJsonDocument for sync status/unblock; +2 fix wave 13 PR2: the transaction-pooler stderr line (P2.2) and the staged catch-up result field (P2.14, loop in commands/sync/perform.ts); +2 fix wave 15 P4.5 (#5459 adjacent): SyncResult.working_tree_kept interface field (the tree-walk keep lives in persistence/sync-discovery.ts); +4 #6643: SyncResult.retryWait / knockOns interface fields (recovery lives in persistence/sync-run.ts, sync-knock-on.ts); +2 #6696 C1: SyncOpts.embedDeferred interface field (the runtime cost-gate deferral; consumed in persistence/sync-run.ts freezeEntry)- src/core/cycle.ts 3303 ratchet +2 System One v1 S9: extract_facts phase tail runs the conflict sweep (ai/decide/sweep.ts) only when the slot is not off; +2 System One v1: purge phase prunes decision receipts (ai/decide/store.ts); grown v0.46.26.0 megawave (#4102 #2608) + master v0.46.26.0 cycle-start orphan recovery; +10 wave G #3974: cycle-sync uncommitted-drift warn; grown wave-g (#4416): synthesize_concepts source threading; grown wave-g (#4416): synthesize_concepts source threading (same fix absorbed as #4417 on wave-k); wave-k: ); +7: #4077 abort threading; +10: #4745 fullImplicitSourceCycle opt-in contract; +3: #4890 extract phase jsonMode/quiet + pages-not-links totals; +1: wave review — extract phase passes quiet:true + jsonMode:false; +1: extract_facts pagesFailed detail; +8 fix wave 3: one cycle date resolved in runCycle and threaded to synthesize/patterns/drift (C-15); +1 #5632: cycle sync resumes an unfinished managed cursor with its stored options; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +1 at the merge; -41 #5809: anyAbortSignal peeled to abort-signals.ts; +5 #5809: extract_atoms phase gets a real abort signal; +4 #5809: cycle_already_running names the lock holder; +7 #5255: cycle sync runs a managed pull request as no-pull and reports upstream_refresh; +1 #4578: a lock steal during the last selected phase reports lock_stolen, not aborted; +3 #5536: keyless embed phase clean-skips when embedding_disabled is set; +5 F4b: planner-stats refresh after the freshness phases (logic in planner-stats.ts); +2 agent operator wave A1: PhaseResult sibling code/fix; +20 #5876: Life Chronicle phase registration (CyclePhase, ALL_PHASES, NEEDS_LOCK) and its runCycle dispatch block; v0.60.46.0 merge: re-summed to the merged line count (3224); +3 retrieval feedback retention in the purge phase (logic in feedback/store.ts pruneRetrievalFeedback); 12 Lane D: facts_drain phase registration (CyclePhase, ALL_PHASES, NEEDS_LOCK) and its runCycle dispatch line (logic in cycle/facts-drain.ts); P3 x foundations-2 composition: deltas re-summed at the merge; 12 Lane D: facts_drain phase registration (CyclePhase, ALL_PHASES, NEEDS_LOCK) and its runCycle dispatch line (logic in cycle/facts-drain.ts); +15 GBRA-49 temporal typed edges: edge_contradictions phase registration + dispatch block + extract-phase relationship sweep call (logic in cycle/edge-contradictions.ts, link-relationships.ts); P3 x P1 (v0.60.57.0) composition: deltas re-summed at the merge; +1 fix wave 9 lane P (#5151): extract_facts phase passes drain so the facts watermark drain runs (logic in facts/reconcile-watermark.ts); +10 #6188: fence_repair phase registration (CyclePhase, ALL_PHASES, NEEDS_LOCK) and its runCycle dispatch block (logic in cycle/fence-repair.ts); +19 fix wave 12 #6242: source cycles with brain-wide phases also take the shared gbrain-cycle lease (acquireDbCycleLock lease set, needsMaintenanceLease, skipBrainWidePhases, all-skipped deriveStatus case; lease logic in cycle/lock-set.ts); +16 #6377: content_repair phase registration (CyclePhase, ALL_PHASES, NEEDS_LOCK), the REPAIR_LANE_PHASES dispatch helper shared with fence_repair (logic in cycle/content-repair.ts); +10 C4 pinned questions: standing_questions phase registration (CyclePhase, ALL_PHASES, NEEDS_LOCK) and its runCycle dispatch block (logic in questions/phase.ts)+ src/commands/sync.ts 525 ratchet refactor wave 1 split target (W4 sync); ceiling rationale: docs/architecture/key-files/commands-6.md entry for src/commands/sync.ts; +2 for the #5751 SyncResult.legacySkips interface field (fix wave 4); +2 fix wave 4 lane B: SyncResult.connectorHolds interface field (held counts for the sync summary); +1 fix wave 5 (#5032): SyncResult.fileRefusals interface field (named per-file Windows colon refusals); +13 #5984: SyncResult.drain / managedCursor and SyncOpts.drain / drainStartedAt interface fields (drain loop lives in persistence/sync-drain.ts); +1 #5984: SyncOpts.noBulk / bulk interface fields; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (510 measured); +2 #5984 lanes: SyncOpts.lanes field and the lanes progress-event field; +2 #6278: SyncResult.breaker interface field (the preparation-stall breaker verdict); +1 fix wave 13 P4.3 #6386: the JSON-output comment names writeJsonDocument for sync status/unblock; +2 fix wave 13 PR2: the transaction-pooler stderr line (P2.2) and the staged catch-up result field (P2.14, loop in commands/sync/perform.ts); +2 fix wave 15 P4.5 (#5459 adjacent): SyncResult.working_tree_kept interface field (the tree-walk keep lives in persistence/sync-discovery.ts); +4 #6643: SyncResult.retryWait / knockOns interface fields (recovery lives in persistence/sync-run.ts, sync-knock-on.ts); +2 #6696 (A7): SyncOpts.capacityPreflight interface field (preflight lives in persistence/sync-capacity-preflight.ts)+ src/core/cycle.ts 3314 ratchet +2 System One v1 S9: extract_facts phase tail runs the conflict sweep (ai/decide/sweep.ts) only when the slot is not off; +2 System One v1: purge phase prunes decision receipts (ai/decide/store.ts); grown v0.46.26.0 megawave (#4102 #2608) + master v0.46.26.0 cycle-start orphan recovery; +10 wave G #3974: cycle-sync uncommitted-drift warn; grown wave-g (#4416): synthesize_concepts source threading; grown wave-g (#4416): synthesize_concepts source threading (same fix absorbed as #4417 on wave-k); wave-k: ); +7: #4077 abort threading; +10: #4745 fullImplicitSourceCycle opt-in contract; +3: #4890 extract phase jsonMode/quiet + pages-not-links totals; +1: wave review — extract phase passes quiet:true + jsonMode:false; +1: extract_facts pagesFailed detail; +8 fix wave 3: one cycle date resolved in runCycle and threaded to synthesize/patterns/drift (C-15); +1 #5632: cycle sync resumes an unfinished managed cursor with its stored options; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +1 at the merge; -41 #5809: anyAbortSignal peeled to abort-signals.ts; +5 #5809: extract_atoms phase gets a real abort signal; +4 #5809: cycle_already_running names the lock holder; +7 #5255: cycle sync runs a managed pull request as no-pull and reports upstream_refresh; +1 #4578: a lock steal during the last selected phase reports lock_stolen, not aborted; +3 #5536: keyless embed phase clean-skips when embedding_disabled is set; +5 F4b: planner-stats refresh after the freshness phases (logic in planner-stats.ts); +2 agent operator wave A1: PhaseResult sibling code/fix; +20 #5876: Life Chronicle phase registration (CyclePhase, ALL_PHASES, NEEDS_LOCK) and its runCycle dispatch block; v0.60.46.0 merge: re-summed to the merged line count (3224); +3 retrieval feedback retention in the purge phase (logic in feedback/store.ts pruneRetrievalFeedback); 12 Lane D: facts_drain phase registration (CyclePhase, ALL_PHASES, NEEDS_LOCK) and its runCycle dispatch line (logic in cycle/facts-drain.ts); P3 x foundations-2 composition: deltas re-summed at the merge; 12 Lane D: facts_drain phase registration (CyclePhase, ALL_PHASES, NEEDS_LOCK) and its runCycle dispatch line (logic in cycle/facts-drain.ts); +15 GBRA-49 temporal typed edges: edge_contradictions phase registration + dispatch block + extract-phase relationship sweep call (logic in cycle/edge-contradictions.ts, link-relationships.ts); P3 x P1 (v0.60.57.0) composition: deltas re-summed at the merge; +1 fix wave 9 lane P (#5151): extract_facts phase passes drain so the facts watermark drain runs (logic in facts/reconcile-watermark.ts); +10 #6188: fence_repair phase registration (CyclePhase, ALL_PHASES, NEEDS_LOCK) and its runCycle dispatch block (logic in cycle/fence-repair.ts); +19 fix wave 12 #6242: source cycles with brain-wide phases also take the shared gbrain-cycle lease (acquireDbCycleLock lease set, needsMaintenanceLease, skipBrainWidePhases, all-skipped deriveStatus case; lease logic in cycle/lock-set.ts); +16 #6377: content_repair phase registration (CyclePhase, ALL_PHASES, NEEDS_LOCK), the REPAIR_LANE_PHASES dispatch helper shared with fence_repair (logic in cycle/content-repair.ts); +10 C4 pinned questions: standing_questions phase registration (CyclePhase, ALL_PHASES, NEEDS_LOCK) and its runCycle dispatch block (logic in questions/phase.ts); +11 #6696 (A5, A4): runCycle becomes the background-origin wrapper over runCycleUnscoped and adds the capacity notices (logic in persistence/admission-origin.ts, capacity-snapshot.ts) plus the CycleReport.notices interface fieldsrc/core/cycle/synthesize.ts 3228 ratchet +26 System One v1 S7/S8: triage and grounding decide delegation (triage-decide.ts, grounding-decide.ts); merged waves; grown v0.46.26.0 megawave + master rolling lease via shared throttled renewer; grown wave-g (#4506): cycle summaries can stay out of the source repo; +18: expired-verdict sweep + DeepSeek judge thinking pin (#4069); +47: #4077 cooperative-abort threading; +110: eval fix wave F6 spend surfacing (withChatPhase wrap, triage/child token telemetry, zero-page counter); +32: F1b quote-verify call site + kill switch; +2: F1a/F3/F4a OUTPUT POLICY rules; +59: F2 verified-segment rescue (gate at report construction, rescue knobs, telemetry); +19: rubric v2 peak-scoring + docblock rescue branch; +50: #4337 summary link-sample cap + dream_created_cycle_date preserve-on-rerun; +5: #4348 resolveCycleDate wiring (local-day summary bucketing); +3 round-3 rebase true-up; +55: #4805 synth-v2 completion skip (findSynthV2Completion + prefix-parameterized loadSuccessfulSynthesisKeys); +10: #4886 mode-aware buildSynthesisPrompt (oneshot children drop tool-use/final-prose guidance); #5105: small legacy writer/refusal and shared revision CAS delegates; +4: merge of #5666 durable synthesis completions with the v0.59.18.0 verify-epoch wiring; +7 #5413/#5471 discovery exclusions (self-capture session ids, dream output directories); +6 fix wave 2 (v0.60.5.0) integration: W7 paid-loop breaker check before submission and released-key daily-cap count on top of the W1b discovery exclusions; +6 v0.60.5.0 master-merge true-up: the wave-2 growth (+13 W1b, +6 W7) re-summed over master v0.59.18.0 at 3222 lines with no slack; +76 fix wave 3: per-run USD gate + fail-closed daily cap (C-13), child first-write ownership for stamp/reverse-write (C-8, #5685), cycle-date prompt hint (C-15), opt-in attribution rule (#5425); fix wave 3 x fix wave 2 (v0.60.5.0) composition: +19 at the merge; +2 #5806 triageNow clock seam forwarded to triage (interface field + call-site option); +4 #5854: a postprocess or summary publish still pending after its wait is deferred (publish_pending warn, no cooldown stamp; helper in synthesize-postprocess.ts); +14 #5490 review: a triage verdict a chat_fallback_chain model gave is used for the run but not cached (TriageResult.answeredBy, judge-client marker, guarded putDreamVerdict); Foundations 2 Lane C: maintenanceTransaction import (attributed summary page); +14 #5490 review: a triage verdict a chat_fallback_chain model gave is used for the run but not cached (TriageResult.answeredBy, judge-client marker, guarded putDreamVerdict); Foundations 2 Lane C: maintenanceTransaction import (attributed summary page); +14 #5490 review: a triage verdict a chat_fallback_chain model gave is used for the run but not cached (TriageResult.answeredBy, judge-client marker, guarded putDreamVerdict); lowered to 3200 by wave 9 lane W #5145: completion-key helpers (findLegacyCompletion, findSynthV2Completion, loadSuccessfulSynthesisKeys) peeled to synthesize-completion.ts with the new pre-triage partition; +13 P2 extraction.date_grounding: transcript observation date line instead of a run-date "Today's date" (config field + prompt arg); +1 fix wave 11 #6160: oneshot_task_prefixes on the child job data; +18 fix wave 12 #6069: unreliable-verdict backoff in runTriagePass (report code, pass backoff count, triage details entry; marker logic in triage-backoff.ts); +1 fix wave 12 #6242: SYNTH_PHASE_FAIL keeps an OperationError's suggestion and code (OperationError import)src/core/cycle/extract-atoms.ts 1654 ratchet crossed the 1500 unlisted cap in the atoms/extraction fix wave: +21 embed-aware cost gate (#4878), +65 atoms-array anchor scan (#4913); peel candidate: the parse block (parseAtomsOutcome / parseArrayAtOffset / atomsFromParsedArray) into extract-atoms-parse.ts; +35: #4853 transcript-origin atoms link to their conversation page; +130: #4916 transcript failure-count/tombstone (extract_atoms_transcript_state, TODOS P2(b)); wave composition: #4916 transcript-state skip + #4948 zero-atom prompt + #4943 meetings source-id summed; +3: wave review — a later `[]` is an honest zero-yield, a non-atom-shaped array is a counted failure; +13: wave review — explicit budget keeps the cap over an unpriced embed route ($0-priced); +14: wave review — transcript-state write errors surfaced, missing table warns once; merged reliability/shared-skills source integration; +37 fix wave 3: stable undated atom dates + stale-atom retirement (C-14); +3 #5525: effectiveVisibility stamped on non-managed atoms; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +3 at the merge; +6 fix wave 3 lane A (#5601): accepted-pending atom batches count as progress (helper in persistence/accepted-pending.ts); +4 fix wave 4: #5705 transcript-as-data system prompt lines and its message helper, #5627 response schema import (the atom-type list moved to extract-atoms-schema.ts); +30 #5809/#5832: drain hard/soft stop signals (ExtractAtomsOpts.signal/stopSignal, pre-commit abort checks, no strike or post-stop writes after a hard stop) and the cancellable backlog count; +1 #5812: transcript items are paste-stripped (corpusTextForExtraction import) before the input cut; +1 #5820: extract_atoms discovery passes selfCaptureSessionIds like synthesize; +10 #5856/#5854: drain attempt state (one BudgetTracker + one publish wait across batches) and the opt-in connector email/meeting exclusion (predicate in connector-atoms.ts); +1 Foundations 2 Lane C: maintenanceTransaction import (attributed stale-atom retirement); +5 fix wave 9 lane P (#5041): opt-in atom write-through hook and retired-atom slugs returned for file removal (logic in derived-write-through.ts); the parse block (parseAtomsOutcome / parseArrayAtOffset / atomsFromParsedArray) is peeled into extract-atoms-parse.ts (-193, fix wave 10 lane B); +35: #4853 transcript-origin atoms link to their conversation page; +130: #4916 transcript failure-count/tombstone (extract_atoms_transcript_state, TODOS P2(b)); wave composition: #4916 transcript-state skip + #4948 zero-atom prompt + #4943 meetings source-id summed; +3: wave review — a later `[]` is an honest zero-yield, a non-atom-shaped array is a counted failure; +13: wave review — explicit budget keeps the cap over an unpriced embed route ($0-priced); +14: wave review — transcript-state write errors surfaced, missing table warns once; merged reliability/shared-skills source integration; +37 fix wave 3: stable undated atom dates + stale-atom retirement (C-14); +3 #5525: effectiveVisibility stamped on non-managed atoms; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +3 at the merge; +6 fix wave 3 lane A (#5601): accepted-pending atom batches count as progress (helper in persistence/accepted-pending.ts); +4 fix wave 4: #5705 transcript-as-data system prompt lines and its message helper, #5627 response schema import (the atom-type list moved to extract-atoms-schema.ts); +30 #5809/#5832: drain hard/soft stop signals (ExtractAtomsOpts.signal/stopSignal, pre-commit abort checks, no strike or post-stop writes after a hard stop) and the cancellable backlog count; +1 #5812: transcript items are paste-stripped (corpusTextForExtraction import) before the input cut; +1 #5820: extract_atoms discovery passes selfCaptureSessionIds like synthesize; +10 #5856/#5854: drain attempt state (one BudgetTracker + one publish wait across batches) and the opt-in connector email/meeting exclusion (predicate in connector-atoms.ts); +1 Foundations 2 Lane C: maintenanceTransaction import (attributed stale-atom retirement); +5 fix wave 9 lane P (#5041): opt-in atom write-through hook and retired-atom slugs returned for file removal (logic in derived-write-through.ts); +17 #5031: same-page case-insensitive atom adoption fallback (one page-atom scan per source page per run); +12 P2 atomsPrompt helper: extraction.date_grounding source observation date + rule in the atoms prompt; +4 GBRA-75: octet_length-bounded body-length predicate (minCompiledTruthChars) for discovery and the backlog count-src/core/engine.ts 2787 ratchet grown v0.46.26.0 megawave: relational/visibility/usage contract surface (#4352 #4218); grown wave-g (#4524 #4527): orphans-mode contract + removeLink deleted count; wave-k: +4 fail-closed TrajectoryOpts.remote contract doc (#3855), +2 FactListOpts.unconsolidatedOnly (#4070), +14 getAllConfig bulk-read contract (#3980); +1: getBacklinkCounts page-id contract doc (#4380); +9: FactListOpts.grep SQL pre-limit contract (#3851); +13: dream-verdict TTL contract (#4069); +33: softDeletePages batch soft-delete contract (#4587); +8: #4592 scoped getStats/getHealth contract doc; +5 read-time TTL validity contract docs (active vs history read semantics); +12: #4280 findOrphanPages type/quarantined metadata contract; +14: traversePathsDetailed row-cap contract (ship-review); +12: resolveSlugWithAliasDetailed owning-source contract (ship-review) | merged v0.48.1.0: master #4788 + wave traversePathsDetailed/resolveSlugWithAliasDetailed; master: | merged v0.48.1.0 true-up; corrective release: read-policy signatures and Chronicle scope; +7: #4882 listFactsSince entitySlug/sessionId composition doc; #5105: canonical page state shared module and transaction/snapshot delegates; #5105: guarded derived projection preparation and read seals; #5105: resident-stop registration and direct transaction contract; #5105: +1 raw preservation contract for legacy engine migration; merged company ingestion/schema routing changes; safety wave: fact embedding model and text identity contract; +5 write-path wave: findDuplicatePage excludeSlug + id-first ranking contract; +2 fw3 A14: addTag tagSource provenance contract; evidence delivery: getChunkWindows interface member + type import (+3); #5761: +4 markPagesAttendanceBlocked member + countStalePagesForExtraction attendance option; +4 #5888: FactListOpts.fingerprint + FactRow.fact_fingerprint contract (hot-memory duplicate collapse); +1 GBRA-49: LinkReadScope temporal opts on the link read contract; +4 #5984: upsertChunks sealChunkerVersion and createVersion preimage contract docs (round-trip diet); v0.60.58.0 merge: #5984 diet growth re-summed over v0.60.57.0 (2683 measured); +10 P7 relationalChainHop member + ChainHopOpts/ChainHopEdge imports (SQL in search/read-enrichment.ts); +14 contributor audit wave P0: listFactsKeyset member (delta facts keyset read contract) + FactRow.created_at_iso; +1 #5375: get_versions limit/include_body type import (GetVersionsOpts, PageVersionRows); 3 P2 speaker attribution: FactAttribution type + FactRow/NewFact.attributed_to fields + findCandidateDuplicates attributedTo option contract; +4 #5984 lane apply diet: setPageAliases inline option and upsertChunks pageId contract docs; +10 #6278: executeRaw timeoutMs contract (transaction-local statement_timeout for bounded preparation reads); +2 GBRA-69: replaceDerivedLinksBatch member; master v0.60.136.0 merge into #5575 memory trust (both sides kept); +6 GBRA-67: readPageSnapshotsBatch interface member (BrainEngine signatures cannot move); +1 GBRA-75 wave 10: optional findDuplicatePages member (batched findDuplicatePage, contract in engine-sql/pages.ts); +4 FactListOpts/TrajectoryOpts.excludePrivate fact-provenance visibility contract (interface fields cannot move); +18 GBRA-76: TransactionOptions (abort signal) interface and the transaction/transactionDirect signatures (abort logic in postgres-engine/transaction-abort.ts); +2 W14 P3.11 (#4381): LinkBatchInput.resolution_type on top of W13; +1 C2: findCandidateDuplicates arm:'keyword' contract doc (facts.candidate_fusion); re-summed at the master 6ccf30c3e merge (2708 integration + 2707 master - 2707 base); +5 Cat 40 Hard fix wave F2 (#6271): countKeywordPages/searchKeywordPages BrainEngine signatures (SQL in engine-sql/keyword-pages.ts); +6 W15 P1.2 (#6454): countStaleFrontmatterKeyPages/listStaleFrontmatterKeyPages/stripStaleFrontmatterKeys contract (SQL in engine-sql/pages.ts)+src/core/engine.ts 2792 ratchet grown v0.46.26.0 megawave: relational/visibility/usage contract surface (#4352 #4218); grown wave-g (#4524 #4527): orphans-mode contract + removeLink deleted count; wave-k: +4 fail-closed TrajectoryOpts.remote contract doc (#3855), +2 FactListOpts.unconsolidatedOnly (#4070), +14 getAllConfig bulk-read contract (#3980); +1: getBacklinkCounts page-id contract doc (#4380); +9: FactListOpts.grep SQL pre-limit contract (#3851); +13: dream-verdict TTL contract (#4069); +33: softDeletePages batch soft-delete contract (#4587); +8: #4592 scoped getStats/getHealth contract doc; +5 read-time TTL validity contract docs (active vs history read semantics); +12: #4280 findOrphanPages type/quarantined metadata contract; +14: traversePathsDetailed row-cap contract (ship-review); +12: resolveSlugWithAliasDetailed owning-source contract (ship-review) | merged v0.48.1.0: master #4788 + wave traversePathsDetailed/resolveSlugWithAliasDetailed; master: | merged v0.48.1.0 true-up; corrective release: read-policy signatures and Chronicle scope; +7: #4882 listFactsSince entitySlug/sessionId composition doc; #5105: canonical page state shared module and transaction/snapshot delegates; #5105: guarded derived projection preparation and read seals; #5105: resident-stop registration and direct transaction contract; #5105: +1 raw preservation contract for legacy engine migration; merged company ingestion/schema routing changes; safety wave: fact embedding model and text identity contract; +5 write-path wave: findDuplicatePage excludeSlug + id-first ranking contract; +2 fw3 A14: addTag tagSource provenance contract; evidence delivery: getChunkWindows interface member + type import (+3); #5761: +4 markPagesAttendanceBlocked member + countStalePagesForExtraction attendance option; +4 #5888: FactListOpts.fingerprint + FactRow.fact_fingerprint contract (hot-memory duplicate collapse); +1 GBRA-49: LinkReadScope temporal opts on the link read contract; +4 #5984: upsertChunks sealChunkerVersion and createVersion preimage contract docs (round-trip diet); v0.60.58.0 merge: #5984 diet growth re-summed over v0.60.57.0 (2683 measured); +10 P7 relationalChainHop member + ChainHopOpts/ChainHopEdge imports (SQL in search/read-enrichment.ts); +14 contributor audit wave P0: listFactsKeyset member (delta facts keyset read contract) + FactRow.created_at_iso; +1 #5375: get_versions limit/include_body type import (GetVersionsOpts, PageVersionRows); 3 P2 speaker attribution: FactAttribution type + FactRow/NewFact.attributed_to fields + findCandidateDuplicates attributedTo option contract; +4 #5984 lane apply diet: setPageAliases inline option and upsertChunks pageId contract docs; +10 #6278: executeRaw timeoutMs contract (transaction-local statement_timeout for bounded preparation reads); +2 GBRA-69: replaceDerivedLinksBatch member; master v0.60.136.0 merge into #5575 memory trust (both sides kept); +6 GBRA-67: readPageSnapshotsBatch interface member (BrainEngine signatures cannot move); +1 GBRA-75 wave 10: optional findDuplicatePages member (batched findDuplicatePage, contract in engine-sql/pages.ts); +4 FactListOpts/TrajectoryOpts.excludePrivate fact-provenance visibility contract (interface fields cannot move); +18 GBRA-76: TransactionOptions (abort signal) interface and the transaction/transactionDirect signatures (abort logic in postgres-engine/transaction-abort.ts); +2 W14 P3.11 (#4381): LinkBatchInput.resolution_type on top of W13; +1 C2: findCandidateDuplicates arm:'keyword' contract doc (facts.candidate_fusion); re-summed at the master 6ccf30c3e merge (2708 integration + 2707 master - 2707 base); +5 Cat 40 Hard fix wave F2 (#6271): countKeywordPages/searchKeywordPages BrainEngine signatures (SQL in engine-sql/keyword-pages.ts); +6 W15 P1.2 (#6454): countStaleFrontmatterKeyPages/listStaleFrontmatterKeyPages/stripStaleFrontmatterKeys contract (SQL in engine-sql/pages.ts); +5 #6696 B3: readEmbeddingStateCounts/listEmbeddingStateRows signatures + type import (SQL in engine-sql/chunks.ts)src/core/import-file.ts 2027 ratchet +2: pre-publication withdrawal validation; grown v0.46.26.0 megawave: OCR budget + image import + embed-retry rewire (#3973 #3374); grown wave-g (#4530): per-model chunk-token cap wiring; +24 #4548: row-level visibility-aware fence merge on remote write-back (replaces the #2044 whole-block swap + #4553/#4555 warn-only paths); +7 #4546: merge extended to the timeline-embedded fence; +5 #4107: maybeOcr gates on the OCR model's provider; +3 #3893; +7: #4702 disabled_patterns pass-through to the sanity gate; composition true-up (fix-wave multi-train); +8 #4903: importCodeFile writes source_path so the full-sync reconcile can see code pages; -11: wave review — local fence append replaced by facts-fence.replaceOrInsertFactsFence (#4756 rule); security: durable queued authority and confined filesystem dispatch; master integration: grown v0.46.26.0 megawave: OCR budget + image import + embed-retry rewire (#3973 #3374); grown wave-g (#4530): per-model chunk-token cap wiring; +24 #4548: row-level visibility-aware fence merge on remote write-back (replaces the #2044 whole-block swap + #4553/#4555 warn-only paths); +7 #4546: merge extended to the timeline-embedded fence; +5 #4107: maybeOcr gates on the OCR model's provider; +3 #3893; +7: #4702 disabled_patterns pass-through to the sanity gate; composition true-up (fix-wave multi-train); +8 #4903: importCodeFile writes source_path so the full-sync reconcile can see code pages; -11: wave review — local fence append replaced by facts-fence.replaceOrInsertFactsFence (#4756 rule); harness support: boundary wiring to shared grants, isolated setup, withdrawal and delegated guards; merged v0.49: withdrawal preservation after data-only frontmatter parsing; #5105: small legacy writer/refusal and shared revision CAS delegates; #5105: +8 prepared contextual retrieval policy and retry boundary wiring; upstream integration: preserve independently reviewed master additions with branch facade extraction; #5252 wave: shared provider-free Markdown and code preparation; merged company ingestion/schema routing changes; master retrieval/projection integration with company ingestion; shared content: prepare managed image imports without bypassing canonical publication; +29 write-path wave: identity move/collision wiring (logic in import-identity.ts), deferred embedding on provider failure, image index completeness, file-time date anchor; +22 fw3 A13: markdown re-import reuses unchanged chunk vectors under the seal/wrapper/signature/protected-fence gate; +2 fw3 A12: importFromFile firstCommitAt option; +3 fw3 A14: managed imports keep add-only tags; +4 #5675: record the file origin move inference binds to (logic in import-identity.ts); fw3 integration: A12/A13/A14 (+27) and #5675 (+4) compose; +17 wave-2 W4: safe-chunk re-seal of unchanged legacy markdown/code pages (#5050 #5247) and embedding-input provenance on inline imports (#5553); -1 fix wave 2 (v0.60.5.0) integration: W4 delta re-summed over the merged master line count; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +16 at the merge; +11 #4616: markdown and code imports keep the usable vectors of a partially refused batch and leave refused chunks for embed --stale; lowered to 2230: #5621 contextual-mode resolution peeled to core/import-contextual-mode.ts (shared with gbrain repair contextual-mode); +2 wave 8 lane D1 #5158: key-order fallback equality call (comparison lives in page-state/import-guard.ts); +1 F1c: direct imports run in maintenanceTransaction (write attribution; helper in persistence/attribution.ts); lowered to 2178: #5988 content screen and content-sanity config peeled to core/import-screen.ts; +1 #6007: the prepared apply returns its page id and seal (PreparedImportApplied); +1 #5333: trusted imports drop a stale oversized embed_skip/content_flag the gate no longer sets, and an embed_skip transition defeats both unchanged fast paths; wave 10 collector: lane E (#5333) and the other lanes compose at 2183; grown #6188 (+17): fence options interface, result fields and the Tier 1 step call (logic in fence-repair/import-step.ts); +2 #5984 single-write fast path: the coordinated existingSnapshot option (interface field) composes with the lane apply diet at 2202; +1 GBRA-69: a coordinated apply defers its chunker seal to the caller (sealImportedPage in page-state/projections.ts); lowered to 2023: #5001 the edge-mapping loop moved to code-chunks.ts mapCodeEdges (shared with the prepared apply); W14 P3.13 (#5001) lowered 2049→2023 by moving the edge loop to mapCodeEdges; +2 W13 PR1 on top (2025 measured); +2 #6529: the unchanged-image skip path records source_path (refreshSourcePath, as #4588 does for Markdown)src/core/migrate.ts 602 ratchet schema-migration runner only; migrations live in src/core/schema-migrations/ (W3); +3 #5216: resumable page revision backfill runs after every migration pass while pages.knowledge_revision is nullablesrc/core/operations.ts 240 ratchet peel target: containment sprint C4-C7; grown v0.46.26.0 megawave op wiring; +chat-connectors wiring (master merge); +5 v0.47 gmail-loops: loopsOperations spread + OP_AREAS; #5105: receipt operation registry wiring; shared-skills integration on company-ingestion base; +2 security wave: withOutputRedaction applied at op registration; +1 #5616: pageEditOperations import (spread shares the pages line); +1 Foundations 1 F1b: attributionOperations import (spread shares the admin line); +1 agent operator wave A6: ops/notices.ts import (mute_notice); +2 agent operator closeout A1: registerOpRoutes import + call (routing logic in fix-routing.ts); +2 retrieval feedback: feedbackOperations import and spread (ops/feedback.ts); +1 #6007: pageBatchOperations import (spread shares the pages line); +1 P5: wanted_pages area row; lowered GBRA-75 W11 cold start: OP_AREAS + finalize step moved to operation-load.ts (shared with the CLI per-op loader); +1 C4 pinned questions: questionsOperations import and spread (ops/questions.ts; its areas live in operation-load.ts OP_AREAS)diff --cc src/commands/doctor/brain-health-bands.tsindex fbdd15e608,0000000000..05984caf11mode 100644,000000..100644--- a/src/commands/doctor/brain-health-bands.ts+++ b/src/commands/doctor/brain-health-bands.ts@@@ -1,77 -1,0 +1,82 @@@+/**+ * #6696 B2 (Garry decision d2b): what a remote agent without admin scope may+ * see of brain health — bands, never exact counters, slugs, paths, request ids+ * or principal identities. Served by the read-scope operation+ * `get_brain_health` and the thin client's `gbrain doctor --only+ * persistence_capacity` when its token lacks admin.+ *+ * Capacity is brain-wide host state (one band for the brain and every- * principal); write failures are scoped to the caller's readable sources. A++ * principal), read from the shared 60 s capacity snapshot (`cachedCapacitySnapshot`); write failures are scoped to the caller's readable sources. A+ * section that could not be read is `unknown`, never a clear band. Answers are+ * cached per engine and scope for 60 s, so a polling agent costs one read a+ * minute.+ */+import type { BrainEngine } from '../../core/engine.ts';- import { capacityBands, readCapacityView, type CapacityBand, type DaysBand } from '../../core/persistence/capacity-view.ts';++import { capacityBands, type CapacityBand, type DaysBand } from '../../core/persistence/capacity-view.ts';++import { cachedCapacitySnapshot } from '../../core/persistence/capacity-snapshot.ts';++import { readCapacityThresholds } from '../../core/persistence/capacity-forecast.ts';+import { cachedTerminalSummary } from '../serve-http-metrics.ts';+import { readEmbeddingState } from '../../core/embedding-state.ts';+import { readGhostPages } from '../../core/ghost-pages.ts';++export const BRAIN_HEALTH_TTL_MS = 60_000;+export type CountBand = 'none' | '1-9' | '10-99' | '100-999' | '1000+' | 'unknown';++export function countBand(n: number | null | undefined): CountBand {+ if (n === null || n === undefined || !Number.isFinite(n) || n < 0) return 'unknown';+ return n === 0 ? 'none' : n < 10 ? '1-9' : n < 100 ? '10-99' : n < 1000 ? '100-999' : '1000+';+}++export interface BrainHealthBands {+ schema_version: 1;+ status: 'ok' | 'attention' | 'unknown';+ capacity: { band: CapacityBand | 'unknown'; days: DaysBand; max_pct_band: '<80' | '80-95' | '>=95' | 'unknown'; forecast: 'available' | 'unavailable' };+ write_failures: { band: CountBand; active_blockers: CountBand; window_days: number | null };+ /** Chunks search cannot fully see (ops-mode, index-backed: `lower_bound` when some states were not counted). */+ unsearchable: { band: CountBand; lower_bound: boolean };+ /** Live pages whose canonical file is gone on the owner host; `reason` when not counted here (for example not_owner_host). */+ ghost_pages: { band: CountBand; reason?: string };+ /** The read-only command an operator runs on the brain host for the full report. */+ host_command: string[];+}++const cache = new WeakMap<BrainEngine, Map<string, { at: number; value: Promise<BrainHealthBands> }>>();++/** `sourceIds`: the sources this caller may read (undefined: every source). */+export function readBrainHealthBands(engine: BrainEngine, opts: { sourceIds?: string[] } = {}, now = Date.now()): Promise<BrainHealthBands> {+ const key = opts.sourceIds ? [...opts.sourceIds].sort().join('\u0000') : '*';+ const perEngine = cache.get(engine) ?? new Map();+ cache.set(engine, perEngine);+ const hit = perEngine.get(key);+ if (hit && now - hit.at < BRAIN_HEALTH_TTL_MS) return hit.value;+ const value = computeBands(engine, opts.sourceIds);+ perEngine.set(key, { at: now, value });+ return value;+}++async function computeBands(engine: BrainEngine, sourceIds: string[] | undefined): Promise<BrainHealthBands> {+ const [capacity, failures, unsearchable, ghostPages] = await Promise.all([- readCapacityView(engine).then((view) => ({ ...capacityBands(view), forecast: view.forecast ? 'available' as const : 'unavailable' as const }))++ Promise.all([cachedCapacitySnapshot(engine), readCapacityThresholds(engine)])++ .then(([snapshot, thresholds]) => snapshot.status !== 'ok'++ ? { capacity: 'unknown' as const, days: 'unknown' as const, max_pct_band: 'unknown' as const, forecast: 'unavailable' as const }++ : { ...capacityBands(snapshot, thresholds), forecast: 'available' as const })+ .catch(() => ({ capacity: 'unknown' as const, days: 'unknown' as const, max_pct_band: 'unknown' as const, forecast: 'unavailable' as const })),+ cachedTerminalSummary(engine).then((summary) => {+ if (summary.status !== 'ok') return { band: 'unknown' as const, active_blockers: 'unknown' as const, window_days: null };+ const visible = summary.sources.filter((s) => !sourceIds || sourceIds.includes(s.source_id));+ return { band: countBand(visible.reduce((n, s) => n + s.unresolved.rows, 0)), active_blockers: countBand(visible.reduce((n, s) => n + s.active_blockers.length, 0)),+ window_days: summary.window_days };+ }),+ readEmbeddingState(engine, { mode: 'ops', ...(sourceIds ? { sourceIds } : {}) })+ .then((state) => state.status === 'unknown' ? { band: 'unknown' as const, lower_bound: false } : { band: countBand(state.unsearchable), lower_bound: state.unsearchable_complete === false })+ .catch(() => ({ band: 'unknown' as const, lower_bound: false })),+ readGhostPages(engine, { sampleLimit: 0, ...(sourceIds ? { sourceIds } : {}) })+ .then((g): { band: CountBand; reason?: string } => g.status === 'known' ? { band: countBand(g.count) } : { band: 'unknown', ...(g.reason ? { reason: g.reason } : {}) })+ .catch(() => ({ band: 'unknown' as const })),+ ]);+ const bands = { capacity: { band: capacity.capacity, days: capacity.days, max_pct_band: capacity.max_pct_band, forecast: capacity.forecast }, write_failures: failures, unsearchable, ghost_pages: ghostPages };+ const unknown = bands.capacity.band === 'unknown' || failures.band === 'unknown';+ const attention = bands.capacity.band === 'low' || bands.capacity.band === 'critical' || (failures.active_blockers !== 'none' && failures.active_blockers !== 'unknown')+ || (ghostPages.band !== 'none' && ghostPages.band !== 'unknown');+ return { schema_version: 1, status: attention ? 'attention' : unknown ? 'unknown' : 'ok', ...bands, host_command: ['gbrain', 'doctor', '--tier', 'ops', '--json'] };+}diff --cc src/commands/doctor/checks/maintenance-drift.tsindex e90c50e4bb,9d53873d46..5562a6eb44--- a/src/commands/doctor/checks/maintenance-drift.ts+++ b/src/commands/doctor/checks/maintenance-drift.ts@@@ -1,10 -1,8 +1,11 @@@import type { BrainEngine } from '../../../core/engine.ts';import type { Check } from '../../doctor.ts';import { agentFix, checkError } from '../check-fix.ts';+ import { listSuppressedWrites, type SuppressedWrite } from '../../../core/persistence/refusal-breaker.ts';import { auditConflictsCommand, FILE_DRIFT_MESSAGE, fileDriftRepairCommand, liveFileDrift, readDriftSkips } from '../../../core/persistence/drift-conflicts.ts';+import { existingLocalHostId } from '../../../core/persistence/identity.ts';+import { isKeepDbSlug } from '../../../core/storage-config.ts';+import { keepDbReceiptCost, readKeepDbPolicy } from '../../../core/repair/keep-db-policy.ts';/** Newest request sequences scanned for drift conflicts (one range read of the unique sequence index). */const WINDOW = 20_000;@@@ -19,10 -17,8 +20,12 @@@ const LIVE_LIMIT = 100* It measures the drift itself, not conflict-row growth: producers back off* before admission, so a drifted page stops adding receipts. Names the* read-only audit and the explicit-only `gbrain repair file-drift` preview.+ * #6696 C7: on the owner host it also echoes each source's effective+ * `storage.keep_db` policy (`keep_db_policy`, present only when one is+ * declared): its prefixes, how many of the drifted pages checked here it+ * matches, and their receipt cost (one request each).+ * #6696 (A12): also lists the maintenance writes the refusal breaker holds+ * back (`suppressed`, each with the action that releases it).*/export async function maintenanceWriteDriftCheck(engine: BrainEngine, sourceIds?: string[]): Promise<Check> {const docs = 'docs/guides/troubleshooting.md#maintenance-write-drift';@@@ -31,10 -27,10 +34,12 @@@const [bounds] = await engine.executeRaw<{ top: string | null }>('SELECT max(sequence)::text AS top FROM persistence_requests');const floor = String(Math.max(0, Number(bounds?.top ?? 0) - WINDOW));const skips = await readDriftSkips(engine);+ const hostId = existingLocalHostId();const rows = [];+ const policies = [];+ const suppressed: SuppressedWrite[] = [];for (const sourceId of sources) {+ suppressed.push(...await listSuppressedWrites(engine, sourceId));const candidates = await engine.executeRaw<{ slug: string }>(`SELECT DISTINCT r.slug FROM persistence_requests rWHERE r.sequence > $2::bigint AND r.source_id=$1 AND r.state='conflict' AND r.error_code='source_changed' AND r.error_message=$3ORDER BY r.slug LIMIT ${LIVE_LIMIT + 1}`, [sourceId, floor, FILE_DRIFT_MESSAGE]);@@@ -59,10 -47,14 +64,17 @@@}const count = rows.reduce((sum, row) => sum + row.drifted, 0);const skipCount = rows.reduce((sum, row) => sum + row.concept_skips, 0);- const details = { count, concept_skips: skipCount, sources: rows, window_sequences: WINDOW, repair: 'file-drift', docs, ...(policies.length ? { keep_db_policy: policies } : {}) };- const details = { count, concept_skips: skipCount, sources: rows, window_sequences: WINDOW, repair: 'file-drift', docs, suppressed };++ const details = { count, concept_skips: skipCount, sources: rows, window_sequences: WINDOW, repair: 'file-drift', docs, suppressed, ...(policies.length ? { keep_db_policy: policies } : {}) };+ const policyNote = policies.map(policy => 'error' in policy ? ` storage.keep_db of ${policy.source_id} could not be read: ${policy.error}`+ : ` storage.keep_db of ${policy.source_id} (${policy.keep_db.join(', ')}) matches ${policy.matched} of them${policy.unchecked ? ` (${policy.unchecked} more not checked here)` : ''}; `+ + `the owner host's maintenance worker reconciles them with the database copy, one rate-limited request each (${policy.receipt_cost.lifetime_ids} lifetime id(s), ${policy.receipt_cost.receipt_bytes} receipt bytes).`).join('');+ if (!count && !skipCount && suppressed.length) {+ return { name: 'maintenance_write_drift', status: 'warn', details,+ message: `${suppressed.length} maintenance write(s) are held back after repeated identical refusals (#6696), so they stop adding receipts: `+ + `${suppressed.slice(0, 5).map(row => `${row.source_id}:${row.slug} ${row.error_code} x${row.refusals}${row.cause ? ` (${row.cause})` : ''} -> ${row.exit}`).join('; ')}. `+ + 'Each is tried again once its page, planner or write changes, or after a day.',+ fix: agentFix(['gbrain', 'write-request', '--', suppressed[0]!.last_request_id], 'Read-only: the last refused attempt and what it names.', 'maintenance_write_drift', { docs }) };+ }if (!count && !skipCount) {const unknown = rows.reduce((sum, row) => sum + row.unknown, 0);return { name: 'maintenance_write_drift', status: 'ok', details,diff --cc src/commands/doctor/checks/ops-sections.tsindex 2d1d7b3842,0000000000..dee206c4bamode 100644,000000..100644--- a/src/commands/doctor/checks/ops-sections.ts+++ b/src/commands/doctor/checks/ops-sections.ts@@@ -1,116 -1,0 +1,84 @@@+/**+ * #6696 B1: the ops-tier sections of `gbrain doctor --tier ops` — "what is+ * wrong right now", answered in seconds. Each entry is tagged `tier: 'ops'`, so+ * the default run puts them first (registry order) and `--tier ops` runs only+ * them, under one absolute deadline (./budget.ts).+ *- * Sections owned here: managed write capacity, terminal write failures, receipt- * compaction freshness and schema-pack consistency. The other ops sections are++ * Sections owned here: managed write capacity and its forecast, terminal write++ * failures, receipt compaction freshness (`persistence_compaction`, the++ * consumer's `persistence.maintenance.last_compaction` record) and schema-pack++ * consistency. The other ops sections are+ * tagged where they live: `embedding_state` (embedding coverage),+ * `managed_sync_not_moving` (sync cursor movement and age) and+ * `serve_build_drift` (serve build drift).+ *+ * On PGLite the ops tier reads only counters, config and catalog: an entry with+ * `opsPglite: 'not_applicable'` (it aggregates request or page tables) reports+ * `not_applicable` there instead of running.+ */+import type { Check } from '../../doctor.ts';+import { connectedEngine, doctorSourceIds, type DoctorContext, type DoctorEntry } from '../context.ts';+import { checkPersistenceCapacity } from './persistence-capacity.ts';+import { terminalFailuresCheck } from './persistence-requests.ts';+import { checkSchemaPackConsistency } from '../schema-pack-checks.ts';- import { LAST_COMPACTION_KEY, readCapacityView } from '../../../core/persistence/capacity-view.ts';- import { agentFix, checkError, infoCheck } from '../check-fix.ts';-- /** A consumer that has not compacted receipts for this long, while one is live, warns. */- export const COMPACTION_STALE_HOURS = 24;- const COMPACTION_DOCS = 'docs/guides/troubleshooting.md#receipt-compaction';++import { checkPersistenceCompaction } from './persistence-compaction.ts';++async function runPersistenceCapacity(ctx: DoctorContext): Promise<Check[]> {+ const checks: Check[] = [];+ ctx.progress.heartbeat('persistence_capacity');+ checks.push(await checkPersistenceCapacity(connectedEngine(ctx)));+ return checks;+}++export const persistenceCapacityEntry: DoctorEntry = {+ name: 'persistence_capacity',+ emits: ['persistence_capacity'],+ tier: 'ops',+ run: runPersistenceCapacity,+};++async function runTerminalFailures(ctx: DoctorContext): Promise<Check[]> {+ const checks: Check[] = [];+ ctx.progress.heartbeat('persistence_terminal_failures');+ const check = await terminalFailuresCheck(connectedEngine(ctx), doctorSourceIds(ctx));+ if (check) checks.push({ ...check, name: 'persistence_terminal_failures' });+ return checks;+}++export const terminalFailuresEntry: DoctorEntry = {+ name: 'persistence_terminal_failures',+ emits: ['persistence_terminal_failures'],+ tier: 'ops',+ opsPglite: 'not_applicable',+ run: runTerminalFailures,+};+- /**- * Receipt compaction freshness: the consumer records its last compaction under- * `persistence.maintenance.last_compaction`. Nothing recorded is information- * (a build or brain that has not compacted yet); a record older than 24 h while a- * persistence consumer heartbeats warns, because receipts then keep their full- * reservation and capacity only grows.- */- async function runReceiptCompaction(ctx: DoctorContext): Promise<Check[]> {++async function runPersistenceCompaction(ctx: DoctorContext): Promise<Check[]> {+ const checks: Check[] = [];- ctx.progress.heartbeat('receipt_compaction');- const engine = connectedEngine(ctx);- try {- const { last_compaction: last } = await readCapacityView(engine);- if (!last) {- checks.push(infoCheck('receipt_compaction', `No receipt compaction recorded yet (${LAST_COMPACTION_KEY} is unset): the persistence consumer records one after it compacts.`,- 'not_applicable', undefined, { recorded: false, docs: COMPACTION_DOCS }));- return checks;- }- const ageHours = (Date.now() - Date.parse(last.at)) / 3_600_000;- const live = await engine.executeRaw<{ n: string }>(- "SELECT count(*)::text AS n FROM persistence_consumers WHERE renewed_at > now() - interval '5 minutes'").catch(() => [{ n: '0' }]);- const details = { recorded: true, last_compaction: last, age_hours: Math.round(ageHours * 10) / 10, stale_after_hours: COMPACTION_STALE_HOURS, live_consumers: Number(live[0]?.n ?? 0), docs: COMPACTION_DOCS };- if (ageHours > COMPACTION_STALE_HOURS && details.live_consumers > 0) {- checks.push({ name: 'receipt_compaction', status: 'warn', details,- message: `The last receipt compaction ran ${Math.round(ageHours)} h ago (${last.at}${last.host ? ` on ${last.host}` : ''}) while a persistence consumer is live: retained receipts keep their reservation, so write capacity only grows.`,- fix: agentFix(['gbrain', 'sources', 'writer', 'status', '--json'], 'Read-only: names the live consumer, its version and its last maintenance step.', 'receipt_compaction', { docs: COMPACTION_DOCS }) });- } else {- checks.push({ name: 'receipt_compaction', status: 'ok', details,- message: `Receipts last compacted ${Math.round(ageHours)} h ago (${last.at})${last.compacted !== undefined ? `, ${last.compacted} receipt(s)` : ''}.` });- }- } catch (error) {- checks.push(checkError('receipt_compaction', 'read the last receipt compaction', error, { details: { health: 'unknown', docs: COMPACTION_DOCS } }));- }++ ctx.progress.heartbeat('persistence_compaction');++ checks.push(await checkPersistenceCompaction(connectedEngine(ctx)));+ return checks;+}+- export const receiptCompactionEntry: DoctorEntry = {- name: 'receipt_compaction',- emits: ['receipt_compaction'],++export const persistenceCompactionEntry: DoctorEntry = {++ name: 'persistence_compaction',++ emits: ['persistence_compaction'],+ tier: 'ops',- run: runReceiptCompaction,++ run: runPersistenceCompaction,+};++async function runSchemaPackConsistency(ctx: DoctorContext): Promise<Check[]> {+ const checks: Check[] = [];+ ctx.progress.heartbeat('schema_pack_consistency');+ const sourceIds = doctorSourceIds(ctx);+ checks.push(await checkSchemaPackConsistency(connectedEngine(ctx), sourceIds ? { sourceIds } : {}));+ return checks;+}++export const schemaPackConsistencyEntry: DoctorEntry = {+ name: 'schema_pack_consistency',+ emits: ['schema_pack_consistency'],+ tier: 'ops',+ opsPglite: 'not_applicable',+ run: runSchemaPackConsistency,+};diff --cc src/commands/doctor/checks/persistence-capacity.tsindex 2f51e0c659,52ad65369e..64b7c38957--- a/src/commands/doctor/checks/persistence-capacity.ts+++ b/src/commands/doctor/checks/persistence-capacity.ts@@@ -1,36 -1,72 +1,73 @@@import type { BrainEngine } from '../../../core/engine.ts';import type { Check } from '../../doctor.ts';- import { oneYearCapacity } from '../../../core/persistence/limits.ts';- import { CUMULATIVE_RESOURCES, capacityVerify, readCapacityView } from '../../../core/persistence/capacity-view.ts';+ import { capacityDiagnostics } from '../../../core/persistence/diagnostics.ts';+ import { oneYearCapacity, readJournalLimits } from '../../../core/persistence/limits.ts';+ import { readCapacityForecast, type CapacityForecast } from '../../../core/persistence/capacity-forecast.ts';-import { doctorVerify } from '../check-fix.ts';++import { capacityVerify } from '../../../core/persistence/capacity-view.ts';+ import { BACKGROUND_PRODUCERS, readBackgroundPauseShare } from '../../../core/persistence/admission-origin.ts';++ const VERIFY = 'gbrain doctor --only persistence_capacity --json';+ const DOCS = 'docs/guides/concurrent-writes.md#quota-near-exhaustion';/**- * #5470: warn at 80% of a cumulative managed-write cap (permanent request IDs,- * receipt bytes) before admission refuses. Transient caps drain on their own.- * Bounded: one indexed read per counter row (brain plus each principal), through- * the capacity view the ops tier and `get_brain_health` share (#6696).+ * #5470/#6696 (A3): a cumulative managed-write cap (permanent request IDs,+ * receipt bytes) is a warning when it is at 80% or would refuse admission+ * within `persistence.capacity.warn_days` (30) at its 7-day rate, and a+ * failure at 95% or within `persistence.capacity.fail_days` (7). The rate is+ * the full 7-day aggregate (capacity-forecast.ts); receipt bytes forecast at+ * their compacted (net) size. Each key gets the one value that covers a year.+ * A scope past the background pause line (A5) names the producers it pauses.++ * The fix verifies through doctor and the read-scope `get_brain_health` band (#6696 B2).*/export async function checkPersistenceCapacity(engine: BrainEngine): Promise<Check> {try {- const view = await readCapacityView(engine);- const near = view.rows.filter(row => row.approaching_capacity && CUMULATIVE_RESOURCES.has(row.resource));+ const counters = await engine.executeRaw<{ key: string; outstanding_count: string; intent_bytes: string; lifetime_ids: string;+ terminal_bytes: string; recovery_bytes: string }>(`SELECT key,outstanding_count::text,intent_bytes::text,lifetime_ids::text,+ terminal_bytes::text,recovery_bytes::text FROM persistence_counters WHERE key='brain' OR key LIKE 'principal:%' ORDER BY key`);+ const limits = await readJournalLimits(engine);+ const forecast: CapacityForecast | null = await readCapacityForecast(engine, { limits }).catch(() => null);+ const pause = await readBackgroundPauseShare(engine);+ const cumulative = capacityDiagnostics(counters, limits).filter(row => row.resource === 'lifetime_ids' || row.resource === 'terminal_bytes');const resources = [];const needed = new Map<string, number>();- for (const row of near) {- const value = await oneYearCapacity(engine, row.scope, row.resource === 'lifetime_ids' ? 'LifetimeIds' : 'TerminalBytes', row.used, row.limit);- resources.push({ scope: row.scope, resource: row.resource, used: row.used, limit: row.limit, config_key: row.config_key });+ let worst: 'ok' | 'warn' | 'fail' = 'ok';+ for (const row of cumulative) {+ const predicted = forecast?.rows.find(f => f.scope === row.scope && f.resource === row.resource);+ const paused = row.used >= Math.floor(row.limit * pause);+ const predictedStatus = predicted?.status ?? (row.approaching_capacity ? 'warn' : 'ok');+ const status = paused && predictedStatus === 'ok' ? 'warn' : predictedStatus;+ if (status === 'ok') continue;+ if (status === 'fail' || worst === 'ok') worst = status;+ // No admission inside the window: the latest admissions, however old, size the year instead.+ const value = predicted && predicted.per_day_7d > 0 ? predicted.recommended_limit+ : await oneYearCapacity(engine, row.scope, row.resource === 'lifetime_ids' ? 'LifetimeIds' : 'TerminalBytes', row.used, row.limit);+ resources.push({ scope: row.scope, resource: row.resource, used: row.used, limit: row.limit, config_key: row.config_key, status, background_paused: paused,+ ...(predicted ? { pct: predicted.pct, days_to_exhaustion: predicted.days_to_exhaustion, exhaustion_date: predicted.exhaustion_date, basis: predicted.basis,+ per_day_7d: predicted.per_day_7d, ...(predicted.net_per_day_7d !== undefined ? { net_per_day_7d: predicted.net_per_day_7d } : {}),+ ...(predicted.reclaimable_bytes !== undefined ? { reclaimable_bytes: predicted.reclaimable_bytes } : {}) } : {}) });+ // Every principal shares one brain-wide key, so each key gets the largest value any scope needs.needed.set(row.config_key, Math.max(needed.get(row.config_key) ?? 0, value));}- // Every principal shares one brain-wide key, so each key gets the largest value any scope needs.+ const anyPaused = resources.some(r => r.background_paused);const commands = [...needed].map(([key, value]) => `gbrain config set ${key} ${value}`);- const details = { exact: true, inspected: view.counters_read, truncated: false, resources, commands, ...(view.forecast ? { forecast: view.forecast } : {}) };- if (!resources.length) return { name: 'persistence_capacity', status: 'ok', message: 'Managed write capacity is below 80% of every cumulative limit.', details };- const [key, value] = [...needed][0]!;- return { name: 'persistence_capacity', status: 'warn', details,- fix: { argv: ['gbrain', 'config', 'set', key, String(value)], consent: [], actor: 'host_admin', requires_exclusive: false, verify: capacityVerify(),- why: 'Raises the limit on the brain host (reversible with gbrain config unset); admission refuses writes at the limit.', docs: 'docs/guides/concurrent-writes.md' },- message: `${resources.length} managed write limit(s) at or above 80%: ${resources.map(r =>- `${r.scope} ${r.resource} ${r.used}/${r.limit}`).join('; ')}. Admission refuses at the limit. Run on the brain host: ${commands.join('; ')} ` +- '(each covers about one more year at the current admission rate). This is a mitigation: permanent request IDs are never evicted.' };+ const details = { exact: true, inspected: counters.length, truncated: false, resources, commands, verify: VERIFY, docs: DOCS,+ background_pause_pct: Math.round(pause * 100), paused_producers: anyPaused ? [...BACKGROUND_PRODUCERS] : [],+ forecast: forecast ? { thresholds: forecast.thresholds, window_days: forecast.window_days, retention_days: forecast.retention_days,+ table_bytes: forecast.table_bytes, rows: forecast.rows } : { health: 'unknown' } };+ const thresholds = forecast?.thresholds;+ if (!resources.length) return { name: 'persistence_capacity', status: 'ok', details,+ message: thresholds ? `Managed write capacity is below ${thresholds.warn_pct}% of every cumulative limit and none runs out within ${thresholds.warn_days} days at its 7-day rate.`+ : 'Managed write capacity is below 80% of every cumulative limit.' };+ const [first] = [...needed];+ return { name: 'persistence_capacity', status: worst, details,+ fix: { argv: ['gbrain', 'config', 'set', first![0], String(first![1])], consent: [], actor: 'host_admin', requires_exclusive: false,- verify: doctorVerify('persistence_capacity'), docs: DOCS,++ verify: capacityVerify(), docs: DOCS,+ why: `Raises ${first![0]} to a value that covers about one more year at the 7-day rate; reversible with gbrain config unset.${commands.length > 1 ? ` Also run: ${commands.slice(1).join('; ')}.` : ''}` },+ message: `${resources.length} managed write limit(s) near exhaustion: ${resources.map(r => `${r.scope} ${r.resource} ${r.used}/${r.limit}`+ + ('days_to_exhaustion' in r && r.days_to_exhaustion !== null ? ` (about ${r.days_to_exhaustion} day(s) left at the 7-day rate, ${r.basis})` : '')).join('; ')}. `+ + `Admission refuses at the limit. Run on the brain host: ${commands.join('; ')} (each covers about one more year at the current admission rate), `+ + `then verify with ${VERIFY}. Permanent request IDs are never evicted.`+ + (anyPaused ? ` Background writes are paused past ${Math.round(pause * 100)}% (write_capacity_backpressure): ${BACKGROUND_PRODUCERS.join(', ')}; interactive writes keep the rest.` : '') };} catch (error) {return { name: 'persistence_capacity', status: 'warn',message: `Managed write capacity could not be read: ${error instanceof Error ? error.message : String(error)}. Health is unknown.`,diff --cc src/commands/doctor/checks/schema-health.tsindex b3a42205f3,7e46a02e50..c27ba2d1c6--- a/src/commands/doctor/checks/schema-health.ts+++ b/src/commands/doctor/checks/schema-health.ts@@@ -18,6 -18,8 +18,7 @@@ import { pgliteScaleCheck } from './engimport { checkParkedEffects } from './parked-effects.ts';import { checkManagedGuardSchemaDrift, checkPublicationRefusals } from './managed-guard.ts';import { checkWorktreeRefreshStuck } from './worktree-refresh.ts';-import { checkPersistenceCapacity } from './persistence-capacity.ts';-import { checkPersistenceCompaction, checkPersistenceCounterDrift } from './persistence-compaction.ts';++import { checkPersistenceCounterDrift } from './persistence-compaction.ts';import { checkPostgresCancellationDriver } from './postgres-cancellation.ts';import { checkProjectionReadiness } from './projection-readiness.ts';import type { Check } from '../../doctor.ts';@@@ -44,9 -46,10 +45,9 @@@ async function runPgvector(ctx: DoctorCchecks.push(await pagesUpsertArbiterCheck(engine));checks.push(await checkProjectionReadiness(engine));- // 4a-bis. Parked postcommit effects (#5612); managed write capacity is an ops entry (checks/ops-sections.ts).- // 4a-bis. Managed write capacity (#5470) and parked postcommit effects (#5612).- progress.heartbeat('persistence_capacity');- checks.push(await checkPersistenceCapacity(engine), await checkPersistenceCompaction(engine), await checkPersistenceCounterDrift(engine),- await checkParkedEffects(engine), await checkWorktreeRefreshStuck(engine));++ // 4a-bis. Parked postcommit effects (#5612) and receipt-bytes counter drift (#6696 A10); capacity and compaction are ops entries (checks/ops-sections.ts).+ progress.heartbeat('parked_effects');- checks.push(await checkParkedEffects(engine), await checkWorktreeRefreshStuck(engine));++ checks.push(await checkPersistenceCounterDrift(engine), await checkParkedEffects(engine), await checkWorktreeRefreshStuck(engine));// #5983/#5974: schema drift on guarded tables and writes the database refused.checks.push(await checkManagedGuardSchemaDrift(engine), await checkPublicationRefusals(engine));@@@ -73,6 -76,9 +74,7 @@@ export const pgvectorEntry: DoctorEntr'postgres_cancellation_driver','pages_upsert_arbiter','text_projection_readiness',- 'persistence_capacity',- 'persistence_compaction',+ 'persistence_counter_drift','parked_effects','worktree_refresh_stuck','managed_guard_schema_drift',diff --cc src/commands/doctor/registry.tsindex f180b908a2,78a9020c1f..fccbfaa984--- a/src/commands/doctor/registry.ts+++ b/src/commands/doctor/registry.ts@@@ -109,20 -108,9 +109,20 @@@ import { chatFallbackChainEntry } fromimport { providerConsentEntry } from './checks/provider-consent.ts';import { behaviorChangesEntry } from './checks/behavior-changes.ts';import { fenceIntegrityEntry } from './checks/fence-integrity.ts';+import { ghostPagesEntry } from './checks/ghost-pages.ts';import { managedSyncMovementEntry } from './checks/managed-sync-movement.ts';import { atomHeldFailedEntry } from './checks/atom-holds.ts';-import { STOP_DOCTOR, type DoctorContext, type DoctorEntry } from './context.ts';+import {+ persistenceCapacityEntry,+ terminalFailuresEntry,- receiptCompactionEntry,++ persistenceCompactionEntry,+ schemaPackConsistencyEntry,+} from './checks/ops-sections.ts';+import { STOP_DOCTOR, type DoctorContext, type DoctorEntry, type DoctorTier } from './context.ts';+import {+ BUDGET_EXPIRED, DoctorBudgetError, budgetExpired, type BudgetExpired, ENTRY_BUDGET_KEY, ENTRY_BUDGET_MS_DEFAULT, budgetUnknownCheck, deadlineEngine, entryRunsAt,+ opsNotApplicableCheck, raceBudget,+} from './budget.ts';import type { Check } from '../doctor.ts';import { infoCheck } from './check-fix.ts';import { withGitListingCache } from '../../core/git-visible-files.ts';@@@ -150,14 -138,6 +150,14 @@@ export const DOCTOR_CHECK_REGISTRY: readbChecksGateEntry,connectionEntry,connectionGateEntry,+ // #6696 B1: ops sections first (`tier: 'ops'`), so a default run answers them before the slower checks.+ persistenceCapacityEntry,+ terminalFailuresEntry,+ managedSyncMovementEntry,- receiptCompactionEntry,++ persistenceCompactionEntry,+ serveBuildDriftEntry,+ schemaPackConsistencyEntry,+ embeddingStateEntry,pgvectorEntry,rlsEntry,schemaVersionEntry,diff --cc src/commands/repair.tsindex a85bd7baef,50a6dd732a..463557b2cf--- a/src/commands/repair.ts+++ b/src/commands/repair.ts@@@ -63,11 -64,12 +64,13 @@@ export const REPAIR_HELP = `Usage: gbra[--apply --expect <preview-hash> --yes] [--json]gbrain repair fences [--source <id>] [--only <path>]... [--skip <path>]... [--slug <slug>]... [--diff][--no-llm] [--max-usd <n>] [--apply [--expect <preview-hash>]] [--limit <n>] [--json]+ gbrain repair receipt-compaction [--older-than <72h|30d>] [--include-failures] [--force]+ [--apply --expect <preview-hash> --yes] [--limit <n>] [--json]gbrain repair file-drift --source <id> (--slug <slug>... | --request <id>... | --all-drifted [--class <name>])- --prefer file|database [--apply --expect <preview-hash>] [--json]+ [--only <glob>]... [--skip <glob>]... --prefer file|database [--apply --expect <preview-hash>] [--json]gbrain repair stuck-recovery [--source <id>] [--request-id <uuid>][--keep prior|disk --apply --expect <preview-hash> --yes] [--json]+ gbrain repair ghost-pages --source <id> [--apply --expect <preview-hash> --yes] [--json]${REPAIR_CONTENT_HELP}Repair residual damage that \`gbrain doctor\` reports. Dry run unless --apply.@@@ -119,16 -118,16 +122,17 @@@ run gbrain doctor --remediate --yes --iWith no kind, previews every kind. Run it on the brain host.Held files (the content lane, then the two-pass frontmatter repair): docs/guides/repair.md#held-files.Malformed facts/takes fences (preview, apply, undo): docs/guides/repair.md#fences.-A write recovery blocked on unexpected_file_bytes: docs/guides/repair.md#stuck-recovery.`;+A write recovery blocked on unexpected_file_bytes: docs/guides/repair.md#stuck-recovery.+Live pages whose canonical file is missing (ghost pages): docs/guides/repair.md#ghost-pages.`;- const BOOLEAN_FLAGS = new Set(['--apply', '--all', '--json', '--no-embed', '--include-ambiguous', '--diff', '--yes', '--no-llm', '--all-drifted']);- const VALUE_FLAGS = new Set(['--source', '--limit', '--expect', '--only', '--skip', '--slug', '--max-usd', '--prefer', '--request', '--class', '--keep', '--request-id']);+ const BOOLEAN_FLAGS = new Set(['--apply', '--all', '--json', '--no-embed', '--include-ambiguous', '--diff', '--yes', '--no-llm', '--all-drifted', '--include-failures', '--force']);+ const VALUE_FLAGS = new Set(['--source', '--limit', '--expect', '--only', '--skip', '--slug', '--max-usd', '--prefer', '--request', '--class', '--keep', '--request-id', '--older-than']);/** Flags only some kinds accept, with the kinds that do. */const KIND_FLAGS: Record<string, readonly string[]> = {- '--only': ['frontmatter', 'fences', 'slug-conflicts', CONTENT_LANE], '--skip': ['frontmatter', 'fences', 'slug-conflicts', CONTENT_LANE], '--diff': ['frontmatter', 'fences', 'slug-conflicts', CONTENT_LANE], '--yes': ['frontmatter', 'conversation-labels', 'stuck-recovery'],+ '--only': ['frontmatter', 'fences', 'slug-conflicts', 'file-drift', CONTENT_LANE], '--skip': ['frontmatter', 'fences', 'slug-conflicts', 'file-drift', CONTENT_LANE], '--diff': ['frontmatter', 'fences', 'slug-conflicts', CONTENT_LANE], '--yes': ['frontmatter', 'conversation-labels', 'stuck-recovery', 'ghost-pages'],'--slug': ['fences', 'file-drift'], '--prefer': ['file-drift'], '--request': ['file-drift'], '--all-drifted': ['file-drift'], '--class': ['file-drift'],'--keep': ['stuck-recovery'], '--request-id': ['stuck-recovery'],+ '--older-than': ['receipt-compaction'], '--include-failures': ['receipt-compaction'], '--force': ['receipt-compaction'],};const VALUE_EXAMPLES: Record<string, string> = { '--source': 'default', '--limit': '50', '--expect': 'PLAN_HASH', '--only': 'notes/a.md', '--skip': 'notes/a.md','--slug': 'notes/a', '--max-usd': '0.50', '--prefer': 'file', '--request': 'REQUEST_UUID', '--class': 'review_required', '--keep': 'prior',@@@ -219,8 -199,16 +225,13 @@@ export function parseRepairArgs(args: s}else if (flag === '--request') parsed.requests.push(value);else if (flag === '--class') parsed.driftClass = value;+ else if (flag === '--older-than') {+ if (!OLDER_THAN_RE.test(value)) throw invalid(`--older-than takes hours (72 or 72h) or days (30d) (got "${value}").`, 'Pass the age, e.g. --older-than 30d.',+ ['gbrain', 'repair', 'receipt-compaction', '--json']);+ parsed.olderThan = value;+ }- else if (flag === '--keep') {- if (value !== 'prior' && value !== 'disk') throw invalid(`--keep must be prior or disk (got "${value}").`,- 'Pass --keep prior to write the recorded prior bytes back, or --keep disk to keep the bytes on disk; the preview lists which are available.', ['gbrain', 'repair', 'stuck-recovery', '--json']);- parsed.keep = value;- } else if (flag === '--request-id') {+ else if (flag === '--keep') keepText = value;+ else if (flag === '--request-id') {if (!/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(value)) throw invalid(`--request-id must be a request UUID (got "${value}").`,'Pass the request_id the stuck-recovery preview (or gbrain sources writer status --json) lists, e.g. --request-id 123e4567-e89b-42d3-a456-426614174000.', ['gbrain', 'repair', 'stuck-recovery', '--json']);parsed.requestId = value.toLowerCase();diff --cc src/commands/sync-delegate.tsindex 972fbcc466,7a86262056..ba678ae6ef--- a/src/commands/sync-delegate.ts+++ b/src/commands/sync-delegate.ts@@@ -582,13 -577,11 +582,14 @@@ export async function maybeDelegateManaconst hard = await deriveDelegatedTimeoutSeconds(args, { env });const timeoutSeconds = soft && soft > 0 ? (hard > 0 ? Math.min(soft, hard) : soft) : hard;const options: DelegatedSyncOptions = {- sourceId, timeoutSeconds,+ // #6696 (A5): an operator's sync keeps the capacity background producers leave free.+ sourceId, timeoutSeconds, origin: 'interactive',...pick(opts, ['dryRun', 'full', 'noPull', 'noEmbed', 'noExtract', 'noSchemaPack', 'skipFailed', 'retryFailed', 'includeGitignored', 'noBulk'] as const),...(opts.lanes !== undefined ? { lanes: opts.lanes } : {}),- ...(opts.explicitProcessing?.length ? { explicitProcessing: [...opts.explicitProcessing] } : {}),+ // #6696: an empty list crosses the wire (a flagless run adopts the cursor's options); a caller that set none is strict, as in-process.+ explicitProcessing: [...opts.explicitProcessing ?? DELEGATED_SYNC_PROCESSING_KEYS],+ // Sent only when set, so a serve that predates the field keeps accepting every run without a deferral.+ ...(opts.embedDeferred ? { embedDeferred: true } : {}),};const clientToken = randomUUID();const { probeLiveFullConsumer, consumerIdentity } = await import('../core/persistence/consumer-heartbeat.ts');diff --cc src/commands/sync.tsindex f28e9bb29f,8d92c08a69..e22dbaa073--- a/src/commands/sync.ts+++ b/src/commands/sync.ts@@@ -174,10 -174,10 +174,12 @@@ export interface SyncOpts* Threaded through performSync AND syncOneSource so `sync --all` honors it.*/noSchemaPack?: boolean;+ /** #6696 (A7): server-only; the drain's first pass checks the run's estimated receipts against the capacity left before admitting. */+ capacityPreflight?: boolean;/** Processing options this caller set; an unfinished managed cursor supplies the rest (unset = all explicit). */explicitProcessing?: Array<'noEmbed' | 'noExtract' | 'noSchemaPack'>;+ /** #6696: a runtime paid-work constraint (the cost gate deferred this run's embedding); never a processing option, never lifted by cursor adoption. */+ embedDeferred?: boolean;/*** v0.18.0 Step 5 — sync a specific named source. When set, sync reads* local_path + last_commit from the sources table (not the globaldiff --cc src/core/behavior-change-notice.tsindex f02050e854,e5210b0c53..d90c9336d7--- a/src/core/behavior-change-notice.ts+++ b/src/core/behavior-change-notice.ts@@@ -561,26 -561,6 +561,26 @@@ export const BEHAVIOR_CHANGES: Readonly// #6650 L0 (convergence harness fixes). `since` is a placeholder equal to the branch's VERSION until the merge-slot stamp.{ since: '0.60.223.0', text: 'On Linux, a `gbrain sync` started after another gbrain process on the same machine was killed no longer treats the dead process\'s heartbeat as a live write owner. Before, it refused to hand its catch-up to the running `gbrain serve` for up to 30 s and ran its own consumer next to it; now it hands the catch-up to the serve (or runs its own consumer when no serve is running). A waiter-only consumer deferring to the dead process promotes on its next check instead of after 60 s. A heartbeat row from another host or container, or from an older gbrain, keeps the time-only rule, as does every row where `/proc` is unavailable.' },{ since: '0.60.223.0', text: 'On Linux, when the process holding write claims on this host is killed, another consumer on the same machine now reclaims those claims within about 5 s instead of waiting out their lease (up to `persistence.publication_ceiling_ms` plus about 65 s, so about 365 s by default). Only claims with no recovery record and no publication started are taken, the same guard an expired claim has. An owner that is alive, however slow, or on another host or container keeps its full lease.' },+ // #6696 PR C (GBRA-93 lane C). `since` is a placeholder equal to the branch's VERSION until the merge-slot stamp.+ { since: '0.60.229.0', text: '`gbrain sources writer failures`, `gbrain write-request`, `gbrain sync status` and doctor `persistence_terminal_failures` now report a write refused because its page\'s canonical file is missing (a ghost page) as category `canonical_file_missing`, whose fix previews `gbrain repair ghost-pages --source <id>`, instead of a sync retry that refuses the same way. A `fence_unrenderable` fact-fence adoption refusal is its own category, and one written by a build older than 0.60.218.0 (the release that stopped the adoption loop) counts as historical and no longer warns.' },+ { since: '0.60.229.0', text: '`gbrain apply-migrations` no longer prints "All migrations up to date" (exit 0) while a migration is wedged (3 or more consecutive partial runs) and no newer migration has run past it. It exits 1 with `migrations_pending` reason `wedged` and a fix to ask the user about (`gbrain apply-migrations --force-retry <version>` after fixing the cause); `--list` names the wedged migration and its clearing command, `--list --json` adds a `wedged` list, `gbrain post-upgrade` exits non-zero and `gbrain upgrade` prints `Migrations: wedged` instead of `Migrations: complete`.' },+ { since: '0.60.229.0', text: '`gbrain repair file-drift` now takes `--only <path>` and `--skip <path>` (repeatable; source-relative canonical file paths: a value without `*` is an exact path, and on file-drift only a glob takes `*` within a segment and `**` across segments, so `--only \'concepts/**\'` selects every drifted page filed under concepts/). The globs narrow the selection before the mixed-class check, are bound into the preview hash and appear in the printed apply command, so running that command applies exactly the previewed pages; an apply under other globs refuses `preview_changed`. `--keep` on file-drift is now refused with a pointer at `--prefer database` (keep the database copy) or `--prefer file`, instead of the stuck-recovery value error.' },+ { since: '0.60.229.0', text: 'gbrain.yml `storage:` accepts an opt-in `keep_db:` list of directory prefixes. On the canonical owner host, the resident `gbrain serve`, `gbrain jobs` or `gbrain autopilot` consumer reconciles each drifted page under those prefixes with the database copy (the `gbrain repair file-drift --prefer database` resolution, inside reconcile\'s protections and backups), at most 10 requests every 10 minutes, never twice for the same drift and never past 90% of the write-quota stop line; other hosts and remote or caller writes are unchanged and keep refusing `source_changed`. Doctor `maintenance_write_drift` echoes each declared policy with how many drifted pages it matches and their receipt cost. An unknown key under `storage:` now prints a warning instead of being ignored silently.' },+ { since: '0.60.229.0', text: '`gbrain repair content` (the `slug-conflicts` kind) now judges a held `frontmatter_slug_conflict` file with the same screen managed sync froze it with. A held file sync would now import as it is (its `slug:` line names the file\'s own page, or it no longer conflicts) is listed as `import` and imported unchanged, clearing the hold only while it is still the observation the repair read; before, it was skipped as `already_exempt` or `already_clean` and the hold stayed. A file in a source that is a subdirectory of its Git repository now loses its stray `slug:` line instead of being held `still_invalid`. A file sync would hold whatever the repair writes is now held `slug_page_mismatch` naming both slugs, instead of the generic `still_invalid` or `already_exempt` (an alias to the file\'s own page is one).' },+ { since: '0.60.229.0', text: 'A managed `gbrain sync` whose final checkpoint committed no longer ends `blocked` / `drain_stalled` / `no_admission` (with advice to move the database to port 5432) while it finishes planner statistics and link extraction. That tail now has its own budget: link extraction stops after 5 minutes and leaves the remaining pages for `gbrain extract --stale`, and a tail that is still stuck 30 s later stops `no_progress` at step `finish`. A run stuck before admission still stops `no_admission` after 5 minutes.' },+ { since: '0.60.229.0', text: 'New doctor check `serve_build_drift` (ops): on a managed Postgres brain it warns "serve is running an older build than this checkout; restart serve and workers" when a live `serve`, jobs worker, autopilot, sync or MCP process on this host reports an older gbrain version in its consumer heartbeat than the binary running doctor. The fix names the installed serve service\'s restart (`systemctl --user restart gbrain-serve.service` or `launchctl kickstart -k gui/<uid>/com.gbrain.serve`), or the pid to stop and start again, and the verify is `gbrain doctor --only serve_build_drift --json`. Nothing restarts automatically; PGLite reads ok.' },+ { since: '0.60.229.0', text: 'A `gbrain sync` handed to a running `gbrain serve` on a managed brain now treats processing options as the in-process sync does. With no `--no-embed` / `--no-extract` / `--no-schema-pack` flag it adopts an unfinished run\'s stored options instead of refusing `invalid_params`; an older CLI that omits the explicit-flag list counts each processing flag it sends as true as typed. The resident-owner lane of a PGLite brain follows the same rule and keeps an explicit list it is sent. A cost-gate embedding deferral stays a property of that run, so resuming a run that stored embedding on embeds nothing in it. A source with a configured strategy now gets one cursor for `gbrain sync --all`, a single-source sync, the cycle and a delegated run; an unfinished run under the old key finishes under that key first.' },+ { since: '0.60.229.0', text: '`--skip-failed` and `--include-gitignored` on a managed source now refuse with `managed_sync_flag_refused`, naming the flag, before anything runs: at `gbrain sync` parse (`--all` included), before a hand-off to `gbrain serve`, and for jobs, MCP and the cycle. Before, the refusal was `writer_coordinator_required` "cannot bypass ignored-file or failed-receipt guards", raised later. Rerun without the flag.' },+ { since: '0.60.229.0', text: '`gbrain sync --retry-failed` on a managed source now prints, for each failure held under another run\'s options, its class and the command that settles it: `resumable` (a replay of the unfinished run, or a fresh discovery under the failed run\'s options, labelled apart), `safely orphaned` (the `gbrain repair managed-sync-orphans` preview) or `unresolved` (what has to finish first). A failure recorded before runs kept their options no longer prints "with the same options as the failed run (this receipt no longer records them)"; its options are recovered when an option set reproduces its cursor key exactly.' },+ // #6696 PR B (GBRA-93 lane B). `since` is a placeholder equal to the branch's VERSION until the merge-slot stamp.- { since: '0.60.229.0', text: '`gbrain doctor` now runs its operator sections (write capacity, unresolved write failures, managed sync movement, receipt compaction, serve build drift, schema-pack consistency) before the slower checks, and bounds every other check by `doctor.entry_budget_ms` (default 15000). A check that does not finish in time is a warn with `details.health: "unknown"` and `reason: "budget"` and a command to rerun it alone, instead of holding the whole run; every check reports `elapsed_ms`. Above `doctor.orphan_ratio.full_scan_max_pages` pages (default 50000) `orphan_ratio` is a sampled estimate marked `estimated: true`; `gbrain doctor --tier deep` scans fully. New: `gbrain doctor --tier ops` runs only the operator sections under a 4000 ms deadline (`--budget-ms` changes it) and reports `complete`, `unknown_sections` and `elapsed_ms`; on PGLite the sections that need a Postgres serve read `not_applicable`. New check `receipt_compaction` warns when receipts were last compacted more than 24 hours ago while a persistence consumer is live, and the local doctor now runs `schema_pack_consistency` (pages whose type the source\'s schema pack neither declares nor aliases), which only the remote `run_doctor` report ran before.' },++ { since: '0.60.229.0', text: '`gbrain doctor` now runs its operator sections (write capacity, unresolved write failures, managed sync movement, receipt compaction (`persistence_compaction`), serve build drift, schema-pack consistency) before the slower checks, and bounds every other check by `doctor.entry_budget_ms` (default 15000). A check that does not finish in time is a warn with `details.health: "unknown"` and `reason: "budget"` and a command to rerun it alone, instead of holding the whole run; every check reports `elapsed_ms`. Above `doctor.orphan_ratio.full_scan_max_pages` pages (default 50000) `orphan_ratio` is a sampled estimate marked `estimated: true`; `gbrain doctor --tier deep` scans fully. New: `gbrain doctor --tier ops` runs only the operator sections under a 4000 ms deadline (`--budget-ms` changes it) and reports `complete`, `unknown_sections` and `elapsed_ms`; on PGLite the sections that need a Postgres serve read `not_applicable`. The local doctor now runs `schema_pack_consistency` (pages whose type the source\'s schema pack neither declares nor aliases), which only the remote `run_doctor` report ran before.' },+ { since: '0.60.229.0', text: 'A thin client\'s `gbrain doctor --tier ops` or `gbrain doctor --only <check>` now asks the remote serve instead of running the thin-client connectivity checks with `--only` ignored: an admin token gets `run_doctor` with `tier: "ops"` / `only`, a read token gets the new read-scope MCP operation `get_brain_health` (write capacity as `ok|low|critical` with a days band, write failures, unsearchable chunks and ghost pages as count bands for the sources it can read, no slugs or exact counts, cached 60 s), and a serve older than this release refuses with `doctor_tier_unavailable` naming `gbrain doctor --tier ops --json` on the brain host. `get_brain_health` is also the MCP verify of the capacity and `maintenance_backpressure` fixes.' },+ { since: '0.60.229.0', text: 'New doctor check `embedding_state` (brain, runs on the ops tier) counts where indexed text stands against the active embedding column: embedded, pending, keyword_only (embed_skip pages, by design), quarantined, empty, chunks on deleted pages and chunkless pages. It warns only on chunks of pages soft-deleted more than 72 hours ago (`deleted_page_chunks_overdue`, fix `gbrain pages purge-deleted`) and, on a keyed brain, on live pages with body text but no chunk rows (`chunkless_pages_healable`, fix `gbrain embed --stale`); the pending backlog stays the `embeddings` check\'s warning and quarantined pages stay `quarantined_pages`\'. On the ops tier a brain whose active embedding column has no partial index `WHERE <column> IS NULL` reports `unknown` (`embedding_state_unknown`) instead of scanning. Check with `gbrain doctor --only embedding_state --json`.' },+ { since: '0.60.229.0', text: 'New read-only `gbrain pages unsearchable --source <id> [--state <state>] [--limit N] [--json]` lists the pages search cannot fully see, one row per page and embedding state with its reason, chunk count, bytes and fix; an unknown `--state` refuses with `invalid_params` naming the valid states.' },+ // #6696 PR B5 (GBRA-93 lane B, ghost pages). `since` is a placeholder equal to the branch's VERSION until the merge-slot stamp.+ { since: '0.60.229.0', text: 'New doctor check `ghost_pages`: on a source\'s canonical owner host it counts live pages whose canonical file is missing (ghost pages: every write to them refuses `source_changed` with reason `canonical_file_missing` and no sync can import them) and names the read-only `gbrain repair ghost-pages --source <id>` preview. Off the owner host, or on a brain with no source checkout, it is `ok` (info, not applicable); an unreadable checkout warns with health unknown. `gbrain pages ghosts --source <id> [--json]` lists them, read-only. `undeclared_db_only_pages` is unchanged.' },+ { since: '0.60.229.0', text: 'New explicit-only repair kind `gbrain repair ghost-pages --source <id>`: the preview lists each ghost page with its recorded canonical path and revision and prints the apply command with its hash; `--apply --expect <hash> --yes` soft-deletes exactly that set (without `--yes` a non-interactive run exits 3 with the consent payload and changes nothing). It refuses off the owner host (`not_owner_host`), on an unreadable checkout (`ghost_storage_unknown`), and when ghosts are more than half of a source\'s file-backed pages (`ghost_mass_delete_refused`, unless `GBRAIN_ALLOW_MASS_RECONCILE=1`); a page whose file came back before the apply is kept. Removed pages are purged after 72 h; `gbrain restore <slug> --force` undoes one until then. Sync never removes ghost pages by itself.' },+ { since: '0.60.229.0', text: 'A coordinated write refused because the page\'s canonical file is missing now carries `detail: canonical_file_missing` (message unchanged), and the live file check behind the conflict audit, maintenance and doctor reports reason `canonical_file_missing` for such a page instead of `file_missing`; other `source_changed` refusals keep `file_missing`.' },// GBRA-96 (default reranker). `since` is a placeholder equal to the branch's VERSION until the merge-slot stamp.{ since: '0.60.228.0', text: 'The default search reranker is now Voyage `rerank-3-lite` instead of `rerank-2.5`, for brains that never set `search.reranker.model` (a brain that set one keeps it). In gbrain-evals #148 (v0.10.93) it cut rerank cost 60% at the same 50 candidates × 1,400 tokens, with retrieval quality within noise. To go back: `gbrain config set search.reranker.model voyage:rerank-2.5`.' },// #6650 follow-up (group follower stamps). `since` is a placeholder equal to the branch's VERSION until the merge-slot stamp.diff --cc src/core/cli-flag-registry.generated.tsindex 0ef2bd70cc,118b948d0d..33e4640478--- a/src/core/cli-flag-registry.generated.ts+++ b/src/core/cli-flag-registry.generated.ts@@@ -47,7 -47,7 +47,7 @@@ export const CLI_FLAG_REGISTRY: Record<'creds': ['--allow-create-db', '--allow-docker', '--brain', '--chat-model', '--content-root', '--db-only', '--embedding-dimensions', '--embedding-model', '--expansion-model', '--force', '--git', '--grant-types', '--help', '--http', '--ids', '--issuer-url', '--json', '--key', '--local-postgres', '--mcp-only', '--mcp-url', '--migrate-only', '--model', '--no-embedding', '--no-git', '--non-interactive', '--oauth-client-id', '--oauth-client-secret', '--out', '--passphrase-env', '--path', '--pglite', '--plan', '--prefer-postgres', '--provenance', '--provider', '--query', '--schema-pack', '--scopes', '--search-mode', '--skip-embed-check', '--source', '--status', '--supabase', '--surface', '--to', '--url', '--version'],'db-repair': ['--accept-pending', '--apply', '--apply-rewrites', '--background', '--brain', '--break-lock', '--db-url', '--dry-run', '--explain', '--filter', '--follow', '--force', '--force-retry', '--format', '--help', '--http', '--json', '--locks', '--name', '--no-accept-pending', '--path', '--prefer-postgres', '--probe', '--progress-interval', '--progress-json', '--quiet', '--remediate', '--restart', '--skip-verify', '--source', '--supabase', '--timeout', '--undo-last-rewrite', '--url', '--version', '--wait', '--yes'],'decide': ['--accept-all', '--all', '--all-from', '--apply', '--brain', '--call-site', '--dataset', '--dry-run', '--egress', '--embedding-dimensions', '--embedding-model', '--expect', '--from', '--help', '--include-withdrawals', '--input', '--json', '--kind', '--limit', '--max-cost', '--max-usd', '--min', '--non-interactive', '--out', '--provenance', '--provider', '--query', '--rate', '--reason', '--reason-family', '--recommended', '--remove', '--shadow', '--since', '--slot', '--source', '--status', '--suite', '--target', '--threshold', '--trust', '--undo', '--uri-prefix', '--version', '--what-if-threshold', '--yes'],- 'doctor': ['--abandon', '--abbrev-ref', '--accept-pending', '--access', '--acknowledge-managed', '--add', '--admin-intent', '--adopt', '--adopt-columns', '--adopt-permissions', '--all', '--all-drifted', '--all-from', '--allow-old-serve', '--allow-shell-jobs', '--allow-unverified-remote', '--allowed-operations', '--apply', '--apply-rewrites', '--assign-corpus', '--audit', '--auto', '--auto-fix', '--autostash', '--background', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--branch', '--break-lock', '--budget-ms', '--budget-usd', '--by-mention', '--cached', '--call-site', '--catch-up', '--check', '--class', '--client', '--concurrency', '--confidence', '--confirm', '--confirm-quiesced', '--confirm-relocated-root', '--conflicts', '--contacts-dir', '--content-audit', '--content-root', '--count', '--dataset', '--db-url', '--delegated-namespace', '--delegated-slug-prefixes', '--delete-brain', '--dest', '--detach', '--diff-filter', '--dim', '--dir', '--disable', '--drain', '--drain-timeout', '--dry-run', '--egress', '--embedding-dimensions', '--embedding-model', '--enable', '--enable-dcr', '--end-of-options', '--env', '--error-unmatch', '--exclude', '--exclude-standard', '--expand', '--expect', '--expect-remote', '--expected-epoch', '--expected-revision', '--expected-state', '--explain', '--facts', '--fast', '--federated-read', '--fetch-timeout-ms', '--ff-only', '--file', '--fix', '--follow', '--force', '--force-rechunk', '--force-retry', '--force-schema', '--format', '--fresh', '--from', '--from-meetings', '--from-pages', '--full', '--fuzzy', '--get', '--git-common-dir', '--git-dir', '--git-path', '--group', '--group-by', '--hard', '--hard-deadline', '--harness', '--help', '--home', '--http', '--id', '--if-version', '--ignore-env-override', '--images', '--include-ambiguous', '--include-deleted', '--include-flagged', '--include-gitignored', '--include-hidden', '--include-pseudo', '--include-repairs', '--include-withdrawals', '--index-audit', '--init', '--input', '--install', '--is-ancestor', '--is-inside-work-tree', '--job-isolation', '--jq', '--json', '--keep', '--lanes', '--lang', '--left-right', '--limit', '--link-source', '--link-type', '--list', '--local', '--local-env-vars', '--locks', '--log-noop', '--manifest', '--markdown', '--max-cost', '--max-cost-usd', '--max-jobs', '--max-rss', '--max-runtime', '--max-usd', '--max-waiting', '--mcp-only', '--migrate-legacy', '--migrate-only', '--migration', '--min', '--mode', '--multimodal', '--name', '--name-only', '--nice', '--no-accept-pending', '--no-autopilot-install', '--no-autostash', '--no-capture', '--no-confirm', '--no-cron', '--no-delegate', '--no-edit', '--no-embed', '--no-embedding', '--no-expand', '--no-extract', '--no-hooks', '--no-lanes', '--no-llm', '--no-migrate', '--no-pull', '--no-renames', '--no-repair', '--no-schema-pack', '--no-seat', '--no-tags', '--no-verify', '--non-interactive', '--now', '--once', '--only', '--operations', '--others', '--out', '--output', '--overwrite', '--page', '--parallel', '--params', '--pat-file', '--path', '--path-format', '--pglite', '--phase', '--pid-file', '--plan', '--porcelain', '--port', '--prefer', '--prefer-postgres', '--preset', '--preview', '--probe', '--probe-pglite', '--profile', '--progress-interval', '--progress-json', '--project', '--provider', '--providers', '--prune-orphans', '--public-url', '--pull', '--pure', '--purge', '--push-only', '--query', '--question', '--queue', '--quiet', '--rate', '--reauth', '--rebase', '--recommended', '--reference-date', '--refresh', '--refresh-operations', '--refresh-skills', '--regenerate', '--reissue', '--relative', '--remediate', '--remediation-plan', '--remove', '--remove-core', '--repair', '--replace', '--repo', '--request', '--request-id', '--require-clean', '--reranker', '--reset', '--reset-checkpoint', '--reset-default', '--resolve', '--restore-only', '--resume', '--retry-failed', '--reverse', '--review-lower', '--revision', '--rollback-to-source', '--scope', '--scopes', '--search-mode', '--seat', '--section', '--select', '--self-transfer', '--session', '--set', '--set-upstream-to', '--shadow', '--short', '--show-current', '--show-prefix', '--show-token', '--show-toplevel', '--since', '--skills-dir', '--skip', '--skip-bare-tweet', '--skip-failed', '--skip-urls', '--skip-verify', '--slot', '--slug', '--slugs', '--source', '--source-id', '--sources', '--src-subpath', '--staged', '--stale', '--state', '--status', '--stdin', '--strategy', '--strict', '--suite', '--supabase', '--surface', '--symbol-kind', '--symbolic-full-name', '--takes-holders', '--target', '--target-score', '--threshold', '--tier', '--timeout', '--to', '--token', '--token-ttl', '--top-k', '--trust', '--type', '--uninstall', '--unsafe-bypass-dream-guard', '--unset-all', '--untracked-files', '--url', '--url-env', '--user', '--vectors', '--verbose', '--verify', '--version', '--wait', '--wait-drain', '--warn-only', '--what-if-threshold', '--window', '--workers', '--working-tree', '--workspace', '--yes'],- 'doctor': ['--abandon', '--abbrev-ref', '--accept-pending', '--access', '--acknowledge-managed', '--add', '--admin-intent', '--adopt', '--adopt-columns', '--adopt-permissions', '--all', '--all-drifted', '--all-from', '--allow-old-serve', '--allow-shell-jobs', '--allow-unverified-remote', '--allowed-operations', '--apply', '--apply-rewrites', '--assign-corpus', '--audit', '--auto', '--auto-fix', '--autostash', '--background', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--branch', '--break-lock', '--budget-ms', '--budget-usd', '--by-mention', '--cached', '--call-site', '--catch-up', '--check', '--class', '--client', '--concurrency', '--confidence', '--confirm', '--confirm-quiesced', '--confirm-relocated-root', '--conflicts', '--contacts-dir', '--content-audit', '--content-root', '--count', '--dataset', '--db-url', '--delegated-namespace', '--delegated-slug-prefixes', '--delete-brain', '--dest', '--detach', '--diff-filter', '--dim', '--dir', '--disable', '--drain', '--drain-timeout', '--dry-run', '--egress', '--embedding-dimensions', '--embedding-model', '--enable', '--end-of-options', '--env', '--error-unmatch', '--exclude', '--exclude-standard', '--expand', '--expect', '--expect-remote', '--expected-epoch', '--expected-revision', '--expected-state', '--explain', '--facts', '--fast', '--federated-read', '--fetch-timeout-ms', '--ff-only', '--file', '--fix', '--follow', '--force', '--force-rechunk', '--force-retry', '--force-schema', '--format', '--fresh', '--from', '--from-meetings', '--from-pages', '--full', '--get', '--git-common-dir', '--git-dir', '--git-path', '--group', '--group-by', '--hard', '--hard-deadline', '--harness', '--help', '--home', '--http', '--id', '--if-version', '--ignore-env-override', '--images', '--include-ambiguous', '--include-failures', '--include-flagged', '--include-gitignored', '--include-hidden', '--include-pseudo', '--include-repairs', '--include-withdrawals', '--index-audit', '--init', '--input', '--install', '--is-ancestor', '--is-inside-work-tree', '--job-isolation', '--jq', '--json', '--keep', '--lanes', '--lang', '--left-right', '--limit', '--link-source', '--link-type', '--list', '--local', '--local-env-vars', '--locks', '--log-noop', '--manifest', '--markdown', '--max-cost', '--max-cost-usd', '--max-jobs', '--max-rss', '--max-runtime', '--max-usd', '--max-waiting', '--mcp-only', '--migrate-legacy', '--migrate-only', '--migration', '--min', '--mode', '--multimodal', '--name', '--name-only', '--nice', '--no-accept-pending', '--no-autopilot-install', '--no-autostash', '--no-capture', '--no-confirm', '--no-cron', '--no-delegate', '--no-edit', '--no-embed', '--no-embedding', '--no-expand', '--no-extract', '--no-hooks', '--no-lanes', '--no-llm', '--no-migrate', '--no-pull', '--no-renames', '--no-repair', '--no-schema-pack', '--no-seat', '--no-tags', '--no-verify', '--non-interactive', '--older-than', '--once', '--only', '--operations', '--others', '--out', '--output', '--overwrite', '--page', '--parallel', '--params', '--pat-file', '--path', '--path-format', '--pglite', '--phase', '--pid-file', '--plan', '--porcelain', '--port', '--prefer', '--prefer-postgres', '--preset', '--preview', '--probe', '--probe-pglite', '--profile', '--progress-interval', '--progress-json', '--project', '--provider', '--providers', '--prune-orphans', '--pull', '--pure', '--purge', '--push-only', '--query', '--question', '--queue', '--quiet', '--rate', '--reauth', '--rebase', '--recommended', '--reference-date', '--refresh', '--refresh-operations', '--refresh-skills', '--regenerate', '--reissue', '--relative', '--remediate', '--remediation-plan', '--remove', '--remove-core', '--repair', '--replace', '--repo', '--request', '--request-id', '--require-clean', '--reranker', '--reset', '--reset-checkpoint', '--reset-default', '--resolve', '--restore-only', '--resume', '--retry-failed', '--reverse', '--review-lower', '--revision', '--rollback-to-source', '--scope', '--scopes', '--search-mode', '--seat', '--section', '--select', '--self-transfer', '--session', '--set', '--set-upstream-to', '--shadow', '--short', '--show-current', '--show-prefix', '--show-token', '--show-toplevel', '--since', '--skills-dir', '--skip', '--skip-bare-tweet', '--skip-failed', '--skip-urls', '--skip-verify', '--slot', '--slug', '--slugs', '--source', '--source-id', '--sources', '--src-subpath', '--staged', '--stale', '--status', '--stdin', '--strategy', '--strict', '--suite', '--supabase', '--surface', '--symbol-kind', '--symbolic-full-name', '--takes-holders', '--target', '--target-score', '--threshold', '--timeout', '--to', '--token', '--token-ttl', '--top-k', '--trust', '--type', '--uninstall', '--unsafe-bypass-dream-guard', '--unset-all', '--untracked-files', '--url', '--url-env', '--user', '--vectors', '--verbose', '--verify', '--version', '--wait', '--wait-drain', '--warn-only', '--what-if-threshold', '--window', '--workers', '--working-tree', '--workspace', '--yes'],++ 'doctor': ['--abandon', '--abbrev-ref', '--accept-pending', '--access', '--acknowledge-managed', '--add', '--admin-intent', '--adopt', '--adopt-columns', '--adopt-permissions', '--all', '--all-drifted', '--all-from', '--allow-old-serve', '--allow-shell-jobs', '--allow-unverified-remote', '--allowed-operations', '--apply', '--apply-rewrites', '--assign-corpus', '--audit', '--auto', '--auto-fix', '--autostash', '--background', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--branch', '--break-lock', '--budget-ms', '--budget-usd', '--by-mention', '--cached', '--call-site', '--catch-up', '--check', '--class', '--client', '--concurrency', '--confidence', '--confirm', '--confirm-quiesced', '--confirm-relocated-root', '--conflicts', '--contacts-dir', '--content-audit', '--content-root', '--count', '--dataset', '--db-url', '--delegated-namespace', '--delegated-slug-prefixes', '--delete-brain', '--dest', '--detach', '--diff-filter', '--dim', '--dir', '--disable', '--drain', '--drain-timeout', '--dry-run', '--egress', '--embedding-dimensions', '--embedding-model', '--enable', '--enable-dcr', '--end-of-options', '--env', '--error-unmatch', '--exclude', '--exclude-standard', '--expand', '--expect', '--expect-remote', '--expected-epoch', '--expected-revision', '--expected-state', '--explain', '--facts', '--fast', '--federated-read', '--fetch-timeout-ms', '--ff-only', '--file', '--fix', '--follow', '--force', '--force-rechunk', '--force-retry', '--force-schema', '--format', '--fresh', '--from', '--from-meetings', '--from-pages', '--full', '--fuzzy', '--get', '--git-common-dir', '--git-dir', '--git-path', '--group', '--group-by', '--hard', '--hard-deadline', '--harness', '--help', '--home', '--http', '--id', '--if-version', '--ignore-env-override', '--images', '--include-ambiguous', '--include-deleted', '--include-failures', '--include-flagged', '--include-gitignored', '--include-hidden', '--include-pseudo', '--include-repairs', '--include-withdrawals', '--index-audit', '--init', '--input', '--install', '--is-ancestor', '--is-inside-work-tree', '--job-isolation', '--jq', '--json', '--keep', '--lanes', '--lang', '--left-right', '--limit', '--link-source', '--link-type', '--list', '--local', '--local-env-vars', '--locks', '--log-noop', '--manifest', '--markdown', '--max-cost', '--max-cost-usd', '--max-jobs', '--max-rss', '--max-runtime', '--max-usd', '--max-waiting', '--mcp-only', '--migrate-legacy', '--migrate-only', '--migration', '--min', '--mode', '--multimodal', '--name', '--name-only', '--nice', '--no-accept-pending', '--no-autopilot-install', '--no-autostash', '--no-capture', '--no-confirm', '--no-cron', '--no-delegate', '--no-edit', '--no-embed', '--no-embedding', '--no-expand', '--no-extract', '--no-hooks', '--no-lanes', '--no-llm', '--no-migrate', '--no-pull', '--no-renames', '--no-repair', '--no-schema-pack', '--no-seat', '--no-tags', '--no-verify', '--non-interactive', '--now', '--older-than', '--once', '--only', '--operations', '--others', '--out', '--output', '--overwrite', '--page', '--parallel', '--params', '--pat-file', '--path', '--path-format', '--pglite', '--phase', '--pid-file', '--plan', '--porcelain', '--port', '--prefer', '--prefer-postgres', '--preset', '--preview', '--probe', '--probe-pglite', '--profile', '--progress-interval', '--progress-json', '--project', '--provider', '--providers', '--prune-orphans', '--public-url', '--pull', '--pure', '--purge', '--push-only', '--query', '--question', '--queue', '--quiet', '--rate', '--reauth', '--rebase', '--recommended', '--reference-date', '--refresh', '--refresh-operations', '--refresh-skills', '--regenerate', '--reissue', '--relative', '--remediate', '--remediation-plan', '--remove', '--remove-core', '--repair', '--replace', '--repo', '--request', '--request-id', '--require-clean', '--reranker', '--reset', '--reset-checkpoint', '--reset-default', '--resolve', '--restore-only', '--resume', '--retry-failed', '--reverse', '--review-lower', '--revision', '--rollback-to-source', '--scope', '--scopes', '--search-mode', '--seat', '--section', '--select', '--self-transfer', '--session', '--set', '--set-upstream-to', '--shadow', '--short', '--show-current', '--show-prefix', '--show-token', '--show-toplevel', '--since', '--skills-dir', '--skip', '--skip-bare-tweet', '--skip-failed', '--skip-urls', '--skip-verify', '--slot', '--slug', '--slugs', '--source', '--source-id', '--sources', '--src-subpath', '--staged', '--stale', '--state', '--status', '--stdin', '--strategy', '--strict', '--suite', '--supabase', '--surface', '--symbol-kind', '--symbolic-full-name', '--takes-holders', '--target', '--target-score', '--threshold', '--tier', '--timeout', '--to', '--token', '--token-ttl', '--top-k', '--trust', '--type', '--uninstall', '--unsafe-bypass-dream-guard', '--unset-all', '--untracked-files', '--url', '--url-env', '--user', '--vectors', '--verbose', '--verify', '--version', '--wait', '--wait-drain', '--warn-only', '--what-if-threshold', '--window', '--workers', '--working-tree', '--workspace', '--yes'],'dream': ['--audit-rejects', '--brain', '--cancel-unmatched', '--date', '--dir', '--drain', '--dry-run', '--eval-run', '--force', '--from', '--help', '--input', '--install', '--json', '--limit', '--list', '--max-usd', '--once', '--path', '--phase', '--pull', '--reconcile-queue', '--since', '--source', '--source-id', '--threshold', '--to', '--unsafe-bypass-dream-guard', '--window', '--yes'],'edge-proposals': ['--access', '--add', '--all-applied', '--all-held', '--allowed-operations', '--asof', '--bound-slug-prefixes', '--brain', '--client', '--date', '--dated-since', '--days', '--entities', '--federated-read', '--full', '--fuzzy', '--help', '--http', '--id', '--include-deleted', '--json', '--kind', '--limit', '--max-usd', '--model', '--multimodal', '--no-autopilot-install', '--page', '--params', '--path', '--phase', '--purge', '--recent', '--refresh-operations', '--row', '--scopes', '--session', '--since', '--slugs', '--source', '--sources', '--stale', '--status', '--surface', '--to', '--updated-after', '--url', '--yes'],'edges-backfill': ['--all-sources', '--brain', '--concurrency', '--help', '--json', '--max-chunks', '--source', '--workers'],diff --cc src/core/context/sync-ipc.tsindex 39c386e9ff,198b9fef7d..c50c0feab3--- a/src/core/context/sync-ipc.ts+++ b/src/core/context/sync-ipc.ts@@@ -54,8 -54,8 +54,9 @@@ export const DELEGATED_SYNC_OPTION_FIELnoBulk: 'boolean',lanes: 'number',explicitProcessing: 'string[]',+ embedDeferred: 'boolean',timeoutSeconds: 'number',+ origin: 'string',} as const;/** `--lanes N` bounds (`src/commands/sync/args.ts`). */@@@ -85,10 -85,10 +86,12 @@@ export interface DelegatedSyncOptionsnoBulk?: boolean;/** #6317: `--lanes N` / `--no-lanes` (1..DELEGATED_SYNC_LANES_MAX) for the managed catch-up. */lanes?: number;+ /** #6696 (A5): who the run's writes are for; the operator's CLI sends `interactive`, absent is `background`. */+ origin?: 'interactive' | 'background';- /** #6317: the processing options the caller set itself; the managed cursor supplies the rest. */+ /** #6317: the processing options the caller set itself; the managed cursor supplies the rest. #6696: a missing list (an older CLI) means none. */explicitProcessing?: Array<typeof DELEGATED_SYNC_PROCESSING_KEYS[number]>;+ /** #6696: the client's cost gate deferred this run's embedding; cursor adoption never lifts it. Sent only when true. */+ embedDeferred?: boolean;/*** REQUIRED — the client always sends its resolved hard deadline so a job* whose client died stays bounded. `0` is the single unbounded encodingdiff --cc src/core/error-registry.tsindex c7546889c8,5a94396727..aac1775a7f--- a/src/core/error-registry.ts+++ b/src/core/error-registry.ts@@@ -508,6 -491,8 +513,8 @@@ export const CODES =verification_failed: { class: 'server', summary: "Source content or relationships changed during verification." },withdrawal_capacity: { class: 'caller', summary: "Withdrawal capacity." },withdrawal_provenance: { class: 'server', summary: "The withdrawal target manifest is invalid." },- write_capacity_backpressure: { class: 'host_only', retryable: false, summary: "A background producer (maintenance, conversation facts, an autopilot phase or an autopilot catch-up sync) stopped admitting writes because a cumulative write cap is past `persistence.capacity.background_pause_pct` (default 80); interactive writes keep the rest. Nothing was submitted and no receipt was written.", why: "Near a cumulative cap the remaining request ids and receipt bytes are kept for the user's own writes (remember, put_page, edit_page, operator sync, approved repair). Request ids are never freed, so past the line on ids only the brain host's config raise resumes background work; receipt bytes also free as receipts compact.", docs: 'docs/guides/write-refusals.md#write_capacity_backpressure', fix: { argv: ['gbrain', 'doctor', '--only', 'persistence_capacity', '--json'], consent: [], actor: 'agent', why: "Names the cap past the pause line, its days left and the reversible config raise, read-only.", requires_exclusive: false }, exit: 12 },- write_capacity_low: { class: 'host_only', retryable: false, summary: "A cumulative write cap is at or past 80% or runs out within `persistence.capacity.warn_days` (30) days at its 7-day rate; writes still work.", why: "Request ids are permanent and receipt bytes free only as receipts compact, so the cap is raised before admission refuses.", docs: 'docs/guides/write-refusals.md#write_capacity_low', fix: { argv: ['gbrain', 'doctor', '--only', 'persistence_capacity', '--json'], consent: [], actor: 'agent', why: "Reads the forecast and the one-year config value, read-only.", requires_exclusive: false } },++ write_capacity_backpressure: { class: 'host_only', retryable: false, summary: "A background producer (maintenance, conversation facts, an autopilot phase or an autopilot catch-up sync) stopped admitting writes because a cumulative write cap is past `persistence.capacity.background_pause_pct` (default 80); interactive writes keep the rest. Nothing was submitted and no receipt was written.", why: "Near a cumulative cap the remaining request ids and receipt bytes are kept for the user's own writes (remember, put_page, edit_page, operator sync, approved repair). Request ids are never freed, so past the line on ids only the brain host's config raise resumes background work; receipt bytes also free as receipts compact.", docs: 'docs/guides/write-refusals.md#write_capacity_backpressure', fix: { argv: ['gbrain', 'doctor', '--only', 'persistence_capacity', '--json'], consent: [], actor: 'agent', why: "Names the cap past the pause line, its days left and the reversible config raise, read-only.", requires_exclusive: false, verify: { argv: ['gbrain', 'doctor', '--only', 'persistence_capacity', '--json'], mcp: { tool: 'get_brain_health', arguments: {} } } }, exit: 12 },++ write_capacity_low: { class: 'host_only', retryable: false, summary: "A cumulative write cap is at or past 80% or runs out within `persistence.capacity.warn_days` (30) days at its 7-day rate; writes still work.", why: "Request ids are permanent and receipt bytes free only as receipts compact, so the cap is raised before admission refuses.", docs: 'docs/guides/write-refusals.md#write_capacity_low', fix: { argv: ['gbrain', 'doctor', '--only', 'persistence_capacity', '--json'], consent: [], actor: 'agent', why: "Reads the forecast and the one-year config value, read-only.", requires_exclusive: false, verify: { argv: ['gbrain', 'doctor', '--only', 'persistence_capacity', '--json'], mcp: { tool: 'get_brain_health', arguments: {} } } } },write_claim_lost: { class: 'retryable', summary: "Execution claim changed before publication." },write_gate_rejected: { class: 'caller', summary: "The write gate refused external instruction-like content because the operator set `write_gate.external_mode` to `reject`.", why: "Text from an untrusted source that reads like an instruction to an agent (an override, a standing rule, an exfiltration or credential request) is refused instead of held under that setting, so nothing was written. The same content refuses on every retry.", reasons: ['override', 'standing_instruction', 'exfiltration', 'credential', 'detector_error'], suggestion: 'Tell the user the content was refused; whether to accept it or switch `write_gate.external_mode` back to `quarantine` is their decision.' },write_held: { class: 'consent', summary: "The write gate held this content for the owner's review instead of saving it as memory.", why: "Content from an untrusted source read like an instruction to an agent, so it was quarantined in the write-gate holding table. It is not searchable or recalled until the owner releases it; retrying the same write only re-opens the same hold.", reasons: ['override', 'standing_instruction', 'exfiltration', 'credential', 'detector_error'], actor: 'user', exit: 3, suggestion: 'Do not retry. Tell the user what was held and give them the release command from the fix; releasing is their decision.' },@@@ -517,6 -502,8 +524,8 @@@docs: 'docs/guides/write-refusals.md#write_outcome_unknown',suggestion: 'Read the request first (the fix names it): a committed or pending row means the write was accepted, replay the same request_id to wait for it; no row means it was not, submit it again with the same request_id. Never resubmit under a new request_id without that read.' },write_pending: { class: 'retryable', summary: "The write was accepted and is still pending; it may commit later.", exit: 10 },- write_quota_exhausted: { class: 'host_only', retryable: false, reasons: ['lifetime_ids', 'terminal_bytes'], summary: "A cumulative write cap (permanent request ids or reserved receipt bytes, for the principal or the brain) is full, so the write was not admitted and nothing changed.", why: "Request ids are permanent replay protection and a receipt keeps its bytes until it compacts, so waiting does not free the cap; the brain host raises it with gbrain config set (reversible).", docs: 'docs/guides/write-refusals.md#write_quota_exhausted', fix: { argv: ['gbrain', 'doctor', '--only', 'persistence_capacity', '--json'], consent: [], actor: 'agent', why: "Reads which cap is full and the config value that covers one more year, read-only.", requires_exclusive: false }, exit: 12 },- write_quota_insufficient: { class: 'host_only', retryable: false, reasons: ['lifetime_ids', 'terminal_bytes'], summary: "A bulk run (managed sync catch-up, reclone or a repair) estimated more new receipts than the remaining write capacity allows before its producer's pause line, so it did not start; other writes still work.", why: "Starting a run that the cap would stop part way leaves a long tail of pending pages; the preflight refuses up front with the config raise that covers the run.", docs: 'docs/guides/write-refusals.md#write_quota_insufficient', fix: { argv: ['gbrain', 'doctor', '--only', 'persistence_capacity', '--json'], consent: [], actor: 'agent', why: "Reads the remaining capacity and the one-year config value, read-only.", requires_exclusive: false }, exit: 12 },++ write_quota_exhausted: { class: 'host_only', retryable: false, reasons: ['lifetime_ids', 'terminal_bytes'], summary: "A cumulative write cap (permanent request ids or reserved receipt bytes, for the principal or the brain) is full, so the write was not admitted and nothing changed.", why: "Request ids are permanent replay protection and a receipt keeps its bytes until it compacts, so waiting does not free the cap; the brain host raises it with gbrain config set (reversible).", docs: 'docs/guides/write-refusals.md#write_quota_exhausted', fix: { argv: ['gbrain', 'doctor', '--only', 'persistence_capacity', '--json'], consent: [], actor: 'agent', why: "Reads which cap is full and the config value that covers one more year, read-only.", requires_exclusive: false, verify: { argv: ['gbrain', 'doctor', '--only', 'persistence_capacity', '--json'], mcp: { tool: 'get_brain_health', arguments: {} } } }, exit: 12 },++ write_quota_insufficient: { class: 'host_only', retryable: false, reasons: ['lifetime_ids', 'terminal_bytes'], summary: "A bulk run (managed sync catch-up, reclone or a repair) estimated more new receipts than the remaining write capacity allows before its producer's pause line, so it did not start; other writes still work.", why: "Starting a run that the cap would stop part way leaves a long tail of pending pages; the preflight refuses up front with the config raise that covers the run.", docs: 'docs/guides/write-refusals.md#write_quota_insufficient', fix: { argv: ['gbrain', 'doctor', '--only', 'persistence_capacity', '--json'], consent: [], actor: 'agent', why: "Reads the remaining capacity and the one-year config value, read-only.", requires_exclusive: false, verify: { argv: ['gbrain', 'doctor', '--only', 'persistence_capacity', '--json'], mcp: { tool: 'get_brain_health', arguments: {} } } }, exit: 12 },worktree_dirty: { class: 'caller', retryable: false, actor: 'agent',summary: "A managed sync held a file whose uncommitted working-tree bytes match neither the pinned commit nor the current page; the rest of the source synced and the local edit was not overwritten.",why: "On a live checkout an agent may be mid-edit on a file the catch-up reaches. The bytes are not committed at HEAD, so sync cannot tell a deliberate local change from a stray one, and importing the pinned version would discard the edit; before #6340 this refusal stopped the whole run.",diff --cc src/core/persistence/admission-origin.tsindex 0000000000,f29f5397cc..382c736c36mode 000000,100644..100644--- a/src/core/persistence/admission-origin.ts+++ b/src/core/persistence/admission-origin.ts@@@ -1,0 -1,74 +1,75 @@@+ /**+ * #6696 (A5): who a write is for. `interactive` writes are the user's own+ * (`remember`, `put_page`, `edit_page` from the CLI or an MCP client, an+ * operator's `gbrain sync`, an approved `gbrain repair`); everything else is+ * `background` (maintenance, conversation facts, autopilot cycle phases,+ * autopilot catch-up syncs, minion jobs). Trusted host-side callers set the+ * origin explicitly: `OperationContext.admissionOrigin` at the CLI and MCP+ * entry points and the persistence owner's verified IPC dispatch, or a+ * `withAdmissionOrigin` scope around a command (`gbrain sync`, its delegated+ * run on the owner, `gbrain repair`; `runCycle` scopes itself background).+ * A caller that sets nothing is background. It is never inferred from+ * `ctx.remote`: an autopilot phase writes with `remote: true` too.+ *+ * Near a cumulative cap (`persistence.capacity.background_pause_pct`, default+ * 80 percent, of a principal's or the brain's request ids or receipt bytes) a+ * background admission refuses `write_capacity_backpressure` before any+ * receipt exists, so the rest stays free for interactive writes.+ */+ import { AsyncLocalStorage } from 'node:async_hooks';+ import { opError, type OperationError } from '../ops/contract.ts';+ import type { SqlEngine } from './model.ts';++import { CAPACITY_VERIFY } from './capacity-verify.ts';++ export type AdmissionOrigin = 'interactive' | 'background';+ export const ADMISSION_ORIGINS: readonly AdmissionOrigin[] = ['interactive', 'background'];+ export const BACKGROUND_PAUSE_KEY = 'persistence.capacity.background_pause_pct';+ export const DEFAULT_BACKGROUND_PAUSE_SHARE = 0.8;+ /** What a paused admission's doctor finding names as paused. */+ export const BACKGROUND_PRODUCERS = ['managed maintenance', 'conversation facts', 'autopilot cycle phases', 'autopilot catch-up sync', 'minion jobs'] as const;++ const scope = new AsyncLocalStorage<AdmissionOrigin>();++ /** Runs `fn` with every admission inside it attributed to `origin` (a background scope wins over an inner interactive caller). */+ export function withAdmissionOrigin<T>(origin: AdmissionOrigin, fn: () => T): T {+ return scope.run(scope.getStore() === 'background' ? 'background' : origin, fn);+ }++ /** The origin an admission is charged to: a surrounding background scope, else the explicit origin, else the scope, else background. */+ export function resolveAdmissionOrigin(explicit?: AdmissionOrigin): AdmissionOrigin {+ const surrounding = scope.getStore();+ if (surrounding === 'background') return 'background';+ return explicit ?? surrounding ?? 'background';+ }++ export function isAdmissionOrigin(value: unknown): value is AdmissionOrigin {+ return value === 'interactive' || value === 'background';+ }++ /** The pause line as a share of each cumulative cap (0 < share <= 1); the setting is a percent (80), and a share (0.8) reads the same. */+ export async function readBackgroundPauseShare(engine: SqlEngine): Promise<number> {+ const [row] = await engine.executeRaw<{ value: string }>('SELECT value FROM config WHERE key=$1', [BACKGROUND_PAUSE_KEY]);+ const value = row ? Number(row.value) : DEFAULT_BACKGROUND_PAUSE_SHARE;+ if (!Number.isFinite(value) || value <= 0 || value > 100) return DEFAULT_BACKGROUND_PAUSE_SHARE;+ return value > 1 ? value / 100 : value;+ }++ /**+ * The refusal of a background admission past the pause line; nothing was+ * submitted. Request ids are never freed, so past the line on ids the only fix+ * is the host's config raise; receipt bytes also free as receipts compact.+ */+ export function backgroundPaused(scopeKey: string, resource: 'lifetime_ids' | 'terminal_bytes', used: number, limit: number, share: number,+ configKey: string, value: number, context: { what?: string; alternative?: string } = {}): OperationError {+ const raise = `gbrain config set ${configKey} ${value}`;+ return opError('write_capacity_backpressure',+ `${context.what ?? 'Background writes are paused'}: ${scopeKey} ${resource} is at ${used} of ${limit}, past the ${Math.round(share * 100)}% pause line (${BACKGROUND_PAUSE_KEY}).`,+ `Nothing was submitted; interactive writes keep the rest of ${configKey}. ${context.alternative ? `${context.alternative} ` : ''}${resource === 'lifetime_ids'+ ? `Request ids are never freed, so background work resumes only after the brain host runs ${raise} (covers about one more year; undo with gbrain config unset ${configKey}).`+ : `Background work resumes as retained receipts compact, or at once after the brain host runs ${raise} (covers about one more year; undo with gbrain config unset ${configKey}).`}`,+ { reason: resource, detail: configKey.slice('persistence.limits.'.length), docs: 'docs/guides/write-refusals.md#write_capacity_backpressure',+ fix: { argv: ['gbrain', 'config', 'set', configKey, String(value)], consent: [], actor: 'host_admin', requires_exclusive: false,+ why: resource === 'lifetime_ids' ? 'Request ids are permanent, so only a larger cap moves the pause line; the raise is reversible.'+ : 'The raise moves the pause line at once and is reversible; compaction frees reserved bytes only as receipts age out of the retention window.',- verify: { argv: ['gbrain', 'doctor', '--only', 'persistence_capacity', '--json'] }, docs: 'docs/guides/concurrent-writes.md#quota-near-exhaustion' } });++ verify: CAPACITY_VERIFY, docs: 'docs/guides/concurrent-writes.md#quota-near-exhaustion' } });+ }diff --cc src/core/persistence/capacity-snapshot.tsindex 0000000000,ade1f6e2fa..329a8e15a7mode 000000,100644..100644--- a/src/core/persistence/capacity-snapshot.ts+++ b/src/core/persistence/capacity-snapshot.ts@@@ -1,0 -1,114 +1,115 @@@+ /**+ * #6696 (A4): pushed capacity warnings, from a per-engine snapshot that one+ * light forecast (capacity-forecast.ts) fills at most once a minute (the+ * #6650 `cachedTerminalSummary` pattern); a write never computes a forecast.+ *+ * `write_capacity_low` (notice kind `info`, so `gbrain notices mute+ * write_capacity_low` mutes it on receipts) names every cumulative cap at or+ * past 80% or out within `persistence.capacity.warn_days`. Write and sync+ * receipts carry it at most once an hour per process per scope and resource;+ * `gbrain sync status`, doctor and autopilot cycle output carry it every time.+ * `write_capacity_backpressure` (kind `degraded`, never muted) fires once+ * when a scope passes the background pause line (A5), again only after it+ * clears and passes it anew.+ */+ import type { Notice } from '../agent-output.ts';+ import type { SqlEngine } from './model.ts';+ import { BACKGROUND_PRODUCERS, readBackgroundPauseShare } from './admission-origin.ts';+ import { readCapacityForecast } from './capacity-forecast.ts';++import { CAPACITY_VERIFY } from './capacity-verify.ts';++ export const CAPACITY_SNAPSHOT_TTL_MS = 60_000;+ export const CAPACITY_NOTICE_INTERVAL_MS = 60 * 60_000;++ export interface CapacityAttention {+ scope: string; resource: 'lifetime_ids' | 'terminal_bytes'; used: number; limit: number; pct: number;+ days_to_exhaustion: number | null; config_key: string; recommended_limit: number; command: string;+ }+ export interface CapacitySnapshot {+ /** Every cumulative cap of every scope (the /metrics gauges). */+ rows: CapacityAttention[];+ /** Caps at or past the warn percentage or out within the warn days. */+ low: CapacityAttention[];+ /** Caps past the background pause line: background producers refuse there. */+ paused: CapacityAttention[];+ pause_pct: number;+ status: 'ok' | 'unknown';+ }++ const snapshots = new WeakMap<object, { at: number; value: Promise<CapacitySnapshot> }>();+ const lowShownAt = new Map<string, number>();+ const pausedShown = new Set<string>();++ /** The snapshot for `engine`, shared by every caller within CAPACITY_SNAPSHOT_TTL_MS (in flight included); a failed read is cached as `unknown`. */+ export function cachedCapacitySnapshot(engine: SqlEngine, now: number = Date.now()): Promise<CapacitySnapshot> {+ const hit = snapshots.get(engine);+ if (hit && now - hit.at < CAPACITY_SNAPSHOT_TTL_MS) return hit.value;+ const value = Promise.all([readCapacityForecast(engine, { light: true }), readBackgroundPauseShare(engine)]).then(([forecast, share]): CapacitySnapshot => {+ const attention = (row: typeof forecast.rows[number]): CapacityAttention => ({ scope: row.scope, resource: row.resource, used: row.used, limit: row.limit,+ pct: row.pct, days_to_exhaustion: row.days_to_exhaustion, config_key: row.config_key, recommended_limit: row.recommended_limit,+ command: `gbrain config set ${row.config_key} ${row.recommended_limit}` });+ return { rows: forecast.rows.map(attention), low: forecast.rows.filter(row => row.status !== 'ok').map(attention),+ paused: forecast.rows.filter(row => row.used >= Math.floor(row.limit * share)).map(attention), pause_pct: Math.round(share * 100), status: 'ok' };+ }).catch((): CapacitySnapshot => ({ rows: [], low: [], paused: [], pause_pct: 0, status: 'unknown' }));+ snapshots.set(engine, { at: now, value });+ return value;+ }++ const key = (row: CapacityAttention) => `${row.scope}|${row.resource}`;+ const describe = (row: CapacityAttention) => `${row.scope} ${row.resource} ${row.used}/${row.limit} (${row.pct}%`+ + `${row.days_to_exhaustion !== null ? `, about ${row.days_to_exhaustion} day(s) left` : ''})`;-const VERIFY = { argv: ['gbrain', 'doctor', '--only', 'persistence_capacity', '--json'] };++const VERIFY = CAPACITY_VERIFY;++ function lowNotice(rows: CapacityAttention[]): Notice {+ const [first] = rows;+ return { code: 'write_capacity_low', kind: 'info',+ why: `Write capacity is running low: ${rows.map(describe).join('; ')}. Writes still work; admission refuses at the cap. `+ + `The brain host raises it with ${rows.map(row => row.command).join('; ')} (each covers about one more year; reversible).`,+ fix: { argv: ['gbrain', 'config', 'set', first!.config_key, String(first!.recommended_limit)], consent: [], actor: 'host_admin', requires_exclusive: false,+ why: 'Raises the cap that runs out first to a value that covers about one more year; undo with gbrain config unset.', verify: VERIFY,+ docs: 'docs/guides/concurrent-writes.md#quota-near-exhaustion' } };+ }++ function pausedNotice(rows: CapacityAttention[], pausePct: number): Notice {+ const [first] = rows;+ return { code: 'write_capacity_backpressure', kind: 'degraded',+ why: `Background writes are paused: ${rows.map(describe).join('; ')} passed the ${pausePct}% pause line (persistence.capacity.background_pause_pct). `+ + `Paused: ${BACKGROUND_PRODUCERS.join(', ')}. Interactive writes keep the rest of the cap.`,+ fix: { argv: ['gbrain', 'config', 'set', first!.config_key, String(first!.recommended_limit)], consent: [], actor: 'host_admin', requires_exclusive: false,+ why: 'Moves the pause line by raising the cap; request ids never free, receipt bytes free as receipts compact.', verify: VERIFY,+ docs: 'docs/guides/write-refusals.md#write_capacity_backpressure' } };+ }++ /**+ * The capacity notices one output carries. `throttle` (write and sync+ * receipts) shows `write_capacity_low` at most once an hour per process per+ * scope and resource; unthrottled (sync status, doctor, cycle output) shows it+ * whenever a cap needs attention. The pause notice fires on each transition+ * into the pause, in either mode. `scopes` limits both to the scopes a+ * caller may see (a remote client: the brain and its own principal).+ */+ export async function capacityNotices(engine: SqlEngine, opts: { throttle: boolean; now?: number; scopes?: string[] } = { throttle: true }): Promise<Notice[]> {+ const now = opts.now ?? Date.now();+ const snapshot = await cachedCapacitySnapshot(engine, now);+ const visible = (row: CapacityAttention) => !opts.scopes || opts.scopes.includes(row.scope);+ const notices: Notice[] = [];+ const candidates = snapshot.low.filter(visible);+ const low = opts.throttle ? candidates.filter(row => now - (lowShownAt.get(key(row)) ?? -Infinity) >= CAPACITY_NOTICE_INTERVAL_MS) : candidates;+ if (low.length) {+ if (opts.throttle) for (const row of low) lowShownAt.set(key(row), now);+ notices.push(lowNotice(low));+ }+ const pausedNow = new Set(snapshot.paused.map(key));+ for (const shown of pausedShown) if (!pausedNow.has(shown)) pausedShown.delete(shown);+ const started = snapshot.paused.filter(row => visible(row) && !pausedShown.has(key(row)));+ if (started.length) {+ for (const row of started) pausedShown.add(key(row));+ notices.push(pausedNotice(started, snapshot.pause_pct));+ }+ return notices;+ }++ export function __resetCapacityNoticesForTests(): void {+ lowShownAt.clear();+ pausedShown.clear();+ }diff --cc src/core/persistence/capacity-verify.tsindex 0000000000,0000000000..8e965eccdenew file mode 100644--- /dev/null+++ b/src/core/persistence/capacity-verify.ts@@@ -1,0 -1,0 +1,6 @@@++/**++ * #6696 (A6/B2): the read-only verification of every write-capacity fix: doctor++ * on the brain host, and the read-scope `get_brain_health` operation for an++ * agent without admin scope (its capacity band clears).++ */++export const CAPACITY_VERIFY = { argv: ['gbrain', 'doctor', '--only', 'persistence_capacity', '--json'], mcp: { tool: 'get_brain_health', arguments: {} } };diff --cc src/core/persistence/capacity-view.tsindex d59ff22c6e,0000000000..016660c68amode 100644,000000..100644--- a/src/core/persistence/capacity-view.ts+++ b/src/core/persistence/capacity-view.ts@@@ -1,102 -1,0 +1,71 @@@+/**- * #6696 B1/B2: the one read of managed write capacity that doctor's ops tier,- * the read-scope `get_brain_health` operation and `/admin/api/ops` share.- *- * Today it carries the counter diagnostics (`capacityDiagnostics`: used and- * limit per scope and resource) and the last receipt compaction the consumer- * recorded (`persistence.maintenance.last_compaction`). `forecast` is the seam- * for the 7-day forecast (days to exhaustion per scope and resource): null- * until a build provides it, and every consumer here treats null as "days- * unknown", never as "plenty".- *- * Bounded: one indexed read of the counter rows (brain plus each principal),- * the journal limits and one config key.++ * #6696 B1/B2: the one read of managed write capacity that `/admin/api/ops`++ * and the remote bands share: the counter diagnostics (`capacityDiagnostics`:++ * used and limit per scope and resource), the 7-day forecast++ * (`readCapacityForecast`, light: days to exhaustion per scope and resource,++ * null when it could not be read, which every consumer treats as "days++ * unknown", never "plenty"), and the last receipt compaction the consumer++ * recorded (`readLastCompaction`).+ */+import type { BrainEngine } from '../engine.ts';+import { capacityDiagnostics } from './diagnostics.ts';+import { readJournalLimits } from './limits.ts';++import { readCapacityForecast, type CapacityForecast } from './capacity-forecast.ts';++import { readLastCompaction, type CompactionRecord } from './compaction-pass.ts';++import type { CapacitySnapshot } from './capacity-snapshot.ts';++import { CAPACITY_VERIFY } from './capacity-verify.ts';++export type CapacityRow = ReturnType<typeof capacityDiagnostics>[number];+- /** Days to exhaustion of one scope and resource at the recent admission rate (the forecast's per-row answer). */- export interface CapacityForecastRow {- scope: string;- resource: string;- days_to_exhaustion: number | null;- /** How the days were derived (for example `net_after_compaction`). */- basis: string;- }-- export interface CapacityForecast {- per_day_7d: number | null;- max_day_7d: number | null;- spike: boolean;- rows: CapacityForecastRow[];- }-- /** The consumer's last receipt compaction, as recorded under `LAST_COMPACTION_KEY`. */- export interface LastCompaction {- at: string;- host?: string;- compacted?: number;- freed_bytes?: number;- }-+export interface CapacityView {+ rows: CapacityRow[];+ counters_read: number;+ forecast: CapacityForecast | null;- last_compaction: LastCompaction | null;++ last_compaction: CompactionRecord | null;+}+- export const LAST_COMPACTION_KEY = 'persistence.maintenance.last_compaction';+/** Resources that never drain on their own (transient caps refill as requests finish). */+export const CUMULATIVE_RESOURCES: ReadonlySet<string> = new Set(['lifetime_ids', 'terminal_bytes']);++export type CounterRow = { key: string; outstanding_count: string; intent_bytes: string; lifetime_ids: string; terminal_bytes: string; recovery_bytes: string };++/** The brain and principal counter rows (the input `capacityDiagnostics` reads). */+export async function readCapacityCounters(engine: BrainEngine): Promise<CounterRow[]> {+ return engine.executeRaw<CounterRow>(`SELECT key,outstanding_count::text,intent_bytes::text,lifetime_ids::text,+ terminal_bytes::text,recovery_bytes::text FROM persistence_counters WHERE key='brain' OR key LIKE 'principal:%' ORDER BY key`);+}++export async function readCapacityView(engine: BrainEngine): Promise<CapacityView> {+ const counters = await readCapacityCounters(engine);- const rows = capacityDiagnostics(counters, await readJournalLimits(engine));- const [compaction] = await engine.executeRaw<{ value: string }>('SELECT value FROM config WHERE key = $1', [LAST_COMPACTION_KEY]);- return { rows, counters_read: counters.length, forecast: null, last_compaction: parseLastCompaction(compaction?.value ?? null) };- }-- function parseLastCompaction(raw: string | null): LastCompaction | null {- if (!raw) return null;- try {- const value = JSON.parse(raw) as Partial<LastCompaction>;- return typeof value?.at === 'string' && !Number.isNaN(Date.parse(value.at)) ? value as LastCompaction : null;- } catch {- return null;- }++ const limits = await readJournalLimits(engine);++ const forecast = await readCapacityForecast(engine, { limits, light: true }).catch(() => null);++ return { rows: capacityDiagnostics(counters, limits), counters_read: counters.length, forecast, last_compaction: await readLastCompaction(engine) };+}++/**+ * The read-only verification of every capacity fix: doctor on the brain host, and+ * the read-scope `get_brain_health` operation where it is callable (remote agents+ * without admin scope see the band clear).+ */+export function capacityVerify(): { argv: string[]; mcp: { tool: string; arguments: Record<string, unknown> } } {- return { argv: ['gbrain', 'doctor', '--only', 'persistence_capacity', '--json'], mcp: { tool: 'get_brain_health', arguments: {} } };++ return { argv: [...CAPACITY_VERIFY.argv], mcp: { ...CAPACITY_VERIFY.mcp } };+}++export type CapacityBand = 'ok' | 'low' | 'critical';+export type DaysBand = 'under_7' | '7_to_30' | '30_to_90' | '90_to_365' | 'over_365' | 'unknown';+- /** Remote-safe banding: no scope identities, no exact counters. Thresholds match doctor `persistence_capacity` (80% warns). */- export function capacityBands(view: CapacityView): { capacity: CapacityBand; days: DaysBand; max_pct_band: '<80' | '80-95' | '>=95' } {- const cumulative = view.rows.filter((r) => CUMULATIVE_RESOURCES.has(r.resource));- const pct = cumulative.reduce((max, r) => Math.max(max, r.limit > 0 ? r.used / r.limit : r.used > 0 ? 1 : 0), 0);- const known = (view.forecast?.rows ?? []).map((r) => r.days_to_exhaustion).filter((d): d is number => typeof d === 'number' && Number.isFinite(d));++/**++ * Remote-safe banding of the cached capacity snapshot: no scope identities, no exact counters. `low` and++ * `critical` follow doctor `persistence_capacity` (80% / 95%, or out within the warn / fail days); a snapshot++ * that could not be read is days `unknown`, never plenty.++ */++export function capacityBands(snapshot: CapacitySnapshot, thresholds: { warnDays: number; failDays: number }): { capacity: CapacityBand; days: DaysBand; max_pct_band: '<80' | '80-95' | '>=95' } {++ const pct = snapshot.rows.reduce((max, r) => Math.max(max, r.pct), 0);++ const known = snapshot.rows.map((r) => r.days_to_exhaustion).filter((d): d is number => typeof d === 'number' && Number.isFinite(d));+ const days = known.length ? Math.min(...known) : null;- const daysBand: DaysBand = days === null ? 'unknown' : days < 7 ? 'under_7' : days < 30 ? '7_to_30' : days < 90 ? '30_to_90' : days < 365 ? '90_to_365' : 'over_365';- const capacity: CapacityBand = pct >= 0.95 || (days !== null && days < 7) ? 'critical' : pct >= 0.8 || (days !== null && days < 30) ? 'low' : 'ok';- return { capacity, days: daysBand, max_pct_band: pct >= 0.95 ? '>=95' : pct >= 0.8 ? '80-95' : '<80' };++ // A row without days does not run out within the forecast horizon (3650 days) at its 7-day rate.++ const daysBand: DaysBand = snapshot.status !== 'ok' ? 'unknown' : days === null ? 'over_365' : days < 7 ? 'under_7' : days < 30 ? '7_to_30' : days < 90 ? '30_to_90' : days < 365 ? '90_to_365' : 'over_365';++ const capacity: CapacityBand = pct >= 95 || (days !== null && days < thresholds.failDays) ? 'critical'++ : pct >= 80 || snapshot.low.length > 0 || (days !== null && days < thresholds.warnDays) ? 'low' : 'ok';++ return { capacity, days: daysBand, max_pct_band: pct >= 95 ? '>=95' : pct >= 80 ? '80-95' : '<80' };+}diff --cc src/core/persistence/consumer.tsindex 7542ff7968,27c24dd39b..d552cb0ccf--- a/src/core/persistence/consumer.ts+++ b/src/core/persistence/consumer.ts@@@ -497,14 -491,9 +498,14 @@@ export class PersistenceConsumer implemawait this.phase('refresh_roots', signal => refreshManagedFilesystemRoots(this.engine,this.engine.kind === 'pglite' ? this.config.database_path : undefined, signal));// F4b: idle maintenance also refreshes stale PGLite planner statistics (a no-op on Postgres).- this.maintenanceWorker = compactWriteReceipts(this.engine).then(() => maybeRefreshPlannerStats(this.engine, 'idle'))+ this.maintenanceWorker = runCompactionPass(this.engine, { hostId: this.hostId, notice: this.opts.drainNotice }).then(() => maybeRefreshPlannerStats(this.engine, 'idle')).catch(error => this.report(error)).finally(() => { this.maintenanceWorker = undefined; });}+ if (this.opts.keepDbPolicy && !this.opts.requestsOnly && !this.keepDbWorker && Date.now() >= this.nextKeepDb) {+ this.nextKeepDb = Date.now() + KEEP_DB_POLICY_INTERVAL_MS;+ this.keepDbWorker = import('../repair/keep-db-policy.ts').then(({ runKeepDbPolicy }) => runKeepDbPolicy(this.engine, { hostId: this.hostId }))+ .catch(error => this.report(error)).finally(() => { this.keepDbWorker = undefined; });+ }return;}}diff --cc src/core/persistence/journal.tsindex 2e73b801dd,1cdb9e83e2..5c749e71c3--- a/src/core/persistence/journal.ts+++ b/src/core/persistence/journal.ts@@@ -21,6 -24,6 +24,7 @@@ import { catalogueError } from '../erroimport { ACTIVE_REFRESH_STATES_SQL, refreshFenceClear } from './worktree-refresh-schema.ts';import { assertMutationProtocol, assertSharedSkillPersistence, declareDurablePersistence, declarePersistenceProtocol, PERSISTENCE_PROTOCOL_PREDICATE } from './protocol.ts';import { assertGraduationAdmission } from './graduation-custody.ts';++import { CAPACITY_VERIFY } from './capacity-verify.ts';import {isTerminal, principalKey, requestPrincipal, recoveryFiles,type JournalLimits, type Principal, type RecoveryRecord, type RequestState,@@@ -76,15 -95,30 +96,30 @@@ export function capacityError(resourceif (outstanding) error.detail = outstandingCapacityDetail(outstanding.used, outstanding.limit);return error;}- /** Cumulative caps name their config key and a value that covers one more year at the current admission rate. */+ /**+ * #6696 (A6): a cumulative cap refusal is `write_quota_exhausted` (host only;+ * waiting does not free a permanent id, and receipt bytes free only as+ * receipts compact). It names the config key and a value that covers one more+ * year at the current admission rate; `detail` keeps the limit key, `reason`+ * the resource.+ */async function cumulativeCapacityError(tx: SqlEngine, resource: string, scope: string, setting: keyof JournalLimits, used: number, limit: number): Promise<OperationError> {const key = journalLimitKey(setting);- const value = await oneYearCapacity(tx, scope, setting.endsWith('LifetimeIds') ? 'LifetimeIds' : 'TerminalBytes', used, limit);- const error = new OperationError('queue_capacity', `Write capacity exhausted: ${resource} (${used} used of ${limit}).`,- `Run on the brain host: gbrain config set ${key} ${value} (covers about one more year at the current admission rate). ` +- 'Keep the same request_id and retry after the change. Accepted request IDs and retained receipts are never evicted.');- error.detail = key.slice('persistence.limits.'.length);- return error;+ const ids = setting.endsWith('LifetimeIds');+ const value = await oneYearCapacity(tx, scope, ids ? 'LifetimeIds' : 'TerminalBytes', used, limit);+ return quotaExhausted(resource, key, value, used, limit, ids ? 'lifetime_ids' : 'terminal_bytes');+ }+ /** The `write_quota_exhausted` refusal for config key `key`; the fix is the reversible raise, verified by the capacity check. */+ export function quotaExhausted(resource: string, key: string, value: number, used: number, limit: number, reason: 'lifetime_ids' | 'terminal_bytes'): OperationError {+ return opError('write_quota_exhausted', `Write capacity exhausted: ${resource} (${used} used of ${limit}).`,+ `Run on the brain host: gbrain config set ${key} ${value} (covers about one more year at the current admission rate; undo with gbrain config unset ${key}). ` ++ `Keep the same request_id and retry after the change. Accepted request IDs and retained receipts are never evicted.${reason === 'terminal_bytes'+ ? ' Then gbrain repair receipt-compaction previews the retained receipt bytes compaction would free.' : ''}`,+ { reason, detail: key.slice('persistence.limits.'.length), docs: 'docs/guides/write-refusals.md#write_quota_exhausted',+ fix: { argv: ['gbrain', 'config', 'set', key, String(value)], consent: [], actor: 'host_admin', requires_exclusive: false,+ why: reason === 'lifetime_ids' ? 'Request ids are permanent, so only a larger cap admits more writes; the raise is reversible.'+ : 'The raise unblocks writes at once and is reversible; compaction frees reserved bytes only over time.',- verify: { argv: ['gbrain', 'doctor', '--only', 'persistence_capacity', '--json'] }, docs: 'docs/guides/concurrent-writes.md#quota-near-exhaustion' } });++ verify: CAPACITY_VERIFY, docs: 'docs/guides/concurrent-writes.md#quota-near-exhaustion' } });}/*** Up-front refusal for a backfill that will admit `needed` new requests: when@@@ -93,16 -127,41 +128,41 @@@* the caller mutates anything.*/export async function assertLifetimeIdHeadroom(engine: SqlEngine, principal: Principal, needed: number): Promise<void> {- if (needed <= 0) return;+ await assertWriteHeadroom(engine, principal, { ids: needed });+ }+ /**+ * #6696 (A7): a bulk run's preflight. `needed` is the run's estimate (new+ * request ids, and receipt bytes at `receiptReservation` each); `share` is the+ * producer's pause line (`backgroundPauseShare`) or 1 for an interactive run.+ * A cap already full refuses `write_quota_exhausted`; a cap that still admits+ * writes but cannot cover the run refuses `write_quota_insufficient`, both+ * with the config value that covers the run and one more year.+ */+ export async function assertWriteHeadroom(engine: SqlEngine, principal: Principal, needed: { ids: number; bytes?: number }, share = 1): Promise<void> {+ if (needed.ids <= 0 && !needed.bytes) return;const limits = await readJournalLimits(engine);const keys = ['brain', principalKey(principal)];- const rows = await engine.executeRaw<{ key: string; lifetime_ids: number | string }>(- 'SELECT key,lifetime_ids FROM persistence_counters WHERE key=ANY($1::text[])', [keys]);+ const rows = await engine.executeRaw<{ key: string; lifetime_ids: number | string; terminal_bytes: number | string }>(+ 'SELECT key,lifetime_ids,terminal_bytes FROM persistence_counters WHERE key=ANY($1::text[])', [keys]);for (const key of keys) {const scope = key === 'brain' ? 'brain' : 'principal';- const used = Number(rows.find(row => row.key === key)?.lifetime_ids ?? 0);- const limit = limits[`${scope}LifetimeIds`];- if (used + needed > limit) throw await cumulativeCapacityError(engine, `${scope} permanent request IDs`, key, `${scope}LifetimeIds`, used, limit);+ for (const [resource, setting, need, label] of [['lifetime_ids', `${scope}LifetimeIds`, needed.ids, 'permanent request IDs'],+ ['terminal_bytes', `${scope}TerminalBytes`, needed.bytes ?? 0, 'reserved receipt bytes']] as const) {+ if (need <= 0) continue;+ const used = Number(rows.find(row => row.key === key)?.[resource] ?? 0);+ const limit = limits[setting];+ if (used + need <= Math.floor(limit * share)) continue;+ if (used + (resource === 'lifetime_ids' ? 1 : RECEIPT_RESERVATION_FLOOR) > limit) {+ throw await cumulativeCapacityError(engine, `${scope} ${label}`, key, setting, used, limit);+ }+ const configKey = journalLimitKey(setting);+ const value = Math.max(Math.ceil((used + need) / share) + 1, await oneYearCapacity(engine, key, resource === 'lifetime_ids' ? 'LifetimeIds' : 'TerminalBytes', used, limit));+ throw opError('write_quota_insufficient', `This run needs ${need} more ${scope} ${label} than the ${Math.floor(limit * share) - used} left before its limit (${used} used of ${limit}${share < 1 ? `, pausing at ${Math.round(share * 100)}%` : ''}).`,+ `Nothing was started and other writes still work. Run on the brain host: gbrain config set ${configKey} ${value} (undo with gbrain config unset ${configKey}), then rerun the same command.`,+ { reason: resource, detail: configKey.slice('persistence.limits.'.length), docs: 'docs/guides/write-refusals.md#write_quota_insufficient',+ fix: { argv: ['gbrain', 'config', 'set', configKey, String(value)], consent: [], actor: 'host_admin', requires_exclusive: false,- why: 'Covers this run and about one more year at the current rate; reversible.', verify: { argv: ['gbrain', 'doctor', '--only', 'persistence_capacity', '--json'] } } });++ why: 'Covers this run and about one more year at the current rate; reversible.', verify: CAPACITY_VERIFY } });+ }}}/** Creates and locks the counter rows in key order: two statements for any number of keys (#5984 round-trip diet). */diff --cc src/core/persistence/prepared-maintenance.tsindex 57fd9dbc15,96447e2815..33fb062140--- a/src/core/persistence/prepared-maintenance.ts+++ b/src/core/persistence/prepared-maintenance.ts@@@ -191,6 -198,18 +198,22 @@@ export function maintenanceDriftRefusal{ argv: ['gbrain', 'sources', 'reconcile', sourceId, '--brain', 'host', '--audit', '--conflicts', '--json'] }) });}-/** #6696 (A12): maintenance kinds whose preparer passes `allowMissingFile` (chronicle, stale-atom retirement): a missing canonical file publishes, so it is no ghost. */-export const PUBLISHES_WITHOUT_FILE: ReadonlySet<string> = new Set(['managed_maintenance_chronicle_event', 'managed_maintenance_chronicle_retire', 'managed_maintenance_retire_stale_atoms']);++/**++ * #6696 (A12): maintenance kinds whose preparer passes `allowMissingFile` (chronicle, stale-atom retirement, ghost-page++ * retirement, which exists to soft-delete pages whose canonical file is gone): a missing canonical file publishes, so it is no ghost.++ */++export const PUBLISHES_WITHOUT_FILE: ReadonlySet<string> = new Set(['managed_maintenance_chronicle_event', 'managed_maintenance_chronicle_retire', 'managed_maintenance_retire_stale_atoms',++ 'managed_maintenance_retire_ghost_page']);++ /** #6696 (A12): `source_changed` / `canonical_file_missing` before admission: the page's recorded file is gone; never a new request. */+ export function maintenanceGhostRefusal(sourceId: string, slug: string): OperationError {+ return opError('source_changed', 'The canonical file was removed outside coordinated publication.',+ `Maintenance submitted nothing for ${slug} in '${sourceId}': the page's canonical file is missing, so the write would only add another conflict receipt. `+ + `Import the deletion with gbrain sync --source ${sourceId}, or restore the file and preview the page with gbrain sources reconcile ${sourceId} ${slug} --brain host --preview. Neither copy was changed.`,+ { detail: CANONICAL_FILE_MISSING, docs: 'docs/guides/write-refusals.md#canonical_file_missing', fix: readFix(`Previews how page ${slug} and its missing canonical file reconcile; read-only.`,+ { argv: ['gbrain', 'sources', 'reconcile', sourceId, slug, '--brain', 'host', '--preview', '--json'] }) });+ }+/** #5523: a Life Chronicle timeline row projected onto the depth page in the same publication. */export interface MaintenanceEventProjection { depth_slug: string; date: string; summary: string; }diff --cc src/core/persistence/preview-approval.tsindex e385c97d45,e5fc942b41..8365fe5b4a--- a/src/core/persistence/preview-approval.ts+++ b/src/core/persistence/preview-approval.ts@@@ -40,7 -40,7 +40,7 @@@ export const PREVIEW_APPROVAL_OP = 'rep/** The default `purgeStaleCheckpoints` TTL; an older approved set may already be gone. */export const APPROVAL_MAX_AGE_DAYS = 7;- export type PreviewApprovalCommand = 'authorize-legacy' | 'jobs-cancel' | 'stale-atoms' | 'extractor-facts' | 'conversation-labels' | 'captured-facts' | 'loop-facts' | 'ontology-facts' | 'failed-writes' | 'frontmatter' | 'fences' | 'slug-conflicts' | 'managed-sync-orphans' | 'frontmatter-keys' | 'file-drift' | 'stuck-recovery' | 'ghost-pages';-export type PreviewApprovalCommand = 'authorize-legacy' | 'jobs-cancel' | 'stale-atoms' | 'extractor-facts' | 'conversation-labels' | 'captured-facts' | 'loop-facts' | 'ontology-facts' | 'failed-writes' | 'frontmatter' | 'fences' | 'slug-conflicts' | 'managed-sync-orphans' | 'frontmatter-keys' | 'file-drift' | 'stuck-recovery' | 'receipt-compaction';++export type PreviewApprovalCommand = 'authorize-legacy' | 'jobs-cancel' | 'stale-atoms' | 'extractor-facts' | 'conversation-labels' | 'captured-facts' | 'loop-facts' | 'ontology-facts' | 'failed-writes' | 'frontmatter' | 'fences' | 'slug-conflicts' | 'managed-sync-orphans' | 'frontmatter-keys' | 'file-drift' | 'stuck-recovery' | 'ghost-pages' | 'receipt-compaction';export interface ApprovedSetKey {command: PreviewApprovalCommand;diff --cc src/core/repair/core.tsindex 740e7b43fa,ddec179fd2..79403eedf0--- a/src/core/repair/core.ts+++ b/src/core/repair/core.ts@@@ -34,8 -35,9 +35,9 @@@ import { redactConnectionInfo } from '.import type { RepairKindSpec } from './registry.ts';import { acceptedPendingReceipt } from '../persistence/accepted-pending.ts';import { repairAdmissionWindow, repairPublicationOwner, settleRepairReceipts, type PendingRepair } from './settle.ts';+ import { RECEIPT_RESERVATION_FLOOR } from '../persistence/receipt-bytes.ts';- export const REPAIR_KINDS = ['timeline', 'visibility', 'safe-chunks', 'contextual-mode', 'connector-checkpoints', 'request-indexes', 'connector-fences', 'take-supersession', 'orphan-bindings', 'embedding-effects', 'attribution-backfill', 'planner-stats', 'google-file-modes', 'stale-atoms', 'extractor-facts', 'conversation-labels', 'captured-facts', 'loop-facts', 'ontology-facts', 'orphan-children', 'failed-writes', 'frontmatter', 'fences', 'slug-conflicts', 'timeline-comments', 'managed-sync-orphans', 'frontmatter-keys', 'file-drift', 'stuck-recovery', 'ghost-pages'] as const;-export const REPAIR_KINDS = ['timeline', 'visibility', 'safe-chunks', 'contextual-mode', 'connector-checkpoints', 'request-indexes', 'connector-fences', 'take-supersession', 'orphan-bindings', 'embedding-effects', 'attribution-backfill', 'planner-stats', 'google-file-modes', 'stale-atoms', 'extractor-facts', 'conversation-labels', 'captured-facts', 'loop-facts', 'ontology-facts', 'orphan-children', 'failed-writes', 'frontmatter', 'fences', 'slug-conflicts', 'timeline-comments', 'managed-sync-orphans', 'frontmatter-keys', 'file-drift', 'stuck-recovery', 'receipt-compaction'] as const;++export const REPAIR_KINDS = ['timeline', 'visibility', 'safe-chunks', 'contextual-mode', 'connector-checkpoints', 'request-indexes', 'connector-fences', 'take-supersession', 'orphan-bindings', 'embedding-effects', 'attribution-backfill', 'planner-stats', 'google-file-modes', 'stale-atoms', 'extractor-facts', 'conversation-labels', 'captured-facts', 'loop-facts', 'ontology-facts', 'orphan-children', 'failed-writes', 'frontmatter', 'fences', 'slug-conflicts', 'timeline-comments', 'managed-sync-orphans', 'frontmatter-keys', 'file-drift', 'stuck-recovery', 'ghost-pages', 'receipt-compaction'] as const;export type RepairKind = typeof REPAIR_KINDS[number];export interface RepairScope { brain_id: string; source_ids: string[] }diff --cc src/core/repair/keep-db-policy.tsindex 8675be1685,0000000000..ea04a3eab1mode 100644,000000..100644--- a/src/core/repair/keep-db-policy.ts+++ b/src/core/repair/keep-db-policy.ts@@@ -1,147 -1,0 +1,161 @@@+/**+ * #6696 C7: the opt-in `storage.keep_db` policy (gbrain.yml), consumed only by+ * the trusted local maintenance worker on the canonical owner host.+ *+ * A source whose gbrain.yml declares `keep_db:` prefixes asks that a drifted+ * page under them (its canonical file differs from the database copy, so every+ * coordinated write refuses `source_changed` / `file_database_drift`) be+ * reconciled with the database copy winning, the resolution+ * `gbrain repair file-drift --prefer database` previews, inside the same+ * reconcile protections. Nothing else reads the policy: remote and caller+ * writes to those pages keep refusing until the worker (or an operator)+ * reconciles them.+ *+ * `runKeepDbPolicy` runs only for a source whose active binding this host+ * owns. Candidates are the slugs under the prefixes with a drift conflict+ * receipt in the newest `CONFLICT_WINDOW_DEFAULT` request sequences, plus the+ * recorded concept drift skips; each is checked live before anything is+ * prepared. Each drifted page gets one reconcile request (`runReconcileApply`)+ * whose id is derived from the page revision and file bytes, so the same drift+ * is never submitted twice, whatever its outcome. A run submits at most `limit`+ * requests (`KEEP_DB_BATCH`; the consumer runs it at most every 10 minutes) and- * stops before an admission the `admission` gate refuses.++ * stops before an admission the `admission` gate refuses, or at the first++ * `write_capacity_backpressure` refusal (it submits as a background producer).+ */+import { join } from 'node:path';+import type { BrainEngine } from '../engine.ts';+import { OperationError, type OperationContext } from '../ops/contract.ts';+import { isKeepDbSlug, loadStorageConfig } from '../storage-config.ts';+import { getWorktreeBinding } from '../persistence/ownership.ts';+import { CONFLICT_WINDOW_DEFAULT, FILE_DRIFT_MESSAGE, liveFileDrift, readDriftSkips } from '../persistence/drift-conflicts.ts';+import { readLocalWriter, withVerifiedLocalRegistration } from '../persistence/identity.ts';+import { getWriteRequest } from '../persistence/journal.ts';+import { runReconcileApply } from '../persistence/reconcile.ts';+import { acceptedPendingReceipt } from '../persistence/accepted-pending.ts';+import { digest } from '../persistence/digest.ts';- import { capacity, RECEIPT_BYTES } from './core.ts';++import { capacity } from './core.ts';++import { RECEIPT_RESERVATION_FLOOR } from '../persistence/receipt-bytes.ts';++import { readBackgroundPauseShare, withAdmissionOrigin } from '../persistence/admission-origin.ts';+import { prepareDriftPage } from './file-drift.ts';++/** Reconcile requests one policy run submits at most. */+export const KEEP_DB_BATCH = 10;+/** Candidate slugs one source contributes to a run. */+const CANDIDATE_LIMIT = 1000;++export interface KeepDbPolicy { source_id: string; keep_db: string[] }++export interface KeepDbRun {+ submitted: number;+ skipped_by_reason: Record<string, number>;- /** `rate_limit`: candidates remain past `limit`; `capacity`: the admission gate refused the next request. */- stopped?: 'rate_limit' | 'capacity';++ /**++ * `rate_limit`: candidates remain past `limit`; `capacity`: the admission gate refused the next request;++ * `write_capacity_backpressure`: admission refused this background producer past the pause line, with no receipt.++ */++ stopped?: 'rate_limit' | 'capacity' | 'write_capacity_backpressure';+ sources: Array<KeepDbPolicy & { submitted: number }>;+}++/**- * The admission seam for this background producer: a stop reason when it must not admit now. The default is the- * repair core's 90% stop line on lifetime ids and receipt bytes; near-cap backpressure for background producers- * plugs in here.++ * The admission seam for this background producer: a stop reason when it must not admit now. The default stops at++ * the repair core's 90% stop line on lifetime ids and receipt bytes (`capacity`) and, before that, at the background++ * pause line (`persistence.capacity.background_pause_pct`, 80%) where admission would refuse this background request++ * `write_capacity_backpressure`. Checking first keeps a refused attempt from retaining a reconcile backup under the++ * page's deterministic request id; an admission-time refusal (another writer crossed the line meanwhile) also stops the run.+ */- export type KeepDbAdmission = (engine: BrainEngine) => Promise<'capacity' | null>;++export type KeepDbAdmission = (engine: BrainEngine) => Promise<'capacity' | 'write_capacity_backpressure' | null>;+- const headroom: KeepDbAdmission = async engine => (await capacity({ engine, remote: false } as OperationContext))- .some(c => c.used + (c.resource === 'lifetime_ids' ? 1 : RECEIPT_BYTES) > c.stop_at) ? 'capacity' : null;++const headroom: KeepDbAdmission = async engine => {++ const rows = await capacity({ engine, remote: false } as OperationContext);++ const need = (resource: string) => resource === 'lifetime_ids' ? 1 : RECEIPT_RESERVATION_FLOOR;++ if (rows.some(c => c.used + need(c.resource) > c.stop_at)) return 'capacity';++ const share = await readBackgroundPauseShare(engine);++ return rows.some(c => c.used + need(c.resource) > Math.floor(c.limit * share)) ? 'write_capacity_backpressure' : null;++};++/** One request's receipt cost, as doctor `maintenance_write_drift` reports it for the matched pages. */- export const keepDbReceiptCost = (pages: number) => ({ lifetime_ids: pages, receipt_bytes: pages * RECEIPT_BYTES });++export const keepDbReceiptCost = (pages: number) => ({ lifetime_ids: pages, receipt_bytes: pages * RECEIPT_RESERVATION_FLOOR });++/**+ * The effective policy of one source on this host: the `keep_db` prefixes of its canonical checkout's gbrain.yml,+ * read only when `hostId` owns the source's active binding (null otherwise, or when none are declared).+ * Throws `StorageConfigError` for a gbrain.yml whose tiers overlap.+ */+export async function readKeepDbPolicy(engine: BrainEngine, sourceId: string, hostId: string | null): Promise<KeepDbPolicy | null> {+ const binding = hostId ? await getWorktreeBinding(engine, sourceId, hostId) : null;+ if (!binding?.local_path || binding.owner_host_id !== hostId || binding.state !== 'active') return null;+ const keepDb = loadStorageConfig(join(binding.local_path, binding.relative_path))?.keep_db ?? [];+ return keepDb.length ? { source_id: sourceId, keep_db: keepDb } : null;+}++const likeEscape = (value: string) => value.replace(/[\\%_]/g, char => `\\${char}`);++async function candidates(engine: BrainEngine, policy: KeepDbPolicy): Promise<string[]> {+ const [bounds] = await engine.executeRaw<{ top: string | null }>('SELECT max(sequence)::text AS top FROM persistence_requests');+ const floor = String(Math.max(0, Number(bounds?.top ?? 0) - CONFLICT_WINDOW_DEFAULT));+ const prefixes = policy.keep_db.map(dir => `${likeEscape(dir.toLowerCase())}%`);+ const rows = await engine.executeRaw<{ slug: string }>(`SELECT DISTINCT r.slug FROM persistence_requests r+ WHERE r.sequence > $2::bigint AND r.source_id=$1 AND r.state='conflict' AND r.error_code='source_changed' AND r.error_message=$3+ AND lower(r.slug) LIKE ANY($4::text[]) ORDER BY r.slug LIMIT ${CANDIDATE_LIMIT}`, [policy.source_id, floor, FILE_DRIFT_MESSAGE, prefixes]);+ const skipped = Object.keys(await readDriftSkips(engine)).filter(key => key.startsWith(`${policy.source_id}:`)).map(key => key.slice(policy.source_id.length + 1));+ return [...new Set([...rows.map(row => row.slug), ...skipped])].filter(slug => isKeepDbSlug(slug, policy.keep_db)).sort();+}++/**+ * One drifted page: submitted, the capacity stop, or the reason it was skipped. It always runs as this+ * installation's own CLI writer registration, never as whatever caller context the worker's timer inherited:+ * the policy is the owner host's declaration, so no remote caller's grant applies to it or is widened by it.+ */+async function reconcileWithDatabase(engine: BrainEngine, sourceId: string, slug: string, admission: KeepDbAdmission): Promise<string> {+ return withVerifiedLocalRegistration(engine, await readLocalWriter(engine, 'cli'), async writer => {+ const live = await liveFileDrift(engine, sourceId, slug);+ if (live.still_present !== true) return live.still_present === false ? 'no_drift' : live.reason;+ let page;+ try { page = await prepareDriftPage(engine, sourceId, slug, 'database', new Date().toISOString()); }+ catch (error) { if (error instanceof OperationError) return error.code; throw error; }+ const h = digest(['keep-db-policy-v1', sourceId, slug, page.preview.preconditions.revision, page.preview.preconditions.raw_file_hash]);+ const requestId = `${h.slice(0, 8)}-${h.slice(8, 12)}-4${h.slice(13, 16)}-a${h.slice(17, 20)}-${h.slice(20, 32)}`;+ if (await getWriteRequest(engine, writer.principal, requestId)) return 'already_submitted';- if (await admission(engine)) return 'capacity';++ const stop = await admission(engine);++ if (stop) return stop;+ try {- // TODO(#6696 PR A, A5): submit with PR A's `background` write origin once it is on master, so near-cap backpressure refuses- // this producer first; until then `admission` (default: the repair core's 90% stop line) is the only gate.- await runReconcileApply(engine, { source_id: sourceId, slug, preview: page.preview, request_id: requestId });++ // #6696 A5: a background producer, so near-cap backpressure refuses it before any receipt and interactive writes keep the rest.++ await withAdmissionOrigin('background', () => runReconcileApply(engine, { source_id: sourceId, slug, preview: page.preview, request_id: requestId }));+ } catch (error) {+ if (acceptedPendingReceipt(error)) return 'submitted';+ if (!(error instanceof OperationError)) throw error;++ if (error.code === 'write_capacity_backpressure') return error.code;+ return await getWriteRequest(engine, writer.principal, requestId) ? 'submitted' : error.code;+ }+ return 'submitted';+ });+}++/**+ * One rate-limited pass of the keep_db policy over `sourceIds` (default: every active source) for the owner host+ * `hostId`. Sources this host does not own, or that declare no policy, are skipped without a read of their pages.+ */+export async function runKeepDbPolicy(engine: BrainEngine, opts: { hostId: string; sourceIds?: string[]; limit?: number; admission?: KeepDbAdmission }): Promise<KeepDbRun> {+ const limit = opts.limit ?? KEEP_DB_BATCH;+ const run: KeepDbRun = { submitted: 0, skipped_by_reason: {}, sources: [] };+ const skip = (reason: string) => { run.skipped_by_reason[reason] = (run.skipped_by_reason[reason] ?? 0) + 1; };+ const sourceIds = opts.sourceIds ?? (await engine.executeRaw<{ id: string }>('SELECT id FROM sources WHERE archived IS NOT TRUE ORDER BY id')).map(row => row.id);+ for (const sourceId of sourceIds) {+ let policy: KeepDbPolicy | null;+ try { policy = await readKeepDbPolicy(engine, sourceId, opts.hostId); } catch { skip('storage_config_error'); continue; }+ if (!policy) continue;+ const entry = { ...policy, submitted: 0 };+ run.sources.push(entry);+ for (const slug of await candidates(engine, policy)) {+ if (run.submitted >= limit) { run.stopped = 'rate_limit'; return run; }+ let outcome: string;+ try { outcome = await reconcileWithDatabase(engine, sourceId, slug, opts.admission ?? headroom); }+ catch (error) { if (!(error instanceof OperationError)) throw error; outcome = error.code; }- if (outcome === 'capacity') { run.stopped = 'capacity'; return run; }++ if (outcome === 'capacity' || outcome === 'write_capacity_backpressure') { run.stopped = outcome; return run; }+ if (outcome !== 'submitted') { skip(outcome); continue; }+ run.submitted++;+ entry.submitted++;+ }+ }+ return run;+}diff --cc src/core/repair/registry.tsindex 5432700793,6aa905dc4e..2bd846b94b--- a/src/core/repair/registry.ts+++ b/src/core/repair/registry.ts@@@ -63,7 -63,7 +63,8 @@@ import { slugConflictsRepair } from './import { frontmatterKeysRepair } from './frontmatter-keys.ts';import { fileDriftRepair } from './file-drift.ts';import { stuckRecoveryRepair } from './stuck-recovery.ts';+import { ghostPagesRepair, GHOST_CONSENT_TEXT, GHOST_CONSEQUENCES, GHOST_PURGE_FUSE_HOURS } from './ghost-pages.ts';+ import { receiptCompactionRepair } from './receipt-compaction.ts';import { ERROR_CATALOGUE, catalogueError } from '../error-catalogue.ts';import type { OperationError } from '../ops/contract.ts';@@@ -295,16 -294,20 +296,30 @@@ const SPECS: Record<RepairKind, Omit<Re+ 'bytes back and the accepted write publishes again, disk keeps the edit and abandons the write (reconcile the page afterwards). A terminal request is '+ 'refused (recovery_choice_refused). Runs only when named.',},+ 'ghost-pages': {+ handler: ghostPagesRepair, embeds: 'none', checks: ['ghost_pages'], explicit_only: true, preview_bound: true, consent: 'destructive',+ consentText: GHOST_CONSENT_TEXT,+ summary: 'Soft-delete live pages whose canonical file is missing on the owner host (ghost pages, #6696): every write to them refuses source_changed / '+ + 'canonical_file_missing and no sync can import a file that is not there. Needs --source; refused off the canonical owner host (not_owner_host) '+ + 'and when the checkout cannot be read (ghost_storage_unknown). Declared db_only and never-filed derived pages are never listed. The preview lists '+ + 'each page with its recorded path and revision, bound to the owner; --apply --expect <hash> --yes soft-deletes exactly that set through delete_page, '+ + 'rechecking each file is still absent (a restored file keeps its page and asks for a new preview). Refused when ghosts are over half of the source\'s '+ + `file-backed pages unless GBRAIN_ALLOW_MASS_RECONCILE=1. Purged after ${GHOST_PURGE_FUSE_HOURS} h; ${GHOST_CONSEQUENCES.undo} Runs only when named.`,+ },+ 'receipt-compaction': {+ handler: receiptCompactionRepair, embeds: 'none', checks: ['persistence_capacity'], explicit_only: true, preview_bound: true, consent: 'destructive',+ consentText: {+ what: 'Compact the previewed terminal write receipts now',+ why: 'The preview selected terminal receipts older than the cutoff it printed; compacting them drops each one\'s intent and error message and returns its unused receipt bytes to the capacity counters.',+ risk: 'Database rows only. A compacted receipt still answers its request id with its outcome, error code and detail, but its original intent is gone and cannot be restored. Open sync runs and the newest sync receipt of each worktree are never touched.',+ user_message: 'Compact the previewed write receipts? Their original request bodies are dropped for good; outcomes stay',+ },+ summary: 'Compact terminal write receipts now instead of waiting for idle maintenance (#6696), returning their unused receipt bytes. Same compaction as the '+ + 'consumer: the intent and error message go, the outcome, error code and detail stay. --older-than <72h|30d> is floored at the configured retention '+ + '(persistence.receipt_retention_days) unless --force; committed receipts only unless --include-failures. Receipts of a run whose sync cursor is '+ + 'open, and the newest sync receipt per worktree, are kept. Preview-bound and destructive: --apply --expect <hash> --yes compacts only the '+ + 'previewed set. No admission, so it runs at a full cap. Brain-wide. Runs only when named.',+ },};export const REPAIR_REGISTRY: readonly RepairKindSpec[] = REPAIR_KINDS.map(kind => ({ kind, ...SPECS[kind] }));diff --cc src/core/serve-sync-runner.tsindex f0a675e7d1,a904154c28..f9db84eb5c--- a/src/core/serve-sync-runner.ts+++ b/src/core/serve-sync-runner.ts@@@ -54,8 -54,9 +54,9 @@@* CLI's effective flags (the managed cursor owns processing options).*/+ import { isAdmissionOrigin, withAdmissionOrigin } from './persistence/admission-origin.ts';import { randomUUID } from 'node:crypto';-import { withLegacySyncDelegation } from './persistence/sync-authority.ts';+import { typedSyncProcessing, withLegacySyncDelegation } from './persistence/sync-authority.ts';import { verifyLocalWriter, withVerifiedLocalRegistration } from './persistence/identity.ts';import { readManagedMode } from './persistence/managed-mode.ts';import { OperationError } from './ops/contract.ts';diff --cc test/doctor-ops-remote-6696.test.tsindex a536efe770,0000000000..f4200ff8e9mode 100644,000000..100644--- a/test/doctor-ops-remote-6696.test.ts+++ b/test/doctor-ops-remote-6696.test.ts@@@ -1,247 -1,0 +1,249 @@@+/**+ * #6696 B2: the ops tier for agents and remote clients.+ *+ * - `get_brain_health` (read scope) answers bands only, scoped to the caller's+ * sources, cached 60 s per engine and scope.+ * - `run_doctor` takes `tier: "ops"` and `only`, runs only the ops sections and+ * refuses other tiers and unknown names.+ * - The thin client's `gbrain doctor --tier ops` / `--only persistence_capacity`+ * asks the serve what it lists: run_doctor with the parameters, else the+ * read-scope bands, else the structured handoff `doctor_tier_unavailable`.+ * - `/admin/api/ops` is served from one ops run a minute.+ * - Capacity fixes verify through MCP `get_brain_health` as well as the CLI.+ */+import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, test } from 'bun:test';+import { createServer, type Server } from 'http';+import { randomUUID } from 'crypto';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import type { OperationContext } from '../src/core/ops/contract.ts';+import { operations } from '../src/core/operations.ts';+import { BRAIN_HEALTH_TTL_MS, countBand, readBrainHealthBands } from '../src/commands/doctor/brain-health-bands.ts';+import { runRemoteDoctorTier } from '../src/commands/doctor/remote-tier.ts';+import { cachedOpsSnapshot, OPS_SNAPSHOT_TTL_MS } from '../src/commands/doctor/ops-snapshot.ts';+import { opsCheckNames } from '../src/commands/doctor/registry.ts';+import { capacityVerify } from '../src/core/persistence/capacity-view.ts';+import { runScopedRemoteDoctor } from '../src/core/doctor-remote-tier.ts';+import { _resetCliExitVerdictForTests, currentExitCode } from '../src/core/cli-force-exit.ts';+import type { GBrainConfig } from '../src/core/config.ts';++let engine: PGLiteEngine;++beforeAll(async () => {+ engine = new PGLiteEngine();+ await engine.connect({});+ await engine.initSchema();+ await engine.executeRaw("INSERT INTO sources(id,name) VALUES('acme-a','acme-a'),('fund-b','fund-b') ON CONFLICT DO NOTHING");+}, 120_000);++afterAll(async () => {+ await engine.disconnect();+});++async function seedFailures(source: string, count: number): Promise<void> {+ for (let i = 0; i < count; i++) {+ await engine.executeRaw(`INSERT INTO persistence_requests(principal_kind,principal_id,request_id,operation,source_id,source_incarnation,slug,digest,authority,intent_bytes,terminal_reservation,+ state,error_code,error_message,intent,completed_at,updated_at,admitter_version)+ VALUES('local_cli','fixture',$1::uuid,'put_page',$2,(SELECT incarnation FROM sources WHERE id=$2),$3,$4,'{}'::jsonb,0,0,'failed','made_up_code','fixture failure','{"content":"x"}'::jsonb,+ now()-interval '1 hour',now()-interval '1 hour','0.60.229.0')`,+ [randomUUID(), source, `notes/alice-example-${source}-${i}`, randomUUID()]);+ }+}++function ctx(o: Partial<OperationContext> = {}): OperationContext {+ return { engine, remote: true, transport: 'http', sourceId: 'default', config: {} as never,+ logger: { info() {}, warn() {}, error() {} }, ...o } as unknown as OperationContext;+}++describe('get_brain_health bands', () => {+ test('the operation is read scope, takes no parameters and is not admin-only', () => {+ const op = operations.find((o) => o.name === 'get_brain_health')!;+ expect(op.scope).toBe('read');+ expect(op.mutating).toBe(false);+ expect(Object.keys(op.params)).toEqual([]);+ const runDoctor = operations.find((o) => o.name === 'run_doctor')!;+ expect(runDoctor.scope).toBe('admin');+ expect(Object.keys(runDoctor.params)).toEqual(expect.arrayContaining(['tier', 'only']));+ });++ test('countBand never leaks an exact count', () => {+ expect([0, 1, 9, 10, 99, 100, 999, 1000, 50_000].map(countBand)).toEqual(['none', '1-9', '1-9', '10-99', '10-99', '100-999', '100-999', '1000+', '1000+']);+ expect(countBand(null)).toBe('unknown');+ expect(countBand(Number.NaN)).toBe('unknown');+ });++ test('write failures are banded per readable source; no slug, request id or exact count leaves', async () => {+ await engine.executeRaw('DELETE FROM persistence_requests');+ await seedFailures('acme-a', 12);+ await seedFailures('fund-b', 3);+ const t = Date.now() + 10 * BRAIN_HEALTH_TTL_MS;+ const acme = await readBrainHealthBands(engine, { sourceIds: ['acme-a'] }, t);+ const fund = await readBrainHealthBands(engine, { sourceIds: ['fund-b'] }, t);+ const all = await readBrainHealthBands(engine, {}, t);+ expect(acme.write_failures.band).toBe('10-99');+ expect(fund.write_failures.band).toBe('1-9');+ expect(all.write_failures.band).toBe('10-99');+ expect(['ok', 'low', 'critical', 'unknown']).toContain(acme.capacity.band);- expect(acme.capacity.forecast).toBe('unavailable');++ expect(acme.capacity.forecast).toBe('available');++ expect(acme.capacity.days).toBe('over_365');++ expect(acme.capacity.band).toBe('ok');+ expect(['none', '1-9', '10-99', '100-999', '1000+', 'unknown']).toContain(acme.unsearchable.band);+ expect(typeof acme.unsearchable.lower_bound).toBe('boolean');+ expect(['none', '1-9', '10-99', '100-999', '1000+', 'unknown']).toContain(acme.ghost_pages.band);+ expect(acme.host_command).toEqual(['gbrain', 'doctor', '--tier', 'ops', '--json']);+ const wire = JSON.stringify([acme, fund, all]);+ expect(wire).not.toMatch(/alice-example|"12"|:12\b|:15\b|:3\b/);+ });++ test('cached 60 s per engine and scope', async () => {+ const t = Date.now() + 100 * BRAIN_HEALTH_TTL_MS;+ const first = readBrainHealthBands(engine, { sourceIds: ['acme-a'] }, t);+ expect(readBrainHealthBands(engine, { sourceIds: ['acme-a'] }, t + BRAIN_HEALTH_TTL_MS - 1)).toBe(first);+ expect(readBrainHealthBands(engine, { sourceIds: ['fund-b'] }, t)).not.toBe(first);+ expect(readBrainHealthBands(engine, { sourceIds: ['acme-a'] }, t + BRAIN_HEALTH_TTL_MS)).not.toBe(first);+ await first;+ });++ test('the handler scopes to the caller grant', async () => {+ const op = operations.find((o) => o.name === 'get_brain_health')!;+ const out = await op.handler(ctx({ sourceId: 'fund-b' }), {}) as { write_failures: { band: string } };+ expect(['1-9', 'unknown']).toContain(out.write_failures.band);+ });++ test('capacity fixes verify through MCP get_brain_health and the CLI', () => {+ expect(capacityVerify()).toMatchObject({ argv: ['gbrain', 'doctor', '--only', 'persistence_capacity', '--json'], mcp: { tool: 'get_brain_health', arguments: {} } });+ });+});++describe('run_doctor tier / only', () => {+ test('tier ops runs only the ops sections on the serve', async () => {+ const report = await runRemoteDoctorTier(ctx({ remote: false }), { tier: 'ops' });+ const ops = opsCheckNames();+ expect(report.checks.length).toBeGreaterThan(0);+ expect(report.checks.every((c) => ops.has(c.name) || c.name === 'connection')).toBe(true);+ expect(report.tier).toBe('ops');+ expect(report.complete).toBe(true);+ });++ test('only narrows to the named section', async () => {+ const report = await runRemoteDoctorTier(ctx(), { only: ['persistence_capacity'] });+ expect(report.checks.map((c) => c.name)).toEqual(['persistence_capacity']);+ });++ test('other tiers and unknown names are invalid_params', async () => {+ await expect(runRemoteDoctorTier(ctx(), { tier: 'deep' })).rejects.toMatchObject({ code: 'invalid_params' });+ await expect(runRemoteDoctorTier(ctx(), { only: ['no_such_check'] })).rejects.toMatchObject({ code: 'invalid_params' });+ await expect(runRemoteDoctorTier(ctx(), { only: [] })).rejects.toMatchObject({ code: 'invalid_params' });+ });+});++describe('/admin/api/ops snapshot', () => {+ test('one ops run per engine a minute', async () => {+ const t = Date.now();+ const first = cachedOpsSnapshot(engine, t);+ expect(cachedOpsSnapshot(engine, t + OPS_SNAPSHOT_TTL_MS - 1)).toBe(first);+ const snap = await first;+ expect(snap.report.tier).toBe('ops');+ expect(cachedOpsSnapshot(engine, t + OPS_SNAPSHOT_TTL_MS)).not.toBe(first);+ });+});++// ---- thin client against a scripted serve ----------------------------------+let server: Server;+let port: number;+let listed: Array<{ name: string; inputSchema: Record<string, unknown> }> = [];+let results: Record<string, unknown> = {};+let calls: Array<{ name: string; args: unknown }> = [];++describe('thin-client doctor --tier ops / --only routing', () => {+ beforeAll(async () => {+ server = createServer((req, res) => {+ if (req.url === '/.well-known/oauth-authorization-server') {+ res.setHeader('Content-Type', 'application/json');+ res.end(JSON.stringify({ token_endpoint: `http://localhost:${port}/token` }));+ return;+ }+ if (req.url === '/token') {+ res.setHeader('Content-Type', 'application/json');+ res.end(JSON.stringify({ access_token: `t-${randomUUID()}`, token_type: 'bearer', expires_in: 3600, scope: 'read' }));+ return;+ }+ let body = '';+ req.on('data', (c) => { body += c; });+ req.on('end', () => {+ const msg = JSON.parse(body || '{}') as { id?: number; method?: string; params?: { name?: string; arguments?: unknown } };+ if (msg.id === undefined) { res.statusCode = 202; res.end(); return; }+ res.setHeader('Content-Type', 'application/json');+ const reply = (result: unknown) => res.end(JSON.stringify({ jsonrpc: '2.0', id: msg.id, result }));+ if (msg.method === 'initialize') return reply({ protocolVersion: '2025-03-26', capabilities: { tools: {} }, serverInfo: { name: 'fixture', version: '1' } });+ if (msg.method === 'tools/list') return reply({ tools: listed });+ if (msg.method === 'tools/call') {+ calls.push({ name: msg.params!.name!, args: msg.params!.arguments });+ return reply({ content: [{ type: 'text', text: JSON.stringify(results[msg.params!.name!] ?? {}) }] });+ }+ reply({});+ });+ });+ await new Promise<void>((r) => server.listen(0, '127.0.0.1', () => r()));+ port = (server.address() as { port: number }).port;+ });+ afterAll(async () => { await new Promise<void>((r) => server.close(() => r())); });++ let out = '';+ const restore: Array<() => void> = [];+ beforeEach(() => {+ listed = []; results = {}; calls = []; out = '';+ _resetCliExitVerdictForTests();+ const so = process.stdout.write.bind(process.stdout), se = process.stderr.write.bind(process.stderr), log = console.log;+ process.stdout.write = ((s: string) => { out += s; return true; }) as typeof process.stdout.write;+ process.stderr.write = ((s: string) => { out += s; return true; }) as typeof process.stderr.write;+ console.log = (...a: unknown[]) => { out += a.join(' ') + '\n'; };+ restore.push(() => { process.stdout.write = so; process.stderr.write = se; console.log = log; });+ });+ afterEach(() => { while (restore.length) restore.pop()!(); _resetCliExitVerdictForTests(); });++ const config = (): GBrainConfig => ({ engine: 'postgres', remote_mcp: { issuer_url: `http://localhost:${port}`, mcp_url: `http://localhost:${port}/mcp`,+ oauth_client_id: `client-${randomUUID()}`, oauth_client_secret: 's' } } as GBrainConfig);+ const tool = (name: string, props: string[] = []) => ({ name, inputSchema: { type: 'object', properties: Object.fromEntries(props.map((p) => [p, { type: 'string' }])) } });+ const bands = { schema_version: 1, status: 'attention', capacity: { band: 'low', days: '7_to_30', max_pct_band: '80-95', forecast: 'available' },+ write_failures: { band: '1-9', active_blockers: 'none', window_days: 30 }, host_command: ['gbrain', 'doctor', '--tier', 'ops', '--json'] };++ test('an admin token on a current serve: run_doctor with tier ops', async () => {+ listed = [tool('run_doctor', ['tier', 'only']), tool('get_brain_health')];+ results.run_doctor = { status: 'healthy', tier: 'ops', checks: [{ name: 'persistence_capacity', status: 'ok', message: 'fine' }] };+ await runScopedRemoteDoctor(config(), { tier: 'ops', only: null, json: true, label: '--tier ops' });+ expect(calls).toEqual([{ name: 'run_doctor', args: { tier: 'ops' } }]);+ expect(JSON.parse(out)).toMatchObject({ tier: 'ops', checks: [{ name: 'persistence_capacity' }] });+ expect(currentExitCode()).toBe(0);+ });++ test('a read token (run_doctor not listed): --only persistence_capacity answers from get_brain_health bands', async () => {+ listed = [tool('get_brain_health')];+ results.get_brain_health = bands;+ await runScopedRemoteDoctor(config(), { only: new Set(['persistence_capacity']), json: true, label: '--only persistence_capacity' });+ expect(calls.map((c) => c.name)).toEqual(['get_brain_health']);+ const report = JSON.parse(out);+ expect(report).toMatchObject({ mode: 'bands', source: 'get_brain_health', status: 'warnings' });+ expect(report.checks).toEqual([expect.objectContaining({ name: 'persistence_capacity', status: 'warn', details: expect.objectContaining({ band: 'low' }) })]);+ });++ test('an older serve: structured handoff doctor_tier_unavailable, never the full report', async () => {+ listed = [tool('run_doctor'), tool('get_brain_identity')];+ await runScopedRemoteDoctor(config(), { tier: 'ops', only: null, json: true, label: '--tier ops' });+ expect(calls).toEqual([]);+ expect(out).toContain('doctor_tier_unavailable');+ expect(out).toContain('gbrain doctor --tier ops --json');+ expect(currentExitCode()).not.toBe(0);+ });++ test('a read token asking for a check the bands do not cover: handoff', async () => {+ listed = [tool('get_brain_health')];- await runScopedRemoteDoctor(config(), { only: new Set(['receipt_compaction']), json: true, label: '--only receipt_compaction' });++ await runScopedRemoteDoctor(config(), { only: new Set(['persistence_compaction']), json: true, label: '--only persistence_compaction' });+ expect(calls).toEqual([]);+ expect(out).toContain('doctor_tier_unavailable');+ });++ test('--tier deep is never served remotely', async () => {+ await runScopedRemoteDoctor(config(), { tier: 'deep', only: null, json: true, label: '--tier deep' });+ expect(out).toContain('doctor_tier_unavailable');+ });+});diff --cc test/doctor-tier-6696.test.tsindex 8cecc3b7e3,0000000000..4623fc7f63mode 100644,000000..100644--- a/test/doctor-tier-6696.test.ts+++ b/test/doctor-tier-6696.test.ts@@@ -1,165 -1,0 +1,165 @@@+/**+ * #6696 B1: doctor tiers and budgets (in-process, PGLite).+ *+ * - `--tier ops` runs only the ops sections plus the connection lane, reads no+ * page aggregate (getHealth / findOrphanPages / getStats throw if called) on a+ * 2,000-page brain, reports PGLite-skipped sections as `not_applicable` info,+ * and stays complete.+ * - The default run puts every ops section before the slower checks and reads+ * getHealth once.+ * - A section past the deadline (or the per-entry budget) is unknown with+ * `reason: budget`, `exact: false`, `elapsed_ms`; the report says+ * `complete: false` and names it.+ * - `orphan_ratio` estimates above `doctor.orphan_ratio.full_scan_max_pages`+ * and scans fully under `--tier deep`.+ * - A connect the deadline ended reports every check of the tier as unknown.+ */+import { afterAll, beforeAll, beforeEach, describe, expect, test } from 'bun:test';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import type { BrainEngine } from '../src/core/engine.ts';+import { sqlQueryForEngine } from '../src/core/sql-query.ts';+import { resetPgliteState } from './helpers/reset-pglite.ts';+import { buildChecks, computeDoctorReport, doctorRunSummary, type Check } from '../src/commands/doctor.ts';+import { DOCTOR_CHECK_REGISTRY, opsCheckNames } from '../src/commands/doctor/registry.ts';+import { DoctorBudgetError, parseBudgetMs, parseDoctorTier, startDoctorDeadline, OPS_BUDGET_MS_DEFAULT } from '../src/commands/doctor/budget.ts';+import { ORPHAN_FULL_SCAN_KEY } from '../src/commands/doctor/checks/orphan-estimate.ts';++let engine: PGLiteEngine;++beforeAll(async () => {+ engine = new PGLiteEngine();+ await engine.connect({ database_url: '' });+ await engine.initSchema();+});++afterAll(async () => {+ await engine.disconnect();+});++beforeEach(async () => {+ await resetPgliteState(engine);+});++async function insertNotes(count: number, prefix = 'notes/acme-example'): Promise<void> {+ const sql = sqlQueryForEngine(engine);+ await sql`+ INSERT INTO pages (slug, source_id, type, title, compiled_truth, frontmatter, content_hash, created_at, updated_at)+ SELECT ${prefix}::text || '-' || g, 'default', 'note', 'Note ' || g, '', '{}', ${prefix}::text || '-h' || g, now(), now()+ FROM generate_series(1, ${count}::int) AS g+ `;+}++/** The engine with the named methods throwing, and executeRaw optionally delayed for statements matching `slow`. */+function guarded(throwing: string[], slow?: { match: RegExp; ms: number }, calls?: Record<string, number>): BrainEngine {+ return new Proxy(engine, {+ get(target, key) {+ if (typeof key === 'string' && throwing.includes(key)) return () => { throw new Error(`${key} must not run in this tier`); };+ if (key === 'getHealth' && calls) return (...a: unknown[]) => { calls.getHealth = (calls.getHealth ?? 0) + 1; return target.getHealth(...(a as [])); };+ if (key === 'executeRaw' && slow) {+ return async (sql: string, params?: unknown[], opts?: unknown) => {+ if (slow.match.test(sql)) await new Promise((r) => setTimeout(r, slow.ms));+ return target.executeRaw(sql, params, opts as never);+ };+ }+ const value = Reflect.get(target, key, target);+ return typeof value === 'function' ? value.bind(target) : value;+ },+ }) as BrainEngine;+}++const names = (checks: Check[]) => checks.map((c) => c.name);++describe('#6696 B1 doctor tiers', () => {+ test('parses --tier and --budget-ms; ops defaults to a 4000 ms deadline, others to none', () => {+ expect(parseDoctorTier([])).toBe('standard');+ expect(parseDoctorTier(['--tier', 'ops'])).toBe('ops');+ expect(parseDoctorTier(['--tier=deep'])).toBe('deep');+ expect(() => parseDoctorTier(['--tier', 'fast'])).toThrow(/Unknown doctor tier/);+ expect(parseBudgetMs(['--tier', 'ops'], 'ops')).toBe(OPS_BUDGET_MS_DEFAULT);+ expect(parseBudgetMs([], 'standard')).toBeNull();+ expect(parseBudgetMs(['--budget-ms', '900'], 'standard')).toBe(900);+ expect(() => parseBudgetMs(['--budget-ms', '0'], 'ops')).toThrow(/positive integer/);+ });++ test('--tier ops on a 2,000-page PGLite brain: only ops sections, no page aggregates, complete, PGLite skips are not_applicable info', async () => {+ await insertNotes(2000);+ const args = ['--json', '--tier', 'ops'];+ const deadline = startDoctorDeadline(args);+ const checks = await buildChecks(guarded(['getHealth', 'findOrphanPages', 'getStats']), args, undefined, undefined, deadline);+ const ops = opsCheckNames();+ expect(names(checks).filter((n) => n !== 'connection').every((n) => ops.has(n))).toBe(true);- for (const n of ['persistence_capacity', 'persistence_terminal_failures', 'managed_sync_not_moving', 'receipt_compaction', 'serve_build_drift', 'schema_pack_consistency', 'embedding_state']) {++ for (const n of ['persistence_capacity', 'persistence_terminal_failures', 'managed_sync_not_moving', 'persistence_compaction', 'serve_build_drift', 'schema_pack_consistency', 'embedding_state']) {+ expect(names(checks)).toContain(n);+ }+ expect(checks.filter((c) => c.status !== 'ok')).toEqual([]);+ const skipped = checks.filter((c) => c.details?.health === 'not_applicable');+ expect(skipped.map((c) => c.name).sort()).toEqual(['embedding_state', 'managed_sync_not_moving', 'persistence_terminal_failures', 'schema_pack_consistency']);+ for (const c of skipped) expect(c.severity).toBe('info');+ const report = computeDoctorReport(checks, { engine: 'pglite', run: doctorRunSummary(args, deadline) });+ expect(report.tier).toBe('ops');+ expect(report.complete).toBe(true);+ expect(report.unknown_sections).toEqual([]);+ expect(report.budget_ms).toBe(OPS_BUDGET_MS_DEFAULT);+ expect(checks.every((c) => typeof c.elapsed_ms === 'number')).toBe(true);+ });++ test('the default run puts every ops section before the slower checks and reads getHealth once', async () => {+ const calls: Record<string, number> = {};+ const checks = await buildChecks(guarded([], undefined, calls), ['--json', '--scope=brain']);+ const order = names(checks);+ const ops = [...opsCheckNames()].filter((n) => order.includes(n));+ const firstSlow = order.indexOf('pgvector');+ expect(firstSlow).toBeGreaterThan(0);+ for (const n of ops) expect(order.indexOf(n)).toBeLessThan(firstSlow);+ expect(calls.getHealth).toBe(1);+ expect(checks.every((c) => typeof c.elapsed_ms === 'number')).toBe(true);+ // The registry tags exactly the plan's ops sections.+ expect(DOCTOR_CHECK_REGISTRY.filter((e) => e.tier === 'ops').map((e) => e.name)).toEqual(- expect.arrayContaining(['persistence_capacity', 'persistence_terminal_failures', 'managed_sync_not_moving', 'receipt_compaction', 'serve_build_drift', 'schema_pack_consistency', 'embedding_state']));++ expect.arrayContaining(['persistence_capacity', 'persistence_terminal_failures', 'managed_sync_not_moving', 'persistence_compaction', 'serve_build_drift', 'schema_pack_consistency', 'embedding_state']));+ });++ test('a section past the --budget-ms deadline is unknown (reason budget) and the report is incomplete', async () => {+ const args = ['--json', '--tier', 'ops', '--budget-ms', '150'];+ const deadline = startDoctorDeadline(args);+ const started = Date.now();+ const checks = await buildChecks(guarded([], { match: /FROM persistence_counters/, ms: 600 }), args, undefined, undefined, deadline);+ expect(Date.now() - started).toBeLessThan(600);+ const capacity = checks.find((c) => c.name === 'persistence_capacity')!;+ expect(capacity.status).toBe('warn');+ expect(capacity.details).toMatchObject({ health: 'unknown', reason: 'budget', exact: false });+ expect(typeof capacity.elapsed_ms).toBe('number');+ expect(capacity.fix).toBeDefined();+ const report = computeDoctorReport(checks, { engine: 'pglite', run: doctorRunSummary(args, deadline) });+ expect(report.complete).toBe(false);+ expect(report.unknown_sections).toContain('persistence_capacity');+ });++ test('the per-entry budget (doctor.entry_budget_ms) bounds a standard-tier entry', async () => {+ await engine.setConfig('doctor.entry_budget_ms', '100');+ const checks = await buildChecks(guarded([], { match: /FROM persistence_counters/, ms: 500 }), ['--json', '--scope=brain', '--only', 'persistence_capacity']);+ const capacity = checks.find((c) => c.name === 'persistence_capacity')!;+ expect(capacity.details).toMatchObject({ health: 'unknown', reason: 'budget', budget_ms: 100 });+ });++ test('a connect the deadline ended: connection and every ops section are unknown, nothing claims clear', async () => {+ const args = ['--json', '--tier', 'ops', '--budget-ms', '50'];+ const deadline = startDoctorDeadline(args);+ const checks = await buildChecks(null, args, 'config-file', new DoctorBudgetError(60), deadline);+ const connection = checks.find((c) => c.name === 'connection')!;+ expect(connection.details).toMatchObject({ health: 'unknown', reason: 'budget' });+ for (const n of opsCheckNames()) expect(checks.find((c) => c.name === n)?.details?.health).toBe('unknown');+ expect(computeDoctorReport(checks, { run: doctorRunSummary(args, deadline) }).complete).toBe(false);+ });++ test('orphan_ratio estimates above the full-scan cutoff in standard and scans fully under --tier deep', async () => {+ await insertNotes(400, 'people/alice-example');+ await engine.executeRaw(`UPDATE pages SET type = 'person' WHERE slug LIKE 'people/%'`);+ await engine.setConfig(ORPHAN_FULL_SCAN_KEY, '100');+ const standard = (await buildChecks(engine, ['--json', '--scope=brain', '--only', 'orphan_ratio'])).find((c) => c.name === 'orphan_ratio')!;+ expect(standard.details).toMatchObject({ estimated: true, exact: false, full_scan_max_pages: 100 });+ expect(standard.message).toMatch(/estimated/);+ const deep = (await buildChecks(engine, ['--json', '--scope=brain', '--tier', 'deep', '--only', 'orphan_ratio'])).find((c) => c.name === 'orphan_ratio')!;+ expect(deep.details?.estimated).toBeUndefined();+ expect(deep.message).toMatch(/400\/400 linkable pages/);+ });+});diff --cc test/file-drift-bulk-reconcile.test.tsindex a6be209ed3,0000000000..d8c98a8e67mode 100644,000000..100644--- a/test/file-drift-bulk-reconcile.test.ts+++ b/test/file-drift-bulk-reconcile.test.ts@@@ -1,271 -1,0 +1,293 @@@+/**+ * #6696 PR C, C7: bulk file-drift reconcile.+ *+ * `gbrain repair file-drift` takes repeatable `--only` / `--skip` globs over+ * the canonical file path, like the other kinds' `--only` (`*` within a+ * segment, `**` across segments, an exact path matches itself), bound into the preview hash and+ * carried through the printed apply command, so executing that exact command+ * applies exactly the selected pages. `--keep` is refused on file-drift with a+ * pointer at `--prefer database`. An opt-in `storage.keep_db` list in+ * gbrain.yml lets the trusted local maintenance worker on the canonical owner+ * host reconcile drifted pages under those prefixes with the database copy, one+ * rate-limited request per page; doctor `maintenance_write_drift` echoes the+ * policy, how many drifted pages it matches and their receipt cost.+ *+ * Runs on PGLite, and on Postgres when DATABASE_URL is set+ * (test/e2e/file-drift-bulk-reconcile-postgres.test.ts).+ */+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';+import { execFileSync } from 'node:child_process';+import { randomUUID } from 'node:crypto';+import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import type { BrainEngine } from '../src/core/engine.ts';+import type { OperationContext } from '../src/core/operations.ts';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { claimWorktree } from '../src/core/persistence/ownership.ts';+import { submitPageMutation } from '../src/core/persistence/page-mutations.ts';+import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';+import { DRIFT_SKIPS_KEY, liveFileDrift } from '../src/core/persistence/drift-conflicts.ts';+import { existingLocalHostId } from '../src/core/persistence/identity.ts';+import { argvFromCommand } from '../src/core/agent-output.ts';+import { parseRepairArgs, runRepairCommand } from '../src/commands/repair.ts';+import { repairRunner } from '../src/core/repair/registry.ts';+import { resolveRepairScope } from '../src/core/repair/core.ts';+import { maintenanceWriteDriftCheck } from '../src/commands/doctor/checks/maintenance-drift.ts';+import { __resetMissingStorageWarning, loadStorageConfig } from '../src/core/storage-config.ts';+import { configureGateway, resetGateway } from '../src/core/ai/gateway.ts';+import { withEnv } from './helpers/with-env.ts';+import { requirePostgresTestDatabase, testBackends } from './helpers/test-backends.ts';+import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';++const logger = { info() {}, warn() {}, error() {} };+const CONCEPTS = ['concepts/alpha-example', 'concepts/beta-example', 'concepts/gamma-example'];+const PERSON = 'people/alice-example';++describe('C7 file-drift argument rules', () => {+ test('--only and --skip are repeatable file path globs on file-drift', () => {+ const parsed = parseRepairArgs(['file-drift', '--source', 'default', '--all-drifted', '--only', 'concepts/**', '--only', 'ideas/*',+ '--skip', 'concepts/archive/**', '--prefer', 'database']);+ expect(parsed).toMatchObject({ kind: 'file-drift', allDrifted: true, prefer: 'database', only: ['concepts/**', 'ideas/*'], skip: ['concepts/archive/**'] });+ });+ test('--keep on file-drift is refused with a pointer at --prefer database, wherever it appears', () => {+ for (const args of [['file-drift', '--source', 'default', '--all-drifted', '--keep', 'db'], ['--keep', 'prior', 'file-drift', '--slug', 'notes/a'],+ ['file-drift', '--keep=disk', '--slug', 'notes/a', '--apply', '--expect', 'abc']]) {+ let error: { code?: string; message?: string; suggestion?: string; fix?: { argv?: string[] } } | undefined;+ try { parseRepairArgs(args); } catch (caught) { error = caught as never; }+ expect(error?.code).toBe('invalid_params');+ expect(error?.message).toContain('--keep');+ expect(error?.suggestion).toContain('--prefer database');+ expect(error?.fix?.argv).toContain('--prefer');+ expect(error?.fix?.argv).not.toContain('--keep');+ expect(error?.fix?.argv).not.toContain('--apply');+ }+ });+ test('stuck-recovery keeps validating --keep values', () => {+ expect(() => parseRepairArgs(['stuck-recovery', '--keep', 'db'])).toThrow('--keep must be prior or disk');+ expect(parseRepairArgs(['stuck-recovery', '--keep', 'disk']).keep).toBe('disk');+ });+});++describe('C7 doctor on a fresh keyless PGLite brain', () => {+ let engine: PGLiteEngine;+ beforeAll(async () => { engine = new PGLiteEngine(); await engine.connect({}); await engine.initSchema(); }, 120_000);+ afterAll(async () => { await engine.disconnect(); });+ test('maintenance_write_drift stays ok and echoes no keep_db policy', async () => {+ const check = await maintenanceWriteDriftCheck(engine);+ expect(check.status).toBe('ok');+ expect(check.details).not.toHaveProperty('keep_db_policy');+ });+});++describe('C7 storage.keep_db in gbrain.yml', () => {+ test('keep_db is a declared prefix list, normalized like the tiers, and an unknown storage key warns', () => {+ const dir = mkdtempSync(join(tmpdir(), 'gbrain-c7-yml-'));+ const warnings: string[] = [];+ const original = console.warn;+ console.warn = (...args: unknown[]) => { warnings.push(args.join(' ')); };+ try {+ __resetMissingStorageWarning();+ writeFileSync(join(dir, 'gbrain.yml'), 'storage:\n db_tracked:\n - people/\n keep_db:\n - concepts\n - ideas/\n kep_db:\n - extracts/\n');+ expect(loadStorageConfig(dir)).toEqual({ db_tracked: ['people/'], db_only: [], keep_db: ['concepts/', 'ideas/'] });+ expect(warnings.some(line => line.includes("'kep_db'") && line.includes('keep_db'))).toBe(true);+ __resetMissingStorageWarning();+ warnings.length = 0;+ writeFileSync(join(dir, 'gbrain.yml'), 'storage:\n keep_db:\n - concepts/\n');+ expect(loadStorageConfig(dir)).toEqual({ db_tracked: [], db_only: [], keep_db: ['concepts/'] });+ expect(warnings.filter(line => line.includes('no storage configuration'))).toEqual([]);+ } finally {+ console.warn = original;+ __resetMissingStorageWarning();+ rmSync(dir, { recursive: true, force: true });+ }+ });+});++for (const backend of testBackends()) describe(`C7 bulk file-drift reconcile (${backend})`, () => {+ let engine: BrainEngine;+ let closePostgres: (() => Promise<void>) | undefined;+ const dataDir = mkdtempSync(join(tmpdir(), 'gbrain-c7-db-'));++ beforeAll(async () => {+ configureGateway({ embedding_model: 'openai:text-embedding-3-large', embedding_dimensions: 1536, env: {} });+ if (backend === 'pglite') {+ const pglite = new PGLiteEngine();+ await pglite.connect({ database_path: dataDir }); await pglite.initSchema(); engine = pglite;+ } else {+ const pg = await isolatedPersistencePostgres(requirePostgresTestDatabase());+ engine = pg.engine; closePostgres = pg.close;+ }+ }, 120_000);+ afterAll(async () => {+ await disposePersistenceConsumer(engine);+ if (closePostgres) await closePostgres(); else await engine.disconnect();+ resetGateway(); rmSync(dataDir, { recursive: true, force: true });+ });++ async function fixture(run: (input: { root: string; sourceId: string; ctx: OperationContext }) => Promise<void>): Promise<void> {+ const dir = mkdtempSync(join(tmpdir(), 'gbrain-c7-'));+ const root = join(dir, 'brain'); mkdirSync(root);+ execFileSync('git', ['init', '-q'], { cwd: root });+ const sourceId = `c7-${randomUUID().slice(0, 8)}`;+ try {+ await withEnv({ GBRAIN_HOME: join(dir, 'home') }, async () => {+ await engine.executeRaw('INSERT INTO sources(id,name,local_path) VALUES($1,$1,$2)', [sourceId, root]);+ await engine.setConfig('sync.write_through', 'true');+ await claimWorktree(engine, sourceId, root);+ await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1');+ const ctx = { engine, sourceId, remote: false, config: { engine: engine.kind, embedding_disabled: true } as never, dryRun: false, logger } as OperationContext;+ await run({ root, sourceId, ctx });+ });+ } finally {+ await disposePersistenceConsumer(engine);+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');+ await engine.unsetConfig(DRIFT_SKIPS_KEY);+ await engine.unsetConfig('persistence.limits.principal_lifetime_ids');+ rmSync(dir, { recursive: true, force: true });+ }+ }++ const put = (ctx: OperationContext, slug: string, content: string) =>+ submitPageMutation(ctx, { operation: 'put_page', params: { slug, content, request_id: randomUUID() } });+ const drift = (root: string, slug: string, edit: (text: string) => string) => {+ const file = join(root, `${slug}.md`);+ writeFileSync(file, edit(readFileSync(file, 'utf8')));+ };+ /** A caller write refused source_changed: one conflict receipt for the slug. */+ const refusedWrite = async (ctx: OperationContext, slug: string) => {+ const expected_revision = (await engine.readPageSnapshot(slug, { sourceId: ctx.sourceId! }))!.revision;+ await submitPageMutation(ctx, { operation: 'put_page', params: { slug, content: '---\ntype: note\ntitle: Refused\n---\nRefused.\n', expected_revision, request_id: randomUUID() } })+ .then(() => { throw new Error(`write to ${slug} committed`); }, (error: { code?: string }) => expect(error.code).toBe('source_changed'));+ };+ const requests = async (sourceId: string) => Number((await engine.executeRaw<{ n: number }>(+ 'SELECT count(*)::int AS n FROM persistence_requests WHERE source_id=$1', [sourceId]))[0].n);+ const stillDrifted = async (sourceId: string, slugs: string[]) => {+ const drifted: string[] = [];+ for (const slug of slugs) if ((await liveFileDrift(engine, sourceId, slug)).still_present === true) drifted.push(slug);+ return drifted;+ };+ /** Three concepts drifted by an appended line, one person rewritten (another drift class); each with a conflict receipt. */+ async function driftedPages(root: string, ctx: OperationContext): Promise<void> {+ for (const slug of CONCEPTS) await put(ctx, slug, `---\ntype: concept\ntitle: ${slug.slice(9)}\n---\nStored ${slug}.\n`);+ await put(ctx, PERSON, '---\ntype: person\ntitle: Alice Example\n---\nOriginal sentence.\n');+ for (const slug of CONCEPTS) drift(root, slug, text => `${text}\nA line added in the file only.\n`);+ drift(root, PERSON, text => text.replace('Original sentence.', 'A different sentence.'));+ for (const slug of [...CONCEPTS, PERSON]) await refusedWrite(ctx, slug);+ expect(await stillDrifted(ctx.sourceId!, [...CONCEPTS, PERSON])).toEqual([...CONCEPTS, PERSON]);+ }+ async function json(args: string[]): Promise<{ results: Array<Record<string, unknown>> }> {+ const lines: string[] = [];+ const original = console.log;+ console.log = (...values: unknown[]) => { lines.push(values.join(' ')); };+ try { await runRepairCommand(engine, [...args, '--json']); } finally { console.log = original; }+ return JSON.parse(lines.join('\n'));+ }++ test('--all-drifted --only concepts/** previews 3 of 4 drifted pages, and executing the exact returned command applies exactly those 3', () => fixture(async ({ root, sourceId, ctx }) => {+ await driftedPages(root, ctx);+ const preview = (await json(['file-drift', '--source', sourceId, '--all-drifted', '--only', 'concepts/**', '--prefer', 'database'])).results[0]!;+ expect(preview).toMatchObject({ mode: 'dry_run', affected: 3 });+ expect(preview.sample).toEqual(CONCEPTS.map(slug => `${sourceId}:${slug}`));+ const command = String(preview.apply_command);+ expect(command).toContain("--only 'concepts/**'");+ expect(command).toContain(`--expect ${preview.preview_hash}`);+ const argv = argvFromCommand(command)!;+ expect(argv.slice(0, 2)).toEqual(['gbrain', 'repair']);+ const before = await requests(sourceId);+ const applied = (await json(argv.slice(2))).results[0]!;+ expect(applied).toMatchObject({ mode: 'apply', applied: 3, complete: true, outcomes: { repaired: 3 } });+ expect(await requests(sourceId)).toBe(before + 3);+ expect(await stillDrifted(sourceId, [...CONCEPTS, PERSON])).toEqual([PERSON]);+ expect((await engine.getPage(CONCEPTS[0]!, { sourceId }))!.compiled_truth).toBe(`Stored ${CONCEPTS[0]}.`);+ }), 240_000);++ test('the globs are bound into the preview hash: --skip narrows the set, and an apply under other globs refuses preview_changed', () => fixture(async ({ root, sourceId, ctx }) => {+ await driftedPages(root, ctx);+ const scope = await resolveRepairScope(engine, sourceId);+ const runner = await repairRunner(engine, { apply: false, logger });+ const mixed = await runner.run('file-drift', scope, { explicit: true, sourceFlag: sourceId, allDrifted: true, prefer: 'database' }).then(() => null, error => error);+ expect(mixed).toMatchObject({ code: 'invalid_params' });+ const all = await runner.run('file-drift', scope, { explicit: true, sourceFlag: sourceId, allDrifted: true, prefer: 'database', only: ['concepts/*'] });+ const skipped = await runner.run('file-drift', scope, { explicit: true, sourceFlag: sourceId, allDrifted: true, prefer: 'database',+ only: ['concepts/*'], skip: ['concepts/beta-*'] });+ expect(all.affected).toBe(3);+ expect(skipped.affected).toBe(2);+ expect(skipped.sample).toEqual([`${sourceId}:${CONCEPTS[0]}`, `${sourceId}:${CONCEPTS[2]}`]);+ expect(skipped.preview_hash).not.toBe(all.preview_hash);+ expect(skipped.apply_command).toContain("--skip 'concepts/beta-*'");+ const other = await (await repairRunner(engine, { apply: true, logger })).run('file-drift', scope,+ { explicit: true, sourceFlag: sourceId, allDrifted: true, prefer: 'database', only: ['concepts/*'], expect: skipped.preview_hash })+ .then(() => null, error => error);+ expect(other).toMatchObject({ code: 'preview_changed' });+ const bySlug = await runner.run('file-drift', scope, { explicit: true, sourceFlag: sourceId, allDrifted: true, prefer: 'database', only: [CONCEPTS[0]!] });+ expect(bySlug).toMatchObject({ affected: 0, residuals: { not_selected: 4 } });+ const exact = await runner.run('file-drift', scope, { explicit: true, sourceFlag: sourceId, slugs: [CONCEPTS[0]!, PERSON], prefer: 'database',+ only: [`${CONCEPTS[0]}.md`] });+ expect(exact).toMatchObject({ affected: 1, sample: [`${sourceId}:${CONCEPTS[0]}`], residuals: { not_selected: 1 } });+ const bad = await runner.run('file-drift', scope, { explicit: true, sourceFlag: sourceId, allDrifted: true, prefer: 'database', only: ['../concepts/*'] })+ .then(() => null, error => error);+ expect(bad).toMatchObject({ code: 'invalid_params' });+ }), 240_000);++ test('storage.keep_db: the owner host submits one rate-limited reconcile per drifted page under the prefixes; elsewhere and for callers nothing changes', () => fixture(async ({ root, sourceId, ctx }) => {+ writeFileSync(join(root, 'gbrain.yml'), 'storage:\n keep_db:\n - concepts/\n');+ await driftedPages(root, ctx);+ const doctor = await maintenanceWriteDriftCheck(engine, [sourceId]);+ expect(doctor).toMatchObject({ status: 'warn', details: { count: 4, keep_db_policy: [{ source_id: sourceId, keep_db: ['concepts/'], matched: 3,+ receipt_cost: { lifetime_ids: 3, receipt_bytes: 3 * 16_384 } }] } });+ expect(doctor.message).toContain('storage.keep_db');++ const { runKeepDbPolicy } = await import('../src/core/repair/keep-db-policy.ts');+ const ownerHost = () => existingLocalHostId()!;+ const before = await requests(sourceId);+ const elsewhere = await runKeepDbPolicy(engine, { hostId: randomUUID(), sourceIds: [sourceId] });+ expect(elsewhere.submitted).toBe(0);+ expect(await requests(sourceId)).toBe(before);++ const ids = (await engine.executeRaw<{ lifetime_ids: string }>("SELECT lifetime_ids::text FROM persistence_counters WHERE key LIKE 'principal:%' ORDER BY lifetime_ids DESC LIMIT 1"))[0]!;+ await engine.setConfig('persistence.limits.principal_lifetime_ids', ids.lifetime_ids);+ const full = await runKeepDbPolicy(engine, { hostId: ownerHost(), sourceIds: [sourceId] });+ expect(full).toMatchObject({ submitted: 0, stopped: 'capacity' });+ expect(await requests(sourceId)).toBe(before);+ await engine.unsetConfig('persistence.limits.principal_lifetime_ids');++ const first = await runKeepDbPolicy(engine, { hostId: ownerHost(), sourceIds: [sourceId], limit: 2 });+ expect(first).toMatchObject({ submitted: 2, stopped: 'rate_limit' });+ expect(await requests(sourceId)).toBe(before + 2);+ expect(await stillDrifted(sourceId, [...CONCEPTS, PERSON])).toEqual([CONCEPTS[2]!, PERSON]);+ const second = await runKeepDbPolicy(engine, { hostId: ownerHost(), sourceIds: [sourceId], limit: 2 });+ expect(second.submitted).toBe(1);+ expect(await stillDrifted(sourceId, [...CONCEPTS, PERSON])).toEqual([PERSON]);+ expect(readFileSync(join(root, `${CONCEPTS[0]}.md`), 'utf8')).not.toContain('A line added in the file only.');+ const third = await runKeepDbPolicy(engine, { hostId: ownerHost(), sourceIds: [sourceId] });+ expect(third.submitted).toBe(0);+ expect(await requests(sourceId)).toBe(before + 3);+ const reconciles = await engine.executeRaw<{ slug: string; state: string }>(+ "SELECT slug, state FROM persistence_requests WHERE source_id=$1 AND intent->>'kind'='canonical_reconcile' ORDER BY slug", [sourceId]);+ expect(reconciles).toEqual(CONCEPTS.map(slug => ({ slug, state: 'committed' })));+ await refusedWrite(ctx, PERSON);+ }), 240_000);++++ test('storage.keep_db at 81% of a cumulative cap: the worker is refused write_capacity_backpressure and writes no receipt (#6696 A5)', () => fixture(async ({ root, sourceId, ctx }) => {++ writeFileSync(join(root, 'gbrain.yml'), 'storage:\n keep_db:\n - concepts/\n');++ await driftedPages(root, ctx);++ const { runKeepDbPolicy } = await import('../src/core/repair/keep-db-policy.ts');++ const ownerHost = existingLocalHostId()!;++ const [writer] = await engine.executeRaw<{ key: string }>("SELECT 'principal:'||principal_kind||':'||principal_id AS key FROM persistence_requests WHERE source_id=$1 LIMIT 1", [sourceId]);++ const lifetime = async () => (await engine.executeRaw<{ n: string }>('SELECT lifetime_ids::text AS n FROM persistence_counters WHERE key=$1', [writer!.key]))[0]!.n;++ const used = Number(await lifetime());++ const limit = Math.ceil(used * 100 / 81);++ expect(used / limit).toBeGreaterThanOrEqual(0.8);++ expect(used / limit).toBeLessThan(0.9);++ await engine.setConfig('persistence.limits.principal_lifetime_ids', String(limit));++ const before = await requests(sourceId);++ // The default seam sees the pause line before preparing anything.++ expect(await runKeepDbPolicy(engine, { hostId: ownerHost, sourceIds: [sourceId] })).toMatchObject({ submitted: 0, stopped: 'write_capacity_backpressure' });++ // Admission itself refuses this background producer even with the seam open.++ expect(await runKeepDbPolicy(engine, { hostId: ownerHost, sourceIds: [sourceId], admission: async () => null })).toMatchObject({ submitted: 0, stopped: 'write_capacity_backpressure' });++ expect(await requests(sourceId)).toBe(before);++ expect(await lifetime()).toBe(String(used));++ expect(await stillDrifted(sourceId, [...CONCEPTS])).toEqual([...CONCEPTS]);++ }), 240_000);+});diff --cc test/fix-wave-5-integration.test.tsindex 355961bd1e,31ebeef30d..4289d7687b--- a/test/fix-wave-5-integration.test.ts+++ b/test/fix-wave-5-integration.test.ts@@@ -196,7 -196,7 +196,7 @@@ for (const backend of testBackends())const previews = { 'google-file-modes': 'gbrain repair google-file-modes', 'stale-atoms': 'gbrain repair stale-atoms', 'extractor-facts': 'gbrain repair extractor-facts','conversation-labels': 'gbrain repair conversation-labels', 'captured-facts': 'gbrain repair captured-facts', 'loop-facts': 'gbrain repair loop-facts', 'ontology-facts': 'gbrain repair ontology-facts', 'orphan-children': 'gbrain repair orphan-children', 'failed-writes': 'gbrain repair failed-writes',frontmatter: 'gbrain repair frontmatter', 'timeline-comments': 'gbrain repair timeline-comments', 'managed-sync-orphans': 'gbrain repair managed-sync-orphans', 'frontmatter-keys': 'gbrain repair frontmatter-keys', 'file-drift': 'gbrain repair file-drift',- 'stuck-recovery': 'gbrain repair stuck-recovery' };- 'stuck-recovery': 'gbrain repair stuck-recovery', 'receipt-compaction': 'gbrain repair receipt-compaction' };++ 'stuck-recovery': 'gbrain repair stuck-recovery', 'ghost-pages': 'gbrain repair ghost-pages', 'receipt-compaction': 'gbrain repair receipt-compaction' };// The post-upgrade banner names both findings with the kind's read-only preview.const banner = await postUpgradeRecoveryBanner(engine, 'host');diff --cc test/fixtures/goldens/doctor/content-pglite-human.jsonindex 70fd9f97a3,fa48a634e2..e3d0583569--- a/test/fixtures/goldens/doctor/content-pglite-human.json+++ b/test/fixtures/goldens/doctor/content-pglite-human.json@@@ -53,16 -53,12 +53,17 @@@" [INFO] harness_wiring: No agent harness was detected. Wire one when the user picks an agent app."," [OK] agent_contract: No agent dead ends in the last 7 days (0 non-success event(s) logged)."," [OK] connection: Connected, 5 pages",- " [OK] persistence_capacity: Managed write capacity is below 80% of every cumulative limit.",++ " [OK] persistence_capacity: Managed write capacity is below 80% of every cumulative limit and none runs out within 30 days at its 7-day rate.",+ " [OK] persistence_terminal_failures: No terminal write failures in the last 7 d.",+ " [OK] managed_sync_not_moving: No managed sync is pending.",- " [INFO] receipt_compaction: No receipt compaction recorded yet (persistence.maintenance.last_compaction is unset): the persistence consumer records one after it compacts.",++ " [OK] persistence_compaction: Receipt compaction last ran 0 hour(s) ago (compacted 0, freed 0 bytes).",+ " [OK] serve_build_drift: PGLite admits one process; no consumer heartbeat rows are kept to compare builds.",+ " [OK] schema_pack_consistency: All pages match the active schema pack across every source.",+ " [INFO] embedding_state: Embedding state (exact, column 'embedding'): 0 embedded, 7 pending, 0 keyword-only, 0 quarantined, 0 empty, 0 on deleted pages, 0 chunkless (healable); 0 unsearchable. Embeddings are disabled by choice: keyword search reads the pending chunks."," [OK] pgvector: Extension installed"," [OK] pages_upsert_arbiter: pages has the UNIQUE(source_id, slug) upsert arbiter"," [OK] text_projection_readiness: Visible text projections match their canonical revisions.",- " [OK] persistence_capacity: Managed write capacity is below 80% of every cumulative limit and none runs out within 30 days at its 7-day rate.",- " [OK] persistence_compaction: Receipt compaction last ran 0 hour(s) ago (compacted 0, freed 0 bytes).",+ " [OK] persistence_counter_drift: Receipt-bytes counters match the receipts they account for (2 scope(s))."," [OK] parked_effects: No Git or withdrawal effect is parked."," [OK] worktree_refresh_stuck: No worktree refresh is stuck."," [OK] managed_guard_schema_drift: Guarded tables carry only the columns gbrain creates.",@@@ -94,9 -90,10 +95,9 @@@" [OK] credential_projection_pending: No page waits for the credential-safe re-chunk."," [OK] connector_checkpoints: No orphan connector checkpoint rows older than 7 days."," [OK] persistence_request_indexes: Managed sync request indexes are valid.",- " [OK] persistence_request_growth: 6 request row(s); no scope exhausts its lifetime request IDs within 90 days at its last-7-day rate.",+ " [OK] persistence_request_growth: 6 request row(s); no scope exhausts its lifetime request IDs within 30 days at its last-7-day rate."," [OK] persistence_write_stall: No write request has held its claim longer than persistence.max_claim_ms (600000 ms)."," [OK] lost_caller_writes: Every caller write with a retained receipt committed or was superseded.",- " [OK] persistence_terminal_failures: No terminal write failures in the last 7 d."," [OK] persistence_session_timeouts: PGLite has no session to time out."," [OK] connector_held_items: No connector items are held."," [OK] git_held_files: No Git source files are held.",diff --cc test/fixtures/goldens/doctor/content-pglite-json.jsonindex 2229df3bc7,077be19231..0e1323b1fb--- a/test/fixtures/goldens/doctor/content-pglite-json.json+++ b/test/fixtures/goldens/doctor/content-pglite-json.json@@@ -480,14 -448,126 +480,105 @@@{"category": "ops","details": {+ "background_pause_pct": 80,"commands": [],+ "docs": "docs/guides/concurrent-writes.md#quota-near-exhaustion","exact": true,+ "forecast": {+ "retention_days": 30,+ "rows": [+ {+ "basis": "aggregate_1d_short_history",+ "config_key": "persistence.limits.brain_lifetime_ids",+ "days_to_exhaustion": null,+ "exhaustion_date": null,+ "limit": 8000000,+ "max_day_7d": 7,+ "pct": 0,+ "per_day_7d": 7,+ "recommended_limit": 16000000,+ "resource": "lifetime_ids",+ "scope": "brain",+ "spike_day": null,+ "status": "ok",+ "used": 7,+ "window_days": 1+ },+ {+ "basis": "aggregate_1d_short_history:gross_then_net",+ "config_key": "persistence.limits.brain_terminal_bytes",+ "days_to_exhaustion": null,+ "exhaustion_date": null,+ "limit": 68719476736,+ "max_day_7d": 113645,+ "net_per_day_7d": 22378,+ "pct": 0,+ "per_day_7d": 113645,+ "reclaimable_bytes": 16318,+ "recommended_limit": 137438953472,+ "resource": "terminal_bytes",+ "scope": "brain",+ "spike_day": null,+ "status": "ok",+ "under_reserved_receipts": 0,+ "used": 113645,+ "window_days": 1+ },+ {+ "basis": "aggregate_1d_short_history",+ "config_key": "persistence.limits.principal_lifetime_ids",+ "days_to_exhaustion": null,+ "exhaustion_date": null,+ "limit": 2000000,+ "max_day_7d": 7,+ "pct": 0,+ "per_day_7d": 7,+ "recommended_limit": 4000000,+ "resource": "lifetime_ids",+ "scope": "principal:local_cli:<uuid>",+ "spike_day": null,+ "status": "ok",+ "used": 7,+ "window_days": 1+ },+ {+ "basis": "aggregate_1d_short_history:gross_then_net",+ "config_key": "persistence.limits.principal_terminal_bytes",+ "days_to_exhaustion": null,+ "exhaustion_date": null,+ "limit": 17179869184,+ "max_day_7d": 113645,+ "net_per_day_7d": 22378,+ "pct": 0,+ "per_day_7d": 113645,+ "reclaimable_bytes": 16318,+ "recommended_limit": 34359738368,+ "resource": "terminal_bytes",+ "scope": "principal:local_cli:<uuid>",+ "spike_day": null,+ "status": "ok",+ "under_reserved_receipts": 0,+ "used": 113645,+ "window_days": 1+ }+ ],+ "table_bytes": "<volatile>",+ "thresholds": {+ "fail_days": 7,+ "fail_pct": 95,+ "warn_days": 30,+ "warn_pct": 80+ },+ "window_days": 1+ },"inspected": 2,+ "paused_producers": [],"resources": [],- "truncated": false+ "truncated": false,+ "verify": "gbrain doctor --only persistence_capacity --json"},+ "elapsed_ms": "<volatile>",- "message": "Managed write capacity is below 80% of every cumulative limit.",+ "message": "Managed write capacity is below 80% of every cumulative limit and none runs out within 30 days at its 7-day rate.","name": "persistence_capacity","status": "ok"},@@@ -560,168 -574,34 +651,188 @@@{"category": "ops","details": {- "docs": "docs/guides/troubleshooting.md#receipt-compaction",- "recorded": false+ "docs": "docs/guides/repair.md#receipt-compaction",+ "last_compaction": {+ "at": "<ts>",+ "compacted": 0,+ "freed_bytes": 0,+ "host_id": "<uuid>",+ "skipped_by_reason": {}+ },+ "last_compaction_age_hours": 0,+ "live_consumers": 0,+ "stale_hours": 24},+ "elapsed_ms": "<volatile>",- "message": "No receipt compaction recorded yet (persistence.maintenance.last_compaction is unset): the persistence consumer records one after it compacts.",- "name": "receipt_compaction",- "readiness_state": "not_applicable",- "severity": "info",+ "message": "Receipt compaction last ran 0 hour(s) ago (compacted 0, freed 0 bytes).",+ "name": "persistence_compaction","status": "ok"},+ {+ "category": "ops",+ "details": {+ "count": 0,+ "docs": "docs/guides/troubleshooting.md#serve-build-drift"+ },+ "elapsed_ms": "<volatile>",+ "message": "PGLite admits one process; no consumer heartbeat rows are kept to compare builds.",+ "name": "serve_build_drift",+ "status": "ok"+ },+ {+ "category": "meta",+ "details": {+ "docs": "docs/architecture/schema-packs.md#undeclared-page-types",+ "per_source": [+ {+ "pack": "gbrain-base-v2",+ "source_id": "notes",+ "total": 5,+ "undeclared": 0,+ "undeclared_types": [],+ "untyped": 0+ }+ ],+ "unresolved_sources": []+ },+ "elapsed_ms": "<volatile>",+ "message": "All pages match the active schema pack across every source.",+ "name": "schema_pack_consistency",+ "status": "ok"+ },+ {+ "category": "brain",+ "details": {+ "active_column": "embedding",+ "basis": "exact",+ "counts": {+ "chunkless_healable": 0,+ "deleted_page_chunks": 0,+ "embedded": 0,+ "empty": 0,+ "keyword_only": 0,+ "pending": 7,+ "quarantined": 0+ },+ "coverage": {+ "basis": "exact",+ "eligible": 7,+ "embedded": 0,+ "ratio": 0+ },+ "covering_index": null,+ "deleted_page_chunks": {+ "past_window": 0,+ "window_hours": 72,+ "within_window": 0+ },+ "embeddings_enabled": false,+ "exact": true,+ "keyword_only": {+ "marker_bytes": 0,+ "pages": 0,+ "reason": "embed_skip",+ "threshold_bytes": 500000+ },+ "mode": "full",+ "omitted_states": [],+ "reason": "embeddings_disabled",+ "status": "known",+ "units": "content_chunks rows, plus one unit per page with no chunk rows",+ "unsearchable": 0,+ "unsearchable_complete": true,+ "unstamped_pending": {+ "count": 0,+ "created_at_lower_bound": null,+ "writer_version": "<version>"+ }+ },+ "elapsed_ms": "<volatile>",+ "fix": {+ "actor": "user",+ "argv": [+ "gbrain",+ "init",+ "--force",+ "--embedding-model",+ "voyage:voyage-4",+ "--embedding-dimensions",+ "1024",+ "--path",+ "<home>/.gbrain/brain.pglite"+ ],+ "command": "gbrain init --force --embedding-model voyage:voyage-4 --embedding-dimensions 1024 --path <home>/.gbrain/brain.pglite",+ "consent": [+ "credentials",+ "paid"+ ],+ "docs": "https://github.com/garrytan/gbrain/blob/master/docs/guides/search-modes.md",+ "inputs": [+ {+ "how": "Ask the user for an API key for Voyage AI; store it with `gbrain config set voyage_api_key <key>` (every gbrain process reads it), or export VOYAGE_API_KEY in the environment of every gbrain process. Then run the command.",+ "name": "VOYAGE_API_KEY"+ }+ ],+ "next": "tell_user_to_run",+ "requires_exclusive": true,+ "user_message": "Semantic search needs an embedding API key. Voyage AI works with this brain; if you add a key (VOYAGE_API_KEY), I can turn it on. Embedding costs a little per page; your notes and facts stay as they are.",+ "verify": {+ "argv": [+ "gbrain",+ "doctor",+ "--only",+ "embeddings",+ "--json",+ "--brain",+ "host"+ ]+ },+ "why": "Embeddings are off, so search is keyword-only, and no configured embedding key fits this brain. Once the key is set this turns on voyage:voyage-4 (1024d) for the PGLite brain at <home>/.gbrain/brain.pglite. Pages, facts and keyword search are kept; existing chunks and facts are queued for vectors, which `gbrain embed --stale` (or the next maintenance cycle) fills."+ },+ "message": "Embedding state (exact, column 'embedding'): 0 embedded, 7 pending, 0 keyword-only, 0 quarantined, 0 empty, 0 on deleted pages, 0 chunkless (healable); 0 unsearchable. Embeddings are disabled by choice: keyword search reads the pending chunks.",+ "name": "embedding_state",+ "readiness_state": "disabled_by_choice",+ "severity": "info",+ "status": "ok"+ },+ {+ "category": "ops",+ "elapsed_ms": "<volatile>",+ "message": "Extension installed",+ "name": "pgvector",+ "status": "ok"+ },+ {+ "category": "meta",+ "elapsed_ms": "<volatile>",+ "message": "pages has the UNIQUE(source_id, slug) upsert arbiter",+ "name": "pages_upsert_arbiter",+ "status": "ok"+ },+ {+ "category": "brain",+ "details": {+ "readiness": "ready",+ "ready": true+ },+ "elapsed_ms": "<volatile>",+ "message": "Visible text projections match their canonical revisions.",+ "name": "text_projection_readiness",+ "status": "ok"+ },+ {+ "category": "ops",+ "details": {+ "docs": "docs/guides/concurrent-writes.md#counter-drift",+ "drift": [],+ "inspected": 2,+ "true_up_clamped": 0+ },++ "elapsed_ms": "<volatile>",+ "message": "Receipt-bytes counters match the receipts they account for (2 scope(s)).",+ "name": "persistence_counter_drift",+ "status": "ok"+ },{"category": "brain","details": {@@@ -1162,8 -1012,7 +1273,8 @@@"verify": "gbrain doctor --json (check persistence_request_growth)","window_days": 7},+ "elapsed_ms": "<volatile>",- "message": "6 request row(s); no scope exhausts its lifetime request IDs within 90 days at its last-7-day rate.",+ "message": "6 request row(s); no scope exhausts its lifetime request IDs within 30 days at its last-7-day rate.","name": "persistence_request_growth","status": "ok"},@@@ -1491,9 -1370,9 +1602,10 @@@"docs": "docs/guides/troubleshooting.md#maintenance-write-drift","repair": "file-drift","sources": [],+ "suppressed": [],"window_sequences": 20000},+ "elapsed_ms": "<volatile>","message": "No page whose writes refuse source_changed still has a canonical file that differs from the database.","name": "maintenance_write_drift","status": "ok"diff --cc test/fixtures/goldens/doctor/hot-checks-pglite-json.jsonindex f688f7a4a0,5905d50240..5f0981b2bc--- a/test/fixtures/goldens/doctor/hot-checks-pglite-json.json+++ b/test/fixtures/goldens/doctor/hot-checks-pglite-json.json@@@ -481,14 -449,127 +481,105 @@@{"category": "ops","details": {+ "background_pause_pct": 80,"commands": [],+ "docs": "docs/guides/concurrent-writes.md#quota-near-exhaustion","exact": true,+ "forecast": {+ "retention_days": 30,+ "rows": [+ {+ "basis": "aggregate_1d_short_history",+ "config_key": "persistence.limits.brain_lifetime_ids",+ "days_to_exhaustion": null,+ "exhaustion_date": null,+ "limit": 8000000,+ "max_day_7d": 24,+ "pct": 0,+ "per_day_7d": 24,+ "recommended_limit": 16000000,+ "resource": "lifetime_ids",+ "scope": "brain",+ "spike_day": null,+ "status": "ok",+ "used": 24,+ "window_days": 1+ },+ {+ "basis": "aggregate_1d_short_history:gross_then_net",+ "config_key": "persistence.limits.brain_terminal_bytes",+ "days_to_exhaustion": null,+ "exhaustion_date": null,+ "limit": 68719476736,+ "max_day_7d": 194961,+ "net_per_day_7d": 58816,+ "pct": 0,+ "per_day_7d": 194961,+ "reclaimable_bytes": 136145,+ "recommended_limit": 137438953472,+ "resource": "terminal_bytes",+ "scope": "brain",+ "spike_day": null,+ "status": "ok",+ "under_reserved_receipts": 0,+ "used": 194961,+ "window_days": 1+ },+ {+ "basis": "aggregate_1d_short_history",+ "config_key": "persistence.limits.principal_lifetime_ids",+ "days_to_exhaustion": null,+ "exhaustion_date": null,+ "limit": 2000000,+ "max_day_7d": 24,+ "pct": 0,+ "per_day_7d": 24,+ "recommended_limit": 4000000,+ "resource": "lifetime_ids",+ "scope": "principal:local_cli:<uuid>",+ "spike_day": null,+ "status": "ok",+ "used": 24,+ "window_days": 1+ },+ {+ "basis": "aggregate_1d_short_history:gross_then_net",+ "config_key": "persistence.limits.principal_terminal_bytes",+ "days_to_exhaustion": null,+ "exhaustion_date": null,+ "limit": 17179869184,+ "max_day_7d": 194961,+ "net_per_day_7d": 58816,+ "pct": 0,+ "per_day_7d": 194961,+ "reclaimable_bytes": 136145,+ "recommended_limit": 34359738368,+ "resource": "terminal_bytes",+ "scope": "principal:local_cli:<uuid>",+ "spike_day": null,+ "status": "ok",+ "under_reserved_receipts": 0,+ "used": 194961,+ "window_days": 1+ }+ ],+ "table_bytes": "<volatile>",+ "thresholds": {+ "fail_days": 7,+ "fail_pct": 95,+ "warn_days": 30,+ "warn_pct": 80+ },+ "window_days": 1+ },"inspected": 2,+ "paused_producers": [],"resources": [],- "truncated": false+ "truncated": false,+ "verify": "gbrain doctor --only persistence_capacity --json"},+ "elapsed_ms": "<volatile>",- "message": "Managed write capacity is below 80% of every cumulative limit.",+ "message": "Managed write capacity is below 80% of every cumulative limit and none runs out within 30 days at its 7-day rate.","name": "persistence_capacity","status": "ok"},@@@ -561,184 -576,34 +652,204 @@@{"category": "ops","details": {- "docs": "docs/guides/troubleshooting.md#receipt-compaction",- "recorded": false+ "docs": "docs/guides/repair.md#receipt-compaction",+ "last_compaction": {+ "at": "<ts>",+ "compacted": 0,+ "freed_bytes": 0,+ "host_id": "<uuid>",+ "skipped_by_reason": {}+ },+ "last_compaction_age_hours": 0,+ "live_consumers": 0,+ "stale_hours": 24},+ "elapsed_ms": "<volatile>",- "message": "No receipt compaction recorded yet (persistence.maintenance.last_compaction is unset): the persistence consumer records one after it compacts.",- "name": "receipt_compaction",- "readiness_state": "not_applicable",- "severity": "info",+ "message": "Receipt compaction last ran 0 hour(s) ago (compacted 0, freed 0 bytes).",+ "name": "persistence_compaction","status": "ok"},+ {+ "category": "ops",+ "details": {+ "count": 0,+ "docs": "docs/guides/troubleshooting.md#serve-build-drift"+ },+ "elapsed_ms": "<volatile>",+ "message": "PGLite admits one process; no consumer heartbeat rows are kept to compare builds.",+ "name": "serve_build_drift",+ "status": "ok"+ },+ {+ "category": "meta",+ "details": {+ "code": "page_type_undeclared",+ "docs": "docs/architecture/schema-packs.md#undeclared-page-types",+ "per_source": [+ {+ "pack": "gbrain-base-v2",+ "source_id": "notes",+ "total": 19,+ "undeclared": 1,+ "undeclared_types": [+ {+ "count": 1,+ "type": "2024"+ }+ ],+ "untyped": 0+ },+ {+ "pack": "gbrain-base-v2",+ "source_id": "plain",+ "total": 1,+ "undeclared": 0,+ "undeclared_types": [],+ "untyped": 0+ }+ ],+ "unresolved_sources": []+ },+ "elapsed_ms": "<volatile>",+ "fix_unavailable_reason": "unstructured",+ "message": "Source `notes`: 1 page(s) use 1 type(s) pack `gbrain-base-v2` neither declares nor aliases: '2024' (1). List them with `gbrain schema review-orphans --source notes`, then declare the type (`gbrain schema add-type <type>`, which takes its primitive and prefix) or retype the pages to a declared type.",+ "name": "schema_pack_consistency",+ "status": "warn"+ },+ {+ "category": "brain",+ "details": {+ "active_column": "embedding",+ "basis": "exact",+ "counts": {+ "chunkless_healable": 0,+ "deleted_page_chunks": 0,+ "embedded": 0,+ "empty": 1,+ "keyword_only": 0,+ "pending": 23,+ "quarantined": 0+ },+ "coverage": {+ "basis": "exact",+ "eligible": 23,+ "embedded": 0,+ "ratio": 0+ },+ "covering_index": null,+ "deleted_page_chunks": {+ "past_window": 0,+ "window_hours": 72,+ "within_window": 0+ },+ "embeddings_enabled": false,+ "exact": true,+ "keyword_only": {+ "marker_bytes": 0,+ "pages": 0,+ "reason": "embed_skip",+ "threshold_bytes": 500000+ },+ "mode": "full",+ "omitted_states": [],+ "reason": "embeddings_disabled",+ "status": "known",+ "units": "content_chunks rows, plus one unit per page with no chunk rows",+ "unsearchable": 1,+ "unsearchable_complete": true,+ "unstamped_pending": {+ "count": 0,+ "created_at_lower_bound": null,+ "writer_version": "<version>"+ }+ },+ "elapsed_ms": "<volatile>",+ "fix": {+ "actor": "user",+ "argv": [+ "gbrain",+ "init",+ "--force",+ "--embedding-model",+ "voyage:voyage-4",+ "--embedding-dimensions",+ "1024",+ "--path",+ "<home>/.gbrain/brain.pglite"+ ],+ "command": "gbrain init --force --embedding-model voyage:voyage-4 --embedding-dimensions 1024 --path <home>/.gbrain/brain.pglite",+ "consent": [+ "credentials",+ "paid"+ ],+ "docs": "https://github.com/garrytan/gbrain/blob/master/docs/guides/search-modes.md",+ "inputs": [+ {+ "how": "Ask the user for an API key for Voyage AI; store it with `gbrain config set voyage_api_key <key>` (every gbrain process reads it), or export VOYAGE_API_KEY in the environment of every gbrain process. Then run the command.",+ "name": "VOYAGE_API_KEY"+ }+ ],+ "next": "tell_user_to_run",+ "requires_exclusive": true,+ "user_message": "Semantic search needs an embedding API key. Voyage AI works with this brain; if you add a key (VOYAGE_API_KEY), I can turn it on. Embedding costs a little per page; your notes and facts stay as they are.",+ "verify": {+ "argv": [+ "gbrain",+ "doctor",+ "--only",+ "embeddings",+ "--json",+ "--brain",+ "host"+ ]+ },+ "why": "Embeddings are off, so search is keyword-only, and no configured embedding key fits this brain. Once the key is set this turns on voyage:voyage-4 (1024d) for the PGLite brain at <home>/.gbrain/brain.pglite. Pages, facts and keyword search are kept; existing chunks and facts are queued for vectors, which `gbrain embed --stale` (or the next maintenance cycle) fills."+ },+ "message": "Embedding state (exact, column 'embedding'): 0 embedded, 23 pending, 0 keyword-only, 0 quarantined, 1 empty, 0 on deleted pages, 0 chunkless (healable); 1 unsearchable. Embeddings are disabled by choice: keyword search reads the pending chunks.",+ "name": "embedding_state",+ "readiness_state": "disabled_by_choice",+ "severity": "info",+ "status": "ok"+ },+ {+ "category": "ops",+ "elapsed_ms": "<volatile>",+ "message": "Extension installed",+ "name": "pgvector",+ "status": "ok"+ },+ {+ "category": "meta",+ "elapsed_ms": "<volatile>",+ "message": "pages has the UNIQUE(source_id, slug) upsert arbiter",+ "name": "pages_upsert_arbiter",+ "status": "ok"+ },+ {+ "category": "brain",+ "details": {+ "readiness": "projection_pending",+ "ready": false+ },+ "elapsed_ms": "<volatile>",+ "fix_unavailable_reason": "unstructured",+ "message": "Visible pages have missing or stale text projections; search and code results may be incomplete. Run `gbrain projections drain` to rebuild queued Markdown and code projections now; it is safe while `gbrain serve` runs on Postgres. For code metadata repair, run `gbrain reindex-code --force --no-embed`. If work stays pending, inspect the recorded source path. No repair or embedding was started by this check.",+ "name": "text_projection_readiness",+ "status": "warn"+ },+ {+ "category": "ops",+ "details": {+ "docs": "docs/guides/concurrent-writes.md#counter-drift",+ "drift": [],+ "inspected": 2,+ "true_up_clamped": 0+ },++ "elapsed_ms": "<volatile>",+ "message": "Receipt-bytes counters match the receipts they account for (2 scope(s)).",+ "name": "persistence_counter_drift",+ "status": "ok"+ },{"category": "brain","details": {@@@ -1205,8 -1040,7 +1316,8 @@@"verify": "gbrain doctor --json (check persistence_request_growth)","window_days": 7},+ "elapsed_ms": "<volatile>",- "message": "22 request row(s); no scope exhausts its lifetime request IDs within 90 days at its last-7-day rate.",+ "message": "22 request row(s); no scope exhausts its lifetime request IDs within 30 days at its last-7-day rate.","name": "persistence_request_growth","status": "ok"},@@@ -1616,9 -1480,9 +1727,10 @@@"docs": "docs/guides/troubleshooting.md#maintenance-write-drift","repair": "file-drift","sources": [],+ "suppressed": [],"window_sequences": 20000},+ "elapsed_ms": "<volatile>","message": "No page whose writes refuse source_changed still has a canonical file that differs from the database.","name": "maintenance_write_drift","status": "ok"@@@ -4032,14 -3743,127 +4144,105 @@@{"category": "ops","details": {+ "background_pause_pct": 80,"commands": [],+ "docs": "docs/guides/concurrent-writes.md#quota-near-exhaustion","exact": true,+ "forecast": {+ "retention_days": 30,+ "rows": [+ {+ "basis": "aggregate_1d_short_history",+ "config_key": "persistence.limits.brain_lifetime_ids",+ "days_to_exhaustion": null,+ "exhaustion_date": null,+ "limit": 8000000,+ "max_day_7d": 24,+ "pct": 0,+ "per_day_7d": 24,+ "recommended_limit": 16000000,+ "resource": "lifetime_ids",+ "scope": "brain",+ "spike_day": null,+ "status": "ok",+ "used": 24,+ "window_days": 1+ },+ {+ "basis": "aggregate_1d_short_history:gross_then_net",+ "config_key": "persistence.limits.brain_terminal_bytes",+ "days_to_exhaustion": null,+ "exhaustion_date": null,+ "limit": 68719476736,+ "max_day_7d": 194961,+ "net_per_day_7d": 58816,+ "pct": 0,+ "per_day_7d": 194961,+ "reclaimable_bytes": 136145,+ "recommended_limit": 137438953472,+ "resource": "terminal_bytes",+ "scope": "brain",+ "spike_day": null,+ "status": "ok",+ "under_reserved_receipts": 0,+ "used": 194961,+ "window_days": 1+ },+ {+ "basis": "aggregate_1d_short_history",+ "config_key": "persistence.limits.principal_lifetime_ids",+ "days_to_exhaustion": null,+ "exhaustion_date": null,+ "limit": 2000000,+ "max_day_7d": 24,+ "pct": 0,+ "per_day_7d": 24,+ "recommended_limit": 4000000,+ "resource": "lifetime_ids",+ "scope": "principal:local_cli:<uuid>",+ "spike_day": null,+ "status": "ok",+ "used": 24,+ "window_days": 1+ },+ {+ "basis": "aggregate_1d_short_history:gross_then_net",+ "config_key": "persistence.limits.principal_terminal_bytes",+ "days_to_exhaustion": null,+ "exhaustion_date": null,+ "limit": 17179869184,+ "max_day_7d": 194961,+ "net_per_day_7d": 58816,+ "pct": 0,+ "per_day_7d": 194961,+ "reclaimable_bytes": 136145,+ "recommended_limit": 34359738368,+ "resource": "terminal_bytes",+ "scope": "principal:local_cli:<uuid>",+ "spike_day": null,+ "status": "ok",+ "under_reserved_receipts": 0,+ "used": 194961,+ "window_days": 1+ }+ ],+ "table_bytes": "<volatile>",+ "thresholds": {+ "fail_days": 7,+ "fail_pct": 95,+ "warn_days": 30,+ "warn_pct": 80+ },+ "window_days": 1+ },"inspected": 2,+ "paused_producers": [],"resources": [],- "truncated": false+ "truncated": false,+ "verify": "gbrain doctor --only persistence_capacity --json"},+ "elapsed_ms": "<volatile>",- "message": "Managed write capacity is below 80% of every cumulative limit.",+ "message": "Managed write capacity is below 80% of every cumulative limit and none runs out within 30 days at its 7-day rate.","name": "persistence_capacity","status": "ok"},@@@ -4112,184 -3870,34 +4315,204 @@@{"category": "ops","details": {- "docs": "docs/guides/troubleshooting.md#receipt-compaction",- "recorded": false+ "docs": "docs/guides/repair.md#receipt-compaction",+ "last_compaction": {+ "at": "<ts>",+ "compacted": 0,+ "freed_bytes": 0,+ "host_id": "<uuid>",+ "skipped_by_reason": {}+ },+ "last_compaction_age_hours": 0,+ "live_consumers": 0,+ "stale_hours": 24},+ "elapsed_ms": "<volatile>",- "message": "No receipt compaction recorded yet (persistence.maintenance.last_compaction is unset): the persistence consumer records one after it compacts.",- "name": "receipt_compaction",- "readiness_state": "not_applicable",- "severity": "info",+ "message": "Receipt compaction last ran 0 hour(s) ago (compacted 0, freed 0 bytes).",+ "name": "persistence_compaction","status": "ok"},+ {+ "category": "ops",+ "details": {+ "count": 0,+ "docs": "docs/guides/troubleshooting.md#serve-build-drift"+ },+ "elapsed_ms": "<volatile>",+ "message": "PGLite admits one process; no consumer heartbeat rows are kept to compare builds.",+ "name": "serve_build_drift",+ "status": "ok"+ },+ {+ "category": "meta",+ "details": {+ "code": "page_type_undeclared",+ "docs": "docs/architecture/schema-packs.md#undeclared-page-types",+ "per_source": [+ {+ "pack": "gbrain-base-v2",+ "source_id": "notes",+ "total": 19,+ "undeclared": 1,+ "undeclared_types": [+ {+ "count": 1,+ "type": "2024"+ }+ ],+ "untyped": 0+ },+ {+ "pack": "gbrain-base-v2",+ "source_id": "plain",+ "total": 1,+ "undeclared": 0,+ "undeclared_types": [],+ "untyped": 0+ }+ ],+ "unresolved_sources": []+ },+ "elapsed_ms": "<volatile>",+ "fix_unavailable_reason": "unstructured",+ "message": "Source `notes`: 1 page(s) use 1 type(s) pack `gbrain-base-v2` neither declares nor aliases: '2024' (1). List them with `gbrain schema review-orphans --source notes`, then declare the type (`gbrain schema add-type <type>`, which takes its primitive and prefix) or retype the pages to a declared type.",+ "name": "schema_pack_consistency",+ "status": "warn"+ },+ {+ "category": "brain",+ "details": {+ "active_column": "embedding",+ "basis": "exact",+ "counts": {+ "chunkless_healable": 0,+ "deleted_page_chunks": 0,+ "embedded": 0,+ "empty": 1,+ "keyword_only": 0,+ "pending": 23,+ "quarantined": 0+ },+ "coverage": {+ "basis": "exact",+ "eligible": 23,+ "embedded": 0,+ "ratio": 0+ },+ "covering_index": null,+ "deleted_page_chunks": {+ "past_window": 0,+ "window_hours": 72,+ "within_window": 0+ },+ "embeddings_enabled": false,+ "exact": true,+ "keyword_only": {+ "marker_bytes": 0,+ "pages": 0,+ "reason": "embed_skip",+ "threshold_bytes": 500000+ },+ "mode": "full",+ "omitted_states": [],+ "reason": "embeddings_disabled",+ "status": "known",+ "units": "content_chunks rows, plus one unit per page with no chunk rows",+ "unsearchable": 1,+ "unsearchable_complete": true,+ "unstamped_pending": {+ "count": 0,+ "created_at_lower_bound": null,+ "writer_version": "<version>"+ }+ },+ "elapsed_ms": "<volatile>",+ "fix": {+ "actor": "user",+ "argv": [+ "gbrain",+ "init",+ "--force",+ "--embedding-model",+ "voyage:voyage-4",+ "--embedding-dimensions",+ "1024",+ "--path",+ "<home>/.gbrain/brain.pglite"+ ],+ "command": "gbrain init --force --embedding-model voyage:voyage-4 --embedding-dimensions 1024 --path <home>/.gbrain/brain.pglite",+ "consent": [+ "credentials",+ "paid"+ ],+ "docs": "https://github.com/garrytan/gbrain/blob/master/docs/guides/search-modes.md",+ "inputs": [+ {+ "how": "Ask the user for an API key for Voyage AI; store it with `gbrain config set voyage_api_key <key>` (every gbrain process reads it), or export VOYAGE_API_KEY in the environment of every gbrain process. Then run the command.",+ "name": "VOYAGE_API_KEY"+ }+ ],+ "next": "tell_user_to_run",+ "requires_exclusive": true,+ "user_message": "Semantic search needs an embedding API key. Voyage AI works with this brain; if you add a key (VOYAGE_API_KEY), I can turn it on. Embedding costs a little per page; your notes and facts stay as they are.",+ "verify": {+ "argv": [+ "gbrain",+ "doctor",+ "--only",+ "embeddings",+ "--json",+ "--brain",+ "host"+ ]+ },+ "why": "Embeddings are off, so search is keyword-only, and no configured embedding key fits this brain. Once the key is set this turns on voyage:voyage-4 (1024d) for the PGLite brain at <home>/.gbrain/brain.pglite. Pages, facts and keyword search are kept; existing chunks and facts are queued for vectors, which `gbrain embed --stale` (or the next maintenance cycle) fills."+ },+ "message": "Embedding state (exact, column 'embedding'): 0 embedded, 23 pending, 0 keyword-only, 0 quarantined, 1 empty, 0 on deleted pages, 0 chunkless (healable); 1 unsearchable. Embeddings are disabled by choice: keyword search reads the pending chunks.",+ "name": "embedding_state",+ "readiness_state": "disabled_by_choice",+ "severity": "info",+ "status": "ok"+ },+ {+ "category": "ops",+ "elapsed_ms": "<volatile>",+ "message": "Extension installed",+ "name": "pgvector",+ "status": "ok"+ },+ {+ "category": "meta",+ "elapsed_ms": "<volatile>",+ "message": "pages has the UNIQUE(source_id, slug) upsert arbiter",+ "name": "pages_upsert_arbiter",+ "status": "ok"+ },+ {+ "category": "brain",+ "details": {+ "readiness": "projection_pending",+ "ready": false+ },+ "elapsed_ms": "<volatile>",+ "fix_unavailable_reason": "unstructured",+ "message": "Visible pages have missing or stale text projections; search and code results may be incomplete. Run `gbrain projections drain` to rebuild queued Markdown and code projections now; it is safe while `gbrain serve` runs on Postgres. For code metadata repair, run `gbrain reindex-code --force --no-embed`. If work stays pending, inspect the recorded source path. No repair or embedding was started by this check.",+ "name": "text_projection_readiness",+ "status": "warn"+ },+ {+ "category": "ops",+ "details": {+ "docs": "docs/guides/concurrent-writes.md#counter-drift",+ "drift": [],+ "inspected": 2,+ "true_up_clamped": 0+ },++ "elapsed_ms": "<volatile>",+ "message": "Receipt-bytes counters match the receipts they account for (2 scope(s)).",+ "name": "persistence_counter_drift",+ "status": "ok"+ },{"category": "brain","details": {@@@ -4756,8 -4334,7 +4979,8 @@@"verify": "gbrain doctor --json (check persistence_request_growth)","window_days": 7},+ "elapsed_ms": "<volatile>",- "message": "22 request row(s); no scope exhausts its lifetime request IDs within 90 days at its last-7-day rate.",+ "message": "22 request row(s); no scope exhausts its lifetime request IDs within 30 days at its last-7-day rate.","name": "persistence_request_growth","status": "ok"},@@@ -5167,9 -4774,9 +5390,10 @@@"docs": "docs/guides/troubleshooting.md#maintenance-write-drift","repair": "file-drift","sources": [],+ "suppressed": [],"window_sequences": 20000},+ "elapsed_ms": "<volatile>","message": "No page whose writes refuse source_changed still has a canonical file that differs from the database.","name": "maintenance_write_drift","status": "ok"diff --cc test/fixtures/goldens/doctor/hot-checks-postgres-json.jsonindex 6d597e1df5,56f400cbc4..2bb515aa0d--- a/test/fixtures/goldens/doctor/hot-checks-postgres-json.json+++ b/test/fixtures/goldens/doctor/hot-checks-postgres-json.json@@@ -475,14 -442,133 +475,105 @@@{"category": "ops","details": {+ "background_pause_pct": 80,"commands": [],+ "docs": "docs/guides/concurrent-writes.md#quota-near-exhaustion","exact": true,+ "forecast": {+ "retention_days": 30,+ "rows": [+ {+ "basis": "aggregate_1d_short_history",+ "config_key": "persistence.limits.brain_lifetime_ids",+ "days_to_exhaustion": null,+ "exhaustion_date": null,+ "limit": 8000000,+ "max_day_7d": 24,+ "pct": 0,+ "per_day_7d": 24,+ "recommended_limit": 16000000,+ "resource": "lifetime_ids",+ "scope": "brain",+ "spike_day": null,+ "status": "ok",+ "used": 24,+ "window_days": 1+ },+ {+ "basis": "aggregate_1d_short_history:gross_then_net",+ "config_key": "persistence.limits.brain_terminal_bytes",+ "days_to_exhaustion": null,+ "exhaustion_date": null,+ "limit": 68719476736,+ "max_day_7d": 196014,+ "net_per_day_7d": 58822,+ "pct": 0,+ "per_day_7d": 196014,+ "reclaimable_bytes": 137192,+ "recommended_limit": 137438953472,+ "resource": "terminal_bytes",+ "scope": "brain",+ "spike_day": null,+ "status": "ok",+ "under_reserved_receipts": 0,+ "used": 196014,+ "window_days": 1+ },+ {+ "basis": "aggregate_1d_short_history",+ "config_key": "persistence.limits.principal_lifetime_ids",+ "days_to_exhaustion": null,+ "exhaustion_date": null,+ "limit": 2000000,+ "max_day_7d": 24,+ "pct": 0,+ "per_day_7d": 24,+ "recommended_limit": 4000000,+ "resource": "lifetime_ids",+ "scope": "principal:local_cli:<uuid>",+ "spike_day": null,+ "status": "ok",+ "used": 24,+ "window_days": 1+ },+ {+ "basis": "aggregate_1d_short_history:gross_then_net",+ "config_key": "persistence.limits.principal_terminal_bytes",+ "days_to_exhaustion": null,+ "exhaustion_date": null,+ "limit": 17179869184,+ "max_day_7d": 196014,+ "net_per_day_7d": 58822,+ "pct": 0,+ "per_day_7d": 196014,+ "reclaimable_bytes": 137192,+ "recommended_limit": 34359738368,+ "resource": "terminal_bytes",+ "scope": "principal:local_cli:<uuid>",+ "spike_day": null,+ "status": "ok",+ "under_reserved_receipts": 0,+ "used": 196014,+ "window_days": 1+ }+ ],+ "table_bytes": "<volatile>",+ "thresholds": {+ "fail_days": 7,+ "fail_pct": 95,+ "warn_days": 30,+ "warn_pct": 80+ },+ "window_days": 1+ },"inspected": 2,+ "paused_producers": [],"resources": [],- "truncated": false+ "truncated": false,+ "verify": "gbrain doctor --only persistence_capacity --json"},+ "elapsed_ms": "<volatile>",- "message": "Managed write capacity is below 80% of every cumulative limit.",+ "message": "Managed write capacity is below 80% of every cumulative limit and none runs out within 30 days at its 7-day rate.","name": "persistence_capacity","status": "ok"},@@@ -555,193 -575,34 +646,213 @@@{"category": "ops","details": {- "docs": "docs/guides/troubleshooting.md#receipt-compaction",- "recorded": false+ "docs": "docs/guides/repair.md#receipt-compaction",+ "last_compaction": {+ "at": "<ts>",+ "compacted": 0,+ "freed_bytes": 0,+ "host_id": "<uuid>",+ "skipped_by_reason": {}+ },+ "last_compaction_age_hours": 0,+ "live_consumers": 0,+ "stale_hours": 24},+ "elapsed_ms": "<volatile>",- "message": "No receipt compaction recorded yet (persistence.maintenance.last_compaction is unset): the persistence consumer records one after it compacts.",- "name": "receipt_compaction",- "readiness_state": "not_applicable",- "severity": "info",+ "message": "Receipt compaction last ran 0 hour(s) ago (compacted 0, freed 0 bytes).",+ "name": "persistence_compaction","status": "ok"},+ {+ "category": "ops",+ "details": {+ "count": 0,+ "docs": "docs/guides/troubleshooting.md#serve-build-drift",+ "newer": [],+ "older": [],+ "owner": null,+ "this_version": "<version>"+ },+ "elapsed_ms": "<volatile>",+ "message": "No live gbrain consumer on this host writes a heartbeat row. A serve that predates heartbeats writes none; consumers_without_heartbeat names it when it holds claims.",+ "name": "serve_build_drift",+ "status": "ok"+ },+ {+ "category": "meta",+ "details": {+ "code": "page_type_undeclared",+ "docs": "docs/architecture/schema-packs.md#undeclared-page-types",+ "per_source": [+ {+ "pack": "gbrain-base-v2",+ "source_id": "notes",+ "total": 19,+ "undeclared": 1,+ "undeclared_types": [+ {+ "count": 1,+ "type": "2024"+ }+ ],+ "untyped": 0+ },+ {+ "pack": "gbrain-base-v2",+ "source_id": "plain",+ "total": 1,+ "undeclared": 0,+ "undeclared_types": [],+ "untyped": 0+ }+ ],+ "unresolved_sources": []+ },+ "elapsed_ms": "<volatile>",+ "fix_unavailable_reason": "unstructured",+ "message": "Source `notes`: 1 page(s) use 1 type(s) pack `gbrain-base-v2` neither declares nor aliases: '2024' (1). List them with `gbrain schema review-orphans --source notes`, then declare the type (`gbrain schema add-type <type>`, which takes its primitive and prefix) or retype the pages to a declared type.",+ "name": "schema_pack_consistency",+ "status": "warn"+ },+ {+ "category": "brain",+ "details": {+ "active_column": "embedding",+ "basis": "exact",+ "counts": {+ "chunkless_healable": 0,+ "deleted_page_chunks": 0,+ "embedded": 0,+ "empty": 1,+ "keyword_only": 0,+ "pending": 23,+ "quarantined": 0+ },+ "coverage": {+ "basis": "exact",+ "eligible": 23,+ "embedded": 0,+ "ratio": 0+ },+ "covering_index": null,+ "deleted_page_chunks": {+ "past_window": 0,+ "window_hours": 72,+ "within_window": 0+ },+ "embeddings_enabled": false,+ "exact": true,+ "keyword_only": {+ "marker_bytes": 0,+ "pages": 0,+ "reason": "embed_skip",+ "threshold_bytes": 500000+ },+ "mode": "full",+ "omitted_states": [],+ "reason": "embeddings_disabled",+ "status": "known",+ "units": "content_chunks rows, plus one unit per page with no chunk rows",+ "unsearchable": 1,+ "unsearchable_complete": true,+ "unstamped_pending": {+ "count": 0,+ "created_at_lower_bound": null,+ "writer_version": "<version>"+ }+ },+ "elapsed_ms": "<volatile>",+ "fix": {+ "actor": "user",+ "argv": [+ "gbrain",+ "init",+ "--force",+ "--embedding-model",+ "voyage:voyage-4",+ "--embedding-dimensions",+ "1024"+ ],+ "command": "gbrain init --force --embedding-model voyage:voyage-4 --embedding-dimensions 1024",+ "consent": [+ "credentials",+ "paid"+ ],+ "docs": "https://github.com/garrytan/gbrain/blob/master/docs/guides/search-modes.md",+ "inputs": [+ {+ "how": "Ask the user for an API key for Voyage AI; store it with `gbrain config set voyage_api_key <key>` (every gbrain process reads it), or export VOYAGE_API_KEY in the environment of every gbrain process. Then run the command.",+ "name": "VOYAGE_API_KEY"+ }+ ],+ "next": "tell_user_to_run",+ "requires_exclusive": true,+ "user_message": "Semantic search needs an embedding API key. Voyage AI works with this brain; if you add a key (VOYAGE_API_KEY), I can turn it on. Embedding costs a little per page; your notes and facts stay as they are.",+ "verify": {+ "argv": [+ "gbrain",+ "doctor",+ "--only",+ "embeddings",+ "--json",+ "--brain",+ "host"+ ]+ },+ "why": "Embeddings are off, so search is keyword-only, and no configured embedding key fits this brain. Once the key is set this turns on voyage:voyage-4 (1024d) for this Postgres brain. Pages, facts and keyword search are kept; existing chunks and facts are queued for vectors, which `gbrain embed --stale` (or the next maintenance cycle) fills."+ },+ "message": "Embedding state (exact, column 'embedding'): 0 embedded, 23 pending, 0 keyword-only, 0 quarantined, 1 empty, 0 on deleted pages, 0 chunkless (healable); 1 unsearchable. Embeddings are disabled by choice: keyword search reads the pending chunks.",+ "name": "embedding_state",+ "readiness_state": "disabled_by_choice",+ "severity": "info",+ "status": "ok"+ },+ {+ "category": "ops",+ "elapsed_ms": "<volatile>",+ "message": "Extension installed",+ "name": "pgvector",+ "status": "ok"+ },+ {+ "category": "ops",+ "elapsed_ms": "<volatile>",+ "message": "Postgres driver supports safe query cancellation.",+ "name": "postgres_cancellation_driver",+ "status": "ok"+ },+ {+ "category": "meta",+ "elapsed_ms": "<volatile>",+ "message": "pages has the UNIQUE(source_id, slug) upsert arbiter",+ "name": "pages_upsert_arbiter",+ "status": "ok"+ },+ {+ "category": "brain",+ "details": {+ "readiness": "projection_pending",+ "ready": false+ },+ "elapsed_ms": "<volatile>",+ "fix_unavailable_reason": "unstructured",+ "message": "Visible pages have missing or stale text projections; search and code results may be incomplete. Run `gbrain projections drain` to rebuild queued Markdown and code projections now; it is safe while `gbrain serve` runs on Postgres. For code metadata repair, run `gbrain reindex-code --force --no-embed`. If work stays pending, inspect the recorded source path. No repair or embedding was started by this check.",+ "name": "text_projection_readiness",+ "status": "warn"+ },+ {+ "category": "ops",+ "details": {+ "docs": "docs/guides/concurrent-writes.md#counter-drift",+ "drift": [],+ "inspected": 2,+ "true_up_clamped": 0+ },++ "elapsed_ms": "<volatile>",+ "message": "Receipt-bytes counters match the receipts they account for (2 scope(s)).",+ "name": "persistence_counter_drift",+ "status": "ok"+ },{"category": "brain","details": {@@@ -1197,8 -1029,7 +1308,8 @@@"verify": "gbrain doctor --json (check persistence_request_growth)","window_days": 7},+ "elapsed_ms": "<volatile>",- "message": "~22 request row(s); no scope exhausts its lifetime request IDs within 90 days at its last-7-day rate.",+ "message": "~22 request row(s); no scope exhausts its lifetime request IDs within 30 days at its last-7-day rate.","name": "persistence_request_growth","status": "ok"},@@@ -1615,9 -1476,9 +1726,10 @@@"docs": "docs/guides/troubleshooting.md#maintenance-write-drift","repair": "file-drift","sources": [],+ "suppressed": [],"window_sequences": 20000},+ "elapsed_ms": "<volatile>","message": "No page whose writes refuse source_changed still has a canonical file that differs from the database.","name": "maintenance_write_drift","status": "ok"@@@ -3984,274 -3693,15 +4096,372 @@@"consent": ["persistent_install"],- "docs": "https://github.com/garrytan/gbrain/blob/master/docs/protocol/MEMORY_VERBS_v1.md#install-the-4-command-quickstart",- "next": "report",- "requires_exclusive": false,- "user_message": "Which agent app should get gbrain memory? The install guide has a one-line command for each.",- "why": "Register `<absolute path to gbrain> serve --surface full` as a stdio MCP server in your agent host; the install section lists the exact command per harness (Claude Code, Codex, Grok Build, opencode, OpenClaw)."+ "docs": "https://github.com/garrytan/gbrain/blob/master/docs/protocol/MEMORY_VERBS_v1.md#install-the-4-command-quickstart",+ "next": "report",+ "requires_exclusive": false,+ "user_message": "Which agent app should get gbrain memory? The install guide has a one-line command for each.",+ "why": "Register `<absolute path to gbrain> serve --surface full` as a stdio MCP server in your agent host; the install section lists the exact command per harness (Claude Code, Codex, Grok Build, opencode, OpenClaw)."+ },+ "message": "No agent harness was detected. Wire one when the user picks an agent app.",+ "name": "harness_wiring",+ "readiness_state": "missing",+ "severity": "info",+ "status": "ok"+ },+ {+ "category": "meta",+ "details": {+ "consent_refused": 0,+ "derived_cap_exhausted": 0,+ "events": 0,+ "internal_errors": 0,+ "json_document_missing": 0,+ "window_days": 7+ },+ "elapsed_ms": "<volatile>",+ "message": "No agent dead ends in the last 7 days (0 non-success event(s) logged).",+ "name": "agent_contract",+ "status": "ok"+ },+ {+ "category": "ops",+ "elapsed_ms": "<volatile>",+ "message": "Connected, 20 pages",+ "name": "connection",+ "status": "ok"+ },+ {+ "category": "ops",+ "details": {++ "background_pause_pct": 80,+ "commands": [],++ "docs": "docs/guides/concurrent-writes.md#quota-near-exhaustion",+ "exact": true,++ "forecast": {++ "retention_days": 30,++ "rows": [++ {++ "basis": "aggregate_1d_short_history",++ "config_key": "persistence.limits.brain_lifetime_ids",++ "days_to_exhaustion": null,++ "exhaustion_date": null,++ "limit": 8000000,++ "max_day_7d": 24,++ "pct": 0,++ "per_day_7d": 24,++ "recommended_limit": 16000000,++ "resource": "lifetime_ids",++ "scope": "brain",++ "spike_day": null,++ "status": "ok",++ "used": 24,++ "window_days": 1++ },++ {++ "basis": "aggregate_1d_short_history:gross_then_net",++ "config_key": "persistence.limits.brain_terminal_bytes",++ "days_to_exhaustion": null,++ "exhaustion_date": null,++ "limit": 68719476736,++ "max_day_7d": 196014,++ "net_per_day_7d": 58822,++ "pct": 0,++ "per_day_7d": 196014,++ "reclaimable_bytes": 137192,++ "recommended_limit": 137438953472,++ "resource": "terminal_bytes",++ "scope": "brain",++ "spike_day": null,++ "status": "ok",++ "under_reserved_receipts": 0,++ "used": 196014,++ "window_days": 1++ },++ {++ "basis": "aggregate_1d_short_history",++ "config_key": "persistence.limits.principal_lifetime_ids",++ "days_to_exhaustion": null,++ "exhaustion_date": null,++ "limit": 2000000,++ "max_day_7d": 24,++ "pct": 0,++ "per_day_7d": 24,++ "recommended_limit": 4000000,++ "resource": "lifetime_ids",++ "scope": "principal:local_cli:<uuid>",++ "spike_day": null,++ "status": "ok",++ "used": 24,++ "window_days": 1++ },++ {++ "basis": "aggregate_1d_short_history:gross_then_net",++ "config_key": "persistence.limits.principal_terminal_bytes",++ "days_to_exhaustion": null,++ "exhaustion_date": null,++ "limit": 17179869184,++ "max_day_7d": 196014,++ "net_per_day_7d": 58822,++ "pct": 0,++ "per_day_7d": 196014,++ "reclaimable_bytes": 137192,++ "recommended_limit": 34359738368,++ "resource": "terminal_bytes",++ "scope": "principal:local_cli:<uuid>",++ "spike_day": null,++ "status": "ok",++ "under_reserved_receipts": 0,++ "used": 196014,++ "window_days": 1++ }++ ],++ "table_bytes": "<volatile>",++ "thresholds": {++ "fail_days": 7,++ "fail_pct": 95,++ "warn_days": 30,++ "warn_pct": 80++ },++ "window_days": 1++ },+ "inspected": 2,++ "paused_producers": [],+ "resources": [],- "truncated": false++ "truncated": false,++ "verify": "gbrain doctor --only persistence_capacity --json"+ },+ "elapsed_ms": "<volatile>",- "message": "Managed write capacity is below 80% of every cumulative limit.",++ "message": "Managed write capacity is below 80% of every cumulative limit and none runs out within 30 days at its 7-day rate.",+ "name": "persistence_capacity",+ "status": "ok"+ },+ {+ "category": "ops",+ "details": {+ "active_blockers": [],+ "config": {+ "receipt_retention_days": 30,+ "spike_factor": {+ "key": "persistence.terminal_failures.spike_factor",+ "value": 3+ },+ "spike_min": {+ "key": "persistence.terminal_failures.spike_min",+ "value": 25+ },+ "window_clamped": false,+ "window_days": {+ "key": "persistence.terminal_failures.window_days",+ "value": 7+ }+ },+ "count": 0,+ "defects": [],+ "docs": "docs/guides/troubleshooting.md#terminal-write-failures",+ "historical_rows": 0,+ "new_last_24h": 0,+ "sources": [],+ "spike": {+ "daily_7d": [+ 0,+ 0,+ 0,+ 0,+ 0,+ 0,+ 0+ ],+ "last_24h": 0,+ "median_7d": 0,+ "spiking": false+ },+ "unresolved": {+ "distinct_intents": 0,+ "distinct_slugs": 0,+ "oldest_age_seconds": null,+ "rows": 0+ },+ "window_days": 7+ },+ "elapsed_ms": "<volatile>",+ "message": "No terminal write failures in the last 7 d.",+ "name": "persistence_terminal_failures",+ "status": "ok"+ },+ {+ "category": "ops",+ "details": {+ "count": 0,+ "docs": "docs/guides/troubleshooting.md#managed-sync-not-moving",+ "parked": 0,+ "sources": []+ },+ "elapsed_ms": "<volatile>",+ "message": "No managed sync is pending.",+ "name": "managed_sync_not_moving",+ "status": "ok"+ },+ {+ "category": "ops",+ "details": {- "docs": "docs/guides/troubleshooting.md#receipt-compaction",- "recorded": false++ "docs": "docs/guides/repair.md#receipt-compaction",++ "last_compaction": {++ "at": "<ts>",++ "compacted": 0,++ "freed_bytes": 0,++ "host_id": "<uuid>",++ "skipped_by_reason": {}++ },++ "last_compaction_age_hours": 0,++ "live_consumers": 0,++ "stale_hours": 24+ },+ "elapsed_ms": "<volatile>",- "message": "No receipt compaction recorded yet (persistence.maintenance.last_compaction is unset): the persistence consumer records one after it compacts.",- "name": "receipt_compaction",- "readiness_state": "not_applicable",- "severity": "info",++ "message": "Receipt compaction last ran 0 hour(s) ago (compacted 0, freed 0 bytes).",++ "name": "persistence_compaction",+ "status": "ok"+ },+ {+ "category": "ops",+ "details": {+ "count": 0,+ "docs": "docs/guides/troubleshooting.md#serve-build-drift",+ "newer": [],+ "older": [],+ "owner": null,+ "this_version": "<version>"+ },+ "elapsed_ms": "<volatile>",+ "message": "No live gbrain consumer on this host writes a heartbeat row. A serve that predates heartbeats writes none; consumers_without_heartbeat names it when it holds claims.",+ "name": "serve_build_drift",+ "status": "ok"+ },+ {+ "category": "meta",+ "details": {+ "code": "page_type_undeclared",+ "docs": "docs/architecture/schema-packs.md#undeclared-page-types",+ "per_source": [+ {+ "pack": "gbrain-base-v2",+ "source_id": "notes",+ "total": 19,+ "undeclared": 1,+ "undeclared_types": [+ {+ "count": 1,+ "type": "2024"+ }+ ],+ "untyped": 0+ },+ {+ "pack": "gbrain-base-v2",+ "source_id": "plain",+ "total": 1,+ "undeclared": 0,+ "undeclared_types": [],+ "untyped": 0+ }+ ],+ "unresolved_sources": []+ },+ "elapsed_ms": "<volatile>",+ "fix_unavailable_reason": "unstructured",+ "message": "Source `notes`: 1 page(s) use 1 type(s) pack `gbrain-base-v2` neither declares nor aliases: '2024' (1). List them with `gbrain schema review-orphans --source notes`, then declare the type (`gbrain schema add-type <type>`, which takes its primitive and prefix) or retype the pages to a declared type.",+ "name": "schema_pack_consistency",+ "status": "warn"+ },+ {+ "category": "brain",+ "details": {+ "active_column": "embedding",+ "basis": "exact",+ "counts": {+ "chunkless_healable": 0,+ "deleted_page_chunks": 0,+ "embedded": 0,+ "empty": 1,+ "keyword_only": 0,+ "pending": 23,+ "quarantined": 0+ },+ "coverage": {+ "basis": "exact",+ "eligible": 23,+ "embedded": 0,+ "ratio": 0+ },+ "covering_index": null,+ "deleted_page_chunks": {+ "past_window": 0,+ "window_hours": 72,+ "within_window": 0+ },+ "embeddings_enabled": false,+ "exact": true,+ "keyword_only": {+ "marker_bytes": 0,+ "pages": 0,+ "reason": "embed_skip",+ "threshold_bytes": 500000+ },+ "mode": "full",+ "omitted_states": [],+ "reason": "embeddings_disabled",+ "status": "known",+ "units": "content_chunks rows, plus one unit per page with no chunk rows",+ "unsearchable": 1,+ "unsearchable_complete": true,+ "unstamped_pending": {+ "count": 0,+ "created_at_lower_bound": null,+ "writer_version": "<version>"+ }+ },+ "elapsed_ms": "<volatile>",+ "fix": {+ "actor": "user",+ "argv": [+ "gbrain",+ "init",+ "--force",+ "--embedding-model",+ "voyage:voyage-4",+ "--embedding-dimensions",+ "1024"+ ],+ "command": "gbrain init --force --embedding-model voyage:voyage-4 --embedding-dimensions 1024",+ "consent": [+ "credentials",+ "paid"+ ],+ "docs": "https://github.com/garrytan/gbrain/blob/master/docs/guides/search-modes.md",+ "inputs": [+ {+ "how": "Ask the user for an API key for Voyage AI; store it with `gbrain config set voyage_api_key <key>` (every gbrain process reads it), or export VOYAGE_API_KEY in the environment of every gbrain process. Then run the command.",+ "name": "VOYAGE_API_KEY"+ }+ ],+ "next": "tell_user_to_run",+ "requires_exclusive": true,+ "user_message": "Semantic search needs an embedding API key. Voyage AI works with this brain; if you add a key (VOYAGE_API_KEY), I can turn it on. Embedding costs a little per page; your notes and facts stay as they are.",+ "verify": {+ "argv": [+ "gbrain",+ "doctor",+ "--only",+ "embeddings",+ "--json",+ "--brain",+ "host"+ ]+ },+ "why": "Embeddings are off, so search is keyword-only, and no configured embedding key fits this brain. Once the key is set this turns on voyage:voyage-4 (1024d) for this Postgres brain. Pages, facts and keyword search are kept; existing chunks and facts are queued for vectors, which `gbrain embed --stale` (or the next maintenance cycle) fills."},- "message": "No agent harness was detected. Wire one when the user picks an agent app.",- "name": "harness_wiring",- "readiness_state": "missing",+ "message": "Embedding state (exact, column 'embedding'): 0 embedded, 23 pending, 0 keyword-only, 0 quarantined, 1 empty, 0 on deleted pages, 0 chunkless (healable); 1 unsearchable. Embeddings are disabled by choice: keyword search reads the pending chunks.",+ "name": "embedding_state",+ "readiness_state": "disabled_by_choice","severity": "info","status": "ok"},@@@ -4288,6 -3754,141 +4498,19 @@@"name": "text_projection_readiness","status": "warn"},- {- "category": "ops",- "details": {- "background_pause_pct": 80,- "commands": [],- "docs": "docs/guides/concurrent-writes.md#quota-near-exhaustion",- "exact": true,- "forecast": {- "retention_days": 30,- "rows": [- {- "basis": "aggregate_1d_short_history",- "config_key": "persistence.limits.brain_lifetime_ids",- "days_to_exhaustion": null,- "exhaustion_date": null,- "limit": 8000000,- "max_day_7d": 24,- "pct": 0,- "per_day_7d": 24,- "recommended_limit": 16000000,- "resource": "lifetime_ids",- "scope": "brain",- "spike_day": null,- "status": "ok",- "used": 24,- "window_days": 1- },- {- "basis": "aggregate_1d_short_history:gross_then_net",- "config_key": "persistence.limits.brain_terminal_bytes",- "days_to_exhaustion": null,- "exhaustion_date": null,- "limit": 68719476736,- "max_day_7d": 196014,- "net_per_day_7d": 58822,- "pct": 0,- "per_day_7d": 196014,- "reclaimable_bytes": 137192,- "recommended_limit": 137438953472,- "resource": "terminal_bytes",- "scope": "brain",- "spike_day": null,- "status": "ok",- "under_reserved_receipts": 0,- "used": 196014,- "window_days": 1- },- {- "basis": "aggregate_1d_short_history",- "config_key": "persistence.limits.principal_lifetime_ids",- "days_to_exhaustion": null,- "exhaustion_date": null,- "limit": 2000000,- "max_day_7d": 24,- "pct": 0,- "per_day_7d": 24,- "recommended_limit": 4000000,- "resource": "lifetime_ids",- "scope": "principal:local_cli:<uuid>",- "spike_day": null,- "status": "ok",- "used": 24,- "window_days": 1- },- {- "basis": "aggregate_1d_short_history:gross_then_net",- "config_key": "persistence.limits.principal_terminal_bytes",- "days_to_exhaustion": null,- "exhaustion_date": null,- "limit": 17179869184,- "max_day_7d": 196014,- "net_per_day_7d": 58822,- "pct": 0,- "per_day_7d": 196014,- "reclaimable_bytes": 137192,- "recommended_limit": 34359738368,- "resource": "terminal_bytes",- "scope": "principal:local_cli:<uuid>",- "spike_day": null,- "status": "ok",- "under_reserved_receipts": 0,- "used": 196014,- "window_days": 1- }- ],- "table_bytes": "<volatile>",- "thresholds": {- "fail_days": 7,- "fail_pct": 95,- "warn_days": 30,- "warn_pct": 80- },- "window_days": 1- },- "inspected": 2,- "paused_producers": [],- "resources": [],- "truncated": false,- "verify": "gbrain doctor --only persistence_capacity --json"- },- "message": "Managed write capacity is below 80% of every cumulative limit and none runs out within 30 days at its 7-day rate.",- "name": "persistence_capacity",- "status": "ok"- },- {- "category": "ops",- "details": {- "docs": "docs/guides/repair.md#receipt-compaction",- "last_compaction": {- "at": "<ts>",- "compacted": 0,- "freed_bytes": 0,- "host_id": "<uuid>",- "skipped_by_reason": {}- },- "last_compaction_age_hours": 0,- "live_consumers": 0,- "stale_hours": 24- },- "message": "Receipt compaction last ran 0 hour(s) ago (compacted 0, freed 0 bytes).",- "name": "persistence_compaction",- "status": "ok"- },+ {+ "category": "ops",+ "details": {+ "docs": "docs/guides/concurrent-writes.md#counter-drift",+ "drift": [],+ "inspected": 2,+ "true_up_clamped": 0+ },++ "elapsed_ms": "<volatile>",+ "message": "Receipt-bytes counters match the receipts they account for (2 scope(s)).",+ "name": "persistence_counter_drift",+ "status": "ok"+ },{"category": "brain","details": {@@@ -4743,8 -4315,7 +4966,8 @@@"verify": "gbrain doctor --json (check persistence_request_growth)","window_days": 7},+ "elapsed_ms": "<volatile>",- "message": "~22 request row(s); no scope exhausts its lifetime request IDs within 90 days at its last-7-day rate.",+ "message": "~22 request row(s); no scope exhausts its lifetime request IDs within 30 days at its last-7-day rate.","name": "persistence_request_growth","status": "ok"},@@@ -5161,9 -4762,9 +5384,10 @@@"docs": "docs/guides/troubleshooting.md#maintenance-write-drift","repair": "file-drift","sources": [],+ "suppressed": [],"window_sequences": 20000},+ "elapsed_ms": "<volatile>","message": "No page whose writes refuse source_changed still has a canonical file that differs from the database.","name": "maintenance_write_drift","status": "ok"diff --cc test/fixtures/goldens/doctor/json-pglite-degraded.jsonindex 9efc82f247,d6f84ec2c3..8781073674--- a/test/fixtures/goldens/doctor/json-pglite-degraded.json+++ b/test/fixtures/goldens/doctor/json-pglite-degraded.json@@@ -462,14 -431,126 +462,105 @@@{"category": "ops","details": {+ "background_pause_pct": 80,"commands": [],+ "docs": "docs/guides/concurrent-writes.md#quota-near-exhaustion","exact": true,+ "forecast": {+ "retention_days": 30,+ "rows": [+ {+ "basis": "aggregate_1d_short_history",+ "config_key": "persistence.limits.brain_lifetime_ids",+ "days_to_exhaustion": null,+ "exhaustion_date": null,+ "limit": 8000000,+ "max_day_7d": 1,+ "pct": 0,+ "per_day_7d": 1,+ "recommended_limit": 16000000,+ "resource": "lifetime_ids",+ "scope": "brain",+ "spike_day": null,+ "status": "ok",+ "used": 1,+ "window_days": 1+ },+ {+ "basis": "aggregate_1d_short_history:gross_then_net",+ "config_key": "persistence.limits.brain_terminal_bytes",+ "days_to_exhaustion": null,+ "exhaustion_date": null,+ "limit": 68719476736,+ "max_day_7d": 19163,+ "net_per_day_7d": 2845,+ "pct": 0,+ "per_day_7d": 19163,+ "reclaimable_bytes": 16318,+ "recommended_limit": 137438953472,+ "resource": "terminal_bytes",+ "scope": "brain",+ "spike_day": null,+ "status": "ok",+ "under_reserved_receipts": 0,+ "used": 19163,+ "window_days": 1+ },+ {+ "basis": "aggregate_1d_short_history",+ "config_key": "persistence.limits.principal_lifetime_ids",+ "days_to_exhaustion": null,+ "exhaustion_date": null,+ "limit": 2000000,+ "max_day_7d": 1,+ "pct": 0,+ "per_day_7d": 1,+ "recommended_limit": 4000000,+ "resource": "lifetime_ids",+ "scope": "principal:local_cli:<uuid>",+ "spike_day": null,+ "status": "ok",+ "used": 1,+ "window_days": 1+ },+ {+ "basis": "aggregate_1d_short_history:gross_then_net",+ "config_key": "persistence.limits.principal_terminal_bytes",+ "days_to_exhaustion": null,+ "exhaustion_date": null,+ "limit": 17179869184,+ "max_day_7d": 19163,+ "net_per_day_7d": 2845,+ "pct": 0,+ "per_day_7d": 19163,+ "reclaimable_bytes": 16318,+ "recommended_limit": 34359738368,+ "resource": "terminal_bytes",+ "scope": "principal:local_cli:<uuid>",+ "spike_day": null,+ "status": "ok",+ "under_reserved_receipts": 0,+ "used": 19163,+ "window_days": 1+ }+ ],+ "table_bytes": "<volatile>",+ "thresholds": {+ "fail_days": 7,+ "fail_pct": 95,+ "warn_days": 30,+ "warn_pct": 80+ },+ "window_days": 1+ },"inspected": 2,+ "paused_producers": [],"resources": [],- "truncated": false+ "truncated": false,+ "verify": "gbrain doctor --only persistence_capacity --json"},+ "elapsed_ms": "<volatile>",- "message": "Managed write capacity is below 80% of every cumulative limit.",+ "message": "Managed write capacity is below 80% of every cumulative limit and none runs out within 30 days at its 7-day rate.","name": "persistence_capacity","status": "ok"},@@@ -542,110 -557,34 +633,130 @@@{"category": "ops","details": {- "docs": "docs/guides/troubleshooting.md#receipt-compaction",- "recorded": false+ "docs": "docs/guides/repair.md#receipt-compaction",+ "last_compaction": {+ "at": "<ts>",+ "compacted": 0,+ "freed_bytes": 0,+ "host_id": "<uuid>",+ "skipped_by_reason": {}+ },+ "last_compaction_age_hours": 0,+ "live_consumers": 0,+ "stale_hours": 24},+ "elapsed_ms": "<volatile>",- "message": "No receipt compaction recorded yet (persistence.maintenance.last_compaction is unset): the persistence consumer records one after it compacts.",- "name": "receipt_compaction",- "readiness_state": "not_applicable",- "severity": "info",+ "message": "Receipt compaction last ran 0 hour(s) ago (compacted 0, freed 0 bytes).",+ "name": "persistence_compaction","status": "ok"},+ {+ "category": "ops",+ "details": {+ "count": 0,+ "docs": "docs/guides/troubleshooting.md#serve-build-drift"+ },+ "elapsed_ms": "<volatile>",+ "message": "PGLite admits one process; no consumer heartbeat rows are kept to compare builds.",+ "name": "serve_build_drift",+ "status": "ok"+ },+ {+ "category": "meta",+ "elapsed_ms": "<volatile>",+ "message": "No pages in any source — schema consistency N/A.",+ "name": "schema_pack_consistency",+ "status": "ok"+ },+ {+ "category": "brain",+ "details": {+ "active_column": "embedding",+ "basis": "exact",+ "counts": {+ "chunkless_healable": 0,+ "deleted_page_chunks": 0,+ "embedded": 0,+ "empty": 0,+ "keyword_only": 0,+ "pending": 0,+ "quarantined": 0+ },+ "coverage": {+ "basis": "exact",+ "eligible": 0,+ "embedded": 0,+ "ratio": null+ },+ "covering_index": null,+ "deleted_page_chunks": {+ "past_window": 0,+ "window_hours": 72,+ "within_window": 0+ },+ "embeddings_enabled": true,+ "exact": true,+ "keyword_only": {+ "marker_bytes": 0,+ "pages": 0,+ "reason": "embed_skip",+ "threshold_bytes": 500000+ },+ "mode": "full",+ "omitted_states": [],+ "status": "known",+ "units": "content_chunks rows, plus one unit per page with no chunk rows",+ "unsearchable": 0,+ "unsearchable_complete": true,+ "unstamped_pending": {+ "count": 0,+ "created_at_lower_bound": null,+ "writer_version": "<version>"+ }+ },+ "elapsed_ms": "<volatile>",+ "message": "Embedding state (exact, column 'embedding'): 0 embedded, 0 pending, 0 keyword-only, 0 quarantined, 0 empty, 0 on deleted pages, 0 chunkless (healable); 0 unsearchable.",+ "name": "embedding_state",+ "status": "ok"+ },+ {+ "category": "ops",+ "elapsed_ms": "<volatile>",+ "message": "Extension installed",+ "name": "pgvector",+ "status": "ok"+ },+ {+ "category": "meta",+ "elapsed_ms": "<volatile>",+ "message": "pages has the UNIQUE(source_id, slug) upsert arbiter",+ "name": "pages_upsert_arbiter",+ "status": "ok"+ },+ {+ "category": "brain",+ "details": {+ "readiness": "ready",+ "ready": true+ },+ "elapsed_ms": "<volatile>",+ "message": "Visible text projections match their canonical revisions.",+ "name": "text_projection_readiness",+ "status": "ok"+ },+ {+ "category": "ops",+ "details": {+ "docs": "docs/guides/concurrent-writes.md#counter-drift",+ "drift": [],+ "inspected": 2,+ "true_up_clamped": 0+ },++ "elapsed_ms": "<volatile>",+ "message": "Receipt-bytes counters match the receipts they account for (2 scope(s)).",+ "name": "persistence_counter_drift",+ "status": "ok"+ },{"category": "brain","details": {@@@ -1043,8 -952,7 +1154,8 @@@"verify": "gbrain doctor --json (check persistence_request_growth)","window_days": 7},+ "elapsed_ms": "<volatile>",- "message": "1 request row(s); no scope exhausts its lifetime request IDs within 90 days at its last-7-day rate.",+ "message": "1 request row(s); no scope exhausts its lifetime request IDs within 30 days at its last-7-day rate.","name": "persistence_request_growth","status": "ok"},@@@ -1372,9 -1310,9 +1483,10 @@@"docs": "docs/guides/troubleshooting.md#maintenance-write-drift","repair": "file-drift","sources": [],+ "suppressed": [],"window_sequences": 20000},+ "elapsed_ms": "<volatile>","message": "No page whose writes refuse source_changed still has a canonical file that differs from the database.","name": "maintenance_write_drift","status": "ok"diff --cc test/fixtures/goldens/doctor/json-pglite-fresh.jsonindex 360e8eaf7d,61cbf6b81b..125074040f--- a/test/fixtures/goldens/doctor/json-pglite-fresh.json+++ b/test/fixtures/goldens/doctor/json-pglite-fresh.json@@@ -465,14 -434,126 +465,105 @@@{"category": "ops","details": {+ "background_pause_pct": 80,"commands": [],+ "docs": "docs/guides/concurrent-writes.md#quota-near-exhaustion","exact": true,+ "forecast": {+ "retention_days": 30,+ "rows": [+ {+ "basis": "aggregate_1d_short_history",+ "config_key": "persistence.limits.brain_lifetime_ids",+ "days_to_exhaustion": null,+ "exhaustion_date": null,+ "limit": 8000000,+ "max_day_7d": 1,+ "pct": 0,+ "per_day_7d": 1,+ "recommended_limit": 16000000,+ "resource": "lifetime_ids",+ "scope": "brain",+ "spike_day": null,+ "status": "ok",+ "used": 1,+ "window_days": 1+ },+ {+ "basis": "aggregate_1d_short_history:gross_then_net",+ "config_key": "persistence.limits.brain_terminal_bytes",+ "days_to_exhaustion": null,+ "exhaustion_date": null,+ "limit": 68719476736,+ "max_day_7d": 19163,+ "net_per_day_7d": 2845,+ "pct": 0,+ "per_day_7d": 19163,+ "reclaimable_bytes": 16318,+ "recommended_limit": 137438953472,+ "resource": "terminal_bytes",+ "scope": "brain",+ "spike_day": null,+ "status": "ok",+ "under_reserved_receipts": 0,+ "used": 19163,+ "window_days": 1+ },+ {+ "basis": "aggregate_1d_short_history",+ "config_key": "persistence.limits.principal_lifetime_ids",+ "days_to_exhaustion": null,+ "exhaustion_date": null,+ "limit": 2000000,+ "max_day_7d": 1,+ "pct": 0,+ "per_day_7d": 1,+ "recommended_limit": 4000000,+ "resource": "lifetime_ids",+ "scope": "principal:local_cli:<uuid>",+ "spike_day": null,+ "status": "ok",+ "used": 1,+ "window_days": 1+ },+ {+ "basis": "aggregate_1d_short_history:gross_then_net",+ "config_key": "persistence.limits.principal_terminal_bytes",+ "days_to_exhaustion": null,+ "exhaustion_date": null,+ "limit": 17179869184,+ "max_day_7d": 19163,+ "net_per_day_7d": 2845,+ "pct": 0,+ "per_day_7d": 19163,+ "reclaimable_bytes": 16318,+ "recommended_limit": 34359738368,+ "resource": "terminal_bytes",+ "scope": "principal:local_cli:<uuid>",+ "spike_day": null,+ "status": "ok",+ "under_reserved_receipts": 0,+ "used": 19163,+ "window_days": 1+ }+ ],+ "table_bytes": "<volatile>",+ "thresholds": {+ "fail_days": 7,+ "fail_pct": 95,+ "warn_days": 30,+ "warn_pct": 80+ },+ "window_days": 1+ },"inspected": 2,+ "paused_producers": [],"resources": [],- "truncated": false+ "truncated": false,+ "verify": "gbrain doctor --only persistence_capacity --json"},+ "elapsed_ms": "<volatile>",- "message": "Managed write capacity is below 80% of every cumulative limit.",+ "message": "Managed write capacity is below 80% of every cumulative limit and none runs out within 30 days at its 7-day rate.","name": "persistence_capacity","status": "ok"},@@@ -545,154 -560,34 +636,174 @@@{"category": "ops","details": {- "docs": "docs/guides/troubleshooting.md#receipt-compaction",- "recorded": false+ "docs": "docs/guides/repair.md#receipt-compaction",+ "last_compaction": {+ "at": "<ts>",+ "compacted": 0,+ "freed_bytes": 0,+ "host_id": "<uuid>",+ "skipped_by_reason": {}+ },+ "last_compaction_age_hours": 0,+ "live_consumers": 0,+ "stale_hours": 24},+ "elapsed_ms": "<volatile>",- "message": "No receipt compaction recorded yet (persistence.maintenance.last_compaction is unset): the persistence consumer records one after it compacts.",- "name": "receipt_compaction",- "readiness_state": "not_applicable",- "severity": "info",+ "message": "Receipt compaction last ran 0 hour(s) ago (compacted 0, freed 0 bytes).",+ "name": "persistence_compaction","status": "ok"},+ {+ "category": "ops",+ "details": {+ "count": 0,+ "docs": "docs/guides/troubleshooting.md#serve-build-drift"+ },+ "elapsed_ms": "<volatile>",+ "message": "PGLite admits one process; no consumer heartbeat rows are kept to compare builds.",+ "name": "serve_build_drift",+ "status": "ok"+ },+ {+ "category": "meta",+ "elapsed_ms": "<volatile>",+ "message": "No pages in any source — schema consistency N/A.",+ "name": "schema_pack_consistency",+ "status": "ok"+ },+ {+ "category": "brain",+ "details": {+ "active_column": "embedding",+ "basis": "exact",+ "counts": {+ "chunkless_healable": 0,+ "deleted_page_chunks": 0,+ "embedded": 0,+ "empty": 0,+ "keyword_only": 0,+ "pending": 0,+ "quarantined": 0+ },+ "coverage": {+ "basis": "exact",+ "eligible": 0,+ "embedded": 0,+ "ratio": null+ },+ "covering_index": null,+ "deleted_page_chunks": {+ "past_window": 0,+ "window_hours": 72,+ "within_window": 0+ },+ "embeddings_enabled": false,+ "exact": true,+ "keyword_only": {+ "marker_bytes": 0,+ "pages": 0,+ "reason": "embed_skip",+ "threshold_bytes": 500000+ },+ "mode": "full",+ "omitted_states": [],+ "reason": "embeddings_disabled",+ "status": "known",+ "units": "content_chunks rows, plus one unit per page with no chunk rows",+ "unsearchable": 0,+ "unsearchable_complete": true,+ "unstamped_pending": {+ "count": 0,+ "created_at_lower_bound": null,+ "writer_version": "<version>"+ }+ },+ "elapsed_ms": "<volatile>",+ "fix": {+ "actor": "user",+ "argv": [+ "gbrain",+ "init",+ "--force",+ "--embedding-model",+ "voyage:voyage-4",+ "--embedding-dimensions",+ "1024",+ "--path",+ "<home>/.gbrain/brain.pglite"+ ],+ "command": "gbrain init --force --embedding-model voyage:voyage-4 --embedding-dimensions 1024 --path <home>/.gbrain/brain.pglite",+ "consent": [+ "credentials",+ "paid"+ ],+ "docs": "https://github.com/garrytan/gbrain/blob/master/docs/guides/search-modes.md",+ "inputs": [+ {+ "how": "Ask the user for an API key for Voyage AI; store it with `gbrain config set voyage_api_key <key>` (every gbrain process reads it), or export VOYAGE_API_KEY in the environment of every gbrain process. Then run the command.",+ "name": "VOYAGE_API_KEY"+ }+ ],+ "next": "tell_user_to_run",+ "requires_exclusive": true,+ "user_message": "Semantic search needs an embedding API key. Voyage AI works with this brain; if you add a key (VOYAGE_API_KEY), I can turn it on. Embedding costs a little per page; your notes and facts stay as they are.",+ "verify": {+ "argv": [+ "gbrain",+ "doctor",+ "--only",+ "embeddings",+ "--json",+ "--brain",+ "host"+ ]+ },+ "why": "Embeddings are off, so search is keyword-only, and no configured embedding key fits this brain. Once the key is set this turns on voyage:voyage-4 (1024d) for the PGLite brain at <home>/.gbrain/brain.pglite. Pages, facts and keyword search are kept; existing chunks and facts are queued for vectors, which `gbrain embed --stale` (or the next maintenance cycle) fills."+ },+ "message": "Embedding state (exact, column 'embedding'): 0 embedded, 0 pending, 0 keyword-only, 0 quarantined, 0 empty, 0 on deleted pages, 0 chunkless (healable); 0 unsearchable.",+ "name": "embedding_state",+ "readiness_state": "disabled_by_choice",+ "severity": "info",+ "status": "ok"+ },+ {+ "category": "ops",+ "elapsed_ms": "<volatile>",+ "message": "Extension installed",+ "name": "pgvector",+ "status": "ok"+ },+ {+ "category": "meta",+ "elapsed_ms": "<volatile>",+ "message": "pages has the UNIQUE(source_id, slug) upsert arbiter",+ "name": "pages_upsert_arbiter",+ "status": "ok"+ },+ {+ "category": "brain",+ "details": {+ "readiness": "ready",+ "ready": true+ },+ "elapsed_ms": "<volatile>",+ "message": "Visible text projections match their canonical revisions.",+ "name": "text_projection_readiness",+ "status": "ok"+ },+ {+ "category": "ops",+ "details": {+ "docs": "docs/guides/concurrent-writes.md#counter-drift",+ "drift": [],+ "inspected": 2,+ "true_up_clamped": 0+ },++ "elapsed_ms": "<volatile>",+ "message": "Receipt-bytes counters match the receipts they account for (2 scope(s)).",+ "name": "persistence_counter_drift",+ "status": "ok"+ },{"category": "brain","details": {@@@ -1106,8 -971,7 +1217,8 @@@"verify": "gbrain doctor --json (check persistence_request_growth)","window_days": 7},+ "elapsed_ms": "<volatile>",- "message": "1 request row(s); no scope exhausts its lifetime request IDs within 90 days at its last-7-day rate.",+ "message": "1 request row(s); no scope exhausts its lifetime request IDs within 30 days at its last-7-day rate.","name": "persistence_request_growth","status": "ok"},@@@ -1435,9 -1329,9 +1546,10 @@@"docs": "docs/guides/troubleshooting.md#maintenance-write-drift","repair": "file-drift","sources": [],+ "suppressed": [],"window_sequences": 20000},+ "elapsed_ms": "<volatile>","message": "No page whose writes refuse source_changed still has a canonical file that differs from the database.","name": "maintenance_write_drift","status": "ok"diff --cc test/fixtures/goldens/doctor/json-postgres-fresh.jsonindex 7a3da61866,ae81d944c0..1880629593--- a/test/fixtures/goldens/doctor/json-postgres-fresh.json+++ b/test/fixtures/goldens/doctor/json-postgres-fresh.json@@@ -459,14 -427,132 +459,105 @@@{"category": "ops","details": {+ "background_pause_pct": 80,"commands": [],+ "docs": "docs/guides/concurrent-writes.md#quota-near-exhaustion","exact": true,+ "forecast": {+ "retention_days": 30,+ "rows": [+ {+ "basis": "aggregate_1d_short_history",+ "config_key": "persistence.limits.brain_lifetime_ids",+ "days_to_exhaustion": null,+ "exhaustion_date": null,+ "limit": 8000000,+ "max_day_7d": 1,+ "pct": 0,+ "per_day_7d": 1,+ "recommended_limit": 16000000,+ "resource": "lifetime_ids",+ "scope": "brain",+ "spike_day": null,+ "status": "ok",+ "used": 1,+ "window_days": 1+ },+ {+ "basis": "aggregate_1d_short_history:gross_then_net",+ "config_key": "persistence.limits.brain_terminal_bytes",+ "days_to_exhaustion": null,+ "exhaustion_date": null,+ "limit": 68719476736,+ "max_day_7d": 19163,+ "net_per_day_7d": 2845,+ "pct": 0,+ "per_day_7d": 19163,+ "reclaimable_bytes": 16318,+ "recommended_limit": 137438953472,+ "resource": "terminal_bytes",+ "scope": "brain",+ "spike_day": null,+ "status": "ok",+ "under_reserved_receipts": 0,+ "used": 19163,+ "window_days": 1+ },+ {+ "basis": "aggregate_1d_short_history",+ "config_key": "persistence.limits.principal_lifetime_ids",+ "days_to_exhaustion": null,+ "exhaustion_date": null,+ "limit": 2000000,+ "max_day_7d": 1,+ "pct": 0,+ "per_day_7d": 1,+ "recommended_limit": 4000000,+ "resource": "lifetime_ids",+ "scope": "principal:local_cli:<uuid>",+ "spike_day": null,+ "status": "ok",+ "used": 1,+ "window_days": 1+ },+ {+ "basis": "aggregate_1d_short_history:gross_then_net",+ "config_key": "persistence.limits.principal_terminal_bytes",+ "days_to_exhaustion": null,+ "exhaustion_date": null,+ "limit": 17179869184,+ "max_day_7d": 19163,+ "net_per_day_7d": 2845,+ "pct": 0,+ "per_day_7d": 19163,+ "reclaimable_bytes": 16318,+ "recommended_limit": 34359738368,+ "resource": "terminal_bytes",+ "scope": "principal:local_cli:<uuid>",+ "spike_day": null,+ "status": "ok",+ "under_reserved_receipts": 0,+ "used": 19163,+ "window_days": 1+ }+ ],+ "table_bytes": "<volatile>",+ "thresholds": {+ "fail_days": 7,+ "fail_pct": 95,+ "warn_days": 30,+ "warn_pct": 80+ },+ "window_days": 1+ },"inspected": 2,+ "paused_producers": [],"resources": [],- "truncated": false+ "truncated": false,+ "verify": "gbrain doctor --only persistence_capacity --json"},+ "elapsed_ms": "<volatile>",- "message": "Managed write capacity is below 80% of every cumulative limit.",+ "message": "Managed write capacity is below 80% of every cumulative limit and none runs out within 30 days at its 7-day rate.","name": "persistence_capacity","status": "ok"},@@@ -539,163 -559,34 +630,183 @@@{"category": "ops","details": {- "docs": "docs/guides/troubleshooting.md#receipt-compaction",- "recorded": false+ "docs": "docs/guides/repair.md#receipt-compaction",+ "last_compaction": {+ "at": "<ts>",+ "compacted": 0,+ "freed_bytes": 0,+ "host_id": "<uuid>",+ "skipped_by_reason": {}+ },+ "last_compaction_age_hours": 0,+ "live_consumers": 0,+ "stale_hours": 24},+ "elapsed_ms": "<volatile>",- "message": "No receipt compaction recorded yet (persistence.maintenance.last_compaction is unset): the persistence consumer records one after it compacts.",- "name": "receipt_compaction",- "readiness_state": "not_applicable",- "severity": "info",+ "message": "Receipt compaction last ran 0 hour(s) ago (compacted 0, freed 0 bytes).",+ "name": "persistence_compaction","status": "ok"},+ {+ "category": "ops",+ "details": {+ "count": 0,+ "docs": "docs/guides/troubleshooting.md#serve-build-drift",+ "newer": [],+ "older": [],+ "owner": null,+ "this_version": "<version>"+ },+ "elapsed_ms": "<volatile>",+ "message": "No live gbrain consumer on this host writes a heartbeat row. A serve that predates heartbeats writes none; consumers_without_heartbeat names it when it holds claims.",+ "name": "serve_build_drift",+ "status": "ok"+ },+ {+ "category": "meta",+ "elapsed_ms": "<volatile>",+ "message": "No pages in any source — schema consistency N/A.",+ "name": "schema_pack_consistency",+ "status": "ok"+ },+ {+ "category": "brain",+ "details": {+ "active_column": "embedding",+ "basis": "exact",+ "counts": {+ "chunkless_healable": 0,+ "deleted_page_chunks": 0,+ "embedded": 0,+ "empty": 0,+ "keyword_only": 0,+ "pending": 0,+ "quarantined": 0+ },+ "coverage": {+ "basis": "exact",+ "eligible": 0,+ "embedded": 0,+ "ratio": null+ },+ "covering_index": null,+ "deleted_page_chunks": {+ "past_window": 0,+ "window_hours": 72,+ "within_window": 0+ },+ "embeddings_enabled": false,+ "exact": true,+ "keyword_only": {+ "marker_bytes": 0,+ "pages": 0,+ "reason": "embed_skip",+ "threshold_bytes": 500000+ },+ "mode": "full",+ "omitted_states": [],+ "reason": "embeddings_disabled",+ "status": "known",+ "units": "content_chunks rows, plus one unit per page with no chunk rows",+ "unsearchable": 0,+ "unsearchable_complete": true,+ "unstamped_pending": {+ "count": 0,+ "created_at_lower_bound": null,+ "writer_version": "<version>"+ }+ },+ "elapsed_ms": "<volatile>",+ "fix": {+ "actor": "user",+ "argv": [+ "gbrain",+ "init",+ "--force",+ "--embedding-model",+ "voyage:voyage-4",+ "--embedding-dimensions",+ "1024"+ ],+ "command": "gbrain init --force --embedding-model voyage:voyage-4 --embedding-dimensions 1024",+ "consent": [+ "credentials",+ "paid"+ ],+ "docs": "https://github.com/garrytan/gbrain/blob/master/docs/guides/search-modes.md",+ "inputs": [+ {+ "how": "Ask the user for an API key for Voyage AI; store it with `gbrain config set voyage_api_key <key>` (every gbrain process reads it), or export VOYAGE_API_KEY in the environment of every gbrain process. Then run the command.",+ "name": "VOYAGE_API_KEY"+ }+ ],+ "next": "tell_user_to_run",+ "requires_exclusive": true,+ "user_message": "Semantic search needs an embedding API key. Voyage AI works with this brain; if you add a key (VOYAGE_API_KEY), I can turn it on. Embedding costs a little per page; your notes and facts stay as they are.",+ "verify": {+ "argv": [+ "gbrain",+ "doctor",+ "--only",+ "embeddings",+ "--json",+ "--brain",+ "host"+ ]+ },+ "why": "Embeddings are off, so search is keyword-only, and no configured embedding key fits this brain. Once the key is set this turns on voyage:voyage-4 (1024d) for this Postgres brain. Pages, facts and keyword search are kept; existing chunks and facts are queued for vectors, which `gbrain embed --stale` (or the next maintenance cycle) fills."+ },+ "message": "Embedding state (exact, column 'embedding'): 0 embedded, 0 pending, 0 keyword-only, 0 quarantined, 0 empty, 0 on deleted pages, 0 chunkless (healable); 0 unsearchable.",+ "name": "embedding_state",+ "readiness_state": "disabled_by_choice",+ "severity": "info",+ "status": "ok"+ },+ {+ "category": "ops",+ "elapsed_ms": "<volatile>",+ "message": "Extension installed",+ "name": "pgvector",+ "status": "ok"+ },+ {+ "category": "ops",+ "elapsed_ms": "<volatile>",+ "message": "Postgres driver supports safe query cancellation.",+ "name": "postgres_cancellation_driver",+ "status": "ok"+ },+ {+ "category": "meta",+ "elapsed_ms": "<volatile>",+ "message": "pages has the UNIQUE(source_id, slug) upsert arbiter",+ "name": "pages_upsert_arbiter",+ "status": "ok"+ },+ {+ "category": "brain",+ "details": {+ "readiness": "ready",+ "ready": true+ },+ "elapsed_ms": "<volatile>",+ "message": "Visible text projections match their canonical revisions.",+ "name": "text_projection_readiness",+ "status": "ok"+ },+ {+ "category": "ops",+ "details": {+ "docs": "docs/guides/concurrent-writes.md#counter-drift",+ "drift": [],+ "inspected": 2,+ "true_up_clamped": 0+ },++ "elapsed_ms": "<volatile>",+ "message": "Receipt-bytes counters match the receipts they account for (2 scope(s)).",+ "name": "persistence_counter_drift",+ "status": "ok"+ },{"category": "brain","details": {@@@ -1098,8 -960,7 +1209,8 @@@"verify": "gbrain doctor --json (check persistence_request_growth)","window_days": 7},+ "elapsed_ms": "<volatile>",- "message": "~0 request row(s); no scope exhausts its lifetime request IDs within 90 days at its last-7-day rate.",+ "message": "~0 request row(s); no scope exhausts its lifetime request IDs within 30 days at its last-7-day rate.","name": "persistence_request_growth","status": "ok"},@@@ -1434,9 -1325,9 +1545,10 @@@"docs": "docs/guides/troubleshooting.md#maintenance-write-drift","repair": "file-drift","sources": [],+ "suppressed": [],"window_sequences": 20000},+ "elapsed_ms": "<volatile>","message": "No page whose writes refuse source_changed still has a canonical file that differs from the database.","name": "maintenance_write_drift","status": "ok"diff --cc test/fixtures/goldens/doctor/registry-build-checks.jsonindex 4e92dfc5b1,b8e161a2ce..668458c090--- a/test/fixtures/goldens/doctor/registry-build-checks.json+++ b/test/fixtures/goldens/doctor/registry-build-checks.json@@@ -255,19 -255,7 +255,19 @@@},{"category": "ops",- "name": "postgres_cancellation_driver"+ "name": "persistence_terminal_failures"+ },+ {+ "category": "ops",+ "name": "managed_sync_not_moving"+ },+ {+ "category": "ops",- "name": "receipt_compaction"++ "name": "persistence_compaction"+ },+ {+ "category": "ops",+ "name": "serve_build_drift"},{"category": "meta",@@@ -283,12 -267,12 +283,16 @@@},{"category": "ops",- "name": "persistence_compaction"+ "name": "postgres_cancellation_driver"+ },+ {+ "category": "meta",+ "name": "pages_upsert_arbiter"},+ {+ "category": "ops",+ "name": "persistence_counter_drift"+ },{"category": "brain","name": "parked_effects"diff --cc test/fixtures/goldens/exports/runtime.jsonindex b174fe3151,b174fe3151..798f84b9ae--- a/test/fixtures/goldens/exports/runtime.json+++ b/test/fixtures/goldens/exports/runtime.json@@@ -107,6 -107,6 +107,7 @@@"listChunklessPagesWithContent","listConfigKeys","listCorpusSample",++ "listEmbeddingStateRows","listEnrichCandidates","listEvalCandidates","listEvalCaptureFailures",@@@ -138,6 -138,6 +139,7 @@@"putDreamVerdict","putPage","putRawData",++ "readEmbeddingStateCounts","readPageSnapshot","readPageSnapshotsBatch","reconnect",@@@ -299,6 -299,6 +301,7 @@@"listChunklessPagesWithContent","listConfigKeys","listCorpusSample",++ "listEmbeddingStateRows","listEnrichCandidates","listEvalCandidates","listEvalCaptureFailures",@@@ -331,6 -331,6 +334,7 @@@"putDreamVerdict","putPage","putRawData",++ "readEmbeddingStateCounts","readPageSnapshot","readPageSnapshotsBatch","reconnect",diff --cc test/fixtures/goldens/exports/types.jsonindex 5cce27c22d,bc20ae6999..218fba60cb--- a/test/fixtures/goldens/exports/types.json+++ b/test/fixtures/goldens/exports/types.json@@@ -81,7 -81,7 +81,7 @@@"deletePages: (slugs: string[], opts: { sourceId: string; }) => Promise<string[]>","disconnect: () => Promise<void>","discoverOntologyDimensions: (opts?: { sourceId?: string; sourceIds?: string[]; }) => Promise<OntologyDimensionStat[]>",-- "executeRaw: <T = Record<string, unknown>>(sql: string, params?: unknown[], opts?: { signal?: AbortSignal; timeoutMs?: number; }) => Promise<T[]>",++ "executeRaw: <T = Record<string, unknown>>(sql: string, params?: unknown[], opts?: { signal?: AbortSignal; timeoutMs?: number; deadlineAt?: number; }) => Promise<T[]>","executeRawDirect: <T = Record<string, unknown>>(sql: string, params?: unknown[], opts?: { signal?: AbortSignal; }) => Promise<T[]>","expireFact: (id: number, opts?: { supersededBy?: number; at?: Date; }) => Promise<boolean>","findAnomalies: (opts: AnomaliesOpts) => Promise<AnomalyResult[]>",@@@ -143,6 -143,6 +143,7 @@@"listChunklessPagesWithContent: (opts?: { batchSize?: number; afterPageId?: number; sourceId?: string; }) => Promise<ChunklessPageRow[]>","listConfigKeys: (prefix: string) => Promise<string[]>","listCorpusSample: (opts: CorpusSampleOpts) => Promise<DomainBankRow[]>",++ "listEmbeddingStateRows: (opts: { sourceIds?: string[]; states: readonly EmbeddingState[]; limit: number; purgeWindowHours: number; }) => Promise<EmbeddingStateRow[]>","listEnrichCandidates: (opts: EnrichCandidatesOpts) => Promise<EnrichCandidate[]>","listEvalCandidates: (filter?: { since?: Date; limit?: number; tool?: \"query\" | \"search\"; }) => Promise<EvalCandidate[]>","listEvalCaptureFailures: (filter?: { since?: Date; }) => Promise<EvalCaptureFailure[]>",@@@ -174,6 -174,6 +175,7 @@@"putDreamVerdict: (filePath: string, contentHash: string, verdict: DreamVerdictInput) => Promise<void>","putPage: (slug: string, page: PageInput, opts?: PageWriteOptions) => Promise<Page>","putRawData: (slug: string, source: string, data: object, opts?: { sourceId?: string; }) => Promise<void>",++ "readEmbeddingStateCounts: (opts: { mode: \"ops\" | \"full\"; sourceIds?: string[]; purgeWindowHours: number; }) => Promise<EmbeddingStateCounts>","readPageSnapshot: (slug: string, opts?: PageSnapshotOptions) => Promise<PageSnapshot | null>","readPageSnapshotsBatch: (refs: ReadonlyArray<{ slug: string; sourceId: string; }>, opts?: { maxBytes?: number; includeDeleted?: boolean; absentIsNull?: boolean; }) => Promise<PageSnapshotBatch>","readonly kind: \"postgres\" | \"pglite\"",@@@ -842,7 -842,7 +844,7 @@@"entitySlug: string","source: string","sourceId?: string | undefined",-- "status?: \"active\" | \"quarantined\" | undefined",++ "status?: \"quarantined\" | \"active\" | undefined","validFrom?: string | null | undefined","validTo?: string | null | undefined","value: string",@@@ -1053,7 -1053,7 +1055,7 @@@"deletePages: (slugs: string[], opts: { sourceId: string; }) => Promise<string[]>","disconnect: () => Promise<void>","discoverOntologyDimensions: (opts?: { sourceId?: string; sourceIds?: string[]; }) => Promise<OntologyDimensionStat[]>",-- "executeRaw: <T = Record<string, unknown>>(sql: string, params?: unknown[], opts?: { signal?: AbortSignal; timeoutMs?: number; }) => Promise<T[]>",++ "executeRaw: <T = Record<string, unknown>>(sql: string, params?: unknown[], opts?: { signal?: AbortSignal; timeoutMs?: number; deadlineAt?: number; }) => Promise<T[]>","executeRawDirect: <T = Record<string, unknown>>(sql: string, params?: unknown[], opts?: { signal?: AbortSignal; }) => Promise<T[]>","expireFact: (id: number, opts?: { supersededBy?: number; at?: Date; }) => Promise<boolean>","explainVectorSearch: (embedding: Float32Array, opts?: SearchOpts) => Promise<Record<string, unknown>>",@@@ -1117,6 -1117,6 +1119,7 @@@"listChunklessPagesWithContent: (opts?: { batchSize?: number; afterPageId?: number; sourceId?: string; }) => Promise<ChunklessPageRow[]>","listConfigKeys: (prefix: string) => Promise<string[]>","listCorpusSample: (opts: CorpusSampleOpts) => Promise<DomainBankRow[]>",++ "listEmbeddingStateRows: (opts: { sourceIds?: string[]; states: readonly EmbeddingState[]; limit: number; purgeWindowHours: number; }) => Promise<EmbeddingStateRow[]>","listEnrichCandidates: (opts: EnrichCandidatesOpts) => Promise<EnrichCandidate[]>","listEvalCandidates: (filter?: { since?: Date; limit?: number; tool?: \"query\" | \"search\"; }) => Promise<EvalCandidate[]>","listEvalCaptureFailures: (filter?: { since?: Date; }) => Promise<EvalCaptureFailure[]>",@@@ -1188,6 -1188,6 +1191,7 @@@"putDreamVerdict: (filePath: string, contentHash: string, verdict: DreamVerdictInput) => Promise<void>","putPage: (slug: string, page: PageInput, opts?: PageWriteOptions) => Promise<Page>","putRawData: (slug: string, source: string, data: object, opts?: { sourceId?: string; }) => Promise<void>",++ "readEmbeddingStateCounts: (opts: { mode: \"ops\" | \"full\"; sourceIds?: string[]; purgeWindowHours: number; }) => Promise<EmbeddingStateCounts>","readPageSnapshot: (slug: string, opts?: PageSnapshotOptions) => Promise<PageSnapshot | null>","readPageSnapshotsBatch: (refs: ReadonlyArray<{ slug: string; sourceId: string; }>, opts?: { maxBytes?: number; includeDeleted?: boolean; absentIsNull?: boolean; }) => Promise<PageSnapshotBatch>","readonly kind: \"postgres\"",@@@ -3325,7 -3325,7 +3329,7 @@@"deletePages: (slugs: string[], opts: { sourceId: string; }) => Promise<string[]>","disconnect: () => Promise<void>","discoverOntologyDimensions: (opts?: { sourceId?: string; sourceIds?: string[]; }) => Promise<OntologyDimensionStat[]>",-- "executeRaw: <T = Record<string, unknown>>(sql: string, params?: unknown[], opts?: { signal?: AbortSignal; timeoutMs?: number; }) => Promise<T[]>",++ "executeRaw: <T = Record<string, unknown>>(sql: string, params?: unknown[], opts?: { signal?: AbortSignal; timeoutMs?: number; deadlineAt?: number; }) => Promise<T[]>","executeRawDirect: <T = Record<string, unknown>>(sql: string, params?: unknown[], opts?: { signal?: AbortSignal; }) => Promise<T[]>","expireFact: (id: number, opts?: { supersededBy?: number; at?: Date; }) => Promise<boolean>","findAnomalies: (opts: AnomaliesOpts) => Promise<AnomalyResult[]>",@@@ -3387,6 -3387,6 +3391,7 @@@"listChunklessPagesWithContent: (opts?: { batchSize?: number; afterPageId?: number; sourceId?: string; }) => Promise<ChunklessPageRow[]>","listConfigKeys: (prefix: string) => Promise<string[]>","listCorpusSample: (opts: CorpusSampleOpts) => Promise<DomainBankRow[]>",++ "listEmbeddingStateRows: (opts: { sourceIds?: string[]; states: readonly EmbeddingState[]; limit: number; purgeWindowHours: number; }) => Promise<EmbeddingStateRow[]>","listEnrichCandidates: (opts: EnrichCandidatesOpts) => Promise<EnrichCandidate[]>","listEvalCandidates: (filter?: { since?: Date; limit?: number; tool?: \"query\" | \"search\"; }) => Promise<EvalCandidate[]>","listEvalCaptureFailures: (filter?: { since?: Date; }) => Promise<EvalCaptureFailure[]>",@@@ -3418,6 -3418,6 +3423,7 @@@"putDreamVerdict: (filePath: string, contentHash: string, verdict: DreamVerdictInput) => Promise<void>","putPage: (slug: string, page: PageInput, opts?: PageWriteOptions) => Promise<Page>","putRawData: (slug: string, source: string, data: object, opts?: { sourceId?: string; }) => Promise<void>",++ "readEmbeddingStateCounts: (opts: { mode: \"ops\" | \"full\"; sourceIds?: string[]; purgeWindowHours: number; }) => Promise<EmbeddingStateCounts>","readPageSnapshot: (slug: string, opts?: PageSnapshotOptions) => Promise<PageSnapshot | null>","readPageSnapshotsBatch: (refs: ReadonlyArray<{ slug: string; sourceId: string; }>, opts?: { maxBytes?: number; includeDeleted?: boolean; absentIsNull?: boolean; }) => Promise<PageSnapshotBatch>","readonly kind: \"postgres\" | \"pglite\"",@@@ -4501,7 -4501,7 +4507,7 @@@"kind": "interface","members": ["error?: string | undefined",-- "status: \"superseded\" | \"failed\" | \"embedded\""++ "status: \"embedded\" | \"superseded\" | \"failed\""],"name": "ImportEmbeddingResult"},@@@ -6129,7 -6130,7 +6136,7 @@@{"kind": "class","members": [- "canonical?: \"unknown\" | \"keyword_candidates_incomplete\" | \"projection_pending\" | \"timeout\" | \"rate_limited\" | \"embedding_disabled\" | \"writer_lock_unavailable\" | \"writer_pool_capacity\" | \"owner_unavailable\" | \"recovery_required\" | \"queue_capacity\" | \"revision_required\" | \"revision_conflict\" | \"idempotency_conflict\" | \"source_changed\" | \"write_pending\" | \"storage_error\" | \"cancelled\" | \"permission_denied\" | \"scope_denied\" | \"invalid_params\" | \"not_found\" | \"page_not_found\" | \"page_identity_changed\" | \"write_claim_lost\" | \"request_too_large\" | \"response_too_large\" | \"writer_registration_required\" | \"writer_identity_invalid\" | \"writer_not_initialized\" | \"writer_coordinator_required\" | \"fact_already_expired\" | \"source_writeback_required\" | \"unsupported_mutation_protocol\" | \"writer_upgrade_required\" | \"writer_not_quiesced\" | \"skill_bundle_required\" | \"take_row_collision\" | \"invalid_source_uri\" | \"writer_admin_locked\" | \"connector_account_changed\" | \"connector_intent_outdated\" | \"checkpoint_validation_timeout\" | \"invalid_connector_text\" | \"connector_holds_exhausted\" | \"connector_fence_below_timeline\" | \"core_budget_exceeded\" | \"core_mark_owner_only\" | \"core_remote_edit_refused\" | \"core_delete_owner_only\" | \"timeline_rows_would_be_removed\" | \"purged_content\" | \"preparation_stalled\" | \"fence_unrenderable\" | \"write_outcome_unknown\" | \"embedding_failed\" | \"bucket_not_found\" | \"database_error\" | \"unknown_transport\" | \"extraction_failed\" | \"fact_not_found\" | \"provenance_required\" | \"unavailable\" | \"budget_unsatisfiable\" | \"embedding_budget_below_worst_case\" | \"access_command_failed\" | \"access_denied_test_user\" | \"access_env_missing\" | \"acknowledgment_unavailable\" | \"admin_policy_enforced\" | \"ambient_capture_off\" | \"ambiguous_id\" | \"ambiguous_ref\" | \"ambiguous_skill\" | \"answer_not_yours\" | \"answer_pending\" | \"answer_unavailable\" | \"api_not_enabled\" | \"approval_required\" | \"autopilot_job_owned_by_other_brain\" | \"budget_below_recent_runtime\" | \"backup_dump_failed\" | \"benchmark_duplicate_task_id\" | \"benchmark_empty\" | \"benchmark_exists\" | \"benchmark_judge_llm_no_rubric\" | \"benchmark_judge_qrels_no_expected\" | \"benchmark_judge_rule_no_checks\" | \"benchmark_judge_unknown_kind\" | \"benchmark_malformed\" | \"benchmark_missing_judge\" | \"benchmark_missing_task\" | \"benchmark_missing_task_id\" | \"benchmark_not_found\" | \"benchmark_rule_check_bad_arg\" | \"benchmark_rule_check_malformed\" | \"benchmark_rule_check_unknown_op\" | \"bootstrap_empty\" | \"bootstrap_pending_review\" | \"bridge_ownership_conflict\" | \"cache_quota_exceeded\" | \"catalog_capacity_exceeded\" | \"catalog_unavailable\" | \"changed_since_preview\" | \"chronicle_skipped\" | \"no_pricing\" | \"checkpoint_missing\" | \"claim_already_used\" | \"client_json_unreadable\" | \"client_json_wrong_type\" | \"client_shape_invalid\" | \"code_callees_requires_symbol\" | \"code_callers_requires_symbol\" | \"code_def_requires_symbol\" | \"code_refs_requires_symbol\" | \"code_reused\" | \"colon_slug_windows_write_through\" | \"command_failed\" | \"commit_lock_busy\" | \"commit_paths_invalid\" | \"concurrent_write\" | \"config_error\" | \"confirmation_required\" | \"conflicting_source_scope\" | \"connection_lost\" | \"consent_required\" | \"consent_timeout\" | \"consumers_without_heartbeat\" | \"content_repair_needs_human\" | \"content_rejected\" | \"cost_cap_exceeded\" | \"cost_preview_requires_yes\" | \"cursor_incarnation_retired\" | \"cycle_failed\" | \"d_sel_too_small\" | \"delta_cursor_upgrade_required\" | \"demo_graph_failed\" | \"demo_import_failed\" | \"demo_verification_failed\" | \"derived_cap_exhausted\" | \"destination_not_ready\" | \"drain_stalled\" | \"managed_sync_not_moving\" | \"dream_breaker_tripped\" | \"dirty_tree\" | \"effect_not_failed\" | \"embedding_auth_failed\" | \"embedding_configuration\" | \"embedding_model_mismatch\" | \"embedding_plane_split\" | \"embedding_storage_unavailable\" | \"embedding_unavailable\" | \"embedding_unconfigured\" | \"embedding_width_mismatch\" | \"engine_graduated\" | \"eval_suite_unwired\" | \"export_limit\" | \"extractor_identity_mismatch\" | \"fact_withdrawn\" | \"facts_absorb_write_refused\" | \"facts_backstop_skipped\" | \"facts_drain_deferred\" | \"facts_drain_job_failed\" | \"facts_payload_expired\" | \"feedback_disabled\" | \"feedback_not_authorized\" | \"fetch_failed\" | \"fix_not_writable\" | \"file_removed_during_scan\" | \"file_too_large\" | \"follow_approval_required\" | \"forget_requires_owner\" | \"frontmatter_slug_conflict\" | \"full_resync_required\" | \"gate_failed\" | \"git_branch_unborn\" | \"git_checkout_required\" | \"git_detached_head\" | \"git_index_locked\" | \"git_index_stale\" | \"git_operation_in_progress\" | \"git_push_unavailable\" | \"git_target_unsafe\" | \"git_unavailable\" | \"graduation_drain_timeout\" | \"graduation_embedding_dimension_mismatch\" | \"graduation_foreign_host_binding\" | \"graduation_in_progress\" | \"graduation_interrupted\" | \"graduation_rollback_writes_lost\" | \"graduation_source_writer_held\" | \"graduation_split_brain\" | \"graduation_target_auth_failed\" | \"graduation_target_ddl_unreachable\" | \"graduation_target_not_empty\" | \"graduation_target_unsupported\" | \"graduation_unclassified_table\" | \"graduation_unsupported_platform\" | \"graduation_verify_failed\" | \"graph_incomplete\" | \"host_identity_mismatch\" | \"harness_hook_duplicates\" | \"harness_hook_unowned\" | \"head_blocked\" | \"held_failed\" | \"held_out_overlaps_benchmark\" | \"held_out_required_for_bundled\" | \"independent_principal_required\" | \"insufficient_scope\" | \"integrate_conflict\" | \"internal\" | \"internal_error\" | \"interrupted\" | \"invalid_acknowledgment\" | \"invalid_client\" | \"invalid_fence\" | \"unclosed_ambiguous_tail\" | \"tail_exposure_approval\" | \"sync_in_progress\" | \"invalid_frontmatter\" | \"invalid_grant_clock_skew\" | \"invalid_grant_revoked\" | \"invalid_grant_testing_expiry\" | \"invalid_rating\" | \"invalid_receipt\" | \"invalid_receipt_transition\" | \"invalid_request\" | \"invalid_source\" | \"invalid_source_pin\" | \"invalid_token\" | \"invalid_write_wait\" | \"legacy_job_selection_invalid\" | \"legacy_jobs_active\" | \"local_conflict\" | \"lock_busy\" | \"loops_extraction_skipped\" | \"maintenance_backpressure\" | \"maintenance_lock_busy\" | \"managed_failure_unsettled\" | \"merge_recommended\" | \"managed_sync_flag_refused\" | \"managed_pull_skipped\" | \"manual_only_skipped\" | \"membership_inactive\" | \"membership_not_found\" | \"method_not_allowed\" | \"migration_lease_lost\" | \"migration_declined\" | \"migration_failed\" | \"migrations_pending\" | \"migrations_running\" | \"missing_source_scope\" | \"missing_source_value\" | \"models_strict_violation\" | \"no_refresh_token\" | \"no_routing_eval\" | \"no_skill_md\" | \"no_worker\" | \"no_worker_surface\" | \"not_a_git_repo\" | \"not_connected\" | \"no_brain\" | \"overlapping_path\" | \"page_projection_conflict\" | \"parse_error\" | \"parser_regression\" | \"pasted_wrong_url\" | \"payload_too_large\" | \"pattern_claims_pending\" | \"pending_writes\" | \"persistence_restart_required\" | \"pool_inflight_over_budget\" | \"deep_health_probe_failed\" | \"serve_self_exit_suppressed\" | \"serve_unhealthy_exit\" | \"persistence_write_stall\" | \"push_unconfirmed\" | \"schema_lock_blocked\" | \"pg_connection_recovery_failed\" | \"pg_connection_stuck\" | \"pg_pool_stalled\" | \"pg_statement_build_failed\" | \"pglite_busy\" | \"pglite_vector_index_too_large\" | \"plan_output_failed\" | \"plan_stale\" | \"port_in_use\" | \"preview_changed\" | \"profile_incompatible\" | \"projection_owner_resident\" | \"knock_on_exhausted\" | \"publication_pending\" | \"purge_blocked_pending_recovery\" | \"purge_lookup_timeout\" | \"question_not_found\" | \"question_owner_only\" | \"receipt_conflict\" | \"receipt_fence_changed\" | \"receipt_fence_required\" | \"receipt_identity_mismatch\" | \"pat_file_unreadable\" | \"redirect_uri_mismatch\" | \"ref_not_in_answer\" | \"refresh_dirty\" | \"refresh_diverged\" | \"refresh_drain_timeout\" | \"refresh_no_upstream\" | \"refresh_not_managed\" | \"refresh_not_owner\" | \"refresh_source_changed\" | \"relay_disabled\" | \"relay_session_expired\" | \"relay_unreachable\" | \"rename_held\" | \"request_already_submitted\" | \"requirements_changed\" | \"requires_local_engine\" | \"resume_spec_mismatch\" | \"revision_unavailable\" | \"scope_missing\" | \"search_cursor_requires_keyword\" | \"search_mode_local_only\" | \"search_offset_over_cap\" | \"serve_build_drift\" | \"serve_port_in_use\" | \"serve_status_only\" | \"setup_harness_unsupported\" | \"setup_hosted_connection\" | \"setup_owner_conflict\" | \"shared_skills_unavailable\" | \"shared_skills_unsupported\" | \"skill_asset_not_found\" | \"skill_candidate_invalid\" | \"skill_not_found\" | \"skill_retention_capacity\" | \"skill_unavailable\" | \"slug_page_mismatch\" | \"source_binding_required\" | \"source_id_taken\" | \"source_mismatch\" | \"source_not_ready\" | \"source_profile_no_backfill\" | \"source_referenced\" | \"source_root_conflict\" | \"split_bad_ratio\" | \"split_unparseable\" | \"stale_unavailable\" | \"state_mismatch\" | \"sync_not_applicable\" | \"sync_cursor_replaced\" | \"sync_parser_regression\" | \"target_escape\" | \"timeline_comment_markup\" | \"topology_change_required\" | \"transcript_secret_exposure\" | \"triage_unreliable_backoff\" | \"trust_raise_refused\" | \"two_consumers_on_host\" | \"trusted_local_only\" | \"unexpected_file_bytes\" | \"unexpected_staging_bytes\" | \"unknown_command\" | \"unknown_flag\" | \"unknown_method\" | \"unknown_source\" | \"unknown_tool\" | \"unpriced_model\" | \"unmanaged_path\" | \"unsupported_export_data\" | \"upstream\" | \"verification_failed\" | \"withdrawal_capacity\" | \"withdrawal_provenance\" | \"write_gate_rejected\" | \"write_held\" | \"worktree_dirty\" | \"writer_admin_intent_required\" | \"writer_admin_state_changed\" | \"writer_busy\" | \"writer_identity_publish_failed\" | \"writer_manifest_mismatch\" | \"writer_manifest_rescope_required\" | \"writer_manifest_unsafe\" | \"writer_regrant_required\" | \"writer_transfer_conflict\" | \"writer_transfer_required\" | \"wrong_account_consented\" | \"schema_pack_too_large\" | \"schema_pack_emit_mismatch\" | undefined",- "canonical?: \"unknown\" | \"keyword_candidates_incomplete\" | \"projection_pending\" | \"timeout\" | \"rate_limited\" | \"embedding_disabled\" | \"writer_lock_unavailable\" | \"writer_pool_capacity\" | \"owner_unavailable\" | \"recovery_required\" | \"queue_capacity\" | \"write_quota_exhausted\" | \"write_quota_insufficient\" | \"write_capacity_backpressure\" | \"revision_required\" | \"revision_conflict\" | \"idempotency_conflict\" | \"source_changed\" | \"write_pending\" | \"storage_error\" | \"cancelled\" | \"permission_denied\" | \"scope_denied\" | \"invalid_params\" | \"not_found\" | \"page_not_found\" | \"page_identity_changed\" | \"write_claim_lost\" | \"request_too_large\" | \"response_too_large\" | \"writer_registration_required\" | \"writer_identity_invalid\" | \"writer_not_initialized\" | \"writer_coordinator_required\" | \"fact_already_expired\" | \"source_writeback_required\" | \"unsupported_mutation_protocol\" | \"writer_upgrade_required\" | \"writer_not_quiesced\" | \"skill_bundle_required\" | \"take_row_collision\" | \"invalid_source_uri\" | \"writer_admin_locked\" | \"connector_account_changed\" | \"connector_intent_outdated\" | \"checkpoint_validation_timeout\" | \"invalid_connector_text\" | \"connector_holds_exhausted\" | \"connector_fence_below_timeline\" | \"core_budget_exceeded\" | \"core_mark_owner_only\" | \"core_remote_edit_refused\" | \"core_delete_owner_only\" | \"timeline_rows_would_be_removed\" | \"purged_content\" | \"preparation_stalled\" | \"fence_unrenderable\" | \"write_outcome_unknown\" | \"embedding_failed\" | \"bucket_not_found\" | \"database_error\" | \"unknown_transport\" | \"extraction_failed\" | \"fact_not_found\" | \"provenance_required\" | \"unavailable\" | \"budget_unsatisfiable\" | \"embedding_budget_below_worst_case\" | \"access_command_failed\" | \"access_denied_test_user\" | \"access_env_missing\" | \"acknowledgment_unavailable\" | \"admin_policy_enforced\" | \"ambient_capture_off\" | \"ambiguous_id\" | \"ambiguous_ref\" | \"ambiguous_skill\" | \"answer_not_yours\" | \"answer_pending\" | \"answer_unavailable\" | \"api_not_enabled\" | \"approval_required\" | \"autopilot_job_owned_by_other_brain\" | \"budget_below_recent_runtime\" | \"backup_dump_failed\" | \"benchmark_duplicate_task_id\" | \"benchmark_empty\" | \"benchmark_exists\" | \"benchmark_judge_llm_no_rubric\" | \"benchmark_judge_qrels_no_expected\" | \"benchmark_judge_rule_no_checks\" | \"benchmark_judge_unknown_kind\" | \"benchmark_malformed\" | \"benchmark_missing_judge\" | \"benchmark_missing_task\" | \"benchmark_missing_task_id\" | \"benchmark_not_found\" | \"benchmark_rule_check_bad_arg\" | \"benchmark_rule_check_malformed\" | \"benchmark_rule_check_unknown_op\" | \"bootstrap_empty\" | \"bootstrap_pending_review\" | \"bridge_ownership_conflict\" | \"cache_quota_exceeded\" | \"capacity_paused\" | \"catalog_capacity_exceeded\" | \"catalog_unavailable\" | \"changed_since_preview\" | \"chronicle_skipped\" | \"no_pricing\" | \"checkpoint_missing\" | \"claim_already_used\" | \"client_json_unreadable\" | \"client_json_wrong_type\" | \"client_shape_invalid\" | \"code_callees_requires_symbol\" | \"code_callers_requires_symbol\" | \"code_def_requires_symbol\" | \"code_refs_requires_symbol\" | \"code_reused\" | \"colon_slug_windows_write_through\" | \"command_failed\" | \"commit_lock_busy\" | \"commit_paths_invalid\" | \"concurrent_write\" | \"config_error\" | \"confirmation_required\" | \"conflicting_source_scope\" | \"connection_lost\" | \"consent_required\" | \"consent_timeout\" | \"consumers_without_heartbeat\" | \"content_repair_needs_human\" | \"content_rejected\" | \"cost_cap_exceeded\" | \"cost_preview_requires_yes\" | \"cursor_incarnation_retired\" | \"cycle_failed\" | \"d_sel_too_small\" | \"delta_cursor_upgrade_required\" | \"demo_graph_failed\" | \"demo_import_failed\" | \"demo_verification_failed\" | \"derived_cap_exhausted\" | \"destination_not_ready\" | \"drain_stalled\" | \"managed_sync_not_moving\" | \"dream_breaker_tripped\" | \"dirty_tree\" | \"effect_not_failed\" | \"embedding_auth_failed\" | \"embedding_configuration\" | \"embedding_model_mismatch\" | \"embedding_plane_split\" | \"embedding_storage_unavailable\" | \"embedding_unavailable\" | \"embedding_unconfigured\" | \"embedding_width_mismatch\" | \"engine_graduated\" | \"eval_suite_unwired\" | \"export_limit\" | \"extractor_identity_mismatch\" | \"fact_withdrawn\" | \"facts_absorb_write_refused\" | \"facts_backstop_skipped\" | \"facts_drain_deferred\" | \"facts_drain_job_failed\" | \"facts_payload_expired\" | \"feedback_disabled\" | \"feedback_not_authorized\" | \"fetch_failed\" | \"fix_not_writable\" | \"file_removed_during_scan\" | \"file_too_large\" | \"follow_approval_required\" | \"forget_requires_owner\" | \"frontmatter_slug_conflict\" | \"full_resync_required\" | \"gate_failed\" | \"git_branch_unborn\" | \"git_checkout_required\" | \"git_detached_head\" | \"git_index_locked\" | \"git_index_stale\" | \"git_operation_in_progress\" | \"git_push_unavailable\" | \"git_target_unsafe\" | \"git_unavailable\" | \"graduation_drain_timeout\" | \"graduation_embedding_dimension_mismatch\" | \"graduation_foreign_host_binding\" | \"graduation_in_progress\" | \"graduation_interrupted\" | \"graduation_rollback_writes_lost\" | \"graduation_source_writer_held\" | \"graduation_split_brain\" | \"graduation_target_auth_failed\" | \"graduation_target_ddl_unreachable\" | \"graduation_target_not_empty\" | \"graduation_target_unsupported\" | \"graduation_unclassified_table\" | \"graduation_unsupported_platform\" | \"graduation_verify_failed\" | \"graph_incomplete\" | \"host_identity_mismatch\" | \"harness_hook_duplicates\" | \"harness_hook_unowned\" | \"head_blocked\" | \"held_failed\" | \"held_out_overlaps_benchmark\" | \"held_out_required_for_bundled\" | \"independent_principal_required\" | \"insufficient_scope\" | \"integrate_conflict\" | \"internal\" | \"internal_error\" | \"interrupted\" | \"invalid_acknowledgment\" | \"invalid_client\" | \"invalid_fence\" | \"unclosed_ambiguous_tail\" | \"tail_exposure_approval\" | \"sync_in_progress\" | \"invalid_frontmatter\" | \"invalid_grant_clock_skew\" | \"invalid_grant_revoked\" | \"invalid_grant_testing_expiry\" | \"invalid_rating\" | \"invalid_receipt\" | \"invalid_receipt_transition\" | \"invalid_request\" | \"invalid_source\" | \"invalid_source_pin\" | \"invalid_token\" | \"invalid_write_wait\" | \"legacy_job_selection_invalid\" | \"legacy_jobs_active\" | \"local_conflict\" | \"lock_busy\" | \"loops_extraction_skipped\" | \"maintenance_backpressure\" | \"maintenance_lock_busy\" | \"managed_failure_unsettled\" | \"merge_recommended\" | \"managed_pull_skipped\" | \"manual_only_skipped\" | \"membership_inactive\" | \"membership_not_found\" | \"method_not_allowed\" | \"migration_lease_lost\" | \"migration_declined\" | \"migration_failed\" | \"migrations_pending\" | \"migrations_running\" | \"missing_source_scope\" | \"missing_source_value\" | \"models_strict_violation\" | \"no_refresh_token\" | \"no_routing_eval\" | \"no_skill_md\" | \"no_worker\" | \"no_worker_surface\" | \"not_a_git_repo\" | \"not_connected\" | \"no_brain\" | \"overlapping_path\" | \"page_projection_conflict\" | \"parse_error\" | \"parser_regression\" | \"pasted_wrong_url\" | \"payload_too_large\" | \"pattern_claims_pending\" | \"pending_writes\" | \"persistence_restart_required\" | \"pool_inflight_over_budget\" | \"deep_health_probe_failed\" | \"serve_self_exit_suppressed\" | \"serve_unhealthy_exit\" | \"persistence_write_stall\" | \"push_unconfirmed\" | \"schema_lock_blocked\" | \"pg_connection_recovery_failed\" | \"pg_connection_stuck\" | \"pg_pool_stalled\" | \"pg_statement_build_failed\" | \"pglite_busy\" | \"pglite_vector_index_too_large\" | \"plan_output_failed\" | \"plan_stale\" | \"port_in_use\" | \"preview_changed\" | \"profile_incompatible\" | \"projection_owner_resident\" | \"knock_on_exhausted\" | \"publication_pending\" | \"purge_blocked_pending_recovery\" | \"purge_lookup_timeout\" | \"question_not_found\" | \"question_owner_only\" | \"receipt_conflict\" | \"receipt_fence_changed\" | \"receipt_fence_required\" | \"receipt_identity_mismatch\" | \"pat_file_unreadable\" | \"redirect_uri_mismatch\" | \"ref_not_in_answer\" | \"refresh_dirty\" | \"refresh_diverged\" | \"refresh_drain_timeout\" | \"refresh_no_upstream\" | \"refresh_not_managed\" | \"refresh_not_owner\" | \"refresh_source_changed\" | \"relay_disabled\" | \"relay_session_expired\" | \"relay_unreachable\" | \"rename_held\" | \"request_already_submitted\" | \"requirements_changed\" | \"requires_local_engine\" | \"resume_spec_mismatch\" | \"revision_unavailable\" | \"scope_missing\" | \"search_cursor_requires_keyword\" | \"search_mode_local_only\" | \"search_offset_over_cap\" | \"serve_port_in_use\" | \"serve_status_only\" | \"setup_harness_unsupported\" | \"setup_hosted_connection\" | \"setup_owner_conflict\" | \"shared_skills_unavailable\" | \"shared_skills_unsupported\" | \"skill_asset_not_found\" | \"skill_candidate_invalid\" | \"skill_not_found\" | \"skill_retention_capacity\" | \"skill_unavailable\" | \"source_binding_required\" | \"source_id_taken\" | \"source_mismatch\" | \"source_not_ready\" | \"source_profile_no_backfill\" | \"source_referenced\" | \"source_root_conflict\" | \"split_bad_ratio\" | \"split_unparseable\" | \"stale_unavailable\" | \"state_mismatch\" | \"sync_not_applicable\" | \"sync_cursor_replaced\" | \"sync_parser_regression\" | \"target_escape\" | \"timeline_comment_markup\" | \"topology_change_required\" | \"transcript_secret_exposure\" | \"triage_unreliable_backoff\" | \"trust_raise_refused\" | \"two_consumers_on_host\" | \"trusted_local_only\" | \"unexpected_file_bytes\" | \"unexpected_staging_bytes\" | \"unknown_command\" | \"unknown_flag\" | \"unknown_method\" | \"unknown_source\" | \"unknown_tool\" | \"unpriced_model\" | \"unmanaged_path\" | \"unsupported_export_data\" | \"upstream\" | \"verification_failed\" | \"withdrawal_capacity\" | \"withdrawal_provenance\" | \"write_capacity_low\" | \"write_gate_rejected\" | \"write_held\" | \"worktree_dirty\" | \"writer_admin_intent_required\" | \"writer_admin_state_changed\" | \"writer_busy\" | \"writer_identity_publish_failed\" | \"writer_manifest_mismatch\" | \"writer_manifest_rescope_required\" | \"writer_manifest_unsafe\" | \"writer_regrant_required\" | \"writer_transfer_conflict\" | \"writer_transfer_required\" | \"wrong_account_consented\" | \"schema_pack_too_large\" | \"schema_pack_emit_mismatch\" | undefined",++ "canonical?: \"unknown\" | \"keyword_candidates_incomplete\" | \"projection_pending\" | \"timeout\" | \"rate_limited\" | \"embedding_disabled\" | \"writer_lock_unavailable\" | \"writer_pool_capacity\" | \"owner_unavailable\" | \"recovery_required\" | \"queue_capacity\" | \"write_quota_exhausted\" | \"write_quota_insufficient\" | \"write_capacity_backpressure\" | \"revision_required\" | \"revision_conflict\" | \"idempotency_conflict\" | \"source_changed\" | \"write_pending\" | \"storage_error\" | \"cancelled\" | \"permission_denied\" | \"scope_denied\" | \"invalid_params\" | \"not_found\" | \"page_not_found\" | \"page_identity_changed\" | \"write_claim_lost\" | \"request_too_large\" | \"response_too_large\" | \"writer_registration_required\" | \"writer_identity_invalid\" | \"writer_not_initialized\" | \"writer_coordinator_required\" | \"fact_already_expired\" | \"source_writeback_required\" | \"unsupported_mutation_protocol\" | \"writer_upgrade_required\" | \"writer_not_quiesced\" | \"skill_bundle_required\" | \"take_row_collision\" | \"invalid_source_uri\" | \"writer_admin_locked\" | \"connector_account_changed\" | \"connector_intent_outdated\" | \"checkpoint_validation_timeout\" | \"invalid_connector_text\" | \"connector_holds_exhausted\" | \"connector_fence_below_timeline\" | \"core_budget_exceeded\" | \"core_mark_owner_only\" | \"core_remote_edit_refused\" | \"core_delete_owner_only\" | \"timeline_rows_would_be_removed\" | \"purged_content\" | \"preparation_stalled\" | \"fence_unrenderable\" | \"write_outcome_unknown\" | \"embedding_failed\" | \"bucket_not_found\" | \"database_error\" | \"unknown_transport\" | \"extraction_failed\" | \"fact_not_found\" | \"provenance_required\" | \"unavailable\" | \"budget_unsatisfiable\" | \"embedding_budget_below_worst_case\" | \"access_command_failed\" | \"access_denied_test_user\" | \"access_env_missing\" | \"acknowledgment_unavailable\" | \"admin_policy_enforced\" | \"ambient_capture_off\" | \"ambiguous_id\" | \"ambiguous_ref\" | \"ambiguous_skill\" | \"answer_not_yours\" | \"answer_pending\" | \"answer_unavailable\" | \"api_not_enabled\" | \"approval_required\" | \"autopilot_job_owned_by_other_brain\" | \"budget_below_recent_runtime\" | \"backup_dump_failed\" | \"benchmark_duplicate_task_id\" | \"benchmark_empty\" | \"benchmark_exists\" | \"benchmark_judge_llm_no_rubric\" | \"benchmark_judge_qrels_no_expected\" | \"benchmark_judge_rule_no_checks\" | \"benchmark_judge_unknown_kind\" | \"benchmark_malformed\" | \"benchmark_missing_judge\" | \"benchmark_missing_task\" | \"benchmark_missing_task_id\" | \"benchmark_not_found\" | \"benchmark_rule_check_bad_arg\" | \"benchmark_rule_check_malformed\" | \"benchmark_rule_check_unknown_op\" | \"bootstrap_empty\" | \"bootstrap_pending_review\" | \"bridge_ownership_conflict\" | \"cache_quota_exceeded\" | \"capacity_paused\" | \"catalog_capacity_exceeded\" | \"catalog_unavailable\" | \"changed_since_preview\" | \"chronicle_skipped\" | \"no_pricing\" | \"checkpoint_missing\" | \"claim_already_used\" | \"client_json_unreadable\" | \"client_json_wrong_type\" | \"client_shape_invalid\" | \"code_callees_requires_symbol\" | \"code_callers_requires_symbol\" | \"code_def_requires_symbol\" | \"code_refs_requires_symbol\" | \"code_reused\" | \"colon_slug_windows_write_through\" | \"command_failed\" | \"commit_lock_busy\" | \"commit_paths_invalid\" | \"concurrent_write\" | \"config_error\" | \"confirmation_required\" | \"conflicting_source_scope\" | \"connection_lost\" | \"chunkless_pages_healable\" | \"consent_required\" | \"consent_timeout\" | \"consumers_without_heartbeat\" | \"content_repair_needs_human\" | \"content_rejected\" | \"cost_cap_exceeded\" | \"cost_preview_requires_yes\" | \"cursor_incarnation_retired\" | \"cycle_failed\" | \"d_sel_too_small\" | \"delta_cursor_upgrade_required\" | \"deleted_page_chunks_overdue\" | \"demo_graph_failed\" | \"demo_import_failed\" | \"demo_verification_failed\" | \"derived_cap_exhausted\" | \"destination_not_ready\" | \"drain_stalled\" | \"managed_sync_not_moving\" | \"dream_breaker_tripped\" | \"dirty_tree\" | \"doctor_tier_unavailable\" | \"effect_not_failed\" | \"embedding_auth_failed\" | \"embedding_configuration\" | \"embedding_model_mismatch\" | \"embedding_plane_split\" | \"embedding_state_unknown\" | \"embedding_storage_unavailable\" | \"embedding_unavailable\" | \"embedding_unconfigured\" | \"embedding_width_mismatch\" | \"engine_graduated\" | \"eval_suite_unwired\" | \"export_limit\" | \"extractor_identity_mismatch\" | \"fact_withdrawn\" | \"facts_absorb_write_refused\" | \"facts_backstop_skipped\" | \"facts_drain_deferred\" | \"facts_drain_job_failed\" | \"facts_payload_expired\" | \"feedback_disabled\" | \"feedback_not_authorized\" | \"fetch_failed\" | \"fix_not_writable\" | \"file_removed_during_scan\" | \"file_too_large\" | \"follow_approval_required\" | \"forget_requires_owner\" | \"frontmatter_slug_conflict\" | \"full_resync_required\" | \"gate_failed\" | \"ghost_mass_delete_refused\" | \"ghost_storage_unknown\" | \"git_branch_unborn\" | \"git_checkout_required\" | \"git_detached_head\" | \"git_index_locked\" | \"git_index_stale\" | \"git_operation_in_progress\" | \"git_push_unavailable\" | \"git_target_unsafe\" | \"git_unavailable\" | \"graduation_drain_timeout\" | \"graduation_embedding_dimension_mismatch\" | \"graduation_foreign_host_binding\" | \"graduation_in_progress\" | \"graduation_interrupted\" | \"graduation_rollback_writes_lost\" | \"graduation_source_writer_held\" | \"graduation_split_brain\" | \"graduation_target_auth_failed\" | \"graduation_target_ddl_unreachable\" | \"graduation_target_not_empty\" | \"graduation_target_unsupported\" | \"graduation_unclassified_table\" | \"graduation_unsupported_platform\" | \"graduation_verify_failed\" | \"graph_incomplete\" | \"host_identity_mismatch\" | \"harness_hook_duplicates\" | \"harness_hook_unowned\" | \"head_blocked\" | \"held_failed\" | \"held_out_overlaps_benchmark\" | \"held_out_required_for_bundled\" | \"independent_principal_required\" | \"insufficient_scope\" | \"integrate_conflict\" | \"internal\" | \"internal_error\" | \"interrupted\" | \"invalid_acknowledgment\" | \"invalid_client\" | \"invalid_fence\" | \"unclosed_ambiguous_tail\" | \"tail_exposure_approval\" | \"sync_in_progress\" | \"invalid_frontmatter\" | \"invalid_grant_clock_skew\" | \"invalid_grant_revoked\" | \"invalid_grant_testing_expiry\" | \"invalid_rating\" | \"invalid_receipt\" | \"invalid_receipt_transition\" | \"invalid_request\" | \"invalid_source\" | \"invalid_source_pin\" | \"invalid_token\" | \"invalid_write_wait\" | \"legacy_job_selection_invalid\" | \"legacy_jobs_active\" | \"local_conflict\" | \"lock_busy\" | \"loops_extraction_skipped\" | \"maintenance_backpressure\" | \"maintenance_lock_busy\" | \"managed_failure_unsettled\" | \"merge_recommended\" | \"managed_sync_flag_refused\" | \"managed_pull_skipped\" | \"manual_only_skipped\" | \"membership_inactive\" | \"membership_not_found\" | \"method_not_allowed\" | \"migration_lease_lost\" | \"migration_declined\" | \"migration_failed\" | \"migrations_pending\" | \"migrations_running\" | \"missing_source_scope\" | \"missing_source_value\" | \"models_strict_violation\" | \"no_refresh_token\" | \"no_routing_eval\" | \"no_skill_md\" | \"no_worker\" | \"no_worker_surface\" | \"not_a_git_repo\" | \"not_owner_host\" | \"not_connected\" | \"no_brain\" | \"overlapping_path\" | \"page_projection_conflict\" | \"parse_error\" | \"parser_regression\" | \"pasted_wrong_url\" | \"payload_too_large\" | \"pattern_claims_pending\" | \"pending_writes\" | \"persistence_restart_required\" | \"pool_inflight_over_budget\" | \"deep_health_probe_failed\" | \"serve_self_exit_suppressed\" | \"serve_unhealthy_exit\" | \"persistence_write_stall\" | \"push_unconfirmed\" | \"schema_lock_blocked\" | \"pg_connection_recovery_failed\" | \"pg_connection_stuck\" | \"pg_pool_stalled\" | \"pg_statement_build_failed\" | \"pglite_busy\" | \"pglite_vector_index_too_large\" | \"plan_output_failed\" | \"plan_stale\" | \"port_in_use\" | \"preview_changed\" | \"profile_incompatible\" | \"projection_owner_resident\" | \"knock_on_exhausted\" | \"publication_pending\" | \"purge_blocked_pending_recovery\" | \"purge_lookup_timeout\" | \"question_not_found\" | \"question_owner_only\" | \"receipt_conflict\" | \"receipt_fence_changed\" | \"receipt_fence_required\" | \"receipt_identity_mismatch\" | \"pat_file_unreadable\" | \"redirect_uri_mismatch\" | \"ref_not_in_answer\" | \"refresh_dirty\" | \"refresh_diverged\" | \"refresh_drain_timeout\" | \"refresh_no_upstream\" | \"refresh_not_managed\" | \"refresh_not_owner\" | \"refresh_source_changed\" | \"relay_disabled\" | \"relay_session_expired\" | \"relay_unreachable\" | \"rename_held\" | \"request_already_submitted\" | \"requirements_changed\" | \"requires_local_engine\" | \"resume_spec_mismatch\" | \"revision_unavailable\" | \"scope_missing\" | \"search_cursor_requires_keyword\" | \"search_mode_local_only\" | \"search_offset_over_cap\" | \"serve_build_drift\" | \"serve_port_in_use\" | \"serve_status_only\" | \"setup_harness_unsupported\" | \"setup_hosted_connection\" | \"setup_owner_conflict\" | \"shared_skills_unavailable\" | \"shared_skills_unsupported\" | \"skill_asset_not_found\" | \"skill_candidate_invalid\" | \"skill_not_found\" | \"skill_retention_capacity\" | \"skill_unavailable\" | \"slug_page_mismatch\" | \"source_binding_required\" | \"source_id_taken\" | \"source_mismatch\" | \"source_not_ready\" | \"source_profile_no_backfill\" | \"source_referenced\" | \"source_root_conflict\" | \"split_bad_ratio\" | \"split_unparseable\" | \"stale_unavailable\" | \"state_mismatch\" | \"sync_not_applicable\" | \"sync_cursor_replaced\" | \"sync_parser_regression\" | \"target_escape\" | \"timeline_comment_markup\" | \"topology_change_required\" | \"transcript_secret_exposure\" | \"triage_unreliable_backoff\" | \"trust_raise_refused\" | \"two_consumers_on_host\" | \"trusted_local_only\" | \"unexpected_file_bytes\" | \"unexpected_staging_bytes\" | \"unknown_command\" | \"unknown_flag\" | \"unknown_method\" | \"unknown_source\" | \"unknown_tool\" | \"unpriced_model\" | \"unmanaged_path\" | \"unsupported_export_data\" | \"upstream\" | \"verification_failed\" | \"withdrawal_capacity\" | \"withdrawal_provenance\" | \"write_capacity_low\" | \"write_gate_rejected\" | \"write_held\" | \"worktree_dirty\" | \"writer_admin_intent_required\" | \"writer_admin_state_changed\" | \"writer_busy\" | \"writer_identity_publish_failed\" | \"writer_manifest_mismatch\" | \"writer_manifest_rescope_required\" | \"writer_manifest_unsafe\" | \"writer_regrant_required\" | \"writer_transfer_conflict\" | \"writer_transfer_required\" | \"wrong_account_consented\" | \"schema_pack_too_large\" | \"schema_pack_emit_mismatch\" | undefined","canonicalCode: string","cause?: unknown","code: ErrorCode",@@@ -6426,6 -6427,6 +6433,7 @@@"listChunklessPagesWithContent: (opts?: { batchSize?: number; afterPageId?: number; sourceId?: string; }) => Promise<ChunklessPageRow[]>","listConfigKeys: (prefix: string) => Promise<string[]>","listCorpusSample: (opts: CorpusSampleOpts) => Promise<DomainBankRow[]>",++ "listEmbeddingStateRows: (opts: { sourceIds?: string[]; states: readonly EmbeddingState[]; limit: number; purgeWindowHours: number; }) => Promise<EmbeddingStateRow[]>","listEnrichCandidates: (opts: EnrichCandidatesOpts) => Promise<EnrichCandidate[]>","listEvalCandidates: (filter?: { since?: Date; limit?: number; tool?: \"query\" | \"search\"; }) => Promise<EvalCandidate[]>","listEvalCaptureFailures: (filter?: { since?: Date; }) => Promise<EvalCaptureFailure[]>",@@@ -6489,6 -6490,6 +6497,7 @@@"putDreamVerdict: (filePath: string, contentHash: string, verdict: DreamVerdictInput) => Promise<void>","putPage: (slug: string, page: PageInput, opts?: PageWriteOptions) => Promise<Page>","putRawData: (slug: string, source: string, data: object, opts?: { sourceId?: string; }) => Promise<void>",++ "readEmbeddingStateCounts: (opts: { mode: \"ops\" | \"full\"; sourceIds?: string[]; purgeWindowHours: number; }) => Promise<EmbeddingStateCounts>","readPageSnapshot: (slug: string, opts?: PageSnapshotOptions) => Promise<PageSnapshot | null>","readPageSnapshotsBatch: (refs: ReadonlyArray<{ slug: string; sourceId: string; }>, opts?: { maxBytes?: number; includeDeleted?: boolean; absentIsNull?: boolean; }) => Promise<PageSnapshotBatch>","readonly kind: \"pglite\"",@@@ -8598,7 -8599,7 +8607,7 @@@"entitySlug: string","source: string","sourceId?: string | undefined",-- "status?: \"active\" | \"quarantined\" | undefined",++ "status?: \"quarantined\" | \"active\" | undefined","validFrom?: string | null | undefined","validTo?: string | null | undefined","value: string",diff --cc test/repair-explicit-only.test.tsindex b008a0c8e8,65999cbf91..f073f8b7cf--- a/test/repair-explicit-only.test.ts+++ b/test/repair-explicit-only.test.ts@@@ -24,7 -24,7 +24,7 @@@ import { REPAIR_HELP, parseRepairArgs,import { _resetCliExitVerdictForTests, currentExitCode } from '../src/core/cli-force-exit.ts';import { withEnv } from './helpers/with-env.ts';- const EXPLICIT: RepairKind[] = ['google-file-modes', 'stale-atoms', 'extractor-facts', 'conversation-labels', 'captured-facts', 'loop-facts', 'ontology-facts', 'orphan-children', 'failed-writes', 'frontmatter', 'timeline-comments', 'managed-sync-orphans', 'frontmatter-keys', 'file-drift', 'stuck-recovery', 'ghost-pages'];-const EXPLICIT: RepairKind[] = ['google-file-modes', 'stale-atoms', 'extractor-facts', 'conversation-labels', 'captured-facts', 'loop-facts', 'ontology-facts', 'orphan-children', 'failed-writes', 'frontmatter', 'timeline-comments', 'managed-sync-orphans', 'frontmatter-keys', 'file-drift', 'stuck-recovery', 'receipt-compaction'];++const EXPLICIT: RepairKind[] = ['google-file-modes', 'stale-atoms', 'extractor-facts', 'conversation-labels', 'captured-facts', 'loop-facts', 'ontology-facts', 'orphan-children', 'failed-writes', 'frontmatter', 'timeline-comments', 'managed-sync-orphans', 'frontmatter-keys', 'file-drift', 'stuck-recovery', 'ghost-pages', 'receipt-compaction'];let engine: PGLiteEngine;const home = mkdtempSync(join(tmpdir(), 'gbrain-repair-explicit-'));