Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(db-repair): an auto-tier --yes that could not fix access escalates to the user instead of prescribing itself again (#7137)
garrytan145f9e5cf5c4
diff --git a/src/commands/db-repair.ts b/src/commands/db-repair.tsindex 324b9043f3..6a828532ad 100644--- a/src/commands/db-repair.ts+++ b/src/commands/db-repair.ts@@ -297,14 +297,20 @@ interface JsonReport {* 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).+ * the fix). An auto tier this call already ran escalates to the user rather+ * than prescribing the same --yes again (#7137).*/-function emit(json: boolean, report: JsonReport, humanLines: string[]): void {+function emit(json: boolean, report: JsonReport, humanLines: string[], ranAutoTier = false): void {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' && ranAutoTier+ ? { consent: [], actor: 'user', requires_exclusive: false,+ why: 'gbrain db-repair --yes already ran its bounded retries in this call and the database is still unreachable; running it again repeats them.',+ user_message: `gbrain could not reach the database after its repair attempts (${d?.reason ?? report.reason}). ${d?.remediation ?? ''} Check the database server's status and its startup log; once it accepts connections, re-check with: gbrain db-repair`,+ verify: { argv: ['gbrain', 'db-repair'] } }: 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).' }@@ -312,7 +318,7 @@ function emit(json: boolean, report: JsonReport, humanLines: string[]): void {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.'),+ fix?.argv ? `Apply the plan: ${fix.argv.join(' ')}` : (fix?.user_message ?? 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 } });}@@ -542,7 +548,7 @@ async function repairHost(opts: DbRepairOpts, cfg: GBrainConfig, brainId: string}const outcome = await applyLadder(diagnosis, tier, opts, cfg, engineConfig, url, source, brainId, deps, report);- emit(opts.json, report, outcome.humanLines);+ emit(opts.json, report, outcome.humanLines, tier === 'auto');return outcome.code;}diff --git a/test/db-repair.serial.test.ts b/test/db-repair.serial.test.tsindex cb1d25c2b5..14d28cd96d 100644--- a/test/db-repair.serial.test.ts+++ b/test/db-repair.serial.test.ts@@ -556,3 +556,62 @@ describe('db-repair docker arm + healthy-path bonus + rewrite restart note', ()expect(logs.join('\n')).toContain('restart them to pick up the new URL');});});++describe('db-repair --yes that could not fix the access failure (#7137)', () => {+ // Value: protects=an agent following the operator contract stops after one failed --yes instead of looping on it;+ // fails_when=an exhausted conn_refused --yes run hands back fix argv [gbrain, db-repair, --yes] with next run;+ // why_new=no test read the --json fix of an unfixed --yes run; seam=runDbRepair deps in a child process (the+ // envelope is written to fd 1); no_claim=diagnosing why the local server refuses connections.+ function runJson(args: string[], probes: number): { status: number | null; doc: Record<string, any>; accessCalls: number } {+ const repo = join(import.meta.dir, '..');+ const script = `+ import { runDbRepair } from ${JSON.stringify(join(repo, 'src/commands/db-repair.ts'))};+ import { classifyPgAccessError } from ${JSON.stringify(join(repo, 'src/core/pg-access-classify.ts'))};+ const e = Object.assign(new Error('connect ECONNREFUSED 127.0.0.1:5432'), { code: 'ECONNREFUSED' });+ const d = classifyPgAccessError(e, { url: ${JSON.stringify(PLAIN_PG_URL)}, source: 'config-file' });+ let calls = 0;+ const code = await runDbRepair(${JSON.stringify(args)}, {+ probeAccess: async () => (++calls <= ${probes} ? d : null),+ probeSchema: async () => null,+ withEngine: async () => { throw new Error('unexpected database access'); },+ docker: { available: () => false, state: () => 'absent', start: () => { throw new Error('unexpected service start'); } },+ sleep: async () => {},+ now: () => ${FIXED_NOW},+ });+ process.stderr.write('ACCESS_CALLS=' + calls + '\\n');+ process.exitCode = code;+ `;+ const env: Record<string, string | undefined> = { ...process.env, GBRAIN_HOME: home };+ for (const k of ['GBRAIN_DATABASE_URL', 'DATABASE_URL', 'GBRAIN_BRAIN_ID', 'GBRAIN_MOUNTS_PATH']) delete env[k];+ const r = spawnSync(process.execPath, ['--no-env-file', '-e', script], { cwd: repo, env, encoding: 'utf-8' });+ const calls = Number(/ACCESS_CALLS=(\d+)/.exec(r.stderr)?.[1] ?? -1);+ return { status: r.status, doc: JSON.parse(r.stdout), accessCalls: calls };+ }++ test('an exhausted bounded retry escalates to the user instead of prescribing db-repair --yes again', () => {+ writeConfig({ engine: 'postgres', database_url: PLAIN_PG_URL });+ const { status, doc, accessCalls } = runJson(['--yes', '--json'], 99);+ expect(status).toBe(1);+ expect(accessCalls).toBe(2);+ expect(doc.reason).toBe('conn_refused');+ expect(doc.fixed).toBe(false);+ expect(doc.applied).toEqual([]);+ expect(doc.fix.argv).toBeUndefined();+ expect(doc.fix.next).toBe('report');+ expect(doc.fix.user_message).toContain('status and its startup log');+ expect(doc.fix.verify.argv).toEqual(['gbrain', 'db-repair']);+ expect(readReceipts().filter((r) => r.outcome === 'applied').length).toBe(0);+ });++ test('without --yes the auto tier is still the next step, and a transient refusal still heals under --yes', () => {+ writeConfig({ engine: 'postgres', database_url: PLAIN_PG_URL });+ const diagnose = runJson(['--json'], 99);+ expect(diagnose.status).toBe(1);+ expect(diagnose.doc.fix.argv).toEqual(['gbrain', 'db-repair', '--yes']);+ expect(diagnose.doc.fix.next).toBe('run');+ const healed = runJson(['--yes', '--json'], 1);+ expect(healed.status).toBe(0);+ expect(healed.doc.fixed).toBe(true);+ expect(healed.doc.applied).toEqual(['bounded_reconnect']);+ });+});