Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(upgrade): gate every swap on the target release's Bun floor (#5855)
garrytanb4fed9a75910
diff --git a/docs/architecture/key-files/commands-6.md b/docs/architecture/key-files/commands-6.mdindex 4874d0dd9f..5e5ca2b765 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`; 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`. 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.-- `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. Tests: `upgrade-migration-outcome.serial.test.ts`, `upgrade-no-autopilot.serial.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. 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). Tests: `upgrade-migration-outcome.serial.test.ts`, `upgrade-no-autopilot.serial.test.ts`, `upgrade-bun-link-arc.serial.test.ts`.- `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 6031af254a..24f3fd3fc1 100644--- a/docs/architecture/key-files/core-utilities-2.md+++ b/docs/architecture/key-files/core-utilities-2.md@@ -11,7 +11,8 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/core/restore-target.ts` -- `resolveRestoreTarget(engine, source, repo)`: the source and repo `gbrain export --restore-only` restores, shared with `gbrain storage status` so its printed restore command restores exactly the files it lists. An explicit source (already resolved) wins; a repo without a source selects the one active source registered at that exact path, refuses a repo registered only to an archived source, else selects the only active source; neither selects the flagless resolver chain's source and its `local_path` (the legacy `sync.repo_path` answers for `default` only). `restoreFilePath(repo, slug, sourcePath, sourcePathBytes, slugRootMode)` is the file whose absence makes the restore write a page: the recorded `source_path` resolved in the repo in the source's slug-root mode (`scannerSlugRootMode`), else `<slug>.md`; an over-long or unsafe recorded path throws. Refusals throw `RestoreTargetError`; resolver and database errors propagate unchanged.-- `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`).+- `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.serial.test.ts`, `upgrade-bun-link-arc.serial.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 25890b25a1..caf4476c9a 100644--- a/docs/guides/upgrades-auto-update.md+++ b/docs/guides/upgrades-auto-update.md@@ -34,7 +34,7 @@ construction. The behavior is governed by one file-plane config key,| Mode | Behavior | Who it's for ||------|----------|--------------|| `notify` (default) | Emit the marker + a 4-option prompt; never apply without confirmation. | Interactive installs / anyone with a human in the loop. |-| `auto` (opt-in) | Apply silently, but ONLY during quiet hours, ONLY when the brain is idle, doctor-gated, and never re-trying a known-bad version. | Headless / always-on installs (autopilot daemon, the `gbrain serve` host). |+| `auto` (opt-in) | Apply silently, but ONLY during quiet hours, ONLY when the brain is idle, doctor-gated, never re-trying a known-bad version, and never installing a release the host's Bun cannot start ([Bun floor](#bun-floor)). | Headless / always-on installs (autopilot daemon, the `gbrain serve` host). || `off` | Never check. | Air-gapped / pinned installs. |Enable hands-off upgrades on an always-on install with one line:@@ -57,6 +57,57 @@ action on the user's local sleep window — is owned by[quiet-hours.md](quiet-hours.md); this doc only covers the self-upgradehook into it.+### Bun floor++A source (bun-link) or package install runs the new release on the host's+Bun, and a release refuses to start on a Bun below its `engines.bun` floor.+So before swapping, `gbrain upgrade`, `gbrain self-upgrade` and the autopilot+channel read the target's floor and compare it with the lower of the `bun` on+PATH and the Bun the running process uses:++- **bun-link clone:** `git fetch`, then `package.json` at the fetched upstream+ commit; the swap fast-forwards to exactly that commit+ (`git merge --ff-only <sha>`), so a floor raised upstream after the check is+ not installed unchecked.+- **global package (`bun`) and ClawHub:** `package.json` at the ref the+ install's `github:` spec names (the default branch when unpinned) on+ raw.githubusercontent.com.+- **compiled binary:** exempt; it carries its own Bun.++When the floor is above the host's Bun, a manual upgrade refuses and changes+nothing (exit 78):++```+gbrain <target> requires Bun >=<floor>; bun on PATH (<path>) is <found>. Fix: bun upgrade, then gbrain upgrade. Docs: docs/guides/upgrades-auto-update.md#bun-floor+```++Run `bun upgrade`, then `gbrain upgrade` again. When the floor cannot be read+(offline, no upstream branch, or a floor not of the form `>=X.Y.Z`), the+refusal names the read that failed; after checking the target yourself,+`gbrain upgrade --no-bun-floor-check` (or `gbrain self-upgrade+--no-bun-floor-check`) upgrades without the check. The override is for manual+upgrades only; autopilot never passes it.++The autopilot channel holds instead of refusing: the tick records an+`unsupported_runtime` audit row, `gbrain doctor` reports+`Auto-upgrade to <target> held: …` under `self_upgrade_health` with the same+fix line, and the target is not marked known-bad, so the first quiet-hours+tick after `bun upgrade` applies it (an unreadable floor is retried on the+next tick). A swap that `gbrain upgrade` itself refuses for the floor (for+example, upstream raised it after the channel's check) is a hold too.++After the swap, `gbrain upgrade` runs `gbrain --help` (a command that passes+the startup Bun check, unlike `--version`). If the new release does not+start, the upgrade exits non-zero and prints recovery: `bun upgrade`, then+`gbrain post-upgrade`; or return to the previous release with+`git -C <clone> checkout <previous sha> && bun install` (bun-link) or+`bun install -g github:garrytan/gbrain#v<previous>` (package). Nothing is+rolled back automatically, and the autopilot channel records that version as+failed.++Hosts still running a release from before this check do not run it, so a Bun+floor raise reaches them only after they have upgraded past this release.+`gbrain config set self_upgrade.<key>` writes `~/.gbrain/config.json` (thefile plane every self-upgrade reader uses) and refuses a value the readerswould ignore: an unknown key or mode, a quiet-hours window with an hourdiff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsvindex 7a8df14bb3..3b973d377e 100644--- a/scripts/module-size-limits.tsv+++ b/scripts/module-size-limits.tsv@@ -4,7 +4,7 @@# the same commit as any peel (the guard fails on >50 lines of stale slack).# Columns: path max_lines policy notesrc/cli.ts 3202 ratchet +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5433: list_pages TSV cell escaping in formatResult-src/commands/autopilot.ts 1637 ratchet refactor wave 1 split target (W4 autopilot, cut line); ceiling rationale: docs/architecture/key-files/commands-1.md entry for src/commands/autopilot.ts; +2 fix wave 5: nosemgrep justifications on the per-brain job launchctl/systemctl calls (#5195); +2 #5813: boot reconcile names attempted and running versions in log + audit+src/commands/autopilot.ts 1639 ratchet refactor wave 1 split target (W4 autopilot, cut line); ceiling rationale: docs/architecture/key-files/commands-1.md entry for src/commands/autopilot.ts; +2 fix wave 5: nosemgrep justifications on the per-brain job launchctl/systemctl calls (#5195); +2 #5813: boot reconcile names attempted and running versions in log + audit; +2 #5855: Bun floor gate before the swap and the swap-refusal hold (logic in core/bun-floor.ts)src/commands/doctor.ts 653 ratchet refactor wave 1 split target (W4 doctor); ceiling rationale: docs/architecture/key-files/commands-2.md entry for src/commands/doctor.tssrc/commands/embed.ts 2190 ratchet lowered v0.46.26.0: embedBatchWithBackoff + retry cluster peeled to core/embed-retry.ts (core/commands layering fix); grown wave-g (#4530): per-model input-limit wiring; wave-k #3622 reimpl: --stale zero-progress failure quarantine; +29 #4668 (#4530): oversize-heal call sites in both --stale drains — kept low by peeling the healed-row remap to core/embed-oversize-heal.ts (shared with embed-stale.ts); +35 #4647 (refs #4599): per-tick timeout+abort on the single-flight lock heartbeat refresh (interval deliberately NOT unref'd); +122 refs #4599: stall-watchdog race around the drain + shared idempotent flushAndRelease + CLI stall exit mapping (watchdog machinery itself lives in core/embed-stall.ts); +12: adversarial-review hardening (healed_splits progress key + heal-tick comment); #5105: guarded derived projection preparation and read seals; #5105: conditional embedding installer wiring; archived eligibility: active-only dispatch with honest stranded-work reporting; explicit archived admission: live-source snapshots and honest refused-installation failures; +2 fw3: embed --stale --images dispatch (sweep lives in core/embed-stale-images.ts); +5 #5289: dry run reports restamp-only chunks apart from chunks to embed (count lives in core/embedding-invalidation.ts); +6 #4616: keep a partially refused batch in embedPageTexts and name the recovery command in failure samples (guard lives in core/ai/embedding-guard.ts); +5 #5226: embed summary counts distinct pages; +3 #5804: null projection snapshot counted as a failure with one batch summary in embed --stalesrc/commands/extract-conversation-facts.ts 2182 ratchet grown v0.46.x per-provider gateway-unavailable copy; grown wave-g (#4482): expected budget/deadline caps classified apart from error halts; wave-k: save-time resolution caller (#4052/#3729 — supersedes wave-g's per-row resolveEntitySlug mapper); +1: key-aware llm-fallback default (#3813); +1: pricingOverrides wiring into the owned BudgetTracker (#4633 adoption); +3: #4869 snapshot-mismatch counts as pages_failed; merged reliability/shared-skills source integration; +19: additive skip reasons and model-free dry-run (#5364); +21 #5757: managed extraction buffers a page's rows and replaces the prior batch in one coordinator transaction (replacement helper lives in core/persistence/derived-facts.ts); +18 #5823: result diagnostics, strict explicit-cap parsing and CLI recovery/help; default-cap decision lives in facts/conversation-budget.ts; +18 fix wave 7 (#5704, #5448): --json envelope on stdout (parser flag, help line, summary block gated behind the human-output branch)diff --git a/src/commands/autopilot.ts b/src/commands/autopilot.tsindex 2856d3c9ec..a22d99bb37 100644--- a/src/commands/autopilot.ts+++ b/src/commands/autopilot.ts@@ -34,6 +34,7 @@ import { VERSION } from '../version.ts';import {canSelfUpdate,decideSelfUpgrade,+ gateOnTargetRuntime,isCacheFresh,readUpdateCache,reconcileBreadcrumb,@@ -41,7 +42,8 @@ import {resolveSelfUpgradeMode,} from '../core/self-upgrade.ts';import { logSelfUpgrade } from '../core/audit/self-upgrade-audit.ts';-import { detectInstallMethod } from './upgrade.ts';+import { BUN_FLOOR_EXIT_CODE, BUN_FLOOR_FIX, 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';import { relativeSourceLocalPathSkipWarning } from '../core/sources-load.ts';@@ -444,7 +446,7 @@ export async function attemptAutopilotSelfUpgrade(const verdict = evaluateQuietHours(resolveQuietHoursWindow(cfg.self_upgrade?.quiet_hours), new Date());const installMethod = detectInstallMethod();- const decision = decideSelfUpgrade({+ let decision = decideSelfUpgrade({mode: 'auto',channel: 'autopilot',currentVersion: VERSION,@@ -455,9 +457,13 @@ export async function attemptAutopilotSelfUpgrade(canSelfUpdate: canSelfUpdate(installMethod),throttledByInterval: false, // cache TTL is the fetch throttle});+ // #5855: never swap in a release the host's Bun cannot start (a binary carries its own Bun).+ if (decision.action === 'apply' && installMethod !== 'binary') {+ decision = gateOnTargetRuntime(decision, await readInstallTargetFloor(installMethod), readHostBun());+ }if (decision.action !== 'apply') {- if (['unsupported_install', 'known_bad'].includes(decision.action)) {+ if (['unsupported_install', 'known_bad', 'unsupported_runtime'].includes(decision.action)) {logSelfUpgrade({channel: 'autopilot',action: decision.action,@@ -485,21 +491,18 @@ export async function attemptAutopilotSelfUpgrade(});} 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 ?? []);- failed.add(latestVersion);+ if (!held) failed.add(latestVersion);fresh.self_upgrade = { ...(fresh.self_upgrade ?? {}), failed_versions: [...failed] };delete fresh.self_upgrade.attempting_version;saveConfig(fresh);}- logSelfUpgrade({- channel: 'autopilot',- action: 'apply',- current: VERSION,- latest: latestVersion,- outcome: 'failed',- error: e instanceof Error ? e.message : String(e),- });+ 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;}diff --git a/src/commands/doctor/checks/upgrade-health.ts b/src/commands/doctor/checks/upgrade-health.tsindex 4db360be6d..01ea93f3e1 100644--- a/src/commands/doctor/checks/upgrade-health.ts+++ b/src/commands/doctor/checks/upgrade-health.ts@@ -11,6 +11,9 @@ 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 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';@@ -44,11 +47,24 @@ export function upgradeErrorResolved(return true; // equal → the failed target version is now running}+/**+ * #5855: the auto-upgrade the newest autopilot event holds for the Bun floor,+ * while its target is still newer than the running binary (a later apply, or+ * a manual upgrade to the target, ends the hold); null otherwise. `recent` is+ * in ts order.+ */+function heldAutoUpgrade(recent: SelfUpgradeAuditEvent[], runningVersion: string): SelfUpgradeAuditEvent | null {+ const last = recent.filter((e) => e.channel === 'autopilot').at(-1);+ if (last?.action !== ('unsupported_runtime' satisfies SelfUpgradeAction) || !last.latest) return null;+ return isNewerVersion(runningVersion, last.latest) ? last : null;+}+/*** v0.42 self_upgrade_health. Surfaces the self-upgrade mode, whether an update- * is pending (from the cache), and any recent failed auto-upgrade attempts.- * File-plane only (no DB) so it runs on thin clients. Three-state: warn on- * recent failures, otherwise ok.+ * is pending (from the cache), an auto-upgrade held for the Bun floor (#5855),+ * and any recent failed auto-upgrade attempts. File-plane only (no DB) so it+ * runs on thin clients. Warn on a held auto-upgrade or recent failures,+ * otherwise ok.*/export function checkSelfUpgradeHealth(): Check {try {@@ -81,7 +97,17 @@ export function checkSelfUpgradeHealth(): Check {parts.push(`skipping known-bad: ${failedVersions.join(', ')}`);}- const recent = readRecentSelfUpgrades(7) as Array<{ outcome?: string; error?: string; latest?: string | null }>;+ // 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));+ const held = heldAutoUpgrade(recent, GBRAIN_BINARY_VERSION);+ if (held) {+ return {+ name: 'self_upgrade_health',+ status: 'warn',+ message: `Auto-upgrade to ${held.latest} held: ${held.reason ?? 'Bun floor not met'} (${parts.join('; ')}).`,+ };+ }const failures = recent.filter((e) => e.outcome === 'failed');if (failures.length > 0) {const last = failures[failures.length - 1];diff --git a/src/commands/self-upgrade.ts b/src/commands/self-upgrade.tsindex f4859b8474..e0c908279b 100644--- a/src/commands/self-upgrade.ts+++ b/src/commands/self-upgrade.ts@@ -5,7 +5,7 @@ import { detectInstallMethod, runUpgrade } from './upgrade.ts';import { writeUpdateCache } from '../core/self-upgrade.ts';/**- * `gbrain self-upgrade [--check-only] [--force] [--json]`+ * `gbrain self-upgrade [--check-only] [--force] [--json] [--no-bun-floor-check]`** The universal substrate every agent ecosystem (Codex / Claude Code / Hermes /* OpenClaw / Perplexity-server) can call to stay current. The CLI startup hook@@ -16,17 +16,20 @@ import { writeUpdateCache } from '../core/self-upgrade.ts';* --check-only Report whether an upgrade is available; never apply.* --force Apply even if not behind (re-run the install-method swap).* --json Machine-readable output for the check.+ * --no-bun-floor-check Passed through to `gbrain upgrade` (#5855).*/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]\n\n' ++ 'Usage: gbrain self-upgrade [--check-only] [--force] [--json] [--no-bun-floor-check]\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' +' --check-only Report whether an upgrade is available; do not apply.\n' +' --force Apply even when not behind.\n' +- ' --json Machine-readable output (with --check-only).',+ ' --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',);return;}@@ -101,7 +104,7 @@ export async function runSelfUpgrade(args: string[]): Promise<void> {// Apply: delegate to the hardcoded upgrade path (full swap + post-upgrade).// Pass the fetched target so runUpgrade can detect exact-tag no-op// "upgrades" instead of reporting false success (#4366).- await runUpgrade([], {+ await runUpgrade(args.filter((a) => a === '--no-bun-floor-check'), {targetVersion: latest && isValidVersionString(latest) ? latest : undefined,});}diff --git a/src/commands/upgrade.ts b/src/commands/upgrade.tsindex 805505d87f..6c3dc6098f 100644--- a/src/commands/upgrade.ts+++ b/src/commands/upgrade.ts@@ -1,4 +1,4 @@-import { execSync, execFileSync } from 'child_process';+import { execSync, execFileSync, spawnSync } from 'child_process';import { existsSync, readFileSync, writeFileSync, mkdirSync, appendFileSync, realpathSync } from 'fs';import { basename, join, dirname, resolve } from 'path';import { parseSemver, semverGt } from '../core/semver.ts';@@ -6,6 +6,15 @@ import { setCliExitVerdict } from '../core/cli-force-exit.ts';import { VERSION } from '../version.ts';import { migrationLedgerSummary } from '../core/migration-ledger.ts';import { MIGRATIONS_RUNNING_EXIT_CODE, readMigrationLockHolder } from '../core/migration-orchestration-lock.ts';+import {+ BUN_FLOOR_EXIT_CODE,+ evaluateBunFloor,+ globalGbrainSpec,+ readBunLinkTarget,+ readHostBun,+ readPackageTarget,+ type TargetFloor,+} from '../core/bun-floor.ts';const GBRAIN_GITHUB_REPO = 'garrytan/gbrain';@@ -29,7 +38,7 @@ export function assessUpgradeOutcome(export async function runUpgrade(args: string[], opts: { targetVersion?: string } = {}) {if (args.includes('--help') || args.includes('-h')) {- console.log('Usage: gbrain upgrade [--swap-only] [--no-autopilot-install]\n\nSelf-update the CLI.\n\nDetects install method (bun, binary, clawhub) and runs the appropriate update.\nAfter upgrading, shows what\'s new and offers to set up new features.\n\n--no-autopilot-install Skip autopilot installation and service rewrites, including package postinstall.\n Also supported as GBRAIN_NO_AUTOPILOT_INSTALL=1.\n--swap-only Perform ONLY the binary/source swap and skip post-upgrade\n (migrations run on the next launch). Used by the autopilot\n silent self-upgrade channel so the daemon can swap + relaunch\n without a 30-min blocking post-upgrade inside its tick.');+ console.log('Usage: gbrain upgrade [--swap-only] [--no-autopilot-install] [--no-bun-floor-check]\n\nSelf-update the CLI.\n\nDetects install method (bun, binary, clawhub) and runs the appropriate update.\nAfter upgrading, shows what\'s new and offers to set up new features.\n\n--no-autopilot-install Skip autopilot installation and service rewrites, including package postinstall.\n Also supported as GBRAIN_NO_AUTOPILOT_INSTALL=1.\n--no-bun-floor-check Upgrade even when the target release\'s Bun floor cannot be read or is above\n this host\'s Bun (manual upgrades only). Docs: docs/guides/upgrades-auto-update.md#bun-floor.\n--swap-only Perform ONLY the binary/source swap and skip post-upgrade\n (migrations run on the next launch). Used by the autopilot\n silent self-upgrade channel so the daemon can swap + relaunch\n without a 30-min blocking post-upgrade inside its tick.');return;}@@ -37,6 +46,7 @@ export async function runUpgrade(args: string[], opts: { targetVersion?: string// relaunched binary runs migrations on boot (split-brain guard). v0.42.const swapOnly = args.includes('--swap-only');const noAutopilotInstall = args.includes('--no-autopilot-install') || process.env.GBRAIN_NO_AUTOPILOT_INSTALL === '1';+ const checkBunFloor = !args.includes('--no-bun-floor-check');// #5693: post-upgrade owns migrations, so package postinstall skips them.const upgradeEnv = { ...process.env, GBRAIN_UPGRADE_OWNS_MIGRATIONS: '1', ...(noAutopilotInstall ? { GBRAIN_NO_AUTOPILOT_INSTALL: '1' } : {}) };@@ -47,6 +57,7 @@ export async function runUpgrade(args: string[], opts: { targetVersion?: stringconsole.log(`Detected install method: ${method}`);let upgraded = false;+ const recovery: SmokeRecovery = { method, oldVersion };switch (method) {case 'bun-link': {const linkInfo = detectBunLink();@@ -55,8 +66,14 @@ export async function runUpgrade(args: string[], opts: { targetVersion?: stringbreak;}console.log(`Upgrading bun-link source clone at ${linkInfo.repoRoot}...`);+ // #5855: fast-forward to the exact commit whose Bun floor was checked.+ const checked = checkBunFloor ? readBunLinkTarget(linkInfo.repoRoot) : null;+ if (checked && refuseForBunFloor(checked.target, opts.targetVersion)) return;+ const sha = checked?.sha;+ try { recovery.previousSha = execFileSync('git', ['-C', linkInfo.repoRoot, 'rev-parse', 'HEAD'], { encoding: 'utf-8', timeout: 10_000 }).trim(); } catch { /* recovery text falls back */ }+ recovery.repoRoot = linkInfo.repoRoot;try {- execFileSync('git', ['-C', linkInfo.repoRoot, 'pull', '--ff-only'], { stdio: 'inherit', timeout: 120_000 });+ execFileSync('git', ['-C', linkInfo.repoRoot, ...(sha ? ['merge', '--ff-only', sha] : ['pull', '--ff-only'])], { stdio: 'inherit', timeout: 120_000 });execFileSync('bun', ['install'], { cwd: linkInfo.repoRoot, env: upgradeEnv, stdio: 'inherit', timeout: 120_000 });upgraded = true;} catch {@@ -72,6 +89,7 @@ export async function runUpgrade(args: string[], opts: { targetVersion?: stringcase 'bun': {console.log('Upgrading via bun...');const bunGlobalRoot = resolveBunGlobalRoot();+ if (checkBunFloor && refuseForBunFloor(await readPackageTarget(globalGbrainSpec(bunGlobalRoot)), opts.targetVersion)) return;try {execFileSync('bun', ['update', 'gbrain'], { cwd: bunGlobalRoot, env: upgradeEnv, stdio: 'inherit', timeout: 120_000 });upgraded = true;@@ -141,6 +159,7 @@ export async function runUpgrade(args: string[], opts: { targetVersion?: stringcase 'clawhub':console.log('Upgrading via ClawHub...');+ if (checkBunFloor && refuseForBunFloor(await readPackageTarget(null), opts.targetVersion)) return;try {execSync('clawhub update gbrain', { env: upgradeEnv, stdio: 'inherit', timeout: 120_000 });upgraded = true;@@ -207,6 +226,8 @@ export async function runUpgrade(args: string[], opts: { targetVersion?: string}// Save old version for post-upgrade migration detectionsaveUpgradeState(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):@@ -267,6 +288,70 @@ export async function runUpgrade(args: string[], opts: { targetVersion?: stringconsole.log(migrationsLine);}+/**+ * #5855: the Bun floor of the release `gbrain upgrade` would install for this+ * install method (the autopilot channel's pre-swap check). The swap re-reads+ * it, so a floor raised in between still refuses there.+ */+export async function readInstallTargetFloor(method: string): Promise<TargetFloor> {+ if (method === 'bun-link') {+ const link = detectBunLink();+ return link ? readBunLinkTarget(link.repoRoot).target : { ok: false, failedRead: 'the bun-link source clone could not be found' };+ }+ return readPackageTarget(method === 'bun' ? globalGbrainSpec(resolveBunGlobalRoot()) : null);+}++/**+ * #5855: refuse a swap whose target the host's Bun cannot start, or whose+ * floor cannot be read. Prints the refusal and sets the floor exit code,+ * which the autopilot channel treats as a hold rather than a failed version.+ */+function refuseForBunFloor(target: TargetFloor, targetVersion: string | undefined): boolean {+ const verdict = evaluateBunFloor(target, readHostBun(), targetVersion);+ if (verdict.ok) return false;+ console.error(verdict.message);+ console.error(verdict.kind === 'unreadable'+ ? 'Nothing was changed. Re-run with --no-bun-floor-check to upgrade without this check.'+ : 'Nothing was changed.');+ setCliExitVerdict(BUN_FLOOR_EXIT_CODE);+ return true;+}++interface SmokeRecovery { method: string; oldVersion: string; repoRoot?: string; previousSha?: string }++/**+ * #5855: after the swap, run a command that passes the CLI's runtime gate+ * (`--version` is exempt from it). A failure prints per-method recovery and+ * exits non-zero; nothing is rolled back automatically.+ */+function postSwapSmoke(newVersion: string, r: SmokeRecovery): boolean {+ const run = spawnSync('gbrain', ['--help'], {+ encoding: 'utf-8',+ stdio: ['ignore', 'ignore', 'pipe'],+ timeout: 60_000,+ env: { ...process.env, GBRAIN_SKIP_STARTUP_HOOKS: '1' },+ });+ if (run.status === 0) return true;+ const why = run.error ? run.error.message : `exit ${run.status ?? run.signal}`;+ const detail = (run.stderr ?? '').trim().split('\n')[0];+ const back = r.method === 'bun-link' && r.repoRoot && r.previousSha+ ? `git -C ${r.repoRoot} checkout ${r.previousSha} && bun install`+ : r.method === 'bun' ? `bun install -g github:${GBRAIN_GITHUB_REPO}#v${r.oldVersion}` : null;+ console.error(`gbrain ${newVersion || '(new version)'} was installed but does not start: \`gbrain --help\` failed (${why}).${detail ? `\n ${detail}` : ''}`);+ console.error('Recovery:');+ console.error(' If it names an old Bun: bun upgrade, then gbrain post-upgrade');+ if (back) console.error(` To return to ${r.oldVersion}: ${back}`);+ recordUpgradeError({+ phase: 'post-swap-smoke',+ fromVersion: r.oldVersion,+ toVersion: newVersion || 'unknown',+ error: `gbrain --help failed after the swap (${why})${detail ? `: ${detail}` : ''}`,+ hint: back ? `bun upgrade && gbrain post-upgrade, or return to ${r.oldVersion}: ${back}` : 'bun upgrade && gbrain post-upgrade',+ });+ setCliExitVerdict(1);+ return false;+}+/*** #5693: an install step can fail or time out after the new version is* already in place (postinstall work outlived the install timeout). Treat a@@ -967,7 +1052,7 @@ export function detectInstallMethod(): 'bun' | 'bun-link' | 'binary' | 'clawhub'* Returns { repoRoot } when confident; null otherwise (caller falls* through to the existing detection chain).*/-function detectBunLink(): { repoRoot: string } | null {+export function detectBunLink(): { repoRoot: string } | null {try {const argv1 = process.argv[1];if (!argv1) return null;diff --git a/src/core/bun-floor.ts b/src/core/bun-floor.tsnew file mode 100644index 0000000000..151c8a597c--- /dev/null+++ b/src/core/bun-floor.ts@@ -0,0 +1,193 @@+/**+ * The Bun floor of an upgrade target (#5855). A source or package install+ * runs the new release on the host's Bun, and a release whose `engines.bun`+ * floor that Bun does not meet refuses every command but `--version` once it+ * is swapped in. `gbrain upgrade` (and `gbrain self-upgrade`) refuse such a+ * swap and the autopilot channel holds it; this module reads the target's+ * floor per install method and the host's Bun, and words the refusal.+ *+ * Floors: a bun-link clone reads `package.json` at the commit `git fetch`+ * fetched (the SHA the swap then fast-forwards to, so the checked commit is+ * the installed one); a global package reads `package.json` at the ref its+ * `github:` spec names on raw.githubusercontent.com (the default branch when+ * unpinned, which `bun update gbrain` installs). Only the `>=X.Y.Z` shape the+ * release pins is accepted; any other shape is unreadable, and an unreadable+ * floor holds (autopilot) or refuses (manual) rather than guessing.+ *+ * Runtime: the `bun` on PATH (what the swapped-in CLI's shebang and+ * `bun install` use) and the Bun at `process.execPath` (the running daemon's+ * binary, which `bun upgrade` may have replaced in place); the lower decides.+ * No DB; readers return failure values instead of throwing.+ */++import { execFileSync } from 'node:child_process';+import { readFileSync } from 'node:fs';+import { join } from 'node:path';+import { VERSION } from '../version.ts';+import { BUN_VERSION_RE, bunVersionMeets, compareBunVersions } from './runtime-version.ts';++/** Exit code of a `gbrain upgrade` refused for the Bun floor (sysexits EX_CONFIG). */+export const BUN_FLOOR_EXIT_CODE = 78;+export const BUN_FLOOR_DOCS = 'docs/guides/upgrades-auto-update.md#bun-floor';+export const BUN_FLOOR_FIX = `Fix: bun upgrade, then gbrain upgrade. Docs: ${BUN_FLOOR_DOCS}`;++const PACKAGE_BODY_LIMIT = 256 * 1024;+const FLOOR_RE = /^>= ?(\d{1,4}\.\d{1,4}\.\d{1,4})$/;++/** `engines.bun` (as `X.Y.Z`) and `version` of a raw package.json body. */+export function parseReleasePackage(body: string): { floor: string | null; version: string | null } {+ if (body.length > PACKAGE_BODY_LIMIT) return { floor: null, version: null };+ let pkg: { engines?: { bun?: unknown }; version?: unknown };+ try {+ pkg = JSON.parse(body);+ } catch {+ return { floor: null, version: null };+ }+ const bun = pkg?.engines?.bun;+ const floor = typeof bun === 'string' ? FLOOR_RE.exec(bun)?.[1] ?? null : null;+ const version = typeof pkg?.version === 'string' && /^\d+(\.\d+){2,3}$/.test(pkg.version) ? pkg.version : null;+ return { floor, version };+}++export type TargetFloor =+ | { ok: true; floor: string; version: string | null }+ | { ok: false; failedRead: string; version?: string | null };++function floorFromBody(body: string, read: string): TargetFloor {+ const { floor, version } = parseReleasePackage(body);+ return floor ? { ok: true, floor, version } : { ok: false, failedRead: `${read} has no \`engines.bun\` floor of the form >=X.Y.Z`, version };+}++function git(repoRoot: string, args: string[], timeout = 10_000): string {+ return execFileSync('git', ['-C', repoRoot, ...args], {+ encoding: 'utf8',+ stdio: ['ignore', 'pipe', 'ignore'],+ timeout,+ maxBuffer: PACKAGE_BODY_LIMIT + 1,+ env: { ...process.env, GIT_TERMINAL_PROMPT: '0' },+ });+}++/**+ * A bun-link clone's upgrade target: `git fetch`, the fetched upstream SHA,+ * and the floor in `package.json` at that SHA. `sha` is null when the fetch+ * or the upstream lookup failed; the caller fast-forwards to `sha`, never to+ * a later upstream.+ */+export function readBunLinkTarget(repoRoot: string): { sha: string | null; target: TargetFloor } {+ try {+ git(repoRoot, ['fetch', '-q'], 60_000);+ } catch {+ return { sha: null, target: { ok: false, failedRead: '`git fetch` in the source clone failed' } };+ }+ let sha: string;+ try {+ sha = git(repoRoot, ['rev-parse', '--verify', '@{u}^{commit}']).trim();+ } catch {+ return { sha: null, target: { ok: false, failedRead: 'the source clone has no upstream branch to read' } };+ }+ const read = `\`git show ${sha.slice(0, 12)}:package.json\``;+ try {+ return { sha, target: floorFromBody(git(repoRoot, ['show', `${sha}:package.json`]), read) };+ } catch {+ return { sha, target: { ok: false, failedRead: `${read} failed` } };+ }+}++/** The `gbrain` dependency spec of a Bun global install (`<root>/package.json`). */+export function globalGbrainSpec(globalRoot: string): string | null {+ try {+ // nosemgrep: javascript.lang.security.audit.path-traversal.path-join-resolve-traversal.path-join-resolve-traversal -- globalRoot is Bun's own global install dir (resolveBunGlobalRoot)+ const spec = (JSON.parse(readFileSync(join(globalRoot, 'package.json'), 'utf8')) as { dependencies?: Record<string, unknown> })+ .dependencies?.gbrain;+ return typeof spec === 'string' ? spec.trim() : null;+ } catch {+ return null;+ }+}++const GITHUB_SPEC_RE = /^(?:github:|git\+https:\/\/github\.com\/|git\+ssh:\/\/git@github\.com[:/]|https:\/\/github\.com\/)?([A-Za-z0-9_.-]+)\/([A-Za-z0-9_.-]+?)(?:\.git)?(?:#([A-Za-z0-9_./-]+))?$/;++/** raw.githubusercontent.com URL of `package.json` at the ref a GitHub spec installs; null for any other spec. */+export function rawPackageUrlForSpec(spec: string): string | null {+ const m = GITHUB_SPEC_RE.exec(spec);+ if (!m || m[3]?.includes('..')) return null;+ return `https://raw.githubusercontent.com/${m[1]}/${m[2]}/${m[3] ?? 'HEAD'}/package.json`;+}++/**+ * A package install's upgrade target: `package.json` at the ref its spec+ * installs (the default branch when unpinned). A null spec (a clawhub+ * install) reads the canonical repository's default branch.+ */+export async function readPackageTarget(spec: string | null): Promise<TargetFloor> {+ const url = rawPackageUrlForSpec(spec ?? 'github:garrytan/gbrain');+ if (!url) return { ok: false, failedRead: `the global install's gbrain spec (${spec}) is not a GitHub spec` };+ const read = `GET ${url}`;+ try {+ const res = await fetch(url, { headers: { 'User-Agent': `gbrain/${VERSION}` }, signal: AbortSignal.timeout(5_000) });+ if (!res.ok) return { ok: false, failedRead: `${read} returned HTTP ${res.status}` };+ return floorFromBody(await res.text(), read);+ } catch {+ return { ok: false, failedRead: `${read} failed (network)` };+ }+}++export interface HostBun {+ /** How messages name it: the PATH lookup or the running binary. */+ label: 'bun on PATH' | 'the running Bun';+ path: string;+ version: string;+}++function bunVersionAt(path: string): string | null {+ try {+ const out = execFileSync(path, ['--version'], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'], timeout: 10_000 }).trim();+ return BUN_VERSION_RE.test(out) ? out : null;+ } catch {+ return null;+ }+}++/**+ * The host's Bun as the swapped-in release will meet it: the lower of the+ * `bun` on PATH and the Bun at `process.execPath` (its `Bun.version` when the+ * binary does not answer). null when the `bun` on PATH cannot be run.+ */+export function readHostBun(): HostBun | null {+ const pathBin = typeof Bun === 'undefined' ? null : Bun.which('bun', { PATH: process.env.PATH ?? '' });+ const pathVersion = pathBin ? bunVersionAt(pathBin) : null;+ if (!pathBin || !pathVersion) return null;+ const onPath: HostBun = { label: 'bun on PATH', path: pathBin, version: pathVersion };+ if (typeof Bun === 'undefined' || process.execPath === pathBin) return onPath;+ const execVersion = bunVersionAt(process.execPath) ?? Bun.version;+ if (!BUN_VERSION_RE.test(execVersion)) return onPath;+ const running: HostBun = { label: 'the running Bun', path: process.execPath, version: execVersion };+ return (compareBunVersions(execVersion, pathVersion) ?? 0) < 0 ? running : onPath;+}++export type BunFloorVerdict =+ | { ok: true }+ | { ok: false; kind: 'unmet' | 'unreadable'; message: string; auditReason: string };++/**+ * The gate: ok, or a refusal whose `message` names the target, floor, the+ * Bun found with its path and the fix, and whose `auditReason` is the same+ * text without the local path (the self-upgrade audit records no paths).+ */+export function evaluateBunFloor(target: TargetFloor, host: HostBun | null, targetVersion?: string | null): BunFloorVerdict {+ const version = target.version ?? targetVersion;+ const name = version ? `gbrain ${version}` : 'the target release';+ if (!target.ok) {+ const text = `Could not read the Bun floor of ${name}: ${target.failedRead}. Docs: ${BUN_FLOOR_DOCS}`;+ return { ok: false, kind: 'unreadable', message: text, auditReason: text };+ }+ if (!host) {+ const text = `${name} requires Bun >=${target.floor}; could not run \`bun --version\` on PATH. ${BUN_FLOOR_FIX}`;+ return { ok: false, kind: 'unreadable', message: text, auditReason: text };+ }+ if (bunVersionMeets(host.version, target.floor)) return { ok: true };+ const head = `${name} requires Bun >=${target.floor}; ${host.label}`;+ const tail = ` is ${host.version}. ${BUN_FLOOR_FIX}`;+ return { ok: false, kind: 'unmet', message: `${head} (${host.path})${tail}`, auditReason: `${head}${tail}` };+}diff --git a/src/core/cli-flag-registry.generated.ts b/src/core/cli-flag-registry.generated.tsindex 8ab8e64c61..9ed0551905 100644--- a/src/core/cli-flag-registry.generated.ts+++ b/src/core/cli-flag-registry.generated.ts@@ -19,7 +19,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {'anomalies': ['--brain', '--help', '--json', '--lookback-days', '--mcp-only', '--sigma', '--since', '--source'],'apply-migrations': ['--acknowledge-no-backup', '--apply', '--backup-confirmed', '--brain', '--break-lock', '--confirm-quiesced', '--content-root', '--dry-run', '--export-db-only', '--export-source', '--force', '--force-all', '--force-orchestrator', '--force-retry', '--force-schema', '--help', '--host-dir', '--json', '--list', '--locks', '--migrate-only', '--migration', '--mode', '--no-autopilot-install', '--non-interactive', '--require-db', '--skip-verify', '--source', '--yes'],'auth': ['--admin-intent', '--allowed-operations', '--before', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--budget-usd-per-day', '--cleanup-dead-local-locks', '--confirm-quiesced', '--days', '--delegated-namespace', '--delegated-slug-prefixes', '--enable-dcr-insecure', '--expected-epoch', '--expected-state', '--federated-read', '--fix', '--force', '--grant-types', '--help', '--id', '--if-version', '--json', '--limit', '--manifest', '--max-concurrent', '--no-pull', '--path', '--probe', '--profile', '--redirect-uri', '--repair', '--replace', '--request-id', '--retry-failed', '--scopes', '--self-transfer', '--shared-skills', '--slug-prefixes', '--source', '--source-ids', '--surface', '--takes-holders', '--token', '--token-endpoint-auth-method', '--token-ttl', '--usage', '--yes'],- 'autopilot': ['--batch', '--brain', '--check', '--dimensions', '--dir', '--drain', '--embedding-dimensions', '--embedding-model', '--explain', '--ff-only', '--force', '--force-retry', '--from-pages', '--help', '--inject-bootstrap', '--inline', '--install', '--interval', '--json', '--markdown', '--max-rss', '--max-usd', '--migrate-only', '--no-autopilot-install', '--no-inject', '--no-worker', '--non-interactive', '--now', '--once', '--output', '--path', '--pause', '--phase', '--reason', '--refresh-cache', '--remediation-plan', '--repo', '--resume', '--source', '--stale', '--status', '--swap-only', '--target', '--uninstall', '--user', '--version', '--yes'],+ 'autopilot': ['--batch', '--brain', '--check', '--dimensions', '--dir', '--drain', '--embedding-dimensions', '--embedding-model', '--explain', '--ff-only', '--force', '--force-retry', '--from-pages', '--help', '--inject-bootstrap', '--inline', '--install', '--interval', '--json', '--markdown', '--max-rss', '--max-usd', '--migrate-only', '--no-autopilot-install', '--no-bun-floor-check', '--no-inject', '--no-worker', '--non-interactive', '--now', '--once', '--output', '--path', '--pause', '--phase', '--reason', '--refresh-cache', '--remediation-plan', '--repo', '--resume', '--source', '--stale', '--status', '--swap-only', '--target', '--uninstall', '--user', '--verify', '--version', '--yes'],'backfill': ['--batch-size', '--brain', '--concurrency', '--dry-run', '--fresh', '--help', '--json', '--keep-index', '--list', '--max-errors', '--max-rows', '--resume', '--source'],'backup': ['--background', '--brain', '--confirm-authority-reviewed', '--confirm-backup-compatible', '--confirm-quiesced', '--dir', '--explain', '--follow', '--full', '--help', '--into', '--json', '--mode', '--output', '--path', '--progress-interval', '--progress-json', '--quiet', '--restore-only', '--source', '--timeout'],'bench': ['--baseline', '--brain', '--force', '--from', '--help', '--json', '--label', '--limit', '--source', '--threshold-jaccard', '--threshold-latency-multiplier', '--threshold-top1', '--to', '--tool'],@@ -32,7 +32,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {'capture': ['--access', '--asof', '--background', '--bound-slug-prefixes', '--brain', '--date', '--days', '--depth', '--entities', '--expected-revision', '--explain', '--federated-read', '--file', '--follow', '--force', '--full', '--help', '--http', '--image', '--json', '--kind', '--limit', '--mcp-only', '--mode', '--multimodal', '--once', '--page', '--path', '--progress-interval', '--progress-json', '--quiet', '--request-id', '--scopes', '--session', '--since', '--slug', '--slugs', '--source', '--stats', '--stdin', '--surface', '--timeout', '--trusted-extraction', '--type', '--types', '--url', '--what', '--where', '--who', '--yes'],'check-backlinks': ['--background', '--brain', '--dir', '--dry-run', '--explain', '--follow', '--help', '--json', '--progress-interval', '--progress-json', '--quiet', '--source', '--timeout'],'check-resolvable': ['--brain', '--dry-run', '--fix', '--help', '--json', '--skills-dir', '--source', '--strict', '--verbose'],- 'check-update': ['--brain', '--ff-only', '--force-retry', '--help', '--json', '--markdown', '--migrate-only', '--no-autopilot-install', '--non-interactive', '--refresh-cache', '--remediation-plan', '--source', '--swap-only', '--version', '--yes'],+ 'check-update': ['--brain', '--ff-only', '--force-retry', '--help', '--json', '--markdown', '--migrate-only', '--no-autopilot-install', '--no-bun-floor-check', '--non-interactive', '--refresh-cache', '--remediation-plan', '--source', '--swap-only', '--version', '--yes'],'claw-test': ['--agent', '--apply', '--brain', '--dir', '--force-retry', '--format', '--help', '--json', '--keep-tempdir', '--list-agents', '--live', '--local', '--locks', '--message', '--no-embed', '--no-embedding', '--output-format', '--pglite', '--progress-json', '--run-id', '--scenario', '--skip-verify', '--source', '--version', '--yes'],'code-callees': ['--all-sources', '--brain', '--force', '--help', '--json', '--lang', '--limit', '--no-embed', '--no-json', '--source'],'code-callers': ['--all-sources', '--brain', '--force', '--help', '--json', '--lang', '--limit', '--no-embed', '--no-json', '--source'],@@ -84,7 +84,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {'orphans': ['--background', '--brain', '--count', '--explain', '--follow', '--help', '--include-pseudo', '--json', '--mode', '--progress-interval', '--progress-json', '--quiet', '--source', '--timeout'],'pages': ['--brain', '--dry-run', '--help', '--json', '--older-than', '--source'],'pglite-repair': ['--brain', '--break-lock', '--dry-run', '--help', '--json', '--path', '--source', '--vectors', '--yes'],- 'post-upgrade': ['--acknowledge-no-backup', '--admin-intent', '--all', '--apply', '--apply-clean-hunks', '--backup-confirmed', '--brain', '--check', '--concurrency', '--confirm-quiesced', '--content-root', '--cost-estimate', '--embedding-dimensions', '--embedding-model', '--expected-epoch', '--expected-state', '--export-db-only', '--export-source', '--ff-only', '--force', '--force-all', '--force-orchestrator', '--force-retry', '--force-schema', '--format', '--help', '--host-dir', '--inject-bootstrap', '--inline', '--install', '--interval', '--json', '--limit', '--list', '--manifest', '--markdown', '--max-rss', '--migrate-only', '--migration', '--mode', '--multimodal', '--name-only', '--no-autopilot-install', '--no-embed', '--no-inject', '--no-worker', '--non-interactive', '--now', '--once', '--path', '--pause', '--quiet', '--reason', '--remediation-plan', '--repo', '--require-db', '--resume', '--self-transfer', '--skills-dir', '--skip-verify', '--source', '--stale', '--status', '--swap-only', '--target', '--uninstall', '--user', '--vectors', '--verify', '--version', '--workers', '--yes'],+ 'post-upgrade': ['--acknowledge-no-backup', '--admin-intent', '--all', '--apply', '--apply-clean-hunks', '--backup-confirmed', '--brain', '--check', '--concurrency', '--confirm-quiesced', '--content-root', '--cost-estimate', '--embedding-dimensions', '--embedding-model', '--expected-epoch', '--expected-state', '--export-db-only', '--export-source', '--ff-only', '--force', '--force-all', '--force-orchestrator', '--force-retry', '--force-schema', '--format', '--help', '--host-dir', '--inject-bootstrap', '--inline', '--install', '--interval', '--json', '--limit', '--list', '--manifest', '--markdown', '--max-rss', '--migrate-only', '--migration', '--mode', '--multimodal', '--name-only', '--no-autopilot-install', '--no-bun-floor-check', '--no-embed', '--no-inject', '--no-worker', '--non-interactive', '--now', '--once', '--path', '--pause', '--quiet', '--reason', '--remediation-plan', '--repo', '--require-db', '--resume', '--self-transfer', '--skills-dir', '--skip-verify', '--source', '--stale', '--status', '--swap-only', '--target', '--uninstall', '--user', '--vectors', '--verify', '--version', '--workers', '--yes'],'projections': ['--brain', '--enable-dcr', '--help', '--http', '--install', '--json', '--limit', '--now', '--port', '--public-url', '--remove', '--source', '--status', '--surface', '--user'],'protocol': ['--access', '--asof', '--bound-slug-prefixes', '--brain', '--date', '--days', '--entities', '--federated-read', '--file', '--full', '--help', '--http', '--image', '--json', '--kind', '--limit', '--mode', '--multimodal', '--once', '--page', '--path', '--session', '--since', '--slug', '--slugs', '--source', '--stats', '--surface', '--synthesize', '--target', '--token', '--trusted-extraction', '--types', '--url', '--yes'],'providers': ['--brain', '--embedding-dimensions', '--embedding-model', '--help', '--json', '--model', '--source', '--status', '--touchpoint'],@@ -107,7 +107,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', '--force', '--help', '--inverse', '--json', '--kind', '--pack', '--page-type', '--prefix', '--primitive', '--schema-pack', '--since', '--source', '--source-id', '--target-type', '--to', '--with-db'],- 'self-upgrade': ['--brain', '--check-only', '--ff-only', '--force', '--force-retry', '--help', '--json', '--markdown', '--migrate-only', '--no-autopilot-install', '--non-interactive', '--refresh-cache', '--remediation-plan', '--source', '--swap-only', '--version', '--yes'],+ 'self-upgrade': ['--brain', '--check-only', '--ff-only', '--force', '--force-retry', '--help', '--json', '--markdown', '--migrate-only', '--no-autopilot-install', '--no-bun-floor-check', '--non-interactive', '--refresh-cache', '--remediation-plan', '--source', '--swap-only', '--version', '--yes'],'serve': ['--bind', '--brain', '--enable-dcr', '--enable-dcr-insecure', '--help', '--http', '--json', '--log-full-params', '--oauth-request', '--port', '--print-admin-token', '--public-url', '--source', '--source-guard', '--stdio-idle-timeout', '--suppress-bootstrap-token', '--surface', '--token-ttl', '--url', '--yes'],'skillify': ['--brain', '--description', '--dry-run', '--force', '--help', '--json', '--mutating', '--recent', '--skills-dir', '--source', '--strict', '--triggers', '--writes-pages', '--writes-to'],'skillopt': ['--all', '--allow-mutate-bundled', '--background', '--batch-size', '--benchmark', '--bootstrap-from-routing', '--bootstrap-from-skill', '--bootstrap-reviewed', '--bootstrap-tasks', '--brain', '--brain-wide-max-cost-usd', '--dry-run', '--epochs', '--follow', '--force', '--held-out', '--help', '--json', '--judge-model', '--lr', '--lr-schedule', '--max-cost-usd', '--max-runtime-min', '--models-strict', '--no-max-cost', '--no-mutate', '--optimizer-model', '--patch', '--reflect-max-tokens', '--resume', '--rewrite', '--skills-dir', '--source', '--split', '--status', '--target-model', '--target-models'],@@ -122,7 +122,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {'takes': ['--accept', '--batch-size', '--brain', '--bucket-size', '--by', '--claim', '--dim', '--dir', '--domain', '--dry-run', '--embedding-dimensions', '--embedding-model', '--evidence', '--expected-revision', '--expired', '--force', '--from-pages', '--help', '--holder', '--include-covered', '--json', '--kind', '--limit', '--max-pages', '--no-embed', '--no-embedding', '--offset', '--outcome', '--pglite', '--quality', '--reject', '--request-id', '--row', '--semantic', '--since', '--sort', '--source', '--source-id', '--stale', '--status', '--supabase', '--to', '--unit', '--until', '--value', '--weight', '--who', '--yes'],'think': ['--anchor', '--brain', '--calibration-holder', '--help', '--json', '--mcp-only', '--model', '--rounds', '--save', '--since', '--source', '--take', '--until', '--with-calibration'],'transcripts': ['--all', '--all-discovery', '--background', '--brain', '--days', '--dry-run', '--embed', '--explain', '--facts', '--follow', '--format', '--full', '--help', '--include-self', '--json', '--limit', '--max-bytes', '--max-cost-usd', '--progress-interval', '--progress-json', '--quiet', '--since', '--source', '--source-id', '--timeout'],- 'upgrade': ['--acknowledge-no-backup', '--admin-intent', '--all', '--apply', '--apply-clean-hunks', '--backup-confirmed', '--brain', '--check', '--concurrency', '--confirm-quiesced', '--content-root', '--cost-estimate', '--embedding-dimensions', '--embedding-model', '--expected-epoch', '--expected-state', '--export-db-only', '--export-source', '--ff-only', '--force', '--force-all', '--force-orchestrator', '--force-retry', '--force-schema', '--format', '--help', '--host-dir', '--inject-bootstrap', '--inline', '--install', '--interval', '--json', '--limit', '--list', '--manifest', '--markdown', '--max-rss', '--migrate-only', '--migration', '--mode', '--multimodal', '--name-only', '--no-autopilot-install', '--no-embed', '--no-inject', '--no-worker', '--non-interactive', '--now', '--once', '--path', '--pause', '--quiet', '--reason', '--remediation-plan', '--repo', '--require-db', '--resume', '--self-transfer', '--skills-dir', '--skip-verify', '--source', '--stale', '--status', '--swap-only', '--target', '--uninstall', '--user', '--vectors', '--verify', '--version', '--workers', '--yes'],+ 'upgrade': ['--acknowledge-no-backup', '--admin-intent', '--all', '--apply', '--apply-clean-hunks', '--backup-confirmed', '--brain', '--check', '--concurrency', '--confirm-quiesced', '--content-root', '--cost-estimate', '--embedding-dimensions', '--embedding-model', '--expected-epoch', '--expected-state', '--export-db-only', '--export-source', '--ff-only', '--force', '--force-all', '--force-orchestrator', '--force-retry', '--force-schema', '--format', '--help', '--host-dir', '--inject-bootstrap', '--inline', '--install', '--interval', '--json', '--limit', '--list', '--manifest', '--markdown', '--max-rss', '--migrate-only', '--migration', '--mode', '--multimodal', '--name-only', '--no-autopilot-install', '--no-bun-floor-check', '--no-embed', '--no-inject', '--no-worker', '--non-interactive', '--now', '--once', '--path', '--pause', '--quiet', '--reason', '--remediation-plan', '--repo', '--require-db', '--resume', '--self-transfer', '--skills-dir', '--skip-verify', '--source', '--stale', '--status', '--swap-only', '--target', '--uninstall', '--user', '--vectors', '--verify', '--version', '--workers', '--yes'],'waiting': ['--all', '--as-of', '--brain', '--help', '--json', '--note', '--source', '--stale-ok', '--status', '--top', '--type'],'watch': ['--brain', '--help', '--json', '--max-pages', '--min-confidence', '--source', '--window-turns'],'whoknows': ['--access', '--asof', '--bound-slug-prefixes', '--brain', '--date', '--days', '--entities', '--explain', '--federated-read', '--file', '--full', '--help', '--http', '--image', '--json', '--kind', '--limit', '--mcp-only', '--mode', '--multimodal', '--once', '--page', '--path', '--session', '--since', '--slug', '--slugs', '--source', '--stats', '--surface', '--trusted-extraction', '--types', '--url', '--yes'],diff --git a/src/core/runtime-version.ts b/src/core/runtime-version.tsindex fb376986c5..362e2c8642 100644--- a/src/core/runtime-version.ts+++ b/src/core/runtime-version.ts@@ -4,8 +4,34 @@*/export const MINIMUM_BUN_VERSION = '1.4.0';+export const BUN_VERSION_RE = /^(\d{1,4})\.(\d{1,4})\.(\d{1,4})(-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?$/;++/**+ * Order two Bun versions (`1.4.2`, `1.4.2+5a1b2c3` from `bun --revision`,+ * `1.5.0-canary.3+abc`): negative, zero or positive. A prerelease orders+ * before its release and build metadata is ignored (semver), so+ * `1.4.0-canary.1` is below `1.4.0` and `1.5.0-canary.1` above it. null when+ * either does not parse.+ */+export function compareBunVersions(a: string, b: string): number | null {+ const x = BUN_VERSION_RE.exec(a.trim());+ const y = BUN_VERSION_RE.exec(b.trim());+ if (!x || !y) return null;+ for (let i = 1; i <= 3; i++) {+ const d = Number(x[i]) - Number(y[i]);+ if (d !== 0) return d;+ }+ return (x[4] ? 0 : 1) - (y[4] ? 0 : 1);+}++/** Whether a Bun version meets an `X.Y.Z` floor; null when it does not parse. */+export function bunVersionMeets(version: string, floor: string): boolean | null {+ const order = compareBunVersions(version, floor);+ return order === null ? null : order >= 0;+}+export function unsupportedBunMessage(version = typeof Bun === 'undefined' ? '' : Bun.version): string | null {- if (/^\d+\.\d+\.\d+(?:\+.*)?$/.test(version) && Bun.semver.satisfies(version, `>=${MINIMUM_BUN_VERSION}`)) return null;+ if (bunVersionMeets(version, MINIMUM_BUN_VERSION)) return null;return `GBrain requires Bun ${MINIMUM_BUN_VERSION} or newer (found ${version ? `Bun ${version}` : 'no Bun runtime'}).\n`+ 'Fix: run `bun upgrade`, then restart GBrain. If a `gbrain upgrade` stopped here, finish it with `gbrain post-upgrade`.';}diff --git a/src/core/self-upgrade.ts b/src/core/self-upgrade.tsindex 65a48c7975..5fa047b43f 100644--- a/src/core/self-upgrade.ts+++ b/src/core/self-upgrade.ts@@ -31,6 +31,7 @@ import { dirname, join } from 'node:path';import { gbrainPath, isConfigTruthy } from './config.ts';import { isValidTimeZone } from './cycle/cycle-date.ts';import { isValidConfig as isValidQuietHoursWindow } from './minions/quiet-hours.ts';+import { evaluateBunFloor, type HostBun, type TargetFloor } from './bun-floor.ts';import { acquirePackLock, type PackLockOpts } from './schema-pack/pack-lock.ts';import { isNewerVersion, isValidVersionString, parseSemver, semverGt, semverLte } from './semver.ts';@@ -72,6 +73,7 @@ export type SelfUpgradeAction =| 'busy'| 'outside_quiet_hours'| 'unsupported_install'+ | 'unsupported_runtime'| 'notify'| 'apply';@@ -178,6 +180,28 @@ export function decideSelfUpgrade(inp: DecideSelfUpgradeInputs): SelfUpgradeDecireturn { action: 'apply', reason: `auto-upgrading ${inp.currentVersion} -> ${inp.latestVersion}`, ...base };}+/**+ * Runtime gate for an `apply` on an install that runs the target on the host's+ * Bun (every method but `binary`, which carries its own runtime). Holds the+ * upgrade when the target's `engines.bun` floor is above the host's Bun, or+ * when either could not be read: once swapped, every command refuses at+ * startup (the relaunched daemon included, before it can reconcile the+ * breadcrumb) and an unattended host has nothing that upgrades Bun (#5855).+ * The target is NOT recorded known-bad, so the first tick after the cause+ * clears applies it. Pure.+ */+export function gateOnTargetRuntime(+ decision: SelfUpgradeDecision,+ target: TargetFloor,+ host: HostBun | null,+): SelfUpgradeDecision {+ if (decision.action !== 'apply') return decision;+ const verdict = evaluateBunFloor(target, host, decision.latest);+ if (verdict.ok) return decision;+ const retry = verdict.kind === 'unreadable' ? ' The next quiet-hours tick retries.' : '';+ return { ...decision, action: 'unsupported_runtime', reason: `${verdict.auditReason}${retry}` };+}+/*** Whether this install method + platform/arch can apply an upgrade unattended.* `bun` / `bun-link` / `clawhub` delegate to their package managers; `binary`diff --git a/test/autopilot-bun-floor.serial.test.ts b/test/autopilot-bun-floor.serial.test.tsnew file mode 100644index 0000000000..9ca0da5f13--- /dev/null+++ b/test/autopilot-bun-floor.serial.test.ts@@ -0,0 +1,189 @@+/**+ * #5855: the autopilot self-upgrade channel never swaps in a release the+ * host's Bun cannot start. Drives the real `attemptAutopilotSelfUpgrade` in a+ * spawned driver (Bun resolves child PATH at process start, so the `bun` and+ * `gbrain` shims must be on the driver's startup PATH; see+ * test/upgrade-bun-link-arc.serial.test.ts).+ *+ * Protects: a quiet-hours `apply` on a bun-link clone or a global package is+ * held as `unsupported_runtime` (audited, breadcrumb not written, not+ * known-bad) when the target's floor is above the host Bun or unreadable;+ * a met floor still swaps; a swap that `gbrain upgrade` itself refuses for+ * the floor (exit 78) is a hold, while any other swap failure stays known-bad.+ * Regression: the channel deciding without reading the target's floor (the+ * #5855 crash loop), or recording a floor refusal as a failed version.+ * Existing coverage: test/autopilot-self-upgrade.test.ts reads source text+ * only; this replaces PR #5860's source-regex check with behavior.+ */+import { afterAll, describe, expect, test } from 'bun:test';+import { execFileSync } from 'node:child_process';+import { existsSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { VERSION } from '../src/version.ts';++const AUTOPILOT_TS = join(import.meta.dir, '..', 'src', 'commands', 'autopilot.ts');+const TARGET = '99.0.0.0';+const dirs: string[] = [];+afterAll(() => { for (const d of dirs) rmSync(d, { recursive: true, force: true }); });++const GIT_ENV = { ...process.env, GIT_CONFIG_NOSYSTEM: '1', GIT_TERMINAL_PROMPT: '0' };+const IDENTITY = ['-c', 'user.name=gbrain-test', '-c', '[email protected]', '-c', 'commit.gpgsign=false'];+function git(args: string[], cwd?: string): string {+ return execFileSync('git', args, { cwd, encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'], env: GIT_ENV });+}++interface Harness { root: string; home: string; shims: string; argvLog: string }++function harness(label: string): Harness {+ const root = mkdtempSync(join(tmpdir(), `gbrain-ap-floor-${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' } },+ }));+ writeFileSync(join(dotG, 'last-update-check'), `UPGRADE_AVAILABLE ${VERSION} ${TARGET}\n`);+ const shims = join(root, 'bin');+ mkdirSync(shims);+ const argvLog = join(root, 'argv.log');+ writeFileSync(argvLog, '');+ writeFileSync(join(shims, 'bun'), '#!/usr/bin/env bash\necho "$FAKE_BUN_VERSION"\n', { mode: 0o755 });+ writeFileSync(join(shims, 'gbrain'), `#!/usr/bin/env bash\nprintf 'gbrain %s\\n' "$*" >> "${argvLog}"\nexit "\${FAKE_GBRAIN_EXIT:-0}"\n`, { mode: 0o755 });+ return { root, home, shims, argvLog };+}++function writeDriver(path: string, h: Harness): void {+ mkdirSync(join(path, '..'), { recursive: true });+ writeFileSync(path, [+ 'const fetched: string[] = [];',+ 'globalThis.fetch = (async (url: unknown) => {',+ ' fetched.push(String(url));',+ " const body = process.env.FAKE_PACKAGE_BODY;",+ " return body ? new Response(body) : new Response('Not Found', { 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(h.root, 'autopilot.lock'))});`,+ "console.log('FETCHED ' + JSON.stringify(fetched));",+ "console.log('RETURNED');",+ '',+ ].join('\n'));+}++/** A bun-link clone one commit behind an origin whose head pins `floor`. */+function bunLinkInstall(h: Harness, floor: string): string {+ const origin = join(h.root, 'remotes', 'garrytan', 'gbrain');+ mkdirSync(origin, { recursive: true });+ git(['init', '-q', '-b', 'master'], origin);+ writeFileSync(join(origin, 'package.json'), JSON.stringify({ version: '0.0.1.0', engines: { bun: '>=1.4.0' } }));+ git(['add', '-A'], origin);+ git([...IDENTITY, 'commit', '-q', '-m', 'old'], origin);+ const clone = join(h.root, 'clone');+ git(['clone', '-q', origin, clone]);+ writeFileSync(join(origin, 'package.json'), JSON.stringify({ version: TARGET, engines: { bun: floor } }));+ git(['add', '-A'], origin);+ git([...IDENTITY, 'commit', '-q', '-m', 'new'], origin);+ const driver = join(clone, 'src', 'cli.ts');+ writeDriver(driver, h);+ return driver;+}++/** A Bun global install of `github:garrytan/gbrain` with the driver inside node_modules. */+function packageInstall(h: Harness): { driver: string; bunInstall: string } {+ const bunInstall = join(h.root, 'bunhome');+ const globalRoot = join(bunInstall, 'install', 'global');+ mkdirSync(join(globalRoot, 'node_modules'), { recursive: true });+ writeFileSync(join(globalRoot, 'package.json'), JSON.stringify({ dependencies: { gbrain: 'github:garrytan/gbrain' } }));+ const pkgDir = join(globalRoot, 'node_modules', 'gbrain');+ mkdirSync(pkgDir, { recursive: true });+ 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');+ writeDriver(driver, h);+ return { driver, bunInstall };+}++async function tick(h: Harness, driver: string, env: Record<string, string>) {+ const proc = Bun.spawn([process.execPath, driver], {+ cwd: h.root,+ env: {+ PATH: `${h.shims}:/usr/bin:/bin`,+ HOME: h.root,+ GBRAIN_HOME: h.home,+ GBRAIN_AUDIT_DIR: join(h.root, 'audit'),+ 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 audit = existsSync(join(h.root, 'audit'))+ ? readdirSync(join(h.root, 'audit')).flatMap((f) => readFileSync(join(h.root, 'audit', 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 fetched = JSON.parse(/FETCHED (.*)/.exec(out)?.[1] ?? '[]') as string[];+ return { code, out, err, audit, su: config.self_upgrade, swaps: readFileSync(h.argvLog, 'utf8').split('\n').filter(Boolean), fetched };+}++function expectHeld(r: Awaited<ReturnType<typeof tick>>, reason: string): void {+ expect(r.code, r.err).toBe(0);+ expect(r.out).toContain('RETURNED');+ expect(r.out).not.toContain('EXIT_CALLED');+ expect(r.swaps).toEqual([]);+ expect(r.su.attempting_version).toBeUndefined();+ expect(r.su.failed_versions).toBeUndefined();+ const last = r.audit.at(-1);+ expect(last).toMatchObject({ channel: 'autopilot', action: 'unsupported_runtime', latest: TARGET, outcome: 'skipped' });+ expect(last.reason).toContain(reason);+}++describe('autopilot self-upgrade Bun floor gate (#5855)', () => {+ test('bun-link: the fetched upstream floor above the PATH bun holds the upgrade', async () => {+ const h = harness('link-unmet');+ const r = await tick(h, bunLinkInstall(h, '>=1.4.0'), { FAKE_BUN_VERSION: '1.3.14' });+ expectHeld(r, `gbrain ${TARGET} requires Bun >=1.4.0; bun on PATH is 1.3.14. Fix: bun upgrade, then gbrain upgrade.`);+ }, 60_000);++ test('bun-link: a met floor swaps and exits for relaunch', async () => {+ const h = harness('link-met');+ const r = await tick(h, bunLinkInstall(h, '>=1.4.0'), { FAKE_BUN_VERSION: Bun.version });+ expect(r.out).toContain('EXIT_CALLED 0');+ expect(r.swaps).toEqual(['gbrain upgrade --swap-only']);+ expect(r.su.attempting_version).toBe(TARGET);+ }, 60_000);++ test('package: the floor at the spec ref above the host Bun holds; an unreadable floor holds', async () => {+ const h = harness('pkg');+ const { driver, bunInstall } = packageInstall(h);+ const unmet = await tick(h, driver, { FAKE_BUN_VERSION: Bun.version, BUN_INSTALL: bunInstall, FAKE_PACKAGE_BODY: JSON.stringify({ version: TARGET, engines: { bun: '>=9.9.9' } }) });+ expectHeld(unmet, `gbrain ${TARGET} requires Bun >=9.9.9;`);+ expect(unmet.fetched).toContain('https://raw.githubusercontent.com/garrytan/gbrain/HEAD/package.json');++ const unreadable = await tick(h, driver, { FAKE_BUN_VERSION: Bun.version, BUN_INSTALL: bunInstall, FAKE_PACKAGE_BODY: JSON.stringify({ version: TARGET, engines: { bun: '^1.4.0' } }) });+ expectHeld(unreadable, `Could not read the Bun floor of gbrain ${TARGET}`);+ expect(unreadable.audit.at(-1).reason).toContain('The next quiet-hours tick retries.');+ }, 60_000);++ test('a swap refused by `gbrain upgrade` for the floor is a hold; another swap failure is known-bad', async () => {+ const h = harness('swap-exit');+ const { driver, bunInstall } = packageInstall(h);+ const env = { FAKE_BUN_VERSION: Bun.version, BUN_INSTALL: bunInstall, FAKE_PACKAGE_BODY: JSON.stringify({ version: TARGET, engines: { bun: '>=1.4.0' } }) };+ const held = await tick(h, driver, { ...env, FAKE_GBRAIN_EXIT: '78' });+ expect(held.swaps).toEqual(['gbrain upgrade --swap-only']);+ expect(held.su.attempting_version).toBeUndefined();+ expect(held.su.failed_versions ?? []).toEqual([]);+ expect(held.audit.at(-1)).toMatchObject({ action: 'unsupported_runtime', outcome: 'skipped', latest: TARGET });++ const failed = await tick(h, driver, { ...env, FAKE_GBRAIN_EXIT: '1' });+ expect(failed.su.failed_versions).toEqual([TARGET]);+ expect(failed.audit.at(-1)).toMatchObject({ action: 'apply', outcome: 'failed', latest: TARGET });+ }, 60_000);+});diff --git a/test/bun-floor.test.ts b/test/bun-floor.test.tsnew file mode 100644index 0000000000..c125408118--- /dev/null+++ b/test/bun-floor.test.ts@@ -0,0 +1,173 @@+/**+ * #5855: reading an upgrade target's Bun floor and the host's Bun.+ *+ * Protects: the floor shapes a release can pin (only `>=X.Y.Z`; anything else+ * is unreadable and holds), canary and `--revision` Bun versions ordering by+ * semver, the bun-link reader returning the fetched SHA it read the floor at,+ * the package reader following the global install's pinned spec, the host Bun+ * being the lower of PATH and the running binary, and the refusal wording.+ * Regression: a looser floor parse that reads `^1.4.0` or `--1` as satisfied,+ * a canary read as unparseable (holding forever), a bun-link check that reads+ * the floor of a commit other than the one installed, a PATH-only Bun reading.+ * Existing coverage: none (the readers are new; adapted from PR #5860's tests).+ */+import { afterAll, afterEach, describe, expect, test } from 'bun:test';+import { execFileSync } from 'node:child_process';+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import {+ BUN_FLOOR_FIX,+ evaluateBunFloor,+ globalGbrainSpec,+ parseReleasePackage,+ rawPackageUrlForSpec,+ readBunLinkTarget,+ readHostBun,+ readPackageTarget,+} from '../src/core/bun-floor.ts';+import { bunVersionMeets, compareBunVersions } from '../src/core/runtime-version.ts';+import { makeGitFixture } from './helpers/git-fixture.ts';+import { withEnv } from './helpers/with-env.ts';++const realFetch = globalThis.fetch;+const dirs: string[] = [];+afterEach(() => { globalThis.fetch = realFetch; });+afterAll(() => { for (const d of dirs) rmSync(d, { recursive: true, force: true }); });+function tmp(label: string): string {+ const d = mkdtempSync(join(tmpdir(), `gbrain-bun-floor-${label}-`));+ dirs.push(d);+ return d;+}++describe('Bun version ordering', () => {+ test('canary and revision builds parse and order by semver', () => {+ const cases: Array<[string, string, boolean | null]> = [+ ['1.4.0', '1.4.0', true],+ ['1.4.2', '1.4.0', true],+ ['1.4.2+5a1b2c3', '1.4.0', true],+ ['1.3.14', '1.4.0', false],+ ['1.4.0-canary.1', '1.4.0', false],+ ['1.4.0-canary.1+abc', '1.4.0', false],+ ['1.5.0-canary.3+abc', '1.4.0', true],+ ['2.0.0', '1.99.99', true],+ ['bun is great', '1.4.0', null],+ ['', '1.4.0', null],+ ];+ for (const [version, floor, meets] of cases) expect(bunVersionMeets(version, floor), version).toBe(meets);+ expect(compareBunVersions('1.4.0-canary.2', '1.4.0')! < 0).toBe(true);+ expect(compareBunVersions('1.4.2+abc', '1.4.2')).toBe(0);+ });+});++describe('release package.json', () => {+ test('only a `>=X.Y.Z` engines.bun floor is read; every other shape is null', () => {+ const cases: Array<[string, string | null]> = [+ [JSON.stringify({ name: 'gbrain', version: '0.61.0.0', engines: { bun: '>=1.4.0' } }), '1.4.0'],+ [JSON.stringify({ engines: { bun: '>= 1.5.1' } }), '1.5.1'],+ [JSON.stringify({ engines: { node: '>=20' } }), null],+ [JSON.stringify({ engines: { bun: 140 } }), null],+ [JSON.stringify({ engines: { bun: '*' } }), null],+ [JSON.stringify({ engines: { bun: '^1.4.0' } }), null],+ [JSON.stringify({ engines: { bun: '>=1.4.0 <2' } }), null],+ [JSON.stringify({ engines: { bun: '=>1.4.0' } }), null],+ [JSON.stringify({ engines: { bun: '--1' } }), null],+ [JSON.stringify({ engines: { bun: '$(rm -rf /)' } }), null],+ [JSON.stringify({ engines: { bun: `>=${'1'.repeat(200)}.0.0` } }), null],+ ['<html>rate limited</html>', null],+ [`{"engines":{"bun":">=1.4.0"},"pad":"${'x'.repeat(300_000)}"}`, null],+ ];+ for (const [body, floor] of cases) expect(parseReleasePackage(body).floor, body.slice(0, 60)).toBe(floor);+ expect(parseReleasePackage(cases[0][0]).version).toBe('0.61.0.0');+ });++ test('a GitHub spec maps to package.json at the ref it installs; other specs are unreadable', () => {+ expect(rawPackageUrlForSpec('github:garrytan/gbrain')).toBe('https://raw.githubusercontent.com/garrytan/gbrain/HEAD/package.json');+ expect(rawPackageUrlForSpec('github:garrytan/gbrain#v0.51.0')).toBe('https://raw.githubusercontent.com/garrytan/gbrain/v0.51.0/package.json');+ expect(rawPackageUrlForSpec('git+https://github.com/acme-example/gbrain-fork.git#main')).toBe('https://raw.githubusercontent.com/acme-example/gbrain-fork/main/package.json');+ expect(rawPackageUrlForSpec('^1.3.0')).toBeNull();+ expect(rawPackageUrlForSpec('github:garrytan/gbrain#../../x')).toBeNull();+ });++ test('the package reader fetches the pinned ref of the global install and fails closed', async () => {+ const root = tmp('global');+ writeFileSync(join(root, 'package.json'), JSON.stringify({ dependencies: { gbrain: 'github:garrytan/gbrain#v0.70.0' } }));+ expect(globalGbrainSpec(root)).toBe('github:garrytan/gbrain#v0.70.0');+ const fetched: string[] = [];+ globalThis.fetch = (async (url: any) => {+ fetched.push(String(url));+ return new Response(JSON.stringify({ version: '0.70.0.0', engines: { bun: '>=1.6.0' } }));+ }) as typeof fetch;+ expect(await readPackageTarget(globalGbrainSpec(root))).toEqual({ ok: true, floor: '1.6.0', version: '0.70.0.0' });+ expect(fetched).toEqual(['https://raw.githubusercontent.com/garrytan/gbrain/v0.70.0/package.json']);++ globalThis.fetch = (async () => new Response('Not Found', { status: 404 })) as unknown as typeof fetch;+ expect(await readPackageTarget(null)).toEqual({ ok: false, failedRead: 'GET https://raw.githubusercontent.com/garrytan/gbrain/HEAD/package.json returned HTTP 404' });+ globalThis.fetch = (async () => { throw new Error('network down'); }) as unknown as typeof fetch;+ expect((await readPackageTarget(null)).ok).toBe(false);+ expect((await readPackageTarget('^1.3.0')).ok).toBe(false);+ });+});++describe('bun-link target', () => {+ test('reads the floor at the fetched upstream SHA, not the checkout; no upstream is unreadable', async () => {+ const root = tmp('bunlink');+ const origin = join(root, 'origin');+ mkdirSync(origin);+ const upstream = await makeGitFixture(origin);+ writeFileSync(join(origin, 'package.json'), JSON.stringify({ version: '0.60.0.0', engines: { bun: '>=1.4.0' } }));+ upstream.commitAll('floor 1.4.0');+ const clone = join(root, 'clone');+ execFileSync('git', ['clone', '-q', origin, clone], { stdio: 'ignore' });+ writeFileSync(join(origin, 'package.json'), JSON.stringify({ version: '0.61.0.0', engines: { bun: '>=1.9.0' } }));+ upstream.commitAll('floor 1.9.0');+ const originHead = execFileSync('git', ['-C', origin, 'rev-parse', 'HEAD'], { encoding: 'utf8' }).trim();++ expect(readBunLinkTarget(clone)).toEqual({ sha: originHead, target: { ok: true, floor: '1.9.0', version: '0.61.0.0' } });++ execFileSync('git', ['-C', clone, 'checkout', '-q', '-b', 'no-upstream'], { stdio: 'ignore' });+ expect(readBunLinkTarget(clone)).toEqual({ sha: null, target: { ok: false, failedRead: 'the source clone has no upstream branch to read' } });+ });+});++describe('host Bun', () => {+ test('the lower of the bun on PATH and the running Bun decides; an unrunnable PATH bun is null', async () => {+ const dir = tmp('path-bun');+ const bun = join(dir, 'bun');+ const stub = (body: string | null) => {+ rmSync(bun, { force: true });+ if (body) writeFileSync(bun, `#!/bin/sh\n${body}\n`, { mode: 0o755 });+ };+ stub('echo 1.3.14');+ expect(await withEnv({ PATH: dir }, () => readHostBun())).toEqual({ label: 'bun on PATH', path: bun, version: '1.3.14' });+ stub('echo 1.3.14+5a1b2c3');+ expect((await withEnv({ PATH: dir }, () => readHostBun()))?.version).toBe('1.3.14+5a1b2c3');+ stub('echo 99.0.0');+ const running = await withEnv({ PATH: dir }, () => readHostBun());+ expect(running?.label).toBe('the running Bun');+ expect(running?.path).toBe(process.execPath);+ expect(running?.version.split('+')[0]).toBe(Bun.version);+ for (const body of ['echo "bun is great"', 'exit 1', null]) {+ stub(body);+ expect(await withEnv({ PATH: dir }, () => readHostBun()), String(body)).toBeNull();+ }+ });+});++describe('refusal wording', () => {+ test('names the target, floor, Bun found with its path, the fix and the docs; the audit copy drops the path', () => {+ const verdict = evaluateBunFloor({ ok: true, floor: '1.4.0', version: '0.61.0.0' }, { label: 'bun on PATH', path: '/opt/bun/bin/bun', version: '1.3.14' });+ expect(verdict).toEqual({+ ok: false,+ kind: 'unmet',+ message: 'gbrain 0.61.0.0 requires Bun >=1.4.0; bun on PATH (/opt/bun/bin/bun) is 1.3.14. Fix: bun upgrade, then gbrain upgrade. Docs: docs/guides/upgrades-auto-update.md#bun-floor',+ auditReason: `gbrain 0.61.0.0 requires Bun >=1.4.0; bun on PATH is 1.3.14. ${BUN_FLOOR_FIX}`,+ });+ expect(evaluateBunFloor({ ok: true, floor: '1.4.0', version: null }, { label: 'bun on PATH', path: '/b', version: '1.4.0' })).toEqual({ ok: true });+ const unreadable = evaluateBunFloor({ ok: false, failedRead: '`git fetch` in the source clone failed' }, null, '0.99.0.0');+ expect(unreadable.ok || unreadable.message).toBe('Could not read the Bun floor of gbrain 0.99.0.0: `git fetch` in the source clone failed. Docs: docs/guides/upgrades-auto-update.md#bun-floor');+ const noBun = evaluateBunFloor({ ok: true, floor: '1.4.0', version: '0.61.0.0' }, null);+ expect(noBun.ok || noBun.kind).toBe('unreadable');+ expect(noBun.ok || noBun.message).toContain('could not run `bun --version` on PATH');+ });+});diff --git a/test/doctor-self-upgrade.test.ts b/test/doctor-self-upgrade.test.tsindex d4eb2749c5..1785b8f231 100644--- a/test/doctor-self-upgrade.test.ts+++ b/test/doctor-self-upgrade.test.ts@@ -1,10 +1,10 @@-import { describe, expect, test } from 'bun:test';+import { describe, expect, setSystemTime, test } from 'bun:test';import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';import { tmpdir } from 'node:os';import { join } from 'node:path';import { withEnv } from './helpers/with-env.ts';import { buildChecks, checkSelfUpgradeHealth } from '../src/commands/doctor.ts';-import { writeUpdateCache } from '../src/core/self-upgrade.ts';+import { decideSelfUpgrade, gateOnTargetRuntime, writeUpdateCache } from '../src/core/self-upgrade.ts';import { logSelfUpgrade } from '../src/core/audit/self-upgrade-audit.ts';import { VERSION } from '../src/version.ts';@@ -66,6 +66,58 @@ describe('checkSelfUpgradeHealth', () => {});});+ test('#5855: an auto-upgrade held for the Bun floor warns with the fix line until a later apply or a manual upgrade to it', async () => {+ const apply = decideSelfUpgrade({ mode: 'auto', channel: 'autopilot', currentVersion: '0.42.0', latestVersion: '0.99.0', failedVersions: [], idle: true, inQuietHours: true, canSelfUpdate: true });+ const unmet = gateOnTargetRuntime(apply, { ok: true, floor: '9.0.0', version: '0.99.0' }, { label: 'bun on PATH', path: '/opt/bun', version: '1.4.2' });+ await withHome(() => {+ logSelfUpgrade({ channel: 'autopilot', action: 'apply', current: '0.42.0', latest: '0.43.0', outcome: 'failed', error: 'boom' });+ logSelfUpgrade({ channel: 'autopilot', action: unmet.action, current: '0.42.0', latest: '0.99.0', outcome: 'skipped', reason: unmet.reason });+ const c = checkSelfUpgradeHealth();+ expect(c.status).toBe('warn');+ expect(c.message).toContain('Auto-upgrade to 0.99.0 held: gbrain 0.99.0 requires Bun >=9.0.0; bun on PATH is 1.4.2. Fix: bun upgrade, then gbrain upgrade. Docs: docs/guides/upgrades-auto-update.md#bun-floor');++ logSelfUpgrade({ channel: 'autopilot', action: 'apply', current: '0.42.0', latest: '0.99.0', reason: 'auto-upgrading 0.42.0 -> 0.99.0' });+ expect(checkSelfUpgradeHealth().message).not.toContain('held');++ logSelfUpgrade({ channel: 'autopilot', action: 'unsupported_runtime', current: '0.42.0', latest: VERSION, outcome: 'skipped', reason: `gbrain ${VERSION} requires Bun >=9.0.0` });+ expect(checkSelfUpgradeHealth().message).not.toContain('held');+ });+ });++ test('#5855: a hold on an unreadable floor names the failed read', async () => {+ const apply = decideSelfUpgrade({ mode: 'auto', channel: 'autopilot', currentVersion: '0.42.0', latestVersion: '0.99.0', failedVersions: [], idle: true, inQuietHours: true, canSelfUpdate: true });+ const unreadable = gateOnTargetRuntime(apply, { ok: false, failedRead: 'GET https://raw.githubusercontent.com/garrytan/gbrain/HEAD/package.json returned HTTP 503' }, { label: 'bun on PATH', path: '/opt/bun', version: '1.4.2' });+ await withHome(() => {+ logSelfUpgrade({ channel: 'autopilot', action: unreadable.action, current: '0.42.0', latest: '0.99.0', outcome: 'skipped', reason: unreadable.reason });+ const c = checkSelfUpgradeHealth();+ expect(c.status).toBe('warn');+ expect(c.message).toContain('Auto-upgrade to 0.99.0 held: Could not read the Bun floor of gbrain 0.99.0: GET https://raw.githubusercontent.com/garrytan/gbrain/HEAD/package.json returned HTTP 503.');+ expect(c.message).toContain('The next quiet-hours tick retries.');+ });+ });++ test('#5855: the newest event decides across the ISO-week boundary (held state and the last failure)', async () => {+ // Wednesday of ISO week 40; the previous-week events sit on Sunday of week 39.+ setSystemTime(new Date('2026-09-30T12:00:00Z'));+ try {+ await withHome(() => {+ logSelfUpgrade({ ts: '2026-09-27T23:00:00.000Z', channel: 'autopilot', action: 'apply', current: '0.42.0', latest: '0.43.0', reason: 'auto-upgrading 0.42.0 -> 0.43.0' });+ logSelfUpgrade({ channel: 'autopilot', action: 'unsupported_runtime', current: '0.43.0', latest: '0.99.0', outcome: 'skipped', reason: 'gbrain 0.99.0 requires Bun >=9.0.0' });+ expect(checkSelfUpgradeHealth().message).toContain('Auto-upgrade to 0.99.0 held');+ });+ await withHome(() => {+ logSelfUpgrade({ ts: '2026-09-27T23:00:00.000Z', channel: 'autopilot', action: 'apply', current: '0.42.0', latest: '0.43.0', outcome: 'failed', error: 'older' });+ logSelfUpgrade({ channel: 'autopilot', action: 'apply', current: '0.42.0', latest: '0.44.0', outcome: 'failed', error: 'newer' });+ const message = checkSelfUpgradeHealth().message;+ expect(message).toContain('Last: 0.44.0');+ expect(message).toContain('newer');+ expect(message).not.toContain('older');+ });+ } finally {+ setSystemTime();+ }+ });+test('known-bad versions in config are surfaced', async () => {await withHome((home) => {mkdirSync(join(home, '.gbrain'), { recursive: true });diff --git a/test/runtime-version.test.ts b/test/runtime-version.test.tsindex ee73ceafe3..eca260796e 100644--- a/test/runtime-version.test.ts+++ b/test/runtime-version.test.ts@@ -40,7 +40,7 @@ describe('Bun runtime floor', () => {});test('the floor and newer releases start', () => {- for (const version of ['1.4.0', '1.4.2', '1.5.0', '2.0.0', '1.4.2+abc123']) {+ for (const version of ['1.4.0', '1.4.2', '1.5.0', '2.0.0', '1.4.2+abc123', '1.5.0-canary.3+abc123']) {expect(unsupportedBunMessage(version)).toBeNull();expect(() => assertSupportedBun(version)).not.toThrow();}diff --git a/test/self-upgrade.test.ts b/test/self-upgrade.test.tsindex 46b433c068..848bd39e19 100644--- a/test/self-upgrade.test.ts+++ b/test/self-upgrade.test.ts@@ -9,6 +9,7 @@ import {clearUpdateCache,decideSelfUpgrade,formatMarker,+ gateOnTargetRuntime,isCacheFresh,isSnoozeActive,parseMarker,@@ -20,8 +21,10 @@ import {writeSnooze,writeUpdateCache,type DecideSelfUpgradeInputs,+ type SelfUpgradeAction,type SelfUpgradeState,} from '../src/core/self-upgrade.ts';+import type { HostBun, TargetFloor } from '../src/core/bun-floor.ts';function baseInputs(over: Partial<DecideSelfUpgradeInputs> = {}): DecideSelfUpgradeInputs {return {@@ -121,6 +124,33 @@ describe('decideSelfUpgrade — pure branches', () => {test('gate order: known_bad beats idle/quiet gates', () => {expect(auto({ failedVersions: ['0.43.0'], idle: false }).action).toBe('known_bad');});++ test('#5855: an apply is held when the target Bun floor is above the host Bun, or either is unknown', () => {+ const bun = (version: string): HostBun => ({ label: 'bun on PATH', path: '/opt/bun', version });+ const floor = (f: string): TargetFloor => ({ ok: true, floor: f, version: null });+ const cases: Array<{ target: TargetFloor; host: HostBun | null; action: SelfUpgradeAction; reason?: string[] }> = [+ { target: floor('1.4.0'), host: bun('1.4.2'), action: 'apply' },+ { target: floor('1.4.0'), host: bun('1.4.0'), action: 'apply' },+ { target: floor('1.4.0'), host: bun('1.4.0+5a1b2c3'), action: 'apply' },+ { target: floor('1.4.0'), host: bun('1.5.0-canary.2'), action: 'apply' },+ { target: floor('1.4.0'), host: bun('1.4.0-canary.9'), action: 'unsupported_runtime', reason: ['gbrain 0.43.0 requires Bun >=1.4.0', 'bun on PATH is 1.4.0-canary.9'] },+ { target: floor('1.4.0'), host: bun('1.3.14'), action: 'unsupported_runtime', reason: ['gbrain 0.43.0 requires Bun >=1.4.0', 'bun on PATH is 1.3.14', 'Fix: bun upgrade, then gbrain upgrade'] },+ { target: { ok: false, failedRead: '`git fetch` in the source clone failed' }, host: bun('1.4.2'), action: 'unsupported_runtime', reason: ['Could not read the Bun floor of gbrain 0.43.0', 'The next quiet-hours tick retries'] },+ { target: floor('1.4.0'), host: null, action: 'unsupported_runtime', reason: ['could not run `bun --version` on PATH'] },+ ];+ for (const c of cases) {+ const d = gateOnTargetRuntime(auto(), c.target, c.host);+ expect(d.action, JSON.stringify(c)).toBe(c.action);+ expect(d.latest).toBe('0.43.0');+ for (const fragment of c.reason ?? []) expect(d.reason).toContain(fragment);+ expect(d.reason).not.toContain('/opt/bun');+ }+ });++ test('#5855: the runtime gate leaves a non-apply decision unchanged', () => {+ const busy = auto({ idle: false });+ expect(gateOnTargetRuntime(busy, { ok: true, floor: '9.0.0', version: null }, null)).toEqual(busy);+ });});});diff --git a/test/upgrade-bun-link-arc.serial.test.ts b/test/upgrade-bun-link-arc.serial.test.tsindex 898eef1681..18512cf6bc 100644--- a/test/upgrade-bun-link-arc.serial.test.ts+++ b/test/upgrade-bun-link-arc.serial.test.ts@@ -104,6 +104,7 @@ interface BaseFixture {interface Fixture extends BaseFixture {origin: string; // local bare origin; its PATH carries the detection markerclone: string; // the "bun-linked" source clone, one commit behind origin+ ahead: string; // working copy that pushes to origindriver: string; // untracked <clone>/src/cli.ts — the bun-link entry pointoriginHead: string; // commit B (ahead)cloneHeadBefore: string; // commit A@@ -126,16 +127,22 @@ function makeBase(label: string): BaseFixture {// Recorder ONLY (never runs the real bun, prints nothing). Also notes the// cwd repo's HEAD at call time so "git pull ran BEFORE bun install" is// provable without shimming git itself.+ // #5855: `bun --version` is the Bun-floor probe, answered (not recorded) with+ // GBRAIN_TEST_BUN_VERSION; GBRAIN_TEST_ON_BUN_PROBE runs a script there, the+ // moment between the floor check and the fast-forward.writeShim(shimDir,'bun',- `printf 'bun %s ::head=%s\\n' "$*" "$(git rev-parse HEAD 2>/dev/null || echo none)" >> "${argvLog}"\nexit 0\n`,+ `if [ "\${1:-}" = "--version" ]; then echo "\${GBRAIN_TEST_BUN_VERSION:-1.4.2}"; if [ -n "\${GBRAIN_TEST_ON_BUN_PROBE:-}" ]; then bash "$GBRAIN_TEST_ON_BUN_PROBE" >/dev/null 2>&1; fi; exit 0; fi\n`+ + `printf 'bun %s ::head=%s\\n' "$*" "$(git rev-parse HEAD 2>/dev/null || echo none)" >> "${argvLog}"\nexit 0\n`,);- // Recorder; answers --version so verifyUpgrade resolves a new version.+ // Recorder; answers --version so verifyUpgrade resolves a new version, and+ // fails the post-swap `--help` smoke when GBRAIN_TEST_HELP_EXIT is set.writeShim(shimDir,'gbrain',- `printf 'gbrain %s\\n' "$*" >> "${argvLog}"\nif [ "\${1:-}" = "--version" ]; then echo 'gbrain ${SHIM_NEW_VERSION}'; fi\nexit 0\n`,+ `printf 'gbrain %s\\n' "$*" >> "${argvLog}"\nif [ "\${1:-}" = "--version" ]; then echo 'gbrain ${SHIM_NEW_VERSION}'; fi\n`+ + `if [ "\${1:-}" = "--help" ] && [ -n "\${GBRAIN_TEST_HELP_EXIT:-}" ]; then echo 'GBrain requires Bun 1.4.0 or newer (found Bun 1.3.14).' >&2; exit "$GBRAIN_TEST_HELP_EXIT"; fi\nexit 0\n`,);// Containment no-ops: nothing in these arcs should reach machine-global// schedulers; if a future regression does, it lands here, not in crontab.@@ -145,13 +152,21 @@ function makeBase(label: string): BaseFixture {return { root, home, shimDir, argvLog };}-/** Local seed repo → bare origin (path contains the marker) → clone one commit behind. */-function buildFixture(label: string): Fixture {+function releasePackage(version: string, bunFloor: string): string {+ return JSON.stringify({ name: 'gbrain', version, engines: { bun: bunFloor } }) + '\n';+}++/**+ * Local seed repo → bare origin (path contains the marker) → clone one commit+ * behind. `aheadFloor` is the `engines.bun` of the commit the clone upgrades to.+ */+function buildFixture(label: string, aheadFloor = '>=1.4.0'): Fixture {const base = makeBase(label);const seed = join(base.root, 'seed');mkdirSync(seed, { recursive: true });writeFileSync(join(seed, 'notes.txt'), 'commit one\n');+ writeFileSync(join(seed, 'package.json'), releasePackage('0.0.1.0', '>=1.4.0'));git(['init', '-q'], seed);git(['add', '-A'], seed);git([...GIT_IDENTITY, 'commit', '-q', '-m', 'c1'], seed);@@ -169,6 +184,7 @@ function buildFixture(label: string): Fixture {const ahead = join(base.root, 'ahead');git(['clone', '-q', origin, ahead]);writeFileSync(join(ahead, 'feature.txt'), 'commit two\n');+ writeFileSync(join(ahead, 'package.json'), releasePackage(SHIM_NEW_VERSION, aheadFloor));git(['add', '-A'], ahead);git([...GIT_IDENTITY, 'commit', '-q', '-m', 'c2'], ahead);git(['push', '-q', 'origin', 'HEAD'], ahead);@@ -209,7 +225,7 @@ function buildFixture(label: string): Fixture {].join('\n'),);- return { ...base, origin, clone, driver, originHead, cloneHeadBefore };+ return { ...base, origin, clone, ahead, driver, originHead, cloneHeadBefore };}function argvLines(fx: BaseFixture): string[] {@@ -335,6 +351,7 @@ describe('runUpgrade — bun-link arc (real git vs local bare origin; bun/gbrainexpect(argvLines(fx)).toEqual([`bun install ::head=${fx.originHead}`,'gbrain --version',+ 'gbrain --help','gbrain post-upgrade','gbrain features',]);@@ -358,10 +375,11 @@ describe('runUpgrade — bun-link arc (real git vs local bare origin; bun/gbrain// Swap still happened...expect(git(['rev-parse', 'HEAD'], fx.clone).trim()).toBe(fx.originHead);- // ...but the child chain stops after the version verify.+ // ...but the child chain stops after the version verify and runtime smoke.expect(argvLines(fx)).toEqual([`bun install ::head=${fx.originHead}`,'gbrain --version',+ 'gbrain --help',]);// State + breadcrumb still written (the next launch runs post-upgrade).@@ -372,6 +390,66 @@ describe('runUpgrade — bun-link arc (real git vs local bare origin; bun/gbrain}, 120_000);});+// ── 2b. the Bun floor gate and post-swap smoke (#5855) ───────────────────────++describe('runUpgrade — bun-link Bun floor gate (#5855)', () => {+ test('a target whose Bun floor is above the host Bun is refused with the fix; nothing is swapped', async () => {+ const fx = buildFixture('floor-unmet', '>=9.9.9');+ const run = await spawnWithShims(fx, [fx.driver, '--swap-only']);+ expect(run.code).toBe(78);+ expect(run.err).toContain(`gbrain ${SHIM_NEW_VERSION} requires Bun >=9.9.9; bun on PATH (${join(fx.shimDir, 'bun')}) is 1.4.2. `+ + 'Fix: bun upgrade, then gbrain upgrade. Docs: docs/guides/upgrades-auto-update.md#bun-floor');+ expect(run.err).toContain('Nothing was changed.');+ expect(git(['rev-parse', 'HEAD'], fx.clone).trim()).toBe(fx.cloneHeadBefore);+ expect(argvLines(fx)).toEqual([]);+ expect(existsSync(join(fx.home, '.gbrain', 'upgrade-state.json'))).toBe(false);+ expect(existsSync(join(fx.home, '.gbrain', 'just-upgraded-from'))).toBe(false);+ }, 120_000);++ test('an unreadable floor refuses and names the read and --no-bun-floor-check, which overrides it', async () => {+ const fx = buildFixture('floor-unreadable', '^1.4.0');+ const refused = await spawnWithShims(fx, [fx.driver, '--swap-only']);+ expect(refused.code).toBe(78);+ expect(refused.err).toContain(`Could not read the Bun floor of gbrain ${SHIM_NEW_VERSION}: \`git show ${fx.originHead.slice(0, 12)}:package.json\` has no \`engines.bun\` floor of the form >=X.Y.Z.`);+ expect(refused.err).toContain('Re-run with --no-bun-floor-check to upgrade without this check.');+ expect(git(['rev-parse', 'HEAD'], fx.clone).trim()).toBe(fx.cloneHeadBefore);++ const forced = await spawnWithShims(fx, [fx.driver, '--swap-only', '--no-bun-floor-check']);+ assertExit0('upgrade driver (--no-bun-floor-check)', forced);+ expect(git(['rev-parse', 'HEAD'], fx.clone).trim()).toBe(fx.originHead);+ }, 120_000);++ test('the installed commit is the checked one when upstream raises its floor after the check (E11)', async () => {+ const fx = buildFixture('floor-race');+ const advance = join(fx.root, 'advance.sh');+ writeFileSync(advance, [+ `cd ${JSON.stringify(fx.ahead)}`,+ `printf '%s' ${JSON.stringify(releasePackage('9.9.9.10', '>=9.9.9'))} > package.json`,+ 'git add -A',+ `git ${GIT_IDENTITY.join(' ')} commit -q -m c3`,+ 'git push -q origin HEAD',+ ].join('\n'));+ const run = await spawnWithShims(fx, [fx.driver, '--swap-only'], { GBRAIN_TEST_ON_BUN_PROBE: advance });+ assertExit0('upgrade driver (upstream advanced mid-upgrade)', run);+ const originNow = git(['rev-parse', 'HEAD'], fx.origin).trim();+ expect(originNow).not.toBe(fx.originHead);+ expect(git(['rev-parse', 'HEAD'], fx.clone).trim()).toBe(fx.originHead);+ }, 120_000);++ test('a swapped release that fails the runtime smoke exits non-zero with per-method recovery', async () => {+ const fx = buildFixture('smoke');+ const run = await spawnWithShims(fx, [fx.driver, '--swap-only'], { GBRAIN_TEST_HELP_EXIT: '1' });+ expect(run.code).toBe(1);+ expect(run.err).toContain(`gbrain ${SHIM_NEW_VERSION} was installed but does not start: \`gbrain --help\` failed (exit 1).`);+ expect(run.err).toContain('GBrain requires Bun 1.4.0 or newer (found Bun 1.3.14).');+ expect(run.err).toContain('If it names an old Bun: bun upgrade, then gbrain post-upgrade');+ expect(run.err).toContain(`To return to ${VERSION}: git -C ${fx.clone} checkout ${fx.cloneHeadBefore} && bun install`);+ const errors = readFileSync(join(fx.home, '.gbrain', 'upgrade-errors.jsonl'), 'utf-8').trim().split('\n').map((l) => JSON.parse(l));+ expect(errors.at(-1)).toMatchObject({ phase: 'post-swap-smoke', from_version: VERSION, to_version: SHIM_NEW_VERSION });+ expect(existsSync(join(fx.home, '.gbrain', 'just-upgraded-from'))).toBe(false);+ }, 120_000);+});+// ── 3. runPostUpgrade checkpoint (spawned — runApplyMigrations owns exit(0)) ──describe('runPostUpgrade — migration-ledger checkpoint (spawned)', () => {diff --git a/test/upgrade-exact-tag-pin.serial.test.ts b/test/upgrade-exact-tag-pin.serial.test.tsindex a7fd3b4265..35e6f42b5a 100644--- a/test/upgrade-exact-tag-pin.serial.test.ts+++ b/test/upgrade-exact-tag-pin.serial.test.ts@@ -35,7 +35,7 @@ async function runBareUpgrade(spec: string, observedVersion: string): Promise<{writeFileSync(join(globalRoot, 'package.json'), JSON.stringify({ dependencies: { gbrain: spec } }));writeFileSync(join(pkgDir, 'package.json'), JSON.stringify({ name: 'gbrain', repository: 'github:garrytan/gbrain' }));const driver = join(pkgDir, 'driver.ts');- writeFileSync(driver, `import { runUpgrade } from '${REPO}/src/commands/upgrade.ts';\nawait runUpgrade(['--swap-only']);\n`);+ writeFileSync(driver, `import { runUpgrade } from '${REPO}/src/commands/upgrade.ts';\nawait runUpgrade(['--swap-only', '--no-bun-floor-check']);\n`);const env: Record<string, string | undefined> = { ...process.env, HOME: home, GBRAIN_HOME: home, PATH: `${bin}:${process.env.PATH}` };delete env.BUN_INSTALL;const proc = Bun.spawn([process.execPath, 'run', driver], { cwd: REPO, env, stdout: 'pipe', stderr: 'pipe' });diff --git a/test/upgrade-migration-outcome.serial.test.ts b/test/upgrade-migration-outcome.serial.test.tsindex 39e58c2312..116e014ce3 100644--- a/test/upgrade-migration-outcome.serial.test.ts+++ b/test/upgrade-migration-outcome.serial.test.ts@@ -27,7 +27,7 @@ function runUpgradeHarness(opts: { bunExit?: number; postUpgradeExit?: number; copts.setup?.(home);writeFileSync(join(pkg, 'package.json'), JSON.stringify({ name: 'gbrain', repository: { url: 'https://github.com/garrytan/gbrain' } }));const driver = join(pkg, 'src', 'cli.ts');- writeFileSync(driver, `const { runUpgrade } = await import(${JSON.stringify(join(REPO, 'src/commands/upgrade.ts'))});\nawait runUpgrade([]);\n`);+ writeFileSync(driver, `const { runUpgrade } = await import(${JSON.stringify(join(REPO, 'src/commands/upgrade.ts'))});\nawait runUpgrade(['--no-bun-floor-check']);\n`);writeFileSync(join(bin, 'bun'), `#!/bin/sh\nprintf 'bun:%s:owns=%s\\n' "$*" "$GBRAIN_UPGRADE_OWNS_MIGRATIONS" >> "$HOME/calls.log"\n${JSON.stringify(process.execPath)} ${JSON.stringify(join(REPO, 'scripts/postinstall.ts'))}\nexit ${opts.bunExit ?? 0}\n`, { mode: 0o755 });writeFileSync(join(bin, 'gbrain'), `#!/bin/sh\nprintf 'gbrain:%s\\n' "$*" >> "$HOME/calls.log"\nif [ "$1" = '--version' ]; then echo 'gbrain ${NEWER}'; fi\nif [ "$1" = 'post-upgrade' ]; then exit ${opts.postUpgradeExit ?? 0}; fi\nexit 0\n`, { mode: 0o755 });const result = spawnSync(process.execPath, ['--no-env-file', driver], {diff --git a/test/upgrade-no-autopilot.serial.test.ts b/test/upgrade-no-autopilot.serial.test.tsindex 8f45c35474..737586ca05 100644--- a/test/upgrade-no-autopilot.serial.test.ts+++ b/test/upgrade-no-autopilot.serial.test.ts@@ -18,7 +18,7 @@ describe('upgrade autopilot opt-out propagation', () => {mkdirSync(join(home, '.bun', 'install', 'global'), { recursive: true });writeFileSync(join(pkg, 'package.json'), JSON.stringify({ name: 'gbrain', repository: { url: 'https://github.com/garrytan/gbrain' } }));const driver = join(pkg, 'src', 'cli.ts');- writeFileSync(driver, `const { runUpgrade } = await import(${JSON.stringify(join(REPO, 'src/commands/upgrade.ts'))});\nawait runUpgrade(['--no-autopilot-install']);\n`);+ writeFileSync(driver, `const { runUpgrade } = await import(${JSON.stringify(join(REPO, 'src/commands/upgrade.ts'))});\nawait runUpgrade(['--no-autopilot-install', '--no-bun-floor-check']);\n`);writeFileSync(join(bin, 'bun'), `#!/bin/sh\nprintf 'bun:%s:no-autopilot=%s\\n' "$*" "$GBRAIN_NO_AUTOPILOT_INSTALL" >> "$HOME/calls.log"\nexec ${JSON.stringify(process.execPath)} ${JSON.stringify(join(REPO, 'scripts/postinstall.ts'))}\n`, { mode: 0o755 });writeFileSync(join(bin, 'gbrain'), `#!/bin/sh\nprintf 'gbrain:%s:no-autopilot=%s\\n' "$*" "$GBRAIN_NO_AUTOPILOT_INSTALL" >> "$HOME/calls.log"\nif [ "$1" = '--version' ]; then echo 'gbrain ${VERSION}'; fi\n`, { mode: 0o755 });const result = spawnSync(process.execPath, ['--no-env-file', driver], {diff --git a/test/upgrade.serial.test.ts b/test/upgrade.serial.test.tsindex 1dc0bbe5cd..34698b6b97 100644--- a/test/upgrade.serial.test.ts+++ b/test/upgrade.serial.test.ts@@ -272,7 +272,7 @@ describe('runUpgrade target verification (#4366)', () => {mockPrelude +`import { runUpgrade } from '${repoRoot}src/commands/upgrade.ts';\n` +`const t = process.env.TEST_TARGET_VERSION;\n` +- `await runUpgrade(['--swap-only'], t ? { targetVersion: t } : {});\n`,+ `await runUpgrade(['--swap-only', '--no-bun-floor-check'], t ? { targetVersion: t } : {});\n`,);let bunExec = process.execPath;if (opts.binaryResult) {@@ -429,7 +429,8 @@ describe('runUpgrade target verification (#4366)', () => {try {const root = join(home, repoDir);expect(stdout).toContain('Detected install method: bun-link');- const calls = readFileSync(join(home, 'calls.log'), 'utf-8').trim().split('\n');+ // `rev-parse HEAD` records the pre-swap commit for #5855's recovery text.+ const calls = readFileSync(join(home, 'calls.log'), 'utf-8').trim().split('\n').filter((c) => !c.endsWith(' rev-parse HEAD'));expect(calls[0]!.split('|')[1]).toBe(`-C ${root} pull --ff-only`);expect(calls[1]).toBe(`${realpathSync(root)}|install`);for (const dir of [home, repoRoot, join(root, 'src')]) {