Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(backup): never emit an empty failure message from backup create/restore (#5419)
time-attack7ee1cc045ec6
diff --git a/src/commands/backup.ts b/src/commands/backup.tsindex 1af5fe9ce9..2b4566f0f3 100644--- a/src/commands/backup.ts+++ b/src/commands/backup.ts@@ -16,6 +16,8 @@*/import { OperationError, opError } from '../core/ops/contract.ts';+import { redactUrlsInText } from '../core/url-redact.ts';+import { redactConnectionInfo } from '../core/audit/redact-connection-info.ts';import type { BrainEngine } from '../core/engine.ts';import { getCliOptions } from '../core/cli-options.ts';import { getBackupStatus } from '../core/backup/coverage.ts';@@ -44,6 +46,27 @@ function backupUsageError(sub: string, message: string): OperationError {return opError('invalid_params', message, `Usage: ${u.usage}. Example: ${u.example}`);}+const SAFE_ERROR_FIELD = /^[A-Za-z0-9_.:-]{1,64}$/;++/**+ * A nonempty diagnostic for a failed create/restore (#5312). An error's own+ * message is used, URL- and connection-redacted. A message-less thrown value+ * (PGLite's ErrnoError) is described only by its bounded name/code/errno,+ * never `String(object)`, which prints `[object Object]` or serializes+ * whatever the object carries.+ */+export function backupFailureMessage(error: unknown): string {+ const e = (typeof error === 'object' && error !== null ? error : {}) as { message?: unknown; name?: unknown; code?: unknown; errno?: unknown };+ const own = typeof error === 'string' ? error : typeof e.message === 'string' ? e.message : '';+ if (own.trim()) return redactConnectionInfo(redactUrlsInText(own));+ const fields = [+ typeof e.name === 'string' && SAFE_ERROR_FIELD.test(e.name) && e.name !== 'Error' ? e.name : null,+ typeof e.code === 'string' && SAFE_ERROR_FIELD.test(e.code) ? `code ${e.code}` : null,+ typeof e.errno === 'number' && Number.isInteger(e.errno) ? `errno ${e.errno}` : null,+ ].filter((f): f is string => f !== null);+ return fields.length ? `Backup failed with no error message (${fields.join(', ')}).` : 'Backup failed with no error message.';+}+export interface BackupCliResult {exitCode: 0 | 1 | 2;}@@ -170,9 +193,16 @@ export async function runBackupCli(writeCliError(error, 'backup', { json, legacy: { ok: false, reason: 'invalid_params', message: error.message } });return { exitCode: 2 };}- const detail = error as Error & { code?: string; retryable?: boolean };- if (json) console.log(JSON.stringify({ ok: false, reason: detail.code ?? 'backup_failed', message: detail.message, ...(detail.retryable ? { retryable: true } : {}) }));- else console.error(detail.message);+ const detail = (typeof error === 'object' && error !== null ? error : {}) as { code?: unknown; retryable?: unknown };+ const reason = typeof detail.code === 'string' && SAFE_ERROR_FIELD.test(detail.code) ? detail.code : 'backup_failed';+ const message = backupFailureMessage(error);+ const { writeCliError } = await import('../cli/cli-error.ts');+ writeCliError(opError('storage_error', message,+ 'Tell the user the backup failed with this message, then run `gbrain doctor --json` to check storage and locks before retrying.', {+ why: `gbrain backup ${sub} stopped on a database or filesystem error before it finished.`,+ fix: { argv: ['gbrain', 'doctor', '--json'], consent: [], actor: 'agent', requires_exclusive: false,+ why: 'Doctor reports the brain\'s storage, lock and connection state, read-only.', verify: { argv: ['gbrain', 'doctor', '--json'] } },+ }), 'backup', { json, legacy: { ok: false, reason, message, ...(detail.retryable === true ? { retryable: true } : {}) } });return { exitCode: 1 };}}diff --git a/test/backup-cli.serial.test.ts b/test/backup-cli.serial.test.tsindex 42612273c2..1cbf7b130e 100644--- a/test/backup-cli.serial.test.ts+++ b/test/backup-cli.serial.test.ts@@ -14,7 +14,7 @@* with the executeRaw idiom from test/backup-coverage.serial.test.ts —* no real PGLite, no real engine lock.*/-import { describe, test, expect, beforeEach, afterEach } from 'bun:test';+import { describe, test, expect, beforeEach, afterEach, spyOn } from 'bun:test';import { existsSync, mkdtempSync, readFileSync, rmSync } from 'node:fs';import { tmpdir } from 'node:os';import { join } from 'node:path';@@ -33,6 +33,8 @@ import {type BackupStatus,} from '../src/core/backup/status-file.ts';import { surfaceSource } from './helpers/source-surface.ts';+import * as snapshot from '../src/core/backup/snapshot.ts';+import * as fs from 'node:fs';/** The exact literal thrown by src/core/pglite-engine.ts on lock contention.* isLockError in src/commands/backup.ts matches on the leading substring —@@ -466,3 +468,80 @@ describe('runBackupCli — nag impression', () => {expect(existsSync(nagPath)).toBe(false);});});++// ── create/restore failure diagnostic (#5312) ────────────────────────────────++describe('runBackupCli create — failure diagnostic for message-less errors (#5312)', () => {+ async function failCreate(thrown: unknown, json: boolean) {+ const spy = spyOn(snapshot, 'createPgliteBackup').mockImplementation(async () => { throw thrown; });+ const fd1: string[] = [];+ const realWriteSync = fs.writeSync;+ const fdSpy = spyOn(fs, 'writeSync').mockImplementation(((fd: number, buf: Buffer, off = 0, len?: number) => {+ if (fd !== 1) return (realWriteSync as (...a: unknown[]) => number)(fd, buf, off, len);+ const end = len === undefined ? buf.length : off + len;+ fd1.push(Buffer.from(buf).subarray(off, end).toString('utf8'));+ return end - off;+ }) as never);+ const stderrChunks: string[] = [];+ const origStderr = process.stderr.write;+ (process.stderr as { write: unknown }).write = (chunk: unknown) => { stderrChunks.push(String(chunk)); return true; };+ try {+ const args = ['create', '--output', join(tmp, 'out.gbrain-backup'), ...(json ? ['--json'] : [])];+ const r = await run(args, async () => { throw new Error('create never connects'); });+ return { ...r, stdout: `${r.stdout}${fd1.join('')}`, stderr: `${r.stderr}${stderrChunks.join('')}` };+ } finally {+ (process.stderr as { write: unknown }).write = origStderr;+ fdSpy.mockRestore();+ spy.mockRestore();+ }+ }++ test('--json: a thrown {code:"EPERM"} gets a nonempty message, its legacy keys and the v1 contract', async () => {+ const r = await failCreate({ code: 'EPERM' }, true);+ expect(r.exitCode).toBe(1);+ const doc = JSON.parse(r.stdout.trim());+ expect(doc).toMatchObject({ ok: false, reason: 'EPERM', code: 'storage_error' });+ expect(doc.message).toBe('Backup failed with no error message (code EPERM).');+ expect(doc.why).toContain('gbrain backup create stopped');+ expect(doc.fix).toMatchObject({ argv: ['gbrain', 'doctor', '--json'], next: 'run', verify: { argv: ['gbrain', 'doctor', '--json'] } });+ expect(doc.retryable).toBe(false);+ });++ test('human: the same error renders code, message, fix and why, never undefined or [object Object]', async () => {+ const r = await failCreate({ code: 'EPERM', errno: -1 }, false);+ expect(r.exitCode).toBe(1);+ expect(r.stderr).toContain('Error [storage_error]: Backup failed with no error message (code EPERM, errno -1).');+ expect(r.stderr).toContain('Fix: gbrain doctor --json');+ expect(r.stderr).toContain('Why: gbrain backup create stopped');+ expect(r.stderr).not.toContain('undefined');+ expect(r.stderr).not.toContain('[object Object]');+ });++ test('a secret-bearing message-less object is described by safe fields only', async () => {+ const secret = 'postgres://alice-example:[email protected]/brain';+ const thrown = { name: 'ErrnoError', code: 'EIO', connection: secret, toString: () => secret };+ for (const json of [true, false]) {+ const r = await failCreate(thrown, json);+ const out = `${r.stdout}${r.log}${r.stderr}`;+ expect(out).toContain('Backup failed with no error message (ErrnoError, code EIO).');+ expect(out).not.toContain('hunter2-secret');+ }+ });++ test('an error message keeps its text with URL credentials redacted; retryable is preserved', async () => {+ const err = Object.assign(new Error('dump failed for postgres://alice-example:[email protected]/brain'), { code: 'writers_active', retryable: true });+ const r = await failCreate(err, true);+ const doc = JSON.parse(r.stdout.trim());+ expect(doc).toMatchObject({ ok: false, reason: 'writers_active', retryable: true });+ expect(doc.message).toContain('dump failed for');+ expect(JSON.stringify(doc)).not.toContain('hunter2-secret');+ });++ test('null and an empty object still produce a nonempty message', async () => {+ for (const thrown of [null, {}]) {+ const r = await failCreate(thrown, true);+ const doc = JSON.parse(r.stdout.trim());+ expect(doc).toMatchObject({ ok: false, reason: 'backup_failed', message: 'Backup failed with no error message.' });+ }+ });+});