Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(upgrade): refuse --dry-run outside --restart-only, scrub git env for the stable lookup, keep docs and help resolvable

garrytanfc5a7d6e6a83
diff --git a/docs/RELEASING.md b/docs/RELEASING.md
index da9a7937af..cc2049df8d 100644
--- a/docs/RELEASING.md
+++ b/docs/RELEASING.md
@@ -608,7 +608,7 @@ gh workflow run promote-stable.yml -f version=<VERSION> \
`https://raw.githubusercontent.com/<owner>/<repo>/stable/VERSION`.
`refs/tags/stable-v<VERSION>` is an immutable annotated record created on a
version's first promotion and never moved or deleted. Both carry the same
- message: a `gbrain stable channel: v<VERSION>` title, then one
+ message: a title line (`gbrain`, then `stable channel: v<VERSION>`), then one
`key: value` line each for `version`, `commit`, `tree`, `soak_run`,
`scoreboard`, `promoted_by`, `promoted_at` (UTC), `previous`
(`none` on the first promotion), `rollback` and `reason` (`-` when
diff --git a/scripts/generate-flag-registry.ts b/scripts/generate-flag-registry.ts
index 850a82901c..717ff0ab0a 100644
--- a/scripts/generate-flag-registry.ts
+++ b/scripts/generate-flag-registry.ts
@@ -70,6 +70,10 @@ const DELEGATED_MODULES: Record<string, string[]> = {
// `forget --purge` (and forget --help) hand the argv to runForgetPurge, which
// parses --dry-run itself; a plain forget refuses --dry-run (recall.ts).
forget: ['src/commands/forget-purge.ts'],
+ // `upgrade --restart-only --dry-run` is parsed by restartDryRun in
+ // upgrade-restart.ts, which refuses --dry-run without --restart-only;
+ // post-upgrade shares upgrade.ts and never takes it.
+ upgrade: ['src/commands/upgrade-restart.ts'],
};
/**
diff --git a/src/commands/upgrade-restart.ts b/src/commands/upgrade-restart.ts
index 3e89e4194f..33622ee205 100644
--- a/src/commands/upgrade-restart.ts
+++ b/src/commands/upgrade-restart.ts
@@ -176,6 +176,21 @@ export function restartRefusal(plan: RestartPlan, rerunArgv: readonly string[],
export interface HostRestartOptions { stopMcp: boolean; json: boolean; rerunArgv: string[] }
+/**
+ * `gbrain upgrade --restart-only [--dry-run]`. `--dry-run` belongs to `--restart-only`: anywhere else it is refused,
+ * never ignored while the upgrade installs for real (#2185). True when this handled the invocation.
+ */
+export async function handleRestartOnly(args: readonly string[], opts: HostRestartOptions): Promise<boolean> {
+ const dryRun = args.includes('--dry-run');
+ if (args.includes('--restart-only')) {
+ await runHostRestart({ ...opts, rerunArgv: ['gbrain', 'upgrade', '--restart-only', ...(opts.stopMcp ? ['--stop-mcp'] : [])], dryRun });
+ return true;
+ }
+ if (!dryRun) return false;
+ setCliExitVerdict(writeCliError(opError('invalid_params', '--dry-run previews only a restart; nothing was installed.', 'Run gbrain upgrade --restart-only --dry-run to preview the restart.'), 'upgrade', { json: opts.json }));
+ return true;
+}
+
/** The package directory this process loaded its code from (realpath), the install the upgrade replaces. */
function ownInstallRoot(): string | null {
const root = runtimeInstallRoot();
diff --git a/src/commands/upgrade.ts b/src/commands/upgrade.ts
index 303680f155..1f6c7afdc5 100644
--- a/src/commands/upgrade.ts
+++ b/src/commands/upgrade.ts
@@ -13,7 +13,7 @@ import { loadCompletedMigrations } from '../core/preferences.ts';
import { MIGRATIONS_RUNNING_EXIT_CODE, readMigrationLockHolder } from '../core/migration-orchestration-lock.ts';
import { loadConfig, gbrainPath } from '../core/config.ts';
import { clearSnooze, clearUpdateCache, resolveReleaseChannel, writeJustUpgraded, writeSwapReceipt, type ReleaseChannel } from '../core/self-upgrade.ts';
-import { preflightHostRestart, runHostRestart } from './upgrade-restart.ts';
+import { handleRestartOnly, preflightHostRestart } from './upgrade-restart.ts';
import { parseChannelArg, resolveStableRelease, stableUnresolvedMessage } from '../core/stable-channel.ts';
export { parseChannelArg, resolveStableRelease } from '../core/stable-channel.ts';
import { MOVEMENT_SUPERVISOR_STEP } from './movement-step.ts';
@@ -49,7 +49,7 @@ export function assessUpgradeOutcome(
export async function runUpgrade(args: string[], opts: { targetVersion?: string } = {}) {
if (args.includes('--help') || args.includes('-h')) {
- console.log('Usage: gbrain upgrade [--channel latest|stable] [--stop-mcp] [--no-restart] [--swap-only] [--no-autopilot-install] [--no-bun-floor-check]\n gbrain upgrade --restart-only [--stop-mcp] [--dry-run] [--json]\n\nSelf-update the CLI, then restart every gbrain process on this host onto the new build.\n\nDetects install method (bun, binary, clawhub) and runs the appropriate update.\nAfter upgrading, shows what\'s new and offers to set up new features.\n\n--channel <name> latest (every published release) or stable (the newest release promoted after the\n production-shaped soak passed on its exact tree). Default: self_upgrade.channel, else latest.\n Set it per brain with: gbrain config set self_upgrade.channel stable\n--stop-mcp Stop MCP stdio servers agent harnesses started, instead of refusing; reconnect gbrain\n in each harness afterwards.\n--no-restart Install without restarting anything (doctor reports runtime_build_skew until\n \'gbrain upgrade --restart-only\' runs).\n--restart-only Restart serve, autopilot, the jobs supervisor and its worker (and, with --stop-mcp, MCP\n servers) onto the installed build, then verify every process reports it and the warm\n CLI socket accepts it. A process it cannot restart refuses with the exact step (exit 3).\n--dry-run With --restart-only: print the plan and change nothing.\n--no-autopilot-install Skip autopilot installation and service rewrites, including package postinstall.\n Also supported as GBRAIN_NO_AUTOPILOT_INSTALL=1.\n--no-bun-floor-check Upgrade even when the target release\'s Bun floor cannot be read or is above\n this host\'s Bun (manual upgrades only). Docs: docs/guides/upgrades-auto-update.md#bun-floor.\n--swap-only Perform ONLY the binary/source swap and skip post-upgrade\n (migrations run on the next launch). Used by the autopilot\n silent self-upgrade channel so the daemon can swap + relaunch\n without a 30-min blocking post-upgrade inside its tick.');
+ console.log('Usage: gbrain upgrade [--channel latest|stable] [--stop-mcp] [--no-restart] [--swap-only] [--no-autopilot-install] [--no-bun-floor-check]\n gbrain upgrade --restart-only [--stop-mcp] [--dry-run] [--json]\n\nSelf-update the CLI, then restart every gbrain process on this host onto the new build.\n\nDetects install method (bun, binary, clawhub) and runs the appropriate update.\nAfter upgrading, shows what\'s new and offers to set up new features.\n\n--channel <name> latest (every published release) or stable (the newest release promoted after the\n production-shaped soak passed on its exact tree). Default: self_upgrade.channel, else latest.\n Set it per brain with gbrain config set self_upgrade.channel stable — update checks follow it too.\n--stop-mcp Stop MCP stdio servers agent harnesses started, instead of refusing; reconnect gbrain\n in each harness afterwards.\n--no-restart Install without restarting anything (doctor reports runtime_build_skew until\n \'gbrain upgrade --restart-only\' runs).\n--restart-only Restart serve, autopilot, the jobs supervisor and its worker (and, with --stop-mcp, MCP\n servers) onto the installed build, then verify every process reports it and the warm\n CLI socket accepts it. A process it cannot restart refuses with the exact step (exit 3).\n--dry-run With --restart-only: print the plan and change nothing.\n--no-autopilot-install Skip autopilot installation and service rewrites, including package postinstall.\n Also supported as GBRAIN_NO_AUTOPILOT_INSTALL=1.\n--no-bun-floor-check Upgrade even when the target release\'s Bun floor cannot be read or is above\n this host\'s Bun (manual upgrades only). Docs: docs/guides/upgrades-auto-update.md#bun-floor.\n--swap-only Perform ONLY the binary/source swap and skip post-upgrade\n (migrations run on the next launch). Used by the autopilot\n silent self-upgrade channel so the daemon can swap + relaunch\n without a 30-min blocking post-upgrade inside its tick.');
return;
}
@@ -63,11 +63,8 @@ export async function runUpgrade(args: string[], opts: { targetVersion?: string
const json = jsonRequested(args);
const stopMcp = args.includes('--stop-mcp');
- const restartOpts = { stopMcp, json, rerunArgv: ['gbrain', 'upgrade', ...args.filter(a => a !== '--json' && a !== '--dry-run')] };
- if (args.includes('--restart-only')) {
- await runHostRestart({ ...restartOpts, rerunArgv: ['gbrain', 'upgrade', '--restart-only', ...(stopMcp ? ['--stop-mcp'] : [])], dryRun: args.includes('--dry-run') });
- return;
- }
+ const restartOpts = { stopMcp, json, rerunArgv: ['gbrain', 'upgrade', ...args.filter(a => a !== '--json')] };
+ if (await handleRestartOnly(args, restartOpts)) return;
const noRestart = args.includes('--no-restart');
// Capture old version BEFORE upgrading (Codex finding: old binary runs this code)
const oldVersion = VERSION;
diff --git a/src/core/cli-flag-registry.generated.ts b/src/core/cli-flag-registry.generated.ts
index 9c6bdf02e1..fde20210b6 100644
--- a/src/core/cli-flag-registry.generated.ts
+++ b/src/core/cli-flag-registry.generated.ts
@@ -94,7 +94,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {
'orphans': ['--accept-pending', '--all', '--background', '--brain', '--count', '--cursor', '--explain', '--follow', '--force', '--help', '--include-pseudo', '--json', '--limit', '--mode', '--no-accept-pending', '--progress-interval', '--progress-json', '--quiet', '--source', '--timeout', '--timings', '--wait'],
'pages': ['--brain', '--dry-run', '--force', '--help', '--json', '--limit', '--literal-pathspecs', '--name-only', '--older-than', '--quiet', '--retry-parked', '--show-toplevel', '--source', '--source-id', '--state', '--verify', '--yes'],
'pglite-repair': ['--brain', '--break-lock', '--dry-run', '--expect', '--help', '--http', '--json', '--legacy-lock', '--path', '--probe', '--source', '--vectors', '--yes'],
- 'post-upgrade': ['--accept-reviewed-inventory', '--acknowledge-no-backup', '--admin-intent', '--all', '--all-applied', '--apply', '--apply-clean-hunks', '--backup-confirmed', '--brain', '--catch-up', '--changed', '--channel', '--check', '--concurrency', '--confirm-quiesced', '--confirm-relocated-root', '--content-root', '--cost-estimate', '--dry-run', '--embedding-dimensions', '--embedding-model', '--exit-code', '--expand', '--expected-epoch', '--expected-state', '--explain', '--export-db-only', '--export-source', '--ff-only', '--force', '--force-all', '--force-orchestrator', '--force-retry', '--force-schema', '--format', '--held', '--help', '--host-dir', '--images', '--inject-bootstrap', '--inline', '--install', '--interval', '--is-ancestor', '--json', '--limit', '--list', '--manifest', '--markdown', '--max-rss', '--max-usd', '--migrate-only', '--migration', '--mode', '--multimodal', '--name-only', '--no-autopilot-install', '--no-bun-floor-check', '--no-embed', '--no-expand', '--no-inject', '--no-restart', '--no-worker', '--non-interactive', '--now', '--once', '--only', '--oversized', '--path', '--pause', '--phase', '--quiet', '--reason', '--refs', '--remediation-plan', '--repo', '--require-db', '--restart-only', '--resume', '--retry-global', '--search-mode', '--self-transfer', '--skills-dir', '--skip-verify', '--source', '--stale', '--statement-timeout', '--status', '--stop-mcp', '--swap-only', '--tags', '--target', '--uninstall', '--user', '--value', '--vectors', '--verify', '--version', '--workers', '--yes'],
+ 'post-upgrade': ['--accept-reviewed-inventory', '--acknowledge-no-backup', '--admin-intent', '--all', '--all-applied', '--apply', '--apply-clean-hunks', '--backup-confirmed', '--brain', '--catch-up', '--changed', '--channel', '--check', '--concurrency', '--confirm-quiesced', '--confirm-relocated-root', '--content-root', '--cost-estimate', '--embedding-dimensions', '--embedding-model', '--exit-code', '--expand', '--expected-epoch', '--expected-state', '--explain', '--export-db-only', '--export-source', '--ff-only', '--force', '--force-all', '--force-orchestrator', '--force-retry', '--force-schema', '--format', '--held', '--help', '--host-dir', '--images', '--inject-bootstrap', '--inline', '--install', '--interval', '--is-ancestor', '--json', '--limit', '--list', '--manifest', '--markdown', '--max-rss', '--max-usd', '--migrate-only', '--migration', '--mode', '--multimodal', '--name-only', '--no-autopilot-install', '--no-bun-floor-check', '--no-embed', '--no-expand', '--no-inject', '--no-restart', '--no-worker', '--non-interactive', '--now', '--once', '--only', '--oversized', '--path', '--pause', '--phase', '--quiet', '--reason', '--refs', '--remediation-plan', '--repo', '--require-db', '--restart-only', '--resume', '--retry-global', '--search-mode', '--self-transfer', '--skills-dir', '--skip-verify', '--source', '--stale', '--statement-timeout', '--status', '--stop-mcp', '--swap-only', '--tags', '--target', '--uninstall', '--user', '--value', '--vectors', '--verify', '--version', '--workers', '--yes'],
'pricing': ['--brain', '--help', '--input', '--json', '--max-cost', '--max-runtime', '--output', '--rate', '--source'],
'projections': ['--brain', '--dry-run', '--enable-dcr', '--help', '--http', '--images', '--install', '--json', '--limit', '--now', '--only', '--port', '--public-url', '--remove', '--source', '--stale', '--status', '--surface', '--user'],
'protocol': ['--access', '--add', '--all', '--allowed-operations', '--asof', '--body', '--bound-slug-prefixes', '--brain', '--client', '--cursor', '--date', '--dated-since', '--days', '--entities', '--federated-read', '--from-index', '--full', '--fuzzy', '--group-by', '--help', '--http', '--id', '--include-deleted', '--json', '--kind', '--limit', '--max-usd', '--model', '--multimodal', '--no-autopilot-install', '--page', '--params', '--path', '--phase', '--prefer', '--provenance', '--purge', '--recent', '--refresh-operations', '--row', '--scopes', '--session', '--since', '--slugs', '--source', '--sources', '--stale', '--surface', '--synthesize', '--target', '--to', '--token', '--updated-after', '--url', '--yes'],
diff --git a/src/core/stable-channel.ts b/src/core/stable-channel.ts
index 9db25d26dd..70c8a10b1e 100644
--- a/src/core/stable-channel.ts
+++ b/src/core/stable-channel.ts
@@ -4,13 +4,14 @@
* installs it; .github/workflows/promote-stable.yml moves the tag.
*/
import { spawnSync } from './spawn.ts';
+import { gitChildEnv } from './git-env.ts';
import { isNewerVersion } from './semver.ts';
import { normalizeChannel, type ReleaseChannel } from './self-upgrade.ts';
const GBRAIN_GIT_URL = 'https://github.com/garrytan/gbrain';
export type GitRunner = (args: string[]) => { status: number | null; stdout: string };
const runGit: GitRunner = (args) => {
- const r = spawnSync('git', args, { encoding: 'utf-8', stdio: ['ignore', 'pipe', 'ignore'], timeout: 15_000 });
+ const r = spawnSync('git', args, { encoding: 'utf-8', env: gitChildEnv(), stdio: ['ignore', 'pipe', 'ignore'], timeout: 15_000 });
return { status: r.error ? null : r.status, stdout: r.stdout ?? '' };
};
diff --git a/test/upgrade-restart.test.ts b/test/upgrade-restart.test.ts
index 2299dae274..2198913c66 100644
--- a/test/upgrade-restart.test.ts
+++ b/test/upgrade-restart.test.ts
@@ -10,7 +10,9 @@ import {
bunGlobalCopyOf, classifyGbrainCommand, collectHostProcesses, mismatchedBuilds, planRestart, restartProblems, runRestartSteps, supervisorRestartArgv, unverifiedBuilds, verifyRestart,
type HostProcess, type ProcessSources, type RestartContext, type RestartExecutor, type WarmSocketState,
} from '../src/core/upgrade-restart.ts';
-import { mismatchFix, restartRefusal } from '../src/commands/upgrade-restart.ts';
+import { handleRestartOnly, mismatchFix, restartRefusal } from '../src/commands/upgrade-restart.ts';
+import { CLI_FLAG_REGISTRY } from '../src/core/cli-flag-registry.generated.ts';
+import { _resetCliExitVerdictForTests, currentExitCode } from '../src/core/cli-force-exit.ts';
import { exitCodeForCode } from '../src/core/error-catalogue.ts';
const NEW = '0.60.400.0';
@@ -379,3 +381,29 @@ describe('another install on the host (GBRA-175 production finding: serve ran fr
expect(mismatchedBuilds(plan, [fromCopy(112, 'serve', OWN, NEW, { version: NEW, started_ms: 5_000 })])).toEqual([]);
});
});
+
+describe('--dry-run belongs to --restart-only (#2185)', () => {
+ test('a dry run without --restart-only is refused instead of ignored', async () => {
+ const opts = { stopMcp: false, json: false, rerunArgv: ['gbrain', 'upgrade'] };
+ const writes: string[] = [];
+ const write = process.stderr.write;
+ process.stderr.write = ((chunk: string) => { writes.push(String(chunk)); return true; }) as typeof process.stderr.write;
+ const prevExit = process.exitCode;
+ try {
+ expect(await handleRestartOnly(['--channel', 'stable'], opts)).toBe(false);
+ expect(currentExitCode()).toBe(0);
+ expect(await handleRestartOnly(['--dry-run'], opts)).toBe(true);
+ expect(currentExitCode()).toBe(exitCodeForCode('invalid_params'));
+ } finally {
+ process.stderr.write = write;
+ process.exitCode = prevExit;
+ _resetCliExitVerdictForTests();
+ }
+ expect(writes.join('')).toContain('--dry-run previews only a restart');
+ });
+
+ test('upgrade accepts --dry-run and post-upgrade, which shares its module, does not', () => {
+ expect(CLI_FLAG_REGISTRY['upgrade']).toContain('--dry-run');
+ expect(CLI_FLAG_REGISTRY['post-upgrade']).not.toContain('--dry-run');
+ });
+});