Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(upgrade): never run `clawhub update gbrain`; detect renamed compiled binaries
garrytan97bc17a55135
diff --git a/docs/RELEASING.md b/docs/RELEASING.mdindex 6a57c1bb9f..04934b3e8a 100644--- a/docs/RELEASING.md+++ b/docs/RELEASING.md@@ -944,8 +944,10 @@ bun run publish:clawhub # clawhub package publish . --family bundle-plugin````build:all` compiles only those two targets; the full binary matrix ships-through the GitHub release job above. ClawHub users upgrade with-`clawhub update gbrain`, which `gbrain upgrade` runs for ClawHub installs.+through the GitHub release job above. `gbrain upgrade` never runs+`clawhub update gbrain` (#8464): that command updates a ClawHub *skill* named+gbrain from any publisher, and we publish none, so it would install someone+else's package.## Plugin dist tree (codex/claude lanes)diff --git a/docs/architecture/key-files/commands-6.md b/docs/architecture/key-files/commands-6.mdindex d1df7f91b3..ed04be8b3c 100644--- a/docs/architecture/key-files/commands-6.md+++ b/docs/architecture/key-files/commands-6.md@@ -12,7 +12,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/commands/transcripts.ts` — the transcripts command family, all local-only (`ctx.remote=false` by construction). `recent`: raw `.txt` corpus reads via `listRecentTranscripts` (same library as the gated `get_recent_transcripts` op). `ingest <path-or-glob>`: the cross-harness session importer — resolves ONE source id (6-tier chain), threads activePack once, streams progress (phase `transcripts.ingest`), and calls `runTranscriptsIngest` with the CLI's `makeContext` context, so on a writer-claimed brain each rendered part is submitted as a `put_page` write request naming the page's current revision (a part whose publication would change nothing is screened request-free first and takes no admission; unmanaged brains and dry runs keep the direct importer; `recover codex --apply` passes the same context; pinned by `test/transcripts-managed-ingest.test.ts`); embedding is OFF by default (embed backfill is the catch-up lane; the embed flag opts in); the max-bytes flag (validated size string, e.g. `4gb`) overrides the per-format file/store byte caps for oversized stores while omission preserves each adapter's native default; the since-last watermark is an op-checkpoint (op `transcripts-ingest`, fingerprint = source + pathspec + format + adapter version + any explicit byte cap via `ingestCheckpointFingerprintInput` — a checkpoint written under one cap is never silently reused under another, so a capped run's skipped tail can't read as scanned; the pathspec binds the user-stated paths resolved + sorted, and the no-arg/all lane substitutes hostname + sorted harness roots so DB-backed checkpoints shared across a brain's machines never let one machine inherit another's watermark and skip sessions it never scanned) advanced ONLY after a clean, untruncated, non-dry scan (a Codex sub-agent rollout, `session_meta` payload.source.subagent, has no user turn by design: the adapter reports `subagentRollout`, the scan counts it in `subagentRollouts` and prints `N sub-agent rollouts (no user turns by design)`, and it keeps the scan clean; an ordinary assistant-only rollout is still `userTurnsMissing` drift); no-arg = confined discovery table, the all flag imports the discovered set. `status`: found-vs-imported gap table (disk scan vs ONE conversation-pages frontmatter query — `executeRaw`, both engines — in `src/core/transcripts/discover.ts`) — the correctness surface that catches late-arriving sessions no watermark can. The facts flag hands EVERY touched slug (including hash-skipped) to `src/core/transcripts/ingest-facts.ts`; a page that fails extraction counts in `facts.pagesFailed`, stays unfinished, and makes the command exit 1. Registered in CLI_ONLY + CLI_ONLY_SELF_HELP + SELF_HELP_WITHOUT_ENGINE (engine-free help). `expandTilde(raw)` (bare `~`, leading `~/` or `~\\` → home dir; `~user` forms and a mid-string `~` stay literal) is the one tilde expansion `expandPaths` applies to every path spec. `recover codex` (`src/commands/transcripts-recover.ts`, logic `src/core/transcripts/recover.ts`; D15 for #5163): finds codex conversation pages in one source with no `**User**` anchor, re-parses the retained rollouts (discovery root + archived store, or given paths) and classifies each session recoverable / still userless / unrecoverable (rollout gone); preview by default, `--apply` re-imports only the recoverable rollouts through `runTranscriptsIngest` (content-hash dedup, no facts, no watermark write). Pinned by `test/transcripts-recover-codex.test.ts`. `audit-secrets [--source-id S] [--json]` (`src/commands/transcripts-audit.ts`, logic `src/core/transcripts/secret-audit.ts`): the read-only installed-base audit that streams imported conversation pages (`type = 'conversation'` with `transcript_import` frontmatter) in id-keyset batches of 25, scans title and body with the transcript-lane detectors, lists slug, source, hit counts per pattern and up to 20 line numbers (never values or previews), and caches the summary without slugs in config row `transcripts.secret_audit` for the doctor check `transcript_secret_exposure` (`src/commands/doctor/checks/transcript-secrets.ts`, brain category), which counts imported conversation pages and reads that summary (never scans): no audit, an older `TRANSCRIPT_SECRET_AUDIT_VERSION` or a source-scoped audit warns with the audit as fix; hits warn with the audit's age; a clean full audit is ok. Pinned by `test/transcripts-secret-audit.test.ts`.-- `src/commands/upgrade.ts` — self-update CLI. It sets `GBRAIN_UPGRADE_OWNS_MIGRATIONS=1` for the install step, so package postinstall (`scripts/postinstall.ts`) skips `apply-migrations`; post-upgrade owns them. An install step that fails or times out after `gbrain --version` already reports a newer version counts as installed. The run ends with a `Binary:` line (installed version, or upgrade failed) and a `Migrations:` line: complete; running, with the lock holder's host and pid when post-upgrade exits 75; or failed, with the recovery command (`--force-retry <v>` for wedged versions). `runPostUpgrade()` enumerates migrations from the TS registry (`src/commands/migrations/index.ts`) and tail-calls `runApplyMigrations(['--yes', '--non-interactive'])` so the mechanical side of every outstanding migration runs unconditionally. After schema apply it prints the one-shot auto_chronicle default-on `[AGENT]` notice (`core/chronicle/upgrade-notice.ts`). Before the swap of a bun-link, package or ClawHub install it refuses (exit 78, nothing changed) a target whose Bun floor is above the host's Bun or unreadable (`--no-bun-floor-check` overrides, manual only; `src/core/bun-floor.ts`); after the swap it runs `gbrain --help` as a smoke that passes the startup Bun check and, on failure, exits 1 with per-method recovery (#5855). Everything the post-swap tail needs is imported statically, so the old process never loads new-release modules into its cached graph (#6604; the supervisor step constant lives in the import-free leaf `src/commands/movement-step.ts`; guard: `test/upgrade-post-swap-imports.test.ts`). A tag-pinned reinstall hint (`bunReinstallCommand`, `reinstallHintLines`) probes `git ls-remote --exit-code --tags … refs/tags/v<x>` before `bun remove -g gbrain`, prints a restore line, and on Windows prints one step per line; `planPinnedReinstall` probes the tag itself (published / not published / unknown) and falls back to the newest published `v<x>` tag (`latestPublishedVersion`) when the requested one is missing (#6662, D24; `test/upgrade-release-tag-hint.test.ts`). A verified version equal to the running one after the install step is no swap (#6828): it prints `No newer version was installed`, skips `last_upgrade`, `JUST_UPGRADED`, the cache reset and the smoke, and on a tag pin with no newer published tag the hint moves the install off the pin with `to_version: latest`, never a cached unpublished version (#6718). With `GBRAIN_SWAP_RECEIPT` set it writes a `SwapReceipt` (`installed` / `not_installed` / `installed_broken`) for the autopilot channel (`test/autopilot-unpublished-target-6828.test.ts`). Tests: `upgrade-migration-outcome.test.ts`, `upgrade-no-autopilot.serial.test.ts`, `upgrade-bun-link-arc.serial.test.ts`. `post-upgrade --json` (D2, `json: 'document'`): human lines go to stderr and stdout is one report `{status, apply_migrations:{exit_code}, schema, warnings[]}`; it calls `applyMigrations()` and still ends on any status apply-migrations returns (a failure is one envelope leading with the report). GBRA-175: `--channel stable|alpha` (`latest` is an alias of `alpha`; resolution order in the Release channels entry below): `resolveStableRelease` maps the commit `refs/tags/stable` peels to onto its `v<version>` tag through `git ls-remote`, and `installStableRelease` installs exactly that release (bun: remove then add `#v<version>`, restoring the previous release on failure; bun-link: fast-forward only; binary: `fetchReleaseByTag`), never downgrading. Before the swap `preflightHostRestart` refuses (`restart_refused`, exit 3) when a running process could not be restarted; after post-upgrade the new build runs `gbrain upgrade --restart-only` (`--no-restart` skips it). Tests: `upgrade-stable-channel.test.ts`. A global install pinned to a tag or commit (`bunGlobalExactTagPin(root, true)`) is replaced with the newest published release the same way instead of `bun update`, which keeps the pin. `parseChannelArg` and `resolveStableRelease` live in `src/core/stable-channel.ts` (re-exported).+- `src/commands/upgrade.ts` — self-update CLI. It sets `GBRAIN_UPGRADE_OWNS_MIGRATIONS=1` for the install step, so package postinstall (`scripts/postinstall.ts`) skips `apply-migrations`; post-upgrade owns them. An install step that fails or times out after `gbrain --version` already reports a newer version counts as installed. The run ends with a `Binary:` line (installed version, or upgrade failed) and a `Migrations:` line: complete; running, with the lock holder's host and pid when post-upgrade exits 75; or failed, with the recovery command (`--force-retry <v>` for wedged versions). `runPostUpgrade()` enumerates migrations from the TS registry (`src/commands/migrations/index.ts`) and tail-calls `runApplyMigrations(['--yes', '--non-interactive'])` so the mechanical side of every outstanding migration runs unconditionally. After schema apply it prints the one-shot auto_chronicle default-on `[AGENT]` notice (`core/chronicle/upgrade-notice.ts`). Install methods are bun, bun-link and binary (a compiled binary is found by Bun's `/$bunfs/` entrypoint, so a release asset keeps its published name); anything else is `unknown` and prints manual steps. It never runs `clawhub update gbrain`, which would install whatever skill anyone publishes under that name (#8464; `test/upgrade.serial.test.ts`). Before the swap of a bun-link or package install it refuses (exit 78, nothing changed) a target whose Bun floor is above the host's Bun or unreadable (`--no-bun-floor-check` overrides, manual only; `src/core/bun-floor.ts`); after the swap it runs `gbrain --help` as a smoke that passes the startup Bun check and, on failure, exits 1 with per-method recovery (#5855). Everything the post-swap tail needs is imported statically, so the old process never loads new-release modules into its cached graph (#6604; the supervisor step constant lives in the import-free leaf `src/commands/movement-step.ts`; guard: `test/upgrade-post-swap-imports.test.ts`). A tag-pinned reinstall hint (`bunReinstallCommand`, `reinstallHintLines`) probes `git ls-remote --exit-code --tags … refs/tags/v<x>` before `bun remove -g gbrain`, prints a restore line, and on Windows prints one step per line; `planPinnedReinstall` probes the tag itself (published / not published / unknown) and falls back to the newest published `v<x>` tag (`latestPublishedVersion`) when the requested one is missing (#6662, D24; `test/upgrade-release-tag-hint.test.ts`). A verified version equal to the running one after the install step is no swap (#6828): it prints `No newer version was installed`, skips `last_upgrade`, `JUST_UPGRADED`, the cache reset and the smoke, and on a tag pin with no newer published tag the hint moves the install off the pin with `to_version: latest`, never a cached unpublished version (#6718). With `GBRAIN_SWAP_RECEIPT` set it writes a `SwapReceipt` (`installed` / `not_installed` / `installed_broken`) for the autopilot channel (`test/autopilot-unpublished-target-6828.test.ts`). Tests: `upgrade-migration-outcome.test.ts`, `upgrade-no-autopilot.serial.test.ts`, `upgrade-bun-link-arc.serial.test.ts`. `post-upgrade --json` (D2, `json: 'document'`): human lines go to stderr and stdout is one report `{status, apply_migrations:{exit_code}, schema, warnings[]}`; it calls `applyMigrations()` and still ends on any status apply-migrations returns (a failure is one envelope leading with the report). GBRA-175: `--channel stable|alpha` (`latest` is an alias of `alpha`; resolution order in the Release channels entry below): `resolveStableRelease` maps the commit `refs/tags/stable` peels to onto its `v<version>` tag through `git ls-remote`, and `installStableRelease` installs exactly that release (bun: remove then add `#v<version>`, restoring the previous release on failure; bun-link: fast-forward only; binary: `fetchReleaseByTag`), never downgrading. Before the swap `preflightHostRestart` refuses (`restart_refused`, exit 3) when a running process could not be restarted; after post-upgrade the new build runs `gbrain upgrade --restart-only` (`--no-restart` skips it). Tests: `upgrade-stable-channel.test.ts`. A global install pinned to a tag or commit (`bunGlobalExactTagPin(root, true)`) is replaced with the newest published release the same way instead of `bun update`, which keeps the pin. `parseChannelArg` and `resolveStableRelease` live in `src/core/stable-channel.ts` (re-exported).- Release channels: `src/core/self-upgrade.ts` resolves the channel (`resolveReleaseChannel`: `--channel`, `GBRAIN_RELEASE_CHANNEL`, `self_upgrade.channel`, default `stable`; `latest` normalizes to `alpha`; an invalid value at the first present source is an error) and keeps the update cache (`update-check.<channel>.json`, tagged with the evidence policy; an older answer never overwrites a newer one) and the time-based snooze (`update-snoozed.<channel>.json`) per channel; `offeredVersion` never offers a downgrade except to move off a `known_bad` version. `src/core/stable-channel.ts` reads and strictly parses the evidence record (`stable.json` on `stable-record`; `requiredEvidenceKeys`: `soak_run`, plus `matrix_run` from `MATRIX_REQUIRED_FROM`), maps failures to `stable_missing` / `stable_invalid` / `stable_unreadable` with sanitized causes, and `resolveStableRelease` checks the `stable` and `v<version>` tags against the record commit. `src/commands/upgrade-channel.ts` plans an upgrade's target (`channelTarget`, `runUpgradeDryRun` for `gbrain upgrade --dry-run --json`) and refuses with the typed code. `src/commands/check-update.ts` `refreshUpdateCache` never reads a bare VERSION for stable and never falls back to alpha. `src/core/release-channel-notice.ts` prints the one-time `[gbrain notice release_channel]` line on stderr (marker file under `notices/`; not under `--json`, `serve` or `mcp`; only when no channel is set). `src/core/install-ref.ts` is the one ref every install surface names, linted by `scripts/check-install-ref.ts`. Tests: `test/release-channel-w1.serial.test.ts`, `test/upgrade-stable-channel.test.ts`, `test/install-ref.test.ts`. Docs: `docs/guides/upgrades-auto-update.md#stable-channel`.- `src/commands/upgrade-restart.ts` — GBRA-175: the host side of the upgrade restart. Real process sources (consumer heartbeat rows on Postgres, the supervisor PID file, the worker registry, `ps -U <uid> -ww -o pid=,ppid=,etime=,command=` with `/proc/<pid>/environ` GBRAIN_HOME matching on Linux; the install version above each entry point), the installed serve and autopilot services with the pid each manager runs (`hostServices`: `systemctl --user show -p MainPID`, `launchctl list`), `terminateIfUnchanged` (SIGTERM an MCP pid only while `ps` still shows the same server and start time), `restartRefusal` (ask_user + `--stop-mcp` when only MCP servers block, else the first manual step for the user), `preflightHostRestart` (pre-swap, every process stale) and `runHostRestart` (`gbrain upgrade --restart-only [--stop-mcp] [--dry-run] [--json]`: plan, run, verify for up to 180 s with the warm-socket probe `probeCliSocket`). #7475: `restartServeAfterSelfUpgrade`, called each autopilot-daemon tick, restarts the serve the serve service runs once it is on an older build than the relaunched autopilot. It runs once per autopilot process, only in auto mode, in quiet hours and when the brain is idle (`computeAutopilotIdle`), and audits as `restart_serve`. `planServeRestart` reports a serve the service does not run, or one on another install, as `manual` and never restarts it. A serve counts as older only on evidence (a recorded build below this one, or no recorded build and a start before the install's `package.json` was written); a newer or unknown serve, or an install on disk that is not this build, is left alone. Tests: `upgrade-restart.test.ts`, `autopilot-serve-restart-7475.test.ts`.- `src/core/upgrade-restart.ts` — GBRA-175: the pure half of the upgrade restart. `collectHostProcesses` (the process table is the authority: a heartbeat, PID-file or registry record whose pid `ps` does not show as gbrain is dropped; `gbrainEntry` skips wrappers such as tini, `bunx`, `bun x` and `bun run <bin>`, skips interpreter flags that take a value, resolves a relative entry against the process's `/proc/<pid>/cwd` and accepts a `src/cli.ts` whose package two levels up is named gbrain (#8723); a process's parent is its nearest gbrain ancestor, and a worker with none is refused naming its parent's pid and executable, never its command line), `planRestart` (a service restarts only processes under its manager's pid; `supervisorRestartArgv` keeps the launch options and PID file, read from `--pid-file <path>`, and drops a `--flag=value` token that is neither a global flag nor `--job-isolation=`, because the supervisor that holds it ignored it and this build's `=` gate refuses it (#7619); anything else is a `ManualStep`), `runRestartSteps`, `restartProblems` (old pids gone, one build, roles and the supervised worker back, warm socket accepts) and `unverifiedBuilds`. A stale process whose `install_root` is another install than the one being upgraded gets a `replace_copy` step first when it is a Bun global copy (`bunGlobalCopyOf`: probe the tag, `bun remove -g` then `bun add -g` under its `BUN_INSTALL`, restore on failure), else a manual step from `copyFix`; after the restart `mismatchedBuilds` names any process back on another build, and the host's `mismatchFix` chains that replacement with `gbrain upgrade --restart-only`.diff --git a/docs/guides/upgrades-auto-update.md b/docs/guides/upgrades-auto-update.mdindex 7706f714fb..8944ef5607 100644--- a/docs/guides/upgrades-auto-update.md+++ b/docs/guides/upgrades-auto-update.md@@ -74,7 +74,7 @@ PATH and the Bun the running process uses:commit; the swap fast-forwards to exactly that commit(`git merge --ff-only <sha>`), so a floor raised upstream after the check isnot installed unchecked.-- **global package (`bun`) and ClawHub:** `package.json` at the ref the+- **global package (`bun`):** `package.json` at the ref theinstall's `github:` spec names (the default branch when unpinned) onraw.githubusercontent.com.- **compiled binary:** exempt; it carries its own Bun.@@ -181,8 +181,8 @@ release commit, and the binary install downloads that release's asset.**Never downgrade.** A build at or above the stable release is offerednothing, so an install that ran ahead on alpha waits until stable passes it.The one exception is a build on the record's `known_bad` list: it is offered-the current stable release even when that is older. A ClawHub install follows-ClawHub's own line and is refused with the reinstall command.+the current stable release even when that is older. An install whose method+cannot be detected is refused with the reinstall command.**The update cache and snooze are per channel.** Each channel keeps its ownanswer (`update-check.<channel>.json`, which also records the evidence policy)diff --git a/src/commands/check-update.ts b/src/commands/check-update.tsindex d50ed104e5..99a95b6d49 100644--- a/src/commands/check-update.ts+++ b/src/commands/check-update.ts@@ -55,7 +55,6 @@ interface CheckUpdateResult {function upgradeCommandForMethod(method: string): string {switch (method) {case 'bun': return 'bun update gbrain';- case 'clawhub': return 'clawhub update gbrain';case 'binary': return 'gbrain self-upgrade';default: return 'gbrain upgrade';}diff --git a/src/commands/upgrade.ts b/src/commands/upgrade.tsindex ba14e4a773..4cf5f4e4d2 100644--- a/src/commands/upgrade.ts+++ b/src/commands/upgrade.ts@@ -50,7 +50,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 [--channel stable|alpha] [--dry-run] [--stop-mcp] [--no-restart] [--swap-only] [--no-autopilot-install] [--no-bun-floor-check]\n gbrain upgrade --restart-only [--stop-mcp] [--dry-run] [--json]\n\nSelf-update the CLI, then restart every gbrain process on this host onto the new build.\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--channel <name> stable (weekly, promoted after its gates passed on the exact release; the default) or alpha\n (every published release; latest is an alias). Precedence: --channel, GBRAIN_RELEASE_CHANNEL,\n self_upgrade.channel, stable. Persist it as self_upgrade.channel in config.\n--stop-mcp Stop MCP stdio servers agent harnesses started, instead of refusing; reconnect gbrain\n in each harness afterwards.\n--no-restart Install without restarting anything (doctor reports runtime_build_skew until\n \'gbrain upgrade --restart-only\' runs).\n--restart-only Restart serve, autopilot, the jobs supervisor and its worker (and, with --stop-mcp, MCP\n servers) onto the installed build, then verify every process reports it and the warm\n CLI socket accepts it. A process it cannot restart refuses with the exact step (exit 3).\n--dry-run Print the effective channel, where it came from and what would install; change nothing.\n With --restart-only: print the restart plan instead.\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.');+ console.log('Usage: gbrain upgrade [--channel stable|alpha] [--dry-run] [--stop-mcp] [--no-restart] [--swap-only] [--no-autopilot-install] [--no-bun-floor-check]\n gbrain upgrade --restart-only [--stop-mcp] [--dry-run] [--json]\n\nSelf-update the CLI, then restart every gbrain process on this host onto the new build.\n\nDetects install method (bun, bun-link, binary) and runs the appropriate update.\nAfter upgrading, shows what\'s new and offers to set up new features.\n\n--channel <name> stable (weekly, promoted after its gates passed on the exact release; the default) or alpha\n (every published release; latest is an alias). Precedence: --channel, GBRAIN_RELEASE_CHANNEL,\n self_upgrade.channel, stable. Persist it as self_upgrade.channel in config.\n--stop-mcp Stop MCP stdio servers agent harnesses started, instead of refusing; reconnect gbrain\n in each harness afterwards.\n--no-restart Install without restarting anything (doctor reports runtime_build_skew until\n \'gbrain upgrade --restart-only\' runs).\n--restart-only Restart serve, autopilot, the jobs supervisor and its worker (and, with --stop-mcp, MCP\n servers) onto the installed build, then verify every process reports it and the warm\n CLI socket accepts it. A process it cannot restart refuses with the exact step (exit 3).\n--dry-run Print the effective channel, where it came from and what would install; change nothing.\n With --restart-only: print the restart plan instead.\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;}@@ -186,22 +186,10 @@ export async function runUpgrade(args: string[], opts: { targetVersion?: stringbreak;}- case '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;- } catch {- console.error('ClawHub upgrade failed. Try: clawhub update gbrain');- }- break;-default:console.error('Could not detect installation method.');console.log('Try one of:');console.log(' bun update gbrain');- console.log(' clawhub update gbrain');console.log(' Download from https://github.com/garrytan/gbrain/releases');}@@ -373,12 +361,12 @@ interface StableInstallContext { oldVersion: string; upgradeEnv: NodeJS.ProcessE/*** GBRA-175: install exactly the stable release. bun: reinstall pinned to its tag (an in-place tag swap corrupts a* global install, #5034), restoring the previous release when the add fails. bun-link: fast-forward the clone to the- * release commit, never backward or across a fork. binary: the release's own asset. clawhub follows its own line.+ * release commit, never backward or across a fork. binary: the release's own asset.*/async function installStableRelease(method: string, target: { version: string; commit: string }, ctx: StableInstallContext): Promise<'installed' | 'failed' | 'refused'> {const spec = `github:${GBRAIN_GITHUB_REPO}#v${target.version}`;- if (method === 'clawhub' || method === 'unknown') {- console.error(`The stable channel installs through bun, a bun-link clone or the release binary; this install (${method}) follows its own release line. Nothing was changed.`);+ if (method === 'unknown') {+ console.error('The stable channel installs through bun, a bun-link clone or the release binary, and this install method could not be detected. Nothing was changed.');console.error(`Reinstall on the stable release with: ${bunReinstallCommand(`#v${target.version}`)}`);setCliExitVerdict(1);return 'refused';@@ -1282,7 +1270,7 @@ function isNewerThan(version: string, baseline: string): boolean {return false;}-export function detectInstallMethod(): 'bun' | 'bun-link' | 'binary' | 'clawhub' | 'unknown' {+export function detectInstallMethod(): 'bun' | 'bun-link' | 'binary' | 'unknown' {const execPath = process.execPath || '';// v0.28.5 cluster D: bun-link signal first.@@ -1304,19 +1292,14 @@ export function detectInstallMethod(): 'bun' | 'bun-link' | 'binary' | 'clawhub'return 'bun';}- // Check if running as compiled binary- if (execPath.endsWith('/gbrain') || execPath.endsWith('\\gbrain.exe')) {+ // A compiled binary runs from Bun's virtual entrypoint whatever its file is+ // named, so a release asset run as gbrain-linux-x64 is still the binary.+ if (execPath.endsWith('/gbrain') || execPath.endsWith('\\gbrain.exe') || /^(\/\$bunfs\/|[A-Za-z]:[\\/]~BUN[\\/])/.test(process.argv[1] ?? '')) {return 'binary';}- // Check if clawhub is available (use --version, not which, to avoid false positives)- try {- execSync('clawhub --version', { stdio: 'pipe', timeout: 5_000 });- return 'clawhub';- } catch {- // not available- }-+ // #8464: never `clawhub update gbrain`. We publish no gbrain skill on ClawHub, and that+ // command installs whatever skill anyone else publishes under the name.return 'unknown';}diff --git a/src/core/binary-self-update.ts b/src/core/binary-self-update.tsindex 14deb26a27..6aa1e7a40c 100644--- a/src/core/binary-self-update.ts+++ b/src/core/binary-self-update.ts@@ -3,7 +3,7 @@* (v0.42 self-upgrading-gbrain wave, eng-review Finding 2 — "make the atomic* swap claim true for the one method we own").*- * `bun` / `bun-link` / `clawhub` delegate their swap to those package managers.+ * `bun` / `bun-link` delegate their swap to those package managers.* The compiled standalone binary is the only method gbrain itself writes, so* it's the only place we can (and now do) guarantee atomicity:*diff --git a/src/core/bun-floor.ts b/src/core/bun-floor.tsindex e44793e090..b0d4168f7d 100644--- a/src/core/bun-floor.ts+++ b/src/core/bun-floor.ts@@ -118,8 +118,8 @@ export function rawPackageUrlForSpec(spec: string): string | null {/*** 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.+ * installs (the default branch when unpinned). A null spec reads the+ * canonical repository's default branch.*/export async function readPackageTarget(spec: string | null): Promise<TargetFloor> {const url = rawPackageUrlForSpec(spec ?? 'github:garrytan/gbrain');diff --git a/src/core/self-upgrade.ts b/src/core/self-upgrade.tsindex e18d44624f..cf4b7bec57 100644--- a/src/core/self-upgrade.ts+++ b/src/core/self-upgrade.ts@@ -293,7 +293,7 @@ export function gateOnTargetRuntime(/*** Whether this install method + platform/arch can apply an upgrade unattended.- * `bun` / `bun-link` / `clawhub` delegate to their package managers; `binary`+ * `bun` / `bun-link` delegate to their package managers; `binary`* self-updates via atomic rename ONLY where a release asset is published —* today that's darwin-arm64 and linux-x64 (see `.github/workflows/release.yml`).* Other binary platform/arch combos (darwin-x64, linux-arm64, win32) have no@@ -307,7 +307,6 @@ export function canSelfUpdate(switch (installMethod) {case 'bun':case 'bun-link':- case 'clawhub':return true;case 'binary':return (platform === 'darwin' && arch === 'arm64') || (platform === 'linux' && arch === 'x64');diff --git a/src/core/thin-client-upgrade-prompt.ts b/src/core/thin-client-upgrade-prompt.tsindex 984a470ed9..5fc8d02f7c 100644--- a/src/core/thin-client-upgrade-prompt.ts+++ b/src/core/thin-client-upgrade-prompt.ts@@ -12,7 +12,7 @@* the original command on the stale in-memory binary.* - D2 — Exclusive non-blocking advisory lock around the prompt; loser no-ops.* - D5 — Re-read `gbrain --version` post-upgrade to verify the binary actually- * advanced. `gbrain upgrade` returns 0 even on bun/clawhub catch-and-print+ * advanced. `gbrain upgrade` returns 0 even on bun catch-and-print* paths and on the `binary` install ("not yet implemented").* - D6 — Gate on both stdin AND stdout TTY; prompt writes to stderr.* - D7 — When `bannerSuppressed()` is true, emit nothing about upgrades.diff --git a/test/self-upgrade.test.ts b/test/self-upgrade.test.tsindex ede2298c19..fe65252633 100644--- a/test/self-upgrade.test.ts+++ b/test/self-upgrade.test.ts@@ -155,12 +155,16 @@ describe('decideSelfUpgrade — pure branches', () => {});describe('canSelfUpdate', () => {- test('bun / bun-link / clawhub always self-update', () => {- for (const m of ['bun', 'bun-link', 'clawhub']) {+ test('bun / bun-link always self-update', () => {+ for (const m of ['bun', 'bun-link']) {expect(canSelfUpdate(m, 'darwin', 'arm64')).toBe(true);expect(canSelfUpdate(m, 'win32', 'x64')).toBe(true);}});+ test('#8464: clawhub is never an unattended upgrade path', () => {+ expect(canSelfUpdate('clawhub', 'darwin', 'arm64')).toBe(false);+ expect(canSelfUpdate('clawhub', 'linux', 'x64')).toBe(false);+ });test('binary self-updates only where a release asset exists (darwin-arm64, linux-x64)', () => {expect(canSelfUpdate('binary', 'darwin', 'arm64')).toBe(true);expect(canSelfUpdate('binary', 'linux', 'x64')).toBe(true);diff --git a/test/upgrade.serial.test.ts b/test/upgrade.serial.test.tsindex 872659df6d..b8383bc56a 100644--- a/test/upgrade.serial.test.ts+++ b/test/upgrade.serial.test.ts@@ -10,7 +10,7 @@ import { VERSION } from '../src/version.ts';import { fileURLToPath } from 'node:url';// Install-method detection runs in-process where it spawns nothing (argv[1] /-// execPath patched); PATH-shimmed paths (clawhub, bun-link, bun update) run+// execPath patched); PATH-shimmed paths (bun-link, bun update) run// runUpgrade in a subprocess, because Bun snapshots PATH at process start.describe('upgrade command', () => {@@ -42,7 +42,7 @@ describe('upgrade command', () => {describe('detectInstallMethod — package-install classification (in-process)', () => {// The node_modules branch spawns nothing, so argv[1] / execPath are patched- // in-process (serial file). The bun-link, clawhub and cwd contracts need+ // in-process (serial file). The bun-link and cwd contracts need// PATH shims and live in the subprocess suite below.const originalArgv1 = process.argv[1];const originalExecPath = process.execPath;@@ -93,6 +93,29 @@ describe('detectInstallMethod — package-install classification (in-process)',const r = detectFrom({ name: 'gbrain', repository: 'github:garrytan/gbrain' }, 'dist/cli.js', '/opt/bin/gbrain');expect(r.method).toBe('bun');});++ // #8464: a release asset run under its published name is the compiled binary, found by Bun's virtual entrypoint.+ for (const [argv1, execPath] of [+ ['/$bunfs/root/gbrain-linux-x64', '/opt/bin/gbrain-linux-x64'],+ ['/$bunfs/root/gbrain-darwin-arm64', '/Users/alice-example/Downloads/gbrain-darwin-arm64'],+ ['B:\\~BUN\\root\\gb.exe', 'C:\\tools\\gb.exe'],+ ] as const) {+ test(`a compiled binary named ${execPath} is the binary install`, () => {+ const cwd = process.cwd();+ const elsewhere = mkdtempSync(join(tmpdir(), 'gbrain-upgrade-compiled-'));+ try {+ process.chdir(elsewhere);+ process.argv[1] = argv1;+ Object.defineProperty(process, 'execPath', { value: execPath, configurable: true, writable: true });+ expect(upgradeModule.detectInstallMethod()).toBe('binary');+ } finally {+ process.chdir(cwd);+ rmSync(elsewhere, { recursive: true, force: true });+ process.argv[1] = originalArgv1;+ Object.defineProperty(process, 'execPath', { value: originalExecPath, configurable: true, writable: true });+ }+ });+ }});describe('resolveBunGlobalRoot', () => {@@ -214,21 +237,27 @@ describe('runUpgrade target verification (#4366)', () => {* Build a hermetic fake install under a temp HOME and run runUpgrade in a* subprocess (Bun snapshots environ at birth, so PATH shims cannot be* injected in-process):- * - a PATH-first `clawhub` shim exiting 0 without changing anything —- * the same successful-no-op shape as `bun update` on an exact-tag Git- * pin (the issue's install);+ * - by default a global package install whose PATH `bun` shim exits 0+ * without changing anything (`bun update` on an exact-tag Git pin, the+ * issue's install);+ * - a PATH `clawhub` CLI that answers every command and logs it to+ * HOME/clawhub.log, which must never be run (#8464);* - a PATH-first `gbrain` shim that keeps reporting `observedVersion`;* - a pre-seeded upgrade-available marker so cache retention is observable;* - with `binaryResult`, the driver runs under a copy of bun named `gbrain`* (detectInstallMethod keys on execPath's basename) and the driver mocks- * runBinarySelfUpdate to return that result, reaching the binary branch.+ * runBinarySelfUpdate to return that result, reaching the binary branch;+ * - with `execName`, the driver runs outside any install under a copy of+ * bun with that name.*/async function runUpgradeAgainstFakeInstall(opts: {observedVersion: string;targetVersion?: string;binaryResult?: BinarySelfUpdateResult;- /** Body of the PATH `clawhub` shim (default: exit 0 for everything). */+ /** Body of the PATH `clawhub` shim after it logs the call (default: exit 0 for everything). */clawhub?: string;+ /** Run the driver outside any install under a copy of bun with this name. */+ execName?: string;/** Driver directory relative to the fake HOME (default: HOME itself). */driverDir?: string;/** Shim `git` and `bun` as recorders appending `<cwd>|<args>` to HOME/calls.log. */@@ -239,7 +268,7 @@ describe('runUpgrade target verification (#4366)', () => {const home = mkdtempSync(join(tmpdir(), 'gbrain-upgrade-target-'));const bin = join(home, 'bin');mkdirSync(bin);- writeFileSync(join(bin, 'clawhub'), `#!/bin/sh\n${opts.clawhub ?? 'exit 0'}\n`);+ writeFileSync(join(bin, 'clawhub'), `#!/bin/sh\necho "$*" >> "${join(home, 'clawhub.log')}"\n${opts.clawhub ?? 'exit 0'}\n`);writeFileSync(join(bin, 'gbrain'), `#!/bin/sh\necho "gbrain ${opts.observedVersion}"\n`);chmodSync(join(bin, 'clawhub'), 0o755);chmodSync(join(bin, 'gbrain'), 0o755);@@ -259,10 +288,19 @@ describe('runUpgrade target verification (#4366)', () => {formatMarker({ kind: 'upgrade_available', current: OLD, latest: TARGET }) + '\n',);- // The driver lives OUTSIDE the repo so detectInstallMethod() cannot see a- // node_modules/.git ancestor and falls through to the clawhub shim.- const driverDir = join(home, opts.driverDir ?? '');+ // The driver lives OUTSIDE the repo so detectInstallMethod() cannot see the+ // checkout's node_modules/.git ancestor.+ const globalInstall = opts.driverDir === undefined && !opts.binaryResult && !opts.execName;+ const driverDir = join(home, globalInstall ? join('global', 'node_modules', 'gbrain', 'src') : opts.driverDir ?? '');mkdirSync(driverDir, { recursive: true });+ if (globalInstall) {+ writeFileSync(join(home, 'global', 'package.json'), '{}');+ writeFileSync(join(home, 'global', 'node_modules', 'gbrain', 'package.json'), JSON.stringify({ name: 'gbrain', repository: 'github:garrytan/gbrain' }));+ if (!opts.recordGitAndBun) {+ writeFileSync(join(bin, 'bun'), '#!/bin/sh\nexit 0\n');+ chmodSync(join(bin, 'bun'), 0o755);+ }+ }opts.setup?.(home);const driverPath = join(driverDir, 'driver.ts');const mockPrelude = opts.binaryResult@@ -279,8 +317,8 @@ describe('runUpgrade target verification (#4366)', () => {`await runUpgrade(['--swap-only', '--no-bun-floor-check'], t ? { targetVersion: t } : {});\n`,);let bunExec = process.execPath;- if (opts.binaryResult) {- bunExec = join(home, 'exec', 'gbrain');+ if (opts.binaryResult || opts.execName) {+ bunExec = join(home, 'exec', opts.execName ?? 'gbrain');mkdirSync(dirname(bunExec));copyFileSync(process.execPath, bunExec);chmodSync(bunExec, 0o755);@@ -388,30 +426,32 @@ describe('runUpgrade target verification (#4366)', () => {// ── install-method detection + upgrade commands (PATH-shimmed) ──────────- test('clawhub is detected by running `clawhub --version`, not by PATH presence', async () => {- // The shim is ON PATH but fails `--version`: a `which clawhub` probe would- // pick it; the real probe falls through to 'unknown'.- const { home, stdout, stderr } = await runUpgradeAgainstFakeInstall({- observedVersion: OLD,- clawhub: '[ "$1" = "--version" ] && exit 1\nexit 0',+ // #8464: `clawhub update gbrain` installs whatever skill anyone publishes as gbrain, so a working clawhub CLI on+ // PATH must never become the install method, for a renamed release asset or any other undetected install.+ for (const execName of ['gbrain-linux-x64', 'bun']) {+ test(`an undetected install run as ${execName} never runs clawhub, even when the clawhub CLI works`, async () => {+ const { home, stdout, stderr } = await runUpgradeAgainstFakeInstall({ observedVersion: OLD, execName });+ try {+ expect(stdout).toContain('Detected install method: unknown');+ expect(stderr).toContain('Could not detect installation method.');+ expect(existsSync(join(home, 'clawhub.log'))).toBe(false);+ expect(`${stdout}${stderr}`).not.toMatch(/clawhub|\bnpm\b/i);+ } finally {+ rmSync(home, { recursive: true, force: true });+ }});- try {- expect(stdout).toContain('Detected install method: unknown');- expect(stderr).toContain('Could not detect installation method.');- expect(`${stdout}${stderr}`).not.toMatch(/\bnpm\b/);- } finally {- rmSync(home, { recursive: true, force: true });- }- });+ }- test('a hung `clawhub --version` probe times out instead of wedging upgrade', async () => {+ test('a hung clawhub CLI on PATH is never probed, so upgrade cannot wedge on it', async () => {const started = Date.now();const { home, stdout } = await runUpgradeAgainstFakeInstall({observedVersion: OLD,- clawhub: '[ "$1" = "--version" ] && exec sleep 60\nexit 0',+ execName: 'gbrain-linux-x64',+ clawhub: 'exec sleep 60',});try {expect(stdout).toContain('Detected install method: unknown');+ expect(existsSync(join(home, 'clawhub.log'))).toBe(false);expect(Date.now() - started).toBeLessThan(30_000);} finally {rmSync(home, { recursive: true, force: true });