Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(migrations): run migration children through the running CLI, not PATH (#5184)
garrytan1b7be3bf9911
diff --git a/src/commands/migrations/in-process.ts b/src/commands/migrations/in-process.tsindex 9c9c66271b..6cc64d48e3 100644--- a/src/commands/migrations/in-process.ts+++ b/src/commands/migrations/in-process.ts@@ -22,6 +22,7 @@*/import { execSync } from 'child_process';+import { resolveChildCliInvocation } from '../../core/minions/job-isolation.ts';import { loadConfig, toEngineConfig } from '../../core/config.ts';import { buildGatewayConfig } from '../../core/ai/build-gateway-config.ts';@@ -88,6 +89,32 @@ export async function runMigrateOnlyCore(opts?: { timeoutMs?: number }): Promisereturn { engine: config.engine };}+/**+ * #5184: point every `gbrain` command word in a migration's shell command at+ * the CLI that is running this migration (the compiled executable, or bun plus+ * the source entrypoint), through the same `resolveChildCliInvocation` the+ * supervisor and autopilot use. A bare `gbrain` resolved from PATH can be a+ * different version, or a wrapper that sets its own GBRAIN_HOME or database+ * URL, so backfills and installs would act on another brain. When the running+ * CLI cannot be identified the command is left as written (PATH resolution).+ */+export function gbrainChildCommand(+ cmd: string,+ env: Record<string, string | undefined> = process.env,+ execPath: string = process.execPath,+ argv1: string | undefined = process.argv[1],+ platform: NodeJS.Platform = process.platform,+): string {+ const inv = resolveChildCliInvocation(env, execPath, argv1, () => null);+ if (!inv) return cmd;+ // execSync runs cmd.exe on Windows, which does not understand single quotes.+ const quote = platform === 'win32'+ ? (s: string) => `"${s}"`+ : (s: string) => `'${s.replace(/'/g, "'\\''")}'`;+ const prefix = [inv.cmd, ...inv.argsPrefix].map(quote).join(' ');+ return cmd.replace(/(^|\|\||&&|;)(\s*)gbrain(?=\s|$)/g, (_m, sep: string, space: string) => `${sep}${space}${prefix}`);+}+/*** Run a `gbrain ...` subcommand as a subprocess, capturing child stderr so a* failure surfaces the real reason. Used for the non-schema backfill phases@@ -101,7 +128,7 @@ export async function runMigrateOnlyCore(opts?: { timeoutMs?: number }): Promise*/export function runGbrainSubprocess(cmd: string, opts?: { timeoutMs?: number }): string {try {- const out = execSync(cmd, {+ const out = execSync(gbrainChildCommand(cmd), {stdio: ['inherit', 'pipe', 'pipe'],timeout: opts?.timeoutMs ?? MIGRATE_ONLY_TIMEOUT_MS,env: process.env,diff --git a/src/commands/migrations/v0_11_0.ts b/src/commands/migrations/v0_11_0.tsindex fd7980104b..60c58eeed8 100644--- a/src/commands/migrations/v0_11_0.ts+++ b/src/commands/migrations/v0_11_0.ts@@ -24,6 +24,7 @@ import { existsSync, readFileSync, writeFileSync, mkdirSync, appendFileSync, lstimport { join, resolve, dirname } from 'path';import { execSync } from 'child_process';import type { Migration, OrchestratorOpts, OrchestratorResult, OrchestratorPhaseResult } from './types.ts';+import { gbrainChildCommand } from './in-process.ts';import { savePreferences, loadPreferences } from '../../core/preferences.ts';import { loadConfig, configPath, gbrainPath } from '../../core/config.ts';// Bug 3 — appendCompletedMigration moved to the runner (apply-migrations.ts).@@ -84,7 +85,7 @@ async function phaseASchema(opts: OrchestratorOpts): Promise<OrchestratorPhaseRefunction phaseBSmoke(opts: OrchestratorOpts): OrchestratorPhaseResult {if (opts.dryRun) return { name: 'smoke', status: 'skipped', detail: 'dry-run' };try {- execSync('gbrain jobs smoke', { stdio: 'inherit', timeout: 30_000, env: process.env });+ execSync(gbrainChildCommand('gbrain jobs smoke'), { stdio: 'inherit', timeout: 30_000, env: process.env });return { name: 'smoke', status: 'complete' };} catch (e) {const msg = e instanceof Error ? e.message : String(e);@@ -408,7 +409,7 @@ function phaseFInstall(opts: OrchestratorOpts): OrchestratorPhaseResult {if (loadConfig()?.engine === 'pglite') {return { name: 'install', status: 'skipped', detail: 'PGLite is single-writer; use gbrain serve for background maintenance' };}- execSync('gbrain autopilot --install --yes', { stdio: 'inherit', timeout: 60_000, env: process.env });+ execSync(gbrainChildCommand('gbrain autopilot --install --yes'), { stdio: 'inherit', timeout: 60_000, env: process.env });return { name: 'install', status: 'complete' };} catch (e) {return { name: 'install', status: 'failed', detail: e instanceof Error ? e.message : String(e) };diff --git a/src/commands/migrations/v0_12_0.ts b/src/commands/migrations/v0_12_0.tsindex 206e5ed023..55c3c2137d 100644--- a/src/commands/migrations/v0_12_0.ts+++ b/src/commands/migrations/v0_12_0.ts@@ -31,7 +31,7 @@*/import { execSync } from 'child_process';-import { runGbrainSubprocess } from './in-process.ts';+import { gbrainChildCommand, runGbrainSubprocess } from './in-process.ts';import type { Migration, OrchestratorOpts, OrchestratorResult, OrchestratorPhaseResult } from './types.ts';import { childGlobalFlags } from '../../core/cli-options.ts';// Bug 3 — ledger writes moved to the runner (apply-migrations.ts).@@ -69,7 +69,7 @@ function phaseBConfigCheck(opts: OrchestratorOpts): OrchestratorPhaseResult & {// Default behavior when unset = enabled (per isAutoLinkEnabled).let raw = '';try {- raw = execSync('gbrain config get auto_link', { encoding: 'utf-8', timeout: 10_000, env: process.env }).trim();+ raw = execSync(gbrainChildCommand('gbrain config get auto_link'), { encoding: 'utf-8', timeout: 10_000, env: process.env }).trim();} catch {// get exits non-zero when the key isn't set — that's fine, defaults to enabled.raw = '';@@ -124,7 +124,7 @@ interface StatsSnapshot {function readStats(): StatsSnapshot | null {try {- const out = execSync('gbrain get_stats --json 2>/dev/null || gbrain stats', {+ const out = execSync(gbrainChildCommand('gbrain get_stats --json 2>/dev/null || gbrain stats'), {encoding: 'utf-8', timeout: 30_000, env: process.env,});// The fallback `gbrain stats` prints human-readable output; parse loosely.diff --git a/src/commands/migrations/v0_12_2.ts b/src/commands/migrations/v0_12_2.tsindex 28d61d0ba4..27ae984f95 100644--- a/src/commands/migrations/v0_12_2.ts+++ b/src/commands/migrations/v0_12_2.ts@@ -21,7 +21,7 @@*/import { execSync } from 'child_process';-import { runGbrainSubprocess } from './in-process.ts';+import { gbrainChildCommand, runGbrainSubprocess } from './in-process.ts';import type { Migration, OrchestratorOpts, OrchestratorResult, OrchestratorPhaseResult } from './types.ts';import { childGlobalFlags } from '../../core/cli-options.ts';// Bug 3 — ledger writes moved to the runner (apply-migrations.ts).@@ -66,7 +66,7 @@ function phaseCVerify(opts: OrchestratorOpts): OrchestratorPhaseResult {// Any accidental stdout progress from the child would break JSON.parse// (per Codex review #12). NOTE: we deliberately do NOT pass// --progress-json here — this child is parsed, not watched.- const out = execSync('gbrain repair-jsonb --dry-run --json', {+ const out = execSync(gbrainChildCommand('gbrain repair-jsonb --dry-run --json'), {encoding: 'utf-8', timeout: 60_000, env: process.env,stdio: ['ignore', 'pipe', 'inherit'],});diff --git a/src/commands/migrations/v0_13_0.ts b/src/commands/migrations/v0_13_0.tsindex 076369725b..181b460a97 100644--- a/src/commands/migrations/v0_13_0.ts+++ b/src/commands/migrations/v0_13_0.ts@@ -26,7 +26,7 @@*/import { execSync } from 'child_process';-import { runGbrainSubprocess } from './in-process.ts';+import { gbrainChildCommand, runGbrainSubprocess } from './in-process.ts';import type { Migration, OrchestratorOpts, OrchestratorResult, OrchestratorPhaseResult } from './types.ts';// Bug 3 — ledger writes moved to the runner (apply-migrations.ts). The// orchestrator returns its result and the runner persists it.@@ -38,12 +38,14 @@ import type { Migration, OrchestratorOpts, OrchestratorResult, OrchestratorPhase// ~10s (ALTER + index builds). Bumped timeout accounts for slow Supabase// links (v0.12.1 pattern — migrations can time out on the 60s default).//-// Shell out to the canonical `gbrain` shim on PATH (`/usr/local/bin/gbrain`-// by default). An earlier revision resolved via the active Node/Bun runtime-// binary, but on bun-installed trees that binary is `bun` — the spawned-// `bun extract ...` gets reinterpreted as `bun run extract` and crashes the-// upgrade mid-migration. The shim is already the canonical wrapper; trust-// it. Regression guarded by test/migrations-v0_13_0.test.ts.+// Children run the CLI that is running this migration (#5184,+// gbrainChildCommand): the compiled executable, or bun plus the running+// cli.ts, else the `gbrain` on PATH. An earlier revision spawned the bare+// runtime binary, which on bun-installed trees is `bun` — `bun extract ...`+// was reinterpreted as `bun run extract` and crashed the upgrade+// mid-migration; resolveChildCliInvocation never returns bun without the+// cli.ts entrypoint. Regression guarded by test/migrations-v0_13_0.test.ts+// and test/migration-child-cli.test.ts.async function phaseASchema(opts: OrchestratorOpts): Promise<OrchestratorPhaseResult> {if (opts.dryRun) return { name: 'schema', status: 'skipped', detail: 'dry-run' };@@ -87,7 +89,7 @@ function phaseCVerify(opts: OrchestratorOpts): OrchestratorPhaseResult {// docs-only brains, and brains with no entity pages legitimately// produce 0. Phase B's own stdout shows `Links: created N` which is// the authoritative signal — user sees it during upgrade.- const out = execSync('gbrain call get_stats', {+ const out = execSync(gbrainChildCommand('gbrain call get_stats'), {encoding: 'utf-8', timeout: 60_000, env: process.env,});const parsed = JSON.parse(out) as { link_count?: number; page_count?: number };diff --git a/test/apply-migrations-safety.serial.test.ts b/test/apply-migrations-safety.serial.test.tsindex b2a1c2500b..ed83b006f9 100644--- a/test/apply-migrations-safety.serial.test.ts+++ b/test/apply-migrations-safety.serial.test.ts@@ -207,7 +207,7 @@ await runApplyMigrations(process.argv.slice(2));writeFileSync(join(bin, 'gbrain'), `#!/bin/sh\nprintf '%s\\n' "$*" >> '${calls}'\nif [ "$1" = autopilot ]; then exit 99; fi\nexit 0\n`, { mode: 0o755 });const result = await runCli(['apply-migrations', '--yes', '--migration', '0.11.0'], {home, cwd: home,- env: { PATH: `${bin}:${process.env.PATH ?? ''}`, GBRAIN_NO_AUTOPILOT_INSTALL: undefined },+ env: { PATH: `${bin}:${process.env.PATH ?? ''}`, GBRAIN_JOB_CHILD_CLI: join(bin, 'gbrain'), GBRAIN_NO_AUTOPILOT_INSTALL: undefined },});expect(readFileSync(calls, 'utf8')).not.toContain('autopilot');expect(result.exitCode).toBe(0);@@ -231,7 +231,7 @@ await runApplyMigrations(process.argv.slice(2));const args = ['apply-migrations', '--yes', '--migration', '0.11.0', ...(disable === 'flag' ? ['--no-autopilot-install'] : [])];const result = await runCli(args, {home, cwd: home,- env: { PATH: `${bin}:${process.env.PATH ?? ''}`, GBRAIN_NO_AUTOPILOT_INSTALL: disable === 'env' ? '1' : undefined },+ env: { PATH: `${bin}:${process.env.PATH ?? ''}`, GBRAIN_JOB_CHILD_CLI: join(bin, 'gbrain'), GBRAIN_NO_AUTOPILOT_INSTALL: disable === 'env' ? '1' : undefined },});expect(result.exitCode).toBe(0);expect(entries(ledger).at(-1)!.status).toBe('complete');diff --git a/test/migration-child-cli.test.ts b/test/migration-child-cli.test.tsnew file mode 100644index 0000000000..931f52f20d--- /dev/null+++ b/test/migration-child-cli.test.ts@@ -0,0 +1,80 @@+/**+ * #5184: migration children run the CLI that is running the migration, not+ * whatever `gbrain` PATH resolves to. A PATH `gbrain` can be another version,+ * or a wrapper that sets its own GBRAIN_HOME / database URL, so backfills+ * (extract links/timeline, repair-jsonb), smoke checks and the autopilot+ * install acted on another brain.+ */++import { describe, test, expect } from 'bun:test';+import { mkdtempSync, readdirSync, readFileSync, rmSync, writeFileSync } from 'fs';+import { join, resolve } from 'path';+import { tmpdir } from 'os';++import { gbrainChildCommand, runGbrainSubprocess } from '../src/commands/migrations/in-process.ts';+import { withEnv } from './helpers/with-env.ts';++const REPO = resolve(import.meta.dir, '..');++describe('#5184 gbrainChildCommand', () => {+ test('a compiled CLI replaces every gbrain command word, including after ||', () => {+ expect(gbrainChildCommand('gbrain get_stats --json 2>/dev/null || gbrain stats', {}, '/opt/gbrain-1/gbrain', undefined))+ .toBe("'/opt/gbrain-1/gbrain' get_stats --json 2>/dev/null || '/opt/gbrain-1/gbrain' stats");+ });++ test('a source run invokes bun with the running cli.ts', () => {+ expect(gbrainChildCommand('gbrain extract links --source db', {}, '/usr/local/bin/bun', '/repo/src/cli.ts'))+ .toBe("'/usr/local/bin/bun' '/repo/src/cli.ts' extract links --source db");+ });++ test('paths with quotes stay one shell word', () => {+ expect(gbrainChildCommand('gbrain jobs smoke', {}, "/opt/o'brien/gbrain", undefined))+ .toBe("'/opt/o'\\''brien/gbrain' jobs smoke");+ });++ test('Windows uses double quotes (execSync runs cmd.exe there)', () => {+ expect(gbrainChildCommand('gbrain jobs smoke', {}, 'C:\\Program Files\\gbrain\\gbrain.exe', undefined, 'win32'))+ .toBe('"C:\\Program Files\\gbrain\\gbrain.exe" jobs smoke');+ });++ test('only command words change: arguments and other commands are left alone', () => {+ expect(gbrainChildCommand('gbrain jobs submit gbrain-x', {}, '/b/gbrain', undefined)).toBe("'/b/gbrain' jobs submit gbrain-x");+ expect(gbrainChildCommand("sh -c 'echo gbrain'", {}, '/b/gbrain', undefined)).toBe("sh -c 'echo gbrain'");+ });++ test('when the running CLI cannot be identified, PATH resolution is kept', () => {+ expect(gbrainChildCommand('gbrain jobs smoke', {}, '/usr/local/bin/bun', '/repo/test/x.test.ts')).toBe('gbrain jobs smoke');+ });+});++describe('#5184 runGbrainSubprocess runs the resolved CLI, not a PATH decoy', () => {+ test('the child is the resolved CLI even with a different gbrain first on PATH', async () => {+ const dir = mkdtempSync(join(tmpdir(), 'gbrain-5184-'));+ try {+ writeFileSync(join(dir, 'gbrain'), '#!/bin/sh\necho "DECOY $@"\n', { mode: 0o755 });+ const running = join(dir, 'running-cli');+ writeFileSync(running, '#!/bin/sh\necho "RUNNING $@"\n', { mode: 0o755 });+ await withEnv({ PATH: `${dir}:${process.env.PATH ?? ''}`, GBRAIN_JOB_CHILD_CLI: running }, () => {+ expect(runGbrainSubprocess('gbrain extract links --source db').trim()).toBe('RUNNING extract links --source db');+ });+ } finally {+ rmSync(dir, { recursive: true, force: true });+ }+ });+});++describe('#5184 no migration spawns a name-resolved gbrain', () => {+ test('every direct execSync of a gbrain command goes through gbrainChildCommand', () => {+ const dir = join(REPO, 'src', 'commands', 'migrations');+ const offenders: string[] = [];+ for (const file of readdirSync(dir).filter(f => f.endsWith('.ts'))) {+ const src = readFileSync(join(dir, file), 'utf-8');+ const lines = src.split('\n');+ lines.forEach((line, i) => {+ if (/^\s*(\/\/|\*)/.test(line)) return;+ if (/(?:execSync|spawnSync|execFileSync)\(\s*['"`]gbrain\b/.test(line)) offenders.push(`${file}:${i + 1}`);+ });+ }+ expect(offenders).toEqual([]);+ });+});diff --git a/test/migrations-v0_13_0.test.ts b/test/migrations-v0_13_0.test.tsindex 8e213fe5d2..04778f0e76 100644--- a/test/migrations-v0_13_0.test.ts+++ b/test/migrations-v0_13_0.test.ts@@ -61,8 +61,9 @@ describe('v0.13.0 — Frontmatter relationship indexing migration', () => {// Backfill extract goes through the stderr-capturing wrapper (still bare// `gbrain` so the canonical shim on PATH wins).expect(src).toContain("runGbrainSubprocess('gbrain extract links --source db --include-frontmatter'");- // Stats readback still shells out (reads stdout); bare gbrain.- expect(src).toContain("execSync('gbrain call get_stats'");+ // Stats readback still shells out (reads stdout), through the running+ // CLI rather than PATH (#5184).+ expect(src).toContain("execSync(gbrainChildCommand('gbrain call get_stats')");});test('phase commands never reference `bun` or `.ts` paths (Bug 1 regression)', () => {