Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
doctor: ops tier, budgets, unknown-on-budget, get_brain_health bands (#6696 B1/B2)
garrytana58992d85bea
diff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsvindex ba331f52a7..b6116fac5b 100644--- a/scripts/module-size-limits.tsv+++ b/scripts/module-size-limits.tsv@@ -5,7 +5,7 @@# Columns: path max_lines policy notesrc/cli/main.ts 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/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 baselinediff --git a/src/cli/commands/doctor.ts b/src/cli/commands/doctor.tsindex 3e7145f028..33f037e10b 100644--- a/src/cli/commands/doctor.ts+++ b/src/cli/commands/doctor.ts@@ -21,6 +21,15 @@ export async function run(args: string[], ctx: CliDispatchContext): Promise<void// before any local-engine work.const cfgForDoctor = loadConfig();if (isThinClient(cfgForDoctor)) {+ // #6696 B2: --tier, or --only naming brain checks, asks the serve (run_doctor / get_brain_health) or hands off; never the full report.+ const { parseOnlyChecks, doctorCheckNames } = await import('../../commands/doctor/registry.ts');+ const only = parseOnlyChecks(args);+ const tier = args.find((a, i) => args[i - 1] === '--tier') ?? args.find((a) => a.startsWith('--tier='))?.slice('--tier='.length);+ if (tier !== undefined || (only && only.size > 0 && [...only].every((n) => doctorCheckNames().has(n)))) {+ const { runScopedRemoteDoctor } = await import('../../core/doctor-remote-tier.ts');+ await runScopedRemoteDoctor(cfgForDoctor!, { tier, only, json: args.includes('--json'), label: args.filter((a) => a !== '--json').join(' ') });+ return;+ }const { runRemoteDoctor } = await import('../../core/doctor-remote.ts');await runRemoteDoctor(cfgForDoctor!, args);return;@@ -44,14 +53,21 @@ export async function run(args: string[], ctx: CliDispatchContext): Promise<voidreturn;}+ // #6696 B1: the absolute deadline starts before connecting; a bad --tier / --budget-ms exits 2 before any work.+ const { startDoctorDeadline } = await import('../../commands/doctor/budget.ts');+ let deadline: import('../../commands/doctor/budget.ts').DoctorDeadline;+ try { deadline = startDoctorDeadline(args); } catch (error) { await renderDoctorParamError(error, args); return; }+// Doctor runs filesystem checks first (no DB needed), then DB checks.// --fast skips DB checks entirely.const { runDoctor } = await import('../../commands/doctor.ts');- if (await runDoctorOnly(args, connectEngine, runDoctor)) return;+ if (await runDoctorOnly(args, connectEngine, runDoctor, deadline)) return;if (args.includes('--fast')) {// Pass the DB URL source so doctor can tell "no config at all" from// "user chose --fast while config is present".- await runDoctor(null, args, getDbUrlSource());+ await runDoctor(null, args, getDbUrlSource(), undefined, deadline);+ } else if (deadline.deadlineAt !== null) {+ await runDoctorWithDeadline(args, connectEngine, runDoctor, deadline);} else {// #2084: both failure kinds (connect throw, runDoctor(eng) throw) still// fall back to filesystem-only checks — identical to the prior shape.@@ -65,7 +81,7 @@ export async function run(args: string[], ctx: CliDispatchContext): Promise<void// connectEngine's auto-migrate block so a clean/behind DB is reported// on as-is instead of being migrated before the health checks run.eng = await connectEngine({ probeOnly: args.includes('--no-migrate') });- await runDoctor(eng, args);+ await runDoctor(eng, args, undefined, undefined, deadline);} catch (e) {// DB unavailable OR the DB-backed run threw — still run filesystem// checks. Say so on stderr: a silent fallback looks identical to a@@ -86,13 +102,53 @@ export async function run(args: string[], ctx: CliDispatchContext): Promise<voidconsole.error(`${formatDbMarker(d)}\n${d.remediation} Run: gbrain db-repair`);}} catch { /* marker is best-effort */ }- await runDoctor(null, args, getDbUrlSource(), e);+ await runDoctor(null, args, getDbUrlSource(), e, deadline);} finally {if (eng) await finishCliTeardown({ engine: eng });}}}+/** A `--tier` / `--budget-ms` value doctor cannot use: the structured error, exit 2. */+async function renderDoctorParamError(error: unknown, args: string[]): Promise<void> {+ const { renderCliError } = await import('../../core/agent-output.ts');+ const out = renderCliError(error, { json: args.includes('--json'), command: 'doctor', tty: !!process.stderr.isTTY });+ if (out.stdout) process.stdout.write(out.stdout);+ if (out.stderr) process.stderr.write(out.stderr);+ setCliExitVerdict(out.exitCode);+}++/**+ * #6696 B1: a run with an overall deadline (`--tier ops`, or `--budget-ms`).+ * Observational from connection onward (probe-only connect: no migrations, no+ * maintenance), and the connect itself counts against the deadline: a connect+ * still pending at the deadline reports the run as unknown instead of waiting.+ */+async function runDoctorWithDeadline(+ args: string[],+ connectEngine: CliDispatchContext['connectEngine'],+ runDoctor: typeof import('../../commands/doctor.ts').runDoctor,+ deadline: import('../../commands/doctor/budget.ts').DoctorDeadline,+): Promise<void> {+ const { raceBudget, budgetExpired, DoctorBudgetError } = await import('../../commands/doctor/budget.ts');+ const connecting = connectEngine({ probeOnly: true });+ let eng: BrainEngine | null = null;+ try {+ const connected = await raceBudget(connecting, deadline.deadlineAt! - Date.now());+ if (budgetExpired(connected)) {+ connecting.then((late) => finishCliTeardown({ engine: late }), () => undefined);+ await runDoctor(null, args, getDbUrlSource(), new DoctorBudgetError(Date.now() - deadline.startedAt), deadline);+ return;+ }+ eng = connected;+ await runDoctor(eng, args, undefined, undefined, deadline);+ } catch (e) {+ await runDoctor(null, args, getDbUrlSource(), e, deadline);+ } finally {+ if (eng) await finishCliTeardown({ engine: eng });+ }+}+/*** `gbrain doctor --only <check>[,…] [--json]` — the default `fix.verify`:* read-only, observational startup (probeOnly: no migrations or maintenance),@@ -103,6 +159,7 @@ async function runDoctorOnly(args: string[],connectEngine: CliDispatchContext['connectEngine'],runDoctor: typeof import('../../commands/doctor.ts').runDoctor,+ deadline: import('../../commands/doctor/budget.ts').DoctorDeadline,): Promise<boolean> {const { parseOnlyChecks, doctorCheckNames, onlyNeedsEngine } = await import('../../commands/doctor/registry.ts');const only = parseOnlyChecks(args);@@ -124,15 +181,19 @@ async function runDoctorOnly(return true;}if (!onlyNeedsEngine(only)) {- await runDoctor(null, args, getDbUrlSource());+ await runDoctor(null, args, getDbUrlSource(), undefined, deadline);+ return true;+ }+ if (deadline.deadlineAt !== null) {+ await runDoctorWithDeadline(args, connectEngine, runDoctor, deadline);return true;}let eng: BrainEngine | null = null;try {eng = await connectEngine({ probeOnly: true });- await runDoctor(eng, args);+ await runDoctor(eng, args, undefined, undefined, deadline);} catch (e) {- await runDoctor(null, args, getDbUrlSource(), e);+ await runDoctor(null, args, getDbUrlSource(), e, deadline);} finally {if (eng) await finishCliTeardown({ engine: eng });}diff --git a/src/cli/help/doctor.ts b/src/cli/help/doctor.tsindex 57a8bceb6d..be1e3acf9f 100644--- a/src/cli/help/doctor.ts+++ b/src/cli/help/doctor.ts@@ -5,7 +5,8 @@ export const help: CliHelpSpec = {summary: 'Check brain health; preview and run remediation.',usage: ['gbrain doctor [--fast] [--json] [--fix [--dry-run]] [--scope=brain] [--source <id>] [--no-migrate] [--locks]',- 'gbrain doctor --only <check>[,<check>…] [--json]',+ 'gbrain doctor --tier ops|standard|deep [--budget-ms <n>] [--json]',+ 'gbrain doctor --only <check>[,<check>…] [--tier ops] [--json]','gbrain doctor --remediation-plan [--target-score <n>] [--no-embed] [--json]','gbrain doctor --remediate [--yes [--expect <plan_hash>]] [--include-repairs] [--max-usd <n>] [--target-score <n>]',' [--max-jobs <n>] [--no-embed] [--dry-run] [--resume [<plan_hash>]] [--json]',@@ -14,6 +15,8 @@ export const help: CliHelpSpec = {{ name: '--json', type: 'boolean', desc: 'Print one JSON document (checks, score, findings) on stdout.' },{ name: '--only', type: 'string', desc: 'Read-only: run just the named checks (comma-separated or repeated; no migrations). The usual fix.verify. An unknown name exits 2 with the valid list.' },{ name: '--fast', type: 'boolean', desc: 'Skip database checks; filesystem and config checks only.' },+ { name: '--tier', type: 'enum', values: ['ops', 'standard', 'deep'], desc: 'ops: only the operational sections (capacity, write failures, embedding state, sync movement, compaction, serve build, schema pack) under a 4 s deadline, observational (no migrations). standard (default): ops first, then the rest. deep: adds full scans (orphan_ratio on brains over 50,000 pages).' },+ { name: '--budget-ms', type: 'number', desc: 'Absolute end-to-end deadline in ms, counted from before the connect (default 4000 with --tier ops; none otherwise). Checks past it report health unknown (reason budget); the report says complete: false.' },{ name: '--fix', type: 'boolean', desc: 'Apply the local fixes doctor knows (skill files, stale locks); pair with --dry-run to preview.' },{ name: '--dry-run', type: 'boolean', desc: 'Preview --fix or --remediate without changing anything.' },{ name: '--scope', type: 'enum', values: ['all', 'brain'], desc: 'Pass --scope=brain to skip the skill-file check group (default all).' },@@ -40,6 +43,7 @@ export const help: CliHelpSpec = {examples: ['gbrain doctor --json','gbrain doctor --only harness_wiring --json',+ 'gbrain doctor --tier ops --json','gbrain doctor --remediation-plan --json','gbrain doctor --remediate --yes --include-repairs --expect <plan_hash> --max-usd 5',],diff --git a/src/commands/doctor.ts b/src/commands/doctor.tsindex bd1b453843..8020d0806b 100644--- a/src/commands/doctor.ts+++ b/src/commands/doctor.ts@@ -135,7 +135,9 @@ export {buildMemoryVerbsCheck,buildRetrievalReflexCheck,} from './doctor/checks/verbs-reflex.ts';-import type { DoctorContext } from './doctor/context.ts';+import type { DoctorContext, DoctorTier } from './doctor/context.ts';+import { doctorRunSummary, parseDoctorTier, startDoctorDeadline, tierFields, type DoctorDeadline, type DoctorRunSummary } from './doctor/budget.ts';+export { doctorRunSummary, type DoctorRunSummary } from './doctor/budget.ts';import { runDoctorRegistry, parseOnlyChecks } from './doctor/registry.ts';import { finalizeCheckFixes, fixLine, unknownScoreCategories, type CheckAgentFields } from './doctor/check-fix.ts';import { throttleDoctorHeartbeat } from './doctor/heartbeat.ts';@@ -173,6 +175,8 @@ export interface Check extends CheckAgentFields {* Source of truth: `src/core/doctor-categories.ts`.*/category?: CheckCategory;+ /** #6696 B1: wall time of the registry entry that produced this check. */+ elapsed_ms?: number;}/**@@ -237,6 +241,12 @@ export interface DoctorReport {capped_by?: string[];/** E10: category scores that are not evidence because their checks did not run (e.g. `brain` when the DB was unreachable). */unknown_scores?: Array<'brain'>;+ /** #6696 B1, only with `--tier` / `--budget-ms`: the tier, whether every check is known, the unknown ones, wall time, budget (null: none). */+ tier?: DoctorTier;+ complete?: boolean;+ unknown_sections?: string[];+ elapsed_ms?: number;+ budget_ms?: number | null;}function _penaltyScore(checks: Check[]): number {@@ -264,7 +274,7 @@ function _penaltyScore(checks: Check[]): number {*/export function computeDoctorReport(checks: Check[],- extras?: { engine?: 'postgres' | 'pglite'; db_url_source?: DbUrlSource | null; render?: RenderContext },+ extras?: { engine?: 'postgres' | 'pglite'; db_url_source?: DbUrlSource | null; render?: RenderContext; run?: DoctorRunSummary },): DoctorReport {const tagged = finalizeCheckFixes(checks, extras?.render).map((c) =>c.category ? c : { ...c, category: categorizeCheck(c.name) },@@ -298,6 +308,7 @@ export function computeDoctorReport(...(extras?.db_url_source !== undefined ? { db_url_source: extras.db_url_source } : {}),...(capped_by.length ? { capped_by } : {}),...(unknownScoreCategories(tagged).length ? { unknown_scores: unknownScoreCategories(tagged) } : {}),+ ...(extras?.run ? tierFields(tagged, extras.run) : {}),};}@@ -381,6 +392,9 @@ export async function buildChecks(// `connection` check — without it, a total outage produced NO connection// entry at all, which is exactly the field smoke-test branches on.connectError?: unknown,+ // #6696: the run's deadline (started by the CLI before connecting) and a remote caller's readable sources.+ deadline: DoctorDeadline = startDoctorDeadline(args),+ remoteScope: { sourceIds?: string[] } = {},): Promise<Check[]> {const jsonOutput = args.includes('--json');const fastMode = args.includes('--fast');@@ -455,7 +469,9 @@ export async function buildChecks(schemaVersion: 0,connectionFailed: false,only: parseOnlyChecks(args),- tier: 'standard',+ tier: parseDoctorTier(args),+ deadline,+ ...(remoteScope.sourceIds ? { sourceIds: remoteScope.sourceIds } : {}),};return runDoctorRegistry(ctx);@@ -485,6 +501,7 @@ export async function runDoctor(// db-availability loop: the connect error from the CLI's dead-DB fallback,// threaded to buildChecks for the synthesized `connection` check (2c-bis).connectError?: unknown,+ deadline: DoctorDeadline = startDoctorDeadline(args),) {const jsonOutput = args.includes('--json');const locksMode = args.includes('--locks');@@ -498,11 +515,12 @@ export async function runDoctor(}if (args.includes('--probe') && !(await (await import('./doctor/probe-consent.ts')).authorizeProviderProbe(engine, args, jsonOutput))) return;- const checks = await buildChecks(engine, args, dbSource, connectError);- const hasFail = outputResults(checks, jsonOutput, { engine: engine?.kind, db_url_source: dbSource ?? null });+ const checks = await buildChecks(engine, args, dbSource, connectError, deadline);+ const run = doctorRunSummary(args, deadline);+ const hasFail = outputResults(checks, jsonOutput, { engine: engine?.kind, db_url_source: dbSource ?? null, run });- // Features teaser (non-JSON, non-failing only)- if (!jsonOutput && !hasFail && engine) {+ // Features teaser (non-JSON, non-failing only; never under the ops deadline)+ if (!jsonOutput && !hasFail && engine && run?.tier !== 'ops') {try {const { featuresTeaserForDoctor } = await import('./features.ts');const teaser = await featuresTeaserForDoctor(engine);@@ -531,7 +549,7 @@ export function doctorProgressOptions(jsonOutput: boolean) {function outputResults(checks: Check[],json: boolean,- extras?: { engine?: 'postgres' | 'pglite'; db_url_source?: DbUrlSource | null },+ extras?: { engine?: 'postgres' | 'pglite'; db_url_source?: DbUrlSource | null; run?: DoctorRunSummary },): boolean {// v0.41.19.0 — render goes through computeDoctorReport so the human// output, JSON output, and remote MCP envelope all share one shape.@@ -595,6 +613,7 @@ function outputResults(console.log(`Ops checks: ${report.category_scores.ops}/100`);console.log(`Meta checks: ${report.category_scores.meta}/100`);if (brainScoreLine) console.log(brainScoreLine);+ if (report.tier) console.log(`Tier: ${report.tier}, ${report.complete ? 'complete' : `incomplete (unknown: ${report.unknown_sections!.join(', ')})`}, ${report.elapsed_ms} ms${report.budget_ms ? ` of ${report.budget_ms} ms` : ''}`);console.log('');if (hasFail) {diff --git a/src/commands/doctor/brain-health-bands.ts b/src/commands/doctor/brain-health-bands.tsnew file mode 100644index 0000000000..9b2a2d09ad--- /dev/null+++ b/src/commands/doctor/brain-health-bands.ts@@ -0,0 +1,64 @@+/**+ * #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';++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 };+ /** 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] = 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 };+ }),+ ]);+ const bands = { capacity: { band: capacity.capacity, days: capacity.days, max_pct_band: capacity.max_pct_band, forecast: capacity.forecast }, write_failures: failures };+ 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');+ return { schema_version: 1, status: attention ? 'attention' : unknown ? 'unknown' : 'ok', ...bands, host_command: ['gbrain', 'doctor', '--tier', 'ops', '--json'] };+}diff --git a/src/commands/doctor/budget.ts b/src/commands/doctor/budget.tsnew file mode 100644index 0000000000..27e565b072--- /dev/null+++ b/src/commands/doctor/budget.ts@@ -0,0 +1,169 @@+/**+ * #6696 B1: doctor tiers and budgets.+ *+ * `--tier ops|standard|deep` selects which registry entries run (see+ * `DoctorTier` in ./context.ts); `--budget-ms <n>` is one absolute end-to-end+ * deadline that starts before the CLI connects (default 4000 for `ops`, none+ * for the other tiers). Every entry also has its own budget+ * (`doctor.entry_budget_ms`, default 15000; the remaining overall time when+ * that is shorter).+ *+ * An entry past its budget reports each check it emits with the shared unknown+ * convention: `status: 'warn'`, `details.health: 'unknown'`,+ * `details.reason: 'budget'`, `details.exact: false`, `elapsed_ms`. Under+ * `--tier ops` the entry reads through `deadlineEngine`, whose raw statements+ * carry the absolute deadline to the server (a transaction-local+ * `statement_timeout` recomputed after the pool wait, and an abort of the pool+ * wait itself at the deadline), so no doctor backend outlives the report.+ */+import type { BrainEngine } from '../../core/engine.ts';+import { opError } from '../../core/ops/contract.ts';+import type { Check, DoctorReport } from '../doctor.ts';+import { agentFix } from './check-fix.ts';+import type { DoctorTier } from './context.ts';++export const DOCTOR_TIERS: readonly DoctorTier[] = ['ops', 'standard', 'deep'];+/** Default `--budget-ms` for `--tier ops`; the other tiers have no overall deadline unless one is given. */+export const OPS_BUDGET_MS_DEFAULT = 4000;+/** Config key and default of the per-entry budget (standard and deep tiers; ops entries use the overall deadline). */+export const ENTRY_BUDGET_KEY = 'doctor.entry_budget_ms';+export const ENTRY_BUDGET_MS_DEFAULT = 15_000;++/** The deadline of one doctor run: `deadlineAt` is absolute epoch ms, null without an overall budget. */+export interface DoctorDeadline {+ startedAt: number;+ budgetMs: number | null;+ deadlineAt: number | null;+}++/** Thrown (and caught by the runner) when a read starts after the deadline passed. */+export class DoctorBudgetError extends Error {+ readonly code = 'doctor_budget';+ constructor(readonly elapsedMs: number) {+ super(`The doctor budget ran out after ${elapsedMs} ms.`);+ this.name = 'DoctorBudgetError';+ }+}++function flagValue(args: readonly string[], flag: string): string | undefined {+ for (let i = 0; i < args.length; i++) {+ if (args[i] === flag && i + 1 < args.length) return args[i + 1];+ if (args[i].startsWith(`${flag}=`)) return args[i].slice(flag.length + 1);+ }+ return undefined;+}++/** `--tier <t>` (default `standard`); an unknown value is `invalid_params` naming the valid tiers. */+export function parseDoctorTier(args: readonly string[]): DoctorTier {+ const raw = flagValue(args, '--tier');+ if (raw === undefined) return 'standard';+ if ((DOCTOR_TIERS as readonly string[]).includes(raw)) return raw as DoctorTier;+ throw opError('invalid_params', `Unknown doctor tier: ${raw}`, `Valid tiers: ${DOCTOR_TIERS.join(', ')}.`,+ { fix: { argv: ['gbrain', 'doctor', '--tier', 'ops', '--json'], consent: [], actor: 'agent', requires_exclusive: false,+ why: 'The ops tier answers the operational questions (capacity, failures, embedding, sync, compaction, serve build) in seconds.' } });+}++/** `--budget-ms <n>` (a positive integer), else the tier default. */+export function parseBudgetMs(args: readonly string[], tier: DoctorTier): number | null {+ const raw = flagValue(args, '--budget-ms');+ if (raw === undefined) return tier === 'ops' ? OPS_BUDGET_MS_DEFAULT : null;+ const n = Number(raw);+ if (!Number.isSafeInteger(n) || n < 1) {+ throw opError('invalid_params', `--budget-ms must be a positive integer number of milliseconds (got ${raw}).`, 'Example: --budget-ms 4000.');+ }+ return n;+}++/** The deadline of a run starting now (call it before connecting). */+export function startDoctorDeadline(args: readonly string[], now = Date.now()): DoctorDeadline {+ const budgetMs = parseBudgetMs(args, parseDoctorTier(args));+ return { startedAt: now, budgetMs, deadlineAt: budgetMs === null ? null : now + budgetMs };+}++/** Whether a registry entry runs at `tier` (`standard` includes `ops`; `deep` includes both). */+export function entryRunsAt(entryTier: DoctorTier | undefined, tier: DoctorTier): boolean {+ const own = entryTier ?? 'standard';+ if (tier === 'ops') return own === 'ops';+ if (tier === 'standard') return own !== 'deep';+ return true;+}++/**+ * The engine an ops entry reads through: every raw statement carries the+ * absolute deadline (server-side bound recomputed after the pool wait; the pool+ * wait aborts at the deadline). A statement that would start after the deadline+ * is not sent. PGLite has one in-process connection and no other session to wait+ * on, so it is returned as it is.+ */+export function deadlineEngine(engine: BrainEngine, deadline: DoctorDeadline): BrainEngine {+ const deadlineAt = deadline.deadlineAt;+ if (deadlineAt === null || engine.kind !== 'postgres') return engine;+ return new Proxy(engine, { get(target, key) {+ if (key === 'executeRaw') return async (sql: string, params?: unknown[], opts?: { signal?: AbortSignal; timeoutMs?: number }) => {+ const left = deadlineAt - Date.now();+ if (left <= 0) throw new DoctorBudgetError(Date.now() - deadline.startedAt);+ const signal = opts?.signal ? AbortSignal.any([opts.signal, AbortSignal.timeout(left)]) : AbortSignal.timeout(left);+ return target.executeRaw(sql, params, { signal, timeoutMs: Math.min(left, opts?.timeoutMs ?? left), deadlineAt });+ };+ const value = Reflect.get(target, key, target);+ return typeof value === 'function' ? value.bind(target) : value;+ } });+}++const EXPIRED: unique symbol = Symbol('doctor_budget_expired');++/** Resolves `work`, or `EXPIRED` once `ms` passes (the work keeps running; its result is dropped). */+export async function raceBudget<T>(work: Promise<T>, ms: number): Promise<T | typeof EXPIRED> {+ let timer: ReturnType<typeof setTimeout> | undefined;+ const expiry = new Promise<typeof EXPIRED>((resolve) => { timer = setTimeout(() => resolve(EXPIRED), Math.max(0, ms)); });+ try {+ return await Promise.race([work, expiry]);+ } finally {+ if (timer) clearTimeout(timer);+ }+}+export { EXPIRED as BUDGET_EXPIRED };+export type BudgetExpired = typeof EXPIRED;++/** Whether a raced result is the budget's expiry marker. */+export function budgetExpired(value: unknown): value is BudgetExpired {+ return value === EXPIRED;+}++/** One check an entry could not finish within its budget, in the shared unknown convention. */+export function budgetUnknownCheck(name: string, elapsedMs: number, budgetMs: number): Check {+ return {+ name, status: 'warn', elapsed_ms: elapsedMs,+ message: `Not finished within the doctor budget (${budgetMs} ms). Health is unknown, not clear; rerun this check alone: gbrain doctor --only ${name} --json`,+ details: { health: 'unknown', reason: 'budget', exact: false, elapsed_ms: elapsedMs, budget_ms: budgetMs },+ fix: agentFix(['gbrain', 'doctor', '--only', name, '--json'], 'Runs only this check, without the deadline of a full run; read-only.', name),+ };+}++/** An ops section skipped by design on PGLite: info, so the ops report stays complete. */+export function opsNotApplicableCheck(name: string): Check {+ return {+ name, status: 'ok', severity: 'info', readiness_state: 'not_applicable', elapsed_ms: 0,+ message: 'Not applicable to the ops tier on PGLite (it reads only counters, config and catalog there); run gbrain doctor for this check.',+ details: { health: 'not_applicable', reason: 'pglite_ops_tier', exact: true },+ };+}++/** Whether a check is an over-budget unknown (the ops report's `unknown_sections`). */+export function isBudgetUnknown(check: Pick<Check, 'details'>): boolean {+ return check.details?.health === 'unknown' && check.details?.reason === 'budget';+}++/** #6696 B1: what the report says about the run's tier and deadline (`--tier` / `--budget-ms` given). */+export interface DoctorRunSummary { tier: DoctorTier; startedAt: number; budgetMs: number | null }++export function tierFields(checks: Check[], run: DoctorRunSummary): Pick<DoctorReport, 'tier' | 'complete' | 'unknown_sections' | 'elapsed_ms' | 'budget_ms'> {+ const unknown = checks.filter((c) => c.status !== 'ok' && c.details?.health === 'unknown').map((c) => c.name);+ return { tier: run.tier, complete: unknown.length === 0, unknown_sections: unknown, elapsed_ms: Date.now() - run.startedAt, budget_ms: run.budgetMs };+}++/** The run summary a report carries: only when the caller chose a tier or a budget, so default output keeps its shape. */+export function doctorRunSummary(args: readonly string[], deadline: DoctorDeadline): DoctorRunSummary | undefined {+ if (!args.some((a) => a === '--tier' || a.startsWith('--tier=') || a === '--budget-ms' || a.startsWith('--budget-ms='))) return undefined;+ return { tier: parseDoctorTier(args), startedAt: deadline.startedAt, budgetMs: deadline.budgetMs };+}diff --git a/src/commands/doctor/checks/db-connection.ts b/src/commands/doctor/checks/db-connection.tsindex ead18da7ac..7a5f002910 100644--- a/src/commands/doctor/checks/db-connection.ts+++ b/src/commands/doctor/checks/db-connection.ts@@ -21,6 +21,7 @@ import type { Check } from '../../doctor.ts';import { classifyPgAccessError } from '../../../core/pg-access-classify.ts';import { dbRepairRecurrenceCheck } from './engine-fit.ts';import { STOP_DOCTOR, connectedEngine, type DoctorContext, type DoctorEntry } from '../context.ts';+import { DoctorBudgetError, budgetUnknownCheck } from '../budget.ts';async function runPgliteDataDir(ctx: DoctorContext): Promise<Check[]> {const { args, engine, fastMode, progress } = ctx;@@ -189,7 +190,10 @@ async function runOfflineConnection(ctx: DoctorContext): Promise<Check[]> {// whether a URL exists (env or config-file) — the caller simply// skipped the connection. When null, there really is no config// anywhere.- if (!fastMode && dbSource && connectError !== undefined) {+ if (connectError instanceof DoctorBudgetError) {+ // #6696 B1: the connect was still pending at the run's deadline: unknown, not an outage.+ checks.push(budgetUnknownCheck('connection', connectError.elapsedMs, ctx.deadline?.budgetMs ?? connectError.elapsedMs));+ } else if (!fastMode && dbSource && connectError !== undefined) {// 2c-bis: a REAL connect failure — synthesize the classified check so// `checks[name=="connection"]` exists in every failure shape.checks.push(classifiedConnectionCheck(connectError, dbSource));@@ -268,9 +272,19 @@ async function runConnection(ctx: DoctorContext): Promise<Check[]> {// 3. Connectionprogress.heartbeat('connection');try {- const stats = await engine.getStats();- checks.push({ name: 'connection', status: 'ok', message: `Connected, ${stats.page_count} pages` });+ // #6696 B1: the ops tier proves the round trip only; the page count is a full count the deadline does not afford.+ if (ctx.tier === 'ops') {+ await engine.executeRaw('SELECT 1 AS ok');+ checks.push({ name: 'connection', status: 'ok', message: 'Connected (ops tier: page count not read).' });+ } else {+ const stats = await engine.getStats();+ checks.push({ name: 'connection', status: 'ok', message: `Connected, ${stats.page_count} pages` });+ }} catch (e: unknown) {+ // A round trip the ops deadline ended (a saturated pool, a blocked server) is unknown, not a classified outage.+ const deadlineAt = ctx.deadline?.deadlineAt;+ if (e instanceof DoctorBudgetError) throw e;+ if (ctx.tier === 'ops' && deadlineAt != null && Date.now() >= deadlineAt) throw new DoctorBudgetError(Date.now() - ctx.deadline!.startedAt);// db-availability loop (2c): classified + redacted, with the fix hint.checks.push(classifiedConnectionCheck(e));progress.finish();diff --git a/src/commands/doctor/checks/graph-health.ts b/src/commands/doctor/checks/graph-health.tsindex b0467d1af4..ee1d51e914 100644--- a/src/commands/doctor/checks/graph-health.ts+++ b/src/commands/doctor/checks/graph-health.ts@@ -13,8 +13,9 @@ import { quarantineFilterFragment } from '../../../core/quarantine.ts';import { entityTypePredicateSql, resolveEntityTypes } from '../../../core/schema-pack/entity-types.ts';import { MIN_ENTITY_PAGES_FOR_COVERAGE } from '../../../core/types.ts';import type { Check } from '../../doctor.ts';-import { connectedEngine, type DoctorContext, type DoctorEntry } from '../context.ts';-import { brainScorePlanFix, checkError } from '../check-fix.ts';+import { connectedEngine, type DoctorContext, type DoctorEntry, doctorHealth } from '../context.ts';+import { agentFix, brainScorePlanFix, checkError } from '../check-fix.ts';+import { ORPHAN_FULL_SCAN_KEY, countLivePages, estimateOrphanRatio, orphanFullScanMaxPages, type OrphanEstimate } from './orphan-estimate.ts';async function runGraphCoverage(ctx: DoctorContext): Promise<Check[]> {const { progress } = ctx;@@ -30,7 +31,7 @@ async function runGraphCoverage(ctx: DoctorContext): Promise<Check[]> {// condition is a false positive. Closes #530.progress.heartbeat('graph_coverage');try {- const health = await engine.getHealth();+ const health = await doctorHealth(ctx);// #4772: the entity types come from the active schema pack(s), per source,// through the same policy getHealth binds. A pack that does not load is a// warn below, never a legacy-list reading.@@ -194,6 +195,13 @@ async function runOrphanRatio(ctx: DoctorContext): Promise<Check[]> {message: `Vacuous: ${entityCount} entity pages (<100). Orphan ratio not meaningful at this scale.`,});} else {+ // #6696 B1: above the cutoff the full anti-join belongs to --tier deep; the standard tier estimates from a sample.+ const livePages = ctx.tier === 'deep' ? 0 : await countLivePages(engine, srcId);+ const cutoff = ctx.tier === 'deep' ? Infinity : await orphanFullScanMaxPages(engine);+ if (livePages > cutoff) {+ checks.push(estimatedOrphanRatioCheck(await estimateOrphanRatio(engine, livePages, srcId), cutoff, srcId));+ return checks;+ }// F7 (Codex): under EXPLICIT --source, an operator deliberately asked// about one source — answer it even below 100 entities, with a// low-scale caveat, instead of swallowing a real per-source failure@@ -240,6 +248,19 @@ async function runOrphanRatio(ctx: DoctorContext): Promise<Check[]> {return checks;}+/** The standard tier's sampled orphan ratio: same thresholds, labelled an estimate, with the deep-tier command for the exact figure. */+function estimatedOrphanRatioCheck(est: OrphanEstimate, cutoff: number, srcId: string | undefined): Check {+ const pct = (est.ratio * 100).toFixed(0);+ const deep = ['gbrain', 'doctor', '--tier', 'deep', '--only', 'orphan_ratio', ...(srcId ? ['--source', srcId] : []), '--json'];+ const details = { exact: false, estimated: true, ...est, full_scan_max_pages: cutoff, config_key: ORPHAN_FULL_SCAN_KEY, exact_command: deep.join(' ') };+ const message = `Orphan ratio about ${pct}%${srcId ? ` in source '${srcId}'` : ''} (estimated: ${est.sample_orphans}/${est.sample_linkable} linkable pages in a `+ + `${est.sample_pages}-page sample of ${est.live_pages} live pages; the full scan runs above ${cutoff} pages only with --tier deep: ${deep.join(' ')}).`;+ if (est.ratio <= 0.5) return { name: 'orphan_ratio', status: 'ok', message, details };+ return { name: 'orphan_ratio', status: est.ratio > 0.8 ? 'fail' : 'warn', details,+ message: `${message} Run: gbrain extract links --by-mention --source db${srcId ? ` --source-id ${srcId}` : ''} (auto-links entity mentions in body text).`,+ fix: agentFix(deep, 'Read-only: the exact orphan ratio from the full scan, before acting on an estimate.', 'orphan_ratio') };+}+export const orphanRatioEntry: DoctorEntry = {name: 'orphan_ratio',emits: ['orphan_ratio'],@@ -308,7 +329,6 @@ export const timelineHistoryEntry: DoctorEntry = {'persistence_request_growth','persistence_write_stall','lost_caller_writes',- 'persistence_terminal_failures','persistence_session_timeouts','connector_held_items','git_held_files',diff --git a/src/commands/doctor/checks/managed-sync-movement.ts b/src/commands/doctor/checks/managed-sync-movement.tsindex 03b8439a18..5d44b10fa2 100644--- a/src/commands/doctor/checks/managed-sync-movement.ts+++ b/src/commands/doctor/checks/managed-sync-movement.ts@@ -44,4 +44,5 @@ async function runManagedSyncMovementCheck(ctx: DoctorContext): Promise<Check[]>return checks;}-export const managedSyncMovementEntry: DoctorEntry = { name: 'managed_sync_not_moving', emits: ['managed_sync_not_moving'], run: runManagedSyncMovementCheck };+/** #6696 B1: an ops section (sync cursor movement and age); it reads request and checkpoint tables, so on PGLite the ops tier skips it. */+export const managedSyncMovementEntry: DoctorEntry = { name: 'managed_sync_not_moving', emits: ['managed_sync_not_moving'], tier: 'ops', opsPglite: 'not_applicable', run: runManagedSyncMovementCheck };diff --git a/src/commands/doctor/checks/ops-sections.ts b/src/commands/doctor/checks/ops-sections.tsnew file mode 100644index 0000000000..2d1d7b3842--- /dev/null+++ b/src/commands/doctor/checks/ops-sections.ts@@ -0,0 +1,116 @@+/**+ * #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+ * 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';++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[]> {+ 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 } }));+ }+ return checks;+}++export const receiptCompactionEntry: DoctorEntry = {+ name: 'receipt_compaction',+ emits: ['receipt_compaction'],+ tier: 'ops',+ run: runReceiptCompaction,+};++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 --git a/src/commands/doctor/checks/orphan-estimate.ts b/src/commands/doctor/checks/orphan-estimate.tsnew file mode 100644index 0000000000..24ffb418e5--- /dev/null+++ b/src/commands/doctor/checks/orphan-estimate.ts@@ -0,0 +1,58 @@+/**+ * #6696 B1: `orphan_ratio` without the full anti-join on large brains.+ *+ * The full scan (`findOrphans`: every live page against both link directions)+ * takes most of a default doctor run on a 61k-page brain. Above+ * `doctor.orphan_ratio.full_scan_max_pages` live pages (default 50,000) the+ * standard tier estimates the ratio from a `TABLESAMPLE SYSTEM` page sample of+ * about `SAMPLE_TARGET` pages, with the same islanded predicate (no live inbound+ * and no live outbound link), the same quarantine flag, slug exclusions and+ * connector-render exclusion; `--tier deep` runs the full scan.+ */+import type { BrainEngine } from '../../../core/engine.ts';+import { loadOrphanPolicyOverrides } from '../../../core/orphan-policy.ts';+import { quarantineFilterFragment } from '../../../core/quarantine.ts';+import { CONNECTOR_RENDER_TYPES, loadConnectorSourceIds, shouldExclude } from '../../orphans.ts';++export const ORPHAN_FULL_SCAN_KEY = 'doctor.orphan_ratio.full_scan_max_pages';+export const ORPHAN_FULL_SCAN_MAX_PAGES_DEFAULT = 50_000;+export const SAMPLE_TARGET = 2000;++/** The live-page cutoff above which the standard tier estimates (a positive integer config value, else the default). */+export async function orphanFullScanMaxPages(engine: BrainEngine): Promise<number> {+ const raw = await engine.getConfig(ORPHAN_FULL_SCAN_KEY).catch(() => null);+ const n = raw === null ? NaN : Number(raw);+ return Number.isSafeInteger(n) && n > 0 ? n : ORPHAN_FULL_SCAN_MAX_PAGES_DEFAULT;+}++export async function countLivePages(engine: BrainEngine, sourceId?: string): Promise<number> {+ const rows = await engine.executeRaw<{ n: string }>(`SELECT count(*)::text AS n FROM pages WHERE deleted_at IS NULL${sourceId ? ' AND source_id = $1' : ''}`,+ sourceId ? [sourceId] : []);+ return Number(rows[0]?.n ?? 0);+}++export interface OrphanEstimate {+ ratio: number;+ sample_pages: number;+ sample_linkable: number;+ sample_orphans: number;+ sample_percent: number;+ live_pages: number;+}++export async function estimateOrphanRatio(engine: BrainEngine, livePages: number, sourceId?: string): Promise<OrphanEstimate> {+ const percent = Math.min(100, Math.max(0.01, (SAMPLE_TARGET / Math.max(livePages, 1)) * 100));+ const rows = await engine.executeRaw<{ slug: string; type: string | null; source_id: string; quarantined: boolean; islanded: boolean }>(+ `SELECT p.slug, p.type, p.source_id, (NOT ${quarantineFilterFragment('p')}) AS quarantined,+ (NOT EXISTS (SELECT 1 FROM links l JOIN pages src ON src.id = l.from_page_id WHERE l.to_page_id = p.id AND src.deleted_at IS NULL)+ AND NOT EXISTS (SELECT 1 FROM links l JOIN pages tgt ON tgt.id = l.to_page_id WHERE l.from_page_id = p.id AND tgt.deleted_at IS NULL)) AS islanded+ FROM pages p TABLESAMPLE SYSTEM (${percent.toFixed(4)})+ WHERE p.deleted_at IS NULL${sourceId ? ' AND p.source_id = $1' : ''}`,+ sourceId ? [sourceId] : []);+ const overrides = await loadOrphanPolicyOverrides(engine);+ const connectors = await loadConnectorSourceIds(engine);+ const linkable = rows.filter((r) => !shouldExclude(r.slug, overrides, r) && !(connectors.has(r.source_id) && !!r.type && CONNECTOR_RENDER_TYPES.has(r.type)));+ const orphans = linkable.filter((r) => r.islanded).length;+ return { ratio: linkable.length ? orphans / linkable.length : 0, sample_pages: rows.length, sample_linkable: linkable.length, sample_orphans: orphans,+ sample_percent: Number(percent.toFixed(4)), live_pages: livePages };+}diff --git a/src/commands/doctor/checks/persistence-capacity.ts b/src/commands/doctor/checks/persistence-capacity.tsindex 01358d1d4b..2f51e0c659 100644--- a/src/commands/doctor/checks/persistence-capacity.ts+++ b/src/commands/doctor/checks/persistence-capacity.ts@@ -1,21 +1,18 @@import type { BrainEngine } from '../../../core/engine.ts';import type { Check } from '../../doctor.ts';-import { capacityDiagnostics } from '../../../core/persistence/diagnostics.ts';-import { oneYearCapacity, readJournalLimits } from '../../../core/persistence/limits.ts';+import { oneYearCapacity } from '../../../core/persistence/limits.ts';+import { CUMULATIVE_RESOURCES, capacityVerify, readCapacityView } from '../../../core/persistence/capacity-view.ts';/*** #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).+ * Bounded: one indexed read per counter row (brain plus each principal), through+ * the capacity view the ops tier and `get_brain_health` share (#6696).*/export async function checkPersistenceCapacity(engine: BrainEngine): Promise<Check> {try {- 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 near = capacityDiagnostics(counters, limits)- .filter(row => row.approaching_capacity && (row.resource === 'lifetime_ids' || row.resource === 'terminal_bytes'));+ const view = await readCapacityView(engine);+ const near = view.rows.filter(row => row.approaching_capacity && CUMULATIVE_RESOURCES.has(row.resource));const resources = [];const needed = new Map<string, number>();for (const row of near) {@@ -25,9 +22,12 @@ export async function checkPersistenceCapacity(engine: BrainEngine): Promise<Che}// Every principal shares one brain-wide key, so each key gets the largest value any scope needs.const commands = [...needed].map(([key, value]) => `gbrain config set ${key} ${value}`);- const details = { exact: true, inspected: counters.length, truncated: false, resources, commands };+ 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.' };diff --git a/src/commands/doctor/checks/persistence-consumers.ts b/src/commands/doctor/checks/persistence-consumers.tsindex 53d67e36fc..a9cbdbee3c 100644--- a/src/commands/doctor/checks/persistence-consumers.ts+++ b/src/commands/doctor/checks/persistence-consumers.ts@@ -170,5 +170,6 @@ async function runServeBuildDrift(ctx: DoctorContext): Promise<Check[]> {export const serveBuildDriftEntry: DoctorEntry = {name: 'serve_build_drift',emits: ['serve_build_drift'],+ tier: 'ops',run: runServeBuildDrift,};diff --git a/src/commands/doctor/checks/schema-health.ts b/src/commands/doctor/checks/schema-health.tsindex fc710cf1bc..b3a42205f3 100644--- a/src/commands/doctor/checks/schema-health.ts+++ b/src/commands/doctor/checks/schema-health.ts@@ -18,12 +18,11 @@ import { pgliteScaleCheck } from './engine-fit.ts';import { 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 { checkPostgresCancellationDriver } from './postgres-cancellation.ts';import { checkProjectionReadiness } from './projection-readiness.ts';import type { Check } from '../../doctor.ts';import type { BrainEngine } from '../../../core/engine.ts';-import { connectedEngine, type DoctorContext, type DoctorEntry } from '../context.ts';+import { connectedEngine, type DoctorContext, type DoctorEntry, doctorHealth } from '../context.ts';import { embeddingsDisabled } from '../../../core/embedding-disabled.ts';import { quoteIdentifier, resolveActiveEmbeddingColumnFromEngine } from '../../../core/search/embedding-column.ts';import { checkError, infoCheck, keylessEnablementFix } from '../check-fix.ts';@@ -45,9 +44,9 @@ async function runPgvector(ctx: DoctorContext): Promise<Check[]> {checks.push(await pagesUpsertArbiterCheck(engine));checks.push(await checkProjectionReadiness(engine));- // 4a-bis. Managed write capacity (#5470) and parked postcommit effects (#5612).- progress.heartbeat('persistence_capacity');- checks.push(await checkPersistenceCapacity(engine), await checkParkedEffects(engine), await checkWorktreeRefreshStuck(engine));+ // 4a-bis. Parked postcommit effects (#5612); managed write capacity is an ops entry (checks/ops-sections.ts).+ progress.heartbeat('parked_effects');+ checks.push(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));@@ -74,7 +73,6 @@ export const pgvectorEntry: DoctorEntry = {'postgres_cancellation_driver','pages_upsert_arbiter','text_projection_readiness',- 'persistence_capacity','parked_effects','worktree_refresh_stuck','managed_guard_schema_drift',@@ -395,7 +393,7 @@ async function runEmbeddings(ctx: DoctorContext): Promise<Check[]> {checks.push(infoCheck('embeddings', 'Not applicable: embeddings are disabled on this brain (keyword search keeps working).', 'disabled_by_choice', keylessEnablementFix()));return checks;}- const health = await engine.getHealth();+ const health = await doctorHealth(ctx);const pct = (health.embed_coverage * 100).toFixed(0);// Coverage + missing now share one source (the stored vector over// eligible chunks), so the two numbers can no longer contradict eachdiff --git a/src/commands/doctor/context.ts b/src/commands/doctor/context.tsindex 72d3516640..27fc985bab 100644--- a/src/commands/doctor/context.ts+++ b/src/commands/doctor/context.ts@@ -14,6 +14,8 @@ import type { AutoFixReport } from '../../core/dry-fix.ts';import type { createProgress } from '../../core/progress.ts';import type { resolveSkillsDir } from '../check-resolvable.ts';import type { Check } from '../doctor.ts';+import type { DoctorDeadline } from './budget.ts';+import type { BrainHealth } from '../../core/types.ts';/** Returned by an entry to end the run; the checks gathered so far are the result. */export const STOP_DOCTOR: unique symbol = Symbol('STOP_DOCTOR');@@ -72,6 +74,23 @@ export interface DoctorContext {only?: ReadonlySet<string> | null;/** #6696 B1: the tier this run selected (default `standard`). */tier: DoctorTier;+ /** #6696 B1: the run's absolute deadline (absent in tests that build a context by hand). */+ deadline?: DoctorDeadline;+ /** #6696 B2: the remote caller's readable sources (run_doctor tier/only); undefined: brain-wide or `--source`. */+ sourceIds?: string[];+ /** #6696 B1: one `getHealth()` per run, shared by every entry that reads it (`doctorHealth`). */+ healthMemo?: Promise<BrainHealth>;+}++/** #6696 B2: the source scope of a source-aware section: the remote caller's sources, else `--source`, else brain-wide. */+export function doctorSourceIds(ctx: DoctorContext): string[] | undefined {+ return ctx.sourceIds ?? (ctx.orphanRatioSourceId ? [ctx.orphanRatioSourceId] : undefined);+}++/** #6696 B1: the brain health of this run, read once (graph coverage and the embeddings check both use it). */+export function doctorHealth(ctx: DoctorContext): Promise<BrainHealth> {+ ctx.healthMemo ??= connectedEngine(ctx).getHealth();+ return ctx.healthMemo;}/**diff --git a/src/commands/doctor/ops-snapshot.ts b/src/commands/doctor/ops-snapshot.tsnew file mode 100644index 0000000000..d045d9542a--- /dev/null+++ b/src/commands/doctor/ops-snapshot.ts@@ -0,0 +1,38 @@+/**+ * #6696 B2: the full ops snapshot behind `/admin/api/ops` (admin-gated): the+ * doctor ops-tier report and the capacity view, computed at most once per+ * engine every 60 s (in flight included), so a dashboard polling it costs one+ * ops run a minute. A failed run is cached too, so a struggling database is not+ * asked again on every poll.+ */+import type { BrainEngine } from '../../core/engine.ts';+import { readCapacityView, type CapacityView } from '../../core/persistence/capacity-view.ts';+import { buildChecks, computeDoctorReport, type DoctorReport } from '../doctor.ts';+import { startDoctorDeadline } from './budget.ts';++export const OPS_SNAPSHOT_TTL_MS = 60_000;++export interface OpsSnapshot {+ generated_at: string;+ report: DoctorReport;+ capacity: CapacityView | { status: 'unknown'; reason: string };+}++const snapshots = new WeakMap<BrainEngine, { at: number; value: Promise<OpsSnapshot> }>();++export function cachedOpsSnapshot(engine: BrainEngine, now = Date.now()): Promise<OpsSnapshot> {+ const hit = snapshots.get(engine);+ if (hit && now - hit.at < OPS_SNAPSHOT_TTL_MS) return hit.value;+ const value = computeOpsSnapshot(engine);+ snapshots.set(engine, { at: now, value });+ return value;+}++async function computeOpsSnapshot(engine: BrainEngine): Promise<OpsSnapshot> {+ const args = ['--json', '--tier', 'ops'];+ const deadline = startDoctorDeadline(args);+ const checks = await buildChecks(engine, args, undefined, undefined, deadline);+ const capacity = await readCapacityView(engine).catch((error: unknown) => ({ status: 'unknown' as const, reason: error instanceof Error ? error.message : String(error) }));+ return { generated_at: new Date().toISOString(),+ report: computeDoctorReport(checks, { engine: engine.kind, run: { tier: 'ops', startedAt: deadline.startedAt, budgetMs: deadline.budgetMs } }), capacity };+}diff --git a/src/commands/doctor/registry.ts b/src/commands/doctor/registry.tsindex 118498301f..b3c94d439f 100644--- a/src/commands/doctor/registry.ts+++ b/src/commands/doctor/registry.ts@@ -110,7 +110,17 @@ import { behaviorChangesEntry } from './checks/behavior-changes.ts';import { fenceIntegrityEntry } from './checks/fence-integrity.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';@@ -138,6 +148,13 @@ export const DOCTOR_CHECK_REGISTRY: readonly DoctorEntry[] = [dbChecksGateEntry,connectionEntry,connectionGateEntry,+ // #6696 B1: ops sections first (`tier: 'ops'`), so a default run answers them before the slower checks.+ persistenceCapacityEntry,+ terminalFailuresEntry,+ managedSyncMovementEntry,+ receiptCompactionEntry,+ serveBuildDriftEntry,+ schemaPackConsistencyEntry,pgvectorEntry,rlsEntry,schemaVersionEntry,@@ -193,9 +210,7 @@ export const DOCTOR_CHECK_REGISTRY: readonly DoctorEntry[] = [trustScanEntry,trustSourcesUnclaimedEntry,coreMemoryEntry,- managedSyncMovementEntry,persistenceConsumersEntry,- serveBuildDriftEntry,atomHeldFailedEntry,fenceIntegrityEntry,searchModeEntry,@@ -208,6 +223,11 @@ export function doctorCheckNames(): Set<string> {return new Set(DOCTOR_CHECK_REGISTRY.flatMap((e) => e.emits));}+/** #6696 B1: every check an ops-tier entry can emit (what `--tier ops` and `run_doctor` `tier: ops` report). */+export function opsCheckNames(): Set<string> {+ return new Set(DOCTOR_CHECK_REGISTRY.filter((e) => e.tier === 'ops').flatMap((e) => e.emits));+}+/** `--only a,b` / `--only=a,b` (repeatable) → the requested check names, or null when absent. */export function parseOnlyChecks(args: readonly string[]): Set<string> | null {const raw: string[] = [];@@ -248,17 +268,87 @@ function onlyResult(checks: Check[], only: ReadonlySet<string>, stopped: boolean* (the connection lane always runs so its early stops still hold). The run is* one `withGitListingCache` scope, so entries that list the same source* checkout share one `git ls-files` per listing.+ *+ * #6696 B1: `ctx.tier` selects entries (`entryRunsAt`; the connection lane runs+ * at every tier). Each entry runs under its budget: the per-entry budget+ * (`doctor.entry_budget_ms`) clipped to the overall deadline, or under `--tier+ * ops` the overall deadline alone with raw reads bounded on the server+ * (`deadlineEngine`). An entry past its budget reports each check it emits as+ * an unknown; an ops entry that is not applicable on PGLite reports+ * `not_applicable`. Every check carries its entry's `elapsed_ms`.*/export function runDoctorRegistry(ctx: DoctorContext): Promise<Check[]> {return withGitListingCache(async () => {+ const tier = ctx.tier ?? 'standard';+ // Under ops every entry, the connection lane included, reads through the deadline-bound engine.+ if (tier === 'ops' && ctx.engine && ctx.deadline) ctx.engine = deadlineEngine(ctx.engine, ctx.deadline);const checks: Check[] = [];+ let entryBudgetMs: number | null = null;for (const entry of DOCTOR_CHECK_REGISTRY) {if (!selected(entry, ctx.only)) continue;- const result = await entry.run(ctx);- if (result === STOP_DOCTOR) return ctx.only ? onlyResult(checks, ctx.only, true) : checks;- checks.push(...result);+ if (!CONNECTION_LANE.has(entry) && !entryRunsAt(entry.tier, tier)) continue;+ const started = Date.now();+ const emitted = entry.emits.filter((n) => !ctx.only || ctx.only.has(n));+ if (tier === 'ops' && entry.opsPglite === 'not_applicable' && ctx.engine?.kind === 'pglite') {+ checks.push(...emitted.map(opsNotApplicableCheck));+ continue;+ }+ if (entryBudgetMs === null && ctx.engine && !ctx.fastMode && !ctx.connectionFailed && DOCTOR_CHECK_REGISTRY.indexOf(entry) > DOCTOR_CHECK_REGISTRY.indexOf(connectionGateEntry)) {+ entryBudgetMs = await readEntryBudget(ctx);+ }+ const budgetMs = entryBudget(ctx, tier, CONNECTION_LANE.has(entry) ? null : entryBudgetMs, started);+ if (budgetMs !== null && budgetMs <= 0) {+ checks.push(...emitted.map((n) => budgetUnknownCheck(n, 0, ctx.deadline?.budgetMs ?? 0)));+ continue;+ }+ const run = entry.run(ctx)+ .catch((error: unknown): BudgetExpired => { if (error instanceof DoctorBudgetError) return BUDGET_EXPIRED; throw error; });+ const result = budgetMs === null ? await run : await raceBudget(run, budgetMs);+ const elapsed = Date.now() - started;+ if (budgetExpired(result)) {+ checks.push(...emitted.map((n) => budgetUnknownCheck(n, elapsed, budgetMs ?? ctx.deadline?.budgetMs ?? 0)));+ continue;+ }+ if (result === STOP_DOCTOR) {+ // A connect the deadline ended: every check this tier would have run is unknown, so the report says what it does not know.+ if (ctx.connectError instanceof DoctorBudgetError) {+ const at = DOCTOR_CHECK_REGISTRY.indexOf(entry);+ for (const later of DOCTOR_CHECK_REGISTRY.slice(at + 1)) {+ if (CONNECTION_LANE.has(later) || !entryRunsAt(later.tier, tier) || !selected(later, ctx.only)) continue;+ checks.push(...later.emits.filter((n) => !ctx.only || ctx.only.has(n)).map((n) => budgetUnknownCheck(n, ctx.connectError instanceof DoctorBudgetError ? ctx.connectError.elapsedMs : 0, ctx.deadline?.budgetMs ?? 0)));+ }+ }+ return ctx.only ? onlyResult(checks, ctx.only, true) : checks;+ }+ const pastDeadline = ctx.deadline?.deadlineAt != null && Date.now() >= ctx.deadline.deadlineAt;+ checks.push(...result.map((c) => {+ if (pastDeadline && c.details?.health === 'unknown' && c.details.reason === undefined) {+ const unknown = budgetUnknownCheck(c.name, elapsed, ctx.deadline!.budgetMs ?? 0);+ return { ...unknown, details: { ...unknown.details, cause: c.message } };+ }+ return c.elapsed_ms === undefined ? { ...c, elapsed_ms: elapsed } : c;+ }));}ctx.progress.finish();return ctx.only ? onlyResult(checks, ctx.only, false) : checks;});}++/** The time this entry may take: the per-entry budget (not under ops) clipped to the overall deadline; null: unbounded. */+function entryBudget(ctx: DoctorContext, tier: DoctorTier, perEntry: number | null, now: number): number | null {+ const overall = ctx.deadline?.deadlineAt != null ? ctx.deadline.deadlineAt - now : null;+ const own = tier === 'ops' ? null : perEntry;+ if (overall === null) return own;+ return own === null ? overall : Math.min(own, overall);+}++/** `doctor.entry_budget_ms` (a positive integer), else the default; an unreadable config keeps the default. */+async function readEntryBudget(ctx: DoctorContext): Promise<number> {+ try {+ const raw = await ctx.engine!.getConfig(ENTRY_BUDGET_KEY);+ const n = raw === null || raw === undefined ? NaN : Number(raw);+ return Number.isSafeInteger(n) && n > 0 ? n : ENTRY_BUDGET_MS_DEFAULT;+ } catch {+ return ENTRY_BUDGET_MS_DEFAULT;+ }+}diff --git a/src/commands/doctor/remote-tier.ts b/src/commands/doctor/remote-tier.tsnew file mode 100644index 0000000000..16cde7ae83--- /dev/null+++ b/src/commands/doctor/remote-tier.ts@@ -0,0 +1,40 @@+/**+ * #6696 B2: `run_doctor` with `tier` / `only` (admin scope). `tier: 'ops'`+ * runs the ops sections of the local registry on the serving host under one+ * 4 s deadline (observational: the serve's engine is already connected);+ * `only` narrows it, or narrows the focused remote report when none of the+ * names is an ops section. Every source-aware section is confined to the+ * caller's source scope. Nothing here mutates.+ */+import type { OperationContext } from '../../core/ops/contract.ts';+import { sourceScopeOpts } from '../../core/ops/context.ts';+import { invalidParam } from '../../core/ops/op-fix.ts';+import { computeDoctorReport, doctorReportRemote, buildChecks, type DoctorReport } from '../doctor.ts';+import { doctorCheckNames, opsCheckNames } from './registry.ts';+import { startDoctorDeadline } from './budget.ts';++export async function runRemoteDoctorTier(ctx: OperationContext, p: Record<string, unknown>): Promise<DoctorReport> {+ if (p.tier !== undefined && p.tier !== 'ops') {+ throw invalidParam(ctx, 'run_doctor', 'tier', 'run_doctor: tier must be "ops" (the standard and deep tiers run only on the brain host: gbrain doctor --tier deep).', { example: 'ops' });+ }+ const only = p.only === undefined ? null : Array.isArray(p.only) && p.only.every((n) => typeof n === 'string' && n.length > 0) ? p.only as string[] : undefined;+ if (only === undefined || (only && only.length === 0)) throw invalidParam(ctx, 'run_doctor', 'only', 'run_doctor: only must be a non-empty array of check names.', { example: ['persistence_capacity'] });+ const known = doctorCheckNames();+ const unknown = (only ?? []).filter((n) => !known.has(n));+ if (unknown.length) throw invalidParam(ctx, 'run_doctor', 'only', `run_doctor: unknown check ${unknown.join(', ')}. Valid names: ${[...known].sort().join(', ')}.`, { example: ['persistence_capacity'] });++ const scope = sourceScopeOpts(ctx);+ const sourceIds = scope.sourceIds ?? (scope.sourceId ? [scope.sourceId] : undefined);+ const transport = ctx.remote === false ? 'cli' : ctx.transport ?? 'http';+ const render = { transport, isCallable: (op: string) => op === 'run_doctor' || op === 'get_brain_health', preapproved: () => false } as const;+ const ops = opsCheckNames();+ if (p.tier === 'ops' || (only && only.every((n) => ops.has(n)))) {+ const args = ['--json', '--tier', 'ops', ...(only ? ['--only', only.join(',')] : [])];+ const deadline = startDoctorDeadline(args);+ const checks = await buildChecks(ctx.engine, args, undefined, undefined, deadline, { sourceIds });+ return computeDoctorReport(checks, { engine: ctx.engine.kind, render, run: { tier: 'ops', startedAt: deadline.startedAt, budgetMs: deadline.budgetMs } });+ }+ const report = await doctorReportRemote(ctx.engine, { sourceIds, remote: ctx.remote, render });+ const kept = report.checks.filter((c) => only!.includes(c.name));+ return computeDoctorReport(kept, { engine: report.engine, render });+}diff --git a/src/commands/doctor/wave-checks.ts b/src/commands/doctor/wave-checks.tsindex 5f3fb98179..46fb2c0fbc 100644--- a/src/commands/doctor/wave-checks.ts+++ b/src/commands/doctor/wave-checks.ts@@ -127,7 +127,7 @@ export const WAVE_CHECKS: readonly WaveCheckSpec[] = [run: async (engine, scope) => (await import('./checks/persistence-requests.ts')).lostCallerWritesCheck(engine, scope.sourceIds),},{- id: 'persistence_terminal_failures', resolution: 'operator', registration: 'wave',+ id: 'persistence_terminal_failures', resolution: 'operator', registration: 'doctor.ts',hostOnly: 'Request ids, roots and recovery records are brain-host persistence state outside any source scope.',count: d => Number(d.count ?? 0),impact: 'A write receipt that did not commit blocks work now (a recovery record or a checkpoint blocker), or an unresolved receipt is a gbrain-defect class',diff --git a/src/commands/orphans.ts b/src/commands/orphans.tsindex 48aeb79b06..809c698291 100644--- a/src/commands/orphans.ts+++ b/src/commands/orphans.ts@@ -52,14 +52,14 @@ export interface OrphanResult {connector_renders_excluded?: number;}-const CONNECTOR_RENDER_TYPES = new Set(['email', 'meeting']);+export const CONNECTOR_RENDER_TYPES = new Set(['email', 'meeting']);/*** #5877: ids of connector-kind sources. Their `email`/`meeting` pages are* leaf renders (participants are raw addresses, never wikilinks), so an* islanded render is expected and is reported apart rather than as an orphan.*/-async function loadConnectorSourceIds(engine: BrainEngine): Promise<Set<string>> {+export async function loadConnectorSourceIds(engine: BrainEngine): Promise<Set<string>> {const rows = await engine.executeRaw<{ id: string; kind: string | null }>(`SELECT id, config->>'kind' AS kind FROM sources`);return new Set(rows.filter(r => isConnectorSourceKind(r.kind)).map(r => r.id));}diff --git a/src/commands/serve-http-admin-api.ts b/src/commands/serve-http-admin-api.tsindex 87e05530af..46890304b7 100644--- a/src/commands/serve-http-admin-api.ts+++ b/src/commands/serve-http-admin-api.ts@@ -341,6 +341,15 @@ function mountAdminOverviewApi(app: Express, ctx: ServeHttpContext): void {}});+ // #6696 B2: the full ops snapshot (doctor ops tier + capacity view), cached 60 s per engine (doctor/ops-snapshot.ts).+ app.get('/admin/api/ops', requireAdmin, async (_req: Request, res: Response) => {+ try {+ res.json(await (await import('./doctor/ops-snapshot.ts')).cachedOpsSnapshot(engine));+ } catch {+ res.status(503).json({ error: 'service_unavailable' });+ }+ });+// Full engine stats. v0.28.10 moved this off /health (which is now liveness// only — see probeLiveness) so dashboards needing page_count / chunk_count// / etc. authenticate as admin and call this endpoint. probeHealth racesdiff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.tsindex 8156ae4422..f5793e5bd1 100644--- a/src/core/behavior-change-notice.ts+++ b/src/core/behavior-change-notice.ts@@ -572,6 +572,9 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText }{ 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.' },+ { 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.' },// 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 --git a/src/core/cli-flag-registry.generated.ts b/src/core/cli-flag-registry.generated.tsindex 8a587978cb..d66c72c249 100644--- a/src/core/cli-flag-registry.generated.ts+++ b/src/core/cli-flag-registry.generated.ts@@ -47,7 +47,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {'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', '--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-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', '--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-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', '--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'],@@ -73,14 +73,14 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {'graph-query': ['--brain', '--depth', '--direction', '--help', '--hop', '--include-foreign', '--json', '--mcp-only', '--source', '--type'],'hook': ['--allow-unverified-remote', '--auto', '--brain', '--branch', '--cached', '--count', '--diff-filter', '--enable', '--end-of-options', '--env', '--get', '--harness', '--help', '--jq', '--json', '--limit', '--name-only', '--others', '--pat-file', '--path', '--porcelain', '--pure', '--quiet', '--remove', '--seat', '--session', '--show-current', '--show-toplevel', '--since', '--source', '--yes'],'import': ['--accept-pending', '--admin-intent', '--allow-empty', '--allow-noncanonical-root', '--apply', '--background', '--brain', '--cached', '--confirm-relocated-root', '--diff-filter', '--dim', '--embedding-dimensions', '--embedding-model', '--empty', '--exclude', '--exclude-standard', '--expected-epoch', '--expected-state', '--explain', '--follow', '--force', '--force-rechunk', '--format', '--fresh', '--help', '--include-gitignored', '--is-shallow-repository', '--json', '--log-noop', '--manifest', '--name-only', '--no-accept-pending', '--no-embed', '--no-embedding', '--no-gpg-sign', '--no-pull', '--no-renames', '--no-verify', '--only', '--others', '--path', '--probe', '--progress-interval', '--progress-json', '--quiet', '--self-transfer', '--show-toplevel', '--skip-failed', '--slugs', '--source', '--source-id', '--stale', '--status', '--supabase', '--timeout', '--to', '--url', '--verify', '--wait', '--workers'],- 'init': ['--access', '--acknowledge-managed', '--adopt', '--all', '--allow-create-db', '--allow-docker', '--apply', '--assign-corpus', '--audit', '--auto', '--background', '--bound-slug-prefixes', '--brain', '--break-lock', '--budget-ms', '--budget-usd', '--chat-model', '--check', '--confirm-relocated-root', '--conflicts', '--content-root', '--db-only', '--dest', '--dim', '--disable', '--drain', '--embedding-dimensions', '--embedding-model', '--enable', '--expand', '--expansion-model', '--expect', '--expect-remote', '--facts', '--fast', '--fix', '--force', '--force-retry', '--from-meetings', '--full', '--git', '--grant-types', '--group-by', '--harness', '--help', '--http', '--id', '--images', '--include-gitignored', '--issuer-url', '--json', '--keep', '--key', '--lanes', '--limit', '--list', '--local-postgres', '--markdown', '--max-usd', '--mcp-only', '--mcp-url', '--migrate-only', '--migration', '--model', '--no-autopilot-install', '--no-autostash', '--no-delegate', '--no-embed', '--no-embedding', '--no-expand', '--no-extract', '--no-git', '--no-llm', '--no-pull', '--no-repair', '--no-schema-pack', '--non-interactive', '--oauth-client-id', '--oauth-client-secret', '--once', '--only', '--page', '--params', '--pat-file', '--path', '--pglite', '--phase', '--plan', '--prefer', '--prefer-postgres', '--preview', '--probe', '--profile', '--provenance', '--providers', '--pull', '--purge', '--push-only', '--query', '--question', '--quiet', '--rebase', '--reference-date', '--remediate', '--remove', '--reset', '--resolve', '--resume', '--retry-failed', '--save', '--schema-pack', '--scope', '--scopes', '--search-mode', '--section', '--self-transfer', '--show-toplevel', '--skip', '--skip-embed-check', '--skip-failed', '--slugs', '--source', '--source-id', '--stale', '--status', '--supabase', '--surface', '--to', '--touchpoint', '--url', '--url-env', '--user', '--version', '--wait', '--warn-only', '--workspace', '--yes'],+ 'init': ['--access', '--acknowledge-managed', '--adopt', '--all', '--allow-create-db', '--allow-docker', '--apply', '--assign-corpus', '--audit', '--auto', '--background', '--bound-slug-prefixes', '--brain', '--break-lock', '--budget-ms', '--budget-usd', '--chat-model', '--check', '--confirm-relocated-root', '--conflicts', '--content-root', '--db-only', '--dest', '--dim', '--disable', '--drain', '--embedding-dimensions', '--embedding-model', '--enable', '--expand', '--expansion-model', '--expect', '--expect-remote', '--facts', '--fast', '--fix', '--force', '--force-retry', '--from-meetings', '--full', '--git', '--grant-types', '--group-by', '--harness', '--help', '--http', '--id', '--images', '--include-gitignored', '--issuer-url', '--json', '--keep', '--key', '--lanes', '--limit', '--list', '--local-postgres', '--markdown', '--max-usd', '--mcp-only', '--mcp-url', '--migrate-only', '--migration', '--model', '--no-autopilot-install', '--no-autostash', '--no-delegate', '--no-embed', '--no-embedding', '--no-expand', '--no-extract', '--no-git', '--no-llm', '--no-pull', '--no-repair', '--no-schema-pack', '--non-interactive', '--oauth-client-id', '--oauth-client-secret', '--once', '--only', '--page', '--params', '--pat-file', '--path', '--pglite', '--phase', '--plan', '--prefer', '--prefer-postgres', '--preview', '--probe', '--profile', '--provenance', '--providers', '--pull', '--purge', '--push-only', '--query', '--question', '--quiet', '--rebase', '--reference-date', '--remediate', '--remove', '--reset', '--resolve', '--resume', '--retry-failed', '--save', '--schema-pack', '--scope', '--scopes', '--search-mode', '--section', '--self-transfer', '--show-toplevel', '--skip', '--skip-embed-check', '--skip-failed', '--slugs', '--source', '--source-id', '--stale', '--status', '--supabase', '--surface', '--tier', '--to', '--touchpoint', '--url', '--url-env', '--user', '--version', '--wait', '--warn-only', '--workspace', '--yes'],'integrations': ['--auto', '--brain', '--dry-run', '--help', '--json', '--overwrite', '--refresh', '--source', '--target'],'integrity': ['--accept-pending', '--auto', '--backend', '--background', '--brain', '--confidence', '--cost', '--dry-run', '--explain', '--follow', '--fresh', '--help', '--json', '--limit', '--no-accept-pending', '--probe', '--progress-interval', '--progress-json', '--quiet', '--review-lower', '--skip-bare-tweet', '--skip-urls', '--source', '--supabase', '--timeout', '--type', '--url', '--wait'],'jobs': ['--abbrev-ref', '--access', '--acknowledge-managed', '--add', '--admin-intent', '--aliases', '--all', '--allow-empty', '--allow-shell-jobs', '--allowed-operations', '--apply', '--asof', '--auto', '--background', '--backoff-delay', '--backoff-jitter', '--backoff-type', '--batch-size', '--bound-slug-prefixes', '--brain', '--break-lock', '--by-mention', '--cached', '--catch-up', '--check', '--cli-path', '--client', '--cluster-errors', '--concurrency', '--confidence', '--confirm-destructive', '--confirm-quiesced', '--cost-estimate', '--date', '--dated-since', '--days', '--delay', '--detach', '--diff-filter', '--dir', '--drain', '--dry-run', '--embedding-dimensions', '--embedding-model', '--empty', '--entities', '--exclude', '--exclude-standard', '--expect', '--expected-state', '--explain', '--facts', '--federated-read', '--filters', '--fix', '--follow', '--force', '--force-break-lock', '--format', '--fresh', '--from-meetings', '--full', '--full-history', '--fuzzy', '--grammar-diagnostics', '--group', '--hard-deadline', '--health-interval', '--help', '--http', '--id', '--idempotency-key', '--ids', '--images', '--include-deleted', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--include-null-signature', '--infer-dates', '--inject-bootstrap', '--inline', '--input', '--install', '--interval', '--is-ancestor', '--is-shallow-repository', '--job-id', '--job-isolation', '--json', '--kind', '--lanes', '--limit', '--lock-duration-ms', '--log-noop', '--markdown', '--max-age', '--max-attempts', '--max-cost', '--max-cost-usd', '--max-crashes', '--max-rss', '--max-sources', '--max-stalled', '--max-usd', '--max-waiting', '--mcp-only', '--min-context', '--missing-path', '--model', '--multimodal', '--name-only', '--ner', '--nice', '--no-auto-embed', '--no-autopilot-install', '--no-bulk', '--no-confirm', '--no-delegate', '--no-embed', '--no-extract', '--no-gpg-sign', '--no-hard-deadline', '--no-inject', '--no-lanes', '--no-llm', '--no-pull', '--no-renames', '--no-repair', '--no-schema-pack', '--no-verify', '--no-worker', '--non-interactive', '--now', '--older-than', '--once', '--only', '--order', '--others', '--output', '--override-disabled', '--pace', '--pace-max-concurrency', '--pack', '--page', '--parallel', '--params', '--path', '--pause', '--phase', '--pid-file', '--priority', '--probe', '--prune-orphans', '--purge', '--queue', '--queue-only', '--quiet', '--reason', '--rebuild', '--recent', '--redact-secrets', '--reenrich-after', '--refresh-ms', '--refresh-operations', '--replace', '--repo', '--reset-checkpoint', '--resume', '--retry-failed', '--retry-held', '--review-lower', '--row', '--scopes', '--segment-limit', '--select', '--serial', '--session', '--show-toplevel', '--sigkill-rescue', '--since', '--skip-bare-tweet', '--skip-failed', '--skip-urls', '--sleep', '--slug', '--slugs', '--source', '--source-id', '--sources', '--src-subpath', '--stale', '--status', '--strategy', '--surface', '--swap-only', '--target', '--thin', '--thin-threshold', '--timeout', '--timeout-ms', '--to', '--trust', '--type', '--types', '--uninstall', '--updated-after', '--url', '--user', '--vectors', '--verbose', '--verify', '--version', '--watch', '--wedge-rescue', '--workers', '--working-tree', '--yes'],'lint': ['--abbrev-ref', '--accept-pending', '--adopt-slug-path', '--audit', '--autostash', '--background', '--brain', '--branch', '--cached', '--client', '--confirm-relocated-root', '--conflicts', '--dry-run', '--enable', '--exclude', '--expect-remote', '--expected-epoch', '--expected-revision', '--explain', '--ff-only', '--file', '--fix', '--follow', '--force', '--full', '--get', '--git-dir', '--git-path', '--grammar-diagnostics', '--hard', '--help', '--id', '--is-inside-work-tree', '--json', '--local', '--local-env-vars', '--manifest', '--no-accept-pending', '--no-autostash', '--no-cron', '--no-pull', '--no-tags', '--no-verify', '--only', '--pat-file', '--path', '--prefer', '--preview', '--probe', '--progress-interval', '--progress-json', '--pull', '--purge', '--push-only', '--quiet', '--rebase', '--require-clean', '--resolve', '--scopes', '--self-transfer', '--short', '--show-toplevel', '--slug', '--source', '--source-id', '--timeout', '--unset-all', '--wait', '--yes'],'loops': ['--all', '--as-of', '--brain', '--fail-fast', '--help', '--json', '--note', '--source', '--stale-ok', '--status', '--tools-json', '--top', '--type'],'lsd': ['--brain', '--force-resume', '--help', '--json', '--judge-model', '--limit', '--list-runs', '--max-cost', '--max-far-set', '--max-ideas-per-judge-call', '--max-usd', '--no-save', '--resume', '--save', '--source', '--strict-budget', '--yes'],- 'maintain': ['--adopt-columns', '--adopt-permissions', '--all', '--apply', '--assign-corpus', '--audit', '--background', '--brain', '--break-lock', '--budget-ms', '--by-mention', '--cached', '--catch-up', '--concurrency', '--conflicts', '--contacts-dir', '--content-audit', '--count', '--detach', '--dim', '--dir', '--drain', '--dry-run', '--enable', '--expect', '--expected-revision', '--explain', '--facts', '--fast', '--fix', '--follow', '--force', '--force-retry', '--force-schema', '--format', '--from-meetings', '--full', '--group-by', '--hard-deadline', '--harness', '--help', '--http', '--id', '--images', '--include-ambiguous', '--include-flagged', '--include-frontmatter', '--include-gitignored', '--include-repairs', '--index-audit', '--infer-dates', '--install', '--json', '--kind', '--lang', '--left-right', '--link-source', '--link-type', '--locks', '--markdown', '--max-cost', '--max-cost-usd', '--max-jobs', '--max-rss', '--max-usd', '--migrate-legacy', '--migrate-only', '--multimodal', '--name', '--ner', '--no-autopilot-install', '--no-capture', '--no-delegate', '--no-embed', '--no-pull', '--once', '--only', '--operations', '--pack', '--page', '--parallel', '--params', '--path', '--pglite', '--phase', '--pid-file', '--plan', '--porcelain', '--prefer', '--preview', '--probe', '--probe-pglite', '--project', '--providers', '--prune-orphans', '--query', '--queue', '--reauth', '--rebuild', '--regenerate', '--remediate', '--remediation-plan', '--remove', '--remove-core', '--request-id', '--reset', '--reset-default', '--resume', '--retry-failed', '--reverse', '--safe', '--scope', '--scopes', '--show-current', '--show-toplevel', '--since', '--skills-dir', '--skip-failed', '--slot', '--slug', '--slugs', '--source', '--source-id', '--sources', '--stale', '--status', '--supabase', '--symbol-kind', '--takes-holders', '--target', '--target-score', '--to', '--token', '--top-k', '--type', '--url-env', '--user', '--verbose', '--version', '--window', '--workers', '--yes'],+ 'maintain': ['--adopt-columns', '--adopt-permissions', '--all', '--apply', '--assign-corpus', '--audit', '--background', '--brain', '--break-lock', '--budget-ms', '--by-mention', '--cached', '--catch-up', '--concurrency', '--conflicts', '--contacts-dir', '--content-audit', '--count', '--detach', '--dim', '--dir', '--drain', '--dry-run', '--enable', '--expect', '--expected-revision', '--explain', '--facts', '--fast', '--fix', '--follow', '--force', '--force-retry', '--force-schema', '--format', '--from-meetings', '--full', '--group-by', '--hard-deadline', '--harness', '--help', '--http', '--id', '--images', '--include-ambiguous', '--include-flagged', '--include-frontmatter', '--include-gitignored', '--include-repairs', '--index-audit', '--infer-dates', '--install', '--json', '--kind', '--lang', '--left-right', '--link-source', '--link-type', '--locks', '--markdown', '--max-cost', '--max-cost-usd', '--max-jobs', '--max-rss', '--max-usd', '--migrate-legacy', '--migrate-only', '--multimodal', '--name', '--ner', '--no-autopilot-install', '--no-capture', '--no-delegate', '--no-embed', '--no-pull', '--once', '--only', '--operations', '--pack', '--page', '--parallel', '--params', '--path', '--pglite', '--phase', '--pid-file', '--plan', '--porcelain', '--prefer', '--preview', '--probe', '--probe-pglite', '--project', '--providers', '--prune-orphans', '--query', '--queue', '--reauth', '--rebuild', '--regenerate', '--remediate', '--remediation-plan', '--remove', '--remove-core', '--request-id', '--reset', '--reset-default', '--resume', '--retry-failed', '--reverse', '--safe', '--scope', '--scopes', '--show-current', '--show-toplevel', '--since', '--skills-dir', '--skip-failed', '--slot', '--slug', '--slugs', '--source', '--source-id', '--sources', '--stale', '--status', '--supabase', '--symbol-kind', '--takes-holders', '--target', '--target-score', '--tier', '--to', '--token', '--top-k', '--type', '--url-env', '--user', '--verbose', '--version', '--window', '--workers', '--yes'],'mcp': ['--admin-token-file', '--agent', '--arg', '--bearer-token-env-var', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--budget-usd-per-day', '--client', '--credentials-file', '--credentials-out', '--delegate', '--delegated-namespace', '--delegated-slug-prefixes', '--dry-run', '--enable-dcr', '--federated-read', '--flow', '--force', '--funnel', '--harness', '--header', '--help', '--if-version', '--install', '--issuer-url', '--json', '--limit', '--mcp-only', '--mcp-url', '--no-install', '--no-service', '--no-tailscale', '--oauth-client-id', '--oauth-client-secret', '--oauth-request', '--port', '--profile', '--queue', '--redirect-uri', '--remove', '--resume', '--root', '--scope', '--scopes', '--skills', '--source', '--status', '--surface', '--timeout-ms', '--token', '--token-endpoint-auth-method', '--token-ttl', '--url', '--yes'],'migrate': ['--accept-pending', '--admin-intent', '--all', '--apply', '--background', '--batch-size', '--brain', '--catch-up', '--dim', '--drain-timeout', '--dry-run', '--embedding-dimensions', '--embedding-model', '--expect', '--expected-epoch', '--expected-state', '--explain', '--facts', '--follow', '--force', '--force-retry', '--full', '--harness', '--help', '--ignore-env-override', '--images', '--include-null-signature', '--json', '--locks', '--manifest', '--max-cost', '--max-cost-usd', '--max-usd', '--no-accept-pending', '--no-embed', '--no-embedding', '--no-migrate', '--non-interactive', '--only', '--pace', '--pace-max-concurrency', '--path', '--pglite', '--plan', '--priority', '--probe', '--progress-interval', '--progress-json', '--quiet', '--replace', '--reranker', '--resume', '--retarget', '--rollback-to-source', '--scope', '--skip-verify', '--slugs', '--source', '--stale', '--status', '--timeout', '--to', '--trigger-bypass', '--trust', '--url', '--url-env', '--wait', '--yes'],'models': ['--batch', '--brain', '--concurrent', '--cycles', '--dim', '--dimensions', '--embedding-dimensions', '--embedding-model', '--help', '--json', '--limit', '--max-tokens', '--max-usd', '--output', '--receipt-dir', '--skip', '--slot-a-model', '--slot-b-model', '--slot-c-model', '--slug', '--source', '--status', '--task', '--to', '--yes'],@@ -128,7 +128,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {'status': ['--abbrev-ref', '--acknowledge-managed', '--all', '--allow-empty', '--apply', '--brain', '--break-lock', '--cached', '--concurrency', '--confirm-destructive', '--deadline-ms', '--diff-filter', '--empty', '--exclude', '--exclude-standard', '--fast', '--filters', '--fix', '--force-break-lock', '--format', '--full', '--full-history', '--hard-deadline', '--help', '--include-gitignored', '--include-hidden', '--install', '--interval', '--is-ancestor', '--is-shallow-repository', '--json', '--lanes', '--max-age', '--max-sources', '--mcp-only', '--missing-path', '--name-only', '--no-auto-embed', '--no-bulk', '--no-delegate', '--no-embed', '--no-extract', '--no-gpg-sign', '--no-hard-deadline', '--no-lanes', '--no-llm', '--no-pull', '--no-renames', '--no-repair', '--no-schema-pack', '--no-verify', '--others', '--parallel', '--path', '--priority', '--quiet', '--repo', '--reset-checkpoint', '--retry-failed', '--retry-held', '--section', '--serial', '--show-toplevel', '--skip-failed', '--slugs', '--source', '--source-id', '--src-subpath', '--stale', '--strategy', '--timeout', '--url', '--verify', '--watch', '--workers', '--working-tree', '--yes'],'storage': ['--brain', '--fix', '--help', '--json', '--plan', '--repo', '--restore-only', '--source', '--to'],'sweep': ['--accept-pending', '--apply', '--assign-corpus', '--background', '--batch-limit', '--brain', '--budget-ms', '--delete-brain', '--explain', '--follow', '--help', '--home', '--json', '--no-accept-pending', '--no-delegate', '--once', '--only', '--progress-interval', '--progress-json', '--quiet', '--session', '--source', '--timeout', '--wait'],- 'sync': ['--abbrev-ref', '--accept-pending', '--account', '--acknowledge-managed', '--admin-intent', '--adopt-columns', '--adopt-permissions', '--all', '--allow-empty', '--apply', '--apply-rewrites', '--assign-corpus', '--audit', '--auto', '--background', '--batch-size', '--brain', '--branch', '--break-lock', '--budget-ms', '--by-mention', '--cached', '--catch-up', '--client', '--concurrency', '--confirm-destructive', '--confirm-quiesced', '--confirm-relocated-root', '--conflicts', '--contacts-dir', '--content-audit', '--count', '--db-url', '--delete-brain', '--depth', '--detach', '--diff-filter', '--dim', '--dir', '--drain', '--dry-run', '--embedding-dimensions', '--embedding-model', '--empty', '--enable', '--exclude', '--exclude-standard', '--expect', '--expected-epoch', '--expected-revision', '--expected-state', '--explain', '--facts', '--fast', '--ff-only', '--filters', '--first-parent', '--fix', '--follow', '--force', '--force-break-lock', '--force-rechunk', '--force-retry', '--force-schema', '--format', '--fresh', '--from-meetings', '--full', '--full-history', '--git-dir', '--git-path', '--group-by', '--hard-deadline', '--harness', '--help', '--home', '--http', '--id', '--images', '--include-ambiguous', '--include-flagged', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--include-null-signature', '--include-repairs', '--index-audit', '--infer-dates', '--install', '--interval', '--is-ancestor', '--is-shallow-repository', '--json', '--kind', '--lanes', '--lang', '--left-right', '--link-source', '--link-type', '--locks', '--log-noop', '--manifest', '--markdown', '--max-age', '--max-cost', '--max-cost-usd', '--max-jobs', '--max-rss', '--max-sources', '--max-usd', '--migrate-legacy', '--migrate-only', '--missing-path', '--multimodal', '--name', '--name-only', '--name-status', '--ner', '--no-accept-pending', '--no-auto-embed', '--no-autopilot-install', '--no-bulk', '--no-capture', '--no-delegate', '--no-embed', '--no-extract', '--no-gpg-sign', '--no-hard-deadline', '--no-lanes', '--no-llm', '--no-pull', '--no-renames', '--no-repair', '--no-schema-pack', '--no-verify', '--once', '--only', '--operations', '--others', '--overwrite', '--pace', '--pace-max-concurrency', '--pack', '--page', '--parallel', '--params', '--path', '--path-format', '--pglite', '--phase', '--pid-file', '--plan', '--porcelain', '--prefer', '--prefer-postgres', '--preview', '--priority', '--probe', '--probe-pglite', '--progress-interval', '--progress-json', '--project', '--providers', '--prune-orphans', '--query', '--queue', '--quiet', '--reauth', '--rebuild', '--refresh', '--regenerate', '--remediate', '--remediation-plan', '--remove', '--remove-core', '--replace', '--repo', '--request-id', '--reset', '--reset-checkpoint', '--reset-default', '--restore-only', '--resume', '--retry-failed', '--retry-held', '--reverse', '--scope', '--scopes', '--self-transfer', '--serial', '--short', '--show-current', '--show-toplevel', '--since', '--skills-dir', '--skip', '--skip-failed', '--slot', '--slug', '--slugs', '--source', '--source-id', '--sources', '--src-subpath', '--stale', '--status', '--stdin', '--strategy', '--supabase', '--symbol-kind', '--symbolic-full-name', '--takes-holders', '--target', '--target-score', '--timeout', '--to', '--token', '--top-k', '--type', '--url', '--url-env', '--user', '--verbose', '--verify', '--version', '--wait', '--watch', '--window', '--workers', '--working-tree', '--yes'],+ 'sync': ['--abbrev-ref', '--accept-pending', '--account', '--acknowledge-managed', '--admin-intent', '--adopt-columns', '--adopt-permissions', '--all', '--allow-empty', '--apply', '--apply-rewrites', '--assign-corpus', '--audit', '--auto', '--background', '--batch-size', '--brain', '--branch', '--break-lock', '--budget-ms', '--by-mention', '--cached', '--catch-up', '--client', '--concurrency', '--confirm-destructive', '--confirm-quiesced', '--confirm-relocated-root', '--conflicts', '--contacts-dir', '--content-audit', '--count', '--db-url', '--delete-brain', '--depth', '--detach', '--diff-filter', '--dim', '--dir', '--drain', '--dry-run', '--embedding-dimensions', '--embedding-model', '--empty', '--enable', '--exclude', '--exclude-standard', '--expect', '--expected-epoch', '--expected-revision', '--expected-state', '--explain', '--facts', '--fast', '--ff-only', '--filters', '--first-parent', '--fix', '--follow', '--force', '--force-break-lock', '--force-rechunk', '--force-retry', '--force-schema', '--format', '--fresh', '--from-meetings', '--full', '--full-history', '--git-dir', '--git-path', '--group-by', '--hard-deadline', '--harness', '--help', '--home', '--http', '--id', '--images', '--include-ambiguous', '--include-flagged', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--include-null-signature', '--include-repairs', '--index-audit', '--infer-dates', '--install', '--interval', '--is-ancestor', '--is-shallow-repository', '--json', '--kind', '--lanes', '--lang', '--left-right', '--link-source', '--link-type', '--locks', '--log-noop', '--manifest', '--markdown', '--max-age', '--max-cost', '--max-cost-usd', '--max-jobs', '--max-rss', '--max-sources', '--max-usd', '--migrate-legacy', '--migrate-only', '--missing-path', '--multimodal', '--name', '--name-only', '--name-status', '--ner', '--no-accept-pending', '--no-auto-embed', '--no-autopilot-install', '--no-bulk', '--no-capture', '--no-delegate', '--no-embed', '--no-extract', '--no-gpg-sign', '--no-hard-deadline', '--no-lanes', '--no-llm', '--no-pull', '--no-renames', '--no-repair', '--no-schema-pack', '--no-verify', '--once', '--only', '--operations', '--others', '--overwrite', '--pace', '--pace-max-concurrency', '--pack', '--page', '--parallel', '--params', '--path', '--path-format', '--pglite', '--phase', '--pid-file', '--plan', '--porcelain', '--prefer', '--prefer-postgres', '--preview', '--priority', '--probe', '--probe-pglite', '--progress-interval', '--progress-json', '--project', '--providers', '--prune-orphans', '--query', '--queue', '--quiet', '--reauth', '--rebuild', '--refresh', '--regenerate', '--remediate', '--remediation-plan', '--remove', '--remove-core', '--replace', '--repo', '--request-id', '--reset', '--reset-checkpoint', '--reset-default', '--restore-only', '--resume', '--retry-failed', '--retry-held', '--reverse', '--scope', '--scopes', '--self-transfer', '--serial', '--short', '--show-current', '--show-toplevel', '--since', '--skills-dir', '--skip', '--skip-failed', '--slot', '--slug', '--slugs', '--source', '--source-id', '--sources', '--src-subpath', '--stale', '--status', '--stdin', '--strategy', '--supabase', '--symbol-kind', '--symbolic-full-name', '--takes-holders', '--target', '--target-score', '--tier', '--timeout', '--to', '--token', '--top-k', '--type', '--url', '--url-env', '--user', '--verbose', '--verify', '--version', '--wait', '--watch', '--window', '--workers', '--working-tree', '--yes'],'takes': ['--accept', '--batch-size', '--before', '--brain', '--bucket-size', '--by', '--claim', '--dim', '--dir', '--domain', '--dry-run', '--embedding-dimensions', '--embedding-model', '--evidence', '--expected-revision', '--expired', '--force', '--from-pages', '--help', '--holder', '--include-covered', '--json', '--kind', '--limit', '--max-pages', '--no-embed', '--no-embedding', '--offset', '--outcome', '--path', '--quality', '--reject', '--request-id', '--row', '--semantic', '--since', '--sort', '--source', '--source-id', '--stale', '--status', '--supabase', '--to', '--unit', '--until', '--value', '--weight', '--who', '--yes'],'think': ['--anchor', '--brain', '--calibration-holder', '--help', '--json', '--mcp-only', '--model', '--only', '--reference-date', '--rounds', '--save', '--since', '--source', '--take', '--until', '--with-calibration'],'transcripts': ['--accept-pending', '--all', '--all-discovery', '--apply', '--background', '--brain', '--days', '--dry-run', '--embed', '--explain', '--facts', '--follow', '--format', '--full', '--help', '--include-self', '--json', '--limit', '--max-bytes', '--max-cost-usd', '--no-accept-pending', '--only', '--progress-interval', '--progress-json', '--purge', '--quiet', '--since', '--source', '--source-id', '--timeout', '--wait'],diff --git a/src/core/doctor-categories.ts b/src/core/doctor-categories.tsindex cf278f28c8..0cf1811a36 100644--- a/src/core/doctor-categories.ts+++ b/src/core/doctor-categories.ts@@ -257,6 +257,8 @@ export const OPS_CHECK_NAMES: ReadonlySet<string> = new Set(['oauth_confidential_client_health','orphan_clones','persistence_capacity',+ // #6696 B1: receipt compaction freshness, an ops-tier section (doctor/checks/ops-sections.ts).+ 'receipt_compaction','worktree_refresh_stuck','managed_guard_schema_drift','publication_refusals',diff --git a/src/core/doctor-remote-tier.ts b/src/core/doctor-remote-tier.tsnew file mode 100644index 0000000000..ad398f6124--- /dev/null+++ b/src/core/doctor-remote-tier.ts@@ -0,0 +1,98 @@+/**+ * #6696 B2: thin-client `gbrain doctor --tier ops` and `--only <check>`.+ *+ * The thin client asks the serve what it lists for this token (tools/list,+ * already filtered by scope) and sends a parameter only where it is+ * advertised:+ *+ * 1. `run_doctor` lists `tier` / `only` -> the serve runs the ops sections+ * (admin scope) and the client prints that report;+ * 2. otherwise, when every requested check is one the bands cover (or the+ * tier is ops) and `get_brain_health` is listed -> the read-scope bands,+ * shown as checks (a token without admin lands here);+ * 3. otherwise (an older serve) -> the structured handoff+ * `doctor_tier_unavailable`: run doctor on the brain host. The full+ * thin-client report is never run in place of the request.+ */+import type { GBrainConfig } from './config.ts';+import { callRemoteTool, listRemoteTools, RemoteMcpError, unpackToolResult } from './mcp-client.ts';+import { isScopeErrorCode } from './error-catalogue.ts';+import { opError } from './ops/contract.ts';+import { renderCliError } from './agent-output.ts';+import { setCliExitVerdict, writeJsonDocument } from './cli-force-exit.ts';++/** The checks `get_brain_health` answers, and the band each is read from. */+export const BAND_CHECKS: ReadonlySet<string> = new Set(['persistence_capacity', 'persistence_terminal_failures']);++interface BandsResult {+ status: string;+ capacity: { band: string; days: string; max_pct_band: string; forecast: string };+ write_failures: { band: string; active_blockers: string; window_days: number | null };+ [section: string]: unknown;+}+interface ScopedCheck { name: string; status: 'ok' | 'warn' | 'fail'; message: string; details?: Record<string, unknown> }++/** Bands as doctor checks: `low` warns, `critical` fails, `unknown` warns with health unknown (never a clear band). */+export function bandChecks(bands: BandsResult, only: ReadonlySet<string> | null): ScopedCheck[] {+ const checks: ScopedCheck[] = [];+ const c = bands.capacity;+ if (!only || only.has('persistence_capacity')) {+ const status = c.band === 'critical' ? 'fail' : c.band === 'ok' ? 'ok' : 'warn';+ checks.push({ name: 'persistence_capacity', status, details: { band: c.band, days: c.days, max_pct_band: c.max_pct_band, forecast: c.forecast, ...(c.band === 'unknown' ? { health: 'unknown' } : {}) },+ message: c.band === 'unknown' ? 'Write capacity could not be read on the serve. Health is unknown.'+ : `Write capacity band ${c.band} (highest use ${c.max_pct_band}%, days to exhaustion ${c.days.replaceAll('_', ' ')}).${c.band === 'ok' ? '' : ' Run on the brain host: gbrain doctor --only persistence_capacity --json'}` });+ }+ const f = bands.write_failures;+ if (!only || only.has('persistence_terminal_failures')) {+ const blocked = f.active_blockers !== 'none' && f.active_blockers !== 'unknown';+ checks.push({ name: 'persistence_terminal_failures', status: f.band === 'unknown' || blocked ? 'warn' : 'ok',+ details: { band: f.band, active_blockers: f.active_blockers, window_days: f.window_days, ...(f.band === 'unknown' ? { health: 'unknown' } : {}) },+ message: f.band === 'unknown' ? 'Write failures could not be read on the serve. Health is unknown.'+ : `Unresolved write failures in your sources: ${f.band}; active blockers: ${f.active_blockers}.${blocked ? ' Run on the brain host: gbrain doctor --only persistence_terminal_failures --json' : ''}` });+ }+ return checks;+}++/** `tier` / `only` as parsed by the doctor dispatch (src/cli/commands/doctor.ts); `label` names the request in the handoff. */+export async function runScopedRemoteDoctor(config: GBrainConfig, req: { tier?: string; only: ReadonlySet<string> | null; json: boolean; label: string }): Promise<void> {+ const { tier, only, json } = req;+ const handoff = (why: string) => {+ const out = renderCliError(opError('doctor_tier_unavailable', `The remote brain cannot answer gbrain doctor ${req.label} for this client: ${why}`,+ 'Run gbrain doctor --tier ops --json on the brain host, or upgrade and restart its serve.'), { json, command: 'doctor', tty: !!process.stderr.isTTY });+ if (out.stdout) process.stdout.write(out.stdout);+ if (out.stderr) process.stderr.write(out.stderr);+ setCliExitVerdict(out.exitCode);+ };+ if (tier !== undefined && tier !== 'ops') return handoff(`only the ops tier is served remotely (the ${tier} tier runs on the brain host).`);++ const tools = await listRemoteTools(config);+ const runDoctor = tools.find((t) => t.name === 'run_doctor');+ const needs = [...(tier ? ['tier'] : []), ...(only ? ['only'] : [])];+ if (runDoctor && needs.every((p) => runDoctor.params.includes(p))) {+ try {+ const report = unpackToolResult<{ status: string; checks: unknown[] }>(await callRemoteTool(config, 'run_doctor', { ...(tier ? { tier } : {}), ...(only ? { only: [...only] } : {}) }));+ return print(report, json);+ } catch (e) {+ if (!(e instanceof RemoteMcpError && isScopeErrorCode(e.detail?.code, e.detail?.canonical_code, e.detail?.reason))) throw e;+ }+ }+ const bandsCover = !only || [...only].every((n) => BAND_CHECKS.has(n));+ if (bandsCover && tools.some((t) => t.name === 'get_brain_health')) {+ const bands = unpackToolResult<BandsResult>(await callRemoteTool(config, 'get_brain_health', {}));+ const checks = bandChecks(bands, only);+ const status = checks.some((c) => c.status === 'fail') ? 'unhealthy' : checks.some((c) => c.status === 'warn') ? 'warnings' : 'healthy';+ return print({ schema_version: 2, mode: 'bands', status, source: 'get_brain_health', ...(tier ? { tier } : {}), checks, bands }, json);+ }+ return handoff(runDoctor || tools.some((t) => t.name === 'get_brain_health')+ ? `this token cannot run ${only ? `the ${[...only].join(', ')} check(s)` : 'the ops tier'} remotely and the read-scope bands do not cover ${only ? 'them' : 'every ops section'}.`+ : 'the serve predates the doctor ops tier (run_doctor lists no tier or only parameter and get_brain_health is not served).');+}++function print(report: { status: string; checks: unknown[] } & Record<string, unknown>, json: boolean): void {+ if (json) void writeJsonDocument(JSON.stringify(report));+ else {+ console.log(`\nGBrain Health Check (remote${report.mode === 'bands' ? ', bands' : report.tier ? `, ${report.tier} tier` : ''})`);+ for (const c of report.checks as ScopedCheck[]) console.log(` [${c.status === 'ok' ? 'OK' : c.status === 'warn' ? 'WARN' : 'FAIL'}] ${c.name}: ${c.message}`);+ }+ setCliExitVerdict(report.status === 'unhealthy' ? 1 : 0);+}diff --git a/src/core/engine.ts b/src/core/engine.tsindex 2fb0089b3f..788f4434af 100644--- a/src/core/engine.ts+++ b/src/core/engine.ts@@ -2615,12 +2615,12 @@ export interface BrainEngine {* parameters; a statement past it fails with SQLSTATE 57014). Inside a* transaction the option is ignored (a `SET LOCAL` there would change the* enclosing transaction). PGLite ignores it: one in-process connection has- * no other session to wait on.+ * no other session to wait on. `deadlineAt` (#6696, epoch ms) recomputes the bound after the pool wait.*/executeRaw<T = Record<string, unknown>>(sql: string,params?: unknown[],- opts?: { signal?: AbortSignal; timeoutMs?: number },+ opts?: { signal?: AbortSignal; timeoutMs?: number; deadlineAt?: number },): Promise<T[]>;/**diff --git a/src/core/error-registry.ts b/src/core/error-registry.tsindex d7ef18dbd1..0319787752 100644--- a/src/core/error-registry.ts+++ b/src/core/error-registry.ts@@ -166,6 +166,7 @@ export const CODES = {verify: { argv: ['gbrain', 'doctor', '--only', 'managed_sync_not_moving', '--json'] } } },dream_breaker_tripped: { class: 'unavailable', summary: "A dream synthesize or patterns submission died (or, for patterns, was cancelled at its timeout after paid work) the breaker limit of times within 24 hours, so it was not submitted again.", why: "A run that keeps dying keeps paying; the breaker stops resubmitting until the cause is fixed and the key is reset. Patterns count per source (`dream:patterns:source:<id>`) whatever reflections each run read, and a completed run resets that count.", docs: 'docs/operations/spend-controls.md#dream-paid-loop-breaker-dreambreakermax_dead_submissions', fix: { argv: ['gbrain', 'doctor', '--only', 'dream_paid_loop', '--json'], consent: [], actor: 'agent', why: 'Shows the tripped dream keys with their counts and reset commands, read-only.', requires_exclusive: false } },dirty_tree: { class: 'caller', summary: "Commit or stash canonical skill edits before optimization." },+ doctor_tier_unavailable: { class: 'host_only', actor: 'host_admin', summary: "The remote serve cannot answer this doctor tier or check for this client, so the thin client ran nothing.", why: "A serve older than the doctor ops tier does not advertise run_doctor's tier and only parameters or get_brain_health, and a token without admin scope cannot call run_doctor; the thin client never falls back to the full report.", docs: 'docs/guides/troubleshooting.md#doctor-ops-tier', fix: { argv: ['gbrain', 'doctor', '--tier', 'ops', '--json'], consent: [], actor: 'host_admin', why: 'The ops report, run on the brain host (or after upgrading and restarting its serve).', requires_exclusive: false } },effect_not_failed: { class: 'caller', summary: "Only a failed, non-running embedding effect can be explicitly retried." },embedding_auth_failed: { class: 'unavailable', summary: "The embedding provider rejected the credentials." },embedding_budget_below_worst_case: { class: 'unavailable', summary: "The embedding migration cap is below its worst-case cost; nothing was changed." },@@ -271,7 +272,7 @@ export const CODES = {local_conflict: { class: 'caller', summary: "A local file or registration conflicts with the requested change." },lock_busy: { class: 'retryable', summary: "Another process holds the lock this command needs." },loops_extraction_skipped: { class: 'unavailable', summary: "A Google sweep or the managed catch-up queued no paid loop extraction; the sync summary's `skipped_reason` says why. Nothing failed and the email pages still imported.", why: "Extraction is gated before any model call: a kill switch, a missing chat provider, the day's spend cap (`loops.extraction_max_usd_per_day`, default $2.00; `spend_cap_zero` means the user set it to 0), or an exclusion label (`g_loops_exclude_labels` / `loops.extraction_exclude_labels`) that did not resolve against the account's labels, which fails closed until a sweep resolves it.", reasons: ['no_candidates', 'extraction_disabled', 'chat_unavailable', 'enqueue_failed', 'daily_spend_cap', 'spend_cap_zero', 'excluded_label', 'excluded_label_unresolved'], docs: 'docs/guides/open-loops.md#two-detectors', suggestion: 'Read the reason. `daily_spend_cap` clears at the next UTC day or when the user raises `loops.extraction_max_usd_per_day`; `excluded_label_unresolved` names the label token to fix in `gbrain sources status <id>` or `gbrain config get loops.extraction_exclude_labels`; the threads are extracted on their next touch or by `gbrain sync --source <id> --full`.', fix: { argv: ['gbrain', 'sync', 'status', '--source', '{source_id}', '--json'], consent: [], actor: 'agent', why: 'Read-only: the last sweep\'s loop extraction report with its skipped_reason and the unresolved label tokens.', requires_exclusive: false, verify: { argv: ['gbrain', 'config', 'get', 'loops.extraction_max_usd_per_day'] } } },- maintenance_backpressure: { class: 'retryable', summary: "Managed maintenance stopped admitting requests because this writer's outstanding requests, reserved receipt bytes or permanent request ids would pass 80% of their limit; nothing more was submitted.", why: "Each page of a maintenance run publishes as its own request under the local CLI writer the user's own CLI writes share. Stopping at 80% leaves room for those writes: reserved receipt bytes free only when receipts compact, request ids never.", docs: 'docs/guides/write-refusals.md#maintenance_backpressure', fix: { argv: ['gbrain', 'sources', 'writer', 'status', '--source', '{source_id}', '--json'], consent: [], actor: 'agent', why: "Shows the pending requests holding this writer's capacity, read-only.", requires_exclusive: false }, exit: 12 },+ maintenance_backpressure: { class: 'retryable', summary: "Managed maintenance stopped admitting requests because this writer's outstanding requests, reserved receipt bytes or permanent request ids would pass 80% of their limit; nothing more was submitted.", why: "Each page of a maintenance run publishes as its own request under the local CLI writer the user's own CLI writes share. Stopping at 80% leaves room for those writes: reserved receipt bytes free only when receipts compact, request ids never.", docs: 'docs/guides/write-refusals.md#maintenance_backpressure', fix: { argv: ['gbrain', 'sources', 'writer', 'status', '--source', '{source_id}', '--json'], consent: [], actor: 'agent', why: "Shows the pending requests holding this writer's capacity, read-only.", requires_exclusive: false, verify: { argv: ['gbrain', 'doctor', '--only', 'persistence_capacity', '--json'], mcp: { tool: 'get_brain_health', arguments: {} } } }, exit: 12 },maintenance_lock_busy: { class: 'retryable', summary: "A source-scoped dream cycle skipped its brain-wide phases because another cycle (usually autopilot maintenance) holds the shared gbrain-cycle lease; its source phases still ran.", why: 'Brain-wide phases (synthesize, patterns, embed, purge and the other mixed or global phases) must not run twice at once, so a cycle that cannot take gbrain-cycle runs only the phases its own source lease covers.', docs: 'docs/guides/cron-schedule.md#dream-beside-autopilot', suggestion: 'Nothing is lost: the holder runs those phases itself. To run one now, wait until the lease is released, then re-run `gbrain dream --phase <phase>` (LLM-backed phases spend; ask the user first).', fix: { argv: ['gbrain', 'status', '--section', 'locks', '--json'], consent: [], actor: 'agent', why: 'Shows who holds gbrain-cycle and when its lease expires, read-only.', requires_exclusive: false } },managed_failure_unsettled: { class: 'caller', summary: "The recorded managed sync failure is not settled by the imported state, so it was not acknowledged.", why: "Acknowledging removes a failure record only when the file it failed on is already imported unchanged (or deleted in both the commit and the brain); anything else would hide content that never reached the brain.", suggestion: 'Resume or retry the sync the failure names (gbrain sync status --source <id> --json shows it), then acknowledge again if the record remains.' },merge_recommended: { class: 'caller', retryable: false, actor: 'user',diff --git a/src/core/mcp-client.ts b/src/core/mcp-client.tsindex a14ef3e153..677bc55402 100644--- a/src/core/mcp-client.ts+++ b/src/core/mcp-client.ts@@ -496,6 +496,43 @@ export async function callRemoteTool(}}+/** One tool a remote serve lists for this token: its name and the parameter names its input schema declares. */+export interface RemoteToolListing { name: string; params: string[] }++/**+ * #6696 B2: the tools a remote serve lists for this client's token (tools/list+ * already filters by the token's scope and surface). Lets the thin client send+ * a parameter only to a serve that advertises it. Same token handling as+ * `callRemoteTool`: a cached token, one refresh on an HTTP 401.+ */+export async function listRemoteTools(config: GBrainConfig, opts: CallRemoteToolOptions = {}): Promise<RemoteToolListing[]> {+ const remote = requireRemoteMcp(config);+ const { signal, cleanup } = buildAbortController(opts);+ const list = async (token: string): Promise<RemoteToolListing[]> => {+ const client = await buildClient(remote.mcp_url, token, signal);+ try {+ const { tools } = await client.listTools(undefined, buildMcpRequestOptions(opts, signal));+ return tools.map((t) => ({ name: t.name, params: Object.keys((t.inputSchema as { properties?: Record<string, unknown> } | undefined)?.properties ?? {}) }));+ } finally {+ try { await client.close(); } catch { /* best-effort */ }+ }+ };+ try {+ try {+ return await list(await getAccessToken(config, false, signal));+ } catch (e) {+ signal.throwIfAborted();+ if (!isStreamableHttpError(e) || e.code !== 401) throw e;+ tokenCache.delete(remote.mcp_url);+ return await list(await getAccessToken(config, true, signal));+ }+ } catch (e) {+ throw toRemoteMcpError(e, remote.mcp_url, signal);+ } finally {+ cleanup();+ }+}+/*** Extract the structured result from a successful tool-call response. The MCP* spec says tool results are returned as `content: Array<{type, text|...}>`.diff --git a/src/core/operation-loaders.generated.ts b/src/core/operation-loaders.generated.tsindex 4f5e648de8..02cf6b2e3e 100644--- a/src/core/operation-loaders.generated.ts+++ b/src/core/operation-loaders.generated.ts@@ -95,6 +95,7 @@ export const OPERATION_LOADERS: Record<string, readonly [() => Promise<Record<st"get_stats": [load_admin, "adminOperations"],"get_health": [load_admin, "adminOperations"],"run_doctor": [load_admin, "adminOperations"],+ "get_brain_health": [load_admin, "adminOperations"],"get_versions": [load_admin, "adminOperations"],"revert_version": [load_admin, "adminOperations"],"get_brain_identity": [load_admin, "adminOperations"],diff --git a/src/core/operation-manifest.generated.ts b/src/core/operation-manifest.generated.tsindex 899ae59575..9ccf4dc3fc 100644--- a/src/core/operation-manifest.generated.ts+++ b/src/core/operation-manifest.generated.ts@@ -1938,12 +1938,36 @@ export const OPERATION_MANIFEST: OperationMeta[] = ["mutating": false,"idempotent": true,"outputRedaction": "no_stored_text",- "description": "Run brain health checks and return a structured DoctorReport (thin-client doctor surface).",- "params": {},+ "description": "Run brain health checks and return a structured DoctorReport (thin-client doctor surface). tier \"ops\": only the operational sections under a 4 s deadline; only: just the named checks.",+ "params": {+ "tier": {+ "type": "string",+ "enum": [+ "ops"+ ],+ "description": "ops: capacity, write failures, embedding state, sync movement, compaction, serve build and schema pack, under one 4 s deadline. Omit for the focused remote report."+ },+ "only": {+ "type": "array",+ "items": {+ "type": "string"+ },+ "description": "Run just these checks (doctor check names, for example persistence_capacity)."+ }+ },"scope": "admin","localOnly": false,"area": "admin"},+ {+ "name": "get_brain_health",+ "mutating": false,+ "idempotent": true,+ "outputRedaction": "no_stored_text",+ "description": "Brain health as bands for agents without admin scope: write capacity (ok|low|critical with a days band) and counts of write failures, ghost pages and unsearchable chunks as bands, for the sources you can read. No slugs. Cached 60 s.",+ "params": {},+ "scope": "read"+ },{"name": "get_versions","mutating": false,diff --git a/src/core/ops/admin.ts b/src/core/ops/admin.tsindex 4ab493f970..59b7f7ba23 100644--- a/src/core/ops/admin.ts+++ b/src/core/ops/admin.ts@@ -166,9 +166,13 @@ const run_doctor: Operation = {mutating: false,idempotent: true,outputRedaction: 'no_stored_text',- description: 'Run brain health checks and return a structured DoctorReport (thin-client doctor surface).',- params: {},- handler: async (ctx) => {+ description: 'Run brain health checks and return a structured DoctorReport (thin-client doctor surface). tier "ops": only the operational sections under a 4 s deadline; only: just the named checks.',+ params: {+ tier: { type: 'string', enum: ['ops'], description: 'ops: capacity, write failures, embedding state, sync movement, compaction, serve build and schema pack, under one 4 s deadline. Omit for the focused remote report.' },+ only: { type: 'array', items: { type: 'string' }, description: 'Run just these checks (doctor check names, for example persistence_capacity).' },+ },+ handler: async (ctx, p) => {+ if (p.tier !== undefined || p.only !== undefined) return (await import('../../commands/doctor/remote-tier.ts')).runRemoteDoctorTier(ctx, p);const { doctorReportRemote } = await import('../../commands/doctor.ts');// Source isolation (cross-model P1): a source-bound caller's report must// not aggregate other sources' activity. Scope-aware checks (connection,@@ -286,8 +290,29 @@ const quarantine_list: Operation = {},};+/**+ * #6696 B2 (Garry decision d2b): banded brain health for any read-scope caller,+ * the `verify.mcp` of every write-capacity fix. Capacity band with a days band,+ * write-failure, ghost-page and unsearchable-chunk counts as bands, scoped to+ * the sources the caller may read; no slugs, paths or exact counters.+ */+const get_brain_health: Operation = {+ name: 'get_brain_health',+ mutating: false,+ idempotent: true,+ outputRedaction: 'no_stored_text',+ description: 'Brain health as bands for agents without admin scope: write capacity (ok|low|critical with a days band) and counts of write failures, ghost pages and unsearchable chunks as bands, for the sources you can read. No slugs. Cached 60 s.',+ params: {},+ handler: async (ctx) => {+ const scope = sourceScopeOpts(ctx);+ const sourceIds = scope.sourceIds ?? (scope.sourceId ? [scope.sourceId] : undefined);+ return (await import('../../commands/doctor/brain-health-bands.ts')).readBrainHealthBands(ctx.engine, { sourceIds });+ },+ scope: 'read',+};+// Ops in EXACTLY the canonical `operations` array order.export const adminOperations: Operation[] = [- get_stats, get_health, run_doctor, get_versions, revert_version,+ get_stats, get_health, run_doctor, get_brain_health, get_versions, revert_version,get_brain_identity, quarantine_list,];diff --git a/src/core/persistence/capacity-view.ts b/src/core/persistence/capacity-view.tsnew file mode 100644index 0000000000..8a3920294b--- /dev/null+++ b/src/core/persistence/capacity-view.ts@@ -0,0 +1,101 @@+/**+ * #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.+ */+import type { BrainEngine } from '../engine.ts';+import { capacityDiagnostics } from './diagnostics.ts';+import { readJournalLimits } from './limits.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;+}++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));+ return { rows, counters_read: counters.length, forecast: null, last_compaction: parseLastCompaction(await engine.getConfig(LAST_COMPACTION_KEY)) };+}++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;+ }+}++/**+ * 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: {} } };+}++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));+ 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' };+}diff --git a/src/core/postgres-engine.ts b/src/core/postgres-engine.tsindex 3f7fd515c2..b88f2b118d 100644--- a/src/core/postgres-engine.ts+++ b/src/core/postgres-engine.ts@@ -2839,7 +2839,7 @@ export class PostgresEngine implements BrainEngine {async executeRaw<T = Record<string, unknown>>(sql: string,params?: unknown[],- opts?: { signal?: AbortSignal; timeoutMs?: number },+ opts?: { signal?: AbortSignal; timeoutMs?: number; deadlineAt?: number },): Promise<T[]> {// try/finally (not .finally on the promise): runUnsafe throws// SYNCHRONOUSLY on a pre-aborted signal, which would skip a chaineddiff --git a/src/core/postgres-engine/bounded-statement.ts b/src/core/postgres-engine/bounded-statement.tsindex dc2402ff7e..681da08d3f 100644--- a/src/core/postgres-engine/bounded-statement.ts+++ b/src/core/postgres-engine/bounded-statement.ts@@ -10,17 +10,19 @@* wait counts toward it). `COMMIT` after a failed statement is a rollback,* never an error of its own. `signal` covers only the wait for a free* connection (a saturated pool must not hold the bound off); the statement- * itself ends at the bound, never by a cancel request.+ * itself ends at the bound, never by a cancel request. With `deadlineAt` the+ * bound is the time left after the connection was reserved (#6696 B1).*/import type postgres from '#postgres';import { reserveWithCancellation } from './cancellation.ts';// engine-sql-ok: transaction control around a caller's statement (BEGIN / SET LOCAL statement_timeout / COMMIT), no storage-domain SQLexport async function runBoundedStatement<T>(conn: ReturnType<typeof postgres>, sql: string, params: unknown[] | undefined,- opts: { timeoutMs: number; signal?: AbortSignal }, onReserved: () => void): Promise<T[]> {- const ms = Math.max(1, Math.ceil(opts.timeoutMs));+ opts: { timeoutMs: number; deadlineAt?: number; signal?: AbortSignal }, onReserved: () => void): Promise<T[]> {const reserved = opts.signal ? await reserveWithCancellation(reserve => conn.reserve(reserve), opts.signal) : await conn.reserve();onReserved();+ // #6696 B1: an absolute deadline is re-read after the pool wait, so time spent waiting for a connection is not granted again.+ const ms = Math.max(1, Math.ceil(opts.deadlineAt !== undefined ? Math.min(opts.timeoutMs, opts.deadlineAt - Date.now()) : opts.timeoutMs));try {const open = reserved.unsafe(`BEGIN; SET LOCAL statement_timeout = ${ms}`).simple().execute();const read = reserved.unsafe(sql, params as Parameters<typeof reserved.unsafe>[1], { prepare: true }).execute();diff --git a/test/doctor-day-zero.test.ts b/test/doctor-day-zero.test.tsindex 18cbffc25b..9053a0be57 100644--- a/test/doctor-day-zero.test.ts+++ b/test/doctor-day-zero.test.ts@@ -50,6 +50,21 @@ describe('day-zero keyless doctor', () => {}}, 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 --git a/test/doctor-ops-remote-6696.test.ts b/test/doctor-ops-remote-6696.test.tsnew file mode 100644index 0000000000..b45d518355--- /dev/null+++ b/test/doctor-ops-remote-6696.test.ts@@ -0,0 +1,244 @@+/**+ * #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.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 --git a/test/doctor-tier-6696.test.ts b/test/doctor-tier-6696.test.tsnew file mode 100644index 0000000000..99253e7134--- /dev/null+++ b/test/doctor-tier-6696.test.ts@@ -0,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']) {+ 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(['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']));+ });++ 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 --git a/test/e2e/doctor-ops-tier-postgres.test.ts b/test/e2e/doctor-ops-tier-postgres.test.tsnew file mode 100644index 0000000000..c8cda5b484--- /dev/null+++ b/test/e2e/doctor-ops-tier-postgres.test.ts@@ -0,0 +1,77 @@+/**+ * #6696 B1 on Postgres: the ops tier and its deadline.+ *+ * - executeRaw `deadlineAt` ends the statement at the absolute deadline+ * (statement_timeout from the time left), not at the longer timeoutMs.+ * - `--tier ops` runs every ops section for real (none not_applicable), stays+ * complete on a fresh brain and reads no page aggregate.+ * - A section slower than `--budget-ms` is unknown with reason budget and the+ * run returns near the deadline.+ *+ * Run: DATABASE_URL=... bun test test/e2e/doctor-ops-tier-postgres.test.ts+ */+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';+import { hasDatabase, setupDB, teardownDB } from './helpers.ts';+import type { PostgresEngine } from '../../src/core/postgres-engine.ts';+import type { BrainEngine } from '../../src/core/engine.ts';+import { buildChecks, computeDoctorReport, doctorRunSummary } from '../../src/commands/doctor.ts';+import { opsCheckNames } from '../../src/commands/doctor/registry.ts';+import { startDoctorDeadline } from '../../src/commands/doctor/budget.ts';++const describeE2E = hasDatabase() ? describe : describe.skip;+let engine: PostgresEngine;++describeE2E('doctor --tier ops on Postgres (#6696)', () => {+ beforeAll(async () => { engine = await setupDB(); }, 120_000);+ afterAll(async () => { await teardownDB(); });++ test('executeRaw deadlineAt bounds the statement by the time left', async () => {+ const started = Date.now();+ await expect(engine.executeRaw('SELECT pg_sleep(5)', [], { timeoutMs: 10_000, deadlineAt: started + 300 })).rejects.toThrow(/statement timeout|canceling statement/i);+ expect(Date.now() - started).toBeLessThan(2_000);+ const rows = await engine.executeRaw<{ one: number }>('SELECT 1 AS one', [], { timeoutMs: 10_000, deadlineAt: Date.now() + 2_000 });+ expect(rows[0]!.one).toBe(1);+ });++ test('every ops section runs (none not_applicable), the report is complete and no page aggregate is read', async () => {+ const args = ['--json', '--tier', 'ops'];+ const deadline = startDoctorDeadline(args);+ const guarded = new Proxy(engine, {+ get(target, key) {+ if (key === 'getHealth' || key === 'findOrphanPages' || key === 'getStats') return () => { throw new Error(`${String(key)} must not run in the ops tier`); };+ const value = Reflect.get(target, key, target);+ return typeof value === 'function' ? value.bind(target) : value;+ },+ }) as BrainEngine;+ const checks = await buildChecks(guarded, args, undefined, undefined, deadline);+ const ops = opsCheckNames();+ expect(checks.filter((c) => c.name !== 'connection').every((c) => ops.has(c.name))).toBe(true);+ expect(checks.filter((c) => c.details?.health === 'not_applicable').map((c) => c.name)).toEqual([]);+ expect(checks.filter((c) => c.details?.health === 'unknown').map((c) => c.name)).toEqual([]);+ const report = computeDoctorReport(checks, { engine: 'postgres', run: doctorRunSummary(args, deadline) });+ expect(report.complete).toBe(true);+ expect(report.elapsed_ms).toBeLessThan(4_000);+ });++ test('a section slower than --budget-ms is unknown (reason budget) and the run ends near the deadline', async () => {+ const args = ['--json', '--tier', 'ops', '--budget-ms', '400'];+ const deadline = startDoctorDeadline(args);+ const slow = new Proxy(engine, {+ get(target, key) {+ if (key === 'executeRaw') {+ return async (sql: string, params?: unknown[], opts?: never) => {+ if (/FROM persistence_counters/.test(sql)) await target.executeRaw('SELECT pg_sleep(3)', [], opts);+ return target.executeRaw(sql, params, opts);+ };+ }+ const value = Reflect.get(target, key, target);+ return typeof value === 'function' ? value.bind(target) : value;+ },+ }) as BrainEngine;+ const started = Date.now();+ const checks = await buildChecks(slow, args, undefined, undefined, deadline);+ expect(Date.now() - started).toBeLessThan(2_500);+ expect(checks.find((c) => c.name === 'persistence_capacity')?.details).toMatchObject({ health: 'unknown', reason: 'budget' });+ expect(computeDoctorReport(checks, { engine: 'postgres', run: doctorRunSummary(args, deadline) }).unknown_sections).toContain('persistence_capacity');+ });+});diff --git a/test/fixtures/goldens/cli/tools-json.json b/test/fixtures/goldens/cli/tools-json.jsonindex ef1c3f7b8a..c8fda4a461 100644--- a/test/fixtures/goldens/cli/tools-json.json+++ b/test/fixtures/goldens/cli/tools-json.json@@ -2,8 +2,8 @@"golden": {"exitCode": 0,"stderr": "",- "stdoutBytes": 232698,- "stdoutSha256": "efcd4e38b964afc730f5c34369c4f9f3d8cec4ad1e885a6df5186b69830924e8",+ "stdoutBytes": 233904,+ "stdoutSha256": "d5850e9b9c861afa85440c8f3c47adb3ce22998c744278f19fec262bebe08e42","toolNames": ["remember","entity",@@ -47,6 +47,7 @@"get_stats","get_health","run_doctor",+ "get_brain_health","get_versions","revert_version","get_brain_identity",@@ -2340,11 +2341,44 @@"scope": "admin"},{- "description": "Run brain health checks and return a structured DoctorReport (thin-client doctor surface).",+ "description": "Run brain health checks and return a structured DoctorReport (thin-client doctor surface). tier \"ops\": only the operational sections under a 4 s deadline; only: just the named checks.","idempotent": true,"local_only": false,"mutating": false,"name": "run_doctor",+ "parameters": {+ "only": "array?",+ "tier": "string?"+ },+ "required_scopes": [],+ "schema": {+ "properties": {+ "only": {+ "description": "Run just these checks (doctor check names, for example persistence_capacity).",+ "items": {+ "type": "string"+ },+ "type": "array"+ },+ "tier": {+ "description": "ops: capacity, write failures, embedding state, sync movement, compaction, serve build and schema pack, under one 4 s deadline. Omit for the focused remote report.",+ "enum": [+ "ops"+ ],+ "type": "string"+ }+ },+ "required": [],+ "type": "object"+ },+ "scope": "admin"+ },+ {+ "description": "Brain health as bands for agents without admin scope: write capacity (ok|low|critical with a days band) and counts of write failures, ghost pages and unsearchable chunks as bands, for the sources you can read. No slugs. Cached 60 s.",+ "idempotent": true,+ "local_only": false,+ "mutating": false,+ "name": "get_brain_health","parameters": {},"required_scopes": [],"schema": {@@ -2352,7 +2386,7 @@"required": [],"type": "object"},- "scope": "admin"+ "scope": "read"},{"description": "Page version history, newest snapshot first. Trusted local and admin callers also get written_by and archived_by (who wrote each snapshot and whose write archived it). `limit` returns only the newest N; `include_body: false` returns metadata only.",diff --git a/test/fixtures/goldens/doctor/json-pglite-degraded.json b/test/fixtures/goldens/doctor/json-pglite-degraded.jsonindex 39a0aea1cd..d47ac36b8e 100644--- a/test/fixtures/goldens/doctor/json-pglite-degraded.json+++ b/test/fixtures/goldens/doctor/json-pglite-degraded.json@@ -18,6 +18,7 @@"checks": [{"category": "skill",+ "elapsed_ms": "<volatile>","message": "1 skills, all reachable","name": "resolver_health","status": "ok"@@ -32,6 +33,7 @@"path": "pglite — serve IPC socket not present","policy_skill_installed": false},+ "elapsed_ms": "<volatile>","fix": {"actor": "user","consent": [@@ -55,30 +57,35 @@"channels": {},"window_days": 7},+ "elapsed_ms": "<volatile>","message": "no push-context activity in 7 days — if a hook adapter is installed, confirm its registration landed and the harness session was RESTARTED (hooks snapshot at session start); a serve older than this build logs NOTHING for the hook lane — restart serve on the new build to activate the feedback loop","name": "volunteer_channels","status": "ok"},{"category": "skill",+ "elapsed_ms": "<volatile>","message": "no verb calls recorded yet (sidecar appears on first remember/recall/entity/synthesize/forget)","name": "memory_verbs_usage","status": "ok"},{"category": "skill",+ "elapsed_ms": "<volatile>","message": "1/1 skills pass","name": "skill_conformance","status": "ok"},{"category": "skill",+ "elapsed_ms": "<volatile>","message": "1 skill(s) compliant or exempt","name": "skill_brain_first","status": "ok"},{"category": "skill",+ "elapsed_ms": "<volatile>","message": "No skills.lock.json in <home>/skills — integrity check not applicable","name": "skills_manifest_integrity","status": "ok"@@ -154,6 +161,7 @@"webhook-transforms"]},+ "elapsed_ms": "<volatile>","fix_unavailable_reason": "unstructured","message": "64 new built-in skill(s) available that this workspace hasn't installed: academic-verify, archive-crawler, article-enrichment, ask-user, blog-ingest, book-mirror, brain-ingest-gate, brain-link-discipline, … +56 more. Add them with `gbrain skillpack sync`.","name": "skill_currency",@@ -161,6 +169,7 @@},{"category": "skill",+ "elapsed_ms": "<volatile>","message": "no installed skills declare preconditions","name": "skill_preconditions","status": "ok"@@ -172,6 +181,7 @@"out_of_band_settable": true,"reason": "disabled"},+ "elapsed_ms": "<volatile>","message": "memorable relay off (default)","name": "memorable_relay_health","status": "ok"@@ -205,12 +215,14 @@"ttl_valid": true,"visibility_note": "world = readable by agents authorized on THIS brain, not the public internet"},+ "elapsed_ms": "<volatile>","message": "ambient writeback off (default): Stop-hook turn capture is off, but the compaction harvest and SessionEnd transcripts still extract (installing the harness hooks opted into them; stop them: gbrain config set memory.auto_writeback off). Enable: gbrain config set memory.auto_writeback salient","name": "memory_writeback","status": "ok"},{"category": "ops",+ "elapsed_ms": "<volatile>","message": "No chat connectors configured (optional).","name": "connectors","status": "ok"@@ -224,6 +236,7 @@"keys": [],"threshold": 3},+ "elapsed_ms": "<volatile>","message": "No dream key died 3+ times in 24h","name": "dream_paid_loop","status": "ok"@@ -239,6 +252,7 @@"0.53.0"]},+ "elapsed_ms": "<volatile>","fix": {"actor": "agent","argv": [@@ -271,18 +285,21 @@},{"category": "ops",+ "elapsed_ms": "<volatile>","message": "mode=notify","name": "self_upgrade_health","status": "ok"},{"category": "ops",+ "elapsed_ms": "<volatile>","message": "Bun <bun-version> (minimum 1.4.0)","name": "bun_runtime","status": "ok"},{"category": "brain",+ "elapsed_ms": "<volatile>","message": "disabled (opt-in). Enable with: gbrain config set autopilot.nightly_quality_probe.enabled true","name": "nightly_quality_probe_health","status": "ok"@@ -293,12 +310,14 @@"kinds": [],"schema_version": 1},+ "elapsed_ms": "<volatile>","message": "no extractions in last 7 days","name": "extract_health","status": "ok"},{"category": "brain",+ "elapsed_ms": "<volatile>","message": "disabled (opt-in). Enable with: gbrain config set cycle.conversation_facts_backfill.enabled true","name": "conversation_facts_backlog","status": "ok"@@ -310,6 +329,7 @@"known_approximation": "page backlog only; transcript corpus not counted","pack_declares_phase": false},+ "elapsed_ms": "<volatile>","message": "no pages awaiting atom extraction","name": "extract_atoms_backlog","status": "ok"@@ -324,36 +344,42 @@"source_gone": 0,"total_atoms": 0},+ "elapsed_ms": "<volatile>","message": "no atoms to check","name": "atom_provenance_drift","status": "ok"},{"category": "brain",+ "elapsed_ms": "<volatile>","message": "No conversation-type pages — coverage check not applicable","name": "conversation_format_coverage","status": "ok"},{"category": "ops",+ "elapsed_ms": "<volatile>","message": "No progressive-batch operations in the last 7 days","name": "progressive_batch_audit_health","status": "ok"},{"category": "brain",+ "elapsed_ms": "<volatile>","message": "disabled (opt-in; default-on only for search.mode=tokenmax). Enable with: `gbrain config set autopilot.conversation_parser_probe.enabled true`","name": "conversation_parser_probe_health","status": "ok"},{"category": "ops",+ "elapsed_ms": "<volatile>","message": "gbrain home is outside any enclosing git worktree.","name": "home_dir_in_worktree","status": "ok"},{"category": "meta",+ "elapsed_ms": "<volatile>","message": "default source local_path is set: <home>/.gbrain/content/<uuid>/default","name": "default_source_local_path","status": "ok"@@ -370,6 +396,7 @@"embedding_model": "openai:text-embedding-3-large","shadows": []},+ "elapsed_ms": "<volatile>","message": "No embedding key is set here (OPENAI_API_KEY or openai_api_key). No environment variable overrides a different config-plane provider key. This check sees only the environment `gbrain doctor` runs in; a daemon (gbrain serve, autopilot) has its own, and reports a mismatch in its log with a startup warning or embedding_auth_failed.","name": "embedding_key_source","status": "ok"@@ -380,6 +407,7 @@"decision": null,"provider_env": []},+ "elapsed_ms": "<volatile>","message": "No gbrain setup receipt records a provider-use decision for this install; provider calls follow the configured keys.","name": "provider_consent","readiness_state": "not_applicable",@@ -391,6 +419,7 @@"details": {"reason": "no_harness_detected"},+ "elapsed_ms": "<volatile>","fix": {"actor": "user","consent": [@@ -418,24 +447,139 @@"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, 0 pages","name": "connection","status": "ok"},{"category": "ops",+ "details": {+ "commands": [],+ "exact": true,+ "inspected": 2,+ "resources": [],+ "truncated": false+ },+ "elapsed_ms": "<volatile>",+ "message": "Managed write capacity is below 80% of every cumulative limit.",+ "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+ },+ "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",+ "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": "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"@@ -446,23 +590,11 @@"readiness": "ready","ready": true},+ "elapsed_ms": "<volatile>","message": "Visible text projections match their canonical revisions.","name": "text_projection_readiness","status": "ok"},- {- "category": "ops",- "details": {- "commands": [],- "exact": true,- "inspected": 2,- "resources": [],- "truncated": false- },- "message": "Managed write capacity is below 80% of every cumulative limit.",- "name": "persistence_capacity",- "status": "ok"- },{"category": "brain","details": {@@ -472,6 +604,7 @@"parked_effects": 0,"truncated": false},+ "elapsed_ms": "<volatile>","message": "No Git or withdrawal effect is parked.","name": "parked_effects","status": "ok"@@ -481,6 +614,7 @@"details": {"refreshes": []},+ "elapsed_ms": "<volatile>","message": "No worktree refresh is stuck.","name": "worktree_refresh_stuck","status": "ok"@@ -492,6 +626,7 @@"page_child_source_columns": [],"runbook": "docs/guides/write-refusals.md#managed-guard-page-children"},+ "elapsed_ms": "<volatile>","message": "Guarded tables carry only the columns gbrain creates.","name": "managed_guard_schema_drift","status": "ok"@@ -505,42 +640,49 @@"unclassified_p0001": 0,"window_days": 7},+ "elapsed_ms": "<volatile>","message": "No write was refused by a database guard in the last 7 days.","name": "publication_refusals","status": "ok"},{"category": "meta",+ "elapsed_ms": "<volatile>","message": "links_link_source_check has the v114 kebab-case gate","name": "links_link_source_check","status": "ok"},{"category": "ops",+ "elapsed_ms": "<volatile>","message": "PGLite at 0 pages — comfortable below the 1000-page threshold","name": "pglite_scale","status": "ok"},{"category": "ops",+ "elapsed_ms": "<volatile>","message": "Skipped (PGLite — no PostgREST exposure, RLS not applicable)","name": "rls","status": "ok"},{"category": "meta",+ "elapsed_ms": "<volatile>","message": "Version <latest> (latest: <latest>)","name": "schema_version","status": "ok"},{"category": "meta",+ "elapsed_ms": "<volatile>","message": "1115 column(s) verified against live schema","name": "schema_columns","status": "ok"},{"category": "ops",+ "elapsed_ms": "<volatile>","message": "Skipped (PGLite — no event trigger support)","name": "rls_event_trigger","status": "ok"@@ -552,18 +694,21 @@"backlog": 0,"oldest_pending_age_s": null},+ "elapsed_ms": "<volatile>","message": "100% coverage, 0 missing","name": "embeddings","status": "ok"},{"category": "brain",+ "elapsed_ms": "<volatile>","message": "Skipped (no provider credentials). Model: openai:text-embedding-3-large.","name": "embedding_provider","status": "ok"},{"category": "brain",+ "elapsed_ms": "<volatile>","fix_unavailable_reason": "unstructured","message": "embedding: declared dims=3072 but actual is vector(1024). Fix one side: update config OR ALTER TABLE content_chunks ALTER COLUMN embedding TYPE vector(3072);","name": "embedding_column_registry",@@ -571,12 +716,14 @@},{"category": "brain",+ "elapsed_ms": "<volatile>","message": "no embedding env overrides set","name": "embedding_env_override","status": "ok"},{"category": "brain",+ "elapsed_ms": "<volatile>","message": "no embedding migration in flight","name": "embedding_migration_state","status": "ok"@@ -592,6 +739,7 @@"source": "uncalibrated","threshold": null},+ "elapsed_ms": "<volatile>","fix": {"actor": "agent","argv": [@@ -655,48 +803,56 @@},{"category": "ops",+ "elapsed_ms": "<volatile>","message": "No chat_fallback_chain is set: every chat call uses only its own model.","name": "chat_fallback_chain","status": "ok"},{"category": "meta",+ "elapsed_ms": "<volatile>","message": "Nothing to disclose: this brain is a fresh install at v<version>, after every disclosed behavior change, so the one-time behavior-change notice does not apply.","name": "behavior_changes","status": "ok"},{"category": "brain",+ "elapsed_ms": "<volatile>","message": "No entity pages — graph_coverage not applicable (markdown-only brain)","name": "graph_coverage","status": "ok"},{"category": "brain",+ "elapsed_ms": "<volatile>","message": "Brain score 100/100","name": "brain_score","status": "ok"},{"category": "brain",+ "elapsed_ms": "<volatile>","message": "Vacuous: 0 entity pages (<100). Orphan ratio not meaningful at this scale.","name": "orphan_ratio","status": "ok"},{"category": "brain",+ "elapsed_ms": "<volatile>","message": "No by-mention links in this brain.","name": "stale_mentions","status": "ok"},{"category": "brain",+ "elapsed_ms": "<volatile>","message": "No orphaned timeline rows across 0 page(s).","name": "timeline_orphans","status": "ok"},{"category": "brain",+ "elapsed_ms": "<volatile>","message": "No slug collisions across 1 source checkout(s).","name": "slug_collisions","status": "ok"@@ -712,6 +868,7 @@"repair": "timeline","truncated": false},+ "elapsed_ms": "<volatile>","message": "Every timeline row has a bullet in its page (0 page(s) inspected).","name": "timeline_history","status": "ok"@@ -727,6 +884,7 @@"unstamped_atoms": 0,"unstamped_concepts": 0},+ "elapsed_ms": "<volatile>","message": "Every extracted atom and synthesized concept carries an explicit visibility no looser than its origin.","name": "derived_visibility","status": "ok"@@ -740,6 +898,7 @@"repair": "safe-chunks","truncated": false},+ "elapsed_ms": "<volatile>","message": "Every re-sealable page is at the safe-chunk index version.","name": "safe_index_pending","status": "ok"@@ -752,6 +911,7 @@"pages_pending": 0,"truncated": false},+ "elapsed_ms": "<volatile>","message": "No page waits for the credential-safe re-chunk.","name": "credential_projection_pending","status": "ok"@@ -766,6 +926,7 @@"retries": 0,"truncated": false},+ "elapsed_ms": "<volatile>","message": "No orphan connector checkpoint rows older than 7 days.","name": "connector_checkpoints","status": "ok"@@ -792,6 +953,7 @@],"repair": "request-indexes"},+ "elapsed_ms": "<volatile>","message": "Managed sync request indexes are valid.","name": "persistence_request_indexes","status": "ok"@@ -830,6 +992,7 @@"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.","name": "persistence_request_growth","status": "ok"@@ -849,6 +1012,7 @@},"stalls": []},+ "elapsed_ms": "<volatile>","message": "No write request has held its claim longer than persistence.max_claim_ms (600000 ms).","name": "persistence_write_stall","status": "ok"@@ -862,62 +1026,11 @@"repair": "failed-writes","writes": []},+ "elapsed_ms": "<volatile>","message": "Every caller write with a retained receipt committed or was superseded.","name": "lost_caller_writes","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- },- "message": "No terminal write failures in the last 7 d.",- "name": "persistence_terminal_failures",- "status": "ok"- },{"category": "ops","details": {@@ -925,6 +1038,7 @@"configured": "5min","docs": "docs/guides/troubleshooting.md#session-timeouts-not-applied"},+ "elapsed_ms": "<volatile>","message": "PGLite has no session to time out.","name": "persistence_session_timeouts","status": "ok"@@ -936,6 +1050,7 @@"held": 0,"sources": []},+ "elapsed_ms": "<volatile>","message": "No connector items are held.","name": "connector_held_items","status": "ok"@@ -949,6 +1064,7 @@"source_ids": [],"sources": []},+ "elapsed_ms": "<volatile>","message": "No Git source files are held.","name": "git_held_files","status": "ok"@@ -960,6 +1076,7 @@"docs": "docs/guides/repair.md#held-files","hooks": []},+ "elapsed_ms": "<volatile>","message": "No outdated gbrain frontmatter pre-commit hook is installed.","name": "frontmatter_hook","status": "ok"@@ -973,6 +1090,7 @@"repair": "orphan-bindings","truncated": false},+ "elapsed_ms": "<volatile>","message": "Every persistence source binding belongs to an existing source.","name": "orphan_persistence_bindings","status": "ok"@@ -984,6 +1102,7 @@"docs": "docs/guides/write-refusals.md#foreign-ownership-marker","markers": []},+ "elapsed_ms": "<volatile>","message": "Every ownership marker beside a source checkout belongs to this brain.","name": "foreign_ownership_marker","status": "ok"@@ -994,6 +1113,7 @@"sources": [],"total": 0},+ "elapsed_ms": "<volatile>","message": "No page was written database-only to an unbound source.","name": "unbound_source","status": "ok"@@ -1023,6 +1143,7 @@"truncated": false,"window_days": 7},+ "elapsed_ms": "<volatile>","message": "Every writer that admitted or published a request in the last 7 days is v0.60.5.0 or newer.","name": "writer_version","status": "ok"@@ -1035,6 +1156,7 @@"truncated": false,"unclassifiable": 0},+ "elapsed_ms": "<volatile>","message": "No session corpus is configured; nothing to classify.","name": "self_capture","status": "ok"@@ -1045,6 +1167,7 @@"outcome": "skipped","reason": "pglite"},+ "elapsed_ms": "<volatile>","message": "Skipped: PGLite runs vector search in-process; the plan check applies to Postgres brains.","name": "vector_plan","status": "ok"@@ -1055,6 +1178,7 @@"outcome": "skipped","reason": "pglite"},+ "elapsed_ms": "<volatile>","message": "Skipped: PGLite runs keyword search with no statement timeout; the canary applies to Postgres brains.","name": "keyword_plan","status": "ok"@@ -1073,6 +1197,7 @@"stale_effects": 0,"truncated": false},+ "elapsed_ms": "<volatile>","message": "No committed write has a stale queued or failed embedding effect.","name": "stale_embedding_effects","status": "ok"@@ -1085,6 +1210,7 @@"repair": "google-file-modes","sources": []},+ "elapsed_ms": "<volatile>","message": "No group- or world-readable gbrain files under Google source directories outside ~/.gbrain.","name": "google_file_modes","status": "ok"@@ -1098,6 +1224,7 @@"excluded": 0,"repair": "extractor-facts"},+ "elapsed_ms": "<volatile>","message": "No conversation-extractor fact is left expired by the pre-v0.60.11.0 projection.","name": "extractor_facts_expired","status": "ok"@@ -1110,6 +1237,7 @@"evidenced": 0,"repair": "conversation-labels"},+ "elapsed_ms": "<volatile>","message": "No conversation fact carries the pre-fix meeting-label signature (a 1970-01-01 segment on a label page).","name": "conversation_label_facts","status": "ok"@@ -1125,6 +1253,7 @@"stale": 0,"unstamped": 0},+ "elapsed_ms": "<volatile>","message": "No conversation extraction outcome predates extractor version 1.","name": "conversation_outcomes_stale","status": "ok"@@ -1139,6 +1268,7 @@"repair": "captured-facts","unclassifiable": 0},+ "elapsed_ms": "<volatile>","message": "No active fact from a gbrain self-capture or paste candidate remains. This counts facts in the database; the self_capture check counts corpus files.","name": "captured_facts_active","status": "ok"@@ -1150,6 +1280,7 @@"drifted": 0,"repair": "loop-facts"},+ "elapsed_ms": "<volatile>","message": "Every closed commitment loop has its fact retired.","name": "loop_facts_drift","status": "ok"@@ -1163,6 +1294,7 @@"repair": "ontology-facts","retired": 0},+ "elapsed_ms": "<volatile>","message": "No ontology observation is held by a page's Facts table.","name": "ontology_facts_fenced","status": "ok"@@ -1176,6 +1308,7 @@"source_ids": [],"sources": []},+ "elapsed_ms": "<volatile>","message": "No stored frontmatter carries a parser-reserved key (type, title, tags, slug).","name": "stale_frontmatter_keys","status": "ok"@@ -1190,102 +1323,119 @@"sources": [],"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"},{"category": "brain",+ "elapsed_ms": "<volatile>","message": "Relative dates resolve against each source's observation date in fact extraction, dream synthesis, extract_atoms and propose_takes (the default). life chronicle events keep their current prompt unless extraction.date_grounding is set to true. Facts extracted before this was on keep their original wording; re-extract a source only with the user's consent (gbrain extract-conversation-facts --source-id <id> --dry-run previews it).","name": "extraction_date_grounding","status": "ok"},{"category": "brain",+ "elapsed_ms": "<volatile>","message": "Sampled 0 pages; no bare-tweet phrases or external links.","name": "integrity","status": "ok"},{"category": "brain",+ "elapsed_ms": "<volatile>","message": "All JSONB columns store objects/arrays","name": "jsonb_integrity","status": "ok"},{"category": "brain",+ "elapsed_ms": "<volatile>","message": "No takes yet","name": "takes_weight_grid","status": "ok"},{"category": "brain",+ "elapsed_ms": "<volatile>","message": "All FK-child tables clean (10 tables checked)","name": "child_table_orphans","status": "ok"},{"category": "brain",+ "elapsed_ms": "<volatile>","message": "All synthesized pages carry a raw trace or explicit exemption","name": "raw_provenance","status": "ok"},{"category": "brain",+ "elapsed_ms": "<volatile>","message": "All source config values are JSON objects","name": "source_config_shape","status": "ok"},{"category": "skill",+ "elapsed_ms": "<volatile>","message": "whoknows eval fixture present (10 queries). Run `gbrain eval whoknows test/fixtures/whoknows-eval.jsonl` to grade.","name": "whoknows_health","status": "ok"},{"category": "brain",+ "elapsed_ms": "<volatile>","message": "All image-asset chunks have modality=image","name": "cross_modal_modality_backfill","status": "ok"},{"category": "brain",+ "elapsed_ms": "<volatile>","message": "search.unified_multimodal is off; coverage check N/A","name": "unified_multimodal_coverage","status": "ok"},{"category": "brain",+ "elapsed_ms": "<volatile>","message": "No truncated bodies detected","name": "markdown_body_completeness","status": "ok"},{"category": "brain",+ "elapsed_ms": "<volatile>","message": "No pages exceed 500000 bytes (excluding embed_skip pages, which already took the accepted non-embeddable remediation)","name": "oversized_pages","status": "ok"},{"category": "brain",+ "elapsed_ms": "<volatile>","message": "No junk-pattern hits in 0 recent page(s) (use --content-audit for full scan)","name": "scraper_junk_pages","status": "ok"},{"category": "brain",+ "elapsed_ms": "<volatile>","message": "No content-sanity events in last 7 days (audit JSONL is local to this host; share GBRAIN_AUDIT_DIR for multi-host visibility)","name": "content_sanity_audit_recent","status": "ok"},{"category": "brain",+ "elapsed_ms": "<volatile>","message": "No quarantined pages","name": "quarantined_pages","status": "ok"},{"category": "brain",+ "elapsed_ms": "<volatile>","message": "No flagged pages","name": "flagged_pages","status": "ok"@@ -1297,12 +1447,14 @@"days": 7,"source_id": null},+ "elapsed_ms": "<volatile>","message": "No stale unverified extraction stubs","name": "unverified_extractions","status": "ok"},{"category": "brain",+ "elapsed_ms": "<volatile>","message": "1 source(s) clean — no frontmatter issues","name": "frontmatter_integrity","status": "ok"@@ -1317,36 +1469,42 @@"sources": [],"unscanned": []},+ "elapsed_ms": "<volatile>","message": "No file has frontmatter gbrain repair frontmatter would fix.","name": "frontmatter_repairable","status": "ok"},{"category": "meta",+ "elapsed_ms": "<volatile>","message": "No capture failures in the last 24h","name": "eval_capture","status": "ok"},{"category": "brain",+ "elapsed_ms": "<volatile>","message": "No probe runs in the last 7 days. Run `gbrain eval suspected-contradictions --query \"...\" --top-k 5` to populate.","name": "contradictions","status": "ok"},{"category": "brain",+ "elapsed_ms": "<volatile>","message": "Automatic fact extraction not configured (keyless) — memory comes from agent-authored `## Facts` fences and the `remember` verb. One optional key enables automatic extraction (OpenAI or Anthropic).","name": "facts_extraction_health","status": "ok"},{"category": "brain",+ "elapsed_ms": "<volatile>","message": "Sample of last 1000 pages clean (no fallback-with-parseable-fm-date, no future-dated, no pre-1990)","name": "effective_date_health","status": "ok"},{"category": "brain",+ "elapsed_ms": "<volatile>","message": "Skipped (no pages have emotional_weight > 0; either fresh install or recompute hasn't run yet)","name": "salience_health","status": "ok"@@ -1359,24 +1517,28 @@"engine": "pglite","worker_alive": true},+ "elapsed_ms": "<volatile>","message": "PGLite: no jobs waiting for a worker.","name": "queue_health","status": "ok"},{"category": "ops",+ "elapsed_ms": "<volatile>","message": "Subagent tier resolves to default (claude-sonnet-4-6) — full tool-loop capability","name": "subagent_capability","status": "ok"},{"category": "brain",+ "elapsed_ms": "<volatile>","message": "facts_health(default): 0 active, 0 today, 0 this week, 0 consolidated, top entities —","name": "facts_health","status": "ok"},{"category": "ops",+ "elapsed_ms": "<volatile>","message": "Brain-wide maintenance jobs are finishing within their deadline.","name": "global_maintenance_timeouts","status": "ok"@@ -1399,6 +1561,7 @@"unsupported": 0,"unsupported_ids": []},+ "elapsed_ms": "<volatile>","message": "No queued job predates submission authority.","name": "legacy_job_authority","status": "ok"@@ -1412,6 +1575,7 @@"malformed": [],"mirror_window_ends": "2026-11-04"},+ "elapsed_ms": "<volatile>","message": "Every active legacy token uses the unified grant columns. The permissions mirror for older gbrain binaries is kept until 2026-11-04.","name": "legacy_token_grant_shape","status": "ok"@@ -1423,6 +1587,7 @@"drift": [],"mirror_window_ends": "2026-11-04"},+ "elapsed_ms": "<volatile>","message": "No legacy token grant has drifted from its permissions mirror.","name": "legacy_token_grant_drift","status": "ok"@@ -1434,6 +1599,7 @@"null_scope_count": 0,"tokens": []},+ "elapsed_ms": "<volatile>","message": "Every active legacy token has explicit scopes.","name": "legacy_token_null_scope","status": "ok"@@ -1445,18 +1611,21 @@"grants": [],"server_surface": "full"},+ "elapsed_ms": "<volatile>","message": "Every active client and token can call the operations its scopes allow.","name": "grant_new_ops_available","status": "ok"},{"category": "brain",+ "elapsed_ms": "<volatile>","message": "No image assets indexed yet","name": "image_assets","status": "ok"},{"category": "brain",+ "elapsed_ms": "<volatile>","message": "OCR not in use (or no images ingested with OCR opt-in)","name": "ocr_health","status": "ok"@@ -1470,6 +1639,7 @@"unsupported_holds": 0,"without_image_vector": 0},+ "elapsed_ms": "<volatile>","message": "No image pages indexed yet.","name": "image_embedding_coverage","status": "ok"@@ -1482,6 +1652,7 @@"unchanged_count": 0,"writer_owned_count": 1},+ "elapsed_ms": "<volatile>","message": "1 writer-owned canonical content source(s): upstream sync is not applicable; see canonical_content_writes for publication status.","name": "sync_freshness","status": "ok"@@ -1493,6 +1664,7 @@"recovering_count": 0,"writer_owned_count": 1},+ "elapsed_ms": "<volatile>","message": "1 writer-owned content source(s); no pending canonical publication or recovery.","name": "canonical_content_writes","status": "ok"@@ -1515,6 +1687,7 @@"unpushed": 0}},+ "elapsed_ms": "<volatile>","fix": {"actor": "agent","argv": [@@ -1559,18 +1732,21 @@},{"category": "ops",+ "elapsed_ms": "<volatile>","message": "Single-source brain — sync --all consolidation not applicable.","name": "sync_consolidation","status": "ok"},{"category": "brain",+ "elapsed_ms": "<volatile>","message": "Extraction lag not applicable (no pages)","name": "links_extraction_lag","status": "ok"},{"category": "brain",+ "elapsed_ms": "<volatile>","message": "No full cycle yet for 'default': it holds no pages or only pages from the last 24h, so there is nothing to consolidate yet.","name": "cycle_freshness","readiness_state": "not_applicable",@@ -1579,24 +1755,28 @@},{"category": "brain",+ "elapsed_ms": "<volatile>","message": "No same-source content-hash duplicate groups","name": "content_hash_duplicates","status": "ok"},{"category": "brain",+ "elapsed_ms": "<volatile>","message": "All code-page chunks carry symbol metadata","name": "code_chunk_metadata","status": "ok"},{"category": "brain",+ "elapsed_ms": "<volatile>","message": "Every DB page is file-backed or under a declared/default db_only path (derive-phase defaults: life/events/ atoms/ concepts/ extracts/ dream-cycle-summaries/).","name": "undeclared_db_only_pages","status": "ok"},{"category": "ops",+ "elapsed_ms": "<volatile>","message": "No configured collectors declare output paths","name": "db_only_collector_collision","status": "ok"@@ -1607,12 +1787,14 @@"checkouts": 0,"tracked": []},+ "elapsed_ms": "<volatile>","message": "0 Git checkout(s) track no ownership marker (markers on disk stay untracked and are denied on push).","name": "tracked_ownership_marker","status": "ok"},{"category": "ops",+ "elapsed_ms": "<volatile>","message": "System One is off (every decide slot is off; nothing is sent).","name": "decide_health","status": "ok"@@ -1641,6 +1823,7 @@"unlinked": 0}},+ "elapsed_ms": "<volatile>","message": "No active facts yet; nothing to link.","name": "unlinked_facts","status": "ok"@@ -1659,6 +1842,7 @@"relationships": {},"stale_assertions": []},+ "elapsed_ms": "<volatile>","message": "relationships: none yet; read policy on; contradiction mode propose (default)","name": "edge_validity","status": "ok"@@ -1697,6 +1881,7 @@"unpricedCalls": 0}},+ "elapsed_ms": "<volatile>","message": "auto_chronicle is on (default). Last 24 h: 0 of 200 automatic extraction calls. Last 7 days: 0 extracted, 0 failed, 0 skipped; $0.00 known spend. 0 page(s) pending. No chat provider is configured, so nothing will be extracted until one is.","name": "auto_chronicle","readiness_state": "missing",@@ -1704,6 +1889,7 @@},{"category": "brain",+ "elapsed_ms": "<volatile>","message": "chronicle.* settings are valid.","name": "chronicle_config_invalid","status": "ok"@@ -1815,6 +2001,7 @@},"severity": "info"},+ "elapsed_ms": "<volatile>","fix": {"actor": "agent","argv": [@@ -1870,6 +2057,7 @@"last_run": null,"max_jobs": 50},+ "elapsed_ms": "<volatile>","message": "No facts-absorb jobs are queued (no run recorded yet).","name": "facts_drain","status": "ok"@@ -1892,6 +2080,7 @@"stale": 0}},+ "elapsed_ms": "<volatile>","message": "Every active fact and take has a voyage:voyage-4 vector for its current text.","name": "fact_take_vectors","status": "ok"@@ -1913,6 +2102,7 @@"missing_search_statistics": [],"stale": []},+ "elapsed_ms": "<volatile>","message": "Planner statistics are fresh on 6 hot tables.","name": "planner_stats_stale","status": "ok"@@ -1933,6 +2123,7 @@"weights": 0,"weights_off_neutral": 0},+ "elapsed_ms": "<volatile>","message": "Retrieval feedback is off; rankings do not learn from ratings. Turn it on with: gbrain config set feedback.enabled true","name": "retrieval_feedback_health","status": "ok"@@ -1944,6 +2135,7 @@"failed": [],"pending": 0},+ "elapsed_ms": "<volatile>","message": "Every page has its revision; the page revision backfill is complete.","name": "revision_backfill","status": "ok"@@ -2021,6 +2213,7 @@],"unknown_pct": 0},+ "elapsed_ms": "<volatile>","message": "No facts, takes, timeline entries or pages yet.","name": "trust_tiers","status": "ok"@@ -2038,6 +2231,7 @@"timeline_entries": 0}},+ "elapsed_ms": "<volatile>","message": "Every agent-written or lower row has been scanned by the current write-gate detector; flagged rows carry their flag, and proactive surfaces withhold them when trust.agent_activation is suppress.","name": "trust_scan","status": "ok"@@ -2049,6 +2243,7 @@"pending": [],"unclaimed": []},+ "elapsed_ms": "<volatile>","message": "No unclaimed source holds rows from before trust tiers.","name": "trust_sources_unclaimed","status": "ok"@@ -2064,22 +2259,11 @@"enabled": false,"pages": 0},+ "elapsed_ms": "<volatile>","message": "Core memory is off (opt-in). If the user wants a profile loaded in every session: gbrain config set memory.core.enabled true, then gbrain core init.","name": "core_memory","status": "ok"},- {- "category": "ops",- "details": {- "count": 0,- "docs": "docs/guides/troubleshooting.md#managed-sync-not-moving",- "parked": 0,- "sources": []- },- "message": "No managed sync is pending.",- "name": "managed_sync_not_moving",- "status": "ok"- },{"category": "ops","details": {@@ -2087,6 +2271,7 @@"count": 0,"docs": "docs/guides/troubleshooting.md#two-consumers-on-host"},+ "elapsed_ms": "<volatile>","message": "PGLite admits one process; no consumer heartbeat rows are kept.","name": "two_consumers_on_host","status": "ok"@@ -2098,6 +2283,7 @@"docs": "docs/guides/troubleshooting.md#two-consumers-on-host","owners": []},+ "elapsed_ms": "<volatile>","message": "PGLite admits one process; no consumer heartbeat rows are kept.","name": "consumers_without_heartbeat","status": "ok"@@ -2111,20 +2297,11 @@"host_json_path": "<home>/.gbrain/persistence/host.json","mismatches": []},+ "elapsed_ms": "<volatile>","message": "This process's host identity (<home>/.gbrain/persistence/host.json) owns every binding this filesystem holds.","name": "host_identity_mismatch","status": "ok"},- {- "category": "ops",- "details": {- "count": 0,- "docs": "docs/guides/troubleshooting.md#serve-build-drift"- },- "message": "PGLite admits one process; no consumer heartbeat rows are kept to compare builds.",- "name": "serve_build_drift",- "status": "ok"- },{"category": "brain","details": {@@ -2132,6 +2309,7 @@"held": 0,"items": []},+ "elapsed_ms": "<volatile>","message": "No managed atom page or transcript is held after repeated extraction failures.","name": "extract_atoms_held_failed","status": "ok"@@ -2209,12 +2387,14 @@},"warn_at_normalized_7d": 20},+ "elapsed_ms": "<volatile>","message": "No malformed facts or takes fence is held, stored or waiting in a checkout (1 source(s) scanned).","name": "fence_integrity","status": "ok"},{"category": "ops",+ "elapsed_ms": "<volatile>","message": "Mode: conservative (no per-key overrides — mode bundle is canonical).","name": "search_mode","status": "ok"@@ -2229,78 +2409,91 @@".raw/"]},+ "elapsed_ms": "<volatile>","message": "No pages hidden by search-exclude policy.","name": "hidden_by_search_policy","status": "ok"},{"category": "brain",+ "elapsed_ms": "<volatile>","message": "No retrieval-affecting files changed in working tree.","name": "eval_drift","status": "ok"},{"category": "ops",+ "elapsed_ms": "<volatile>","message": "Reranker disabled — no failures expected","name": "reranker_health","status": "ok"},{"category": "ops",+ "elapsed_ms": "<volatile>","message": "No exhausted batch retries in last 24h.","name": "batch_retry_health","status": "ok"},{"category": "ops",+ "elapsed_ms": "<volatile>","message": "PGLite — no queue to check","name": "wedged_queue","status": "ok"},{"category": "ops",+ "elapsed_ms": "<volatile>","message": "No orphaned private queues","name": "orphaned_private_queue","status": "ok"},{"category": "ops",+ "elapsed_ms": "<volatile>","message": "PGLite — single-writer, fan-out is 1","name": "autopilot_fanout_concurrency","status": "ok"},{"category": "ops",+ "elapsed_ms": "<volatile>","message": "no Google accounts connected (gbrain google connect to start)","name": "google_oauth","status": "ok"},{"category": "brain",+ "elapsed_ms": "<volatile>","message": "graph_signals disabled — coverage not checked","name": "graph_signals_coverage","status": "ok"},{"category": "brain",+ "elapsed_ms": "<volatile>","message": "No junk entity hubs (pages with <=2 chunks and >1000 edges)","name": "junk_entity_hubs","status": "ok"},{"category": "ops",+ "elapsed_ms": "<volatile>","message": "Migration v79 applied; tracking enabled. Calibration profile not yet generated — brainstorm/lsd will run unbiased until enough takes are resolved.","name": "brainstorm_health","status": "ok"},{"category": "brain",+ "elapsed_ms": "<volatile>","message": "Brain is empty — nothing to scan","name": "link_resolution_opportunity","status": "ok"},{"category": "brain",+ "elapsed_ms": "<volatile>","fix_unavailable_reason": "unstructured","message": "Schema width mismatch: content_chunks.embedding is vector(1024) but gateway resolved embedding_dimensions = 3072.\n\nEmbedding dimension mismatch detected.\n\n Existing column: vector(1024)\n Requested: vector(3072) (openai:text-embedding-3-large)\n\nSwitching dims re-embeds every chunk and fact;\nPGLite cannot ALTER vector column types in place (pgvector ships as WASM).\n\nKeep this brain's width (no rebuild; pages and facts kept):\n\n gbrain init --force --embedding-model openai:text-embedding-3-large --embedding-dimensions 1024 --path <home>/.gbrain/brain.pglite\n\nChange the width (re-embeds; pages and DB-only facts kept; preview first):\n\n gbrain migrate embeddings --to openai:text-embedding-3-large --dim 3072 --dry-run\n\nLast resort (moves the datastore aside; DB-only pages and facts are NOT carried over):\n\n gbrain reinit-pglite --embedding-model openai:text-embedding-3-large --embedding-dimensions 3072\n\nFull guide: docs/embedding-migrations.md","name": "embedding_width_consistency",@@ -2308,36 +2501,42 @@},{"category": "brain",+ "elapsed_ms": "<volatile>","message": "Skipped on PGLite (single bundled pgvector version).","name": "facts_embedding_width_consistency","status": "ok"},{"category": "brain",+ "elapsed_ms": "<volatile>","message": "Single-source brain (no federation to check)","name": "source_routing_health","status": "ok"},{"category": "ops",+ "elapsed_ms": "<volatile>","message": "No OAuth clients registered","name": "oauth_confidential_client_health","status": "ok"},{"category": "ops",+ "elapsed_ms": "<volatile>","message": "Scoped-client grants consistent (no dangling federated reads, no orphaned workspace sources, no privileged self-registered clients)","name": "oauth_client_scope_health","status": "ok"},{"category": "ops",+ "elapsed_ms": "<volatile>","message": "Lock path: <home>/.gbrain/autopilot.lock","name": "autopilot_lock_scope","status": "ok"},{"category": "ops",+ "elapsed_ms": "<volatile>","message": "No stale locks (no rows with ttl_expires_at < NOW())","name": "stale_locks","status": "ok"@@ -2382,30 +2581,35 @@"synthesize_concepts": "global"}},+ "elapsed_ms": "<volatile>","message": "Phase taxonomy: 12 source-scoped, 15 brain-global, 2 mixed. Source-safe: [lint, backlinks, sync, extract, extract_facts, extract_atoms, recompute_emotional_weight, consolidate, propose_takes, conversation_facts_backfill, enrich_thin, schema-suggest]. Brain-global: [fence_repair, content_repair, resolve_symbol_edges, synthesize_concepts, grade_takes, calibration_profile, edge_contradictions, drift, standing_questions, chronicle, facts_drain, skillopt, embed, orphans, purge]. Mixed: [synthesize, patterns].","name": "cycle_phase_scope","status": "ok"},{"category": "brain",+ "elapsed_ms": "<volatile>","message": "No stale chunks","name": "embed_staleness","status": "ok"},{"category": "brain",+ "elapsed_ms": "<volatile>","message": "No entity pages — coverage check vacuous","name": "entity_link_coverage","status": "ok"},{"category": "brain",+ "elapsed_ms": "<volatile>","message": "No entity pages — coverage check vacuous","name": "timeline_coverage","status": "ok"},{"category": "brain",+ "elapsed_ms": "<volatile>","fix": {"actor": "agent","argv": [@@ -2445,18 +2649,21 @@},{"category": "meta",+ "elapsed_ms": "<volatile>","message": "Active pack [email protected]+a50a67b9 is current (no successor declared)","name": "pack_upgrade_available","status": "ok"},{"category": "meta",+ "elapsed_ms": "<volatile>","message": "no typed pages","name": "type_proliferation","status": "ok"},{"category": "brain",+ "elapsed_ms": "<volatile>","message": "No dangling aliases","name": "dangling_aliases","status": "ok"diff --git a/test/fixtures/goldens/doctor/json-pglite-fast.json b/test/fixtures/goldens/doctor/json-pglite-fast.jsonindex c7b4947856..31de1f57ac 100644--- a/test/fixtures/goldens/doctor/json-pglite-fast.json+++ b/test/fixtures/goldens/doctor/json-pglite-fast.json@@ -19,6 +19,7 @@"checks": [{"category": "skill",+ "elapsed_ms": "<volatile>","message": "1 skills, all reachable","name": "resolver_health","status": "ok"@@ -33,6 +34,7 @@"path": "pglite — serve IPC socket not present","policy_skill_installed": false},+ "elapsed_ms": "<volatile>","fix": {"actor": "user","consent": [@@ -52,24 +54,28 @@},{"category": "skill",+ "elapsed_ms": "<volatile>","message": "no verb calls recorded yet (sidecar appears on first remember/recall/entity/synthesize/forget)","name": "memory_verbs_usage","status": "ok"},{"category": "skill",+ "elapsed_ms": "<volatile>","message": "1/1 skills pass","name": "skill_conformance","status": "ok"},{"category": "skill",+ "elapsed_ms": "<volatile>","message": "1 skill(s) compliant or exempt","name": "skill_brain_first","status": "ok"},{"category": "skill",+ "elapsed_ms": "<volatile>","message": "No skills.lock.json in <home>/skills — integrity check not applicable","name": "skills_manifest_integrity","status": "ok"@@ -145,6 +151,7 @@"webhook-transforms"]},+ "elapsed_ms": "<volatile>","fix_unavailable_reason": "unstructured","message": "64 new built-in skill(s) available that this workspace hasn't installed: academic-verify, archive-crawler, article-enrichment, ask-user, blog-ingest, book-mirror, brain-ingest-gate, brain-link-discipline, … +56 more. Add them with `gbrain skillpack sync`.","name": "skill_currency",@@ -152,6 +159,7 @@},{"category": "skill",+ "elapsed_ms": "<volatile>","message": "skill preconditions not checked (no connected brain)","name": "skill_preconditions","status": "ok"@@ -163,6 +171,7 @@"out_of_band_settable": true,"reason": "disabled"},+ "elapsed_ms": "<volatile>","message": "memorable relay off (default)","name": "memorable_relay_health","status": "ok"@@ -176,6 +185,7 @@"transient_ttl": "3d","ttl_valid": true},+ "elapsed_ms": "<volatile>","message": "ambient writeback off (default; file-plane mirror — database unreachable)","name": "memory_writeback","status": "ok"@@ -191,6 +201,7 @@"0.53.0"]},+ "elapsed_ms": "<volatile>","fix": {"actor": "agent","argv": [@@ -223,36 +234,42 @@},{"category": "ops",+ "elapsed_ms": "<volatile>","message": "mode=notify","name": "self_upgrade_health","status": "ok"},{"category": "ops",+ "elapsed_ms": "<volatile>","message": "Bun <bun-version> (minimum 1.4.0)","name": "bun_runtime","status": "ok"},{"category": "brain",+ "elapsed_ms": "<volatile>","message": "disabled (opt-in). Enable with: gbrain config set autopilot.nightly_quality_probe.enabled true","name": "nightly_quality_probe_health","status": "ok"},{"category": "ops",+ "elapsed_ms": "<volatile>","message": "No progressive-batch operations in the last 7 days","name": "progressive_batch_audit_health","status": "ok"},{"category": "brain",+ "elapsed_ms": "<volatile>","message": "disabled (opt-in; default-on only for search.mode=tokenmax). Enable with: `gbrain config set autopilot.conversation_parser_probe.enabled true`","name": "conversation_parser_probe_health","status": "ok"},{"category": "ops",+ "elapsed_ms": "<volatile>","message": "gbrain home is outside any enclosing git worktree.","name": "home_dir_in_worktree","status": "ok"@@ -269,6 +286,7 @@"embedding_model": "voyage:voyage-4","shadows": []},+ "elapsed_ms": "<volatile>","message": "No embedding key is set here (VOYAGE_API_KEY or voyage_api_key). No environment variable overrides a different config-plane provider key. This check sees only the environment `gbrain doctor` runs in; a daemon (gbrain serve, autopilot) has its own, and reports a mismatch in its log with a startup warning or embedding_auth_failed.","name": "embedding_key_source","status": "ok"@@ -279,6 +297,7 @@"decision": null,"provider_env": []},+ "elapsed_ms": "<volatile>","message": "No gbrain setup receipt records a provider-use decision for this install; provider calls follow the configured keys.","name": "provider_consent","readiness_state": "not_applicable",@@ -290,6 +309,7 @@"details": {"reason": "no_harness_detected"},+ "elapsed_ms": "<volatile>","fix": {"actor": "user","consent": [@@ -317,12 +337,14 @@"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>","fix": {"actor": "agent","argv": [diff --git a/test/fixtures/goldens/doctor/json-pglite-fresh.json b/test/fixtures/goldens/doctor/json-pglite-fresh.jsonindex 495967df89..b132031224 100644--- a/test/fixtures/goldens/doctor/json-pglite-fresh.json+++ b/test/fixtures/goldens/doctor/json-pglite-fresh.json@@ -21,6 +21,7 @@"checks": [{"category": "skill",+ "elapsed_ms": "<volatile>","message": "1 skills, all reachable","name": "resolver_health","status": "ok"@@ -35,6 +36,7 @@"path": "pglite — serve IPC socket not present","policy_skill_installed": false},+ "elapsed_ms": "<volatile>","fix": {"actor": "user","consent": [@@ -58,30 +60,35 @@"channels": {},"window_days": 7},+ "elapsed_ms": "<volatile>","message": "no push-context activity in 7 days — if a hook adapter is installed, confirm its registration landed and the harness session was RESTARTED (hooks snapshot at session start); a serve older than this build logs NOTHING for the hook lane — restart serve on the new build to activate the feedback loop","name": "volunteer_channels","status": "ok"},{"category": "skill",+ "elapsed_ms": "<volatile>","message": "no verb calls recorded yet (sidecar appears on first remember/recall/entity/synthesize/forget)","name": "memory_verbs_usage","status": "ok"},{"category": "skill",+ "elapsed_ms": "<volatile>","message": "1/1 skills pass","name": "skill_conformance","status": "ok"},{"category": "skill",+ "elapsed_ms": "<volatile>","message": "1 skill(s) compliant or exempt","name": "skill_brain_first","status": "ok"},{"category": "skill",+ "elapsed_ms": "<volatile>","message": "No skills.lock.json in <home>/skills — integrity check not applicable","name": "skills_manifest_integrity","status": "ok"@@ -157,6 +164,7 @@"webhook-transforms"]},+ "elapsed_ms": "<volatile>","fix_unavailable_reason": "unstructured","message": "64 new built-in skill(s) available that this workspace hasn't installed: academic-verify, archive-crawler, article-enrichment, ask-user, blog-ingest, book-mirror, brain-ingest-gate, brain-link-discipline, … +56 more. Add them with `gbrain skillpack sync`.","name": "skill_currency",@@ -164,6 +172,7 @@},{"category": "skill",+ "elapsed_ms": "<volatile>","message": "no installed skills declare preconditions","name": "skill_preconditions","status": "ok"@@ -175,6 +184,7 @@"out_of_band_settable": true,"reason": "disabled"},+ "elapsed_ms": "<volatile>","message": "memorable relay off (default)","name": "memorable_relay_health","status": "ok"@@ -208,12 +218,14 @@"ttl_valid": true,"visibility_note": "world = readable by agents authorized on THIS brain, not the public internet"},+ "elapsed_ms": "<volatile>","message": "ambient writeback off (default): Stop-hook turn capture is off, but the compaction harvest and SessionEnd transcripts still extract (installing the harness hooks opted into them; stop them: gbrain config set memory.auto_writeback off). Enable: gbrain config set memory.auto_writeback salient","name": "memory_writeback","status": "ok"},{"category": "ops",+ "elapsed_ms": "<volatile>","message": "No chat connectors configured (optional).","name": "connectors","status": "ok"@@ -227,6 +239,7 @@"keys": [],"threshold": 3},+ "elapsed_ms": "<volatile>","message": "No dream key died 3+ times in 24h","name": "dream_paid_loop","status": "ok"@@ -242,6 +255,7 @@"0.53.0"]},+ "elapsed_ms": "<volatile>","fix": {"actor": "agent","argv": [@@ -274,18 +288,21 @@},{"category": "ops",+ "elapsed_ms": "<volatile>","message": "mode=notify","name": "self_upgrade_health","status": "ok"},{"category": "ops",+ "elapsed_ms": "<volatile>","message": "Bun <bun-version> (minimum 1.4.0)","name": "bun_runtime","status": "ok"},{"category": "brain",+ "elapsed_ms": "<volatile>","message": "disabled (opt-in). Enable with: gbrain config set autopilot.nightly_quality_probe.enabled true","name": "nightly_quality_probe_health","status": "ok"@@ -296,12 +313,14 @@"kinds": [],"schema_version": 1},+ "elapsed_ms": "<volatile>","message": "no extractions in last 7 days","name": "extract_health","status": "ok"},{"category": "brain",+ "elapsed_ms": "<volatile>","message": "disabled (opt-in). Enable with: gbrain config set cycle.conversation_facts_backfill.enabled true","name": "conversation_facts_backlog","status": "ok"@@ -313,6 +332,7 @@"known_approximation": "page backlog only; transcript corpus not counted","pack_declares_phase": false},+ "elapsed_ms": "<volatile>","message": "no pages awaiting atom extraction","name": "extract_atoms_backlog","status": "ok"@@ -327,36 +347,42 @@"source_gone": 0,"total_atoms": 0},+ "elapsed_ms": "<volatile>","message": "no atoms to check","name": "atom_provenance_drift","status": "ok"},{"category": "brain",+ "elapsed_ms": "<volatile>","message": "No conversation-type pages — coverage check not applicable","name": "conversation_format_coverage","status": "ok"},{"category": "ops",+ "elapsed_ms": "<volatile>","message": "No progressive-batch operations in the last 7 days","name": "progressive_batch_audit_health","status": "ok"},{"category": "brain",+ "elapsed_ms": "<volatile>","message": "disabled (opt-in; default-on only for search.mode=tokenmax). Enable with: `gbrain config set autopilot.conversation_parser_probe.enabled true`","name": "conversation_parser_probe_health","status": "ok"},{"category": "ops",+ "elapsed_ms": "<volatile>","message": "gbrain home is outside any enclosing git worktree.","name": "home_dir_in_worktree","status": "ok"},{"category": "meta",+ "elapsed_ms": "<volatile>","message": "default source local_path is set: <home>/.gbrain/content/<uuid>/default","name": "default_source_local_path","status": "ok"@@ -373,6 +399,7 @@"embedding_model": "voyage:voyage-4","shadows": []},+ "elapsed_ms": "<volatile>","message": "No embedding key is set here (VOYAGE_API_KEY or voyage_api_key). No environment variable overrides a different config-plane provider key. This check sees only the environment `gbrain doctor` runs in; a daemon (gbrain serve, autopilot) has its own, and reports a mismatch in its log with a startup warning or embedding_auth_failed.","name": "embedding_key_source","status": "ok"@@ -383,6 +410,7 @@"decision": null,"provider_env": []},+ "elapsed_ms": "<volatile>","message": "No gbrain setup receipt records a provider-use decision for this install; provider calls follow the configured keys.","name": "provider_consent","readiness_state": "not_applicable",@@ -394,6 +422,7 @@"details": {"reason": "no_harness_detected"},+ "elapsed_ms": "<volatile>","fix": {"actor": "user","consent": [@@ -421,24 +450,139 @@"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, 0 pages","name": "connection","status": "ok"},{"category": "ops",+ "details": {+ "commands": [],+ "exact": true,+ "inspected": 2,+ "resources": [],+ "truncated": false+ },+ "elapsed_ms": "<volatile>",+ "message": "Managed write capacity is below 80% of every cumulative limit.",+ "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+ },+ "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",+ "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": "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"@@ -449,23 +593,11 @@"readiness": "ready","ready": true},+ "elapsed_ms": "<volatile>","message": "Visible text projections match their canonical revisions.","name": "text_projection_readiness","status": "ok"},- {- "category": "ops",- "details": {- "commands": [],- "exact": true,- "inspected": 2,- "resources": [],- "truncated": false- },- "message": "Managed write capacity is below 80% of every cumulative limit.",- "name": "persistence_capacity",- "status": "ok"- },{"category": "brain","details": {@@ -475,6 +607,7 @@"parked_effects": 0,"truncated": false},+ "elapsed_ms": "<volatile>","message": "No Git or withdrawal effect is parked.","name": "parked_effects","status": "ok"@@ -484,6 +617,7 @@"details": {"refreshes": []},+ "elapsed_ms": "<volatile>","message": "No worktree refresh is stuck.","name": "worktree_refresh_stuck","status": "ok"@@ -495,6 +629,7 @@"page_child_source_columns": [],"runbook": "docs/guides/write-refusals.md#managed-guard-page-children"},+ "elapsed_ms": "<volatile>","message": "Guarded tables carry only the columns gbrain creates.","name": "managed_guard_schema_drift","status": "ok"@@ -508,48 +643,56 @@"unclassified_p0001": 0,"window_days": 7},+ "elapsed_ms": "<volatile>","message": "No write was refused by a database guard in the last 7 days.","name": "publication_refusals","status": "ok"},{"category": "meta",+ "elapsed_ms": "<volatile>","message": "links_link_source_check has the v114 kebab-case gate","name": "links_link_source_check","status": "ok"},{"category": "ops",+ "elapsed_ms": "<volatile>","message": "PGLite at 0 pages — comfortable below the 1000-page threshold","name": "pglite_scale","status": "ok"},{"category": "ops",+ "elapsed_ms": "<volatile>","message": "Skipped (PGLite — no PostgREST exposure, RLS not applicable)","name": "rls","status": "ok"},{"category": "meta",+ "elapsed_ms": "<volatile>","message": "Version <latest> (latest: <latest>)","name": "schema_version","status": "ok"},{"category": "meta",+ "elapsed_ms": "<volatile>","message": "1115 column(s) verified against live schema","name": "schema_columns","status": "ok"},{"category": "ops",+ "elapsed_ms": "<volatile>","message": "Skipped (PGLite — no event trigger support)","name": "rls_event_trigger","status": "ok"},{"category": "brain",+ "elapsed_ms": "<volatile>","fix": {"actor": "user","argv": [@@ -599,6 +742,7 @@},{"category": "brain",+ "elapsed_ms": "<volatile>","fix": {"actor": "user","argv": [@@ -648,24 +792,28 @@},{"category": "brain",+ "elapsed_ms": "<volatile>","message": "Registry healthy: 1 columns (embedding_image); primary embeddings disabled","name": "embedding_column_registry","status": "ok"},{"category": "brain",+ "elapsed_ms": "<volatile>","message": "no embedding env overrides set","name": "embedding_env_override","status": "ok"},{"category": "brain",+ "elapsed_ms": "<volatile>","message": "no embedding migration in flight","name": "embedding_migration_state","status": "ok"},{"category": "brain",+ "elapsed_ms": "<volatile>","message": "Embeddings are off on this brain, so facts are only deduplicated by exact text; no supersession threshold applies.","name": "supersession_calibration","readiness_state": "not_applicable",@@ -674,48 +822,56 @@},{"category": "ops",+ "elapsed_ms": "<volatile>","message": "No chat_fallback_chain is set: every chat call uses only its own model.","name": "chat_fallback_chain","status": "ok"},{"category": "meta",+ "elapsed_ms": "<volatile>","message": "Nothing to disclose: this brain is a fresh install at v<version>, after every disclosed behavior change, so the one-time behavior-change notice does not apply.","name": "behavior_changes","status": "ok"},{"category": "brain",+ "elapsed_ms": "<volatile>","message": "No entity pages — graph_coverage not applicable (markdown-only brain)","name": "graph_coverage","status": "ok"},{"category": "brain",+ "elapsed_ms": "<volatile>","message": "Brain score 100/100","name": "brain_score","status": "ok"},{"category": "brain",+ "elapsed_ms": "<volatile>","message": "Vacuous: 0 entity pages (<100). Orphan ratio not meaningful at this scale.","name": "orphan_ratio","status": "ok"},{"category": "brain",+ "elapsed_ms": "<volatile>","message": "No by-mention links in this brain.","name": "stale_mentions","status": "ok"},{"category": "brain",+ "elapsed_ms": "<volatile>","message": "No orphaned timeline rows across 0 page(s).","name": "timeline_orphans","status": "ok"},{"category": "brain",+ "elapsed_ms": "<volatile>","message": "No slug collisions across 1 source checkout(s).","name": "slug_collisions","status": "ok"@@ -731,6 +887,7 @@"repair": "timeline","truncated": false},+ "elapsed_ms": "<volatile>","message": "Every timeline row has a bullet in its page (0 page(s) inspected).","name": "timeline_history","status": "ok"@@ -746,6 +903,7 @@"unstamped_atoms": 0,"unstamped_concepts": 0},+ "elapsed_ms": "<volatile>","message": "Every extracted atom and synthesized concept carries an explicit visibility no looser than its origin.","name": "derived_visibility","status": "ok"@@ -759,6 +917,7 @@"repair": "safe-chunks","truncated": false},+ "elapsed_ms": "<volatile>","message": "Every re-sealable page is at the safe-chunk index version.","name": "safe_index_pending","status": "ok"@@ -771,6 +930,7 @@"pages_pending": 0,"truncated": false},+ "elapsed_ms": "<volatile>","message": "No page waits for the credential-safe re-chunk.","name": "credential_projection_pending","status": "ok"@@ -785,6 +945,7 @@"retries": 0,"truncated": false},+ "elapsed_ms": "<volatile>","message": "No orphan connector checkpoint rows older than 7 days.","name": "connector_checkpoints","status": "ok"@@ -811,6 +972,7 @@],"repair": "request-indexes"},+ "elapsed_ms": "<volatile>","message": "Managed sync request indexes are valid.","name": "persistence_request_indexes","status": "ok"@@ -849,6 +1011,7 @@"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.","name": "persistence_request_growth","status": "ok"@@ -868,6 +1031,7 @@},"stalls": []},+ "elapsed_ms": "<volatile>","message": "No write request has held its claim longer than persistence.max_claim_ms (600000 ms).","name": "persistence_write_stall","status": "ok"@@ -881,62 +1045,11 @@"repair": "failed-writes","writes": []},+ "elapsed_ms": "<volatile>","message": "Every caller write with a retained receipt committed or was superseded.","name": "lost_caller_writes","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- },- "message": "No terminal write failures in the last 7 d.",- "name": "persistence_terminal_failures",- "status": "ok"- },{"category": "ops","details": {@@ -944,6 +1057,7 @@"configured": "5min","docs": "docs/guides/troubleshooting.md#session-timeouts-not-applied"},+ "elapsed_ms": "<volatile>","message": "PGLite has no session to time out.","name": "persistence_session_timeouts","status": "ok"@@ -955,6 +1069,7 @@"held": 0,"sources": []},+ "elapsed_ms": "<volatile>","message": "No connector items are held.","name": "connector_held_items","status": "ok"@@ -968,6 +1083,7 @@"source_ids": [],"sources": []},+ "elapsed_ms": "<volatile>","message": "No Git source files are held.","name": "git_held_files","status": "ok"@@ -979,6 +1095,7 @@"docs": "docs/guides/repair.md#held-files","hooks": []},+ "elapsed_ms": "<volatile>","message": "No outdated gbrain frontmatter pre-commit hook is installed.","name": "frontmatter_hook","status": "ok"@@ -992,6 +1109,7 @@"repair": "orphan-bindings","truncated": false},+ "elapsed_ms": "<volatile>","message": "Every persistence source binding belongs to an existing source.","name": "orphan_persistence_bindings","status": "ok"@@ -1003,6 +1121,7 @@"docs": "docs/guides/write-refusals.md#foreign-ownership-marker","markers": []},+ "elapsed_ms": "<volatile>","message": "Every ownership marker beside a source checkout belongs to this brain.","name": "foreign_ownership_marker","status": "ok"@@ -1013,6 +1132,7 @@"sources": [],"total": 0},+ "elapsed_ms": "<volatile>","message": "No page was written database-only to an unbound source.","name": "unbound_source","status": "ok"@@ -1042,6 +1162,7 @@"truncated": false,"window_days": 7},+ "elapsed_ms": "<volatile>","message": "Every writer that admitted or published a request in the last 7 days is v0.60.5.0 or newer.","name": "writer_version","status": "ok"@@ -1054,6 +1175,7 @@"truncated": false,"unclassifiable": 0},+ "elapsed_ms": "<volatile>","message": "No session corpus is configured; nothing to classify.","name": "self_capture","status": "ok"@@ -1064,6 +1186,7 @@"outcome": "skipped","reason": "pglite"},+ "elapsed_ms": "<volatile>","message": "Skipped: PGLite runs vector search in-process; the plan check applies to Postgres brains.","name": "vector_plan","status": "ok"@@ -1074,6 +1197,7 @@"outcome": "skipped","reason": "pglite"},+ "elapsed_ms": "<volatile>","message": "Skipped: PGLite runs keyword search with no statement timeout; the canary applies to Postgres brains.","name": "keyword_plan","status": "ok"@@ -1092,6 +1216,7 @@"stale_effects": 0,"truncated": false},+ "elapsed_ms": "<volatile>","message": "No committed write has a stale queued or failed embedding effect.","name": "stale_embedding_effects","status": "ok"@@ -1104,6 +1229,7 @@"repair": "google-file-modes","sources": []},+ "elapsed_ms": "<volatile>","message": "No group- or world-readable gbrain files under Google source directories outside ~/.gbrain.","name": "google_file_modes","status": "ok"@@ -1117,6 +1243,7 @@"excluded": 0,"repair": "extractor-facts"},+ "elapsed_ms": "<volatile>","message": "No conversation-extractor fact is left expired by the pre-v0.60.11.0 projection.","name": "extractor_facts_expired","status": "ok"@@ -1129,6 +1256,7 @@"evidenced": 0,"repair": "conversation-labels"},+ "elapsed_ms": "<volatile>","message": "No conversation fact carries the pre-fix meeting-label signature (a 1970-01-01 segment on a label page).","name": "conversation_label_facts","status": "ok"@@ -1144,6 +1272,7 @@"stale": 0,"unstamped": 0},+ "elapsed_ms": "<volatile>","message": "No conversation extraction outcome predates extractor version 1.","name": "conversation_outcomes_stale","status": "ok"@@ -1158,6 +1287,7 @@"repair": "captured-facts","unclassifiable": 0},+ "elapsed_ms": "<volatile>","message": "No active fact from a gbrain self-capture or paste candidate remains. This counts facts in the database; the self_capture check counts corpus files.","name": "captured_facts_active","status": "ok"@@ -1169,6 +1299,7 @@"drifted": 0,"repair": "loop-facts"},+ "elapsed_ms": "<volatile>","message": "Every closed commitment loop has its fact retired.","name": "loop_facts_drift","status": "ok"@@ -1182,6 +1313,7 @@"repair": "ontology-facts","retired": 0},+ "elapsed_ms": "<volatile>","message": "No ontology observation is held by a page's Facts table.","name": "ontology_facts_fenced","status": "ok"@@ -1195,6 +1327,7 @@"source_ids": [],"sources": []},+ "elapsed_ms": "<volatile>","message": "No stored frontmatter carries a parser-reserved key (type, title, tags, slug).","name": "stale_frontmatter_keys","status": "ok"@@ -1209,102 +1342,119 @@"sources": [],"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"},{"category": "brain",+ "elapsed_ms": "<volatile>","message": "Relative dates resolve against each source's observation date in fact extraction, dream synthesis, extract_atoms and propose_takes (the default). life chronicle events keep their current prompt unless extraction.date_grounding is set to true. Facts extracted before this was on keep their original wording; re-extract a source only with the user's consent (gbrain extract-conversation-facts --source-id <id> --dry-run previews it).","name": "extraction_date_grounding","status": "ok"},{"category": "brain",+ "elapsed_ms": "<volatile>","message": "Sampled 0 pages; no bare-tweet phrases or external links.","name": "integrity","status": "ok"},{"category": "brain",+ "elapsed_ms": "<volatile>","message": "All JSONB columns store objects/arrays","name": "jsonb_integrity","status": "ok"},{"category": "brain",+ "elapsed_ms": "<volatile>","message": "No takes yet","name": "takes_weight_grid","status": "ok"},{"category": "brain",+ "elapsed_ms": "<volatile>","message": "All FK-child tables clean (10 tables checked)","name": "child_table_orphans","status": "ok"},{"category": "brain",+ "elapsed_ms": "<volatile>","message": "All synthesized pages carry a raw trace or explicit exemption","name": "raw_provenance","status": "ok"},{"category": "brain",+ "elapsed_ms": "<volatile>","message": "All source config values are JSON objects","name": "source_config_shape","status": "ok"},{"category": "skill",+ "elapsed_ms": "<volatile>","message": "whoknows eval fixture present (10 queries). Run `gbrain eval whoknows test/fixtures/whoknows-eval.jsonl` to grade.","name": "whoknows_health","status": "ok"},{"category": "brain",+ "elapsed_ms": "<volatile>","message": "All image-asset chunks have modality=image","name": "cross_modal_modality_backfill","status": "ok"},{"category": "brain",+ "elapsed_ms": "<volatile>","message": "search.unified_multimodal is off; coverage check N/A","name": "unified_multimodal_coverage","status": "ok"},{"category": "brain",+ "elapsed_ms": "<volatile>","message": "No truncated bodies detected","name": "markdown_body_completeness","status": "ok"},{"category": "brain",+ "elapsed_ms": "<volatile>","message": "No pages exceed 500000 bytes (excluding embed_skip pages, which already took the accepted non-embeddable remediation)","name": "oversized_pages","status": "ok"},{"category": "brain",+ "elapsed_ms": "<volatile>","message": "No junk-pattern hits in 0 recent page(s) (use --content-audit for full scan)","name": "scraper_junk_pages","status": "ok"},{"category": "brain",+ "elapsed_ms": "<volatile>","message": "No content-sanity events in last 7 days (audit JSONL is local to this host; share GBRAIN_AUDIT_DIR for multi-host visibility)","name": "content_sanity_audit_recent","status": "ok"},{"category": "brain",+ "elapsed_ms": "<volatile>","message": "No quarantined pages","name": "quarantined_pages","status": "ok"},{"category": "brain",+ "elapsed_ms": "<volatile>","message": "No flagged pages","name": "flagged_pages","status": "ok"@@ -1316,12 +1466,14 @@"days": 7,"source_id": null},+ "elapsed_ms": "<volatile>","message": "No stale unverified extraction stubs","name": "unverified_extractions","status": "ok"},{"category": "brain",+ "elapsed_ms": "<volatile>","message": "1 source(s) clean — no frontmatter issues","name": "frontmatter_integrity","status": "ok"@@ -1336,36 +1488,42 @@"sources": [],"unscanned": []},+ "elapsed_ms": "<volatile>","message": "No file has frontmatter gbrain repair frontmatter would fix.","name": "frontmatter_repairable","status": "ok"},{"category": "meta",+ "elapsed_ms": "<volatile>","message": "No capture failures in the last 24h","name": "eval_capture","status": "ok"},{"category": "brain",+ "elapsed_ms": "<volatile>","message": "No probe runs in the last 7 days. Run `gbrain eval suspected-contradictions --query \"...\" --top-k 5` to populate.","name": "contradictions","status": "ok"},{"category": "brain",+ "elapsed_ms": "<volatile>","message": "Automatic fact extraction not configured (keyless) — memory comes from agent-authored `## Facts` fences and the `remember` verb. One optional key enables automatic extraction (OpenAI or Anthropic).","name": "facts_extraction_health","status": "ok"},{"category": "brain",+ "elapsed_ms": "<volatile>","message": "Sample of last 1000 pages clean (no fallback-with-parseable-fm-date, no future-dated, no pre-1990)","name": "effective_date_health","status": "ok"},{"category": "brain",+ "elapsed_ms": "<volatile>","message": "Skipped (no pages have emotional_weight > 0; either fresh install or recompute hasn't run yet)","name": "salience_health","status": "ok"@@ -1378,24 +1536,28 @@"engine": "pglite","worker_alive": true},+ "elapsed_ms": "<volatile>","message": "PGLite: no jobs waiting for a worker.","name": "queue_health","status": "ok"},{"category": "ops",+ "elapsed_ms": "<volatile>","message": "Subagent tier resolves to default (claude-sonnet-4-6) — full tool-loop capability","name": "subagent_capability","status": "ok"},{"category": "brain",+ "elapsed_ms": "<volatile>","message": "facts_health(default): 0 active, 0 today, 0 this week, 0 consolidated, top entities —","name": "facts_health","status": "ok"},{"category": "ops",+ "elapsed_ms": "<volatile>","message": "Brain-wide maintenance jobs are finishing within their deadline.","name": "global_maintenance_timeouts","status": "ok"@@ -1418,6 +1580,7 @@"unsupported": 0,"unsupported_ids": []},+ "elapsed_ms": "<volatile>","message": "No queued job predates submission authority.","name": "legacy_job_authority","status": "ok"@@ -1431,6 +1594,7 @@"malformed": [],"mirror_window_ends": "2026-11-04"},+ "elapsed_ms": "<volatile>","message": "Every active legacy token uses the unified grant columns. The permissions mirror for older gbrain binaries is kept until 2026-11-04.","name": "legacy_token_grant_shape","status": "ok"@@ -1442,6 +1606,7 @@"drift": [],"mirror_window_ends": "2026-11-04"},+ "elapsed_ms": "<volatile>","message": "No legacy token grant has drifted from its permissions mirror.","name": "legacy_token_grant_drift","status": "ok"@@ -1453,6 +1618,7 @@"null_scope_count": 0,"tokens": []},+ "elapsed_ms": "<volatile>","message": "Every active legacy token has explicit scopes.","name": "legacy_token_null_scope","status": "ok"@@ -1464,18 +1630,21 @@"grants": [],"server_surface": "full"},+ "elapsed_ms": "<volatile>","message": "Every active client and token can call the operations its scopes allow.","name": "grant_new_ops_available","status": "ok"},{"category": "brain",+ "elapsed_ms": "<volatile>","message": "No image assets indexed yet","name": "image_assets","status": "ok"},{"category": "brain",+ "elapsed_ms": "<volatile>","message": "OCR not in use (or no images ingested with OCR opt-in)","name": "ocr_health","status": "ok"@@ -1489,6 +1658,7 @@"unsupported_holds": 0,"without_image_vector": 0},+ "elapsed_ms": "<volatile>","message": "No image pages indexed yet.","name": "image_embedding_coverage","status": "ok"@@ -1501,6 +1671,7 @@"unchanged_count": 0,"writer_owned_count": 1},+ "elapsed_ms": "<volatile>","message": "1 writer-owned canonical content source(s): upstream sync is not applicable; see canonical_content_writes for publication status.","name": "sync_freshness","status": "ok"@@ -1512,6 +1683,7 @@"recovering_count": 0,"writer_owned_count": 1},+ "elapsed_ms": "<volatile>","message": "1 writer-owned content source(s); no pending canonical publication or recovery.","name": "canonical_content_writes","status": "ok"@@ -1534,6 +1706,7 @@"unpushed": 0}},+ "elapsed_ms": "<volatile>","fix": {"actor": "agent","argv": [@@ -1578,18 +1751,21 @@},{"category": "ops",+ "elapsed_ms": "<volatile>","message": "Single-source brain — sync --all consolidation not applicable.","name": "sync_consolidation","status": "ok"},{"category": "brain",+ "elapsed_ms": "<volatile>","message": "Extraction lag not applicable (no pages)","name": "links_extraction_lag","status": "ok"},{"category": "brain",+ "elapsed_ms": "<volatile>","message": "No full cycle yet for 'default': it holds no pages or only pages from the last 24h, so there is nothing to consolidate yet.","name": "cycle_freshness","readiness_state": "not_applicable",@@ -1598,24 +1774,28 @@},{"category": "brain",+ "elapsed_ms": "<volatile>","message": "No same-source content-hash duplicate groups","name": "content_hash_duplicates","status": "ok"},{"category": "brain",+ "elapsed_ms": "<volatile>","message": "All code-page chunks carry symbol metadata","name": "code_chunk_metadata","status": "ok"},{"category": "brain",+ "elapsed_ms": "<volatile>","message": "Every DB page is file-backed or under a declared/default db_only path (derive-phase defaults: life/events/ atoms/ concepts/ extracts/ dream-cycle-summaries/).","name": "undeclared_db_only_pages","status": "ok"},{"category": "ops",+ "elapsed_ms": "<volatile>","message": "No configured collectors declare output paths","name": "db_only_collector_collision","status": "ok"@@ -1626,12 +1806,14 @@"checkouts": 0,"tracked": []},+ "elapsed_ms": "<volatile>","message": "0 Git checkout(s) track no ownership marker (markers on disk stay untracked and are denied on push).","name": "tracked_ownership_marker","status": "ok"},{"category": "ops",+ "elapsed_ms": "<volatile>","message": "System One is off (every decide slot is off; nothing is sent).","name": "decide_health","status": "ok"@@ -1660,6 +1842,7 @@"unlinked": 0}},+ "elapsed_ms": "<volatile>","message": "No active facts yet; nothing to link.","name": "unlinked_facts","status": "ok"@@ -1678,6 +1861,7 @@"relationships": {},"stale_assertions": []},+ "elapsed_ms": "<volatile>","message": "relationships: none yet; read policy on; contradiction mode propose (default)","name": "edge_validity","status": "ok"@@ -1716,6 +1900,7 @@"unpricedCalls": 0}},+ "elapsed_ms": "<volatile>","message": "auto_chronicle is on (default). Last 24 h: 0 of 200 automatic extraction calls. Last 7 days: 0 extracted, 0 failed, 0 skipped; $0.00 known spend. 0 page(s) pending. No chat provider is configured, so nothing will be extracted until one is.","name": "auto_chronicle","readiness_state": "missing",@@ -1723,6 +1908,7 @@},{"category": "brain",+ "elapsed_ms": "<volatile>","message": "chronicle.* settings are valid.","name": "chronicle_config_invalid","status": "ok"@@ -1834,6 +2020,7 @@},"severity": "info"},+ "elapsed_ms": "<volatile>","fix": {"actor": "agent","argv": [@@ -1889,6 +2076,7 @@"last_run": null,"max_jobs": 50},+ "elapsed_ms": "<volatile>","message": "No facts-absorb jobs are queued (no run recorded yet).","name": "facts_drain","status": "ok"@@ -1898,6 +2086,7 @@"details": {"applicable": false},+ "elapsed_ms": "<volatile>","message": "Not applicable: embeddings are disabled on this brain (keyword search keeps working).","name": "fact_take_vectors","readiness_state": "disabled_by_choice",@@ -1921,6 +2110,7 @@"missing_search_statistics": [],"stale": []},+ "elapsed_ms": "<volatile>","message": "Planner statistics are fresh on 6 hot tables.","name": "planner_stats_stale","status": "ok"@@ -1941,6 +2131,7 @@"weights": 0,"weights_off_neutral": 0},+ "elapsed_ms": "<volatile>","message": "Retrieval feedback is off; rankings do not learn from ratings. Turn it on with: gbrain config set feedback.enabled true","name": "retrieval_feedback_health","status": "ok"@@ -1952,6 +2143,7 @@"failed": [],"pending": 0},+ "elapsed_ms": "<volatile>","message": "Every page has its revision; the page revision backfill is complete.","name": "revision_backfill","status": "ok"@@ -2029,6 +2221,7 @@],"unknown_pct": 0},+ "elapsed_ms": "<volatile>","message": "No facts, takes, timeline entries or pages yet.","name": "trust_tiers","status": "ok"@@ -2046,6 +2239,7 @@"timeline_entries": 0}},+ "elapsed_ms": "<volatile>","message": "Every agent-written or lower row has been scanned by the current write-gate detector; flagged rows carry their flag, and proactive surfaces withhold them when trust.agent_activation is suppress.","name": "trust_scan","status": "ok"@@ -2057,6 +2251,7 @@"pending": [],"unclaimed": []},+ "elapsed_ms": "<volatile>","message": "No unclaimed source holds rows from before trust tiers.","name": "trust_sources_unclaimed","status": "ok"@@ -2072,22 +2267,11 @@"enabled": false,"pages": 0},+ "elapsed_ms": "<volatile>","message": "Core memory is off (opt-in). If the user wants a profile loaded in every session: gbrain config set memory.core.enabled true, then gbrain core init.","name": "core_memory","status": "ok"},- {- "category": "ops",- "details": {- "count": 0,- "docs": "docs/guides/troubleshooting.md#managed-sync-not-moving",- "parked": 0,- "sources": []- },- "message": "No managed sync is pending.",- "name": "managed_sync_not_moving",- "status": "ok"- },{"category": "ops","details": {@@ -2095,6 +2279,7 @@"count": 0,"docs": "docs/guides/troubleshooting.md#two-consumers-on-host"},+ "elapsed_ms": "<volatile>","message": "PGLite admits one process; no consumer heartbeat rows are kept.","name": "two_consumers_on_host","status": "ok"@@ -2106,6 +2291,7 @@"docs": "docs/guides/troubleshooting.md#two-consumers-on-host","owners": []},+ "elapsed_ms": "<volatile>","message": "PGLite admits one process; no consumer heartbeat rows are kept.","name": "consumers_without_heartbeat","status": "ok"@@ -2119,20 +2305,11 @@"host_json_path": "<home>/.gbrain/persistence/host.json","mismatches": []},+ "elapsed_ms": "<volatile>","message": "This process's host identity (<home>/.gbrain/persistence/host.json) owns every binding this filesystem holds.","name": "host_identity_mismatch","status": "ok"},- {- "category": "ops",- "details": {- "count": 0,- "docs": "docs/guides/troubleshooting.md#serve-build-drift"- },- "message": "PGLite admits one process; no consumer heartbeat rows are kept to compare builds.",- "name": "serve_build_drift",- "status": "ok"- },{"category": "brain","details": {@@ -2140,6 +2317,7 @@"held": 0,"items": []},+ "elapsed_ms": "<volatile>","message": "No managed atom page or transcript is held after repeated extraction failures.","name": "extract_atoms_held_failed","status": "ok"@@ -2217,12 +2395,14 @@},"warn_at_normalized_7d": 20},+ "elapsed_ms": "<volatile>","message": "No malformed facts or takes fence is held, stored or waiting in a checkout (1 source(s) scanned).","name": "fence_integrity","status": "ok"},{"category": "ops",+ "elapsed_ms": "<volatile>","message": "Mode: conservative (no per-key overrides — mode bundle is canonical).","name": "search_mode","status": "ok"@@ -2237,114 +2417,133 @@".raw/"]},+ "elapsed_ms": "<volatile>","message": "No pages hidden by search-exclude policy.","name": "hidden_by_search_policy","status": "ok"},{"category": "brain",+ "elapsed_ms": "<volatile>","message": "No retrieval-affecting files changed in working tree.","name": "eval_drift","status": "ok"},{"category": "ops",+ "elapsed_ms": "<volatile>","message": "Reranker disabled — no failures expected","name": "reranker_health","status": "ok"},{"category": "ops",+ "elapsed_ms": "<volatile>","message": "No exhausted batch retries in last 24h.","name": "batch_retry_health","status": "ok"},{"category": "ops",+ "elapsed_ms": "<volatile>","message": "PGLite — no queue to check","name": "wedged_queue","status": "ok"},{"category": "ops",+ "elapsed_ms": "<volatile>","message": "No orphaned private queues","name": "orphaned_private_queue","status": "ok"},{"category": "ops",+ "elapsed_ms": "<volatile>","message": "PGLite — single-writer, fan-out is 1","name": "autopilot_fanout_concurrency","status": "ok"},{"category": "ops",+ "elapsed_ms": "<volatile>","message": "no Google accounts connected (gbrain google connect to start)","name": "google_oauth","status": "ok"},{"category": "brain",+ "elapsed_ms": "<volatile>","message": "graph_signals disabled — coverage not checked","name": "graph_signals_coverage","status": "ok"},{"category": "brain",+ "elapsed_ms": "<volatile>","message": "No junk entity hubs (pages with <=2 chunks and >1000 edges)","name": "junk_entity_hubs","status": "ok"},{"category": "ops",+ "elapsed_ms": "<volatile>","message": "Migration v79 applied; tracking enabled. Calibration profile not yet generated — brainstorm/lsd will run unbiased until enough takes are resolved.","name": "brainstorm_health","status": "ok"},{"category": "brain",+ "elapsed_ms": "<volatile>","message": "Brain is empty — nothing to scan","name": "link_resolution_opportunity","status": "ok"},{"category": "brain",+ "elapsed_ms": "<volatile>","message": "Embeddings disabled — no active embedding width to reconcile.","name": "embedding_width_consistency","status": "ok"},{"category": "brain",+ "elapsed_ms": "<volatile>","message": "Skipped on PGLite (single bundled pgvector version).","name": "facts_embedding_width_consistency","status": "ok"},{"category": "brain",+ "elapsed_ms": "<volatile>","message": "Single-source brain (no federation to check)","name": "source_routing_health","status": "ok"},{"category": "ops",+ "elapsed_ms": "<volatile>","message": "No OAuth clients registered","name": "oauth_confidential_client_health","status": "ok"},{"category": "ops",+ "elapsed_ms": "<volatile>","message": "Scoped-client grants consistent (no dangling federated reads, no orphaned workspace sources, no privileged self-registered clients)","name": "oauth_client_scope_health","status": "ok"},{"category": "ops",+ "elapsed_ms": "<volatile>","message": "Lock path: <home>/.gbrain/autopilot.lock","name": "autopilot_lock_scope","status": "ok"},{"category": "ops",+ "elapsed_ms": "<volatile>","message": "No stale locks (no rows with ttl_expires_at < NOW())","name": "stale_locks","status": "ok"@@ -2389,12 +2588,14 @@"synthesize_concepts": "global"}},+ "elapsed_ms": "<volatile>","message": "Phase taxonomy: 12 source-scoped, 15 brain-global, 2 mixed. Source-safe: [lint, backlinks, sync, extract, extract_facts, extract_atoms, recompute_emotional_weight, consolidate, propose_takes, conversation_facts_backfill, enrich_thin, schema-suggest]. Brain-global: [fence_repair, content_repair, resolve_symbol_edges, synthesize_concepts, grade_takes, calibration_profile, edge_contradictions, drift, standing_questions, chronicle, facts_drain, skillopt, embed, orphans, purge]. Mixed: [synthesize, patterns].","name": "cycle_phase_scope","status": "ok"},{"category": "brain",+ "elapsed_ms": "<volatile>","fix": {"actor": "user","argv": [@@ -2444,18 +2645,21 @@},{"category": "brain",+ "elapsed_ms": "<volatile>","message": "No entity pages — coverage check vacuous","name": "entity_link_coverage","status": "ok"},{"category": "brain",+ "elapsed_ms": "<volatile>","message": "No entity pages — coverage check vacuous","name": "timeline_coverage","status": "ok"},{"category": "brain",+ "elapsed_ms": "<volatile>","fix": {"actor": "agent","argv": [@@ -2495,18 +2699,21 @@},{"category": "meta",+ "elapsed_ms": "<volatile>","message": "Active pack [email protected]+a50a67b9 is current (no successor declared)","name": "pack_upgrade_available","status": "ok"},{"category": "meta",+ "elapsed_ms": "<volatile>","message": "no typed pages","name": "type_proliferation","status": "ok"},{"category": "brain",+ "elapsed_ms": "<volatile>","message": "No dangling aliases","name": "dangling_aliases","status": "ok"diff --git a/test/fixtures/goldens/doctor/json-postgres-fresh.json b/test/fixtures/goldens/doctor/json-postgres-fresh.jsonindex 366c25fbe2..5253ef2601 100644--- a/test/fixtures/goldens/doctor/json-postgres-fresh.json+++ b/test/fixtures/goldens/doctor/json-postgres-fresh.json@@ -21,6 +21,7 @@"checks": [{"category": "skill",+ "elapsed_ms": "<volatile>","message": "1 skills, all reachable","name": "resolver_health","status": "ok"@@ -35,6 +36,7 @@"path": "postgres direct","policy_skill_installed": false},+ "elapsed_ms": "<volatile>","message": "postgres direct; enabled; not observed firing yet — policy skill not installed; run `gbrain integrations install retrieval-reflex --target <host-repo>`","name": "retrieval_reflex_health","status": "ok"@@ -45,30 +47,35 @@"channels": {},"window_days": 7},+ "elapsed_ms": "<volatile>","message": "no push-context activity in 7 days — note: the harness-hook channels require a PGLite serve socket — on this engine the hook lane stays quiet by design (pull-mode retrieval covers it)","name": "volunteer_channels","status": "ok"},{"category": "skill",+ "elapsed_ms": "<volatile>","message": "no verb calls recorded yet (sidecar appears on first remember/recall/entity/synthesize/forget)","name": "memory_verbs_usage","status": "ok"},{"category": "skill",+ "elapsed_ms": "<volatile>","message": "1/1 skills pass","name": "skill_conformance","status": "ok"},{"category": "skill",+ "elapsed_ms": "<volatile>","message": "1 skill(s) compliant or exempt","name": "skill_brain_first","status": "ok"},{"category": "skill",+ "elapsed_ms": "<volatile>","message": "No skills.lock.json in <home>/skills — integrity check not applicable","name": "skills_manifest_integrity","status": "ok"@@ -144,6 +151,7 @@"webhook-transforms"]},+ "elapsed_ms": "<volatile>","fix_unavailable_reason": "unstructured","message": "64 new built-in skill(s) available that this workspace hasn't installed: academic-verify, archive-crawler, article-enrichment, ask-user, blog-ingest, book-mirror, brain-ingest-gate, brain-link-discipline, … +56 more. Add them with `gbrain skillpack sync`.","name": "skill_currency",@@ -151,6 +159,7 @@},{"category": "skill",+ "elapsed_ms": "<volatile>","message": "no installed skills declare preconditions","name": "skill_preconditions","status": "ok"@@ -162,6 +171,7 @@"out_of_band_settable": true,"reason": "disabled"},+ "elapsed_ms": "<volatile>","message": "memorable relay off (default)","name": "memorable_relay_health","status": "ok"@@ -195,12 +205,14 @@"ttl_valid": true,"visibility_note": "world = readable by agents authorized on THIS brain, not the public internet"},+ "elapsed_ms": "<volatile>","message": "ambient writeback off (default): Stop-hook turn capture is off, but the compaction harvest and SessionEnd transcripts still extract (installing the harness hooks opted into them; stop them: gbrain config set memory.auto_writeback off). Enable: gbrain config set memory.auto_writeback salient","name": "memory_writeback","status": "ok"},{"category": "ops",+ "elapsed_ms": "<volatile>","message": "No chat connectors configured (optional).","name": "connectors","status": "ok"@@ -214,6 +226,7 @@"keys": [],"threshold": 3},+ "elapsed_ms": "<volatile>","message": "No dream key died 3+ times in 24h","name": "dream_paid_loop","status": "ok"@@ -229,6 +242,7 @@"0.53.0"]},+ "elapsed_ms": "<volatile>","fix": {"actor": "agent","argv": [@@ -261,18 +275,21 @@},{"category": "ops",+ "elapsed_ms": "<volatile>","message": "mode=notify","name": "self_upgrade_health","status": "ok"},{"category": "ops",+ "elapsed_ms": "<volatile>","message": "Bun <bun-version> (minimum 1.4.0)","name": "bun_runtime","status": "ok"},{"category": "brain",+ "elapsed_ms": "<volatile>","message": "disabled (opt-in). Enable with: gbrain config set autopilot.nightly_quality_probe.enabled true","name": "nightly_quality_probe_health","status": "ok"@@ -283,12 +300,14 @@"kinds": [],"schema_version": 1},+ "elapsed_ms": "<volatile>","message": "no extractions in last 7 days","name": "extract_health","status": "ok"},{"category": "brain",+ "elapsed_ms": "<volatile>","message": "disabled (opt-in). Enable with: gbrain config set cycle.conversation_facts_backfill.enabled true","name": "conversation_facts_backlog","status": "ok"@@ -300,6 +319,7 @@"known_approximation": "page backlog only; transcript corpus not counted","pack_declares_phase": false},+ "elapsed_ms": "<volatile>","message": "no pages awaiting atom extraction","name": "extract_atoms_backlog","status": "ok"@@ -314,42 +334,49 @@"source_gone": 0,"total_atoms": 0},+ "elapsed_ms": "<volatile>","message": "no atoms to check","name": "atom_provenance_drift","status": "ok"},{"category": "brain",+ "elapsed_ms": "<volatile>","message": "No conversation-type pages — coverage check not applicable","name": "conversation_format_coverage","status": "ok"},{"category": "ops",+ "elapsed_ms": "<volatile>","message": "No progressive-batch operations in the last 7 days","name": "progressive_batch_audit_health","status": "ok"},{"category": "brain",+ "elapsed_ms": "<volatile>","message": "disabled (opt-in; default-on only for search.mode=tokenmax). Enable with: `gbrain config set autopilot.conversation_parser_probe.enabled true`","name": "conversation_parser_probe_health","status": "ok"},{"category": "ops",+ "elapsed_ms": "<volatile>","message": "gbrain home is outside any enclosing git worktree.","name": "home_dir_in_worktree","status": "ok"},{"category": "ops",+ "elapsed_ms": "<volatile>","message": "No abandoned PGLite store under the gbrain home (engine: postgres).","name": "pglite_leftovers","status": "ok"},{"category": "meta",+ "elapsed_ms": "<volatile>","message": "default source local_path is set: <home>/.gbrain/content/<uuid>/default","name": "default_source_local_path","status": "ok"@@ -366,6 +393,7 @@"embedding_model": "voyage:voyage-4","shadows": []},+ "elapsed_ms": "<volatile>","message": "No embedding key is set here (VOYAGE_API_KEY or voyage_api_key). No environment variable overrides a different config-plane provider key. This check sees only the environment `gbrain doctor` runs in; a daemon (gbrain serve, autopilot) has its own, and reports a mismatch in its log with a startup warning or embedding_auth_failed.","name": "embedding_key_source","status": "ok"@@ -376,6 +404,7 @@"decision": null,"provider_env": []},+ "elapsed_ms": "<volatile>","message": "No gbrain setup receipt records a provider-use decision for this install; provider calls follow the configured keys.","name": "provider_consent","readiness_state": "not_applicable",@@ -387,6 +416,7 @@"details": {"reason": "no_harness_detected"},+ "elapsed_ms": "<volatile>","fix": {"actor": "user","consent": [@@ -414,30 +444,150 @@"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, 0 pages","name": "connection","status": "ok"},{"category": "ops",+ "details": {+ "commands": [],+ "exact": true,+ "inspected": 2,+ "resources": [],+ "truncated": false+ },+ "elapsed_ms": "<volatile>",+ "message": "Managed write capacity is below 80% of every cumulative limit.",+ "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+ },+ "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",+ "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": "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"@@ -448,23 +598,11 @@"readiness": "ready","ready": true},+ "elapsed_ms": "<volatile>","message": "Visible text projections match their canonical revisions.","name": "text_projection_readiness","status": "ok"},- {- "category": "ops",- "details": {- "commands": [],- "exact": true,- "inspected": 2,- "resources": [],- "truncated": false- },- "message": "Managed write capacity is below 80% of every cumulative limit.",- "name": "persistence_capacity",- "status": "ok"- },{"category": "brain","details": {@@ -474,6 +612,7 @@"parked_effects": 0,"truncated": false},+ "elapsed_ms": "<volatile>","message": "No Git or withdrawal effect is parked.","name": "parked_effects","status": "ok"@@ -483,6 +622,7 @@"details": {"refreshes": []},+ "elapsed_ms": "<volatile>","message": "No worktree refresh is stuck.","name": "worktree_refresh_stuck","status": "ok"@@ -494,6 +634,7 @@"page_child_source_columns": [],"runbook": "docs/guides/write-refusals.md#managed-guard-page-children"},+ "elapsed_ms": "<volatile>","message": "Guarded tables carry only the columns gbrain creates.","name": "managed_guard_schema_drift","status": "ok"@@ -507,42 +648,49 @@"unclassified_p0001": 0,"window_days": 7},+ "elapsed_ms": "<volatile>","message": "No write was refused by a database guard in the last 7 days.","name": "publication_refusals","status": "ok"},{"category": "meta",+ "elapsed_ms": "<volatile>","message": "links_link_source_check has the v114 kebab-case gate","name": "links_link_source_check","status": "ok"},{"category": "ops",+ "elapsed_ms": "<volatile>","message": "RLS enabled on 134/134 public tables","name": "rls","status": "ok"},{"category": "meta",+ "elapsed_ms": "<volatile>","message": "Version <latest> (latest: <latest>)","name": "schema_version","status": "ok"},{"category": "meta",+ "elapsed_ms": "<volatile>","message": "1121 column(s) verified against live schema","name": "schema_columns","status": "ok"},{"category": "ops",+ "elapsed_ms": "<volatile>","message": "Auto-RLS event trigger installed","name": "rls_event_trigger","status": "ok"},{"category": "brain",+ "elapsed_ms": "<volatile>","fix": {"actor": "user","argv": [@@ -590,6 +738,7 @@},{"category": "brain",+ "elapsed_ms": "<volatile>","fix": {"actor": "user","argv": [@@ -637,24 +786,28 @@},{"category": "brain",+ "elapsed_ms": "<volatile>","message": "Registry healthy: 1 columns (embedding_image) (all indexed); primary embeddings disabled","name": "embedding_column_registry","status": "ok"},{"category": "brain",+ "elapsed_ms": "<volatile>","message": "no embedding env overrides set","name": "embedding_env_override","status": "ok"},{"category": "brain",+ "elapsed_ms": "<volatile>","message": "no embedding migration in flight","name": "embedding_migration_state","status": "ok"},{"category": "brain",+ "elapsed_ms": "<volatile>","message": "Embeddings are off on this brain, so facts are only deduplicated by exact text; no supersession threshold applies.","name": "supersession_calibration","readiness_state": "not_applicable",@@ -663,48 +816,56 @@},{"category": "ops",+ "elapsed_ms": "<volatile>","message": "No chat_fallback_chain is set: every chat call uses only its own model.","name": "chat_fallback_chain","status": "ok"},{"category": "meta",+ "elapsed_ms": "<volatile>","message": "Nothing to disclose: this brain is a fresh install at v<version>, after every disclosed behavior change, so the one-time behavior-change notice does not apply.","name": "behavior_changes","status": "ok"},{"category": "brain",+ "elapsed_ms": "<volatile>","message": "No entity pages — graph_coverage not applicable (markdown-only brain)","name": "graph_coverage","status": "ok"},{"category": "brain",+ "elapsed_ms": "<volatile>","message": "Brain score 100/100","name": "brain_score","status": "ok"},{"category": "brain",+ "elapsed_ms": "<volatile>","message": "Vacuous: 0 entity pages (<100). Orphan ratio not meaningful at this scale.","name": "orphan_ratio","status": "ok"},{"category": "brain",+ "elapsed_ms": "<volatile>","message": "No by-mention links in this brain.","name": "stale_mentions","status": "ok"},{"category": "brain",+ "elapsed_ms": "<volatile>","message": "No orphaned timeline rows across 0 page(s).","name": "timeline_orphans","status": "ok"},{"category": "brain",+ "elapsed_ms": "<volatile>","message": "No slug collisions across 1 source checkout(s).","name": "slug_collisions","status": "ok"@@ -720,6 +881,7 @@"repair": "timeline","truncated": false},+ "elapsed_ms": "<volatile>","message": "Every timeline row has a bullet in its page (0 page(s) inspected).","name": "timeline_history","status": "ok"@@ -735,6 +897,7 @@"unstamped_atoms": 0,"unstamped_concepts": 0},+ "elapsed_ms": "<volatile>","message": "Every extracted atom and synthesized concept carries an explicit visibility no looser than its origin.","name": "derived_visibility","status": "ok"@@ -748,6 +911,7 @@"repair": "safe-chunks","truncated": false},+ "elapsed_ms": "<volatile>","message": "Every re-sealable page is at the safe-chunk index version.","name": "safe_index_pending","status": "ok"@@ -760,6 +924,7 @@"pages_pending": 0,"truncated": false},+ "elapsed_ms": "<volatile>","message": "No page waits for the credential-safe re-chunk.","name": "credential_projection_pending","status": "ok"@@ -774,6 +939,7 @@"retries": 0,"truncated": false},+ "elapsed_ms": "<volatile>","message": "No orphan connector checkpoint rows older than 7 days.","name": "connector_checkpoints","status": "ok"@@ -800,6 +966,7 @@],"repair": "request-indexes"},+ "elapsed_ms": "<volatile>","message": "Managed sync request indexes are valid.","name": "persistence_request_indexes","status": "ok"@@ -838,6 +1005,7 @@"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.","name": "persistence_request_growth","status": "ok"@@ -857,6 +1025,7 @@},"stalls": []},+ "elapsed_ms": "<volatile>","message": "No write request has held its claim longer than persistence.max_claim_ms (600000 ms).","name": "persistence_write_stall","status": "ok"@@ -870,62 +1039,11 @@"repair": "failed-writes","writes": []},+ "elapsed_ms": "<volatile>","message": "Every caller write with a retained receipt committed or was superseded.","name": "lost_caller_writes","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- },- "message": "No terminal write failures in the last 7 d.",- "name": "persistence_terminal_failures",- "status": "ok"- },{"category": "ops","details": {@@ -933,6 +1051,7 @@"configured": "5min","docs": "docs/guides/troubleshooting.md#session-timeouts-not-applied"},+ "elapsed_ms": "<volatile>","message": "The session statement_timeout (5min) reaches the server.","name": "persistence_session_timeouts","status": "ok"@@ -944,6 +1063,7 @@"held": 0,"sources": []},+ "elapsed_ms": "<volatile>","message": "No connector items are held.","name": "connector_held_items","status": "ok"@@ -957,6 +1077,7 @@"source_ids": [],"sources": []},+ "elapsed_ms": "<volatile>","message": "No Git source files are held.","name": "git_held_files","status": "ok"@@ -968,6 +1089,7 @@"docs": "docs/guides/repair.md#held-files","hooks": []},+ "elapsed_ms": "<volatile>","message": "No outdated gbrain frontmatter pre-commit hook is installed.","name": "frontmatter_hook","status": "ok"@@ -981,6 +1103,7 @@"repair": "orphan-bindings","truncated": false},+ "elapsed_ms": "<volatile>","message": "Every persistence source binding belongs to an existing source.","name": "orphan_persistence_bindings","status": "ok"@@ -992,6 +1115,7 @@"docs": "docs/guides/write-refusals.md#foreign-ownership-marker","markers": []},+ "elapsed_ms": "<volatile>","message": "Every ownership marker beside a source checkout belongs to this brain.","name": "foreign_ownership_marker","status": "ok"@@ -1002,6 +1126,7 @@"sources": [],"total": 0},+ "elapsed_ms": "<volatile>","message": "No page was written database-only to an unbound source.","name": "unbound_source","status": "ok"@@ -1031,6 +1156,7 @@"truncated": false,"window_days": 7},+ "elapsed_ms": "<volatile>","message": "Every writer that admitted or published a request in the last 7 days is v0.60.5.0 or newer.","name": "writer_version","status": "ok"@@ -1043,6 +1169,7 @@"truncated": false,"unclassifiable": 0},+ "elapsed_ms": "<volatile>","message": "No session corpus is configured; nothing to classify.","name": "self_capture","status": "ok"@@ -1057,6 +1184,7 @@"outcome": "skipped","reason": "small_brain"},+ "elapsed_ms": "<volatile>","message": "Skipped: about 0 embedded chunk(s) in embedding; below 10000 a sequential scan is the right plan.","name": "vector_plan","status": "ok"@@ -1070,6 +1198,7 @@"reason": "small_brain","timeout_ms": "<volatile>"},+ "elapsed_ms": "<volatile>","message": "Skipped: fewer than 10000 chunks by the planner's estimate; the keyword statements finish well inside search.keyword_statement_timeout_ms = 8000 ms (range 1000-60000).","name": "keyword_plan","status": "ok"@@ -1088,6 +1217,7 @@"stale_effects": 0,"truncated": false},+ "elapsed_ms": "<volatile>","message": "No committed write has a stale queued or failed embedding effect.","name": "stale_embedding_effects","status": "ok"@@ -1100,6 +1230,7 @@"repair": "google-file-modes","sources": []},+ "elapsed_ms": "<volatile>","message": "No group- or world-readable gbrain files under Google source directories outside ~/.gbrain.","name": "google_file_modes","status": "ok"@@ -1113,6 +1244,7 @@"excluded": 0,"repair": "extractor-facts"},+ "elapsed_ms": "<volatile>","message": "No conversation-extractor fact is left expired by the pre-v0.60.11.0 projection.","name": "extractor_facts_expired","status": "ok"@@ -1125,6 +1257,7 @@"evidenced": 0,"repair": "conversation-labels"},+ "elapsed_ms": "<volatile>","message": "No conversation fact carries the pre-fix meeting-label signature (a 1970-01-01 segment on a label page).","name": "conversation_label_facts","status": "ok"@@ -1140,6 +1273,7 @@"stale": 0,"unstamped": 0},+ "elapsed_ms": "<volatile>","message": "No conversation extraction outcome predates extractor version 1.","name": "conversation_outcomes_stale","status": "ok"@@ -1154,6 +1288,7 @@"repair": "captured-facts","unclassifiable": 0},+ "elapsed_ms": "<volatile>","message": "No active fact from a gbrain self-capture or paste candidate remains. This counts facts in the database; the self_capture check counts corpus files.","name": "captured_facts_active","status": "ok"@@ -1165,6 +1300,7 @@"drifted": 0,"repair": "loop-facts"},+ "elapsed_ms": "<volatile>","message": "Every closed commitment loop has its fact retired.","name": "loop_facts_drift","status": "ok"@@ -1178,6 +1314,7 @@"repair": "ontology-facts","retired": 0},+ "elapsed_ms": "<volatile>","message": "No ontology observation is held by a page's Facts table.","name": "ontology_facts_fenced","status": "ok"@@ -1191,6 +1328,7 @@"source_ids": [],"sources": []},+ "elapsed_ms": "<volatile>","message": "No stored frontmatter carries a parser-reserved key (type, title, tags, slug).","name": "stale_frontmatter_keys","status": "ok"@@ -1205,102 +1343,119 @@"sources": [],"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"},{"category": "brain",+ "elapsed_ms": "<volatile>","message": "Relative dates resolve against each source's observation date in fact extraction, dream synthesis, extract_atoms and propose_takes (the default). life chronicle events keep their current prompt unless extraction.date_grounding is set to true. Facts extracted before this was on keep their original wording; re-extract a source only with the user's consent (gbrain extract-conversation-facts --source-id <id> --dry-run previews it).","name": "extraction_date_grounding","status": "ok"},{"category": "brain",+ "elapsed_ms": "<volatile>","message": "Sampled 0 pages; no bare-tweet phrases or external links.","name": "integrity","status": "ok"},{"category": "brain",+ "elapsed_ms": "<volatile>","message": "All JSONB columns store objects/arrays","name": "jsonb_integrity","status": "ok"},{"category": "brain",+ "elapsed_ms": "<volatile>","message": "No takes yet","name": "takes_weight_grid","status": "ok"},{"category": "brain",+ "elapsed_ms": "<volatile>","message": "All FK-child tables clean (10 tables checked)","name": "child_table_orphans","status": "ok"},{"category": "brain",+ "elapsed_ms": "<volatile>","message": "All synthesized pages carry a raw trace or explicit exemption","name": "raw_provenance","status": "ok"},{"category": "brain",+ "elapsed_ms": "<volatile>","message": "All source config values are JSON objects","name": "source_config_shape","status": "ok"},{"category": "skill",+ "elapsed_ms": "<volatile>","message": "whoknows eval fixture present (10 queries). Run `gbrain eval whoknows test/fixtures/whoknows-eval.jsonl` to grade.","name": "whoknows_health","status": "ok"},{"category": "brain",+ "elapsed_ms": "<volatile>","message": "All image-asset chunks have modality=image","name": "cross_modal_modality_backfill","status": "ok"},{"category": "brain",+ "elapsed_ms": "<volatile>","message": "search.unified_multimodal is off; coverage check N/A","name": "unified_multimodal_coverage","status": "ok"},{"category": "brain",+ "elapsed_ms": "<volatile>","message": "No truncated bodies detected","name": "markdown_body_completeness","status": "ok"},{"category": "brain",+ "elapsed_ms": "<volatile>","message": "No pages exceed 500000 bytes (excluding embed_skip pages, which already took the accepted non-embeddable remediation)","name": "oversized_pages","status": "ok"},{"category": "brain",+ "elapsed_ms": "<volatile>","message": "No junk-pattern hits in 0 recent page(s) (use --content-audit for full scan)","name": "scraper_junk_pages","status": "ok"},{"category": "brain",+ "elapsed_ms": "<volatile>","message": "No content-sanity events in last 7 days (audit JSONL is local to this host; share GBRAIN_AUDIT_DIR for multi-host visibility)","name": "content_sanity_audit_recent","status": "ok"},{"category": "brain",+ "elapsed_ms": "<volatile>","message": "No quarantined pages","name": "quarantined_pages","status": "ok"},{"category": "brain",+ "elapsed_ms": "<volatile>","message": "No flagged pages","name": "flagged_pages","status": "ok"@@ -1312,12 +1467,14 @@"days": 7,"source_id": null},+ "elapsed_ms": "<volatile>","message": "No stale unverified extraction stubs","name": "unverified_extractions","status": "ok"},{"category": "brain",+ "elapsed_ms": "<volatile>","message": "1 source(s) clean — no frontmatter issues","name": "frontmatter_integrity","status": "ok"@@ -1332,36 +1489,42 @@"sources": [],"unscanned": []},+ "elapsed_ms": "<volatile>","message": "No file has frontmatter gbrain repair frontmatter would fix.","name": "frontmatter_repairable","status": "ok"},{"category": "meta",+ "elapsed_ms": "<volatile>","message": "No capture failures in the last 24h","name": "eval_capture","status": "ok"},{"category": "brain",+ "elapsed_ms": "<volatile>","message": "No probe runs in the last 7 days. Run `gbrain eval suspected-contradictions --query \"...\" --top-k 5` to populate.","name": "contradictions","status": "ok"},{"category": "brain",+ "elapsed_ms": "<volatile>","message": "Automatic fact extraction not configured (keyless) — memory comes from agent-authored `## Facts` fences and the `remember` verb. One optional key enables automatic extraction (OpenAI or Anthropic).","name": "facts_extraction_health","status": "ok"},{"category": "brain",+ "elapsed_ms": "<volatile>","message": "Sample of last 1000 pages clean (no fallback-with-parseable-fm-date, no future-dated, no pre-1990)","name": "effective_date_health","status": "ok"},{"category": "brain",+ "elapsed_ms": "<volatile>","message": "Skipped (no pages have emotional_weight > 0; either fresh install or recompute hasn't run yet)","name": "salience_health","status": "ok"@@ -1373,24 +1536,28 @@"oldest_age_seconds": null,"worker_alive": true},+ "elapsed_ms": "<volatile>","message": "No stalled-forever jobs; no queue over depth 10; no old embed-backfill jobs without a worker.","name": "queue_health","status": "ok"},{"category": "ops",+ "elapsed_ms": "<volatile>","message": "Subagent tier resolves to default (claude-sonnet-4-6) — full tool-loop capability","name": "subagent_capability","status": "ok"},{"category": "brain",+ "elapsed_ms": "<volatile>","message": "facts_health(default): 0 active, 0 today, 0 this week, 0 consolidated, top entities —","name": "facts_health","status": "ok"},{"category": "ops",+ "elapsed_ms": "<volatile>","message": "Brain-wide maintenance jobs are finishing within their deadline.","name": "global_maintenance_timeouts","status": "ok"@@ -1413,6 +1580,7 @@"unsupported": 0,"unsupported_ids": []},+ "elapsed_ms": "<volatile>","message": "No queued job predates submission authority.","name": "legacy_job_authority","status": "ok"@@ -1426,6 +1594,7 @@"malformed": [],"mirror_window_ends": "2026-11-04"},+ "elapsed_ms": "<volatile>","message": "Every active legacy token uses the unified grant columns. The permissions mirror for older gbrain binaries is kept until 2026-11-04.","name": "legacy_token_grant_shape","status": "ok"@@ -1437,6 +1606,7 @@"drift": [],"mirror_window_ends": "2026-11-04"},+ "elapsed_ms": "<volatile>","message": "No legacy token grant has drifted from its permissions mirror.","name": "legacy_token_grant_drift","status": "ok"@@ -1448,6 +1618,7 @@"null_scope_count": 0,"tokens": []},+ "elapsed_ms": "<volatile>","message": "Every active legacy token has explicit scopes.","name": "legacy_token_null_scope","status": "ok"@@ -1459,18 +1630,21 @@"grants": [],"server_surface": "full"},+ "elapsed_ms": "<volatile>","message": "Every active client and token can call the operations its scopes allow.","name": "grant_new_ops_available","status": "ok"},{"category": "brain",+ "elapsed_ms": "<volatile>","message": "No image assets indexed yet","name": "image_assets","status": "ok"},{"category": "brain",+ "elapsed_ms": "<volatile>","message": "OCR not in use (or no images ingested with OCR opt-in)","name": "ocr_health","status": "ok"@@ -1484,6 +1658,7 @@"unsupported_holds": 0,"without_image_vector": 0},+ "elapsed_ms": "<volatile>","message": "No image pages indexed yet.","name": "image_embedding_coverage","status": "ok"@@ -1496,6 +1671,7 @@"unchanged_count": 0,"writer_owned_count": 1},+ "elapsed_ms": "<volatile>","message": "1 writer-owned canonical content source(s): upstream sync is not applicable; see canonical_content_writes for publication status.","name": "sync_freshness","status": "ok"@@ -1507,6 +1683,7 @@"recovering_count": 0,"writer_owned_count": 1},+ "elapsed_ms": "<volatile>","message": "1 writer-owned content source(s); no pending canonical publication or recovery.","name": "canonical_content_writes","status": "ok"@@ -1529,6 +1706,7 @@"unpushed": 0}},+ "elapsed_ms": "<volatile>","fix": {"actor": "agent","argv": [@@ -1573,18 +1751,21 @@},{"category": "ops",+ "elapsed_ms": "<volatile>","message": "Single-source brain — sync --all consolidation not applicable.","name": "sync_consolidation","status": "ok"},{"category": "brain",+ "elapsed_ms": "<volatile>","message": "Extraction lag not applicable (no pages)","name": "links_extraction_lag","status": "ok"},{"category": "brain",+ "elapsed_ms": "<volatile>","message": "No full cycle yet for 'default': it holds no pages or only pages from the last 24h, so there is nothing to consolidate yet.","name": "cycle_freshness","readiness_state": "not_applicable",@@ -1593,24 +1774,28 @@},{"category": "brain",+ "elapsed_ms": "<volatile>","message": "No same-source content-hash duplicate groups","name": "content_hash_duplicates","status": "ok"},{"category": "brain",+ "elapsed_ms": "<volatile>","message": "All code-page chunks carry symbol metadata","name": "code_chunk_metadata","status": "ok"},{"category": "brain",+ "elapsed_ms": "<volatile>","message": "Every DB page is file-backed or under a declared/default db_only path (derive-phase defaults: life/events/ atoms/ concepts/ extracts/ dream-cycle-summaries/).","name": "undeclared_db_only_pages","status": "ok"},{"category": "ops",+ "elapsed_ms": "<volatile>","message": "No configured collectors declare output paths","name": "db_only_collector_collision","status": "ok"@@ -1621,12 +1806,14 @@"checkouts": 0,"tracked": []},+ "elapsed_ms": "<volatile>","message": "0 Git checkout(s) track no ownership marker (markers on disk stay untracked and are denied on push).","name": "tracked_ownership_marker","status": "ok"},{"category": "ops",+ "elapsed_ms": "<volatile>","message": "System One is off (every decide slot is off; nothing is sent).","name": "decide_health","status": "ok"@@ -1655,6 +1842,7 @@"unlinked": 0}},+ "elapsed_ms": "<volatile>","message": "No active facts yet; nothing to link.","name": "unlinked_facts","status": "ok"@@ -1673,6 +1861,7 @@"relationships": {},"stale_assertions": []},+ "elapsed_ms": "<volatile>","message": "relationships: none yet; read policy on; contradiction mode propose (default)","name": "edge_validity","status": "ok"@@ -1711,6 +1900,7 @@"unpricedCalls": 0}},+ "elapsed_ms": "<volatile>","message": "auto_chronicle is on (default). Last 24 h: 0 of 200 automatic extraction calls. Last 7 days: 0 extracted, 0 failed, 0 skipped; $0.00 known spend. 0 page(s) pending. No chat provider is configured, so nothing will be extracted until one is.","name": "auto_chronicle","readiness_state": "missing",@@ -1718,6 +1908,7 @@},{"category": "brain",+ "elapsed_ms": "<volatile>","message": "chronicle.* settings are valid.","name": "chronicle_config_invalid","status": "ok"@@ -1829,6 +2020,7 @@},"severity": "info"},+ "elapsed_ms": "<volatile>","fix": {"actor": "agent","argv": [@@ -1880,6 +2072,7 @@"health": "not_applicable","last_run": null},+ "elapsed_ms": "<volatile>","message": "Postgres brains run facts-absorb jobs on the job worker (gbrain jobs supervisor), not the automatic drain.","name": "facts_drain","readiness_state": "not_applicable",@@ -1891,6 +2084,7 @@"details": {"applicable": false},+ "elapsed_ms": "<volatile>","message": "Not applicable: embeddings are disabled on this brain (keyword search keeps working).","name": "fact_take_vectors","readiness_state": "disabled_by_choice",@@ -1914,6 +2108,7 @@"missing_search_statistics": [],"stale": []},+ "elapsed_ms": "<volatile>","message": "Planner statistics are fresh on 6 hot tables.","name": "planner_stats_stale","status": "ok"@@ -1934,6 +2129,7 @@"weights": 0,"weights_off_neutral": 0},+ "elapsed_ms": "<volatile>","message": "Retrieval feedback is off; rankings do not learn from ratings. Turn it on with: gbrain config set feedback.enabled true","name": "retrieval_feedback_health","status": "ok"@@ -1945,6 +2141,7 @@"failed": [],"pending": 0},+ "elapsed_ms": "<volatile>","message": "Every page has its revision; the page revision backfill is complete.","name": "revision_backfill","status": "ok"@@ -2022,6 +2219,7 @@],"unknown_pct": 0},+ "elapsed_ms": "<volatile>","message": "No facts, takes, timeline entries or pages yet.","name": "trust_tiers","status": "ok"@@ -2039,6 +2237,7 @@"timeline_entries": 0}},+ "elapsed_ms": "<volatile>","message": "Every agent-written or lower row has been scanned by the current write-gate detector; flagged rows carry their flag, and proactive surfaces withhold them when trust.agent_activation is suppress.","name": "trust_scan","status": "ok"@@ -2050,6 +2249,7 @@"pending": [],"unclaimed": []},+ "elapsed_ms": "<volatile>","message": "No unclaimed source holds rows from before trust tiers.","name": "trust_sources_unclaimed","status": "ok"@@ -2065,22 +2265,11 @@"enabled": false,"pages": 0},+ "elapsed_ms": "<volatile>","message": "Core memory is off (opt-in). If the user wants a profile loaded in every session: gbrain config set memory.core.enabled true, then gbrain core init.","name": "core_memory","status": "ok"},- {- "category": "ops",- "details": {- "count": 0,- "docs": "docs/guides/troubleshooting.md#managed-sync-not-moving",- "parked": 0,- "sources": []- },- "message": "No managed sync is pending.",- "name": "managed_sync_not_moving",- "status": "ok"- },{"category": "ops","details": {@@ -2089,6 +2278,7 @@"docs": "docs/guides/troubleshooting.md#two-consumers-on-host","min_age_ms": "<volatile>"},+ "elapsed_ms": "<volatile>","message": "No persistence consumer is running on this host.","name": "two_consumers_on_host","status": "ok"@@ -2100,6 +2290,7 @@"docs": "docs/guides/troubleshooting.md#two-consumers-on-host","owners": []},+ "elapsed_ms": "<volatile>","message": "Every owner of a live running claim on this host has a consumer heartbeat row.","name": "consumers_without_heartbeat","status": "ok"@@ -2113,24 +2304,11 @@"host_json_path": "<home>/.gbrain/persistence/host.json","mismatches": []},+ "elapsed_ms": "<volatile>","message": "This process's host identity (<home>/.gbrain/persistence/host.json) owns every binding this filesystem holds.","name": "host_identity_mismatch","status": "ok"},- {- "category": "ops",- "details": {- "count": 0,- "docs": "docs/guides/troubleshooting.md#serve-build-drift",- "newer": [],- "older": [],- "owner": null,- "this_version": "<version>"- },- "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": "brain","details": {@@ -2138,6 +2316,7 @@"held": 0,"items": []},+ "elapsed_ms": "<volatile>","message": "No managed atom page or transcript is held after repeated extraction failures.","name": "extract_atoms_held_failed","status": "ok"@@ -2215,12 +2394,14 @@},"warn_at_normalized_7d": 20},+ "elapsed_ms": "<volatile>","message": "No malformed facts or takes fence is held, stored or waiting in a checkout (1 source(s) scanned).","name": "fence_integrity","status": "ok"},{"category": "ops",+ "elapsed_ms": "<volatile>","message": "Mode: conservative (no per-key overrides — mode bundle is canonical).","name": "search_mode","status": "ok"@@ -2235,114 +2416,133 @@".raw/"]},+ "elapsed_ms": "<volatile>","message": "No pages hidden by search-exclude policy.","name": "hidden_by_search_policy","status": "ok"},{"category": "brain",+ "elapsed_ms": "<volatile>","message": "No retrieval-affecting files changed in working tree.","name": "eval_drift","status": "ok"},{"category": "ops",+ "elapsed_ms": "<volatile>","message": "Reranker disabled — no failures expected","name": "reranker_health","status": "ok"},{"category": "ops",+ "elapsed_ms": "<volatile>","message": "No exhausted batch retries in last 24h. Disconnect-call audit: 2 call(s) in 24h (most recent caller: <frame>).","name": "batch_retry_health","status": "ok"},{"category": "ops",+ "elapsed_ms": "<volatile>","message": "No wedged queues","name": "wedged_queue","status": "ok"},{"category": "ops",+ "elapsed_ms": "<volatile>","message": "No orphaned private queues","name": "orphaned_private_queue","status": "ok"},{"category": "ops",+ "elapsed_ms": "<volatile>","message": "No supervisor observed — skipping fan-out/concurrency check","name": "autopilot_fanout_concurrency","status": "ok"},{"category": "ops",+ "elapsed_ms": "<volatile>","message": "no Google accounts connected (gbrain google connect to start)","name": "google_oauth","status": "ok"},{"category": "brain",+ "elapsed_ms": "<volatile>","message": "graph_signals disabled — coverage not checked","name": "graph_signals_coverage","status": "ok"},{"category": "brain",+ "elapsed_ms": "<volatile>","message": "No junk entity hubs (pages with <=2 chunks and >1000 edges)","name": "junk_entity_hubs","status": "ok"},{"category": "ops",+ "elapsed_ms": "<volatile>","message": "Migration v79 applied; tracking enabled. Calibration profile not yet generated — brainstorm/lsd will run unbiased until enough takes are resolved.","name": "brainstorm_health","status": "ok"},{"category": "brain",+ "elapsed_ms": "<volatile>","message": "Brain is empty — nothing to scan","name": "link_resolution_opportunity","status": "ok"},{"category": "brain",+ "elapsed_ms": "<volatile>","message": "Embeddings disabled — no active embedding width to reconcile.","name": "embedding_width_consistency","status": "ok"},{"category": "brain",+ "elapsed_ms": "<volatile>","message": "gateway not configured — facts.embedding width check skipped.","name": "facts_embedding_width_consistency","status": "ok"},{"category": "brain",+ "elapsed_ms": "<volatile>","message": "Single-source brain (no federation to check)","name": "source_routing_health","status": "ok"},{"category": "ops",+ "elapsed_ms": "<volatile>","message": "No OAuth clients registered","name": "oauth_confidential_client_health","status": "ok"},{"category": "ops",+ "elapsed_ms": "<volatile>","message": "Scoped-client grants consistent (no dangling federated reads, no orphaned workspace sources, no privileged self-registered clients)","name": "oauth_client_scope_health","status": "ok"},{"category": "ops",+ "elapsed_ms": "<volatile>","message": "Lock path: <home>/.gbrain/autopilot.lock","name": "autopilot_lock_scope","status": "ok"},{"category": "ops",+ "elapsed_ms": "<volatile>","message": "No stale locks (no rows with ttl_expires_at < NOW())","name": "stale_locks","status": "ok"@@ -2387,12 +2587,14 @@"synthesize_concepts": "global"}},+ "elapsed_ms": "<volatile>","message": "Phase taxonomy: 12 source-scoped, 15 brain-global, 2 mixed. Source-safe: [lint, backlinks, sync, extract, extract_facts, extract_atoms, recompute_emotional_weight, consolidate, propose_takes, conversation_facts_backfill, enrich_thin, schema-suggest]. Brain-global: [fence_repair, content_repair, resolve_symbol_edges, synthesize_concepts, grade_takes, calibration_profile, edge_contradictions, drift, standing_questions, chronicle, facts_drain, skillopt, embed, orphans, purge]. Mixed: [synthesize, patterns].","name": "cycle_phase_scope","status": "ok"},{"category": "brain",+ "elapsed_ms": "<volatile>","fix": {"actor": "user","argv": [@@ -2440,18 +2642,21 @@},{"category": "brain",+ "elapsed_ms": "<volatile>","message": "No entity pages — coverage check vacuous","name": "entity_link_coverage","status": "ok"},{"category": "brain",+ "elapsed_ms": "<volatile>","message": "No entity pages — coverage check vacuous","name": "timeline_coverage","status": "ok"},{"category": "brain",+ "elapsed_ms": "<volatile>","fix": {"actor": "agent","argv": [@@ -2491,18 +2696,21 @@},{"category": "meta",+ "elapsed_ms": "<volatile>","message": "Active pack [email protected]+a50a67b9 is current (no successor declared)","name": "pack_upgrade_available","status": "ok"},{"category": "meta",+ "elapsed_ms": "<volatile>","message": "no typed pages","name": "type_proliferation","status": "ok"},{"category": "brain",+ "elapsed_ms": "<volatile>","message": "No dangling aliases","name": "dangling_aliases","status": "ok"diff --git a/test/fixtures/goldens/doctor/json-postgres-unreachable-fast.json b/test/fixtures/goldens/doctor/json-postgres-unreachable-fast.jsonindex a7e7d0a91f..07d609918b 100644--- a/test/fixtures/goldens/doctor/json-postgres-unreachable-fast.json+++ b/test/fixtures/goldens/doctor/json-postgres-unreachable-fast.json@@ -19,6 +19,7 @@"checks": [{"category": "skill",+ "elapsed_ms": "<volatile>","message": "1 skills, all reachable","name": "resolver_health","status": "ok"@@ -33,30 +34,35 @@"path": "postgres direct","policy_skill_installed": false},+ "elapsed_ms": "<volatile>","message": "postgres direct; enabled; not observed firing yet — policy skill not installed; run `gbrain integrations install retrieval-reflex --target <host-repo>`","name": "retrieval_reflex_health","status": "ok"},{"category": "skill",+ "elapsed_ms": "<volatile>","message": "no verb calls recorded yet (sidecar appears on first remember/recall/entity/synthesize/forget)","name": "memory_verbs_usage","status": "ok"},{"category": "skill",+ "elapsed_ms": "<volatile>","message": "1/1 skills pass","name": "skill_conformance","status": "ok"},{"category": "skill",+ "elapsed_ms": "<volatile>","message": "1 skill(s) compliant or exempt","name": "skill_brain_first","status": "ok"},{"category": "skill",+ "elapsed_ms": "<volatile>","message": "No skills.lock.json in <home>/skills — integrity check not applicable","name": "skills_manifest_integrity","status": "ok"@@ -132,6 +138,7 @@"webhook-transforms"]},+ "elapsed_ms": "<volatile>","fix_unavailable_reason": "unstructured","message": "64 new built-in skill(s) available that this workspace hasn't installed: academic-verify, archive-crawler, article-enrichment, ask-user, blog-ingest, book-mirror, brain-ingest-gate, brain-link-discipline, … +56 more. Add them with `gbrain skillpack sync`.","name": "skill_currency",@@ -139,6 +146,7 @@},{"category": "skill",+ "elapsed_ms": "<volatile>","message": "skill preconditions not checked (no connected brain)","name": "skill_preconditions","status": "ok"@@ -150,6 +158,7 @@"out_of_band_settable": true,"reason": "disabled"},+ "elapsed_ms": "<volatile>","message": "memorable relay off (default)","name": "memorable_relay_health","status": "ok"@@ -163,48 +172,56 @@"transient_ttl": "3d","ttl_valid": true},+ "elapsed_ms": "<volatile>","message": "ambient writeback off (default; file-plane mirror — database unreachable)","name": "memory_writeback","status": "ok"},{"category": "ops",+ "elapsed_ms": "<volatile>","message": "mode=notify","name": "self_upgrade_health","status": "ok"},{"category": "ops",+ "elapsed_ms": "<volatile>","message": "Bun <bun-version> (minimum 1.4.0)","name": "bun_runtime","status": "ok"},{"category": "brain",+ "elapsed_ms": "<volatile>","message": "disabled (opt-in). Enable with: gbrain config set autopilot.nightly_quality_probe.enabled true","name": "nightly_quality_probe_health","status": "ok"},{"category": "ops",+ "elapsed_ms": "<volatile>","message": "No progressive-batch operations in the last 7 days","name": "progressive_batch_audit_health","status": "ok"},{"category": "brain",+ "elapsed_ms": "<volatile>","message": "disabled (opt-in; default-on only for search.mode=tokenmax). Enable with: `gbrain config set autopilot.conversation_parser_probe.enabled true`","name": "conversation_parser_probe_health","status": "ok"},{"category": "ops",+ "elapsed_ms": "<volatile>","message": "gbrain home is outside any enclosing git worktree.","name": "home_dir_in_worktree","status": "ok"},{"category": "ops",+ "elapsed_ms": "<volatile>","message": "No abandoned PGLite store under the gbrain home (engine: postgres).","name": "pglite_leftovers","status": "ok"@@ -221,6 +238,7 @@"embedding_model": "voyage:voyage-4","shadows": []},+ "elapsed_ms": "<volatile>","message": "No embedding key is set here (VOYAGE_API_KEY or voyage_api_key). No environment variable overrides a different config-plane provider key. This check sees only the environment `gbrain doctor` runs in; a daemon (gbrain serve, autopilot) has its own, and reports a mismatch in its log with a startup warning or embedding_auth_failed.","name": "embedding_key_source","status": "ok"@@ -231,6 +249,7 @@"decision": null,"provider_env": []},+ "elapsed_ms": "<volatile>","message": "No gbrain setup receipt records a provider-use decision for this install; provider calls follow the configured keys.","name": "provider_consent","readiness_state": "not_applicable",@@ -242,6 +261,7 @@"details": {"reason": "no_harness_detected"},+ "elapsed_ms": "<volatile>","fix": {"actor": "user","consent": [@@ -269,12 +289,14 @@"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>","fix": {"actor": "agent","argv": [diff --git a/test/fixtures/goldens/doctor/json-postgres-unreachable.json b/test/fixtures/goldens/doctor/json-postgres-unreachable.jsonindex c09b650421..a33a186216 100644--- a/test/fixtures/goldens/doctor/json-postgres-unreachable.json+++ b/test/fixtures/goldens/doctor/json-postgres-unreachable.json@@ -18,6 +18,7 @@"checks": [{"category": "skill",+ "elapsed_ms": "<volatile>","message": "1 skills, all reachable","name": "resolver_health","status": "ok"@@ -32,30 +33,35 @@"path": "postgres direct","policy_skill_installed": false},+ "elapsed_ms": "<volatile>","message": "postgres direct; enabled; not observed firing yet — policy skill not installed; run `gbrain integrations install retrieval-reflex --target <host-repo>`","name": "retrieval_reflex_health","status": "ok"},{"category": "skill",+ "elapsed_ms": "<volatile>","message": "no verb calls recorded yet (sidecar appears on first remember/recall/entity/synthesize/forget)","name": "memory_verbs_usage","status": "ok"},{"category": "skill",+ "elapsed_ms": "<volatile>","message": "1/1 skills pass","name": "skill_conformance","status": "ok"},{"category": "skill",+ "elapsed_ms": "<volatile>","message": "1 skill(s) compliant or exempt","name": "skill_brain_first","status": "ok"},{"category": "skill",+ "elapsed_ms": "<volatile>","message": "No skills.lock.json in <home>/skills — integrity check not applicable","name": "skills_manifest_integrity","status": "ok"@@ -131,6 +137,7 @@"webhook-transforms"]},+ "elapsed_ms": "<volatile>","fix_unavailable_reason": "unstructured","message": "64 new built-in skill(s) available that this workspace hasn't installed: academic-verify, archive-crawler, article-enrichment, ask-user, blog-ingest, book-mirror, brain-ingest-gate, brain-link-discipline, … +56 more. Add them with `gbrain skillpack sync`.","name": "skill_currency",@@ -138,6 +145,7 @@},{"category": "skill",+ "elapsed_ms": "<volatile>","message": "skill preconditions not checked (no connected brain)","name": "skill_preconditions","status": "ok"@@ -149,6 +157,7 @@"out_of_band_settable": true,"reason": "disabled"},+ "elapsed_ms": "<volatile>","message": "memorable relay off (default)","name": "memorable_relay_health","status": "ok"@@ -162,48 +171,56 @@"transient_ttl": "3d","ttl_valid": true},+ "elapsed_ms": "<volatile>","message": "ambient writeback off (default; file-plane mirror — database unreachable)","name": "memory_writeback","status": "ok"},{"category": "ops",+ "elapsed_ms": "<volatile>","message": "mode=notify","name": "self_upgrade_health","status": "ok"},{"category": "ops",+ "elapsed_ms": "<volatile>","message": "Bun <bun-version> (minimum 1.4.0)","name": "bun_runtime","status": "ok"},{"category": "brain",+ "elapsed_ms": "<volatile>","message": "disabled (opt-in). Enable with: gbrain config set autopilot.nightly_quality_probe.enabled true","name": "nightly_quality_probe_health","status": "ok"},{"category": "ops",+ "elapsed_ms": "<volatile>","message": "No progressive-batch operations in the last 7 days","name": "progressive_batch_audit_health","status": "ok"},{"category": "brain",+ "elapsed_ms": "<volatile>","message": "disabled (opt-in; default-on only for search.mode=tokenmax). Enable with: `gbrain config set autopilot.conversation_parser_probe.enabled true`","name": "conversation_parser_probe_health","status": "ok"},{"category": "ops",+ "elapsed_ms": "<volatile>","message": "gbrain home is outside any enclosing git worktree.","name": "home_dir_in_worktree","status": "ok"},{"category": "ops",+ "elapsed_ms": "<volatile>","message": "No abandoned PGLite store under the gbrain home (engine: postgres).","name": "pglite_leftovers","status": "ok"@@ -220,6 +237,7 @@"embedding_model": "voyage:voyage-4","shadows": []},+ "elapsed_ms": "<volatile>","message": "No embedding key is set here (VOYAGE_API_KEY or voyage_api_key). No environment variable overrides a different config-plane provider key. This check sees only the environment `gbrain doctor` runs in; a daemon (gbrain serve, autopilot) has its own, and reports a mismatch in its log with a startup warning or embedding_auth_failed.","name": "embedding_key_source","status": "ok"@@ -230,6 +248,7 @@"decision": null,"provider_env": []},+ "elapsed_ms": "<volatile>","message": "No gbrain setup receipt records a provider-use decision for this install; provider calls follow the configured keys.","name": "provider_consent","readiness_state": "not_applicable",@@ -241,6 +260,7 @@"details": {"reason": "no_harness_detected"},+ "elapsed_ms": "<volatile>","fix": {"actor": "user","consent": [@@ -268,6 +288,7 @@"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"@@ -280,6 +301,7 @@"transient": true,"url_source": "database_url in <home>/.gbrain/config.json"},+ "elapsed_ms": "<volatile>","fix": {"actor": "agent","argv": [diff --git a/test/fixtures/goldens/doctor/registry-build-checks.json b/test/fixtures/goldens/doctor/registry-build-checks.jsonindex c938d62a59..ce438d2005 100644--- a/test/fixtures/goldens/doctor/registry-build-checks.json+++ b/test/fixtures/goldens/doctor/registry-build-checks.json@@ -251,19 +251,39 @@},{"category": "ops",- "name": "pgvector"+ "name": "persistence_capacity"},{"category": "ops",- "name": "postgres_cancellation_driver"+ "name": "persistence_terminal_failures"+ },+ {+ "category": "ops",+ "name": "managed_sync_not_moving"+ },+ {+ "category": "ops",+ "name": "receipt_compaction"+ },+ {+ "category": "ops",+ "name": "serve_build_drift"},{"category": "meta",- "name": "pages_upsert_arbiter"+ "name": "schema_pack_consistency"},{"category": "ops",- "name": "persistence_capacity"+ "name": "pgvector"+ },+ {+ "category": "ops",+ "name": "postgres_cancellation_driver"+ },+ {+ "category": "meta",+ "name": "pages_upsert_arbiter"},{"category": "brain",@@ -405,10 +425,6 @@"category": "ops","name": "lost_caller_writes"},- {- "category": "ops",- "name": "persistence_terminal_failures"- },{"category": "ops","name": "persistence_session_timeouts"@@ -757,10 +773,6 @@"category": "brain","name": "core_memory"},- {- "category": "ops",- "name": "managed_sync_not_moving"- },{"category": "ops","name": "two_consumers_on_host"@@ -773,10 +785,6 @@"category": "ops","name": "host_identity_mismatch"},- {- "category": "ops",- "name": "serve_build_drift"- },{"category": "brain","name": "extract_atoms_held_failed"