Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(doctor): --only connects for engine-only pre-gate checks; patterns deaths attributed (#6303)

time-attackac4df69881ce
diff --git a/docs/architecture/key-files/commands-2.md b/docs/architecture/key-files/commands-2.md
index d4e1c699ed..b9151d2112 100644
--- a/docs/architecture/key-files/commands-2.md
+++ b/docs/architecture/key-files/commands-2.md
@@ -27,7 +27,7 @@ Doctor's embedding-dimension warning treats existing chunks as existing data eve
- `src/commands/doctor/remediate.ts` — the `--remediation-plan` / `--remediate` CLI shell (re-exported from doctor.ts): per-step `command` (`gbrain jobs submit …` for job steps, `gbrain repair <kind> --apply` for repair steps; a repair step with `llm_usd` names its paid chat model spend, and any embedding part, in its fix and plan line), `combinedRemediateCommand` (with repair steps it ends `--expect <plan_hash>`, the same hash `--remediation-plan --json` reports as `plan_hash`), a `Repair kinds whose preview failed` block for `repair_preview_failures` (each `{kind, code, message, why, fix}`; such a kind is not planned, so a plan approved while it failed refuses `preview_changed` once it succeeds), `REMEDIATE_HELP`, `--include-repairs`/`--no-embed`/`--resume` handling, the resume command after budget exhaustion (repeats the recorded cap and consent), `classifyWaveFindings` (cleared / pending / consent_required / operator_required / explicit_kind_required / unsupported, from wave checks run before and after; `details.partial` is pending; an explicit-only kind's preview gets `--source <id>` via `findingSource` when the finding names one source; `--remediation-plan` runs the wave checks too and reports the same classification as `findings`) and `remediationExitStatus` (0 when no repairable finding remains and no step failed; 1 otherwise, on budget exhaustion or when a repair preview failed; 2 when the target is unreachable with no repair step, or a resume is refused), set through `setCliExitVerdict`; 3 when consent is required), set through `setCliExitVerdict`. Consent (agent operator wave C1) lives in `doctor/remediate-consent.ts`: the CLI connects probe-only (no migrations) and computes the plan; when anything would run it calls `requireConsent` (effects `paid`, plus `destructive` with `--include-repairs`, bound to a `plan_hash` over the brain id, job step ids, repair kinds and pending counts, and the parameters, and persisted with the approval). Non-TTY without authorization changes nothing and exits 3 with the consent payload; `--json` never implies consent; `--yes` without `--max-usd` runs under the derived cap (estimate ×1.5, floor $0.25; the default cap when unpriced), and derived-cap exhaustion prints the `--max-usd` resume command. Startup (migrations) completes only after consent. A `--resume` is bound by its checkpoint manifest, not a new plan hash. Pinned by `test/doctor-remediate-consent.test.ts`.
-- `src/commands/doctor/checks/global-maintenance-timeouts.ts` — `global_maintenance_timeouts` (#4578): warns when the last three finished `autopilot-global-maintenance` jobs died at their deadline, or one phase was running in three consecutive job deaths (read from config `autopilot.global_maintenance.progress`). Details carry `code`, `cause`, `fix` (`gbrain dream --phase <name>`, else the deadline config key) and the `docs/guides/troubleshooting.md#global-maintenance-timeouts` anchor. Pinned by `test/autopilot-global-maintenance-resume-4578.test.ts`.
+- `src/commands/doctor/checks/global-maintenance-timeouts.ts` — `global_maintenance_timeouts` (#4578): warns when the last three finished `autopilot-global-maintenance` jobs died at their deadline, or one phase was running in three consecutive job deaths (read from config `autopilot.global_maintenance.progress`), or (#6303) the last three finished dream `patterns` / `synthesize` subagent children (keyed by idempotency prefix) all died at their own `timeout exceeded` while the jobs completed, naming `dream.<phase>.subagent_timeout_ms` (`details.child_timeouts`). Details carry `code`, `cause`, `fix` (`gbrain dream --phase <name>`, else the deadline config key) and the `docs/guides/troubleshooting.md#global-maintenance-timeouts` anchor. Pinned by `test/autopilot-global-maintenance-resume-4578.test.ts`.
- `src/commands/doctor/checks/legacy-job-authority.ts` — `legacy_job_authority` (#5157): the claim gate's population (`UNREVIEWED_LIVE_JOBS_WHERE`), split into authorizable SQL NULL and unsupported rows; terminal keyed SQL NULL rows are reported as `ok`. Live rows `fail` with the filled recovery. `legacyJobAuthorityBannerNote` feeds the banner. The same check counts queued paid jobs by spend basis (`details.queued_spend`) and warns, with the read-only fix `gbrain jobs list --status waiting --json`, when spend-authorized rows wait over 10 minutes while registered workers run (an un-upgraded worker is fenced off them); `legacyDefaultSpendBannerNote` names queued `legacy_default` rows after an upgrade. Tests: `test/doctor-legacy-job-authority.test.ts`, `test/doctor-queued-spend.test.ts`.
- `src/commands/doctor/upgrade-banner.ts` — `postUpgradeRecoveryBanner`: runs the wave checks once and returns one `[AGENT] Relay this to your operator` block (brain, per-finding count and resolution, refined by the check's `bannerHow`, the read-only `gbrain doctor --remediation-plan`, ask before applying), never an applying command; empty for a clean brain. `POST_UPGRADE_NOTES` lets other subsystems add lines (`fenceHoldsBannerNote` among them). Test: `test/post-upgrade-banner.test.ts`.
@@ -40,7 +40,7 @@ Doctor's embedding-dimension warning treats existing chunks as existing data eve
Size ceiling: `scripts/module-size-limits.tsv` (per-change raise history: `git log -p` on that file). The ceiling covers the façade: re-exports, `Check`/`DoctorReport` and report scoring, the `buildChecks` flag parse, `runDoctor`, output rendering and `--locks`; every check block lives in a registry entry under `doctor/checks/*` (refactor wave 1 W4 doctor), remediation in `doctor/remediate.ts`, wave checks in `doctor/wave-checks.ts`.
- `src/commands/doctor/check-fix.ts` (+ `heartbeat.ts`, `checks/harness-wiring.ts`, `checks/agent-contract.ts`) — doctor speaks agent contract v1. `Check` carries optional `fix` (stored `Action`; `computeDoctorReport` renders it for the report's transport via `finalizeCheckFixes`, redacted on http), `fix_unavailable_reason` (`check_errored`, `operator_judgement`, `no_safe_automatic_fix`, `unstructured` for legacy prose-only warns), `severity: 'info'` and `readiness_state`; `schema_version` stays 2 and status stays `ok | warn | fail`. Capabilities that are off by choice or not applicable yet (keyless embeddings and their staleness/vector checks, opt-in takes, no serve running, 0 pages, never-cycled empty or <24 h sources, backup before 25 pages+facts or 7 days via `backupCoachingDue`) report `ok` + `info` with the enable command as `fix`; the report adds `capped_by: ['embeddings_disabled']` and, when the `connection` check is present and not ok, `unknown_scores: ['brain']`. `top_issues[]` gain `action` (the rendered fix) beside the legacy `fix` string. `checkError(name, what, err)` is the one "Could not …" shape (a `gbrain db-repair` fix when the error classifies as DB access). `gbrain doctor --only <check>[,…] [--json]` (`parseOnlyChecks`, `onlyNeedsEngine`, CLI `runDoctorOnly`) runs only the entries that emit those names plus the connection lane, engine-free when every name is a filesystem check, else `connectEngine({ probeOnly: true })`; unknown names exit 2 with the valid list; a requested check that produced nothing reports `info`/`not_applicable` (or `check_errored` after an early stop). It is every doctor fix's `verify`. `harness_wiring` reads the gbrain registration from `~/.claude.json`, Codex `config.toml` and `opencode.json`; under `--only harness_wiring` it smoke-tests it (live serve lock owner → `wired_running`; else spawn the registered argv, 15 s, initialize + tools/list + `recall`; `gbrain_status` replies reported with their reason/fix); it writes nothing. `agent_contract` reads `readAgentContractEvents()` (7 days) and warns on `internal_error`/suggestion-less envelopes, consent refusals, `derived_cap_exhausted` and `json_document_missing`, with the user-only `consent.preapprove.*` command as fix. `throttleDoctorHeartbeat`: piped doctor progress emits at most one heartbeat per 5 s. Tests: `test/doctor-status-set.test.ts`, `test/doctor-harness-smoke.test.ts`, `test/doctor-day-zero.test.ts` (keyless init then doctor: 0 WARN, health ≥ 90), `test/doctor-remote-parity.test.ts` (run_doctor and CLI agree per shared check; run_doctor renders fixes for its transport). `harness_wiring` with no registration drops every detected harness an enabled plugin lane covers (`enabledPluginLanes`): all covered → `ok`, `reason: plugin_lane_enabled` with the plugins, harnesses and a verify hint (plugin lanes are not smoke-tested); partly covered → the missing-registration warning for the uncovered harnesses only. Claude Code detection also honors `CLAUDE_CONFIG_DIR`.
-- `src/commands/doctor/registry.ts` + `src/commands/doctor/context.ts` — the doctor check registry (refactor wave 1, W4 doctor). `DOCTOR_CHECK_REGISTRY` lists 67 `DoctorEntry` records `{ name, emits, run(ctx) -> Promise<Check[] | STOP_DOCTOR> }` in output order; `runDoctorRegistry(ctx)` runs them, returns the checks gathered so far on `STOP_DOCTOR`, and otherwise finishes the DB-checks progress phase. The run is one `withGitListingCache` scope (`src/core/git-visible-files.ts`), so entries that list the same source checkout (frontmatter scan, fence census, slug collisions) share one `git ls-files` per listing and one "not a git repository" verdict per directory (`ls-files`, `discoverGitRoot`, the census HEAD probe; any repository-changing `sync-git.ts` command or `invalidateGitListingCache()` drops the scope's memo: `test/git-listing-memo.serial.test.ts`). Execution groups: filesystem-first entries (the resolver-health entry applies `--fix` before it scans), the no-engine connection lane plus a STOP when `--fast` or no engine, the live connection entry plus a STOP when `getStats` failed, then the DB entries, which take the engine via `connectedEngine(ctx)`. `DoctorContext` carries the parsed flags (`jsonOutput`, `fastMode`, `doFix`, `dryRun`, `scope`, `orphanRatioSourceId`, `args`), `engine`, `dbSource`, `connectError`, `progress`, the skills-dir resolution and the cross-entry values `autoFixReport`, `schemaVersion`, `connectionFailed`, each written by the entry that computes it. Entry modules (one `run*` function per former `buildChecks` block, moved verbatim): `checks/skill-group.ts`, `local-runtime.ts`, `supervisor-health.ts`, `local-audits.ts`, `db-connection.ts` (also `pgbouncerPrepareCheck`, `classifiedConnectionCheck` and the two STOP gates), `schema-health.ts`, `embedding-health.ts`, `graph-health.ts`, `data-integrity.ts`, `content-quality.ts`, `knowledge-health.ts`, `queue-assets.ts`, `sync-search.ts`; `checks/legacy-token-grants.ts` (F3) emits `legacy_token_grant_shape` (info: active tokens still on the JSONB-only grant shape, fix `gbrain auth rescope --migrate-legacy`) and `legacy_token_grant_drift` (warn: per-token drifted axes with the two adopt commands); `checks/grant-new-ops.ts` (D4) emits `grant_new_ops_available` (warn: active clients and tokens whose operation snapshot or stored surface keeps operations their scopes allow out of reach, with proven blockers apart from inferred grant age, per-grant names in details, and an ask_user fix whose rescope argv differs for tokens and clients; `--operations all` is a disclosed choice, never the fix); `checks/upgrade-health.ts` holds `checkUpgradeErrors` / `checkSelfUpgradeHealth` / `upgradeErrorResolved` (re-exported by the façade). To add a check: add an entry in the topic module, place it in `DOCTOR_CHECK_REGISTRY` where its output belongs, and categorize every emitted name in `src/core/doctor-categories.ts`. Tests: `test/doctor-registry.test.ts` (category contract with FAIL/Why/Fix/See, `emits[]` equals the AST walk, STOP positions), `test/doctor-mode-matrix.serial.test.ts` (entries run, STOP point, engine calls and `--fix` mutations per mode), and the W0 goldens `test/doctor-registry-golden.test.ts` (the AST walker follows `runDoctorRegistry` into the registry), `test/doctor-early-stop-golden.serial.test.ts`, `test/doctor-json-golden.test.ts`.
+- `src/commands/doctor/registry.ts` + `src/commands/doctor/context.ts` — the doctor check registry (refactor wave 1, W4 doctor). `DOCTOR_CHECK_REGISTRY` lists 67 `DoctorEntry` records `{ name, emits, run(ctx) -> Promise<Check[] | STOP_DOCTOR> }` in output order; `runDoctorRegistry(ctx)` runs them, returns the checks gathered so far on `STOP_DOCTOR`, and otherwise finishes the DB-checks progress phase. The run is one `withGitListingCache` scope (`src/core/git-visible-files.ts`), so entries that list the same source checkout (frontmatter scan, fence census, slug collisions) share one `git ls-files` per listing and one "not a git repository" verdict per directory (`ls-files`, `discoverGitRoot`, the census HEAD probe; any repository-changing `sync-git.ts` command or `invalidateGitListingCache()` drops the scope's memo: `test/git-listing-memo.serial.test.ts`). Execution groups: filesystem-first entries (the resolver-health entry applies `--fix` before it scans), the no-engine connection lane plus a STOP when `--fast` or no engine, the live connection entry plus a STOP when `getStats` failed, then the DB entries, which take the engine via `connectedEngine(ctx)`. `DoctorContext` carries the parsed flags (`jsonOutput`, `fastMode`, `doFix`, `dryRun`, `scope`, `orphanRatioSourceId`, `args`), `engine`, `dbSource`, `connectError`, `progress`, the skills-dir resolution and the cross-entry values `autoFixReport`, `schemaVersion`, `connectionFailed`, each written by the entry that computes it. Entry modules (one `run*` function per former `buildChecks` block, moved verbatim): `checks/skill-group.ts`, `local-runtime.ts`, `supervisor-health.ts`, `local-audits.ts`, `db-connection.ts` (also `pgbouncerPrepareCheck`, `classifiedConnectionCheck` and the two STOP gates), `schema-health.ts`, `embedding-health.ts`, `graph-health.ts`, `data-integrity.ts`, `content-quality.ts`, `knowledge-health.ts`, `queue-assets.ts`, `sync-search.ts`; `checks/legacy-token-grants.ts` (F3) emits `legacy_token_grant_shape` (info: active tokens still on the JSONB-only grant shape, fix `gbrain auth rescope --migrate-legacy`) and `legacy_token_grant_drift` (warn: per-token drifted axes with the two adopt commands); `checks/grant-new-ops.ts` (D4) emits `grant_new_ops_available` (warn: active clients and tokens whose operation snapshot or stored surface keeps operations their scopes allow out of reach, with proven blockers apart from inferred grant age, per-grant names in details, and an ask_user fix whose rescope argv differs for tokens and clients; `--operations all` is a disclosed choice, never the fix); `checks/upgrade-health.ts` holds `checkUpgradeErrors` / `checkSelfUpgradeHealth` / `upgradeErrorResolved` (re-exported by the façade). A pre-gate entry declares the names it only emits with a connected engine in `engineChecks` (#6303), so `onlyNeedsEngine` connects for `--only` of them; `test/doctor-only-engine-checks.test.ts` is the drift guard. To add a check: add an entry in the topic module, place it in `DOCTOR_CHECK_REGISTRY` where its output belongs, and categorize every emitted name in `src/core/doctor-categories.ts`. Tests: `test/doctor-registry.test.ts` (category contract with FAIL/Why/Fix/See, `emits[]` equals the AST walk, STOP positions), `test/doctor-mode-matrix.serial.test.ts` (entries run, STOP point, engine calls and `--fix` mutations per mode), and the W0 goldens `test/doctor-registry-golden.test.ts` (the AST walker follows `runDoctorRegistry` into the registry), `test/doctor-early-stop-golden.serial.test.ts`, `test/doctor-json-golden.test.ts`.
- `src/commands/doctor/checks/git-convergence.ts` — `git_convergence` (#5063, brain category, after `sync_freshness`): for every non-archived filesystem source root plus `sync.repo_path` (connector sources skipped), `git status --porcelain -z` and `rev-list --left-right --count @{u}...HEAD` against the local upstream ref, never a fetch, each call bounded at 5 s and at most 50 roots. Commits not on the upstream warn after 6 h and fail after 24 h (oldest unpushed commit time); uncommitted changes warn once the oldest changed file is older than 6 h; behind is reported, not judged. Emits nothing when no probed root has an upstream. `bootstrap-checks.ts` `bootstrap_push_health` also warns, instead of `ok`, when a recent successful push leaves the receipt workspace ahead of `origin/<branch>`. `scripts/smoke-test.sh` accepts a configured database URL (`engine status` `db_url_source`) and trusts doctor `embedding_provider` over raw OpenAI/Voyage keys. Tests: `doctor-git-convergence-5063.test.ts`, `bootstrap-doctor-checks.test.ts`, `smoke-test-worker.test.ts`.
- `src/commands/doctor/` — the doctor module directory (the meat behind the `doctor.ts` façade). `checks/` holds the check-function library in bundles grouped by concern (`core-health.ts`, `queue-jobs.ts`, `extraction-sync.ts` (its `sync_freshness` check excludes sources disabled by `isSyncDisabledConfig` and adds `--no-pull` to its sync hint on a managed brain; `content_hash_duplicates` prescribes `GBRAIN_SOURCE=<id> gbrain delete <bare-slug> --force` per wrong-root pair, naming each source when pairs span several, and never a hard purge; `cycle_freshness` in `consolidation-cycle.ts` still monitors their maintenance; its `atom_provenance_drift` check scopes drift to page-bound atoms and splits it into `source_changed` / `source_gone`; atoms with no `source_slug` — transcript-origin `source_path`-only rows, whose hash is over a file and whose page liveness cannot be resolved by slug — are reported as their own `slug_unbound` count and never enter the drift total or the WARN ratio), `graph-embedding.ts`, `search-eval.ts`, `calibration.ts`, `consolidation-cycle.ts`, `pglite-worker.ts`, `routing-federation.ts` (`source_routing_health` exempts zero-page skill-pack sources), `verbs-reflex.ts`, `stale-mentions.ts`, `timeline-history.ts` (`timeline_history`: database-only timeline rows, bounded to 2,000 pages / 10 s per run with a cursor kept in config `doctor.timeline_history.scan:<sources>` so successive runs finish a pass (a clean finished pass stays `ok` until a newer timeline row; `doctor-timeline-history-cursor-5821.test.ts`), exact-or-lower-bound counts, kept non-round-trippable rows informational, repair `gbrain repair timeline`), `derived-visibility.ts` (`derived_visibility`: atoms and synthesized concepts without explicit visibility or looser than their origin, one exact aggregate, repair `gbrain repair visibility`), `engine-fit.ts` — the last carrying `pglite_scale` + the engine-free `db_repair_recurrence` over the db-repair receipts); `schema-pack-checks.ts`, `report-remote.ts`, `bootstrap-checks.ts`, and `skill-checks.ts` are the four tail-cluster modules (schema-pack checks, the remote/thin-client doctor report, bootstrap checks, skill checks). `harness-hook-checks.ts` (`harnessHookCarrierChecks`, called from `bootstrap_harness_health`) reads each receipt-named Claude Code hook carrier read-only: an event wired more than once by this install warns `harness_hook_duplicates` with a consented re-run carrying the install's `--project`/`--no-capture` choices, a lookalike it did not write warns `harness_hook_unowned` (operator judgement), an unparseable carrier warns naming the file, and entries the host stripped of their marker are an `ok` info row; `plugin_lane_collision` iterates `enabledPluginLanes`. `multiSourceDriftCheck` is the one local/remote `multi_source_drift` verdict: on a managed brain (`managedPersistenceEnabled`) its sync advice names `--no-pull` and drops `--include-gitignored`, unmanaged wording is unchanged, and any skipped source keeps it warn/not_verified. `src/core/multi-source-drift.ts` derives a `git-root`-pinned source's slug prefix from its git toplevel (realpaths, empty at the repo root) and skips only a source whose toplevel cannot be resolved (`git_root_skipped`). `graph-health.ts` `graph_coverage`, like onboard's link and timeline coverage, is `ok` (not applicable, with the count) below `MIN_ENTITY_PAGES_FOR_COVERAGE` (5) eligible entity pages. All are re-exported by the façade. Structural guards that pin doctor source text load it through `test/helpers/doctor-source.ts`: `doctorSource()` concatenates the façade plus every `src/commands/doctor/**/*.ts` (façade first, then sorted) so a module move can never take a pinned string out of a guard's sight; `doctorFileSource(rel)` reads one named file for positional/ordering assertions; the helper also feeds the `doctor-source-helper` detector in `scripts/classify-tests.ts`. `facadeExpansion` in `scripts/generate-flag-registry.ts` keeps this directory on the doctor command's flag-scan surface. Two read-only derived-data checks live beside them: `timeline-orphans.ts` (`timeline_orphans`, samples 500 pages for rows an earlier page version produced that the current text no longer does; fix is `gbrain extract timeline --prune-orphans`) and `slug-collisions.ts` (`slug_collisions`, walks each live source checkout with `collectSyncableFiles` and reports paths that map to one slug plus the indexed one; sources without a checkout are skipped). `checks/graph-embedding.ts` `checkJunkEntityHubs` (#6158) splits connector contact pages (frontmatter `google_contact_id` or a connector source kind) into `details.connector_twins` with their main-brain `canonical_twin`, never calls them extractor-minted or offers `junk_hub_exempt`, and carries `fix_unavailable_reason: 'operator_judgement'` while the defer-to-twin policy is open.
diff --git a/docs/guides/troubleshooting.md b/docs/guides/troubleshooting.md
index 1812789bc5..cd6d8eb58a 100644
--- a/docs/guides/troubleshooting.md
+++ b/docs/guides/troubleshooting.md
@@ -381,6 +381,13 @@ at the deadline).
Unset both to return to the default.
3. Confirm with `gbrain doctor`: `global_maintenance_timeouts` is `ok` after the
next job finishes within its deadline.
+
+Doctor also warns when the last three dream `patterns` or `synthesize`
+subagent children died at their own subagent timeout, even though each
+maintenance job completed (the phase records a partial result). Raise that
+child's timeout with `gbrain config set dream.<phase>.subagent_timeout_ms <ms>`;
+`gbrain dream --phase <phase>` reruns it and spends model tokens, so ask the
+user first. The warning clears once that phase's next child completes.
## auto_chronicle has no effect
**Say to your agent:** *"Why aren't my meetings showing up as timeline events?"*
diff --git a/src/commands/doctor/checks/global-maintenance-timeouts.ts b/src/commands/doctor/checks/global-maintenance-timeouts.ts
index ce8ccb6fa4..a0d98d6a48 100644
--- a/src/commands/doctor/checks/global-maintenance-timeouts.ts
+++ b/src/commands/doctor/checks/global-maintenance-timeouts.ts
@@ -4,7 +4,9 @@
* its last three finished jobs were all timeout deaths, or when one phase was
* running in three consecutive job deaths (the handler then skips it each
* pass). The fix runs the phase alone, without the job deadline, and the
- * deadline itself is configurable.
+ * deadline itself is configurable. #6303: a dream patterns or synthesize child
+ * dies at its own subagent timeout while the maintenance job completes, so the
+ * check also warns when a phase's last three finished children all died that way.
*/
import type { BrainEngine } from '../../../core/engine.ts';
import type { Check } from '../../doctor.ts';
@@ -26,23 +28,45 @@ export async function globalMaintenanceTimeoutsCheck(engine: BrainEngine): Promi
const phases = Object.entries(progress.timeouts ?? {})
.filter(([, t]) => t.count >= DEATHS)
.map(([phase, t]) => ({ phase, consecutive_deaths: t.count, last_at: t.last_at }));
- const phase = phases[0]?.phase ?? progress.running_phase ?? progress.next_phase;
- if (!timeoutDeaths && phases.length === 0) {
+ const children = await engine.executeRaw<{ phase: 'patterns' | 'synthesize'; deaths: number; last_at: string | null }>(
+ `SELECT phase, count(*)::int AS deaths, max(finished_at)::text AS last_at FROM (
+ SELECT phase, status, error_text, finished_at,
+ row_number() OVER (PARTITION BY phase ORDER BY finished_at DESC NULLS LAST, id DESC) AS n
+ FROM (SELECT id, status, error_text, finished_at,
+ CASE WHEN key LIKE 'dream:patterns:%' THEN 'patterns' ELSE 'synthesize' END AS phase
+ FROM (SELECT id, status, error_text, finished_at,
+ COALESCE(idempotency_key, data->>'__released_idempotency_key') AS key
+ FROM minion_jobs
+ WHERE name = 'subagent' AND status IN ('completed', 'failed', 'dead', 'cancelled')) keyed
+ WHERE key LIKE 'dream:patterns:%' OR key LIKE 'dream:synth%') phased
+ ) recent
+ WHERE n <= ${DEATHS}
+ GROUP BY phase
+ HAVING count(*) = ${DEATHS} AND bool_and(status = 'dead' AND error_text ~ 'timeout exceeded')`);
+ const childTimeouts = children.map(c => ({ phase: c.phase, consecutive_deaths: Number(c.deaths), last_at: c.last_at }));
+ const phase = phases[0]?.phase ?? childTimeouts[0]?.phase ?? progress.running_phase ?? progress.next_phase;
+ if (!timeoutDeaths && phases.length === 0 && childTimeouts.length === 0) {
return { name: 'global_maintenance_timeouts', status: 'ok', message: 'Brain-wide maintenance jobs are finishing within their deadline.' };
}
const fix = phase
? { kind: 'run_command', argv: ['gbrain', 'dream', '--phase', phase] }
: { kind: 'run_command', argv: ['gbrain', 'config', 'set', 'autopilot.global_maintenance_timeout_ms', '3600000'] };
- const cause = phases.length > 0
- ? `phase ${phases.map(p => p.phase).join(', ')} was running in ${DEATHS}+ consecutive autopilot-global-maintenance job deaths and is skipped each pass`
- : `the last ${DEATHS} autopilot-global-maintenance jobs (${recent.map(j => `#${j.id}`).join(', ')}) died at their deadline`;
+ const causes = [
+ ...(phases.length > 0 ? [`phase ${phases.map(p => p.phase).join(', ')} was running in ${DEATHS}+ consecutive autopilot-global-maintenance job deaths and is skipped each pass`] : []),
+ ...(timeoutDeaths && phases.length === 0 ? [`the last ${DEATHS} autopilot-global-maintenance jobs (${recent.map(j => `#${j.id}`).join(', ')}) died at their deadline`] : []),
+ ...childTimeouts.map(c => `the last ${DEATHS} dream ${c.phase} subagent children died at their subagent timeout`),
+ ];
+ const cause = causes.join('; ');
+ const childAdvice = childTimeouts.map(c =>
+ `Raise the ${c.phase} child timeout with: gbrain config set dream.${c.phase}.subagent_timeout_ms <ms> (gbrain dream --phase ${c.phase} reruns it and is paid). `).join('');
return {
name: 'global_maintenance_timeouts',
status: 'warn',
message: `Brain-wide maintenance is not finishing: ${cause}. `
- + (phase ? `Run the phase without the job deadline: gbrain dream --phase ${phase}. ` : '')
+ + (phase && childTimeouts.length === 0 ? `Run the phase without the job deadline: gbrain dream --phase ${phase}. ` : '')
+ + childAdvice
+ `Raise the job deadline with: gbrain config set autopilot.global_maintenance_timeout_ms <ms> (or GBRAIN_GLOBAL_MAINTENANCE_TIMEOUT_MS). See ${DOCS}.`,
- details: { code: 'global_maintenance_timeouts', cause, fix, docs: DOCS, recent_job_ids: recent.map(j => j.id), phases,
+ details: { code: 'global_maintenance_timeouts', cause, fix, docs: DOCS, recent_job_ids: recent.map(j => j.id), phases, child_timeouts: childTimeouts,
resume_phase: progress.next_phase ?? null },
};
} catch (error) {
diff --git a/src/commands/doctor/checks/local-audits.ts b/src/commands/doctor/checks/local-audits.ts
index 7b9207cf5c..870015f98d 100644
--- a/src/commands/doctor/checks/local-audits.ts
+++ b/src/commands/doctor/checks/local-audits.ts
@@ -364,6 +364,7 @@ export const extractionBacklogsEntry: DoctorEntry = {
'progressive_batch_audit_health',
'conversation_parser_probe_health',
],
+ engineChecks: ['malformed_path_pages', 'extract_health', 'conversation_facts_backlog', 'extract_atoms_backlog', 'atom_provenance_drift', 'conversation_format_coverage'],
run: runExtractionBacklogs,
};
@@ -596,5 +597,6 @@ async function runDefaultSourcePath(ctx: DoctorContext): Promise<Check[]> {
export const defaultSourcePathEntry: DoctorEntry = {
name: 'default_source_local_path',
emits: ['default_source_local_path', 'fts_reindex_incomplete', 'multi_source_drift', 'orphan_clones'],
+ engineChecks: ['default_source_local_path', 'fts_reindex_incomplete', 'multi_source_drift'],
run: runDefaultSourcePath,
};
diff --git a/src/commands/doctor/checks/local-runtime.ts b/src/commands/doctor/checks/local-runtime.ts
index 681ee3a21e..23cc715f97 100644
--- a/src/commands/doctor/checks/local-runtime.ts
+++ b/src/commands/doctor/checks/local-runtime.ts
@@ -104,6 +104,7 @@ async function runConnectors(ctx: DoctorContext): Promise<Check[]> {
export const connectorsEntry: DoctorEntry = {
name: 'connectors',
emits: ['connectors', 'dream_paid_loop'],
+ engineChecks: ['connectors', 'dream_paid_loop'],
run: runConnectors,
};
diff --git a/src/commands/doctor/checks/queue-jobs.ts b/src/commands/doctor/checks/queue-jobs.ts
index ae7edb4c20..67c9b99f2a 100644
--- a/src/commands/doctor/checks/queue-jobs.ts
+++ b/src/commands/doctor/checks/queue-jobs.ts
@@ -87,15 +87,20 @@ export async function computeQueueHealthCheck(
);
const rssKillCount = Number(rssKillRows[0]?.cnt ?? 0);
- const promptTooLongRows: Array<{ cnt: number }> = await engine.executeRaw(
- `SELECT count(*)::int AS cnt
- FROM minion_jobs
- WHERE name = 'subagent'
- AND status = 'dead'
- AND finished_at > now() - interval '24 hours'
- AND error_text LIKE 'prompt_too_long:%'`,
+ const promptTooLongRows: Array<{ phase: 'patterns' | 'synthesize' | 'other'; cnt: number }> = await engine.executeRaw(
+ `SELECT CASE WHEN key LIKE 'dream:patterns:%' THEN 'patterns'
+ WHEN key LIKE 'dream:synth%' THEN 'synthesize'
+ ELSE 'other' END AS phase,
+ count(*)::int AS cnt
+ FROM (SELECT COALESCE(idempotency_key, data->>'__released_idempotency_key') AS key
+ FROM minion_jobs
+ WHERE name = 'subagent'
+ AND status = 'dead'
+ AND finished_at > now() - interval '24 hours'
+ AND error_text LIKE 'prompt_too_long:%') dead
+ GROUP BY 1`,
);
- const promptTooLongCount = Number(promptTooLongRows[0]?.cnt ?? 0);
+ const promptTooLong = Object.fromEntries(promptTooLongRows.map(r => [r.phase, Number(r.cnt)]));
const oldWaitingHours = opts.oldWaitingHours
?? _resolveEnvNumber('GBRAIN_QUEUE_NO_WORKER_WARN_HOURS', 1);
@@ -253,15 +258,28 @@ export async function computeQueueHealthCheck(
);
}
} catch { /* best-effort — divergence probes never break doctor */ }
- if (promptTooLongCount > 0) {
+ if (promptTooLong.patterns) {
problems.push(
- `${promptTooLongCount} subagent job(s) dead-lettered with prompt_too_long in last 24h. ` +
+ `${promptTooLong.patterns} dream patterns subagent job(s) dead-lettered with prompt_too_long in last 24h. ` +
+ `The reflections batch exceeded the patterns model's input context. ` +
+ `Fix: set a larger-context \`models.dream.patterns\`, or shorten \`dream.patterns.lookback_days\`.`
+ );
+ }
+ if (promptTooLong.synthesize) {
+ problems.push(
+ `${promptTooLong.synthesize} dream synthesize subagent job(s) dead-lettered with prompt_too_long in last 24h. ` +
`Dream/synthesize transcripts exceeded the model's input context. ` +
`Fix: \`gbrain dream --phase synthesize --dry-run --json\` to identify fat transcripts; ` +
`set \`dream.synthesize.max_prompt_tokens\` to bound the per-chunk budget, or use a ` +
`larger-context model (Opus 4.7 = 1M tokens vs Sonnet 4.6 = 200K).`
);
}
+ if (promptTooLong.other) {
+ problems.push(
+ `${promptTooLong.other} subagent job(s) dead-lettered with prompt_too_long in last 24h. ` +
+ `The prompt exceeded the model's input context; use a larger-context model or a shorter prompt.`
+ );
+ }
if (problems.length === 0) {
return {
diff --git a/src/commands/doctor/checks/skill-group.ts b/src/commands/doctor/checks/skill-group.ts
index 13d1d291b6..554b39302d 100644
--- a/src/commands/doctor/checks/skill-group.ts
+++ b/src/commands/doctor/checks/skill-group.ts
@@ -121,6 +121,7 @@ async function runRetrievalReflex(ctx: DoctorContext): Promise<Check[]> {
export const retrievalReflexEntry: DoctorEntry = {
name: 'retrieval_reflex_health',
emits: ['retrieval_reflex_health', 'volunteer_channels', 'memory_verbs_usage'],
+ engineChecks: ['volunteer_channels'],
run: runRetrievalReflex,
};
diff --git a/src/commands/doctor/context.ts b/src/commands/doctor/context.ts
index 9786fa83fc..38e0661faf 100644
--- a/src/commands/doctor/context.ts
+++ b/src/commands/doctor/context.ts
@@ -23,6 +23,12 @@ export interface DoctorEntry {
name: string;
/** Every check name `run` can push, categorized in src/core/doctor-categories.ts. */
emits: readonly string[];
+ /**
+ * Names a pre-gate entry only emits with a connected engine (#6303). `--only`
+ * of one of them connects the engine; test/doctor-only-engine-checks.test.ts
+ * fails when an engine-only name is not declared.
+ */
+ engineChecks?: readonly string[];
run(ctx: DoctorContext): Promise<Check[] | typeof STOP_DOCTOR>;
}
diff --git a/src/commands/doctor/registry.ts b/src/commands/doctor/registry.ts
index 596da068ef..49d1241b5c 100644
--- a/src/commands/doctor/registry.ts
+++ b/src/commands/doctor/registry.ts
@@ -210,10 +210,10 @@ export function parseOnlyChecks(args: readonly string[]): Set<string> | null {
return new Set(raw.flatMap((r) => r.split(',')).map((n) => n.trim()).filter(Boolean));
}
-/** True when any requested check is a DB check (ordered after the DB-checks early stop). */
+/** True when any requested check is a DB check (after the DB-checks early stop) or a declared engine check of a pre-gate entry. */
export function onlyNeedsEngine(only: ReadonlySet<string>): boolean {
const gate = DOCTOR_CHECK_REGISTRY.indexOf(dbChecksGateEntry);
- return DOCTOR_CHECK_REGISTRY.some((e, i) => i > gate && e.emits.some((n) => only.has(n)));
+ return DOCTOR_CHECK_REGISTRY.some((e, i) => (i > gate ? e.emits : e.engineChecks ?? []).some((n) => only.has(n)));
}
function selected(entry: DoctorEntry, only: ReadonlySet<string> | null | undefined): boolean {
diff --git a/test/autopilot-global-maintenance-resume-4578.test.ts b/test/autopilot-global-maintenance-resume-4578.test.ts
index dce2f6573f..ace92c8151 100644
--- a/test/autopilot-global-maintenance-resume-4578.test.ts
+++ b/test/autopilot-global-maintenance-resume-4578.test.ts
@@ -122,4 +122,37 @@ describe('global_maintenance_timeouts doctor check (#4578)', () => {
await engine.executeRaw(`UPDATE minion_jobs SET status = 'completed', finished_at = now() + interval '1 hour' WHERE id = $1`, [job.id]);
expect((await globalMaintenanceTimeoutsCheck(engine)).status).toBe('ok');
});
+ test('#6303: three dead patterns children at their own timeout warn while the jobs complete', async () => {
+ const queue = new MinionQueue(engine);
+ const job = await queue.add('autopilot-global-maintenance', {}, { idempotency_key: 'completed-partial' });
+ await engine.executeRaw(`UPDATE minion_jobs SET status = 'completed', finished_at = now() WHERE id = $1`, [job.id]);
+ const child = async (i: number, error: string, key = `dream:patterns:k${i}`) => {
+ const sub = await queue.add('subagent', {}, { idempotency_key: key }, { allowProtectedSubmit: true });
+ await engine.executeRaw(`UPDATE minion_jobs SET status = 'dead', error_text = $2, finished_at = now() + ($1 || ' seconds')::interval WHERE id = $3`,
+ [String(i), error, sub.id]);
+ };
+ await child(0, 'timeout exceeded');
+ await child(1, 'wall-clock timeout exceeded');
+ expect((await globalMaintenanceTimeoutsCheck(engine)).status).toBe('ok');
+ await child(2, 'timeout exceeded');
+ await child(3, 'prompt_too_long: 1', 'dream:synth-v2:default:filename:a.md:0123456789abcdef');
+ const check = await globalMaintenanceTimeoutsCheck(engine);
+ expect(check.status).toBe('warn');
+ expect(check.message).toContain('dream.patterns.subagent_timeout_ms');
+ expect(check.message).toContain('autopilot.global_maintenance_timeout_ms');
+ expect(check.message).toContain('gbrain dream --phase patterns');
+ expect(check.message).toContain('paid');
+ expect(check.details).toMatchObject({ child_timeouts: [{ phase: 'patterns', consecutive_deaths: 3 }] });
+ expect(check.message).not.toContain('synthesize');
+ });
+
+ test('#6303: a completed patterns child after timeouts clears the child warning', async () => {
+ const queue = new MinionQueue(engine);
+ for (let i = 0; i < 4; i++) {
+ const sub = await queue.add('subagent', {}, { idempotency_key: `dream:patterns:c${i}` }, { allowProtectedSubmit: true });
+ await engine.executeRaw(`UPDATE minion_jobs SET status = $4, error_text = $2, finished_at = now() + ($1 || ' seconds')::interval WHERE id = $3`,
+ [String(i), i < 3 ? 'timeout exceeded' : null, sub.id, i < 3 ? 'dead' : 'completed']);
+ }
+ expect((await globalMaintenanceTimeoutsCheck(engine)).status).toBe('ok');
+ });
});
diff --git a/test/doctor-only-engine-checks.test.ts b/test/doctor-only-engine-checks.test.ts
new file mode 100644
index 0000000000..bec4b2cd5b
--- /dev/null
+++ b/test/doctor-only-engine-checks.test.ts
@@ -0,0 +1,76 @@
+/**
+ * #6303: `gbrain doctor --only <check>` for a check that a pre-gate entry only
+ * emits with an engine must connect the engine. `onlyNeedsEngine` used to look
+ * only past the DB-checks gate, so `--only dream_paid_loop` ran engine-free and
+ * reported "Could not connect" / "Not run". Pre-gate entries now declare those
+ * names in `engineChecks`; the drift guard below fails when a pre-gate entry
+ * emits a name only with an engine and does not declare it.
+ */
+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
+import { mkdtempSync, rmSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { buildChecks } from '../src/commands/doctor.ts';
+import { DOCTOR_CHECK_REGISTRY, onlyNeedsEngine } from '../src/commands/doctor/registry.ts';
+import { dbChecksGateEntry } from '../src/commands/doctor/checks/db-connection.ts';
+import { withEnv } from './helpers/with-env.ts';
+
+let engine: PGLiteEngine;
+let home: string;
+
+beforeAll(async () => {
+ home = mkdtempSync(join(tmpdir(), 'gbrain-doctor-only-'));
+ engine = new PGLiteEngine();
+ await engine.connect({});
+ await engine.initSchema();
+});
+
+afterAll(async () => {
+ await engine.disconnect();
+ rmSync(home, { recursive: true, force: true });
+});
+
+const gate = DOCTOR_CHECK_REGISTRY.indexOf(dbChecksGateEntry);
+const preGate = DOCTOR_CHECK_REGISTRY.slice(0, gate);
+const postGate = new Set(DOCTOR_CHECK_REGISTRY.slice(gate + 1).flatMap((e) => e.emits));
+
+describe('doctor --only engine need (#6303)', () => {
+ test('engine-reading pre-gate checks need the engine', () => {
+ for (const name of ['dream_paid_loop', 'connectors', 'extract_atoms_backlog', 'default_source_local_path', 'volunteer_channels']) {
+ expect(`${name}:${onlyNeedsEngine(new Set([name]))}`).toBe(`${name}:true`);
+ }
+ expect(onlyNeedsEngine(new Set(['pglite_data_dir', 'supervisor', 'harness_wiring']))).toBe(false);
+ });
+
+ test('declared engine checks are names the entry emits', () => {
+ for (const entry of DOCTOR_CHECK_REGISTRY) {
+ for (const name of entry.engineChecks ?? []) expect(`${entry.name}:${entry.emits.includes(name)}`).toBe(`${entry.name}:true`);
+ }
+ });
+
+ test('drift guard: every name a pre-gate entry emits only with an engine is declared', async () => {
+ const names = preGate.flatMap((e) => e.emits).filter((n) => n !== 'connection');
+ const args = ['--only', names.join(','), '--json'];
+ const real = (checks: { name: string; message?: string }[]) => new Set(checks
+ .filter((c) => !c.message?.startsWith('No finding') && !c.message?.startsWith('Not run'))
+ .map((c) => c.name));
+ await withEnv({ GBRAIN_HOME: home }, async () => {
+ const without = real(await buildChecks(null, args));
+ const withEngine = real(await buildChecks(engine, args));
+ const undeclared = [...withEngine]
+ .filter((n) => !without.has(n) && !postGate.has(n))
+ .filter((n) => !onlyNeedsEngine(new Set([n])));
+ expect(undeclared).toEqual([]);
+ });
+ });
+
+ test('--only dream_paid_loop with an engine returns the real check', async () => {
+ await withEnv({ GBRAIN_HOME: home }, async () => {
+ const checks = await buildChecks(engine, ['--only', 'dream_paid_loop', '--json']);
+ const check = checks.find((c) => c.name === 'dream_paid_loop')!;
+ expect(check.status).toBe('ok');
+ expect(check.message).not.toMatch(/^Not run|^No finding/);
+ });
+ });
+});
diff --git a/test/doctor-queue-divergence.test.ts b/test/doctor-queue-divergence.test.ts
index 3d49cc41e1..b22edb8fd7 100644
--- a/test/doctor-queue-divergence.test.ts
+++ b/test/doctor-queue-divergence.test.ts
@@ -139,3 +139,33 @@ describe('malformed_path_pages discovery check (buildChecks seam)', () => {
expect(checks.find((c) => c.name === 'malformed_path_pages')).toBeUndefined();
});
});
+
+describe('queue_health — prompt_too_long deaths are attributed per dream phase (#6303)', () => {
+ async function seedDead(key: string | null): Promise<void> {
+ await base.executeRaw(
+ `INSERT INTO minion_jobs (submission_authority, name, queue, status, error_text, idempotency_key, created_at, updated_at, finished_at)
+ VALUES ('{"version":1,"kind":"application"}'::jsonb, 'subagent', 'default', 'dead', 'prompt_too_long: 300000 tokens', $1, now(), now(), now())`,
+ [key],
+ );
+ }
+
+ it('patterns deaths get patterns advice, never the synthesize budget knob', async () => {
+ await seedDead('dream:patterns:abc');
+ await seedDead('dream:patterns:def');
+ const check = await computeQueueHealthCheck(pgLike);
+ expect(check.message).toContain('2 dream patterns subagent job(s)');
+ expect(check.message).toContain('models.dream.patterns');
+ expect(check.message).toContain('dream.patterns.lookback_days');
+ expect(check.message).not.toContain('dream.synthesize.max_prompt_tokens');
+ });
+
+ it('synthesize and other deaths keep their own lines', async () => {
+ await seedDead('dream:synth-v2:default:filename:a.md:0123456789abcdef');
+ await seedDead(null);
+ const check = await computeQueueHealthCheck(pgLike);
+ expect(check.message).toContain('1 dream synthesize subagent job(s)');
+ expect(check.message).toContain('dream.synthesize.max_prompt_tokens');
+ expect(check.message).toContain('1 subagent job(s) dead-lettered with prompt_too_long');
+ expect(check.message).not.toContain('models.dream.patterns');
+ });
+});