Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(closeout): ENG-6 doctor --remediation-plan connects probe-only and reports pending migrations

garrytan76ff62740d3b
diff --git a/scripts/serial-weights.json b/scripts/serial-weights.json
index 540d7307fa..956313d0b9 100644
--- a/scripts/serial-weights.json
+++ b/scripts/serial-weights.json
@@ -93,6 +93,7 @@
"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-remediation-plan-observational.serial.test.ts": 11,
"test/doctor-remote.serial.test.ts": 1,
"test/doctor-report-remote.serial.test.ts": 10,
"test/dream-drain-failure-summary.serial.test.ts": 3,
diff --git a/scripts/test-weights.json b/scripts/test-weights.json
index 4f0445f0a5..7e1184e81d 100644
--- a/scripts/test-weights.json
+++ b/scripts/test-weights.json
@@ -861,6 +861,7 @@
"test/files.test.ts": 710,
"test/filing-audit.test.ts": 5,
"test/find-experts-op.test.ts": 435,
+ "test/fix-routing.test.ts": 3000,
"test/fix-wave-structural.test.ts": 8,
"test/fixtures/preload-guard/guard-probe.test.ts": 2,
"test/fixtures/preload-guard/operator-env-probe.test.ts": 556,
diff --git a/src/cli/commands/doctor.ts b/src/cli/commands/doctor.ts
index a2b031d997..3e7145f028 100644
--- a/src/cli/commands/doctor.ts
+++ b/src/cli/commands/doctor.ts
@@ -31,7 +31,8 @@ export async function run(args: string[], ctx: CliDispatchContext): Promise<void
// (cheap path D7), NOT the full doctor walk.
if (args.includes('--remediation-plan')) {
const { runRemediationPlan } = await import('../../commands/doctor.ts');
- const eng = await connectEngine();
+ // ENG-6: observational — probe-only connect (no migrations, no maintenance); pending migrations are reported in the plan.
+ const eng = await connectEngine({ probeOnly: true });
try { await runRemediationPlan(eng, args); } finally { await finishCliTeardown({ engine: eng }); }
return;
}
diff --git a/src/commands/doctor/remediate.ts b/src/commands/doctor/remediate.ts
index 5ac0d15a3a..ff44d27117 100644
--- a/src/commands/doctor/remediate.ts
+++ b/src/commands/doctor/remediate.ts
@@ -31,6 +31,7 @@ import { repairPreviewCommand, repairSpec, type ExplicitRepairNotice } from '../
import { runWaveChecks, waveRepairKind, type WaveFinding } from './wave-checks.ts';
import { derivedCapExhaustedError, type CapSource } from '../../core/consent.ts';
import { previewRemediationPlan, remediateConsent, remediateFlags, remediationPlanHash, type RemediateFlags } from './remediate-consent.ts';
+import { cliRenderContext, renderNotice, type Notice } from '../../core/agent-output.ts';
export const REMEDIATE_HELP = `Usage: gbrain doctor --remediation-plan [--target-score <n>] [--no-embed] [--json]
gbrain doctor --remediate [--yes [--expect <plan_hash>]] [--include-repairs] [--max-usd <n>] [--target-score <n>]
@@ -102,23 +103,55 @@ export function combinedRemediateCommand(plan: Pick<RemediationPlanShape, 'est_t
+ `${opts.noEmbed ? ' --no-embed' : ''}${repairs.length && opts.planHash ? ` --expect ${opts.planHash}` : ''}`;
}
+/**
+ * ENG-6: the plan is observational. The doctor CLI connects probe-only (no
+ * migrations, no maintenance), so a brain whose schema is behind is reported,
+ * not upgraded: a `migrations_pending` safety notice naming the command that
+ * applies them (`doctor --remediate` also applies them, after consent).
+ * Mounts never auto-migrate from the CLI, so only the host brain reports it.
+ */
+export async function pendingMigrationsNotice(engine: BrainEngine): Promise<Notice | null> {
+ const { hasPendingMigrations, LATEST_VERSION } = await import('../../core/migrate.ts');
+ const { resolveBrainId } = await import('../../core/brain-resolver.ts');
+ const { getCliOptions } = await import('../../core/cli-options.ts');
+ try { if (resolveBrainId(getCliOptions().brain) !== 'host') return null; } catch { return null; }
+ if (!(await hasPendingMigrations(engine))) return null;
+ const current = await engine.getConfig('version').catch(() => null);
+ return {
+ code: 'migrations_pending', kind: 'safety',
+ why: `Schema migrations are pending (brain at v${current ?? 'unknown'}, this gbrain expects v${LATEST_VERSION}). `
+ + 'The plan was computed without applying them; `doctor --remediate` applies them after consent, before any step runs.',
+ fix: { argv: ['gbrain', 'apply-migrations', '--yes'], consent: [], actor: 'agent', requires_exclusive: true,
+ why: 'Applies the pending schema migrations (the same ones every command applies on connect).',
+ verify: { argv: ['gbrain', 'doctor', '--only', 'schema_version', '--json'] } },
+ };
+}
+
/**
* CLI wrapper around computeRemediationPlan. Read-only — never enqueues,
- * never mutates. JSON adds a `command` per job step, the repair steps and
- * the combined command to the library's stable envelope.
+ * never mutates, never migrates (the engine is probe-only). JSON adds a
+ * `command` per job step, the repair steps, the combined command and a
+ * `notices` array (pending migrations) to the library's stable envelope.
*/
export async function runRemediationPlan(engine: BrainEngine, args: string[]): Promise<void> {
if (args.includes('--help') || args.includes('-h')) { console.log(REMEDIATE_HELP); return; }
const { computeRemediationPlan } = await import('../../core/remediation/index.ts');
const targetScore = parseIntFlag(args, '--target-score') ?? 90;
const noEmbed = args.includes('--no-embed');
+ const migrations = await pendingMigrationsNotice(engine);
const plan = await computeRemediationPlan(engine, { targetScore, repairs: { noEmbed } });
const planHash = plan.repair_steps?.length ? await remediationPlanHash(engine, args, plan) : undefined;
if (args.includes('--json')) {
await writeJsonDocument(JSON.stringify({ ...plan, plan: plan.plan.map(step => ({ ...step, command: jobStepCommand(step) })),
- combined_command: combinedRemediateCommand(plan, plan.target_unreachable ? plan.max_reachable_score : targetScore, { noEmbed, planHash }), ...(planHash ? { plan_hash: planHash } : {}) }, null, 2));
+ combined_command: combinedRemediateCommand(plan, plan.target_unreachable ? plan.max_reachable_score : targetScore, { noEmbed, planHash }), ...(planHash ? { plan_hash: planHash } : {}),
+ ...(migrations ? { notices: [renderNotice(migrations, cliRenderContext())] } : {}) }, null, 2));
return;
}
+ if (migrations) {
+ const fix = renderNotice(migrations, cliRenderContext()).fix;
+ console.log(`Schema migrations pending: ${migrations.why}`);
+ if (fix?.command) console.log(` apply: ${fix.command}`);
+ }
for (const line of renderRemediationPlanLines(plan, targetScore, { noEmbed, planHash })) console.log(line);
}
diff --git a/test/doctor-remediation-plan-observational.serial.test.ts b/test/doctor-remediation-plan-observational.serial.test.ts
new file mode 100644
index 0000000000..61e441226f
--- /dev/null
+++ b/test/doctor-remediation-plan-observational.serial.test.ts
@@ -0,0 +1,66 @@
+/**
+ * ENG-6: `gbrain doctor --remediation-plan` is observational. On a brain whose
+ * schema is behind, it connects probe-only, leaves the schema version
+ * unchanged, and reports the pending migrations as a `migrations_pending`
+ * safety notice whose fix applies them (the remediate consent path already
+ * connects this way, test/agent-journey.serial.test.ts).
+ *
+ * Serial: real CLI subprocesses against a temp PGLite brain.
+ */
+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 { LATEST_VERSION, hasPendingMigrations } from '../src/core/migrate.ts';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { gb, oneDocument } from './helpers/agent-journey.ts';
+
+async function withBrain<T>(home: string, fn: (engine: PGLiteEngine) => Promise<T>): Promise<T> {
+ const engine = new PGLiteEngine();
+ await engine.connect({ engine: 'pglite', database_path: join(home, '.gbrain', 'brain.pglite') });
+ try { return await fn(engine); } finally { await engine.disconnect(); }
+}
+
+describe('doctor --remediation-plan on a pending-migration brain', () => {
+ let home = '';
+ const pending = String(LATEST_VERSION - 1);
+ beforeAll(async () => {
+ home = mkdtempSync(join(tmpdir(), 'gbrain-plan-observational-'));
+ expect((await gb(home, ['init', '--pglite', '--no-embedding', '--json'], { timeoutMs: 120_000 })).exitCode).toBe(0);
+ await withBrain(home, engine => engine.setConfig('version', pending));
+ }, 150_000);
+ afterAll(() => { rmSync(home, { recursive: true, force: true }); });
+
+ test('--json: schema version unchanged; the plan carries a migrations_pending notice with the apply fix', async () => {
+ const r = await gb(home, ['doctor', '--remediation-plan', '--json']);
+ expect(r.exitCode, r.stderr.slice(-2000)).toBe(0);
+ const doc = oneDocument(r, 'doctor --remediation-plan --json');
+ expect(typeof doc.brain_score_current).toBe('number');
+ const notice = (doc.notices as Array<Record<string, any>>).find(n => n.code === 'migrations_pending')!;
+ expect(notice).toBeTruthy();
+ expect(notice.kind).toBe('safety');
+ expect(notice.why).toContain(`v${pending}`);
+ expect(notice.fix.argv).toEqual(['gbrain', 'apply-migrations', '--yes']);
+ expect(notice.fix.next).toBe('run');
+ await withBrain(home, async engine => {
+ expect(await engine.getConfig('version')).toBe(pending);
+ expect(await hasPendingMigrations(engine)).toBe(true);
+ });
+ }, 150_000);
+
+ test('human output names the pending migrations; still nothing migrated', async () => {
+ const r = await gb(home, ['doctor', '--remediation-plan']);
+ expect(r.exitCode, r.stderr.slice(-2000)).toBe(0);
+ expect(r.stdout).toContain('Schema migrations pending');
+ expect(r.stdout).toContain('apply: gbrain apply-migrations --yes');
+ await withBrain(home, async engine => expect(await engine.getConfig('version')).toBe(pending));
+ }, 150_000);
+
+ test('following the notice fix migrates; the next plan has no notice', async () => {
+ const applied = await gb(home, ['apply-migrations', '--yes', '--no-autopilot-install'], { timeoutMs: 240_000 });
+ expect(applied.exitCode, applied.stderr.slice(-2000)).toBe(0);
+ await withBrain(home, async engine => expect(await engine.getConfig('version')).toBe(String(LATEST_VERSION)));
+ const doc = oneDocument(await gb(home, ['doctor', '--remediation-plan', '--json']), 'plan after migrating');
+ expect(doc.notices).toBeUndefined();
+ }, 300_000);
+});