Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

Slow whole-brain reads say what they are doing: stderr heartbeat, elapsed_ms/complete on --json, interrupted note, gbrain diag

garrytan8c10a4f0a11b
diff --git a/docs/architecture/key-files/runtime.md b/docs/architecture/key-files/runtime.md
index 65604ff27c..0fa5bad639 100644
--- a/docs/architecture/key-files/runtime.md
+++ b/docs/architecture/key-files/runtime.md
@@ -26,7 +26,9 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
- `src/core/op-checkpoint.ts` — DB-backed checkpoint primitive for long-running ops. Migration v67 introduces `op_checkpoints (op TEXT, fingerprint TEXT, completed_keys JSONB, updated_at TIMESTAMPTZ, PK(op, fingerprint))`. Per-op fingerprint helpers (`embedFingerprint`, `extractFingerprint`, `reindexFingerprint`, `integrityFingerprint`, `purgeFingerprint`) compute `sha8(canonical-JSON(relevant-params))` so re-running with the same params resumes from `completed_keys` and re-running with different params (e.g. `--limit 100` vs `--limit 200`) starts fresh. Cross-worker safe on Postgres (DB row, no file-lock race); PGLite degrades gracefully. The 7-day TTL GC runs in the cycle's `purge` phase. All writes (`recordCompleted`, `clearOpCheckpoint`) route through `engine.executeRawDirect` + `withRetry(BULK_RETRY_OPTS)` so they survive Supavisor pool exhaustion, and `recordCompleted` returns `boolean` (banked vs failed-after-retries) — the 9 non-sync consumers keep its REPLACE-into-`completed_keys` semantics. Resumable sync uses the additive `appendCompleted(key, deltaKeys)` / `appendCompletedOnce` (the latter no-retry for the SIGTERM path) which INSERT a delta into the `op_checkpoint_paths` child table (migration v115: `(op, fingerprint, path)` PK, FK to `op_checkpoints` ON DELETE CASCADE) via a single writable-CTE `unnest($3::text[])` write — O(delta), never an O(N²) full-set rewrite. `loadOpCheckpoint` returns the `UNION ALL` of legacy `completed_keys` + child-table paths (deduped in JS), so an in-flight upgrade loses nothing. The legacy arm is gated on `jsonb_typeof(completed_keys) = 'array'` so a non-array (scalar) parent row can't make `jsonb_array_elements_text` throw "cannot extract elements from a scalar" and take down the whole union (which would discard the valid child rows and lose all banked progress for the key); a third union arm flags the corruption so the loader logs it once and keeps the child rows. Migration v119 adds the `op_checkpoints_completed_keys_array` CHECK (`jsonb_typeof(completed_keys) = 'array'`) — a DB-enforced, always-on guard that makes the scalar-corruption class structurally impossible going forward; the migration repairs any pre-existing scalar to `'[]'` under `LOCK TABLE ... IN SHARE ROW EXCLUSIVE MODE` and `src/core/schema-embedded.generated.ts` + `src/core/pglite-schema.ts` ship the same CHECK on fresh installs (a loader hit implies schema drift, a disabled constraint, or an out-of-band writer). `recordCompleted` binds its array through `$3::text::jsonb` (NOT a bare `$3::jsonb`) so postgres.js `.unsafe()` doesn't double-encode `JSON.stringify(sorted)` into the scalar string that CHECK rejects (PGLite parses it silently, so only real Postgres surfaces the bug). A DATABASE_URL-gated `test/e2e/op-checkpoint-jsonb-parity.test.ts` (its own CI job) asserts the array shape on real Postgres. `syncFingerprint({sourceId, lastCommit})` keys the sync rows. Pinned by `test/op-checkpoint.test.ts` (incl. delta-append, union read, cascade clear, durable-write boolean, and the scalar-parent guard). `import-checkpoint.ts` stays a separate file-backed checkpoint — both systems coexist without conflict (unifying them would mean async-propagating the four sync call sites in `src/commands/import.ts`; deferred). TTL cleanup preserves unresolved managed cursors, their manifests and failure observations; a completed full cursor does not hide a different failed incremental cursor. Unfinished `managed-atoms` and `managed-atoms-generation` checkpoints survive ordinary seven-day GC so accepted output/retry state is not silently forgotten. Git sync holds (`sync-hold`), their per-source summary while it counts any, `sync-hold-retry` requests, `sync-import-provenance` rows, the blocked-cursor conversion log, the #6188 fence census (`fence-candidate`, `fence-scan`) and paid fence-repair attempt claims and memos (`fence-repair-attempt`) of a live source incarnation survive GC (they leave on resolution; a retired incarnation's rows age out), and `connector-hold-retry` requests and `stuck-recovery-resolution` audit entries (`gbrain repair stuck-recovery`) never expire.
- `src/core/persistence/preview-approval.ts` — preview-bound approval shared by `jobs authorize-legacy --select`, `jobs cancel --select`, `repair stale-atoms`, `repair extractor-facts` and the other preview-bound repair kinds such as `repair ontology-facts` (fix wave 5, ENG-O1). `previewHash(parts)` is SHA-256 over key-sorted JSON, byte-identical to `authorityDigest`; `saveApprovedSet` / `loadApprovedSet` / `clearApprovedSet` keep the approved items in `op_checkpoints` (`op='repair-approval'`, fingerprint `<command>:<hash>`). A missing, foreign, malformed or older-than-`APPROVAL_MAX_AGE_DAYS` (7, the purge TTL) set refuses whole with `preview_changed`. Tests: `test/preview-approval.test.ts` (PGLite; Postgres via `test/e2e/preview-approval-postgres.test.ts`). #6351: `loadApprovedSet` takes an optional lazy `emptyHash` (the hash a preview of the same selection prints when it finds nothing, from current state including source incarnations); with no saved row and a matching hash it returns an empty set, so the apply command an empty preview prints succeeds while a changed incarnation still refuses `preview_changed`. The eight preview-bound repair kinds without a local `emptyPlanHash` (stale-atoms, captured-facts, conversation-labels, extractor-facts, failed-writes, frontmatter, loop-facts, ontology-facts) pass it. Pinned by `test/repair-empty-preview-apply.test.ts`.
-- `src/core/process-cleanup.ts` — cleanup registry + abnormal-termination handlers (SIGTERM/SIGHUP/SIGPIPE, uncaughtException/unhandledRejection, EPIPE-on-stdout) that release locks before exit. `registerCleanup(name, fn)` returns a deregister handle; `tryAcquireDbLock` auto-registers. `abortOnCleanupPass(name)` wraps that for child work: it returns `{ signal, release }`, the signal aborts when the cleanup pass runs (sync's `git pull` uses it), and `release` deregisters it. `installSignalHandlers()` is idempotent and called from INSIDE cli.ts's `import.meta.main` seam (first statement before `main()`), NOT at module load — installing at import time would leak a process-wide SIGTERM→`process.exit(143)` handler into any process that merely imports cli.ts (a bun test runner would die mid-suite when a test emits a synthetic SIGTERM, misreading rc=143 as an external kill). Spawned/compiled CLI processes are entrypoints, so they still install. Every attached listener ref is recorded so `_resetForTests()` DETACHES them (clearing flags alone would leave the exit(143) listener live on the shared runner). Tests that must emit synthetic signals strip foreign listeners around the emit (see `test/run-child-entry.test.ts`). #5079: `serve --http` (detected by `isHttpServeInvocation` in `src/core/serve-invocation.ts`) installs it with `keepServingOnLogEpipe`, so a closed stdout/stderr pipe (SIGPIPE under Bun, or an EPIPE stream error) drops the log write instead of exiting; stdio `serve` and every other command still exit. Pinned by `test/serve-http-log-epipe.test.ts`. #5062: `registerSignalOwner(name, onSignal)` lets a long-lived command (`jobs supervisor`, `jobs work`) claim SIGTERM/SIGHUP/SIGPIPE and a broken stdout/stderr pipe: while an owner is registered the generic handler only forwards the signal (no cleanup pass, no exit), so the owner can drain while still holding its DB lock and then exit through `triggerCleanupAndExit`; crashes keep the generic path. Pinned by `test/process-cleanup.test.ts` and `test/e2e/supervisor-stop-drain-5062.test.ts`.
+- `src/core/process-cleanup.ts` — cleanup registry + abnormal-termination handlers (SIGTERM/SIGHUP/SIGPIPE, uncaughtException/unhandledRejection, EPIPE-on-stdout) that release locks before exit. `registerCleanup(name, fn)` returns a deregister handle; `tryAcquireDbLock` auto-registers. `abortOnCleanupPass(name)` wraps that for child work: it returns `{ signal, release }`, the signal aborts when the cleanup pass runs (sync's `git pull` uses it), and `release` deregisters it. `installSignalHandlers()` is idempotent and called from INSIDE cli.ts's `import.meta.main` seam (first statement before `main()`), NOT at module load — installing at import time would leak a process-wide SIGTERM→`process.exit(143)` handler into any process that merely imports cli.ts (a bun test runner would die mid-suite when a test emits a synthetic SIGTERM, misreading rc=143 as an external kill). Spawned/compiled CLI processes are entrypoints, so they still install. Every attached listener ref is recorded so `_resetForTests()` DETACHES them (clearing flags alone would leave the exit(143) listener live on the shared runner). Tests that must emit synthetic signals strip foreign listeners around the emit (see `test/run-child-entry.test.ts`). #5079: `serve --http` (detected by `isHttpServeInvocation` in `src/core/serve-invocation.ts`) installs it with `keepServingOnLogEpipe`, so a closed stdout/stderr pipe (SIGPIPE under Bun, or an EPIPE stream error) drops the log write instead of exiting; stdio `serve` and every other command still exit. Pinned by `test/serve-http-log-epipe.test.ts`. #5062: `registerSignalOwner(name, onSignal)` lets a long-lived command (`jobs supervisor`, `jobs work`) claim SIGTERM/SIGHUP/SIGPIPE and a broken stdout/stderr pipe: while an owner is registered the generic handler only forwards the signal (no cleanup pass, no exit), so the owner can drain while still holding its DB lock and then exit through `triggerCleanupAndExit`; crashes keep the generic path. Pinned by `test/process-cleanup.test.ts` and `test/e2e/supervisor-stop-drain-5062.test.ts`. The signal handler calls `noteInterrupted(signal)` (`read-heartbeat.ts`) before the cleanup pass, except on SIGPIPE.
+- `src/core/read-heartbeat.ts` + `src/cli/slow-read.ts` — slow whole-brain reads say what they are doing. A `CliCommandRecord.slowRead(args)` (`src/cli/command-table.ts`) names the read for doctor, sync status, sources status, orphans, anomalies, status and diag; `beginCommandRead` (skipped for `--help` and `--quiet`) wraps the CLI_ONLY dispatch in `src/cli/main.ts` and calls `beginSlowRead`, which prints one stderr start line and an unref'd `still reading` line every `READ_HEARTBEAT_EVERY_MS` (10 s); stdout is untouched. `withReadMeta(doc)` adds `elapsed_ms` and `complete` to a `--json` document and lists `incomplete` (`{field, reason}`) from the markers the documents already carry (`incompleteFields`: a `status: not_read` object, `complete: false` or a `*_complete: false` key, `budget_hit: true`, a doctor check unknown for its budget); an error envelope gets `elapsed_ms` only and an array stays bare. `writeStdoutFinal` (`cli-force-exit.ts`) applies it to a guarded document during a slow read, and orphans, sources status and status call it directly. `noteInterrupted` prints the interrupt line and, under `--json`, writes `{error: 'interrupted', signal, read, elapsed_ms, complete: false}` at once through the writer `cli-force-exit.ts` registers (`setInterruptedDocumentWriter`); a SIGINT handler is installed only when nothing else listens. The fallback document for exits 129, 130 and 143 is `code: 'interrupted'`. Pinned by `test/read-heartbeat-cli.test.ts` (real spawned CLI fixture `test/fixtures/slow-read-cli.ts`: SIGTERM, SIGINT, SIGHUP, SIGKILL after SIGTERM, no `--json`, a kill outside a read) and `test/read-meta-diag.test.ts`.
+- `src/commands/diag.ts` (+ `src/cli/commands/diag.ts`, `src/cli/help/diag.ts`) — `gbrain diag [--json] [--budget-ms N] [--query TEXT]`, read-only and refused on a thin client: one bounded bundle an agent pastes whole. `collectDiag` runs six sections in turn, each through `diagSection` under min(its cap in `DIAG_SECTION_CAP_MS`, what is left of the budget, default 30 s): `gbrain` (version, engine, runtime), `skew` (doctor `runtime_build_skew` and `writer_version`), `sources` (per source `last_sync_at`, last commit, `behind_head` from `readGitBehind`, the managed pass row's state from `readLivePassRows`), `holds` (counts per source and code), `pool` (Postgres only: backends by state, lock waits, idle transactions over 60 s, `pg_stat_database` session endings on 14+) and `search` (one search's stage timings and result count, never its results). Each section carries `elapsed_ms` and `status` `ok`, `not_read` (reason `budget`), `not_applicable` or `error` (with its code); the bundle carries `elapsed_ms`, `complete` and `incomplete`, error sections included. It never reads a source's file level (`sync status --detail`). Pinned by `test/read-meta-diag.test.ts`.
- `src/core/process-watchdog.ts` — out-of-band hard-deadline killer for `gbrain sync`. A spinning sync (synchronous catastrophic-regex / ReDoS in pack link-inference) STARVES the main event loop, so the existing SIGTERM handler (`process-cleanup.ts`), `--timeout` `setTimeout`, and abort-flag checks can't fire — the process becomes unkillable-by-SIGTERM and, under cron, orphans pile up for 24h+. `installProcessWatchdog({deadlineMs, graceMs?, label?, heartbeatMs?, onWarn?}): WatchdogHandle` spawns a Bun `worker_threads` Worker via `new Worker(code, {eval: true, workerData})` — its own OS thread + event loop fires even while main is in an unyielding sync loop. At `deadlineMs` it `process.kill(process.pid, 'SIGTERM')` (clean-shutdown chance if responsive); at `deadlineMs+graceMs` `process.kill(process.pid, 'SIGKILL')` (uncatchable — guaranteed death under starvation). Signaling SELF has NO PID-reuse footgun (current PID never reused while alive — the reason the detached-child-watches-parent design was rejected). `eval: true` bakes the worker body into the `bun build --compile` binary with no separate-file embedding. Empirically validated on Bun 1.3.13 (worker timer + SIGKILL killed a `while(true){}`-starved process). `handle.dispose()` (clean-exit `finally`) `worker.terminate()`s it; `unref()`'d so it never keeps the process alive. Pure `watchdogDecision(elapsedMs, deadlineMs, graceMs) → 'wait'|'sigterm'|'sigkill'` extracted for unit tests, and pure exported `clampWatchdogTimers(deadlineMs, graceMs)` + `MAX_WATCHDOG_TIMER_MS` clamp BOTH worker timers so the deadline AND the `deadline+grace` SUM stay ≤ 2^31−1 — `setTimeout` overflow-fires above that at ~1ms, which for the sum timer would be an instant SIGKILL of a healthy process (unit-tested as pure arithmetic only; never arm a real max-deadline worker in-suite — its firing SIGTERMs the test runner itself). Optional `heartbeatMs` emits periodic `[<label>] parent alive Ns, hard-kill in ~Ms` lines (visible in cron logs even under starvation — the diagnosis surface). Optional `progressWindowMs` makes the deadline progress-aware: the handle forwards `noteForwardProgress()` notes (`src/core/forward-progress.ts`, throttled to at most one `postMessage` per min(1 s, window/4)) to the worker, which past the deadline extends while the last note is younger than the window and sends SIGTERM only after a full window without progress (pure mirror `progressDeadlineDecision(elapsedMs, deadlineMs, sinceProgressMs, windowMs) → 'wait'|'extend'|'stop'`; the window starts at install). A starved loop sends no notes, so starvation is still killed. Optional `stopNotice` is written to stdout (fd 1) when the watchdog stops the run, so the agent sees why and how to resume. Fallback: if `new Worker` throws, degrades to an in-process timer with a loud warning that it can't fire under starvation. Two adopters: `gbrain sync` (below) and the opt-in PGLite disconnect watchdog (`pglite-engine.ts` entry above); autopilot/cycle are follow-up candidates. Pinned by `test/process-watchdog.test.ts` (pure decision matrices + clamp arithmetic + handle contract) + `test/process-watchdog-harness.test.ts` (Bun-pinned spawn integration: a starved harness process IS killed ~deadline+grace, a no-watchdog control does NOT self-exit, clean dispose never kills, a progressing run outlives its deadline, a run that stops progressing is stopped one window later with its stop notice on stdout). Wired into `src/cli.ts` sync dispatch BEFORE `connectEngine` (so a connect-phase hang is bounded too) through `syncWatchdogPlan` in `src/core/sync-reconcile.ts`; deadline resolved by `resolveSyncHardDeadline` (precedence: `--no-hard-deadline` > `--hard-deadline` > `--timeout`(non-`--all`) > `GBRAIN_SYNC_MAX_RUNTIME_SECONDS` env > non-TTY default 3600s > none). The env and default deadlines carry `progressWindowMs` = the sync stall window (`GBRAIN_SYNC_STALL_ABORT_SECONDS`, default 900 s; the default when that is disabled), so a large first sync that keeps importing is never stopped; the explicit flags stay strict. The stop notice (`syncDeadlineStopNotice`: `code=sync_deadline_stop`, cause, resume command; one JSON object under `--json`) is pinned by `test/sync-hard-deadline.test.ts`, and the real CLI journey by `test/large-brain-ceilings.test.ts`.
diff --git a/docs/protocol/AGENT_OPERATOR_v1.md b/docs/protocol/AGENT_OPERATOR_v1.md
index b864e1839a..2fd96466b5 100644
--- a/docs/protocol/AGENT_OPERATOR_v1.md
+++ b/docs/protocol/AGENT_OPERATOR_v1.md
@@ -1026,7 +1026,26 @@ exactly one JSON document to stdout (or NDJSON lines for `eval export`,
`eval replay`, `eval gate` and `bench-publish`); everything else goes to
stderr. If such a command exits non-zero without writing its document, gbrain
writes a fallback: `{error: "command_failed", code, message, suggestion,
-exit_code, contract_version: 1}`.
+exit_code, contract_version: 1}`. A signal (exit 129, 130 or 143) writes
+`error: "interrupted"` with `code: "interrupted"` instead: the command was cut
+off, and it read nothing. That is not an empty result.
+
+**Slow reads.** `sync status`, `sources status`, `doctor`, `orphans`,
+`anomalies`, `status` and `diag` can take minutes on a large brain. They print
+`[gbrain] reading <what>; large brains can take minutes` on stderr when they
+start and a `still reading` line every 10 s, so silence on stdout means "not
+ready yet". Their `--json` document carries `elapsed_ms` and `complete`. When
+`complete` is false, `incomplete` lists each field a budget or bound left out
+(`{field, reason}`, reason `not_read`, `bounded` or `budget`); read those
+fields as unknown, never as none. A signal mid-read prints
+`[gbrain] Interrupted by <signal> after N s while reading <what>` on stderr and,
+under `--json`, writes `{error: "interrupted", signal, read, elapsed_ms,
+complete: false}` at once. If your harness cut the call off, re-run it with a
+longer timeout, or run `gbrain diag --json`: it returns one bounded bundle
+(version and build skew, each source's freshness and HEAD lag, holds by code,
+database connections, one search's stage timing). Each of its sections carries
+`elapsed_ms` and a status: `ok`, `not_read` with its reason, `not_applicable`
+or `error`.
## A write refused `owner_unavailable` with `detail: unbound_source`
diff --git a/llms-full.txt b/llms-full.txt
index d7f4ab3837..6dcd0e7cfe 100644
--- a/llms-full.txt
+++ b/llms-full.txt
@@ -4421,7 +4421,26 @@ exactly one JSON document to stdout (or NDJSON lines for `eval export`,
`eval replay`, `eval gate` and `bench-publish`); everything else goes to
stderr. If such a command exits non-zero without writing its document, gbrain
writes a fallback: `{error: "command_failed", code, message, suggestion,
-exit_code, contract_version: 1}`.
+exit_code, contract_version: 1}`. A signal (exit 129, 130 or 143) writes
+`error: "interrupted"` with `code: "interrupted"` instead: the command was cut
+off, and it read nothing. That is not an empty result.
+
+**Slow reads.** `sync status`, `sources status`, `doctor`, `orphans`,
+`anomalies`, `status` and `diag` can take minutes on a large brain. They print
+`[gbrain] reading <what>; large brains can take minutes` on stderr when they
+start and a `still reading` line every 10 s, so silence on stdout means "not
+ready yet". Their `--json` document carries `elapsed_ms` and `complete`. When
+`complete` is false, `incomplete` lists each field a budget or bound left out
+(`{field, reason}`, reason `not_read`, `bounded` or `budget`); read those
+fields as unknown, never as none. A signal mid-read prints
+`[gbrain] Interrupted by <signal> after N s while reading <what>` on stderr and,
+under `--json`, writes `{error: "interrupted", signal, read, elapsed_ms,
+complete: false}` at once. If your harness cut the call off, re-run it with a
+longer timeout, or run `gbrain diag --json`: it returns one bounded bundle
+(version and build skew, each source's freshness and HEAD lag, holds by code,
+database connections, one search's stage timing). Each of its sections carries
+`elapsed_ms` and a status: `ok`, `not_read` with its reason, `not_applicable`
+or `error`.
## A write refused `owner_unavailable` with `detail: unbound_source`
diff --git a/plugin-variants/gbrain-coding/skills/conventions/agent-operator-protocol.md b/plugin-variants/gbrain-coding/skills/conventions/agent-operator-protocol.md
index 1ee28e8c3e..98b8739441 100644
--- a/plugin-variants/gbrain-coding/skills/conventions/agent-operator-protocol.md
+++ b/plugin-variants/gbrain-coding/skills/conventions/agent-operator-protocol.md
@@ -1028,7 +1028,26 @@ exactly one JSON document to stdout (or NDJSON lines for `eval export`,
`eval replay`, `eval gate` and `bench-publish`); everything else goes to
stderr. If such a command exits non-zero without writing its document, gbrain
writes a fallback: `{error: "command_failed", code, message, suggestion,
-exit_code, contract_version: 1}`.
+exit_code, contract_version: 1}`. A signal (exit 129, 130 or 143) writes
+`error: "interrupted"` with `code: "interrupted"` instead: the command was cut
+off, and it read nothing. That is not an empty result.
+
+**Slow reads.** `sync status`, `sources status`, `doctor`, `orphans`,
+`anomalies`, `status` and `diag` can take minutes on a large brain. They print
+`[gbrain] reading <what>; large brains can take minutes` on stderr when they
+start and a `still reading` line every 10 s, so silence on stdout means "not
+ready yet". Their `--json` document carries `elapsed_ms` and `complete`. When
+`complete` is false, `incomplete` lists each field a budget or bound left out
+(`{field, reason}`, reason `not_read`, `bounded` or `budget`); read those
+fields as unknown, never as none. A signal mid-read prints
+`[gbrain] Interrupted by <signal> after N s while reading <what>` on stderr and,
+under `--json`, writes `{error: "interrupted", signal, read, elapsed_ms,
+complete: false}` at once. If your harness cut the call off, re-run it with a
+longer timeout, or run `gbrain diag --json`: it returns one bounded bundle
+(version and build skew, each source's freshness and HEAD lag, holds by code,
+database connections, one search's stage timing). Each of its sections carries
+`elapsed_ms` and a status: `ok`, `not_read` with its reason, `not_applicable`
+or `error`.
## A write refused `owner_unavailable` with `detail: unbound_source`
diff --git a/plugin-variants/gbrain-daily/skills/conventions/agent-operator-protocol.md b/plugin-variants/gbrain-daily/skills/conventions/agent-operator-protocol.md
index 1ee28e8c3e..98b8739441 100644
--- a/plugin-variants/gbrain-daily/skills/conventions/agent-operator-protocol.md
+++ b/plugin-variants/gbrain-daily/skills/conventions/agent-operator-protocol.md
@@ -1028,7 +1028,26 @@ exactly one JSON document to stdout (or NDJSON lines for `eval export`,
`eval replay`, `eval gate` and `bench-publish`); everything else goes to
stderr. If such a command exits non-zero without writing its document, gbrain
writes a fallback: `{error: "command_failed", code, message, suggestion,
-exit_code, contract_version: 1}`.
+exit_code, contract_version: 1}`. A signal (exit 129, 130 or 143) writes
+`error: "interrupted"` with `code: "interrupted"` instead: the command was cut
+off, and it read nothing. That is not an empty result.
+
+**Slow reads.** `sync status`, `sources status`, `doctor`, `orphans`,
+`anomalies`, `status` and `diag` can take minutes on a large brain. They print
+`[gbrain] reading <what>; large brains can take minutes` on stderr when they
+start and a `still reading` line every 10 s, so silence on stdout means "not
+ready yet". Their `--json` document carries `elapsed_ms` and `complete`. When
+`complete` is false, `incomplete` lists each field a budget or bound left out
+(`{field, reason}`, reason `not_read`, `bounded` or `budget`); read those
+fields as unknown, never as none. A signal mid-read prints
+`[gbrain] Interrupted by <signal> after N s while reading <what>` on stderr and,
+under `--json`, writes `{error: "interrupted", signal, read, elapsed_ms,
+complete: false}` at once. If your harness cut the call off, re-run it with a
+longer timeout, or run `gbrain diag --json`: it returns one bounded bundle
+(version and build skew, each source's freshness and HEAD lag, holds by code,
+database connections, one search's stage timing). Each of its sections carries
+`elapsed_ms` and a status: `ok`, `not_read` with its reason, `not_applicable`
+or `error`.
## A write refused `owner_unavailable` with `detail: unbound_source`
diff --git a/plugin/skills/conventions/agent-operator-protocol.md b/plugin/skills/conventions/agent-operator-protocol.md
index 1ee28e8c3e..98b8739441 100644
--- a/plugin/skills/conventions/agent-operator-protocol.md
+++ b/plugin/skills/conventions/agent-operator-protocol.md
@@ -1028,7 +1028,26 @@ exactly one JSON document to stdout (or NDJSON lines for `eval export`,
`eval replay`, `eval gate` and `bench-publish`); everything else goes to
stderr. If such a command exits non-zero without writing its document, gbrain
writes a fallback: `{error: "command_failed", code, message, suggestion,
-exit_code, contract_version: 1}`.
+exit_code, contract_version: 1}`. A signal (exit 129, 130 or 143) writes
+`error: "interrupted"` with `code: "interrupted"` instead: the command was cut
+off, and it read nothing. That is not an empty result.
+
+**Slow reads.** `sync status`, `sources status`, `doctor`, `orphans`,
+`anomalies`, `status` and `diag` can take minutes on a large brain. They print
+`[gbrain] reading <what>; large brains can take minutes` on stderr when they
+start and a `still reading` line every 10 s, so silence on stdout means "not
+ready yet". Their `--json` document carries `elapsed_ms` and `complete`. When
+`complete` is false, `incomplete` lists each field a budget or bound left out
+(`{field, reason}`, reason `not_read`, `bounded` or `budget`); read those
+fields as unknown, never as none. A signal mid-read prints
+`[gbrain] Interrupted by <signal> after N s while reading <what>` on stderr and,
+under `--json`, writes `{error: "interrupted", signal, read, elapsed_ms,
+complete: false}` at once. If your harness cut the call off, re-run it with a
+longer timeout, or run `gbrain diag --json`: it returns one bounded bundle
+(version and build skew, each source's freshness and HEAD lag, holds by code,
+database connections, one search's stage timing). Each of its sections carries
+`elapsed_ms` and a status: `ok`, `not_read` with its reason, `not_applicable`
+or `error`.
## A write refused `owner_unavailable` with `detail: unbound_source`
diff --git a/skills/conventions/agent-operator-protocol.md b/skills/conventions/agent-operator-protocol.md
index 1ee28e8c3e..98b8739441 100644
--- a/skills/conventions/agent-operator-protocol.md
+++ b/skills/conventions/agent-operator-protocol.md
@@ -1028,7 +1028,26 @@ exactly one JSON document to stdout (or NDJSON lines for `eval export`,
`eval replay`, `eval gate` and `bench-publish`); everything else goes to
stderr. If such a command exits non-zero without writing its document, gbrain
writes a fallback: `{error: "command_failed", code, message, suggestion,
-exit_code, contract_version: 1}`.
+exit_code, contract_version: 1}`. A signal (exit 129, 130 or 143) writes
+`error: "interrupted"` with `code: "interrupted"` instead: the command was cut
+off, and it read nothing. That is not an empty result.
+
+**Slow reads.** `sync status`, `sources status`, `doctor`, `orphans`,
+`anomalies`, `status` and `diag` can take minutes on a large brain. They print
+`[gbrain] reading <what>; large brains can take minutes` on stderr when they
+start and a `still reading` line every 10 s, so silence on stdout means "not
+ready yet". Their `--json` document carries `elapsed_ms` and `complete`. When
+`complete` is false, `incomplete` lists each field a budget or bound left out
+(`{field, reason}`, reason `not_read`, `bounded` or `budget`); read those
+fields as unknown, never as none. A signal mid-read prints
+`[gbrain] Interrupted by <signal> after N s while reading <what>` on stderr and,
+under `--json`, writes `{error: "interrupted", signal, read, elapsed_ms,
+complete: false}` at once. If your harness cut the call off, re-run it with a
+longer timeout, or run `gbrain diag --json`: it returns one bounded bundle
+(version and build skew, each source's freshness and HEAD lag, holds by code,
+database connections, one search's stage timing). Each of its sections carries
+`elapsed_ms` and a status: `ok`, `not_read` with its reason, `not_applicable`
+or `error`.
## A write refused `owner_unavailable` with `detail: unbound_source`
diff --git a/skills/skills.lock.json b/skills/skills.lock.json
index c449c8adc0..976dcd4270 100644
--- a/skills/skills.lock.json
+++ b/skills/skills.lock.json
@@ -44,7 +44,7 @@
"concept-synthesis/routing-eval.jsonl": "96dbd7d9c1b606e9e06262d0c06282399741e2bccb8eeb7b9ca88c20f44cda0e",
"context-audit/SKILL.md": "6d786629d40544ddaab4f4e6e333569d270bcb8b581589dc16fb9f8bcb4f6207",
"context-audit/routing-eval.jsonl": "fb1832e24cc1b04163a74c5cde72bca53050a66246ca902e1a5f40303f52b5ab",
- "conventions/agent-operator-protocol.md": "2ef1e6ec2cdacfd6d666bf93b5f06c6d0d8bb7112a5cde49cc83ff43ff6b7a9a",
+ "conventions/agent-operator-protocol.md": "b42b19223aa9dffbe783ce7c5c681d762377c740f3c609cbc555b9a60a035235",
"conventions/brain-first.md": "b98dc24e086a35f136f74ca4abd856949d8b282e1298a47a250b2d18f69e0927",
"conventions/brain-routing.md": "392998d9a109b330c9225af4ca5c8798b0ff02eba4d441c93fdb7c263687d0c6",
"conventions/calibration.md": "500dc26bd7c8400f50dc4c16fd83f1a588f3e7e68c59050a21fd8a0f69e4d198",
diff --git a/src/cli/command-table.ts b/src/cli/command-table.ts
index 53b249050c..aa5055e461 100644
--- a/src/cli/command-table.ts
+++ b/src/cli/command-table.ts
@@ -115,8 +115,19 @@ interface CliCommandBase {
routes_source?: true | '--source-id';
/** D3: lazy curated help module. */
help?: () => Promise<{ help: CliHelpSpec }>;
+ /**
+ * A slow whole-brain read: the label its stderr heartbeat names for these arguments (`reading <label>`), or null
+ * when these arguments are not one (cli/slow-read.ts, core/read-heartbeat.ts).
+ */
+ slowRead?: (args: readonly string[]) => string | null;
}
+const positional = (args: readonly string[]) => args.find(a => !a.startsWith('-'));
+const sourceArg = (args: readonly string[]) => {
+ const i = args.indexOf('--source');
+ return i >= 0 && args[i + 1] && !args[i + 1]!.startsWith('-') ? args[i + 1] : args.find(a => a.startsWith('--source='))?.slice(9);
+};
+
export type CliCommandRecord =
| (CliCommandBase & {
phase: 'pre-connect' | 'pre-connect-own-engine';
@@ -228,7 +239,8 @@ export const CLI_COMMANDS: readonly CliCommandRecord[] = [ // Pre-connect: disp
{ name: 'apply-migrations', phase: 'pre-connect', thinClient: 'refuse', json: 'document', help: () => import('./help/apply-migrations.ts'), load: () => import('./commands/apply-migrations.ts') },
{ name: 'repair-jsonb', phase: 'pre-connect', thinClient: 'refuse', load: () => import('./commands/repair-jsonb.ts') },
{ name: 'skillpack-check', phase: 'pre-connect', thinClient: 'none', selfHelp: true, load: () => import('./commands/skillpack-check.ts') },
- { name: 'doctor', phase: 'pre-connect-own-engine', thinClient: 'none', json: 'document', help: () => import('./help/doctor.ts'), load: () => import('./commands/doctor.ts') },
+ { name: 'doctor', phase: 'pre-connect-own-engine', thinClient: 'none', json: 'document',
+ slowRead: args => args.includes('--remediate') || args.includes('--fix') ? null : 'doctor checks', help: () => import('./help/doctor.ts'), load: () => import('./commands/doctor.ts') },
// CLI_ONLY: cathedral-5: deterministic compiled-context views (engine-needing; refused on thin
// clients; help answers engine-free).
// selfHelp: cathedral-5: compile-context ships its own detailed usage (targets, check-mode exit
@@ -306,7 +318,8 @@ export const CLI_COMMANDS: readonly CliCommandRecord[] = [ // Pre-connect: disp
// selfHelp: v0.37 fix wave (Lane D.4 + CDX2-12): sync's --no-embed flag was unreachable via help
// because the dispatcher's generic CLI-only short-circuit fired before runSync could print its own
// usage block. Adding `sync` here routes `gbrain sync --help` into runSync.
- { name: 'sync', phase: 'post-connect', thinClient: 'refuse', selfHelp: true, json: 'document', routes_source: true, load: () => import('./commands/sync.ts') },
+ { name: 'sync', phase: 'post-connect', thinClient: 'refuse', selfHelp: true, json: 'document', routes_source: true,
+ slowRead: args => args.includes('status') ? `sync status for ${sourceArg(args) ? `source ${sourceArg(args)}` : 'the selected source'}` : null, load: () => import('./commands/sync.ts') },
// selfHelp: #3834: extract ships detailed help for its mode-specific flags. Keep the generic
// CLI-only stub from hiding that contract.
{ name: 'extract', phase: 'post-connect', thinClient: 'refuse', selfHelp: true, routes_source: '--source-id', load: () => import('./commands/extract.ts') },
@@ -324,14 +337,15 @@ export const CLI_COMMANDS: readonly CliCommandRecord[] = [ // Pre-connect: disp
// selfHelp: gbrain repair prints REPAIR_HELP (kinds + dry-run/apply contract).
// thin client: Wave 2 repair core: repairs publish coordinated writes on the brain host.
{ name: 'repair', phase: 'post-connect', thinClient: 'refuse', selfHelp: true, load: () => import('./commands/repair.ts') },
- { name: 'orphans', phase: 'post-connect', thinClient: 'refuse', selfHelp: true, load: () => import('./commands/orphans.ts') },
+ { name: 'diag', phase: 'post-connect', thinClient: 'refuse', json: 'document', read_only: true, slowRead: () => 'the diagnostic bundle', help: () => import('./help/diag.ts'), load: () => import('./commands/diag.ts') },
+ { name: 'orphans', phase: 'post-connect', thinClient: 'refuse', selfHelp: true, slowRead: () => 'orphan pages', load: () => import('./commands/orphans.ts') },
// selfHelp: maintain (#3015) prints its own usage block (modes + not-auto-applied list).
{ name: 'maintain', phase: 'post-connect', thinClient: 'none', selfHelp: true, load: () => import('./commands/maintain.ts') },
{ name: 'reindex', phase: 'post-connect', thinClient: 'none', selfHelp: true, load: () => import('./commands/reindex.ts') },
{ name: 'salience', phase: 'post-connect', thinClient: 'none', selfHelp: true, load: () => import('./commands/salience.ts') },
- { name: 'anomalies', phase: 'post-connect', thinClient: 'none', selfHelp: true, load: () => import('./commands/anomalies.ts') },
+ { name: 'anomalies', phase: 'post-connect', thinClient: 'none', selfHelp: true, slowRead: () => 'anomalous cohorts', load: () => import('./commands/anomalies.ts') },
{ name: 'feedback', phase: 'post-connect', thinClient: 'refuse', selfHelp: true, load: () => import('./commands/feedback.ts') },
- { name: 'status', phase: 'post-connect', thinClient: 'none', help: () => import('./help/status.ts'), load: () => import('./commands/status.ts') },
+ { name: 'status', phase: 'post-connect', thinClient: 'none', slowRead: args => args.includes('--funnel') ? null : 'the brain status snapshot', help: () => import('./help/status.ts'), load: () => import('./commands/status.ts') },
{ name: 'advisor', phase: 'post-connect', thinClient: 'refuse', selfHelp: true, load: () => import('./commands/advisor.ts') },
{ name: 'conversation-parser', phase: 'post-connect', thinClient: 'none', selfHelp: true, load: () => import('./commands/conversation-parser.ts') },
{ name: 'edges-backfill', phase: 'post-connect', thinClient: 'none', selfHelp: true, routes_source: true, load: () => import('./commands/edges-backfill.ts') },
@@ -374,7 +388,8 @@ export const CLI_COMMANDS: readonly CliCommandRecord[] = [ // Pre-connect: disp
// top-level help's own SOURCES block promises `sources --help` as the place to find the long tail
// (rename, default, attach, current, federate, set-cr-mode, webhook, harden, ...). That made the
// pointer circular and those subcommands undiscoverable from the CLI in either direction.
- { name: 'sources', phase: 'post-connect', thinClient: 'route-then-refuse', selfHelp: true, load: () => import('./commands/sources.ts') },
+ { name: 'sources', phase: 'post-connect', thinClient: 'route-then-refuse', selfHelp: true,
+ slowRead: args => args[0] === 'status' ? `source status for ${positional(args.slice(1)) ?? 'every source'}` : null, load: () => import('./commands/sources.ts') },
// CLI_ONLY: Open-loop engine CLI (engine-bound; trusted-local op dispatch).
{ name: 'waiting', phase: 'post-connect', thinClient: 'none', selfHelp: true, routes_source: true, load: () => import('./commands/waiting.ts') },
{ name: 'loops', phase: 'post-connect', thinClient: 'none', selfHelp: true, routes_source: true, load: () => import('./commands/loops.ts') },
diff --git a/src/cli/commands/diag.ts b/src/cli/commands/diag.ts
new file mode 100644
index 0000000000..a81335dd11
--- /dev/null
+++ b/src/cli/commands/diag.ts
@@ -0,0 +1,8 @@
+/** `gbrain diag`: post-connect dispatch (record in src/cli/command-table.ts, logic in src/commands/diag.ts). */
+import type { BrainEngine } from '../../core/engine.ts';
+import type { CliDispatchContext } from '../command-table.ts';
+
+export async function run(engine: BrainEngine, args: string[], ctx: CliDispatchContext): Promise<void> {
+ const { runDiag } = await import('../../commands/diag.ts');
+ await runDiag(engine, args, ctx.makeContext);
+}
diff --git a/src/cli/help/diag.ts b/src/cli/help/diag.ts
new file mode 100644
index 0000000000..80a40bfa96
--- /dev/null
+++ b/src/cli/help/diag.ts
@@ -0,0 +1,17 @@
+/** D3 curated help for `gbrain diag` (flags read by src/commands/diag.ts runDiag). */
+import type { CliHelpSpec } from '../command-table.ts';
+
+export const help: CliHelpSpec = {
+ summary: 'One bounded diagnostic bundle: version and build skew, each source\'s freshness and HEAD lag, held files by code, database connections, and the stage timing of one search. Read-only.',
+ usage: 'gbrain diag [--json] [--budget-ms <ms>] [--query <text>]',
+ flags: [
+ { name: '--json', type: 'boolean', desc: 'Print the bundle as one JSON document; every section carries elapsed_ms and a status (ok, not_read with its reason, not_applicable, error).' },
+ { name: '--budget-ms', type: 'number', desc: 'Total time for the bundle (default 30000); a section the budget cuts off says not_read.' },
+ { name: '--query', type: 'string', desc: 'Query for the timed search (default a fixed probe); the bundle shows its result count, never its results.' },
+ ],
+ examples: [
+ 'gbrain diag --json',
+ 'gbrain diag --json --budget-ms 60000',
+ 'gbrain diag --query "acme-example pricing"',
+ ],
+};
diff --git a/src/cli/main.ts b/src/cli/main.ts
index 67a96324c7..e1ec204742 100755
--- a/src/cli/main.ts
+++ b/src/cli/main.ts
@@ -516,7 +516,7 @@ async function main() {
if (['search', 'query', 'get', 'recall'].includes(command) && await (await import('./cli-socket-client.ts')).maybeServeFromCliSocket(command, subArgs)) return; // warm serve socket (opt-in)
// CLI-only commands
if (CLI_ONLY.has(command)) {
- await handleCliOnly(command, subArgs);
+ const endRead = (await import('./slow-read.ts')).beginCommandRead(command, subArgs); try { await handleCliOnly(command, subArgs); } finally { endRead(); }
return;
}
diff --git a/src/cli/slow-read.ts b/src/cli/slow-read.ts
new file mode 100644
index 0000000000..d95c91117c
--- /dev/null
+++ b/src/cli/slow-read.ts
@@ -0,0 +1,23 @@
+/**
+ * Which CLI invocations are slow whole-brain reads, and the start of their heartbeat (core/read-heartbeat.ts).
+ * Each command record names its reads with `slowRead` (command-table.ts).
+ */
+import { findCliCommand } from './command-table.ts';
+import { beginSlowRead } from '../core/read-heartbeat.ts';
+import { jsonRequested } from '../core/cli-force-exit.ts';
+import { getCliOptions } from '../core/cli-options.ts';
+
+/** The value after `flag` (`--source x` or `--source=x`), else undefined. */
+export function flagValue(args: readonly string[], flag: string): string | undefined {
+ const at = args.indexOf(flag);
+ if (at >= 0 && args[at + 1] && !args[at + 1]!.startsWith('-')) return args[at + 1];
+ return args.find(a => a.startsWith(flag + '='))?.slice(flag.length + 1);
+}
+
+/** Starts the heartbeat when `command args` is a slow read; returns the function that ends it (a no-op otherwise). */
+export function beginCommandRead(command: string, args: readonly string[]): () => void {
+ if (args.includes('--help') || args.includes('-h') || getCliOptions().quiet) return () => {};
+ const label = findCliCommand(command)?.slowRead?.(args);
+ if (!label) return () => {};
+ return beginSlowRead(label, { json: jsonRequested(args) });
+}
diff --git a/src/commands/diag.ts b/src/commands/diag.ts
new file mode 100644
index 0000000000..bb4ddc6c45
--- /dev/null
+++ b/src/commands/diag.ts
@@ -0,0 +1,178 @@
+/**
+ * `gbrain diag [--json] [--budget-ms <ms>] [--query <text>]`: one bounded diagnostic bundle an agent can paste
+ * whole instead of answering question by question. Read-only. Sections, each with its own `elapsed_ms`:
+ *
+ * gbrain this CLI's version, engine and runtime
+ * skew builds of this host's resident gbrain processes (doctor runtime_build_skew) and the writer version
+ * sources per source: last_sync_at, last synced commit, commits on this host's checkout HEAD after it, managed pass row
+ * holds held files per source and code (counts only)
+ * pool database connections: limit, backends by state, lock waits, long idle transactions, sessions the
+ * server ended on an error (Postgres 14+ pg_stat_database), and this process's pool size
+ * search per-stage timing of one search (`--query`, default a fixed probe), with its result count only
+ *
+ * Every section runs under the remaining budget (default 30 s). A section that did not run or did not finish in
+ * time says so (`status: 'not_read'` with its reason), never an implicit "none"; one that cannot apply here (a PGLite
+ * brain's pool, a source with no checkout) says `not_applicable`; one that failed carries `status: 'error'` with its code. It never reads a source's file level (`sync status --detail` does).
+ */
+import type { BrainEngine } from '../core/engine.ts';
+import type { OperationContext } from '../core/ops/contract.ts';
+import { VERSION } from '../version.ts';
+import { endSlowRead, incompleteFields } from '../core/read-heartbeat.ts';
+import { classifyItemFailure } from '../core/item-failure.ts';
+
+export const DIAG_DEFAULT_BUDGET_MS = 30_000;
+export const DIAG_SECTION_CAP_MS = { gbrain: 2_000, skew: 5_000, sources: 10_000, holds: 5_000, pool: 3_000, search: 10_000 } as const;
+export const DIAG_PROBE_QUERY = 'gbrain diagnostic probe';
+type SectionName = keyof typeof DIAG_SECTION_CAP_MS;
+
+export type DiagSection = { status: 'ok' | 'not_read' | 'not_applicable' | 'error'; elapsed_ms: number; reason?: string; code?: string; message?: string } & Record<string, unknown>;
+
+/** Runs `read` under min(its cap, what is left of the bundle's budget); never throws. */
+export async function diagSection(read: () => Promise<Record<string, unknown>>, capMs: number, deadline: number, now = () => performance.now()): Promise<DiagSection> {
+ const left = Math.min(capMs, deadline - now());
+ if (left <= 0) return { status: 'not_read', elapsed_ms: 0, reason: 'budget', message: 'The bundle budget ran out before this section started.' };
+ const started = now();
+ let timer: ReturnType<typeof setTimeout> | undefined;
+ const timeout = new Promise<'timeout'>(resolve => { timer = setTimeout(() => resolve('timeout'), left); timer.unref?.(); });
+ try {
+ const value = await Promise.race([read(), timeout]);
+ const elapsed = Math.round(now() - started);
+ if (value === 'timeout') return { status: 'not_read', elapsed_ms: elapsed, reason: 'budget', message: `Did not finish within ${Math.round(left)} ms; nothing from it is shown.` };
+ return { status: 'ok', elapsed_ms: elapsed, ...value };
+ } catch (error) {
+ if ((error as { notApplicable?: boolean }).notApplicable) return { status: 'not_applicable', elapsed_ms: Math.round(now() - started), message: (error as Error).message };
+ const failure = classifyItemFailure(error);
+ return { status: 'error', elapsed_ms: Math.round(now() - started), code: failure.code, message: failure.message.slice(0, 300) };
+ } finally { clearTimeout(timer); }
+}
+
+const notApplicable = (why: string): Record<string, unknown> => { throw Object.assign(new Error(why), { notApplicable: true }); };
+
+async function readSkew(engine: BrainEngine) {
+ const { runtimeBuildSkewCheck } = await import('./doctor/checks/runtime-build-skew.ts');
+ const { writerVersionCheck } = await import('./doctor/checks/writer-version.ts');
+ const { localHostIdentity } = await import('../core/persistence/identity.ts');
+ const brief = (c: { status: string; message?: string; details?: unknown }) => ({ status: c.status, message: c.message ?? null, ...(c.details && c.status !== 'ok' ? { details: c.details } : {}) });
+ return { runtime_build_skew: brief(await runtimeBuildSkewCheck(engine, localHostIdentity().id)), writer_version: brief(await writerVersionCheck(engine)) };
+}
+
+async function readSources(engine: BrainEngine, deadline: number) {
+ const { readGitBehind } = await import('../core/persistence/sync-freshness.ts');
+ const { readLivePassRows } = await import('../core/persistence/sync-pass-row.ts');
+ const rows = await engine.executeRaw<{ id: string; local_path: string | null; last_commit: string | null; last_sync_at: Date | string | null }>(
+ 'SELECT id, local_path, last_commit, last_sync_at FROM sources WHERE archived IS NOT TRUE ORDER BY id');
+ const passes = await readLivePassRows(engine).catch(() => null);
+ const items = [];
+ for (const row of rows) {
+ const behind = !row.local_path || !row.last_commit
+ ? { status: 'not_applicable' as const, elapsed_ms: 0, reason: row.local_path ? 'never_synced' : 'no_checkout' }
+ : await diagSection(async () => {
+ const lag = await readGitBehind(row.local_path!, row.last_commit!);
+ if (!lag) throw Object.assign(new Error('git could not count the commits after the last synced one on this checkout.'), { code: 'git_unavailable' });
+ return { commits: lag.commits, oldest_seconds: lag.oldest === null ? null : Math.max(0, Math.round(Date.now() / 1000 - lag.oldest)) };
+ }, 3_000, deadline);
+ const pass = passes?.get(row.id);
+ items.push({ id: row.id, last_sync_at: row.last_sync_at ? new Date(row.last_sync_at).toISOString() : null, last_commit: row.last_commit, behind_head: behind,
+ managed_pass: passes === null ? { status: 'not_read', reason: 'read_failed' } : pass ? { updated_at: pass.updated_at, state: (pass.value as { state?: unknown }).state ?? null } : { status: 'not_applicable', reason: 'no_pass_row' } });
+ }
+ return { count: items.length, items };
+}
+
+async function readHolds(engine: BrainEngine) {
+ const { GIT_HOLD_OP } = await import('../core/persistence/sync-holds.ts');
+ const rows = await engine.executeRaw<{ source_id: string; code: string; n: number | string }>(
+ `SELECT s.id AS source_id, h.completed_keys->0->>'code' AS code, count(*) AS n FROM op_checkpoints h
+ JOIN sources s ON s.id=h.completed_keys->0->>'source_id' AND s.incarnation::text=h.completed_keys->0->>'incarnation'
+ WHERE h.op=$1 GROUP BY 1, 2 ORDER BY 1, 2`, [GIT_HOLD_OP]);
+ const bySource: Record<string, { total: number; by_code: Record<string, number> }> = {};
+ for (const row of rows) {
+ const entry = bySource[row.source_id] ??= { total: 0, by_code: {} };
+ entry.by_code[row.code ?? 'unknown'] = Number(row.n);
+ entry.total += Number(row.n);
+ }
+ return { total: Object.values(bySource).reduce((sum, s) => sum + s.total, 0), by_source: bySource };
+}
+
+async function readPool(engine: BrainEngine) {
+ if (engine.kind !== 'postgres') return notApplicable(`The ${engine.kind} engine has no connection pool.`);
+ const [activity] = await engine.executeRaw<Record<string, number | string | null>>(
+ `SELECT current_setting('max_connections')::int AS max_connections, count(*) AS backends,
+ count(*) FILTER (WHERE state='active') AS active, count(*) FILTER (WHERE state='idle') AS idle,
+ count(*) FILTER (WHERE state LIKE 'idle in transaction%') AS idle_in_transaction,
+ count(*) FILTER (WHERE state LIKE 'idle in transaction%' AND state_change < now() - interval '60 seconds') AS idle_in_transaction_over_60s,
+ count(*) FILTER (WHERE wait_event_type='Lock') AS waiting_on_lock
+ FROM pg_stat_activity WHERE datname=current_database()`);
+ const num = (v: unknown) => (v === null || v === undefined ? null : Number(v));
+ let ended: Record<string, unknown>;
+ try {
+ const [s] = await engine.executeRaw<Record<string, unknown>>(
+ 'SELECT sessions, sessions_abandoned, sessions_fatal, sessions_killed, deadlocks, stats_reset FROM pg_stat_database WHERE datname=current_database()');
+ ended = { status: 'ok', sessions: num(s?.sessions), abandoned: num(s?.sessions_abandoned), fatal: num(s?.sessions_fatal), killed: num(s?.sessions_killed),
+ deadlocks: num(s?.deadlocks), since: s?.stats_reset ? new Date(s.stats_reset as string).toISOString() : null };
+ } catch { ended = { status: 'not_read', reason: 'server_before_postgres_14' }; }
+ return { process_pool_size: Number(process.env.GBRAIN_POOL_SIZE) || null, max_connections: num(activity?.max_connections), backends: num(activity?.backends),
+ by_state: { active: num(activity?.active), idle: num(activity?.idle), idle_in_transaction: num(activity?.idle_in_transaction) },
+ idle_in_transaction_over_60s: num(activity?.idle_in_transaction_over_60s), waiting_on_lock: num(activity?.waiting_on_lock), sessions_ended: ended };
+}
+
+async function readSearch(engine: BrainEngine, query: string, makeContext: ((engine: BrainEngine, params: Record<string, unknown>) => Promise<OperationContext>) | undefined) {
+ if (!makeContext) return notApplicable('No operation context is available to this caller.');
+ const { operationsByName } = await import('../core/operations.ts');
+ const params = { query, limit: 5 };
+ let meta: Record<string, unknown> | null = null;
+ const ctx: OperationContext = { ...await makeContext(engine, params), emitResponseMeta: (key: string, value: unknown) => { if (key === 'retrieval') meta = value as Record<string, unknown>; } };
+ const result = await operationsByName.search!.handler(ctx, params);
+ const rows = Array.isArray(result) ? result : Array.isArray((result as { results?: unknown })?.results) ? (result as { results: unknown[] }).results : [];
+ const m = meta as Record<string, unknown> | null;
+ return { query, result_count: rows.length, timings: m?.timings ?? { status: 'not_read', reason: 'no_timings_reported' }, degraded: m?.degraded ?? null, cost: m?.cost ?? null };
+}
+
+export interface DiagOptions { budgetMs: number; query: string; makeContext?: (engine: BrainEngine, params: Record<string, unknown>) => Promise<OperationContext>; caps?: Partial<Record<SectionName, number>> }
+
+/** The bundle (without `elapsed_ms`/`complete`, which the caller's read meta adds). */
+export async function collectDiag(engine: BrainEngine, opts: DiagOptions): Promise<Record<string, unknown>> {
+ const deadline = performance.now() + opts.budgetMs;
+ const cap = (name: SectionName) => opts.caps?.[name] ?? DIAG_SECTION_CAP_MS[name];
+ const run = (name: SectionName, read: () => Promise<Record<string, unknown>>) => diagSection(read, cap(name), deadline);
+ return {
+ schema_version: 1, budget_ms: opts.budgetMs,
+ gbrain: await run('gbrain', async () => ({ version: VERSION, engine: engine.kind, runtime: `bun ${Bun.version}`, platform: `${process.platform}-${process.arch}` })),
+ skew: await run('skew', () => readSkew(engine)),
+ sources: await run('sources', () => readSources(engine, deadline)),
+ holds: await run('holds', () => readHolds(engine)),
+ pool: await run('pool', () => readPool(engine)),
+ search: await run('search', () => readSearch(engine, opts.query, opts.makeContext)),
+ };
+}
+
+const SECTIONS: SectionName[] = ['gbrain', 'skew', 'sources', 'holds', 'pool', 'search'];
+
+export function formatDiag(doc: Record<string, unknown>): string {
+ const lines = [`gbrain diag (budget ${doc.budget_ms} ms, took ${doc.elapsed_ms ?? '?'} ms, ${doc.complete === false ? 'incomplete' : 'complete'})`];
+ for (const name of SECTIONS) {
+ const s = doc[name] as DiagSection;
+ const head = ` ${name}: ${s.status} (${s.elapsed_ms} ms)`;
+ if (s.status !== 'ok') { lines.push(`${head}${s.reason ? ` ${s.reason}` : ''}${s.code ? ` ${s.code}` : ''}${s.message ? `: ${s.message}` : ''}`); continue; }
+ const { status: _s, elapsed_ms: _e, ...rest } = s;
+ lines.push(`${head} ${JSON.stringify(rest)}`);
+ }
+ return lines.join('\n');
+}
+
+export async function runDiag(engine: BrainEngine, args: string[], makeContext?: DiagOptions['makeContext']): Promise<void> {
+ const json = args.includes('--json');
+ const budgetArg = args[args.indexOf('--budget-ms') + 1];
+ const budgetMs = args.includes('--budget-ms') ? Number(budgetArg) : DIAG_DEFAULT_BUDGET_MS;
+ if (!Number.isFinite(budgetMs) || budgetMs <= 0) {
+ const { opError } = await import('../core/ops/contract.ts');
+ throw opError('invalid_params', `--budget-ms needs a positive number of milliseconds, got ${budgetArg ?? 'nothing'}.`, 'Pass e.g. --budget-ms 30000, or omit it for the 30 s default.');
+ }
+ const query = args.includes('--query') ? args[args.indexOf('--query') + 1] ?? DIAG_PROBE_QUERY : DIAG_PROBE_QUERY;
+ const started = performance.now();
+ const bundle = await collectDiag(engine, { budgetMs, query, makeContext });
+ endSlowRead();
+ const incomplete = [...incompleteFields(bundle), ...SECTIONS.filter(name => (bundle[name] as DiagSection).status === 'error').map(name => ({ field: name, reason: 'error' as const }))];
+ const doc = { ...bundle, elapsed_ms: Math.round(performance.now() - started), complete: incomplete.length === 0, ...(incomplete.length ? { incomplete } : {}) };
+ if (json) { const { writeJsonDocument } = await import('../core/cli-force-exit.ts'); await writeJsonDocument(JSON.stringify(doc, null, 2)); }
+ else console.log(formatDiag(doc));
+}
diff --git a/src/commands/orphans.ts b/src/commands/orphans.ts
index e06e87b600..7224aff413 100644
--- a/src/commands/orphans.ts
+++ b/src/commands/orphans.ts
@@ -34,6 +34,7 @@ import { quarantineFilterFragment } from '../core/quarantine.ts';
import { isConnectorSourceKind } from '../core/persistence/connector-identity.ts';
import { pageSortedRows, topCounts, type ListingPage } from '../core/bounded-listing.ts';
import { nextListingCommand, parseListingFlags } from '../core/bounded-listing-cli.ts';
+import { withReadMeta } from '../core/read-heartbeat.ts';
// --- Types ---
@@ -362,7 +363,7 @@ Pages: the totals always count every orphan; one page of rows follows, and
const nextCommand = nextListingCommand(['gbrain', 'orphans', ...rest], page);
if (json) {
- console.log(JSON.stringify(orphansJson(result, page, nextCommand, request.cursor !== undefined || !page.complete), null, 2));
+ console.log(JSON.stringify(withReadMeta(orphansJson(result, page, nextCommand, request.cursor !== undefined || !page.complete)), null, 2));
return;
}
diff --git a/src/commands/sources.ts b/src/commands/sources.ts
index 498f8ec1d4..968b74d4c4 100644
--- a/src/commands/sources.ts
+++ b/src/commands/sources.ts
@@ -1273,7 +1273,7 @@ async function runStatus(engine: BrainEngine, rawArgs: string[]): Promise<void>
...(sharedSkills.get(m.source_id) ? { shared_skills: sharedSkills.get(m.source_id) } : {}),
...(uncommitted.get(m.source_id) ? { fence_repairs_uncommitted: uncommitted.get(m.source_id) } : {}), ...(watermarks.get(m.source_id) ? { watermark: watermarks.get(m.source_id) } : {}),
}));
- console.log(JSON.stringify({ schema_version: 1, sources: enriched }, null, 2));
+ console.log(JSON.stringify((await import('../core/read-heartbeat.ts')).withReadMeta({ schema_version: 1, sources: enriched }), null, 2));
return;
}
diff --git a/src/commands/status.ts b/src/commands/status.ts
index 67c313d782..02c3c6e406 100644
--- a/src/commands/status.ts
+++ b/src/commands/status.ts
@@ -54,6 +54,7 @@ import {
summarizeCrashes,
} from '../core/minions/handlers/supervisor-audit.ts';
import { formatSyncFreshness, readSyncFreshness, type SourceFreshness } from '../core/persistence/sync-freshness.ts';
+import { withReadMeta } from '../core/read-heartbeat.ts';
const SCHEMA_VERSION = 1 as const;
@@ -903,7 +904,7 @@ export async function runStatus(
}
if (json) {
- stdout(JSON.stringify(report) + '\n');
+ stdout(JSON.stringify(withReadMeta(report)) + '\n');
} else {
stdout(renderHuman(report));
}
diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.ts
index 5d416f75f3..9a6aeacfe0 100644
--- a/src/core/behavior-change-notice.ts
+++ b/src/core/behavior-change-notice.ts
@@ -1129,6 +1129,11 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText;
{ since: '0.60.372.0', text: 'MCP `find_anomalies` and `gbrain anomalies --json` list at most 20 slugs per anomalous cohort; `count` still covers the whole cohort and `page_slugs_complete: false` marks a row that left slugs out. `gbrain anomalies --json --all` lists every slug on a local brain.' },
{ since: '0.60.372.0', text: 'When `gbrain serve`\'s stdout or stderr is a regular file (the `gbrain mcp expose` service installs, or any `>>` redirect), serve rotates that file at 10 MiB, keeping 5 copies (`<log>.1` to `<log>.5`), and writes a line repeated within 10 minutes once, followed by one "[gbrain serve-log] repeated N more time(s)" line. `GBRAIN_SERVE_LOG_MAX_BYTES` (0 turns rotation off), `GBRAIN_SERVE_LOG_MAX_FILES` and `GBRAIN_SERVE_LOG_DEDUPE_SECONDS` (0 turns dedupe off) change it.' },
{ since: '0.60.372.0', text: '`gbrain sources status --json` no longer prints every held file of a source by default: `git_holds` now carries `count`, `by_code` (each hold code with its count and one example item, whose `fix` applies to the rest), and the first 10 items with `items_complete: false` and an `items_command`. `--holds` lists every held file read, as before, and `--limit <n> [--cursor <c>]` pages them by path (the cursor needs the source id). The text output is unchanged.' },
+ // GBRA-151 (slow reads say what they are doing; #7357). `since` is stamped at the merge slot.
+ { since: 'TBD', text: 'The slow whole-brain reads (`gbrain sync status`, `gbrain sources status`, `gbrain doctor`, `gbrain orphans`, `gbrain anomalies`, `gbrain status`, `gbrain diag`) print one stderr line when they start ("[gbrain] reading <what>; large brains can take minutes") and one every 10 s while they run, so a cut-off call is never silent. stdout is unchanged and still carries only the result; `--quiet` turns the lines off.' },
+ { since: 'TBD', text: 'The `--json` documents of those reads now carry `elapsed_ms` and `complete`. `complete` is false when a budget or bound cut the result short (a `*_read` field with `status: not_read`, a paged or capped list, a doctor check unknown for its budget), and `incomplete` lists each field with its reason. An error document gets `elapsed_ms` only, and `gbrain anomalies --json` stays a bare array.' },
+ { since: 'TBD', text: 'A `--json` command stopped by SIGTERM, SIGINT or SIGHUP before its result now writes `{error: "interrupted", code: "interrupted", ...}` instead of `command_failed`. During a slow read it does so at once, before cleanup, with the read and its `elapsed_ms`, plus one stderr line saying nothing was read, so the result is not empty.' },
+ { since: 'TBD', text: '`gbrain extract --stale` no longer exits 1 when one page holds a line or fence longer than the block bound (`page_body_segmented`). The link phase and the mention pass report that page by code, leave it stale and due, and finish every other page; before, the mention pass threw, and the unmanaged sweep stopped at that page.' },
];
/** The newest disclosed change's release: the notice id moves only when a release adds rows. */
diff --git a/src/core/cli-flag-registry.generated.ts b/src/core/cli-flag-registry.generated.ts
index 4feef0b6da..ae51dd8710 100644
--- a/src/core/cli-flag-registry.generated.ts
+++ b/src/core/cli-flag-registry.generated.ts
@@ -49,6 +49,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', '--legacy-lock', '--locks', '--name', '--no-accept-pending', '--path', '--prefer-postgres', '--probe', '--progress-interval', '--progress-json', '--quiet', '--remediate', '--restart', '--skip-verify', '--source', '--statement-timeout', '--supabase', '--timeout', '--timings', '--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', '--items-out', '--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'],
+ 'diag': ['--access', '--add', '--all', '--allowed-operations', '--apply', '--asof', '--body', '--bound-slug-prefixes', '--brain', '--budget-ms', '--client', '--count', '--cursor', '--date', '--dated-since', '--days', '--detach', '--entities', '--expect', '--expected-revision', '--federated-read', '--format', '--from-index', '--full', '--fuzzy', '--group-by', '--held', '--help', '--http', '--id', '--include-ambiguous', '--include-deleted', '--json', '--kind', '--limit', '--max-usd', '--model', '--multimodal', '--no-autopilot-install', '--no-pull', '--no-walk', '--only', '--page', '--params', '--path', '--phase', '--prefer', '--preview', '--purge', '--query', '--recent', '--refresh-operations', '--replace', '--reverse', '--row', '--scopes', '--session', '--side', '--since', '--slug', '--slugs', '--source', '--source-id', '--sources', '--stale', '--state', '--surface', '--to', '--updated-after', '--url', '--yes'],
'doctor': ['--abandon', '--abbrev-ref', '--accept-pending', '--access', '--account', '--acknowledge-managed', '--add', '--admin-intent', '--adopt', '--adopt-columns', '--adopt-permissions', '--after', '--aliases', '--all', '--all-drifted', '--all-from', '--allow-old-serve', '--allow-shell-jobs', '--allow-unverified-remote', '--allowed-operations', '--applied', '--apply', '--apply-rewrites', '--assign-corpus', '--audit', '--auto', '--auto-additive', '--auto-fix', '--autostash', '--background', '--batch', '--batch-check', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--branch', '--break-lock', '--budget-ms', '--budget-policy', '--budget-tokens', '--budget-usd', '--by-mention', '--cached', '--call-site', '--catch-up', '--check', '--class', '--clear', '--clear-never-installed', '--cli-socket', '--client', '--close', '--concurrency', '--confidence', '--confirm', '--confirm-quiesced', '--confirm-relocated-root', '--conflicts', '--contacts-dir', '--content-audit', '--content-root', '--conversation', '--count', '--cursor', '--dataset', '--db-url', '--delegated-namespace', '--delegated-slug-prefixes', '--delete-brain', '--dest', '--detach', '--detail', '--diff-filter', '--dim', '--dimensions', '--dir', '--disable', '--drain', '--drain-timeout', '--dry-run', '--egress', '--embedding-dimensions', '--embedding-model', '--enable', '--enable-dcr', '--end-of-options', '--entity', '--env', '--error-unmatch', '--exclude', '--exclude-standard', '--expand', '--expect', '--expect-local', '--expect-remote', '--expect-upstream', '--expected-epoch', '--expected-revision', '--expected-state', '--explain', '--facts', '--fast', '--federated-read', '--fetch-timeout-ms', '--ff-only', '--file', '--first-parent', '--fix', '--follow', '--force', '--force-break-lock', '--force-rechunk', '--force-retry', '--force-schema', '--format', '--fresh', '--fresh-token', '--from', '--from-meetings', '--from-pages', '--full', '--fuzzy', '--get', '--git-common-dir', '--git-dir', '--git-path', '--group', '--group-by', '--hard', '--hard-deadline', '--harness', '--held', '--help', '--holds', '--home', '--http', '--id', '--if-version', '--ignore-env-override', '--images', '--include-ambiguous', '--include-deleted', '--include-failures', '--include-flagged', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--include-pseudo', '--include-repairs', '--include-withdrawals', '--index-audit', '--init', '--input', '--install', '--is-ancestor', '--is-inside-work-tree', '--items-out', '--job-isolation', '--jq', '--json', '--keep', '--keep-checkout', '--lanes', '--lang', '--left-right', '--legacy-lock', '--limit', '--link-source', '--link-type', '--list', '--literal-pathspecs', '--local', '--local-env-vars', '--locks', '--log-noop', '--manifest', '--markdown', '--max-cost', '--max-cost-usd', '--max-facts', '--max-jobs', '--max-rss', '--max-runtime', '--max-usd', '--max-waiting', '--mcp-only', '--migrate-legacy', '--migrate-only', '--migration', '--min', '--min-n', '--mode', '--model', '--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-embed-cache', '--no-embedding', '--no-expand', '--no-extract', '--no-filters', '--no-hooks', '--no-lanes', '--no-llm', '--no-migrate', '--no-probe', '--no-pull', '--no-renames', '--no-repair', '--no-schema-pack', '--no-seat', '--no-tags', '--no-verify', '--no-walk', '--non-interactive', '--now', '--older-than', '--once', '--only', '--operations', '--others', '--out', '--output', '--oversized', '--overwrite', '--page', '--parallel', '--params', '--parked-pushes', '--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', '--provenance', '--provider', '--providers', '--prune-orphans', '--public-url', '--pull', '--pure', '--purge', '--push-only', '--query', '--question', '--queue', '--quiet', '--rate', '--reader-mode', '--reauth', '--rebase', '--rebuild', '--recommended', '--redact-paths', '--reference-date', '--refresh', '--refresh-operations', '--refresh-skills', '--regenerate', '--reissue', '--relative', '--relower', '--remediate', '--remediation-plan', '--remove', '--remove-core', '--repair', '--repair-unknown-markers', '--replace', '--repo', '--request', '--request-id', '--require-clean', '--reranker', '--reset', '--reset-checkpoint', '--reset-default', '--resolve', '--restore-only', '--resume', '--retry-failed', '--retry-global', '--retry-held', '--retry-parked', '--reverse', '--review-lower', '--revision', '--rollback-to-source', '--save', '--scope', '--scopes', '--search-mode', '--seat', '--section', '--select', '--self-transfer', '--semantic', '--session', '--session-id', '--set', '--set-upstream-to', '--shadow', '--short', '--show-current', '--show-prefix', '--show-token', '--show-toplevel', '--side', '--since', '--since-last-run', '--skills-dir', '--skip', '--skip-bare-tweet', '--skip-failed', '--skip-urls', '--skip-verify', '--slot', '--slot-a-model', '--slot-b-model', '--slot-c-model', '--slug', '--slugs', '--source', '--source-id', '--sources', '--src-subpath', '--staged', '--stale', '--state', '--statement-timeout', '--status', '--stdin', '--strategy', '--strict', '--suite', '--supabase', '--surface', '--symbol-kind', '--symbolic-full-name', '--takes-holders', '--target', '--target-score', '--threshold', '--tier', '--timeout', '--timings', '--to', '--token', '--token-ttl', '--top-k', '--trust', '--type', '--unindexed', '--uninstall', '--unsafe-bypass-dream-guard', '--unset-all', '--untracked-files', '--url', '--url-env', '--user', '--vacuum', '--vectors', '--verbose', '--verify', '--version', '--wait', '--wait-drain', '--warn-only', '--watch', '--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', '--probe', '--pull', '--reconcile-queue', '--since', '--source', '--source-id', '--threshold', '--to', '--unsafe-bypass-dream-guard', '--window', '--yes'],
'edge-proposals': ['--access', '--add', '--all', '--all-applied', '--all-held', '--allowed-operations', '--asof', '--body', '--bound-slug-prefixes', '--brain', '--client', '--cursor', '--date', '--dated-since', '--days', '--entities', '--federated-read', '--from-index', '--full', '--fuzzy', '--group-by', '--help', '--http', '--id', '--include-deleted', '--json', '--kind', '--limit', '--max-usd', '--model', '--multimodal', '--no-autopilot-install', '--page', '--params', '--path', '--phase', '--prefer', '--purge', '--recent', '--refresh-operations', '--row', '--scopes', '--session', '--since', '--slugs', '--source', '--sources', '--stale', '--status', '--surface', '--to', '--updated-after', '--url', '--yes'],
@@ -172,6 +173,7 @@ export const CLI_ROUTING_FLAGS: Record<string, readonly string[]> = {
'core': ['--brain'],
'db-repair': ['--brain'],
'decide': ['--brain'],
+ 'diag': ['--brain'],
'doctor': ['--brain'],
'dream': ['--brain', '--source'],
'edge-proposals': ['--brain'],
diff --git a/src/core/cli-force-exit.ts b/src/core/cli-force-exit.ts
index 6535ae905a..d7b7fa876d 100644
--- a/src/core/cli-force-exit.ts
+++ b/src/core/cli-force-exit.ts
@@ -66,6 +66,7 @@ import {
} from './background-work.ts';
import { POOL_END_TIMEOUT_SECONDS } from './db.ts';
import { parseGlobalFlags } from './cli-options.ts';
+import { setInterruptedDocumentWriter, slowReadElapsedMs, withReadMeta } from './read-heartbeat.ts';
const DAEMON_COMMANDS: ReadonlySet<string> = new Set(['serve']);
@@ -759,6 +760,11 @@ export function installStdoutPipeDelivery(opts: { json?: 'document' | 'ndjson' }
if (process.stdout.isTTY && !opts.json) return;
stdoutInterposed = true;
jsonGuardMode = opts.json ?? null;
+ setInterruptedDocumentWriter(doc => {
+ if (jsonDocumentWritten) return;
+ jsonDocumentWritten = true;
+ void chainStdoutWrite(`${JSON.stringify(doc, null, jsonGuardMode === 'ndjson' ? undefined : 2)}\n`).catch(() => { /* fd 1 gone */ });
+ });
const toStderr = (data: string | Uint8Array, encoding?: BufferEncoding): Promise<void> => {
try { process.stderr.write(typeof data === 'string' ? Buffer.from(data, encoding ?? 'utf8') : data); } catch { /* best effort */ }
return Promise.resolve();
@@ -835,12 +841,16 @@ function writeJsonFallbackIfMissing(exitCode: number): void {
return;
}
jsonDocumentWritten = true;
+ // 129/130/143: a signal stopped the command before its result; say so, so a harness timeout never reads as empty.
+ const signalled = exitCode === 129 || exitCode === 130 || exitCode === 143;
const doc = {
...(jsonGuardMode === 'ndjson' ? { status: 'error' } : {}),
- error: 'command_failed',
- code: lastRenderedErrorCode ?? 'command_failed',
- message: `The command exited with status ${exitCode} without writing its JSON result.`,
- suggestion: 'Re-run without --json to read the error on stderr, or run `gbrain doctor --json`.',
+ error: signalled ? 'interrupted' : 'command_failed',
+ code: signalled ? 'interrupted' : lastRenderedErrorCode ?? 'command_failed',
+ message: signalled ? `The command was interrupted by a signal (exit ${exitCode}) before it wrote its JSON result. Nothing was read, so this is not an empty result.`
+ : `The command exited with status ${exitCode} without writing its JSON result.`,
+ suggestion: signalled ? 'Re-run the same command with a longer timeout; large brains can take minutes.'
+ : 'Re-run without --json to read the error on stderr, or run `gbrain doctor --json`.',
exit_code: exitCode,
contract_version: 1,
};
@@ -875,7 +885,15 @@ function recordJsonDocumentMissing(): void {
*/
export async function writeStdoutFinal(output: string): Promise<void> {
jsonDocumentWritten = true;
- await chainStdoutWrite(output);
+ await chainStdoutWrite(jsonGuardMode === 'document' && slowReadElapsedMs() !== null ? withReadMetaText(output) : output);
+}
+
+/** A slow read's document text with `elapsed_ms` and `complete` (read-heartbeat.ts), in the text's own indentation. */
+function withReadMetaText(output: string): string {
+ let doc: unknown;
+ try { doc = JSON.parse(output); } catch { return output; }
+ const indent = /^\{\n( +)"/.exec(output)?.[1]?.length;
+ return `${JSON.stringify(withReadMeta(doc), null, indent)}${output.endsWith('\n') ? '\n' : ''}`;
}
/**
diff --git a/src/core/process-cleanup.ts b/src/core/process-cleanup.ts
index a11b282daa..9b5d83d333 100644
--- a/src/core/process-cleanup.ts
+++ b/src/core/process-cleanup.ts
@@ -43,6 +43,8 @@
* double-DELETE.
*/
+import { noteInterrupted } from './read-heartbeat.ts';
+
const CLEANUP_DEADLINE_MS = 3_000;
interface CleanupEntry {
@@ -204,6 +206,9 @@ export function installSignalHandlers(opts: { keepServingOnLogEpipe?: boolean }
const handleSignal = (signal: NodeJS.Signals) => {
if (forwardToSignalOwner(signal)) return;
+ // A slow read (sync status, doctor, ...) says it was cut off before cleanup runs, so a harness that follows its
+ // SIGTERM with SIGKILL still sees the note.
+ if (signal !== 'SIGPIPE') noteInterrupted(signal);
void runCleanupPass().finally(() => {
// Match GNU `kill` exit-code convention: 128 + signal number for
// signal-terminated processes. The actual integer doesn't matter
diff --git a/src/core/read-heartbeat.ts b/src/core/read-heartbeat.ts
new file mode 100644
index 0000000000..13e168e8f4
--- /dev/null
+++ b/src/core/read-heartbeat.ts
@@ -0,0 +1,128 @@
+/**
+ * Slow whole-brain reads (sync status, sources status, doctor, orphans, anomalies, status, diag) tell their caller
+ * what is happening while they run, so an agent whose harness cuts the command off cannot mistake silence for an
+ * empty result:
+ *
+ * - one stderr line when the read starts, then one every 10 s while it runs (stdout stays the one result);
+ * - the `--json` document carries `elapsed_ms` and `complete`, and `incomplete` lists each field a budget or
+ * bound left out (the existing markers: a `*_read` field with `status: 'not_read'`, `complete: false`,
+ * `items_complete: false`, `budget_hit: true`, a doctor check unknown for its budget);
+ * - SIGTERM, SIGHUP or SIGINT before the result prints one stderr line and, under `--json`, one `interrupted`
+ * document saying how long it ran and that no result was read.
+ *
+ * One read per CLI process, so module state is safe.
+ */
+
+export const READ_HEARTBEAT_EVERY_MS = 10_000;
+
+export interface IncompleteField { field: string; reason: 'not_read' | 'bounded' | 'budget' | 'error' }
+
+interface ActiveRead {
+ label: string;
+ startedAt: number;
+ json: boolean;
+ timer: ReturnType<typeof setInterval> | null;
+ sigint: (() => void) | null;
+ writeErr: (line: string) => void;
+}
+
+let active: ActiveRead | null = null;
+let interruptWriter: ((doc: Record<string, unknown>) => void) | null = null;
+
+/** The CLI's stdout writer for the `interrupted` document (cli-force-exit.ts registers it, so this module imports nothing). */
+export function setInterruptedDocumentWriter(write: ((doc: Record<string, unknown>) => void) | null): void { interruptWriter = write; }
+
+const seconds = (ms: number) => Math.round(ms / 1000);
+
+/**
+ * Starts the heartbeat for one read. `json`: the caller asked for `--json` (an interrupt then writes the
+ * `interrupted` document). Returns the function that ends the read.
+ */
+export function beginSlowRead(label: string, opts: { json: boolean; everyMs?: number; writeErr?: (line: string) => void; now?: () => number }): () => void {
+ endSlowRead();
+ const now = opts.now ?? Date.now;
+ const writeErr = opts.writeErr ?? (line => { try { process.stderr.write(line + '\n'); } catch { /* stderr gone */ } });
+ const read: ActiveRead = { label, startedAt: now(), json: opts.json, timer: null, sigint: null, writeErr };
+ active = read;
+ writeErr(`[gbrain] reading ${label}; large brains can take minutes. Progress prints here every ${seconds(opts.everyMs ?? READ_HEARTBEAT_EVERY_MS)} s; the result prints on stdout when it is ready.`);
+ read.timer = setInterval(() => writeErr(`[gbrain] still reading ${label} (${seconds(now() - read.startedAt)} s so far); no result yet.`), opts.everyMs ?? READ_HEARTBEAT_EVERY_MS);
+ read.timer.unref?.();
+ if (process.listenerCount('SIGINT') === 0) {
+ read.sigint = () => { noteInterrupted('SIGINT', now()); process.exit(130); };
+ process.on('SIGINT', read.sigint);
+ }
+ return endSlowRead;
+}
+
+/** Ends the active read: the heartbeat stops and an interrupt no longer prints a note. Idempotent. */
+export function endSlowRead(): void {
+ if (!active) return;
+ if (active.timer) clearInterval(active.timer);
+ if (active.sigint) process.off('SIGINT', active.sigint);
+ active = null;
+}
+
+/** Milliseconds since the active read started; null when none is active. */
+export function slowReadElapsedMs(now = Date.now()): number | null {
+ return active ? now - active.startedAt : null;
+}
+
+const MAX_NODES = 50_000;
+
+/** Every field a budget or bound left out of `doc`, by path (`sources[0].holds_read`), from the existing markers. */
+export function incompleteFields(doc: unknown): IncompleteField[] {
+ const out: IncompleteField[] = [];
+ let nodes = 0;
+ const walk = (value: unknown, path: string, depth: number) => {
+ if (value === null || typeof value !== 'object' || depth > 8 || ++nodes > MAX_NODES) return;
+ if (Array.isArray(value)) { value.forEach((item, i) => walk(item, `${path}[${i}]`, depth + 1)); return; }
+ const record = value as Record<string, unknown>;
+ if (path && record.status === 'not_read') out.push({ field: path, reason: 'not_read' });
+ if (path && record.health === 'unknown' && record.reason === 'budget') out.push({ field: path, reason: 'budget' });
+ for (const [key, child] of Object.entries(record)) {
+ const at = path ? `${path}.${key}` : key;
+ if (child === false && (key === 'complete' || key.endsWith('_complete')) && at !== 'complete') out.push({ field: at, reason: 'bounded' });
+ else if (child === true && key === 'budget_hit') out.push({ field: at, reason: 'budget' });
+ else walk(child, at, depth + 1);
+ }
+ };
+ walk(doc, '', 0);
+ return out;
+}
+
+/**
+ * The read's `--json` document with `elapsed_ms` (since the read started) and `complete` (false when the document
+ * says it is paged or a field was not read; `incomplete` names each). A field the document already sets wins; an
+ * error envelope gets `elapsed_ms` only; a non-object document (a bare array) is returned as is. Ends the read.
+ */
+export function withReadMeta<T>(doc: T, now = Date.now()): T {
+ const elapsed = slowReadElapsedMs(now);
+ endSlowRead();
+ if (elapsed === null || doc === null || typeof doc !== 'object' || Array.isArray(doc)) return doc;
+ const record = doc as Record<string, unknown>;
+ // An error envelope read nothing: it gains the elapsed time, never a completeness claim.
+ if (record.error !== undefined && record.error !== null) return (record.elapsed_ms === undefined ? { ...record, elapsed_ms: elapsed } : record) as T;
+ const incomplete = incompleteFields(record);
+ const complete = record.complete !== false && incomplete.length === 0;
+ return { ...record, ...(record.elapsed_ms === undefined ? { elapsed_ms: elapsed } : {}), ...(record.complete === undefined ? { complete } : {}),
+ ...(incomplete.length && record.incomplete === undefined ? { incomplete } : {}) } as T;
+}
+
+/**
+ * A signal arrived while a read was active: one stderr line and, under `--json`, the `interrupted` document.
+ * Returns false (and writes nothing) when no read is active.
+ */
+export function noteInterrupted(signal: string, now = Date.now()): boolean {
+ const read = active;
+ if (!read) return false;
+ endSlowRead();
+ const elapsedMs = now - read.startedAt;
+ const message = `Interrupted by ${signal} after ${seconds(elapsedMs)} s while reading ${read.label}, before the result was ready. Nothing was read, so this is not an empty result.`;
+ read.writeErr(`[gbrain] ${message} Re-run with a longer timeout; large brains can take minutes.`);
+ if (read.json) {
+ interruptWriter?.({ error: 'interrupted', code: 'interrupted', message,
+ suggestion: 'Re-run the same command with a longer timeout (large brains can take minutes), or run `gbrain diag --json` for a bounded summary.',
+ signal, read: read.label, elapsed_ms: elapsedMs, complete: false, contract_version: 1 });
+ }
+ return true;
+}
diff --git a/test/cli-dispatch-phase.test.ts b/test/cli-dispatch-phase.test.ts
index 42acf8542c..1107d57a59 100644
--- a/test/cli-dispatch-phase.test.ts
+++ b/test/cli-dispatch-phase.test.ts
@@ -89,7 +89,7 @@ describe('CLI dispatch shape (master AST)', () => {
const shape = await expectNormalizerStable(extractCliDispatch, astNormalizer);
expect(shape.sets.CLI_ONLY).toEqual([...CLI_ONLY].sort());
expect(shape.sets.THIN_CLIENT_REFUSED_COMMANDS).toEqual([...THIN_CLIENT_REFUSED_COMMANDS].sort());
- expect(shape.switchCases.length).toBe(69);
+ expect(shape.switchCases.length).toBe(70);
expect(Object.keys(shape.commands).length).toBeGreaterThanOrEqual(shape.sets.CLI_ONLY.length);
});
diff --git a/test/cli-help-curated.test.ts b/test/cli-help-curated.test.ts
index ee21b0c5bf..b0e5342dc2 100644
--- a/test/cli-help-curated.test.ts
+++ b/test/cli-help-curated.test.ts
@@ -2,7 +2,7 @@
* Agent contract v1 D3/D4 (CLI-only half): curated help specs, their renderer
* and the typed flag-value validator built from them.
*
- * Protects: the 7 ops-critical commands carry a curated spec whose flags the
+ * Protects: the 8 ops-critical commands carry a curated spec whose flags the
* acceptance registry accepts (so help never advertises a flag the CLI then
* rejects), `--yes` is listed wherever the handler parses it, the rendered
* help shows type/values/consent, `curatedFlagError` turns a NaN number or an
@@ -22,7 +22,7 @@ import { loadCuratedHelp, renderCuratedHelp } from '../src/cli/help/render.ts';
import { curatedFlagError } from '../src/cli/help/validate.ts';
import { unknownFlagError } from '../src/cli/cli-error.ts';
-const OPS_CRITICAL = ['apply-migrations', 'autopilot', 'doctor', 'import', 'onboard', 'serve', 'status'];
+const OPS_CRITICAL = ['apply-migrations', 'autopilot', 'diag', 'doctor', 'import', 'onboard', 'serve', 'status'];
/** Handlers that parse `--yes` (doctor --remediate, apply-migrations parseArgs). */
const PARSES_YES = ['apply-migrations', 'doctor'];
diff --git a/test/fixtures/goldens/cli/dispatch-phase.json b/test/fixtures/goldens/cli/dispatch-phase.json
index d0b234a0b2..2ad9141a05 100644
--- a/test/fixtures/goldens/cli/dispatch-phase.json
+++ b/test/fixtures/goldens/cli/dispatch-phase.json
@@ -547,6 +547,13 @@
"thinClient": "refuse",
"thinClientRoutedSubcommands": []
},
+ "diag": {
+ "hasSwitchCase": true,
+ "phase": "post-connect",
+ "preConnectRules": [],
+ "thinClient": "refuse",
+ "thinClientRoutedSubcommands": []
+ },
"doctor": {
"hasSwitchCase": false,
"phase": "pre-connect-own-engine",
diff --git a/test/fixtures/goldens/cli/literal-imports.json b/test/fixtures/goldens/cli/literal-imports.json
index 2a9ea2f538..235c104741 100644
--- a/test/fixtures/goldens/cli/literal-imports.json
+++ b/test/fixtures/goldens/cli/literal-imports.json
@@ -52,6 +52,9 @@
"core": [
"./commands/core.ts"
],
+ "diag": [
+ "./commands/diag.ts"
+ ],
"edge-proposals": [
"./commands/edge-proposals.ts"
],
diff --git a/test/fixtures/goldens/cli/membership-sets.json b/test/fixtures/goldens/cli/membership-sets.json
index 9fc28b73f2..4e33f1fd45 100644
--- a/test/fixtures/goldens/cli/membership-sets.json
+++ b/test/fixtures/goldens/cli/membership-sets.json
@@ -69,6 +69,7 @@
"refusedNotInCliOnly": [],
"refusedWithoutHint": [
"beliefs",
+ "diag",
"edge-proposals",
"feedback",
"questions",
@@ -124,6 +125,7 @@
"creds",
"db-repair",
"decide",
+ "diag",
"doctor",
"dream",
"edge-proposals",
@@ -381,6 +383,7 @@
"compile-context",
"config",
"decide",
+ "diag",
"dream",
"edge-proposals",
"embed",
diff --git a/test/fixtures/goldens/doctor/json-postgres-fresh.json b/test/fixtures/goldens/doctor/json-postgres-fresh.json
index be281d5300..4042f5378e 100644
--- a/test/fixtures/goldens/doctor/json-postgres-fresh.json
+++ b/test/fixtures/goldens/doctor/json-postgres-fresh.json
@@ -3580,6 +3580,7 @@
"unknown_sections": []
},
"stderr": [
+ "[gbrain] reading doctor checks; large brains can take minutes. Progress prints here every 10 s; the result prints on stdout when it is ready.",
"[gbrain doctor] non-interactive run: the check run (not connect or migrations) is capped at 90000 ms (doctor.default_budget_ms); checks past it report health unknown. Off for one run: --budget-ms 0; off for good: gbrain config set doctor.default_budget_ms 0. On PGLite a statement already running cannot be stopped, so a check can finish late.",
"[backup] checked 1 asset(s): 0 without a git remote (computed_by=doctor)"
],
diff --git a/test/fixtures/slow-read-cli.ts b/test/fixtures/slow-read-cli.ts
new file mode 100644
index 0000000000..acdeaf7be4
--- /dev/null
+++ b/test/fixtures/slow-read-cli.ts
@@ -0,0 +1,15 @@
+/**
+ * A CLI process stuck in a slow read, for the harness-timeout tests (test/read-heartbeat-cli.test.ts): the CLI's own
+ * signal handlers and stdout guard, then a read that never finishes. `--json` turns the document guard on;
+ * READ_EVERY_MS sets the heartbeat interval; NO_READ=1 skips the read (a command killed outside one).
+ */
+import { installSignalHandlers } from '../../src/core/process-cleanup.ts';
+import { installStdoutPipeDelivery } from '../../src/core/cli-force-exit.ts';
+import { beginSlowRead } from '../../src/core/read-heartbeat.ts';
+
+const json = process.argv.includes('--json');
+installSignalHandlers();
+installStdoutPipeDelivery(json ? { json: 'document' } : {});
+if (process.env.NO_READ !== '1') beginSlowRead('sync status for source alpha-example', { json, everyMs: Number(process.env.READ_EVERY_MS ?? 10_000) });
+process.stderr.write('fixture: ready\n');
+setInterval(() => {}, 1_000);
diff --git a/test/read-heartbeat-cli.test.ts b/test/read-heartbeat-cli.test.ts
new file mode 100644
index 0000000000..07772128e7
--- /dev/null
+++ b/test/read-heartbeat-cli.test.ts
@@ -0,0 +1,97 @@
+/**
+ * A harness that times out a slow read must not read silence as an empty result.
+ *
+ * 1. Protects: a slow read prints its start line on stderr at once and a progress line on every interval; SIGTERM,
+ * SIGINT or SIGHUP mid-read prints one stderr line and, under --json, one `interrupted` document on stdout saying how
+ * long it ran and that nothing was read; a harness that follows SIGTERM with SIGKILL still gets both; a guarded
+ * command killed outside a read gets the `interrupted` fallback, not `command_failed`. Real CLI: `doctor --json`
+ * prints the start line on stderr and `elapsed_ms`/`complete` in its document, stdout staying one JSON document.
+ * 2. Fails when: the heartbeat waits for the result, the note runs only after cleanup, or the fallback calls a signal a
+ * command failure.
+ */
+import { describe, expect, test } from 'bun:test';
+import { mkdtempSync, rmSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+
+const FIXTURE = join(import.meta.dir, 'fixtures', 'slow-read-cli.ts');
+const CLI = join(import.meta.dir, '..', 'src', 'cli.ts');
+
+async function readUntil(stream: ReadableStream<Uint8Array>, sink: { text: string }, needle: string, timeoutMs = 20_000): Promise<void> {
+ const reader = stream.getReader();
+ const decoder = new TextDecoder();
+ const deadline = Date.now() + timeoutMs;
+ (async () => { for (;;) { const { value, done } = await reader.read(); if (done) return; sink.text += decoder.decode(value); } })();
+ while (!sink.text.includes(needle)) {
+ if (Date.now() > deadline) throw new Error(`never saw ${JSON.stringify(needle)} in: ${sink.text}`);
+ await Bun.sleep(20);
+ }
+}
+
+async function harness(opts: { json: boolean; signal: NodeJS.Signals; killAfterMs?: number; env?: Record<string, string>; waitFor?: string }) {
+ const proc = Bun.spawn([process.execPath, FIXTURE, ...(opts.json ? ['--json'] : [])], { stdout: 'pipe', stderr: 'pipe', env: { ...process.env, ...opts.env } });
+ const err = { text: '' };
+ await readUntil(proc.stderr, err, opts.waitFor ?? 'fixture: ready');
+ proc.kill(opts.signal);
+ if (opts.killAfterMs !== undefined) setTimeout(() => proc.kill('SIGKILL'), opts.killAfterMs);
+ const [stdout, code] = await Promise.all([new Response(proc.stdout).text(), proc.exited]);
+ await Bun.sleep(50);
+ return { stdout, stderr: err.text, code };
+}
+
+describe('slow read heartbeat and interrupt note', () => {
+ test('the start line prints at once and a progress line on every interval, before any result', async () => {
+ const r = await harness({ json: true, signal: 'SIGTERM', env: { READ_EVERY_MS: '200' }, waitFor: 'still reading' });
+ const lines = r.stderr.split('\n');
+ expect(lines[0]).toContain('[gbrain] reading sync status for source alpha-example; large brains can take minutes.');
+ expect(lines.some(l => /\[gbrain\] still reading sync status for source alpha-example \(\d+ s so far\); no result yet\./.test(l))).toBe(true);
+ }, 30_000);
+
+ for (const [signal, exit] of [['SIGTERM', 143], ['SIGINT', 130], ['SIGHUP', 129]] as const) {
+ test(`${signal} mid-read: one stderr line and one interrupted document, never an empty result`, async () => {
+ const r = await harness({ json: true, signal });
+ expect(r.code).toBe(exit);
+ expect(r.stderr).toMatch(new RegExp(`\\[gbrain\\] Interrupted by ${signal} after \\d+ s while reading sync status for source alpha-example, before the result was ready\\. Nothing was read, so this is not an empty result\\.`));
+ const doc = JSON.parse(r.stdout);
+ expect(doc).toMatchObject({ error: 'interrupted', code: 'interrupted', signal, read: 'sync status for source alpha-example', complete: false, contract_version: 1 });
+ expect(typeof doc.elapsed_ms).toBe('number');
+ expect(r.stdout.trim().split('\n').join('')).toBe(JSON.stringify(doc, null, 2).split('\n').join(''));
+ }, 30_000);
+ }
+
+ test('a harness that sends SIGKILL 200 ms after SIGTERM still gets the note and the document', async () => {
+ const r = await harness({ json: true, signal: 'SIGTERM', killAfterMs: 200 });
+ expect(r.stderr).toContain('Interrupted by SIGTERM');
+ expect(JSON.parse(r.stdout)).toMatchObject({ code: 'interrupted', complete: false });
+ }, 30_000);
+
+ test('without --json the note goes to stderr only and stdout stays empty', async () => {
+ const r = await harness({ json: false, signal: 'SIGTERM' });
+ expect(r.code).toBe(143);
+ expect(r.stderr).toContain('Interrupted by SIGTERM');
+ expect(r.stdout).toBe('');
+ }, 30_000);
+
+ test('a guarded command killed outside a read gets the interrupted fallback, not command_failed', async () => {
+ const r = await harness({ json: true, signal: 'SIGTERM', env: { NO_READ: '1' } });
+ expect(r.code).toBe(143);
+ expect(JSON.parse(r.stdout)).toMatchObject({ error: 'interrupted', code: 'interrupted', exit_code: 143 });
+ expect(r.stderr).not.toContain('[gbrain] reading');
+ }, 30_000);
+});
+
+describe('real CLI: doctor --json', () => {
+ test('prints the start line on stderr and elapsed_ms/complete in its one document', async () => {
+ const home = mkdtempSync(join(tmpdir(), 'gbrain-slow-read-'));
+ try {
+ const env = { ...process.env, GBRAIN_HOME: home, GBRAIN_NO_UPDATE_CHECK: '1', GBRAIN_TELEMETRY: '0' } as Record<string, string>;
+ delete env.DATABASE_URL; delete env.GBRAIN_DATABASE_URL; delete env.OPENAI_API_KEY;
+ expect(Bun.spawnSync([process.execPath, CLI, 'init', '--pglite', '--no-embedding'], { env, stdout: 'ignore', stderr: 'ignore' }).exitCode).toBe(0);
+ const r = Bun.spawnSync([process.execPath, CLI, 'doctor', '--json', '--only', 'connection'], { env, stdout: 'pipe', stderr: 'pipe' });
+ expect(r.stderr.toString().split('\n')[0]).toContain('[gbrain] reading doctor checks; large brains can take minutes.');
+ const doc = JSON.parse(r.stdout.toString());
+ expect(typeof doc.elapsed_ms).toBe('number');
+ expect(doc.complete).toBe(true);
+ } finally { rmSync(home, { recursive: true, force: true }); }
+ }, 120_000);
+});
diff --git a/test/read-meta-diag.test.ts b/test/read-meta-diag.test.ts
new file mode 100644
index 0000000000..e5b355d46d
--- /dev/null
+++ b/test/read-meta-diag.test.ts
@@ -0,0 +1,119 @@
+/**
+ * Self-describing slow-read documents (core/read-heartbeat.ts) and the bounded `gbrain diag` bundle.
+ *
+ * 1. Protects: a slow read's --json document gains elapsed_ms and complete, and complete is false with each field
+ * named when a field was not read (a `*_read` with status not_read), a listing is paged or capped, a budget stopped
+ * the run or a doctor check is unknown for its budget; an error envelope never claims complete; diag returns every
+ * section with its own elapsed_ms and status, says not_read with reason budget for what its budget cut off and
+ * not_applicable for what cannot apply, and never lists search results.
+ * 2. Fails when: completeness is assumed, a cut-off section silently disappears, or diag waits past its budget.
+ */
+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import type { BrainEngine } from '../src/core/engine.ts';
+import { beginSlowRead, endSlowRead, incompleteFields, withReadMeta } from '../src/core/read-heartbeat.ts';
+import { collectDiag, diagSection, DIAG_PROBE_QUERY } from '../src/commands/diag.ts';
+import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';
+
+const quiet = { json: true, writeErr: () => {} };
+
+describe('withReadMeta', () => {
+ test('a document with nothing left out is complete, with the elapsed time since the read began', () => {
+ let clock = 1_000;
+ beginSlowRead('orphan pages', { ...quiet, now: () => clock });
+ clock = 4_500;
+ expect(withReadMeta<Record<string, unknown>>({ total: 3 }, clock)).toEqual({ total: 3, elapsed_ms: 3_500, complete: true });
+ });
+
+ test('each marker of a cut makes it incomplete and is named', () => {
+ beginSlowRead('sync status for source alpha-example', quiet);
+ const doc = withReadMeta({
+ sources: [{ id: 'alpha-example', holds_read: { status: 'not_read', fix: 'gbrain sync status --detail' } }],
+ git_holds: { count: 40, items_complete: false },
+ budget_hit: true,
+ checks: [{ name: 'a', details: { health: 'unknown', reason: 'budget' } }, { name: 'b', status: 'ok' }],
+ }) as Record<string, unknown>;
+ expect(doc.complete).toBe(false);
+ expect(doc.incomplete).toEqual([
+ { field: 'sources[0].holds_read', reason: 'not_read' },
+ { field: 'git_holds.items_complete', reason: 'bounded' },
+ { field: 'budget_hit', reason: 'budget' },
+ { field: 'checks[0].details', reason: 'budget' },
+ ]);
+ });
+
+ test('a paged listing keeps its own complete flag; an error envelope gets elapsed_ms only; an array is unchanged', () => {
+ beginSlowRead('orphan pages', quiet);
+ expect(withReadMeta({ complete: false, next_cursor: 'c1' })).toMatchObject({ complete: false, next_cursor: 'c1' });
+ beginSlowRead('sync status for source alpha-example', quiet);
+ const error = withReadMeta({ error: 'invalid_params', code: 'invalid_params' }) as Record<string, unknown>;
+ expect(typeof error.elapsed_ms).toBe('number');
+ expect('complete' in error).toBe(false);
+ beginSlowRead('anomalous cohorts', quiet);
+ expect(withReadMeta([{ cohort: 'x' }])).toEqual([{ cohort: 'x' }]);
+ });
+
+ test('outside a read nothing is added, and the read ends with its document', () => {
+ endSlowRead();
+ expect(withReadMeta({ total: 1 })).toEqual({ total: 1 });
+ expect(incompleteFields({ a: { b: [{ status: 'not_read' }] } })).toEqual([{ field: 'a.b[0]', reason: 'not_read' }]);
+ });
+});
+
+describe('gbrain diag', () => {
+ let engine: PGLiteEngine;
+ beforeAll(async () => { engine = new PGLiteEngine(); await engine.connect({}); await engine.initSchema(); }, 120_000);
+ afterAll(async () => { await engine.disconnect(); });
+
+ test('every section answers with its own elapsed time and status; what cannot apply says so', async () => {
+ const doc = await collectDiag(engine, { budgetMs: 30_000, query: DIAG_PROBE_QUERY }) as Record<string, Record<string, unknown>>;
+ for (const name of ['gbrain', 'skew', 'sources', 'holds', 'pool', 'search']) {
+ expect(typeof doc[name]!.elapsed_ms).toBe('number');
+ expect(['ok', 'not_read', 'not_applicable', 'error']).toContain(doc[name]!.status as string);
+ }
+ expect(doc.gbrain).toMatchObject({ status: 'ok', engine: 'pglite' });
+ expect(doc.sources).toMatchObject({ status: 'ok', count: 1 });
+ expect(doc.holds).toMatchObject({ status: 'ok', total: 0, by_source: {} });
+ expect(doc.pool).toMatchObject({ status: 'not_applicable' });
+ expect(doc.search).toMatchObject({ status: 'not_applicable' });
+ }, 60_000);
+
+ test('the search section times one search and reports its result count, never its results', async () => {
+ const makeContext = async (e: BrainEngine) => ({ engine: e, config: { engine: 'pglite', embedding_disabled: true }, remote: false, dryRun: false, sourceId: 'default',
+ logger: { info() {}, warn() {}, error() {} } }) as never;
+ await engine.putPage('notes/probe', { type: 'note', title: 'Probe', compiled_truth: 'gbrain diagnostic probe text', timeline: '', frontmatter: {} }, { sourceId: 'default' });
+ const doc = await collectDiag(engine, { budgetMs: 30_000, query: DIAG_PROBE_QUERY, makeContext }) as Record<string, Record<string, unknown>>;
+ expect(doc.search).toMatchObject({ status: 'ok', query: DIAG_PROBE_QUERY });
+ expect(typeof doc.search!.result_count).toBe('number');
+ expect(JSON.stringify(doc.search)).not.toContain('notes/probe');
+ }, 60_000);
+
+ test('a section past its time says not_read with reason budget, and the bundle does not wait for it', async () => {
+ const started = performance.now();
+ const slow = await diagSection(() => new Promise(resolve => setTimeout(() => resolve({ late: true }), 5_000)), 100, performance.now() + 10_000);
+ expect(slow).toMatchObject({ status: 'not_read', reason: 'budget' });
+ expect(performance.now() - started).toBeLessThan(2_000);
+ const spent = await diagSection(async () => ({ never: true }), 1_000, performance.now() - 1);
+ expect(spent).toMatchObject({ status: 'not_read', reason: 'budget', elapsed_ms: 0 });
+ const failed = await diagSection(async () => { throw Object.assign(new Error('relation missing'), { code: '42P01' }); }, 1_000, performance.now() + 1_000);
+ expect(failed).toMatchObject({ status: 'error', code: 'schema_behind' });
+ });
+
+ test.skipIf(!process.env.DATABASE_URL)('on Postgres the pool section reads connections and the sessions the server ended', async () => {
+ const pg = await isolatedPersistencePostgres(process.env.DATABASE_URL!);
+ try {
+ const doc = await collectDiag(pg.engine, { budgetMs: 30_000, query: DIAG_PROBE_QUERY }) as Record<string, Record<string, unknown>>;
+ expect(doc.pool).toMatchObject({ status: 'ok' });
+ expect(doc.pool!.max_connections).toBeGreaterThan(0);
+ expect(doc.pool!.backends).toBeGreaterThanOrEqual(1);
+ expect((doc.pool!.sessions_ended as { status: string }).status).toMatch(/^(ok|not_read)$/);
+ } finally { await pg.close(); }
+ }, 120_000);
+
+ test('a spent bundle budget marks every later section not_read', async () => {
+ const doc = await collectDiag(engine, { budgetMs: 1, query: DIAG_PROBE_QUERY }) as Record<string, Record<string, unknown>>;
+ await Bun.sleep(5);
+ const late = ['holds', 'pool', 'search'].map(name => doc[name]!);
+ expect(late.every(s => s.status === 'not_read' && s.reason === 'budget')).toBe(true);
+ }, 60_000);
+});