Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(upgrade): hand autopilot to its launcher instead of refusing (#8776); stable-daily skips rolled-back releases (#8792)
garrytanf89fc8de283f
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 46b4302e55..740af6699f 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -10,6 +10,20 @@ credits are retained; no result has been reassigned to another provider. Originaidentifiers and attribution are available in the pre-removal Git revision`6040075c6cb95be5881cc2e1b76ef7d71f4e5d29` (retained on 2026-09-23).+## [Unreleased]++**`gbrain upgrade` finishes on hosts where autopilot runs outside launchd and systemd, instead of refusing every time.**++The upgrade restarted autopilot only through an installed launchd or systemd service, and refused (`restart_refused`, exit 3) for any other autopilot. That included gbrain's own Linux cron install (`gbrain autopilot --install` on a host without a user systemd bus), so a scheduled stable upgrade on such a host failed on every run. An autopilot whose launcher starts it again is now handed to that launcher: the upgrade stops it (only while `ps` still shows the same process; SIGTERM drains it) and waits up to six minutes for the launcher to start the installed build.++| Situation | Before | Now |+|---|---|---|+| Autopilot started by this brain's gbrain cron line | `restart_refused` | handed to the cron line and verified back on the new build |+| Autopilot started by your own cron entry or wrapper | `restart_refused`, fix `kill <pid>` | still refuses, naming `gbrain autopilot --install` or `gbrain config set self_upgrade.autopilot_launcher external` (declare it only when the launcher starts autopilot again within 5 minutes); declared, it is handed over like the cron line |+| doctor `self_upgrade_health` | silent until an upgrade failed | runs the same pre-swap plan read-only: warns while `gbrain upgrade` would refuse, naming each process and its step (autopilot outside gbrain's service, a process from another install), and names a hand-off or a second Bun global install the upgrade replaces itself |++**The daily stable check no longer sticks on a rolled-back release.** A release that was stable before (its `stable-v<version>` record tag exists) or that `stable.json` lists in `known_bad` is skipped and logged, so the newest release gets its soak instead of a refused promotion on every scheduled run (#8792).+## [0.60.606.0] - 2026-11-07**Updates follow a stable channel by default; every release is one setting away on alpha.**diff --git a/docs/RELEASING.md b/docs/RELEASING.mdindex 6a57c1bb9f..3679abf288 100644--- a/docs/RELEASING.md+++ b/docs/RELEASING.md@@ -699,6 +699,10 @@ and keeps stable between one day and one week behind what matters:the full default one: both the 65 ms and 2 ms cells, at least 2 hours each,on the requested 600,000-page fixture, with privacy probes run and noneerroring, so a smaller smoke dispatch never qualifies. On the important-only path the candidate must contain the fix.+ A release that was stable before (its `stable-v<version>` record tag exists,+ so it was promoted and rolled back) or that `stable.json` lists in `known_bad`+ is skipped, logged, and never promoted or soaked by the schedule; a maintainer+ re-promotes it by hand if it should return.It is promoted through the same `promote()` as a manual promotion, so everycheck above still applies and the record's `promoted_by` is`schedule (.github/workflows/stable-daily.yml)` with the reason in `reason`.diff --git a/docs/architecture/key-files/ci-health-and-test-guards.md b/docs/architecture/key-files/ci-health-and-test-guards.mdindex 46f3a15d00..4c7726e1a1 100644--- a/docs/architecture/key-files/ci-health-and-test-guards.md+++ b/docs/architecture/key-files/ci-health-and-test-guards.md@@ -11,7 +11,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `scripts/ci-manifest.ts` — the versioned failure and execution manifest (`gbrain-ci-manifest/v1`). The `executed-receipts` job of test.yml and e2e.yml builds it from every lane's receipts (via `scripts/ci-executed-counts.ts`, declared skips from the expected-deltas TSV), binds it to the workflow, event, SHA, run id and attempt, and uploads it as `ci-manifest`; each failure carries the JUnit message (credentials redacted) and the stress gate's `failureSignature` (omitted when the message holds a credential); `checkManifest` refuses a manifest for another run or attempt; `passedFiles` lists files that executed tests and failed none. Docs: `docs/ci-red-runbook.md#ci-failure-manifest`.- `scripts/release-gate.ts` — release.yml's `ci-gate` job. Polls the push-to-master runs of Test and E2E Tests on the release commit and writes `publish`/`sha`: both green publishes; a failed run publishes nothing and fails with the next step; a run cancelled by a newer push is followed to the next master commit with the same VERSION (published there) or marks the version superseded; non-master refs are refused; it fails with the backfill command after 110 minutes. Build, release, `latest-stable` and the publish jobs use the gated commit. Tests: `test/scripts/release-gate.test.ts`. Docs: `docs/RELEASING.md#release-ci-gate`.- `.github/workflows/promote-stable.yml` + `scripts/promote-stable.ts` — stable channel promotion (`workflow_dispatch`: `version`, `soak_run_url`, `scoreboard_url`, `rollback`, `reason`, `withdraw`; concurrency group `promote-stable`). `promote()` refuses unless the actor's `role_name` is admin or maintain (`authorize()`; the one exception is `PromoteDeps.scheduled`, set by `scheduleAuthorized()` only for a schedule event of `stable-daily.yml` on the default branch, which also requires the release commit on master and records `promoted_by: schedule (.github/workflows/stable-daily.yml)`), `v<VERSION>` exists with a `VERSION` file naming it and a published (non-draft) GitHub release, the soak run URL names a completed, successful run of this repository's `STABLE_SOAK_WORKFLOW` workflow (repository variable; bare file name or path), the run's head commit has the release tag's exact tree (fetched when missing), and the version is newer than the current stable (the highest `v*` tag on `refs/tags/stable^{commit}`), or older with `rollback` and a reason. Re-promoting the current stable (no rollback) moves no tag: `recordCurrentStable()` writes `stable.json` from the stable tag's message (`parseTagMessage()`, which must name the same commit, tree and soak run) when the published record does not name that release, leasing `stable` unchanged and the record branch, and refuses as a no-op otherwise (GBRA-346 backfill for releases promoted before the record existed). It creates the immutable annotated `stable-v<VERSION>` record (refused when it exists, except on a rollback re-promotion of the same commit) and moves the annotated `stable` tag, both with `renderTagMessage()`'s `key: value` body, commits the evidence record (`renderRecord()`, `stable.json`, `known_bad` carried forward and merged with `withdraw` by `mergeKnownBad()`) on the `stable-record` branch, then pushes all three in one `--atomic` push (`stable` and `stable-record` leased on the values it read, so a failed push changes nothing) and writes the step summary. Side effects come in through `PromoteDeps`. Tests: `test/scripts/promote-stable.test.ts`. Docs: `docs/RELEASING.md#stable-channel-promotion`.-- `.github/workflows/stable-daily.yml` + `scripts/stable-daily.ts` — the daily stable check (05:17 and 13:17 UTC; dispatch defaults to `dry_run`, and `dry_run=false` needs admin or maintain; concurrency group `promote-stable`). Off when `STABLE_AUTO_PROMOTE` is `off`, paused while the stable record says `rollback: true`. Acts only on a reason: a merged `stable:important` PR released but not in stable, or stable older than `WEEKLY_FLOOR_DAYS` (7) with a newer release. Promotes, through `promote()`, the newest release on master newer than stable whose exact tree passed a full `SOAK_SHAPE` `STABLE_SOAK_WORKFLOW` run with every `INTEGRITY_GATES` gate passing in every cell (on the important-only path it must contain the fix); otherwise dispatches one soak on the newest release's tag, never while a soak runs or after a soak on a newer release failed to qualify. Tests: `test/scripts/stable-daily.test.ts`. Docs: `docs/RELEASING.md#daily-stable-check`.+- `.github/workflows/stable-daily.yml` + `scripts/stable-daily.ts` — the daily stable check (05:17 and 13:17 UTC; dispatch defaults to `dry_run`, and `dry_run=false` needs admin or maintain; concurrency group `promote-stable`). Off when `STABLE_AUTO_PROMOTE` is `off`, paused while the stable record says `rollback: true`. Acts only on a reason: a merged `stable:important` PR released but not in stable, or stable older than `WEEKLY_FLOOR_DAYS` (7) with a newer release. Promotes, through `promote()`, the newest release on master newer than stable whose exact tree passed a full `SOAK_SHAPE` `STABLE_SOAK_WORKFLOW` run with every `INTEGRITY_GATES` gate passing in every cell (on the important-only path it must contain the fix), skipping a release with a `stable-v<version>` tag (stable before, then rolled back) or on stable.json's `known_bad` (#8792); otherwise dispatches one soak on the newest release's tag, never while a soak runs or after a soak on a newer release failed to qualify. Tests: `test/scripts/stable-daily.test.ts`. Docs: `docs/RELEASING.md#daily-stable-check`.- `scripts/check-install-ref.ts` (`bun run check:install-ref`, in verify) — every install pin, bootstrap runbook fetch and setup-helper fetch in tracked files (not CHANGELOG.md or test/) names `INSTALL_REF` from `src/core/install-ref.ts`; exact `v<version>` and commit pins are left alone; TypeScript must import the constant; `--write` rewrites the text surfaces. `scripts/check-bootstrap-tag.sh` reads its sanctioned ref from the same constant. Tests: `test/install-ref.test.ts`.- `scripts/regen-all.ts` — one entry point for every generated artifact (`ARTIFACTS`: regen and check command per artifact). `bun run regen:all` regenerates offline and keyless (provider keys and database URLs removed) and lists what changed; a second run changes nothing. `--check` is read-only and runs in `verify` as `check:regen-all`; `--goldens` also regenerates the offline contract goldens. Postgres goldens are named with their own commands, and `llms.txt` regenerates last because it inlines other generated docs. Every `bun test` it spawns (two checks and the goldens) carries `--timeout=60000` through one `BUN_TEST` prefix, because Bun does not apply bunfig.toml's `[test] timeout`. Tests: `test/scripts/regen-all.test.ts`.- `scripts/release-restamp.ts` + `scripts/lib/restamp.ts` — `bun run release:restamp`, run when a PR is next to merge. The CLI refuses a dirty tree, fetches `origin/master`, captures the branch CHANGELOG entry and migration inventory, merges master with a merge commit (version-only stamp hunks, `CHANGELOG.md` and the `GENERATED_PATHS` files resolve mechanically; anything else stops), sets VERSION to master's PATCH + 1, renumbers branch-only migrations from master's latest + 1 (filename, export name and `version:` literal only; `migrationPayloadKey` proves the rest is token-identical and refuses a copy of a published migration or an edited published one), rewrites `STAMPS` (the CLAUDE.md "Version locations" Required rows) plus CHANGELOG and TODOS, runs `DEFAULT_STEPS`, lists branch-added lines that still name an old number (`findLeftoverRefs`, never rewritten), runs `DEFAULT_CHECKS` and commits once. Stops save `.git/gbrain-restamp.json` for `--continue` / `--abort`; `--dry-run` prints the plan, `--no-commit` stages. Generators run through `offlineEnv` (no database URLs, no provider keys). Tests: `test/scripts/release-restamp.test.ts` (fixture repos with the real migration generator; also pins CLAUDE.md table coverage and docs anchors).diff --git a/docs/architecture/key-files/commands-6.md b/docs/architecture/key-files/commands-6.mdindex d1df7f91b3..827416f2de 100644--- a/docs/architecture/key-files/commands-6.md+++ b/docs/architecture/key-files/commands-6.md@@ -14,8 +14,8 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `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 stable|alpha` (`latest` is an alias of `alpha`; resolution order in the Release channels entry below): `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).- Release channels: `src/core/self-upgrade.ts` resolves the channel (`resolveReleaseChannel`: `--channel`, `GBRAIN_RELEASE_CHANNEL`, `self_upgrade.channel`, default `stable`; `latest` normalizes to `alpha`; an invalid value at the first present source is an error) and keeps the update cache (`update-check.<channel>.json`, tagged with the evidence policy; an older answer never overwrites a newer one) and the time-based snooze (`update-snoozed.<channel>.json`) per channel; `offeredVersion` never offers a downgrade except to move off a `known_bad` version. `src/core/stable-channel.ts` reads and strictly parses the evidence record (`stable.json` on `stable-record`; `requiredEvidenceKeys`: `soak_run`, plus `matrix_run` from `MATRIX_REQUIRED_FROM`), maps failures to `stable_missing` / `stable_invalid` / `stable_unreadable` with sanitized causes, and `resolveStableRelease` checks the `stable` and `v<version>` tags against the record commit. `src/commands/upgrade-channel.ts` plans an upgrade's target (`channelTarget`, `runUpgradeDryRun` for `gbrain upgrade --dry-run --json`) and refuses with the typed code. `src/commands/check-update.ts` `refreshUpdateCache` never reads a bare VERSION for stable and never falls back to alpha. `src/core/release-channel-notice.ts` prints the one-time `[gbrain notice release_channel]` line on stderr (marker file under `notices/`; not under `--json`, `serve` or `mcp`; only when no channel is set). `src/core/install-ref.ts` is the one ref every install surface names, linted by `scripts/check-install-ref.ts`. Tests: `test/release-channel-w1.serial.test.ts`, `test/upgrade-stable-channel.test.ts`, `test/install-ref.test.ts`. Docs: `docs/guides/upgrades-auto-update.md#stable-channel`.-- `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. A serve counts as older only on evidence (a recorded build below this one, or no recorded build and a start before the install's `package.json` was written); a newer or unknown serve, or an install on disk that is not this build, is left alone. 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, `bunx`, `bun x` and `bun run <bin>`, skips interpreter flags that take a value, resolves a relative entry against the process's `/proc/<pid>/cwd` and accepts a `src/cli.ts` whose package two levels up is named gbrain (#8723); a process's parent is its nearest gbrain ancestor, and a worker with none is refused naming its parent's pid and executable, never its command line), `planRestart` (a service restarts only processes under its manager's pid; `supervisorRestartArgv` keeps the launch options and PID file, read from `--pid-file <path>`, and drops a `--flag=value` token that is neither a global flag nor `--job-isolation=`, because the supervisor that holds it ignored it and this build's `=` gate refuses it (#7619); 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/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 (360 s after an autopilot hand-off) 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`. #8776: `autopilotLauncher` (this brain's gbrain cron line from `crontab -l`, else `self_upgrade.autopilot_launcher external`) feeds the planner's hand-off; `upgradeRestartReadiness` is the preflight plan from the process table alone, which doctor's `self_upgrade_health` reads (local doctor only). `planServeRestart` reports a serve the service does not run, or one on another install, as `manual` and never restarts it. A serve counts as older only on evidence (a recorded build below this one, or no recorded build and a start before the install's `package.json` was written); a newer or unknown serve, or an install on disk that is not this build, is left alone. 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, `bunx`, `bun x` and `bun run <bin>`, skips interpreter flags that take a value, resolves a relative entry against the process's `/proc/<pid>/cwd` and accepts a `src/cli.ts` whose package two levels up is named gbrain (#8723); a process's parent is its nearest gbrain ancestor, and a worker with none is refused naming its parent's pid and executable, never its command line), `planRestart` (a service restarts only processes under its manager's pid; `supervisorRestartArgv` keeps the launch options and PID file, read from `--pid-file <path>`, and drops a `--flag=value` token that is neither a global flag nor `--job-isolation=`, because the supervisor that holds it ignored it and this build's `=` gate refuses it (#7619); an autopilot under no installed service gets a `handoff` step when `ctx.autopilotLauncher` is known (#8776: SIGTERM while the pid is unchanged, then the launcher must bring autopilot back), else a manual step naming `gbrain autopilot --install`; 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/error-codes.md b/docs/guides/error-codes.mdindex c5cc27ed0f..d852b3d0e6 100644--- a/docs/guides/error-codes.md+++ b/docs/guides/error-codes.md@@ -4182,7 +4182,7 @@ More: [docs/guides/troubleshooting.md#upstream-rewritten](../../docs/guides/trou| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable ||---|---|---|---|---|---|---|-| `gbrain upgrade` (or `--restart-only`) found a gbrain process on this host it cannot restart onto the new build (a serve or worker started by hand, an autopilot without its service, a running sync, or an MCP server an agent harness started), so it restarted nothing and, before a swap, installed nothing. | A process keeps the build it started with, so restarting only some of them leaves serve, workers and MCP servers on different builds; the upgrade refuses instead of leaving that skew. Each process is named with the exact step that restarts it. | Handle each listed process as the message says (MCP servers only: rerun with --stop-mcp after the user agrees), then run the same command again; `gbrain upgrade --no-restart` installs without restarting. Run: gbrain upgrade --restart-only --dry-run --json | user | `repeat the read that failed` | 3 | no |+| `gbrain upgrade` (or `--restart-only`) found a gbrain process on this host it cannot restart onto the new build (a serve or worker started by hand, an autopilot started outside its service by a launcher gbrain does not know, a running sync, or an MCP server an agent harness started), so it restarted nothing and, before a swap, installed nothing. | A process keeps the build it started with, so restarting only some of them leaves serve, workers and MCP servers on different builds; the upgrade refuses instead of leaving that skew. Each process is named with the exact step that restarts it. | Handle each listed process as the message says (MCP servers only: rerun with --stop-mcp after the user agrees), then run the same command again; `gbrain upgrade --no-restart` installs without restarting. Run: gbrain upgrade --restart-only --dry-run --json | user | `repeat the read that failed` | 3 | no |More: [docs/guides/upgrades-auto-update.md#restart](../../docs/guides/upgrades-auto-update.md#restart)diff --git a/docs/guides/upgrades-auto-update.md b/docs/guides/upgrades-auto-update.mdindex 7706f714fb..567d2197d2 100644--- a/docs/guides/upgrades-auto-update.md+++ b/docs/guides/upgrades-auto-update.md@@ -293,8 +293,16 @@ process this brain runs on the host, or refuses before it installs anything:and one that starts from another kind of install refuses with its commands;the supervisor with `gbrain jobs supervisor stop` then `start --detach` withthe queue, concurrency and PID file it was launched with (its worker, under- tini or not, restarts with it). A serve or worker started by hand, an- autopilot without its service, a running `gbrain sync`, or an MCP server an agent+ tini or not, restarts with it). An autopilot that no installed service runs+ is handed to its launcher when one is known to start it again: this brain's+ own gbrain cron line (what `gbrain autopilot --install` writes on Linux+ without a user systemd bus), or a cron entry or wrapper of your own once you+ declare it with `gbrain config set self_upgrade.autopilot_launcher external`+ (only when it starts autopilot again within 5 minutes of it exiting). The+ restart stops that autopilot (only the daemon this brain's autopilot lock+ names, and only while `ps` still shows the same process; SIGTERM drains it)+ and waits for the launcher. A serve or worker started by+ hand, an autopilot started any other way, a running `gbrain sync`, or an MCP server an agentharness started refuses the upgrade with `restart_refused` (exit 3), namingthe exact step for each process; nothing is installed. For MCP servers thefix asks the user, then reruns with `--stop-mcp`: the upgrade stops them@@ -303,8 +311,9 @@ process this brain runs on the host, or refuses before it installs anything:`/mcp`, then reconnect; other harnesses: a new session).2. **After the swap and migrations** the new build runs`gbrain upgrade --restart-only`: serve first, then autopilot, then the- supervisor, then the MCP servers `--stop-mcp` named. It then polls for up to- three minutes until no old pid is alive, every process reports the installed+ supervisor, then an autopilot handed to its launcher, then the MCP servers+ `--stop-mcp` named. It then polls for up to three minutes (six when an+ autopilot was handed to its launcher) until no old pid is alive, every process reports the installedbuild (a process that records no build must have started after the restartfrom an install that holds it; a compiled binary's build is inferred fromits start time and listed as such), each restarted role and the supervisor's@@ -318,6 +327,13 @@ gbrain upgrade --restart-only # restart onto the installed bugbrain upgrade --no-restart # install only; doctor fails runtime_build_skew until the restart runs```+`gbrain doctor` runs the same pre-swap plan read-only: `self_upgrade_health`+warns while the next `gbrain upgrade` would refuse, naming each process and its+step (for an autopilot started outside gbrain's service, `gbrain autopilot+--install`, after retiring the launcher that starts it now, or the declared+hand-off above), and names a hand-off or a second Bun global install the+upgrade replaces itself.+On an always-on host, start with `gbrain autopilot pause --reason "upgrade"`and wait until `gbrain jobs list --status active --json` returns no jobs, so nojob runs half on each build; resume with `gbrain autopilot resume` once thediff --git a/plugin/skills/gbrain-upgrade/SKILL.md b/plugin/skills/gbrain-upgrade/SKILL.mdindex dea7d1f820..83f6bb817f 100644--- a/plugin/skills/gbrain-upgrade/SKILL.md+++ b/plugin/skills/gbrain-upgrade/SKILL.md@@ -138,8 +138,9 @@ With the operator's go-ahead, upgrade in this order:lists the installs on PATH; a harness, cron wrapper or service may runanother by absolute path). It restarts serve, autopilot and the jobssupervisor onto the new build and verifies one build runs. A process it- cannot restart (one started by hand, a running `gbrain sync`, an MCP server- a harness started) refuses with `restart_refused` (exit 3) before anything+ cannot restart (one started by hand, an autopilot a cron entry or wrapper+ starts unless `self_upgrade.autopilot_launcher external` declares it, a+ running `gbrain sync`, an MCP server a harness started) refuses with `restart_refused` (exit 3) before anythinginstalls: relay the step it names; `--stop-mcp` only after the user agrees.5. Verify: `gbrain --version` per install, and`gbrain doctor --only runtime_build_skew,serve_build_drift --json` ok. On adiff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsvindex b603074aa7..077f0c964a 100644--- a/scripts/module-size-limits.tsv+++ b/scripts/module-size-limits.tsv@@ -36,7 +36,7 @@ src/core/embedding-migration.ts 1587 ratchet new row: crossed 1500 in v0.46.25.0src/core/github-source.ts 1530 ratchet new row: crossed the 1500 unlisted cap in v0.46.23.0 review fix wave (scope-state gating, client hardening, symlink containment); merged reliability/shared-skills source integration; managed sweep lease wrapper; fix wave 3 lane A: config parser peeled to github-source-config.ts (-47), +account pin wiring and pinned-installation refreshsrc/commands/hook.ts 1996 ratchet cathedral-5 heartbeat extraction offsets part of the BrainBench-seam growth; grown v0.46.26.0 megawave hooks-ipc (#4245); +108 monthly backup check: banner + gated session-start note + detached spawn (backup/status-file readers); +28 ship-review egress hardening: per-harness capture dispatch (capture-spec), memorable gate + receipt + relay block, fail-closed unscanned/newest-guess skips; +79 ambient-writeback WP4: hookStop bank step (gate -> bankWritebackTurn -> IPC flush; gate/bank logic live in core/facts + corpus-segments); +41 adversarial fix wave: wide-tail retry when the 128KB window misses the user turn, by-design heartbeat outcome classes, source-in-name banking; +11 #5413 session-end skips claude-cli self-transcripts; +11 #5701: hook lanes pass allowOversize so a long session reaches the bounded tail read; +1 #5371: the stop-hook dirty probe ignores physical-root ownership metadata (root-metadata.ts, engine-free); 2 core memory: user-prompt context-pressure notice wiring (logic in core/context/pressure.ts; session-start composition in core/context/session-start-output.ts); +3 fix wave 11 W2.1 #6091: PreCompact/SessionEnd capture-time consent record calls (logic in core/context/capture-consent.ts); +5 fix wave 11 W2.9 #6083: the three detached-push call sites skip a managed canonical worktree (push_managed_coordinator) + import; +2 fix wave 11 integration: W1 router help guard import beside the W2 managed-root import; +2 fix wave 13 P4.9 #6399: a header-only Codex rollout ends empty_session, not parser_drift; +3 W14 P4.16 (#5799): banner and SessionStart note read livePushStatuses (predicate in core/workspace-push.ts); +1 W15 P5.7 (#4992): gitChildEnv import for the hook git probes (launches moved onto core/spawn.ts); +13 GBRA-188 per-turn brain-first rule: user-prompt emission and its HookIo seam (rule and ledger read in core/setup/brain-first.ts); +3 GBRA-188 plugin lane: GBRAIN_HOOK_LANE=plugin yields to another gbrain lane wiring the event (import, comment and guard; detection in bootstrap/plugin-lanes.ts otherLaneWiresHook); +5 GBRA-243 turn-rule lane: GBRAIN_HOOK_LANE=turn-rule yields to every other lane and answers rule-only (import, two guards and comments; logic in core/setup/turn-hook.ts), user-prompt passes cwd to the scope-aware rule; +34 #8064/#8016/#8028: the session-speaker banking decision at compact, stop and session-end (logic in context/session-speaker.ts), the harness-prompt skip and the lane-scoped parser_drift clear; +1 #8424: hookSessionCwd import (the session directory the hook launcher records; logic in core/setup/hook-launcher.ts); +1 #8424 review: runHook captures the launcher-recorded session directory first (logic in setup/hook-launcher.ts captureHookSessionCwd); +7 #8427: the hook git probes skip core.fsmonitor and run only in the workspace the install receipt namessrc/core/chunkers/code.ts 1602 ratchet new row: crossed the 1500 unlisted cap in v0.46.26.0 megawave (decorated-python defs #3821, version-gate + timeout chunker fixes); grown wave-g (#4511): named defs never folded into merged chunks; grown #4669: skip WASM parse for languages without TOP_LEVEL_TYPES; +6 N13-1: CodeChunkMetadata.definesFunction field + merge-guard stamp (predicate lives in def-types.ts); +10 Lua grammar swap: GRAMMAR_REVISIONS + chunkerStamp() (per-language re-chunk gate); +4: CodeChunkOptions.timeoutMs (per-call parse cap; markdown fences parse under a short cap) and the "Parsing failed" → ChunkerTimeoutError mapping in parseWithTimeout-src/core/config.ts 2021 ratchet +1 GBRA-154 #7175: search.keyword_phrase KNOWN_CONFIG_KEYS row; +1 search.saved_facts_supersede KNOWN_CONFIG_KEYS row (read in search/saved-facts-match.ts; re-summed at the #7703 merge: 2014 + 1); +2 W5: search.page_rank_cut / page_rank_cut_factor KNOWN_CONFIG_KEYS rows (read in search/page-rank-cut.ts); +3 W3 confidence-gated reranking: search.reranker.gate / gate_min_gap KNOWN_CONFIG_KEYS rows (values parsed in search/crag.ts); re-summed at the W3 merge onto master v0.60.169.0 (1951 measured); +1 budgeted delivery PR 1: the search.auto_packing KNOWN_CONFIG_KEYS row (values validated in search/evidence-packing.ts); +1 #6278: persistence.sync_preparation_ms/maintenance_preparation_ms/preparation_ceiling_ms/max_preparation_attempts/preparation_deadlines key row (logic in persistence/preparation-budget.ts, switches.ts); +22 fix wave 11 W6.2/W6.3 (#5989, #6132): search.cjk_keyword_deadline_ms and search.hnsw_iterative_scan type fields, KNOWN_CONFIG_KEYS rows and the mergeSearchScanKnobs helper that keeps loadConfigWithEngine under its function-size baseline (logic in search/cjk-keyword-deadline.ts, search/hnsw-iterative-scan.ts); +8 #5988: sync.holds/hold_cap/hold_escalate_count/hold_escalate_pct/parser_regression key registration (read by persistence/sync-holds.ts); +3 agent operator wave A4: GBrainConfig.consent file-plane slot + 2 consent.preapprove.* key rows (logic in core/consent.ts); +1 System One v1: decide.* key prefix (validated by ai/decide/config.ts); new row: crossed the 1500 unlisted cap in v0.46.26.0 megawave (spend-controls hint #3703, config-set validation); +3 wave G #3974: sync.include_working_tree key; grown wave-g (#4540 #4494 #4415): extractor caps + intent-pattern config keys; +1 chat-connectors: connectors. config prefix; wave-k: config-table snapshot serving the DB-plane reads (#3980 + #2119 merge); +8: loadConfig hook for ~/.gbrain/.env, loader lives in gbrain-env-file.ts (#3893); +17: litellm/together key-fold slots (#3904 reimpl: two GBrainConfig fields + KNOWN_CONFIG_KEYS rows); +1: link_resolution.cross_source key (#3908); +4 v0.47 gmail-loops: loops.extraction_enabled key; +1: pricing.overrides key (#4633 adoption); +7 #4667 adoption: sync.exclude key registration; +4: eval fix wave keys (quote_verify + 3 rescue knobs); +memorable file-plane key registration (integrations.memorable.enabled + consent-event doc); +33 ambient-writeback: memory.* + brain.audience key registration + GBrainConfig.memory mirror slot (resolvers live in facts/writeback-config.ts); +38 2026-08 wave: retrieval_reflex_volunteer key + env mapping (volunteer-arm kill switch) + E5a registration of the 10 adaptive_return*/autocut*/crag_* search (incl. adversarial batch isEnvDisabled dedup); ambient-writeback (master merge): facts/writeback-config.ts); new row: crossed the 1500 unlisted cap in v0.46.26.0 megawave; prior growth: sync/intent/chat-connectors/litellm/pricing/loops key folds; +34: #4702 content_sanity.disabled_patterns (type + DB-plane parse/merge + key registration); composition true-up (fix-wave multi-train) | merged v0.48.1.0: master #4788 writeback keys + wave #4702/#4748 keys; master: | merged v0.48.1.0 true-up; ranker wave v0.48.4.0: +4 KNOWN_CONFIG_KEYS rows (+8); +5 #4895: CWD_DOTENV_FILES gains the per-NODE_ENV .local variants Bun auto-loads; +2 #5003: sync.include_hidden key registration; +57 #4605: search.* registry reconciled to the keys mode.ts reads (+20 knob rows, +4 direct-read singletons) + GBrainConfig.search slot + adaptive_return* DB-plane merge; +2 pre-landing review: fts.reindex_in_progress key registration (#4795 marker escape hatch); +4 #4987: auto_timeline key registration (the documented off switch was rejected as unknown); lowered to 1793: GHSA wave v0.50.5.0 moved CWD_DOTENV_FILES + dotenvValuesForKey into core/env-trust.ts (-49, re-exported); re-summed to the merged line count after merging master v0.50.2.0 (#5122) with the v0.50.5.0 security wave; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +1 at the merge; evidence delivery: 5 registered config keys + comment (+7); +2 #5691: embedding_query_prefix key registration; evidence delivery auto v2: search.return_budget_conversation key row (+1); +1 #5836: facts.entity_inference key row; +6 #5824: search.vector_legacy_guard key row + GBrainConfig.search slot + DB-plane merge; +3 wave 8 lane D1 #5885: takes.auto_embed key row; +3 #5232: GBrainConfig.persistence.write_wait_ms file-plane slot + key row (resolver in persistence/write-wait.ts); +2 F4b: planner.* and import.analyze_every_pages keys; +3 cat40 cost wave C1 (garrytan/gbrain-evals#57 follow-ups): mcp.result_rows GBrainConfig slot + key row (resolver in mcp/result-rows.ts); v0.60.46.0 merge: both waves' +3 compose (1824 + 3 = 1827 measured); +4 #5984: sync.bulk, sync.bulk_size, sync.bulk_max_txn_ms known keys; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (1838 measured); +3 retrieval feedback: the feedback keys in KNOWN_CONFIG_KEYS; 2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); P3 x engine graduation composition: both deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); P3 x foundations-2 composition: deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); +1 GBRA-49: graph.* key prefix (graph.edge_validity, read by link-validity.ts); P3 x P1 (v0.60.57.0) composition: deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); +1 GBRA-49: graph.* key prefix (graph.edge_validity, read by link-validity.ts); +3 P7 search.relational_planner / search.relational_orient_onehop key registration; +2 P7 search.relational_chain_slots key registration; P3 x P7 (v0.60.60.0) composition: deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); +1 GBRA-49: graph.* key prefix (graph.edge_validity, read by link-validity.ts); +3 P7 search.relational_planner / search.relational_orient_onehop key registration; +2 P7 search.relational_chain_slots key registration; +3 agent operator follow-up Item 2: mcp.allow_session_widen (GBrainConfig.mcp slot + known key); P3 x aow-followup composition: deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); +1 GBRA-49: graph.* key prefix (graph.edge_validity, read by link-validity.ts); +3 P7 search.relational_planner / search.relational_orient_onehop key registration; +2 P7 search.relational_chain_slots key registration; +3 agent operator follow-up Item 2: mcp.allow_session_widen (GBrainConfig.mcp slot + known key); +2 entity mention index: mentions.auto_link, mentions.entity_types, mentions.ignore key rows (resolver in core/mentions/policy.ts); cat40 entity wave merge with v0.60.61.0 (1853 measured); P3 x cat40-entity-wave composition: deltas re-summed at the merge; +6 fix wave lane B3: chat_fallback_on_refusal (GBrainConfig slot, GBRAIN_CHAT_FALLBACK_ON_REFUSAL env fold, known key); +2 W-B4: shared_skills.inventory.* known keys (logic in shared-skills/inventory-limits.ts); +2 fix wave 9 lane B #4921: ai.chat.per_turn_timeout_ms known key; +1 wave 9 lane W #5363: cycle.consolidate.cluster_threshold key row; +1 #5984 lanes: sync.lanes key registration; +2 P8: dream.quote_verify and think.quote_verify known keys; +2 P8: GBrainConfig.mcp.advertised_surface interface slot (resolver in mcp/surface.ts); +2 fix wave 10 lane L1 #4907: cycle.synthesize_concepts.budget_usd registered (validation in cycle/phase-config-values.ts); +2 #5958: dream.propose_takes.call_timeout_ms registered; 3 core memory: memory.core.* and memory.pressure.* known keys; +15 P5: wanted_pages.enabled/remote, line_grammar.enabled/allow_undeclared_types/effective_ranges and put_page.similar_pages key rows (logic in wanted-links.ts, line-grammar.ts, similar-pages.ts); +1 P2 extraction.date_grounding / facts.attribution keys; +1 #6188: fences.normalize registered in KNOWN_CONFIG_KEYS; +2 #6188: fences.repair.max_usd_per_page/per_day key rows; +1 fix wave 12 W2.3 #6231: facts.page_write_notability_filter key row (resolver in facts/notability-filter.ts); +1 #6317: persistence.single_consumer key row (logic in persistence/switches.ts, consumer-election.ts); +2 newer mentions on context_pack cards: mentions.newer_on_cards key row (logic in mentions/newer-mentions.ts); master v0.60.136.0 merge into #5575 memory trust (both sides kept); +1 #5329 (W14 PR3): chronicle.max_events_per_page registered in KNOWN_CONFIG_KEYS (validation in chronicle/config.ts); +2 C1/C2 memory proof wave: search.evidence_date_header + facts.candidate_fusion registry rows; +1 facts.supersession_thresholds registry row (per-model supersession calibration); +1 C4: models.standing_questions key row; +1 search.entity_anchoring key registration (default off; search/entity-anchor.ts); +1 search.query_facts_arm key registration (default off; search/facts-arm.ts); re-summed at the master 6ccf30c3e merge (1871 integration + 1868 master - 1865 base); +1 search.temporal_fact_reserve key registration (default off; search/facts-arm.ts); +1 fix wave 13 PR2: persistence.publication_ceiling_ms (P2.1/P2.3); v0.60.165.0 merge: W14 PR4 +7 and master +2 compose (1947 measured); +1 memory proof wave 2 W1: the recall.question_admission KNOWN_CONFIG_KEYS row (values validated in facts/question-recall.ts); +2 Cat 40 Hard fix wave (#6271) on top: mentions.alias_deny/multiword_aliases/sibling_merge and search.alias_fanout_max/demote_generated KNOWN_CONFIG_KEYS rows (1950 measured); +1 wave 15 P7.1 #5213: cycle.propose_takes.types KNOWN_CONFIG_KEYS row (parse + filter live in cycle/propose-takes.ts); +1 wave 15 P7.2 #6451: autopilot.git_pull KNOWN_CONFIG_KEYS row (read in persistence/automatic-sync-policy.ts); +1 wave 15 P7.3 #6369: cycle.lint.enabled KNOWN_CONFIG_KEYS row (read in cycle/lint-fix-setting.ts); +2 wave 15 P7.4 #5461: think.pages_budget_chars / think.excerpt_ceiling_chars KNOWN_CONFIG_KEYS rows (validation in think/pages-budget.ts); +6 wave 16 G5.1 (#6495): search.keyword_statement_timeout_ms type field, DB merge and KNOWN_CONFIG_KEYS row, toEngineConfig carries it (range + resolver live in postgres-engine/keyword-statement-timeout.ts); +1 GBRA-81 item 1: search.mode_source registered; +1 GBRA-60 S1: search.diverse_pool_depth in the known search keys; +3 #6643: sync.knock_on_refreeze_limit / sync.knock_on_run_limit KNOWN_CONFIG_KEYS rows (read by persistence/sync-run.ts knockOnLimits); +3 #6696: KNOWN_CONFIG_KEYS rows for persistence.maintenance.compaction_stale_hours and refusal_breaker_threshold; +1 wave 5 D5: context.proactive_brief KNOWN_CONFIG_KEYS row (read in context/proactive-brief.ts); +3 Cat 40 next wave part 1: KNOWN_CONFIG_KEYS rows for entity.names_references + entity.record_types + entity.row_page_status (one line), mcp.instructions_governing_rule and search.long_page_unit (re-summed at the 0.60.242.0 merge: master 1975 + 3); +1 wave 17 (#6667): cycle.consolidate.enabled KNOWN_CONFIG_KEYS row (read in cycle/phases/consolidate.ts); +2 Wave B PR 1: pages.segmented_storage and the segmented ceiling/retention keys (page-body/limits.ts); merge v0.60.249.0: Wave B PR 1 and master growth compose at 1981; +1 #6297: dream.patterns.min_interval_hours / child_read_budget_kb known keys; +1 #5012: loops.updates_require_reciprocity known key; +1 wave 18b lane 2 (#6495): search.keyword_timeout_negative_cache_seconds KNOWN_CONFIG_KEYS row; integrated at wave 18b: master 1981 + 4 (lanes 2, 3, 5 known keys); +1 #6948: sync.origin_twins.auto_resolve KNOWN_CONFIG_KEYS row (read in repair/origin-twins-heal.ts); +1 #6948 sweep C-9: facts.absorb_retry.max_resubmits KNOWN_CONFIG_KEYS row (read in facts/dead-absorb-retry.ts); +1 #6907: backup.remote_timeout_ms KNOWN_CONFIG_KEYS row (resolver in backup/repository.ts); +1 at the #6712 PR 4b merge onto master v0.60.310.0 (both sides added a key); +3 #7130: sync.max_deletes / sync.max_delete_ratio / purge.retention_hours KNOWN_CONFIG_KEYS rows and the two per-source cap prefixes (parsers live in core/sync-reconcile.ts); +2 GBRA-154: search.collapse / search.rank_priors KNOWN_CONFIG_KEYS rows (read in search/mode.ts); +1 GBRA-150: sync.metafile_pages KNOWN_CONFIG_KEYS row (read in core/sync.ts); +1 GBRA-159: visibility.honor_aliases KNOWN_CONFIG_KEYS row (read in search/private-visibility.ts); +4 GBRA-156 warm CLI socket: GBrainConfig.serve_cli_socket slot and the published-config.ts import/re-export (snapshot-only merge and MERGED_CONFIG_BY_ENGINE live in core/published-config.ts); re-summed at the GBRA-159 hotfix merge (2000 measured); +2 #7242 GBrainConfig.minions.terminal_hook (interface field); #7252 merge of master v0.60.343.0: both sides grew the file, re-summed (2002 measured); +1 GBRA-155: entity.name_variants KNOWN_CONFIG_KEYS row (read in verbs/entity-variants.ts); +2 GBRA-161: the generations.* KNOWN_CONFIG_KEYS rows and their comment (bounds and reader in generations/config.ts); +1 GBRA-156: search.evidence_tail_trim KNOWN_CONFIG_KEYS row (read in search/evidence-tail-trim.ts); +2 GBRA-175: self_upgrade.channel (the GBrainConfig field and its KNOWN_CONFIG_KEYS row; resolved in core/self-upgrade.ts); re-summed at the master 440eeef6 merge (2009 measured); +2 GBRA-156 vector prewarm: GBrainConfig.serve_vector_prewarm slot (snapshot merge lives in core/published-config.ts); +1 GBRA-95 G7a: storage.git_lfs KNOWN_CONFIG_KEYS row (read in persistence/git-declared.ts); re-summed at the v0.60.449.0 merge (2012 measured); +2 GBRA-205: search.evidence_titles / query_budget_unit / query_facts_block / fact_source_pages KNOWN_CONFIG_KEYS rows (read in search/evidence-date.ts, evidence-packing.ts, facts-arm.ts); +1 GBRA-156: search.remote_page_cap KNOWN_CONFIG_KEYS row (read in search/remote-page-cap.ts); re-summed at the memory train #8481 merge with v0.60.576.0 (2021 measured)+src/core/config.ts 2024 ratchet +1 GBRA-154 #7175: search.keyword_phrase KNOWN_CONFIG_KEYS row; +1 search.saved_facts_supersede KNOWN_CONFIG_KEYS row (read in search/saved-facts-match.ts; re-summed at the #7703 merge: 2014 + 1); +2 W5: search.page_rank_cut / page_rank_cut_factor KNOWN_CONFIG_KEYS rows (read in search/page-rank-cut.ts); +3 W3 confidence-gated reranking: search.reranker.gate / gate_min_gap KNOWN_CONFIG_KEYS rows (values parsed in search/crag.ts); re-summed at the W3 merge onto master v0.60.169.0 (1951 measured); +1 budgeted delivery PR 1: the search.auto_packing KNOWN_CONFIG_KEYS row (values validated in search/evidence-packing.ts); +1 #6278: persistence.sync_preparation_ms/maintenance_preparation_ms/preparation_ceiling_ms/max_preparation_attempts/preparation_deadlines key row (logic in persistence/preparation-budget.ts, switches.ts); +22 fix wave 11 W6.2/W6.3 (#5989, #6132): search.cjk_keyword_deadline_ms and search.hnsw_iterative_scan type fields, KNOWN_CONFIG_KEYS rows and the mergeSearchScanKnobs helper that keeps loadConfigWithEngine under its function-size baseline (logic in search/cjk-keyword-deadline.ts, search/hnsw-iterative-scan.ts); +8 #5988: sync.holds/hold_cap/hold_escalate_count/hold_escalate_pct/parser_regression key registration (read by persistence/sync-holds.ts); +3 agent operator wave A4: GBrainConfig.consent file-plane slot + 2 consent.preapprove.* key rows (logic in core/consent.ts); +1 System One v1: decide.* key prefix (validated by ai/decide/config.ts); new row: crossed the 1500 unlisted cap in v0.46.26.0 megawave (spend-controls hint #3703, config-set validation); +3 wave G #3974: sync.include_working_tree key; grown wave-g (#4540 #4494 #4415): extractor caps + intent-pattern config keys; +1 chat-connectors: connectors. config prefix; wave-k: config-table snapshot serving the DB-plane reads (#3980 + #2119 merge); +8: loadConfig hook for ~/.gbrain/.env, loader lives in gbrain-env-file.ts (#3893); +17: litellm/together key-fold slots (#3904 reimpl: two GBrainConfig fields + KNOWN_CONFIG_KEYS rows); +1: link_resolution.cross_source key (#3908); +4 v0.47 gmail-loops: loops.extraction_enabled key; +1: pricing.overrides key (#4633 adoption); +7 #4667 adoption: sync.exclude key registration; +4: eval fix wave keys (quote_verify + 3 rescue knobs); +memorable file-plane key registration (integrations.memorable.enabled + consent-event doc); +33 ambient-writeback: memory.* + brain.audience key registration + GBrainConfig.memory mirror slot (resolvers live in facts/writeback-config.ts); +38 2026-08 wave: retrieval_reflex_volunteer key + env mapping (volunteer-arm kill switch) + E5a registration of the 10 adaptive_return*/autocut*/crag_* search (incl. adversarial batch isEnvDisabled dedup); ambient-writeback (master merge): facts/writeback-config.ts); new row: crossed the 1500 unlisted cap in v0.46.26.0 megawave; prior growth: sync/intent/chat-connectors/litellm/pricing/loops key folds; +34: #4702 content_sanity.disabled_patterns (type + DB-plane parse/merge + key registration); composition true-up (fix-wave multi-train) | merged v0.48.1.0: master #4788 writeback keys + wave #4702/#4748 keys; master: | merged v0.48.1.0 true-up; ranker wave v0.48.4.0: +4 KNOWN_CONFIG_KEYS rows (+8); +5 #4895: CWD_DOTENV_FILES gains the per-NODE_ENV .local variants Bun auto-loads; +2 #5003: sync.include_hidden key registration; +57 #4605: search.* registry reconciled to the keys mode.ts reads (+20 knob rows, +4 direct-read singletons) + GBrainConfig.search slot + adaptive_return* DB-plane merge; +2 pre-landing review: fts.reindex_in_progress key registration (#4795 marker escape hatch); +4 #4987: auto_timeline key registration (the documented off switch was rejected as unknown); lowered to 1793: GHSA wave v0.50.5.0 moved CWD_DOTENV_FILES + dotenvValuesForKey into core/env-trust.ts (-49, re-exported); re-summed to the merged line count after merging master v0.50.2.0 (#5122) with the v0.50.5.0 security wave; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +1 at the merge; evidence delivery: 5 registered config keys + comment (+7); +2 #5691: embedding_query_prefix key registration; evidence delivery auto v2: search.return_budget_conversation key row (+1); +1 #5836: facts.entity_inference key row; +6 #5824: search.vector_legacy_guard key row + GBrainConfig.search slot + DB-plane merge; +3 wave 8 lane D1 #5885: takes.auto_embed key row; +3 #5232: GBrainConfig.persistence.write_wait_ms file-plane slot + key row (resolver in persistence/write-wait.ts); +2 F4b: planner.* and import.analyze_every_pages keys; +3 cat40 cost wave C1 (garrytan/gbrain-evals#57 follow-ups): mcp.result_rows GBrainConfig slot + key row (resolver in mcp/result-rows.ts); v0.60.46.0 merge: both waves' +3 compose (1824 + 3 = 1827 measured); +4 #5984: sync.bulk, sync.bulk_size, sync.bulk_max_txn_ms known keys; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (1838 measured); +3 retrieval feedback: the feedback keys in KNOWN_CONFIG_KEYS; 2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); P3 x engine graduation composition: both deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); P3 x foundations-2 composition: deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); +1 GBRA-49: graph.* key prefix (graph.edge_validity, read by link-validity.ts); P3 x P1 (v0.60.57.0) composition: deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); +1 GBRA-49: graph.* key prefix (graph.edge_validity, read by link-validity.ts); +3 P7 search.relational_planner / search.relational_orient_onehop key registration; +2 P7 search.relational_chain_slots key registration; P3 x P7 (v0.60.60.0) composition: deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); +1 GBRA-49: graph.* key prefix (graph.edge_validity, read by link-validity.ts); +3 P7 search.relational_planner / search.relational_orient_onehop key registration; +2 P7 search.relational_chain_slots key registration; +3 agent operator follow-up Item 2: mcp.allow_session_widen (GBrainConfig.mcp slot + known key); P3 x aow-followup composition: deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); +1 GBRA-49: graph.* key prefix (graph.edge_validity, read by link-validity.ts); +3 P7 search.relational_planner / search.relational_orient_onehop key registration; +2 P7 search.relational_chain_slots key registration; +3 agent operator follow-up Item 2: mcp.allow_session_widen (GBrainConfig.mcp slot + known key); +2 entity mention index: mentions.auto_link, mentions.entity_types, mentions.ignore key rows (resolver in core/mentions/policy.ts); cat40 entity wave merge with v0.60.61.0 (1853 measured); P3 x cat40-entity-wave composition: deltas re-summed at the merge; +6 fix wave lane B3: chat_fallback_on_refusal (GBrainConfig slot, GBRAIN_CHAT_FALLBACK_ON_REFUSAL env fold, known key); +2 W-B4: shared_skills.inventory.* known keys (logic in shared-skills/inventory-limits.ts); +2 fix wave 9 lane B #4921: ai.chat.per_turn_timeout_ms known key; +1 wave 9 lane W #5363: cycle.consolidate.cluster_threshold key row; +1 #5984 lanes: sync.lanes key registration; +2 P8: dream.quote_verify and think.quote_verify known keys; +2 P8: GBrainConfig.mcp.advertised_surface interface slot (resolver in mcp/surface.ts); +2 fix wave 10 lane L1 #4907: cycle.synthesize_concepts.budget_usd registered (validation in cycle/phase-config-values.ts); +2 #5958: dream.propose_takes.call_timeout_ms registered; 3 core memory: memory.core.* and memory.pressure.* known keys; +15 P5: wanted_pages.enabled/remote, line_grammar.enabled/allow_undeclared_types/effective_ranges and put_page.similar_pages key rows (logic in wanted-links.ts, line-grammar.ts, similar-pages.ts); +1 P2 extraction.date_grounding / facts.attribution keys; +1 #6188: fences.normalize registered in KNOWN_CONFIG_KEYS; +2 #6188: fences.repair.max_usd_per_page/per_day key rows; +1 fix wave 12 W2.3 #6231: facts.page_write_notability_filter key row (resolver in facts/notability-filter.ts); +1 #6317: persistence.single_consumer key row (logic in persistence/switches.ts, consumer-election.ts); +2 newer mentions on context_pack cards: mentions.newer_on_cards key row (logic in mentions/newer-mentions.ts); master v0.60.136.0 merge into #5575 memory trust (both sides kept); +1 #5329 (W14 PR3): chronicle.max_events_per_page registered in KNOWN_CONFIG_KEYS (validation in chronicle/config.ts); +2 C1/C2 memory proof wave: search.evidence_date_header + facts.candidate_fusion registry rows; +1 facts.supersession_thresholds registry row (per-model supersession calibration); +1 C4: models.standing_questions key row; +1 search.entity_anchoring key registration (default off; search/entity-anchor.ts); +1 search.query_facts_arm key registration (default off; search/facts-arm.ts); re-summed at the master 6ccf30c3e merge (1871 integration + 1868 master - 1865 base); +1 search.temporal_fact_reserve key registration (default off; search/facts-arm.ts); +1 fix wave 13 PR2: persistence.publication_ceiling_ms (P2.1/P2.3); v0.60.165.0 merge: W14 PR4 +7 and master +2 compose (1947 measured); +1 memory proof wave 2 W1: the recall.question_admission KNOWN_CONFIG_KEYS row (values validated in facts/question-recall.ts); +2 Cat 40 Hard fix wave (#6271) on top: mentions.alias_deny/multiword_aliases/sibling_merge and search.alias_fanout_max/demote_generated KNOWN_CONFIG_KEYS rows (1950 measured); +1 wave 15 P7.1 #5213: cycle.propose_takes.types KNOWN_CONFIG_KEYS row (parse + filter live in cycle/propose-takes.ts); +1 wave 15 P7.2 #6451: autopilot.git_pull KNOWN_CONFIG_KEYS row (read in persistence/automatic-sync-policy.ts); +1 wave 15 P7.3 #6369: cycle.lint.enabled KNOWN_CONFIG_KEYS row (read in cycle/lint-fix-setting.ts); +2 wave 15 P7.4 #5461: think.pages_budget_chars / think.excerpt_ceiling_chars KNOWN_CONFIG_KEYS rows (validation in think/pages-budget.ts); +6 wave 16 G5.1 (#6495): search.keyword_statement_timeout_ms type field, DB merge and KNOWN_CONFIG_KEYS row, toEngineConfig carries it (range + resolver live in postgres-engine/keyword-statement-timeout.ts); +1 GBRA-81 item 1: search.mode_source registered; +1 GBRA-60 S1: search.diverse_pool_depth in the known search keys; +3 #6643: sync.knock_on_refreeze_limit / sync.knock_on_run_limit KNOWN_CONFIG_KEYS rows (read by persistence/sync-run.ts knockOnLimits); +3 #6696: KNOWN_CONFIG_KEYS rows for persistence.maintenance.compaction_stale_hours and refusal_breaker_threshold; +1 wave 5 D5: context.proactive_brief KNOWN_CONFIG_KEYS row (read in context/proactive-brief.ts); +3 Cat 40 next wave part 1: KNOWN_CONFIG_KEYS rows for entity.names_references + entity.record_types + entity.row_page_status (one line), mcp.instructions_governing_rule and search.long_page_unit (re-summed at the 0.60.242.0 merge: master 1975 + 3); +1 wave 17 (#6667): cycle.consolidate.enabled KNOWN_CONFIG_KEYS row (read in cycle/phases/consolidate.ts); +2 Wave B PR 1: pages.segmented_storage and the segmented ceiling/retention keys (page-body/limits.ts); merge v0.60.249.0: Wave B PR 1 and master growth compose at 1981; +1 #6297: dream.patterns.min_interval_hours / child_read_budget_kb known keys; +1 #5012: loops.updates_require_reciprocity known key; +1 wave 18b lane 2 (#6495): search.keyword_timeout_negative_cache_seconds KNOWN_CONFIG_KEYS row; integrated at wave 18b: master 1981 + 4 (lanes 2, 3, 5 known keys); +1 #6948: sync.origin_twins.auto_resolve KNOWN_CONFIG_KEYS row (read in repair/origin-twins-heal.ts); +1 #6948 sweep C-9: facts.absorb_retry.max_resubmits KNOWN_CONFIG_KEYS row (read in facts/dead-absorb-retry.ts); +1 #6907: backup.remote_timeout_ms KNOWN_CONFIG_KEYS row (resolver in backup/repository.ts); +1 at the #6712 PR 4b merge onto master v0.60.310.0 (both sides added a key); +3 #7130: sync.max_deletes / sync.max_delete_ratio / purge.retention_hours KNOWN_CONFIG_KEYS rows and the two per-source cap prefixes (parsers live in core/sync-reconcile.ts); +2 GBRA-154: search.collapse / search.rank_priors KNOWN_CONFIG_KEYS rows (read in search/mode.ts); +1 GBRA-150: sync.metafile_pages KNOWN_CONFIG_KEYS row (read in core/sync.ts); +1 GBRA-159: visibility.honor_aliases KNOWN_CONFIG_KEYS row (read in search/private-visibility.ts); +4 GBRA-156 warm CLI socket: GBrainConfig.serve_cli_socket slot and the published-config.ts import/re-export (snapshot-only merge and MERGED_CONFIG_BY_ENGINE live in core/published-config.ts); re-summed at the GBRA-159 hotfix merge (2000 measured); +2 #7242 GBrainConfig.minions.terminal_hook (interface field); #7252 merge of master v0.60.343.0: both sides grew the file, re-summed (2002 measured); +1 GBRA-155: entity.name_variants KNOWN_CONFIG_KEYS row (read in verbs/entity-variants.ts); +2 GBRA-161: the generations.* KNOWN_CONFIG_KEYS rows and their comment (bounds and reader in generations/config.ts); +1 GBRA-156: search.evidence_tail_trim KNOWN_CONFIG_KEYS row (read in search/evidence-tail-trim.ts); +2 GBRA-175: self_upgrade.channel (the GBrainConfig field and its KNOWN_CONFIG_KEYS row; resolved in core/self-upgrade.ts); re-summed at the master 440eeef6 merge (2009 measured); +2 GBRA-156 vector prewarm: GBrainConfig.serve_vector_prewarm slot (snapshot merge lives in core/published-config.ts); +1 GBRA-95 G7a: storage.git_lfs KNOWN_CONFIG_KEYS row (read in persistence/git-declared.ts); re-summed at the v0.60.449.0 merge (2012 measured); +2 GBRA-205: search.evidence_titles / query_budget_unit / query_facts_block / fact_source_pages KNOWN_CONFIG_KEYS rows (read in search/evidence-date.ts, evidence-packing.ts, facts-arm.ts); +1 GBRA-156: search.remote_page_cap KNOWN_CONFIG_KEYS row (read in search/remote-page-cap.ts); re-summed at the memory train #8481 merge with v0.60.576.0 (2021 measured); +3 #8776: self_upgrade.autopilot_launcher (GBrainConfig field with its doc line, and the KNOWN_CONFIG_KEYS row; parsed in core/self-upgrade.ts)src/core/persistence/sync-run.ts 1697 ratchet new row: crossed the 1500 unlisted cap in #6643 (knock-on re-freeze, checkpoint revival, root cause and the truthful --retry-failed wait all drive the private cursor/gate machinery: holdUnderGate, freezeEntry, saveCursor); classification lives in sync-knock-on.ts, the checkpoint clause in checkpoint-validation.ts; peel the settle path (settleFailedRequest and its recoveries) into a sibling module next; +3 #6722: committed pages' size_state tallied into the cursor and the sync receipt size_states (logic in page-embedding-budget.ts addSizeState); merge v0.60.240.0: large pages and master growth compose at 1687; +2 #6694: the slug-mode checkpoint revival import and its doc line (predicate lives in persistence/sync-slug-mode.ts); +11 #6712 PR 3 (L7): a plain sync retries the recorded failure --retry-failed used to (retryRecordedFailure; the unchanged-refusal replay lives in persistence/sync-stop-class.ts replaysUnchangedRefusal), the moved-checkpoint and company content-refusal exceptions; #6712 PR 3 integration: lanes L7 (retryRecordedFailure, +19) and L8 (#6727 legacy-slug refusal line, #6735 timeout revival, +6) compose at 1762; +2 wave 18a integration: #6729 (lane 2, written against the 1745 ceiling) records identity downgrades in performManagedPass through noteIdentityDowngrades (logic in core/sync-identity-downgrades.ts), composed with master 1762; +14 Wave B PR 2: freezeEntry freezes a Markdown file over the read bound by reference (body_ref) and holdFailedFenceRequest holds a streamed refusal; both set freezeEntry/holdFailedFenceRequest locals (blob, oversize, rawHash) so they stay here, the hashing and preparation live in persistence/sync-streamed.ts and the hold in sync-screen.ts streamedRefusalHold; integrated at the master 4e29d0904 merge: master 1764 + Wave B PR 2 14 = 1778 measured; +4 #6948: freezeEntry holds an entry several live pages claim (hold in sync-screen.ts originConflictHold, verdict in persistence/origin-twins.ts); +1 #7167: managedDryRun reports the writer state (the import of persistence/sync-dry-run-writer.ts, where the read lives); +4 G3 git-canonical: freezeEntry reads a strict source's entry from its commit (pinnedBlob) and carries committedOnly to publication; both use freezeEntry locals (rule in persistence/sync-classify.ts); +1 #7886: the import of persistence/sync-receipt-wait.ts, where the managed sync receipt waits and their test seam live; +3 #7931: the freeze drift screen also accepts a file that holds the page as prepareFileTarget reads it (fileMatchesSnapshot import, comment, the split condition line); +5 GBRA-218: performManagedSync wraps every managed pass (sync, drain, sources refresh, git conversion, owner slice) in withCommittedPolicy (logic in access/policy-git.ts) and keeps the lease path in performLeasedPass; re-summed at the memory train #8481 merge with v0.60.576.0 (1696 measured); +1 convergence nightly fix: the sync:passed_over fault point after the pass-over cursor save (a kill seam sits where its cursor commits, so it cannot move)src/core/bootstrap/harness.ts 2630 ratchet +29 live-PGLite-serve lane: LIVE_SERVE refusal ahead of source resolution + unpinned --token hooks (CI e2e fix); +46 wave review: resolveHookSource dep (serve-parity resolver + federated grant), --source shape validation, loud SOURCE_UNRESOLVED instead of a silent 'default'; +10: #4574 parseCodexBlockBearer http_headers shape + legacy bearer_token fallback; +4 at megawave/wave-k merge; +codex hooks lane: step-7 codex hooks.json + config.toml trust pair, removeHarness arm; +234 ambient-writeback WP3: kind:'instructions' targets (plan/apply/converge-off/remove/status probes, OV-A4 override pre-check) — splice/render mechanics live in instructions-block.ts; +59 adversarial fix wave: registrar-mode block suppression, converge-failure receipt tracking, MCP-confirmed guard before block install; +26 round-3 fixes: codex-lane MCP-confirmed guard + smoke-rollback block strip; master: | merged v0.48.1.0 true-up; +41 #4897 resolveImplicitSource dep + defaultResolveImplicitSource: hooks/token/receipt bind to the serve's implicit default source when --source is omitted; +23 #4586 statusHarness live claude-code mcp verdict (URL mismatch or same-scope non-HTTP registration reads failed, receipt untouched); shared-skills integration on company-ingestion base; +18 #5671: logAmbientPostureNotes helper (registrar note moved out of applyHarness + pre-consent warning when an explicit private facts default meets the HTTP harness; text shared with doctor in facts/writeback-config.ts); +24 #5893: rotation grant carry wiring and its rotationCarry/withheldOperationsNote helpers (carry rules live in token-mint.ts carryLegacyGrant); +6 #5878: --refresh-skills flag and status epoch line (refresh logic lives in harness-skills.ts); +7 #4618 seat: HarnessFlags.seat field, --seat/--no-seat parse via hooks.ts parseSeatFlags, GBRAIN_SEAT in the hook env; -119 #6082: plugin-lane detectors moved to plugin-lanes.ts (re-exported); +18 #6092/#6171: hook ownership identity on write/remove/converge, permission ownership carry, --remove --dry-run and the --status hook census (logic in hooks.ts + harness-hooks.ts); +5 D8 Codex slice: the Codex SessionEnd capture hook obeys the recorded consent (wireCodexCapture: hooks on, capture accepted, never registrar mode) and is disclosed in the consent block; -31 #6743: cleanup gate moved to harness-cleanup.ts; +8 #6798: supersededEnrollments dep (interface field + default) and the --status epoch hint printed only for a superseded enrollment (the brain read lives in harness-skills.ts brainSupersededEnrollments); +13 brain-first block lane: --no-instructions flag field + parse, opencodeAgentsPath dep (field + default) and the step-10b / remove call sites (logic lives in harness-brain-first.ts); +7 GBRA-243 per-turn rule hook: consent-block interface field, step-10c call site, turn_hooks JSON field, exit code and the remove arm (writer, host list and consent text live in harness-brain-first.ts); +2 #8428: the harness lane Claude Code and Codex SessionEnd hooks start gbrain through the hook launcher; +16 GBRA-194 skills index lane: --skill-loading flag field + parse, step-10b and remove call sites, skills_index JSON field and exit-code wiring (logic lives in harness-skills-index.ts and setup/skills-block.ts)src/core/oauth-provider.ts 1237 ratchet new row: crossed the 1500 unlisted cap absorbing #3819 (DCR 400 invalid_client_metadata + scope filtering + custom-scheme redirect_uris + pseudo-scheme guard); merged v0.49: transactional grant enforcement shared with hosted grant policies; +1 #5222 resourceUrl option; +1 GST-1113 transactional token mintdiff --git a/scripts/promote-stable.ts b/scripts/promote-stable.tsindex 0baec549ce..89165c6b0f 100644--- a/scripts/promote-stable.ts+++ b/scripts/promote-stable.ts@@ -277,7 +277,7 @@ async function gitOut(deps: PromoteDeps, args: string[], refusal: string, input?return r.stdout.trim();}-async function refExists(deps: PromoteDeps, ref: string): Promise<boolean> {+export async function refExists(deps: PromoteDeps, ref: string): Promise<boolean> {return (await deps.git(['rev-parse', '--verify', '--quiet', ref])).code === 0;}diff --git a/scripts/stable-daily.ts b/scripts/stable-daily.tsindex b15dbe5664..29b83c1d91 100644--- a/scripts/stable-daily.ts+++ b/scripts/stable-daily.ts@@ -24,7 +24,10 @@* soak with every integrity gate (INTEGRITY_GATES) passing in every cell; on the* important-only path it must contain one of the important fixes. It is* promoted through scripts/promote-stable.ts promote(), so every promotion- * check (published release, exact tree, never older) still applies.+ * check (published release, exact tree, never older) still applies. A release+ * that was stable before (its stable-v<version> record tag exists: promoted,+ * then rolled back) or that stable.json lists as known_bad is never a+ * candidate or soaked (#8792).* 4. Nothing promotable yet: the newest release is soaked (one dispatch of the* soak on its tag) unless a soak is already running, or a soak on any newer* release did not qualify (a maintainer decides; past the weekly floor it@@ -37,7 +40,7 @@ import { appendFileSync, mkdtempSync, readdirSync, readFileSync, rmSync } from 'import { tmpdir } from 'node:os';import { join } from 'node:path';import {- authorize, compareVersions, currentStable, DOCS, onReleaseBranch, processDeps, promote, readPriorRecord, Refusal, requireSoakWorkflow, scheduleAuthorized, STABLE_REF,+ authorize, compareVersions, currentStable, DOCS, onReleaseBranch, processDeps, promote, readPriorRecord, refExists, Refusal, requireSoakWorkflow, scheduleAuthorized, STABLE_REF,type PromoteDeps, type Promotion,} from './promote-stable.ts';@@ -150,6 +153,8 @@ export async function daily(deps: DailyDeps): Promise<DailyResult> {if (!VERSION_RE.test(version) || compareVersions(version, current.version) <= 0) continue;const commit = await ok(deps, ['rev-parse', `refs/tags/${tag}^{commit}`]);if (!(await onReleaseBranch(deps, commit))) { deps.log(`[stable-daily] skipping ${tag}: ${commit} is not on master.`); continue; }+ if (published.knownBad.includes(version)) { deps.log(`[stable-daily] skipping ${tag}: stable.json lists it as known bad (withdrawn).`); continue; }+ if (await refExists(deps, `refs/tags/stable-v${version}`)) { deps.log(`[stable-daily] skipping ${tag}: stable-v${version} exists, so it was stable before and was rolled back; a maintainer re-promotes it by hand if it should return.`); continue; }releases.push({ version, commit });}releases.sort((a, b) => compareVersions(b.version, a.version));diff --git a/skills/gbrain-upgrade/SKILL.md b/skills/gbrain-upgrade/SKILL.mdindex 5438841684..0ca5f78956 100644--- a/skills/gbrain-upgrade/SKILL.md+++ b/skills/gbrain-upgrade/SKILL.md@@ -137,8 +137,9 @@ With the operator's go-ahead, upgrade in this order:lists the installs on PATH; a harness, cron wrapper or service may runanother by absolute path). It restarts serve, autopilot and the jobssupervisor onto the new build and verifies one build runs. A process it- cannot restart (one started by hand, a running `gbrain sync`, an MCP server- a harness started) refuses with `restart_refused` (exit 3) before anything+ cannot restart (one started by hand, an autopilot a cron entry or wrapper+ starts unless `self_upgrade.autopilot_launcher external` declares it, a+ running `gbrain sync`, an MCP server a harness started) refuses with `restart_refused` (exit 3) before anythinginstalls: relay the step it names; `--stop-mcp` only after the user agrees.5. Verify: `gbrain --version` per install, and`gbrain doctor --only runtime_build_skew,serve_build_drift --json` ok. On adiff --git a/skills/skills.lock.json b/skills/skills.lock.jsonindex 76abef9092..889a4da2ef 100644--- a/skills/skills.lock.json+++ b/skills/skills.lock.json@@ -88,7 +88,7 @@"functional-area-resolver/SKILL.md": "fe6e35fbb34dffec7af9ce4a6cc9c0b0eaa8345f97f33262a2abe0983431b421","functional-area-resolver/routing-eval.jsonl": "f80674d915acdfe229046737a5b171da834be15ac6524b5a3fd18048e9b37028","gbrain-advisor/SKILL.md": "976b3c5c3798f9fec764fa5bacd1567f751875bd837fe188a0c6df041805ed51",- "gbrain-upgrade/SKILL.md": "8f3082539194ffd6d7f4ad1fa85e4b993ed6d8731f8ea83a28558d852a009f93",+ "gbrain-upgrade/SKILL.md": "84532557d02350a3bf7113e823e36cf9ccc790fcf97c76b548c9149e99c3176b","google-loops/SKILL.md": "20955fac0a94bbe9298a8aa7416e851cac86eb145bc551ed0fc556d2f583fa5e","idea-ingest/SKILL.md": "863be3660ead12a45d3b86309d73df0ffda6c5db6ca69873cce1810680df79b4","idea-lineage/SKILL.md": "8cb36179dbf94abc17065613b8e773b1bb2b22670742aa77347b91ac885a05c5",diff --git a/src/commands/doctor/checks/local-runtime.ts b/src/commands/doctor/checks/local-runtime.tsindex e44914d7d5..0c14872fd3 100644--- a/src/commands/doctor/checks/local-runtime.ts+++ b/src/commands/doctor/checks/local-runtime.ts@@ -246,7 +246,10 @@ async function runMinionsMigration(ctx: DoctorContext): Promise<Check[]> {// the surface an operator actually runs on the host, never emitted it,// so a wedged auto-upgrade loop was invisible exactly where it would be// diagnosed. Sits beside the upgrade_errors trail it complements.- checks.push(checkSelfUpgradeHealth());+ // #8776: with the plan the next `gbrain upgrade` makes, so a restart it would+ // refuse (an autopilot started outside gbrain's service) shows before it fails.+ const restart = await import('../../upgrade-restart.ts').then((m) => m.upgradeRestartReadiness()).catch(() => null);+ checks.push(checkSelfUpgradeHealth(restart));checks.push(checkBunRuntime());return checks;}diff --git a/src/commands/doctor/checks/upgrade-health.ts b/src/commands/doctor/checks/upgrade-health.tsindex 89a3bdcb6f..e929a925d5 100644--- a/src/commands/doctor/checks/upgrade-health.ts+++ b/src/commands/doctor/checks/upgrade-health.ts@@ -14,6 +14,7 @@ import { MINIMUM_BUN_VERSION, SECURE_BUN_VERSION, bunVersionMeets, unsupportedBuimport { isNewerVersion, isValidVersionString } from '../../../core/semver.ts';import type { SelfUpgradeAction } from '../../../core/self-upgrade.ts';import type { SelfUpgradeAuditEvent } from '../../../core/audit/self-upgrade-audit.ts';+import { launcherName, type RestartPlan } from '../../../core/upgrade-restart.ts';import { VERSION as GBRAIN_BINARY_VERSION } from '../../../version.ts';import type { Check } from '../../doctor.ts';import { agentFix, doctorVerify } from '../check-fix.ts';@@ -73,8 +74,16 @@ function heldAutoUpgrade(recent: SelfUpgradeAuditEvent[], runningVersion: string* and any recent failed auto-upgrade attempts. File-plane only (no DB) so it* runs on thin clients. Warn on a held auto-upgrade or recent failures,* otherwise ok.+ *+ * #8776: `restart` is the plan the next `gbrain upgrade` makes before it installs+ * (commands/upgrade-restart.ts upgradeRestartReadiness), passed by the local+ * doctor only, so a remote report never carries host processes. A manual step in+ * it means that upgrade refuses: warn, naming each blocker (an autopilot started+ * outside gbrain's service, a process from another install). A hand-off to an+ * autopilot launcher and a second Bun global install the upgrade replaces are+ * named in the message.*/-export function checkSelfUpgradeHealth(): Check {+export function checkSelfUpgradeHealth(restart?: RestartPlan | null): Check {try {const { loadConfig } = require('../../../core/config.ts');const {@@ -106,6 +115,10 @@ export function checkSelfUpgradeHealth(): Check {}const parts: string[] = [`mode=${mode}`];if (resolution.source !== 'default') parts.push(`channel=${resolution.channel} (${resolution.source})`);+ for (const step of restart?.steps ?? []) {+ if (step.kind === 'handoff') parts.push(`upgrades restart autopilot pid ${step.pid} through ${launcherName(step.launcher)}`);+ if (step.kind === 'replace_copy') parts.push(`pid ${step.pids.join(', ')} run${step.pids.length === 1 ? 's' : ''} from a second install at ${step.root} (${step.from ? `v${step.from}` : 'version unknown'}), which upgrades replace too`);+ }// Shared stale/foreign-cache guard: only report an upgrade strictly newer// than the RUNNING binary (pendingUpgradeVersion owns the rule).const pendingLatest = pendingUpgradeVersion(GBRAIN_BINARY_VERSION, Date.now(), resolution.channel);@@ -150,6 +163,20 @@ export function checkSelfUpgradeHealth(): Check {}}+ if (restart?.manual.length) {+ const autopilot = restart.manual.find((m) => m.role === 'autopilot');+ return {+ name: 'self_upgrade_health',+ status: 'warn',+ message: `gbrain upgrade refuses on this host, so ${mode === 'auto' ? 'auto-upgrades' : 'upgrades'} cannot finish: ${restart.manual.map((m) => m.instruction).join(' ')} (${parts.join('; ')}).`,+ fix: autopilot+ ? agentFix(['gbrain', 'autopilot', '--install'], 'Runs autopilot under launchd, systemd or a gbrain cron line, which every upgrade restarts; the launcher that starts it now has to be retired first.', 'self_upgrade_health', {+ ask_user: true, docs: 'docs/guides/upgrades-auto-update.md#restart',+ user_message: `autopilot pid ${autopilot.pid} was started outside gbrain's autopilot service, so gbrain upgrade refuses on this host. May I run gbrain autopilot --install, which runs autopilot under launchd, systemd or a gbrain cron line so upgrades restart it, after you retire whatever starts it now? If that launcher starts autopilot again within 5 minutes of it exiting, gbrain config set self_upgrade.autopilot_launcher external keeps it and lets upgrades hand autopilot to it instead.`,+ })+ : agentFix(['gbrain', 'upgrade', '--restart-only', '--dry-run', '--json'], 'Read-only: lists every gbrain process on this host with the restart each one needs and the steps the upgrade cannot take.', 'self_upgrade_health', { docs: 'docs/guides/upgrades-auto-update.md#restart' }),+ };+ }// readRecent lists the current week before the previous one; order by ts.const recent = (readRecentSelfUpgrades(7) as SelfUpgradeAuditEvent[]).toSorted((a, b) => (a.ts < b.ts ? -1 : a.ts > b.ts ? 1 : 0));diff --git a/src/commands/upgrade-restart.ts b/src/commands/upgrade-restart.tsindex c617e4926c..51a028388f 100644--- a/src/commands/upgrade-restart.ts+++ b/src/commands/upgrade-restart.ts@@ -18,8 +18,8 @@ import type { Action } from '../core/agent-output.ts';import { writeCliError } from '../cli/cli-error.ts';import { setCliExitVerdict } from '../core/cli-force-exit.ts';import { SERVE_LAUNCHD_LABEL, SERVE_SYSTEMD_UNIT, serveServiceRestartArgv } from '../core/serve-service.ts';-import { resolveAutopilotJob } from '../core/autopilot-paths.ts';-import { plistPath, systemdUnitPath } from './autopilot/jobs.ts';+import { autopilotLockPath, resolveAutopilotJob } from '../core/autopilot-paths.ts';+import { cronLineBelongsToBrain, plistPath, systemdUnitPath } from './autopilot/jobs.ts';import { readSupervisorBuild, readSupervisorPid } from '../core/minions/supervisor-pid.ts';import { parseEtimeToMs, readWorkers } from '../core/minions/worker-registry.ts';import { installedVersion, runtimeInstallRoot } from '../core/runtime-build.ts';@@ -29,14 +29,16 @@ import { resolveQuietHoursWindow, resolveSelfUpgradeMode } from '../core/self-upimport { 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 RestartExecutor, type RestartPlan, type ServiceHandle, type WarmSocketState,+ classifyGbrainCommand, collectHostProcesses, copyFix, gbrainEntry, launcherName, mismatchedBuilds, PENDING_BUILD, planRestart, runRestartSteps, verifyRestart,+ type AutopilotLauncher, 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';const DRY_RUN_VERIFY = ['gbrain', 'upgrade', '--restart-only', '--dry-run', '--json'];const VERIFY_TIMEOUT_MS = 180_000;const VERIFY_POLL_MS = 2_000;+/** #8776: how long verification waits for a launcher to start autopilot again: gbrain's cron line runs every 5 minutes. */+const HANDOFF_WAIT_MS = 360_000;const brainHome = () => process.env.GBRAIN_HOME?.trim() || homedir();@@ -118,13 +120,41 @@ export function hostServices(platform: string = process.platform, home: string =};}-/** The real process sources; `close` releases the database connection the heartbeat read holds (Postgres only). */-async function hostSources(): Promise<{ sources: ProcessSources; notes: string[]; close: () => Promise<void>; pidFile: string }> {+function readCrontab(): string | null {+ if (process.platform === 'win32') return null;+ const r = spawnSync('crontab', ['-l'], { encoding: 'utf8', timeout: 10_000, stdio: ['ignore', 'pipe', 'ignore'] });+ return r.status === 0 && typeof r.stdout === 'string' ? r.stdout : null;+}++/**+ * #8776: what starts autopilot again when it exits, for an autopilot launchd or systemd does not run: this brain's own+ * gbrain cron line (`gbrain autopilot --install` on Linux without a user systemd bus), else a launcher the operator+ * declared with `self_upgrade.autopilot_launcher external`; null when neither, so the upgrade refuses as before.+ * `pid` is the daemon this brain's autopilot lock names, the only one the hand-off may stop.+ */+export function autopilotLauncher(crontab: () => string | null = readCrontab, declared: string | undefined = loadConfig()?.self_upgrade?.autopilot_launcher,+ lockPid: number | null = readAutopilotLockPid()): AutopilotLauncher | null {+ const job = resolveAutopilotJob();+ if (crontab()?.split('\n').some(line => cronLineBelongsToBrain(line, job))) return { kind: 'cron', wait_ms: HANDOFF_WAIT_MS, pid: lockPid };+ return declared === 'external' ? { kind: 'declared', wait_ms: HANDOFF_WAIT_MS, pid: lockPid } : null;+}++function readAutopilotLockPid(): number | null {+ try {+ const pid = Number(readFileSync(autopilotLockPath(), 'utf8').trim());+ return Number.isInteger(pid) && pid > 1 ? pid : null;+ } catch {+ return null;+ }+}++/** The real process sources; `close` releases the database connection the heartbeat read holds (Postgres only, and only with `heartbeats`). */+async function hostSources(withHeartbeats = true): Promise<{ sources: ProcessSources; notes: string[]; close: () => Promise<void>; pidFile: string }> {const notes: string[] = [];let heartbeats: ProcessSources['heartbeats'] = async () => [];let close = async () => {};const config = loadConfig();- if (config?.engine === 'postgres' && !isThinClient(config)) {+ if (withHeartbeats && config?.engine === 'postgres' && !isThinClient(config)) {try {const { createEngine } = await import('../core/engine-factory.ts');const { listHostConsumers } = await import('../core/persistence/consumer-heartbeat.ts');@@ -171,11 +201,11 @@ function hostExecutor(pidFile: string): RestartExecutor {};}-/** 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' {+/** SIGTERM pid only while it is still the MCP server or autopilot the plan saw: same role, same start time (ps reports it to the second). */+function terminateIfUnchanged(pid: number, startedMs: number | null, role: 'mcp' | 'autopilot'): 'stopped' | 'gone' | 'changed' {const row = readProcessTable(undefined, [pid])?.find(r => r.pid === pid);if (!row) return 'gone';- if (classifyGbrainCommand(row.command, { cwd: row.cwd, packageName: packageNameAt }) !== 'mcp' || startedMs === null || row.started_ms === null || Math.abs(row.started_ms - startedMs) > 2_000) return 'changed';+ if (classifyGbrainCommand(row.command, { cwd: row.cwd, packageName: packageNameAt }) !== role || startedMs === null || row.started_ms === null || Math.abs(row.started_ms - startedMs) > 2_000) return 'changed';try { process.kill(pid, 'SIGTERM'); return 'stopped'; } catch { return 'gone'; }}@@ -187,6 +217,7 @@ function describeSteps(plan: RestartPlan): string[] {return plan.steps.map(step => step.kind === 'service' ? `${step.pids.map(name).join(', ')}: \`${step.argv.join(' ')}\``: step.kind === 'supervisor' ? `${[step.pid, ...step.workers].map(name).join(', ')}: \`${step.stop.join(' ')}\`, then \`${step.start.join(' ')}\``: step.kind === 'replace_copy' ? `${step.pids.map(name).join(', ')} run from the Bun global copy at ${step.root} (${step.from ? `v${step.from}` : 'version unknown'}): replace it with v${step.to} (BUN_INSTALL=${step.bun_install}: bun remove -g gbrain, then bun add -g the tag) before the restarts`+ : step.kind === 'handoff' ? `${name(step.pid)}: stop it (SIGTERM drains it); ${launcherName(step.launcher)} starts the installed build again (verified for up to ${Math.round(step.launcher.wait_ms / 60_000)} minutes)`: `${name(step.pid)}: stop it (reconnect gbrain in its harness afterwards)`);}@@ -255,7 +286,7 @@ export async function preflightHostRestart(opts: HostRestartOptions): Promise<boconst { sources, close } = await hostSources();try {const services = hostServices();- const plan = planRestart(await collectHostProcesses(sources), { expected: PENDING_BUILD, serveService: services.serve, autopilotService: services.autopilot, stopMcp: opts.stopMcp, ownInstallRoot: ownInstallRoot() });+ const plan = planRestart(await collectHostProcesses(sources), { expected: PENDING_BUILD, serveService: services.serve, autopilotService: services.autopilot, stopMcp: opts.stopMcp, ownInstallRoot: ownInstallRoot(), autopilotLauncher: autopilotLauncher() });const refusal = restartRefusal(plan, opts.rerunArgv, false);if (!refusal) return true;setCliExitVerdict(writeCliError(refusal, 'upgrade', { json: opts.json }));@@ -265,13 +296,25 @@ export async function preflightHostRestart(opts: HostRestartOptions): Promise<bo}}+/**+ * #8776, for doctor's `self_upgrade_health`: the plan the next `gbrain upgrade` makes before it installs (the preflight+ * plan), from the process table alone (no database connection). Read-only; null when ps cannot run.+ */+export async function upgradeRestartReadiness(): Promise<RestartPlan | null> {+ const { sources } = await hostSources(false);+ const processes = sources.processTable() === null ? null : await collectHostProcesses(sources);+ if (!processes) return null;+ const services = hostServices();+ return planRestart(processes, { expected: PENDING_BUILD, serveService: services.serve, autopilotService: services.autopilot, stopMcp: false, ownInstallRoot: ownInstallRoot(), autopilotLauncher: autopilotLauncher() });+}+/** `gbrain upgrade --restart-only [--stop-mcp] [--dry-run] [--json]`: restart every process onto the installed build and verify. */export async function runHostRestart(opts: HostRestartOptions & { dryRun: boolean }): Promise<void> {const { sources, notes, close, pidFile } = await hostSources();try {const services = hostServices();const before = await collectHostProcesses(sources);- const plan = planRestart(before, { expected: VERSION, serveService: services.serve, autopilotService: services.autopilot, stopMcp: opts.stopMcp, ownInstallRoot: ownInstallRoot() });+ const plan = planRestart(before, { expected: VERSION, serveService: services.serve, autopilotService: services.autopilot, stopMcp: opts.stopMcp, ownInstallRoot: ownInstallRoot(), autopilotLauncher: autopilotLauncher() });const { probeCliSocket } = await import('../core/cli-socket/probe.ts');const warmBefore = await probeCliSocket();const planDoc = { expected: VERSION, processes: before, steps: plan.steps, manual: plan.manual, warm_socket: warmBefore, notes };@@ -289,7 +332,7 @@ export async function runHostRestart(opts: HostRestartOptions & { dryRun: booleaconst verified = await verifyRestart(plan, startedMs, warmBefore, {collect: () => collectHostProcesses(sources), probeWarmSocket: () => probeCliSocket(),sleep: ms => new Promise(r => setTimeout(r, ms)), now: () => Date.now(),- }, { timeoutMs: plan.steps.length ? VERIFY_TIMEOUT_MS : 0, pollMs: VERIFY_POLL_MS });+ }, { timeoutMs: plan.steps.length ? Math.max(VERIFY_TIMEOUT_MS, ...plan.steps.map(step => step.kind === 'handoff' ? step.launcher.wait_ms : 0)) : 0, pollMs: VERIFY_POLL_MS });const doc = { status: verified.ok ? 'ok' : 'unverified', ...planDoc, results, verified: { processes: verified.processes, warm_socket: verified.warm_socket, problems: verified.problems, unverified: verified.unverified } };if (!verified.ok) {const failed = results.find(r => !r.ok);diff --git a/src/core/cli-flag-registry.generated.ts b/src/core/cli-flag-registry.generated.tsindex 05563cc8d3..bd88186151 100644--- a/src/core/cli-flag-registry.generated.ts+++ b/src/core/cli-flag-registry.generated.ts@@ -52,7 +52,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {'db-repair': ['--accept-pending', '--apply', '--apply-rewrites', '--as', '--background', '--brain', '--break-lock', '--db-url', '--dry-run', '--explain', '--filter', '--follow', '--force', '--force-retry', '--format', '--help', '--http', '--json', '--legacy-lock', '--locks', '--name', '--no-accept-pending', '--path', '--prefer-postgres', '--probe', '--progress-interval', '--progress-json', '--quiet', '--remediate', '--restart', '--skip-verify', '--source', '--statement-timeout', '--supabase', '--timeout', '--timings', '--undo-last-rewrite', '--url', '--version', '--wait', '--yes'],'decide': ['--accept-all', '--all', '--all-from', '--apply', '--brain', '--call-site', '--claims', '--dataset', '--dry-run', '--egress', '--embedding-dimensions', '--embedding-model', '--expect', '--from', '--help', '--include-withdrawals', '--input', '--items-out', '--json', '--kind', '--limit', '--max-cost', '--max-usd', '--min', '--non-interactive', '--out', '--provenance', '--provider', '--query', '--rate', '--reason', '--reason-family', '--recommended', '--remove', '--shadow', '--since', '--slot', '--source', '--status', '--suite', '--target', '--threshold', '--trust', '--undo', '--uri-prefix', '--version', '--what-if-threshold', '--yes'],'diag': ['--access', '--add', '--all', '--allowed-operations', '--apply', '--as', '--asof', '--body', '--bound-slug-prefixes', '--brain', '--budget-ms', '--client', '--count', '--cursor', '--date', '--dated-since', '--days', '--detach', '--entities', '--expect', '--expected-revision', '--federated-read', '--follow', '--format', '--from-index', '--full', '--fuzzy', '--group-by', '--held', '--help', '--http', '--id', '--include', '--include-ambiguous', '--include-deleted', '--json', '--kind', '--limit', '--max-usd', '--model', '--multimodal', '--no-autopilot-install', '--no-pull', '--no-walk', '--of', '--only', '--page', '--params', '--path', '--phase', '--prefer', '--preview', '--purge', '--query', '--recent', '--refresh-operations', '--replace', '--restart-only', '--reverse', '--row', '--scopes', '--session', '--side', '--since', '--slug', '--slugs', '--source', '--source-id', '--sources', '--stale', '--state', '--surface', '--to', '--updated-after', '--url', '--yes'],- 'doctor': ['--abandon', '--abbrev-ref', '--absolute-git-dir', '--accept-all', '--accept-capabilities', '--accept-pending', '--access', '--access-policy', '--account', '--acknowledge-managed', '--add', '--admin-intent', '--adopt', '--adopt-columns', '--adopt-permissions', '--advertise', '--after', '--aggressive', '--aliases', '--all', '--all-drifted', '--all-from', '--allow-old-serve', '--allow-outside-source-root', '--allow-shell-jobs', '--allow-unverified-remote', '--allowed-operations', '--applied', '--apply', '--apply-rewrites', '--approval-out', '--approved', '--as', '--assign-corpus', '--attest-actor', '--attest-ops', '--attest-sources', '--audit', '--auto', '--auto-additive', '--auto-fix', '--autostash', '--background', '--base', '--batch', '--batch-check', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--branch', '--break-lock', '--budget-ms', '--budget-policy', '--budget-tokens', '--budget-usd', '--by-mention', '--cached', '--cacheinfo', '--call-site', '--catch-up', '--channel', '--check', '--check-downgrade', '--check-only', '--cherry-mark', '--claims', '--class', '--clear', '--clear-never-installed', '--cli-socket', '--client', '--close', '--code', '--concurrency', '--confidence', '--confirm', '--confirm-quiesced', '--confirm-relocated-root', '--conflicts', '--contacts-dir', '--content-audit', '--content-root', '--continue', '--conversation', '--count', '--credentials-file', '--cursor', '--cwd', '--dataset', '--day', '--db-url', '--deadline', '--decisions', '--delegated-namespace', '--delegated-slug-prefixes', '--delete-brain', '--dest', '--detach', '--detail', '--diff-filter', '--dim', '--dimensions', '--dir', '--disable', '--drain', '--drain-timeout', '--dry-run', '--egress', '--embedding-dimensions', '--embedding-model', '--enable', '--enable-dcr', '--end-of-options', '--entity', '--env', '--error-unmatch', '--exclude', '--exclude-standard', '--exit-code', '--expand', '--expect', '--expect-local', '--expect-remote', '--expect-upstream', '--expected-epoch', '--expected-revision', '--expected-state', '--explain', '--facts', '--fast', '--federated', '--federated-read', '--fetch-timeout-ms', '--ff-only', '--file', '--first-parent', '--fix', '--follow', '--force', '--force-break-lock', '--force-rechunk', '--force-remove', '--force-retry', '--force-schema', '--force-with-lease', '--format', '--fresh', '--fresh-token', '--from', '--from-meetings', '--from-pages', '--full', '--full-tree', '--fuzzy', '--gbrain-bin', '--generation', '--get', '--get-all', '--get-url', '--git-common-dir', '--git-dir', '--git-path', '--grammar', '--group', '--group-by', '--hard', '--hard-deadline', '--harness', '--held', '--help', '--hold-state', '--holds', '--home', '--http', '--id', '--if-version', '--ignore-env-override', '--ignore-missing', '--images', '--include-ambiguous', '--include-cross-entity', '--include-deleted', '--include-failures', '--include-flagged', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--include-pseudo', '--include-repairs', '--include-withdrawals', '--index-audit', '--index-info', '--infer-dates', '--init', '--input', '--install', '--instructions', '--instructions-only', '--is-ancestor', '--is-bare-repository', '--is-inside-work-tree', '--is-shallow-repository', '--items-out', '--job-isolation', '--jq', '--json', '--keep', '--keep-checkout', '--key', '--kind', '--lanes', '--lang', '--left-right', '--legacy-lock', '--limit', '--link', '--link-source', '--link-type', '--list', '--list-out', '--literal-pathspecs', '--local', '--local-env-vars', '--locks', '--log-noop', '--manifest', '--markdown', '--max-cost', '--max-cost-usd', '--max-count', '--max-facts', '--max-jobs', '--max-requests', '--max-rss', '--max-runtime', '--max-usd', '--max-waiting', '--may-act-for', '--mcp-only', '--member', '--merge-base', '--migrate-legacy', '--migrate-only', '--migration', '--min', '--min-n', '--mode', '--model', '--multimodal', '--name', '--name-only', '--name-status', '--nice', '--no-accept-pending', '--no-autopilot-install', '--no-autostash', '--no-capture', '--no-commit-id', '--no-confirm', '--no-cron', '--no-delegate', '--no-edit', '--no-embed', '--no-embed-cache', '--no-embedding', '--no-expand', '--no-extract', '--no-federated', '--no-filters', '--no-gpg-sign', '--no-hooks', '--no-instructions', '--no-lanes', '--no-llm', '--no-merges', '--no-migrate', '--no-probe', '--no-pull', '--no-renames', '--no-repair', '--no-restart', '--no-schema-pack', '--no-seat', '--no-tags', '--no-verify', '--no-walk', '--no-write-fetch-head', '--non-interactive', '--not', '--now', '--of', '--older-than', '--once', '--only', '--operation', '--operations', '--others', '--out', '--output', '--oversized', '--overwrite', '--page', '--parallel', '--params', '--parents', '--parked-code', '--parked-pushes', '--pat-file', '--path', '--path-format', '--pending', '--pglite', '--phase', '--pid-file', '--plan', '--porcelain', '--port', '--prefer', '--prefer-postgres', '--prefix', '--preset', '--preview', '--principal', '--private-pages', '--probe', '--probe-pglite', '--profile', '--progress-interval', '--progress-json', '--project', '--provenance', '--provider', '--providers', '--prune-orphans', '--public-url', '--pull', '--pure', '--purge', '--push', '--push-only', '--qm', '--query', '--question', '--queue', '--quiet', '--rate', '--reader-mode', '--readers', '--reauth', '--rebase', '--rebuild', '--recommended', '--redact-paths', '--reference-date', '--refresh', '--refresh-operations', '--refresh-skills', '--regenerate', '--reissue', '--relative', '--relower', '--remediate', '--remediation-plan', '--remove', '--remove-core', '--repair', '--repair-unknown-markers', '--replace', '--repo', '--request', '--request-id', '--require-clean', '--reranker', '--reset', '--reset-checkpoint', '--reset-default', '--resolve', '--restart-only', '--restore-only', '--resume', '--retire', '--retry-failed', '--retry-global', '--retry-held', '--retry-parked', '--reverse', '--review-lower', '--revision', '--right-only', '--rollback-to-source', '--root', '--rules', '--run', '--runtime', '--sample', '--save', '--scope', '--scopes', '--search-mode', '--seat', '--section', '--segmented', '--select', '--self-transfer', '--semantic', '--session', '--session-id', '--set', '--set-upstream-to', '--shadow', '--shared-skills', '--short', '--show-current', '--show-object-format', '--show-prefix', '--show-token', '--show-toplevel', '--side', '--since', '--since-last-run', '--skill-loading', '--skills-dir', '--skills-index-only', '--skip', '--skip-bare-tweet', '--skip-failed', '--skip-urls', '--skip-verify', '--slot', '--slot-a-model', '--slot-b-model', '--slot-c-model', '--slug', '--slugs', '--source', '--source-id', '--source-ids', '--sources', '--src-subpath', '--staged', '--stale', '--stat', '--state', '--statement-timeout', '--status', '--stdin', '--stop-mcp', '--strategy', '--strict', '--suite', '--supabase', '--surface', '--swap-only', '--symbol-kind', '--symbolic-full-name', '--takes-holders', '--target', '--target-score', '--threshold', '--tier', '--timeout', '--timings', '--to', '--token', '--token-ttl', '--top-k', '--topo-order', '--trust', '--type', '--types', '--unindexed', '--uninstall', '--unsafe-bypass-dream-guard', '--unset', '--unset-all', '--unsettle', '--unshallow', '--untracked-files', '--url', '--url-env', '--user', '--vacuum', '--vectors', '--verbose', '--verify', '--version', '--wait', '--wait-drain', '--warn-only', '--watch', '--what-if-threshold', '--window', '--workers', '--working-tree', '--workspace', '--worktree', '--write-tree', '--yes'],+ 'doctor': ['--abandon', '--abbrev-ref', '--absolute-git-dir', '--accept-all', '--accept-capabilities', '--accept-pending', '--access', '--access-policy', '--account', '--acknowledge-managed', '--add', '--admin-intent', '--adopt', '--adopt-columns', '--adopt-permissions', '--advertise', '--after', '--aggressive', '--aliases', '--all', '--all-drifted', '--all-from', '--allow-old-serve', '--allow-outside-source-root', '--allow-shell-jobs', '--allow-unverified-remote', '--allowed-operations', '--applied', '--apply', '--apply-rewrites', '--approval-out', '--approved', '--as', '--assign-corpus', '--attest-actor', '--attest-ops', '--attest-sources', '--audit', '--auto', '--auto-additive', '--auto-fix', '--autostash', '--background', '--base', '--batch', '--batch-check', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--branch', '--break-lock', '--budget-ms', '--budget-policy', '--budget-tokens', '--budget-usd', '--by-mention', '--cached', '--cacheinfo', '--call-site', '--catch-up', '--channel', '--check', '--check-downgrade', '--check-only', '--cherry-mark', '--claims', '--class', '--clear', '--clear-never-installed', '--cli-socket', '--client', '--close', '--code', '--concurrency', '--confidence', '--config', '--confirm', '--confirm-quiesced', '--confirm-relocated-root', '--conflicts', '--contacts-dir', '--content-audit', '--content-root', '--continue', '--conversation', '--count', '--credentials-file', '--cursor', '--cwd', '--dataset', '--day', '--db-url', '--deadline', '--decisions', '--delegated-namespace', '--delegated-slug-prefixes', '--delete-brain', '--dest', '--detach', '--detail', '--diff-filter', '--dim', '--dimensions', '--dir', '--disable', '--drain', '--drain-timeout', '--dry-run', '--egress', '--embedding-dimensions', '--embedding-model', '--enable', '--enable-dcr', '--end-of-options', '--entity', '--env', '--env-file', '--error-unmatch', '--exclude', '--exclude-standard', '--exit-code', '--expand', '--expect', '--expect-local', '--expect-remote', '--expect-upstream', '--expected-epoch', '--expected-revision', '--expected-state', '--explain', '--facts', '--fast', '--federated', '--federated-read', '--fetch-timeout-ms', '--ff-only', '--file', '--first-parent', '--fix', '--follow', '--force', '--force-break-lock', '--force-rechunk', '--force-remove', '--force-retry', '--force-schema', '--force-with-lease', '--format', '--fresh', '--fresh-token', '--from', '--from-meetings', '--from-pages', '--full', '--full-tree', '--fuzzy', '--gbrain-bin', '--generation', '--get', '--get-all', '--get-url', '--git-common-dir', '--git-dir', '--git-path', '--grammar', '--group', '--group-by', '--hard', '--hard-deadline', '--harness', '--held', '--help', '--hold-state', '--holds', '--home', '--http', '--id', '--if-version', '--ignore-env-override', '--ignore-missing', '--images', '--import', '--include-ambiguous', '--include-cross-entity', '--include-deleted', '--include-failures', '--include-flagged', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--include-pseudo', '--include-repairs', '--include-withdrawals', '--index-audit', '--index-info', '--infer-dates', '--init', '--input', '--install', '--instructions', '--instructions-only', '--is-ancestor', '--is-bare-repository', '--is-inside-work-tree', '--is-shallow-repository', '--items-out', '--job-isolation', '--jq', '--json', '--keep', '--keep-checkout', '--key', '--kind', '--lanes', '--lang', '--left-right', '--legacy-lock', '--limit', '--link', '--link-source', '--link-type', '--list', '--list-out', '--literal-pathspecs', '--local', '--local-env-vars', '--locks', '--log-noop', '--manifest', '--markdown', '--max-cost', '--max-cost-usd', '--max-count', '--max-facts', '--max-jobs', '--max-requests', '--max-rss', '--max-runtime', '--max-usd', '--max-waiting', '--may-act-for', '--mcp-only', '--member', '--merge-base', '--migrate-legacy', '--migrate-only', '--migration', '--min', '--min-n', '--mode', '--model', '--multimodal', '--name', '--name-only', '--name-status', '--nice', '--no-accept-pending', '--no-autopilot-install', '--no-autostash', '--no-capture', '--no-commit-id', '--no-confirm', '--no-cron', '--no-delegate', '--no-edit', '--no-embed', '--no-embed-cache', '--no-embedding', '--no-expand', '--no-extract', '--no-federated', '--no-filters', '--no-gpg-sign', '--no-hooks', '--no-instructions', '--no-lanes', '--no-llm', '--no-merges', '--no-migrate', '--no-probe', '--no-pull', '--no-renames', '--no-repair', '--no-restart', '--no-schema-pack', '--no-seat', '--no-tags', '--no-verify', '--no-walk', '--no-write-fetch-head', '--non-interactive', '--not', '--now', '--of', '--older-than', '--once', '--only', '--operation', '--operations', '--others', '--out', '--output', '--oversized', '--overwrite', '--page', '--parallel', '--params', '--parents', '--parked-code', '--parked-pushes', '--pat-file', '--path', '--path-format', '--pending', '--pglite', '--phase', '--pid-file', '--plan', '--porcelain', '--port', '--prefer', '--prefer-postgres', '--prefix', '--preload', '--preset', '--preview', '--principal', '--private-pages', '--probe', '--probe-pglite', '--profile', '--progress-interval', '--progress-json', '--project', '--provenance', '--provider', '--providers', '--prune-orphans', '--public-url', '--pull', '--pure', '--purge', '--push', '--push-only', '--qm', '--query', '--question', '--queue', '--quiet', '--rate', '--reader-mode', '--readers', '--reauth', '--rebase', '--rebuild', '--recommended', '--redact-paths', '--reference-date', '--refresh', '--refresh-operations', '--refresh-skills', '--regenerate', '--reissue', '--relative', '--relower', '--remediate', '--remediation-plan', '--remove', '--remove-core', '--repair', '--repair-unknown-markers', '--replace', '--repo', '--request', '--request-id', '--require', '--require-clean', '--reranker', '--reset', '--reset-checkpoint', '--reset-default', '--resolve', '--restart-only', '--restore-only', '--resume', '--retire', '--retry-failed', '--retry-global', '--retry-held', '--retry-parked', '--reverse', '--review-lower', '--revision', '--right-only', '--rollback-to-source', '--root', '--rules', '--run', '--runtime', '--sample', '--save', '--scope', '--scopes', '--search-mode', '--seat', '--section', '--segmented', '--select', '--self-transfer', '--semantic', '--session', '--session-id', '--set', '--set-upstream-to', '--shadow', '--shared-skills', '--short', '--show-current', '--show-object-format', '--show-prefix', '--show-token', '--show-toplevel', '--side', '--since', '--since-last-run', '--skill-loading', '--skills-dir', '--skills-index-only', '--skip', '--skip-bare-tweet', '--skip-failed', '--skip-urls', '--skip-verify', '--slot', '--slot-a-model', '--slot-b-model', '--slot-c-model', '--slug', '--slugs', '--source', '--source-id', '--source-ids', '--sources', '--src-subpath', '--staged', '--stale', '--stat', '--state', '--statement-timeout', '--status', '--stdin', '--stop-mcp', '--strategy', '--strict', '--suite', '--supabase', '--surface', '--swap-only', '--symbol-kind', '--symbolic-full-name', '--tags', '--takes-holders', '--target', '--target-score', '--threshold', '--tier', '--timeout', '--timings', '--to', '--token', '--token-ttl', '--top-k', '--topo-order', '--trust', '--tsconfig-override', '--type', '--types', '--unindexed', '--uninstall', '--unsafe-bypass-dream-guard', '--unset', '--unset-all', '--unsettle', '--unshallow', '--untracked-files', '--url', '--url-env', '--user', '--vacuum', '--vectors', '--verbose', '--verify', '--version', '--wait', '--wait-drain', '--warn-only', '--watch', '--what-if-threshold', '--window', '--workers', '--working-tree', '--workspace', '--worktree', '--write-tree', '--yes'],'dream': ['--audit-rejects', '--brain', '--cancel-unmatched', '--date', '--dir', '--drain', '--dry-run', '--eval-run', '--force', '--from', '--help', '--input', '--install', '--json', '--limit', '--list', '--max-usd', '--once', '--phase', '--probe', '--pull', '--reconcile-queue', '--since', '--source', '--source-id', '--threshold', '--to', '--unsafe-bypass-dream-guard', '--window', '--yes'],'edge-proposals': ['--access', '--add', '--all', '--all-applied', '--all-held', '--allowed-operations', '--as', '--asof', '--body', '--bound-slug-prefixes', '--brain', '--client', '--cursor', '--date', '--dated-since', '--days', '--entities', '--federated-read', '--follow', '--from-index', '--full', '--fuzzy', '--group-by', '--help', '--http', '--id', '--include', '--include-deleted', '--json', '--kind', '--limit', '--max-usd', '--model', '--multimodal', '--no-autopilot-install', '--of', '--only', '--page', '--params', '--path', '--phase', '--prefer', '--purge', '--recent', '--refresh-operations', '--row', '--scopes', '--session', '--since', '--slugs', '--source', '--sources', '--stale', '--status', '--surface', '--to', '--updated-after', '--url', '--yes'],'edges-backfill': ['--all-sources', '--brain', '--concurrency', '--help', '--json', '--max-chunks', '--source', '--workers'],diff --git a/src/core/config.ts b/src/core/config.tsindex aeeea74b96..f307652fdb 100644--- a/src/core/config.ts+++ b/src/core/config.ts@@ -296,6 +296,8 @@ export interface GBrainConfig {/** Epoch ms of the last auto-channel check (24h throttle). */last_check_ts?: number;last_applied_version?: string;+ /** #8776: a launcher outside gbrain's service starts autopilot again when it exits (`gbrain upgrade` hands it over). */+ autopilot_launcher?: 'external';};/**@@ -1679,6 +1681,7 @@ export const KNOWN_CONFIG_KEYS: readonly string[] = ['self_upgrade.attempting_version','self_upgrade.last_check_ts','self_upgrade.last_applied_version',+ 'self_upgrade.autopilot_launcher',// Misc'artifacts_sync_mode','cross_project_learnings',diff --git a/src/core/error-registry.ts b/src/core/error-registry.tsindex f864d6eca5..9d5b4c5477 100644--- a/src/core/error-registry.ts+++ b/src/core/error-registry.ts@@ -685,7 +685,7 @@ export const CODES = {request_too_large: { class: 'caller', summary: "The request exceeds a configured capacity; narrow it." },requirements_changed: { class: 'caller', summary: "The runtime requirements exceed the owner-approved publication policy." },requires_local_engine: { class: 'host_only', summary: "This command needs the brain's local database, and this install is a thin client of a remote brain." },- restart_refused: { class: 'consent', exit: 3, actor: 'user', summary: "`gbrain upgrade` (or `--restart-only`) found a gbrain process on this host it cannot restart onto the new build (a serve or worker started by hand, an autopilot without its service, a running sync, or an MCP server an agent harness started), so it restarted nothing and, before a swap, installed nothing.", why: "A process keeps the build it started with, so restarting only some of them leaves serve, workers and MCP servers on different builds; the upgrade refuses instead of leaving that skew. Each process is named with the exact step that restarts it.", docs: 'docs/guides/upgrades-auto-update.md#restart', suggestion: 'Handle each listed process as the message says (MCP servers only: rerun with --stop-mcp after the user agrees), then run the same command again; `gbrain upgrade --no-restart` installs without restarting.', fix: { argv: ['gbrain', 'upgrade', '--restart-only', '--dry-run', '--json'], consent: [], actor: 'agent', why: 'Read-only: lists every gbrain process on this host with its build and how each one restarts.', requires_exclusive: false } },+ restart_refused: { class: 'consent', exit: 3, actor: 'user', summary: "`gbrain upgrade` (or `--restart-only`) found a gbrain process on this host it cannot restart onto the new build (a serve or worker started by hand, an autopilot started outside its service by a launcher gbrain does not know, a running sync, or an MCP server an agent harness started), so it restarted nothing and, before a swap, installed nothing.", why: "A process keeps the build it started with, so restarting only some of them leaves serve, workers and MCP servers on different builds; the upgrade refuses instead of leaving that skew. Each process is named with the exact step that restarts it.", docs: 'docs/guides/upgrades-auto-update.md#restart', suggestion: 'Handle each listed process as the message says (MCP servers only: rerun with --stop-mcp after the user agrees), then run the same command again; `gbrain upgrade --no-restart` installs without restarting.', fix: { argv: ['gbrain', 'upgrade', '--restart-only', '--dry-run', '--json'], consent: [], actor: 'agent', why: 'Read-only: lists every gbrain process on this host with its build and how each one restarts.', requires_exclusive: false } },restart_unverified: { class: 'host_only', summary: "After `gbrain upgrade` restarted this host's gbrain processes, one of them still runs another build, did not come back, or the warm CLI socket refused the new build.", why: "The restart is done only when every gbrain process on the host reports the installed build and serve's warm CLI socket accepts it; anything less is the version skew the restart exists to remove.", docs: 'docs/guides/upgrades-auto-update.md#restart', suggestion: 'Restart each process the message lists with the command the plan printed, then run `gbrain upgrade --restart-only` again.', fix: { argv: ['gbrain', 'upgrade', '--restart-only', '--dry-run', '--json'], consent: [], actor: 'agent', why: 'Read-only: lists every gbrain process on this host with its build and how each one restarts.', requires_exclusive: false, verify: { argv: ['gbrain', 'doctor', '--only', 'runtime_build_skew', '--json'] } } },reset_upstream_refused: { class: 'caller', summary: "gbrain sources reset-upstream changed nothing: the checkout moved since the reset was proposed, has no upstream, has uncommitted tracked edits, or has local commits that were never on the upstream (named, with the backup ref a reset would create).", why: "The reset is bound to the HEAD and upstream the user agreed to and drops only commits the upstream once had; anything else needs the user's decision first.", reasons: ['expect_mismatch', 'no_upstream', 'dirty_tree', 'local_commits'], reason_overrides: { dirty_tree: { class: 'consent' }, local_commits: { class: 'consent' } }, docs: 'docs/guides/troubleshooting.md#upstream-rewritten' },response_too_large: { class: 'caller', summary: "Persistence response exceeds the local transport limit." },diff --git a/src/core/self-upgrade.ts b/src/core/self-upgrade.tsindex e18d44624f..c7c3c2e54a 100644--- a/src/core/self-upgrade.ts+++ b/src/core/self-upgrade.ts@@ -694,6 +694,8 @@ export interface SelfUpgradeState {attempting_version?: string;last_check_ts?: number;last_applied_version?: string;+ /** #8776: `external` declares that a launcher outside gbrain's service starts autopilot again when it exits, so upgrades hand it over instead of refusing. */+ autopilot_launcher?: 'external';}export type BreadcrumbTransition = 'applied' | 'failed' | null;@@ -814,6 +816,7 @@ export const SELF_UPGRADE_CONFIG_LEAVES = ['attempting_version','last_check_ts','last_applied_version',+ 'autopilot_launcher',] as const satisfies readonly (keyof SelfUpgradeState)[];export type SelfUpgradeConfigLeaf = (typeof SELF_UPGRADE_CONFIG_LEAVES)[number];@@ -918,6 +921,8 @@ export function parseSelfUpgradeConfigValue(leaf: SelfUpgradeConfigLeaf, raw: stif (['false', '0', 'no', 'off'].includes(raw.trim().toLowerCase())) return { ok: true, value: false };return { ok: false, error: `must be true or false (got '${raw}')` };}+ case 'autopilot_launcher':+ return raw.trim() === 'external' ? { ok: true, value: 'external' } : { ok: false, error: `must be external (got '${raw}'); unset it to refuse upgrades while autopilot runs outside gbrain's service` };case 'quiet_hours':return parseQuietHours(raw);case 'failed_versions':diff --git a/src/core/upgrade-restart.ts b/src/core/upgrade-restart.tsindex a674d1ef88..959b1341cc 100644--- a/src/core/upgrade-restart.ts+++ b/src/core/upgrade-restart.ts@@ -203,8 +203,23 @@ export interface RestartContext {stopMcp: boolean;/** The package directory of the install this upgrade replaces (realpath); null when unknown (a compiled binary). */ownInstallRoot?: string | null;+ /** What starts autopilot again when it exits, for an autopilot no installed service runs; null when nothing is known to. */+ autopilotLauncher?: AutopilotLauncher | null;}+/**+ * #8776: a launcher outside launchd and systemd that starts autopilot again when it exits: this brain's own+ * gbrain cron line (the linux-cron install target), or a launcher the operator declared with+ * `self_upgrade.autopilot_launcher external` (a cron entry or wrapper of their own). The restart hands autopilot to+ * it: stop the daemon, then wait `wait_ms` for the launcher to start the installed build. Only the daemon this+ * brain's autopilot lock names (`pid`) is handed over, so another brain's autopilot is never signalled on a host+ * whose process environments cannot be read (macOS).+ */+export interface AutopilotLauncher { kind: 'cron' | 'declared'; wait_ms: number; pid: number | null }++export const launcherName = (launcher: AutopilotLauncher) => launcher.kind === 'cron'+ ? 'this brain\'s gbrain cron line' : 'the launcher self_upgrade.autopilot_launcher declares';+/** Before the swap the installed build is not known yet: every process is stale. */export const PENDING_BUILD = 'pending';@@ -232,6 +247,7 @@ export type RestartStep =| { kind: 'service'; role: 'serve' | 'autopilot'; argv: string[]; pids: number[] }| { kind: 'supervisor'; pid: number; workers: number[]; stop: string[]; start: string[]; pid_file: string | null }| { kind: 'stop'; role: 'mcp'; pid: number; started_ms: number | null }+ | { kind: 'handoff'; role: 'autopilot'; pid: number; started_ms: number | null; launcher: AutopilotLauncher }| { kind: 'replace_copy'; root: string; bun_install: string; from: string | null; to: string; pids: number[] };export interface ManualStep { role: ProcessRole; pid: number; version: string | null; argv: string[]; instruction: string }@@ -274,6 +290,9 @@ export function planRestart(processes: readonly HostProcess[], ctx: RestartConteconst stops: RestartStep[] = [];const byPid = new Map(processes.map(p => [p.pid, p]));const addService = (role: 'serve' | 'autopilot', pid: number) => services.set(role, [...(services.get(role) ?? []), pid]);+ const handoffs = new Map<number, Extract<RestartStep, { kind: 'handoff' }>>();+ const launcherOf = (p: HostProcess) => (ctx.autopilotLauncher?.pid === p.pid ? ctx.autopilotLauncher : null);+ const addHandoff = (p: HostProcess, launcher: AutopilotLauncher) => handoffs.set(p.pid, { kind: 'handoff', role: 'autopilot', pid: p.pid, started_ms: p.started_ms, launcher });const runsUnder = (p: HostProcess, service: ServiceHandle | null) => !!service && service.pid !== null && (p.pid === service.pid || !!p.ancestors?.includes(service.pid));const kill = (p: HostProcess, instruction: string) => manual.push({ role: p.role, pid: p.pid, version: p.version, argv: ['kill', String(p.pid)], instruction });@@ -299,7 +318,11 @@ export function planRestart(processes: readonly HostProcess[], ctx: RestartContebreak;case 'autopilot':if (runsUnder(p, ctx.autopilotService)) addService('autopilot', p.pid);- else kill(p, `${label(p)} does not run under an installed autopilot service: stop it (\`kill ${p.pid}\`) and start it again the way it was launched (\`gbrain autopilot --install\` installs the service).`);+ else if (launcherOf(p)) addHandoff(p, launcherOf(p)!);+ else manual.push({ role: p.role, pid: p.pid, version: p.version, argv: ['gbrain', 'autopilot', '--install'],+ instruction: `${label(p)} was started outside gbrain's autopilot service (by a cron entry, a wrapper or by hand), so the upgrade cannot restart it. `+ + 'Either run `gbrain autopilot --install`, which runs autopilot under launchd, systemd or a gbrain cron line so every upgrade restarts it (retire the launcher that starts it now first, or both race for the autopilot lock), '+ + `or, when that launcher starts autopilot again within 5 minutes of it exiting, \`gbrain config set self_upgrade.autopilot_launcher external\` lets the upgrade stop it and wait for the launcher. By hand: \`kill ${p.pid}\` and start it again the way it was launched.` });break;case 'supervisor':if (p.args) supervisors.set(p.pid, supervisors.get(p.pid) ?? []);@@ -308,6 +331,7 @@ export function planRestart(processes: readonly HostProcess[], ctx: RestartContecase 'worker':if (parent?.role === 'supervisor' && parent.args) supervisors.set(parent.pid, [...(supervisors.get(parent.pid) ?? []), p.pid]);else if (parent?.role === 'autopilot' && runsUnder(parent, ctx.autopilotService)) addService('autopilot', parent.pid);+ else if (parent?.role === 'autopilot' && launcherOf(parent)) addHandoff(parent, launcherOf(parent)!);else kill(p, `${label(p)} is not run by a jobs supervisor this restart can relaunch${parent?.role === 'autopilot' ? ' (its autopilot runs under no installed service)' : ''}${p.unclassified_parent ? ` (its parent, pid ${p.unclassified_parent.pid} (\`${p.unclassified_parent.executable}\`), is not a process this restart recognises as gbrain)` : ''}: stop it (\`kill ${p.pid}\`, SIGTERM drains its jobs) and start \`gbrain jobs work\` again the way it was launched, or run workers under \`gbrain jobs supervisor start --detach\`.`);break;case 'mcp':@@ -327,14 +351,14 @@ export function planRestart(processes: readonly HostProcess[], ctx: RestartConteconst autopilot = services.get('autopilot');if (autopilot && ctx.autopilotService) steps.push({ kind: 'service', role: 'autopilot', argv: ctx.autopilotService.argv, pids: [...new Set(autopilot)] });for (const [pid, workers] of supervisors) steps.push({ kind: 'supervisor', pid, workers, ...supervisorRestartArgv(byPid.get(pid)!.args!) });- steps.push(...stops);+ steps.push(...handoffs.values(), ...stops);return { expected: ctx.expected, current, stale, steps, manual };}export interface RestartExecutor {run: (argv: string[], env?: Record<string, string>) => { status: number | null; output: string };- /** SIGTERM the MCP server at pid only if it is still the process the plan saw: 'changed' when the pid now names another process. */- terminate: (pid: number, startedMs: number | null) => 'stopped' | 'gone' | 'changed';+ /** SIGTERM the MCP server or autopilot at pid only if it is still the process the plan saw: 'changed' when the pid now names another process. */+ terminate: (pid: number, startedMs: number | null, role: 'mcp' | 'autopilot') => 'stopped' | 'gone' | 'changed';/** The live supervisor's pid now (read from its PID file, the default one when null), or null. */supervisorPid: (pidFile: string | null) => number | null;sleep: (ms: number) => Promise<void>;@@ -373,8 +397,13 @@ export async function runRestartSteps(plan: RestartPlan, exec: RestartExecutor):}const start = exec.run(step.start);results.push({ step, ok: start.status === 0, detail: start.status === 0 ? `stopped supervisor pid ${step.pid} and started it again with \`${step.start.join(' ')}\`` : failed(step.start, start) });+ } else if (step.kind === 'handoff') {+ const outcome = exec.terminate(step.pid, step.started_ms, 'autopilot');+ results.push({ step, ok: outcome !== 'changed', detail: outcome === 'changed'+ ? `pid ${step.pid} is no longer the autopilot the plan saw, so it was not signalled`+ : `stopped autopilot pid ${step.pid}; ${launcherName(step.launcher)} starts it again` });} else {- const outcome = exec.terminate(step.pid, step.started_ms);+ const outcome = exec.terminate(step.pid, step.started_ms, 'mcp');results.push({ step, ok: outcome !== 'changed', detail: outcome === 'changed'? `pid ${step.pid} is no longer the MCP server the plan saw, so it was not signalled`: `stopped mcp pid ${step.pid}; reconnect gbrain in its harness` });@@ -391,7 +420,7 @@ function refusesThisBuild(warm: WarmSocketState): boolean {return warm.state === 'refused' && !(warm.reason === 'identity_mismatch' && warm.mismatch && warm.mismatch !== 'version');}-const restartedPids = (plan: RestartPlan) => new Set(plan.steps.flatMap(step => step.kind === 'service' ? step.pids : step.kind === 'supervisor' ? [step.pid, ...step.workers] : step.kind === 'stop' ? [step.pid] : []));+const restartedPids = (plan: RestartPlan) => new Set(plan.steps.flatMap(step => step.kind === 'service' ? step.pids : step.kind === 'supervisor' ? [step.pid, ...step.workers] : step.kind === 'stop' || step.kind === 'handoff' ? [step.pid] : []));/** Processes that came back on a build other than the target, with the install each one runs from. */export function mismatchedBuilds(plan: RestartPlan, processes: readonly HostProcess[]): HostProcess[] {@@ -419,9 +448,9 @@ export function restartProblems(plan: RestartPlan, processes: readonly HostProce}for (const step of plan.steps) {if (step.kind === 'stop' || step.kind === 'replace_copy') continue;- const role = step.kind === 'service' ? step.role : 'supervisor';+ const role = step.kind === 'supervisor' ? 'supervisor' : step.role;if (!fresh.some(p => p.role === role)) {- problems.push(`${role} did not come back after ${step.kind === 'service' ? `\`${step.argv.join(' ')}\`` : 'the supervisor restart'}.`);+ problems.push(`${role} did not come back after ${step.kind === 'service' ? `\`${step.argv.join(' ')}\`` : step.kind === 'handoff' ? `it was stopped for ${launcherName(step.launcher)} to start again` : 'the supervisor restart'}.`);} else if (step.kind === 'supervisor' && step.workers.length && !fresh.some(p => p.role === 'worker' && live.get(p.ppid ?? -1)?.role === 'supervisor' && !restarted.has(p.ppid!))) {problems.push(`the jobs worker did not come back under the restarted supervisor (\`${step.start.join(' ')}\`).`);}diff --git a/test/config-file-plane-keys.test.ts b/test/config-file-plane-keys.test.tsindex 1c447425f2..5548aa34e7 100644--- a/test/config-file-plane-keys.test.ts+++ b/test/config-file-plane-keys.test.ts@@ -427,6 +427,7 @@ describe('config set — self_upgrade.* keys are FILE-plane canonical (#5489)',{ leaf: 'failed_versions', raw: '0.57.1, v0.57.1.0', stored: ['0.57.1.0'] },{ leaf: 'last_check_ts', raw: '1790000000000', stored: 1790000000000 },{ leaf: 'last_applied_version', raw: '0.57.1.0', stored: '0.57.1.0' },+ { leaf: 'autopilot_launcher', raw: 'external', stored: 'external' },];test('the cases cover every registered self_upgrade.* key', async () => {diff --git a/test/scripts/stable-daily.test.ts b/test/scripts/stable-daily.test.tsindex 8dcbb1afb6..6c6c30ce9d 100644--- a/test/scripts/stable-daily.test.ts+++ b/test/scripts/stable-daily.test.ts@@ -349,6 +349,23 @@ describe('daily: weekly floor', () => {expect(w.pushes).toEqual([]);});+ test('a release that was stable and rolled back is skipped: the newest release gets the soak instead of a refused promotion every run (#8792)', async () => {+ const handPromoted = { version: '1.0.2', commit: 2, message: stableMessage('1.0.2', '2026-11-02T05:17:00Z') };+ const w = world(base({ stable: handPromoted, runs: [soak(9, 3)] }));+ w.tags['stable-v1.0.3'] = { commit: 3, object: 'tagobj-record-1.0.3' };+ expect(await daily(w.deps)).toMatchObject({ action: 'soak_dispatched', version: '1.0.4' });+ expect(w.pushes).toEqual([]);+ expect(w.logs.some(l => l.includes('skipping v1.0.3: stable-v1.0.3 exists'))).toBe(true);+ });++ test('a release stable.json lists as known_bad is never a candidate; an older qualifying release still promotes (#8792)', async () => {+ const published = JSON.stringify({ schema: 1, version: '1.0.1', commit: sha(1), known_bad: ['1.0.3'] });+ const w = world(base({ stable: old, published, runs: [soak(8, 2), soak(9, 3)] }));+ const r = await daily(w.deps);+ expect(r.action === 'promoted' && r.promotion.version).toBe('1.0.2');+ expect(w.logs.some(l => l.includes('skipping v1.0.3: stable.json lists it as known bad'))).toBe(true);+ });+test('never moves stable backward: only releases newer than stable are candidates', async () => {const w = world(base({ stable: { ...old, version: '1.0.4', commit: 4, message: stableMessage('1.0.4', '2026-11-02T05:17:00Z') }, runs: [soak(9, 3)] }));expect((await daily(w.deps)).action).toBe('none');diff --git a/test/upgrade-restart-external-autopilot-8776.test.ts b/test/upgrade-restart-external-autopilot-8776.test.tsnew file mode 100644index 0000000000..e7e6ed26b1--- /dev/null+++ b/test/upgrade-restart-external-autopilot-8776.test.ts@@ -0,0 +1,144 @@+/**+ * #8776: `gbrain upgrade` refused on every host where autopilot runs outside launchd and systemd, gbrain's own+ * linux-cron install target included, so the stable auto-upgrade path could never finish there. An autopilot whose+ * launcher starts it again when it exits (this brain's gbrain cron line, or one the operator declares with+ * `self_upgrade.autopilot_launcher external`) is now handed to that launcher: stopped only while the pid is still that+ * autopilot, then verified back on the installed build. Without a launcher the upgrade still refuses, naming+ * `gbrain autopilot --install`, and doctor's `self_upgrade_health` warns before the upgrade fails.+ */+import { describe, expect, test } from 'bun:test';+import { join } from 'node:path';+import { planRestart, restartProblems, runRestartSteps, verifyRestart, PENDING_BUILD, type AutopilotLauncher, type HostProcess, type RestartContext, type RestartExecutor } from '../src/core/upgrade-restart.ts';+import { autopilotLauncher, restartRefusal } from '../src/commands/upgrade-restart.ts';+import { checkSelfUpgradeHealth } from '../src/commands/doctor/checks/upgrade-health.ts';+import { resolveAutopilotJob } from '../src/core/autopilot-paths.ts';+import { parseSelfUpgradeConfigValue, SELF_UPGRADE_CONFIG_LEAVES } from '../src/core/self-upgrade.ts';+import { withEnv } from './helpers/with-env.ts';++const NEW = '0.60.400.0';+const OLD = '0.60.390.0';+const CRON: AutopilotLauncher = { kind: 'cron', wait_ms: 360_000, pid: 30 };+const DECLARED: AutopilotLauncher = { kind: 'declared', wait_ms: 360_000, pid: 30 };+const ctx = (over: Partial<RestartContext> = {}): RestartContext => ({ expected: NEW, serveService: null, autopilotService: null, stopMcp: false, ...over });+/** An autopilot cron started through a wrapper shell: no installed service is among its ancestors. */+const autopilot = (pid = 30, version: string | null = OLD, over: Partial<HostProcess> = {}): HostProcess =>+ ({ pid, ppid: null, role: 'autopilot', version, started_ms: 1_000, ancestors: [7, 6], args: ['autopilot', '--repo', '/srv/brain-example'], ...over });++describe('planRestart: an autopilot started outside gbrain\'s service', () => {+ test('without a known launcher the upgrade refuses and names gbrain autopilot --install and the declared hand-off', () => {+ const plan = planRestart([autopilot()], ctx({ expected: PENDING_BUILD }));+ expect(plan.steps).toEqual([]);+ expect(plan.manual.map(m => [m.role, m.pid, m.argv])).toEqual([['autopilot', 30, ['gbrain', 'autopilot', '--install']]]);+ expect(plan.manual[0]!.instruction).toContain('started outside gbrain\'s autopilot service');+ expect(plan.manual[0]!.instruction).toContain('gbrain config set self_upgrade.autopilot_launcher external');+ const refusal = restartRefusal(plan, ['gbrain', 'upgrade'], false)!;+ expect(refusal.code).toBe('restart_refused');+ expect(refusal.fix).toMatchObject({ actor: 'user', argv: ['gbrain', 'autopilot', '--install'] });+ });++ test('with this brain\'s gbrain cron line, or a declared launcher, the upgrade hands autopilot over instead of refusing', () => {+ for (const launcher of [CRON, DECLARED]) {+ const plan = planRestart([autopilot()], ctx({ expected: PENDING_BUILD, autopilotLauncher: launcher }));+ expect(plan.manual).toEqual([]);+ expect(restartRefusal(plan, ['gbrain', 'upgrade'], false)).toBeNull();+ expect(plan.steps).toEqual([{ kind: 'handoff', role: 'autopilot', pid: 30, started_ms: 1_000, launcher }]);+ }+ });++ test('an installed service still wins; a worker of a handed-off autopilot goes with it; a current autopilot is left alone', () => {+ const underService = planRestart([autopilot(30, OLD, { ancestors: [29] })], ctx({ autopilotService: { argv: ['systemctl', '--user', 'restart', 'gbrain-autopilot.service'], pid: 29 }, autopilotLauncher: CRON }));+ expect(underService.steps).toMatchObject([{ kind: 'service', role: 'autopilot', pids: [30] }]);+ const worker: HostProcess = { pid: 31, ppid: 30, role: 'worker', version: OLD, started_ms: 1_000, ancestors: [30, 7], args: ['jobs', 'work'] };+ const withWorker = planRestart([autopilot(30, NEW), worker], ctx({ autopilotLauncher: CRON }));+ expect(withWorker.manual).toEqual([]);+ expect(withWorker.steps).toEqual([{ kind: 'handoff', role: 'autopilot', pid: 30, started_ms: 1_000, launcher: CRON }]);+ expect(planRestart([autopilot(30, NEW)], ctx({ autopilotLauncher: CRON })).steps).toEqual([]);+ });++ test('only the daemon this brain\'s autopilot lock names is handed over; any other autopilot still refuses', () => {+ const plan = planRestart([autopilot(30), autopilot(31)], ctx({ autopilotLauncher: CRON }));+ expect(plan.steps).toEqual([{ kind: 'handoff', role: 'autopilot', pid: 30, started_ms: 1_000, launcher: CRON }]);+ expect(plan.manual.map(m => m.pid)).toEqual([31]);+ expect(planRestart([autopilot(30)], ctx({ autopilotLauncher: { ...CRON, pid: null } })).manual.map(m => m.pid)).toEqual([30]);+ });++ test('an autopilot from another install that is not a Bun global copy still refuses: the hand-off never moves a clone', () => {+ const plan = planRestart([autopilot(30, OLD, { install_root: '/srv/gbrain-checkout', install_version: OLD })], ctx({ ownInstallRoot: '/opt/gbrain', autopilotLauncher: CRON }));+ expect(plan.steps).toEqual([]);+ expect(plan.manual[0]!.instruction).toContain('runs from another gbrain install');+ });+});++describe('runRestartSteps and verifyRestart: the hand-off', () => {+ const plan = planRestart([autopilot()], ctx({ autopilotLauncher: CRON }));+ const exec = (terminate: RestartExecutor['terminate']): RestartExecutor => ({ run: () => ({ status: 0, output: '' }), terminate, supervisorPid: () => null, sleep: async () => {} });++ test('signals the autopilot only while the pid is still that autopilot', async () => {+ const seen: Array<[number, number | null, string]> = [];+ const ok = await runRestartSteps(plan, exec((pid, started, role) => { seen.push([pid, started, role]); return 'stopped'; }));+ expect(seen).toEqual([[30, 1_000, 'autopilot']]);+ expect(ok[0]).toMatchObject({ ok: true });+ expect(ok[0]!.detail).toContain('this brain\'s gbrain cron line starts it again');+ const changed = await runRestartSteps(plan, exec(() => 'changed'));+ expect(changed[0]).toMatchObject({ ok: false });+ expect(changed[0]!.detail).toContain('no longer the autopilot the plan saw');+ });++ test('done once the launcher starts autopilot on the build; until then it names the launcher', async () => {+ const back = autopilot(130, NEW, { started_ms: 9_000 });+ expect(restartProblems(plan, [back], 5_000, { before: { state: 'absent' }, after: { state: 'absent' } })).toEqual([]);+ expect(restartProblems(plan, [], 5_000, { before: { state: 'absent' }, after: { state: 'absent' } }))+ .toEqual(['autopilot did not come back after it was stopped for this brain\'s gbrain cron line to start again.']);+ let clock = 0;+ let round = 0;+ const verified = await verifyRestart(plan, 5_000, { state: 'absent' }, {+ collect: async () => (round++ < 3 ? [] : [back]), probeWarmSocket: async () => ({ state: 'absent' }), sleep: async ms => { clock += ms; }, now: () => clock,+ }, { timeoutMs: CRON.wait_ms, pollMs: 2_000 });+ expect(verified.ok).toBe(true);+ expect(clock).toBe(6_000);+ });+});++describe('autopilotLauncher', () => {+ test('this brain\'s gbrain cron line is a launcher; a commented line, a monitor-only line or none is not; the declared key is the fallback', () => {+ const job = resolveAutopilotJob();+ const line = `*/5 * * * * '${join(job.homeDir, 'autopilot-run.sh')}' >> '${job.logPath}' 2>&1${job.cronMarker ? ` ${job.cronMarker}` : ''}`;+ expect(autopilotLauncher(() => `MAILTO=""\n${line}\n`, undefined, 30)).toEqual({ kind: 'cron', wait_ms: 360_000, pid: 30 });+ expect(autopilotLauncher(() => `# ${line}\n*/30 * * * * gbrain autopilot --status\n`, undefined, 30)).toBeNull();+ expect(autopilotLauncher(() => null, undefined, 30)).toBeNull();+ expect(autopilotLauncher(() => null, 'external', null)).toEqual({ kind: 'declared', wait_ms: 360_000, pid: null });+ });++ test('self_upgrade.autopilot_launcher is a registered leaf that accepts external only', () => {+ expect(SELF_UPGRADE_CONFIG_LEAVES).toContain('autopilot_launcher');+ expect(parseSelfUpgradeConfigValue('autopilot_launcher', 'external')).toEqual({ ok: true, value: 'external' });+ expect(parseSelfUpgradeConfigValue('autopilot_launcher', 'cron').ok).toBe(false);+ });+});++describe('doctor self_upgrade_health with the restart plan', () => {+ test('warns that gbrain upgrade refuses, naming the autopilot pid, with gbrain autopilot --install as an ask-user fix', async () => {+ await withEnv({ GBRAIN_SELF_UPGRADE_MODE: 'auto' }, () => {+ const check = checkSelfUpgradeHealth(planRestart([autopilot()], ctx({ expected: PENDING_BUILD })));+ expect(check.status).toBe('warn');+ expect(check.message).toContain('gbrain upgrade refuses on this host, so auto-upgrades cannot finish');+ expect(check.message).toContain('autopilot pid 30');+ expect(check.fix).toMatchObject({ ask_user: true, argv: ['gbrain', 'autopilot', '--install'] });+ expect(check.fix?.user_message).toContain('self_upgrade.autopilot_launcher external');+ });+ });++ test('names a hand-off and a second Bun global install in an ok message; no plan, or an empty one, leaves the message as it was', async () => {+ await withEnv({ GBRAIN_SELF_UPGRADE_MODE: 'notify' }, () => {+ const copy = '/home/alice-example/.bun-pinned/install/global/node_modules/gbrain';+ const serve: HostProcess = { pid: 9, ppid: null, role: 'serve', version: OLD, started_ms: 1_000, ancestors: [8], args: ['serve', '--http'], install_root: copy, install_version: OLD };+ const check = checkSelfUpgradeHealth(planRestart([autopilot(), serve], ctx({ expected: PENDING_BUILD, autopilotLauncher: CRON, ownInstallRoot: '/opt/gbrain', serveService: { argv: ['true'], pid: 8 } })));+ expect(check.status).toBe('ok');+ expect(check.message).toContain('upgrades restart autopilot pid 30 through this brain\'s gbrain cron line');+ expect(check.message).toContain(`pid 9 runs from a second install at ${copy} (v${OLD}), which upgrades replace too`);+ const plain = checkSelfUpgradeHealth().message;+ expect(checkSelfUpgradeHealth(null).message).toBe(plain);+ expect(checkSelfUpgradeHealth(planRestart([], ctx({ expected: PENDING_BUILD }))).message).toBe(plain);+ });+ });+});diff --git a/test/upgrade-restart.test.ts b/test/upgrade-restart.test.tsindex b2227a3a60..2924a7ed82 100644--- a/test/upgrade-restart.test.ts+++ b/test/upgrade-restart.test.ts@@ -282,7 +282,7 @@ describe('planRestart', () => {ctx({ serveService: null, autopilotService: null }));expect(plan.steps).toEqual([]);expect(plan.manual.map(m => [m.role, m.argv])).toEqual([- ['serve', ['kill', '10']], ['worker', ['kill', '21']], ['autopilot', ['kill', '30']], ['sync', ['gbrain', 'sync', 'status', '--json']], ['supervisor', ['kill', '20']],+ ['serve', ['kill', '10']], ['worker', ['kill', '21']], ['autopilot', ['gbrain', 'autopilot', '--install']], ['sync', ['gbrain', 'sync', 'status', '--json']], ['supervisor', ['kill', '20']],]);expect(plan.manual[0]!.instruction).toContain('was not started by the installed serve service');expect(plan.manual[1]!.instruction).toContain('gbrain jobs supervisor start --detach');