Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(doctor): bound the home-dir entry's local probes and reserve the DB lane's share of the budget (#8979)

garrytan5c92886085f6
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 4279bd2458..49408fdedd 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -10,6 +10,17 @@ credits are retained; no result has been reassigned to another provider. Origina
identifiers and attribution are available in the pre-removal Git revision
`6040075c6cb95be5881cc2e1b76ef7d71f4e5d29` (retained on 2026-09-23).
+## [Unreleased]
+
+**`gbrain doctor` now ends on its `--budget-ms` deadline when a local probe hangs, and the cheap incident checks keep their share of the budget.** The `home_dir_in_worktree` entry, which runs before the connection checks, ran `npm root -g`, `which -a gbrain` and `crontab -l` synchronously, with 5-second limits on the first and last and none on `which`. While one of them hung, nothing else in the process could run, the deadline included. So a 2500 ms run took about 5100 ms, and every later check, `links_extraction_lag` and `persistence_capacity` included, came back unknown with `elapsed_ms: 0`. Those probes now run asynchronously and are killed with SIGKILL at the entry's deadline (5 s at most, less the 250 ms report reserve), so none of them outlives the run. The entries before the connection checks may use at most half of the time left when the check run starts, so the ops sections and the cheap incident checks keep the other half. `--only`, `--fast` and a run with no database connection still give those entries the whole budget. This was the flaky `#6803 doctor deadlines (postgres)` E2E case (#8979). It failed on every backend-matrix job that ran on the 20261026.1 runner image, where a probe ran into its 5 s limit.
+
+### Itemized changes
+
+- `src/commands/doctor/checks/local-audits.ts`: `localProbe` runs a local command with `execFile`, bounded by `scanDeadline` (5 s, clipped to the entry deadline read when the entry starts) and killed with SIGKILL at that bound. `npm_squat` (`npm root -g`, `which -a gbrain`) and `cron_gbrain_home` (`crontab -l`) use it, and a probe that fails or times out reads as absent, as before.
+- `src/commands/doctor/checks/cron-gbrain-home.ts`: the synchronous `readCrontab` is gone.
+- `src/commands/doctor/registry.ts`: with an engine and without `--fast` or `--only`, an entry before the connection lane runs to the overall deadline less half the time left when the check run starts.
+- Tests: `test/doctor-entry-deadline-6803.test.ts`. One test puts stand-ins for `npm`, `crontab` and `which` on PATH. They ignore SIGTERM and sleep 6 s, yet a 1000 ms run finishes within its budget and none of them is still running afterwards. In the second (PGLite and Postgres), an entry before the connection lane that outlives a 2000 ms budget still leaves `links_extraction_lag` and `persistence_capacity` reporting. A third checks that under `--fast` such an entry keeps the whole budget. The first two fail on the previous code.
+
## [0.60.621.0] - 2026-11-09
**A page a member-bound credential creates in the `default` source is now readable only by that member.** A token bound with `gbrain auth rescope --member <id>` and no `--sources` writes to `default`, the source every credential without a source grant reads, and so does a token granted `--sources default` and an OAuth client left at its registration default. Its `put_page` (and every page write through the same path) used to create an ordinary page there, which another member and an unbound token read through `get_page`, `search`, `query`, `recall` and `list_pages`; its `remember` facts were already kept on the member's own page. A page such a credential creates is now written with `readable_by: [member:<id>]`, in the database row on a repo-less brain and in the file on a repo brain; rewriting it without `readable_by` keeps the stored readers, and the member widens it by naming readers. An edit to an existing page that names no readers leaves it shared, and `POST /ingest`, which cannot keep a page to a member, refuses such a credential with `permission_denied`. Member-bound credentials whose write source is another source (the documented `--sources private-<member>,default` shape) and unbound credentials write exactly as before, apart from slugs a member now creates. Pages derived from such a page (extracted atoms, chronicle events, `derived_from` pages, and a synthesized concept that uses it) follow the rule for pages with readers and are readable by no remote caller, the writer included. A page that teammates should read, such as a shared `people/` or `companies/` entity page or a page in a folder a rule already scopes to a group, names its readers when it is created; otherwise the first member to create a slug keeps it, and every other remote credential writing that slug (another member, an unbound token, a shared agent) gets `page_not_found`. The operator widens such a page from the brain host by adding `readable_by` to it (the local CLI is not member-scoped). A member-bound `put_page` over a page deleted within the last 72 hours is a create, so it is kept to the member too. Pages written before this release keep whatever readers they have: `gbrain access who-can-read <slug>` shows who reads one.
diff --git a/docs/architecture/key-files/commands-2-continued.md b/docs/architecture/key-files/commands-2-continued.md
index b2c2321d0c..dbdab4f430 100644
--- a/docs/architecture/key-files/commands-2-continued.md
+++ b/docs/architecture/key-files/commands-2-continued.md
@@ -33,7 +33,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
- `src/commands/doctor/checks/keyword-plan.ts` — `keyword_plan` (#6495, OPS, wave check with operator resolution; the keyword-side twin of `vector_plan` in commands-2.md). Postgres only: reads the commonest lexeme the planner knows for `content_chunks.search_vector` (`pg_stats.most_common_elems` with its frequency), EXPLAINs (no ANALYZE) the strict page-count statement for it (`buildKeywordCountStatement`, the builder the engine uses) and times the engine's own bounded `countKeywordPages(term, { timeoutMs: 2000 })`; warns `canary_timed_out` when that count hits its bound and `canary_slow` when it takes more than half of `search.keyword_statement_timeout_ms`, naming the knob with its range (1000-60000), the fail-open to the vector arm (`keyword_arm_failed`), that a longer bound buys time and not a cheaper statement, that one canary term is not workload coverage, and that a timed-out count is never "no matches". Skipped on PGLite, below 10,000 chunks (`pg_class.reltuples`) and without planner statistics (it names `ANALYZE content_chunks`); a failing probe reports unknown health. `engineKeywordPlanProbe(engine)` is the database side; `keywordPlanCheck(engine, probe?)` takes a fake for tests. Tested in `test/doctor-keyword-plan-6495.test.ts` (fake probe for every outcome; with DATABASE_URL the real probe on a seeded brain and a lock-forced timeout).
- `src/commands/doctor/checks/image-embedding-coverage.ts` — `image_embedding_coverage` (#6529, brain category, after `image_assets`). Counts live image pages (`page_kind = 'image'`), those with no `embedding_image` chunk, those with a NULL `source_path`, and the `managed_image_sync_unsupported` holds per source, and reads `isMultimodalEnabled()`. Ok when the brain has no image pages, when every image page has an image vector and a `source_path` and nothing is held, or when multimodal embedding is off (the counts are then informational: image search is not expected to work). On a multimodal install it warns with the counts (text coverage counts those pages as embedded while image search does not see them) and names `gbrain embed --stale --images` and `gbrain sync --no-pull --source <id>` for the holds. Read-only; no paid call. Test: `test/doctor-image-embedding-coverage.test.ts`.
- `src/commands/doctor/checks/provider-consent.ts` — `provider_consent` (OPS, engine-free filesystem lane right after `embedding_key_source`; not in `doctorReportRemote`): the provider-use decision `gbrain setup` recorded for this install (`localSetupRecords` in `src/core/setup/local-receipts.ts`). A decline (any live receipt; opt-outs win) is `ok` + info `disabled_by_choice`, "skipped by consent", naming the provider key variables present (names only) and carrying `providerConsentFix`: `gbrain setup <harness> --providers` (+ `--name`/`--scope project`), actor `user`, consent `paid`+`egress`, so `next: tell_user_to_run`. Accepted is plain `ok`; no receipt is info `not_applicable`. The same fix rides `embedding_provider`'s `--probe` skip (`checks/embedding-health.ts`), and `probe-consent.ts` authorizes nothing when a decline is recorded. Reads files only; sends nothing. Pinned by `test/doctor-provider-consent.serial.test.ts` (request counter: zero outbound under a decline, controls prove discovery and the probe are seen otherwise).
-- `src/commands/doctor/budget.ts` + `checks/ops-sections.ts` + `checks/orphan-estimate.ts` — doctor tiers and budgets (#6696 B1). `parseDoctorTier` (`--tier ops|quick|standard|deep`, a bad value is `invalid_params`), `parseBudgetMs` (`--budget-ms`, default 4000 under ops, 10000 under quick, none otherwise) and `startDoctorDeadline` build the `DoctorDeadline` the CLI starts before connecting. `runDoctorRegistry` runs the entries tagged `tier: 'ops'` (persistence capacity, terminal failures, managed sync movement, persistence compaction, serve build drift, schema-pack consistency, embedding state) right after the connection lane; under `--tier ops` it runs only those (each `executeRaw` gets the absolute `deadlineAt`, so `SET LOCAL statement_timeout` is the time left after the pool wait: `postgres-engine/bounded-statement.ts`), reports an entry marked `opsPglite: 'not_applicable'` as an `ok` info row on PGLite, and stays complete. Every other tier bounds each entry by `doctor.entry_budget_ms` (default 15000). An entry past its budget, an unknown reported after the overall deadline, or a connect the deadline ended becomes `budgetUnknownCheck` (warn, `details.health: 'unknown'`, `reason: 'budget'`, `exact: false`, a rerun-alone fix), never a clear result; every check carries `elapsed_ms`, and the report adds `tier`/`complete`/`unknown_sections`/`elapsed_ms`/`budget_ms` only when `--tier` or `--budget-ms` was given (`doctorRunSummary`). `doctorHealth(ctx)` memoizes `getHealth` for one run. `orphan_ratio` estimates from a `TABLESAMPLE SYSTEM` sample above `doctor.orphan_ratio.full_scan_max_pages` (default 50000) unless `--tier deep`. Capacity and compaction freshness live in `checks/ops-sections.ts`. On every tier each entry runs inside its own `StatementDeadline` (`src/core/statement-deadline.ts`: an AsyncLocalStorage scope plus `deadlineBoundEngine`, one stable Proxy per real engine that refuses any engine call past the deadline, carries the deadline to the server on Postgres `executeRaw`, and marks the scope expired on a cancel even when the check catches it; `engineCacheKey` maps the wrapper to the real engine for engine-keyed caches; PGLite gets only the pre-statement refusal). The budget-config read is one bounded statement (2 s). `CHEAP_INCIDENT_CHECKS` (by check name: persistence capacity, managed sync movement, `text_projection_readiness`, `partial_embedding`, `links_extraction_lag`) run right after the ops sections, before any full scan. `scanDeadline` clips the frontmatter walk and the fence census to the entry deadline less 250 ms, so they report partial results. `--only` with an explicit `--budget-ms` gives the selected entries the whole overall budget; `budgetUnknownCheck` names the limiting budget (`details.limit`: `entry` or `overall`) and fixes with `--only <check> --budget-ms N` (N ten times that budget; actor agent while N fits `AGENT_TOOL_LIMIT_MS` less 10 s, else actor user). `--budget-ms 0` is no overall budget. `default-budget.ts`: a plain non-interactive CLI `doctor --json` (stderr not a TTY; no `--budget-ms`, `--tier`, `--fix`, `--remediate` or `--remediation-plan`) caps its check run at `doctor.default_budget_ms` (file plane, default 90000, 0 off), started by `startDeferredDeadline` when the registry starts (connect and migrations are outside it), with one stderr line; the report then carries the tier fields. `capacity-memo.ts` `doctorCapacityForecast`: one forecast per run (shared by `persistence_capacity` and `persistence_request_growth`) read under the run's overall deadline and dropped from the memo on a deadline failure, which makes the waiting check unknown instead of a counter-only verdict. `persistence_session_timeouts` reads `SHOW statement_timeout` outside the entry deadline. Tests: `test/doctor-tier-6696.test.ts`, `test/doctor-day-zero.test.ts` (`--tier ops`), `test/e2e/doctor-ops-tier-postgres.test.ts`, `test/doctor-entry-deadline-6803.test.ts` (+ `test/e2e/doctor-entry-deadline-postgres.test.ts`), `test/doctor-default-budget-6803.test.ts`; bench `scripts/bench/doctor-scale.ts`. #7276: `scoredChecks` keeps over-budget unknowns out of every score (`unknown_count`); `derived_visibility` is its own entry (`test/doctor-unknown-score-7276.test.ts`).
+- `src/commands/doctor/budget.ts` + `checks/ops-sections.ts` + `checks/orphan-estimate.ts` — doctor tiers and budgets (#6696 B1). `parseDoctorTier` (`--tier ops|quick|standard|deep`, a bad value is `invalid_params`), `parseBudgetMs` (`--budget-ms`, default 4000 under ops, 10000 under quick, none otherwise) and `startDoctorDeadline` build the `DoctorDeadline` the CLI starts before connecting. `runDoctorRegistry` runs the entries tagged `tier: 'ops'` (persistence capacity, terminal failures, managed sync movement, persistence compaction, serve build drift, schema-pack consistency, embedding state) right after the connection lane; under `--tier ops` it runs only those (each `executeRaw` gets the absolute `deadlineAt`, so `SET LOCAL statement_timeout` is the time left after the pool wait: `postgres-engine/bounded-statement.ts`), reports an entry marked `opsPglite: 'not_applicable'` as an `ok` info row on PGLite, and stays complete. Every other tier bounds each entry by `doctor.entry_budget_ms` (default 15000). An entry past its budget, an unknown reported after the overall deadline, or a connect the deadline ended becomes `budgetUnknownCheck` (warn, `details.health: 'unknown'`, `reason: 'budget'`, `exact: false`, a rerun-alone fix), never a clear result; every check carries `elapsed_ms`, and the report adds `tier`/`complete`/`unknown_sections`/`elapsed_ms`/`budget_ms` only when `--tier` or `--budget-ms` was given (`doctorRunSummary`). `doctorHealth(ctx)` memoizes `getHealth` for one run. `orphan_ratio` estimates from a `TABLESAMPLE SYSTEM` sample above `doctor.orphan_ratio.full_scan_max_pages` (default 50000) unless `--tier deep`. Capacity and compaction freshness live in `checks/ops-sections.ts`. On every tier each entry runs inside its own `StatementDeadline` (`src/core/statement-deadline.ts`: an AsyncLocalStorage scope plus `deadlineBoundEngine`, one stable Proxy per real engine that refuses any engine call past the deadline, carries the deadline to the server on Postgres `executeRaw`, and marks the scope expired on a cancel even when the check catches it; `engineCacheKey` maps the wrapper to the real engine for engine-keyed caches; PGLite gets only the pre-statement refusal). The budget-config read is one bounded statement (2 s). `CHEAP_INCIDENT_CHECKS` (by check name: persistence capacity, managed sync movement, `text_projection_readiness`, `partial_embedding`, `links_extraction_lag`) run right after the ops sections, before any full scan. #8979: with an engine and without `--fast` or `--only`, the entries before the connection lane stop at half the time left when the check run starts, so the ops sections and the cheap incident checks keep the other half. `local-audits.ts` `localProbe` runs the home-dir entry's `npm root -g`, `which -a gbrain` and `crontab -l` asynchronously and kills each with SIGKILL at the entry deadline (5 s at most), so a hung probe never holds the run past `--budget-ms`. `scanDeadline` clips the frontmatter walk and the fence census to the entry deadline less 250 ms, so they report partial results. `--only` with an explicit `--budget-ms` gives the selected entries the whole overall budget; `budgetUnknownCheck` names the limiting budget (`details.limit`: `entry` or `overall`) and fixes with `--only <check> --budget-ms N` (N ten times that budget; actor agent while N fits `AGENT_TOOL_LIMIT_MS` less 10 s, else actor user). `--budget-ms 0` is no overall budget. `default-budget.ts`: a plain non-interactive CLI `doctor --json` (stderr not a TTY; no `--budget-ms`, `--tier`, `--fix`, `--remediate` or `--remediation-plan`) caps its check run at `doctor.default_budget_ms` (file plane, default 90000, 0 off), started by `startDeferredDeadline` when the registry starts (connect and migrations are outside it), with one stderr line; the report then carries the tier fields. `capacity-memo.ts` `doctorCapacityForecast`: one forecast per run (shared by `persistence_capacity` and `persistence_request_growth`) read under the run's overall deadline and dropped from the memo on a deadline failure, which makes the waiting check unknown instead of a counter-only verdict. `persistence_session_timeouts` reads `SHOW statement_timeout` outside the entry deadline. Tests: `test/doctor-tier-6696.test.ts`, `test/doctor-day-zero.test.ts` (`--tier ops`), `test/e2e/doctor-ops-tier-postgres.test.ts`, `test/doctor-entry-deadline-6803.test.ts` (+ `test/e2e/doctor-entry-deadline-postgres.test.ts`), `test/doctor-default-budget-6803.test.ts`; bench `scripts/bench/doctor-scale.ts`. #7276: `scoredChecks` keeps over-budget unknowns out of every score (`unknown_count`); `derived_visibility` is its own entry (`test/doctor-unknown-score-7276.test.ts`).
- `src/commands/doctor/last-known.ts` — the quick tier's last known results (#7142). `--tier quick` (budget.ts: `QUICK_BUDGET_MS_DEFAULT` 10000, connect included; `entryRunsAt` orders ops ⊂ quick ⊂ standard ⊂ deep; `cheapTier` gives it the ops tier's round-trip connection check and counter-mode embedding state) runs the ops entries plus the entries tagged `tier: 'quick'` (schema version, the stub-guard entry with `sync_failures`, queue health, partial embeddings). `lastKnownMode` turns the store on only for a brain-wide local CLI run (`buildChecks(..., { lastKnown: 'cli' })` from `runDoctor`) or the refresh job, never under `--only`, `--source`, a remote scope, `--fix` or `--tier ops`. `runDoctorRegistry` records each entry's outcome (`done`, `expired` when it ran out of budget or emitted a budget unknown, `not_run` when the tier skipped a standard entry); `withLastKnown` writes the finished entries of a standard or deep run to `op_checkpoints` (op `doctor-last-known`, fingerprint = entry name, `completed_keys[0]` = `{ checks, measured_at, elapsed_ms, emits }`, one bounded statement, best-effort) and `applyLastKnown` replaces an unfinished entry's checks with its last known ones when they are at most `LAST_KNOWN_MAX_AGE_MS` (24 h) old: same status, message prefixed `Last known, N ago (...)`, `details.last_known` `{ measured_at, age_ms, reason: not_in_tier | budget }`. The rest are named in one `doctor_last_known` warning (`details.health: 'unknown'`, `unknown_checks`), which `tierFields` expands into `unknown_sections`; served checks go to `last_known_sections` and make the report incomplete. An entry with no result younger than `REFRESH_AFTER_MS` (1 h) queues one `doctor-refresh` job on Postgres (idempotency key per hour, `maxWaiting: 1`, priority 10 so sync, the autopilot cycles, global maintenance, embed backfill and loops extract claim first, `timeout_ms` 15 min; none when DB config `doctor.background_refresh` is `false`, #7263); the handler (`runDoctorRefresh`, registered in `commands/jobs.ts`) runs `doctorRefreshRegistry()` (the connection lane plus every standard entry after the connection gate; filesystem entries are recorded only by CLI runs) with `REFRESH_ENTRY_BUDGET_MS` (600000) per entry inside the overall `REFRESH_BUDGET_MS` (10 min, passed as `--budget-ms`: past it no entry starts and the running one is cut, so the job completes with what it measured and the rest waits for the next slot) and queues nothing itself. `doctor-refresh` is in `DEFAULT_LONG_JOB_NAMES` (`minions/lanes.ts`). Tests: `test/doctor-refresh-7263.test.ts`, `test/doctor-quick-tier-7142.test.ts` (+ `test/e2e/doctor-quick-tier-7142-postgres.test.ts`).
- `src/commands/doctor/brain-health-bands.ts` + `remote-tier.ts` + `ops-snapshot.ts`, `src/core/doctor-remote-tier.ts`, `src/core/persistence/capacity-view.ts` — the ops tier for agents and remote clients (#6696 B2). `readCapacityView` (for `/admin/api/ops`) reads the counter rows, `capacityDiagnostics`, the light `readCapacityForecast` (null when unreadable: days unknown) and `readLastCompaction`; the bands read `cachedCapacitySnapshot`; `capacityVerify()` is the verify of every capacity fix (`gbrain doctor --only persistence_capacity --json` plus MCP `get_brain_health`). `readBrainHealthBands` backs the read-scope `get_brain_health` op: capacity band and days band, write failures and active blockers as count bands for the caller's readable sources, no slugs or exact counters, cached 60 s per engine and scope. `runRemoteDoctorTier` backs `run_doctor`'s `tier: "ops"` / `only` (admin). `runScopedRemoteDoctor` is the thin client's `gbrain doctor --tier ops` / `--only <registry check>`: it reads `tools/list` and uses `run_doctor` with the parameters, else the bands (`BAND_CHECKS`), else refuses `doctor_tier_unavailable`; it never runs the full remote report in their place. `cachedOpsSnapshot` serves `/admin/api/ops` from one ops run a minute. Tests: `test/doctor-ops-remote-6696.test.ts`.
diff --git a/src/commands/doctor/checks/cron-gbrain-home.ts b/src/commands/doctor/checks/cron-gbrain-home.ts
index 8db9b04229..a4bef39c6c 100644
--- a/src/commands/doctor/checks/cron-gbrain-home.ts
+++ b/src/commands/doctor/checks/cron-gbrain-home.ts
@@ -4,14 +4,13 @@
* a checkout, or the `gbrain` binary while this brain is under a non-default GBRAIN_HOME, reads and writes
* `~/.gbrain` instead: a second, silent brain state (locks, queue, config) beside the real one.
*
- * Read-only and bounded: `crontab -l` (5 s; no check unless the crontab mentions gbrain or src/cli.ts), plus at most 20 scripts the lines name (64 KiB
+ * Read-only and bounded: `crontab -l` (5 s, or the entry deadline when sooner: local-audits.ts `localProbe`; no check unless the crontab mentions gbrain or src/cli.ts), plus at most 20 scripts the lines name (64 KiB
* each). A line or script counts as setting the home when it assigns GBRAIN_HOME (on the line, in the crontab's
* environment lines, or anywhere in the script). Warns, never fails; the user edits the crontab.
*/
import { existsSync, readFileSync, statSync } from 'node:fs';
import { homedir } from 'node:os';
import { isAbsolute, join } from 'node:path';
-import { execFileSync } from '../../../core/spawn.ts';
import type { Check } from '../../doctor.ts';
import { doctorVerify } from '../check-fix.ts';
@@ -97,9 +96,3 @@ export function cronGbrainHomeCheck(crontab: string | null, customHome: string |
user_message: `These cron commands run gbrain without GBRAIN_HOME: ${listed}. Add ${home} to each (or to the script it runs), or point them at a wrapper that exports it, so they act on this brain.`,
verify: doctorVerify('cron_gbrain_home') } };
}
-
-/** `crontab -l` on a local machine; null when there is no crontab or it cannot be read in 5 s. */
-export function readCrontab(): string | null {
- try { return execFileSync('crontab', ['-l'], { stdio: ['ignore', 'pipe', 'ignore'], timeout: 5_000 }).toString(); }
- catch { return null; }
-}
diff --git a/src/commands/doctor/checks/local-audits.ts b/src/commands/doctor/checks/local-audits.ts
index dae5f29a55..e867fe3f0e 100644
--- a/src/commands/doctor/checks/local-audits.ts
+++ b/src/commands/doctor/checks/local-audits.ts
@@ -28,6 +28,7 @@ import {
import type { Check } from '../../doctor.ts';
import { withSkippedSegmented } from '../check-fix.ts';
import type { DoctorContext, DoctorEntry } from '../context.ts';
+import { scanDeadline } from '../budget.ts';
async function runStubGuard(ctx: DoctorContext): Promise<Check[]> {
const { engine, orphanRatioSourceId } = ctx;
@@ -378,8 +379,28 @@ export const extractionBacklogsEntry: DoctorEntry = {
run: runExtractionBacklogs,
};
+/**
+ * #8979: a local probe's stdout, or null when it fails or outlives its bound (5 s, clipped to the entry deadline less
+ * the report reserve; `entryDeadlineAt` is read when the entry starts). It runs asynchronously and is killed with
+ * SIGKILL at its bound, so a probe that hangs never blocks the event loop or outlives the entry's deadline.
+ */
+async function localProbe(entryDeadlineAt: number | undefined, file: string, args: string[]): Promise<string | null> {
+ const timeout = scanDeadline({ entryDeadlineAt }, 5_000) - Date.now();
+ if (timeout <= 0) return null;
+ const { execFile } = await import('../../../core/spawn.ts');
+ return new Promise((resolve) => {
+ const child = execFile(file, args, { encoding: 'utf8', shell: process.platform === 'win32' }, (error, stdout) => {
+ clearTimeout(timer);
+ resolve(error ? null : stdout);
+ });
+ const timer = setTimeout(() => { child.kill('SIGKILL'); resolve(null); }, timeout);
+ child.stdin?.end();
+ });
+}
+
async function runHomeDirInWorktree(ctx: DoctorContext): Promise<Check[]> {
const checks: Check[] = [];
+ const { entryDeadlineAt } = ctx;
// 3e. home_dir_in_worktree (v0.35.8.0; peeled to doctor/checks/home-worktree.ts).
// Walks up from `gbrainPath()` toward $HOME looking for a VALIDATED `.git`
@@ -406,35 +427,18 @@ async function runHomeDirInWorktree(ctx: DoctorContext): Promise<Check[]> {
// whose bin is not on PATH still warns when no real gbrain is. Skips
// silently when neither finds anything (e.g. running via `bun src/cli.ts`).
try {
- const { execSync, execFileSync } = await import('../../../core/spawn.ts');
const { homedir } = await import('node:os');
const bunGlobalRoot = join(process.env.BUN_INSTALL || join(homedir(), '.bun'), 'install', 'global');
const globalPackages = [join(bunGlobalRoot, 'node_modules', 'gbrain')];
- let npmRoot: string | undefined;
- try {
- npmRoot = execFileSync('npm', ['root', '-g'], {
- encoding: 'utf8',
- stdio: ['ignore', 'pipe', 'ignore'],
- timeout: 5000,
- shell: process.platform === 'win32',
- }).trim();
- if (npmRoot) globalPackages.push(join(npmRoot, 'gbrain'));
- } catch {
- // No npm (or it failed): only Bun's global dir is checked.
- }
- let candidates: string[] = [];
- try {
- candidates = execSync('which -a gbrain', {
- encoding: 'utf8',
- stdio: ['ignore', 'pipe', 'ignore'],
- })
- .split('\n')
- .map((s) => s.trim())
- .filter(Boolean);
- } catch {
- // `which` exits non-zero when gbrain isn't on PATH (or is missing
- // entirely on this platform) — nothing to check.
- }
+ // No npm (or it failed): only Bun's global dir is checked.
+ const npmRoot = (await localProbe(entryDeadlineAt, 'npm', ['root', '-g']))?.trim() || undefined;
+ if (npmRoot) globalPackages.push(join(npmRoot, 'gbrain'));
+ // `which` exits non-zero when gbrain isn't on PATH (or is missing
+ // entirely on this platform) — nothing to check.
+ const candidates = ((await localProbe(entryDeadlineAt, 'which', ['-a', 'gbrain'])) ?? '')
+ .split('\n')
+ .map((s) => s.trim())
+ .filter(Boolean);
const { assessGbrainBinaries } = await import('../../../core/npm-squat-check.ts');
const { fileURLToPath } = await import('node:url');
const assessment = assessGbrainBinaries(candidates, {
@@ -517,8 +521,8 @@ async function runHomeDirInWorktree(ctx: DoctorContext): Promise<Check[]> {
// GBRA-108: cron lines (and scripts they run) that call gbrain without GBRAIN_HOME (doctor/checks/cron-gbrain-home.ts).
// No environment gate: a container can run cron too; without a crontab the check emits nothing.
try {
- const { cronGbrainHomeCheck, readCrontab } = await import('./cron-gbrain-home.ts');
- const cron = cronGbrainHomeCheck(readCrontab(), process.env.GBRAIN_HOME || undefined);
+ const { cronGbrainHomeCheck } = await import('./cron-gbrain-home.ts');
+ const cron = cronGbrainHomeCheck(await localProbe(entryDeadlineAt, 'crontab', ['-l']), process.env.GBRAIN_HOME || undefined);
if (cron) checks.push(cron);
} catch {
// Best-effort: an unreadable crontab never blocks doctor.
diff --git a/src/commands/doctor/registry.ts b/src/commands/doctor/registry.ts
index 88f1a8a799..87a3dfce38 100644
--- a/src/commands/doctor/registry.ts
+++ b/src/commands/doctor/registry.ts
@@ -404,7 +404,11 @@ function onlyResult(checks: Check[], only: ReadonlySet<string>, stopped: boolean
* connection lane runs at every tier). Each entry runs under its own deadline:
* the per-entry budget (`doctor.entry_budget_ms`, read with a bounded
* statement) clipped to the overall deadline; under `--tier ops`, or under
- * `--only` with an explicit `--budget-ms`, the overall deadline alone. The
+ * `--only` with an explicit `--budget-ms`, the overall deadline alone. #8979:
+ * with an engine, without `--fast` or `--only`, the entries before the
+ * connection lane stop at half the time left when the run starts, so the ops
+ * sections and the cheap incident checks after it keep the other half however
+ * slow those entries are. The
* entry reads through the run's deadline-bound engine with that deadline in
* its async context, so its statements stop at it (src/core/statement-deadline.ts).
* An entry past its budget, or whose statement was refused or cancelled at its
@@ -423,6 +427,9 @@ export function runDoctorRegistry(ctx: DoctorContext, entries: readonly DoctorEn
const outcomes: EntryOutcome[] = [];
const memo = new Map<string, Promise<unknown>>();
const gateAt = entries.indexOf(connectionGateEntry);
+ const dbLaneAt = ctx.engine && !ctx.fastMode && !ctx.only ? entries.findIndex((e) => CONNECTION_LANE.has(e)) : -1;
+ const startedAt = Date.now();
+ const preLaneReserveMs = dbLaneAt >= 0 && ctx.deadline?.deadlineAt != null ? Math.floor((ctx.deadline.deadlineAt - startedAt) / 2) : 0;
const checks: Check[] = [];
let entryBudgetMs: number | null = null;
for (const entry of entries) {
@@ -441,7 +448,7 @@ export function runDoctorRegistry(ctx: DoctorContext, entries: readonly DoctorEn
entryBudgetMs = await readEntryBudget(ctx);
}
const overallOnly = cheapTier(tier) || (!!ctx.only && ctx.deadline?.explicit === true);
- const budgetMs = entryBudget(ctx, overallOnly, CONNECTION_LANE.has(entry) ? null : entryBudgetMs, started);
+ const budgetMs = entryBudget(ctx, overallOnly, CONNECTION_LANE.has(entry) ? null : entryBudgetMs, started, entries.indexOf(entry) < dbLaneAt ? preLaneReserveMs : 0);
const limit = budgetMs !== null && ctx.deadline?.deadlineAt != null && (overallOnly || entryBudgetMs === null || started + budgetMs >= ctx.deadline.deadlineAt) ? 'overall' : 'entry';
if (budgetMs !== null && budgetMs <= 0) {
checks.push(...emitted.map((n) => budgetUnknownCheck(n, 0, ctx.deadline?.budgetMs ?? 0, 'overall')));
@@ -503,9 +510,9 @@ async function withLastKnown(engine: BrainEngine, checks: Check[], outcomes: Ent
return unmeasured ? [...applied.checks, unmeasured] : applied.checks;
}
-/** The time this entry may take: the per-entry budget (unless only the overall deadline applies) clipped to the overall deadline; null: unbounded. */
-function entryBudget(ctx: DoctorContext, overallOnly: boolean, perEntry: number | null, now: number): number | null {
- const overall = ctx.deadline?.deadlineAt != null ? ctx.deadline.deadlineAt - now : null;
+/** The time this entry may take: the per-entry budget (unless only the overall deadline applies) clipped to the overall deadline less `reservedMs`; null: unbounded. */
+function entryBudget(ctx: DoctorContext, overallOnly: boolean, perEntry: number | null, now: number, reservedMs: number): number | null {
+ const overall = ctx.deadline?.deadlineAt != null ? ctx.deadline.deadlineAt - reservedMs - now : null;
const own = overallOnly ? null : ctx.entryBudgetOverrideMs ?? perEntry;
if (overall === null) return own;
return own === null ? overall : Math.min(own, overall);
diff --git a/test/doctor-entry-deadline-6803.test.ts b/test/doctor-entry-deadline-6803.test.ts
index 5d650d9d52..7cddc54ca3 100644
--- a/test/doctor-entry-deadline-6803.test.ts
+++ b/test/doctor-entry-deadline-6803.test.ts
@@ -13,9 +13,13 @@
* - The frontmatter scan stops at its entry's deadline and names the source it did not finish, not unknown.
* - --only X --budget-ms N gives X the whole N; the budget-unknown fix names --budget-ms above the time taken,
* and running it completes the check (scaled down: 200 ms entry budget, 600 ms statements).
+ * - #8979: the entries before the connection lane get at most half the run's time, so one that runs out the clock
+ * still leaves the cheap incident checks their share; a local probe that hangs (npm, crontab, which) is killed at
+ * its entry's deadline instead of blocking the run past it, and no probe outlives the run.
+ * - #8979: under --fast the entries before the connection lane keep the whole budget (no DB lane follows).
*/
import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
-import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';
+import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import postgres from '#postgres';
@@ -25,6 +29,8 @@ import { buildChecks, type Check } from '../src/commands/doctor.ts';
import { CHEAP_INCIDENT_CHECKS, DOCTOR_CHECK_REGISTRY, runDoctorRegistry } from '../src/commands/doctor/registry.ts';
import { connectionGateEntry } from '../src/commands/doctor/checks/db-connection.ts';
import { frontmatterEntry } from '../src/commands/doctor/checks/content-quality.ts';
+import { homeDirInWorktreeEntry } from '../src/commands/doctor/checks/local-audits.ts';
+import { linksExtractionLagEntry } from '../src/commands/doctor/checks/sync-search.ts';
import { persistenceCapacityEntry } from '../src/commands/doctor/checks/ops-sections.ts';
import { startDoctorDeadline } from '../src/commands/doctor/budget.ts';
import type { DoctorContext, DoctorEntry } from '../src/commands/doctor/context.ts';
@@ -35,7 +41,7 @@ import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';
const ENTRY_BUDGET = 'doctor.entry_budget_ms';
const noProgress = new Proxy({}, { get: () => () => undefined }) as DoctorContext['progress'];
-function ctxFor(engine: BrainEngine, args: string[]): DoctorContext {
+function ctxFor(engine: BrainEngine | null, args: string[]): DoctorContext {
return {
engine, args, jsonOutput: true, fastMode: false, doFix: false, dryRun: false, scope: 'brain', orphanRatioSourceId: undefined,
progress: noProgress, skillsDirResolution: { dir: null, source: 'none' }, skillsDir: null, autoFixReport: null, schemaVersion: 0,
@@ -96,6 +102,42 @@ test('C2: every entry that emits a cheap incident check runs before the first fu
expect([...CHEAP_INCIDENT_CHECKS].filter((n) => !emitted.has(n))).toEqual([]);
});
+test('#8979: a local probe that hangs is killed at its entry deadline instead of blocking the run past it', async () => {
+ const bin = mkdtempSync(join(tmpdir(), 'gbrain-8979-bin-'));
+ const pids = join(bin, 'pids');
+ for (const tool of ['npm', 'crontab', 'which']) {
+ // Ignores SIGTERM, so only a hard kill ends it before its 6 s sleep.
+ writeFileSync(join(bin, tool), `#!/bin/sh\necho $$ >> '${pids}'\ntrap '' TERM\nexec sleep 6\n`, { mode: 0o755 });
+ }
+ const path = process.env.PATH;
+ process.env.PATH = `${bin}:${path}`;
+ try {
+ const args = ['--json', '--budget-ms', '1000'];
+ const started = Date.now();
+ const checks = await runDoctorRegistry(ctxFor(null, args), [homeDirInWorktreeEntry]);
+ expect(Date.now() - started).toBeLessThan(1_000 + 400);
+ expect(byName(checks, 'home_dir_in_worktree')).toBeDefined();
+ await new Promise((r) => setTimeout(r, 1_500));
+ const launched = readFileSync(pids, 'utf8').split('\n').filter(Boolean).map(Number);
+ expect(launched.length).toBeGreaterThan(0);
+ const alive = launched.filter((pid) => { try { process.kill(pid, 0); return true; } catch { return false; } });
+ expect(alive).toEqual([]);
+ } finally {
+ process.env.PATH = path;
+ rmSync(bin, { recursive: true, force: true });
+ }
+}, 30_000);
+
+test('#8979: under --fast an entry before the connection lane keeps the whole budget', async () => {
+ const entry: DoctorEntry = {
+ name: 'fast_filesystem_example', emits: ['fast_filesystem_example'],
+ run: () => new Promise((r) => setTimeout(() => r([{ name: 'fast_filesystem_example', status: 'ok', message: 'ok' }]), 700)),
+ };
+ const args = ['--json', '--fast', '--budget-ms', '1200'];
+ const checks = await runDoctorRegistry({ ...ctxFor(null, args), fastMode: true }, [entry, connectionGateEntry]);
+ expect(byName(checks, 'fast_filesystem_example')?.status).toBe('ok');
+}, 15_000);
+
for (const kind of testBackends()) {
describe(`#6803 doctor deadlines (${kind})`, () => {
let engine: BrainEngine;
@@ -137,6 +179,21 @@ for (const kind of testBackends()) {
expect(checks.some((c) => c.details?.reason === 'budget' && c.details?.limit === 'overall')).toBe(true);
}, 60_000);
+ test('#8979: an entry before the connection lane that runs out the clock leaves the cheap incident checks their share', async () => {
+ const slowFilesystem: DoctorEntry = {
+ name: 'slow_filesystem_example', emits: ['slow_filesystem_example'],
+ run: () => new Promise((r) => setTimeout(() => r([{ name: 'slow_filesystem_example', status: 'ok', message: 'ok' }]), 3_000)),
+ };
+ const args = ['--json', '--scope=brain', '--budget-ms', '2000'];
+ const started = Date.now();
+ const checks = await runDoctorRegistry(ctxFor(engine, args), [slowFilesystem, connectionGateEntry, persistenceCapacityEntry, linksExtractionLagEntry]);
+ expect(Date.now() - started).toBeLessThan(2_000 + 400);
+ expect(byName(checks, 'slow_filesystem_example')?.details).toMatchObject({ health: 'unknown', reason: 'budget', limit: 'overall' });
+ const lag = byName(checks, 'links_extraction_lag');
+ expect(lag?.details?.health, JSON.stringify(lag)).not.toBe('unknown');
+ expect(byName(checks, 'persistence_capacity')?.details?.health).not.toBe('unknown');
+ }, 30_000);
+
test('--only X --budget-ms N gives X the whole N; the budget fix names a larger --budget-ms and running it completes the check', async () => {
const slow = instrumented(engine, { slow: { match: /FROM persistence_counters/, ms: 600 } });
await withEntryBudget(200, async () => {