Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(upgrade): replace a pinned or separate Bun global copy and name the exact fix when a process comes back on another build (GBRA-175)
garrytan069c99ad5daf
diff --git a/docs/UPGRADING_DOWNSTREAM_AGENTS.md b/docs/UPGRADING_DOWNSTREAM_AGENTS.mdindex 093b5673e6..cd52f490a3 100644--- a/docs/UPGRADING_DOWNSTREAM_AGENTS.md+++ b/docs/UPGRADING_DOWNSTREAM_AGENTS.md@@ -79,7 +79,16 @@ each one. Teach your agent's upgrade skill to handle that refusal:(`gbrain autopilot --install`) and workers under`gbrain jobs supervisor start --detach` so later upgrades restart them ontheir own.-3. Verify with `gbrain doctor --only runtime_build_skew --json`: it fails while+3. A process that starts from another gbrain install (a second Bun global copy+ the serve service points at, often pinned to a tag or commit) would come back+ on the old build, so the upgrade replaces that copy first (`bun remove -g`,+ then `bun add -g` the release tag, under the copy's own `BUN_INSTALL`; a+ plain `bun add` or `bun update` keeps a pin) and refuses for any other kind+ of install (a git clone) with its exact commands. If a process still comes+ back on another build, `restart_unverified` names the install it runs from+ and its `fix` is that replacement followed by `gbrain upgrade --restart-only`+ (`ask_user`: relay `user_message`, run the chain after the user agrees).+4. Verify with `gbrain doctor --only runtime_build_skew --json`: it fails whiletwo builds run, and its fix (`gbrain upgrade --restart-only`, after the useragrees) restarts every process onto the installed build.diff --git a/docs/architecture/key-files/commands-2-continued.md b/docs/architecture/key-files/commands-2-continued.mdindex bf489ae6ba..7a8401e509 100644--- a/docs/architecture/key-files/commands-2-continued.md+++ b/docs/architecture/key-files/commands-2-continued.md@@ -11,7 +11,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/commands/doctor/checks/knowledge-health.ts` — `facts_extraction_health` reads the last 24 h of `facts:absorb` rows in `ingest_log` (written by `src/core/facts/absorb-log.ts`) per source and reason (`split_part(summary, ':', 1)`) and warns when a failure reason reaches `facts.absorb_warn_threshold` (default 10) in a source. Two reasons are not failures and never count: `write_pending_accepted` (the absorb log read the facts write's receipt back from the journal and it is still queued, running or recovering after the job's publish wait) and `write_deferred_unadmitted` (`writer_lock_unavailable` before admission, no receipt; the job retries). Deferrals warn on their own when, in a source, more than 10 or one over an hour old have no later completed `facts-absorb` job for the same page; that warning's fix is the read-only `gbrain sources writer status --source <id> --json`. The failure count is history: the message gives the incidents in the rolling 24 h window and when the newest ages out, and `details.facts_absorb` (`incidents_24h`, `ages_out_at`, `jobs_still_dead`, `dead_jobs`) adds the current state, the `facts-absorb` jobs dead or failed in the last 24 h with no later completed job for the same page (source and slug); they never change the status, and when no other fix applies the newest one gets the paid `gbrain jobs retry <id>` fix (`retry_job` over MCP, asks first). Tests: `test/doctor-facts-absorb-contention-6778.test.ts`, `test/facts-absorb-publish-wait-6778.test.ts`, `test/doctor-facts-absorb-history-6761.test.ts`.- `src/commands/doctor/checks/persistence-consumers.ts` — #6317 (B3, T1c): doctor `two_consumers_on_host` (warn only when two live rows of resident kinds on this host have both been alive longer than 30 s; every other row, a `put` or a row younger than 30 s, is listed in `details`) and `consumers_without_heartbeat` (a `claim_phase.owner` pid on a running claim of this host with no heartbeat row: an older process that never defers; named with its kind and version from the stamp). Both carry a structured `agentFix` (`gbrain sources writer status --json`) and `doctorVerify`; with `persistence.single_consumer` off the overlap is reported as the configured behavior. `serve_build_drift` (#6696 C6, its own `serveBuildDriftEntry`, one `listHostConsumers` read, ok on PGLite with no read) compares the live resident rows (not this process) with this binary's `VERSION` through `compareWriterVersions` (an unparsable version counts as older): an older row warns "serve is running an older build than this checkout; restart serve and workers" with `details { count, this_version, owner, older, newer }` and a `fix` (actor `user`, `doctorVerify`) whose argv is the installed serve service's restart (`systemctl --user restart gbrain-serve.service` when `systemdUnitPath` exists on Linux, `launchctl kickstart -k gui/<uid>/com.gbrain.serve` when `launchdPlistPath` exists on macOS; `serveBuildDriftCheck`'s `ServiceHost` argument injects platform, home and uid) or else `kill <pid>`; a newer row is reported in an ok message; no rows names `consumers_without_heartbeat` for a pre-heartbeat serve. Registered in `DOCTOR_CHECK_REGISTRY` (the consumer entry, then `serveBuildDriftEntry`) before `searchModeEntry` and categorised `ops` in `src/core/doctor-categories.ts`. Tests: `test/doctor-serve-build-drift.test.ts`.-- `src/commands/doctor/checks/runtime-build-skew.ts` — #7245: doctor `runtime_build_skew` (standard tier, both engines, read-only). Collects serve and the other live resident consumers from their heartbeat rows (Postgres), worker parents from the worker registry (`version`, `install_root`), the supervisor from its PID file (`readSupervisorBuild`), and job-child builds from `job_build_skew:` history entries on the newest 500 jobs updated in the last 24 h, counted only while their worker pid is live. Fails when two or more builds run (GBRA-175), warns when only an install holds another; the fix asks, then runs `gbrain upgrade --restart-only`; the message names the manual restart: serve (`restartArgv`, exported from persistence-consumers.ts), else the supervisor (`gbrain jobs supervisor stop`), else a worker pid. Output carries pids and versions only. Pinned by `test/doctor-runtime-build-skew.test.ts`.+- `src/commands/doctor/checks/runtime-build-skew.ts` — #7245: doctor `runtime_build_skew` (standard tier, both engines, read-only). Collects serve and the other live resident consumers from their heartbeat rows (Postgres), worker parents from the worker registry (`version`, `install_root`), the supervisor from its PID file (`readSupervisorBuild`), and job-child builds from `job_build_skew:` history on the newest 500 jobs of the last 24 h while their worker pid lives. Fails on 2+ builds (GBRA-175), warns when only an install differs; fix: ask, then `gbrain upgrade --restart-only`; the message names the manual restart: serve (`restartArgv`, exported from persistence-consumers.ts), else the supervisor (`gbrain jobs supervisor stop`), else a worker pid. Output carries pids and versions only. Pinned by `test/doctor-runtime-build-skew.test.ts`.- `src/commands/dream-retriage.ts` — `gbrain dream retriage`: re-scores synthesize's list (`withConversationPages`, #7307) via the shared `runTriagePass` (with `maxMs: 0` — operator sweeps run to completion; `--limit` slices the discovered list caller-side) and reconciles the queued private-queue backlog: synth-v2 rows verdict-gated, plus any row stranded in a provably-dead `dream-inline-*` queue regardless of key family (patterns children, legacy grammars) — doctor's orphaned_private_queue check points here, so the repair selects everything the check can flag. Liveness uses ownership correlation (mirrors the doctor check): a live `gbrain_cycle_locks` row suppresses conversion only for queues born at/after its `acquired_at`; an older crashed cycle's queue stays repairable while a new cycle runs (unknown birth/acquisition stays fail-safe possibly-live). Spend-gated: upfront estimate via `canonicalLookup` on the resolved triage model, confirmation above `SPEND_CONFIRM_USD` ($5, in `dream-retriage-constants.ts`; unpriced models gate on `UNPRICED_CONFIRM_FILES`=500) through `requireConsent` (effect `paid`; `--yes`, `--max-usd`, tokenmax or a per-run preapproval authorize it; otherwise a TTY prompt or exit 3 with the consent payload, `--json` never implying it); the budget (`--max-usd`, else the derived consent cap) soft-stops via the pass's `shouldStop` seam (estimate-based) and bounds the `--audit-rejects` half. `--reconcile-queue` (opt-in — cancels queued work): selects waiting/delayed/paused `dream:synth-v2:%` jobs across ALL queues, parses keys with `parseSynthV2Key`, then per row, reading THE shared gate (`passesTriageGate` from `triage-rescue.ts` — threshold pass OR the verified-segment rescue; a hand-rolled `score >= threshold` here would cancel exactly the jobs the rescue admitted): matched below the gate → cancel; matched above the gate but `waiting` in a stale `dream-inline-*` queue → cancel as `converted_for_resubmit` (the backlog conversion — cancelled rows release their idempotency slot so the next cycle re-adds into a live drain); matched above the gate in a live queue → keep; matched-but-unscored → keep (never cancel on missing data); unmatched → keep unless `--cancel-unmatched`; key-source vs `data.source_id` disagreement → skip + `source_mismatch`; status re-checked immediately before each cancel (rows turned `active` are skipped; residual race matches cancelJob's best-effort contract). Legacy `dream:synth:` keys are excluded at the SQL LIKE filter — never candidates. `--source` scopes cancels (`other_source` counted); `--threshold`/`--since`/`--force`/`--dry-run` (zero judge calls, zero cancels — cached scores only, uncached files report `needs_triage`). `--audit-rejects <n>` re-judges N stride-sampled files that the gate actually REJECTED (below threshold AND not rescued — auditing a rescued file as a rejection would misreport the disagreement rate) with the SYNTHESIS model and reports that rate — the operator calibration loop. Reports carry `rescued`/`verified_segments` so a rescued file reads as accepted everywhere the command renders. Exit 0 success (even when nothing cancelled), 1 no engine/corpus, 2 usage or declined spend gate. Pinned by `test/dream-retriage.test.ts`. With System One S7 on, cached decide verdicts (cache identity from `resolveTriageDecide`) count as valid, the slot threshold joins every gate read, `runTriagePass` gets `decide`, and the spend estimate prices Jev windows (`estimateTriageDecideUsd`).diff --git a/docs/architecture/key-files/commands-6.md b/docs/architecture/key-files/commands-6.mdindex 8592bcd4ee..df69a1e357 100644--- a/docs/architecture/key-files/commands-6.md+++ b/docs/architecture/key-files/commands-6.md@@ -12,9 +12,9 @@ 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 latest|stable` (default `self_upgrade.channel`): `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`.+- `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 latest|stable` (default `self_upgrade.channel`): `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-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`). Tests: `upgrade-restart.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, and a process's parent is its nearest gbrain ancestor), `planRestart` (a service restarts only processes under its manager's pid; `supervisorRestartArgv` keeps the launch options and PID file; anything else is a `ManualStep`), `runRestartSteps`, `restartProblems` (old pids gone, one build, roles and the supervised worker back, warm socket accepts) and `unverifiedBuilds`.+- `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, and a process's parent is its nearest gbrain ancestor), `planRestart` (a service restarts only processes under its manager's pid; `supervisorRestartArgv` keeps the launch options and PID file; anything else is a `ManualStep`), `runRestartSteps`, `restartProblems` (old pids gone, one build, roles and the supervised worker back, warm socket accepts) and `unverifiedBuilds`. A stale process whose `install_root` is another install than the one being upgraded gets a `replace_copy` step first when it is a Bun global copy (`bunGlobalCopyOf`: probe the tag, `bun remove -g` then `bun add -g` under its `BUN_INSTALL`, restore on failure), else a manual step from `copyFix`; after the restart `mismatchedBuilds` names any process back on another build, and the host's `mismatchFix` chains that replacement with `gbrain upgrade --restart-only`.- `src/commands/watch.ts` — `gbrain watch`: the push transport. Reads turns from stdin as they arrive (`user:`/`assistant:` prefixes; unprefixed = user turn), keeps a rolling in-process window (`--window-turns`, default 4), calls `volunteerContext` per turn, streams pointers to stdout (`--json` for JSONL with turn attribution), logs `channel: 'watch'` events with a per-session id. Session dedupe feeds already-pushed slugs back as priorContext so the core's slug-only suppression dedupes. Blocks in the stdin iteration (interactive alive until Ctrl-C/Ctrl-D; piped ends at EOF) — deliberately NOT in DAEMON_COMMANDS; SIGINT closes the stream so teardown flows through finishCliTeardown. Per-turn resolution failures are fail-open. Registered in CLI_ONLY + CLI_ONLY_SELF_HELP + THIN_CLIENT_REFUSED_COMMANDS (thin clients use the `volunteer_context` MCP op). Pinned by `test/watch-command.test.ts`.diff --git a/docs/guides/upgrades-auto-update.md b/docs/guides/upgrades-auto-update.mdindex 392d8e927c..08acb6947d 100644--- a/docs/guides/upgrades-auto-update.md+++ b/docs/guides/upgrades-auto-update.md@@ -110,8 +110,11 @@ start, the upgrade exits non-zero and prints recovery: `bun upgrade`, thenrolled back automatically, and the autopilot channel records that version asfailed.-Tag-pinned package installs (`github:garrytan/gbrain#v<x>`) stay pinned through-`bun update`, so `gbrain upgrade` prints a reinstall instead. Every printed+Tag- or commit-pinned package installs (`github:garrytan/gbrain#v<x>`, `#<sha>`)+stay pinned through `bun update`, so `gbrain upgrade` replaces them itself when a+newer release tag is published (`bun remove -g gbrain`, then `bun add -g` the tag,+restoring the previous release if the add fails), and otherwise prints a+reinstall. Every printedreinstall checks that the release tag exists before `bun remove -g gbrain`runs, and ends with the line that restores the previous version if the addfails. The target is the newest published release tag: master's `VERSION` is@@ -241,6 +244,10 @@ process this brain runs on the host, or refuses before it installs anything:worker registry; a record whose pid `ps` does not show as gbrain is staleand ignored) and checks that each one can be restarted: serve and autopilotthrough their installed services when the service's own process runs them,+ a process that starts from a separate Bun global copy (for example one the+ serve service points at, pinned to a commit) has that copy replaced first+ (`bun remove -g` then `bun add -g` the release tag under its `BUN_INSTALL`),+ and one that starts from another kind of install refuses with its commands;the supervisor with `gbrain jobs supervisor stop` then `start --detach` withthe queue, concurrency and PID file it was launched with (its worker, undertini or not, restarts with it). A serve or worker started by hand, andiff --git a/src/commands/upgrade-restart.ts b/src/commands/upgrade-restart.tsindex fa41271da8..3e89e4194f 100644--- a/src/commands/upgrade-restart.ts+++ b/src/commands/upgrade-restart.ts@@ -22,10 +22,10 @@ import { resolveAutopilotJob } from '../core/autopilot-paths.ts';import { plistPath, systemdUnitPath } from './autopilot/jobs.ts';import { readSupervisorBuild, readSupervisorPid } from '../core/minions/supervisor-pid.ts';import { parseEtimeToMs, readWorkers } from '../core/minions/worker-registry.ts';-import { installedVersion } from '../core/runtime-build.ts';+import { installedVersion, runtimeInstallRoot } from '../core/runtime-build.ts';import { VERSION } from '../version.ts';import {- classifyGbrainCommand, collectHostProcesses, gbrainEntry, planRestart, runRestartSteps, verifyRestart,+ classifyGbrainCommand, collectHostProcesses, copyFix, gbrainEntry, mismatchedBuilds, PENDING_BUILD, planRestart, runRestartSteps, verifyRestart,type HostProcess, type ProcessSources, type ProcessTableRow, type RestartPlan, type ServiceHandle, type WarmSocketState,} from '../core/upgrade-restart.ts';@@ -33,8 +33,6 @@ const DOCS = 'docs/guides/upgrades-auto-update.md#restart';const DRY_RUN_VERIFY = ['gbrain', 'upgrade', '--restart-only', '--dry-run', '--json'];const VERIFY_TIMEOUT_MS = 180_000;const VERIFY_POLL_MS = 2_000;-/** A pre-swap plan treats every process as stale: none can run the build that is not installed yet. */-const PENDING_BUILD = 'pending';const brainHome = () => process.env.GBRAIN_HOME?.trim() || homedir();@@ -64,20 +62,20 @@ function readProcessTable(uid: number | undefined, pids?: number[]): ProcessTabl});}-/** The version the install a gbrain command line starts from holds now: the package.json above its entry point (null for a compiled binary). */-function installVersionOf(command: string): string | null {+/** The gbrain install a command line starts from: the package directory above its entry point and the version it holds now (null for a compiled binary). */+function installOf(command: string): { root: string | null; version: string | null } {const entry = gbrainEntry(command)?.entry;- if (!entry) return null;+ if (!entry) return { root: null, version: null };try {const found = entry.includes('/') ? entry : (process.env.PATH ?? '').split(delimiter).map(dir => join(dir, entry)).find(path => existsSync(path));- if (!found) return null;+ if (!found) return { root: null, version: null };let dir = dirname(realpathSync(found));for (let i = 0; i < 4; i++, dir = dirname(dir)) {const version = installedVersion(dir);- if (version) return version;+ if (version) return { root: dir, version };}} catch { /* unknown */ }- return null;+ return { root: null, version: null };}/** The pid a service manager runs for a unit or label now; null when it is not running or cannot be read. */@@ -133,7 +131,7 @@ async function hostSources(): Promise<{ sources: ProcessSources; notes: string[]},workers: () => { try { return readWorkers(() => null).map(w => ({ pid: w.pid, version: w.version ?? null })); } catch { return []; } },processTable: () => readProcessTable(uid),- installVersion: installVersionOf,+ install: installOf,home: brainHome(),exclude: [process.pid, process.ppid],};@@ -155,6 +153,7 @@ function describeSteps(plan: RestartPlan): string[] {const name = (pid: number) => byPid.has(pid) ? describe(byPid.get(pid)!) : `pid ${pid}`;return plan.steps.map(step => step.kind === 'service' ? `${step.pids.map(name).join(', ')}: \`${step.argv.join(' ')}\``: step.kind === 'supervisor' ? `${[step.pid, ...step.workers].map(name).join(', ')}: \`${step.stop.join(' ')}\`, then \`${step.start.join(' ')}\``+ : step.kind === 'replace_copy' ? `${step.pids.map(name).join(', ')} run from the Bun global copy at ${step.root} (${step.from ? `v${step.from}` : 'version unknown'}): replace it with v${step.to} (BUN_INSTALL=${step.bun_install}: bun remove -g gbrain, then bun add -g the tag) before the restarts`: `${name(step.pid)}: stop it (reconnect gbrain in its harness afterwards)`);}@@ -177,6 +176,30 @@ export function restartRefusal(plan: RestartPlan, rerunArgv: readonly string[],export interface HostRestartOptions { stopMcp: boolean; json: boolean; rerunArgv: string[] }+/** The package directory this process loaded its code from (realpath), the install the upgrade replaces. */+function ownInstallRoot(): string | null {+ const root = runtimeInstallRoot();+ try { return root ? realpathSync(root) : null; } catch { return root; }+}++/**+ * GBRA-175: the fix for a process that came back on another build: move the install it runs from onto the target+ * (a Bun global copy is removed and re-added, since a pinned copy keeps its pin through `bun add`), then restart again.+ */+export function mismatchFix(p: HostProcess, expected: string): Action {+ const restart: Action = { argv: ['gbrain', 'upgrade', '--restart-only'], consent: [], actor: 'agent', requires_exclusive: false, docs: DOCS,+ why: 'Restarts every gbrain process onto the installed build and verifies it.', verify: { argv: DRY_RUN_VERIFY } };+ if (!p.install_root) {+ return { argv: DRY_RUN_VERIFY, consent: [], actor: 'agent', requires_exclusive: false, docs: DOCS, verify: { argv: DRY_RUN_VERIFY },+ why: `${p.role} pid ${p.pid} runs another build from an install that could not be located (a compiled binary): reinstall that binary at v${expected} or start the process from this install, then run gbrain upgrade --restart-only.` };+ }+ const fix = copyFix(p.install_root, p.install_version ?? null, expected);+ const envPrefix = Object.entries(fix.env).map(([k, v]) => `${k}=${v}`);+ const chain = fix.argv.reduceRight<Action>((then, argv) => ({ argv: envPrefix.length ? ['env', ...envPrefix, ...argv] : argv, consent: [], actor: 'user', requires_exclusive: false, docs: DOCS,+ why: `${p.role} pid ${p.pid} came back on another build because it runs from ${p.install_root}: ${fix.instruction}.`, then }), restart);+ return { ...chain, ask_user: true, user_message: `${p.role} pid ${p.pid} still runs another gbrain build after the restart: it starts from ${p.install_root}, which holds ${p.install_version ? `v${p.install_version}` : 'an unknown version'}. May I ${fix.instruction}, then restart again?` };+}+/*** Before the swap: refuse (exit 3, nothing installed) when a running process could not be restarted afterwards.* Returns true when the upgrade may proceed.@@ -185,7 +208,7 @@ export async function preflightHostRestart(opts: HostRestartOptions): Promise<boconst { sources, close } = await hostSources();try {const services = hostServices();- const plan = planRestart(await collectHostProcesses(sources), { expected: PENDING_BUILD, serveService: services.serve, autopilotService: services.autopilot, stopMcp: opts.stopMcp });+ const plan = planRestart(await collectHostProcesses(sources), { expected: PENDING_BUILD, serveService: services.serve, autopilotService: services.autopilot, stopMcp: opts.stopMcp, ownInstallRoot: ownInstallRoot() });const refusal = restartRefusal(plan, opts.rerunArgv, false);if (!refusal) return true;setCliExitVerdict(writeCliError(refusal, 'upgrade', { json: opts.json }));@@ -201,7 +224,7 @@ export async function runHostRestart(opts: HostRestartOptions & { dryRun: booleatry {const services = hostServices();const before = await collectHostProcesses(sources);- const plan = planRestart(before, { expected: VERSION, serveService: services.serve, autopilotService: services.autopilot, stopMcp: opts.stopMcp });+ const plan = planRestart(before, { expected: VERSION, serveService: services.serve, autopilotService: services.autopilot, stopMcp: opts.stopMcp, ownInstallRoot: ownInstallRoot() });const { probeCliSocket } = await import('../core/cli-socket/probe.ts');const warmBefore = await probeCliSocket();const planDoc = { expected: VERSION, processes: before, steps: plan.steps, manual: plan.manual, warm_socket: warmBefore, notes };@@ -215,8 +238,8 @@ export async function runHostRestart(opts: HostRestartOptions & { dryRun: booleaif (!opts.json) printPlan(plan, warmBefore, notes);const startedMs = Date.now();const results = await runRestartSteps(plan, {- run: argv => {- const r = spawnSync(argv[0]!, argv.slice(1), { encoding: 'utf8', timeout: 600_000, stdio: ['ignore', 'pipe', 'pipe'] });+ run: (argv, env) => {+ const r = spawnSync(argv[0]!, argv.slice(1), { encoding: 'utf8', timeout: 600_000, stdio: ['ignore', 'pipe', 'pipe'], env: env ? { ...process.env, ...env } : process.env });return { status: r.error ? null : r.status, output: `${r.stdout ?? ''}${r.stderr ?? ''}${r.error ? r.error.message : ''}` };},terminate: terminateIfUnchanged,@@ -231,10 +254,11 @@ export async function runHostRestart(opts: HostRestartOptions & { dryRun: booleaconst doc = { status: verified.ok ? 'ok' : 'unverified', ...planDoc, results, verified: { processes: verified.processes, warm_socket: verified.warm_socket, problems: verified.problems, unverified: verified.unverified } };if (!verified.ok) {const failed = results.find(r => !r.ok);+ const mismatch = mismatchedBuilds(plan, verified.processes)[0];setCliExitVerdict(writeCliError(opError('restart_unverified',`After the restart this host still runs more than one gbrain build, or a process did not come back: ${verified.problems.join(' ')}`,- `${failed ? `${failed.detail}. ` : ''}Restart what is listed with the command the plan printed, then run \`gbrain upgrade --restart-only\` again.`,- { docs: DOCS, fix: { argv: DRY_RUN_VERIFY, consent: [], actor: 'agent', requires_exclusive: false, docs: DOCS, why: 'Read-only: lists every gbrain process on this host with its build and the restart each one needs.', verify: { argv: ['gbrain', 'doctor', '--only', 'runtime_build_skew', '--json'] } } }),+ `${failed ? `${failed.detail}. ` : ''}${mismatch ? 'Move each listed install onto this build as named' : 'Restart what is listed with the command the plan printed'}, then run \`gbrain upgrade --restart-only\` again.`,+ { docs: DOCS, fix: mismatch ? mismatchFix(mismatch, VERSION) : { argv: DRY_RUN_VERIFY, consent: [], actor: 'agent', requires_exclusive: false, docs: DOCS, why: 'Read-only: lists every gbrain process on this host with its build and the restart each one needs.', verify: { argv: ['gbrain', 'doctor', '--only', 'runtime_build_skew', '--json'] } } }),'upgrade', { json: opts.json, extra: opts.json ? { restart: doc } : undefined }));return;}diff --git a/src/commands/upgrade.ts b/src/commands/upgrade.tsindex 87a41721c1..144e6a0fca 100644--- a/src/commands/upgrade.ts+++ b/src/commands/upgrade.ts@@ -12,8 +12,10 @@ import { forwardProgressPast, migrationLedgerSummary, wedgedLedgerHint } from '.import { loadCompletedMigrations } from '../core/preferences.ts';import { MIGRATIONS_RUNNING_EXIT_CODE, readMigrationLockHolder } from '../core/migration-orchestration-lock.ts';import { loadConfig } from '../core/config.ts';-import { clearSnooze, clearUpdateCache, normalizeChannel, resolveReleaseChannel, writeJustUpgraded, writeSwapReceipt, type ReleaseChannel } from '../core/self-upgrade.ts';+import { clearSnooze, clearUpdateCache, resolveReleaseChannel, writeJustUpgraded, writeSwapReceipt, type ReleaseChannel } from '../core/self-upgrade.ts';import { preflightHostRestart, runHostRestart } from './upgrade-restart.ts';+import { parseChannelArg, resolveStableRelease, stableUnresolvedMessage } from '../core/stable-channel.ts';+export { parseChannelArg, resolveStableRelease } from '../core/stable-channel.ts';import { MOVEMENT_SUPERVISOR_STEP } from './movement-step.ts';import {BUN_FLOOR_EXIT_CODE,@@ -67,7 +69,6 @@ export async function runUpgrade(args: string[], opts: { targetVersion?: stringreturn;}const noRestart = args.includes('--no-restart');-// Capture old version BEFORE upgrading (Codex finding: old binary runs this code)const oldVersion = VERSION;const method = detectInstallMethod();@@ -77,7 +78,6 @@ export async function runUpgrade(args: string[], opts: { targetVersion?: stringconst stableTarget = channelTarget(args, oldVersion, json);if (stableTarget === 'stop') return;if (stableTarget) opts = { ...opts, targetVersion: stableTarget.version };-if (!swapOnly && !noRestart && !await preflightHostRestart(restartOpts)) return;let upgraded = false;@@ -117,6 +117,8 @@ export async function runUpgrade(args: string[], opts: { targetVersion?: stringcase 'bun': {console.log('Upgrading via bun...');const bunGlobalRoot = resolveBunGlobalRoot();+ const pinned = await replacePinnedInstall(bunGlobalRoot, opts.targetVersion ?? null, { oldVersion, upgradeEnv, checkBunFloor, recovery, phase: 'pinned-reinstall' });+ if (pinned) { if (pinned === 'refused') return; upgraded = pinned === 'installed'; break; }if (checkBunFloor && refuseForBunFloor(await readPackageTarget(globalGbrainSpec(bunGlobalRoot)), opts.targetVersion)) return;try {execFileSync('bun', ['update', 'gbrain'], { cwd: bunGlobalRoot, env: upgradeEnv, stdio: 'inherit', timeout: 120_000 });@@ -254,7 +256,7 @@ export async function runUpgrade(args: string[], opts: { targetVersion?: string// the newest PUBLISHED release tag only; with none newer the hint moves the// install off the pin, and the ledger row names no unpublished version.if (!target && method === 'bun' && unchanged) {- const pin = bunGlobalExactTagPin(resolveBunGlobalRoot());+ const pin = bunGlobalExactTagPin(resolveBunGlobalRoot(), true);if (pin) {const plan = planPinnedReinstall(null, oldVersion);console.error(`Upgrade did not take effect: still running ${newVersion}, because the global install is pinned to ${pin} and \`bun update\` keeps a pinned tag.`);@@ -346,14 +348,6 @@ export async function runUpgrade(args: string[], opts: { targetVersion?: stringconsole.log(`Next: ${MOVEMENT_SUPERVISOR_STEP}`);}-/** GBRA-175: `--channel <name>` / `--channel=<name>`; null when absent, 'invalid' for anything but latest or stable. */-export function parseChannelArg(args: readonly string[]): ReleaseChannel | 'invalid' | null {- const at = args.findIndex(a => a === '--channel' || a.startsWith('--channel='));- if (at === -1) return null;- const raw = args[at]!.includes('=') ? args[at]!.slice('--channel='.length) : args[at + 1];- return normalizeChannel(raw) ?? 'invalid';-}-/** GBRA-175: the new build restarts every process onto itself and verifies one build runs; returns the summary line. */function restartOntoNewBuild(stopMcp: boolean, newVersion: string): string {const restart = spawnSync('gbrain', ['upgrade', '--restart-only', ...(stopMcp ? ['--stop-mcp'] : [])], { stdio: cliChildStdio(), env: { ...process.env, GBRAIN_SKIP_STARTUP_HOOKS: '1' }, timeout: 900_000 });@@ -388,37 +382,20 @@ function channelTarget(args: readonly string[], oldVersion: string, json: booleareturn stable;}-function stableUnresolvedMessage(error: 'unreadable' | 'no_stable' | 'no_release_tag'): string {- if (error === 'unreadable') return `The stable channel could not be read: \`git ls-remote --tags ${GBRAIN_GIT_URL}\` failed (offline, or no git).`;- if (error === 'no_stable') return 'No release has been promoted to the stable channel yet (the repository has no `stable` tag).';- return 'The `stable` tag does not point at a published release commit (no `v<version>` tag shares its commit).';-}-/**- * GBRA-175: the release the stable channel names: the `v<version>` tag on the commit `refs/tags/stable` peels to- * (the newest when several share it). promote-stable.yml moves `stable` only to a published release whose exact- * tree passed the soak.+ * GBRA-175: `bun update` keeps a pinned tag or commit, so a pinned global install is replaced with the newest published+ * release (remove, then add the tag). null when the install is not pinned, or a requested version is not published (#6662+ * then reports it after the no-op update).*/-export function resolveStableRelease(git: GitRunner = runGit): { version: string; commit: string } | { error: 'unreadable' | 'no_stable' | 'no_release_tag' } {- const { status, stdout } = git(['ls-remote', '--tags', GBRAIN_GIT_URL]);- if (status !== 0) return { error: 'unreadable' };- const refs = new Map<string, string>();- for (const line of stdout.split('\n')) {- const [sha, ref] = line.trim().split('\t');- if (sha && ref) refs.set(ref, sha);- }- const peel = (tag: string) => refs.get(`refs/tags/${tag}^{}`) ?? refs.get(`refs/tags/${tag}`);- const commit = peel('stable');- if (!commit) return { error: 'no_stable' };- let best: string | null = null;- for (const ref of refs.keys()) {- const v = /^refs\/tags\/v(\d+\.\d+\.\d+(?:\.\d+)?)$/.exec(ref)?.[1];- if (v && peel(`v${v}`) === commit && (!best || isNewerVersion(best, v))) best = v;- }- return best ? { version: best, commit } : { error: 'no_release_tag' };+async function replacePinnedInstall(globalRoot: string, requested: string | null, ctx: StableInstallContext): Promise<'installed' | 'failed' | 'refused' | null> {+ const pin = bunGlobalExactTagPin(globalRoot, true);+ const plan = pin ? planPinnedReinstall(requested, ctx.oldVersion) : null;+ if (!plan?.version || plan.unpublished) return null;+ console.log(`The global install is pinned to ${pin}; replacing it with v${plan.version}.`);+ return installStableRelease('bun', { version: plan.version, commit: '' }, ctx);}-interface StableInstallContext { oldVersion: string; upgradeEnv: NodeJS.ProcessEnv; checkBunFloor: boolean; recovery: SmokeRecovery }+interface StableInstallContext { oldVersion: string; upgradeEnv: NodeJS.ProcessEnv; checkBunFloor: boolean; recovery: SmokeRecovery; phase?: string }/*** GBRA-175: install exactly the stable release. bun: reinstall pinned to its tag (an in-place tag swap corrupts a@@ -485,7 +462,7 @@ async function installStableRelease(method: string, target: { version: string; cconsole.error(`Installing ${spec} failed. Restoring gbrain ${ctx.oldVersion}...`);try { bun(['add', '-g', `github:${GBRAIN_GITHUB_REPO}#v${ctx.oldVersion}`]); console.error(`Restored gbrain ${ctx.oldVersion}.`); }catch { console.error(`Restore failed. Reinstall by hand: ${bunReinstallCommand(`#v${target.version}`)}`); }- recordUpgradeError({ phase: 'stable-reinstall', fromVersion: ctx.oldVersion, toVersion: target.version, error: `bun add -g ${spec} failed`, recover: bunReinstallCommand(`#v${target.version}`) });+ recordUpgradeError({ phase: ctx.phase ?? 'stable-reinstall', fromVersion: ctx.oldVersion, toVersion: target.version, error: `bun add -g ${spec} failed`, recover: bunReinstallCommand(`#v${target.version}`) });setCliExitVerdict(1);return 'failed';}@@ -716,14 +693,15 @@ function pinnedReinstallHint(plan: PinnedReinstallPlan): string {/*** #5311: the exact Git tag the bun global install pins gbrain to* (`github:garrytan/gbrain#v0.51.0`), or null for an unpinned or branch spec.+ * With `commits`, a commit pin (`#<sha>`) counts too (GBRA-175).*/-export function bunGlobalExactTagPin(globalRoot: string): string | null {+export function bunGlobalExactTagPin(globalRoot: string, commits = false): string | null {try {// nosemgrep: javascript.lang.security.audit.path-traversal.path-join-resolve-traversal.path-join-resolve-traversal -- globalRoot is resolveBunGlobalRoot(): Bun's own global install dir from BUN_INSTALL or HOMEconst pkg = JSON.parse(readFileSync(join(globalRoot, 'package.json'), 'utf-8')) as { dependencies?: Record<string, string> };const spec = pkg.dependencies?.gbrain;if (typeof spec !== 'string') return null;- return /#v?\d+\.\d+(\.\d+)*$/.test(spec.trim()) ? spec.trim() : null;+ return /#v?\d+\.\d+(\.\d+)*$/.test(spec.trim()) || (commits && /#[0-9a-f]{7,40}$/.test(spec.trim())) ? spec.trim() : null;} catch {return null;}diff --git a/src/core/stable-channel.ts b/src/core/stable-channel.tsnew file mode 100644index 0000000000..9db25d26dd--- /dev/null+++ b/src/core/stable-channel.ts@@ -0,0 +1,53 @@+/**+ * GBRA-175: the stable release channel on the client side: which release the+ * annotated `stable` tag names, and the `--channel` argument. gbrain upgrade+ * installs it; .github/workflows/promote-stable.yml moves the tag.+ */+import { spawnSync } from './spawn.ts';+import { isNewerVersion } from './semver.ts';+import { normalizeChannel, type ReleaseChannel } from './self-upgrade.ts';++const GBRAIN_GIT_URL = 'https://github.com/garrytan/gbrain';+export type GitRunner = (args: string[]) => { status: number | null; stdout: string };+const runGit: GitRunner = (args) => {+ const r = spawnSync('git', args, { encoding: 'utf-8', stdio: ['ignore', 'pipe', 'ignore'], timeout: 15_000 });+ return { status: r.error ? null : r.status, stdout: r.stdout ?? '' };+};++/** GBRA-175: `--channel <name>` / `--channel=<name>`; null when absent, 'invalid' for anything but latest or stable. */+export function parseChannelArg(args: readonly string[]): ReleaseChannel | 'invalid' | null {+ const at = args.findIndex(a => a === '--channel' || a.startsWith('--channel='));+ if (at === -1) return null;+ const raw = args[at]!.includes('=') ? args[at]!.slice('--channel='.length) : args[at + 1];+ return normalizeChannel(raw) ?? 'invalid';+}++export function stableUnresolvedMessage(error: 'unreadable' | 'no_stable' | 'no_release_tag'): string {+ if (error === 'unreadable') return `The stable channel could not be read: \`git ls-remote --tags ${GBRAIN_GIT_URL}\` failed (offline, or no git).`;+ if (error === 'no_stable') return 'No release has been promoted to the stable channel yet (the repository has no `stable` tag).';+ return 'The `stable` tag does not point at a published release commit (no `v<version>` tag shares its commit).';+}++/**+ * GBRA-175: the release the stable channel names: the `v<version>` tag on the commit `refs/tags/stable` peels to+ * (the newest when several share it). promote-stable.yml moves `stable` only to a published release whose exact+ * tree passed the soak.+ */+export function resolveStableRelease(git: GitRunner = runGit): { version: string; commit: string } | { error: 'unreadable' | 'no_stable' | 'no_release_tag' } {+ const { status, stdout } = git(['ls-remote', '--tags', GBRAIN_GIT_URL]);+ if (status !== 0) return { error: 'unreadable' };+ const refs = new Map<string, string>();+ for (const line of stdout.split('\n')) {+ const [sha, ref] = line.trim().split('\t');+ if (sha && ref) refs.set(ref, sha);+ }+ const peel = (tag: string) => refs.get(`refs/tags/${tag}^{}`) ?? refs.get(`refs/tags/${tag}`);+ const commit = peel('stable');+ if (!commit) return { error: 'no_stable' };+ let best: string | null = null;+ for (const ref of refs.keys()) {+ const v = /^refs\/tags\/v(\d+\.\d+\.\d+(?:\.\d+)?)$/.exec(ref)?.[1];+ if (v && peel(`v${v}`) === commit && (!best || isNewerVersion(best, v))) best = v;+ }+ return best ? { version: best, commit } : { error: 'no_release_tag' };+}diff --git a/src/core/upgrade-restart.ts b/src/core/upgrade-restart.tsindex 8c5e38fda3..2277de240e 100644--- a/src/core/upgrade-restart.ts+++ b/src/core/upgrade-restart.ts@@ -50,6 +50,8 @@ export interface HostProcess {args?: string[];/** The version the install it was started from holds now; null when unknown (a compiled binary). */install_version?: string | null;+ /** The package directory of the gbrain install it was started from (realpath); null when unknown (a compiled binary). */+ install_root?: string | null;}export interface ProcessTableRow { pid: number; ppid: number; command: string; started_ms: number | null; gbrain_home: string | null | undefined }@@ -61,8 +63,8 @@ export interface ProcessSources {workers: () => Array<{ pid: number; version: string | null }>;/** This user's processes, null when ps cannot run; `gbrain_home` is the GBRAIN_HOME (else HOME) from the process's environment, undefined when unreadable. */processTable: () => ProcessTableRow[] | null;- /** The version the install a command line starts from holds now; null when unknown. */- installVersion?: (command: string) => string | null;+ /** The gbrain install a command line starts from: its package directory and the version it holds now (null when unknown). */+ install?: (command: string) => { root: string | null; version: string | null };/** This brain's GBRAIN_HOME (else HOME), resolved. */home: string;/** Pids never listed: this process and its parents (the upgrade that spawned it). */@@ -101,6 +103,8 @@ export function classifyGbrainCommand(command: string): ProcessRole | null {return null;}+const installFields = (install: { root: string | null; version: string | null } | undefined) => ({ install_version: install?.version ?? null, install_root: install?.root ?? null });+const HEARTBEAT_ROLES: Record<string, ProcessRole> = { serve: 'serve', jobs: 'worker', autopilot: 'autopilot', mcp: 'mcp', sync: 'sync' };/** Every gbrain process this brain runs on this host, one per pid. */@@ -120,7 +124,7 @@ export async function collectHostProcesses(sources: ProcessSources): Promise<Hosconst role = classifyGbrainCommand(row.command);if (!role) continue;byPid.set(row.pid, { pid: row.pid, ppid: null, role, version: null, started_ms: row.started_ms, ancestors: ancestry(row.ppid),- args: gbrainEntry(row.command)!.args, install_version: sources.installVersion?.(row.command) ?? null });+ args: gbrainEntry(row.command)!.args, ...installFields(sources.install?.(row.command)) });}const merge = (pid: number, role: ProcessRole | null, version: string | null) => {if (excluded.has(pid)) return;@@ -152,12 +156,38 @@ export interface RestartContext {autopilotService: ServiceHandle | null;/** Stop MCP stdio servers (their harness starts the new build on reconnect) instead of refusing. */stopMcp: boolean;+ /** The package directory of the install this upgrade replaces (realpath); null when unknown (a compiled binary). */+ ownInstallRoot?: string | null;+}++/** Before the swap the installed build is not known yet: every process is stale. */+export const PENDING_BUILD = 'pending';++/** A gbrain package directory inside a Bun global install (`<BUN_INSTALL>/install/global/node_modules/gbrain`): the BUN_INSTALL it belongs to. */+export function bunGlobalCopyOf(pkgDir: string): { bun_install: string } | null {+ const parts = pkgDir.replace(/\/+$/, '').split('/');+ if (parts.length < 6 || parts.slice(-4).join('/') !== 'install/global/node_modules/gbrain') return null;+ return { bun_install: parts.slice(0, -4).join('/') || '/' };+}++/** The steps that move another gbrain install onto the target build, as argv, plus the sentence that names them. */+export function copyFix(root: string, holds: string | null, expected: string): { argv: string[][]; env: Record<string, string>; instruction: string } {+ const release = expected === PENDING_BUILD ? 'the release being installed' : `v${expected}`;+ const copy = bunGlobalCopyOf(root);+ if (copy) {+ const argv = [['bun', 'remove', '-g', 'gbrain'], ['bun', 'add', '-g', `github:garrytan/gbrain#v${expected}`]];+ const shown = argv.map(a => `BUN_INSTALL=${copy.bun_install} ${a.join(' ')}`).join(' && ');+ return { argv, env: { BUN_INSTALL: copy.bun_install }, instruction: `replace the Bun global copy at ${root} (${holds ? `v${holds}` : 'version unknown'}; a pinned copy keeps its pin through bun add alone, so remove it first): \`${shown}\`` };+ }+ const argv = [['git', '-C', root, 'fetch', '--tags', 'origin'], ['git', '-C', root, 'checkout', `v${expected}`], ['bun', 'install', '--cwd', root]];+ return { argv, env: {}, instruction: `move the install at ${root} (${holds ? `v${holds}` : 'version unknown'}) to ${release}: for a git clone, \`${argv.map(a => a.join(' ')).join(' && ')}\`; otherwise start this process from the upgraded install instead` };}export type RestartStep =| { kind: 'service'; role: 'serve' | 'autopilot'; argv: string[]; pids: number[] }| { kind: 'supervisor'; pid: number; workers: number[]; stop: string[]; start: string[]; pid_file: string | null }- | { kind: 'stop'; role: 'mcp'; pid: number; started_ms: number | null };+ | { kind: 'stop'; role: 'mcp'; pid: number; started_ms: number | null }+ | { kind: 'replace_copy'; root: string; bun_install: string; from: string | null; to: string; pids: number[] };export interface ManualStep { role: ProcessRole; pid: number; version: string | null; argv: string[]; instruction: string }@@ -197,8 +227,21 @@ export function planRestart(processes: readonly HostProcess[], ctx: RestartConteconst runsUnder = (p: HostProcess, service: ServiceHandle | null) => !!service && service.pid !== null && (p.pid === service.pid || !!p.ancestors?.includes(service.pid));const kill = (p: HostProcess, instruction: string) => manual.push({ role: p.role, pid: p.pid, version: p.version, argv: ['kill', String(p.pid)], instruction });+ const copies = new Map<string, Extract<RestartStep, { kind: 'replace_copy' }>>();for (const p of stale) {const parent = p.ppid === null ? undefined : byPid.get(p.ppid);+ if (ctx.ownInstallRoot && p.install_root && p.install_root !== ctx.ownInstallRoot && p.install_version !== ctx.expected) {+ const copy = bunGlobalCopyOf(p.install_root);+ if (!copy) {+ const fix = copyFix(p.install_root, p.install_version ?? null, ctx.expected);+ manual.push({ role: p.role, pid: p.pid, version: p.version, argv: fix.argv[0]!,+ instruction: `${label(p)} runs from another gbrain install, which this upgrade does not change, so a restart brings it back on the old build: ${fix.instruction}; then run the upgrade again.` });+ continue;+ }+ const known = copies.get(p.install_root);+ if (known) known.pids.push(p.pid);+ else copies.set(p.install_root, { kind: 'replace_copy', root: p.install_root, bun_install: copy.bun_install, from: p.install_version ?? null, to: ctx.expected, pids: [p.pid] });+ }switch (p.role) {case 'serve':if (runsUnder(p, ctx.serveService)) addService('serve', p.pid);@@ -228,7 +271,7 @@ export function planRestart(processes: readonly HostProcess[], ctx: RestartContebreak;}}- const steps: RestartStep[] = [];+ const steps: RestartStep[] = [...copies.values()];const serve = services.get('serve');if (serve && ctx.serveService) steps.push({ kind: 'service', role: 'serve', argv: ctx.serveService.argv, pids: [...new Set(serve)] });const autopilot = services.get('autopilot');@@ -239,7 +282,7 @@ export function planRestart(processes: readonly HostProcess[], ctx: RestartConte}export interface RestartExecutor {- run: (argv: string[]) => { status: number | null; output: string };+ run: (argv: string[], env?: Record<string, string>) => { status: number | null; output: string };/** SIGTERM the MCP server at pid only if it is still the process the plan saw: 'changed' when the pid now names another process. */terminate: (pid: number, startedMs: number | null) => 'stopped' | 'gone' | 'changed';/** The live supervisor's pid now (read from its PID file, the default one when null), or null. */@@ -255,7 +298,18 @@ const failed = (argv: string[], r: { status: number | null; output: string }) =>export async function runRestartSteps(plan: RestartPlan, exec: RestartExecutor): Promise<StepResult[]> {const results: StepResult[] = [];for (const step of plan.steps) {- if (step.kind === 'service') {+ if (step.kind === 'replace_copy') {+ const env = { BUN_INSTALL: step.bun_install };+ const probe = ['git', 'ls-remote', '--exit-code', '--tags', 'https://github.com/garrytan/gbrain', `refs/tags/v${step.to}`];+ const add = ['bun', 'add', '-g', `github:garrytan/gbrain#v${step.to}`];+ const probed = exec.run(probe);+ if (probed.status !== 0) { results.push({ step, ok: false, detail: `v${step.to} has no release tag, so the copy at ${step.root} was left as it is (${failed(probe, probed)})` }); continue; }+ const removed = exec.run(['bun', 'remove', '-g', 'gbrain'], env);+ const added = removed.status === 0 ? exec.run(add, env) : removed;+ if (added.status === 0) { results.push({ step, ok: true, detail: `replaced the Bun global copy at ${step.root} with v${step.to}` }); continue; }+ const restored = removed.status === 0 && step.from ? exec.run(['bun', 'add', '-g', `github:garrytan/gbrain#v${step.from}`], env).status === 0 : false;+ results.push({ step, ok: false, detail: `could not replace the copy at ${step.root} (${failed(removed.status === 0 ? add : ['bun', 'remove', '-g', 'gbrain'], added)})${restored ? `; restored v${step.from}` : ''}` });+ } else if (step.kind === 'service') {const r = exec.run(step.argv);results.push({ step, ok: r.status === 0, detail: r.status === 0 ? `ran \`${step.argv.join(' ')}\`` : failed(step.argv, r) });} else if (step.kind === 'supervisor') {@@ -287,7 +341,13 @@ function refusesThisBuild(warm: WarmSocketState): boolean {return warm.state === 'refused' && !(warm.reason === 'identity_mismatch' && warm.mismatch && warm.mismatch !== 'version');}-const restartedPids = (plan: RestartPlan) => new Set(plan.steps.flatMap(step => step.kind === 'service' ? step.pids : step.kind === 'supervisor' ? [step.pid, ...step.workers] : [step.pid]));+const restartedPids = (plan: RestartPlan) => new Set(plan.steps.flatMap(step => step.kind === 'service' ? step.pids : step.kind === 'supervisor' ? [step.pid, ...step.workers] : step.kind === 'stop' ? [step.pid] : []));++/** Processes that came back on a build other than the target, with the install each one runs from. */+export function mismatchedBuilds(plan: RestartPlan, processes: readonly HostProcess[]): HostProcess[] {+ const restarted = restartedPids(plan);+ return processes.filter(p => !restarted.has(p.pid) && (p.version ? p.version !== plan.expected : !!p.install_version && p.install_version !== plan.expected));+}/** What still stands between the host and one build after a restart; empty when it is done. */export function restartProblems(plan: RestartPlan, processes: readonly HostProcess[], restartStartedMs: number,@@ -300,13 +360,15 @@ export function restartProblems(plan: RestartPlan, processes: readonly HostProceif (p) problems.push(`${label(p)} is still running after the restart.`);}const fresh = processes.filter(p => !restarted.has(p.pid));+ const mismatched = new Set(mismatchedBuilds(plan, processes));for (const p of fresh) {- if (p.version && p.version !== plan.expected) problems.push(`${label(p)} runs a build other than v${plan.expected}.`);- else if (!p.version && p.install_version && p.install_version !== plan.expected) problems.push(`${label(p)} reports no build and was started from an install that holds v${p.install_version}.`);+ const from = p.install_root ? `; it runs from ${p.install_root}, which holds ${p.install_version ? `v${p.install_version}` : 'an unknown version'}: ${copyFix(p.install_root, p.install_version ?? null, plan.expected).instruction}` : '';+ if (mismatched.has(p) && p.version) problems.push(`${label(p)} runs a build other than v${plan.expected}${from}.`);+ else if (mismatched.has(p)) problems.push(`${label(p)} reports no build and was started from an install that holds v${p.install_version}${from}.`);else if (!p.version && (p.started_ms === null || p.started_ms < restartStartedMs)) problems.push(`${label(p)} reports no build and started before the restart.`);}for (const step of plan.steps) {- if (step.kind === 'stop') continue;+ if (step.kind === 'stop' || step.kind === 'replace_copy') continue;const role = step.kind === 'service' ? step.role : 'supervisor';if (!fresh.some(p => p.role === role)) {problems.push(`${role} did not come back after ${step.kind === 'service' ? `\`${step.argv.join(' ')}\`` : 'the supervisor restart'}.`);diff --git a/test/upgrade-restart.test.ts b/test/upgrade-restart.test.tsindex f48a2c77b8..2299dae274 100644--- a/test/upgrade-restart.test.ts+++ b/test/upgrade-restart.test.ts@@ -7,10 +7,10 @@*/import { describe, expect, test } from 'bun:test';import {- classifyGbrainCommand, collectHostProcesses, planRestart, restartProblems, runRestartSteps, supervisorRestartArgv, unverifiedBuilds, verifyRestart,+ bunGlobalCopyOf, classifyGbrainCommand, collectHostProcesses, mismatchedBuilds, planRestart, restartProblems, runRestartSteps, supervisorRestartArgv, unverifiedBuilds, verifyRestart,type HostProcess, type ProcessSources, type RestartContext, type RestartExecutor, type WarmSocketState,} from '../src/core/upgrade-restart.ts';-import { restartRefusal } from '../src/commands/upgrade-restart.ts';+import { mismatchFix, restartRefusal } from '../src/commands/upgrade-restart.ts';import { exitCodeForCode } from '../src/core/error-catalogue.ts';const NEW = '0.60.400.0';@@ -82,13 +82,13 @@ describe('collectHostProcesses', () => {heartbeats: async () => [{ pid: 10, kind: 'serve', version: OLD }, { pid: 40, kind: 'autopilot', version: NEW }, { pid: 50, kind: 'cli', version: NEW }],supervisor: () => ({ pid: 20, version: OLD }),workers: () => [{ pid: 21, version: OLD }],- installVersion: command => command.startsWith('/usr/local/bin/gbrain') ? NEW : null,+ install: command => command.startsWith('/usr/local/bin/gbrain') ? { root: '/usr/local/lib/gbrain', version: NEW } : { root: null, version: null },}));expect(processes).toEqual([- { pid: 10, ppid: null, role: 'serve', version: OLD, started_ms: 500, ancestors: [SERVE_PID], args: ['serve', '--http'], install_version: null },- { pid: 20, ppid: null, role: 'supervisor', version: OLD, started_ms: 600, ancestors: [], args: ['jobs', 'supervisor', 'start', '--queue', 'ingest'], install_version: null },- { pid: 21, ppid: 20, role: 'worker', version: OLD, started_ms: 700, ancestors: [22, 20], args: ['jobs', 'work', '--queue', 'ingest'], install_version: NEW },- { pid: 30, ppid: null, role: 'mcp', version: null, started_ms: 800, ancestors: [99], args: ['serve'], install_version: null },+ { pid: 10, ppid: null, role: 'serve', version: OLD, started_ms: 500, ancestors: [SERVE_PID], args: ['serve', '--http'], install_version: null, install_root: null },+ { pid: 20, ppid: null, role: 'supervisor', version: OLD, started_ms: 600, ancestors: [], args: ['jobs', 'supervisor', 'start', '--queue', 'ingest'], install_version: null, install_root: null },+ { pid: 21, ppid: 20, role: 'worker', version: OLD, started_ms: 700, ancestors: [22, 20], args: ['jobs', 'work', '--queue', 'ingest'], install_version: NEW, install_root: '/usr/local/lib/gbrain' },+ { pid: 30, ppid: null, role: 'mcp', version: null, started_ms: 800, ancestors: [99], args: ['serve'], install_version: null, install_root: null },]);});@@ -303,3 +303,79 @@ describe('restartProblems and verifyRestart', () => {expect(clock).toBe(6_000);});});++describe('another install on the host (GBRA-175 production finding: serve ran from a separate pinned Bun global copy)', () => {+ const OWN = '/home/alice-example/.bun/install/global/node_modules/gbrain';+ const COPY = '/opt/gbrain-example/install/global/node_modules/gbrain';+ const CLONE = '/srv/gbrain-clone-example';+ const fromCopy = (pid: number, role: HostProcess['role'], root: string, holds: string | null, over: Partial<HostProcess> = {}) =>+ proc(pid, role, OLD, { install_root: root, install_version: holds, ...over });++ test('bunGlobalCopyOf names the BUN_INSTALL a Bun global package directory belongs to', () => {+ expect(bunGlobalCopyOf(COPY)).toEqual({ bun_install: '/opt/gbrain-example' });+ expect(bunGlobalCopyOf(OWN)).toEqual({ bun_install: '/home/alice-example/.bun' });+ expect(bunGlobalCopyOf(CLONE)).toBeNull();+ expect(bunGlobalCopyOf('/srv/app-example/node_modules/gbrain')).toBeNull();+ });++ test('a stale process from a separate Bun global copy replaces that copy (remove, then add the tag) before its restart', () => {+ const plan = planRestart([fromCopy(10, 'serve', COPY, OLD), fromCopy(11, 'mcp', COPY, OLD), proc(20, 'supervisor', OLD, { install_root: OWN, install_version: NEW })],+ ctx({ ownInstallRoot: OWN, stopMcp: true }));+ expect(plan.manual).toEqual([]);+ expect(plan.steps[0]).toEqual({ kind: 'replace_copy', root: COPY, bun_install: '/opt/gbrain-example', from: OLD, to: NEW, pids: [10, 11] });+ expect(plan.steps.slice(1).map(s => s.kind)).toEqual(['service', 'supervisor', 'stop']);+ });++ test('a process from an install that is not a Bun global copy refuses before anything changes, naming the exact fix', () => {+ const plan = planRestart([fromCopy(10, 'serve', CLONE, OLD)], ctx({ ownInstallRoot: OWN }));+ expect(plan.steps).toEqual([]);+ expect(plan.manual[0]!.argv).toEqual(['git', '-C', CLONE, 'fetch', '--tags', 'origin']);+ expect(plan.manual[0]!.instruction).toContain(`git -C ${CLONE} checkout v${NEW}`);+ expect(restartRefusal(plan, ['gbrain', 'upgrade'], false)?.code).toBe('restart_refused');+ expect(planRestart([fromCopy(10, 'serve', OWN, OLD)], ctx({ ownInstallRoot: OWN })).manual).toEqual([]);+ });++ test('replacing a copy probes the tag, removes and re-adds under its BUN_INSTALL, and restores the old tag when the add fails', async () => {+ const plan = planRestart([fromCopy(10, 'serve', COPY, OLD)], ctx({ ownInstallRoot: OWN }));+ const run = (fail: string | null) => {+ const calls: string[] = [];+ const exec: RestartExecutor = {+ run: (argv, env) => { calls.push(`${env?.BUN_INSTALL ? `BUN_INSTALL=${env.BUN_INSTALL} ` : ''}${argv.join(' ')}`); return { status: fail && argv.join(' ').includes(fail) ? 1 : 0, output: 'error: example' }; },+ terminate: () => 'stopped', supervisorPid: () => null, sleep: async () => {},+ };+ return { calls, exec };+ };+ const ok = run(null);+ expect((await runRestartSteps(plan, ok.exec))[0]).toMatchObject({ ok: true });+ expect(ok.calls.slice(0, 3)).toEqual([+ `git ls-remote --exit-code --tags https://github.com/garrytan/gbrain refs/tags/v${NEW}`,+ 'BUN_INSTALL=/opt/gbrain-example bun remove -g gbrain',+ `BUN_INSTALL=/opt/gbrain-example bun add -g github:garrytan/gbrain#v${NEW}`,+ ]);+ const bad = run(`#v${NEW}`);+ const [result] = await runRestartSteps(plan, bad.exec);+ expect(result).toMatchObject({ ok: false });+ expect(result!.detail).toContain(`restored v${OLD}`);+ expect(bad.calls[3]).toBe(`BUN_INSTALL=/opt/gbrain-example bun add -g github:garrytan/gbrain#v${OLD}`);+ const untagged = run('ls-remote');+ expect((await runRestartSteps(plan, untagged.exec))[0]!.detail).toContain('has no release tag');+ expect(untagged.calls.some(c => c.includes('bun remove'))).toBe(false);+ });++ test('after the restart, a process back on the old build from a pinned copy is caught with the exact fix: remove, add, restart', () => {+ const plan = planRestart([fromCopy(10, 'serve', OWN, NEW, { version: OLD })], ctx({ ownInstallRoot: OWN }));+ const back = fromCopy(110, 'serve', COPY, OLD, { started_ms: 5_000 });+ expect(mismatchedBuilds(plan, [back])).toEqual([back]);+ const [problem] = restartProblems(plan, [back], 4_000, { before: { state: 'absent' }, after: { state: 'absent' } });+ expect(problem).toContain(`serve pid 110 (v${OLD}) runs a build other than v${NEW}; it runs from ${COPY}, which holds v${OLD}`);+ expect(problem).toContain(`BUN_INSTALL=/opt/gbrain-example bun remove -g gbrain && BUN_INSTALL=/opt/gbrain-example bun add -g github:garrytan/gbrain#v${NEW}`);+ const fix = mismatchFix(back, NEW);+ expect(fix).toMatchObject({ ask_user: true, actor: 'user', argv: ['env', 'BUN_INSTALL=/opt/gbrain-example', 'bun', 'remove', '-g', 'gbrain'] });+ expect(fix.then?.argv).toEqual(['env', 'BUN_INSTALL=/opt/gbrain-example', 'bun', 'add', '-g', `github:garrytan/gbrain#v${NEW}`]);+ expect(fix.then?.then?.argv).toEqual(['gbrain', 'upgrade', '--restart-only']);+ expect(fix.user_message).toContain(COPY);+ const reportsNone = fromCopy(111, 'serve', COPY, OLD, { version: null, started_ms: 5_000 });+ expect(mismatchedBuilds(plan, [reportsNone])).toEqual([reportsNone]);+ expect(mismatchedBuilds(plan, [fromCopy(112, 'serve', OWN, NEW, { version: NEW, started_ms: 5_000 })])).toEqual([]);+ });+});diff --git a/test/upgrade-stable-channel.test.ts b/test/upgrade-stable-channel.test.tsindex c0ef499371..ca89c843d2 100644--- a/test/upgrade-stable-channel.test.ts+++ b/test/upgrade-stable-channel.test.ts@@ -63,7 +63,7 @@ describe('channel selection', () => {interface Run { home: string; exitCode: number; stdout: string; stderr: string; bunCalls: string[]; gbrainCalls: string[] }-async function runStableUpgrade(args: string[], opts: { stableCommit?: string | null; config?: Record<string, unknown>; failAdd?: string } = {}): Promise<Run> {+async function runStableUpgrade(args: string[], opts: { stableCommit?: string | null; config?: Record<string, unknown>; failAdd?: string; spec?: string } = {}): Promise<Run> {const home = mkdtempSync(join(tmpdir(), 'gbrain-stable-'));const bin = join(home, 'bin');mkdirSync(bin);@@ -82,7 +82,7 @@ async function runStableUpgrade(args: string[], opts: { stableCommit?: string |const globalRoot = join(home, '.bun', 'install', 'global');const pkgDir = join(globalRoot, 'node_modules', 'gbrain');mkdirSync(pkgDir, { recursive: true });- writeFileSync(join(globalRoot, 'package.json'), JSON.stringify({ dependencies: { gbrain: 'github:garrytan/gbrain#latest-stable' } }));+ writeFileSync(join(globalRoot, 'package.json'), JSON.stringify({ dependencies: { gbrain: opts.spec ?? 'github:garrytan/gbrain#latest-stable' } }));writeFileSync(join(pkgDir, 'package.json'), JSON.stringify({ name: 'gbrain', repository: 'github:garrytan/gbrain' }));const driver = join(pkgDir, 'driver.ts');writeFileSync(driver, `import { runUpgrade } from '${REPO}/src/commands/upgrade.ts';\nawait runUpgrade(${JSON.stringify(['--no-bun-floor-check', '--no-autopilot-install', ...args])});\n`);@@ -152,6 +152,17 @@ describe('gbrain upgrade --channel stable', () => {} finally { rmSync(r.home, { recursive: true, force: true }); }});+ test('latest channel: a global install pinned to a commit is replaced (remove, then add the newest release tag), not left on its pin by bun update', async () => {+ const r = await runStableUpgrade(['--swap-only'], { spec: 'github:garrytan/gbrain#0123456789abcdef0123456789abcdef01234567' });+ try {+ expect(r.stdout).toContain('pinned to github:garrytan/gbrain#0123456789abcdef0123456789abcdef01234567');+ expect(r.bunCalls).toEqual(['remove -g gbrain', `add -g github:garrytan/gbrain#v${NEWEST}`]);+ expect(r.bunCalls).not.toContain('update gbrain');+ expect(r.stdout).toContain(`Now running: gbrain ${NEWEST}`);+ expect(r.exitCode).toBe(0);+ } finally { rmSync(r.home, { recursive: true, force: true }); }+ });+test('no promoted release refuses with stable_channel_unresolved and changes nothing', async () => {const r = await runStableUpgrade(['--channel', 'stable'], { stableCommit: null });try {