Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

Merge lane B5 (ghost pages, repair ghost-pages) into capy/gbra93-bc

garrytan01497b9521b9
diff --cc CHANGELOG.md
index 730062e0e4,b54a14ea38..9e3e35773d
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@@ -20,9 -20,6 +20,10 @@@ identifiers and attribution are availab
- 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.
+- 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
@@@ -52,13 -46,6 +53,15 @@@
- **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.
+- **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 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`).
++- **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.
## [0.60.230.0] - 2026-10-14
diff --cc docs/architecture/key-files/commands-4.md
index 005ab28ed7,9e71593705..ea6c868c47
--- a/docs/architecture/key-files/commands-4.md
+++ b/docs/architecture/key-files/commands-4.md
@@@ -36,8 -36,7 +36,8 @@@ Current behavior and load-bearing invar
- `src/commands/orphans.ts` — `gbrain orphans` and MCP `find_orphans` share islanded (no live inbound or outbound links) and legacy inbound-only modes. Read policy scopes candidates and excludes private candidates, endpoints and independent origin pages before counting. Cross-source public links still establish reachability by the documented orphan definition. Reporting exclusions (`shouldExcludeFromOrphanReporting`) stay centralized; the scoped live-page denominator excludes the same private/reporting rows. `--source` remains explicit; no new remote privacy parameter. Connector renders (an `email`/`meeting` page whose source `config.kind` is a connector kind) are islanded by construction, so they leave both totals and are reported as `connector_renders_excluded` (`--include-pseudo` keeps them); doctor `orphan_ratio` carries that count in `details` and prints `gbrain extract links --by-mention --source db` (plus `--source-id` when scoped). Pinned by `test/orphan-ratio-connector-renders.test.ts`.
- - `src/commands/pages.ts` — `gbrain pages purge-deleted [--older-than HOURS|Nh|Nd] [--dry-run] [--json] [--yes]` operator escape hatch. Mirror of `gbrain sources purge` for the page-level lifecycle. Hard-deletes pages whose `deleted_at` is older than the cutoff in every source (per-source purge is not supported); cascades to content_chunks/page_links/chunk_relations. `parsePurgeArgs` is strict (the `pages purge-deleted` row of `src/cli/strict-args.ts`): `--older-than N` and `--older-than=N` both work, and any other token throws `invalid_params` before the engine is touched. The real purge first previews the count and, when anything would be purged, goes through `consentGate` (destructive): a TTY prompt, `--yes`, or exit 3 with the consent payload whose fix is the exact `--yes` argv and whose preview is `--dry-run --json`. The autopilot purge phase calls `purgeDeletedPagesCoordinated` directly and never asks. Exports `SUBCOMMANDS` and `printUsage` for the help route. Pinned by `test/pages-purge-deleted-args.test.ts` and the `pages purge-deleted` consent-table row. Its help points soft-delete and restore at `gbrain delete|restore <slug> --force` (page writes are revisioned).
+ - `src/commands/pages.ts` — `gbrain pages purge-deleted [--older-than HOURS|Nh|Nd] [--dry-run] [--json] [--yes]` operator escape hatch. Mirror of `gbrain sources purge` for the page-level lifecycle. Hard-deletes pages whose `deleted_at` is older than the cutoff in every source (per-source purge is not supported); cascades to content_chunks/page_links/chunk_relations. `parsePurgeArgs` is strict (the `pages purge-deleted` row of `src/cli/strict-args.ts`): `--older-than N` and `--older-than=N` both work, and any other token throws `invalid_params` before the engine is touched. The real purge first previews the count and, when anything would be purged, goes through `consentGate` (destructive): a TTY prompt, `--yes`, or exit 3 with the consent payload whose fix is the exact `--yes` argv and whose preview is `--dry-run --json`. The autopilot purge phase calls `purgeDeletedPagesCoordinated` directly and never asks. `pages ghosts [--source <id>] [--json]` (#6696 B5, `pages-ghosts.ts`) lists ghost pages read-only through `scanGhostSource`. Exports `SUBCOMMANDS` and `printUsage` for the help route. Pinned by `test/pages-purge-deleted-args.test.ts` and the `pages purge-deleted` consent-table row. Its help points soft-delete and restore at `gbrain delete|restore <slug> --force` (page writes are revisioned).
+- `src/commands/pages-unsearchable.ts` — `gbrain pages unsearchable --source <id> [--state <state>] [--limit N] [--json]` (#6696 B3, read-only): one row per (page, embedding state) from `listEmbeddingStateRows` with reason, chunks, bytes and the state's rendered fix; every state but `embedded` unless `--state` names one; `--limit` 1-1000 (default 50) with `complete`; an unknown `--state` or bad `--limit` throws `invalid_params` naming the valid values. Test: `test/pages-unsearchable.test.ts`.
- `src/commands/persistence-admin.ts` + `src/core/persistence/{admin-contract,administration}.ts` — trusted local `sources writer status|failures|claim|transfer` (failures: [Managed sync bookkeeping](managed-sync-bookkeeping.md)) and `auth local-writer list|register|revoke`. Parse and resolve the brain before opening PGLite; an existing owner receives a separate private administration envelope verified against the current CLI registration. These names never enter the public MCP operation registry; stdio, hook credentials, forged trust fields and revoked CLI registrations cannot administer. Transfer requires exact manifest and owner epoch; status `--probe` acquires/releases a real native lock. Explicit credential replacement commits old revocation and new registration together before atomically publishing the private file, preserving old credentials for recovery without keeping their authority. No credential/hash appears in output. `test/persistence-administration.test.ts` covers database rollback, parallel rotations, transfer conflicts, real sockets and real CLI subprocesses. `retry-effects <source> --request-id <original-uuid> --dry-run --json` previews a failed embedding effect without work; applying the same reviewed request requires original/current authority, selected-brain config, source/page/owner CAS and one additional allowance. For a request with parked Git or withdrawal effects the same command previews the parked targets (`--dry-run`) or authorizes one more attempt per parked target, reporting each effect's state and whether it is terminal. It never claims ownership or rewrites canonical receipts.
diff --cc docs/guides/troubleshooting.md
index 33907954b1,d858b5e684..46c1b9968a
--- a/docs/guides/troubleshooting.md
+++ b/docs/guides/troubleshooting.md
@@@ -362,44 -359,10 +363,46 @@@ spawn entirely. The grandfather migrati
pass (keyed on the page PK, soft-delete-filtered, source-safe) and
completes in seconds on an 80K-page PGLite brain.
+ <a id="ghost-pages"></a>**A write refuses `source_changed` with "The canonical file was removed outside coordinated publication." (`canonical_file_missing`), or doctor `ghost_pages` warns?** The page is a ghost: its canonical file is gone on the owner host but the database page is live, so every write refuses and no sync can import a file that is not there. On the owner host, list them with `gbrain pages ghosts --source <id>` (read-only). For each, the user decides: to keep the page, restore its file at the recorded path (from Git or a backup; gbrain has no automated file restore) and run `gbrain sync --source <id>`; to remove it, preview `gbrain repair ghost-pages --source <id>`, show the user the list, and after they agree run the printed `--apply --expect <hash> --yes`. Removed pages are purged after 72 h; `gbrain restore <slug> --force` undoes one until then. Off the owner host it refuses `not_owner_host`; on an unreadable checkout `ghost_storage_unknown`; when ghosts are more than half of the source's file-backed pages `ghost_mass_delete_refused` (check the checkout first). See [ghost pages](repair.md#ghost-pages). **Say to your agent:** *"Which pages lost their files? Show me the list before you remove anything."*
+
<a id="maintenance-write-drift"></a>**Writes to the same pages keep refusing `source_changed` with `file_database_drift`, or doctor `maintenance_write_drift` warns?** Each of those pages has a canonical file that differs from its database copy, usually from an edit outside a coordinated write, so every coordinated write to it refuses and leaves a conflict receipt. Maintenance now checks the file first: `synthesize_concepts` skips a drifted concept before any model call (the phase warns and names the commands below) and other maintenance writes refuse before admission, so the pile stops growing. To list the pages, run `gbrain sources reconcile <id> --brain host --audit --conflicts` (read-only; receipts per slug, whether the file still differs, its drift class and producer; MCP `list_write_conflicts` gives remote readers the database-derived part). Then preview `gbrain repair file-drift --source <id> --all-drifted --prefer file` (add `--class <name>` when the preview reports mixed classes, narrow it with `--only '<path glob>'` / `--skip '<path glob>'` over the canonical file paths, or pick pages with `--slug`), show the user the per-page `exceptions`, and after they agree run the printed `--apply --expect <hash>` command exactly as printed. For derived pages under one directory, such as regenerated concepts: (6) preview `gbrain repair file-drift --source default --all-drifted --only 'concepts/**' --prefer database`, show the user the count and the exceptions, and after they agree run the apply command it prints, which applies exactly the previewed pages. To keep resolving such a directory with the database copy from now on, the user can declare it under `storage:` `keep_db:` in the source's gbrain.yml; the owner host's serve, jobs or autopilot consumer then reconciles drifted pages there at most 10 every 10 minutes, and doctor echoes the policy with its matched count and receipt cost ([keep_db](repair.md#file-drift-keep-db)). `--keep` is refused here: use `--prefer database` or `--prefer file`. See [file drift](repair.md#file-drift). **Say to your agent:** *"Which pages keep refusing source_changed? Preview resolving them and show me before you apply."*
+## Embedding state
+
+**Symptom.** Doctor `embedding_state` warns, `get_brain_health` reports
+`unsearchable` above zero, or a page you know exists never shows up in search.
+
+**Say to your agent:** *"Which pages can search not see, and why?"* The agent
+runs `gbrain pages unsearchable --source <id> --json` (read-only) and follows
+each row's `fix`.
+
+Every chunk, and every live page with no chunk row, is in exactly one state,
+derived from the rows against the active embedding column (no stored status):
+
+| State | What it means | Exit (each row's `fix`) |
+|---|---|---|
+| `embedded` | The chunk has a vector in the active column. | None. |
+| `pending` | The embed job will embed it (no vector, page live, no `embed_skip`). Doctor `embeddings` ages this backlog and owns its warning. | `gbrain embed --stale --catch-up --source <id> --yes` (paid; preview with `--dry-run`). On a brain keyless by choice keyword search reads these chunks and they do not count as unsearchable. |
+| `keyword_only` | The page carries `embed_skip`: the import gate found its body over `content_sanity.bytes_block` (info, by design; its chunks still feed keyword search and are never purged). Removing the marker alone is undone on the next import. | Split the page, or, after the operator approves, `gbrain config set content_sanity.bytes_block <bytes>` then `gbrain sync --source <id> --full`, which re-imports and embeds it. |
+| `quarantined` | The content-quality gate hid the page as junk; it has no searchable chunks. Doctor `quarantined_pages` owns its warning. | Review with `gbrain quarantine list --json`; clear a false positive with `gbrain quarantine clear <slug> --source-id <id> --force` (the owner's call). |
+| `empty` | A live page with no body text: nothing to index. | Write content to it, or delete the stub (`gbrain delete <slug> --source <id> --force`, restorable) after the user agrees. |
+| `deleted_page_chunks` | Chunks of a soft-deleted page. Search never reads them; the purge lifecycle removes them after 72 h (info until then, a warning past it, code `deleted_page_chunks_overdue`). | `gbrain pages purge-deleted --dry-run --json`, then `gbrain pages purge-deleted --yes` once the user agrees (brain-wide, irreversible). |
+| `chunkless_healable` | A live page with body text but no chunk rows (written without the chunking step). Doctor warns on a keyed brain (code `chunkless_pages_healable`). | `gbrain embed --stale --catch-up --source <id> --yes` chunks and embeds it (paid). |
+
+`unsearchable` sums `pending`, `quarantined`, `empty` and `chunkless_healable`;
+`keyword_only` and `deleted_page_chunks` never count. The doctor's ops tier
+reads only index-backed counts: vector-less chunks through the partial index
+`WHERE <active column> IS NULL` (`content_chunks_stale_idx` for the default
+`embedding` column), gated and deleted pages through their indexes, and
+`embedded` as a planner estimate (`basis: estimated`); it omits `empty` and
+`chunkless_healable` (`unsearchable_complete: false`). A registry-routed brain
+whose active column has no such index reports `unknown` there (code
+`embedding_state_unknown`, never a slow scan); the standard tier
+(`gbrain doctor --only embedding_state --json`) counts every state exactly.
+Pending chunks written by a binary older than the pending-age stamp carry no
+age: `details.unstamped_pending` gives their count, this writer's version and
+a `created_at` lower bound, and never warns on its own.
+
## Hybrid search returns only keyword hits
**Symptom.** On a large Postgres brain, `gbrain query` answers look keyword-only,
diff --cc llms-full.txt
index 9f971a0edd,aae796dd66..35de7154ee
--- a/llms-full.txt
+++ b/llms-full.txt
@@@ -10540,44 -10537,10 +10541,46 @@@ spawn entirely. The grandfather migrati
pass (keyed on the page PK, soft-delete-filtered, source-safe) and
completes in seconds on an 80K-page PGLite brain.
+ <a id="ghost-pages"></a>**A write refuses `source_changed` with "The canonical file was removed outside coordinated publication." (`canonical_file_missing`), or doctor `ghost_pages` warns?** The page is a ghost: its canonical file is gone on the owner host but the database page is live, so every write refuses and no sync can import a file that is not there. On the owner host, list them with `gbrain pages ghosts --source <id>` (read-only). For each, the user decides: to keep the page, restore its file at the recorded path (from Git or a backup; gbrain has no automated file restore) and run `gbrain sync --source <id>`; to remove it, preview `gbrain repair ghost-pages --source <id>`, show the user the list, and after they agree run the printed `--apply --expect <hash> --yes`. Removed pages are purged after 72 h; `gbrain restore <slug> --force` undoes one until then. Off the owner host it refuses `not_owner_host`; on an unreadable checkout `ghost_storage_unknown`; when ghosts are more than half of the source's file-backed pages `ghost_mass_delete_refused` (check the checkout first). See [ghost pages](repair.md#ghost-pages). **Say to your agent:** *"Which pages lost their files? Show me the list before you remove anything."*
+
<a id="maintenance-write-drift"></a>**Writes to the same pages keep refusing `source_changed` with `file_database_drift`, or doctor `maintenance_write_drift` warns?** Each of those pages has a canonical file that differs from its database copy, usually from an edit outside a coordinated write, so every coordinated write to it refuses and leaves a conflict receipt. Maintenance now checks the file first: `synthesize_concepts` skips a drifted concept before any model call (the phase warns and names the commands below) and other maintenance writes refuse before admission, so the pile stops growing. To list the pages, run `gbrain sources reconcile <id> --brain host --audit --conflicts` (read-only; receipts per slug, whether the file still differs, its drift class and producer; MCP `list_write_conflicts` gives remote readers the database-derived part). Then preview `gbrain repair file-drift --source <id> --all-drifted --prefer file` (add `--class <name>` when the preview reports mixed classes, narrow it with `--only '<path glob>'` / `--skip '<path glob>'` over the canonical file paths, or pick pages with `--slug`), show the user the per-page `exceptions`, and after they agree run the printed `--apply --expect <hash>` command exactly as printed. For derived pages under one directory, such as regenerated concepts: (6) preview `gbrain repair file-drift --source default --all-drifted --only 'concepts/**' --prefer database`, show the user the count and the exceptions, and after they agree run the apply command it prints, which applies exactly the previewed pages. To keep resolving such a directory with the database copy from now on, the user can declare it under `storage:` `keep_db:` in the source's gbrain.yml; the owner host's serve, jobs or autopilot consumer then reconciles drifted pages there at most 10 every 10 minutes, and doctor echoes the policy with its matched count and receipt cost ([keep_db](repair.md#file-drift-keep-db)). `--keep` is refused here: use `--prefer database` or `--prefer file`. See [file drift](repair.md#file-drift). **Say to your agent:** *"Which pages keep refusing source_changed? Preview resolving them and show me before you apply."*
+## Embedding state
+
+**Symptom.** Doctor `embedding_state` warns, `get_brain_health` reports
+`unsearchable` above zero, or a page you know exists never shows up in search.
+
+**Say to your agent:** *"Which pages can search not see, and why?"* The agent
+runs `gbrain pages unsearchable --source <id> --json` (read-only) and follows
+each row's `fix`.
+
+Every chunk, and every live page with no chunk row, is in exactly one state,
+derived from the rows against the active embedding column (no stored status):
+
+| State | What it means | Exit (each row's `fix`) |
+|---|---|---|
+| `embedded` | The chunk has a vector in the active column. | None. |
+| `pending` | The embed job will embed it (no vector, page live, no `embed_skip`). Doctor `embeddings` ages this backlog and owns its warning. | `gbrain embed --stale --catch-up --source <id> --yes` (paid; preview with `--dry-run`). On a brain keyless by choice keyword search reads these chunks and they do not count as unsearchable. |
+| `keyword_only` | The page carries `embed_skip`: the import gate found its body over `content_sanity.bytes_block` (info, by design; its chunks still feed keyword search and are never purged). Removing the marker alone is undone on the next import. | Split the page, or, after the operator approves, `gbrain config set content_sanity.bytes_block <bytes>` then `gbrain sync --source <id> --full`, which re-imports and embeds it. |
+| `quarantined` | The content-quality gate hid the page as junk; it has no searchable chunks. Doctor `quarantined_pages` owns its warning. | Review with `gbrain quarantine list --json`; clear a false positive with `gbrain quarantine clear <slug> --source-id <id> --force` (the owner's call). |
+| `empty` | A live page with no body text: nothing to index. | Write content to it, or delete the stub (`gbrain delete <slug> --source <id> --force`, restorable) after the user agrees. |
+| `deleted_page_chunks` | Chunks of a soft-deleted page. Search never reads them; the purge lifecycle removes them after 72 h (info until then, a warning past it, code `deleted_page_chunks_overdue`). | `gbrain pages purge-deleted --dry-run --json`, then `gbrain pages purge-deleted --yes` once the user agrees (brain-wide, irreversible). |
+| `chunkless_healable` | A live page with body text but no chunk rows (written without the chunking step). Doctor warns on a keyed brain (code `chunkless_pages_healable`). | `gbrain embed --stale --catch-up --source <id> --yes` chunks and embeds it (paid). |
+
+`unsearchable` sums `pending`, `quarantined`, `empty` and `chunkless_healable`;
+`keyword_only` and `deleted_page_chunks` never count. The doctor's ops tier
+reads only index-backed counts: vector-less chunks through the partial index
+`WHERE <active column> IS NULL` (`content_chunks_stale_idx` for the default
+`embedding` column), gated and deleted pages through their indexes, and
+`embedded` as a planner estimate (`basis: estimated`); it omits `empty` and
+`chunkless_healable` (`unsearchable_complete: false`). A registry-routed brain
+whose active column has no such index reports `unknown` there (code
+`embedding_state_unknown`, never a slow scan); the standard tier
+(`gbrain doctor --only embedding_state --json`) counts every state exactly.
+Pending chunks written by a binary older than the pending-age stamp carry no
+age: `details.unstamped_pending` gives their count, this writer's version and
+a `created_at` lower bound, and never warns on its own.
+
## Hybrid search returns only keyword hits
**Symptom.** On a large Postgres brain, `gbrain query` answers look keyword-only,
diff --cc src/cli/subcommands.ts
index 494f676de5,fc7ba47d2f..5e4cb19ac0
--- a/src/cli/subcommands.ts
+++ b/src/cli/subcommands.ts
@@@ -17,7 -17,7 +17,7 @@@
* returns before startup side effects, strict argument checks and engine
* access.
*/
- export const PAGES_SUBCOMMANDS = ['purge-deleted', 'purges', 'unpurge', 'unsearchable'] as const;
-export const PAGES_SUBCOMMANDS = ['purge-deleted', 'purges', 'unpurge', 'ghosts'] as const;
++export const PAGES_SUBCOMMANDS = ['purge-deleted', 'purges', 'unpurge', 'unsearchable', 'ghosts'] as const;
export const CACHE_SUBCOMMANDS = ['stats', 'clear', 'prune'] as const;
export const INTEGRITY_SUBCOMMANDS = ['check', 'auto', 'review', 'reset-progress'] as const;
export const HOOK_SUBCOMMANDS = ['session-start', 'user-prompt', 'stop', 'session-end', 'compact'] as const;
diff --cc src/commands/doctor/brain-health-bands.ts
index 97179e3719,0000000000..fbdd15e608
mode 100644,000000..100644
--- a/src/commands/doctor/brain-health-bands.ts
+++ b/src/commands/doctor/brain-health-bands.ts
@@@ -1,70 -1,0 +1,77 @@@
+/**
+ * #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
+ * 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 { 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] = await Promise.all([
++ const [capacity, failures, unsearchable, ghostPages] = await Promise.all([
+ readCapacityView(engine).then((view) => ({ ...capacityBands(view), forecast: view.forecast ? 'available' as const : 'unavailable' 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 };
++ 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');
++ 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/registry.ts
index 48d33bdd04,4da37fbec5..f180b908a2
--- a/src/commands/doctor/registry.ts
+++ b/src/commands/doctor/registry.ts
@@@ -109,19 -108,10 +109,20 @@@ import { chatFallbackChainEntry } from
import { 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,
+ 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';
@@@ -212,9 -194,12 +213,10 @@@ export const DOCTOR_CHECK_REGISTRY: rea
trustScanEntry,
trustSourcesUnclaimedEntry,
coreMemoryEntry,
- managedSyncMovementEntry,
persistenceConsumersEntry,
- serveBuildDriftEntry,
atomHeldFailedEntry,
fenceIntegrityEntry,
+ ghostPagesEntry,
searchModeEntry,
];
diff --cc src/commands/pages.ts
index f92917cfa0,a731ee894d..9609884b18
--- a/src/commands/pages.ts
+++ b/src/commands/pages.ts
@@@ -2,7 -2,7 +2,8 @@@
* gbrain pages — page-level operator commands. v0.26.5+.
*
* The first subcommand: `pages purge-deleted [--older-than HOURS|Nh|Nd] [--dry-run] [--json] [--yes]`.
+ * `pages unsearchable` (#6696 B3) lists embedding-state rows; its body is pages-unsearchable.ts.
+ * `pages ghosts [--source <id>] [--json]` (#6696 B5, pages-ghosts.ts) lists ghost pages, read-only.
* Manual escape hatch alongside the autopilot purge phase. Hard-deletes pages
* whose `deleted_at` is older than the cutoff; cascades to content_chunks,
* page_links, chunk_relations via existing FKs.
@@@ -126,7 -122,7 +130,8 @@@ export async function runPages(engine:
switch (sub) {
case 'purge-deleted': return runPurgeDeleted(engine, args.slice(1));
case 'purges': case 'unpurge': return (await import('./pages-purges.ts')).runPagePurges(engine, sub, args.slice(1));
+ case 'unsearchable': return (await import('./pages-unsearchable.ts')).runPagesUnsearchable(engine, args.slice(1));
+ case 'ghosts': return (await import('./pages-ghosts.ts')).runPagesGhosts(engine, args.slice(1));
case undefined:
printUsage();
return;
diff --cc src/core/behavior-change-notice.ts
index 7802acd20e,04ca4cad1e..f02050e854
--- a/src/core/behavior-change-notice.ts
+++ b/src/core/behavior-change-notice.ts
@@@ -572,11 -572,10 +572,15 @@@ export const BEHAVIOR_CHANGES: Readonly
{ 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: '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 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: '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 test/doctor-day-zero.test.ts
index cbd331af49,8c77b36cc4..96452906b0
--- a/test/doctor-day-zero.test.ts
+++ b/test/doctor-day-zero.test.ts
@@@ -45,28 -45,13 +45,30 @@@ describe('day-zero keyless doctor', ()
expect(report.health_score).toBeGreaterThanOrEqual(90);
expect(report.capped_by).toEqual(['embeddings_disabled']);
const info = new Set(report.checks.filter(c => c.severity === 'info').map(c => c.name));
- for (const name of ['embeddings', 'embedding_provider', 'takes_count', 'retrieval_reflex_health', 'skill_preconditions', 'cycle_freshness', 'backup_coverage']) {
+ // #6696 B3: embedding_state runs on day zero and stays info on a keyless brain.
+ expect(report.checks.find(c => c.name === 'embedding_state')).toMatchObject({ status: 'ok', severity: 'info' });
+ for (const name of ['embeddings', 'embedding_provider', 'embedding_state', 'takes_count', 'retrieval_reflex_health', 'skill_preconditions', 'cycle_freshness', 'backup_coverage']) {
if (report.checks.some(c => c.name === name)) expect(info.has(name), name).toBe(true);
}
+ // #6696 B5: ghost_pages runs on day zero and is ok, never a warning.
+ expect(report.checks.find(c => c.name === 'ghost_pages')).toMatchObject({ status: 'ok' });
}, 120_000);
+ test('doctor --tier ops --json (#6696): no WARN or FAIL, complete, PGLite-skipped sections not_applicable', async () => {
+ const run = await runGbrain(h, ['doctor', '--tier', 'ops', '--json']);
+ expect(run.exitCode).toBe(0);
+ const report = run.json as Report & { tier?: string; complete?: boolean; unknown_sections?: string[]; budget_ms?: number };
+ const notOk = report.checks.filter(c => c.status !== 'ok').map(c => `${c.status} ${c.name}: ${c.message}`);
+ expect(notOk).toEqual([]);
+ expect(report.tier).toBe('ops');
+ expect(report.complete).toBe(true);
+ expect(report.unknown_sections).toEqual([]);
+ expect(report.budget_ms).toBe(4000);
+ const skipped = report.checks.filter(c => (c as { details?: { health?: string } }).details?.health === 'not_applicable');
+ expect(skipped.length).toBeGreaterThan(0);
+ for (const c of skipped) expect(c.severity, c.name).toBe('info');
+ }, 120_000);
+
test('human doctor on a pipe keeps the heartbeat within 10 stderr lines', async () => {
const run = await runGbrain(h, ['doctor']);
expect(run.exitCode).toBe(0);
diff --cc test/doctor-ops-remote-6696.test.ts
index e830da0a0c,0000000000..a536efe770
mode 100644,000000..100644
--- a/test/doctor-ops-remote-6696.test.ts
+++ b/test/doctor-ops-remote-6696.test.ts
@@@ -1,246 -1,0 +1,247 @@@
+/**
+ * #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(['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' });
+ 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/fixtures/goldens/doctor/content-pglite-human.json
index ae61ff5e41,e5badca55c..70fd9f97a3
--- a/test/fixtures/goldens/doctor/content-pglite-human.json
+++ b/test/fixtures/goldens/doctor/content-pglite-human.json
@@@ -185,8 -180,10 +185,9 @@@
" [OK] two_consumers_on_host: PGLite admits one process; no consumer heartbeat rows are kept.",
" [OK] consumers_without_heartbeat: PGLite admits one process; no consumer heartbeat rows are kept.",
" [OK] host_identity_mismatch: This process's host identity (<home>/.gbrain/persistence/host.json) owns every binding this filesystem holds.",
- " [OK] serve_build_drift: PGLite admits one process; no consumer heartbeat rows are kept to compare builds.",
" [OK] extract_atoms_held_failed: No managed atom page or transcript is held after repeated extraction failures.",
" [OK] fence_integrity: No malformed facts or takes fence is held, stored or waiting in a checkout (2 source(s) scanned).",
++ " [OK] ghost_pages: No live page is missing its canonical file (5 page(s) inspected).",
" [OK] search_mode: Mode: conservative (no per-key overrides — mode bundle is canonical).",
" [OK] hidden_by_search_policy: No pages hidden by search-exclude policy.",
" [OK] eval_drift: No retrieval-affecting files changed in working tree.",
diff --cc test/fixtures/goldens/doctor/content-pglite-json.json
index 63452b80c3,5ba8248643..2229df3bc7
--- a/test/fixtures/goldens/doctor/content-pglite-json.json
+++ b/test/fixtures/goldens/doctor/content-pglite-json.json
@@@ -2672,9 -2383,8 +2672,36 @@@
"name": "fence_integrity",
"status": "ok"
},
++ {
++ "category": "brain",
++ "details": {
++ "by_source": [
++ {
++ "count": 0,
++ "source_id": "default",
++ "status": "known"
++ },
++ {
++ "count": 0,
++ "source_id": "notes",
++ "status": "known"
++ }
++ ],
++ "count": 0,
++ "docs": "docs/guides/repair.md#ghost-pages",
++ "exact": true,
++ "inspected": 5,
++ "samples": [],
++ "truncated": false
++ },
++ "elapsed_ms": "<volatile>",
++ "message": "No live page is missing its canonical file (5 page(s) inspected).",
++ "name": "ghost_pages",
++ "status": "ok"
++ },
{
"category": "ops",
+ "elapsed_ms": "<volatile>",
"message": "Mode: conservative (no per-key overrides — mode bundle is canonical).",
"name": "search_mode",
"status": "ok"
diff --cc test/fixtures/goldens/doctor/hot-checks-pglite-json.json
index d0573537fe,31b03ab795..f688f7a4a0
--- a/test/fixtures/goldens/doctor/hot-checks-pglite-json.json
+++ b/test/fixtures/goldens/doctor/hot-checks-pglite-json.json
@@@ -2960,9 -2656,8 +2960,41 @@@
"name": "fence_integrity",
"status": "warn"
},
++ {
++ "category": "brain",
++ "details": {
++ "by_source": [
++ {
++ "count": 0,
++ "source_id": "default",
++ "status": "known"
++ },
++ {
++ "count": 0,
++ "source_id": "notes",
++ "status": "known"
++ },
++ {
++ "count": 0,
++ "source_id": "plain",
++ "status": "known"
++ }
++ ],
++ "count": 0,
++ "docs": "docs/guides/repair.md#ghost-pages",
++ "exact": true,
++ "inspected": 20,
++ "samples": [],
++ "truncated": false
++ },
++ "elapsed_ms": "<volatile>",
++ "message": "No live page is missing its canonical file (20 page(s) inspected).",
++ "name": "ghost_pages",
++ "status": "ok"
++ },
{
"category": "ops",
+ "elapsed_ms": "<volatile>",
"message": "Mode: conservative (no per-key overrides — mode bundle is canonical).",
"name": "search_mode",
"status": "ok"
@@@ -6479,9 -5837,8 +6511,41 @@@
"name": "fence_integrity",
"status": "warn"
},
++ {
++ "category": "brain",
++ "details": {
++ "by_source": [
++ {
++ "count": 0,
++ "source_id": "default",
++ "status": "known"
++ },
++ {
++ "count": 0,
++ "source_id": "notes",
++ "status": "known"
++ },
++ {
++ "count": 0,
++ "source_id": "plain",
++ "status": "known"
++ }
++ ],
++ "count": 0,
++ "docs": "docs/guides/repair.md#ghost-pages",
++ "exact": true,
++ "inspected": 20,
++ "samples": [],
++ "truncated": false
++ },
++ "elapsed_ms": "<volatile>",
++ "message": "No live page is missing its canonical file (20 page(s) inspected).",
++ "name": "ghost_pages",
++ "status": "ok"
++ },
{
"category": "ops",
+ "elapsed_ms": "<volatile>",
"message": "Mode: conservative (no per-key overrides — mode bundle is canonical).",
"name": "search_mode",
"status": "ok"
diff --cc test/fixtures/goldens/doctor/hot-checks-postgres-json.json
index 5de390f643,e5979480ab..6d597e1df5
--- a/test/fixtures/goldens/doctor/hot-checks-postgres-json.json
+++ b/test/fixtures/goldens/doctor/hot-checks-postgres-json.json
@@@ -2957,9 -2654,8 +2957,41 @@@
"name": "fence_integrity",
"status": "warn"
},
++ {
++ "category": "brain",
++ "details": {
++ "by_source": [
++ {
++ "count": 0,
++ "source_id": "default",
++ "status": "known"
++ },
++ {
++ "count": 0,
++ "source_id": "notes",
++ "status": "known"
++ },
++ {
++ "count": 0,
++ "source_id": "plain",
++ "status": "known"
++ }
++ ],
++ "count": 0,
++ "docs": "docs/guides/repair.md#ghost-pages",
++ "exact": true,
++ "inspected": 20,
++ "samples": [],
++ "truncated": false
++ },
++ "elapsed_ms": "<volatile>",
++ "message": "No live page is missing its canonical file (20 page(s) inspected).",
++ "name": "ghost_pages",
++ "status": "ok"
++ },
{
"category": "ops",
+ "elapsed_ms": "<volatile>",
"message": "Mode: conservative (no per-key overrides — mode bundle is canonical).",
"name": "search_mode",
"status": "ok"
@@@ -6471,9 -5831,8 +6503,41 @@@
"name": "fence_integrity",
"status": "warn"
},
++ {
++ "category": "brain",
++ "details": {
++ "by_source": [
++ {
++ "count": 0,
++ "source_id": "default",
++ "status": "known"
++ },
++ {
++ "count": 0,
++ "source_id": "notes",
++ "status": "known"
++ },
++ {
++ "count": 0,
++ "source_id": "plain",
++ "status": "known"
++ }
++ ],
++ "count": 0,
++ "docs": "docs/guides/repair.md#ghost-pages",
++ "exact": true,
++ "inspected": 20,
++ "samples": [],
++ "truncated": false
++ },
++ "elapsed_ms": "<volatile>",
++ "message": "No live page is missing its canonical file (20 page(s) inspected).",
++ "name": "ghost_pages",
++ "status": "ok"
++ },
{
"category": "ops",
+ "elapsed_ms": "<volatile>",
"message": "Mode: conservative (no per-key overrides — mode bundle is canonical).",
"name": "search_mode",
"status": "ok"
diff --cc test/fixtures/goldens/doctor/json-pglite-degraded.json
index 5e6f4daef3,37d5ac69ab..9efc82f247
--- a/test/fixtures/goldens/doctor/json-pglite-degraded.json
+++ b/test/fixtures/goldens/doctor/json-pglite-degraded.json
@@@ -2443,9 -2213,29 +2443,31 @@@
"name": "fence_integrity",
"status": "ok"
},
+ {
+ "category": "brain",
+ "details": {
+ "by_source": [
+ {
+ "count": 0,
+ "source_id": "default",
+ "status": "known"
+ }
+ ],
+ "count": 0,
+ "docs": "docs/guides/repair.md#ghost-pages",
+ "exact": true,
+ "inspected": 0,
+ "samples": [],
+ "truncated": false
+ },
++ "elapsed_ms": "<volatile>",
+ "message": "No live page is missing its canonical file (0 page(s) inspected).",
+ "name": "ghost_pages",
+ "status": "ok"
+ },
{
"category": "ops",
+ "elapsed_ms": "<volatile>",
"message": "Mode: conservative (no per-key overrides — mode bundle is canonical).",
"name": "search_mode",
"status": "ok"
diff --cc test/fixtures/goldens/doctor/json-pglite-fresh.json
index 8051b13575,0f040b67d5..360e8eaf7d
--- a/test/fixtures/goldens/doctor/json-pglite-fresh.json
+++ b/test/fixtures/goldens/doctor/json-pglite-fresh.json
@@@ -2495,9 -2221,29 +2495,31 @@@
"name": "fence_integrity",
"status": "ok"
},
+ {
+ "category": "brain",
+ "details": {
+ "by_source": [
+ {
+ "count": 0,
+ "source_id": "default",
+ "status": "known"
+ }
+ ],
+ "count": 0,
+ "docs": "docs/guides/repair.md#ghost-pages",
+ "exact": true,
+ "inspected": 0,
+ "samples": [],
+ "truncated": false
+ },
++ "elapsed_ms": "<volatile>",
+ "message": "No live page is missing its canonical file (0 page(s) inspected).",
+ "name": "ghost_pages",
+ "status": "ok"
+ },
{
"category": "ops",
+ "elapsed_ms": "<volatile>",
"message": "Mode: conservative (no per-key overrides — mode bundle is canonical).",
"name": "search_mode",
"status": "ok"
diff --cc test/fixtures/goldens/doctor/json-postgres-fresh.json
index 8f3d28c1fa,366c25fbe2..7a3da61866
--- a/test/fixtures/goldens/doctor/json-postgres-fresh.json
+++ b/test/fixtures/goldens/doctor/json-postgres-fresh.json
@@@ -2492,9 -2219,8 +2492,31 @@@
"name": "fence_integrity",
"status": "ok"
},
++ {
++ "category": "brain",
++ "details": {
++ "by_source": [
++ {
++ "count": 0,
++ "source_id": "default",
++ "status": "known"
++ }
++ ],
++ "count": 0,
++ "docs": "docs/guides/repair.md#ghost-pages",
++ "exact": true,
++ "inspected": 0,
++ "samples": [],
++ "truncated": false
++ },
++ "elapsed_ms": "<volatile>",
++ "message": "No live page is missing its canonical file (0 page(s) inspected).",
++ "name": "ghost_pages",
++ "status": "ok"
++ },
{
"category": "ops",
+ "elapsed_ms": "<volatile>",
"message": "Mode: conservative (no per-key overrides — mode bundle is canonical).",
"name": "search_mode",
"status": "ok"