Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

feat(post-upgrade): D2 --json report document

garrytane3549e491b40
diff --git a/src/cli/command-table.ts b/src/cli/command-table.ts
index 4defafbb70..8f1d61b40c 100644
--- a/src/cli/command-table.ts
+++ b/src/cli/command-table.ts
@@ -186,7 +186,7 @@ export const CLI_COMMANDS: readonly CliCommandRecord[] = [ // Pre-connect: disp
// the pre-engine lane, so help never touches the PGLite lock).
{ name: 'backup', phase: 'pre-connect-own-engine', thinClient: 'none', selfHelp: true, load: () => import('./commands/backup.ts') },
{ name: 'upgrade', phase: 'pre-connect', thinClient: 'none', selfHelp: true, skipStartupHooks: true, load: () => import('./commands/upgrade.ts') },
- { name: 'post-upgrade', phase: 'pre-connect', thinClient: 'none', selfHelp: true, skipStartupHooks: true, load: () => import('./commands/post-upgrade.ts') },
+ { name: 'post-upgrade', phase: 'pre-connect', thinClient: 'none', selfHelp: true, skipStartupHooks: true, json: 'document', load: () => import('./commands/post-upgrade.ts') },
{ name: 'check-update', phase: 'pre-connect', thinClient: 'none', selfHelp: true, skipStartupHooks: true, load: () => import('./commands/check-update.ts') },
// selfHelp: v0.42 self-upgrade ships its own usage (flags + the agent-skill story).
{ name: 'self-upgrade', phase: 'pre-connect', thinClient: 'none', selfHelp: true, skipStartupHooks: true, load: () => import('./commands/self-upgrade.ts') },
diff --git a/src/commands/apply-migrations.ts b/src/commands/apply-migrations.ts
index 4f35a9ceeb..19fcdfd60c 100644
--- a/src/commands/apply-migrations.ts
+++ b/src/commands/apply-migrations.ts
@@ -361,7 +361,8 @@ function unknownMigrationError(version: string): OperationError {
/** The same invocation again once the underlying failure is fixed; any approval it needs is asked by the run itself. */
function rerunFix(args: readonly string[], why: string, yes = false) {
- const argv = ['gbrain', COMMAND, ...args, ...(yes && !args.includes('--yes') ? ['--yes'] : [])];
+ // Approval flags are dropped: the rerun asks for any consent effect itself.
+ const argv = ['gbrain', COMMAND, ...args.filter(a => a !== '--yes' && a !== '--non-interactive'), ...(yes ? ['--yes'] : [])];
return { argv, consent: [] as Effect[], actor: 'agent' as const, requires_exclusive: true, why };
}
diff --git a/src/commands/upgrade.ts b/src/commands/upgrade.ts
index 3019c3f6bc..1d7ac81930 100644
--- a/src/commands/upgrade.ts
+++ b/src/commands/upgrade.ts
@@ -2,7 +2,9 @@ import { execSync, execFileSync, spawnSync } from 'child_process';
import { existsSync, readFileSync, writeFileSync, mkdirSync, appendFileSync, realpathSync } from 'fs';
import { basename, join, dirname, resolve } from 'path';
import { parseSemver, semverGt } from '../core/semver.ts';
-import { setCliExitVerdict } from '../core/cli-force-exit.ts';
+import { jsonRequested, setCliExitVerdict, writeJsonDocument } from '../core/cli-force-exit.ts';
+import { opError, type OperationError } from '../core/ops/contract.ts';
+import { writeCliError } from '../cli/cli-error.ts';
import { VERSION } from '../version.ts';
import { migrationLedgerSummary } from '../core/migration-ledger.ts';
import { MIGRATIONS_RUNNING_EXIT_CODE, readMigrationLockHolder } from '../core/migration-orchestration-lock.ts';
@@ -577,12 +579,16 @@ async function applySelfUpgradeSetup(noAutopilotInstall: boolean): Promise<void>
export async function runPostUpgrade(args: string[] = []): Promise<void> {
if (args.includes('--help') || args.includes('-h')) {
- console.log('Usage: gbrain post-upgrade [--no-autopilot-install]');
+ console.log('Usage: gbrain post-upgrade [--no-autopilot-install] [--json]');
console.log('Prints feature pitches for new migrations and runs apply-migrations.');
console.log('--no-autopilot-install (or GBRAIN_NO_AUTOPILOT_INSTALL=1) skips autopilot installation and service rewrites.');
+ console.log('--json prints one result document on stdout (progress and banners go to stderr).');
console.log('Idempotent — safe to re-run any time.');
return;
}
+ // D2: under --json the human lines go to stderr (the guard) and this report is the one document.
+ const json = jsonRequested(args);
+ const report: PostUpgradeReport = { status: 'ok', warnings: [] };
// v0.35.8.0: lay down ~/.gbrain/.gitignore retroactively. Existing users
// never re-run `gbrain init`, so init-only coverage misses them entirely
@@ -629,8 +635,12 @@ export async function runPostUpgrade(args: string[] = []): Promise<void> {
// when nothing is pending. Stays inside the same process so a long Phase F
// (autopilot install) doesn't hit a subprocess boundary.
try {
- const { runApplyMigrations } = await import('./apply-migrations.ts');
- await runApplyMigrations(['--yes', '--non-interactive', ...(noAutopilotInstall ? ['--no-autopilot-install'] : [])]);
+ const { applyMigrations } = await import('./apply-migrations.ts');
+ const { exitCode, failure } = await applyMigrations(['--yes', '--non-interactive', ...(noAutopilotInstall ? ['--no-autopilot-install'] : [])]);
+ report.apply_migrations = { exit_code: exitCode ?? 0 };
+ // Any status apply-migrations returns ends post-upgrade here, as its
+ // in-process process.exit always did.
+ if (exitCode !== undefined) process.exit(finishPostUpgrade(json, report, exitCode, failure));
} catch (e) {
// Surface the error but don't throw — post-upgrade is best-effort.
// Users can re-run `gbrain apply-migrations` manually if they want
@@ -638,6 +648,7 @@ export async function runPostUpgrade(args: string[] = []): Promise<void> {
const msg = e instanceof Error ? e.message : String(e);
console.error(`\napply-migrations failed: ${msg}`);
console.error('Run `gbrain apply-migrations --yes` manually to retry.');
+ report.warnings.push(`apply-migrations failed: ${msg}`);
}
// v0.28.5 (X1): explicitly apply pending schema migrations.
@@ -659,6 +670,7 @@ export async function runPostUpgrade(args: string[] = []): Promise<void> {
await engine.connect(toCfgSchema(cfgSchema));
await engine.initSchema();
console.log(' Schema up to date.');
+ report.schema = 'up_to_date';
// v0.32.3 search-lite mode banner. One-shot: fires at most once per
// install (state persisted via `search.mode_upgrade_notice_shown`).
@@ -832,6 +844,7 @@ export async function runPostUpgrade(args: string[] = []): Promise<void> {
} catch (re) {
const msg = re instanceof Error ? re.message : String(re);
console.warn(`\nChunker-bump reindex skipped: ${msg}`);
+ report.warnings.push(`chunker-bump reindex skipped: ${msg}`);
console.warn('Run `gbrain reindex --markdown` manually when ready.');
}
@@ -854,6 +867,8 @@ export async function runPostUpgrade(args: string[] = []): Promise<void> {
// hint to run `gbrain init --migrate-only`.
const msg = e instanceof Error ? e.message : String(e);
console.warn(`\nSchema auto-apply skipped: ${msg}`);
+ report.schema = 'skipped';
+ report.warnings.push(`schema auto-apply skipped: ${msg}`);
console.warn('Run `gbrain init --migrate-only` manually if your brain is wedged.');
}
@@ -893,6 +908,31 @@ export async function runPostUpgrade(args: string[] = []): Promise<void> {
} catch {
// Fail-open per A18: never crash post-upgrade from the banner.
}
+ if (json) await writeJsonDocument(JSON.stringify(report));
+}
+
+interface PostUpgradeReport {
+ status: 'ok' | 'failed';
+ apply_migrations?: { exit_code: number };
+ schema?: 'up_to_date' | 'skipped';
+ warnings: string[];
+}
+
+/**
+ * D2: the exit status once apply-migrations ended the run. Success under
+ * --json writes the report; a failure (apply-migrations already printed its
+ * human lines) is one envelope leading with the report's keys.
+ */
+function finishPostUpgrade(json: boolean, report: PostUpgradeReport, exitCode: number, failure?: OperationError): number {
+ if (exitCode === 0) {
+ if (json) void writeJsonDocument(JSON.stringify(report));
+ return 0;
+ }
+ report.status = 'failed';
+ if (!json) return exitCode;
+ const e = failure ?? opError('migration_failed', `apply-migrations exited with status ${exitCode}.`,
+ 'Read stderr for the failing migration, fix it, then run `gbrain post-upgrade` again.');
+ return writeCliError(e, 'post-upgrade', { json: true, stderr: false, legacy: { ...report } });
}
/**
diff --git a/src/core/cli-flag-registry.generated.ts b/src/core/cli-flag-registry.generated.ts
index cda15efe57..db1612ec76 100644
--- a/src/core/cli-flag-registry.generated.ts
+++ b/src/core/cli-flag-registry.generated.ts
@@ -17,7 +17,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {
'advisor': ['--apply', '--brain', '--help', '--json', '--skills-dir', '--source', '--workspace', '--yes'],
'agent': ['--allow-old-serve', '--brain', '--detach', '--fanout-manifest', '--federated-read', '--flags', '--follow', '--harness', '--help', '--http', '--json', '--max-turns', '--mcp-only', '--model', '--no-follow', '--path', '--port', '--preset', '--reissue', '--scopes', '--show-token', '--since', '--source', '--subagent-def', '--surface', '--timeout-ms', '--token-ttl', '--tools', '--url', '--word', '--yes'],
'anomalies': ['--brain', '--help', '--json', '--lookback-days', '--mcp-only', '--sigma', '--since', '--source'],
- 'apply-migrations': ['--acknowledge-no-backup', '--apply', '--backup-confirmed', '--brain', '--break-lock', '--confirm-quiesced', '--content-root', '--dry-run', '--export-db-only', '--export-source', '--force', '--force-all', '--force-orchestrator', '--force-retry', '--force-schema', '--help', '--host-dir', '--http', '--json', '--list', '--locks', '--migrate-only', '--migration', '--mode', '--no-autopilot-install', '--non-interactive', '--require-db', '--skip-verify', '--source', '--yes'],
+ 'apply-migrations': ['--acknowledge-no-backup', '--apply', '--backup-confirmed', '--brain', '--break-lock', '--confirm-quiesced', '--content-root', '--dry-run', '--export-db-only', '--export-source', '--force', '--force-all', '--force-orchestrator', '--force-retry', '--force-schema', '--help', '--host-dir', '--http', '--json', '--list', '--locks', '--migrate-only', '--migration', '--mode', '--no-autopilot-install', '--no-embedding', '--non-interactive', '--pglite', '--require-db', '--skip-verify', '--source', '--uninstall', '--yes'],
'auth': ['--add', '--admin-intent', '--adopt-columns', '--adopt-permissions', '--all-new', '--allowed-operations', '--before', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--budget-usd-per-day', '--cleanup-dead-local-locks', '--client', '--confirm-quiesced', '--days', '--delegated-namespace', '--delegated-slug-prefixes', '--dry-run', '--enable-dcr-insecure', '--expected-epoch', '--expected-state', '--federated-read', '--fix', '--force', '--grant-types', '--help', '--id', '--if-version', '--json', '--limit', '--manifest', '--max-concurrent', '--migrate-legacy', '--no-pull', '--operations', '--path', '--probe', '--profile', '--read-sources', '--redirect-uri', '--refresh-operations', '--repair', '--replace', '--request-id', '--reset-default', '--retry-failed', '--scopes', '--self-transfer', '--shared-skills', '--slug-prefixes', '--source', '--source-ids', '--sources', '--surface', '--takes-holders', '--token', '--token-endpoint-auth-method', '--token-ttl', '--usage', '--yes'],
'autopilot': ['--batch', '--brain', '--check', '--dimensions', '--dir', '--drain', '--embedding-dimensions', '--embedding-model', '--explain', '--ff-only', '--force', '--force-retry', '--from-pages', '--help', '--inject-bootstrap', '--inline', '--install', '--interval', '--json', '--markdown', '--max-rss', '--max-usd', '--migrate-only', '--no-autopilot-install', '--no-bun-floor-check', '--no-inject', '--no-worker', '--non-interactive', '--now', '--once', '--output', '--params', '--path', '--pause', '--phase', '--reason', '--refresh-cache', '--remediation-plan', '--repo', '--resume', '--source', '--stale', '--status', '--swap-only', '--target', '--uninstall', '--user', '--verify', '--version', '--yes'],
'backfill': ['--batch-size', '--brain', '--concurrency', '--dry-run', '--fresh', '--help', '--json', '--keep-index', '--list', '--max-errors', '--max-rows', '--resume', '--source'],
@@ -87,7 +87,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {
'orphans': ['--accept-pending', '--background', '--brain', '--count', '--explain', '--follow', '--help', '--include-pseudo', '--json', '--mode', '--no-accept-pending', '--progress-interval', '--progress-json', '--quiet', '--source', '--timeout', '--wait'],
'pages': ['--brain', '--dry-run', '--help', '--json', '--older-than', '--source'],
'pglite-repair': ['--apply', '--brain', '--break-lock', '--dry-run', '--expect', '--help', '--http', '--json', '--max-cost', '--max-usd', '--non-interactive', '--path', '--source', '--trust', '--vectors', '--yes'],
- 'post-upgrade': ['--acknowledge-no-backup', '--admin-intent', '--all', '--apply', '--apply-clean-hunks', '--backup-confirmed', '--brain', '--check', '--concurrency', '--confirm-quiesced', '--content-root', '--cost-estimate', '--embedding-dimensions', '--embedding-model', '--expected-epoch', '--expected-state', '--export-db-only', '--export-source', '--ff-only', '--force', '--force-all', '--force-orchestrator', '--force-retry', '--force-schema', '--format', '--help', '--host-dir', '--inject-bootstrap', '--inline', '--install', '--interval', '--json', '--limit', '--list', '--manifest', '--markdown', '--max-rss', '--migrate-only', '--migration', '--mode', '--multimodal', '--name-only', '--no-autopilot-install', '--no-bun-floor-check', '--no-embed', '--no-inject', '--no-worker', '--non-interactive', '--now', '--once', '--path', '--pause', '--quiet', '--reason', '--remediation-plan', '--repo', '--require-db', '--resume', '--self-transfer', '--skills-dir', '--skip-verify', '--source', '--stale', '--status', '--swap-only', '--target', '--uninstall', '--user', '--vectors', '--verify', '--version', '--workers', '--yes'],
+ 'post-upgrade': ['--acknowledge-no-backup', '--admin-intent', '--all', '--apply', '--apply-clean-hunks', '--backup-confirmed', '--brain', '--check', '--concurrency', '--confirm-quiesced', '--content-root', '--cost-estimate', '--embedding-dimensions', '--embedding-model', '--expected-epoch', '--expected-state', '--export-db-only', '--export-source', '--ff-only', '--force', '--force-all', '--force-orchestrator', '--force-retry', '--force-schema', '--format', '--help', '--host-dir', '--inject-bootstrap', '--inline', '--install', '--interval', '--json', '--limit', '--list', '--manifest', '--markdown', '--max-rss', '--migrate-only', '--migration', '--mode', '--multimodal', '--name-only', '--no-autopilot-install', '--no-bun-floor-check', '--no-embed', '--no-embedding', '--no-inject', '--no-worker', '--non-interactive', '--now', '--once', '--path', '--pause', '--pglite', '--quiet', '--reason', '--remediation-plan', '--repo', '--require-db', '--resume', '--self-transfer', '--skills-dir', '--skip-verify', '--source', '--stale', '--status', '--swap-only', '--target', '--uninstall', '--user', '--vectors', '--verify', '--version', '--workers', '--yes'],
'pricing': ['--brain', '--help', '--input', '--json', '--max-cost', '--max-runtime', '--output', '--rate', '--source'],
'projections': ['--brain', '--enable-dcr', '--help', '--http', '--install', '--json', '--limit', '--now', '--port', '--public-url', '--remove', '--source', '--status', '--surface', '--user'],
'protocol': ['--access', '--asof', '--bound-slug-prefixes', '--brain', '--date', '--days', '--entities', '--fact', '--federated-read', '--file', '--full', '--help', '--http', '--image', '--json', '--kind', '--limit', '--mode', '--multimodal', '--once', '--page', '--path', '--session', '--since', '--slug', '--slugs', '--source', '--sources', '--stats', '--surface', '--synthesize', '--take', '--target', '--timeline', '--token', '--trusted-extraction', '--types', '--url', '--yes'],
@@ -126,7 +126,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {
'takes': ['--accept', '--batch-size', '--brain', '--bucket-size', '--by', '--claim', '--dim', '--dir', '--domain', '--dry-run', '--embedding-dimensions', '--embedding-model', '--evidence', '--expected-revision', '--expired', '--force', '--from-pages', '--help', '--holder', '--include-covered', '--json', '--kind', '--limit', '--max-pages', '--no-embed', '--no-embedding', '--offset', '--outcome', '--path', '--quality', '--reject', '--request-id', '--row', '--semantic', '--since', '--sort', '--source', '--source-id', '--stale', '--status', '--supabase', '--to', '--unit', '--until', '--value', '--weight', '--who', '--yes'],
'think': ['--anchor', '--brain', '--calibration-holder', '--help', '--json', '--mcp-only', '--model', '--rounds', '--save', '--since', '--source', '--take', '--until', '--with-calibration'],
'transcripts': ['--accept-pending', '--all', '--all-discovery', '--background', '--brain', '--days', '--dry-run', '--embed', '--explain', '--facts', '--follow', '--format', '--full', '--help', '--include-self', '--json', '--limit', '--max-bytes', '--max-cost-usd', '--no-accept-pending', '--progress-interval', '--progress-json', '--quiet', '--since', '--source', '--source-id', '--timeout', '--wait'],
- 'upgrade': ['--acknowledge-no-backup', '--admin-intent', '--all', '--apply', '--apply-clean-hunks', '--backup-confirmed', '--brain', '--check', '--concurrency', '--confirm-quiesced', '--content-root', '--cost-estimate', '--embedding-dimensions', '--embedding-model', '--expected-epoch', '--expected-state', '--export-db-only', '--export-source', '--ff-only', '--force', '--force-all', '--force-orchestrator', '--force-retry', '--force-schema', '--format', '--help', '--host-dir', '--inject-bootstrap', '--inline', '--install', '--interval', '--json', '--limit', '--list', '--manifest', '--markdown', '--max-rss', '--migrate-only', '--migration', '--mode', '--multimodal', '--name-only', '--no-autopilot-install', '--no-bun-floor-check', '--no-embed', '--no-inject', '--no-worker', '--non-interactive', '--now', '--once', '--path', '--pause', '--quiet', '--reason', '--remediation-plan', '--repo', '--require-db', '--resume', '--self-transfer', '--skills-dir', '--skip-verify', '--source', '--stale', '--status', '--swap-only', '--target', '--uninstall', '--user', '--vectors', '--verify', '--version', '--workers', '--yes'],
+ 'upgrade': ['--acknowledge-no-backup', '--admin-intent', '--all', '--apply', '--apply-clean-hunks', '--backup-confirmed', '--brain', '--check', '--concurrency', '--confirm-quiesced', '--content-root', '--cost-estimate', '--embedding-dimensions', '--embedding-model', '--expected-epoch', '--expected-state', '--export-db-only', '--export-source', '--ff-only', '--force', '--force-all', '--force-orchestrator', '--force-retry', '--force-schema', '--format', '--help', '--host-dir', '--inject-bootstrap', '--inline', '--install', '--interval', '--json', '--limit', '--list', '--manifest', '--markdown', '--max-rss', '--migrate-only', '--migration', '--mode', '--multimodal', '--name-only', '--no-autopilot-install', '--no-bun-floor-check', '--no-embed', '--no-embedding', '--no-inject', '--no-worker', '--non-interactive', '--now', '--once', '--path', '--pause', '--pglite', '--quiet', '--reason', '--remediation-plan', '--repo', '--require-db', '--resume', '--self-transfer', '--skills-dir', '--skip-verify', '--source', '--stale', '--status', '--swap-only', '--target', '--uninstall', '--user', '--vectors', '--verify', '--version', '--workers', '--yes'],
'waiting': ['--all', '--as-of', '--brain', '--help', '--json', '--note', '--source', '--stale-ok', '--status', '--tools-json', '--top', '--type'],
'watch': ['--brain', '--help', '--json', '--max-pages', '--min-confidence', '--source', '--window-turns'],
'whoknows': ['--access', '--asof', '--bound-slug-prefixes', '--brain', '--date', '--days', '--entities', '--explain', '--fact', '--federated-read', '--file', '--full', '--help', '--http', '--image', '--json', '--kind', '--limit', '--mcp-only', '--mode', '--multimodal', '--once', '--page', '--path', '--session', '--since', '--slug', '--slugs', '--source', '--sources', '--stats', '--surface', '--take', '--timeline', '--trusted-extraction', '--types', '--url', '--yes'],
diff --git a/test/cli-contract.serial.test.ts b/test/cli-contract.serial.test.ts
index 27d862f240..9d8ed5b0ed 100644
--- a/test/cli-contract.serial.test.ts
+++ b/test/cli-contract.serial.test.ts
@@ -87,6 +87,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 },
+ '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 },
};
diff --git a/test/upgrade-no-autopilot.serial.test.ts b/test/upgrade-no-autopilot.serial.test.ts
index 737586ca05..eeed22df79 100644
--- a/test/upgrade-no-autopilot.serial.test.ts
+++ b/test/upgrade-no-autopilot.serial.test.ts
@@ -50,7 +50,7 @@ describe('upgrade autopilot opt-out propagation', () => {
writeFileSync(driver, `import { mock } from 'bun:test';
import { writeFileSync } from 'node:fs';
mock.module(${JSON.stringify(join(REPO, 'src/commands/apply-migrations.ts'))}, () => ({
- runApplyMigrations: async (args) => writeFileSync(${JSON.stringify(join(home, 'args.json'))}, JSON.stringify(args)),
+ applyMigrations: async (args) => { writeFileSync(${JSON.stringify(join(home, 'args.json'))}, JSON.stringify(args)); return { exitCode: undefined }; },
}));
const { runPostUpgrade } = await import(${JSON.stringify(join(REPO, 'src/commands/upgrade.ts'))});
await runPostUpgrade(['--no-autopilot-install']);