Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(self-upgrade): target only the published release, never report a no-op as a swap, clear never-installed known-bad entries (#6828, #6718)
garrytan47de0d31958d
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 53acde2c0e..a4ab80aa1b 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -10,6 +10,41 @@ 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]++**Auto-update no longer blocklists the next release.** While master was ahead of the latest published release, the `auto` channel targeted master's unreleased `VERSION`, `bun update` changed nothing, the swap still reported success and relaunched, and the relaunch recorded the unreleased version as known-bad, so that release was never installed automatically once it shipped. Update checks now follow the published release, a swap that installs nothing is not a swap, and one command clears the bad entries an earlier release left behind (#6828, #6718).++### If auto-update skipped a release on your install++`gbrain doctor` shows `self_upgrade_health` warning `Auto-upgrade skips <version> as known-bad, but it was never installed`. On this release:++```bash+gbrain self-upgrade --clear-never-installed # preview: each entry and the swap that recorded it; changes nothing+gbrain 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 '[...]'`.++### What you'd see++| Situation | Before | Now |+|---|---|---|+| Master's `VERSION` is ahead of `latest-stable` | `UPGRADE_AVAILABLE` and doctor announced master's version; `auto` tried to install it | the published release is announced; nothing to install until it ships |+| `gbrain upgrade` where the install step changes nothing | `Upgrade complete. Now running: <same version>`; `last_upgrade` overwritten with `<v> -> <v>` | `No newer version was installed: still running gbrain <v>.`; `last_upgrade` kept |+| `auto` swap that installs nothing (a moving tag already at its head, an exact-tag pin) | `swapped; exiting for supervisor relaunch`, then `crash-on-launch ... (recorded known-bad)` for a version never installed | stays up, audits `skipped: nothing newer was installed`, records nothing known-bad, retries after 24 hours |+| A new release installs and does not start | the attempted version recorded known-bad | the installed version recorded known-bad (unchanged when they are the same) |+| Exact-tag pin with no newer published tag | the reinstall hint could name master's unpublished `#v<VERSION>`, and the `upgrade_errors` warn never cleared | the hint moves the install off the pin, and the warn clears once the binary moves past the version it failed from |++### Itemized changes++- `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 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.+- No schema change.+## [0.60.260.0] - 2026-10-16**An approved `doctor --remediate --include-repairs` run no longer fails with `preview_changed` because autovacuum analyzed a table between the preview and the run.** Hotfix for LHF wave 2 item 6 (GBRA-107, reported by GBRA-101).diff --git a/docs/architecture/key-files/commands-6.md b/docs/architecture/key-files/commands-6.mdindex 6b1c839e00..fe7afae631 100644--- a/docs/architecture/key-files/commands-6.md+++ b/docs/architecture/key-files/commands-6.md@@ -12,7 +12,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/commands/transcripts.ts` — the transcripts command family, all local-only (`ctx.remote=false` by construction). `recent`: raw `.txt` corpus reads via `listRecentTranscripts` (same library as the gated `get_recent_transcripts` op). `ingest <path-or-glob>`: the cross-harness session importer — resolves ONE source id (6-tier chain), threads activePack once, streams progress (phase `transcripts.ingest`), and calls `runTranscriptsIngest` with the CLI's `makeContext` context, so on a writer-claimed brain each rendered part is submitted as a `put_page` write request naming the page's current revision (unmanaged brains and dry runs keep the direct importer; `recover codex --apply` passes the same context; pinned by `test/transcripts-managed-ingest.test.ts`); embedding is OFF by default (embed backfill is the catch-up lane; the embed flag opts in); the max-bytes flag (validated size string, e.g. `4gb`) overrides the per-format file/store byte caps for oversized stores while omission preserves each adapter's native default; the since-last watermark is an op-checkpoint (op `transcripts-ingest`, fingerprint = source + pathspec + format + adapter version + any explicit byte cap via `ingestCheckpointFingerprintInput` — a checkpoint written under one cap is never silently reused under another, so a capped run's skipped tail can't read as scanned; the pathspec binds the user-stated paths resolved + sorted, and the no-arg/all lane substitutes hostname + sorted harness roots so DB-backed checkpoints shared across a brain's machines never let one machine inherit another's watermark and skip sessions it never scanned) advanced ONLY after a clean, untruncated, non-dry scan; no-arg = confined discovery table, the all flag imports the discovered set. `status`: found-vs-imported gap table (disk scan vs ONE conversation-pages frontmatter query — `executeRaw`, both engines — in `src/core/transcripts/discover.ts`) — the correctness surface that catches late-arriving sessions no watermark can. The facts flag hands EVERY touched slug (including hash-skipped) to `src/core/transcripts/ingest-facts.ts`; a page that fails extraction counts in `facts.pagesFailed`, stays unfinished, and makes the command exit 1. Registered in CLI_ONLY + CLI_ONLY_SELF_HELP + SELF_HELP_WITHOUT_ENGINE (engine-free help). `expandTilde(raw)` (bare `~`, leading `~/` or `~\\` → home dir; `~user` forms and a mid-string `~` stay literal) is the one tilde expansion `expandPaths` applies to every path spec. `recover codex` (`src/commands/transcripts-recover.ts`, logic `src/core/transcripts/recover.ts`; D15 for #5163): finds codex conversation pages in one source with no `**User**` anchor, re-parses the retained rollouts (discovery root + archived store, or given paths) and classifies each session recoverable / still userless / unrecoverable (rollout gone); preview by default, `--apply` re-imports only the recoverable rollouts through `runTranscriptsIngest` (content-hash dedup, no facts, no watermark write). Pinned by `test/transcripts-recover-codex.test.ts`. `audit-secrets [--source-id S] [--json]` (`src/commands/transcripts-audit.ts`, logic `src/core/transcripts/secret-audit.ts`): the read-only installed-base audit that streams imported conversation pages (`type = 'conversation'` with `transcript_import` frontmatter) in id-keyset batches of 25, scans title and body with the transcript-lane detectors, lists slug, source, hit counts per pattern and up to 20 line numbers (never values or previews), and caches the summary without slugs in config row `transcripts.secret_audit` for the doctor check `transcript_secret_exposure` (`src/commands/doctor/checks/transcript-secrets.ts`, brain category), which counts imported conversation pages and reads that summary (never scans): no audit, an older `TRANSCRIPT_SECRET_AUDIT_VERSION` or a source-scoped audit warns with the audit as fix; hits warn with the audit's age; a clean full audit is ok. Pinned by `test/transcripts-secret-audit.test.ts`.-- `src/commands/upgrade.ts` — self-update CLI. It sets `GBRAIN_UPGRADE_OWNS_MIGRATIONS=1` for the install step, so package postinstall (`scripts/postinstall.ts`) skips `apply-migrations`; post-upgrade owns them. An install step that fails or times out after `gbrain --version` already reports a newer version counts as installed. The run ends with a `Binary:` line (installed version, or upgrade failed) and a `Migrations:` line: complete; running, with the lock holder's host and pid when post-upgrade exits 75; or failed, with the recovery command (`--force-retry <v>` for wedged versions). `runPostUpgrade()` enumerates migrations from the TS registry (`src/commands/migrations/index.ts`) and tail-calls `runApplyMigrations(['--yes', '--non-interactive'])` so the mechanical side of every outstanding migration runs unconditionally. After schema apply it prints the one-shot auto_chronicle default-on `[AGENT]` notice (`core/chronicle/upgrade-notice.ts`). Before the swap of a bun-link, package or ClawHub install it refuses (exit 78, nothing changed) a target whose Bun floor is above the host's Bun or unreadable (`--no-bun-floor-check` overrides, manual only; `src/core/bun-floor.ts`); after the swap it runs `gbrain --help` as a smoke that passes the startup Bun check and, on failure, exits 1 with per-method recovery (#5855). Everything the post-swap tail needs is imported statically, so the old process never loads new-release modules into its cached graph (#6604; the supervisor step constant lives in the import-free leaf `src/commands/movement-step.ts`; guard: `test/upgrade-post-swap-imports.test.ts`). A tag-pinned reinstall hint (`bunReinstallCommand`, `reinstallHintLines`) probes `git ls-remote --exit-code --tags … refs/tags/v<x>` before `bun remove -g gbrain`, prints a restore line, and on Windows prints one step per line; `planPinnedReinstall` probes the tag itself (published / not published / unknown) and falls back to the newest published `v<x>` tag (`latestPublishedVersion`) when the requested one is missing (#6662, D24; `test/upgrade-release-tag-hint.test.ts`). 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).+- `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).- `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/architecture/key-files/core-utilities-2.md b/docs/architecture/key-files/core-utilities-2.mdindex 02d7294950..0699e6b7df 100644--- a/docs/architecture/key-files/core-utilities-2.md+++ b/docs/architecture/key-files/core-utilities-2.md@@ -26,6 +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/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 2b84f8d7ca..adccd7d41f 100644--- a/docs/guides/upgrades-auto-update.md+++ b/docs/guides/upgrades-auto-update.md@@ -121,6 +121,56 @@ the newest published release if it is newer than yours (#6662). WindowsPowerShell 5.1 has no `&&`, so on Windows the steps print one per line; runthem in order and stop if the tag check fails.+<a id="release-channel"></a>+### Which version counts as available++Every update surface (the startup marker, `gbrain check-update`,+`gbrain self-upgrade`, doctor's `self_upgrade_health` and the `auto` channel)+reads the `VERSION` file at the `latest-stable` tag: the release the canonical+install (`github:garrytan/gbrain#latest-stable`) gets from `bun update`, moved+only after the release checks pass and the assets publish. Master's `VERSION`+is never offered: the next PR stamps it before release.yml tags it, and a+superseded version never gets a tag (#6718, #6828).++A swap is a swap only when the version changed. When `gbrain upgrade` finds+the same version running after the install step (`bun update` on a tag whose+head is already installed), it prints `No newer version was installed`, keeps+`last_upgrade`, writes no `JUST_UPGRADED` breadcrumb and keeps the pending+marker. 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+was installed and then failed (the post-swap `gbrain --help` smoke, or a+relaunch that did not come up on it), under the version actually installed.++<a id="known-bad-never-installed"></a>+### A known-bad version that was never installed++Releases before this fix could record a version known-bad that was never+installed: the swap installed nothing, reported `swapped`, the supervisor+relaunched the same version, and the relaunch recorded the attempted version+in `self_upgrade.failed_versions`, so `auto` skipped that release forever.+doctor's `self_upgrade_health` warns about each such entry and names the+preview as its fix:++```bash+gbrain self-upgrade --clear-never-installed # preview: lists each entry and the swap that recorded it; writes nothing+gbrain self-upgrade --clear-never-installed --apply # removes exactly the listed entries+gbrain 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+upgrade. `gbrain config set self_upgrade.failed_versions '["<version>"]'` puts+an entry back. On a release that does not have this command, read the list+with `gbrain config get self_upgrade.failed_versions`, confirm the entry was+never installed (no `v<version>` tag existed when it was recorded, or the+audit shows the `swapped` row and the relaunch on the same version), then set+the list without it.+Recovery when autopilot is holding an upgrade:```bashdiff --git a/src/commands/autopilot.ts b/src/commands/autopilot.tsindex 8f19b486b7..bde1d997ba 100644--- a/src/commands/autopilot.ts+++ b/src/commands/autopilot.ts@@ -32,6 +32,8 @@ import {import { OwnerProcessingState, readAutopilotProcessingStatus } from '../core/minions/processing-state.ts';import { VERSION } from '../version.ts';import {+ AUTO_CHECK_INTERVAL_MS,+ CRASH_ON_LAUNCH_REASON_PREFIX,canSelfUpdate,decideSelfUpgrade,gateOnTargetRuntime,@@ -40,9 +42,12 @@ import {reconcileBreadcrumb,resolveQuietHoursWindow,resolveSelfUpgradeMode,+ SWAP_RECEIPT_ENV,+ SWAPPED_REASON,} from '../core/self-upgrade.ts';+import { prepareSwapReceipt, settleAutopilotSwap } from '../core/self-upgrade-swap.ts';import { logSelfUpgrade } from '../core/audit/self-upgrade-audit.ts';-import { BUN_FLOOR_EXIT_CODE, BUN_FLOOR_FIX, readHostBun } from '../core/bun-floor.ts';+import { readHostBun } from '../core/bun-floor.ts';import { detectInstallMethod, readInstallTargetFloor } from './upgrade.ts';import { evaluateQuietHours } from '../core/minions/quiet-hours.ts';import { inspectLock } from '../core/db-lock.ts';@@ -355,7 +360,7 @@ export function reconcileSelfUpgradeAtBoot(): void {reason:transition === 'applied'? 'running version is at or past the attempted version'- : 'crash-on-launch: running version is not at or past the attempted version (recorded known-bad)',+ : `${CRASH_ON_LAUNCH_REASON_PREFIX} running version is not at or past the attempted version (recorded known-bad)`,});if (transition === 'applied') {console.log(`[autopilot] self-upgrade confirmed: attempted ${attempted}, now running ${VERSION}.`);@@ -456,7 +461,10 @@ export async function attemptAutopilotSelfUpgrade(idle,inQuietHours: verdict !== 'allow',canSelfUpdate: canSelfUpdate(installMethod),- throttledByInterval: false, // cache TTL is the fetch throttle+ // The cache TTL throttles the fetch; last_check_ts (written when a swap+ // installed nothing, #6828) keeps a no-op swap to one attempt a day.+ throttledByInterval: typeof cfg.self_upgrade?.last_check_ts === 'number'+ && Date.now() - cfg.self_upgrade.last_check_ts < AUTO_CHECK_INTERVAL_MS,});// #5855: never swap in a release the host's Bun cannot start (a binary carries its own Bun).if (decision.action === 'apply' && installMethod !== 'binary') {@@ -484,29 +492,20 @@ export async function attemptAutopilotSelfUpgrade(logSelfUpgrade({ channel: 'autopilot', action: 'apply', current: VERSION, latest: latestVersion, reason: decision.reason });console.log(`[autopilot] self-upgrade: applying ${VERSION} -> ${latestVersion} (idle, quiet hours).`);+ // #6828: the swap writes what it installed to the receipt; exit 0 alone cannot tell a swap from a no-op.+ const receiptPath = prepareSwapReceipt();+ let swapError: unknown = null;try {execSync('gbrain upgrade --swap-only', {stdio: 'inherit',timeout: 300_000,- env: { ...process.env, GBRAIN_SKIP_STARTUP_HOOKS: '1' },+ env: { ...process.env, GBRAIN_SKIP_STARTUP_HOOKS: '1', [SWAP_RECEIPT_ENV]: receiptPath },});} catch (e) {- const fresh = loadConfig();- // #5855: the swap's own floor re-check refused; hold, never known-bad.- const held = (e as { status?: number }).status === BUN_FLOOR_EXIT_CODE;- if (fresh) {- const failed = new Set(fresh.self_upgrade?.failed_versions ?? []);- if (!held) failed.add(latestVersion);- fresh.self_upgrade = { ...(fresh.self_upgrade ?? {}), failed_versions: [...failed] };- delete fresh.self_upgrade.attempting_version;- saveConfig(fresh);- }- logSelfUpgrade(held- ? { channel: 'autopilot', action: 'unsupported_runtime', current: VERSION, 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: VERSION, latest: latestVersion, outcome: 'failed', error: e instanceof Error ? e.message : String(e) });- console.error(`[autopilot] self-upgrade swap failed; staying on ${VERSION}.`);- return;+ swapError = e;}+ const swap = settleAutopilotSwap(VERSION, latestVersion, swapError, receiptPath);+ if (!swap.relaunch) return;if (!mayContinue()) return;// Swap done + smoke-verified by `upgrade --swap-only`. Exit cleanly so the@@ -515,9 +514,9 @@ export async function attemptAutopilotSelfUpgrade(channel: 'autopilot',action: 'apply',current: VERSION,- latest: latestVersion,+ latest: swap.installed,outcome: 'applied',- reason: 'swapped; exiting for supervisor relaunch',+ reason: SWAPPED_REASON,});console.log('[autopilot] self-upgrade swapped; exiting for relaunch.');try {diff --git a/src/commands/check-update.ts b/src/commands/check-update.tsindex c320b4b556..b847a015cd 100644--- a/src/commands/check-update.ts+++ b/src/commands/check-update.ts@@ -45,17 +45,22 @@ function upgradeCommandForMethod(method: string): string {}}-/** Where the latest version is resolved from. The release train's source of- * truth is the `VERSION` file on master — same trusted host `fetchChangelog`- * already uses. GitHub releases are published from it per VERSION bump- * (`.github/workflows/release.yml`, #3521) and carry the binary assets, but- * this check deliberately does NOT read `releases/latest`: it was a permanent- * 404 before releases existed (#3520) and can still lag master. An npm+/** Where the latest version is resolved from: the VERSION file at the+ * `latest-stable` tag, the one sanctioned distribution ref+ * (`bun install -g github:garrytan/gbrain#latest-stable`). release.yml moves+ * it only after the release checks pass and the assets publish, so it names a+ * published release, the one `bun update` installs on the canonical install.+ * Master's VERSION is NOT a release: the next PR stamps it before release.yml+ * mints its tag, and a superseded version never gets one, so offering it made+ * the auto channel "upgrade" to a version the install could not reach and+ * blocklist it (#6718, #6828). Same trusted host as before. `releases/latest`+ * stays unread: it was a permanent 404 before releases existed (#3520). An npm* fallback was rejected: the `gbrain` package on npm is an unrelated GPU* library (#505), so it would produce false upgrade prompts pointing at a* stranger's package. */-const VERSION_SOURCE_URL = 'https://raw.githubusercontent.com/garrytan/gbrain/master/VERSION';-const RELEASE_NOTES_URL = 'https://github.com/garrytan/gbrain/blob/master/CHANGELOG.md';+const RELEASE_REF_RAW = 'https://raw.githubusercontent.com/garrytan/gbrain/latest-stable';+const VERSION_SOURCE_URL = `${RELEASE_REF_RAW}/VERSION`;+const RELEASE_NOTES_URL = 'https://github.com/garrytan/gbrain/blob/latest-stable/CHANGELOG.md';/** Extract a version from the raw VERSION file body: first line, optional `v`* prefix, optional `-suffix` channel tag (`0.31.1.1-fixwave` compares as its@@ -72,8 +77,8 @@ export type LatestReleaseResult =| { ok: false; reason: 'network_error' | 'no_releases' };/**- * Resolve the latest published gbrain version (from VERSION on master — see- * VERSION_SOURCE_URL). Exported (v0.42) so the self-upgrade refresh path and+ * Resolve the latest published gbrain version (from VERSION at the+ * latest-stable tag — see VERSION_SOURCE_URL). Exported (v0.42) so the self-upgrade refresh path and* tests can reuse it. 5s timeout — this runs on the detached refresh, never the* hot path. Failures are discriminated: `network_error` (offline/timeout) vs* `no_releases` (endpoint answered but no usable version).@@ -100,7 +105,7 @@ export async function fetchLatestRelease(): Promise<LatestReleaseResult> {export async function fetchChangelog(currentVersion: string, latestVersion: string): Promise<string> {try {- const res = await fetch('https://raw.githubusercontent.com/garrytan/gbrain/master/CHANGELOG.md', {+ const res = await fetch(`${RELEASE_REF_RAW}/CHANGELOG.md`, {signal: AbortSignal.timeout(5_000),});if (!res.ok) return '';diff --git a/src/commands/doctor/checks/upgrade-health.ts b/src/commands/doctor/checks/upgrade-health.tsindex 01ea93f3e1..22b38d522f 100644--- a/src/commands/doctor/checks/upgrade-health.ts+++ b/src/commands/doctor/checks/upgrade-health.ts@@ -11,11 +11,12 @@ import type { BrainEngine } from '../../../core/engine.ts';import { gbrainPath } from '../../../core/config.ts';import { LATEST_VERSION } from '../../../core/migrate.ts';import { MINIMUM_BUN_VERSION, unsupportedBunMessage } from '../../../core/runtime-version.ts';-import { isNewerVersion } from '../../../core/semver.ts';+import { 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 { VERSION as GBRAIN_BINARY_VERSION } from '../../../version.ts';import type { Check } from '../../doctor.ts';+import { agentFix } from '../check-fix.ts';/*** #4517: is the latest upgrade-errors.jsonl record superseded? True when the@@ -24,15 +25,22 @@ import type { Check } from '../../doctor.ts';* (or retried) upgrade demonstrably finished the job. Pure + exported for* tests. Compares ALL dot-segments (the canonical `compareVersions` stops at* 3, which would treat 0.31.4.1 == 0.31.4.0); a malformed version fails- * closed (keeps warning).+ * closed (keeps warning), except a non-version target with a `from` version.*/export function upgradeErrorResolved(failedToVersion: string,binaryVersion: string,schemaCurrent: boolean,+ failedFromVersion?: string,): boolean {if (!schemaCurrent) return false;if (typeof failedToVersion !== 'string' || typeof binaryVersion !== 'string') return false;+ // #6718: a record with no installable target (`latest` from a pinned install+ // with no newer published tag, `unknown` from a binary swap) can never be+ // reached; the binary moving past the version it failed FROM supersedes it.+ if (!isValidVersionString(failedToVersion) && typeof failedFromVersion === 'string') {+ return isNewerVersion(failedFromVersion, binaryVersion);+ }const a = binaryVersion.replace(/^v/, '').split('.');const b = failedToVersion.replace(/^v/, '').split('.');if (a.length === 0 || b.length === 0) return false;@@ -97,6 +105,29 @@ export function checkSelfUpgradeHealth(): Check {parts.push(`skipping known-bad: ${failedVersions.join(', ')}`);}+ // #6828: a known-bad entry the audit proves was never installed blocks+ // that release forever; the fix is the preview of the clearing step.+ if (failedVersions.length > 0) {+ const { findNeverInstalledFailures, CLEAR_NEVER_INSTALLED_PREVIEW, CLEAR_NEVER_INSTALLED_APPLY } = require('../../../core/self-upgrade-recovery.ts');+ const { clearable } = findNeverInstalledFailures() as { clearable: Array<{ version: string; running: string }> };+ if (clearable.length > 0) {+ const versions = clearable.map((e) => e.version).join(', ');+ return {+ name: 'self_upgrade_health',+ status: 'warn',+ message: `Auto-upgrade skips ${versions} as known-bad, but ${clearable.length === 1 ? 'it was' : 'they were'} never installed: a swap that installed nothing was reported as swapped (#6828) (${parts.join('; ')}).`,+ fix: agentFix([...CLEAR_NEVER_INSTALLED_PREVIEW, '--json'],+ 'The preview lists each entry with the swap that recorded it and changes nothing; its --apply removes exactly those entries.',+ 'self_upgrade_health', {+ docs: 'docs/guides/upgrades-auto-update.md#known-bad-never-installed',+ then: agentFix([...CLEAR_NEVER_INSTALLED_APPLY],+ 'Removes exactly the entries the preview proved were never installed; gbrain config set self_upgrade.failed_versions puts one back.',+ 'self_upgrade_health'),+ }),+ };+ }+ }+// 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));@@ -171,7 +202,7 @@ export async function checkUpgradeErrors(schemaCurrent = v >= LATEST_VERSION;} catch { /* unverifiable → keep warning */ }}- if (upgradeErrorResolved(latest.to_version, GBRAIN_BINARY_VERSION, schemaCurrent)) {+ if (upgradeErrorResolved(latest.to_version, GBRAIN_BINARY_VERSION, schemaCurrent, latest.from_version)) {return {name: 'upgrade_errors',status: 'ok',diff --git a/src/commands/self-upgrade.ts b/src/commands/self-upgrade.tsindex e0c908279b..87f565c3dc 100644--- a/src/commands/self-upgrade.ts+++ b/src/commands/self-upgrade.ts@@ -3,6 +3,56 @@ import { isNewerVersion, isValidVersionString } from '../core/semver.ts';import { fetchChangelog, fetchLatestRelease } from './check-update.ts';import { detectInstallMethod, runUpgrade } from './upgrade.ts';import { writeUpdateCache } from '../core/self-upgrade.ts';+import { loadConfig, saveConfig } from '../core/config.ts';+import { CLEAR_NEVER_INSTALLED_APPLY, findNeverInstalledFailures } from '../core/self-upgrade-recovery.ts';++/**+ * `gbrain self-upgrade --clear-never-installed [--apply] [--json]` (#6828).+ * Preview by default: lists each `self_upgrade.failed_versions` entry the+ * audit proves was never installed (a no-op swap reported "swapped" and the+ * relaunch of the same version recorded it known-bad) and the entries it+ * keeps. `--apply` removes exactly the proven entries from the file-plane+ * config. Reversible: `gbrain config set self_upgrade.failed_versions` puts+ * one back. Nothing else changes and nothing is installed.+ */+function runClearNeverInstalled(apply: boolean, json: boolean): void {+ const { failed, clearable } = findNeverInstalledFailures();+ const clear = new Set(clearable.map((e) => e.version));+ const kept = failed.filter((v) => !clear.has(v));+ if (apply && clear.size > 0) {+ const cfg = loadConfig();+ if (cfg?.self_upgrade) {+ const remaining = (cfg.self_upgrade.failed_versions ?? []).filter((v) => !clear.has(v));+ if (remaining.length > 0) cfg.self_upgrade.failed_versions = remaining;+ else delete cfg.self_upgrade.failed_versions;+ saveConfig(cfg);+ }+ }+ const applied = apply && clear.size > 0;+ if (json) {+ console.log(JSON.stringify({+ failed_versions: failed,+ never_installed: clearable,+ kept,+ applied,+ ...(!apply && clear.size > 0 ? { next: { argv: CLEAR_NEVER_INSTALLED_APPLY } } : {}),+ }, null, 2));+ return;+ }+ if (clear.size === 0) {+ console.log(failed.length === 0+ ? 'No known-bad versions are recorded (self_upgrade.failed_versions is empty).'+ : `No known-bad version is proven never installed; keeping ${failed.join(', ')}.`);+ return;+ }+ console.log(applied ? 'Cleared known-bad versions that were never installed:' : 'Known-bad versions that were never installed:');+ for (const e of clearable) {+ console.log(` ${e.version}: the swap at ${e.swapped_at} left ${e.running} running, and the relaunch of ${e.running} recorded ${e.version} known-bad at ${e.recorded_at}.`);+ }+ if (kept.length > 0) console.log(`Kept (not proven never installed): ${kept.join(', ')}`);+ if (applied) console.log('The auto channel installs them once they are published on its release channel.');+ else console.log(`Clear them: ${CLEAR_NEVER_INSTALLED_APPLY.join(' ')}`);+}/*** `gbrain self-upgrade [--check-only] [--force] [--json] [--no-bun-floor-check]`@@ -21,7 +71,8 @@ import { writeUpdateCache } from '../core/self-upgrade.ts';export async function runSelfUpgrade(args: string[]): Promise<void> {if (args.includes('--help') || args.includes('-h')) {console.log(- 'Usage: gbrain self-upgrade [--check-only] [--force] [--json] [--no-bun-floor-check]\n\n' ++ 'Usage: gbrain self-upgrade [--check-only] [--force] [--json] [--no-bun-floor-check]\n' ++ ' gbrain self-upgrade --clear-never-installed [--apply] [--json]\n\n' +'Check for and apply gbrain updates. The shared entry point used by the\n' +'CLI startup marker, the gbrain-upgrade agent skill, and the autopilot\n' +'silent channel.\n\n' +@@ -29,10 +80,17 @@ export async function runSelfUpgrade(args: string[]): Promise<void> {' --force Apply even when not behind.\n' +' --json Machine-readable output (with --check-only).\n' +' --no-bun-floor-check Apply even when the target\'s Bun floor cannot be read or is\n' +- ' above this host\'s Bun. Docs: docs/guides/upgrades-auto-update.md#bun-floor',+ ' above this host\'s Bun. Docs: docs/guides/upgrades-auto-update.md#bun-floor\n' ++ ' --clear-never-installed Preview the known-bad versions (self_upgrade.failed_versions) the\n' ++ ' audit proves were never installed; --apply removes exactly those.\n' ++ ' Docs: docs/guides/upgrades-auto-update.md#known-bad-never-installed',);return;}+ if (args.includes('--clear-never-installed')) {+ runClearNeverInstalled(args.includes('--apply'), args.includes('--json'));+ return;+ }const checkOnly = args.includes('--check-only');const force = args.includes('--force');diff --git a/src/commands/upgrade.ts b/src/commands/upgrade.tsindex a835b7995d..28f4a749c7 100644--- a/src/commands/upgrade.ts+++ b/src/commands/upgrade.ts@@ -12,7 +12,7 @@ import { forwardProgressPast, migrationLedgerSummary } from '../core/migration-limport { loadCompletedMigrations } from '../core/preferences.ts';import { MIGRATIONS_RUNNING_EXIT_CODE, readMigrationLockHolder } from '../core/migration-orchestration-lock.ts';import { loadConfig } from '../core/config.ts';-import { clearSnooze, clearUpdateCache, pendingUpgradeVersion, writeJustUpgraded } from '../core/self-upgrade.ts';+import { clearSnooze, clearUpdateCache, writeJustUpgraded, writeSwapReceipt } from '../core/self-upgrade.ts';import { MOVEMENT_SUPERVISOR_STEP } from './movement-step.ts';import {BUN_FLOOR_EXIT_CODE,@@ -186,9 +186,25 @@ export async function runUpgrade(args: string[], opts: { targetVersion?: stringif (!upgraded) {console.log('Binary: upgrade failed');+ writeSwapReceipt({ outcome: 'not_installed', from: oldVersion, installed: null });return;}const newVersion = verifyUpgrade();+ // #6828: an install step that exits 0 can install nothing (`bun update` on a+ // moving tag whose head is already installed). A verified version that is+ // not newer than the one running is no swap: no last_upgrade overwrite, no+ // JUST_UPGRADED breadcrumb, no cache reset, and the receipt tells the+ // autopilot channel not to relaunch or record known-bad. A verified version+ // EQUAL to the running one is the no-op; an unreadable one keeps the legacy path.+ const newParsed = parseSemver(newVersion);+ const oldParsed = parseSemver(oldVersion);+ const unchanged = !!newParsed && !!oldParsed && newParsed.join('.') === oldParsed.join('.');+ if (unchanged) {+ console.log(`No newer version was installed: still running gbrain ${newVersion}.`);+ writeSwapReceipt({ outcome: 'not_installed', from: oldVersion, installed: newVersion });+ } else {+ console.log(newVersion ? `Upgrade complete. Now running: gbrain ${newVersion}` : 'Upgrade complete. Could not verify new version.');+ }// #4366: a still-older resolved version means the swap never happened// (exact-tag Git pins make `bun update` a successful no-op). Fail loudly// and return BEFORE the breadcrumb/cache bookkeeping below, so the@@ -211,12 +227,13 @@ export async function runUpgrade(args: string[], opts: { targetVersion?: string// #5311: a bare `gbrain upgrade` has no target, so the check above cannot// fire, and on an exact-tag Git pin `bun update` is a successful no-op.// When the version did not change and the global install pins a tag, say- // so and exit non-zero instead of reporting an upgrade.- if (!target && method === 'bun' && newVersion && newVersion === oldVersion) {+ // so and exit non-zero instead of reporting an upgrade. #6718: the target is+ // the newest PUBLISHED release tag only; with none newer the hint moves the+ // install off the pin, and the ledger row names no unpublished version.+ if (!target && method === 'bun' && unchanged) {const pin = bunGlobalExactTagPin(resolveBunGlobalRoot());if (pin) {- const published = planPinnedReinstall(null, oldVersion);- const plan = published.version ? published : { version: pendingUpgradeVersion(oldVersion), unpublished: null };+ const plan = planPinnedReinstall(null, oldVersion);console.error(`Upgrade did not take effect: still running ${newVersion}, because the global install is pinned to ${pin} and \`bun update\` keeps a pinned tag.`);printPinnedReinstall(plan, oldVersion, 'Reinstall to move off the pin:');recordUpgradeError({@@ -230,29 +247,35 @@ export async function runUpgrade(args: string[], opts: { targetVersion?: stringreturn;}}- // Save old version for post-upgrade migration detection- saveUpgradeState(oldVersion, newVersion);- // #5855: `--version` answers on any Bun, so prove the new release starts.- if (!postSwapSmoke(newVersion, recovery)) return;-- // Self-upgrade breadcrumb + cache reset (covers both the full and- // --swap-only paths, so the autopilot silent channel benefits too):- // - write just-upgraded-from so the next invocation's startup hook prints- // the one-time JUST_UPGRADED confirmation;- // - clear the update-check cache + snooze so a now-stale "upgrade- // available" marker doesn't keep nudging after we've already applied it.- try {- writeJustUpgraded(oldVersion);- clearUpdateCache();- clearSnooze();- } catch {- /* best-effort: never block the upgrade on confirmation bookkeeping */+ if (!unchanged) {+ // Save old version for post-upgrade migration detection+ saveUpgradeState(oldVersion, newVersion);+ // #5855: `--version` answers on any Bun, so prove the new release starts.+ if (!postSwapSmoke(newVersion, recovery)) {+ writeSwapReceipt({ outcome: 'installed_broken', from: oldVersion, installed: newVersion || null });+ return;+ }++ // Self-upgrade breadcrumb + cache reset (covers both the full and+ // --swap-only paths, so the autopilot silent channel benefits too):+ // - write just-upgraded-from so the next invocation's startup hook prints+ // the one-time JUST_UPGRADED confirmation;+ // - clear the update-check cache + snooze so a now-stale "upgrade+ // available" marker doesn't keep nudging after we've already applied it.+ try {+ writeJustUpgraded(oldVersion);+ clearUpdateCache();+ clearSnooze();+ } catch {+ /* best-effort: never block the upgrade on confirmation bookkeeping */+ }+ writeSwapReceipt({ outcome: 'installed', from: oldVersion, installed: newVersion || null });}- // --swap-only stops here: the swap is done + smoke-verified, but the- // (potentially 30-min) post-upgrade is deferred to the next launch so the- // autopilot silent channel can swap + relaunch without freezing its tick.- // connectEngine's pending-migration probe + runPostUpgrade run on boot.+ // --swap-only stops here: the swap is done + smoke-verified (or installed+ // nothing), but the (potentially 30-min) post-upgrade is deferred to the+ // next launch so the autopilot silent channel can swap + relaunch without+ // freezing its tick. connectEngine's pending-migration probe + runPostUpgrade run on boot.if (swapOnly) {return;}@@ -289,7 +312,7 @@ export async function runUpgrade(args: string[], opts: { targetVersion?: string} catch {// features scan is best-effort}- console.log(`Binary: installed ${newVersion || 'a new version (could not verify)'}`);+ console.log(unchanged ? `Binary: no newer version installed (still ${newVersion})` : `Binary: installed ${newVersion || 'a new version (could not verify)'}`);console.log(migrationsLine);// #6317 (I2): upgrade owns no relaunch, so the supervisor proves data movement after it restarts serve and the workers.console.log(`Next: ${MOVEMENT_SUPERVISOR_STEP}`);@@ -556,10 +579,8 @@ function findBunInstallRootFromArgv(): string | null {function verifyUpgrade(): string {try {const output = execSync('gbrain --version', { encoding: 'utf-8', timeout: 10_000 }).trim();- console.log(`Upgrade complete. Now running: ${output}`);return output.replace(/^gbrain\s*/i, '').trim();} catch {- console.log('Upgrade complete. Could not verify new version.');return '';}}diff --git a/src/core/audit/self-upgrade-audit.ts b/src/core/audit/self-upgrade-audit.tsindex 876e1fc864..9cb7ca7fcf 100644--- a/src/core/audit/self-upgrade-audit.ts+++ b/src/core/audit/self-upgrade-audit.ts@@ -7,6 +7,8 @@* Privacy: records only versions + outcome + reason. No paths, no content.*/+import { readdirSync, readFileSync } from 'node:fs';+import { join } from 'node:path';import { createAuditWriter } from './audit-writer.ts';export interface SelfUpgradeAuditEvent {@@ -40,3 +42,37 @@ export function readRecentSelfUpgrades(days = 7, now?: Date): SelfUpgradeAuditEvexport function selfUpgradeAuditFilename(now?: Date): string {return writer.computeFilename(now);}++/**+ * #6828: every retained self-upgrade audit row, in ts order (all weekly files,+ * not the 2-week `readRecent` window): the known-bad recovery needs the swap+ * that recorded an entry, however old. Corrupt rows are skipped.+ */+export function readAllSelfUpgrades(): SelfUpgradeAuditEvent[] {+ const dir = writer.resolveDir();+ let files: string[];+ try {+ files = readdirSync(dir).filter((f) => /^self-upgrade-.*\.jsonl$/.test(f));+ } catch {+ return [];+ }+ const out: SelfUpgradeAuditEvent[] = [];+ for (const f of files) {+ let content: string;+ try {+ content = readFileSync(join(dir, f), 'utf8');+ } catch {+ continue;+ }+ for (const line of content.split('\n')) {+ if (!line) continue;+ try {+ const ev = JSON.parse(line) as SelfUpgradeAuditEvent;+ if (typeof ev.ts === 'string') out.push(ev);+ } catch {+ /* corrupt row */+ }+ }+ }+ return out.toSorted((a, b) => (a.ts < b.ts ? -1 : a.ts > b.ts ? 1 : 0));+}diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.tsindex c923743538..30f4ba2944 100644--- a/src/core/behavior-change-notice.ts+++ b/src/core/behavior-change-notice.ts@@ -692,6 +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.' },];/** 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 292fa12d7d..1ed98c80e5 100644--- a/src/core/cli-flag-registry.generated.ts+++ b/src/core/cli-flag-registry.generated.ts@@ -116,7 +116,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {'routing-eval': ['--brain', '--help', '--json', '--llm', '--skills-dir', '--source'],'salience': ['--brain', '--days', '--help', '--json', '--kind', '--limit', '--mcp-only', '--slug-prefix', '--source'],'schema': ['--alias', '--apply', '--as-filing-rules', '--brain', '--dims', '--expert', '--expert-routing', '--extractable', '--fields', '--force', '--help', '--inverse', '--json', '--kind', '--no-prefix', '--pack', '--page-type', '--prefix', '--primitive', '--schema-pack', '--since', '--source', '--source-id', '--target-type', '--to', '--with-db'],- 'self-upgrade': ['--brain', '--check-only', '--exit-code', '--ff-only', '--force', '--force-retry', '--help', '--json', '--markdown', '--migrate-only', '--no-autopilot-install', '--no-bun-floor-check', '--non-interactive', '--refresh-cache', '--refs', '--remediation-plan', '--source', '--swap-only', '--tags', '--version', '--yes'],+ 'self-upgrade': ['--apply', '--brain', '--check-only', '--clear-never-installed', '--exit-code', '--ff-only', '--force', '--force-retry', '--help', '--json', '--markdown', '--migrate-only', '--no-autopilot-install', '--no-bun-floor-check', '--non-interactive', '--refresh-cache', '--refs', '--remediation-plan', '--source', '--swap-only', '--tags', '--version', '--yes'],'serve': ['--access', '--add', '--adopt-columns', '--adopt-permissions', '--all-new', '--apply-rewrites', '--bind', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--budget-usd-per-day', '--client', '--days', '--delegated-namespace', '--delegated-slug-prefixes', '--enable-dcr', '--enable-dcr-insecure', '--expect', '--fail-fast', '--federated-read', '--grant-types', '--harness', '--help', '--http', '--id', '--if-version', '--json', '--log-full-params', '--migrate-legacy', '--min-trust', '--no-embedding', '--oauth-request', '--only', '--operations', '--path', '--pglite', '--port', '--prefer-postgres', '--print-admin-token', '--profile', '--provenance', '--public-url', '--read-sources', '--redirect-uri', '--refresh-operations', '--repair', '--reset-default', '--retry-failed', '--scopes', '--source', '--source-guard', '--sources', '--stdio-idle-timeout', '--suppress-bootstrap-token', '--surface', '--takes-holders', '--token', '--token-endpoint-auth-method', '--token-ttl', '--tools-json', '--url', '--usage', '--yes'],'setup': ['--auto', '--bearer-token-env-var', '--brain', '--break-lock', '--capture', '--dry-run', '--env', '--gbrain-bin', '--harness', '--header', '--help', '--http', '--install', '--issuer-url', '--json', '--mcp-only', '--mcp-url', '--name', '--no-capture', '--no-embedding', '--no-hooks', '--no-providers', '--oauth-client-id', '--oauth-client-secret', '--only', '--pglite', '--probe', '--providers', '--pure', '--remove', '--save', '--scope', '--source', '--surface', '--token', '--url', '--yes'],'skillify': ['--brain', '--description', '--dry-run', '--force', '--help', '--json', '--mutating', '--recent', '--skills-dir', '--source', '--strict', '--triggers', '--writes-pages', '--writes-to'],diff --git a/src/core/self-upgrade-recovery.ts b/src/core/self-upgrade-recovery.tsnew file mode 100644index 0000000000..23520ad1b8--- /dev/null+++ b/src/core/self-upgrade-recovery.ts@@ -0,0 +1,85 @@+/**+ * #6828 known-bad recovery. Before the fix, a swap that installed nothing+ * (`bun update` on a moving tag whose head was already installed) still+ * reported "swapped", the supervisor relaunched the SAME version, and the+ * boot reconcile recorded the attempted, never-installed version in+ * `self_upgrade.failed_versions`, so the auto channel skipped that release+ * forever. This module finds the entries the audit proves were never+ * installed. Clearing them is the operator step+ * `gbrain self-upgrade --clear-never-installed [--apply]`; doctor's+ * `self_upgrade_health` names its preview as the fix. File plane only.+ */++import { existsSync, readFileSync } from 'node:fs';+import { join } from 'node:path';+import { loadConfig } from './config.ts';+import { readAllSelfUpgrades } from './audit/self-upgrade-audit.ts';+import { CRASH_ON_LAUNCH_REASON_PREFIX, SWAPPED_REASON } from './self-upgrade.ts';++/** The preview and apply commands of the recovery. */+export const CLEAR_NEVER_INSTALLED_PREVIEW = ['gbrain', 'self-upgrade', '--clear-never-installed'];+export const CLEAR_NEVER_INSTALLED_APPLY = [...CLEAR_NEVER_INSTALLED_PREVIEW, '--apply'];++export interface NeverInstalledEntry {+ version: string;+ /** The version that ran both before the swap and after the relaunch. */+ running: string;+ /** When the swap reported "swapped" and when the relaunch recorded the entry. */+ swapped_at: string;+ recorded_at: string;+}++/**+ * 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.+ */+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,+): NeverInstalledEntry[] {+ 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);+ }+ return out;+}++/** The version the last real swap installed (`~/.gbrain/upgrade-state.json`), or null. */+function lastUpgradeTo(): string | 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;+ } catch {+ return null;+ }+}++/** The known-bad entries the audit proves were never installed, with the current list. */+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()) };+}+diff --git a/src/core/self-upgrade-swap.ts b/src/core/self-upgrade-swap.tsnew file mode 100644index 0000000000..b9aac681ce--- /dev/null+++ b/src/core/self-upgrade-swap.ts@@ -0,0 +1,90 @@+/**+ * 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:+ *+ * - 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 swap failed: record known-bad the version that was installed and+ * failed (the attempted one when no receipt says what was installed);+ * - 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).+ */++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';++export type AutopilotSwapResult = { relaunch: false } | { relaunch: true; installed: string };++/** The receipt file for the next swap, with any stale one removed. */+export function prepareSwapReceipt(): string {+ const path = gbrainPath('swap-receipt.json');+ try { unlinkSync(path); } catch { /* absent */ }+ return path;+}++/** 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);+ try { unlinkSync(receiptPath); } catch { /* absent */ }+ 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') {+ 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: `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.`);+ return { relaunch: false };+ }+ const installed = receipt?.installed && isNewerVersion(running, receipt.installed) ? receipt.installed : 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);+ fresh.self_upgrade = { ...(fresh.self_upgrade ?? {}), failed_versions: [...failed] };+ 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 });+ console.error(`[autopilot] self-upgrade swap failed; staying on ${running}.`);+ return { relaunch: false };+ }++ if (installed && installed !== latestVersion) {+ const fresh = loadConfig();+ if (fresh) {+ fresh.self_upgrade = { ...(fresh.self_upgrade ?? {}), attempting_version: installed };+ saveConfig(fresh);+ }+ }+ return { relaunch: true, installed: installed ?? latestVersion };+}diff --git a/src/core/self-upgrade.ts b/src/core/self-upgrade.tsindex 5fa047b43f..8a041efe16 100644--- a/src/core/self-upgrade.ts+++ b/src/core/self-upgrade.ts@@ -457,6 +457,53 @@ export function releaseRefreshLock(lockPath: string): void {}}+// ── Swap receipt (what `gbrain upgrade --swap-only` actually installed) ──────++/**+ * #6828: the autopilot channel names a file in this env var; `gbrain upgrade`+ * writes what its swap installed there. 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), and a no-op must never relaunch or record known-bad.+ */+export const SWAP_RECEIPT_ENV = 'GBRAIN_SWAP_RECEIPT';++/**+ * - `installed`: a newer version is on disk and passed the post-swap smoke.+ * - `not_installed`: the version did not change (the install step failed, or+ * succeeded without installing anything newer).+ * - `installed_broken`: a newer version is on disk and does not start.+ */+export interface SwapReceipt {+ outcome: 'installed' | 'not_installed' | 'installed_broken';+ from: string;+ /** What `gbrain --version` reported after the swap; null when unreadable. */+ installed: string | null;+}++/** Write the receipt when the caller asked for one. Best-effort. */+export function writeSwapReceipt(receipt: SwapReceipt): void {+ const path = process.env[SWAP_RECEIPT_ENV];+ if (!path) return;+ try {+ atomicWrite(path, JSON.stringify(receipt) + '\n');+ } catch {+ /* the channel falls back to the exit status */+ }+}++/** Read a receipt; null when missing or malformed (the channel then trusts the exit status). */+export function readSwapReceipt(path: string): SwapReceipt | null {+ try {+ const r = JSON.parse(readFileSync(path, 'utf8')) as Partial<SwapReceipt>;+ if (r.outcome !== 'installed' && r.outcome !== 'not_installed' && r.outcome !== 'installed_broken') return null;+ if (typeof r.from !== 'string') return null;+ const installed = typeof r.installed === 'string' && isValidVersionString(r.installed) ? r.installed : null;+ return { outcome: r.outcome, from: r.from, installed };+ } catch {+ return null;+ }+}+// ── Breadcrumb reconciliation (attribution for crash-on-launch) ──────────────/** The mutable slice of `config.self_upgrade` the autopilot channel manages. */@@ -524,6 +571,11 @@ export function reconcileBreadcrumb(return { state, transition: 'failed' };}+/** The audit reason the boot reconcile writes when it records a version known-bad (core/self-upgrade-recovery.ts matches on it, #6828). */+export const CRASH_ON_LAUNCH_REASON_PREFIX = 'crash-on-launch:';+/** The audit reason the channel writes when its swap installed a newer version and it exits for relaunch. */+export const SWAPPED_REASON = 'swapped; exiting for supervisor relaunch';+// ── Mode resolution (file plane; no DB on the hot path) ──────────────────────function normalizeMode(raw: unknown): SelfUpgradeMode | null {diff --git a/test/autopilot-unpublished-target-6828.test.ts b/test/autopilot-unpublished-target-6828.test.tsnew file mode 100644index 0000000000..099438622e--- /dev/null+++ b/test/autopilot-unpublished-target-6828.test.ts@@ -0,0 +1,237 @@+/**+ * #6828 / #6718: the auto channel targeted master's VERSION (unpublished,+ * ahead of the latest-stable tag the install follows), `bun update gbrain`+ * changed nothing, the swap still reported "swapped; exiting for supervisor+ * relaunch", and the relaunched (unchanged) binary recorded the never-installed+ * version known-bad, so the release it later became was never auto-installed.+ *+ * Drives the real `attemptAutopilotSelfUpgrade` and the real `gbrain upgrade+ * --swap-only` (runUpgrade) in spawned drivers on a stock Bun global install+ * of `github:garrytan/gbrain#latest-stable`, then the relaunch's+ * `reconcileSelfUpgradeAtBoot`. Bun resolves child PATH at process start, so+ * the `bun`, `git` and `gbrain` shims sit on the driver's startup PATH (see+ * test/autopilot-bun-floor.test.ts).+ *+ * Protects: the update check reads the published release (the latest-stable+ * tag), never master's VERSION; a swap that installs nothing newer is not a+ * swap (no relaunch, no last_upgrade overwrite, no JUST_UPGRADED breadcrumb,+ * no known-bad) and is retried at most once a day; a version that WAS+ * installed and then failed is still recorded known-bad, under the version+ * actually installed.+ */+import { afterAll, describe, expect, test } from 'bun:test';+import { existsSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { parseSemver } from '../src/core/semver.ts';+import { VERSION } from '../src/version.ts';++const REPO = join(import.meta.dir, '..');+const AUTOPILOT_TS = join(REPO, 'src', 'commands', 'autopilot.ts');+const UPGRADE_TS = join(REPO, 'src', 'commands', 'upgrade.ts');+const CLI_EXIT_TS = join(REPO, 'src', 'core', 'cli-force-exit.ts');+const v = parseSemver(VERSION)!;+/** Master's VERSION: stamped by the next PR, not yet tagged or released. */+const MASTER_AHEAD = `${v[0]}.${v[1]}.${v[2] + 1}.0`;+const dirs: string[] = [];+afterAll(() => { for (const d of dirs) rmSync(d, { recursive: true, force: true }); });++interface Harness { root: string; home: string; shims: string; argvLog: string; driver: string; bootDriver: string; bunInstall: string }++/**+ * A stock Bun global install following `spec`. `installed` is what `gbrain+ * --version` reports after `bun update` (VERSION = the no-op); `helpExit` is+ * the post-swap smoke's exit (non-zero = the installed release does not start).+ */+function harness(label: string, opts: { spec?: string; cache?: string } = {}): Harness {+ const root = mkdtempSync(join(tmpdir(), `gbrain-6828-${label}-`));+ dirs.push(root);+ const home = join(root, 'home');+ const dotG = join(home, '.gbrain');+ mkdirSync(dotG, { recursive: true });+ const hour = new Date().getUTCHours();+ writeFileSync(join(dotG, 'config.json'), JSON.stringify({+ engine: 'pglite',+ database_path: join(dotG, 'brain.pglite'),+ self_upgrade: { mode: 'auto', quiet_hours: { start: hour, end: (hour + 2) % 24, tz: 'UTC' } },+ }));+ if (opts.cache) writeFileSync(join(dotG, 'last-update-check'), `${opts.cache}\n`);++ const bunInstall = join(root, 'bunhome');+ const globalRoot = join(bunInstall, 'install', 'global');+ const pkgDir = join(globalRoot, 'node_modules', 'gbrain');+ mkdirSync(join(pkgDir, 'src'), { recursive: true });+ writeFileSync(join(globalRoot, 'package.json'), JSON.stringify({ dependencies: { gbrain: opts.spec ?? 'github:garrytan/gbrain#latest-stable' } }));+ writeFileSync(join(pkgDir, 'package.json'), JSON.stringify({ name: 'gbrain', repository: { url: 'git+https://github.com/garrytan/gbrain.git' } }));++ const driver = join(pkgDir, 'src', 'cli.ts');+ writeFileSync(driver, [+ 'const fetched: string[] = [];',+ 'globalThis.fetch = (async (url: unknown) => {',+ ' const u = String(url);',+ ' fetched.push(u);',+ ` if (u.endsWith('/master/VERSION')) return new Response(${JSON.stringify(`${MASTER_AHEAD}\n`)});`,+ ` if (u.endsWith('/latest-stable/VERSION')) return new Response(${JSON.stringify(`${VERSION}\n`)});`,+ " if (u.endsWith('/package.json')) return new Response(JSON.stringify({ version: process.env.FAKE_TARGET_VERSION, engines: { bun: '>=1.0.0' } }));",+ " return new Response('', { status: 404 });",+ '}) as typeof fetch;',+ 'const realExit = process.exit.bind(process);',+ "process.exit = ((code?: number) => { console.log('FETCHED ' + JSON.stringify(fetched)); console.log('EXIT_CALLED ' + code); realExit(code); }) as typeof process.exit;",+ `const { attemptAutopilotSelfUpgrade } = await import(${JSON.stringify(AUTOPILOT_TS)});`,+ `await attemptAutopilotSelfUpgrade({ kind: 'pglite', db: { query: async () => ({ rows: [] }) } } as never, 'pglite', ${JSON.stringify(join(root, 'autopilot.lock'))});`,+ "console.log('FETCHED ' + JSON.stringify(fetched));",+ "console.log('RETURNED');",+ '',+ ].join('\n'));+ // The supervisor's relaunch: the binary on disk boots and reconciles the breadcrumb.+ const bootDriver = join(pkgDir, 'src', 'boot.ts');+ writeFileSync(bootDriver, `const { reconcileSelfUpgradeAtBoot } = await import(${JSON.stringify(AUTOPILOT_TS)});\nreconcileSelfUpgradeAtBoot();\n`);+ // The real `gbrain upgrade` the channel shells out to, run from inside the global install.+ const upgradeDriver = join(pkgDir, 'src', 'upgrade-driver.ts');+ writeFileSync(upgradeDriver, [+ `const { runUpgrade } = await import(${JSON.stringify(UPGRADE_TS)});`,+ `const { _resetCliExitVerdictForTests, currentExitCode } = await import(${JSON.stringify(CLI_EXIT_TS)});`,+ '_resetCliExitVerdictForTests();',+ "await runUpgrade([...process.argv.slice(2), '--no-bun-floor-check']);",+ 'process.exit(currentExitCode());',+ '',+ ].join('\n'));++ const shims = join(root, 'bin');+ mkdirSync(shims);+ const argvLog = join(root, 'argv.log');+ writeFileSync(argvLog, '');+ // `bun update gbrain` on a moving tag whose head is already installed: exit 0, nothing changes.+ writeFileSync(join(shims, 'bun'), [+ '#!/usr/bin/env bash',+ `if [ "$1" = "update" ]; then printf 'bun %s\\n' "$*" >> "${argvLog}"; echo 'Checked 353 installs across 360 packages (no changes) [6.60s]'; exit 0; fi`,+ `echo "${Bun.version}"`,+ '',+ ].join('\n'), { mode: 0o755 });+ writeFileSync(join(shims, 'git'), `#!/usr/bin/env bash\ncase "$1" in ls-remote) echo "aaa\trefs/tags/v${VERSION}"; exit 0;; esac\nexit 1\n`, { mode: 0o755 });+ writeFileSync(join(shims, 'gbrain'), [+ '#!/usr/bin/env bash',+ `printf 'gbrain %s\\n' "$*" >> "${argvLog}"`,+ 'case "$1" in',+ ' --version) echo "gbrain ${FAKE_INSTALLED_VERSION}"; exit 0;;',+ ' --help) exit "${FAKE_HELP_EXIT:-0}";;',+ ` upgrade) shift; exec "${process.execPath}" "${upgradeDriver}" "$@";;`,+ 'esac',+ 'exit 0',+ '',+ ].join('\n'), { mode: 0o755 });+ return { root, home, shims, argvLog, driver, bootDriver, bunInstall };+}++async function run(h: Harness, script: string, env: Record<string, string> = {}) {+ const proc = Bun.spawn([process.execPath, script], {+ cwd: h.root,+ env: {+ PATH: `${h.shims}:/usr/bin:/bin`,+ HOME: h.root,+ GBRAIN_HOME: h.home,+ GBRAIN_AUDIT_DIR: join(h.root, 'audit'),+ BUN_INSTALL: h.bunInstall,+ FAKE_INSTALLED_VERSION: VERSION,+ FAKE_TARGET_VERSION: VERSION,+ GIT_CONFIG_NOSYSTEM: '1',+ GIT_TERMINAL_PROMPT: '0',+ ...(process.env.TMPDIR ? { TMPDIR: process.env.TMPDIR } : {}),+ ...env,+ },+ stdout: 'pipe',+ stderr: 'pipe',+ });+ const [out, err, code] = await Promise.all([new Response(proc.stdout).text(), new Response(proc.stderr).text(), proc.exited]);+ const auditDir = join(h.root, 'audit');+ const audit = existsSync(auditDir)+ ? readdirSync(auditDir).flatMap((f) => readFileSync(join(auditDir, f), 'utf8').trim().split('\n').filter(Boolean).map((l) => JSON.parse(l)))+ : [];+ const config = JSON.parse(readFileSync(join(h.home, '.gbrain', 'config.json'), 'utf8'));+ const cachePath = join(h.home, '.gbrain', 'last-update-check');+ return {+ code, out, err, audit,+ su: config.self_upgrade,+ calls: readFileSync(h.argvLog, 'utf8').split('\n').filter(Boolean),+ fetched: JSON.parse(/FETCHED (.*)/.exec(out)?.[1] ?? '[]') as string[],+ cache: existsSync(cachePath) ? readFileSync(cachePath, 'utf8').trim() : null,+ upgradeState: existsSync(join(h.root, '.gbrain', 'upgrade-state.json')),+ justUpgraded: existsSync(join(h.home, '.gbrain', 'just-upgraded-from')),+ };+}++describe('#6828: auto-update while master is ahead of latest-stable', () => {+ test('the exact field sequence: no unpublished target, no false swap, the next release is not blocklisted', async () => {+ const h = harness('sequence');+ const tick = await run(h, h.driver);+ expect(tick.code, tick.err).toBe(0);+ // The check follows the published release, never master's VERSION.+ expect(tick.fetched.some((u) => u.endsWith('/latest-stable/VERSION'))).toBe(true);+ expect(tick.fetched.some((u) => u.endsWith('/master/VERSION'))).toBe(false);+ expect(tick.cache).toBe(`UP_TO_DATE ${VERSION}`);+ expect(tick.out).toContain('RETURNED');+ expect(tick.out).not.toContain('EXIT_CALLED');+ expect(tick.calls.filter((c) => c.includes('update gbrain') || c.startsWith('gbrain upgrade'))).toEqual([]);+ expect(tick.audit.some((e) => e.reason === 'swapped; exiting for supervisor relaunch')).toBe(false);++ const boot = await run(h, h.bootDriver);+ expect(boot.code, boot.err).toBe(0);+ expect(boot.su.failed_versions).toBeUndefined();+ expect(boot.su.attempting_version).toBeUndefined();+ expect(boot.audit.some((e) => e.outcome === 'failed')).toBe(false);+ }, 90_000);++ test('a swap that installs nothing newer is held: no relaunch, no known-bad, no last_upgrade, retried after a day', async () => {+ // A marker naming a version the install's channel does not have yet (a cache+ // an older binary wrote from master's VERSION, or a tag that moved after the check).+ const h = harness('noop', { cache: `UPGRADE_AVAILABLE ${VERSION} ${MASTER_AHEAD}` });+ const tick = await run(h, h.driver, { FAKE_TARGET_VERSION: MASTER_AHEAD });+ expect(tick.code, tick.err).toBe(0);+ expect(tick.calls).toContain('bun update gbrain');+ expect(tick.out).toContain('RETURNED');+ expect(tick.out).not.toContain('EXIT_CALLED');+ expect(tick.out).not.toContain('Upgrade complete');+ expect(tick.upgradeState).toBe(false);+ expect(tick.justUpgraded).toBe(false);+ expect(tick.su.attempting_version).toBeUndefined();+ expect(tick.su.failed_versions).toBeUndefined();+ expect(typeof tick.su.last_check_ts).toBe('number');+ expect(tick.audit.some((e) => e.reason === 'swapped; exiting for supervisor relaunch')).toBe(false);+ expect(tick.audit.at(-1)).toMatchObject({ channel: 'autopilot', action: 'apply', outcome: 'skipped', latest: MASTER_AHEAD, current: VERSION });+ expect(tick.audit.at(-1).reason).toContain('nothing newer was installed');++ const again = await run(h, h.driver, { FAKE_TARGET_VERSION: MASTER_AHEAD });+ expect(again.calls.filter((c) => c === 'bun update gbrain')).toHaveLength(1);+ expect(again.su.failed_versions).toBeUndefined();++ const boot = await run(h, h.bootDriver);+ expect(boot.su.failed_versions).toBeUndefined();+ }, 90_000);++ test('an exact-tag pin in auto mode (bun update keeps the pin) is held, not known-bad', async () => {+ const h = harness('pin', { spec: `github:garrytan/gbrain#v${VERSION}`, cache: `UPGRADE_AVAILABLE ${VERSION} ${MASTER_AHEAD}` });+ const tick = await run(h, h.driver, { FAKE_TARGET_VERSION: MASTER_AHEAD });+ expect(tick.out).not.toContain('EXIT_CALLED');+ expect(tick.su.failed_versions).toBeUndefined();+ expect(tick.su.attempting_version).toBeUndefined();+ expect(tick.audit.at(-1)).toMatchObject({ action: 'apply', outcome: 'skipped', latest: MASTER_AHEAD });+ }, 90_000);++ test('a release that was installed and does not start is still known-bad, under the installed version', async () => {+ const h = harness('broken', { cache: `UPGRADE_AVAILABLE ${VERSION} ${MASTER_AHEAD}` });+ const tick = await run(h, h.driver, { FAKE_TARGET_VERSION: MASTER_AHEAD, FAKE_INSTALLED_VERSION: MASTER_AHEAD, FAKE_HELP_EXIT: '1' });+ expect(tick.out).not.toContain('EXIT_CALLED');+ expect(tick.su.failed_versions).toEqual([MASTER_AHEAD]);+ expect(tick.su.attempting_version).toBeUndefined();+ 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 () => {+ 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');+ expect(tick.su.attempting_version).toBe(MASTER_AHEAD);+ expect(tick.upgradeState).toBe(true);+ expect(tick.audit.at(-1)).toMatchObject({ action: 'apply', outcome: 'applied', reason: 'swapped; exiting for supervisor relaunch' });+ }, 90_000);+});diff --git a/test/check-update-refresh.serial.test.ts b/test/check-update-refresh.serial.test.tsindex 7669ec7973..9a26cd255a 100644--- a/test/check-update-refresh.serial.test.ts+++ b/test/check-update-refresh.serial.test.ts@@ -34,7 +34,7 @@ function bump(kind: 'minor' | 'patch' | 'micro'): string {function stubVersionFetch(body: string | null, status = 200): void {globalThis.fetch = (async (url: any) => {const u = String(url);- if (u.includes('/gbrain/master/VERSION')) {+ if (u.includes('/gbrain/latest-stable/VERSION')) {if (body === null) throw new Error('network down');return new Response(body, { status });}diff --git a/test/helpers/source-surface.ts b/test/helpers/source-surface.tsindex f89bd7dfe7..48ebec3d58 100644--- a/test/helpers/source-surface.ts+++ b/test/helpers/source-surface.ts@@ -95,6 +95,8 @@ export const SOURCE_SURFACES = {'src/commands/autopilot-daemon.ts','src/commands/autopilot-dispatch.ts','src/commands/autopilot-probes.ts',+ // #6828: the self-upgrade swap's outcome handling, moved into core.+ 'src/core/self-upgrade-swap.ts',],dirs: ['src/commands/autopilot'],},diff --git a/test/self-upgrade-checkonly.serial.test.ts b/test/self-upgrade-checkonly.serial.test.tsindex f443a66a4e..c6f49eb5ba 100644--- a/test/self-upgrade-checkonly.serial.test.ts+++ b/test/self-upgrade-checkonly.serial.test.ts@@ -31,7 +31,7 @@ function microBump(): string {function stub(tag: string | null, changelog: string): void {globalThis.fetch = (async (url: any) => {const u = String(url);- if (u.includes('/gbrain/master/VERSION')) {+ if (u.includes('/gbrain/latest-stable/VERSION')) {if (tag === null) throw new Error('network down');return new Response(tag + '\n', { status: 200 });}@@ -65,7 +65,7 @@ describe('self-upgrade --check-only surfaces what you get', () => {const out = JSON.parse(captured.join('\n'));expect(out.update_available).toBe(true);expect(out.latest_version).toBe(latest);- expect(out.release_url).toBe('https://github.com/garrytan/gbrain/blob/master/CHANGELOG.md');+ expect(out.release_url).toBe('https://github.com/garrytan/gbrain/blob/latest-stable/CHANGELOG.md');expect(out.changelog_diff).toContain('Shiny new thing');});diff --git a/test/self-upgrade-never-installed-6828.test.ts b/test/self-upgrade-never-installed-6828.test.tsnew file mode 100644index 0000000000..ebda281c67--- /dev/null+++ b/test/self-upgrade-never-installed-6828.test.ts@@ -0,0 +1,141 @@+/**+ * #6828 recovery: installs that already recorded a never-installed version+ * known-bad. Before the fix, a swap that installed nothing reported+ * "swapped", the supervisor relaunched the same version, and the boot+ * reconcile put the attempted version in `self_upgrade.failed_versions`, so+ * the auto channel never installed that release once it was published.+ *+ * Protects: `neverInstalledFailedVersions` clears only entries the audit+ * proves were never installed (the swap row and the relaunch's+ * crash-on-launch row ran the same version; the version never ran; the last+ * recorded upgrade did not install it); `gbrain self-upgrade+ * --clear-never-installed` previews by default and `--apply` removes exactly+ * those entries; doctor's self_upgrade_health names the preview as its fix+ * with the apply as the next step. The audit rows below are the strings the+ * pre-fix channel wrote (the field sequence in #6828).+ */+import { describe, expect, spyOn, test } from 'bun:test';+import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { checkSelfUpgradeHealth } from '../src/commands/doctor.ts';+import { runSelfUpgrade } from '../src/commands/self-upgrade.ts';+import { logSelfUpgrade } from '../src/core/audit/self-upgrade-audit.ts';+import { neverInstalledFailedVersions } from '../src/core/self-upgrade-recovery.ts';+import { withEnv } from './helpers/with-env.ts';++const A = '0.60.257.0';+const B = '0.60.258.0';+const C = '0.60.259.0';++/** The pre-fix channel's rows for one no-op "swap" from `running` to `attempted`, minutes apart. */+function noOpSwapRows(running: string, attempted: string, hour: number) {+ const at = (m: number) => `2026-10-16T0${hour}:0${m}:00.000Z`;+ return [+ { ts: at(1), channel: 'autopilot', action: 'apply', current: running, latest: attempted, reason: `auto-upgrading ${running} -> ${attempted}` },+ { ts: at(2), channel: 'autopilot', action: 'apply', current: running, latest: attempted, outcome: 'applied', reason: 'swapped; exiting for supervisor relaunch' },+ { ts: at(3), channel: 'autopilot', action: 'apply', current: running, latest: attempted, outcome: 'failed', reason: 'crash-on-launch: running version is not at or past the attempted version (recorded known-bad)' },+ { ts: at(4), channel: 'autopilot', action: 'known_bad', current: running, latest: attempted, outcome: 'skipped', reason: `${attempted} previously failed; not retrying` },+ ];+}++describe('neverInstalledFailedVersions (pure)', () => {+ test('the #6828 field sequences: both never-installed entries are proven', () => {+ 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([+ { 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]);+ });++ 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([]);+ // 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([]);+ // 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([]);+ // The crash-on-launch row with no swap row before it.+ expect(neverInstalledFailedVersions([B], [rows[2]], null)).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. */+async function withRecoveryHome(fn: (ctx: { failedVersions: () => string[]; run: (args: string[]) => Promise<string> }) => Promise<void>): Promise<void> {+ const dir = mkdtempSync(join(tmpdir(), 'gbrain-6828-recover-'));+ const log = spyOn(console, 'log').mockImplementation(() => {});+ try {+ await withEnv({ GBRAIN_HOME: dir, GBRAIN_AUDIT_DIR: join(dir, 'audit'), HOME: dir, GBRAIN_SELF_UPGRADE_MODE: undefined }, async () => {+ 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' } }));+ 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({+ failedVersions: () => JSON.parse(readFileSync(join(dir, '.gbrain', 'config.json'), 'utf8')).self_upgrade.failed_versions,+ run: async (args) => {+ log.mockClear();+ await runSelfUpgrade(args);+ return log.mock.calls.map((c) => c.map(String).join(' ')).join('\n');+ },+ });+ });+ } finally {+ log.mockRestore();+ rmSync(dir, { recursive: true, force: true });+ }+}++describe('gbrain self-upgrade --clear-never-installed and doctor', () => {+ test('doctor names the preview as the fix and the apply as the next step', async () => {+ await withRecoveryHome(async () => {+ const c = checkSelfUpgradeHealth();+ expect(c.status).toBe('warn');+ expect(c.message).toContain(`skips ${B} as known-bad`);+ expect(c.message).toContain('never installed');+ const fix = c.fix as { argv: string[]; then?: { argv: string[] } };+ expect(fix.argv).toEqual(['gbrain', 'self-upgrade', '--clear-never-installed', '--json']);+ expect(fix.then?.argv).toEqual(['gbrain', 'self-upgrade', '--clear-never-installed', '--apply']);+ });+ });++ test('the preview writes nothing; --apply removes exactly the proven entry; doctor clears', async () => {+ await withRecoveryHome(async ({ failedVersions, run }) => {+ const preview = JSON.parse(await run(['--clear-never-installed', '--json']));+ expect(preview.never_installed.map((e: { version: string }) => e.version)).toEqual([B]);+ expect(preview.never_installed[0]).toMatchObject({ running: A });+ expect(preview.kept).toEqual([UNPROVEN]);+ expect(preview.applied).toBe(false);+ expect(preview.next.argv).toEqual(['gbrain', 'self-upgrade', '--clear-never-installed', '--apply']);+ expect(failedVersions()).toEqual([B, UNPROVEN]);++ const human = await run(['--clear-never-installed']);+ expect(human).toContain(`${B}: the swap at 2026-10-16T05:02:00.000Z left ${A} running`);+ expect(human).toContain('Clear them: gbrain self-upgrade --clear-never-installed --apply');+ expect(failedVersions()).toEqual([B, UNPROVEN]);++ expect(await run(['--clear-never-installed', '--apply'])).toContain('Cleared known-bad versions that were never installed:');+ expect(failedVersions()).toEqual([UNPROVEN]);+ expect(checkSelfUpgradeHealth().message).not.toContain('never installed');++ expect(JSON.parse(await run(['--clear-never-installed', '--apply', '--json']))).toMatchObject({ never_installed: [], kept: [UNPROVEN], applied: false });+ });+ });+});diff --git a/test/upgrade-exact-tag-pin.test.ts b/test/upgrade-exact-tag-pin.test.tsindex 2e0b9337e3..ce9d27197c 100644--- a/test/upgrade-exact-tag-pin.test.ts+++ b/test/upgrade-exact-tag-pin.test.ts@@ -16,10 +16,11 @@ import { tmpdir } from 'os';import { bunGlobalExactTagPin, bunReinstallCommand } from '../src/commands/upgrade.ts';import { VERSION } from '../src/version.ts';+import { upgradeErrorResolved } from '../src/commands/doctor.ts';const REPO = resolve(import.meta.dir, '..');-async function runBareUpgrade(spec: string, observedVersion: string): Promise<{ home: string; exitCode: number; stdout: string; stderr: string }> {+async function runBareUpgrade(spec: string, observedVersion: string, cache?: string): Promise<{ home: string; exitCode: number; stdout: string; stderr: string }> {const home = mkdtempSync(join(tmpdir(), 'gbrain-5311-'));const bin = join(home, 'bin');mkdirSync(bin);@@ -32,6 +33,10 @@ async function runBareUpgrade(spec: string, observedVersion: string): Promise<{chmodSync(join(bin, 'git'), 0o755);chmodSync(join(bin, 'bun'), 0o755);chmodSync(join(bin, 'gbrain'), 0o755);+ if (cache) {+ mkdirSync(join(home, '.gbrain'), { recursive: true });+ writeFileSync(join(home, '.gbrain', 'last-update-check'), `${cache}\n`);+ }const globalRoot = join(home, '.bun', 'install', 'global');const pkgDir = join(globalRoot, 'node_modules', 'gbrain');mkdirSync(pkgDir, { recursive: true });@@ -83,6 +88,27 @@ describe('#5311 bare upgrade on an exact-tag pin', () => {}}, 60_000);+ test('#6718: with no newer published tag, the hint and the ledger never name an unpublished version', async () => {+ const v = VERSION.split('.').map(Number);+ const unpublished = `${v[0]}.${v[1]}.${v[2] + 1}.0`;+ // A fresh marker naming master's VERSION (what an older binary's check wrote); no tag exists for it.+ const r = await runBareUpgrade(`github:garrytan/gbrain#v${VERSION}`, VERSION, `UPGRADE_AVAILABLE ${VERSION} ${unpublished}`);+ try {+ expect(r.exitCode).toBe(1);+ expect(r.stderr).not.toContain(unpublished);+ const errors = readFileSync(join(r.home, '.gbrain', 'upgrade-errors.jsonl'), 'utf-8').trim().split('\n').map(l => JSON.parse(l));+ const row = errors.find(e => e.phase === 'verify-pin');+ expect(row.to_version).toBe('latest');+ expect(row.hint).not.toContain(unpublished);+ // The record clears once the binary moves past the version it failed from.+ expect(upgradeErrorResolved(row.to_version, VERSION, true, row.from_version)).toBe(false);+ expect(upgradeErrorResolved(row.to_version, unpublished, true, row.from_version)).toBe(true);+ expect(upgradeErrorResolved(row.to_version, unpublished, false, row.from_version)).toBe(false);+ } finally {+ rmSync(r.home, { recursive: true, force: true });+ }+ }, 60_000);+test('every reinstall hint removes the global package before adding the tag (#5034, B-NEW-5)', () => {// #6662: a tag reinstall first proves the tag exists, so a missing tag stops before the removal.expect(bunReinstallCommand('#v0.60.1.0')).toBe('git ls-remote --exit-code --tags https://github.com/garrytan/gbrain refs/tags/v0.60.1.0 && bun remove -g gbrain && bun add -g github:garrytan/gbrain#v0.60.1.0');