Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

feat(doctor): harness_wiring smoke check and agent_contract check (G5 step 2, E11)

garrytana28728a41276
diff --git a/src/commands/doctor/checks/agent-contract.ts b/src/commands/doctor/checks/agent-contract.ts
new file mode 100644
index 0000000000..75bdf15a1f
--- /dev/null
+++ b/src/commands/doctor/checks/agent-contract.ts
@@ -0,0 +1,92 @@
+/**
+ * `agent_contract` (agent-first operator wave E11): reads the bounded
+ * agent-contract event log (`readAgentContractEvents()`, written by dispatch,
+ * `renderCliError`, `requireConsent`, the budget tracker and the `--json`
+ * guard) and warns when agents recently hit a dead end: `internal_error` or
+ * suggestion-less envelopes, unattended runs refused for consent, derived
+ * spend caps exhausted, or a `--json` command that printed no document. The
+ * fix is the exact preapproval command when one would have let the run
+ * proceed. Engine-free, read-only; the log never holds params or messages.
+ */
+import { readAgentContractEvents, type AgentContractEvent } from '../../../core/agent-contract-log.ts';
+import { PREAPPROVE_PAID_MAX_USD_PER_RUN, PREAPPROVE_PERSISTENT_INSTALL, preapprovalCommand } from '../../../core/consent-preapproval.ts';
+import type { Action } from '../../../core/agent-output.ts';
+import type { Check } from '../../doctor.ts';
+import { doctorVerify } from '../check-fix.ts';
+import type { DoctorEntry } from '../context.ts';
+
+const NAME = 'agent_contract';
+export const AGENT_CONTRACT_WINDOW_DAYS = 7;
+const USD_INPUT = 'usd';
+
+type Event = AgentContractEvent & { ts: string };
+
+function who(e: Event): string { return e.op ?? e.command ?? 'unknown'; }
+
+function top(events: readonly Event[], n = 3): string {
+ const counts = new Map<string, number>();
+ for (const e of events) counts.set(who(e), (counts.get(who(e)) ?? 0) + 1);
+ return [...counts.entries()].sort((a, b) => b[1] - a[1] || a[0].localeCompare(b[0])).slice(0, n).map(([k, v]) => `${k}×${v}`).join(', ');
+}
+
+function preapprovePaid(): Action {
+ return {
+ argv: preapprovalCommand(PREAPPROVE_PAID_MAX_USD_PER_RUN, '<usd>'),
+ consent: ['paid'], actor: 'user', requires_exclusive: false, verify: doctorVerify(NAME),
+ inputs: [{ name: USD_INPUT, how: 'Ask the user the most gbrain may spend per run without asking first (for example 1).' }],
+ why: 'Unattended paid runs stopped for consent or hit their derived cap. A per-run preapproval lets them proceed up to that amount; only the user may grant it.',
+ user_message: 'Some background gbrain work stopped because it would spend money and nobody was there to approve it. Want to let gbrain spend up to a fixed amount per run without asking? If so, run this with your limit in dollars.',
+ docs: 'docs/protocol/AGENT_OPERATOR_v1.md',
+ };
+}
+
+function preapproveInstall(): Action {
+ return {
+ argv: preapprovalCommand(PREAPPROVE_PERSISTENT_INSTALL, 'true'),
+ consent: ['persistent_install'], actor: 'user', requires_exclusive: false, verify: doctorVerify(NAME),
+ why: 'Unattended runs that install background services or harness config stopped for consent. This preapproval covers installs only, never credentials.',
+ user_message: 'gbrain wanted to install a background service and nobody was there to approve it. Run this if you want such installs to proceed without asking.',
+ docs: 'docs/protocol/AGENT_OPERATOR_v1.md',
+ };
+}
+
+/** Pure: the check for a list of events (newest last), relative to `now`. */
+export function agentContractCheck(events: readonly Event[], now = Date.now()): Check {
+ const since = now - AGENT_CONTRACT_WINDOW_DAYS * 86_400_000;
+ const recent = events.filter((e) => Date.parse(e.ts) >= since);
+ const faults = recent.filter((e) => e.code === 'internal_error' || e.code === 'internal' || e.has_suggestion === false);
+ const refused = recent.filter((e) => e.code === 'confirmation_required' && (e.outcome === 'refused' || e.outcome === 'declined'));
+ const paidRefused = refused.filter((e) => e.effects?.includes('paid'));
+ const installRefused = refused.filter((e) => e.effects?.includes('persistent_install') && !e.effects.includes('paid'));
+ const capped = recent.filter((e) => e.code === 'derived_cap_exhausted');
+ const noDoc = recent.filter((e) => e.code === 'json_document_missing');
+ const details = {
+ window_days: AGENT_CONTRACT_WINDOW_DAYS, events: recent.length,
+ internal_errors: faults.length, consent_refused: refused.length, derived_cap_exhausted: capped.length, json_document_missing: noDoc.length,
+ };
+ const parts: string[] = [];
+ if (faults.length) parts.push(`${faults.length} error(s) reached an agent without a specific next step (${top(faults)}); report them to the user with \`gbrain doctor --json\` output`);
+ if (refused.length) parts.push(`${refused.length} unattended run(s) stopped for consent (${top(refused)})`);
+ if (capped.length) parts.push(`${capped.length} paid run(s) hit their derived spend cap (${top(capped)})`);
+ if (noDoc.length) parts.push(`${noDoc.length} \`--json\` run(s) printed no JSON document (${top(noDoc)})`);
+ if (parts.length === 0) {
+ return { name: NAME, status: 'ok', message: `No agent dead ends in the last ${AGENT_CONTRACT_WINDOW_DAYS} days (${recent.length} non-success event(s) logged).`, details };
+ }
+ const fix = paidRefused.length || capped.length ? preapprovePaid() : installRefused.length ? preapproveInstall() : undefined;
+ return {
+ name: NAME, status: 'warn', message: `Last ${AGENT_CONTRACT_WINDOW_DAYS} days: ${parts.join('; ')}.`, details,
+ ...(fix ? { fix } : { fix_unavailable_reason: 'operator_judgement' as const }),
+ };
+}
+
+async function runAgentContract(): Promise<Check[]> {
+ const checks: Check[] = [];
+ checks.push(agentContractCheck(readAgentContractEvents()));
+ return checks;
+}
+
+export const agentContractEntry: DoctorEntry = {
+ name: 'agent_contract',
+ emits: ['agent_contract'],
+ run: runAgentContract,
+};
diff --git a/src/commands/doctor/checks/harness-wiring.ts b/src/commands/doctor/checks/harness-wiring.ts
new file mode 100644
index 0000000000..f2ae172b21
--- /dev/null
+++ b/src/commands/doctor/checks/harness-wiring.ts
@@ -0,0 +1,271 @@
+/**
+ * `harness_wiring` (agent-first operator wave G5 step 2 / Lane E): is an agent
+ * harness wired to this brain, and does the registration actually answer?
+ *
+ * Engine-free and read-only. The full doctor run only READS the registration
+ * (Claude Code `~/.claude.json`, Codex `config.toml`, opencode `opencode.json`)
+ * and reports it; `gbrain doctor --only harness_wiring` adds the smoke test:
+ * a live `gbrain serve` holding this brain's lock → pass (`wired_running`);
+ * otherwise spawn the registered argv (15 s bound) and run initialize +
+ * tools/list + `recall {query:"gbrain install check", limit:1}` (an empty
+ * result passes). A `gbrain_status` reply (status-only serve) is reported with
+ * its reason and fix. Doctor writes nothing and seeds nothing.
+ */
+import { existsSync, readFileSync } from 'node:fs';
+import { homedir } from 'node:os';
+import { isAbsolute, join } from 'node:path';
+import { gbrainPath, loadConfig } from '../../../core/config.ts';
+import { peekLock } from '../../../core/pglite-lock.ts';
+import { harnessWiringEntry, type ReadinessHarness } from '../../../core/readiness.ts';
+import { agentProcessMarker } from '../../../core/interaction.ts';
+import { resolveGbrainBin } from '../../../core/gbrain-bin.ts';
+import type { Action } from '../../../core/agent-output.ts';
+import type { Check } from '../../doctor.ts';
+import { checkError, doctorVerify, infoCheck } from '../check-fix.ts';
+import type { DoctorContext, DoctorEntry } from '../context.ts';
+
+export const HARNESS_SMOKE_TIMEOUT_MS = 15_000;
+const NAME = 'harness_wiring';
+const SMOKE_QUERY = 'gbrain install check';
+const STATUS_TOOL = 'gbrain_status';
+const RECALL_TOOL = 'recall';
+
+export interface HarnessRegistration {
+ harness: ReadinessHarness;
+ /** Where it was read from (config file path). */
+ source: string;
+ kind: 'stdio' | 'http';
+ command?: string;
+ args?: string[];
+ env?: Record<string, string>;
+ url?: string;
+}
+
+const HARNESS_LABEL: Record<ReadinessHarness, string> = { 'claude-code': 'Claude Code', codex: 'Codex', opencode: 'opencode' };
+
+function home(): string { return process.env.HOME || homedir(); }
+
+function readJson(path: string): Record<string, unknown> | null {
+ if (!existsSync(path)) return null;
+ try {
+ const text = readFileSync(path, 'utf8').replace(/^\s*\/\/.*$/gm, '');
+ return JSON.parse(text) as Record<string, unknown>;
+ } catch {
+ return null;
+ }
+}
+
+function strings(v: unknown): string[] | undefined {
+ return Array.isArray(v) && v.every((x) => typeof x === 'string') ? (v as string[]) : undefined;
+}
+
+function stringRecord(v: unknown): Record<string, string> | undefined {
+ if (!v || typeof v !== 'object') return undefined;
+ const out: Record<string, string> = {};
+ for (const [k, val] of Object.entries(v as Record<string, unknown>)) if (typeof val === 'string') out[k] = val;
+ return out;
+}
+
+function claudeRegistration(name: string): HarnessRegistration | null {
+ const path = join(home(), '.claude.json');
+ const cfg = readJson(path) as { mcpServers?: Record<string, unknown>; projects?: Record<string, { mcpServers?: Record<string, unknown> }> } | null;
+ if (!cfg) return null;
+ const candidates = [cfg.mcpServers?.[name], ...Object.values(cfg.projects ?? {}).map((p) => p?.mcpServers?.[name])];
+ const entry = candidates.find((c) => c && typeof c === 'object') as Record<string, unknown> | undefined;
+ if (!entry) return null;
+ if (typeof entry.url === 'string') return { harness: 'claude-code', source: path, kind: 'http', url: entry.url };
+ if (typeof entry.command !== 'string') return null;
+ return { harness: 'claude-code', source: path, kind: 'stdio', command: entry.command, args: strings(entry.args) ?? [], env: stringRecord(entry.env) };
+}
+
+/** `[mcp_servers.<name>]` from Codex's config.toml: the `command`/`args`/`url`/`env` keys only. */
+export function parseCodexRegistration(text: string, name: string, source: string): HarnessRegistration | null {
+ const lines = text.replace(/\r\n/g, '\n').split('\n');
+ const header = new RegExp(`^\\[mcp_servers\\.(?:${name}|"${name}")\\]\\s*$`);
+ const start = lines.findIndex((l) => header.test(l.trim()));
+ if (start < 0) return null;
+ const body: string[] = [];
+ for (let i = start + 1; i < lines.length && !lines[i].trim().startsWith('['); i++) body.push(lines[i].trim());
+ const value = (key: string): string | undefined => {
+ const line = body.find((l) => new RegExp(`^${key}\\s*=`).test(l));
+ return line?.slice(line.indexOf('=') + 1).trim();
+ };
+ const parse = (raw: string | undefined): unknown => {
+ if (raw === undefined) return undefined;
+ try { return JSON.parse(raw.replace(/^'(.*)'$/, '"$1"')); } catch { return undefined; }
+ };
+ const url = parse(value('url'));
+ if (typeof url === 'string') return { harness: 'codex', source, kind: 'http', url };
+ const command = parse(value('command'));
+ if (typeof command !== 'string') return null;
+ const envLine = value('env');
+ const env = envLine ? stringRecord(parse(envLine.replace(/(\w+)\s*=/g, '"$1":').replace(/^\{/, '{'))) : undefined;
+ return { harness: 'codex', source, kind: 'stdio', command, args: strings(parse(value('args'))) ?? [], env };
+}
+
+function codexRegistration(name: string): HarnessRegistration | null {
+ const path = join(process.env.CODEX_HOME || join(home(), '.codex'), 'config.toml');
+ if (!existsSync(path)) return null;
+ try { return parseCodexRegistration(readFileSync(path, 'utf8'), name, path); } catch { return null; }
+}
+
+function opencodeRegistration(name: string): HarnessRegistration | null {
+ const path = join(process.env.XDG_CONFIG_HOME || join(home(), '.config'), 'opencode', 'opencode.json');
+ const cfg = readJson(path) as { mcp?: Record<string, Record<string, unknown>> } | null;
+ const entry = cfg?.mcp?.[name];
+ if (!entry) return null;
+ if (typeof entry.url === 'string') return { harness: 'opencode', source: path, kind: 'http', url: entry.url };
+ const argv = strings(entry.command);
+ if (!argv?.length) return null;
+ return { harness: 'opencode', source: path, kind: 'stdio', command: argv[0], args: argv.slice(1), env: stringRecord(entry.environment) };
+}
+
+/** Every gbrain MCP registration this machine's harness configs carry. */
+export function readHarnessRegistrations(name = 'gbrain'): HarnessRegistration[] {
+ return [claudeRegistration(name), codexRegistration(name), opencodeRegistration(name)].filter((r): r is HarnessRegistration => r !== null);
+}
+
+/** Harnesses installed on this machine: the active agent marker, else their config files. */
+function detectedHarnesses(): ReadinessHarness[] {
+ const marker = agentProcessMarker();
+ if (marker) {
+ if (marker.startsWith('CLAUDE')) return ['claude-code'];
+ if (marker.startsWith('CODEX')) return ['codex'];
+ return ['opencode'];
+ }
+ const out: ReadinessHarness[] = [];
+ if (existsSync(join(home(), '.claude.json')) || existsSync(join(home(), '.claude'))) out.push('claude-code');
+ if (existsSync(process.env.CODEX_HOME || join(home(), '.codex'))) out.push('codex');
+ if (existsSync(join(process.env.XDG_CONFIG_HOME || join(home(), '.config'), 'opencode'))) out.push('opencode');
+ return out;
+}
+
+function brainLock(): ReturnType<typeof peekLock> | null {
+ try {
+ const cfg = loadConfig();
+ if (!cfg || cfg.engine !== 'pglite' || cfg.database_url || cfg.remote_mcp) return null;
+ return peekLock(cfg.database_path ?? gbrainPath('brain.pglite'));
+ } catch {
+ return null;
+ }
+}
+
+function describeRegistration(r: HarnessRegistration): string {
+ return r.kind === 'http' ? `${HARNESS_LABEL[r.harness]} → ${r.url}` : `${HARNESS_LABEL[r.harness]} → ${[r.command, ...(r.args ?? [])].join(' ')}`;
+}
+
+function rewireFix(r: HarnessRegistration): Action | undefined {
+ const bin = resolveGbrainBin();
+ return harnessWiringEntry({ transport: 'cli', harnesses: [r.harness], lockOwner: null, gbrainBin: bin }).fix;
+}
+
+interface SmokeOutcome { ok: boolean; reason: string; message: string; fix?: Action }
+
+/** Spawn the registered stdio argv and run initialize + tools/list + recall. Never throws. */
+export async function smokeStdioRegistration(r: HarnessRegistration, timeoutMs = HARNESS_SMOKE_TIMEOUT_MS): Promise<SmokeOutcome> {
+ const { Client } = await import('@modelcontextprotocol/sdk/client/index.js');
+ const { StdioClientTransport } = await import('@modelcontextprotocol/sdk/client/stdio.js');
+ const env: Record<string, string> = {};
+ for (const [k, v] of Object.entries(process.env)) if (typeof v === 'string') env[k] = v;
+ Object.assign(env, r.env ?? {});
+ const transport = new StdioClientTransport({ command: r.command!, args: r.args ?? [], env, stderr: 'pipe' });
+ const client = new Client({ name: 'gbrain-doctor-harness-smoke', version: '1' }, { capabilities: {} });
+ let timer: ReturnType<typeof setTimeout> | undefined;
+ const timeout = new Promise<SmokeOutcome>((resolve) => {
+ timer = setTimeout(() => resolve({ ok: false, reason: 'smoke_timeout', message: `The registered server did not answer within ${timeoutMs / 1000}s.` }), timeoutMs);
+ });
+ const run = (async (): Promise<SmokeOutcome> => {
+ await client.connect(transport);
+ const tools = (await client.listTools()).tools.map((t) => t.name);
+ if (tools.includes(STATUS_TOOL) && !tools.includes(RECALL_TOOL)) {
+ const res = await client.callTool({ name: STATUS_TOOL, arguments: {} });
+ const text = (res.content as Array<{ type: string; text?: string }>)?.[0]?.text ?? '';
+ let status: { reason?: string; why?: string; fix?: Action } = {};
+ try { status = JSON.parse(text); } catch { /* prose status */ }
+ return { ok: false, reason: status.reason ?? 'status_only', message: `The server started in status-only mode: ${status.why ?? text}`, ...(status.fix ? { fix: status.fix } : {}) };
+ }
+ if (!tools.includes(RECALL_TOOL)) return { ok: false, reason: 'recall_missing', message: `The server answered but does not list recall (tools: ${tools.slice(0, 8).join(', ')}).` };
+ const res = await client.callTool({ name: RECALL_TOOL, arguments: { query: SMOKE_QUERY, limit: 1 } });
+ if (res.isError) {
+ const text = (res.content as Array<{ type: string; text?: string }>)?.[0]?.text ?? '';
+ return { ok: false, reason: 'recall_failed', message: `recall returned an error: ${text.slice(0, 300)}` };
+ }
+ return { ok: true, reason: 'smoke_passed', message: `initialize, tools/list (${tools.length} tools) and recall answered.` };
+ })().catch((e: unknown): SmokeOutcome => ({
+ ok: false, reason: 'spawn_failed', message: `The registered server did not complete the MCP handshake: ${e instanceof Error ? e.message : String(e)}`,
+ }));
+ try {
+ return await Promise.race([run, timeout]);
+ } finally {
+ clearTimeout(timer);
+ await client.close().catch(() => {});
+ await transport.close().catch(() => {});
+ }
+}
+
+async function smoke(r: HarnessRegistration): Promise<Check> {
+ const details = { harness: r.harness, registration: r.source, kind: r.kind };
+ const lock = brainLock();
+ if (lock?.held && lock.isServe) {
+ const transport = lock.http ? 'serve --http' : 'stdio serve';
+ if (r.kind === 'http' && !lock.http) {
+ const fix = rewireFix(r);
+ return { name: NAME, status: 'warn', message: `${describeRegistration(r)} is registered over HTTP, but the live server (PID ${lock.pid}) is a stdio serve, so the HTTP endpoint cannot answer.`,
+ details: { ...details, reason: 'http_serve_missing' }, ...(fix ? { fix } : { fix_unavailable_reason: 'no_safe_automatic_fix' as const }) };
+ }
+ return { name: NAME, status: 'ok', message: `${describeRegistration(r)}: a live gbrain ${transport} (PID ${lock.pid}) holds this brain.`, details: { ...details, reason: 'wired_running' } };
+ }
+ if (r.kind === 'http') {
+ return { name: NAME, status: 'warn', message: `${describeRegistration(r)} is registered, but no \`gbrain serve --http\` is running on this machine, so new sessions get no memory tools.`,
+ details: { ...details, reason: 'http_serve_missing' },
+ fix: { argv: ['gbrain', 'serve', '--http'], consent: [], actor: 'user', requires_exclusive: true, verify: doctorVerify(NAME),
+ why: 'The registration points at the shared HTTP server; it must be running (a long-lived process, so the user or a service manager starts it).',
+ user_message: 'gbrain\'s shared memory server is not running. Please start `gbrain serve --http` (or its service) so your agent sessions can reach memory.' } };
+ }
+ const outcome = await smokeStdioRegistration(r);
+ if (outcome.ok) return { name: NAME, status: 'ok', message: `${describeRegistration(r)}: ${outcome.message}`, details: { ...details, reason: 'wired_running', smoke: outcome.reason } };
+ const fix = outcome.fix ?? rewireFix(r);
+ return { name: NAME, status: 'warn', message: `${describeRegistration(r)}: ${outcome.message}`, details: { ...details, reason: outcome.reason },
+ ...(fix ? { fix } : { fix_unavailable_reason: 'no_safe_automatic_fix' as const }) };
+}
+
+/** Registration read (full run) or registration read + smoke (`--only harness_wiring`). */
+export async function harnessWiringCheck(opts: { smoke: boolean }): Promise<Check> {
+ const regs = readHarnessRegistrations();
+ if (regs.length === 0) {
+ const harnesses = detectedHarnesses();
+ const lock = brainLock();
+ const lockOwner = lock?.held && lock.isServe && lock.pid !== undefined ? { pid: lock.pid, transport: lock.http ? 'http' as const : 'stdio' as const, is_self: false } : null;
+ const entry = harnessWiringEntry({ transport: 'cli', harnesses, lockOwner, gbrainBin: resolveGbrainBin() });
+ if (harnesses.length === 0) return infoCheck(NAME, `${entry.why} Wire one when the user picks an agent app.`, entry.state, entry.fix, { reason: entry.reason });
+ return { name: NAME, status: 'warn', message: `${harnesses.map((h) => HARNESS_LABEL[h]).join(', ')} ${harnesses.length > 1 ? 'are' : 'is'} installed but ${harnesses.length > 1 ? 'have' : 'has'} no gbrain MCP registration, so its sessions get no memory tools. ${entry.why}`,
+ details: { reason: entry.reason }, ...(entry.fix ? { fix: entry.fix } : { fix_unavailable_reason: 'no_safe_automatic_fix' as const }) };
+ }
+ const bare = regs.find((r) => r.kind === 'stdio' && r.command && !isAbsolute(r.command) && r.command !== 'bun' && r.command !== 'node');
+ if (bare) {
+ const fix = rewireFix(bare);
+ return { name: NAME, status: 'warn', message: `${describeRegistration(bare)} registers a bare \`${bare.command}\`; GUI-launched harnesses inherit no PATH, so it may not start. Re-register with the absolute binary.`,
+ details: { harness: bare.harness, registration: bare.source, reason: 'bare_binary' }, ...(fix ? { fix } : { fix_unavailable_reason: 'no_safe_automatic_fix' as const }) };
+ }
+ const active = detectedHarnesses()[0];
+ const primary = regs.find((r) => r.harness === active) ?? regs[0];
+ if (opts.smoke) return smoke(primary);
+ return { name: NAME, status: 'ok', message: `Registered: ${regs.map(describeRegistration).join('; ')}. Smoke-test it with \`gbrain doctor --only harness_wiring\`.`,
+ details: { reason: 'registration_unverified', harnesses: regs.map((r) => r.harness) } };
+}
+
+async function runHarnessWiring(ctx: DoctorContext): Promise<Check[]> {
+ const checks: Check[] = [];
+ try {
+ checks.push(await harnessWiringCheck({ smoke: !!ctx.only?.has('harness_wiring') }));
+ } catch (e) {
+ checks.push(checkError('harness_wiring', 'read the harness registrations', e));
+ }
+ return checks;
+}
+
+export const harnessWiringDoctorEntry: DoctorEntry = {
+ name: 'harness_wiring',
+ emits: ['harness_wiring'],
+ run: runHarnessWiring,
+};
diff --git a/src/commands/doctor/registry.ts b/src/commands/doctor/registry.ts
index c0e85db21b..c20b98d777 100644
--- a/src/commands/doctor/registry.ts
+++ b/src/commands/doctor/registry.ts
@@ -87,6 +87,8 @@ import { factTakeVectorsEntry } from './checks/vector-coverage.ts';
import { decideHealthEntry } from './checks/decide.ts';
import { unlinkedFactsEntry } from './checks/unlinked-facts.ts';
import { plannerStatsEntry } from './checks/planner-stats.ts';
+import { harnessWiringDoctorEntry } from './checks/harness-wiring.ts';
+import { agentContractEntry } from './checks/agent-contract.ts';
import { STOP_DOCTOR, type DoctorContext, type DoctorEntry } from './context.ts';
import type { Check } from '../doctor.ts';
import { infoCheck } from './check-fix.ts';
@@ -105,6 +107,8 @@ export const DOCTOR_CHECK_REGISTRY: readonly DoctorEntry[] = [
homeDirInWorktreeEntry,
defaultSourcePathEntry,
embeddingKeySourceEntry,
+ harnessWiringDoctorEntry,
+ agentContractEntry,
pgliteDataDirEntry,
projectionResidentEntry,
offlineConnectionEntry,
diff --git a/src/core/doctor-categories.ts b/src/core/doctor-categories.ts
index d1d979ea06..697a05bfe1 100644
--- a/src/core/doctor-categories.ts
+++ b/src/core/doctor-categories.ts
@@ -184,6 +184,8 @@ export const SKILL_CHECK_NAMES: ReadonlySet<string> = new Set([
* Infrastructure liveness signals. DB, workers, OAuth, RLS, locks, providers.
*/
export const OPS_CHECK_NAMES: ReadonlySet<string> = new Set([
+ // Agent operator wave: is an agent harness wired to this brain (registration read; --only adds the smoke test).
+ 'harness_wiring',
// F4b: PGLite row-delta planner statistics / Postgres autovacuum ANALYZE lag on the hot tables.
'planner_stats_stale',
'alternative_providers',
@@ -267,6 +269,8 @@ export const OPS_CHECK_NAMES: ReadonlySet<string> = new Set([
* housekeeping. Default category for unknown names (with stderr warn).
*/
export const META_CHECK_NAMES: ReadonlySet<string> = new Set([
+ // Agent operator wave E11: recent agent dead ends from the agent-contract event log.
+ 'agent_contract',
'cycle_phase_scope',
'default_source_local_path',
'eval_capture',
diff --git a/test/doctor-early-stop-golden.serial.test.ts b/test/doctor-early-stop-golden.serial.test.ts
index 4b56aaace2..6f270fdc7f 100644
--- a/test/doctor-early-stop-golden.serial.test.ts
+++ b/test/doctor-early-stop-golden.serial.test.ts
@@ -23,7 +23,7 @@ import type { BrainEngine } from '../src/core/engine.ts';
import { defineNormalizer, expectGolden, expectNormalizerStable, mapStrings, scrubKeys } from './helpers/golden.ts';
import { makeDoctorHome, normalizeDoctorText, type DoctorHome } from './helpers/doctor-json-golden.ts';
-const ENV_KEYS = ['PATH', 'GBRAIN_HOME', 'HOME', 'GBRAIN_AUDIT_DIR', 'GBRAIN_SYNC_FAILURES_DIR', 'DATABASE_URL', 'GBRAIN_DATABASE_URL'] as const;
+const ENV_KEYS = ['PATH', 'GBRAIN_HOME', 'HOME', 'GBRAIN_AUDIT_DIR', 'GBRAIN_SYNC_FAILURES_DIR', 'DATABASE_URL', 'GBRAIN_DATABASE_URL', 'CLAUDECODE', 'CLAUDE_CODE_ENTRYPOINT', 'CODEX_SANDBOX', 'CODEX_CI', 'CODEX_HOME', 'OPENCODE', 'OPENCODE_PID', 'XDG_CONFIG_HOME'] as const;
let saved: Record<string, string | undefined> = {};
const homes: DoctorHome[] = [];
@@ -60,6 +60,8 @@ function enterHome(config?: Record<string, unknown>): DoctorHome {
process.env.PATH = [join(h.home, 'bin'), '/usr/bin', '/bin'].join(delimiter);
delete process.env.DATABASE_URL;
delete process.env.GBRAIN_DATABASE_URL;
+ // harness_wiring reads agent markers and harness config homes.
+ for (const k of ['CLAUDECODE', 'CLAUDE_CODE_ENTRYPOINT', 'CODEX_SANDBOX', 'CODEX_CI', 'CODEX_HOME', 'OPENCODE', 'OPENCODE_PID', 'XDG_CONFIG_HOME']) delete process.env[k];
if (config) {
mkdirSync(join(h.home, '.gbrain'), { recursive: true });
writeFileSync(join(h.home, '.gbrain', 'config.json'), JSON.stringify(config) + '\n');
diff --git a/test/fixtures/goldens/doctor/early-stop-connection-failure.json b/test/fixtures/goldens/doctor/early-stop-connection-failure.json
index db10902d2d..90c47afd8f 100644
--- a/test/fixtures/goldens/doctor/early-stop-connection-failure.json
+++ b/test/fixtures/goldens/doctor/early-stop-connection-failure.json
@@ -262,6 +262,39 @@
"name": "embedding_key_source",
"status": "ok"
},
+ {
+ "details": {
+ "reason": "no_harness_detected"
+ },
+ "fix": {
+ "actor": "user",
+ "consent": [
+ "persistent_install"
+ ],
+ "docs": "docs/protocol/MEMORY_VERBS_v1.md#install-the-4-command-quickstart",
+ "requires_exclusive": false,
+ "user_message": "Which agent app should get gbrain memory? The install guide has a one-line command for each.",
+ "why": "Register `<absolute path to gbrain> serve --surface verbs` as a stdio MCP server in your agent host; the install section lists the exact command per harness (Claude Code, Codex, Grok Build, opencode, OpenClaw)."
+ },
+ "message": "No agent harness was detected. Wire one when the user picks an agent app.",
+ "name": "harness_wiring",
+ "readiness_state": "missing",
+ "severity": "info",
+ "status": "ok"
+ },
+ {
+ "details": {
+ "consent_refused": 0,
+ "derived_cap_exhausted": 0,
+ "events": 0,
+ "internal_errors": 0,
+ "json_document_missing": 0,
+ "window_days": 7
+ },
+ "message": "No agent dead ends in the last 7 days (0 non-success event(s) logged).",
+ "name": "agent_contract",
+ "status": "ok"
+ },
{
"message": "Prepared statements disabled (PgBouncer-safe)",
"name": "pgbouncer_prepare",
diff --git a/test/fixtures/goldens/doctor/early-stop-null-engine-connect-error.json b/test/fixtures/goldens/doctor/early-stop-null-engine-connect-error.json
index e18e630c06..937a0bee81 100644
--- a/test/fixtures/goldens/doctor/early-stop-null-engine-connect-error.json
+++ b/test/fixtures/goldens/doctor/early-stop-null-engine-connect-error.json
@@ -189,6 +189,39 @@
"name": "embedding_key_source",
"status": "ok"
},
+ {
+ "details": {
+ "reason": "no_harness_detected"
+ },
+ "fix": {
+ "actor": "user",
+ "consent": [
+ "persistent_install"
+ ],
+ "docs": "docs/protocol/MEMORY_VERBS_v1.md#install-the-4-command-quickstart",
+ "requires_exclusive": false,
+ "user_message": "Which agent app should get gbrain memory? The install guide has a one-line command for each.",
+ "why": "Register `<absolute path to gbrain> serve --surface verbs` as a stdio MCP server in your agent host; the install section lists the exact command per harness (Claude Code, Codex, Grok Build, opencode, OpenClaw)."
+ },
+ "message": "No agent harness was detected. Wire one when the user picks an agent app.",
+ "name": "harness_wiring",
+ "readiness_state": "missing",
+ "severity": "info",
+ "status": "ok"
+ },
+ {
+ "details": {
+ "consent_refused": 0,
+ "derived_cap_exhausted": 0,
+ "events": 0,
+ "internal_errors": 0,
+ "json_document_missing": 0,
+ "window_days": 7
+ },
+ "message": "No agent dead ends in the last 7 days (0 non-success event(s) logged).",
+ "name": "agent_contract",
+ "status": "ok"
+ },
{
"details": {
"fix_hint": "Connection refused. If this is a Supabase direct URL (db.<ref>...:5432), switch to the transaction pooler (port 6543): gbrain db-repair can rewrite it. Run: gbrain db-repair",
diff --git a/test/fixtures/goldens/doctor/early-stop-null-engine-fast.json b/test/fixtures/goldens/doctor/early-stop-null-engine-fast.json
index 81fa2dd6a1..b34c125412 100644
--- a/test/fixtures/goldens/doctor/early-stop-null-engine-fast.json
+++ b/test/fixtures/goldens/doctor/early-stop-null-engine-fast.json
@@ -189,6 +189,39 @@
"name": "embedding_key_source",
"status": "ok"
},
+ {
+ "details": {
+ "reason": "no_harness_detected"
+ },
+ "fix": {
+ "actor": "user",
+ "consent": [
+ "persistent_install"
+ ],
+ "docs": "docs/protocol/MEMORY_VERBS_v1.md#install-the-4-command-quickstart",
+ "requires_exclusive": false,
+ "user_message": "Which agent app should get gbrain memory? The install guide has a one-line command for each.",
+ "why": "Register `<absolute path to gbrain> serve --surface verbs` as a stdio MCP server in your agent host; the install section lists the exact command per harness (Claude Code, Codex, Grok Build, opencode, OpenClaw)."
+ },
+ "message": "No agent harness was detected. Wire one when the user picks an agent app.",
+ "name": "harness_wiring",
+ "readiness_state": "missing",
+ "severity": "info",
+ "status": "ok"
+ },
+ {
+ "details": {
+ "consent_refused": 0,
+ "derived_cap_exhausted": 0,
+ "events": 0,
+ "internal_errors": 0,
+ "json_document_missing": 0,
+ "window_days": 7
+ },
+ "message": "No agent dead ends in the last 7 days (0 non-success event(s) logged).",
+ "name": "agent_contract",
+ "status": "ok"
+ },
{
"message": "Skipping DB checks (--fast mode, URL present from config-file)",
"name": "connection",
diff --git a/test/fixtures/goldens/doctor/early-stop-null-engine-no-config.json b/test/fixtures/goldens/doctor/early-stop-null-engine-no-config.json
index 2d4b0ed931..b4ee619f32 100644
--- a/test/fixtures/goldens/doctor/early-stop-null-engine-no-config.json
+++ b/test/fixtures/goldens/doctor/early-stop-null-engine-no-config.json
@@ -184,6 +184,39 @@
"name": "embedding_key_source",
"status": "ok"
},
+ {
+ "details": {
+ "reason": "no_harness_detected"
+ },
+ "fix": {
+ "actor": "user",
+ "consent": [
+ "persistent_install"
+ ],
+ "docs": "docs/protocol/MEMORY_VERBS_v1.md#install-the-4-command-quickstart",
+ "requires_exclusive": false,
+ "user_message": "Which agent app should get gbrain memory? The install guide has a one-line command for each.",
+ "why": "Register `<absolute path to gbrain> serve --surface verbs` as a stdio MCP server in your agent host; the install section lists the exact command per harness (Claude Code, Codex, Grok Build, opencode, OpenClaw)."
+ },
+ "message": "No agent harness was detected. Wire one when the user picks an agent app.",
+ "name": "harness_wiring",
+ "readiness_state": "missing",
+ "severity": "info",
+ "status": "ok"
+ },
+ {
+ "details": {
+ "consent_refused": 0,
+ "derived_cap_exhausted": 0,
+ "events": 0,
+ "internal_errors": 0,
+ "json_document_missing": 0,
+ "window_days": 7
+ },
+ "message": "No agent dead ends in the last 7 days (0 non-success event(s) logged).",
+ "name": "agent_contract",
+ "status": "ok"
+ },
{
"message": "No database configured (filesystem checks only). Set GBRAIN_DATABASE_URL or run `gbrain init`.",
"name": "connection",
diff --git a/test/fixtures/goldens/doctor/json-pglite-degraded.json b/test/fixtures/goldens/doctor/json-pglite-degraded.json
index dced1eb590..cc83e005d6 100644
--- a/test/fixtures/goldens/doctor/json-pglite-degraded.json
+++ b/test/fixtures/goldens/doctor/json-pglite-degraded.json
@@ -32,6 +32,7 @@
"path": "pglite — serve IPC socket not present",
"policy_skill_installed": false
},
+ "fix_unavailable_reason": "unstructured",
"message": "pglite — serve IPC socket not present; enabled but NO resolve path exists right now: the IPC socket is only bound by a running `gbrain serve` (stdio or --http) — until one is up, hooks/reflex degrade to no_serve on this brain (host capability may still supply pointers; policy skill carries otherwise) — policy skill not installed; run `gbrain integrations install retrieval-reflex --target <host-repo>`",
"name": "retrieval_reflex_health",
"status": "warn"
@@ -141,6 +142,7 @@
"webhook-transforms"
]
},
+ "fix_unavailable_reason": "unstructured",
"message": "64 new built-in skill(s) available that this workspace hasn't installed: academic-verify, archive-crawler, article-enrichment, ask-user, blog-ingest, book-mirror, brain-ingest-gate, brain-link-discipline, … +56 more. Add them with `gbrain skillpack sync`.",
"name": "skill_currency",
"status": "warn"
@@ -309,6 +311,42 @@
"name": "embedding_key_source",
"status": "ok"
},
+ {
+ "category": "ops",
+ "details": {
+ "reason": "no_harness_detected"
+ },
+ "fix": {
+ "actor": "user",
+ "consent": [
+ "persistent_install"
+ ],
+ "docs": "https://github.com/garrytan/gbrain/blob/master/docs/protocol/MEMORY_VERBS_v1.md#install-the-4-command-quickstart",
+ "next": "report",
+ "requires_exclusive": false,
+ "user_message": "Which agent app should get gbrain memory? The install guide has a one-line command for each.",
+ "why": "Register `<absolute path to gbrain> serve --surface verbs` as a stdio MCP server in your agent host; the install section lists the exact command per harness (Claude Code, Codex, Grok Build, opencode, OpenClaw)."
+ },
+ "message": "No agent harness was detected. Wire one when the user picks an agent app.",
+ "name": "harness_wiring",
+ "readiness_state": "missing",
+ "severity": "info",
+ "status": "ok"
+ },
+ {
+ "category": "meta",
+ "details": {
+ "consent_refused": 0,
+ "derived_cap_exhausted": 0,
+ "events": 0,
+ "internal_errors": 0,
+ "json_document_missing": 0,
+ "window_days": 7
+ },
+ "message": "No agent dead ends in the last 7 days (0 non-success event(s) logged).",
+ "name": "agent_contract",
+ "status": "ok"
+ },
{
"category": "ops",
"message": "Connected, 0 pages",
@@ -422,6 +460,7 @@
},
{
"category": "brain",
+ "fix_unavailable_reason": "unstructured",
"message": "embedding: declared dims=3072 but actual is vector(1024). Fix one side: update config OR ALTER TABLE content_chunks ALTER COLUMN embedding TYPE vector(3072);",
"name": "embedding_column_registry",
"status": "warn"
@@ -1008,6 +1047,7 @@
"unpushed": 0
}
},
+ "fix_unavailable_reason": "unstructured",
"message": "1 knowledge asset(s) lack verified recovery: default (not_a_git_repo). Current recovery is not verified for all repositories. Run `gbrain backup status` for fix commands (`gbrain bootstrap repo` / `git remote add origin <url>` / `gbrain sources harden <id>`).",
"name": "backup_coverage",
"status": "warn"
@@ -1026,6 +1066,7 @@
},
{
"category": "brain",
+ "fix_unavailable_reason": "unstructured",
"message": "Source 'default' has never completed a full cycle. Run `gbrain dream --source <id>` to cycle a source, or start `gbrain autopilot`.",
"name": "cycle_freshness",
"status": "warn"
@@ -1227,6 +1268,7 @@
},
{
"category": "brain",
+ "fix_unavailable_reason": "unstructured",
"message": "Schema width mismatch: content_chunks.embedding is vector(1024) but gateway resolved embedding_dimensions = 3072.\n\nEmbedding dimension mismatch detected.\n\n Existing column: vector(1024)\n Requested: vector(3072) (openai:text-embedding-3-large)\n\nSwitching dims re-embeds every chunk and fact;\nPGLite cannot ALTER vector column types in place (pgvector ships as WASM).\n\nKeep this brain's width (no rebuild; pages and facts kept):\n\n gbrain init --force --embedding-model openai:text-embedding-3-large --embedding-dimensions 1024 --path <home>/.gbrain/brain.pglite\n\nChange the width (re-embeds; pages and DB-only facts kept; preview first):\n\n gbrain migrate embeddings --to openai:text-embedding-3-large --dim 3072 --dry-run\n\nLast resort (moves the datastore aside; DB-only pages and facts are NOT carried over):\n\n gbrain reinit-pglite --embedding-model openai:text-embedding-3-large --embedding-dimensions 3072\n\nFull guide: docs/embedding-migrations.md",
"name": "embedding_width_consistency",
"status": "warn"
@@ -1325,6 +1367,7 @@
},
{
"category": "brain",
+ "fix_unavailable_reason": "unstructured",
"message": "0 takes (takes.bootstrap_enabled is false; opt in to enable)",
"name": "takes_count",
"status": "warn"
diff --git a/test/fixtures/goldens/doctor/json-pglite-fast.json b/test/fixtures/goldens/doctor/json-pglite-fast.json
index 0f2b0cb79b..c38816b62b 100644
--- a/test/fixtures/goldens/doctor/json-pglite-fast.json
+++ b/test/fixtures/goldens/doctor/json-pglite-fast.json
@@ -33,6 +33,7 @@
"path": "pglite — serve IPC socket not present",
"policy_skill_installed": false
},
+ "fix_unavailable_reason": "unstructured",
"message": "pglite — serve IPC socket not present; enabled but NO resolve path exists right now: the IPC socket is only bound by a running `gbrain serve` (stdio or --http) — until one is up, hooks/reflex degrade to no_serve on this brain (host capability may still supply pointers; policy skill carries otherwise) — policy skill not installed; run `gbrain integrations install retrieval-reflex --target <host-repo>`",
"name": "retrieval_reflex_health",
"status": "warn"
@@ -132,6 +133,7 @@
"webhook-transforms"
]
},
+ "fix_unavailable_reason": "unstructured",
"message": "64 new built-in skill(s) available that this workspace hasn't installed: academic-verify, archive-crawler, article-enrichment, ask-user, blog-ingest, book-mirror, brain-ingest-gate, brain-link-discipline, … +56 more. Add them with `gbrain skillpack sync`.",
"name": "skill_currency",
"status": "warn"
@@ -220,6 +222,43 @@
},
{
"category": "ops",
+ "details": {
+ "reason": "no_harness_detected"
+ },
+ "fix": {
+ "actor": "user",
+ "consent": [
+ "persistent_install"
+ ],
+ "docs": "https://github.com/garrytan/gbrain/blob/master/docs/protocol/MEMORY_VERBS_v1.md#install-the-4-command-quickstart",
+ "next": "report",
+ "requires_exclusive": false,
+ "user_message": "Which agent app should get gbrain memory? The install guide has a one-line command for each.",
+ "why": "Register `<absolute path to gbrain> serve --surface verbs` as a stdio MCP server in your agent host; the install section lists the exact command per harness (Claude Code, Codex, Grok Build, opencode, OpenClaw)."
+ },
+ "message": "No agent harness was detected. Wire one when the user picks an agent app.",
+ "name": "harness_wiring",
+ "readiness_state": "missing",
+ "severity": "info",
+ "status": "ok"
+ },
+ {
+ "category": "meta",
+ "details": {
+ "consent_refused": 0,
+ "derived_cap_exhausted": 0,
+ "events": 0,
+ "internal_errors": 0,
+ "json_document_missing": 0,
+ "window_days": 7
+ },
+ "message": "No agent dead ends in the last 7 days (0 non-success event(s) logged).",
+ "name": "agent_contract",
+ "status": "ok"
+ },
+ {
+ "category": "ops",
+ "fix_unavailable_reason": "unstructured",
"message": "Skipping DB checks (--fast mode, URL present from config-file-path)",
"name": "connection",
"status": "warn"
diff --git a/test/fixtures/goldens/doctor/json-pglite-fresh.json b/test/fixtures/goldens/doctor/json-pglite-fresh.json
index 7bd709354e..df74171387 100644
--- a/test/fixtures/goldens/doctor/json-pglite-fresh.json
+++ b/test/fixtures/goldens/doctor/json-pglite-fresh.json
@@ -32,6 +32,7 @@
"path": "pglite — serve IPC socket not present",
"policy_skill_installed": false
},
+ "fix_unavailable_reason": "unstructured",
"message": "pglite — serve IPC socket not present; enabled but NO resolve path exists right now: the IPC socket is only bound by a running `gbrain serve` (stdio or --http) — until one is up, hooks/reflex degrade to no_serve on this brain (host capability may still supply pointers; policy skill carries otherwise) — policy skill not installed; run `gbrain integrations install retrieval-reflex --target <host-repo>`",
"name": "retrieval_reflex_health",
"status": "warn"
@@ -141,6 +142,7 @@
"webhook-transforms"
]
},
+ "fix_unavailable_reason": "unstructured",
"message": "64 new built-in skill(s) available that this workspace hasn't installed: academic-verify, archive-crawler, article-enrichment, ask-user, blog-ingest, book-mirror, brain-ingest-gate, brain-link-discipline, … +56 more. Add them with `gbrain skillpack sync`.",
"name": "skill_currency",
"status": "warn"
@@ -309,6 +311,42 @@
"name": "embedding_key_source",
"status": "ok"
},
+ {
+ "category": "ops",
+ "details": {
+ "reason": "no_harness_detected"
+ },
+ "fix": {
+ "actor": "user",
+ "consent": [
+ "persistent_install"
+ ],
+ "docs": "https://github.com/garrytan/gbrain/blob/master/docs/protocol/MEMORY_VERBS_v1.md#install-the-4-command-quickstart",
+ "next": "report",
+ "requires_exclusive": false,
+ "user_message": "Which agent app should get gbrain memory? The install guide has a one-line command for each.",
+ "why": "Register `<absolute path to gbrain> serve --surface verbs` as a stdio MCP server in your agent host; the install section lists the exact command per harness (Claude Code, Codex, Grok Build, opencode, OpenClaw)."
+ },
+ "message": "No agent harness was detected. Wire one when the user picks an agent app.",
+ "name": "harness_wiring",
+ "readiness_state": "missing",
+ "severity": "info",
+ "status": "ok"
+ },
+ {
+ "category": "meta",
+ "details": {
+ "consent_refused": 0,
+ "derived_cap_exhausted": 0,
+ "events": 0,
+ "internal_errors": 0,
+ "json_document_missing": 0,
+ "window_days": 7
+ },
+ "message": "No agent dead ends in the last 7 days (0 non-success event(s) logged).",
+ "name": "agent_contract",
+ "status": "ok"
+ },
{
"category": "ops",
"message": "Connected, 0 pages",
@@ -416,6 +454,7 @@
},
{
"category": "brain",
+ "fix_unavailable_reason": "unstructured",
"message": "Embedding provider probe failed: This brain has no explicit embedding model. Its stored vectors must not be interpreted using a new default. Run gbrain migrate embeddings --status and preview an explicit migration with --dry-run.",
"name": "embedding_provider",
"status": "warn"
@@ -1008,6 +1047,7 @@
"unpushed": 0
}
},
+ "fix_unavailable_reason": "unstructured",
"message": "1 knowledge asset(s) lack verified recovery: default (not_a_git_repo). Current recovery is not verified for all repositories. Run `gbrain backup status` for fix commands (`gbrain bootstrap repo` / `git remote add origin <url>` / `gbrain sources harden <id>`).",
"name": "backup_coverage",
"status": "warn"
@@ -1026,6 +1066,7 @@
},
{
"category": "brain",
+ "fix_unavailable_reason": "unstructured",
"message": "Source 'default' has never completed a full cycle. Run `gbrain dream --source <id>` to cycle a source, or start `gbrain autopilot`.",
"name": "cycle_freshness",
"status": "warn"
@@ -1312,6 +1353,7 @@
},
{
"category": "brain",
+ "fix_unavailable_reason": "unstructured",
"message": "0 takes (takes.bootstrap_enabled is false; opt in to enable)",
"name": "takes_count",
"status": "warn"
diff --git a/test/fixtures/goldens/doctor/json-postgres-unreachable-fast.json b/test/fixtures/goldens/doctor/json-postgres-unreachable-fast.json
index 1bc6294faf..0d9b41ce8d 100644
--- a/test/fixtures/goldens/doctor/json-postgres-unreachable-fast.json
+++ b/test/fixtures/goldens/doctor/json-postgres-unreachable-fast.json
@@ -132,6 +132,7 @@
"webhook-transforms"
]
},
+ "fix_unavailable_reason": "unstructured",
"message": "64 new built-in skill(s) available that this workspace hasn't installed: academic-verify, archive-crawler, article-enrichment, ask-user, blog-ingest, book-mirror, brain-ingest-gate, brain-link-discipline, … +56 more. Add them with `gbrain skillpack sync`.",
"name": "skill_currency",
"status": "warn"
@@ -226,6 +227,43 @@
},
{
"category": "ops",
+ "details": {
+ "reason": "no_harness_detected"
+ },
+ "fix": {
+ "actor": "user",
+ "consent": [
+ "persistent_install"
+ ],
+ "docs": "https://github.com/garrytan/gbrain/blob/master/docs/protocol/MEMORY_VERBS_v1.md#install-the-4-command-quickstart",
+ "next": "report",
+ "requires_exclusive": false,
+ "user_message": "Which agent app should get gbrain memory? The install guide has a one-line command for each.",
+ "why": "Register `<absolute path to gbrain> serve --surface verbs` as a stdio MCP server in your agent host; the install section lists the exact command per harness (Claude Code, Codex, Grok Build, opencode, OpenClaw)."
+ },
+ "message": "No agent harness was detected. Wire one when the user picks an agent app.",
+ "name": "harness_wiring",
+ "readiness_state": "missing",
+ "severity": "info",
+ "status": "ok"
+ },
+ {
+ "category": "meta",
+ "details": {
+ "consent_refused": 0,
+ "derived_cap_exhausted": 0,
+ "events": 0,
+ "internal_errors": 0,
+ "json_document_missing": 0,
+ "window_days": 7
+ },
+ "message": "No agent dead ends in the last 7 days (0 non-success event(s) logged).",
+ "name": "agent_contract",
+ "status": "ok"
+ },
+ {
+ "category": "ops",
+ "fix_unavailable_reason": "unstructured",
"message": "Skipping DB checks (--fast mode, URL present from config-file)",
"name": "connection",
"status": "warn"
diff --git a/test/fixtures/goldens/doctor/json-postgres-unreachable.json b/test/fixtures/goldens/doctor/json-postgres-unreachable.json
index 7272aee15e..bb503bf9b6 100644
--- a/test/fixtures/goldens/doctor/json-postgres-unreachable.json
+++ b/test/fixtures/goldens/doctor/json-postgres-unreachable.json
@@ -131,6 +131,7 @@
"webhook-transforms"
]
},
+ "fix_unavailable_reason": "unstructured",
"message": "64 new built-in skill(s) available that this workspace hasn't installed: academic-verify, archive-crawler, article-enrichment, ask-user, blog-ingest, book-mirror, brain-ingest-gate, brain-link-discipline, … +56 more. Add them with `gbrain skillpack sync`.",
"name": "skill_currency",
"status": "warn"
@@ -223,6 +224,42 @@
"name": "embedding_key_source",
"status": "ok"
},
+ {
+ "category": "ops",
+ "details": {
+ "reason": "no_harness_detected"
+ },
+ "fix": {
+ "actor": "user",
+ "consent": [
+ "persistent_install"
+ ],
+ "docs": "https://github.com/garrytan/gbrain/blob/master/docs/protocol/MEMORY_VERBS_v1.md#install-the-4-command-quickstart",
+ "next": "report",
+ "requires_exclusive": false,
+ "user_message": "Which agent app should get gbrain memory? The install guide has a one-line command for each.",
+ "why": "Register `<absolute path to gbrain> serve --surface verbs` as a stdio MCP server in your agent host; the install section lists the exact command per harness (Claude Code, Codex, Grok Build, opencode, OpenClaw)."
+ },
+ "message": "No agent harness was detected. Wire one when the user picks an agent app.",
+ "name": "harness_wiring",
+ "readiness_state": "missing",
+ "severity": "info",
+ "status": "ok"
+ },
+ {
+ "category": "meta",
+ "details": {
+ "consent_refused": 0,
+ "derived_cap_exhausted": 0,
+ "events": 0,
+ "internal_errors": 0,
+ "json_document_missing": 0,
+ "window_days": 7
+ },
+ "message": "No agent dead ends in the last 7 days (0 non-success event(s) logged).",
+ "name": "agent_contract",
+ "status": "ok"
+ },
{
"category": "ops",
"details": {
@@ -230,6 +267,7 @@
"reason": "conn_refused",
"transient": true
},
+ "fix_unavailable_reason": "unstructured",
"message": "Cannot connect to database: connect ECONNREFUSED <REDACTED:ipv4>:1. Fix: Check your connection URL in ~/.gbrain/config.json",
"name": "connection",
"status": "fail"
diff --git a/test/fixtures/goldens/doctor/registry-build-checks.json b/test/fixtures/goldens/doctor/registry-build-checks.json
index b9e8429c71..853a46816b 100644
--- a/test/fixtures/goldens/doctor/registry-build-checks.json
+++ b/test/fixtures/goldens/doctor/registry-build-checks.json
@@ -205,6 +205,14 @@
"category": "brain",
"name": "embedding_key_source"
},
+ {
+ "category": "ops",
+ "name": "harness_wiring"
+ },
+ {
+ "category": "meta",
+ "name": "agent_contract"
+ },
{
"category": "ops",
"name": "pglite_data_dir"
diff --git a/test/helpers/doctor-json-golden.ts b/test/helpers/doctor-json-golden.ts
index accea8618b..8eec2852c5 100644
--- a/test/helpers/doctor-json-golden.ts
+++ b/test/helpers/doctor-json-golden.ts
@@ -81,6 +81,8 @@ export async function runGbrain(h: DoctorHome, args: string[], env: Record<strin
for (const [k, v] of Object.entries(process.env)) if (v !== undefined) childEnv[k] = v;
for (const k of PROVIDER_ENV_KEYS) delete childEnv[k];
for (const k of ['DATABASE_URL', 'GBRAIN_DATABASE_URL', 'GBRAIN_REMOTE_CLIENT_SECRET', 'GBRAIN_PGLITE_SNAPSHOT', 'GBRAIN_SKILLS_DIR', 'OPENCLAW_WORKSPACE']) delete childEnv[k];
+ // harness_wiring reads agent markers and harness config homes: keep the golden independent of the host's harness.
+ for (const k of ['CLAUDECODE', 'CLAUDE_CODE_ENTRYPOINT', 'CODEX_SANDBOX', 'CODEX_CI', 'CODEX_HOME', 'OPENCODE', 'OPENCODE_PID', 'XDG_CONFIG_HOME']) delete childEnv[k];
Object.assign(childEnv, {
HOME: h.home,
GBRAIN_HOME: h.home,