Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
feat(db-repair): D2 --json document and failure envelopes
garrytan57351bb235b3
diff --git a/src/cli/command-table.ts b/src/cli/command-table.tsindex 8f1d61b40c..d4a7ee740c 100644--- a/src/cli/command-table.ts+++ b/src/cli/command-table.ts@@ -152,7 +152,7 @@ export const CLI_COMMANDS: readonly CliCommandRecord[] = [ // Pre-connect: disp// like pglite-repair.// selfHelp: db-availability loop: both print their own help (engine-free).{ name: 'engine', phase: 'pre-connect', thinClient: 'none', selfHelp: true, load: () => import('./commands/engine.ts') },- { name: 'db-repair', phase: 'pre-connect', thinClient: 'none', selfHelp: true, load: () => import('./commands/db-repair.ts') },+ { name: 'db-repair', phase: 'pre-connect', thinClient: 'none', selfHelp: true, json: 'document', load: () => import('./commands/db-repair.ts') },// selfHelp: #4003: auth ships its own detailed usage (token/OAuth-client commands + flags) in its// `default:` switch case, hit whenever the subcommand isn't one of create/list/revoke/etc —// including --help. Without this entry the generic short-circuit fires first and that usage blockdiff --git a/src/commands/db-repair.ts b/src/commands/db-repair.tsindex 0b3ce44423..1a64f380f8 100644--- a/src/commands/db-repair.ts+++ b/src/commands/db-repair.ts@@ -72,6 +72,11 @@ import {} from '../core/docker-postgres.ts';import { rewriteCooldownBlocked, writeReceipt } from '../core/db-repair-receipts.ts';import type { BrainEngine } from '../core/engine.ts';+import type { Action } from '../core/agent-output.ts';+import { writeJsonDocument } from '../core/cli-force-exit.ts';+import { opError, type OperationError } from '../core/ops/contract.ts';+import type { RegistryCode } from '../core/error-registry.ts';+import { writeCliError } from '../cli/cli-error.ts';class UnknownFlagError extends Error {}@@ -287,11 +292,39 @@ interface JsonReport {remaining?: PgAccessDiagnosis | null;}+/**+ * D2: a healthy/fixed report is the --json document; an unfixed one (exit 1)+ * is the error envelope leading with the report's keys (code+ * database_error, reason = the diagnosis reason, the tier's next step as+ * the fix).+ */function emit(json: boolean, report: JsonReport, humanLines: string[]): void {- if (json) console.log(JSON.stringify(report, null, 2));- else console.log(humanLines.join('\n'));+ if (!json) { console.log(humanLines.join('\n')); return; }+ if (report.fixed) { void writeJsonDocument(JSON.stringify(report, null, 2)); return; }+ const d = report.remaining ?? report.diagnosis;+ const applied = report.applied.length > 0;+ const fix: Action | undefined = applied || report.tier === 'manual' || report.tier === undefined ? undefined+ : report.tier === 'auto'+ ? { argv: ['gbrain', 'db-repair', '--yes'], consent: [], actor: 'agent', requires_exclusive: false,+ why: 'Applies the auto tier the plan names (bounded retries, pending migrations, CREATE EXTENSION vector, starting gbrain\'s own docker container).' }+ : { argv: ['gbrain', 'db-repair', '--yes', '--apply-rewrites'], consent: ['credentials'], actor: 'agent', requires_exclusive: false,+ why: 'Rewrites database_url in ~/.gbrain/config.json as the plan says (undo: gbrain db-repair --yes --undo-last-rewrite).',+ user_message: 'gbrain wants to rewrite the database connection URL in its config to reach your database. Allow it? (It can be undone.)' };+ const e = opError('database_error', d?.message ?? 'The database is still not reachable.',+ fix ? `Apply the plan: ${fix.argv!.join(' ')}` : (d?.remediation ?? 'Follow the remediation in the report.'),+ { ...(report.reason ? { reason: report.reason } : {}), ...(fix ? { fix } : {}), ...(d?.remediation ? { why: d.remediation } : {}) });+ writeCliError(e, 'db-repair', { json: true, stderr: false, legacy: { ...report } });+}++/** A refusal before any probe: the human line on stderr (unchanged), the envelope under --json. Returns `exitCode`. */+function refuse(json: boolean, exitCode: number, human: string, code: RegistryCode, suggestion: string, fix?: Action): number {+ console.error(human);+ if (json) writeCliError(opError(code, human, suggestion, fix ? { fix } : {}), 'db-repair', { json: true, stderr: false });+ return exitCode;}+const helpFix = (why: string): Action => ({ argv: ['gbrain', 'db-repair', '--help'], consent: [], actor: 'agent', requires_exclusive: false, why });+function tierOf(reason: PgAccessReason): 'auto' | 'rewrite' | 'manual' {switch (reason) {case 'conn_dropped':@@ -332,20 +365,19 @@ export async function runDbRepair(args: string[], deps: DbRepairDeps = defaultDetry {opts = parseArgs(args);} catch (e) {- console.error(e instanceof Error ? e.message : String(e));- return 2;+ return refuse(args.includes('--json'), 2, e instanceof Error ? e.message : String(e), 'unknown_flag',+ 'Run `gbrain db-repair --help` for the accepted flags.', helpFix('Lists the flags db-repair accepts.'));}if (opts.help) {printHelp();return 0;}if (opts.applyRewrites && !opts.yes) {- console.error('--apply-rewrites requires --yes (rewrites are the higher consent tier, not a lower one).');- return 2;+ return refuse(opts.json, 2, '--apply-rewrites requires --yes (rewrites are the higher consent tier, not a lower one).', 'invalid_params',+ 'Example: gbrain db-repair --yes --apply-rewrites');}if (opts.undoLastRewrite && !opts.yes) {- console.error('--undo-last-rewrite requires --yes.');- return 2;+ return refuse(opts.json, 2, '--undo-last-rewrite requires --yes.', 'invalid_params', 'Example: gbrain db-repair --yes --undo-last-rewrite');}const brainId = resolveBrainId(null);@@ -353,22 +385,20 @@ export async function runDbRepair(args: string[], deps: DbRepairDeps = defaultDe// A mount outage must never repair — or rewrite — the HOST config.if (brainId !== HOST_BRAIN_ID) {const mount = (() => { try { return loadMounts().find((m) => m.id === brainId) ?? null; } catch { return null; } })();- console.error(+ return refuse(opts.json, 1,`db-repair targets the host brain, but this context resolves to mount '${brainId}'` +(mount ? ` (engine ${mount.engine}, ${mount.database_url ? 'url: ' + redactPgUrl(mount.database_url) : 'path: ' + (mount.database_path ?? '?')})` : '') +`.\nMount-targeted repair is not supported yet — fix that brain on its host, or unset GBRAIN_BRAIN_ID/.gbrain-mount to repair the host brain.`,- );- return 1;+ 'config_error', 'Run db-repair on the mounted brain\'s host, or unset GBRAIN_BRAIN_ID / remove .gbrain-mount to repair the host brain.');}const cfg = loadConfig();if (isThinClient(cfg)) {- console.error(+ return refuse(opts.json, 1,'This machine is a thin client — there is no local database to repair. ' +'The brain lives on the remote MCP server; run db-repair on that host.',- );- return 1;+ 'requires_local_engine', 'Ask the brain host\'s operator to run `gbrain db-repair` there.');}if (!cfg) {@@ -382,18 +412,22 @@ export async function runDbRepair(args: string[], deps: DbRepairDeps = defaultDeschema_version: 1, brain_id: brainId, reason: d.reason, tier: 'manual',marker: formatDbAccessMarker(d), diagnosis: d, plan: [d.remediation], applied: [], fixed: false, remaining: d,}, [`${formatDbAccessMarker(d)}`, d.remediation]);+ return 1;}+ if (opts.json) writeCliError(opError('no_brain', 'No brain is configured, so there is no database to repair.',+ 'Run `gbrain init --pglite --no-embedding` (or `gbrain init --help` for Postgres).'), 'db-repair', { json: true, stderr: false });return 1;}if (cfg.engine === 'pglite') {- console.error('This brain runs PGLite — its repair lane is: gbrain pglite-repair (WAL/data-dir recovery).');- return 1;+ return refuse(opts.json, 1, 'This brain runs PGLite — its repair lane is: gbrain pglite-repair (WAL/data-dir recovery).', 'config_error',+ 'Run `gbrain pglite-repair` for PGLite brains.',+ { argv: ['gbrain', 'pglite-repair', '--help'], consent: [], actor: 'agent', requires_exclusive: false, why: 'Shows the PGLite WAL/data-dir recovery options.' });}if (!acquireRepairLock()) {- console.error('repair in progress — another db-repair holds the advisory lock. Wait for it (do not retry in a loop).');- return 1;+ return refuse(opts.json, 1, 'repair in progress — another db-repair holds the advisory lock. Wait for it (do not retry in a loop).', 'lock_busy',+ 'Wait for the running db-repair to finish, then run `gbrain db-repair` once to read its result.');}try {@@ -411,15 +445,14 @@ export async function runDbRepair(args: string[], deps: DbRepairDeps = defaultDeasync function runUndo(opts: DbRepairOpts, brainId: string, deps: DbRepairDeps): Promise<number> {const rec = readUndoRecord();if (!rec) {- console.error('No rewrite to undo (no undo record on file).');- return 1;+ return refuse(opts.json, 1, 'No rewrite to undo (no undo record on file).', 'not_found', 'Nothing to undo; run `gbrain db-repair` to diagnose the current URL.');}// The undo file is 0600 and same trust class as config.json, but validate// the scheme anyway before writing it INTO config — a corrupted/edited// record must not plant a non-postgres value in database_url.if (!/^postgres(ql)?:\/\//.test(rec.prior_url)) {- console.error('The undo record does not hold a postgres:// URL — refusing to restore it. Remove it: rm ~/.gbrain/db-repair-undo.json');- return 1;+ return refuse(opts.json, 1, 'The undo record does not hold a postgres:// URL — refusing to restore it. Remove it: rm ~/.gbrain/db-repair-undo.json',+ 'config_error', 'Remove ~/.gbrain/db-repair-undo.json; it cannot be restored.');}const fileCfg = loadConfigFileOnly();const rewrittenUrl = fileCfg?.database_url; // the URL undo is about to replacediff --git a/test/cli-contract.serial.test.ts b/test/cli-contract.serial.test.tsindex 9d8ed5b0ed..c3fd34eff9 100644--- a/test/cli-contract.serial.test.ts+++ b/test/cli-contract.serial.test.ts@@ -78,6 +78,8 @@ interface JsonRow {failOnBrain?: boolean;/** The succeeding invocation runs against an empty home (default: the keyless brain). */okOnEmpty?: boolean;+ /** The succeeding invocation needs Postgres: the E2E file (test/e2e/…) that asserts it instead. */+ okE2E?: string;}/** One row per command-table record that declares `json`; a new declaration needs a row. */@@ -87,6 +89,7 @@ const JSON_ROWS: Record<string, JsonRow> = {doctor: { ok: ['doctor', '--json', '--fast'], fail: ['doctor', '--json'] },sync: { ok: ['sync', '--source', 'notes', '--no-pull', '--json'], fail: ['sync', '--source', 'notes', '--json'], failOnBrain: true },embed: { ok: ['embed', '--stale', '--json'], fail: ['embed', '--all', '--json'], failOnBrain: true },+ 'db-repair': { ok: ['db-repair', '--json'], fail: ['db-repair', '--json'], failOnBrain: true, okE2E: 'test/e2e/cli-json-commands-postgres.test.ts' },'post-upgrade': { ok: ['post-upgrade', '--json', '--no-autopilot-install'], fail: ['post-upgrade', '--bogus', '--json'], okOnEmpty: true },'apply-migrations': { ok: ['apply-migrations', '--dry-run', '--json'], fail: ['apply-migrations', '--json', '--migration', '9.9.9'], failOnBrain: true },};@@ -133,9 +136,13 @@ describe('D5 json contract: one success and one failure per json-declared commanconst fresh = mkdtempSync(join(tmpdir(), 'gbrain-cli-contract-ok-'));try {const okHome = row.okOnEmpty ? fresh : brainHome;- const ok = await runCli(row.ok, { home: okHome, cwd: okHome, timeoutMs: 120_000 });- expect(ok.exitCode, `${record.name} ok: ${ok.stderr.slice(-800)}`).toBe(0);- expect(parsedShape(record.json!, ok.stdout).length).toBeGreaterThan(0);+ if (row.okE2E) {+ expect(existsSync(join(import.meta.dir, '..', row.okE2E)), `${record.name}: ${row.okE2E} covers the success shape`).toBe(true);+ } else {+ const ok = await runCli(row.ok, { home: okHome, cwd: okHome, timeoutMs: 120_000 });+ expect(ok.exitCode, `${record.name} ok: ${ok.stderr.slice(-800)}`).toBe(0);+ expect(parsedShape(record.json!, ok.stdout).length).toBeGreaterThan(0);+ }const failHome = row.failOnBrain ? brainHome : emptyHome;assertFailureShape(record.name, record.json!, await runCli(row.fail, { home: failHome, cwd: failHome, timeoutMs: 120_000 }));} finally {diff --git a/test/fixtures/goldens/cli/engine-free-db-down.json b/test/fixtures/goldens/cli/engine-free-db-down.jsonindex 326d5fb3ce..860825eefe 100644--- a/test/fixtures/goldens/cli/engine-free-db-down.json+++ b/test/fixtures/goldens/cli/engine-free-db-down.json@@ -143,34 +143,9 @@"stderr": [],"stderrFirstLine": null,"stdout": [- "{",- " \"schema_version\": 1,",- " \"brain_id\": \"host\",",- " \"reason\": \"conn_refused\",",- " \"tier\": \"auto\",",- " \"marker\": \"GBRAIN_DB_ACCESS conn_refused\",",- " \"diagnosis\": {",- " \"reason\": \"conn_refused\",",- " \"transient\": true,",- " \"message\": \"connect ECONNREFUSED <REDACTED:ipv4>:1\",",- " \"remediation\": \"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.\",",- " \"brainId\": \"host\"",- " },",- " \"plan\": [",- " \"bounded reconnect; if the server is down, start it and re-run\"",- " ],",- " \"applied\": [],",- " \"fixed\": false,",- " \"remaining\": {",- " \"reason\": \"conn_refused\",",- " \"transient\": true,",- " \"message\": \"connect ECONNREFUSED <REDACTED:ipv4>:1\",",- " \"remediation\": \"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.\",",- " \"brainId\": \"host\"",- " }",- "}"+ "{\"schema_version\":1,\"brain_id\":\"host\",\"reason\":\"conn_refused\",\"tier\":\"auto\",\"marker\":\"GBRAIN_DB_ACCESS conn_refused\",\"diagnosis\":{\"reason\":\"conn_refused\",\"transient\":true,\"message\":\"connect ECONNREFUSED <REDACTED:ipv4>:1\",\"remediation\":\"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.\",\"brainId\":\"host\"},\"plan\":[\"bounded reconnect; if the server is down, start it and re-run\"],\"applied\":[],\"fixed\":false,\"remaining\":{\"reason\":\"conn_refused\",\"transient\":true,\"message\":\"connect ECONNREFUSED <REDACTED:ipv4>:1\",\"remediation\":\"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.\",\"brainId\":\"host\"},\"error\":\"database_error\",\"code\":\"database_error\",\"message\":\"connect ECONNREFUSED <REDACTED:ipv4>:1\",\"suggestion\":\"Apply the plan: gbrain db-repair --yes\",\"docs\":\"https://github.com/garrytan/gbrain/blob/master/docs/guides/error-codes.md#database_error\",\"why\":\"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.\",\"fix\":{\"argv\":[\"gbrain\",\"db-repair\",\"--yes\"],\"command\":\"gbrain db-repair --yes\",\"consent\":[],\"actor\":\"agent\",\"next\":\"run\",\"why\":\"Applies the auto tier the plan names (bounded retries, pending migrations, CREATE EXTENSION vector, starting gbrain's own docker container).\",\"requires_exclusive\":false},\"docs_cmd\":[\"gbrain\",\"errors\",\"database_error\"],\"class\":\"server\",\"retryable\":false,\"contract_version\":1}"],- "stdoutFirstLine": "{",+ "stdoutFirstLine": "{\"schema_version\":1,\"brain_id\":\"host\",\"reason\":\"conn_refused\",\"tier\":\"auto\",\"marker\":\"GBRAIN_DB_ACCESS conn_refused\",\"diagnosis\":{\"reason\":\"conn_refused\",\"transient\":true,\"message\":\"connect ECONNREFUSED <REDACTED:ipv4>:1\",\"remediation\":\"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.\",\"brainId\":\"host\"},\"plan\":[\"bounded reconnect; if the server is down, start it and re-run\"],\"applied\":[],\"fixed\":false,\"remaining\":{\"reason\":\"conn_refused\",\"transient\":true,\"message\":\"connect ECONNREFUSED <REDACTED:ipv4>:1\",\"remediation\":\"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.\",\"brainId\":\"host\"},\"error\":\"database_error\",\"code\":\"database_error\",\"message\":\"connect ECONNREFUSED <REDACTED:ipv4>:1\",\"suggestion\":\"Apply the plan: gbrain db-repair --yes\",\"docs\":\"https://github.com/garrytan/gbrain/blob/master/docs/guides/error-codes.md#database_error\",\"why\":\"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.\",\"fix\":{\"argv\":[\"gbrain\",\"db-repair\",\"--yes\"],\"command\":\"gbrain db-repair --yes\",\"consent\":[],\"actor\":\"agent\",\"next\":\"run\",\"why\":\"Applies the auto tier the plan names (bounded retries, pending migrations, CREATE EXTENSION vector, starting gbrain's own docker container).\",\"requires_exclusive\":false},\"docs_cmd\":[\"gbrain\",\"errors\",\"database_error\"],\"class\":\"server\",\"retryable\":false,\"contract_version\":1}","url": "config"},{