Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(autopilot): restart the stale service-managed serve after a self-upgrade (#7475)

garrytane64a5e83ae2f
diff --git a/docs/architecture/key-files/commands-6.md b/docs/architecture/key-files/commands-6.md
index df69a1e357..f63c1a1ed6 100644
--- a/docs/architecture/key-files/commands-6.md
+++ b/docs/architecture/key-files/commands-6.md
@@ -13,7 +13,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
- `src/commands/transcripts.ts` — the transcripts command family, all local-only (`ctx.remote=false` by construction). `recent`: raw `.txt` corpus reads via `listRecentTranscripts` (same library as the gated `get_recent_transcripts` op). `ingest <path-or-glob>`: the cross-harness session importer — resolves ONE source id (6-tier chain), threads activePack once, streams progress (phase `transcripts.ingest`), and calls `runTranscriptsIngest` with the CLI's `makeContext` context, so on a writer-claimed brain each rendered part is submitted as a `put_page` write request naming the page's current revision (a part whose publication would change nothing is screened request-free first and takes no admission; unmanaged brains and dry runs keep the direct importer; `recover codex --apply` passes the same context; pinned by `test/transcripts-managed-ingest.test.ts`); embedding is OFF by default (embed backfill is the catch-up lane; the embed flag opts in); the max-bytes flag (validated size string, e.g. `4gb`) overrides the per-format file/store byte caps for oversized stores while omission preserves each adapter's native default; the since-last watermark is an op-checkpoint (op `transcripts-ingest`, fingerprint = source + pathspec + format + adapter version + any explicit byte cap via `ingestCheckpointFingerprintInput` — a checkpoint written under one cap is never silently reused under another, so a capped run's skipped tail can't read as scanned; the pathspec binds the user-stated paths resolved + sorted, and the no-arg/all lane substitutes hostname + sorted harness roots so DB-backed checkpoints shared across a brain's machines never let one machine inherit another's watermark and skip sessions it never scanned) advanced ONLY after a clean, untruncated, non-dry scan (a Codex sub-agent rollout, `session_meta` payload.source.subagent, has no user turn by design: the adapter reports `subagentRollout`, the scan counts it in `subagentRollouts` and prints `N sub-agent rollouts (no user turns by design)`, and it keeps the scan clean; an ordinary assistant-only rollout is still `userTurnsMissing` drift); no-arg = confined discovery table, the all flag imports the discovered set. `status`: found-vs-imported gap table (disk scan vs ONE conversation-pages frontmatter query — `executeRaw`, both engines — in `src/core/transcripts/discover.ts`) — the correctness surface that catches late-arriving sessions no watermark can. The facts flag hands EVERY touched slug (including hash-skipped) to `src/core/transcripts/ingest-facts.ts`; a page that fails extraction counts in `facts.pagesFailed`, stays unfinished, and makes the command exit 1. Registered in CLI_ONLY + CLI_ONLY_SELF_HELP + SELF_HELP_WITHOUT_ENGINE (engine-free help). `expandTilde(raw)` (bare `~`, leading `~/` or `~\\` → home dir; `~user` forms and a mid-string `~` stay literal) is the one tilde expansion `expandPaths` applies to every path spec. `recover codex` (`src/commands/transcripts-recover.ts`, logic `src/core/transcripts/recover.ts`; D15 for #5163): finds codex conversation pages in one source with no `**User**` anchor, re-parses the retained rollouts (discovery root + archived store, or given paths) and classifies each session recoverable / still userless / unrecoverable (rollout gone); preview by default, `--apply` re-imports only the recoverable rollouts through `runTranscriptsIngest` (content-hash dedup, no facts, no watermark write). Pinned by `test/transcripts-recover-codex.test.ts`. `audit-secrets [--source-id S] [--json]` (`src/commands/transcripts-audit.ts`, logic `src/core/transcripts/secret-audit.ts`): the read-only installed-base audit that streams imported conversation pages (`type = 'conversation'` with `transcript_import` frontmatter) in id-keyset batches of 25, scans title and body with the transcript-lane detectors, lists slug, source, hit counts per pattern and up to 20 line numbers (never values or previews), and caches the summary without slugs in config row `transcripts.secret_audit` for the doctor check `transcript_secret_exposure` (`src/commands/doctor/checks/transcript-secrets.ts`, brain category), which counts imported conversation pages and reads that summary (never scans): no audit, an older `TRANSCRIPT_SECRET_AUDIT_VERSION` or a source-scoped audit warns with the audit as fix; hits warn with the audit's age; a clean full audit is ok. Pinned by `test/transcripts-secret-audit.test.ts`.
- `src/commands/upgrade.ts` — self-update CLI. It sets `GBRAIN_UPGRADE_OWNS_MIGRATIONS=1` for the install step, so package postinstall (`scripts/postinstall.ts`) skips `apply-migrations`; post-upgrade owns them. An install step that fails or times out after `gbrain --version` already reports a newer version counts as installed. The run ends with a `Binary:` line (installed version, or upgrade failed) and a `Migrations:` line: complete; running, with the lock holder's host and pid when post-upgrade exits 75; or failed, with the recovery command (`--force-retry <v>` for wedged versions). `runPostUpgrade()` enumerates migrations from the TS registry (`src/commands/migrations/index.ts`) and tail-calls `runApplyMigrations(['--yes', '--non-interactive'])` so the mechanical side of every outstanding migration runs unconditionally. After schema apply it prints the one-shot auto_chronicle default-on `[AGENT]` notice (`core/chronicle/upgrade-notice.ts`). Before the swap of a bun-link, package or ClawHub install it refuses (exit 78, nothing changed) a target whose Bun floor is above the host's Bun or unreadable (`--no-bun-floor-check` overrides, manual only; `src/core/bun-floor.ts`); after the swap it runs `gbrain --help` as a smoke that passes the startup Bun check and, on failure, exits 1 with per-method recovery (#5855). Everything the post-swap tail needs is imported statically, so the old process never loads new-release modules into its cached graph (#6604; the supervisor step constant lives in the import-free leaf `src/commands/movement-step.ts`; guard: `test/upgrade-post-swap-imports.test.ts`). A tag-pinned reinstall hint (`bunReinstallCommand`, `reinstallHintLines`) probes `git ls-remote --exit-code --tags … refs/tags/v<x>` before `bun remove -g gbrain`, prints a restore line, and on Windows prints one step per line; `planPinnedReinstall` probes the tag itself (published / not published / unknown) and falls back to the newest published `v<x>` tag (`latestPublishedVersion`) when the requested one is missing (#6662, D24; `test/upgrade-release-tag-hint.test.ts`). A verified version equal to the running one after the install step is no swap (#6828): it prints `No newer version was installed`, skips `last_upgrade`, `JUST_UPGRADED`, the cache reset and the smoke, and on a tag pin with no newer published tag the hint moves the install off the pin with `to_version: latest`, never a cached unpublished version (#6718). With `GBRAIN_SWAP_RECEIPT` set it writes a `SwapReceipt` (`installed` / `not_installed` / `installed_broken`) for the autopilot channel (`test/autopilot-unpublished-target-6828.test.ts`). Tests: `upgrade-migration-outcome.test.ts`, `upgrade-no-autopilot.serial.test.ts`, `upgrade-bun-link-arc.serial.test.ts`. `post-upgrade --json` (D2, `json: 'document'`): human lines go to stderr and stdout is one report `{status, apply_migrations:{exit_code}, schema, warnings[]}`; it calls `applyMigrations()` and still ends on any status apply-migrations returns (a failure is one envelope leading with the report). GBRA-175: `--channel latest|stable` (default `self_upgrade.channel`): `resolveStableRelease` maps the commit `refs/tags/stable` peels to onto its `v<version>` tag through `git ls-remote`, and `installStableRelease` installs exactly that release (bun: remove then add `#v<version>`, restoring the previous release on failure; bun-link: fast-forward only; binary: `fetchReleaseByTag`), never downgrading. Before the swap `preflightHostRestart` refuses (`restart_refused`, exit 3) when a running process could not be restarted; after post-upgrade the new build runs `gbrain upgrade --restart-only` (`--no-restart` skips it). Tests: `upgrade-stable-channel.test.ts`. A global install pinned to a tag or commit (`bunGlobalExactTagPin(root, true)`) is replaced with the newest published release the same way instead of `bun update`, which keeps the pin. `parseChannelArg` and `resolveStableRelease` live in `src/core/stable-channel.ts` (re-exported).
-- `src/commands/upgrade-restart.ts` — GBRA-175: the host side of the upgrade restart. Real process sources (consumer heartbeat rows on Postgres, the supervisor PID file, the worker registry, `ps -U <uid> -ww -o pid=,ppid=,etime=,command=` with `/proc/<pid>/environ` GBRAIN_HOME matching on Linux; the install version above each entry point), the installed serve and autopilot services with the pid each manager runs (`hostServices`: `systemctl --user show -p MainPID`, `launchctl list`), `terminateIfUnchanged` (SIGTERM an MCP pid only while `ps` still shows the same server and start time), `restartRefusal` (ask_user + `--stop-mcp` when only MCP servers block, else the first manual step for the user), `preflightHostRestart` (pre-swap, every process stale) and `runHostRestart` (`gbrain upgrade --restart-only [--stop-mcp] [--dry-run] [--json]`: plan, run, verify for up to 180 s with the warm-socket probe `probeCliSocket`). Tests: `upgrade-restart.test.ts`.
+- `src/commands/upgrade-restart.ts` — GBRA-175: the host side of the upgrade restart. Real process sources (consumer heartbeat rows on Postgres, the supervisor PID file, the worker registry, `ps -U <uid> -ww -o pid=,ppid=,etime=,command=` with `/proc/<pid>/environ` GBRAIN_HOME matching on Linux; the install version above each entry point), the installed serve and autopilot services with the pid each manager runs (`hostServices`: `systemctl --user show -p MainPID`, `launchctl list`), `terminateIfUnchanged` (SIGTERM an MCP pid only while `ps` still shows the same server and start time), `restartRefusal` (ask_user + `--stop-mcp` when only MCP servers block, else the first manual step for the user), `preflightHostRestart` (pre-swap, every process stale) and `runHostRestart` (`gbrain upgrade --restart-only [--stop-mcp] [--dry-run] [--json]`: plan, run, verify for up to 180 s with the warm-socket probe `probeCliSocket`). #7475: `restartServeAfterSelfUpgrade`, called each autopilot-daemon tick, restarts the serve the serve service runs once it is on an older build than the relaunched autopilot. It runs once per autopilot process, only in auto mode, in quiet hours and when the brain is idle (`computeAutopilotIdle`), and audits as `restart_serve`. `planServeRestart` reports a serve the service does not run, or one on another install, as `manual` and never restarts it. Tests: `upgrade-restart.test.ts`, `autopilot-serve-restart-7475.test.ts`.
- `src/core/upgrade-restart.ts` — GBRA-175: the pure half of the upgrade restart. `collectHostProcesses` (the process table is the authority: a heartbeat, PID-file or registry record whose pid `ps` does not show as gbrain is dropped; `gbrainEntry` skips wrappers such as tini, and a process's parent is its nearest gbrain ancestor), `planRestart` (a service restarts only processes under its manager's pid; `supervisorRestartArgv` keeps the launch options and PID file; anything else is a `ManualStep`), `runRestartSteps`, `restartProblems` (old pids gone, one build, roles and the supervised worker back, warm socket accepts) and `unverifiedBuilds`. A stale process whose `install_root` is another install than the one being upgraded gets a `replace_copy` step first when it is a Bun global copy (`bunGlobalCopyOf`: probe the tag, `bun remove -g` then `bun add -g` under its `BUN_INSTALL`, restore on failure), else a manual step from `copyFix`; after the restart `mismatchedBuilds` names any process back on another build, and the host's `mismatchFix` chains that replacement with `gbrain upgrade --restart-only`.
- `src/commands/watch.ts` — `gbrain watch`: the push transport. Reads turns from stdin as they arrive (`user:`/`assistant:` prefixes; unprefixed = user turn), keeps a rolling in-process window (`--window-turns`, default 4), calls `volunteerContext` per turn, streams pointers to stdout (`--json` for JSONL with turn attribution), logs `channel: 'watch'` events with a per-session id. Session dedupe feeds already-pushed slugs back as priorContext so the core's slug-only suppression dedupes. Blocks in the stdin iteration (interactive alive until Ctrl-C/Ctrl-D; piped ends at EOF) — deliberately NOT in DAEMON_COMMANDS; SIGINT closes the stream so teardown flows through finishCliTeardown. Per-turn resolution failures are fail-open. Registered in CLI_ONLY + CLI_ONLY_SELF_HELP + THIN_CLIENT_REFUSED_COMMANDS (thin clients use the `volunteer_context` MCP op). Pinned by `test/watch-command.test.ts`.
diff --git a/docs/guides/upgrades-auto-update.md b/docs/guides/upgrades-auto-update.md
index 08acb6947d..c7b2018135 100644
--- a/docs/guides/upgrades-auto-update.md
+++ b/docs/guides/upgrades-auto-update.md
@@ -275,9 +275,18 @@ gbrain upgrade --restart-only # restart onto the installed bu
gbrain upgrade --no-restart # install only; doctor fails runtime_build_skew until the restart runs
```
-The autopilot `--swap-only` channel still exits for its own supervisor to
-relaunch and restarts nothing else; doctor's `runtime_build_skew` fails while
-two builds run, with `gbrain upgrade --restart-only` as its fix.
+The autopilot `--swap-only` channel exits for its own supervisor to relaunch.
+Once the relaunched autopilot runs the new build, it checks the serve that the
+installed serve service runs (`com.gbrain.serve` under launchd,
+`gbrain-serve.service` under systemd). If that serve is on an older build, the
+autopilot restarts it through the service and verifies that it came back on
+the new build. It does this once per autopilot process, under the swap's own
+auto-mode, quiet-hours and idle gates, and records it in the self-upgrade
+audit as `restart_serve` (`applied`, or `skipped` with `manual` or
+`unverified`). It leaves alone a serve that the service does not run (one
+started by hand or from another install), the jobs supervisor and MCP
+servers. For those, doctor's `runtime_build_skew` fails while two builds run,
+and `gbrain upgrade --restart-only` is its fix.
<a id="restart-and-verify"></a>
### Restart and verify: a deploy ends with data movement
diff --git a/src/commands/autopilot-daemon.ts b/src/commands/autopilot-daemon.ts
index 1b1e3d2a90..443e2b0684 100644
--- a/src/commands/autopilot-daemon.ts
+++ b/src/commands/autopilot-daemon.ts
@@ -21,6 +21,7 @@ import { resolveChildCliInvocation } from '../core/minions/job-isolation.ts';
import { setCliExitVerdict } from '../core/cli-force-exit.ts';
import {
attemptAutopilotSelfUpgrade,
+ computeAutopilotIdle,
autopilotEngineIdentity,
chatBootWarning,
classifyReconnectError,
@@ -32,6 +33,7 @@ import {
resolveGbrainCliPath,
shouldSpawnAutopilotWorker,
} from './autopilot.ts';
+import { restartServeAfterSelfUpgrade } from './upgrade-restart.ts';
/**
* Mutable daemon state shared by the tick loop, the shutdown path and the tick
@@ -321,6 +323,8 @@ export async function runAutopilotDaemon(engine: BrainEngine, args: string[]): P
if (configurationBlocked()) continue;
await attemptAutopilotSelfUpgrade(engine, engineType, lockPath, () => !configurationBlocked());
if (configurationBlocked()) continue;
+ await restartServeAfterSelfUpgrade(() => computeAutopilotIdle(engine, engineType));
+ if (configurationBlocked()) continue;
// --no-worker peer-liveness probe (v0.19.1). Runs every cycle, cheap
// (single SELECT). See the NO_WORKER_WARN_TICKS comment for caveats.
diff --git a/src/commands/autopilot.ts b/src/commands/autopilot.ts
index 75279b7ce9..324d27d0c6 100644
--- a/src/commands/autopilot.ts
+++ b/src/commands/autopilot.ts
@@ -377,7 +377,7 @@ export function reconcileSelfUpgradeAtBoot(): void {
/** Conservative idle: no cycle running AND (Postgres) no active/waiting jobs.
* Any ambiguity / error → NOT idle (we'd rather skip an upgrade window). */
-async function computeAutopilotIdle(engine: BrainEngine, engineType: string): Promise<boolean> {
+export async function computeAutopilotIdle(engine: BrainEngine, engineType: string): Promise<boolean> {
try {
const cycle = await inspectLock(engine, 'gbrain-cycle');
if (cycle) return false; // a cycle (sync/extract/embed/...) is running
diff --git a/src/commands/upgrade-restart.ts b/src/commands/upgrade-restart.ts
index 33622ee205..11a4790765 100644
--- a/src/commands/upgrade-restart.ts
+++ b/src/commands/upgrade-restart.ts
@@ -24,9 +24,12 @@ import { readSupervisorBuild, readSupervisorPid } from '../core/minions/supervis
import { parseEtimeToMs, readWorkers } from '../core/minions/worker-registry.ts';
import { installedVersion, runtimeInstallRoot } from '../core/runtime-build.ts';
import { VERSION } from '../version.ts';
+import { resolveQuietHoursWindow, resolveSelfUpgradeMode } from '../core/self-upgrade.ts';
+import { evaluateQuietHours } from '../core/minions/quiet-hours.ts';
+import { logSelfUpgrade } from '../core/audit/self-upgrade-audit.ts';
import {
classifyGbrainCommand, collectHostProcesses, copyFix, gbrainEntry, mismatchedBuilds, PENDING_BUILD, planRestart, runRestartSteps, verifyRestart,
- type HostProcess, type ProcessSources, type ProcessTableRow, type RestartPlan, type ServiceHandle, type WarmSocketState,
+ type HostProcess, type ProcessSources, type ProcessTableRow, type RestartExecutor, type RestartPlan, type ServiceHandle, type WarmSocketState,
} from '../core/upgrade-restart.ts';
const DOCS = 'docs/guides/upgrades-auto-update.md#restart';
@@ -138,6 +141,19 @@ async function hostSources(): Promise<{ sources: ProcessSources; notes: string[]
return { sources, notes, close, pidFile: DEFAULT_PID_FILE };
}
+/** The real executor for restart steps; `pidFile` is the default supervisor PID file. */
+function hostExecutor(pidFile: string): RestartExecutor {
+ return {
+ run: (argv, env) => {
+ const r = spawnSync(argv[0]!, argv.slice(1), { encoding: 'utf8', timeout: 600_000, stdio: ['ignore', 'pipe', 'pipe'], env: env ? { ...process.env, ...env } : process.env });
+ return { status: r.error ? null : r.status, output: `${r.stdout ?? ''}${r.stderr ?? ''}${r.error ? r.error.message : ''}` };
+ },
+ terminate: terminateIfUnchanged,
+ supervisorPid: file => { const status = readSupervisorPid(file ?? pidFile); return status.running ? status.pid : null; },
+ sleep: ms => new Promise(r => setTimeout(r, ms)),
+ };
+}
+
/** SIGTERM pid only while it is still the MCP server the plan saw: same role, same start time (ps reports it to the second). */
function terminateIfUnchanged(pid: number, startedMs: number | null): 'stopped' | 'gone' | 'changed' {
const row = readProcessTable(undefined, [pid])?.find(r => r.pid === pid);
@@ -252,15 +268,7 @@ export async function runHostRestart(opts: HostRestartOptions & { dryRun: boolea
if (refusal) { setCliExitVerdict(writeCliError(refusal, 'upgrade', { json: opts.json })); return; }
if (!opts.json) printPlan(plan, warmBefore, notes);
const startedMs = Date.now();
- const results = await runRestartSteps(plan, {
- run: (argv, env) => {
- const r = spawnSync(argv[0]!, argv.slice(1), { encoding: 'utf8', timeout: 600_000, stdio: ['ignore', 'pipe', 'pipe'], env: env ? { ...process.env, ...env } : process.env });
- return { status: r.error ? null : r.status, output: `${r.stdout ?? ''}${r.stderr ?? ''}${r.error ? r.error.message : ''}` };
- },
- terminate: terminateIfUnchanged,
- supervisorPid: file => { const status = readSupervisorPid(file ?? pidFile); return status.running ? status.pid : null; },
- sleep: ms => new Promise(r => setTimeout(r, ms)),
- });
+ const results = await runRestartSteps(plan, hostExecutor(pidFile));
if (!opts.json) for (const r of results) console.log(` ${r.ok ? 'ok' : 'FAILED'}: ${r.detail}`);
const verified = await verifyRestart(plan, startedMs, warmBefore, {
collect: () => collectHostProcesses(sources), probeWarmSocket: () => probeCliSocket(),
@@ -288,6 +296,73 @@ export async function runHostRestart(opts: HostRestartOptions & { dryRun: boolea
}
}
+export type ServeRestartOutcome = { outcome: 'no_service' | 'current' } | { outcome: 'manual' | 'restarted' | 'unverified'; detail: string };
+
+/** #7475: the serve-only restart plan when the serve service can move every stale serve onto `expected` by itself; otherwise the outcome. */
+export function planServeRestart(processes: readonly HostProcess[], serveService: ServiceHandle, expected: string, ownRoot: string | null): RestartPlan | ServeRestartOutcome {
+ const plan = planRestart(processes.filter(p => p.role === 'serve'), { expected, serveService, autopilotService: null, stopMcp: false, ownInstallRoot: ownRoot });
+ if (!plan.stale.length) return { outcome: 'current' };
+ if (plan.manual.length || plan.steps.some(step => step.kind !== 'service')) {
+ return { outcome: 'manual', detail: `run \`gbrain upgrade --restart-only\`: ${[...describeSteps(plan), ...plan.manual.map(m => m.instruction)].join(' ')}` };
+ }
+ return plan;
+}
+
+/**
+ * #7475: the autopilot self-upgrade swaps and relaunches only itself. Once it runs the new build, it calls this to
+ * restart the serve the installed serve service runs when that serve is on an older build, and to verify it came
+ * back on this one. Serve only: a stale serve the service does not run (started by hand, or from another install)
+ * is reported as `manual` and left to doctor's `runtime_build_skew` and `gbrain upgrade --restart-only`.
+ */
+export async function restartStaleServeService(): Promise<ServeRestartOutcome> {
+ const services = hostServices();
+ if (!services.serve) return { outcome: 'no_service' };
+ const { sources, close, pidFile } = await hostSources();
+ try {
+ const collectServe = async () => (await collectHostProcesses(sources)).filter(p => p.role === 'serve');
+ const plan = planServeRestart(await collectServe(), services.serve, VERSION, ownInstallRoot());
+ if (!('steps' in plan)) return plan;
+ const { probeCliSocket } = await import('../core/cli-socket/probe.ts');
+ const warmBefore = await probeCliSocket();
+ const startedMs = Date.now();
+ const results = await runRestartSteps(plan, hostExecutor(pidFile));
+ const verified = await verifyRestart(plan, startedMs, warmBefore, {
+ collect: collectServe, probeWarmSocket: () => probeCliSocket(),
+ sleep: ms => new Promise(r => setTimeout(r, ms)), now: () => Date.now(),
+ }, { timeoutMs: VERIFY_TIMEOUT_MS, pollMs: VERIFY_POLL_MS });
+ const problems = [...results.filter(r => !r.ok).map(r => r.detail), ...verified.problems];
+ return { outcome: verified.ok ? 'restarted' : 'unverified', detail: `${describeSteps(plan).join(' ')}${problems.length ? `; ${problems.join(' ')}` : ''}` };
+ } finally {
+ await close();
+ }
+}
+
+export type ServeRestartDeps = { state: { tried: boolean }; restart: () => Promise<ServeRestartOutcome> };
+const SERVE_RESTART_DEPS: ServeRestartDeps = { state: { tried: false }, restart: restartStaleServeService };
+
+/**
+ * #7475: the autopilot daemon calls this each tick. In auto mode, under the self-upgrade swap's own quiet-hours and
+ * idle gates, the autopilot (relaunched on the new build after its swap) restarts the stale serve the serve service
+ * runs, and audits the outcome as `restart_serve`. One attempt per autopilot process; the relaunch after the next
+ * swap tries again. Never throws.
+ */
+export async function restartServeAfterSelfUpgrade(isIdle: () => Promise<boolean>, deps: ServeRestartDeps = SERVE_RESTART_DEPS): Promise<void> {
+ if (deps.state.tried) return;
+ try {
+ const cfg = loadConfig();
+ if (!cfg || resolveSelfUpgradeMode(cfg) !== 'auto') return;
+ if (evaluateQuietHours(resolveQuietHoursWindow(cfg.self_upgrade?.quiet_hours), new Date()) === 'allow') return;
+ if (!await isIdle()) return;
+ deps.state.tried = true;
+ const result = await deps.restart();
+ if (!('detail' in result)) return;
+ logSelfUpgrade({ channel: 'autopilot', action: 'restart_serve', current: VERSION, outcome: result.outcome === 'restarted' ? 'applied' : 'skipped', reason: result.outcome });
+ console.log(`[autopilot] serve ${result.outcome === 'restarted' ? `restarted onto v${VERSION}` : `still on another build (${result.outcome})`}: ${result.detail}`);
+ } catch {
+ /* the serve restart must never break the autopilot tick */
+ }
+}
+
function printPlan(plan: RestartPlan, warm: WarmSocketState, notes: string[]): void {
for (const note of notes) console.log(note);
if (!plan.stale.length) console.log(`Every gbrain process on this host already runs v${plan.expected}${plan.current.length ? ` (${plan.current.map(describe).join(', ')})` : ' (none is running)'}.`);
diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.ts
index 722d9c8be4..59d3361c5c 100644
--- a/src/core/behavior-change-notice.ts
+++ b/src/core/behavior-change-notice.ts
@@ -1223,6 +1223,7 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText;
{ since: '0.60.427.0', text: 'More gbrain state follows GBRAIN_HOME: feature offers (`feature-offers.json`), the upgrade state and error log, `mounts.json` and the mounts cache, the brain-pull log (including the log paths a newly installed launchd pull job writes), the default supervisor pid file, skillopt captures, the transcript harvest pattern file, notability eval files and the greenfield import audit directory now live under `<GBRAIN_HOME>/.gbrain` when GBRAIN_HOME is set. Before, they were written under `$HOME/.gbrain` whatever GBRAIN_HOME said. With GBRAIN_HOME unset nothing moves. A host that sets GBRAIN_HOME keeps its old copies under `$HOME/.gbrain`: move them by hand if you want the old offers, mounts or upgrade history, and restart a supervisor that was started before the upgrade so `gbrain jobs supervisor status` finds its pid file.' },
// GBRA-175 (stable channel, upgrade restarts every process). `since` is stamped at the merge slot.
{ since: '0.60.428.0', id: 'upgrade_restarts_7245', text: '`gbrain upgrade` now restarts every gbrain process this brain runs on the host onto the new build (serve and autopilot through their installed services, the jobs supervisor and its worker with `gbrain jobs supervisor stop` then `start --detach`) and verifies that they all report one build and that the warm CLI socket accepts it. Before installing anything it refuses with `restart_refused` (exit 3) when a process cannot be restarted automatically: a serve or worker started by hand, an autopilot without its service, a running sync, or an MCP server an agent harness started (rerun with `--stop-mcp` to stop those; reconnect gbrain in each harness afterwards). `--no-restart` installs without restarting; `gbrain upgrade --restart-only` restarts onto the installed build (`--dry-run` previews). The autopilot `--swap-only` channel is unchanged.' },
+ { since: 'TBD', id: 'autopilot_restarts_serve_7475', text: 'With `self_upgrade.mode auto`, the autopilot that relaunches after a self-upgrade now restarts the serve your installed serve service runs (`com.gbrain.serve` under launchd, `gbrain-serve.service` under systemd) when that serve is still on the old build, and verifies it came back on the new one. It runs once per relaunch, in quiet hours, when the brain is idle, and audits as `restart_serve`. A serve started by hand or from another install is never restarted: doctor `runtime_build_skew` keeps failing with `gbrain upgrade --restart-only` as its fix.' },
{ since: '0.60.428.0', id: 'runtime_build_skew_fails_7245', text: 'doctor `runtime_build_skew` now fails (was a warning) when two or more gbrain builds run on this host, and its fix asks the user before running `gbrain upgrade --restart-only`; one process older than its install alone still warns. New release channel: `gbrain upgrade --channel stable` or `gbrain config set self_upgrade.channel stable` installs only releases a maintainer promoted after the production-shaped soak passed on their exact tree, and the update checks then offer only that release; the default channel (`latest`) is unchanged.' },
];
diff --git a/src/core/cli-flag-registry.generated.ts b/src/core/cli-flag-registry.generated.ts
index fde20210b6..a8e64f2b46 100644
--- a/src/core/cli-flag-registry.generated.ts
+++ b/src/core/cli-flag-registry.generated.ts
@@ -20,7 +20,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {
'append': ['--brain', '--expect-tail', '--expected-revision', '--file', '--force', '--help', '--json', '--region', '--request-id', '--separator', '--source'],
'apply-migrations': ['--accept-reviewed-inventory', '--acknowledge-no-backup', '--apply', '--apply-rewrites', '--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', '--install', '--json', '--legacy-lock', '--list', '--locks', '--migrate-only', '--migration', '--mode', '--no-autopilot-install', '--non-interactive', '--only', '--path', '--prefer-postgres', '--probe', '--repo', '--require-db', '--skip-verify', '--source', '--statement-timeout', '--uninstall', '--url', '--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', '--category', '--cleanup-dead-local-locks', '--client', '--code', '--confirm-quiesced', '--confirm-relocated-root', '--days', '--delegated-namespace', '--delegated-slug-prefixes', '--disable', '--dry-run', '--enable', '--enable-dcr-insecure', '--expected-epoch', '--expected-state', '--federated-read', '--fix', '--force', '--grant-types', '--group-by', '--help', '--id', '--if-version', '--json', '--limit', '--manifest', '--max-concurrent', '--migrate-legacy', '--min-trust', '--no-pull', '--operations', '--origin', '--parked-code', '--parked-pushes', '--pat-file', '--path', '--probe', '--profile', '--read-sources', '--redirect-uri', '--refresh-operations', '--repair', '--replace', '--request-id', '--reset-default', '--scopes', '--self-transfer', '--shared-skills', '--since', '--slug-prefixes', '--source', '--source-ids', '--sources', '--state', '--surface', '--takes-holders', '--token', '--token-endpoint-auth-method', '--token-ttl', '--usage', '--wait', '--warn-only', '--yes'],
- 'autopilot': ['--apply', '--batch', '--brain', '--channel', '--check', '--dimensions', '--dir', '--drain', '--dry-run', '--embedding-dimensions', '--embedding-model', '--exit-code', '--expect', '--explain', '--ff-only', '--force', '--force-retry', '--from-pages', '--help', '--inject-bootstrap', '--inline', '--install', '--interval', '--is-ancestor', '--json', '--markdown', '--max-cost', '--max-rss', '--max-runtime', '--max-usd', '--migrate-only', '--model', '--no-autopilot-install', '--no-bun-floor-check', '--no-embed', '--no-embed-cache', '--no-inject', '--no-restart', '--no-worker', '--non-interactive', '--now', '--once', '--only', '--output', '--params', '--path', '--pause', '--phase', '--quiet', '--reader-mode', '--reason', '--refresh-cache', '--refs', '--remediation-plan', '--repo', '--restart-only', '--resume', '--retry-global', '--slot-a-model', '--slot-b-model', '--slot-c-model', '--source', '--stale', '--status', '--stop-mcp', '--swap-only', '--tags', '--target', '--trust', '--uninstall', '--user', '--verify', '--version', '--yes'],
+ 'autopilot': ['--apply', '--batch', '--brain', '--channel', '--check', '--dimensions', '--dir', '--drain', '--dry-run', '--embedding-dimensions', '--embedding-model', '--exit-code', '--expect', '--explain', '--ff-only', '--force', '--force-retry', '--from-pages', '--help', '--inject-bootstrap', '--inline', '--install', '--interval', '--is-ancestor', '--json', '--markdown', '--max-cost', '--max-rss', '--max-runtime', '--max-usd', '--migrate-only', '--model', '--no-autopilot-install', '--no-bun-floor-check', '--no-embed', '--no-embed-cache', '--no-inject', '--no-restart', '--no-worker', '--non-interactive', '--now', '--once', '--only', '--output', '--params', '--path', '--pause', '--phase', '--quiet', '--reader-mode', '--reason', '--refresh-cache', '--refs', '--remediation-plan', '--repo', '--restart-only', '--resume', '--retry-global', '--slot-a-model', '--slot-b-model', '--slot-c-model', '--source', '--stale', '--status', '--stop-mcp', '--swap-only', '--tags', '--target', '--trust', '--uninstall', '--user', '--value', '--verify', '--version', '--yes'],
'backfill': ['--batch-size', '--brain', '--concurrency', '--dry-run', '--fresh', '--help', '--json', '--keep-index', '--list', '--max-errors', '--max-rows', '--resume', '--source'],
'backup': ['--accept-pending', '--background', '--brain', '--confirm-authority-reviewed', '--confirm-backup-compatible', '--confirm-quiesced', '--dir', '--explain', '--follow', '--full', '--help', '--into', '--json', '--mode', '--no-accept-pending', '--output', '--path', '--progress-interval', '--progress-json', '--purge-mirror', '--quiet', '--restore-only', '--source', '--timeout', '--timings', '--wait'],
'beliefs': ['--apply', '--archived-at', '--brain', '--from-url-env', '--help', '--json', '--probe', '--purge-mirror', '--since', '--source'],
diff --git a/test/autopilot-serve-restart-7475.test.ts b/test/autopilot-serve-restart-7475.test.ts
new file mode 100644
index 0000000000..a62b4ec2d0
--- /dev/null
+++ b/test/autopilot-serve-restart-7475.test.ts
@@ -0,0 +1,114 @@
+/**
+ * #7475: the autopilot self-upgrade swaps and relaunches only autopilot, so a serve the installed serve service runs
+ * stayed on the old build (restart_pending true for days). The relaunched autopilot now restarts that serve once,
+ * under the swap's own auto-mode, quiet-hours and idle gates, and audits the outcome. A serve the service does not
+ * run is never touched: it is reported for `gbrain upgrade --restart-only`.
+ */
+import { afterAll, describe, expect, test } from 'bun:test';
+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { planServeRestart, restartServeAfterSelfUpgrade, type ServeRestartOutcome } from '../src/commands/upgrade-restart.ts';
+import { readRecentSelfUpgrades } from '../src/core/audit/self-upgrade-audit.ts';
+import type { HostProcess } from '../src/core/upgrade-restart.ts';
+import { withEnv } from './helpers/with-env.ts';
+
+const NEW = '0.60.430.0';
+const OLD = '0.60.371.0';
+const SERVE_SERVICE = { argv: ['launchctl', 'kickstart', '-k', 'gui/501/com.gbrain.serve'], pid: 9 };
+const serve = (pid: number, version: string | null, over: Partial<HostProcess> = {}): HostProcess =>
+ ({ pid, ppid: null, role: 'serve', version, started_ms: 1_000, ancestors: [SERVE_SERVICE.pid], args: ['serve', '--http'], ...over });
+
+describe('planServeRestart (#7475)', () => {
+ test('a stale serve the service runs gets the service restart and nothing else', () => {
+ const plan = planServeRestart([serve(9, OLD), { ...serve(40, OLD), role: 'worker', ancestors: [] }], SERVE_SERVICE, NEW, null);
+ expect('steps' in plan && plan.steps).toEqual([{ kind: 'service', role: 'serve', argv: SERVE_SERVICE.argv, pids: [9] }]);
+ });
+
+ test('a serve already on the build needs nothing', () => {
+ expect(planServeRestart([serve(9, NEW)], SERVE_SERVICE, NEW, null)).toEqual({ outcome: 'current' });
+ expect(planServeRestart([], SERVE_SERVICE, NEW, null)).toEqual({ outcome: 'current' });
+ });
+
+ test('a hand-started stale serve is never restarted, only reported', () => {
+ const plan = planServeRestart([serve(77, OLD, { ancestors: [1] })], SERVE_SERVICE, NEW, null);
+ expect(plan).toMatchObject({ outcome: 'manual' });
+ expect('detail' in plan && plan.detail).toContain('gbrain upgrade --restart-only');
+ expect('detail' in plan && plan.detail).toContain('kill 77');
+ });
+
+ test('a serve the service starts from another install is reported, not restarted onto the old build', () => {
+ const other = '/opt/example/install/global/node_modules/gbrain';
+ const plan = planServeRestart([serve(9, OLD, { install_root: other, install_version: OLD })], SERVE_SERVICE, NEW, '/srv/gbrain-example');
+ expect(plan).toMatchObject({ outcome: 'manual' });
+ });
+});
+
+describe('restartServeAfterSelfUpgrade (#7475)', () => {
+ const dirs: string[] = [];
+ afterAll(() => { for (const d of dirs) rmSync(d, { recursive: true, force: true }); });
+ const idle = async () => true;
+
+ function brainHome(mode: string, inQuietHours: boolean): { home: string; audit: string } {
+ const root = mkdtempSync(join(tmpdir(), 'gbrain-serve-restart-7475-'));
+ dirs.push(root);
+ const hour = new Date().getUTCHours();
+ const start = inQuietHours ? hour : (hour + 3) % 24;
+ mkdirSync(join(root, '.gbrain'), { recursive: true });
+ writeFileSync(join(root, '.gbrain', 'config.json'), JSON.stringify({
+ engine: 'pglite', database_path: join(root, '.gbrain', 'brain.pglite'),
+ self_upgrade: { mode, quiet_hours: { start, end: (start + 2) % 24, tz: 'UTC' } },
+ }));
+ return { home: root, audit: join(root, 'audit') };
+ }
+
+ async function run(mode: string, inQuietHours: boolean, results: ServeRestartOutcome[]) {
+ const { home, audit } = brainHome(mode, inQuietHours);
+ const state = { tried: false };
+ let calls = 0;
+ const restart = async () => results[calls++]!;
+ return withEnv({ GBRAIN_HOME: home, GBRAIN_AUDIT_DIR: audit }, async () => {
+ await restartServeAfterSelfUpgrade(idle, { state, restart });
+ await restartServeAfterSelfUpgrade(idle, { state, restart });
+ return { calls, state, audit: readRecentSelfUpgrades(1).filter(e => e.action === 'restart_serve') };
+ });
+ }
+
+ test('auto mode in quiet hours restarts the stale serve once and audits it', async () => {
+ const r = await run('auto', true, [{ outcome: 'restarted', detail: 'serve pid 9 (v0.60.371.0)' }]);
+ expect(r.calls).toBe(1);
+ expect(r.state.tried).toBe(true);
+ expect(r.audit).toHaveLength(1);
+ expect(r.audit[0]).toMatchObject({ channel: 'autopilot', action: 'restart_serve', outcome: 'applied', reason: 'restarted' });
+ });
+
+ test('a restart that does not verify is audited as skipped, never as a failed self-upgrade', async () => {
+ const r = await run('auto', true, [{ outcome: 'unverified', detail: 'serve did not come back' }]);
+ expect(r.calls).toBe(1);
+ expect(r.audit[0]).toMatchObject({ action: 'restart_serve', outcome: 'skipped', reason: 'unverified' });
+ });
+
+ test('a serve already on the build is checked once and writes no audit row', async () => {
+ const r = await run('auto', true, [{ outcome: 'current' }]);
+ expect(r.calls).toBe(1);
+ expect(r.audit).toHaveLength(0);
+ });
+
+ test('a busy brain is not restarted, and the next idle tick may try', async () => {
+ const { home, audit } = brainHome('auto', true);
+ const state = { tried: false };
+ let calls = 0;
+ await withEnv({ GBRAIN_HOME: home, GBRAIN_AUDIT_DIR: audit }, () =>
+ restartServeAfterSelfUpgrade(async () => false, { state, restart: async () => { calls++; return { outcome: 'current' }; } }));
+ expect(calls).toBe(0);
+ expect(state.tried).toBe(false);
+ });
+
+ test('outside quiet hours, or in notify mode, nothing is restarted and the next tick may try', async () => {
+ for (const [mode, quiet] of [['auto', false], ['notify', true]] as const) {
+ const r = await run(mode, quiet, [{ outcome: 'restarted', detail: 'unused' }]);
+ expect(r.calls).toBe(0);
+ expect(r.state.tried).toBe(false);
+ }
+ });
+});