Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

feat(doctor): non-TTY heartbeat budget; tests for the contract fields, --only, harness smoke and day zero (E11, E1, E2)

garrytanf899387d2320
diff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsv
index 0c2c75266d..710958d9be 100644
--- a/scripts/module-size-limits.tsv
+++ b/scripts/module-size-limits.tsv
@@ -5,7 +5,7 @@
# Columns: path max_lines policy note
src/cli.ts 3211 ratchet +2 agent operator wave A4: observational startup (probe-only connect for startup:observational commands; completeEngineStartup split out of connectEngine, exposed as ctx.completeStartup); +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5232: write-wait import, reporter-owned verdict in the op catch, thin-client writeWaitMs, ctx.writeWaitMs (logic in persistence/write-wait.ts); +1 #4768: serve --access help line; +4 #5433: list_pages TSV cell escaping in formatResult; +2 #lane-h pricing: help line + thin-client refusal hint for `gbrain pricing`; +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5433: list_pages TSV cell escaping in formatResult
src/commands/autopilot.ts 1639 ratchet refactor wave 1 split target (W4 autopilot, cut line); ceiling rationale: docs/architecture/key-files/commands-1.md entry for src/commands/autopilot.ts; +2 fix wave 5: nosemgrep justifications on the per-brain job launchctl/systemctl calls (#5195); +2 #5813: boot reconcile names attempted and running versions in log + audit; +2 #5855: Bun floor gate before the swap and the swap-refusal hold (logic in core/bun-floor.ts)
-src/commands/doctor.ts 662 ratchet refactor wave 1 split target (W4 doctor); ceiling rationale: docs/architecture/key-files/commands-2.md entry for src/commands/doctor.ts
+src/commands/doctor.ts 663 ratchet refactor wave 1 split target (W4 doctor); ceiling rationale: docs/architecture/key-files/commands-2.md entry for src/commands/doctor.ts
src/commands/embed.ts 2217 ratchet lowered v0.46.26.0: embedBatchWithBackoff + retry cluster peeled to core/embed-retry.ts (core/commands layering fix); grown wave-g (#4530): per-model input-limit wiring; wave-k #3622 reimpl: --stale zero-progress failure quarantine; +29 #4668 (#4530): oversize-heal call sites in both --stale drains — kept low by peeling the healed-row remap to core/embed-oversize-heal.ts (shared with embed-stale.ts); +35 #4647 (refs #4599): per-tick timeout+abort on the single-flight lock heartbeat refresh (interval deliberately NOT unref'd); +122 refs #4599: stall-watchdog race around the drain + shared idempotent flushAndRelease + CLI stall exit mapping (watchdog machinery itself lives in core/embed-stall.ts); +12: adversarial-review hardening (healed_splits progress key + heal-tick comment); #5105: guarded derived projection preparation and read seals; #5105: conditional embedding installer wiring; archived eligibility: active-only dispatch with honest stranded-work reporting; explicit archived admission: live-source snapshots and honest refused-installation failures; +2 fw3: embed --stale --images dispatch (sweep lives in core/embed-stale-images.ts); +5 #5289: dry run reports restamp-only chunks apart from chunks to embed (count lives in core/embedding-invalidation.ts); +6 #4616: keep a partially refused batch in embedPageTexts and name the recovery command in failure samples (guard lives in core/ai/embedding-guard.ts); +5 #5226: embed summary counts distinct pages; +3 #5804: null projection snapshot counted as a failure with one batch summary in embed --stale; +18 wave 8 lane D1: #5527 mixed-space warning subtracts current-model chunks (+4), #5885 takes option/result fields and the stale-drain takes call (pass lives in core/embed-takes.ts); +9 Foundations 1 F4d: time-budget stop result fields, stdout verdict and stop recording in embed --stale (logic in core/embed-budget-stop.ts)
src/commands/extract-conversation-facts.ts 2182 ratchet grown v0.46.x per-provider gateway-unavailable copy; grown wave-g (#4482): expected budget/deadline caps classified apart from error halts; wave-k: save-time resolution caller (#4052/#3729 — supersedes wave-g's per-row resolveEntitySlug mapper); +1: key-aware llm-fallback default (#3813); +1: pricingOverrides wiring into the owned BudgetTracker (#4633 adoption); +3: #4869 snapshot-mismatch counts as pages_failed; merged reliability/shared-skills source integration; +19: additive skip reasons and model-free dry-run (#5364); +21 #5757: managed extraction buffers a page's rows and replaces the prior batch in one coordinator transaction (replacement helper lives in core/persistence/derived-facts.ts); +18 #5823: result diagnostics, strict explicit-cap parsing and CLI recovery/help; default-cap decision lives in facts/conversation-budget.ts; +18 fix wave 7 (#5704, #5448): --json envelope on stdout (parser flag, help line, summary block gated behind the human-output branch)
src/commands/extract.ts 2528 ratchet grown v0.46.26.0 megawave: FS-walk stamp snapshot + legacy timeline repair wiring (#3957 D4) + PR#4486 rebase onto current master; grown wave-g (#4542): --from-meetings zero-match warning + default-pass note; +29: #3478 federated-only gate on the cross-source 'default' link fallback; +44: #3908 cross_source opt-in — counted drops + deterministic cross-source pick; +36: #4611 configured-sources.default fallback (resolveLinkFallbackDefault); +14: #4890 extractStaleFromDB quiet opt + extractForSlugs jsonMode batch_error stderr fallback; +5: #4855 stroke-letter fold in link extraction; +5: #4793 by-mention scan honours link_resolution.cross_source; +18: wave review — ExtractOpts.quiet threaded through the fs-walk extractors (stdout silence decoupled from jsonMode); +77: shared buildSlugPathIndex — every per-slug extractor resolves the real on-disk path, and the sync hooks report which slugs they actually read; +10 #4999: includeFrontmatter default-resolved inside extractLinksForSlugs + extractStaleFromDB (resolveIncludeFrontmatter), --stale flag absent -> configured knob; +20: pre-landing review of #4967 — resolveSlugRelPath: index miss falls back to the legacy slug+'.md' path so admitted _-prefixed / include_hidden pages keep their edges; T2: source-qualified inference and atomic origin-scoped derived links; standard DB extraction fences captured endpoint revisions; shared authoritative attendance/source reconciliation moved to the core module; +7 A2 preview-bound attendance repair import, help and authority dispatch; bounded incomplete-attendance diagnostics and consistent basename resolution; fail closed before graph mutation when active ontology is unavailable; +16 source-selected ontology cache, type-scoped preflight and non-starving failed stale drain; +7 write-path wave: per-slug extractors replace page links + retract removed timeline rows + rename-alias resolution; +5 fw3 derived-sync: timeline --prune-orphans CLI (#4649) and full-walk page link replacement; +13 fw3 A16/A15: sync link hook reads scoped page metadata and reports per-page extraction errors; +1 fw3 managed-lifecycle: extract --stale dispatches managed brains to the coordinator-safe path; +4 fw3 integration: managed brains refuse the direct timeline orphan prune; +26 #5609: managed extract --stale publishes links, canonical timeline and watermark per page in one coordinated transaction; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +4 at the merge; +6 fix wave 3 lane B: a managed brain routes the extract phase file walk through extractManagedStaleLinks instead of the refused raw timeline batch, keeping the extract.links_fs progress phase; +6 #5761: the unmanaged extract --stale sweep marks unresolved-attendance skips attendance-blocked; +2 eval-wave N9-3/N12-7: a page-type-bound pack attended rule defers to canonical attendance on the filesystem path (ownsAttendanceInference); lowered to 2528 #5904: the DB timeline walk moved to commands/extract-timeline-db.ts (coordinated publication on managed brains, honest refusal + non-zero exit)
diff --git a/scripts/serial-weights.json b/scripts/serial-weights.json
index e7062dc8ae..d26e651907 100644
--- a/scripts/serial-weights.json
+++ b/scripts/serial-weights.json
@@ -75,8 +75,10 @@
"test/doctor-backup-coverage.serial.test.ts": 0,
"test/doctor-cli-smoke.serial.test.ts": 14,
"test/doctor-connection-classified.serial.test.ts": 2,
+ "test/doctor-day-zero.serial.test.ts": 7,
"test/doctor-engine-fit.serial.test.ts": 0,
"test/doctor-eval-drift-branches.serial.test.ts": 1,
+ "test/doctor-harness-smoke.serial.test.ts": 8,
"test/doctor-memory-writeback.serial.test.ts": 3,
"test/doctor-no-migrate.serial.test.ts": 23,
"test/doctor-remote.serial.test.ts": 1,
diff --git a/scripts/test-weights.json b/scripts/test-weights.json
index 52e9cb0c67..f8a597c73d 100644
--- a/scripts/test-weights.json
+++ b/scripts/test-weights.json
@@ -570,6 +570,7 @@
"test/doctor-source-config-shape.test.ts": 2,
"test/doctor-stale-lock-hints.test.ts": 1240,
"test/doctor-stale-mentions.test.ts": 1158,
+ "test/doctor-status-set.test.ts": 3000,
"test/doctor-subagent-capability.test.ts": 6,
"test/doctor-subagent-health.test.ts": 275,
"test/doctor-supervisor-singleton-pidfile.test.ts": 1707,
diff --git a/scripts/ubicloud/weights.json b/scripts/ubicloud/weights.json
index 4824102762..a170d5bc47 100644
--- a/scripts/ubicloud/weights.json
+++ b/scripts/ubicloud/weights.json
@@ -354,8 +354,10 @@
"serial:test/doctor-backup-coverage.serial.test.ts": 682,
"serial:test/doctor-cli-smoke.serial.test.ts": 5745,
"serial:test/doctor-connection-classified.serial.test.ts": 767,
+ "serial:test/doctor-day-zero.serial.test.ts": 7000,
"serial:test/doctor-engine-fit.serial.test.ts": 333,
"serial:test/doctor-eval-drift-branches.serial.test.ts": 315,
+ "serial:test/doctor-harness-smoke.serial.test.ts": 8000,
"serial:test/doctor-keyless.serial.test.ts": 5801,
"serial:test/doctor-memory-writeback.serial.test.ts": 1704,
"serial:test/doctor-no-migrate.serial.test.ts": 10152,
@@ -1175,6 +1177,7 @@
"unit:test/doctor-source-config-shape.test.ts": 292,
"unit:test/doctor-stale-lock-hints.test.ts": 2136,
"unit:test/doctor-stale-mentions.test.ts": 5921,
+ "unit:test/doctor-status-set.test.ts": 3000,
"unit:test/doctor-subagent-capability.test.ts": 299,
"unit:test/doctor-subagent-health.test.ts": 1873,
"unit:test/doctor-supervisor-singleton-pidfile.test.ts": 3270,
diff --git a/src/commands/doctor.ts b/src/commands/doctor.ts
index ebfa4b034c..bb7139e4f6 100644
--- a/src/commands/doctor.ts
+++ b/src/commands/doctor.ts
@@ -139,6 +139,7 @@ export {
import type { DoctorContext } from './doctor/context.ts';
import { runDoctorRegistry, parseOnlyChecks } from './doctor/registry.ts';
import { finalizeCheckFixes, fixLine, type CheckAgentFields } from './doctor/check-fix.ts';
+import { throttleDoctorHeartbeat } from './doctor/heartbeat.ts';
import type { RenderContext } from '../core/agent-output.ts';
export interface Check extends CheckAgentFields {
name: string;
@@ -406,7 +407,7 @@ export async function buildChecks(
// Progress reporter. `--json` is doctor's machine-readable output, so plain
// progress must not leak to stderr unless the caller explicitly asks for
// structured progress with --progress-json.
- const progress = createProgress(doctorProgressOptions(jsonOutput));
+ const progress = throttleDoctorHeartbeat(createProgress(doctorProgressOptions(jsonOutput)));
// --- Filesystem checks (always run, no DB needed) ---
diff --git a/src/commands/doctor/heartbeat.ts b/src/commands/doctor/heartbeat.ts
new file mode 100644
index 0000000000..61d1daf094
--- /dev/null
+++ b/src/commands/doctor/heartbeat.ts
@@ -0,0 +1,34 @@
+/**
+ * Non-TTY doctor heartbeat budget (agent-first operator wave E11): an agent
+ * reading doctor's stderr through a pipe gets at most one heartbeat line per
+ * HEARTBEAT_MIN_GAP_MS. A check that runs longer than the gap still gets its
+ * line (the next heartbeat after a slow check is always due), and a run that
+ * stopped on a fatal error emits nothing more. TTY output (rewritten in place)
+ * and quiet / --progress-json progress are unchanged.
+ */
+import type { ProgressReporter } from '../../core/progress.ts';
+import { getCliOptions } from '../../core/cli-options.ts';
+
+export const HEARTBEAT_MIN_GAP_MS = 5_000;
+
+export function throttleDoctorHeartbeat(
+ inner: ProgressReporter,
+ opts: { tty?: boolean; now?: () => number; gapMs?: number } = {},
+): ProgressReporter {
+ if (opts.tty ?? (process.stderr.isTTY === true || getCliOptions().progressJson)) return inner;
+ const now = opts.now ?? Date.now;
+ const gap = opts.gapMs ?? HEARTBEAT_MIN_GAP_MS;
+ let last = Number.NEGATIVE_INFINITY;
+ return {
+ start: (phase, total) => { last = now(); inner.start(phase, total); },
+ tick: (n, note) => inner.tick(n, note),
+ heartbeat(note) {
+ const t = now();
+ if (t - last < gap) return;
+ last = t;
+ inner.heartbeat(note);
+ },
+ finish: (note) => inner.finish(note),
+ child: (phase, total) => inner.child(phase, total),
+ };
+}
diff --git a/test/doctor-day-zero.serial.test.ts b/test/doctor-day-zero.serial.test.ts
new file mode 100644
index 0000000000..18cbffc25b
--- /dev/null
+++ b/test/doctor-day-zero.serial.test.ts
@@ -0,0 +1,59 @@
+/**
+ * Day-zero doctor on a keyless brain (agent-first operator wave E2 + E11).
+ *
+ * `gbrain init --pglite --no-embedding`, then `gbrain doctor --json` with no
+ * provider keys, non-TTY, from a hermetic HOME. Baseline on 5b20e98 was
+ * 6 WARN / health 70 (retrieval_reflex_health, skill_preconditions,
+ * embedding_provider, backup_coverage, cycle_freshness, takes_count): every
+ * one of them is a capability that is off by choice or not applicable yet.
+ * Now: 0 WARN, 0 FAIL, health >= 90, capped_by names the keyless choice, and
+ * the non-TTY heartbeat stays within 10 stderr lines.
+ *
+ * Serial: subprocess CLI runs against one PGLite brain.
+ */
+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
+import { rmSync } from 'node:fs';
+import { makeDoctorHome, runGbrain, type DoctorHome } from './helpers/doctor-json-golden.ts';
+
+let h: DoctorHome;
+
+beforeAll(async () => {
+ h = makeDoctorHome('doctor-day-zero');
+ // A real first install has no partial skills workspace in HOME (the golden
+ // helper seeds one for the skill checks; day zero must not inherit it).
+ rmSync(h.skillsDir, { recursive: true, force: true });
+ const init = await runGbrain(h, ['init', '--pglite', '--no-embedding']);
+ if (init.exitCode !== 0) throw new Error(`gbrain init failed (${init.exitCode}): ${init.stderr}`);
+}, 120_000);
+
+afterAll(() => h?.cleanup());
+
+interface Report {
+ status: string;
+ health_score: number;
+ capped_by?: string[];
+ checks: Array<{ name: string; status: string; message: string; severity?: string; fix?: unknown; fix_unavailable_reason?: string }>;
+}
+
+describe('day-zero keyless doctor', () => {
+ test('doctor --json: no WARN or FAIL, health >= 90, capped_by embeddings_disabled', async () => {
+ const run = await runGbrain(h, ['doctor', '--json']);
+ expect(run.exitCode).toBe(0);
+ const report = run.json as Report;
+ const notOk = report.checks.filter(c => c.status !== 'ok').map(c => `${c.status} ${c.name}: ${c.message}`);
+ expect(notOk).toEqual([]);
+ expect(report.health_score).toBeGreaterThanOrEqual(90);
+ expect(report.capped_by).toEqual(['embeddings_disabled']);
+ const info = new Set(report.checks.filter(c => c.severity === 'info').map(c => c.name));
+ for (const name of ['embeddings', 'embedding_provider', 'takes_count', 'retrieval_reflex_health', 'skill_preconditions', 'cycle_freshness', 'backup_coverage']) {
+ if (report.checks.some(c => c.name === name)) expect(info.has(name), name).toBe(true);
+ }
+ }, 120_000);
+
+ test('human doctor on a pipe keeps the heartbeat within 10 stderr lines', async () => {
+ const run = await runGbrain(h, ['doctor']);
+ expect(run.exitCode).toBe(0);
+ const lines = run.stderr.split('\n').filter(l => l.trim().length > 0);
+ expect(lines.length, run.stderr).toBeLessThanOrEqual(10);
+ }, 120_000);
+});
diff --git a/test/doctor-harness-smoke.serial.test.ts b/test/doctor-harness-smoke.serial.test.ts
new file mode 100644
index 0000000000..950bde9fce
--- /dev/null
+++ b/test/doctor-harness-smoke.serial.test.ts
@@ -0,0 +1,104 @@
+/**
+ * `gbrain doctor --only harness_wiring --json` (agent-first operator wave G5
+ * step 2, Lane E): engine-free, read-only smoke of the harness registration.
+ *
+ * Hermetic HOME + GBRAIN_HOME on a keyless PGLite brain:
+ * - no harness and no registration → ok + severity:info with the install fix;
+ * - a Claude Code registration (~/.claude.json) whose argv starts a real
+ * `gbrain serve --surface verbs` → the smoke spawns it and runs initialize +
+ * tools/list + recall → ok, reason wired_running / smoke_passed;
+ * - a live `gbrain serve` already holding the brain lock → ok without spawning;
+ * - a registration whose binary does not exist → warn with a fix or reason;
+ * - doctor seeds nothing: the brain holds no pages afterwards.
+ *
+ * Serial: spawns `gbrain serve` subprocesses against one PGLite brain.
+ */
+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
+import { existsSync, rmSync, writeFileSync } from 'node:fs';
+import { join } from 'node:path';
+import { makeDoctorHome, runGbrain, type DoctorHome } from './helpers/doctor-json-golden.ts';
+
+const CLI = join(import.meta.dir, '..', 'src', 'cli.ts');
+let h: DoctorHome;
+
+function register(command: string, args: string[]): void {
+ writeFileSync(join(h.home, '.claude.json'), JSON.stringify({
+ mcpServers: { gbrain: { type: 'stdio', command, args, env: { GBRAIN_HOME: h.home, GBRAIN_SKIP_STARTUP_HOOKS: '1' } } },
+ }));
+}
+
+function harnessCheck(run: { json: unknown; stdout: string }): Record<string, unknown> {
+ const report = run.json as { checks?: Array<Record<string, unknown>> } | null;
+ const check = report?.checks?.find(c => c.name === 'harness_wiring');
+ if (!check) throw new Error(`no harness_wiring check in: ${run.stdout.slice(0, 500)}`);
+ return check;
+}
+
+beforeAll(async () => {
+ h = makeDoctorHome('doctor-harness-smoke');
+ const init = await runGbrain(h, ['init', '--pglite', '--no-embedding']);
+ if (init.exitCode !== 0) throw new Error(`gbrain init failed (${init.exitCode}): ${init.stderr}`);
+}, 120_000);
+
+afterAll(() => h?.cleanup());
+
+describe('doctor --only harness_wiring', () => {
+ test('no harness and no registration: information with the install fix', async () => {
+ rmSync(join(h.home, '.claude.json'), { force: true });
+ const run = await runGbrain(h, ['doctor', '--only', 'harness_wiring', '--json']);
+ expect(run.exitCode).toBe(0);
+ const report = run.json as { checks: unknown[] };
+ expect(report.checks).toHaveLength(1);
+ expect(harnessCheck(run)).toMatchObject({ status: 'ok', severity: 'info', readiness_state: 'missing', details: { reason: 'no_harness_detected' } });
+ }, 60_000);
+
+ test('a registered stdio serve answers initialize + tools/list + recall', async () => {
+ register(process.execPath, ['--no-env-file', CLI, 'serve', '--surface', 'verbs']);
+ const run = await runGbrain(h, ['doctor', '--only', 'harness_wiring', '--json']);
+ const check = harnessCheck(run);
+ expect(check, run.stderr).toMatchObject({ status: 'ok', details: { reason: 'wired_running', smoke: 'smoke_passed', harness: 'claude-code' } });
+ expect(String(check.message)).toContain('recall answered');
+ }, 60_000);
+
+ test('a live serve holding the brain lock passes without spawning a second one', async () => {
+ register(process.execPath, ['--no-env-file', CLI, 'serve', '--surface', 'verbs']);
+ const env: Record<string, string> = {};
+ for (const [k, v] of Object.entries(process.env)) if (v !== undefined) env[k] = v;
+ Object.assign(env, { HOME: h.home, GBRAIN_HOME: h.home, GBRAIN_SKIP_STARTUP_HOOKS: '1' });
+ const serve = Bun.spawn([process.execPath, '--no-env-file', CLI, 'serve', '--surface', 'verbs'], { env, stdin: 'pipe', stdout: 'pipe', stderr: 'pipe' });
+ try {
+ const deadline = Date.now() + 30_000;
+ const lockDir = join(h.home, '.gbrain', 'brain.pglite');
+ while (Date.now() < deadline) {
+ const status = await runGbrain(h, ['doctor', '--only', 'harness_wiring', '--json']);
+ const check = harnessCheck(status);
+ const reason = (check.details as Record<string, unknown>)?.reason;
+ if (reason === 'wired_running' && !(check.details as Record<string, unknown>).smoke) {
+ expect(String(check.message)).toContain('holds this brain');
+ return;
+ }
+ await Bun.sleep(500);
+ }
+ throw new Error(`the live serve never showed as the lock owner (lock dir exists: ${existsSync(lockDir)})`);
+ } finally {
+ serve.kill();
+ await serve.exited;
+ }
+ }, 90_000);
+
+ test('a registration whose binary is missing warns with a next step', async () => {
+ register(join(h.home, 'missing', 'gbrain'), ['serve', '--surface', 'verbs']);
+ const run = await runGbrain(h, ['doctor', '--only', 'harness_wiring', '--json']);
+ const check = harnessCheck(run);
+ expect(check.status).toBe('warn');
+ expect(check.fix !== undefined || check.fix_unavailable_reason !== undefined).toBe(true);
+ expect((check.details as Record<string, unknown>).reason).toBe('spawn_failed');
+ }, 60_000);
+
+ test('doctor seeds nothing into the brain', async () => {
+ rmSync(join(h.home, '.claude.json'), { force: true });
+ const run = await runGbrain(h, ['doctor', '--only', 'connection', '--json']);
+ const conn = (run.json as { checks: Array<{ name: string; message: string }> }).checks.find(c => c.name === 'connection');
+ expect(conn?.message).toMatch(/Connected, 0 pages/);
+ }, 60_000);
+});
diff --git a/test/doctor-status-set.test.ts b/test/doctor-status-set.test.ts
new file mode 100644
index 0000000000..eaf72a1ae6
--- /dev/null
+++ b/test/doctor-status-set.test.ts
@@ -0,0 +1,201 @@
+/**
+ * Agent-first operator wave Lane E (E1/E2/E11): doctor checks speak contract v1.
+ *
+ * - status stays ok | warn | fail (schema_version 2); capabilities off by
+ * choice are `ok` + severity:'info' + readiness_state and do not cost score;
+ * - every non-ok check carries a rendered `fix` or a `fix_unavailable_reason`;
+ * - top_issues[] gain the structured `action` next to the legacy `fix` string;
+ * - checkError() is the one "could not run" shape;
+ * - `--only` parsing / engine need; the backup coaching gate; the non-TTY
+ * heartbeat budget; the agent_contract check.
+ */
+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { buildChecks, computeDoctorReport, type Check } from '../src/commands/doctor.ts';
+import { checkError, finalizeCheckFixes, infoCheck } from '../src/commands/doctor/check-fix.ts';
+import { doctorCheckNames, onlyNeedsEngine, parseOnlyChecks } from '../src/commands/doctor/registry.ts';
+import { throttleDoctorHeartbeat } from '../src/commands/doctor/heartbeat.ts';
+import { agentContractCheck } from '../src/commands/doctor/checks/agent-contract.ts';
+import { backupCoachingDue } from '../src/core/backup/status-file.ts';
+import type { ProgressReporter } from '../src/core/progress.ts';
+import { withEnv } from './helpers/with-env.ts';
+
+const fix = { argv: ['gbrain', 'doctor', '--json'], consent: [], actor: 'agent' as const, why: 'diagnose', requires_exclusive: false, docs: 'docs/guides/troubleshooting.md' };
+
+describe('doctor report status set (E2)', () => {
+ test('info checks are ok, keep the health score, and keyless brains report capped_by', () => {
+ const checks: Check[] = [
+ infoCheck('embeddings', 'off by choice', 'disabled_by_choice', fix),
+ { name: 'connection', status: 'ok', message: 'Connected' },
+ ];
+ const report = computeDoctorReport(checks);
+ expect(report.schema_version).toBe(2);
+ expect(report.status).toBe('healthy');
+ expect(report.health_score).toBe(100);
+ expect(report.capped_by).toEqual(['embeddings_disabled']);
+ for (const c of report.checks) expect(['ok', 'warn', 'fail']).toContain(c.status);
+ const emb = report.checks.find(c => c.name === 'embeddings')!;
+ expect(emb).toMatchObject({ status: 'ok', severity: 'info', readiness_state: 'disabled_by_choice' });
+ expect(report.top_issues).toEqual([]);
+ });
+
+ test('a brain without disabled embeddings carries no capped_by', () => {
+ expect(computeDoctorReport([{ name: 'embeddings', status: 'ok', message: 'ok' }]).capped_by).toBeUndefined();
+ });
+
+ test('fixes render for the transport: next, shell-quoted command, absolute docs; top_issues gain action', () => {
+ const report = computeDoctorReport([{ name: 'sync_failures', status: 'warn', message: 'x', fix }]);
+ const rendered = report.checks[0].fix as Record<string, unknown>;
+ expect(rendered).toMatchObject({ next: 'run', command: 'gbrain doctor --json', actor: 'agent' });
+ expect(String(rendered.docs)).toMatch(/^https:\/\//);
+ expect(report.top_issues?.[0]).toMatchObject({ name: 'sync_failures', fix: 'x', action: { next: 'run', command: 'gbrain doctor --json' } });
+ });
+
+ test('an MCP render context rewrites a CLI-only agent fix to tell_user_to_run', () => {
+ const report = computeDoctorReport([{ name: 'sync_failures', status: 'warn', message: 'x', fix }], {
+ render: { transport: 'http', isCallable: () => false, preapproved: () => false },
+ });
+ expect(report.checks[0].fix).toMatchObject({ actor: 'host_admin', next: 'tell_user_to_run' });
+ });
+
+ test('every non-ok check ends with a fix or a fix_unavailable_reason', () => {
+ const out = finalizeCheckFixes([
+ { name: 'a', status: 'warn', message: 'legacy prose' },
+ { name: 'b', status: 'fail', message: 'x', fix_unavailable_reason: 'operator_judgement' },
+ { name: 'c', status: 'ok', message: 'fine' },
+ ]);
+ expect(out[0].fix_unavailable_reason).toBe('unstructured');
+ expect(out[1].fix_unavailable_reason).toBe('operator_judgement');
+ expect(out[2].fix_unavailable_reason).toBeUndefined();
+ });
+});
+
+describe('checkError (E1)', () => {
+ test('keeps the Could-not message and says the check itself failed', () => {
+ expect(checkError('rls', 'check RLS status', new Error('boom'))).toEqual({
+ name: 'rls', status: 'warn', message: 'Could not check RLS status: boom', fix_unavailable_reason: 'check_errored',
+ });
+ expect(checkError('rls', 'check RLS status')).toMatchObject({ message: 'Could not check RLS status' });
+ });
+
+ test('a database access error gets the read-only db-repair diagnosis as fix', () => {
+ const err = Object.assign(new Error('password authentication failed for user "x"'), { code: '28P01' });
+ const c = checkError('rls', 'check RLS status', err);
+ expect(c.fix).toMatchObject({ argv: ['gbrain', 'db-repair'], consent: [], verify: { argv: ['gbrain', 'doctor', '--only', 'rls', '--json'] } });
+ });
+});
+
+describe('doctor --only (E1)', () => {
+ test('parses comma lists, repeats and = form', () => {
+ expect(parseOnlyChecks(['--json'])).toBeNull();
+ expect([...parseOnlyChecks(['--only', 'a,b', '--only=c'])!]).toEqual(['a', 'b', 'c']);
+ });
+
+ test('knows its vocabulary and which checks need the engine', () => {
+ const names = doctorCheckNames();
+ expect(names.has('harness_wiring')).toBe(true);
+ expect(names.has('agent_contract')).toBe(true);
+ expect(onlyNeedsEngine(new Set(['harness_wiring', 'agent_contract']))).toBe(false);
+ expect(onlyNeedsEngine(new Set(['embeddings']))).toBe(true);
+ });
+
+ test('engine-free run returns exactly the requested checks', async () => {
+ const home = mkdtempSync(join(tmpdir(), 'gbrain-only-'));
+ try {
+ await withEnv({ GBRAIN_HOME: home, HOME: home, CLAUDECODE: undefined, CLAUDE_CODE_ENTRYPOINT: undefined, CODEX_SANDBOX: undefined, CODEX_CI: undefined, CODEX_HOME: undefined, OPENCODE: undefined, OPENCODE_PID: undefined }, async () => {
+ const checks = await buildChecks(null, ['--only', 'agent_contract,harness_wiring', '--json']);
+ expect(checks.map(c => c.name).sort()).toEqual(['agent_contract', 'harness_wiring']);
+ });
+ } finally {
+ rmSync(home, { recursive: true, force: true });
+ }
+ });
+});
+
+describe('backup coaching gate (E7)', () => {
+ const now = Date.parse('2026-10-03T00:00:00Z');
+ const day = 86_400_000;
+ test('young and small brains are not coached; 25 items or 7 days are; old caches keep warning', () => {
+ expect(backupCoachingDue({ maturity: { items: 3, since: new Date(now - day).toISOString() } }, now)).toBe(false);
+ expect(backupCoachingDue({ maturity: { items: 25, since: new Date(now - day).toISOString() } }, now)).toBe(true);
+ expect(backupCoachingDue({ maturity: { items: 0, since: new Date(now - 7 * day).toISOString() } }, now)).toBe(true);
+ expect(backupCoachingDue({ maturity: { items: 0, since: null } }, now)).toBe(false);
+ expect(backupCoachingDue({}, now)).toBe(true);
+ });
+});
+
+describe('non-TTY heartbeat budget (E11)', () => {
+ test('at most one heartbeat per gap; a slow check still gets its line', () => {
+ const lines: string[] = [];
+ const inner = { start: () => {}, tick: () => {}, heartbeat: (n: string) => { lines.push(n); }, finish: () => {}, child: () => inner } as unknown as ProgressReporter;
+ let t = 0;
+ const p = throttleDoctorHeartbeat(inner, { tty: false, now: () => t, gapMs: 5_000 });
+ p.start('doctor.db_checks');
+ for (let i = 0; i < 40; i++) { t += 100; p.heartbeat(`check_${i}`); }
+ expect(lines).toEqual([]);
+ t += 6_000;
+ p.heartbeat('slow_check');
+ expect(lines).toEqual(['slow_check']);
+ expect(throttleDoctorHeartbeat(inner, { tty: true })).toBe(inner);
+ });
+});
+
+describe('agent_contract check (E11)', () => {
+ const now = Date.parse('2026-10-03T00:00:00Z');
+ const ts = new Date(now - 3_600_000).toISOString();
+ test('clean log is ok', () => {
+ expect(agentContractCheck([], now)).toMatchObject({ status: 'ok' });
+ });
+ test('refused paid runs and derived-cap stops warn with the user-only preapproval command', () => {
+ const c = agentContractCheck([
+ { ts, command: 'dream', transport: 'cli', code: 'confirmation_required', effects: ['paid'], outcome: 'refused' },
+ { ts, command: 'embed', transport: 'cli', code: 'derived_cap_exhausted', effects: ['paid'], outcome: 'stopped' },
+ { ts, command: 'dream', transport: 'cli', code: 'confirmation_required', effects: ['paid'], outcome: 'preapproved' },
+ ], now);
+ expect(c.status).toBe('warn');
+ expect(c.details).toMatchObject({ consent_refused: 1, derived_cap_exhausted: 1 });
+ expect(c.fix).toMatchObject({ argv: ['gbrain', 'config', 'set', 'consent.preapprove.paid.max_usd_per_run', '<usd>'], actor: 'user', consent: ['paid'] });
+ });
+ test('internal errors warn without a fabricated fix; old events age out', () => {
+ const c = agentContractCheck([
+ { ts, op: 'find_orphans', transport: 'stdio', code: 'internal_error', has_suggestion: true },
+ { ts: new Date(now - 30 * 86_400_000).toISOString(), op: 'x', transport: 'stdio', code: 'internal_error' },
+ ], now);
+ expect(c).toMatchObject({ status: 'warn', fix_unavailable_reason: 'operator_judgement', details: { internal_errors: 1 } });
+ expect(c.message).toContain('find_orphans');
+ });
+});
+
+describe('keyless brain: capability checks are information, not warnings (E2)', () => {
+ let home: string;
+ let engine: PGLiteEngine;
+ beforeAll(async () => {
+ home = mkdtempSync(join(tmpdir(), 'gbrain-keyless-info-'));
+ mkdirSync(join(home, '.gbrain'));
+ writeFileSync(join(home, '.gbrain', 'config.json'), JSON.stringify({ engine: 'pglite', embedding_disabled: true }));
+ engine = new PGLiteEngine();
+ await engine.connect({});
+ await engine.initSchema();
+ });
+ afterAll(async () => {
+ await engine.disconnect();
+ rmSync(home, { recursive: true, force: true });
+ });
+
+ test('embeddings / embedding_provider / embed_staleness / takes_count / fact_take_vectors / cycle_freshness are ok + info', async () => {
+ await withEnv({ GBRAIN_HOME: home, OPENAI_API_KEY: undefined, VOYAGE_API_KEY: undefined, ANTHROPIC_API_KEY: undefined }, async () => {
+ const checks = await buildChecks(engine, ['--only', 'embeddings,embedding_provider,embed_staleness,takes_count,fact_take_vectors,cycle_freshness']);
+ const byName = new Map(checks.map(c => [c.name, c]));
+ for (const name of ['embeddings', 'embedding_provider', 'embed_staleness', 'fact_take_vectors']) {
+ expect(byName.get(name), name).toMatchObject({ status: 'ok', severity: 'info', readiness_state: 'disabled_by_choice' });
+ }
+ expect(byName.get('embeddings')!.fix).toMatchObject({ argv: expect.arrayContaining(['gbrain', 'init', '--force', '--embedding-model']) });
+ expect(byName.get('embedding_provider')!.message).not.toMatch(/migrate embeddings/);
+ expect(byName.get('takes_count')).toMatchObject({ status: 'ok', severity: 'info', fix: { consent: ['paid'] } });
+ expect(byName.get('cycle_freshness')!.status).toBe('ok');
+ });
+ });
+});