Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(self-upgrade): confirm swaps without a receipt, gate the delivered version, prove never-installed entries from the no-op record (#6828 review)
garrytane42c24d8e80e
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex a4ab80aa1b..a688847ce5 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -23,7 +23,7 @@ gbrain self-upgrade --clear-never-installed # preview: each entry andgbrain self-upgrade --clear-never-installed --apply # removes exactly those entries```-Only entries the self-upgrade audit proves were never installed are listed; anything else stays known-bad. If your install is still on an earlier release, it may be skipping this release as known-bad too: upgrade by hand with `gbrain self-upgrade` (a manual upgrade does not consult the known-bad list), or read the list with `gbrain config get self_upgrade.failed_versions` and, for an entry you have confirmed was never installed (no `v<version>` tag existed when it was recorded), set the list without it with `gbrain config set self_upgrade.failed_versions '[...]'`.+Only an entry proven never installed is listed: the no-op swap's own `last_upgrade` record (same version as `from` and `to`, written during that swap) must still be there, so only the most recent such entry can be proven, and a release that really installed and then crashed stays known-bad. An older entry shows under "Kept"; clear it by hand as below once you have confirmed it. If your install is still on an earlier release, it may be skipping this release as known-bad too: upgrade by hand with `gbrain self-upgrade` (a manual upgrade does not consult the known-bad list), or read the list with `gbrain config get self_upgrade.failed_versions` and, for an entry you have confirmed was never installed (no `v<version>` tag existed when it was recorded), set the list without it with `gbrain config set self_upgrade.failed_versions '[...]'`.### What you'd see@@ -39,7 +39,7 @@ Only entries the self-upgrade audit proves were never installed are listed; anyt- `gbrain check-update`, the startup marker refresh, `gbrain self-upgrade` and the `auto` channel read `VERSION` and `CHANGELOG.md` at the `latest-stable` tag (`src/commands/check-update.ts`).- `gbrain upgrade` compares the version after the install step with the one running; an unchanged version skips `last_upgrade`, `JUST_UPGRADED`, the cache reset and the post-swap smoke. With `GBRAIN_SWAP_RECEIPT` set (the `auto` channel sets it), it writes what it installed (`installed`, `not_installed`, `installed_broken`).-- The `auto` channel reads that receipt: nothing installed holds without known-bad and sets `self_upgrade.last_check_ts` (one attempt a day); a failure records the installed version; a real swap points the relaunch breadcrumb at the installed version (`src/core/self-upgrade-swap.ts`).+- The `auto` channel reads that receipt (or `gbrain --version` when there is none): nothing installed, or no newer version confirmed, holds without known-bad and sets `self_upgrade.last_check_ts` (one attempt a day); a failure records the installed version, and when that is not the checked version also throttles and drops the update cache; a real swap points the relaunch breadcrumb at the installed version (`src/core/self-upgrade-swap.ts`). Before swapping it checks the version the install would get against the known-bad list.- The pinned-install fallback no longer reads the update cache for its target, so it never names an unpublished version (#6718).- `gbrain self-upgrade --clear-never-installed [--apply] [--json]` and the `self_upgrade_health` warn with its fix (`src/core/self-upgrade-recovery.ts`).- `upgrade_errors` treats a record whose target is not a version as superseded once the binary is newer than its `from` version and the schema is current.diff --git a/docs/architecture/key-files/core-utilities-2.md b/docs/architecture/key-files/core-utilities-2.mdindex 0699e6b7df..b2544ffa4b 100644--- a/docs/architecture/key-files/core-utilities-2.md+++ b/docs/architecture/key-files/core-utilities-2.md@@ -26,8 +26,8 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/core/runtime-version.ts` — Bun 1.4.0 minimum (`MINIMUM_BUN_VERSION`; the lowest 1.4 release, carrying the Linux child-exit fix oven-sh/bun#30301). `unsupportedBunMessage` names the found and required versions and the fix (`bun upgrade`, restart, `gbrain post-upgrade` for an interrupted upgrade). `exitOnUnsupportedBun` is the CLI entrypoint gate: every command below the floor exits 1 before dispatch (`--version` still prints, exit 0, so an older gbrain's upgrade can verify the swap; `autopilot` also writes the refusal to stdout, its service log); `scripts/postinstall.ts` prints it when an install lands on an older Bun; the guarded HTTP transport asserts it; doctor reports it as `bun_runtime`. Package engines, runtime checks and the CI minimum-version lanes share the same floor (`test/scripts/ci-pr-scope.test.ts`). `compareBunVersions`/`bunVersionMeets` order Bun versions by semver (a `-canary` prerelease sits below its release; `+revision` metadata is ignored), shared with the upgrade floor gate.- `src/core/bun-floor.ts` — the Bun floor of an upgrade target (#5855): `readBunLinkTarget` (`git fetch`, the fetched upstream SHA, `package.json` at that SHA; the swap fast-forwards to that SHA), `readPackageTarget` (`package.json` at the ref a global install's `github:` spec names, default branch when unpinned; ClawHub reads the canonical default branch), `parseReleasePackage` (only a `>=X.Y.Z` `engines.bun` is a floor; any other shape is unreadable), `readHostBun` (the lower of the `bun` on PATH and the Bun at `process.execPath`) and `evaluateBunFloor` (the refusal text with path, and a path-free copy for the self-upgrade audit). `BUN_FLOOR_EXIT_CODE` (78) marks a `gbrain upgrade` refused for the floor, which the autopilot channel treats as a hold. Tests: `bun-floor.test.ts`, `autopilot-bun-floor.test.ts`, `upgrade-bun-link-arc.serial.test.ts`.-- `src/core/self-upgrade-swap.ts` — the autopilot self-upgrade channel's swap settlement (#6828): `prepareSwapReceipt` and `settleAutopilotSwap` read the receipt `gbrain upgrade --swap-only` writes (`GBRAIN_SWAP_RECEIPT`). Nothing installed: breadcrumb cleared, no known-bad, `self_upgrade.last_check_ts` set so the channel retries after 24 h. A failure: known-bad names the installed version (the attempted one with no receipt); the Bun-floor refusal (exit 78) holds. A real swap: the breadcrumb names the installed version. Tests: `autopilot-unpublished-target-6828.test.ts`, `autopilot-bun-floor.test.ts`.-- `src/core/self-upgrade-recovery.ts` — the #6828 known-bad recovery: `neverInstalledFailedVersions` (pure) lists `self_upgrade.failed_versions` entries the self-upgrade audit proves were never installed (every failure for the entry is a `swapped` row followed by a `crash-on-launch` row on the same running version; the version never ran; `upgrade-state.json` does not name it), `findNeverInstalledFailures` reads the config, every audit file (`readAllSelfUpgrades`) and `last_upgrade`. Used by `gbrain self-upgrade --clear-never-installed [--apply]` and doctor's `self_upgrade_health` fix. Tests: `self-upgrade-never-installed-6828.test.ts`.+- `src/core/self-upgrade-swap.ts` — autopilot swap settlement (#6828): `prepareSwapReceipt`/`settleAutopilotSwap` read the receipt `gbrain upgrade --swap-only` writes (`GBRAIN_SWAP_RECEIPT`; one from another run is ignored, none falls back to `gbrain --version`). Unchanged version, or exit 0 with nothing newer confirmed: hold, no known-bad, `self_upgrade.last_check_ts` (24 h retry). Failure: known-bad names the installed version; when that is not the checked one, also throttle and drop the update cache. Floor refusal (78): hold. Real swap: breadcrumb on the installed version. Tests: `autopilot-unpublished-target-6828.test.ts`, `autopilot-bun-floor.test.ts`.+- `src/core/self-upgrade-recovery.ts` — #6828 known-bad recovery: `neverInstalledFailedVersions` (pure) lists `self_upgrade.failed_versions` entries proven never installed: the no-op swap's own `last_upgrade` (`from` == `to` == running) is timestamped inside that entry's swap window, the entry has one failure (`crash-on-launch` after `swapped`, same running version), and no audit row ran it. Audit rows alone are not proof. `findNeverInstalledFailures` reads config, every audit file (`readAllSelfUpgrades`) and `last_upgrade`; used by `gbrain self-upgrade --clear-never-installed [--apply]` and the `self_upgrade_health` fix. Tests: `self-upgrade-never-installed-6828.test.ts`.- `src/core/shell-quote.ts` -- `shellQuote(arg)`: POSIX single-quotes any argument that is not already shell-safe, so `$()`, backticks and quotes stay inert when a printed command is pasted. A leaf module (no imports), so a command importing it adds no other module's `--flag` text to its generated flag-registry scan; `src/core/mcp-registration.ts` re-exports it unchanged. Used by the `gbrain storage status` restore hint.diff --git a/docs/guides/upgrades-auto-update.md b/docs/guides/upgrades-auto-update.mdindex adccd7d41f..5bd5a01944 100644--- a/docs/guides/upgrades-auto-update.md+++ b/docs/guides/upgrades-auto-update.md@@ -139,7 +139,12 @@ head is already installed), it prints `No newer version was installed`, keepsmarker. The `auto` channel then stays up instead of exiting for a relaunch,clears its breadcrumb, records no known-bad version, audits the attempt as`skipped` (`nothing newer was installed`) and tries again after 24 hours-(`self_upgrade.last_check_ts`). A version is recorded known-bad only when it+(`self_upgrade.last_check_ts`). The channel confirms a swap from a receipt+`gbrain upgrade` writes, or from `gbrain --version` when there is none; a+swap that exits 0 with no newer version confirmed is held the same way, never+relaunched. It also checks the version the install would actually get (a+bun-link clone follows master, a moving tag can pass the checked version)+against the known-bad list before swapping. A version is recorded known-bad only when itwas installed and then failed (the post-swap `gbrain --help` smoke, or arelaunch that did not come up on it), under the version actually installed.@@ -159,11 +164,17 @@ gbrain self-upgrade --clear-never-installed --apply # removes exactly the lisgbrain doctor --only self_upgrade_health --json # verify```-An entry is listed only when the self-upgrade audit proves it was never-installed: every failure recorded for it is a `swapped` row followed by a-`crash-on-launch` row that ran the same version, no audit row ever ran the-version, and `upgrade-state.json` does not name it as the last version-installed. Anything else stays known-bad. Nothing is rewritten during an+An entry is listed only when it is proven never installed. The audit rows+alone are not proof, because a release that installed, crashed before its+first boot finished, and was rolled back by hand leaves the same rows. The proof+is the record the no-op swap wrote itself: `last_upgrade` in+`upgrade-state.json` with the same version as `from` and `to`, timestamped+inside that entry's swap (between its apply row and its `swapped` row), plus+exactly one recorded failure for the entry, a `crash-on-launch` row on the+version that ran the swap, and no audit row that ever ran the entry's version.+Each swap overwrites `last_upgrade`, so only the most recent no-op can be+proven; an older entry stays listed as kept, and you clear it by hand as below+once you have confirmed it. Anything else stays known-bad. Nothing is rewritten during anupgrade. `gbrain config set self_upgrade.failed_versions '["<version>"]'` putsan entry back. On a release that does not have this command, read the listwith `gbrain config get self_upgrade.failed_versions`, confirm the entry wasdiff --git a/src/commands/autopilot.ts b/src/commands/autopilot.tsindex bde1d997ba..cfb325e05a 100644--- a/src/commands/autopilot.ts+++ b/src/commands/autopilot.ts@@ -468,7 +468,7 @@ export async function attemptAutopilotSelfUpgrade(});// #5855: never swap in a release the host's Bun cannot start (a binary carries its own Bun).if (decision.action === 'apply' && installMethod !== 'binary') {- decision = gateOnTargetRuntime(decision, await readInstallTargetFloor(installMethod), readHostBun());+ decision = gateOnTargetRuntime(decision, await readInstallTargetFloor(installMethod), readHostBun(), cfg.self_upgrade?.failed_versions);}if (decision.action !== 'apply') {diff --git a/src/commands/upgrade.ts b/src/commands/upgrade.tsindex 28f4a749c7..8a4ec99c00 100644--- a/src/commands/upgrade.ts+++ b/src/commands/upgrade.ts@@ -186,7 +186,10 @@ export async function runUpgrade(args: string[], opts: { targetVersion?: stringif (!upgraded) {console.log('Binary: upgrade failed');- writeSwapReceipt({ outcome: 'not_installed', from: oldVersion, installed: null });+ // #6828: an install step can fail after replacing files, so only a probe+ // that still reads the old version proves nothing was installed.+ const observed = verifyUpgrade();+ if (observed && observed === oldVersion) writeSwapReceipt({ outcome: 'not_installed', from: oldVersion, installed: observed });return;}const newVersion = verifyUpgrade();diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.tsindex 30f4ba2944..ee2acf6afb 100644--- a/src/core/behavior-change-notice.ts+++ b/src/core/behavior-change-notice.ts@@ -692,10 +692,10 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText }{ since: '0.60.258.0', text: 'A connector source\'s autopilot cycle now extracts facts and recomputes emotional weight only for that source\'s pages changed since its last completed cycle. Before, both phases walked every page in the brain on every connector cycle, which on a large brain ran past the 30-minute job deadline, so the cycle never finished and repeated the full walk.' },// LHF wave 2 item 0 (GBRA-94): tokenmax `query` no longer expands by default.{ since: '0.60.259.0', text: '`gbrain query` no longer runs LLM query expansion by default on `tokenmax`, so no search mode expands by default. On 300 LongMemEval-S questions with the reranker, `query` without expansion kept retrieval within noise (298 vs 299 of 300) and its p50 fell from about 2 s to about 230 ms (gbrain-evals expansion-latency report, 2026-10-14). To keep expanding: `gbrain config set search.expansion true` for the brain, or pass `--expand` / `expand: true` per call.' },- // #6828 / #6718 hotfix. `since` is a placeholder (master VERSION + 1) until the merge-slot stamp.- { since: '0.60.261.0', text: 'The update check (the startup `UPGRADE_AVAILABLE` marker, `gbrain check-update`, `gbrain self-upgrade`, doctor\'s `self_upgrade_health` and the `auto` channel) now reads the version at the `latest-stable` tag, the published release `bun update` installs, instead of master\'s `VERSION`. A version stamped on master but not yet released is no longer announced, and `auto` no longer tries to install it (#6718, #6828).' },- { since: '0.60.261.0', text: 'A `gbrain upgrade` whose install step leaves the same version running now prints `No newer version was installed` instead of `Upgrade complete`, and keeps `last_upgrade`, the pending-update marker and the `JUST_UPGRADED` breadcrumb as they were. The `auto` channel no longer exits for a relaunch after such a swap and no longer records the target known-bad: it audits the attempt as `skipped` and retries after 24 hours. A version is recorded known-bad only when it was installed and then failed, under the version actually installed.' },- { since: '0.60.261.0', text: '`gbrain doctor` (`self_upgrade_health`) now warns when `self_upgrade.failed_versions` holds a version the audit proves was never installed (an earlier release reported a no-op swap as swapped and recorded it known-bad, #6828), so `auto` would skip that release forever. `gbrain self-upgrade --clear-never-installed` previews the entries and the swap that recorded each; `--apply` removes exactly those. A post-upgrade failure recorded with no installable target (`latest`, `unknown`) now clears from `upgrade_errors` once the binary is past the version it failed from.' },+ // #6828 / #6718 hotfix. `since` is a placeholder equal to the branch VERSION until the merge-slot stamp.+ { since: '0.60.260.0', text: 'The update check (the startup `UPGRADE_AVAILABLE` marker, `gbrain check-update`, `gbrain self-upgrade`, doctor\'s `self_upgrade_health` and the `auto` channel) now reads the version at the `latest-stable` tag, the published release `bun update` installs, instead of master\'s `VERSION`. A version stamped on master but not yet released is no longer announced, and `auto` no longer tries to install it (#6718, #6828).' },+ { since: '0.60.260.0', text: 'A `gbrain upgrade` whose install step leaves the same version running now prints `No newer version was installed` instead of `Upgrade complete`, and keeps `last_upgrade`, the pending-update marker and the `JUST_UPGRADED` breadcrumb as they were. The `auto` channel no longer exits for a relaunch after such a swap and no longer records the target known-bad: it audits the attempt as `skipped` and retries after 24 hours. A version is recorded known-bad only when it was installed and then failed, under the version actually installed.' },+ { since: '0.60.260.0', text: '`gbrain doctor` (`self_upgrade_health`) now warns when `self_upgrade.failed_versions` holds a version the audit proves was never installed (an earlier release reported a no-op swap as swapped and recorded it known-bad, #6828), so `auto` would skip that release forever. `gbrain self-upgrade --clear-never-installed` previews the entries and the swap that recorded each; `--apply` removes exactly those. A post-upgrade failure recorded with no installable target (`latest`, `unknown`) now clears from `upgrade_errors` once the binary is past the version it failed from.' },];/** The newest disclosed change's release: the notice id moves only when a release adds rows. */diff --git a/src/core/cli-flag-registry.generated.ts b/src/core/cli-flag-registry.generated.tsindex 1ed98c80e5..0c2857e4be 100644--- a/src/core/cli-flag-registry.generated.ts+++ b/src/core/cli-flag-registry.generated.ts@@ -47,7 +47,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {'creds': ['--allow-create-db', '--allow-docker', '--brain', '--chat-model', '--content-root', '--db-only', '--embedding-dimensions', '--embedding-model', '--expansion-model', '--force', '--git', '--grant-types', '--help', '--http', '--ids', '--issuer-url', '--json', '--key', '--local-postgres', '--mcp-only', '--mcp-url', '--migrate-only', '--model', '--no-embedding', '--no-git', '--non-interactive', '--oauth-client-id', '--oauth-client-secret', '--out', '--passphrase-env', '--path', '--pglite', '--plan', '--prefer-postgres', '--provenance', '--provider', '--query', '--schema-pack', '--scopes', '--search-mode', '--skip-embed-check', '--source', '--status', '--supabase', '--surface', '--to', '--url', '--version'],'db-repair': ['--accept-pending', '--apply', '--apply-rewrites', '--background', '--brain', '--break-lock', '--db-url', '--dry-run', '--explain', '--filter', '--follow', '--force', '--force-retry', '--format', '--help', '--http', '--json', '--locks', '--name', '--no-accept-pending', '--path', '--prefer-postgres', '--probe', '--progress-interval', '--progress-json', '--quiet', '--remediate', '--restart', '--skip-verify', '--source', '--supabase', '--timeout', '--undo-last-rewrite', '--url', '--version', '--wait', '--yes'],'decide': ['--accept-all', '--all', '--all-from', '--apply', '--brain', '--call-site', '--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'],- 'doctor': ['--abandon', '--abbrev-ref', '--accept-pending', '--access', '--account', '--acknowledge-managed', '--add', '--admin-intent', '--adopt', '--adopt-columns', '--adopt-permissions', '--all', '--all-drifted', '--all-from', '--allow-old-serve', '--allow-shell-jobs', '--allow-unverified-remote', '--allowed-operations', '--apply', '--apply-rewrites', '--assign-corpus', '--audit', '--auto', '--auto-fix', '--autostash', '--background', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--branch', '--break-lock', '--budget-ms', '--budget-usd', '--by-mention', '--cached', '--call-site', '--catch-up', '--check', '--class', '--client', '--concurrency', '--confidence', '--confirm', '--confirm-quiesced', '--confirm-relocated-root', '--conflicts', '--contacts-dir', '--content-audit', '--content-root', '--count', '--dataset', '--db-url', '--delegated-namespace', '--delegated-slug-prefixes', '--delete-brain', '--dest', '--detach', '--diff-filter', '--dim', '--dir', '--disable', '--drain', '--drain-timeout', '--dry-run', '--egress', '--embedding-dimensions', '--embedding-model', '--enable', '--enable-dcr', '--end-of-options', '--env', '--error-unmatch', '--exclude', '--exclude-standard', '--expand', '--expect', '--expect-remote', '--expected-epoch', '--expected-revision', '--expected-state', '--explain', '--facts', '--fast', '--federated-read', '--fetch-timeout-ms', '--ff-only', '--file', '--fix', '--follow', '--force', '--force-rechunk', '--force-retry', '--force-schema', '--format', '--fresh', '--from', '--from-meetings', '--from-pages', '--full', '--fuzzy', '--get', '--git-common-dir', '--git-dir', '--git-path', '--group', '--group-by', '--hard', '--hard-deadline', '--harness', '--held', '--help', '--home', '--http', '--id', '--if-version', '--ignore-env-override', '--images', '--include-ambiguous', '--include-deleted', '--include-failures', '--include-flagged', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--include-pseudo', '--include-repairs', '--include-withdrawals', '--index-audit', '--init', '--input', '--install', '--is-ancestor', '--is-inside-work-tree', '--items-out', '--job-isolation', '--jq', '--json', '--keep', '--lanes', '--lang', '--left-right', '--limit', '--link-source', '--link-type', '--list', '--local', '--local-env-vars', '--locks', '--log-noop', '--manifest', '--markdown', '--max-cost', '--max-cost-usd', '--max-jobs', '--max-rss', '--max-runtime', '--max-usd', '--max-waiting', '--mcp-only', '--migrate-legacy', '--migrate-only', '--migration', '--min', '--mode', '--multimodal', '--name', '--name-only', '--nice', '--no-accept-pending', '--no-autopilot-install', '--no-autostash', '--no-capture', '--no-confirm', '--no-cron', '--no-delegate', '--no-edit', '--no-embed', '--no-embedding', '--no-expand', '--no-extract', '--no-hooks', '--no-lanes', '--no-llm', '--no-migrate', '--no-probe', '--no-pull', '--no-renames', '--no-repair', '--no-schema-pack', '--no-seat', '--no-tags', '--no-verify', '--non-interactive', '--now', '--older-than', '--once', '--only', '--operations', '--others', '--out', '--output', '--oversized', '--overwrite', '--page', '--parallel', '--params', '--pat-file', '--path', '--path-format', '--pglite', '--phase', '--pid-file', '--plan', '--porcelain', '--port', '--prefer', '--prefer-postgres', '--preset', '--preview', '--probe', '--probe-pglite', '--profile', '--progress-interval', '--progress-json', '--project', '--provider', '--providers', '--prune-orphans', '--public-url', '--pull', '--pure', '--purge', '--push-only', '--query', '--question', '--queue', '--quiet', '--rate', '--reauth', '--rebase', '--recommended', '--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', '--restore-only', '--resume', '--retry-failed', '--reverse', '--review-lower', '--revision', '--rollback-to-source', '--scope', '--scopes', '--search-mode', '--seat', '--section', '--select', '--self-transfer', '--semantic', '--session', '--set', '--set-upstream-to', '--shadow', '--short', '--show-current', '--show-prefix', '--show-token', '--show-toplevel', '--since', '--skills-dir', '--skip', '--skip-bare-tweet', '--skip-failed', '--skip-urls', '--skip-verify', '--slot', '--slug', '--slugs', '--source', '--source-id', '--sources', '--src-subpath', '--staged', '--stale', '--state', '--status', '--stdin', '--strategy', '--strict', '--suite', '--supabase', '--surface', '--symbol-kind', '--symbolic-full-name', '--takes-holders', '--target', '--target-score', '--threshold', '--tier', '--timeout', '--to', '--token', '--token-ttl', '--top-k', '--trust', '--type', '--uninstall', '--unsafe-bypass-dream-guard', '--unset-all', '--untracked-files', '--url', '--url-env', '--user', '--vectors', '--verbose', '--verify', '--version', '--wait', '--wait-drain', '--warn-only', '--what-if-threshold', '--window', '--workers', '--working-tree', '--workspace', '--yes'],+ 'doctor': ['--abandon', '--abbrev-ref', '--accept-pending', '--access', '--account', '--acknowledge-managed', '--add', '--admin-intent', '--adopt', '--adopt-columns', '--adopt-permissions', '--all', '--all-drifted', '--all-from', '--allow-old-serve', '--allow-shell-jobs', '--allow-unverified-remote', '--allowed-operations', '--apply', '--apply-rewrites', '--assign-corpus', '--audit', '--auto', '--auto-fix', '--autostash', '--background', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--branch', '--break-lock', '--budget-ms', '--budget-usd', '--by-mention', '--cached', '--call-site', '--catch-up', '--check', '--class', '--clear-never-installed', '--client', '--concurrency', '--confidence', '--confirm', '--confirm-quiesced', '--confirm-relocated-root', '--conflicts', '--contacts-dir', '--content-audit', '--content-root', '--count', '--dataset', '--db-url', '--delegated-namespace', '--delegated-slug-prefixes', '--delete-brain', '--dest', '--detach', '--diff-filter', '--dim', '--dir', '--disable', '--drain', '--drain-timeout', '--dry-run', '--egress', '--embedding-dimensions', '--embedding-model', '--enable', '--enable-dcr', '--end-of-options', '--env', '--error-unmatch', '--exclude', '--exclude-standard', '--expand', '--expect', '--expect-remote', '--expected-epoch', '--expected-revision', '--expected-state', '--explain', '--facts', '--fast', '--federated-read', '--fetch-timeout-ms', '--ff-only', '--file', '--fix', '--follow', '--force', '--force-rechunk', '--force-retry', '--force-schema', '--format', '--fresh', '--from', '--from-meetings', '--from-pages', '--full', '--fuzzy', '--get', '--git-common-dir', '--git-dir', '--git-path', '--group', '--group-by', '--hard', '--hard-deadline', '--harness', '--held', '--help', '--home', '--http', '--id', '--if-version', '--ignore-env-override', '--images', '--include-ambiguous', '--include-deleted', '--include-failures', '--include-flagged', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--include-pseudo', '--include-repairs', '--include-withdrawals', '--index-audit', '--init', '--input', '--install', '--is-ancestor', '--is-inside-work-tree', '--items-out', '--job-isolation', '--jq', '--json', '--keep', '--lanes', '--lang', '--left-right', '--limit', '--link-source', '--link-type', '--list', '--local', '--local-env-vars', '--locks', '--log-noop', '--manifest', '--markdown', '--max-cost', '--max-cost-usd', '--max-jobs', '--max-rss', '--max-runtime', '--max-usd', '--max-waiting', '--mcp-only', '--migrate-legacy', '--migrate-only', '--migration', '--min', '--mode', '--multimodal', '--name', '--name-only', '--nice', '--no-accept-pending', '--no-autopilot-install', '--no-autostash', '--no-capture', '--no-confirm', '--no-cron', '--no-delegate', '--no-edit', '--no-embed', '--no-embedding', '--no-expand', '--no-extract', '--no-hooks', '--no-lanes', '--no-llm', '--no-migrate', '--no-probe', '--no-pull', '--no-renames', '--no-repair', '--no-schema-pack', '--no-seat', '--no-tags', '--no-verify', '--non-interactive', '--now', '--older-than', '--once', '--only', '--operations', '--others', '--out', '--output', '--oversized', '--overwrite', '--page', '--parallel', '--params', '--pat-file', '--path', '--path-format', '--pglite', '--phase', '--pid-file', '--plan', '--porcelain', '--port', '--prefer', '--prefer-postgres', '--preset', '--preview', '--probe', '--probe-pglite', '--profile', '--progress-interval', '--progress-json', '--project', '--provider', '--providers', '--prune-orphans', '--public-url', '--pull', '--pure', '--purge', '--push-only', '--query', '--question', '--queue', '--quiet', '--rate', '--reauth', '--rebase', '--recommended', '--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', '--restore-only', '--resume', '--retry-failed', '--reverse', '--review-lower', '--revision', '--rollback-to-source', '--scope', '--scopes', '--search-mode', '--seat', '--section', '--select', '--self-transfer', '--semantic', '--session', '--set', '--set-upstream-to', '--shadow', '--short', '--show-current', '--show-prefix', '--show-token', '--show-toplevel', '--since', '--skills-dir', '--skip', '--skip-bare-tweet', '--skip-failed', '--skip-urls', '--skip-verify', '--slot', '--slug', '--slugs', '--source', '--source-id', '--sources', '--src-subpath', '--staged', '--stale', '--state', '--status', '--stdin', '--strategy', '--strict', '--suite', '--supabase', '--surface', '--symbol-kind', '--symbolic-full-name', '--takes-holders', '--target', '--target-score', '--threshold', '--tier', '--timeout', '--to', '--token', '--token-ttl', '--top-k', '--trust', '--type', '--uninstall', '--unsafe-bypass-dream-guard', '--unset-all', '--untracked-files', '--url', '--url-env', '--user', '--vectors', '--verbose', '--verify', '--version', '--wait', '--wait-drain', '--warn-only', '--what-if-threshold', '--window', '--workers', '--working-tree', '--workspace', '--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', '--path', '--phase', '--pull', '--reconcile-queue', '--since', '--source', '--source-id', '--threshold', '--to', '--unsafe-bypass-dream-guard', '--window', '--yes'],'edge-proposals': ['--access', '--add', '--all-applied', '--all-held', '--allowed-operations', '--asof', '--bound-slug-prefixes', '--brain', '--client', '--date', '--dated-since', '--days', '--entities', '--federated-read', '--from-index', '--full', '--fuzzy', '--help', '--http', '--id', '--include-deleted', '--json', '--kind', '--limit', '--max-usd', '--model', '--multimodal', '--no-autopilot-install', '--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'],@@ -73,7 +73,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {'graph-query': ['--brain', '--depth', '--direction', '--help', '--hop', '--include-foreign', '--json', '--mcp-only', '--source', '--type'],'hook': ['--allow-unverified-remote', '--auto', '--brain', '--branch', '--cached', '--count', '--diff-filter', '--enable', '--end-of-options', '--env', '--get', '--harness', '--help', '--jq', '--json', '--limit', '--name-only', '--others', '--pat-file', '--path', '--porcelain', '--pure', '--quiet', '--remove', '--seat', '--session', '--show-current', '--show-toplevel', '--since', '--source', '--yes'],'import': ['--accept-pending', '--admin-intent', '--allow-empty', '--allow-noncanonical-root', '--apply', '--background', '--brain', '--cached', '--confirm-relocated-root', '--diff-filter', '--dim', '--embedding-dimensions', '--embedding-model', '--empty', '--exclude', '--exclude-standard', '--expected-epoch', '--expected-state', '--explain', '--follow', '--force', '--force-rechunk', '--format', '--fresh', '--help', '--include-gitignored', '--is-shallow-repository', '--json', '--log-noop', '--manifest', '--name-only', '--no-accept-pending', '--no-embed', '--no-embedding', '--no-gpg-sign', '--no-pull', '--no-renames', '--no-verify', '--only', '--others', '--path', '--probe', '--progress-interval', '--progress-json', '--quiet', '--self-transfer', '--show-toplevel', '--skip-failed', '--slugs', '--source', '--source-id', '--stale', '--status', '--supabase', '--timeout', '--to', '--url', '--verify', '--wait', '--workers'],- 'init': ['--access', '--acknowledge-managed', '--adopt', '--all', '--allow-create-db', '--allow-docker', '--apply', '--assign-corpus', '--audit', '--auto', '--background', '--bound-slug-prefixes', '--brain', '--break-lock', '--budget-ms', '--budget-usd', '--chat-model', '--check', '--confirm-relocated-root', '--conflicts', '--content-root', '--db-only', '--dest', '--detach', '--dim', '--disable', '--drain', '--embedding-dimensions', '--embedding-model', '--enable', '--expand', '--expansion-model', '--expect', '--expect-remote', '--facts', '--fast', '--fix', '--force', '--force-retry', '--from-meetings', '--full', '--git', '--grant-types', '--group-by', '--harness', '--held', '--help', '--http', '--id', '--images', '--include-frontmatter', '--include-gitignored', '--issuer-url', '--json', '--keep', '--key', '--lanes', '--limit', '--list', '--local-postgres', '--markdown', '--max-usd', '--mcp-only', '--mcp-url', '--migrate-only', '--migration', '--model', '--no-autopilot-install', '--no-autostash', '--no-delegate', '--no-embed', '--no-embedding', '--no-expand', '--no-extract', '--no-git', '--no-llm', '--no-probe', '--no-pull', '--no-repair', '--no-schema-pack', '--non-interactive', '--oauth-client-id', '--oauth-client-secret', '--once', '--only', '--oversized', '--page', '--params', '--pat-file', '--path', '--pglite', '--phase', '--plan', '--prefer', '--prefer-postgres', '--preview', '--probe', '--profile', '--provenance', '--providers', '--pull', '--purge', '--push-only', '--query', '--question', '--quiet', '--rebase', '--reference-date', '--remediate', '--remove', '--repair-unknown-markers', '--reset', '--resolve', '--resume', '--retry-failed', '--save', '--schema-pack', '--scope', '--scopes', '--search-mode', '--section', '--self-transfer', '--semantic', '--show-toplevel', '--skip', '--skip-embed-check', '--skip-failed', '--slug', '--slugs', '--source', '--source-id', '--stale', '--state', '--status', '--supabase', '--surface', '--tier', '--timeout', '--to', '--token', '--touchpoint', '--url', '--url-env', '--user', '--version', '--wait', '--warn-only', '--workspace', '--yes'],+ 'init': ['--access', '--acknowledge-managed', '--adopt', '--all', '--allow-create-db', '--allow-docker', '--apply', '--assign-corpus', '--audit', '--auto', '--background', '--bound-slug-prefixes', '--brain', '--break-lock', '--budget-ms', '--budget-usd', '--chat-model', '--check', '--clear-never-installed', '--confirm-relocated-root', '--conflicts', '--content-root', '--db-only', '--dest', '--detach', '--dim', '--disable', '--drain', '--embedding-dimensions', '--embedding-model', '--enable', '--expand', '--expansion-model', '--expect', '--expect-remote', '--facts', '--fast', '--fix', '--force', '--force-retry', '--from-meetings', '--full', '--git', '--grant-types', '--group-by', '--harness', '--held', '--help', '--http', '--id', '--images', '--include-frontmatter', '--include-gitignored', '--issuer-url', '--json', '--keep', '--key', '--lanes', '--limit', '--list', '--local-postgres', '--markdown', '--max-usd', '--mcp-only', '--mcp-url', '--migrate-only', '--migration', '--model', '--no-autopilot-install', '--no-autostash', '--no-delegate', '--no-embed', '--no-embedding', '--no-expand', '--no-extract', '--no-git', '--no-llm', '--no-probe', '--no-pull', '--no-repair', '--no-schema-pack', '--non-interactive', '--oauth-client-id', '--oauth-client-secret', '--once', '--only', '--oversized', '--page', '--params', '--pat-file', '--path', '--pglite', '--phase', '--plan', '--prefer', '--prefer-postgres', '--preview', '--probe', '--profile', '--provenance', '--providers', '--pull', '--purge', '--push-only', '--query', '--question', '--quiet', '--rebase', '--reference-date', '--remediate', '--remove', '--repair-unknown-markers', '--reset', '--resolve', '--resume', '--retry-failed', '--save', '--schema-pack', '--scope', '--scopes', '--search-mode', '--section', '--self-transfer', '--semantic', '--show-toplevel', '--skip', '--skip-embed-check', '--skip-failed', '--slug', '--slugs', '--source', '--source-id', '--stale', '--state', '--status', '--supabase', '--surface', '--tier', '--timeout', '--to', '--token', '--touchpoint', '--url', '--url-env', '--user', '--version', '--wait', '--warn-only', '--workspace', '--yes'],'integrations': ['--auto', '--brain', '--dry-run', '--help', '--json', '--overwrite', '--refresh', '--source', '--target'],'integrity': ['--accept-pending', '--auto', '--backend', '--background', '--brain', '--confidence', '--cost', '--dry-run', '--explain', '--follow', '--fresh', '--help', '--json', '--limit', '--no-accept-pending', '--probe', '--progress-interval', '--progress-json', '--quiet', '--review-lower', '--skip-bare-tweet', '--skip-urls', '--source', '--supabase', '--timeout', '--type', '--url', '--wait'],'jobs': ['--abbrev-ref', '--access', '--acknowledge-managed', '--add', '--aliases', '--all', '--allow-empty', '--allow-shell-jobs', '--allowed-operations', '--apply', '--asof', '--auto', '--background', '--backoff-delay', '--backoff-jitter', '--backoff-type', '--batch-size', '--bound-slug-prefixes', '--brain', '--break-lock', '--by-mention', '--cached', '--catch-up', '--check', '--cli-path', '--client', '--cluster-errors', '--concurrency', '--confidence', '--confirm-destructive', '--cost-estimate', '--date', '--dated-since', '--days', '--delay', '--detach', '--diff-filter', '--dir', '--drain', '--dry-run', '--embedding-dimensions', '--embedding-model', '--empty', '--entities', '--exclude', '--exclude-standard', '--expect', '--explain', '--facts', '--federated-read', '--filters', '--fix', '--follow', '--force', '--force-break-lock', '--format', '--fresh', '--from-index', '--from-meetings', '--full', '--full-history', '--fuzzy', '--grammar-diagnostics', '--group', '--hard-deadline', '--health-interval', '--held', '--help', '--http', '--id', '--idempotency-key', '--ids', '--images', '--include-deleted', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--include-null-signature', '--infer-dates', '--inject-bootstrap', '--inline', '--input', '--install', '--interval', '--is-ancestor', '--is-shallow-repository', '--job-id', '--job-isolation', '--json', '--kind', '--lanes', '--limit', '--lock-duration-ms', '--log-noop', '--markdown', '--max-age', '--max-attempts', '--max-cost', '--max-cost-usd', '--max-crashes', '--max-rss', '--max-sources', '--max-stalled', '--max-usd', '--max-waiting', '--mcp-only', '--min-context', '--missing-path', '--model', '--multimodal', '--name-only', '--ner', '--nice', '--no-auto-embed', '--no-autopilot-install', '--no-bulk', '--no-confirm', '--no-delegate', '--no-embed', '--no-extract', '--no-gpg-sign', '--no-hard-deadline', '--no-inject', '--no-lanes', '--no-llm', '--no-pull', '--no-renames', '--no-repair', '--no-schema-pack', '--no-verify', '--no-worker', '--non-interactive', '--now', '--older-than', '--once', '--only', '--order', '--others', '--output', '--override-disabled', '--oversized', '--pace', '--pace-max-concurrency', '--pack', '--page', '--parallel', '--params', '--path', '--pause', '--phase', '--pid-file', '--prefer', '--priority', '--probe', '--prune-orphans', '--purge', '--queue', '--queue-only', '--quiet', '--reason', '--rebuild', '--recent', '--redact-secrets', '--reenrich-after', '--refresh-ms', '--refresh-operations', '--repo', '--reset-checkpoint', '--resume', '--retry-failed', '--retry-held', '--review-lower', '--row', '--scopes', '--segment-limit', '--select', '--serial', '--session', '--show-toplevel', '--sigkill-rescue', '--since', '--skip-bare-tweet', '--skip-failed', '--skip-urls', '--sleep', '--slug', '--slugs', '--source', '--source-id', '--sources', '--src-subpath', '--stale', '--status', '--strategy', '--surface', '--swap-only', '--target', '--thin', '--thin-threshold', '--timeout', '--timeout-ms', '--to', '--trust', '--type', '--types', '--uninstall', '--updated-after', '--url', '--user', '--vectors', '--verbose', '--verify', '--version', '--watch', '--wedge-rescue', '--workers', '--working-tree', '--yes'],diff --git a/src/core/self-upgrade-recovery.ts b/src/core/self-upgrade-recovery.tsindex 23520ad1b8..1415e2a9a6 100644--- a/src/core/self-upgrade-recovery.ts+++ b/src/core/self-upgrade-recovery.ts@@ -29,48 +29,60 @@ export interface NeverInstalledEntry {recorded_at: string;}+/** The last upgrade gbrain recorded (`~/.gbrain/upgrade-state.json` `last_upgrade`). */+export interface LastUpgrade { from: string; to: string; ts: string }++/** The longest a pre-fix swap could run between its apply row and its `swapped` row (the swap's own timeout). */+const SWAP_WINDOW_MS = 300_000;+/**- * The `failed_versions` entries the audit proves were never installed. The- * proof is the pair the pre-fix channel left: the swap row and the relaunch's- * crash-on-launch row ran the same version, so the attempted one was never on- * disk. An entry qualifies only when every failure the audit records for it- * is such a pair, at least one exists, no audit row ever ran it, and the last- * recorded upgrade did not install it. Anything unproven stays known-bad.- * Pure; `events` in ts order.+ * The `failed_versions` entries proven never installed. The audit pair alone+ * (a `swapped` row, then a `crash-on-launch` row on the same running version)+ * is not proof: a release that installed, passed the smoke and crashed before+ * its boot reconcile, with the old version restored by hand, leaves the same+ * rows. The proof is the record the pre-fix no-op swap itself wrote:+ * `last_upgrade` with `from` and `to` both the running version, timestamped+ * between that entry's apply row and its `swapped` row. A real install writes+ * `from` != `to` there, and a later swap overwrites the record with a+ * timestamp outside the window, so only the most recent no-op can be proven.+ * An entry also needs exactly one recorded failure, and no audit row may ever+ * have run it. Anything unproven stays known-bad. Pure; `events` in ts order.*/export function neverInstalledFailedVersions(failedVersions: readonly string[],events: readonly { ts: string; channel: string; action: string; current: string; latest?: string | null; outcome?: string; reason?: string }[],- lastUpgradeTo: string | null,+ lastUpgrade: LastUpgrade | null,): NeverInstalledEntry[] {+ if (!lastUpgrade || lastUpgrade.from !== lastUpgrade.to) return [];+ const recordedAt = Date.parse(lastUpgrade.ts);+ if (!Number.isFinite(recordedAt)) return [];const out: NeverInstalledEntry[] = [];for (const version of failedVersions) {- if (version === lastUpgradeTo) continue;if (events.some((e) => e.current === version)) continue;const failures = events.flatMap((e, i) => (e.outcome === 'failed' && e.latest === version ? [i] : []));- if (failures.length === 0) continue;- let proof: NeverInstalledEntry | null = null;- const allNoOp = failures.every((i) => {- const recorded = events[i];- if (!recorded.reason?.startsWith(CRASH_ON_LAUNCH_REASON_PREFIX)) return false;- const swap = events.slice(0, i).findLast((e) =>- e.channel === 'autopilot' && e.latest === version && e.outcome !== undefined);- if (!swap || swap.outcome !== 'applied' || swap.reason !== SWAPPED_REASON || swap.current !== recorded.current) return false;- proof ??= { version, running: recorded.current, swapped_at: swap.ts, recorded_at: recorded.ts };- return true;- });- if (allNoOp && proof) out.push(proof);+ if (failures.length !== 1) continue;+ const recorded = events[failures[0]];+ if (!recorded.reason?.startsWith(CRASH_ON_LAUNCH_REASON_PREFIX) || recorded.current !== lastUpgrade.from) continue;+ const before = events.slice(0, failures[0]);+ const swapIdx = before.findLastIndex((e) => e.channel === 'autopilot' && e.latest === version && e.outcome !== undefined);+ const swap = before[swapIdx];+ if (!swap || swap.outcome !== 'applied' || swap.reason !== SWAPPED_REASON || swap.current !== recorded.current) continue;+ const start = before.slice(0, swapIdx).findLast((e) => e.channel === 'autopilot' && e.latest === version && e.outcome === undefined);+ const swappedAt = Date.parse(swap.ts);+ const windowStart = start ? Date.parse(start.ts) : swappedAt - SWAP_WINDOW_MS;+ if (!(recordedAt >= windowStart && recordedAt <= swappedAt)) continue;+ out.push({ version, running: recorded.current, swapped_at: swap.ts, recorded_at: recorded.ts });}return out;}-/** The version the last real swap installed (`~/.gbrain/upgrade-state.json`), or null. */-function lastUpgradeTo(): string | null {+/** `last_upgrade` from `~/.gbrain/upgrade-state.json` (where `gbrain upgrade` writes it), or null. */+function readLastUpgrade(): LastUpgrade | null {try {const path = join(process.env.HOME || '', '.gbrain', 'upgrade-state.json');if (!existsSync(path)) return null;- const to = (JSON.parse(readFileSync(path, 'utf8')) as { last_upgrade?: { to?: unknown } }).last_upgrade?.to;- return typeof to === 'string' ? to : null;+ const u = (JSON.parse(readFileSync(path, 'utf8')) as { last_upgrade?: Record<string, unknown> }).last_upgrade;+ return u && typeof u.from === 'string' && typeof u.to === 'string' && typeof u.ts === 'string' ? { from: u.from, to: u.to, ts: u.ts } : null;} catch {return null;}@@ -80,6 +92,6 @@ function lastUpgradeTo(): string | null {export function findNeverInstalledFailures(): { failed: string[]; clearable: NeverInstalledEntry[] } {const failed = loadConfig()?.self_upgrade?.failed_versions ?? [];if (failed.length === 0) return { failed, clearable: [] };- return { failed, clearable: neverInstalledFailedVersions(failed, readAllSelfUpgrades(), lastUpgradeTo()) };+ return { failed, clearable: neverInstalledFailedVersions(failed, readAllSelfUpgrades(), readLastUpgrade()) };}diff --git a/src/core/self-upgrade-swap.ts b/src/core/self-upgrade-swap.tsindex b9aac681ce..bbd70a76f6 100644--- a/src/core/self-upgrade-swap.ts+++ b/src/core/self-upgrade-swap.ts@@ -1,29 +1,36 @@/*** The autopilot self-upgrade channel's swap settlement (v0.42; #5855, #6828):- * what `gbrain upgrade --swap-only` (run by src/commands/autopilot.ts) did. Exit 0 alone cannot- * tell a swap from a no-op (`bun update` on a tag whose head is already- * installed exits 0 and changes nothing), so the swap writes a receipt naming- * what it installed (`SWAP_RECEIPT_ENV`). Outcomes:+ * what `gbrain upgrade --swap-only` (run by src/commands/autopilot.ts) did.+ * Exit 0 alone cannot tell a swap from a no-op (`bun update` on a tag whose+ * head is already installed exits 0 and changes nothing), so the swap writes a+ * receipt naming what it installed (`SWAP_RECEIPT_ENV`). A receipt from+ * another run (its `from` is not the running version) is ignored, and with no+ * usable receipt the installed version is read with `gbrain --version`.+ * Outcomes:** - the swap's own Bun floor re-check refused (exit 78): hold, never known-bad;- * - nothing newer was installed: clear the breadcrumb, record no known-bad,- * retry after AUTO_CHECK_INTERVAL_MS (`self_upgrade.last_check_ts`);+ * - the same version is still installed: clear the breadcrumb, record no+ * known-bad, retry after AUTO_CHECK_INTERVAL_MS (`self_upgrade.last_check_ts`);* - the swap failed: record known-bad the version that was installed and- * failed (the attempted one when no receipt says what was installed);+ * failed (the attempted one when nothing says what was installed); when+ * that is not the checked version, also throttle and drop the update+ * cache, so the next check sees the version the install channel delivers;+ * - exit 0 and nothing proves a newer version is on disk: hold like the+ * unchanged case, never relaunch onto an unproven swap;* - a newer version is on disk: point the breadcrumb at it, so the* relaunch attributes a crash-on-launch to the version that crashed, and* return `relaunch`.*- * Every stay outcome is persisted and audited here. Never throws on the- * swap's failure (the caller still guards the tick).+ * Every stay outcome is persisted and audited here.*/import { unlinkSync } from 'node:fs';import { gbrainPath, loadConfig, saveConfig } from './config.ts';import { logSelfUpgrade } from './audit/self-upgrade-audit.ts';import { BUN_FLOOR_EXIT_CODE, BUN_FLOOR_FIX } from './bun-floor.ts';-import { readSwapReceipt, SWAP_RECEIPT_ENV } from './self-upgrade.ts';-import { isNewerVersion } from './semver.ts';+import { clearUpdateCache, readSwapReceipt, SWAP_RECEIPT_ENV } from './self-upgrade.ts';+import { isNewerVersion, isValidVersionString } from './semver.ts';+import { execSync } from './spawn.ts';export type AutopilotSwapResult = { relaunch: false } | { relaunch: true; installed: string };@@ -34,57 +41,83 @@ export function prepareSwapReceipt(): string {return path;}+/** `gbrain --version` of the binary on PATH, or null when unreadable. */+function probeInstalledVersion(): string | null {+ try {+ const v = String(execSync('gbrain --version', { encoding: 'utf-8', timeout: 10_000, env: { ...process.env, GBRAIN_SKIP_STARTUP_HOOKS: '1' } }))+ .trim().replace(/^gbrain\s*/i, '');+ return isValidVersionString(v) ? v : null;+ } catch {+ return null;+ }+}++function holdWithoutKnownBad(running: string, latestVersion: string, reason: string, errorText?: string): AutopilotSwapResult {+ const fresh = loadConfig();+ if (fresh) {+ fresh.self_upgrade = { ...(fresh.self_upgrade ?? {}), last_check_ts: Date.now() };+ delete fresh.self_upgrade.attempting_version;+ saveConfig(fresh);+ }+ logSelfUpgrade({+ channel: 'autopilot', action: 'apply', current: running, latest: latestVersion, outcome: 'skipped',+ reason: `${reason} (${latestVersion} not recorded known-bad; next attempt in 24h)`,+ ...(errorText ? { error: errorText } : {}),+ });+ console.log(`[autopilot] self-upgrade: ${reason}; staying on ${running}, retrying in 24h.`);+ return { relaunch: false };+}+/** Settle a finished `gbrain upgrade --swap-only` (`swapError` is what it threw, or null). */export function settleAutopilotSwap(running: string, latestVersion: string, swapError: unknown, receiptPath: string): AutopilotSwapResult {- const receipt = readSwapReceipt(receiptPath);+ const raw = readSwapReceipt(receiptPath);try { unlinkSync(receiptPath); } catch { /* absent */ }+ const receipt = raw && raw.from === running ? raw : null;const errorText = swapError === null ? undefined : swapError instanceof Error ? swapError.message : String(swapError);const held = swapError !== null && (swapError as { status?: number }).status === BUN_FLOOR_EXIT_CODE;-- if (!held && receipt?.outcome === 'not_installed') {+ if (held) {+ logSelfUpgrade({ channel: 'autopilot', action: 'unsupported_runtime', current: running, latest: latestVersion, outcome: 'skipped', reason: `gbrain upgrade refused the swap: the Bun floor of ${latestVersion} is not met or unreadable. ${BUN_FLOOR_FIX}` });const fresh = loadConfig();- if (fresh) {- fresh.self_upgrade = { ...(fresh.self_upgrade ?? {}), last_check_ts: Date.now() };+ if (fresh?.self_upgrade?.attempting_version) {delete fresh.self_upgrade.attempting_version;saveConfig(fresh);}- logSelfUpgrade({- channel: 'autopilot',- action: 'apply',- current: running,- latest: latestVersion,- outcome: 'skipped',- reason: `nothing newer was installed: still running ${running} (${latestVersion} not recorded known-bad; next attempt in 24h)`,- ...(errorText ? { error: errorText } : {}),- });- console.log(`[autopilot] self-upgrade installed nothing newer; staying on ${running}, retrying in 24h.`);+ console.error(`[autopilot] self-upgrade swap failed; staying on ${running}.`);return { relaunch: false };}- const installed = receipt?.installed && isNewerVersion(running, receipt.installed) ? receipt.installed : null;++ const observed = receipt ? receipt.installed : probeInstalledVersion();+ if (receipt?.outcome === 'not_installed' || (!receipt && observed === running)) {+ return holdWithoutKnownBad(running, latestVersion, `nothing newer was installed: still running ${running}`, errorText);+ }+ const installed = observed && isNewerVersion(running, observed) ? observed : null;if (swapError !== null) {const bad = installed ?? latestVersion;const fresh = loadConfig();if (fresh) {const failed = new Set(fresh.self_upgrade?.failed_versions ?? []);- if (!held) failed.add(bad);+ failed.add(bad);fresh.self_upgrade = { ...(fresh.self_upgrade ?? {}), failed_versions: [...failed] };+ if (bad !== latestVersion) fresh.self_upgrade.last_check_ts = Date.now();delete fresh.self_upgrade.attempting_version;saveConfig(fresh);}- logSelfUpgrade(held- ? { channel: 'autopilot', action: 'unsupported_runtime', current: running, latest: latestVersion, outcome: 'skipped', reason: `gbrain upgrade refused the swap: the Bun floor of ${latestVersion} is not met or unreadable. ${BUN_FLOOR_FIX}` }- : { channel: 'autopilot', action: 'apply', current: running, latest: bad, outcome: 'failed', error: errorText });+ if (bad !== latestVersion) clearUpdateCache();+ logSelfUpgrade({ channel: 'autopilot', action: 'apply', current: running, latest: bad, outcome: 'failed', error: errorText });console.error(`[autopilot] self-upgrade swap failed; staying on ${running}.`);return { relaunch: false };}- if (installed && installed !== latestVersion) {+ if (!installed) {+ return holdWithoutKnownBad(running, latestVersion, 'the swap exited 0 but no newer installed version could be confirmed');+ }+ if (installed !== latestVersion) {const fresh = loadConfig();if (fresh) {fresh.self_upgrade = { ...(fresh.self_upgrade ?? {}), attempting_version: installed };saveConfig(fresh);}}- return { relaunch: true, installed: installed ?? latestVersion };+ return { relaunch: true, installed };}diff --git a/src/core/self-upgrade.ts b/src/core/self-upgrade.tsindex 8a041efe16..43e921cc10 100644--- a/src/core/self-upgrade.ts+++ b/src/core/self-upgrade.ts@@ -188,14 +188,22 @@ export function decideSelfUpgrade(inp: DecideSelfUpgradeInputs): SelfUpgradeDeci* startup (the relaunched daemon included, before it can reconcile the* breadcrumb) and an unattended host has nothing that upgrades Bun (#5855).* The target is NOT recorded known-bad, so the first tick after the cause- * clears applies it. Pure.+ * clears applies it. #6828: the version the install would actually get (a+ * bun-link clone follows master, a moving tag can pass the checked version)+ * is also checked against `failedVersions`, so a release recorded known-bad+ * under its installed version is not reinstalled while the check names+ * another one. Pure.*/export function gateOnTargetRuntime(decision: SelfUpgradeDecision,target: TargetFloor,host: HostBun | null,+ failedVersions: readonly string[] = [],): SelfUpgradeDecision {if (decision.action !== 'apply') return decision;+ if (target.version && target.version !== decision.latest && failedVersions.includes(target.version)) {+ return { ...decision, action: 'known_bad', reason: `the install would get ${target.version}, which previously failed; not retrying` };+ }const verdict = evaluateBunFloor(target, host, decision.latest);if (verdict.ok) return decision;const retry = verdict.kind === 'unreadable' ? ' The next quiet-hours tick retries.' : '';diff --git a/test/autopilot-bun-floor.test.ts b/test/autopilot-bun-floor.test.tsindex 9ca0da5f13..e649acc303 100644--- a/test/autopilot-bun-floor.test.ts+++ b/test/autopilot-bun-floor.test.ts@@ -53,7 +53,8 @@ function harness(label: string): Harness {const argvLog = join(root, 'argv.log');writeFileSync(argvLog, '');writeFileSync(join(shims, 'bun'), '#!/usr/bin/env bash\necho "$FAKE_BUN_VERSION"\n', { mode: 0o755 });- writeFileSync(join(shims, 'gbrain'), `#!/usr/bin/env bash\nprintf 'gbrain %s\\n' "$*" >> "${argvLog}"\nexit "\${FAKE_GBRAIN_EXIT:-0}"\n`, { mode: 0o755 });+ // #6828: a swap is confirmed by the version it left on disk, so `--version` reports the target (a real swap) and is not logged as a swap call.+ writeFileSync(join(shims, 'gbrain'), `#!/usr/bin/env bash\nif [ "$1" = "--version" ]; then [ "\${FAKE_GBRAIN_EXIT:-0}" = 0 ] && echo "gbrain ${TARGET}"; exit "\${FAKE_GBRAIN_EXIT:-0}"; fi\nprintf 'gbrain %s\\n' "$*" >> "${argvLog}"\nexit "\${FAKE_GBRAIN_EXIT:-0}"\n`, { mode: 0o755 });return { root, home, shims, argvLog };}diff --git a/test/autopilot-unpublished-target-6828.test.ts b/test/autopilot-unpublished-target-6828.test.tsindex 099438622e..d54e88bd31 100644--- a/test/autopilot-unpublished-target-6828.test.ts+++ b/test/autopilot-unpublished-target-6828.test.ts@@ -226,7 +226,7 @@ describe('#6828: auto-update while master is ahead of latest-stable', () => {expect(tick.audit.at(-1)).toMatchObject({ action: 'apply', outcome: 'failed', latest: MASTER_AHEAD });}, 90_000);- test('a real swap still exits for relaunch and the relaunched binary confirms it', async () => {+ test('a real swap still exits for relaunch with the breadcrumb on the installed version', async () => {const h = harness('real', { cache: `UPGRADE_AVAILABLE ${VERSION} ${MASTER_AHEAD}` });const tick = await run(h, h.driver, { FAKE_TARGET_VERSION: MASTER_AHEAD, FAKE_INSTALLED_VERSION: MASTER_AHEAD });expect(tick.out).toContain('EXIT_CALLED 0');@@ -235,3 +235,55 @@ describe('#6828: auto-update while master is ahead of latest-stable', () => {expect(tick.audit.at(-1)).toMatchObject({ action: 'apply', outcome: 'applied', reason: 'swapped; exiting for supervisor relaunch' });}, 90_000);});++describe('#6828 review replays', () => {+ const setConfig = (h: Harness, patch: Record<string, unknown>) => {+ const p = join(h.home, '.gbrain', 'config.json');+ const cfg = JSON.parse(readFileSync(p, 'utf8'));+ cfg.self_upgrade = { ...cfg.self_upgrade, ...patch };+ writeFileSync(p, JSON.stringify(cfg));+ };++ test('a swap whose receipt cannot be written is confirmed by the installed version: a no-op still holds', async () => {+ const h = harness('no-receipt', { cache: `UPGRADE_AVAILABLE ${VERSION} ${MASTER_AHEAD}` });+ // A directory where the receipt goes: the swap cannot write it and the channel cannot read one.+ mkdirSync(join(h.home, '.gbrain', 'swap-receipt.json'));+ const tick = await run(h, h.driver, { FAKE_TARGET_VERSION: MASTER_AHEAD });+ expect(tick.calls).toContain('bun update gbrain');+ expect(tick.out).not.toContain('EXIT_CALLED');+ expect(tick.su.attempting_version).toBeUndefined();+ expect(tick.su.failed_versions).toBeUndefined();+ expect(tick.audit.at(-1)).toMatchObject({ action: 'apply', outcome: 'skipped', latest: MASTER_AHEAD });+ const boot = await run(h, h.bootDriver);+ expect(boot.su.failed_versions).toBeUndefined();+ }, 90_000);++ test('the no-op throttle expires after 24 hours', async () => {+ const h = harness('throttle', { cache: `UPGRADE_AVAILABLE ${VERSION} ${MASTER_AHEAD}` });+ setConfig(h, { last_check_ts: Date.now() - 25 * 60 * 60 * 1000 });+ const tick = await run(h, h.driver, { FAKE_TARGET_VERSION: MASTER_AHEAD });+ expect(tick.calls).toContain('bun update gbrain');+ setConfig(h, { last_check_ts: Date.now() - 23 * 60 * 60 * 1000 });+ const held = await run(h, h.driver, { FAKE_TARGET_VERSION: MASTER_AHEAD });+ expect(held.calls.filter((c) => c === 'bun update gbrain')).toHaveLength(1);+ }, 90_000);++ test('the version the install would get is checked against known-bad, not only the checked version', async () => {+ const delivered = `${v[0]}.${v[1]}.${v[2] + 2}.0`;+ const h = harness('gate-installed', { cache: `UPGRADE_AVAILABLE ${VERSION} ${MASTER_AHEAD}` });+ setConfig(h, { failed_versions: [delivered] });+ const tick = await run(h, h.driver, { FAKE_TARGET_VERSION: delivered });+ expect(tick.calls.filter((c) => c === 'bun update gbrain')).toEqual([]);+ expect(tick.audit.at(-1)).toMatchObject({ action: 'known_bad', outcome: 'skipped', latest: MASTER_AHEAD });+ expect(tick.audit.at(-1).reason).toContain(delivered);+ }, 90_000);++ test('a failure under a different installed version throttles and drops the update cache', async () => {+ const delivered = `${v[0]}.${v[1]}.${v[2] + 2}.0`;+ const h = harness('fail-other', { cache: `UPGRADE_AVAILABLE ${VERSION} ${MASTER_AHEAD}` });+ const tick = await run(h, h.driver, { FAKE_TARGET_VERSION: MASTER_AHEAD, FAKE_INSTALLED_VERSION: delivered, FAKE_HELP_EXIT: '1' });+ expect(tick.su.failed_versions).toEqual([delivered]);+ expect(typeof tick.su.last_check_ts).toBe('number');+ expect(tick.cache).toBeNull();+ }, 90_000);+});diff --git a/test/self-upgrade-never-installed-6828.test.ts b/test/self-upgrade-never-installed-6828.test.tsindex ebda281c67..26af597d9e 100644--- a/test/self-upgrade-never-installed-6828.test.ts+++ b/test/self-upgrade-never-installed-6828.test.ts@@ -39,41 +39,52 @@ function noOpSwapRows(running: string, attempted: string, hour: number) {];}+/** The last_upgrade record a pre-fix no-op swap wrote between its apply row and its swapped row. */+const noOpRecord = (running: string, hour: number) => ({ from: running, to: running, ts: `2026-10-16T0${hour}:01:30.000Z` });+describe('neverInstalledFailedVersions (pure)', () => {- test('the #6828 field sequences: both never-installed entries are proven', () => {+ test('the #6828 field sequences: the entry is proven by the no-op swap\'s own last_upgrade record', () => {const events = [...noOpSwapRows(A, B, 5),// The operator cleared B; B really installed and ran, then the same defect hit C.{ ts: '2026-10-16T05:28:16.000Z', channel: 'autopilot', action: 'apply', current: B, latest: B, outcome: 'applied', reason: 'running version is at or past the attempted version' },...noOpSwapRows(B, C, 6),];- expect(neverInstalledFailedVersions([C], events, B)).toEqual([+ expect(neverInstalledFailedVersions([C], events, noOpRecord(B, 6))).toEqual([{ version: C, running: B, swapped_at: '2026-10-16T06:02:00.000Z', recorded_at: '2026-10-16T06:03:00.000Z' },]);- // B ran (an audit row has current = B), so an entry for it is never cleared here.- expect(neverInstalledFailedVersions([B, C], events, B).map((e) => e.version)).toEqual([C]);- expect(neverInstalledFailedVersions([B], noOpSwapRows(A, B, 5), A).map((e) => e.version)).toEqual([B]);+ // B ran (an audit row has current = B), so an entry for it is never cleared.+ expect(neverInstalledFailedVersions([B, C], events, noOpRecord(B, 6)).map((e) => e.version)).toEqual([C]);+ expect(neverInstalledFailedVersions([B], noOpSwapRows(A, B, 5), noOpRecord(A, 5)).map((e) => e.version)).toEqual([B]);+ });++ test('a release that installed and crashed before its boot reconcile stays known-bad, even after a later no-op', () => {+ // A -> B really installed (last_upgrade A -> B); B crashed before writing anything; the operator restored A,+ // whose boot recorded B. A later no-op swap to C then overwrote last_upgrade with A -> A.+ const events = [...noOpSwapRows(A, B, 5), ...noOpSwapRows(A, C, 6)];+ expect(neverInstalledFailedVersions([B, C], events, noOpRecord(A, 6)).map((e) => e.version)).toEqual([C]);+ expect(neverInstalledFailedVersions([B], noOpSwapRows(A, B, 5), { from: A, to: B, ts: '2026-10-16T05:01:30.000Z' })).toEqual([]);});test('anything unproven stays known-bad', () => {const rows = noOpSwapRows(A, B, 5);- // No audit at all.- expect(neverInstalledFailedVersions([B], [], null)).toEqual([]);- // The last recorded upgrade installed it.- expect(neverInstalledFailedVersions([B], rows, B)).toEqual([]);+ const rec = noOpRecord(A, 5);+ expect(neverInstalledFailedVersions([B], [], rec)).toEqual([]);+ expect(neverInstalledFailedVersions([B], rows, null)).toEqual([]);+ // The record is outside this entry's swap window (another swap wrote it).+ expect(neverInstalledFailedVersions([B], rows, { ...rec, ts: '2026-10-16T05:03:30.000Z' })).toEqual([]);// The relaunch ran a different version than the swap (a rollback): not a no-op.const rollback = rows.map((e, i) => (i === 2 ? { ...e, current: '0.60.256.0' } : e));- expect(neverInstalledFailedVersions([B], rollback, null)).toEqual([]);+ expect(neverInstalledFailedVersions([B], rollback, rec)).toEqual([]);// A swap that failed outright (the install step exited non-zero) proves nothing about the disk.const swapFailed = [rows[0], { ...rows[1], outcome: 'failed', reason: undefined, error: 'Command failed: gbrain upgrade --swap-only' }];- expect(neverInstalledFailedVersions([B], swapFailed, null)).toEqual([]);- // One proven no-op plus one unproven failure for the same version: keep it.- expect(neverInstalledFailedVersions([B], [...rows, ...swapFailed.map((e) => ({ ...e, ts: e.ts.replace('T05', 'T07') }))], null)).toEqual([]);+ expect(neverInstalledFailedVersions([B], swapFailed, rec)).toEqual([]);+ // A second failure for the same version: keep it.+ expect(neverInstalledFailedVersions([B], [...rows, ...swapFailed.map((e) => ({ ...e, ts: e.ts.replace('T05', 'T07') }))], rec)).toEqual([]);// The crash-on-launch row with no swap row before it.- expect(neverInstalledFailedVersions([B], [rows[2]], null)).toEqual([]);+ expect(neverInstalledFailedVersions([B], [rows[2]], rec)).toEqual([]);});});-const UNPROVEN = '0.59.1.0';/** A home whose known-bad list holds B (the #6828 no-op) and an unproven entry, with the pre-fix audit rows. */@@ -85,7 +96,7 @@ async function withRecoveryHome(fn: (ctx: { failedVersions: () => string[]; run:mkdirSync(join(dir, '.gbrain'), { recursive: true });writeFileSync(join(dir, '.gbrain', 'config.json'), JSON.stringify({ engine: 'pglite', self_upgrade: { mode: 'auto', failed_versions: [B, UNPROVEN] } }));// The no-op swap overwrote last_upgrade with A -> A.- writeFileSync(join(dir, '.gbrain', 'upgrade-state.json'), JSON.stringify({ last_upgrade: { from: A, to: A, ts: '2026-10-16T05:03:05.771Z' } }));+ writeFileSync(join(dir, '.gbrain', 'upgrade-state.json'), JSON.stringify({ last_upgrade: { from: A, to: A, ts: '2026-10-16T05:01:30.000Z' } }));for (const row of noOpSwapRows(A, B, 5)) logSelfUpgrade(row as Parameters<typeof logSelfUpgrade>[0]);logSelfUpgrade({ ts: '2026-10-01T01:00:00.000Z', channel: 'autopilot', action: 'apply', current: '0.59.0.0', latest: UNPROVEN, outcome: 'failed', error: 'Command failed: gbrain upgrade --swap-only' });await fn({