Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
feat(upgrade): stable and alpha release channels, stable by default (GBRA-224 W1)
garrytan74515486208d
diff --git a/.github/workflows/promote-stable.yml b/.github/workflows/promote-stable.ymlindex 484b64f275..7cc55093cd 100644--- a/.github/workflows/promote-stable.yml+++ b/.github/workflows/promote-stable.yml@@ -11,10 +11,11 @@ name: Promote stable# tree; and the version is newer than the current stable (an older one only# with rollback=true and a reason). It then creates the immutable annotated# record tag stable-v<version> (first promotion only) and moves the annotated-# `stable` tag to the release commit, both carrying the same key: value body.-# Clients read refs/tags/stable^{}; the update check reads-# raw.githubusercontent.com/<repo>/stable/VERSION, mirroring latest-stable-# in release.yml.+# `stable` tag to the release commit, both carrying the same key: value body,+# and commits the evidence record stable.json (version, commit, tree, soak run,+# known_bad) to the stable-record branch, all in one atomic push. Clients read+# raw.githubusercontent.com/<repo>/stable-record/stable.json and check it+# against refs/tags/stable^{} (src/core/stable-channel.ts).## Inputs reach the script through env only, never interpolated into run:# (script injection). No dependency install runs in this job, so the@@ -46,9 +47,14 @@ on:required: falsetype: stringdefault: ''+ withdraw:+ description: Versions to add to the stable record's known_bad list, comma-separated (clients on them are offered the current stable)+ required: false+ type: string+ default: ''permissions:- contents: write # create and push the stable-v<version> and stable tags+ contents: write # create and push the stable-v<version> and stable tags and the stable-record branchactions: read # read the soak runconcurrency:@@ -77,6 +83,7 @@ jobs:PROMOTE_SCOREBOARD_URL: ${{ inputs.scoreboard_url }}PROMOTE_ROLLBACK: ${{ inputs.rollback }}PROMOTE_REASON: ${{ inputs.reason }}+ PROMOTE_WITHDRAW: ${{ inputs.withdraw }}run: |git config user.name "gbrain-release-bot"git config user.email "41898282+github-actions[bot]@users.noreply.github.com"diff --git a/CHANGELOG.md b/CHANGELOG.mdindex a196fa35b7..b89b26ff37 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -10,6 +10,28 @@ credits are retained; no result has been reassigned to another provider. Originaidentifiers and attribution are available in the pre-removal Git revision`6040075c6cb95be5881cc2e1b76ef7d71f4e5d29` (retained on 2026-09-23).+## [Unreleased]++**Updates follow a stable channel by default; every release is one setting away on alpha.**++gbrain publishes a release for nearly every merged change, more than a hundred a week. Every install followed all of them, so an always-on brain upgraded several times a week onto releases no one had run on a production-shaped brain. Installs now follow the stable channel: weekly releases a maintainer promoted after the soak passed on that release's exact tree. The alpha channel (the old `latest`, which still works as an alias) keeps every release.++### What changed++| Situation | Before | Now |+|---|---|---|+| A new or existing install with no channel set | offered every published release | offered the newest stable release; one notice on stderr says so, once per brain home |+| Following every release | the default | `gbrain config set self_upgrade.channel alpha` (or `--channel alpha`, `GBRAIN_RELEASE_CHANNEL=alpha`) |+| Which stable release is offered | `VERSION` at the `stable` tag | the published evidence record (`stable.json` on `stable-record`): version, commit, tree, soak run, withdrawn versions; a record without the evidence is never trusted |+| Stable has no usable answer | `stable_channel_unresolved` on upgrade | `stable_missing`, `stable_invalid` or `stable_unreadable`; the background check only reports it, an explicit upgrade exits non-zero, neither falls back to alpha |+| An install ahead of stable (it ran alpha) | — | offered nothing until stable passes it; never downgraded unless its version was withdrawn |+| Update cache and snooze | one file for every channel; a snooze ended when a newer release shipped | one per channel, tagged with the evidence policy; a snooze holds its whole window (24 h, 48 h, 7 days); a stable rollback below it clears it |+| `gbrain upgrade --dry-run` | refused without `--restart-only` | reports channel, its source, current and target version and the action, installing nothing |+| doctor `self_upgrade_health` | — | names the channel and its source, warns on an invalid channel or a failed stable check |+| `Promote stable` workflow | moved the `stable` tag | also commits the evidence record in the same atomic push; new `withdraw` input adds versions to `known_bad` |++Install commands still name `latest-stable`. Every install surface now goes through one constant (`src/core/install-ref.ts`), checked by `bun run check:install-ref`; it moves to `stable` after a release with this change has been promoted.+## [0.60.475.0] - 2026-10-27**A repository's own commit checks now apply to commits gbrain makes.**diff --git a/INSTALL_FOR_AGENTS.md b/INSTALL_FOR_AGENTS.mdindex d928ddc015..6ac19294af 100644--- a/INSTALL_FOR_AGENTS.md+++ b/INSTALL_FOR_AGENTS.md@@ -724,8 +724,8 @@ autopilot (`gbrain autopilot pause`), wait until no job is active, run`gbrain upgrade` on every install (it restarts every gbrain process onto thenew build and verifies one build runs, or refuses `restart_refused` naming theprocess it cannot restart), check that each process reports the new version,-then `gbrain autopilot resume`. A production brain follows the stable channel-(`gbrain config set self_upgrade.channel stable`)+then `gbrain autopilot resume`. Installs follow the stable channel by default;+`gbrain config set self_upgrade.channel alpha` follows every release([the order](skills/gbrain-upgrade/SKILL.md#always-on-hosts-pause-drain-upgrade-verify-resume),[stable channel](docs/guides/upgrades-auto-update.md#stable-channel)).diff --git a/docs/RELEASING.md b/docs/RELEASING.mdindex 22f8cd578a..8703d9add7 100644--- a/docs/RELEASING.md+++ b/docs/RELEASING.md@@ -590,8 +590,9 @@ git push origin "+refs/tags/v<VERSION>^{commit}:refs/tags/latest-stable"### Stable channel promotion-The stable channel is a slower ref than `latest-stable`: a release reaches it-only after the production-shaped soak passed on its exact git tree. A+The stable channel, the clients' default since GBRA-224, is a slower ref than+`latest-stable` (the alpha channel): a release reaches it only after the+production-shaped soak passed on its exact git tree. Amaintainer promotes with `.github/workflows/promote-stable.yml`(`scripts/promote-stable.ts`), weekly or whenever a soak passes; both gothrough the same dispatch:@@ -603,8 +604,14 @@ gh workflow run promote-stable.yml -f version=<VERSION> \- **Refs.** `refs/tags/stable` is an annotated tag on the promoted releasecommit, moved only by this workflow. Clients peel it (`refs/tags/stable^{}`)- and take the `v<VERSION>` tag on that commit; the update check reads- `https://raw.githubusercontent.com/<owner>/<repo>/stable/VERSION`.+ and take the `v<VERSION>` tag on that commit. The same push commits the+ evidence record `stable.json` to the `stable-record` branch (parented on+ the previous record): `version`, `commit`, `tree`, `soak_run`,+ `known_bad` and the tag fields. The update check reads only+ `https://raw.githubusercontent.com/<owner>/<repo>/stable-record/stable.json`;+ an upgrade also checks it against `stable^{}` and `v<VERSION>`+ (`src/core/stable-channel.ts`). A record without the evidence its+ generation requires is refused by clients (`stable_invalid`).`refs/tags/stable-v<VERSION>` is an immutable annotated record created on aversion's first promotion and never moved or deleted. Both carry the samemessage: a title line (`gbrain`, then `stable channel: v<VERSION>`), then one@@ -615,7 +622,11 @@ gh workflow run promote-stable.yml -f version=<VERSION> \- **Inputs.** `version` (an existing `v<VERSION>` release tag),`soak_run_url` (the soak's Actions run URL, optionally`/attempts/<n>`), `scoreboard_url` (optional, defaults to the run URL),- `rollback` (default false) and `reason` (required with rollback).+ `rollback` (default false), `reason` (required with rollback) and+ `withdraw` (comma-separated versions added to the record's `known_bad`+ list, carried forward on every later promotion; clients on a withdrawn+ version are offered the current stable, even when older; withdrawing the+ promoted version is refused).- **Who.** Only an actor with the admin or maintain role; anyone else isrefused.- **Soak run.** The run must belong to this repository, be completed with@@ -636,8 +647,9 @@ gh workflow run promote-stable.yml -f version=<VERSION> \no-op refusal. `rollback=true` with a `reason` moves stable to an olderrelease, or back to one promoted before (its record tag already exists andis kept; without rollback an existing record tag is refused).-- **One atomic push.** The record tag and `stable` land together or not at- all, `stable` leased on the value the run read, so a concurrent move fails+- **One atomic push.** The record tag, `stable` and the `stable-record`+ branch land together or not at all, `stable` and `stable-record` leased on+ the values the run read, so a concurrent move failsthe run instead of being overwritten and a failed push leaves nothing toclean up before the re-run. The `promote-stable` concurrency group runs one promotion at atime. The run's step summary lists the version, commit, tree, soak run,diff --git a/docs/UPGRADING_DOWNSTREAM_AGENTS.md b/docs/UPGRADING_DOWNSTREAM_AGENTS.mdindex cd52f490a3..18b2985a26 100644--- a/docs/UPGRADING_DOWNSTREAM_AGENTS.md+++ b/docs/UPGRADING_DOWNSTREAM_AGENTS.md@@ -47,20 +47,21 @@ Total time: ~10 minutes for all four skills.## Upgrading a production agent's brain: the stable channelA downstream agent whose brain is large or always on (an OpenClaw deployment, a-team brain behind `gbrain serve --http`) should not track every PATCH release.-Put that brain on the **stable channel**: the newest release a maintainer-promoted after the production-shaped soak passed on that release's exact git-tree. Promotion is weekly or manual; `git show stable` prints the promoted-version, the soak run and its scoreboard link.+team brain behind `gbrain serve --http`) should not track every PATCH release,+and by default it doesn't: installs follow the **stable channel**, the newest+release a maintainer promoted after the production-shaped soak passed on that+release's exact git tree. Promotion is weekly or manual; `git show stable`+prints the promoted version, the soak run and its scoreboard link.```bash-gbrain config set self_upgrade.channel stable # once per brain home; update checks then offer only the stable release-gbrain upgrade # installs the stable release, then restarts every gbrain process onto it+gbrain self-upgrade --check-only --json # channel, its source and the stable release offered+gbrain upgrade # installs the stable release, then restarts every gbrain process onto it```-`gbrain upgrade --channel stable` does the same for one run without changing-the config. The stable channel never downgrades: a build at or above the stable-release changes nothing.+`gbrain config set self_upgrade.channel alpha` (or `--channel alpha` for one+run) follows every release instead. The stable channel never downgrades: a+build at or above the stable release changes nothing+([channels](guides/upgrades-auto-update.md#stable-channel)).**Restarts are part of the upgrade.** `gbrain upgrade` restarts serve, autopilot,the jobs supervisor and its worker onto the new build, then verifies that everydiff --git a/docs/architecture/key-files/ci-health-and-test-guards.md b/docs/architecture/key-files/ci-health-and-test-guards.mdindex 83b4e01261..21b503ea80 100644--- a/docs/architecture/key-files/ci-health-and-test-guards.md+++ b/docs/architecture/key-files/ci-health-and-test-guards.md@@ -10,7 +10,8 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `scripts/lib/ci-run.ts` — one run's failure evidence (`collectEvidence`): jobs, failing jobs' annotations and, for test.yml and e2e.yml, the `ci-manifest` artifact, returned as structured records (job, step, every failing test file and identity) apart from sanitized excerpts; a cancelled job is not run (listed in `cancelled`) unless its annotation says it timed out, and a red run whose only failures are aggregators of cancelled jobs is `ignored`; with `complete`/`problems` (an unreadable page, annotation or manifest is incomplete evidence, never zero failures). A push run with a succeeded `reused-full-suite` job is judged by the run its `reuse.json` names (`checkRecord` from `scripts/ci-reuse.ts`, recorded attempt, identical commit tree): that run's succeeded jobs and complete `ci-manifest` stand in for the push, and any gap is incomplete. `reproduceCommand` builds `bun run test:stress <file> --iterations 10 [--postgres]` from a validated test path only. `exemptionRows` turns failing identities with an exact test name and signature into the stress gate's `<!-- gbrain-stress-exemption -->` records (backend per `stressBackend`, owner `agent on release duty`), written into master-red, flake and nightly-red bodies; `test/fixtures/nightly-watch/stress-exemption-contract.ts` vendors the gate's parser so the tests prove it accepts them.- `scripts/ci-manifest.ts` — the versioned failure and execution manifest (`gbrain-ci-manifest/v1`). The `executed-receipts` job of test.yml and e2e.yml builds it from every lane's receipts (via `scripts/ci-executed-counts.ts`, declared skips from the expected-deltas TSV), binds it to the workflow, event, SHA, run id and attempt, and uploads it as `ci-manifest`; each failure carries the JUnit message (credentials redacted) and the stress gate's `failureSignature` (omitted when the message holds a credential); `checkManifest` refuses a manifest for another run or attempt; `passedFiles` lists files that executed tests and failed none. Docs: `docs/ci-red-runbook.md#ci-failure-manifest`.- `scripts/release-gate.ts` — release.yml's `ci-gate` job. Polls the push-to-master runs of Test and E2E Tests on the release commit and writes `publish`/`sha`: both green publishes; a failed run publishes nothing and fails with the next step; a run cancelled by a newer push is followed to the next master commit with the same VERSION (published there) or marks the version superseded; non-master refs are refused; it fails with the backfill command after 110 minutes. Build, release, `latest-stable` and the publish jobs use the gated commit. Tests: `test/scripts/release-gate.test.ts`. Docs: `docs/RELEASING.md#release-ci-gate`.-- `.github/workflows/promote-stable.yml` + `scripts/promote-stable.ts` — maintainer-only stable channel promotion (`workflow_dispatch`: `version`, `soak_run_url`, `scoreboard_url`, `rollback`, `reason`; concurrency group `promote-stable`). `promote()` refuses unless the actor's `role_name` is admin or maintain, `v<VERSION>` exists with a `VERSION` file naming it and a published (non-draft) GitHub release, the soak run URL names a completed, successful run of this repository's `STABLE_SOAK_WORKFLOW` workflow (repository variable; bare file name or path), the run's head commit has the release tag's exact tree (fetched when missing), and the version is newer than the current stable (the highest `v*` tag on `refs/tags/stable^{commit}`), or older with `rollback` and a reason; re-promoting the current stable refuses. It creates the immutable annotated `stable-v<VERSION>` record (refused when it exists, except on a rollback re-promotion of the same commit) and moves the annotated `stable` tag, both with `renderTagMessage()`'s `key: value` body, then pushes both in one `--atomic` push (`stable` leased on the tag object it read, so a failed push changes nothing) and writes the step summary. Side effects come in through `PromoteDeps`. Tests: `test/scripts/promote-stable.test.ts`. Docs: `docs/RELEASING.md#stable-channel-promotion`.+- `.github/workflows/promote-stable.yml` + `scripts/promote-stable.ts` — maintainer-only stable channel promotion (`workflow_dispatch`: `version`, `soak_run_url`, `scoreboard_url`, `rollback`, `reason`, `withdraw`; concurrency group `promote-stable`). `promote()` refuses unless the actor's `role_name` is admin or maintain, `v<VERSION>` exists with a `VERSION` file naming it and a published (non-draft) GitHub release, the soak run URL names a completed, successful run of this repository's `STABLE_SOAK_WORKFLOW` workflow (repository variable; bare file name or path), the run's head commit has the release tag's exact tree (fetched when missing), and the version is newer than the current stable (the highest `v*` tag on `refs/tags/stable^{commit}`), or older with `rollback` and a reason; re-promoting the current stable refuses. It creates the immutable annotated `stable-v<VERSION>` record (refused when it exists, except on a rollback re-promotion of the same commit) and moves the annotated `stable` tag, both with `renderTagMessage()`'s `key: value` body, commits the evidence record (`renderRecord()`, `stable.json`, `known_bad` carried forward and merged with `withdraw` by `mergeKnownBad()`) on the `stable-record` branch, then pushes all three in one `--atomic` push (`stable` and `stable-record` leased on the values it read, so a failed push changes nothing) and writes the step summary. Side effects come in through `PromoteDeps`. Tests: `test/scripts/promote-stable.test.ts`. Docs: `docs/RELEASING.md#stable-channel-promotion`.+- `scripts/check-install-ref.ts` (`bun run check:install-ref`, in verify) — every install pin, bootstrap runbook fetch and setup-helper fetch in tracked files (not CHANGELOG.md or test/) names `INSTALL_REF` from `src/core/install-ref.ts`; exact `v<version>` and commit pins are left alone; TypeScript must import the constant; `--write` rewrites the text surfaces. `scripts/check-bootstrap-tag.sh` reads its sanctioned ref from the same constant. Tests: `test/install-ref.test.ts`.- `scripts/regen-all.ts` — one entry point for every generated artifact (`ARTIFACTS`: regen and check command per artifact). `bun run regen:all` regenerates offline and keyless (provider keys and database URLs removed) and lists what changed; a second run changes nothing. `--check` is read-only and runs in `verify` as `check:regen-all`; `--goldens` also regenerates the offline contract goldens. Postgres goldens are named with their own commands, and `llms.txt` regenerates last because it inlines other generated docs. Every `bun test` it spawns (two checks and the goldens) carries `--timeout=60000` through one `BUN_TEST` prefix, because Bun does not apply bunfig.toml's `[test] timeout`. Tests: `test/scripts/regen-all.test.ts`.- `scripts/release-restamp.ts` + `scripts/lib/restamp.ts` — `bun run release:restamp`, run when a PR is next to merge. The CLI refuses a dirty tree, fetches `origin/master`, captures the branch CHANGELOG entry and migration inventory, merges master with a merge commit (version-only stamp hunks, `CHANGELOG.md` and the `GENERATED_PATHS` files resolve mechanically; anything else stops), sets VERSION to master's PATCH + 1, renumbers branch-only migrations from master's latest + 1 (filename, export name and `version:` literal only; `migrationPayloadKey` proves the rest is token-identical and refuses a copy of a published migration or an edited published one), rewrites `STAMPS` (the CLAUDE.md "Version locations" Required rows) plus CHANGELOG and TODOS, runs `DEFAULT_STEPS`, lists branch-added lines that still name an old number (`findLeftoverRefs`, never rewritten), runs `DEFAULT_CHECKS` and commits once. Stops save `.git/gbrain-restamp.json` for `--continue` / `--abort`; `--dry-run` prints the plan, `--no-commit` stages. Generators run through `offlineEnv` (no database URLs, no provider keys). Tests: `test/scripts/release-restamp.test.ts` (fixture repos with the real migration generator; also pins CLAUDE.md table coverage and docs anchors).- `scripts/ci-convergence-scope.sh` — #6712 PR 0: classifies a pull request's changed files (stdin) for the managed-sync convergence gate (`persistence-validation.yml` `convergence`): `run` for persistence, sync commands and sync core, page projections and storage, `bun.lock` and `vendor/postgres/`, the harness (`test/sync-convergence.serial.test.ts`, `test/fixtures/convergence-fault-kill.ts`), this script and its workflows (`persistence-validation.yml`, `convergence-nightly.yml`); `skip` otherwise, and never selected by `package.json` alone, so a release-stamp PR does not run it; an empty list runs. test.yml `changes` calls it for pull requests only (step `convergence`, passed as the `convergence` input). Tests: `test/scripts/ci-pr-scope.test.ts`.diff --git a/docs/architecture/key-files/commands-6.md b/docs/architecture/key-files/commands-6.mdindex e4d832f10c..fb1d07ffe3 100644--- a/docs/architecture/key-files/commands-6.md+++ b/docs/architecture/key-files/commands-6.md@@ -13,6 +13,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 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).+- 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`). 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, 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/error-codes.md b/docs/guides/error-codes.mdindex 6eafb98264..f1cac760de 100644--- a/docs/guides/error-codes.md+++ b/docs/guides/error-codes.md@@ -4111,11 +4111,41 @@ More: [docs/guides/write-refusals.md#slug_page_mismatch](../../docs/guides/write| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable ||---|---|---|---|---|---|---|-| `gbrain upgrade --channel stable` (or `self_upgrade.channel stable`) could not name the stable release: the repository's tags could not be read, no release has been promoted to stable yet, or the `stable` tag does not share a commit with a `v<version>` release tag. Nothing was changed. | The stable channel installs only a release a maintainer promoted after the production-shaped soak passed on its exact tree; without that answer it installs nothing rather than guess. | Retry later, or upgrade on the latest channel with `gbrain upgrade --channel latest`. | agent | `gbrain doctor --json` | 1 | no |+| Retired: an older gbrain could not name the stable release from the repository's tags alone. This build resolves stable from the published evidence record and reports stable_missing, stable_invalid or stable_unreadable instead. | Since GBRA-224 the stable channel is the default and accepts only a release whose evidence record proves its gates passed on that exact tree; a message with this code came from an older build. | Rerun gbrain self-upgrade --check-only --json on this build; it names the current stable code and its fix. Run: gbrain self-upgrade --check-only --json | agent | `gbrain doctor --json` | 1 | no |Reasons: `unreadable`, `no_stable`, `no_release_tag`.-More: [docs/guides/upgrades-auto-update.md#stable-channel](../../docs/guides/upgrades-auto-update.md#stable-channel)+More: [docs/guides/upgrades-auto-update.md#stable-channel-errors](../../docs/guides/upgrades-auto-update.md#stable-channel-errors)++### stable_invalid++<a id="stable_invalid"></a>++| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable |+|---|---|---|---|---|---|---|+| The stable channel has no usable release: the published evidence record is missing, malformed, lacks an evidence key its generation needs (soak_run; matrix_run from the matrix cutover on), or names a version whose release tag is not the stable commit. Nothing was installed. | A stable install accepts only a release whose record proves its gates passed on that exact tree; a record that does not prove it is never trusted, and the client never falls back to alpha by itself. | Wait for a maintainer to repair or re-promote stable, or follow every release on alpha: gbrain config set self_upgrade.channel alpha (or the --channel / GBRAIN_RELEASE_CHANNEL override named in the message). | agent | `gbrain doctor --json` | 1 | no |++More: [docs/guides/upgrades-auto-update.md#stable-channel-errors](../../docs/guides/upgrades-auto-update.md#stable-channel-errors)++### stable_missing++<a id="stable_missing"></a>++| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable |+|---|---|---|---|---|---|---|+| No release has been promoted to the stable channel yet (no stable tag or no published evidence record), so the stable channel has nothing to install. Nothing was installed. | Stable installs only promoted releases; an empty channel installs nothing rather than guess, and the background update check only reports it. | Wait for the first stable promotion, or follow every release on alpha: gbrain config set self_upgrade.channel alpha (or the --channel / GBRAIN_RELEASE_CHANNEL override named in the message). | agent | `gbrain doctor --json` | 1 | no |++More: [docs/guides/upgrades-auto-update.md#stable-channel-errors](../../docs/guides/upgrades-auto-update.md#stable-channel-errors)++### stable_unreadable++<a id="stable_unreadable"></a>++| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable |+|---|---|---|---|---|---|---|+| The stable channel could not be read: the evidence record or the repository's tags did not answer, or the stable tag and the record disagree while a promotion propagates. Nothing was installed. | Without a verified answer the client installs nothing and keeps any earlier verified answer for the notice only; the channel is unchanged. | Retry in a few minutes: gbrain self-upgrade --check-only. Check network access to github.com and raw.githubusercontent.com if it repeats. | agent | `repeat the read that failed` | 1 | yes |++More: [docs/guides/upgrades-auto-update.md#stable-channel-errors](../../docs/guides/upgrades-auto-update.md#stable-channel-errors)### stale_unavailablediff --git a/docs/guides/troubleshooting.md b/docs/guides/troubleshooting.mdindex 37aac2e35a..b2e44dda37 100644--- a/docs/guides/troubleshooting.md+++ b/docs/guides/troubleshooting.md@@ -12,6 +12,7 @@| Symptom | Next step | Who acts | Consent | Verify ||---|---|---|---|---|+| `gbrain upgrade` or `gbrain self-upgrade` exits with `stable_missing`, `stable_invalid` or `stable_unreadable`, or doctor `self_upgrade_health` warns with one | follow the code's fix ([stable channel errors](upgrades-auto-update.md#stable-channel-errors)): retry `stable_unreadable`; for the other two wait for a stable promotion, or follow every release with `gbrain config set self_upgrade.channel alpha`. The background check never falls back to alpha by itself | agent; switching channel: agent, after the user agrees | none | `gbrain self-upgrade --check-only --json` has no `error` field || A withdrawal committed but a large page's file still shows the withdrawn row; writer status lists its mirror parked with [`segmented_mirror_writer_gate`](write-refusals.md#segmented_mirror_writer_gate), or an effect retrying with [`recovery_version_unsupported`](write-refusals.md#recovery_version_unsupported) (or `effect_unavailable` on v0.60.290.0) holds every write on the worktree | `gbrain upgrade` on the hosts the refusal or a doctor `segmented_storage` warning names (for `recovery_version_unsupported`, the owner host; doctor's information case, this host's own superseded pre-upgrade writes, does not hold the mirror), then restart their serve, sync and worker processes. A gated mirror resumes by itself once the older writes are 7 days old; never delete a recovery record or its staging file | brain host | none | `gbrain sources writer status --source <source> --json` shows no parked or retrying mirror || The dream cycle's purge phase fails every night with `managed_purge_failed` (`42P01`, relation `query_cache` does not exist), or doctor `schema_missing_tables` warns | upgrade (#6911: the purge skips a missing rebuildable cache), then preview recreating it: `gbrain repair missing-tables` ([missing tables](repair.md#missing-tables)); apply the printed `--apply --expect <hash>` command. Pages parked by the earlier failures: `gbrain pages purge-deleted --retry-parked --dry-run`, then without `--dry-run` | agent, after the user agrees | `destructive` (the parked-page retry purges them) | `gbrain doctor --only schema_missing_tables --json` reports ok || A managed source's autopilot freshness `sync` jobs each land about one page, or `sources status` says `parked` while a sync job runs | upgrade (#6706: sync jobs drain to their deadline and count as the source's live drain), then restart `gbrain jobs work` / the supervisor so the worker loads the handler; a job result with `incomplete: true` names its follow-up (`continuation_job_id`) or the next step in `next` | agent | none | `gbrain sync status --source <id> --json` shows `live_job_id` or a cursor at `done`; `gbrain jobs get <id> --json` shows `outcome` |diff --git a/docs/guides/upgrades-auto-update.md b/docs/guides/upgrades-auto-update.mdindex 409d6dfe8e..8489c80cea 100644--- a/docs/guides/upgrades-auto-update.md+++ b/docs/guides/upgrades-auto-update.md@@ -128,42 +128,80 @@ them in order and stop if the tag check fails.<a id="release-channel"></a>### Which version counts as available-Every update surface (the startup marker, `gbrain check-update`,-`gbrain self-upgrade`, doctor's `self_upgrade_health` and the `auto` channel)-reads the `VERSION` file at the `latest-stable` tag: the release the canonical-install (`github:garrytan/gbrain#latest-stable`) gets from `bun update`, moved-only after the release checks pass and the assets publish. Master's `VERSION`-is never offered: the next PR stamps it before release.yml tags it, and a-superseded version never gets a tag (#6718, #6828).-<a id="stable-channel"></a>-**The stable channel.** A large or production brain can follow a slower line:-the newest release a maintainer promoted after the production-shaped soak-passed on that release's exact git tree. Promotion is weekly or manual, through-the maintainer-only `Promote stable` workflow-([RELEASING.md](../RELEASING.md#stable-channel-promotion)), which moves the-`stable` tag to the release commit and records the soak scoreboard link in the-tag message (`git show stable`).+gbrain has two release channels, and every update surface (the startup+marker, `gbrain check-update`, `gbrain self-upgrade`, `gbrain upgrade`,+doctor's `self_upgrade_health` and the `auto` mode) follows the one in+effect:++| Channel | What it offers | Read from |+|---------|----------------|-----------|+| `stable` (default) | Weekly releases a maintainer promoted after testing on that release's exact git tree. | The evidence record `stable.json` on the `stable-record` branch, checked against the `stable` tag. |+| `alpha` | Every published release. | `VERSION` at the `latest-stable` tag, which release.yml moves on every publish. |++`latest` is accepted everywhere as an alias for `alpha`. The channel comes+from the first of these that is set: `--channel` on the command, the+`GBRAIN_RELEASE_CHANNEL` environment variable, `self_upgrade.channel` in the+brain home's config, then the default. An invalid value at the first one set+is an error (`invalid_params`), never a fall-through to the next. Channel state+lives under `GBRAIN_HOME`, so a repo-less brain and a repo brain behave the+same. `gbrain doctor` prints `channel=<channel> (<source>)`.```bash-gbrain upgrade --channel stable # one run on the stable channel-gbrain config set self_upgrade.channel stable # make stable the default for this brain home-gbrain config set self_upgrade.channel latest # back to every published release+gbrain config set self_upgrade.channel alpha # follow every release on this brain home+gbrain config set self_upgrade.channel stable # back to the default+gbrain upgrade --channel alpha # one run on alpha, config unchanged+gbrain upgrade --dry-run --json # what an upgrade would install, installing nothing```-With `self_upgrade.channel stable`, every update surface above reads `VERSION`-at the `stable` tag instead of `latest-stable`, so the marker, `check-update`,-`self-upgrade` and the `auto` channel only ever offer the stable release.-`gbrain upgrade` resolves it from `git ls-remote` (the `v<version>` tag on the-commit `stable` peels to) and installs exactly that release: a bun install is+An install with no channel set prints one notice, once per `GBRAIN_HOME`, on stderr (never under `--json`, `serve` or+`mcp`): `[gbrain notice release_channel] This install now follows the stable+channel ...`. It is not an `UPGRADE_AVAILABLE` marker. Setting any channel+silences it.++**The evidence record.** `Promote stable`+([RELEASING.md](../RELEASING.md#stable-channel-promotion)) moves the `stable`+tag and commits `stable.json` to the `stable-record` branch in one atomic+push. The record names the version, commit, tree, the soak run that passed on+that tree and a `known_bad` list of withdrawn releases. The update check reads+only that file (no API call, no git), so a missing record or a record without+the evidence its generation requires is never trusted. Generation 1 records+carry the soak run; from the matrix cutover on, `matrix_run` is required too.+`gbrain upgrade` also checks that `stable` and `v<version>` peel to the+record's commit, then installs exactly that release: a bun install isreinstalled pinned to `#v<version>` (remove, then add; it restores theprevious release if the add fails), a bun-link clone fast-forwards to the-release commit (never backward or across a fork), and the binary install-downloads that release's asset. A build already at or above the stable release-changes nothing: the stable channel never downgrades. A ClawHub install follows-ClawHub's own line and is refused with the reinstall command. When no release-has been promoted yet, or the remote cannot be read, the upgrade stops with-`stable_channel_unresolved` and changes nothing.+release commit, and the binary install downloads that release's asset.++**Never downgrade.** A build at or above the stable release is offered+nothing, 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 update cache and snooze are per channel.** Each channel keeps its own+answer (`update-check.<channel>.json`, which also records the evidence policy)+and its own snooze (`update-snoozed.<channel>.json`). Switching channel reads+that channel's answer; a cached answer from another policy, or the+unpartitioned cache of older builds, is never read. A snooze holds for its+whole window (24 h, then 48 h, then 7 days) however many releases ship+meanwhile; a stable rollback below the snoozed version clears it.++<a id="stable-channel-errors"></a>+**When stable has no usable answer.** The background check only records and+reports these; it never offers alpha instead. An explicit `gbrain upgrade` or+`gbrain self-upgrade` on stable exits non-zero with the code and installs+nothing.++| Code | Meaning | What to do |+|------|---------|------------|+| `stable_missing` | No release has been promoted yet (no record or no `stable` tag). | Wait for the first promotion, or `gbrain config set self_upgrade.channel alpha`. |+| `stable_invalid` | The record is malformed, lacks a required evidence key, lists its own version as known bad, or its version's tag is not the stable commit. | Wait for a maintainer to repair or re-promote stable, or switch to alpha. |+| `stable_unreadable` | The record or the tags did not answer (network, or a promotion still propagating). | Retry: `gbrain self-upgrade --check-only --json`. The last verified answer still shows in the notice, never as an install target. |++When the channel came from `--channel` or `GBRAIN_RELEASE_CHANNEL`, the fix+names that override instead of the config command. Builds before this release+reported `stable_channel_unresolved` (retired).A swap is a swap only when the version changed. When `gbrain upgrade` findsthe same version running after the install step (`bun update` on a tag whosediff --git a/docs/mcp/HERMES.md b/docs/mcp/HERMES.mdindex 635deea025..66dea73b6c 100644--- a/docs/mcp/HERMES.md+++ b/docs/mcp/HERMES.md@@ -6,7 +6,11 @@> this page wires the finished brain into Hermes over stdio MCP.Hermes spawns `gbrain serve` as a local stdio subprocess. No server, no tunnel,-no token needed. Works with both PGLite and Supabase engines.+no token needed. Works with both PGLite and Supabase engines. Updates follow the+stable channel by default: weekly releases promoted after testing+([channels](../guides/upgrades-auto-update.md#stable-channel)). If no machine of+yours stays online, hosted GBrain at [gbrain.io](https://gbrain.io/?ref=hermes-md)+is the always-on option ([hosted harness access](../guides/hosted-harness-access.md)).## Register (recommended)diff --git a/llms-full.txt b/llms-full.txtindex 8bb509c82f..0ab7c9d6e6 100644--- a/llms-full.txt+++ b/llms-full.txt@@ -3389,8 +3389,8 @@ autopilot (`gbrain autopilot pause`), wait until no job is active, run`gbrain upgrade` on every install (it restarts every gbrain process onto thenew build and verifies one build runs, or refuses `restart_refused` naming theprocess it cannot restart), check that each process reports the new version,-then `gbrain autopilot resume`. A production brain follows the stable channel-(`gbrain config set self_upgrade.channel stable`)+then `gbrain autopilot resume`. Installs follow the stable channel by default;+`gbrain config set self_upgrade.channel alpha` follows every release([the order](skills/gbrain-upgrade/SKILL.md#always-on-hosts-pause-drain-upgrade-verify-resume),[stable channel](docs/guides/upgrades-auto-update.md#stable-channel)).@@ -10221,6 +10221,7 @@ Source: https://raw.githubusercontent.com/garrytan/gbrain/master/docs/guides/tro| Symptom | Next step | Who acts | Consent | Verify ||---|---|---|---|---|+| `gbrain upgrade` or `gbrain self-upgrade` exits with `stable_missing`, `stable_invalid` or `stable_unreadable`, or doctor `self_upgrade_health` warns with one | follow the code's fix ([stable channel errors](upgrades-auto-update.md#stable-channel-errors)): retry `stable_unreadable`; for the other two wait for a stable promotion, or follow every release with `gbrain config set self_upgrade.channel alpha`. The background check never falls back to alpha by itself | agent; switching channel: agent, after the user agrees | none | `gbrain self-upgrade --check-only --json` has no `error` field || A withdrawal committed but a large page's file still shows the withdrawn row; writer status lists its mirror parked with [`segmented_mirror_writer_gate`](write-refusals.md#segmented_mirror_writer_gate), or an effect retrying with [`recovery_version_unsupported`](write-refusals.md#recovery_version_unsupported) (or `effect_unavailable` on v0.60.290.0) holds every write on the worktree | `gbrain upgrade` on the hosts the refusal or a doctor `segmented_storage` warning names (for `recovery_version_unsupported`, the owner host; doctor's information case, this host's own superseded pre-upgrade writes, does not hold the mirror), then restart their serve, sync and worker processes. A gated mirror resumes by itself once the older writes are 7 days old; never delete a recovery record or its staging file | brain host | none | `gbrain sources writer status --source <source> --json` shows no parked or retrying mirror || The dream cycle's purge phase fails every night with `managed_purge_failed` (`42P01`, relation `query_cache` does not exist), or doctor `schema_missing_tables` warns | upgrade (#6911: the purge skips a missing rebuildable cache), then preview recreating it: `gbrain repair missing-tables` ([missing tables](repair.md#missing-tables)); apply the printed `--apply --expect <hash>` command. Pages parked by the earlier failures: `gbrain pages purge-deleted --retry-parked --dry-run`, then without `--dry-run` | agent, after the user agrees | `destructive` (the parked-page retry purges them) | `gbrain doctor --only schema_missing_tables --json` reports ok || A managed source's autopilot freshness `sync` jobs each land about one page, or `sources status` says `parked` while a sync job runs | upgrade (#6706: sync jobs drain to their deadline and count as the source's live drain), then restart `gbrain jobs work` / the supervisor so the worker loads the handler; a job result with `incomplete: true` names its follow-up (`continuation_job_id`) or the next step in `next` | agent | none | `gbrain sync status --source <id> --json` shows `live_job_id` or a cursor at `done`; `gbrain jobs get <id> --json` shows `outcome` |diff --git a/package.json b/package.jsonindex 7b838ae233..3379e9ff11 100644--- a/package.json+++ b/package.json@@ -114,6 +114,7 @@"check:batch-audit-site": "bash scripts/check-batch-audit-site.sh","check:worker-lock-renewal-shape": "bash scripts/check-worker-lock-renewal-shape.sh","check:bootstrap-tag": "bash scripts/check-bootstrap-tag.sh",+ "check:install-ref": "bun scripts/check-install-ref.ts","check:bootstrap-templates": "bash scripts/check-bootstrap-templates.sh","check:source-id-projection": "bash scripts/check-source-id-projection.sh","check:privacy": "bash scripts/check-privacy.sh",diff --git a/plugin/skills/gbrain-upgrade/SKILL.md b/plugin/skills/gbrain-upgrade/SKILL.mdindex af5b634fa3..dea7d1f820 100644--- a/plugin/skills/gbrain-upgrade/SKILL.md+++ b/plugin/skills/gbrain-upgrade/SKILL.md@@ -114,7 +114,8 @@ If `changelog_diff` is empty (network blip / no notes), ask without the bulletsrather than blocking — the version numbers alone are enough to decide.- **Yes** → `gbrain self-upgrade`-- **Always** → `gbrain config set self_upgrade.mode auto` then `gbrain self-upgrade`+- **Always** → `gbrain config set self_upgrade.mode auto` then `gbrain self-upgrade`;+ tell the user it applies stable releases (alpha only if they set `self_upgrade.channel alpha`)- **Not now** → do nothing; the snooze escalates (24h → 48h → 7d) and the markerstops nagging for this version until it expires or a newer version ships.- **Never** → `gbrain config set self_upgrade.mode off`@@ -123,9 +124,8 @@ rather than blocking — the version numbers alone are enough to decide.A host that runs autopilot, a jobs worker or a serve must end the upgrade withevery process on the new build, and a job that starts mid-swap can run half on-each. A large or production brain follows the stable channel-(`gbrain config set self_upgrade.channel stable`, or `gbrain upgrade --channel stable`-once), which offers only releases that passed the production-shaped soak.+each. Installs follow the stable channel by default, which offers only releases+that passed the production-shaped soak (`self_upgrade.channel alpha` follows every release).With the operator's go-ahead, upgrade in this order:1. `gbrain autopilot pause --reason "upgrade"` so no new cycle starts.diff --git a/scripts/check-bootstrap-tag.sh b/scripts/check-bootstrap-tag.shindex 24e521609f..646cd0da8a 100755--- a/scripts/check-bootstrap-tag.sh+++ b/scripts/check-bootstrap-tag.sh@@ -38,7 +38,8 @@set -uo pipefailROOT="${GBRAIN_BOOTSTRAP_GUARD_ROOT:-$(cd "$(dirname "$0")/.." && pwd)}"-SANCTIONED='latest-stable'+SANCTIONED=$(sed -n "s/^export const INSTALL_REF = '\(.*\)';$/\1/p" "$(cd "$(dirname "$0")/.." && pwd)/src/core/install-ref.ts")+[ -n "$SANCTIONED" ] || { echo 'FAIL: could not read INSTALL_REF from src/core/install-ref.ts' >&2; exit 1; }# URL terminators: whitespace, ), <, >, ", ', backtick. Built by concatenation# so the single quote and backtick stay literal.@@ -117,10 +118,10 @@ fiwhile IFS=: read -r file line match; doref="${match##*@}"case "$ref" in- latest-stable|codex-plugin) ;;+ "$SANCTIONED"|codex-plugin) ;;*)fail=1- echo "FAIL: $file:$line pins 'marketplace add garrytan/gbrain@$ref' — use @latest-stable or @codex-plugin." >&2+ echo "FAIL: $file:$line pins 'marketplace add garrytan/gbrain@$ref' — use @$SANCTIONED or @codex-plugin." >&2;;esacdone < <(grep -RInE 'plugin marketplace add garrytan/gbrain@[A-Za-z0-9._-]+' \diff --git a/scripts/check-install-ref.ts b/scripts/check-install-ref.tsnew file mode 100644index 0000000000..af7e50b61e--- /dev/null+++ b/scripts/check-install-ref.ts@@ -0,0 +1,91 @@+#!/usr/bin/env bun+/**+ * Install-ref lint (GBRA-224): every install surface names INSTALL_REF (src/core/install-ref.ts).+ *+ * Checked in every tracked file except CHANGELOG.md and test/:+ * - `github:garrytan/gbrain#<ref>` install pins with a named ref (a `v<version>`, a commit or a template is an exact pin,+ * not a channel ref, and is left alone) must name INSTALL_REF; `#master` is never an install ref;+ * - raw fetches of the install artifacts (BOOTSTRAP_FOR_AGENTS.md, scripts/setup-in-agent.sh) must use INSTALL_REF;+ * - the setup helper's `gbrain_install_ref=` must equal INSTALL_REF;+ * - TypeScript sources never spell the ref: they import INSTALL_PIN / INSTALL_RAW_BASE.+ *+ * `--write` rewrites the text surfaces to INSTALL_REF (the flip after a stable promotion); TypeScript violations are+ * listed, never rewritten. Exit 1 on drift.+ */+import { readFileSync, writeFileSync } from 'node:fs';+import { join } from 'node:path';+import { spawnSync } from 'node:child_process';+import { INSTALL_REF } from '../src/core/install-ref.ts';++export interface InstallRefDrift { file: string; line: number; found: string; why: string }++const PIN = /github:garrytan\/gbrain#([A-Za-z][A-Za-z0-9._-]*)/g;+const ARTIFACT = /raw\.githubusercontent\.com\/garrytan\/gbrain\/([A-Za-z0-9._-]+)\/(BOOTSTRAP_FOR_AGENTS\.md|scripts\/setup-in-agent\.sh)/g;+const HELPER_REF = /^gbrain_install_ref=([A-Za-z0-9._-]+)$/gm;+const EXACT_PIN = /^v|^[0-9]/;+const OWNER = 'src/core/install-ref.ts';++const skipped = (file: string) => file === 'CHANGELOG.md' || file.startsWith('test/') || file === OWNER;++/** Drift in one file's text; `ref` is the sanctioned install ref. */+export function driftIn(file: string, text: string, ref: string = INSTALL_REF): InstallRefDrift[] {+ if (skipped(file)) return [];+ const out: InstallRefDrift[] = [];+ const at = (index: number) => text.slice(0, index).split('\n').length;+ const ts = file.endsWith('.ts');+ for (const m of text.matchAll(PIN)) {+ if (EXACT_PIN.test(m[1]!)) continue;+ if (ts) out.push({ file, line: at(m.index!), found: m[0], why: `TypeScript names install refs through INSTALL_PIN (${OWNER})` });+ else if (m[1] !== ref) out.push({ file, line: at(m.index!), found: m[0], why: `install pins name ${ref}` });+ }+ for (const m of text.matchAll(ARTIFACT)) {+ if (/^[0-9a-f]{40}$/.test(m[1]!)) continue;+ if (ts) out.push({ file, line: at(m.index!), found: m[0], why: `TypeScript fetches install artifacts through INSTALL_RAW_BASE (${OWNER})` });+ else if (m[1] !== ref) out.push({ file, line: at(m.index!), found: m[0], why: `install artifacts are fetched from ${ref}` });+ }+ for (const m of text.matchAll(HELPER_REF)) {+ if (m[1] !== ref) out.push({ file, line: at(m.index!), found: m[0], why: `the setup helper resolves ${ref}` });+ }+ return out;+}++/** The text surface rewritten to `ref` (TypeScript is left for a human). */+export function rewriteText(file: string, text: string, ref: string = INSTALL_REF): string {+ if (skipped(file) || file.endsWith('.ts')) return text;+ return text+ .replace(PIN, (all, r: string) => (EXACT_PIN.test(r) ? all : `github:garrytan/gbrain#${ref}`))+ .replace(ARTIFACT, (all, r: string, path: string) => (/^[0-9a-f]{40}$/.test(r) ? all : `raw.githubusercontent.com/garrytan/gbrain/${ref}/${path}`))+ .replace(HELPER_REF, `gbrain_install_ref=${ref}`);+}++function trackedFiles(root: string): string[] {+ const r = spawnSync('git', ['ls-files', '-z'], { cwd: root, encoding: 'utf8' });+ if (r.status !== 0) throw new Error(`git ls-files failed: ${r.stderr}`);+ return r.stdout.split('\0').filter(f => f && /\.(md|txt|ts|sh|json|yml|yaml)$|gbrain-launcher$/.test(f));+}++export function findInstallRefDrift(root: string, write = false): InstallRefDrift[] {+ const drift: InstallRefDrift[] = [];+ for (const file of trackedFiles(root)) {+ let text: string;+ try { text = readFileSync(join(root, file), 'utf8'); } catch { continue; }+ if (write) {+ const next = rewriteText(file, text);+ if (next !== text) writeFileSync(join(root, file), next);+ text = next;+ }+ drift.push(...driftIn(file, text));+ }+ return drift;+}++if (import.meta.main) {+ const root = join(import.meta.dir, '..');+ const drift = findInstallRefDrift(root, process.argv.includes('--write'));+ for (const d of drift) console.error(`FAIL: ${d.file}:${d.line} ${d.found} (${d.why})`);+ if (drift.length) {+ console.error(`check-install-ref: ${drift.length} install surface(s) off ${INSTALL_REF}; run bun run check:install-ref --write for text surfaces.`);+ process.exit(1);+ }+ console.log(`check-install-ref: ok (every install surface names ${INSTALL_REF})`);+}diff --git a/scripts/generate-plugin-tree.ts b/scripts/generate-plugin-tree.tsindex e6ce6dc446..6351f72f4a 100644--- a/scripts/generate-plugin-tree.ts+++ b/scripts/generate-plugin-tree.ts@@ -48,6 +48,7 @@ import { FAILSAFE_SCHEMA, load } from 'js-yaml';// Personas: the SINGLE validation implementation (the harness-bridge CLI// imports the same module), so CLI errors and CI errors match by construction.import { loadPersonas, type PersonaDef } from '../src/core/skillpack/personas.ts';+import { INSTALL_PIN } from '../src/core/install-ref.ts';// GBRAIN_PLUGIN_TREE_ROOT is the negative-fixture test seam: the manifest// test points the generator at a synthetic repo root to prove each curation@@ -315,7 +316,7 @@ with \`GBRAIN_SURFACE=full\` (the server honors it; new sessions pick it up).`}## Requirements-- gbrain CLI installed: \`bun install -g github:garrytan/gbrain#latest-stable\`+- gbrain CLI installed: \`bun install -g ${INSTALL_PIN}\`(the npm package named \`gbrain\` is unrelated — never \`npm install -g gbrain\`).- A brain: \`gbrain init\` (the bundled \`setup\` skill walks the full path).`,diff --git a/scripts/promote-stable.ts b/scripts/promote-stable.tsindex c9161efefd..6e2169725a 100644--- a/scripts/promote-stable.ts+++ b/scripts/promote-stable.ts@@ -21,13 +21,21 @@* rollback with a reason; re-promoting the current stable is a no-op;* 6. the annotated record tag `stable-v<VERSION>` is created (once per* version, never moved) and the annotated `stable` tag is moved to the- * release commit, both carrying renderTagMessage(). One atomic push moves- * both, `stable` leased on the value read in step 5, so a failed push- * leaves the remote unchanged and a re-run starts clean.+ * release commit, both carrying renderTagMessage();+ * 7. the evidence record (renderRecord(): version, commit, tree, soak run,+ * and the `known_bad` list, carried forward from the previous record plus+ * this run's `withdraw` versions) is committed as `stable.json` on the+ * `stable-record` branch, parented on the previous record commit. One+ * atomic push moves all three, `stable` and `stable-record` leased on+ * the values read, so a failed push leaves the remote unchanged and a+ * re-run starts clean.*- * Clients peel `refs/tags/stable^{}`; the update check reads- * https://raw.githubusercontent.com/garrytan/gbrain/stable/VERSION, the same- * pattern as `latest-stable` (src/commands/check-update.ts RELEASE_REF_RAW).+ * Clients read the record at+ * https://raw.githubusercontent.com/garrytan/gbrain/stable-record/stable.json+ * (src/core/stable-channel.ts: no API call, no git) and an explicit upgrade+ * checks it against `refs/tags/stable^{}` and `v<VERSION>`. Generation 1+ * records carry soak evidence only; the upgrade matrix (W2) adds matrix_run+ * and sets MATRIX_REQUIRED_FROM in src/core/self-upgrade.ts.* Side effects (gh, git, clock, log, step summary) come in through* PromoteDeps, so the decisions are tested without network or a real remote* (test/scripts/promote-stable.test.ts). Every refusal exits 1 with one@@ -38,6 +46,9 @@ import { appendFileSync } from 'node:fs';export const DOCS = 'docs/RELEASING.md#stable-channel-promotion';export const STABLE_REF = 'refs/tags/stable';+export const RECORD_BRANCH_REF = 'refs/heads/stable-record';+export const RECORD_REMOTE_REF = 'refs/remotes/origin/stable-record';+export const RECORD_FILE = 'stable.json';const VERSION_RE = /^\d+\.\d+\.\d+(\.\d+)?$/;const SHA_RE = /^[0-9a-f]{40}$/;const PROMOTER_ROLES = new Set(['admin', 'maintain']);@@ -51,6 +62,8 @@ export interface PromoteInputs {scoreboardUrl: string;rollback: boolean;reason: string;+ /** Versions to add to the record's known_bad list (withdrawn releases clients move off). */+ withdraw?: string[];}export interface GitResult { code: number; stdout: string; stderr: string }@@ -60,7 +73,7 @@ export interface PromoteDeps {actor: string;soakWorkflow: string;ghApi(path: string): Promise<unknown>;- git(args: string[]): Promise<GitResult>;+ git(args: string[], input?: string): Promise<GitResult>;now(): Date;log(line: string): void;summary(markdown: string): void;@@ -86,7 +99,36 @@ export interface TagFields {reason: string;}-export interface Promotion extends TagFields { recordCreated: boolean }+export interface Promotion extends TagFields { recordCreated: boolean; knownBad: string[] }++/** The evidence record clients read (src/core/stable-channel.ts parseStableRecord); generation 1: soak evidence. */+export function renderRecord(f: TagFields, knownBad: readonly string[]): string {+ return JSON.stringify({+ schema: 1,+ channel: 'stable',+ version: f.version,+ commit: f.commit,+ tree: f.tree,+ soak_run: f.soakRun,+ scoreboard: f.scoreboard,+ promoted_by: f.promotedBy,+ promoted_at: f.promotedAt,+ previous: f.previous,+ rollback: f.rollback,+ reason: f.reason.trim().replace(/\s+/g, ' '),+ known_bad: [...knownBad],+ }, null, 2) + '\n';+}++/** The previous record's known_bad plus this run's withdrawals, deduplicated and sorted; refuses withdrawing the promoted version. */+export function mergeKnownBad(previous: readonly string[], withdraw: readonly string[], version: string): string[] {+ for (const v of withdraw) {+ if (!VERSION_RE.test(v)) throw new Refusal(`withdraw entry "${v}" is not a release version; pass versions like 0.60.361.0, comma-separated.`);+ }+ const all = [...new Set([...previous, ...withdraw])].sort(compareVersions);+ if (all.includes(version)) throw new Refusal(`v${version} is on the stable record's known_bad list (withdrawn); promote a different release.`);+ return all;+}export function compareVersions(a: string, b: string): number {const pa = a.split('.').map(Number);@@ -158,6 +200,7 @@ export function renderSummary(p: Promotion): string {['Scoreboard', p.scoreboard],['Previous stable', p.previous ? `v${p.previous}` : 'none'],['Rollback', p.rollback ? `yes: ${p.reason.trim()}` : 'no'],+ ['Known bad', p.knownBad.length ? p.knownBad.map(v => `v${v}`).join(', ') : 'none'],['Record tag', p.recordCreated ? `\`stable-v${p.version}\` created` : `\`stable-v${p.version}\` already existed (re-promotion)`],['Promoted by', `${p.promotedBy} at ${p.promotedAt}`],];@@ -165,8 +208,8 @@ export function renderSummary(p: Promotion): string {return [`## Stable channel: v${p.version}`, '', '| Field | Value |', '|---|---|', ...rows.map(([k, v]) => `| ${k} | ${cell(v)} |`), ''].join('\n');}-async function gitOut(deps: PromoteDeps, args: string[], refusal: string): Promise<string> {- const r = await deps.git(args);+async function gitOut(deps: PromoteDeps, args: string[], refusal: string, input?: string): Promise<string> {+ const r = await deps.git(args, input);if (r.code !== 0) throw new Refusal(`${refusal}${r.stderr.trim() ? ` (git: ${r.stderr.trim().split('\n').at(-1)})` : ''}`);return r.stdout.trim();}@@ -248,19 +291,44 @@ export async function promote(deps: PromoteDeps, inputs: PromoteInputs): Promiserollback, reason,};const message = renderTagMessage(fields);++ // The evidence record: carried forward from the previous record commit (none before the first promotion).+ await deps.git(['fetch', '--no-tags', 'origin', `+${RECORD_BRANCH_REF}:${RECORD_REMOTE_REF}`]);+ const priorRecordCommit = (await refExists(deps, `${RECORD_REMOTE_REF}^{commit}`))+ ? await gitOut(deps, ['rev-parse', `${RECORD_REMOTE_REF}^{commit}`], `Could not resolve ${RECORD_REMOTE_REF}; re-run this workflow.`)+ : null;+ let priorKnownBad: string[] = [];+ if (priorRecordCommit) {+ const shown = await deps.git(['show', `${priorRecordCommit}:${RECORD_FILE}`]);+ try {+ const prior = JSON.parse(shown.stdout) as { known_bad?: unknown };+ priorKnownBad = Array.isArray(prior.known_bad) ? prior.known_bad.filter((v): v is string => typeof v === 'string' && VERSION_RE.test(v)) : [];+ } catch {+ throw new Refusal(`The previous stable record (${priorRecordCommit}:${RECORD_FILE}) is not JSON, so its known_bad list cannot be carried forward; repair the stable-record branch by hand (${DOCS}).`);+ }+ }+ const knownBad = mergeKnownBad(priorKnownBad, inputs.withdraw ?? [], version);+ const blob = await gitOut(deps, ['hash-object', '-w', '--stdin'], 'Could not write the stable record blob; re-run this workflow.', renderRecord(fields, knownBad));+ const recordTree = await gitOut(deps, ['mktree'], 'Could not write the stable record tree; re-run this workflow.', `100644 blob ${blob}\t${RECORD_FILE}\n`);+ const recordCommit = await gitOut(deps, ['commit-tree', recordTree, ...(priorRecordCommit ? ['-p', priorRecordCommit] : []), '-m', `stable record: v${version}`],+ 'Could not commit the stable record; re-run this workflow.');+ deps.log(`[promote-stable] stable record ${recordCommit} (known_bad: ${knownBad.length ? knownBad.join(', ') : 'none'}).`);+if (!recordExists) {await gitOut(deps, ['tag', '-a', '--cleanup=verbatim', '-m', message, `stable-v${version}`, commit], `Could not create the tag stable-v${version}; re-run this workflow.`);}await gitOut(deps, ['tag', '-a', '-f', '--cleanup=verbatim', '-m', message, 'stable', commit], 'Could not create the stable tag; re-run this workflow.');- // One atomic push: the record tag and stable land together or not at all. stable is leased on the tag object read above- // (empty: stable must not exist yet), so a concurrent move refuses instead of being overwritten.- await gitOut(deps, ['push', '--atomic', `--force-with-lease=${STABLE_REF}:${current?.tagObject ?? ''}`, 'origin',- ...(recordExists ? [] : [`${recordRef}:${recordRef}`]), `${STABLE_REF}:${STABLE_REF}`],+ // One atomic push: the record tag, stable and the evidence record land together or not at all. stable and the record+ // branch are leased on the values read above (empty: must not exist yet), so a concurrent move refuses instead of being+ // overwritten.+ await gitOut(deps, ['push', '--atomic', `--force-with-lease=${STABLE_REF}:${current?.tagObject ?? ''}`,+ `--force-with-lease=${RECORD_BRANCH_REF}:${priorRecordCommit ?? ''}`, 'origin',+ ...(recordExists ? [] : [`${recordRef}:${recordRef}`]), `${STABLE_REF}:${STABLE_REF}`, `${recordCommit}:${RECORD_BRANCH_REF}`],'Moving the stable tag failed and nothing changed on the remote (stable may have moved since this run read it); re-run this workflow, which re-reads the current stable.');if (!recordExists) deps.log(`[promote-stable] pushed record tag stable-v${version}.`);deps.log(`[promote-stable] stable now points at v${version} (${commit}).`);- const promotion: Promotion = { ...fields, recordCreated: !recordExists };+ const promotion: Promotion = { ...fields, recordCreated: !recordExists, knownBad };deps.summary(renderSummary(promotion));return promotion;}@@ -275,8 +343,8 @@ export function processDeps(env: NodeJS.ProcessEnv = process.env, cwd = process.if (r.status !== 0) throw new Error(`gh api ${path} failed: ${(r.stderr || r.error?.message || '').trim()}`);return JSON.parse(r.stdout);},- async git(args) {- const r = spawnSync('git', args, { cwd, env, encoding: 'utf8' });+ async git(args, input) {+ const r = spawnSync('git', args, { cwd, env, encoding: 'utf8', ...(input !== undefined ? { input } : {}) });return { code: r.status ?? 1, stdout: r.stdout ?? '', stderr: r.stderr ?? '' };},now: () => new Date(),@@ -293,6 +361,7 @@ if (import.meta.main) {scoreboardUrl: env.PROMOTE_SCOREBOARD_URL ?? '',rollback: env.PROMOTE_ROLLBACK === 'true',reason: env.PROMOTE_REASON ?? '',+ withdraw: (env.PROMOTE_WITHDRAW ?? '').split(',').map(v => v.trim().replace(/^v/, '')).filter(Boolean),};const deps = processDeps();try {diff --git a/scripts/run-verify-parallel.sh b/scripts/run-verify-parallel.shindex 9b10122ad5..38b6e1e3b4 100755--- a/scripts/run-verify-parallel.sh+++ b/scripts/run-verify-parallel.sh@@ -153,6 +153,7 @@ CHECKS=("check:pin-doc-privacy""check:worker-lock-renewal-shape""check:bootstrap-tag"+ "check:install-ref""check:plugin-tree""check:skill-refs"# Previously reachable ONLY from the deleted check:all (i.e. never run):diff --git a/scripts/setup-in-agent.sh b/scripts/setup-in-agent.shindex c925a5f634..110190ab8d 100644--- a/scripts/setup-in-agent.sh+++ b/scripts/setup-in-agent.sh@@ -46,6 +46,7 @@ done# The runtime pin follows the repository's supported CI release. Repair reads# its prior version from the non-secret receipt; no mutable latest runtime URL.gbrain_bun_version=1.4.4+gbrain_install_ref=latest-stablegbrain_source_ref=''if [[ -f "$gbrain_receipt" && "$gbrain_upgrade" == 0 ]]; thengbrain_prior_bun=$(sed -n 's/.*"bun_version": *"\([0-9.]*\)".*/\1/p' "$gbrain_receipt" | head -1)@@ -56,7 +57,7 @@ fiif [[ -z "$gbrain_source_ref" ]]; then# Resolve the stable tag once; the installed receipt records this immutable# commit, so an ordinary repair never upgrades the software implicitly.- gbrain_refs=$(git ls-remote https://github.com/garrytan/gbrain.git 'refs/tags/latest-stable' 'refs/tags/latest-stable^{}')+ gbrain_refs=$(git ls-remote https://github.com/garrytan/gbrain.git "refs/tags/$gbrain_install_ref" "refs/tags/$gbrain_install_ref^{}")gbrain_source_ref=$(printf '%s\n' "$gbrain_refs" | awk '/\^\{\}$/ {print $1; found=1} END {if (!found) exit 1}') || gbrain_source_ref=$(printf '%s\n' "$gbrain_refs" | awk 'NR==1 {print $1}')fi[[ "$gbrain_source_ref" =~ ^[a-f0-9]{40}$ ]] || { echo 'Could not resolve the GBrain package commit.' >&2; exit 1; }diff --git a/skills/gbrain-upgrade/SKILL.md b/skills/gbrain-upgrade/SKILL.mdindex 08e2669208..5438841684 100644--- a/skills/gbrain-upgrade/SKILL.md+++ b/skills/gbrain-upgrade/SKILL.md@@ -113,7 +113,8 @@ If `changelog_diff` is empty (network blip / no notes), ask without the bulletsrather than blocking — the version numbers alone are enough to decide.- **Yes** → `gbrain self-upgrade`-- **Always** → `gbrain config set self_upgrade.mode auto` then `gbrain self-upgrade`+- **Always** → `gbrain config set self_upgrade.mode auto` then `gbrain self-upgrade`;+ tell the user it applies stable releases (alpha only if they set `self_upgrade.channel alpha`)- **Not now** → do nothing; the snooze escalates (24h → 48h → 7d) and the markerstops nagging for this version until it expires or a newer version ships.- **Never** → `gbrain config set self_upgrade.mode off`@@ -122,9 +123,8 @@ rather than blocking — the version numbers alone are enough to decide.A host that runs autopilot, a jobs worker or a serve must end the upgrade withevery process on the new build, and a job that starts mid-swap can run half on-each. A large or production brain follows the stable channel-(`gbrain config set self_upgrade.channel stable`, or `gbrain upgrade --channel stable`-once), which offers only releases that passed the production-shaped soak.+each. Installs follow the stable channel by default, which offers only releases+that passed the production-shaped soak (`self_upgrade.channel alpha` follows every release).With the operator's go-ahead, upgrade in this order:1. `gbrain autopilot pause --reason "upgrade"` so no new cycle starts.diff --git a/src/cli/main.ts b/src/cli/main.tsindex 9069c3803e..b0cb624cb0 100755--- a/src/cli/main.ts+++ b/src/cli/main.ts@@ -16,11 +16,12 @@ import {readUpdateCache,isCacheFresh,pendingUpgradeVersion,- readSnooze,- isSnoozeActive,+ snoozeHolds,+ currentReleaseChannel,resolveSelfUpgradeMode,justUpgradedPath,} from '../core/self-upgrade.ts';+import { maybeEmitChannelNotice } from '../core/release-channel-notice.ts';import { loadConfig, loadConfigFileOnly, loadConfigWithEngine, isThinClient, getDbUrlSource, envShadowDetected, MERGED_CONFIG_BY_ENGINE } from '../core/config.ts';import {classifyPgAccessError as classifyDbAccessError,@@ -212,7 +213,7 @@ export const cliAliases = buildCliAliases(OPERATION_MANIFEST, cliOps, CLI_ONLY);* blocks a command and NEVER throws (the marker must not break any command).* Mode resolution is file-plane only (no DB; thin clients have no local DB).*/-function maybeEmitUpdateMarker(command: string): void {+function maybeEmitUpdateMarker(command: string, args: readonly string[]): void {try {if (process.env.GBRAIN_SKIP_STARTUP_HOOKS) return;// Never run during the test suite: tests spawn the CLI hundreds of times,@@ -243,17 +244,21 @@ function maybeEmitUpdateMarker(command: string): void {const cfg = loadConfigFileOnly();const mode = resolveSelfUpgradeMode(cfg);if (mode === 'off') return;+ // GBRA-224: an invalid GBRAIN_RELEASE_CHANNEL / self_upgrade.channel checks nothing (doctor names it).+ const channel = currentReleaseChannel();+ if (!channel) return;+ maybeEmitChannelNotice({ command, args, cfg });const now = Date.now();- const entry = readUpdateCache();+ const entry = readUpdateCache(channel);if (entry && isCacheFresh(entry, now)) {// Shared stale/foreign-cache guard (pendingUpgradeVersion): only nag when- // the cached latest is strictly newer than the RUNNING binary, and print- // the running version — the cache records whatever binary WROTE it.- const latest = pendingUpgradeVersion(VERSION, now);+ // the channel offers this RUNNING binary a release, and print the running+ // version — the cache records whatever binary WROTE it.+ const latest = pendingUpgradeVersion(VERSION, now, channel);if (latest) {- // notify mode honors a per-version snooze; auto mode ignores it.- if (mode === 'notify' && isSnoozeActive(readSnooze(), latest, now)) return;+ // notify mode honors the channel's time-based snooze; auto mode ignores it.+ if (mode === 'notify' && snoozeHolds(latest, now, channel)) return;// One line, once per COVERAGE_NOTICE_WINDOW_MS across calls under// GBRAIN_HOME (a newer latest prints at once, #7147). An agent harness// (stderr not a TTY, or GBRAIN_FORCE_UPGRADE_MARKER=1 under a PTY) gets@@ -346,7 +351,7 @@ async function main() {// only, fail-open, never blocks. Skips the update path's own commands + sets// GBRAIN_SKIP_STARTUP_HOOKS for their children. Runs for every real command.if (!helpRequested) {- maybeEmitUpdateMarker(command);+ maybeEmitUpdateMarker(command, args);// Monthly backup-coverage nag (cache-read-only, bounded by the nag gate;// guards + skip set live inside the helper — one place, every call site).diff --git a/src/commands/autopilot.ts b/src/commands/autopilot.tsindex 02a2b5e72a..9962335a5e 100644--- a/src/commands/autopilot.ts+++ b/src/commands/autopilot.ts@@ -448,7 +448,8 @@ export async function attemptAutopilotSelfUpgrade(/* fail-open */}}- if (!entry || entry.marker.kind !== 'upgrade_available' || !entry.marker.latest) return;+ // GBRA-224: a failed stable lookup (even with a last verified answer kept for the notice) never applies.+ if (!entry || entry.error || entry.marker?.kind !== 'upgrade_available' || !entry.marker.latest) return;const latestVersion = entry.marker.latest;const idle = await computeAutopilotIdle(engine, engineType);diff --git a/src/commands/bootstrap.ts b/src/commands/bootstrap.tsindex 71b9ae4d94..e33102fed5 100644--- a/src/commands/bootstrap.ts+++ b/src/commands/bootstrap.ts@@ -109,6 +109,7 @@ import {} from '../core/bootstrap/status.ts';import { verifyWorkspace, resolveVerifySourceId, deriveWorkspaceSourceId } from '../core/bootstrap/verify.ts';import { auditWritebackContract, repairWritebackContract } from '../core/bootstrap/contract.ts';+import { INSTALL_PIN } from '../core/install-ref.ts';export const BOOTSTRAP_HELP = `gbrain bootstrap — paste-in agent install (Claude Code / Codex / opencode)@@ -1125,7 +1126,7 @@ async function runHooks(if (!gbrainBin) {console.error('cannot resolve an absolute gbrain binary path (GUI hosts inherit no PATH) — ' +- 'install gbrain globally (`bun install -g github:garrytan/gbrain#latest-stable`) or pass --gbrain-bin <abs path>',+ `install gbrain globally (\`bun install -g ${INSTALL_PIN}\`) or pass --gbrain-bin <abs path>`,);return 2;}diff --git a/src/commands/check-update.ts b/src/commands/check-update.tsindex 86975dd722..c57c454275 100644--- a/src/commands/check-update.ts+++ b/src/commands/check-update.ts@@ -8,13 +8,28 @@ import {semverGt,semverLte,} from '../core/semver.ts';-import { readUpdateCache, resolveReleaseChannel, writeUpdateCache, type ReleaseChannel, type UpdateMarker } from '../core/self-upgrade.ts';+import {+ DEFAULT_RELEASE_CHANNEL,+ currentReleaseChannel,+ invalidChannelMessage,+ offeredVersion,+ readUpdateCache,+ resolveReleaseChannel,+ writeUpdateCache,+ type CacheWriteOptions,+ type ReleaseChannel,+ type UpdateMarker,+} from '../core/self-upgrade.ts';import { loadConfig } from '../core/config.ts';+import { fetchStableRecord, stableFailureFix, stableFailureMessage, type StableCode } from '../core/stable-channel.ts';+import { opError } from '../core/ops/contract.ts';+import { writeCliError } from '../cli/cli-error.ts';+import { setCliExitVerdict } from '../core/cli-force-exit.ts';/** Best-effort cache write — a read-only ~/.gbrain must never make the check throw. */-function safeWriteCache(marker: UpdateMarker): void {+function safeWriteCache(marker: UpdateMarker | null, opts: CacheWriteOptions): void {try {- writeUpdateCache(marker);+ writeUpdateCache(marker, opts);} catch {/* fail-open: no cache this run, next invocation re-checks */}@@ -46,9 +61,9 @@ function upgradeCommandForMethod(method: string): string {}}-/** Where the latest version is resolved from: the VERSION file at the- * `latest-stable` tag, the one sanctioned distribution ref- * (`bun install -g github:garrytan/gbrain#latest-stable`). release.yml moves+/** Where the alpha channel's version is resolved from: the VERSION file at the+ * `latest-stable` tag, which release.yml moves on every published release. This+ * is the alpha channel's own ref, not the install ref (core/install-ref.ts). release.yml moves* it only after the release checks pass and the assets publish, so it names a* published release, the one `bun update` installs on the canonical install.* Master's VERSION is NOT a release: the next PR stamps it before release.yml@@ -58,13 +73,10 @@ function upgradeCommandForMethod(method: string): string {* stays unread: it was a permanent 404 before releases existed (#3520). An npm* fallback was rejected: the `gbrain` package on npm is an unrelated GPU* library (#505), so it would produce false upgrade prompts pointing at a- * stranger's package. A brain on the stable channel (`self_upgrade.channel- * stable`) reads the VERSION file at the `stable` tag instead: the newest- * release a maintainer promoted after the production-shaped soak passed on its- * exact tree (.github/workflows/promote-stable.yml). */+ * stranger's package. The stable channel (the default, GBRA-224) never reads a+ * bare VERSION file: it reads the evidence record (core/stable-channel.ts). */const RELEASE_REF_RAW = 'https://raw.githubusercontent.com/garrytan/gbrain/latest-stable';-export const CHANNEL_REFS: Record<ReleaseChannel, string> = { latest: 'latest-stable', stable: 'stable' };-const versionSourceUrl = (channel: ReleaseChannel) => `https://raw.githubusercontent.com/garrytan/gbrain/${CHANNEL_REFS[channel]}/VERSION`;+const ALPHA_VERSION_URL = `${RELEASE_REF_RAW}/VERSION`;const RELEASE_NOTES_URL = 'https://github.com/garrytan/gbrain/blob/latest-stable/CHANGELOG.md';/** Extract a version from the raw VERSION file body: first line, optional `v`@@ -78,20 +90,27 @@ export function parseVersionFileBody(body: string): string | null {}export type LatestReleaseResult =- | { ok: true; tag: string; published_at: string; url: string }- | { ok: false; reason: 'network_error' | 'no_releases' };+ | { ok: true; tag: string; published_at: string; url: string; knownBad: string[] }+ | { ok: false; reason: 'network_error' | 'no_releases' }+ | { ok: false; reason: StableCode; cause: string };/**- * Resolve the newest gbrain version on a release channel (from VERSION at the- * channel's tag — see CHANNEL_REFS). Exported (v0.42) so the self-upgrade refresh path and- * tests can reuse it. 5s timeout — this runs on the detached refresh, never the- * hot path. Failures are discriminated: `network_error` (offline/timeout) vs- * `no_releases` (endpoint answered but no usable version).+ * Resolve a release channel's version: alpha from VERSION at `latest-stable`, stable from the evidence record+ * (with its known_bad list). Exported (v0.42) so the self-upgrade refresh path and tests can reuse it. 5s timeout —+ * this runs on the detached refresh, never the hot path. Failures are discriminated: `network_error`+ * (offline/timeout) vs `no_releases` (endpoint answered but no usable version) on alpha; the typed stable codes on+ * stable.*/-export async function fetchLatestRelease(channel: ReleaseChannel = resolveReleaseChannel(loadConfig())): Promise<LatestReleaseResult> {+export async function fetchLatestRelease(channel: ReleaseChannel = currentReleaseChannel() ?? DEFAULT_RELEASE_CHANNEL): Promise<LatestReleaseResult> {+ if (channel === 'stable') {+ const r = await fetchStableRecord(fetch, `gbrain/${VERSION}`);+ return r.ok+ ? { ok: true, tag: r.record.version, published_at: r.record.promoted_at, url: RELEASE_NOTES_URL, knownBad: r.record.known_bad }+ : { ok: false, reason: r.code, cause: r.cause };+ }let res: Response;try {- res = await fetch(versionSourceUrl(channel), {+ res = await fetch(ALPHA_VERSION_URL, {headers: { 'User-Agent': `gbrain/${VERSION}` },signal: AbortSignal.timeout(5_000),});@@ -102,7 +121,7 @@ export async function fetchLatestRelease(channel: ReleaseChannel = resolveReleasif (!res.ok) return { ok: false, reason: 'no_releases' };const tag = parseVersionFileBody(await res.text());if (!tag) return { ok: false, reason: 'no_releases' };- return { ok: true, tag, published_at: '', url: RELEASE_NOTES_URL };+ return { ok: true, tag, published_at: '', url: RELEASE_NOTES_URL, knownBad: [] };} catch {return { ok: false, reason: 'network_error' };}@@ -160,56 +179,70 @@ export function extractChangelogBetween(changelog: string, from: string, to: str/*** A failed check must NEVER write `up_to_date` — that was #486: the fetch* failed permanently (dead releases API) and every user was told "you're- * current" forever. Instead, re-write the last-known-good marker (bumping its+ * current" forever. Instead, re-write the last-known-good answer (bumping its* mtime so the cache TTL still throttles retries and a network blip can't- * erase a pending upgrade_available notice). No prior marker → write nothing;- * the next invocation retries.+ * erase a pending upgrade_available notice). No prior answer → write nothing on+ * alpha; the next invocation retries. On stable the failure itself is recorded+ * (`error`) so doctor and --check-only report it: an unreadable record keeps the+ * last verified answer for the notice (never for an apply), a missing or invalid+ * one drops it.*/-function preserveCacheOnFailedCheck(): void {+function recordFailedCheck(channel: ReleaseChannel, release: Extract<LatestReleaseResult, { ok: false }>, checkedAt: number): void {try {- const prior = readUpdateCache();- if (prior) safeWriteCache(prior.marker);+ const prior = readUpdateCache(channel);+ if (!('cause' in release)) {+ if (prior?.marker) safeWriteCache(prior.marker, { channel, latest: prior.latest, knownBad: prior.knownBad, checkedAt });+ return;+ }+ const keep = release.reason === 'stable_unreadable' ? prior : null;+ safeWriteCache(keep?.marker ?? null, { channel, latest: keep?.latest ?? null, knownBad: keep?.knownBad ?? [], error: { code: release.reason, cause: release.cause }, checkedAt });} catch {/* best-effort */}}+/** Write a successful check's answer for this build. */+function recordCheck(channel: ReleaseChannel, release: Extract<LatestReleaseResult, { ok: true }>, checkedAt: number): string | null {+ const latestVersion = release.tag.replace(/^v/, '');+ const offered = offeredVersion(VERSION, latestVersion, release.knownBad);+ safeWriteCache(+ offered ? { kind: 'upgrade_available', current: VERSION, latest: offered } : { kind: 'up_to_date', current: VERSION },+ { channel, latest: isValidVersionString(latestVersion) ? latestVersion : null, knownBad: release.knownBad, checkedAt },+ );+ return offered;+}+/**- * Fetch the latest version and write the self-upgrade cache (the marker line- * read by the CLI startup hook). On fetch failure the last-known-good marker is- * preserved (see preserveCacheOnFailedCheck) — never a fabricated `up_to_date`.- * This is the function the detached single-flight refresh (`gbrain- * check-update --refresh-cache`) invokes.+ * Fetch the channel's version and write its cache partition (read by the CLI startup hook). On fetch failure the+ * last-known-good answer is preserved (see recordFailedCheck) — never a fabricated `up_to_date`, and never an alpha+ * answer on stable. This is the function the detached single-flight refresh (`gbrain check-update --refresh-cache`)+ * invokes. An invalid configured channel refreshes nothing.*/-export async function refreshUpdateCache(): Promise<void> {- const release = await fetchLatestRelease();- if (!release.ok) {- preserveCacheOnFailedCheck();- return;- }- const latestVersion = release.tag.replace(/^v/, '');- if (!isValidVersionString(latestVersion) || !isNewerVersion(VERSION, latestVersion)) {- safeWriteCache({ kind: 'up_to_date', current: VERSION });- return;- }- safeWriteCache({ kind: 'upgrade_available', current: VERSION, latest: latestVersion });+export async function refreshUpdateCache(channel: ReleaseChannel | null = currentReleaseChannel()): Promise<void> {+ if (!channel) return;+ const checkedAt = Date.now();+ const release = await fetchLatestRelease(channel);+ if (!release.ok) recordFailedCheck(channel, release, checkedAt);+ else recordCheck(channel, release, checkedAt);}export async function runCheckUpdate(args: string[]) {if (args.includes('--help') || args.includes('-h')) {- console.log('Usage: gbrain check-update [--json] [--refresh-cache]\n\nCheck for new GBrain versions.\n\nReports any strictly newer release, including patch and micro updates.\nFails silently on network errors.\n\n--refresh-cache Fetch + update the self-upgrade cache, print nothing (used by\n the CLI startup hook\'s detached refresh).');+ console.log('Usage: gbrain check-update [--json] [--refresh-cache]\n\nCheck for new GBrain versions on this install\'s release channel (stable by default;\nGBRAIN_RELEASE_CHANNEL or self_upgrade.channel selects alpha, every release).\n\nReports any strictly newer release, including patch and micro updates.\nFails silently on network errors.\n\n--refresh-cache Fetch + update the self-upgrade cache, print nothing (used by\n the CLI startup hook\'s detached refresh).');return;}// Detached refresh path: warm the cache for the next invocation, emit nothing.- // Single-flight via the refresh lock so many simultaneous stale-cache+ // Single-flight via the channel's refresh lock so many simultaneous stale-cache// invocations don't stampede GitHub. If another refresh holds the lock, exit.if (args.includes('--refresh-cache')) {+ const channel = currentReleaseChannel();+ if (!channel) return;const { tryAcquireRefreshLock, releaseRefreshLock } = await import('../core/self-upgrade.ts');- const lock = tryAcquireRefreshLock();+ const lock = tryAcquireRefreshLock(undefined, channel);if (!lock) return; // another refresh is in flighttry {- await refreshUpdateCache();+ await refreshUpdateCache(channel);} finally {releaseRefreshLock(lock);}@@ -217,13 +250,20 @@ export async function runCheckUpdate(args: string[]) {}const json = args.includes('--json');- const channel = resolveReleaseChannel(loadConfig());+ const resolution = resolveReleaseChannel(loadConfig());+ if (!resolution.ok) {+ setCliExitVerdict(writeCliError(opError('invalid_params', invalidChannelMessage(resolution), `Set a valid channel: gbrain config set self_upgrade.channel stable (or alpha).`), 'check-update', { json }));+ return;+ }+ const { channel } = resolution;const upgradeCmd = channel === 'stable' ? 'gbrain upgrade' : upgradeCommandForMethod(detectInstallMethod());-+ const checkedAt = Date.now();const release = await fetchLatestRelease(channel);+ const channelFields = { channel, channel_source: resolution.source };if (!release.ok) {- preserveCacheOnFailedCheck();+ recordFailedCheck(channel, release, checkedAt);+ const stable = 'cause' in release ? { message: stableFailureMessage({ code: release.reason, cause: release.cause }), fix: stableFailureFix({ code: release.reason }, resolution) } : null;if (json) {console.log(JSON.stringify({current_version: VERSION,@@ -235,7 +275,11 @@ export async function runCheckUpdate(args: string[]) {changelog_diff: '',published_at: '',error: release.reason,+ ...channelFields,+ ...(stable ?? {}),}, null, 2));+ } else if (stable) {+ console.log(`GBrain ${VERSION} — ${stable.message} ${stable.fix}`);} else if (release.reason === 'network_error') {console.log(`GBrain ${VERSION} — could not check for updates (network unavailable).`);} else {@@ -245,18 +289,14 @@ export async function runCheckUpdate(args: string[]) {}const latestVersion = release.tag.replace(/^v/, '');- const updateAvailable = isValidVersionString(latestVersion) && isNewerVersion(VERSION, latestVersion);-// Warm the self-upgrade cache so the next `gbrain <cmd>` startup hook can emit// the marker without a network call.- safeWriteCache(- updateAvailable- ? { kind: 'upgrade_available', current: VERSION, latest: latestVersion }- : { kind: 'up_to_date', current: VERSION },- );+ const offered = recordCheck(channel, release, checkedAt);+ const updateAvailable = offered !== null;+ const withdrawn = updateAvailable && release.knownBad.includes(VERSION);let changelogDiff = '';- if (updateAvailable) {+ if (updateAvailable && !withdrawn) {changelogDiff = await fetchChangelog(VERSION, latestVersion);}@@ -272,12 +312,15 @@ export async function runCheckUpdate(args: string[]) {};if (json) {- console.log(JSON.stringify(result, null, 2));+ console.log(JSON.stringify({ ...result, ...channelFields, ...(withdrawn ? { withdrawn: true } : {}) }, null, 2));+ } else if (withdrawn) {+ console.log(`GBrain ${VERSION} was withdrawn from the stable channel; the current stable release is ${latestVersion}.`);+ console.log(`Run: ${upgradeCmd}`);} else if (updateAvailable) {- console.log(`GBrain update available: ${VERSION} → ${latestVersion}`);+ console.log(`GBrain update available (${channel} channel): ${VERSION} → ${latestVersion}`);console.log(`Run: ${upgradeCmd}`);console.log(`Release: ${release.url}`);} else {- console.log(`GBrain ${VERSION} is up to date.`);+ console.log(`GBrain ${VERSION} is up to date on the ${channel} channel.`);}}diff --git a/src/commands/doctor/checks/upgrade-health.ts b/src/commands/doctor/checks/upgrade-health.tsindex ecc04477e7..364272d35a 100644--- a/src/commands/doctor/checks/upgrade-health.ts+++ b/src/commands/doctor/checks/upgrade-health.ts@@ -93,10 +93,31 @@ export function checkSelfUpgradeHealth(): Check {};}- const parts: string[] = [`mode=${mode}`];+ // GBRA-224: the effective release channel and where it came from (env > self_upgrade.channel > default stable).+ const { resolveReleaseChannel, invalidChannelMessage, readUpdateCache } = require('../../../core/self-upgrade.ts');+ const resolution = resolveReleaseChannel(cfg);+ if (!resolution.ok) {+ return {+ name: 'self_upgrade_health',+ status: 'warn',+ message: `${invalidChannelMessage(resolution)} Update checks are off until it is fixed (mode=${mode}).`,+ fix: agentFix(['gbrain', 'config', 'get', 'self_upgrade.channel'], 'Read-only: shows the configured channel; set stable or alpha with gbrain config set self_upgrade.channel <name>.', 'self_upgrade_health'),+ };+ }+ const parts: string[] = [`mode=${mode}`, `channel=${resolution.channel} (${resolution.source})`];// Shared stale/foreign-cache guard: only report an upgrade strictly newer// than the RUNNING binary (pendingUpgradeVersion owns the rule).- const pendingLatest = pendingUpgradeVersion(GBRAIN_BINARY_VERSION, Date.now());+ const pendingLatest = pendingUpgradeVersion(GBRAIN_BINARY_VERSION, Date.now(), resolution.channel);+ const stableError = readUpdateCache(resolution.channel)?.error;+ if (stableError) {+ const { stableFailureMessage, stableFailureFix } = require('../../../core/stable-channel.ts');+ return {+ name: 'self_upgrade_health',+ status: 'warn',+ message: `${stableError.code}: ${stableFailureMessage(stableError)} ${stableFailureFix(stableError, resolution)} (${parts.join('; ')}).`,+ fix: agentFix(['gbrain', 'self-upgrade', '--check-only', '--json'], 'Read-only: looks up the stable channel again and reports the channel, its source and any error code.', 'self_upgrade_health', { docs: 'docs/guides/upgrades-auto-update.md#stable-channel-errors' }),+ };+ }if (pendingLatest) {parts.push(`update available: ${GBRAIN_BINARY_VERSION} -> ${pendingLatest} (run: gbrain self-upgrade)`);}diff --git a/src/commands/self-upgrade.ts b/src/commands/self-upgrade.tsindex 87f565c3dc..5f37490fd0 100644--- a/src/commands/self-upgrade.ts+++ b/src/commands/self-upgrade.ts@@ -1,8 +1,20 @@import { VERSION } from '../version.ts';-import { isNewerVersion, isValidVersionString } from '../core/semver.ts';+import { isValidVersionString } from '../core/semver.ts';import { fetchChangelog, fetchLatestRelease } from './check-update.ts';import { detectInstallMethod, runUpgrade } from './upgrade.ts';-import { writeUpdateCache } from '../core/self-upgrade.ts';+import {+ invalidChannelMessage,+ offeredVersion,+ pendingUpgradeVersion,+ resolveReleaseChannel,+ writeSnooze,+ writeUpdateCache,+ type ReleaseChannel,+} from '../core/self-upgrade.ts';+import { parseChannelArg, stableFailureFix, stableFailureMessage } from '../core/stable-channel.ts';+import { opError } from '../core/ops/contract.ts';+import { writeCliError } from '../cli/cli-error.ts';+import { setCliExitVerdict } from '../core/cli-force-exit.ts';import { loadConfig, saveConfig } from '../core/config.ts';import { CLEAR_NEVER_INSTALLED_APPLY, findNeverInstalledFailures } from '../core/self-upgrade-recovery.ts';@@ -55,7 +67,7 @@ function runClearNeverInstalled(apply: boolean, json: boolean): void {}/**- * `gbrain self-upgrade [--check-only] [--force] [--json] [--no-bun-floor-check]`+ * `gbrain self-upgrade [--check-only] [--snooze] [--force] [--json] [--channel stable|alpha] [--no-bun-floor-check]`** The universal substrate every agent ecosystem (Codex / Claude Code / Hermes /* OpenClaw / Perplexity-server) can call to stay current. The CLI startup hook@@ -64,21 +76,27 @@ function runClearNeverInstalled(apply: boolean, json: boolean): void {* parameterized by any marker content (forged-marker guard).** --check-only Report whether an upgrade is available; never apply.+ * --snooze "Not now": hold this channel's notice for 24h, then 48h, then 7d.* --force Apply even if not behind (re-run the install-method swap).* --json Machine-readable output for the check.+ * --channel stable or alpha for this run (latest is an alias for alpha).* --no-bun-floor-check Passed through to `gbrain upgrade` (#5855).*/export async function runSelfUpgrade(args: string[]): Promise<void> {if (args.includes('--help') || args.includes('-h')) {console.log(- 'Usage: gbrain self-upgrade [--check-only] [--force] [--json] [--no-bun-floor-check]\n' ++ 'Usage: gbrain self-upgrade [--check-only] [--force] [--json] [--channel stable|alpha] [--no-bun-floor-check]\n' ++ ' gbrain self-upgrade --snooze [--json]\n' +' gbrain self-upgrade --clear-never-installed [--apply] [--json]\n\n' +- 'Check for and apply gbrain updates. The shared entry point used by the\n' +- 'CLI startup marker, the gbrain-upgrade agent skill, and the autopilot\n' +- 'silent channel.\n\n' +- ' --check-only Report whether an upgrade is available; do not apply.\n' ++ 'Check for and apply gbrain updates on this install\'s release channel (stable by default;\n' ++ 'alpha follows every release). The shared entry point used by the CLI startup marker,\n' ++ 'the gbrain-upgrade agent skill, and the autopilot silent channel.\n\n' ++ ' --check-only Report whether an upgrade is available, on which channel and why; do not apply.\n' ++ ' --snooze "Not now": hold this channel\'s update notice for 24h, then 48h, then 7d,\n' ++ ' however many releases ship meanwhile; an upgrade clears it.\n' +' --force Apply even when not behind.\n' +- ' --json Machine-readable output (with --check-only).\n' ++ ' --json Machine-readable output (with --check-only or --snooze).\n' ++ ' --channel stable or alpha for this run (latest is an alias for alpha).\n' +' --no-bun-floor-check Apply even when the target\'s Bun floor cannot be read or is\n' +' above this host\'s Bun. Docs: docs/guides/upgrades-auto-update.md#bun-floor\n' +' --clear-never-installed Preview the known-bad versions (self_upgrade.failed_versions) the\n' +@@ -95,20 +113,34 @@ export async function runSelfUpgrade(args: string[]): Promise<void> {const checkOnly = args.includes('--check-only');const force = args.includes('--force');const json = args.includes('--json');+ const resolution = resolveReleaseChannel(loadConfig(), parseChannelArg(args));+ if (!resolution.ok) {+ setCliExitVerdict(writeCliError(opError('invalid_params', invalidChannelMessage(resolution), 'Use --channel stable or --channel alpha, or fix the value where it is set.'), 'self-upgrade', { json }));+ return;+ }+ const { channel } = resolution;+ if (args.includes('--snooze')) {+ runSnooze(channel, json);+ return;+ }- const result = await fetchLatestRelease();+ const checkedAt = Date.now();+ const result = await fetchLatestRelease(channel);const release = result.ok ? result : null;const latest = release ? release.tag.replace(/^v/, '') : null;- const behind = !!latest && isValidVersionString(latest) && isNewerVersion(VERSION, latest);+ const offered = release ? offeredVersion(VERSION, latest, release.knownBad) : null;+ const withdrawn = !!release && offered !== null && release.knownBad.includes(VERSION);+ const stableFailure = !result.ok && 'cause' in result ? { code: result.reason, cause: result.cause } : null;// Warm the cache so the next invocation's startup hook can emit without a fetch.try {if (latest && isValidVersionString(latest)) {writeUpdateCache(- behind- ? { kind: 'upgrade_available', current: VERSION, latest }- : { kind: 'up_to_date', current: VERSION },+ offered ? { kind: 'upgrade_available', current: VERSION, latest: offered } : { kind: 'up_to_date', current: VERSION },+ { channel, latest, knownBad: release?.knownBad ?? [], checkedAt },);+ } else if (stableFailure) {+ writeUpdateCache(null, { channel, error: stableFailure, checkedAt });}} catch {/* best-effort */@@ -119,50 +151,74 @@ export async function runSelfUpgrade(args: string[]): Promise<void> {// behind (so an up-to-date check stays a single release fetch). The agent// skill surfaces these "what's new" bullets in the notify prompt.let changelogDiff = '';- if (behind && latest) {+ if (offered && !withdrawn) {try {- changelogDiff = await fetchChangelog(VERSION, latest);+ changelogDiff = await fetchChangelog(VERSION, offered);} catch {/* best-effort: an unavailable changelog must not block the check */}}+ const failure = stableFailure ? { code: stableFailure.code, message: stableFailureMessage(stableFailure), fix: stableFailureFix(stableFailure, resolution) } : null;if (json) {console.log(JSON.stringify({current_version: VERSION,latest_version: latest ?? '',- update_available: behind,+ update_available: offered !== null,install_method: detectInstallMethod(),release_url: release?.url ?? '',changelog_diff: changelogDiff,+ channel,+ channel_source: resolution.source,+ ...(withdrawn ? { withdrawn: true } : {}),+ ...(failure ? { error: failure } : {}),},null,2,),);- } else if (behind) {- console.log(`Update available: ${VERSION} -> ${latest}. Run: gbrain self-upgrade`);+ } else if (failure) {+ console.log(`${failure.message} ${failure.fix}`);+ } else if (withdrawn) {+ console.log(`gbrain ${VERSION} was withdrawn from the stable channel. Run: gbrain self-upgrade (installs the current stable, ${offered})`);+ } else if (offered) {+ console.log(`Update available on the ${channel} channel: ${VERSION} -> ${offered}. Run: gbrain self-upgrade`);if (changelogDiff) {console.log('\nWhat changed:\n');console.log(changelogDiff);}if (release?.url) console.log(`\nRelease: ${release.url}`);} else {- console.log(`gbrain ${VERSION} is up to date.`);+ console.log(`gbrain ${VERSION} is up to date on the ${channel} channel.`);}return;}- if (!behind && !force) {- console.log(`gbrain ${VERSION} is up to date.`);+ // Stable is resolved and verified again by gbrain upgrade (record + tags), which refuses with the typed code.+ if (!offered && !force && !stableFailure) {+ console.log(`gbrain ${VERSION} is up to date on the ${channel} channel.`);return;}// Apply: delegate to the hardcoded upgrade path (full swap + post-upgrade).// Pass the fetched target so runUpgrade can detect exact-tag no-op// "upgrades" instead of reporting false success (#4366).- await runUpgrade(args.filter((a) => a === '--no-bun-floor-check'), {- targetVersion: latest && isValidVersionString(latest) ? latest : undefined,+ await runUpgrade([...args.filter((a) => a === '--no-bun-floor-check'), '--channel', channel], {+ targetVersion: offered && isValidVersionString(offered) ? offered : undefined,});}++/** `gbrain self-upgrade --snooze`: record "Not now" for the offered version on this channel. */+function runSnooze(channel: ReleaseChannel, json: boolean): void {+ const offered = pendingUpgradeVersion(VERSION, Date.now(), channel);+ if (!offered) {+ if (json) console.log(JSON.stringify({ snoozed: false, channel, reason: 'no update is pending on this channel' }, null, 2));+ else console.log(`No gbrain update is pending on the ${channel} channel; nothing to snooze.`);+ return;+ }+ const record = writeSnooze(offered, Date.now(), channel);+ const until = new Date(record.until).toISOString();+ if (json) console.log(JSON.stringify({ snoozed: true, channel, version: offered, level: record.level, until }, null, 2));+ else console.log(`Snoozed the gbrain ${offered} update on the ${channel} channel until ${until} (run gbrain self-upgrade any time).`);+}diff --git a/src/commands/upgrade-channel.ts b/src/commands/upgrade-channel.tsnew file mode 100644index 0000000000..3775002a2b--- /dev/null+++ b/src/commands/upgrade-channel.ts@@ -0,0 +1,91 @@+/**+ * GBRA-224 W1: which release `gbrain upgrade` installs. The channel comes from `--channel`, then+ * GBRAIN_RELEASE_CHANNEL, then `self_upgrade.channel`, then stable (core/self-upgrade.ts resolveReleaseChannel).+ * Alpha keeps the install method's own path (null target); stable installs exactly the evidence-backed release+ * (core/stable-channel.ts), never moves below the running build except off a version the record withdrew, and+ * refuses with a typed code when stable has no usable release.+ */+import { VERSION } from '../version.ts';+import { loadConfig } from '../core/config.ts';+import { isNewerVersion } from '../core/semver.ts';+import { setCliExitVerdict, writeJsonDocument } from '../core/cli-force-exit.ts';+import { opError } from '../core/ops/contract.ts';+import { writeCliError } from '../cli/cli-error.ts';+import { invalidChannelMessage, resolveReleaseChannel, type ChannelResolution } from '../core/self-upgrade.ts';+import { parseChannelArg, resolveStableRelease, stableFailureAction, stableFailureFix, stableFailureMessage, type StableFailure } from '../core/stable-channel.ts';++export type StableTarget = { version: string; commit: string };+type Resolved = Extract<ChannelResolution, { ok: true }>;+type Plan =+ | { kind: 'invalid'; resolution: Extract<ChannelResolution, { ok: false }> }+ | { kind: 'alpha'; resolution: Resolved }+ | { kind: 'stable_failure'; resolution: Resolved; failure: StableFailure }+ | { kind: 'stable_current'; resolution: Resolved; version: string }+ | { kind: 'stable_ahead'; resolution: Resolved; version: string }+ | { kind: 'stable_install'; resolution: Resolved; target: StableTarget; withdrawn: boolean };++/** Decide what the upgrade would do on the effective channel. Reads the stable record and tags; installs nothing. */+export async function planChannelUpgrade(args: readonly string[], oldVersion: string = VERSION, deps: Parameters<typeof resolveStableRelease>[0] = {}): Promise<Plan> {+ const resolution = resolveReleaseChannel(loadConfig(), parseChannelArg(args));+ if (!resolution.ok) return { kind: 'invalid', resolution };+ if (resolution.channel === 'alpha') return { kind: 'alpha', resolution };+ const stable = await resolveStableRelease(deps);+ if (!stable.ok) return { kind: 'stable_failure', resolution, failure: stable };+ const withdrawn = stable.record.known_bad.includes(oldVersion) && stable.version !== oldVersion;+ if (!withdrawn && !isNewerVersion(oldVersion, stable.version)) {+ return oldVersion === stable.version ? { kind: 'stable_current', resolution, version: stable.version } : { kind: 'stable_ahead', resolution, version: stable.version };+ }+ return { kind: 'stable_install', resolution, target: { version: stable.version, commit: stable.commit }, withdrawn };+}++const sourceLabel = (r: ChannelResolution) => r.source === 'flag' ? '--channel' : r.source === 'env' ? 'GBRAIN_RELEASE_CHANNEL' : r.source === 'config' ? 'self_upgrade.channel' : 'default';++function refuse(plan: Extract<Plan, { kind: 'invalid' | 'stable_failure' }>, oldVersion: string, json: boolean): void {+ if (plan.kind === 'invalid') {+ setCliExitVerdict(writeCliError(opError('invalid_params', invalidChannelMessage(plan.resolution), 'Use --channel stable or --channel alpha, or fix the value where it is set.'), 'upgrade', { json }));+ return;+ }+ const { failure, resolution } = plan;+ setCliExitVerdict(writeCliError(opError(failure.code, stableFailureMessage(failure), stableFailureFix(failure, resolution), {+ fix: stableFailureAction(failure, resolution),+ detail: `channel=stable (from ${sourceLabel(resolution)}); running ${oldVersion}; cause: ${failure.cause}`,+ }), 'upgrade', { json }));+}++/**+ * The release `--channel` (default: env, config, stable) selects: null on alpha, the stable release to install, or+ * 'stop' after reporting an invalid channel, an unusable stable channel (non-zero, typed code) or nothing to install.+ */+export async function channelTarget(args: readonly string[], oldVersion: string, json: boolean): Promise<StableTarget | null | 'stop'> {+ const plan = await planChannelUpgrade(args, oldVersion);+ if (plan.kind === 'invalid' || plan.kind === 'stable_failure') { refuse(plan, oldVersion, json); return 'stop'; }+ if (plan.kind === 'alpha') return null;+ if (plan.kind === 'stable_current') { console.log(`Already on the stable channel's release: gbrain ${oldVersion}.`); return 'stop'; }+ if (plan.kind === 'stable_ahead') {+ console.log(`gbrain ${oldVersion} is newer than the stable channel's release (${plan.version}); the stable channel never downgrades. Nothing was changed.`);+ return 'stop';+ }+ console.log(plan.withdrawn+ ? `gbrain ${oldVersion} was withdrawn from the stable channel (known_bad in the stable record); installing the current stable release, gbrain ${plan.target.version}.`+ : `Stable channel: installing gbrain ${plan.target.version} (promoted after its gates passed on this exact release).`);+ return plan.target;+}++/** `gbrain upgrade --dry-run` (without --restart-only): the effective channel, where it came from and what would install. */+export async function runUpgradeDryRun(args: readonly string[], json: boolean): Promise<void> {+ const plan = await planChannelUpgrade(args);+ if (plan.kind === 'invalid' || plan.kind === 'stable_failure') { refuse(plan, VERSION, json); return; }+ const target = plan.kind === 'stable_install' ? plan.target.version : plan.kind === 'alpha' ? null : plan.version;+ const action = plan.kind === 'alpha' ? 'install_method_update' : plan.kind === 'stable_install' ? (plan.withdrawn ? 'install_withdrawn_replacement' : 'install') : 'none';+ if (json) {+ await writeJsonDocument(JSON.stringify({ dry_run: true, channel: plan.resolution.channel, channel_source: plan.resolution.source, current_version: VERSION, target_version: target, action }, null, 2));+ return;+ }+ console.log(`Channel: ${plan.resolution.channel} (from ${sourceLabel(plan.resolution)})`);+ console.log(plan.kind === 'alpha'+ ? 'Would update through the install method to the newest published release.'+ : plan.kind === 'stable_install' ? `Would install gbrain ${target}${plan.withdrawn ? `, replacing the withdrawn ${VERSION}` : ''}.`+ : plan.kind === 'stable_current' ? `Already on the stable release, gbrain ${VERSION}.`+ : `gbrain ${VERSION} is ahead of stable (${target}); nothing would change.`);+ console.log('Dry run: nothing was changed.');+}diff --git a/src/commands/upgrade-restart.ts b/src/commands/upgrade-restart.tsindex 33622ee205..2047eaade9 100644--- a/src/commands/upgrade-restart.ts+++ b/src/commands/upgrade-restart.ts@@ -177,8 +177,9 @@ export function restartRefusal(plan: RestartPlan, rerunArgv: readonly string[],export interface HostRestartOptions { stopMcp: boolean; json: boolean; rerunArgv: string[] }/**- * `gbrain upgrade --restart-only [--dry-run]`. `--dry-run` belongs to `--restart-only`: anywhere else it is refused,- * never ignored while the upgrade installs for real (#2185). True when this handled the invocation.+ * `gbrain upgrade --restart-only [--dry-run]`. True when this handled the invocation. A `--dry-run` without+ * `--restart-only` is the channel preview (commands/upgrade-channel.ts runUpgradeDryRun), which installs nothing, so it+ * is still never ignored while the upgrade installs for real (#2185).*/export async function handleRestartOnly(args: readonly string[], opts: HostRestartOptions): Promise<boolean> {const dryRun = args.includes('--dry-run');@@ -186,9 +187,7 @@ export async function handleRestartOnly(args: readonly string[], opts: HostRestaawait runHostRestart({ ...opts, rerunArgv: ['gbrain', 'upgrade', '--restart-only', ...(opts.stopMcp ? ['--stop-mcp'] : [])], dryRun });return true;}- if (!dryRun) return false;- setCliExitVerdict(writeCliError(opError('invalid_params', '--dry-run previews only a restart; nothing was installed.', 'Run gbrain upgrade --restart-only --dry-run to preview the restart.'), 'upgrade', { json: opts.json }));- return true;+ return false;}/** The package directory this process loaded its code from (realpath), the install the upgrade replaces. */diff --git a/src/commands/upgrade.ts b/src/commands/upgrade.tsindex 1f6c7afdc5..b56f257a8f 100644--- a/src/commands/upgrade.ts+++ b/src/commands/upgrade.ts@@ -12,9 +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, gbrainPath } from '../core/config.ts';-import { clearSnooze, clearUpdateCache, resolveReleaseChannel, writeJustUpgraded, writeSwapReceipt, type ReleaseChannel } from '../core/self-upgrade.ts';+import { clearSnooze, clearUpdateCache, currentReleaseChannel, writeJustUpgraded, writeSwapReceipt, type ReleaseChannel } from '../core/self-upgrade.ts';import { handleRestartOnly, preflightHostRestart } from './upgrade-restart.ts';-import { parseChannelArg, resolveStableRelease, stableUnresolvedMessage } from '../core/stable-channel.ts';+import { resolveStableRelease } from '../core/stable-channel.ts';+import { channelTarget, runUpgradeDryRun } from './upgrade-channel.ts';export { parseChannelArg, resolveStableRelease } from '../core/stable-channel.ts';import { MOVEMENT_SUPERVISOR_STEP } from './movement-step.ts';import {@@ -49,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 latest|stable] [--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> latest (every published release) or stable (the newest release promoted after the\n production-shaped soak passed on its exact tree). Default: self_upgrade.channel, else latest.\n Set it per brain with gbrain config set self_upgrade.channel stable — update checks follow it too.\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 With --restart-only: print the plan and change nothing.\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, 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. Set it with gbrain config set self_upgrade.channel alpha.\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;}@@ -65,6 +66,7 @@ export async function runUpgrade(args: string[], opts: { targetVersion?: stringconst stopMcp = args.includes('--stop-mcp');const restartOpts = { stopMcp, json, rerunArgv: ['gbrain', 'upgrade', ...args.filter(a => a !== '--json')] };if (await handleRestartOnly(args, restartOpts)) return;+ if (args.includes('--dry-run')) return runUpgradeDryRun(args, json);const noRestart = args.includes('--no-restart');// Capture old version BEFORE upgrading (Codex finding: old binary runs this code)const oldVersion = VERSION;@@ -72,7 +74,7 @@ export async function runUpgrade(args: string[], opts: { targetVersion?: stringconsole.log(`Detected install method: ${method}`);- const stableTarget = channelTarget(args, oldVersion, json);+ const stableTarget = await channelTarget(args, oldVersion, json);if (stableTarget === 'stop') return;if (stableTarget) opts = { ...opts, targetVersion: stableTarget.version };if (!swapOnly && !noRestart && !await preflightHostRestart(restartOpts)) return;@@ -353,32 +355,6 @@ function restartOntoNewBuild(stopMcp: boolean, newVersion: string): string {return `Restart: incomplete (exit ${restart.status ?? restart.signal ?? 'unknown'}). Follow the steps above, then run \`gbrain upgrade --restart-only\``;}-/**- * GBRA-175: the release `--channel` (default self_upgrade.channel) selects: null on latest, the stable release when it- * is newer than this build, or 'stop' after reporting an invalid channel, an unresolved stable tag or nothing newer.- */-function channelTarget(args: readonly string[], oldVersion: string, json: boolean): { version: string; commit: string } | null | 'stop' {- const channel = parseChannelArg(args) ?? resolveReleaseChannel(loadConfig());- if (channel === 'invalid') {- setCliExitVerdict(writeCliError(opError('invalid_params', '--channel takes latest or stable.', 'Run gbrain upgrade --channel stable (or latest).'), 'upgrade', { json }));- return 'stop';- }- if (channel === 'latest') return null;- const stable = resolveStableRelease();- if ('error' in stable) {- setCliExitVerdict(writeCliError(opError('stable_channel_unresolved', stableUnresolvedMessage(stable.error), 'Nothing was changed. Retry later, or run: gbrain upgrade --channel latest', { reason: stable.error }), 'upgrade', { json }));- return 'stop';- }- if (!isNewerVersion(oldVersion, stable.version)) {- console.log(oldVersion === stable.version- ? `Already on the stable channel's release: gbrain ${oldVersion}.`- : `gbrain ${oldVersion} is newer than the stable channel's release (${stable.version}); the stable channel never downgrades. Nothing was changed.`);- return 'stop';- }- console.log(`Stable channel: installing gbrain ${stable.version} (promoted after the production-shaped soak).`);- return stable;-}-/*** 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@@ -471,10 +447,10 @@ async function installStableRelease(method: string, target: { version: string; c* it, so a floor raised in between still refuses there. GBRA-175: on the stable* channel (self_upgrade.channel) it is the stable release's floor.*/-export async function readInstallTargetFloor(method: string, channel: ReleaseChannel = resolveReleaseChannel(loadConfig())): Promise<TargetFloor> {- if (channel === 'stable') {- const stable = resolveStableRelease();- return 'error' in stable ? { ok: false, failedRead: `the stable channel's release (${stable.error})` } : readPackageTarget(`github:${GBRAIN_GITHUB_REPO}#v${stable.version}`);+export async function readInstallTargetFloor(method: string, channel: ReleaseChannel | null = currentReleaseChannel()): Promise<TargetFloor> {+ if (channel !== 'alpha') {+ const stable = channel ? await resolveStableRelease() : null;+ return !stable?.ok ? { ok: false, failedRead: `the stable channel's release (${stable ? stable.code : 'invalid channel'})` } : readPackageTarget(`github:${GBRAIN_GITHUB_REPO}#v${stable.version}`);}if (method === 'bun-link') {const link = detectBunLink();diff --git a/src/core/agent-install/setup.ts b/src/core/agent-install/setup.tsindex 7d278ddef1..a56039bd14 100644--- a/src/core/agent-install/setup.ts+++ b/src/core/agent-install/setup.ts@@ -17,8 +17,9 @@ import {} from './state.ts';import { bunSpawn, bunSpawnSync } from '../spawn.ts';import { MINIMUM_BUN_VERSION, bunVersionMeets } from '../runtime-version.ts';+import { INSTALL_RAW_BASE } from '../install-ref.ts';-const SETUP_HELPER_URL = 'https://raw.githubusercontent.com/garrytan/gbrain/latest-stable/scripts/setup-in-agent.sh';+const SETUP_HELPER_URL = `${INSTALL_RAW_BASE}/scripts/setup-in-agent.sh`;export interface AgentSetupOptions {root: string;diff --git a/src/core/agent-install/state.ts b/src/core/agent-install/state.tsindex a5c94be82a..6155ef8ba6 100644--- a/src/core/agent-install/state.ts+++ b/src/core/agent-install/state.ts@@ -7,6 +7,7 @@ import { flushDirectory } from '../fs-durable.ts';import { shouldDropAgentEnv } from './environment.ts';import { shellQuote } from '../mcp-registration.ts';import type { LocalSharedSkillsResult } from './shared-skills.ts';+import { INSTALL_REF } from '../install-ref.ts';export class AgentInstallError extends Error {constructor(public code: string, message: string) { super(message); this.name = 'AgentInstallError'; }@@ -181,7 +182,7 @@ export function writeInstallReceipt(receipt: AgentInstallReceipt): void {assertNoSymlinks(helper);helperOwned = sha256(readFileSync(helper)) === receipt.owned_files['bin/gbrain-setup'];} catch { /* A missing or changed helper is repaired from the recorded package. */ }- const ref = /^[a-f0-9]{40}$/.test(receipt.artifact?.source_ref ?? '') ? receipt.artifact!.source_ref : 'latest-stable';+ const ref = /^[a-f0-9]{40}$/.test(receipt.artifact?.source_ref ?? '') ? receipt.artifact!.source_ref : INSTALL_REF;const command = helperOwned ? `bash ${shellQuote(helper)} --json`: `curl -fsSL https://raw.githubusercontent.com/garrytan/gbrain/${ref}/scripts/setup-in-agent.sh | bash -s -- --root ${shellQuote(receipt.root)} --harness ${shellQuote(receipt.harness)} --json`;receipt.recovery = { command, action: receipt.last_failurediff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.tsindex 59b8c1aa07..c9ec7662d5 100644--- a/src/core/behavior-change-notice.ts+++ b/src/core/behavior-change-notice.ts@@ -1320,6 +1320,8 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText;{ since: '0.60.471.0', id: 'door_planned_state', text: 'On a source with `canonical: git`, a page write now commits exactly the bytes it published, or nothing. A file edited on disk while the write was publishing refuses `git_target_changed`: nothing is committed, the edit stays on disk and the source\'s writes pause until `gbrain repair stuck-recovery` resolves it (before, Git committed the edit while the database recorded the write\'s content). A staged change of the page\'s file refuses `git_index_conflict`, with the index untouched; commit or unstage it, then retry (before, the write replaced the staged change in the index). When the index still holds the version from before an earlier gbrain commit whose index update failed, the next write restores it and says so with a `git_index_restored` notice.' },// #7679 / #7685 orphaned worktree refresh. `since` is stamped at the merge slot.{ since: '0.60.472.0', id: 'refresh_orphan_7679', text: 'A managed `gbrain sources refresh` whose process died (for example a container replaced mid-refresh) no longer wedges the checkout: the next plain `gbrain sources refresh` on the owner host finishes the orphaned refresh through the `--resume` path before its own refresh and reports it as `recovered`, and the owner completes an orphaned `syncing` refresh once every member has synced to its target. A refresh whose holder is still running, or is recorded on another host, is never taken over. `gbrain sources writer status` and `gbrain sync status` now name the holder and its `liveness` (`live`, `orphaned`, `unknown`) with a fix naming `--resume`. With `--json`, a refusal that carries a structured fix (`refresh_in_progress`, `refresh_diverged`, a git read failure) now prints `fix` as an object (argv, actor, next) instead of a string; the prose stays in `suggestion`, so read that when a script needs text. A plain refresh of a checkout whose interrupted refresh needs a reset decision now refuses `refresh_recovery_required` (it refused `refresh_in_progress`).' },+ // GBRA-224 W1 (stable and alpha channels). `since` is stamped at the merge slot.+ { since: 'TBD', id: 'release_channel_stable_default', text: 'Updates now follow the stable channel by default: weekly releases a maintainer promoted after testing on that release\'s exact tree. Before, every install followed every published release (the channel then called `latest`, now `alpha`; `latest` still works as an alias). Every update surface (the startup marker, `check-update`, `self-upgrade`, `upgrade`, doctor and the `auto` mode) reads the published stable evidence record instead of the release tag. An install ahead of stable is offered nothing until stable passes it, never a downgrade, unless its version was withdrawn. When stable has no usable answer the background check only reports `stable_missing`, `stable_invalid` or `stable_unreadable` and an explicit upgrade exits non-zero with it; neither falls back to alpha (`stable_channel_unresolved` is retired). The update cache and snooze are kept per channel, so the first check after upgrading starts fresh and an earlier snooze no longer applies; a snooze now holds for its whole window however many releases ship. `gbrain upgrade --dry-run` reports the channel and target without installing. To keep every release: gbrain config set self_upgrade.channel alpha. Install commands keep the latest-stable ref for now.' },];/** The newest disclosed change's release: the notice id moves only when a release adds rows. */diff --git a/src/core/bootstrap/template-repo.ts b/src/core/bootstrap/template-repo.tsindex 60c781171e..2dedf3aa11 100644--- a/src/core/bootstrap/template-repo.ts+++ b/src/core/bootstrap/template-repo.ts@@ -31,6 +31,7 @@ import { existsSync, mkdirSync, readFileSync, readdirSync, writeFileSync } fromimport { join, resolve } from 'node:path';import { TEMPLATE_PLACEHOLDER_MANIFEST, writeManifest } from './format.ts';import { renderWorkspace } from './render.ts';+import { INSTALL_PIN, INSTALL_RAW_BASE } from '../install-ref.ts';/** Stamp line contract shared with scripts/check-bootstrap-templates.sh and* the release workflow. `{{VERSION}}` is replaced at generation time from the@@ -65,7 +66,7 @@ const TEMPLATE_README_LINES: readonly string[] = ['',' ```',' Read and follow every step of:',- ' https://raw.githubusercontent.com/garrytan/gbrain/latest-stable/BOOTSTRAP_FOR_AGENTS.md',+ ` ${INSTALL_RAW_BASE}/BOOTSTRAP_FOR_AGENTS.md`,' Goal: finish setting up this cloned template as my persistent personal',' agent, with gbrain as your memory. Interview me before writing any',' identity file — never invent answers. You are not done until',@@ -73,7 +74,7 @@ const TEMPLATE_README_LINES: readonly string[] = [' ```','',' Already running the gbrain CLI',- ' (`bun install -g github:garrytan/gbrain#latest-stable`)? Then the first',+ ` (\`bun install -g ${INSTALL_PIN}\`)? Then the first`,' step is always:','',' ```',diff --git a/src/core/config.ts b/src/core/config.tsindex 0a95052dce..d75594afc8 100644--- a/src/core/config.ts+++ b/src/core/config.ts@@ -284,7 +284,7 @@ export interface GBrainConfig {*/self_upgrade?: {mode?: 'auto' | 'notify' | 'off';- channel?: 'latest' | 'stable';+ channel?: 'stable' | 'alpha' | 'latest';/** Set true once the upgrade-time consent prompt has been shown. */mode_prompted?: boolean;/** Quiet-hours window for the autopilot silent channel. */diff --git a/src/core/error-registry.ts b/src/core/error-registry.tsindex c4d30ed271..ca21ce2357 100644--- a/src/core/error-registry.ts+++ b/src/core/error-registry.ts@@ -679,7 +679,15 @@ export const CODES = {source_writeback_required: { class: 'host_only', summary: "Canonical preparation requires a source-content correction; this profile never writes repository files." },split_bad_ratio: { class: 'caller', summary: "Split bad ratio." },split_unparseable: { class: 'caller', summary: "Split unparseable." },- stable_channel_unresolved: { class: 'unavailable', reasons: ['unreadable', 'no_stable', 'no_release_tag'], summary: "`gbrain upgrade --channel stable` (or `self_upgrade.channel stable`) could not name the stable release: the repository's tags could not be read, no release has been promoted to stable yet, or the `stable` tag does not share a commit with a `v<version>` release tag. Nothing was changed.", why: "The stable channel installs only a release a maintainer promoted after the production-shaped soak passed on its exact tree; without that answer it installs nothing rather than guess.", docs: 'docs/guides/upgrades-auto-update.md#stable-channel', suggestion: 'Retry later, or upgrade on the latest channel with `gbrain upgrade --channel latest`.' },+ stable_channel_unresolved: { class: 'unavailable', retired_in: 'TBD', reasons: ['unreadable', 'no_stable', 'no_release_tag'],+ summary: "Retired: an older gbrain could not name the stable release from the repository's tags alone. This build resolves stable from the published evidence record and reports stable_missing, stable_invalid or stable_unreadable instead.",+ why: "Since GBRA-224 the stable channel is the default and accepts only a release whose evidence record proves its gates passed on that exact tree; a message with this code came from an older build.",+ docs: 'docs/guides/upgrades-auto-update.md#stable-channel-errors',+ suggestion: 'Rerun gbrain self-upgrade --check-only --json on this build; it names the current stable code and its fix.',+ fix: { argv: ['gbrain', 'self-upgrade', '--check-only', '--json'], consent: [], actor: 'agent', requires_exclusive: false, why: 'Read-only: checks the channel in effect and reports the current stable code, if any.' } },+ stable_invalid: { class: 'unavailable', summary: "The stable channel has no usable release: the published evidence record is missing, malformed, lacks an evidence key its generation needs (soak_run; matrix_run from the matrix cutover on), or names a version whose release tag is not the stable commit. Nothing was installed.", why: "A stable install accepts only a release whose record proves its gates passed on that exact tree; a record that does not prove it is never trusted, and the client never falls back to alpha by itself.", docs: 'docs/guides/upgrades-auto-update.md#stable-channel-errors', suggestion: 'Wait for a maintainer to repair or re-promote stable, or follow every release on alpha: gbrain config set self_upgrade.channel alpha (or the --channel / GBRAIN_RELEASE_CHANNEL override named in the message).' },+ stable_missing: { class: 'unavailable', summary: "No release has been promoted to the stable channel yet (no stable tag or no published evidence record), so the stable channel has nothing to install. Nothing was installed.", why: "Stable installs only promoted releases; an empty channel installs nothing rather than guess, and the background update check only reports it.", docs: 'docs/guides/upgrades-auto-update.md#stable-channel-errors', suggestion: 'Wait for the first stable promotion, or follow every release on alpha: gbrain config set self_upgrade.channel alpha (or the --channel / GBRAIN_RELEASE_CHANNEL override named in the message).' },+ stable_unreadable: { class: 'retryable', summary: "The stable channel could not be read: the evidence record or the repository's tags did not answer, or the stable tag and the record disagree while a promotion propagates. Nothing was installed.", why: "Without a verified answer the client installs nothing and keeps any earlier verified answer for the notice only; the channel is unchanged.", docs: 'docs/guides/upgrades-auto-update.md#stable-channel-errors', suggestion: 'Retry in a few minutes: gbrain self-upgrade --check-only. Check network access to github.com and raw.githubusercontent.com if it repeats.' },stale_unavailable: { class: 'unavailable', summary: "No complete, current authorized shared-skills view is available; cached shared skills stay unused.", docs: 'docs/guides/shared-brain-skills.md#troubleshoot-leave-and-recover' },state_mismatch: { class: 'caller', summary: "Google connect credential error: state mismatch.", docs: 'docs/guides/google-connect.md#troubleshooting' },storage_error: { class: 'server', summary: "Reading or writing durable storage failed.",diff --git a/src/core/install-ref.ts b/src/core/install-ref.tsnew file mode 100644index 0000000000..8e0f96a952--- /dev/null+++ b/src/core/install-ref.ts@@ -0,0 +1,14 @@+/**+ * The one git ref every install surface names (GBRA-224): README and agent install docs, the bootstrap runbook fetch,+ * the in-agent setup helper, the template repository, plugin launchers and the CLI's own install hints.+ *+ * Today it is `latest-stable`, the tag release.yml moves on every published release (the alpha channel). Install surfaces+ * stay there until a release that contains the stable channel client has been promoted to `stable`; the flip is then this+ * one line plus `bun run check:install-ref --write` (and the generated plugin and template trees). The lint+ * (scripts/check-install-ref.ts, test/install-ref.test.ts) refuses any install pin, runbook fetch or helper fetch that+ * names another ref, master included. The alpha channel's update check (src/commands/check-update.ts) reads+ * `latest-stable` on its own and does not follow this constant.+ */+export const INSTALL_REF = 'latest-stable';+export const INSTALL_PIN = `github:garrytan/gbrain#${INSTALL_REF}`;+export const INSTALL_RAW_BASE = `https://raw.githubusercontent.com/garrytan/gbrain/${INSTALL_REF}`;diff --git a/src/core/release-channel-notice.ts b/src/core/release-channel-notice.tsnew file mode 100644index 0000000000..3a2fe9f634--- /dev/null+++ b/src/core/release-channel-notice.ts@@ -0,0 +1,41 @@+/**+ * GBRA-224 W1: the one-time notice that an install whose channel was never set now follows stable. Printed on the+ * first update check after the flip, once per GBRAIN_HOME (an exclusively created marker file), on stderr, in the+ * `[gbrain notice …]` form that parseMarker never reads as `UPGRADE_AVAILABLE`. Never under `--json` or the MCP+ * server (it waits for a later plain invocation), and never when a flag, GBRAIN_RELEASE_CHANNEL or+ * `self_upgrade.channel` chose the channel. File plane only, so repo-less and repo brains behave the same.+ */+import { mkdirSync, writeFileSync } from 'node:fs';+import { dirname } from 'node:path';+import { gbrainPath } from './config.ts';+import { jsonRequested } from './cli-force-exit.ts';+import { resolveReleaseChannel } from './self-upgrade.ts';++export const CHANNEL_NOTICE_CODE = 'release_channel';+export const CHANNEL_NOTICE_TEXT = `[gbrain notice ${CHANNEL_NOTICE_CODE}] This install now follows the stable channel: weekly releases promoted after testing. To get every release instead, run: gbrain config set self_upgrade.channel alpha`;+const MCP_COMMANDS = new Set(['serve', 'mcp']);++export function channelNoticePath(): string {+ return gbrainPath('notices', 'release-channel-stable');+}++/** Print the notice when it applies and was never printed under this GBRAIN_HOME; returns whether it printed. */+export function maybeEmitChannelNotice(opts: {+ command: string;+ args: readonly string[];+ cfg: { self_upgrade?: { channel?: string } } | null;+ env?: string | undefined;+ write?: (line: string) => void;+}): boolean {+ if (MCP_COMMANDS.has(opts.command) || jsonRequested(opts.args)) return false;+ if (resolveReleaseChannel(opts.cfg, null, opts.env).source !== 'default') return false;+ const path = channelNoticePath();+ try {+ mkdirSync(dirname(path), { recursive: true });+ writeFileSync(path, `${new Date().toISOString()}\n`, { flag: 'wx', mode: 0o600 });+ } catch {+ return false;+ }+ (opts.write ?? (line => process.stderr.write(line)))(`${CHANNEL_NOTICE_TEXT}\n`);+ return true;+}diff --git a/src/core/self-upgrade.ts b/src/core/self-upgrade.tsindex ff84d59afb..6427ad82ee 100644--- a/src/core/self-upgrade.ts+++ b/src/core/self-upgrade.ts@@ -9,8 +9,9 @@** This module is the PURE + state foundation:* - `decideSelfUpgrade()` — pure decision over already-resolved inputs.- * - cache helpers — atomic temp+rename writes, strict parse, mtime-TTL.- * - snooze helpers — escalating 24h/48h/7d, version-reset.+ * - cache helpers — one file per release channel stamped with its evidence+ * policy; atomic temp+rename writes, strict parse, mtime-TTL.+ * - snooze helpers — per channel, time-based, escalating 24h/48h/7d.* - `formatMarker` / `parseMarker` — ONE marker grammar shared by the CLI* emit, the MCP emit, and the agent skill (no drift; forged markers* rejected via the version regex).@@ -28,7 +29,7 @@import { closeSync, mkdirSync, openSync, readFileSync, renameSync, statSync, unlinkSync, writeFileSync } from 'node:fs';import { dirname, join } from 'node:path';-import { gbrainPath, isConfigTruthy } from './config.ts';+import { gbrainPath, isConfigTruthy, loadConfigFileOnly } from './config.ts';import { isValidTimeZone } from './cycle/cycle-date.ts';import { isValidConfig as isValidQuietHoursWindow } from './minions/quiet-hours.ts';import { evaluateBunFloor, type HostBun, type TargetFloor } from './bun-floor.ts';@@ -58,21 +59,82 @@ export const SNOOZE_DURATIONS_MS = [export type SelfUpgradeMode = 'auto' | 'notify' | 'off';/**- * The release line an install follows. `latest` is every published release (the `latest-stable` tag release.yml- * advances); `stable` is the newest release a maintainer promoted after the production-shaped soak passed on its- * exact tree (the `stable` tag .github/workflows/promote-stable.yml advances). Set per brain home with- * `gbrain config set self_upgrade.channel stable`; `gbrain upgrade --channel <name>` overrides it for one run.+ * The release line an install follows (GBRA-224 W1). `stable` (the default) is the newest release a maintainer+ * promoted after its gates passed on the exact tree, published with an evidence record (core/stable-channel.ts);+ * `alpha` is every published release (the `latest-stable` tag release.yml advances). `latest` is accepted+ * everywhere as an alias for alpha. Precedence: `--channel`, then GBRAIN_RELEASE_CHANNEL, then+ * `self_upgrade.channel` (file plane), then stable.*/-export type ReleaseChannel = 'latest' | 'stable';-export const RELEASE_CHANNELS: readonly ReleaseChannel[] = ['latest', 'stable'];+export type ReleaseChannel = 'stable' | 'alpha';+export const RELEASE_CHANNELS: readonly ReleaseChannel[] = ['stable', 'alpha'];+export const DEFAULT_RELEASE_CHANNEL: ReleaseChannel = 'stable';+export const RELEASE_CHANNEL_ENV = 'GBRAIN_RELEASE_CHANNEL';+export const VALID_CHANNELS_TEXT = 'stable or alpha (latest is an alias for alpha)';export function normalizeChannel(raw: unknown): ReleaseChannel | null {- return raw === 'latest' || raw === 'stable' ? raw : null;+ if (typeof raw !== 'string') return null;+ const v = raw.trim().toLowerCase();+ if (v === 'stable') return 'stable';+ return v === 'alpha' || v === 'latest' ? 'alpha' : null;}-/** The configured channel (file plane), else `latest`. */-export function resolveReleaseChannel(cfg: { self_upgrade?: { channel?: string } } | null | undefined): ReleaseChannel {- return normalizeChannel(cfg?.self_upgrade?.channel) ?? 'latest';+export type ChannelSource = 'flag' | 'env' | 'config' | 'default';+export type ChannelResolution =+ | { ok: true; channel: ReleaseChannel; source: ChannelSource }+ | { ok: false; source: Exclude<ChannelSource, 'default'>; raw: string };++/**+ * The effective channel and where it came from. `flag` is the raw `--channel` value (null when absent, '' when the+ * flag had no value). The first source present decides; an invalid value there is an error, never a fallthrough.+ */+export function resolveReleaseChannel(+ cfg: { self_upgrade?: { channel?: string } } | null | undefined,+ flag: string | null = null,+ env: string | undefined = process.env[RELEASE_CHANNEL_ENV],+): ChannelResolution {+ const sources: Array<[Exclude<ChannelSource, 'default'>, string | null | undefined]> = [+ ['flag', flag],+ ['env', env === '' ? undefined : env],+ ['config', cfg?.self_upgrade?.channel],+ ];+ for (const [source, raw] of sources) {+ if (raw === null || raw === undefined) continue;+ const channel = normalizeChannel(raw);+ return channel ? { ok: true, channel, source } : { ok: false, source, raw: String(raw) };+ }+ return { ok: true, channel: DEFAULT_RELEASE_CHANNEL, source: 'default' };+}++/** The hot-path channel (env and file-plane config, no flag); null when the value there is invalid. */+export function currentReleaseChannel(): ReleaseChannel | null {+ const res = resolveReleaseChannel(loadConfigFileOnly());+ return res.ok ? res.channel : null;+}++/** The command that moves this install to `target`, rendered against what currently decides the channel. */+export function channelSwitchCommand(target: ReleaseChannel, res: ChannelResolution): string {+ if (res.source === 'flag') return `gbrain upgrade --channel ${target}`;+ if (res.source === 'env') return `${RELEASE_CHANNEL_ENV}=${target} (it overrides self_upgrade.channel), or unset ${RELEASE_CHANNEL_ENV} and run gbrain config set self_upgrade.channel ${target}`;+ return `gbrain config set self_upgrade.channel ${target}`;+}++/** A usage-error sentence for an invalid channel value. */+export function invalidChannelMessage(res: Extract<ChannelResolution, { ok: false }>): string {+ const where = res.source === 'flag' ? '--channel' : res.source === 'env' ? RELEASE_CHANNEL_ENV : 'self_upgrade.channel';+ return `${where} is '${res.raw}', which is not a release channel; use ${VALID_CHANNELS_TEXT}.`;+}++/**+ * The evidence policy a cached stable answer was validated under. A record whose version is at or above+ * MATRIX_REQUIRED_FROM must carry `matrix_run` as well as `soak_run`; null until the upgrade matrix (W2) ships, so+ * every generation-1 record (soak evidence only) stays valid. Changing either changes the policy id, which+ * invalidates cached stable answers.+ */+export const MATRIX_REQUIRED_FROM: string | null = null;+export const STABLE_EVIDENCE_POLICY = `stable-record-v1;matrix-from=${MATRIX_REQUIRED_FROM ?? 'none'}`;+export const ALPHA_EVIDENCE_POLICY = 'alpha-version-file-v1';+export function evidencePolicyFor(channel: ReleaseChannel): string {+ return channel === 'stable' ? STABLE_EVIDENCE_POLICY : ALPHA_EVIDENCE_POLICY;}export type SelfUpgradeChannel = 'invocation' | 'autopilot';@@ -135,6 +197,8 @@ export interface SnoozeRecord {level: number;/** Epoch ms when the snooze was written. */ts: number;+ /** Epoch ms when it ends. */+ until: number;}// ── Pure decision ───────────────────────────────────────────────────────────@@ -286,12 +350,18 @@ export function parseMarker(line: string): UpdateMarker | null {// ── State file paths ────────────────────────────────────────────────────────-export function updateCachePath(): string {- return gbrainPath('last-update-check');+/** Files from before the cache was partitioned by channel (GBRA-224): never read, removed on clear. */+const LEGACY_CACHE_FILE = 'last-update-check';+const LEGACY_SNOOZE_FILE = 'update-snoozed';++/** The update-check cache for one channel (default: the hot-path channel; stable when that is invalid). */+export function updateCachePath(channel: ReleaseChannel = currentReleaseChannel() ?? DEFAULT_RELEASE_CHANNEL): string {+ return gbrainPath(`update-check.${channel}.json`);}-export function snoozePath(): string {- return gbrainPath('update-snoozed');+/** The "Not now" snooze for one channel. */+export function snoozePath(channel: ReleaseChannel = currentReleaseChannel() ?? DEFAULT_RELEASE_CHANNEL): string {+ return gbrainPath(`update-snoozed.${channel}.json`);}export function justUpgradedPath(): string {@@ -319,11 +389,41 @@ export function locksDir(): string {// ── Cache (untrusted local state: atomic write, strict parse, mtime-TTL) ─────+/** A stable lookup that failed, kept so doctor and --check-only can report it without a network call. */+export interface StableLookupError {+ code: 'stable_missing' | 'stable_invalid' | 'stable_unreadable';+ cause: string;+}++/**+ * One channel's cached answer. Partitioned by channel (one file each) and stamped with the evidence policy it was+ * validated under, so a channel switch, a default flip or a policy change never reads another partition's answer.+ * `latest` is the channel's release (on stable, the evidence record's version, which can be below the running build);+ * `knownBad` is the record's withdrawn list; `error` is set when the last stable lookup failed.+ */export interface CacheEntry {- marker: UpdateMarker;+ marker: UpdateMarker | null;mtimeMs: number;+ channel: ReleaseChannel;+ policy: string;+ checkedAt: number;+ latest: string | null;+ knownBad: string[];+ error: StableLookupError | null;+}++export interface CacheWriteOptions {+ channel?: ReleaseChannel;+ /** The channel's release when it differs from the marker's (a stable record below the running build). */+ latest?: string | null;+ knownBad?: readonly string[];+ error?: StableLookupError | null;+ /** When the refresh that produced this answer started; an older answer never overwrites a newer one. */+ checkedAt?: number;}+const STABLE_CODES = new Set(['stable_missing', 'stable_invalid', 'stable_unreadable']);+let _tmpCounter = 0;function atomicWrite(path: string, content: string): void {const dir = dirname(path);@@ -338,46 +438,91 @@ function atomicWrite(path: string, content: string): void {renameSync(tmp, path);}-/** Read + strict-parse the cache. Returns null on missing / corrupt. */-export function readUpdateCache(): CacheEntry | null {- const path = updateCachePath();- let content: string;+function unlinkQuiet(path: string): void {+ try {+ unlinkSync(path);+ } catch {+ /* already gone */+ }+}++/**+ * Read + strict-parse one channel's cache. Null on missing, corrupt, another channel's or another evidence policy's+ * entry (a legacy unpartitioned file is never read).+ */+export function readUpdateCache(channel: ReleaseChannel | null = currentReleaseChannel()): CacheEntry | null {+ if (!channel) return null;+ const path = updateCachePath(channel);+ let raw: Record<string, unknown>;let mtimeMs: number;try {- content = readFileSync(path, 'utf8');+ raw = JSON.parse(readFileSync(path, 'utf8'));mtimeMs = statSync(path).mtimeMs;} catch {return null;}- const marker = parseMarker(content);- if (!marker) return null;- return { marker, mtimeMs };-}--/** Atomically write the cache (marker line, 0600). Best-effort: throws only on- * truly unexpected fs errors (callers in the detached refresh swallow). */-export function writeUpdateCache(marker: UpdateMarker): void {- atomicWrite(updateCachePath(), formatMarker(marker) + '\n');+ if (!raw || typeof raw !== 'object' || raw.schema !== 2) return null;+ if (raw.channel !== channel || raw.policy !== evidencePolicyFor(channel)) return null;+ const marker = raw.marker === null ? null : parseMarker(String(raw.marker ?? ''));+ if (raw.marker !== null && !marker) return null;+ const latest = typeof raw.latest === 'string' && isValidVersionString(raw.latest) ? raw.latest : null;+ const knownBad = Array.isArray(raw.known_bad) ? raw.known_bad.filter((v): v is string => typeof v === 'string' && isValidVersionString(v)) : [];+ const e = raw.error as { code?: unknown; cause?: unknown } | null | undefined;+ const error = e && typeof e === 'object' && typeof e.code === 'string' && STABLE_CODES.has(e.code)+ ? { code: e.code as StableLookupError['code'], cause: typeof e.cause === 'string' ? e.cause.slice(0, 300) : '' }+ : null;+ if (!marker && !error) return null;+ const checkedAt = typeof raw.checked_at === 'number' && Number.isFinite(raw.checked_at) ? raw.checked_at : mtimeMs;+ return { marker, mtimeMs, channel, policy: raw.policy as string, checkedAt, latest: latest ?? marker?.latest ?? null, knownBad, error };}-/** Clear the cache (e.g. after a successful upgrade) so the next run re-checks. */+/**+ * Atomically write one channel's cache (0600). A refresh that started before the stored answer's refresh never+ * overwrites it (reversed completion). Best-effort: throws only on truly unexpected fs errors.+ */+export function writeUpdateCache(marker: UpdateMarker | null, opts: CacheWriteOptions = {}): void {+ const channel = opts.channel ?? currentReleaseChannel() ?? DEFAULT_RELEASE_CHANNEL;+ const checkedAt = opts.checkedAt ?? Date.now();+ const prior = readUpdateCache(channel);+ if (prior && prior.checkedAt > checkedAt) return;+ atomicWrite(updateCachePath(channel), JSON.stringify({+ schema: 2,+ channel,+ policy: evidencePolicyFor(channel),+ checked_at: checkedAt,+ marker: marker ? formatMarker(marker) : null,+ latest: opts.latest === undefined ? marker?.latest ?? null : opts.latest,+ known_bad: [...(opts.knownBad ?? [])],+ error: opts.error ?? null,+ }) + '\n');+ unlinkQuiet(gbrainPath(LEGACY_CACHE_FILE));+}++/** Clear every channel's cache (e.g. after a successful upgrade) so the next run re-checks. */export function clearUpdateCache(): void {- try {- unlinkSync(updateCachePath());- } catch {- /* already gone */- }+ for (const channel of RELEASE_CHANNELS) unlinkQuiet(updateCachePath(channel));+ unlinkQuiet(gbrainPath(LEGACY_CACHE_FILE));}export function isCacheFresh(entry: CacheEntry, now: number): boolean {- const ttl = entry.marker.kind === 'upgrade_available' ? CACHE_TTL_UPGRADE_AVAILABLE_MS : CACHE_TTL_UP_TO_DATE_MS;+ const ttl = entry.marker?.kind === 'upgrade_available' && !entry.error ? CACHE_TTL_UPGRADE_AVAILABLE_MS : CACHE_TTL_UP_TO_DATE_MS;return now - entry.mtimeMs < ttl;}+/**+ * The release a channel offers this build: its release when strictly newer, or, on stable, the current stable when+ * the running version is on the record's known_bad list (the one move below the running build the channel makes,+ * because the record says so). Null otherwise. Pure.+ */+export function offeredVersion(runningVersion: string, latest: string | null, knownBad: readonly string[]): string | null {+ if (!latest || !isValidVersionString(latest)) return null;+ if (isNewerVersion(runningVersion, latest)) return latest;+ return knownBad.includes(runningVersion) && latest !== runningVersion ? latest : null;+}+/*** The one shared "is an upgrade actually pending for THIS binary?" predicate.- * Returns the latest version string when the cache is present, fresh, marks an- * upgrade, AND that upgrade is strictly newer than the RUNNING binary — else+ * Returns the offered version (offeredVersion) when the effective channel's cache is present and fresh — else* null. The running-version comparison is the load-bearing part: the cache* records the version of whatever binary WROTE it (an older gbrain on PATH can* write it via the detached refresh), so consumers must never trust@@ -385,13 +530,12 @@ export function isCacheFresh(entry: CacheEntry, now: number): boolean {* startup marker, doctor, advisor, get_brain_identity) routes through here so* the suppression rule cannot drift per-surface. Never throws.*/-export function pendingUpgradeVersion(runningVersion: string, now: number = Date.now()): string | null {+export function pendingUpgradeVersion(runningVersion: string, now: number = Date.now(), channel: ReleaseChannel | null = currentReleaseChannel()): string | null {try {- const entry = readUpdateCache();+ const entry = readUpdateCache(channel);if (!entry || !isCacheFresh(entry, now)) return null;- if (entry.marker.kind !== 'upgrade_available' || !entry.marker.latest) return null;- if (!isNewerVersion(runningVersion, entry.marker.latest)) return null;- return entry.marker.latest;+ if (entry.error?.code === 'stable_missing' || entry.error?.code === 'stable_invalid') return null;+ return offeredVersion(runningVersion, entry.latest, entry.knownBad);} catch {return null;}@@ -399,22 +543,21 @@ export function pendingUpgradeVersion(runningVersion: string, now: number = Date// ── Snooze (interactive prompting only; never overrides mode=off) ────────────-export function readSnooze(): SnoozeRecord | null {- let content: string;+/**+ * Read one channel's snooze. A snooze is time-based: "Not now" holds until `until` whatever the channel ships+ * meanwhile; `version` is what was offered when it was written (a rollback below it ends the snooze).+ */+export function readSnooze(channel: ReleaseChannel = currentReleaseChannel() ?? DEFAULT_RELEASE_CHANNEL): SnoozeRecord | null {+ let raw: Record<string, unknown>;try {- content = readFileSync(snoozePath(), 'utf8');+ raw = JSON.parse(readFileSync(snoozePath(channel), 'utf8'));} catch {return null;}- const parts = content.trim().split(/\s+/);- if (parts.length !== 3) return null;- const version = parts[0];- const level = Number(parts[1]);- const ts = Number(parts[2]);- if (!isValidVersionString(version) || !Number.isInteger(level) || level < 1 || !Number.isFinite(ts)) {- return null;- }- return { version, level, ts };+ const { version, level, ts, until } = raw ?? {};+ if (typeof version !== 'string' || !isValidVersionString(version)) return null;+ if (!Number.isInteger(level) || (level as number) < 1 || !Number.isFinite(ts) || !Number.isFinite(until)) return null;+ return { version, level: level as number, ts: ts as number, until: until as number };}/** Snooze duration for a level (1-indexed; >=3 caps at 7d). */@@ -423,35 +566,44 @@ export function snoozeDurationMs(level: number): number {return SNOOZE_DURATIONS_MS[idx];}-/** True iff an unexpired snooze covers `latestVersion`. A snooze for a- * different (older) version never suppresses a newer one (version-reset). */-export function isSnoozeActive(snooze: SnoozeRecord | null, latestVersion: string, now: number): boolean {- if (!snooze) return false;- if (snooze.version !== latestVersion) return false;- return now - snooze.ts < snoozeDurationMs(snooze.level);+/**+ * True iff an unexpired snooze covers an offer of `offered`. Newer releases never end it (it is time-based); an+ * offer below the snoozed version (a stable rollback) does.+ */+export function isSnoozeActive(snooze: SnoozeRecord | null, offered: string, now: number): boolean {+ if (!snooze || now >= snooze.until) return false;+ return !isNewerVersion(offered, snooze.version);}/**- * Record (or escalate) a snooze for `latestVersion`. If the existing snooze is- * for the same version, escalate its level (capped); otherwise start at level 1.- * Returns the new level.+ * Whether the channel's snooze holds back an offer of `offered`. A snooze the offer rolled back below is cleared,+ * so the rolled-back release is offered at once.*/-export function writeSnooze(latestVersion: string, now: number): number {- const existing = readSnooze();- let level = 1;- if (existing && existing.version === latestVersion) {- level = Math.min(existing.level + 1, SNOOZE_DURATIONS_MS.length);+export function snoozeHolds(offered: string, now: number, channel: ReleaseChannel = currentReleaseChannel() ?? DEFAULT_RELEASE_CHANNEL): boolean {+ const snooze = readSnooze(channel);+ if (snooze && isNewerVersion(offered, snooze.version)) {+ clearSnooze(channel);+ return false;}- atomicWrite(snoozePath(), `${latestVersion} ${level} ${now}\n`);- return level;+ return isSnoozeActive(snooze, offered, now);}-export function clearSnooze(): void {- try {- unlinkSync(snoozePath());- } catch {- /* already gone */- }+/**+ * Record (or escalate) "Not now" on a channel: level 1 (24 h), then 48 h, then 7 d for each later "Not now" until an+ * upgrade clears it. Written atomically. Returns the new record.+ */+export function writeSnooze(offered: string, now: number, channel: ReleaseChannel = currentReleaseChannel() ?? DEFAULT_RELEASE_CHANNEL): SnoozeRecord {+ const existing = readSnooze(channel);+ const level = existing ? Math.min(existing.level + 1, SNOOZE_DURATIONS_MS.length) : 1;+ const record = { version: offered, level, ts: now, until: now + snoozeDurationMs(level) };+ atomicWrite(snoozePath(channel), JSON.stringify(record) + '\n');+ return record;+}++/** Clear one channel's snooze, or every channel's (after an upgrade). */+export function clearSnooze(channel?: ReleaseChannel): void {+ for (const c of channel ? [channel] : RELEASE_CHANNELS) unlinkQuiet(snoozePath(c));+ if (!channel) unlinkQuiet(gbrainPath(LEGACY_SNOOZE_FILE));}// ── Refresh single-flight (anti-stampede) ────────────────────────────────────@@ -462,9 +614,9 @@ export function clearSnooze(): void {* success (caller must release it), or null if another process holds it.* Separate from the upgrade mutex.*/-export function tryAcquireRefreshLock(opts?: Pick<PackLockOpts, 'now' | 'isPidAlive'>): string | null {+export function tryAcquireRefreshLock(opts?: Pick<PackLockOpts, 'now' | 'isPidAlive'>, channel: ReleaseChannel = currentReleaseChannel() ?? DEFAULT_RELEASE_CHANNEL): string | null {try {- const { lockPath } = acquirePackLock('update-refresh', {+ const { lockPath } = acquirePackLock(`update-refresh-${channel}`, {lockDir: locksDir(),ttlMs: 30_000,...opts,@@ -535,7 +687,8 @@ export function readSwapReceipt(path: string): SwapReceipt | null {/** The mutable slice of `config.self_upgrade` the autopilot channel manages. */export interface SelfUpgradeState {mode?: SelfUpgradeMode;- channel?: ReleaseChannel;+ /** Stored as written; `latest` (the pre-alpha name) reads as alpha. */+ channel?: ReleaseChannel | 'latest';mode_prompted?: boolean;quiet_hours?: { start?: number; end?: number; tz?: string };failed_versions?: string[];@@ -759,7 +912,7 @@ export function parseSelfUpgradeConfigValue(leaf: SelfUpgradeConfigLeaf, raw: st}case 'channel': {const channel = normalizeChannel(raw.trim());- return channel ? { ok: true, value: channel } : { ok: false, error: `must be latest or stable (got '${raw}')` };+ return channel ? { ok: true, value: channel } : { ok: false, error: `must be ${VALID_CHANNELS_TEXT} (got '${raw}')` };}case 'mode_prompted': {if (isConfigTruthy(raw)) return { ok: true, value: true };diff --git a/src/core/stable-channel.ts b/src/core/stable-channel.tsindex 70c8a10b1e..af2d5f59a8 100644--- a/src/core/stable-channel.ts+++ b/src/core/stable-channel.ts@@ -1,54 +1,205 @@/**- * 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.+ * The stable release channel on the client side (GBRA-175, GBRA-224 W1).+ *+ * A stable release is accepted only with evidence. scripts/promote-stable.ts moves the annotated `stable` tag and, in+ * the same atomic push, commits the evidence record (`stable.json`) to the `stable-record` branch, so a client reads it+ * at a raw URL with no API call and no git. The record names the version, its commit and tree, the soak run (and,+ * from MATRIX_REQUIRED_FROM on, the upgrade-matrix run) and the `known_bad` list of withdrawn versions. A lookup+ * fails one of three ways, each a typed code: `stable_missing` (nothing promoted), `stable_invalid` (a record or tag+ * that does not describe a release with its evidence) and `stable_unreadable` (could not be read; retry). Nothing is+ * installed on any of them, and the background check never falls back to alpha.*/import { spawnSync } from './spawn.ts';import { gitChildEnv } from './git-env.ts';-import { isNewerVersion } from './semver.ts';-import { normalizeChannel, type ReleaseChannel } from './self-upgrade.ts';+import { isNewerVersion, isValidVersionString } from './semver.ts';+import type { Action } from './agent-output.ts';+import { MATRIX_REQUIRED_FROM, channelSwitchCommand, type ChannelResolution, type StableLookupError } from './self-upgrade.ts';++const GBRAIN_REPO = 'garrytan/gbrain';+const GBRAIN_GIT_URL = `https://github.com/${GBRAIN_REPO}`;+export const STABLE_RECORD_BRANCH = 'stable-record';+export const STABLE_RECORD_FILE = 'stable.json';+export const STABLE_RECORD_URL = `https://raw.githubusercontent.com/${GBRAIN_REPO}/${STABLE_RECORD_BRANCH}/${STABLE_RECORD_FILE}`;+const RECORD_MAX_BYTES = 64 * 1024;+const STABLE_ERRORS_DOCS = 'docs/guides/upgrades-auto-update.md#stable-channel-errors';+const SHA_RE = /^[0-9a-f]{40}$/;+const RUN_URL_RE = /^https:\/\/github\.com\/garrytan\/gbrain\/actions\/runs\/\d+(\/attempts\/\d+)?\/?$/;++export type StableCode = StableLookupError['code'];+export type StableFailure = { ok: false; code: StableCode; cause: string };++export interface StableRecord {+ schema: 1;+ version: string;+ commit: string;+ tree: string;+ soak_run: string;+ matrix_run: string | null;+ promoted_at: string;+ previous: string | null;+ rollback: boolean;+ known_bad: string[];+}-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', env: gitChildEnv(), 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 {+/** `--channel <name>` / `--channel=<name>`: the raw value, '' when the flag has none, null when absent. */+export function parseChannelArg(args: readonly string[]): string | 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';+ if (args[at]!.includes('=')) return args[at]!.slice('--channel='.length);+ const next = args[at + 1];+ return next && !next.startsWith('-') ? next : '';+}++/** Bounded, single-line, credential-free text safe to print and to cache. */+export function sanitizeCause(text: string): string {+ return text+ .replace(/[\s\u0000-\u001f\u007f]+/g, ' ')+ .replace(/(\w+:\/\/)[^\s/@]+@/g, '$1')+ .replace(/\b(gh[pousr]_[A-Za-z0-9]{8,}|github_pat_[A-Za-z0-9_]{8,})\b/g, '[redacted]')+ .trim()+ .slice(0, 200);+}++/** The evidence keys a record for `version` must carry: soak always; the matrix run from `matrixFrom` on. */+export function requiredEvidenceKeys(version: string, matrixFrom: string | null = MATRIX_REQUIRED_FROM): Array<'soak_run' | 'matrix_run'> {+ return matrixFrom && !isNewerVersion(version, matrixFrom) ? ['soak_run', 'matrix_run'] : ['soak_run'];}-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).';+/** Strict parse of the evidence record; the cause names the first thing wrong. */+export function parseStableRecord(body: string, matrixFrom: string | null = MATRIX_REQUIRED_FROM): { ok: true; record: StableRecord } | { ok: false; cause: string } {+ if (body.length > RECORD_MAX_BYTES) return { ok: false, cause: `the record is larger than ${RECORD_MAX_BYTES} bytes` };+ let raw: Record<string, unknown>;+ try {+ raw = JSON.parse(body);+ } catch {+ return { ok: false, cause: 'the record is not JSON' };+ }+ if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return { ok: false, cause: 'the record is not a JSON object' };+ if (raw.schema !== 1) return { ok: false, cause: `unsupported record schema ${JSON.stringify(raw.schema ?? null)}` };+ const version = raw.version;+ if (typeof version !== 'string' || !isValidVersionString(version)) return { ok: false, cause: 'the record has no valid version' };+ for (const key of ['commit', 'tree'] as const) {+ if (typeof raw[key] !== 'string' || !SHA_RE.test(raw[key] as string)) return { ok: false, cause: `the record has no valid ${key}` };+ }+ for (const key of requiredEvidenceKeys(version, matrixFrom)) {+ if (typeof raw[key] !== 'string' || !RUN_URL_RE.test(raw[key] as string)) {+ return { ok: false, cause: `the record for ${version} lacks the evidence key ${key} (a run of ${GBRAIN_REPO})` };+ }+ }+ const knownBad = raw.known_bad ?? [];+ if (!Array.isArray(knownBad) || knownBad.some(v => typeof v !== 'string' || !isValidVersionString(v))) {+ return { ok: false, cause: 'known_bad is not a list of versions' };+ }+ if (knownBad.includes(version)) return { ok: false, cause: `the record lists its own version ${version} as known_bad` };+ return {+ ok: true,+ record: {+ schema: 1,+ version,+ commit: raw.commit as string,+ tree: raw.tree as string,+ soak_run: raw.soak_run as string,+ matrix_run: typeof raw.matrix_run === 'string' ? raw.matrix_run : null,+ promoted_at: typeof raw.promoted_at === 'string' ? raw.promoted_at : '',+ previous: typeof raw.previous === 'string' ? raw.previous : null,+ rollback: raw.rollback === true,+ known_bad: knownBad as string[],+ },+ };+}++/** Fetch and validate the evidence record. 5 s timeout; 404 is stable_missing, any other failure to read is unreadable. */+export async function fetchStableRecord(fetchImpl: typeof fetch = fetch, userAgent = 'gbrain'): Promise<{ ok: true; record: StableRecord } | StableFailure> {+ let res: Response;+ try {+ res = await fetchImpl(STABLE_RECORD_URL, { headers: { 'User-Agent': userAgent }, signal: AbortSignal.timeout(5_000) });+ } catch (e) {+ return { ok: false, code: 'stable_unreadable', cause: sanitizeCause(`fetching the stable record failed: ${e instanceof Error ? e.message : String(e)}`) };+ }+ if (res.status === 404) return { ok: false, code: 'stable_missing', cause: 'no stable record is published (nothing has been promoted to stable)' };+ if (!res.ok) return { ok: false, code: 'stable_unreadable', cause: `the stable record answered HTTP ${res.status}` };+ let body: string;+ try {+ body = await res.text();+ } catch (e) {+ return { ok: false, code: 'stable_unreadable', cause: sanitizeCause(`reading the stable record failed: ${e instanceof Error ? e.message : String(e)}`) };+ }+ const parsed = parseStableRecord(body);+ return parsed.ok ? parsed : { ok: false, code: 'stable_invalid', cause: sanitizeCause(parsed.cause) };}/**- * 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.+ * The release an explicit stable upgrade installs: the record, checked against the repository's tags. The `stable`+ * tag must peel to the record's commit (a mismatch right after a promotion is the raw cache catching up: unreadable,+ * retry) and `v<version>` must be that commit (otherwise the record names no published release: invalid).*/-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' };+export async function resolveStableRelease(deps: { git?: GitRunner; fetch?: typeof fetch } = {}): Promise<{ ok: true; version: string; commit: string; record: StableRecord } | StableFailure> {+ const { status, stdout } = (deps.git ?? runGit)(['ls-remote', '--tags', GBRAIN_GIT_URL]);+ if (status !== 0) return { ok: false, code: 'stable_unreadable', cause: `git ls-remote --tags ${GBRAIN_GIT_URL} failed (offline, or no git)` };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' };+ const stableCommit = peel('stable');+ const fetched = await fetchStableRecord(deps.fetch ?? fetch);+ if (!stableCommit) {+ return fetched.ok || fetched.code !== 'stable_unreadable'+ ? { ok: false, code: 'stable_missing', cause: 'the repository has no stable tag (nothing has been promoted to stable)' }+ : fetched;+ }+ if (!fetched.ok) {+ return fetched.code === 'stable_missing'+ ? { ok: false, code: 'stable_invalid', cause: 'the stable tag exists but has no published evidence record' }+ : fetched;+ }+ const { record } = fetched;+ if (stableCommit !== record.commit) {+ return { ok: false, code: 'stable_unreadable', cause: `the stable tag (${stableCommit.slice(0, 12)}) and the evidence record (${record.commit.slice(0, 12)}) disagree; a promotion may still be propagating` };+ }+ if (peel(`v${record.version}`) !== record.commit) {+ return { ok: false, code: 'stable_invalid', cause: `the record names ${record.version}, but v${record.version} is not the stable commit` };+ }+ return { ok: true, version: record.version, commit: record.commit, record };+}++/** What happened, one sentence. */+export function stableFailureMessage(f: { code: StableCode; cause: string }): string {+ const what = f.code === 'stable_missing' ? 'No release has been promoted to the stable channel yet'+ : f.code === 'stable_invalid' ? 'The stable channel has no usable release: its evidence record does not describe a promoted release'+ : 'The stable channel could not be read';+ return `${what}: ${f.cause}.`;+}++/**+ * The next step, rendered against the precedence that chose stable: retry for unreadable; otherwise wait for a+ * promotion or move this install to alpha with the command that overrides what chose stable.+ */+export function stableFailureFix(f: { code: StableCode }, res: ChannelResolution): string {+ if (f.code === 'stable_unreadable') return 'Nothing was changed. Retry in a few minutes: gbrain self-upgrade --check-only';+ return `Nothing was changed. Wait for a stable promotion, or follow every release on alpha: ${channelSwitchCommand('alpha', res)}`;+}++/**+ * The structured next step for a stable failure (agent operator contract): a read-only retry for unreadable; for+ * missing or invalid, switching to alpha is the user's choice (ask_user), with argv only when a config write is what+ * decides the channel (an env or flag override is changed where it is set).+ */+export function stableFailureAction(f: { code: StableCode }, res: ChannelResolution): Action {+ const verify = { argv: ['gbrain', 'self-upgrade', '--check-only', '--json'] };+ if (f.code === 'stable_unreadable') {+ return { argv: verify.argv, consent: [], actor: 'agent', why: 'Read-only: looks up the stable channel again and reports the channel, its source and any error code.', requires_exclusive: false, verify, docs: STABLE_ERRORS_DOCS };+ }+ const userMessage = `Stable has no usable release right now (${f.code}). Wait for a promotion, or follow every release on alpha: ${channelSwitchCommand('alpha', res)}`;+ const common = { ask_user: true as const, consent: [], why: 'Changes which releases this install follows; the user decides.', user_message: userMessage, requires_exclusive: false, verify, docs: STABLE_ERRORS_DOCS };+ return res.source === 'config' || res.source === 'default'+ ? { ...common, argv: ['gbrain', 'config', 'set', 'self_upgrade.channel', 'alpha'], actor: 'agent' }+ : { ...common, actor: 'user' };}diff --git a/test/autopilot-bun-floor.test.ts b/test/autopilot-bun-floor.test.tsindex e649acc303..6ce0ca3e50 100644--- a/test/autopilot-bun-floor.test.ts+++ b/test/autopilot-bun-floor.test.ts@@ -21,6 +21,7 @@ import { existsSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync,import { tmpdir } from 'node:os';import { join } from 'node:path';import { VERSION } from '../src/version.ts';+import { writeChannelCache } from './helpers/update-cache.ts';const AUTOPILOT_TS = join(import.meta.dir, '..', 'src', 'commands', 'autopilot.ts');const TARGET = '99.0.0.0';@@ -45,9 +46,9 @@ function harness(label: string): Harness {writeFileSync(join(dotG, 'config.json'), JSON.stringify({engine: 'pglite',database_path: join(dotG, 'brain.pglite'),- self_upgrade: { mode: 'auto', quiet_hours: { start: hour, end: (hour + 2) % 24, tz: 'UTC' } },+ self_upgrade: { mode: 'auto', channel: 'alpha', quiet_hours: { start: hour, end: (hour + 2) % 24, tz: 'UTC' } },}));- writeFileSync(join(dotG, 'last-update-check'), `UPGRADE_AVAILABLE ${VERSION} ${TARGET}\n`);+ writeChannelCache(dotG, `UPGRADE_AVAILABLE ${VERSION} ${TARGET}`);const shims = join(root, 'bin');mkdirSync(shims);const argvLog = join(root, 'argv.log');diff --git a/test/autopilot-unpublished-target-6828.test.ts b/test/autopilot-unpublished-target-6828.test.tsindex 1a5d97c74e..ded729cd3f 100644--- a/test/autopilot-unpublished-target-6828.test.ts+++ b/test/autopilot-unpublished-target-6828.test.ts@@ -25,6 +25,7 @@ import { tmpdir } from 'node:os';import { join } from 'node:path';import { parseSemver } from '../src/core/semver.ts';import { VERSION } from '../src/version.ts';+import { writeChannelCache } from './helpers/update-cache.ts';const REPO = join(import.meta.dir, '..');const AUTOPILOT_TS = join(REPO, 'src', 'commands', 'autopilot.ts');@@ -53,9 +54,9 @@ function harness(label: string, opts: { spec?: string; cache?: string } = {}): HwriteFileSync(join(dotG, 'config.json'), JSON.stringify({engine: 'pglite',database_path: join(dotG, 'brain.pglite'),- self_upgrade: { mode: 'auto', quiet_hours: { start: hour, end: (hour + 2) % 24, tz: 'UTC' } },+ self_upgrade: { mode: 'auto', channel: 'alpha', quiet_hours: { start: hour, end: (hour + 2) % 24, tz: 'UTC' } },}));- if (opts.cache) writeFileSync(join(dotG, 'last-update-check'), `${opts.cache}\n`);+ if (opts.cache) writeChannelCache(dotG, opts.cache);const bunInstall = join(root, 'bunhome');const globalRoot = join(bunInstall, 'install', 'global');@@ -148,13 +149,13 @@ async function run(h: Harness, script: string, env: Record<string, string> = {})? readdirSync(auditDir).flatMap((f) => readFileSync(join(auditDir, f), 'utf8').trim().split('\n').filter(Boolean).map((l) => JSON.parse(l))): [];const config = JSON.parse(readFileSync(join(h.home, '.gbrain', 'config.json'), 'utf8'));- const cachePath = join(h.home, '.gbrain', 'last-update-check');+ const cachePath = join(h.home, '.gbrain', 'update-check.alpha.json');return {code, out, err, audit,su: config.self_upgrade,calls: readFileSync(h.argvLog, 'utf8').split('\n').filter(Boolean),fetched: JSON.parse(/FETCHED (.*)/.exec(out)?.[1] ?? '[]') as string[],- cache: existsSync(cachePath) ? readFileSync(cachePath, 'utf8').trim() : null,+ cache: existsSync(cachePath) ? JSON.parse(readFileSync(cachePath, 'utf8')).marker : null,upgradeState: existsSync(join(h.home, '.gbrain', 'upgrade-state.json')),justUpgraded: existsSync(join(h.home, '.gbrain', 'just-upgraded-from')),};diff --git a/test/check-update-refresh.serial.test.ts b/test/check-update-refresh.serial.test.tsindex 9dcfd22445..0eda4db218 100644--- a/test/check-update-refresh.serial.test.ts+++ b/test/check-update-refresh.serial.test.ts@@ -22,6 +22,7 @@ const realFetch = globalThis.fetch;const realLog = console.log;let homeDir: string;let priorHome: string | undefined;+let priorChannel: string | undefined;function bump(kind: 'minor' | 'patch' | 'micro'): string {const v = parseSemver(VERSION)!;@@ -45,6 +46,9 @@ function stubVersionFetch(body: string | null, status = 200): void {beforeEach(() => {priorHome = process.env.GBRAIN_HOME;+ priorChannel = process.env.GBRAIN_RELEASE_CHANNEL;+ // These cases cover the alpha channel (every release, VERSION at latest-stable); stable has its own suites.+ process.env.GBRAIN_RELEASE_CHANNEL = 'alpha';homeDir = mkdtempSync(join(tmpdir(), 'gbrain-refresh-'));process.env.GBRAIN_HOME = homeDir;});@@ -52,6 +56,8 @@ beforeEach(() => {afterEach(() => {globalThis.fetch = realFetch;console.log = realLog;+ if (priorChannel === undefined) delete process.env.GBRAIN_RELEASE_CHANNEL;+ else process.env.GBRAIN_RELEASE_CHANNEL = priorChannel;if (priorHome === undefined) delete process.env.GBRAIN_HOME;else process.env.GBRAIN_HOME = priorHome;rmSync(homeDir, { recursive: true, force: true });@@ -78,22 +84,30 @@ describe('fetchLatestRelease — resolves from the VERSION file, discriminates fexpect(await fetchLatestRelease()).toEqual({ ok: false, reason: 'no_releases' });});- test('GBRA-175: the stable channel reads VERSION at the stable tag, from the argument or self_upgrade.channel', async () => {+ test('GBRA-224: stable reads the evidence record, never a bare VERSION file; alpha (and its alias latest) reads VERSION at latest-stable', async () => {const urls: string[] = [];+ const record = JSON.stringify({ schema: 1, version: '0.99.0.0', commit: 'a'.repeat(40), tree: 'b'.repeat(40), soak_run: 'https://github.com/garrytan/gbrain/actions/runs/1', known_bad: ['0.98.0.0'] });globalThis.fetch = (async (url: any) => {urls.push(String(url));- return new Response(String(url).includes('/gbrain/stable/VERSION') ? '0.99.0.0\n' : '0.99.9.0\n', { status: 200 });+ return new Response(String(url).endsWith('/stable-record/stable.json') ? record : '0.99.9.0\n', { status: 200 });}) as typeof fetch;- expect(await fetchLatestRelease('stable')).toMatchObject({ ok: true, tag: '0.99.0.0' });- expect(await fetchLatestRelease()).toMatchObject({ ok: true, tag: '0.99.9.0' });+ expect(await fetchLatestRelease('stable')).toMatchObject({ ok: true, tag: '0.99.0.0', knownBad: ['0.98.0.0'] });+ expect(await fetchLatestRelease()).toMatchObject({ ok: true, tag: '0.99.9.0', knownBad: [] });+ delete process.env.GBRAIN_RELEASE_CHANNEL;+ expect(await fetchLatestRelease()).toMatchObject({ ok: true, tag: '0.99.0.0' });mkdirSync(join(homeDir, '.gbrain'), { recursive: true });- writeFileSync(join(homeDir, '.gbrain', 'config.json'), JSON.stringify({ engine: 'pglite', database_path: join(homeDir, 'brain.pglite'), self_upgrade: { channel: 'stable' } }));+ writeFileSync(join(homeDir, '.gbrain', 'config.json'), JSON.stringify({ engine: 'pglite', database_path: join(homeDir, 'brain.pglite'), self_upgrade: { channel: 'latest' } }));+ expect(await fetchLatestRelease()).toMatchObject({ ok: true, tag: '0.99.9.0' });+ process.env.GBRAIN_RELEASE_CHANNEL = 'stable';expect(await fetchLatestRelease()).toMatchObject({ ok: true, tag: '0.99.0.0' });expect(urls).toEqual([- 'https://raw.githubusercontent.com/garrytan/gbrain/stable/VERSION',+ 'https://raw.githubusercontent.com/garrytan/gbrain/stable-record/stable.json',+ 'https://raw.githubusercontent.com/garrytan/gbrain/latest-stable/VERSION',+ 'https://raw.githubusercontent.com/garrytan/gbrain/stable-record/stable.json','https://raw.githubusercontent.com/garrytan/gbrain/latest-stable/VERSION',- 'https://raw.githubusercontent.com/garrytan/gbrain/stable/VERSION',+ 'https://raw.githubusercontent.com/garrytan/gbrain/stable-record/stable.json',]);+ expect(urls.some(u => u.includes('/stable/VERSION'))).toBe(false);});});diff --git a/test/e2e/self-upgrade-marker.test.ts b/test/e2e/self-upgrade-marker.test.tsindex ab123da46a..7aa5b3089a 100644--- a/test/e2e/self-upgrade-marker.test.ts+++ b/test/e2e/self-upgrade-marker.test.ts@@ -21,6 +21,7 @@ import { mkdirSync, mkdtempSync, rmSync, writeFileSync, existsSync } from 'node:import { tmpdir } from 'node:os';import { join } from 'node:path';import { VERSION } from '../../src/version.ts';+import { writeChannelCache } from '../helpers/update-cache.ts';let home: string;let gbrainDir: string;@@ -37,7 +38,7 @@ afterEach(() => {});function writeCache(line: string): void {- writeFileSync(join(gbrainDir, 'last-update-check'), line + '\n'); // mtime = now → fresh+ writeChannelCache(gbrainDir, line, { channel: 'stable' }); // checked_at = now → fresh; stable is the default channel}function runGbrain(mode: string | undefined): { stdout: string; stderr: string; code: number } {@@ -106,12 +107,22 @@ describe('self-upgrade marker on a real invocation', () => {test('active snooze for the version → no marker (notify mode honors snooze)', () => {writeCache(`UPGRADE_AVAILABLE ${VERSION} 0.99.0`);- // snooze record: "<version> <level> <epoch-ms>" — fresh ts so it's active.- writeFileSync(join(gbrainDir, 'update-snoozed'), `0.99.0 1 ${Date.now()}\n`);+ const now = Date.now();+ writeFileSync(join(gbrainDir, 'update-snoozed.stable.json'), JSON.stringify({ version: '0.99.0', level: 1, ts: now, until: now + 86_400_000 }) + '\n');const { stderr } = runGbrain('notify');expect(stderr).not.toContain('UPGRADE_AVAILABLE');});+ test('GBRA-224: a legacy unpartitioned cache is never read, and the one-time channel notice prints once', () => {+ writeFileSync(join(gbrainDir, 'last-update-check'), `UPGRADE_AVAILABLE ${VERSION} 0.99.0\n`);+ writeChannelCache(gbrainDir, `UP_TO_DATE ${VERSION}`, { channel: 'stable' });+ const first = runGbrain('notify').stderr;+ expect(first).not.toContain('UPGRADE_AVAILABLE');+ expect(first.split('\n').filter(l => l.startsWith('[gbrain notice release_channel]'))).toHaveLength(1);+ expect(first).toContain('gbrain config set self_upgrade.channel alpha');+ expect(runGbrain('notify').stderr).not.toContain('[gbrain notice release_channel]');+ });+test('JUST_UPGRADED breadcrumb → one-time confirmation on stderr, then cleared', () => {writeCache(`UP_TO_DATE ${VERSION}`);const breadcrumb = join(gbrainDir, 'just-upgraded-from');diff --git a/test/helpers/fresh-brain-snapshot.ts b/test/helpers/fresh-brain-snapshot.tsindex 2a0c70a259..14b58689e5 100644--- a/test/helpers/fresh-brain-snapshot.ts+++ b/test/helpers/fresh-brain-snapshot.ts@@ -10,6 +10,7 @@* - the PGLite datastore directory (binary pages change on any open; its* logical state is the schema/config/row-count part of the snapshot);* - lock files and owner records (rewritten with the opener's pid);+ * - the CLI startup hook's update cache and its one-time channel notice marker;* - Bun's install cache under HOME (not gbrain state).*/import { createHash } from 'node:crypto';@@ -34,7 +35,8 @@ const VOLATILE_FILE = [/(^|\/)\.bun(\/|$)/,/(^|\/)\.capy(\/|$)/,/(^|\/)persistence\/[^/]+\.(cli|stdio|http)\.json$/,- /(^|\/)last-update-check$/,+ /(^|\/)update-check\.[a-z]+\.json$/,+ /(^|\/)notices\/release-channel-stable$/,];function walk(root: string, dir: string, skip: string, out: Record<string, string>): void {diff --git a/test/helpers/update-cache.ts b/test/helpers/update-cache.tsnew file mode 100644index 0000000000..2786d488cc--- /dev/null+++ b/test/helpers/update-cache.ts@@ -0,0 +1,16 @@+/**+ * Test helper (GBRA-224): write one channel's update-check cache in the partitioned format+ * (core/self-upgrade.ts readUpdateCache) without importing the module into a subprocess fixture.+ */+import { mkdirSync, writeFileSync } from 'node:fs';+import { join } from 'node:path';++export function writeChannelCache(gbrainDir: string, markerLine: string | null, opts: { channel?: 'stable' | 'alpha'; latest?: string | null; knownBad?: string[]; checkedAt?: number } = {}): string {+ const channel = opts.channel ?? 'alpha';+ const policy = channel === 'stable' ? 'stable-record-v1;matrix-from=none' : 'alpha-version-file-v1';+ const latest = opts.latest !== undefined ? opts.latest : markerLine?.split(/\s+/)[2] ?? null;+ mkdirSync(gbrainDir, { recursive: true });+ const path = join(gbrainDir, `update-check.${channel}.json`);+ writeFileSync(path, JSON.stringify({ schema: 2, channel, policy, checked_at: opts.checkedAt ?? Date.now(), marker: markerLine, latest, known_bad: opts.knownBad ?? [], error: null }) + '\n');+ return path;+}diff --git a/test/install-ref.test.ts b/test/install-ref.test.tsnew file mode 100644index 0000000000..f1a7149923--- /dev/null+++ b/test/install-ref.test.ts@@ -0,0 +1,56 @@+/**+ * GBRA-224: every install surface routes through one ref, INSTALL_REF (src/core/install-ref.ts).+ */+import { describe, expect, test } from 'bun:test';+import { join } from 'node:path';+import { INSTALL_PIN, INSTALL_RAW_BASE, INSTALL_REF } from '../src/core/install-ref.ts';+import { driftIn, findInstallRefDrift, rewriteText } from '../scripts/check-install-ref.ts';++const ROOT = join(import.meta.dir, '..');++describe('install ref lint', () => {+ test('the constant is latest-stable until a stable-channel release is promoted', () => {+ expect(INSTALL_REF).toBe('latest-stable');+ expect(INSTALL_PIN).toBe('github:garrytan/gbrain#latest-stable');+ expect(INSTALL_RAW_BASE).toBe('https://raw.githubusercontent.com/garrytan/gbrain/latest-stable');+ });++ test('the repository has no install surface off the constant', () => {+ expect(findInstallRefDrift(ROOT).map(d => `${d.file}:${d.line} ${d.found}`)).toEqual([]);+ });++ test('docs: a master or other named pin, or a runbook or helper fetch off the ref, is drift; exact pins are not', () => {+ const doc = [+ 'bun install -g github:garrytan/gbrain#master',+ 'bun install -g github:garrytan/gbrain#stable',+ 'bun add -g github:garrytan/gbrain#v0.60.1.0 and github:garrytan/gbrain#v${VERSION}',+ 'curl https://raw.githubusercontent.com/garrytan/gbrain/master/BOOTSTRAP_FOR_AGENTS.md',+ 'curl https://raw.githubusercontent.com/garrytan/gbrain/main/scripts/setup-in-agent.sh',+ 'read https://raw.githubusercontent.com/garrytan/gbrain/master/INSTALL_FOR_AGENTS.md',+ 'bun install -g github:garrytan/gbrain#latest-stable',+ ].join('\n');+ expect(driftIn('docs/x.md', doc).map(d => [d.line, d.found])).toEqual([+ [1, 'github:garrytan/gbrain#master'],+ [2, 'github:garrytan/gbrain#stable'],+ [4, 'raw.githubusercontent.com/garrytan/gbrain/master/BOOTSTRAP_FOR_AGENTS.md'],+ [5, 'raw.githubusercontent.com/garrytan/gbrain/main/scripts/setup-in-agent.sh'],+ ]);+ expect(driftIn('docs/x.md', doc, 'stable').map(d => d.line).sort()).toEqual([1, 4, 5, 7]);+ expect(driftIn('CHANGELOG.md', doc)).toEqual([]);+ });++ test('TypeScript never spells an install ref; it imports the constant', () => {+ expect(driftIn('src/x.ts', "const a = 'bun install -g github:garrytan/gbrain#latest-stable';")).toHaveLength(1);+ expect(driftIn('src/x.ts', "const u = 'https://raw.githubusercontent.com/garrytan/gbrain/latest-stable/BOOTSTRAP_FOR_AGENTS.md';")).toHaveLength(1);+ expect(driftIn('src/x.ts', 'const a = `github:garrytan/gbrain#v${v}`; const b = INSTALL_PIN;')).toEqual([]);+ });++ test('the setup helper resolves the constant, and --write flips every text surface in one pass', () => {+ expect(driftIn('scripts/setup-in-agent.sh', 'gbrain_install_ref=master\n')).toHaveLength(1);+ const doc = 'github:garrytan/gbrain#latest-stable\nraw.githubusercontent.com/garrytan/gbrain/latest-stable/BOOTSTRAP_FOR_AGENTS.md\ngbrain_install_ref=latest-stable\ngithub:garrytan/gbrain#v1.2.3.4\n';+ const flipped = rewriteText('README.md', doc, 'stable');+ expect(flipped).toBe('github:garrytan/gbrain#stable\nraw.githubusercontent.com/garrytan/gbrain/stable/BOOTSTRAP_FOR_AGENTS.md\ngbrain_install_ref=stable\ngithub:garrytan/gbrain#v1.2.3.4\n');+ expect(driftIn('README.md', flipped, 'stable')).toEqual([]);+ expect(rewriteText('src/x.ts', doc, 'stable')).toBe(doc);+ });+});diff --git a/test/release-channel-w1.serial.test.ts b/test/release-channel-w1.serial.test.tsnew file mode 100644index 0000000000..25fbb70fb0--- /dev/null+++ b/test/release-channel-w1.serial.test.ts@@ -0,0 +1,278 @@+/**+ * GBRA-224 W1: stable and alpha channels with stable as the default (client side).+ *+ * Covers: the evidence record and its generations, the typed stable codes in the background check (report only, never+ * an alpha fallback), the update cache partitioned by channel and evidence policy (legacy entries never read, the+ * warm-cache default flip, reversed refresh completion), never downgrading and the known_bad move, the per-channel+ * time-based snooze across alpha releases and a stable rollback, the one-time channel notice, and the check-only and+ * doctor surfaces. Every flow runs on a repo-less brain and on a repo brain: channel state is file-plane under+ * GBRAIN_HOME and never reads the repository.+ *+ * Serial: stubs globalThis.fetch and process-global env.+ */+import { afterEach, beforeEach, describe, expect, test } from 'bun:test';+import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { spawnSync } from 'node:child_process';+import { VERSION } from '../src/version.ts';+import { parseSemver } from '../src/core/semver.ts';+import {+ STABLE_EVIDENCE_POLICY,+ offeredVersion,+ parseMarker,+ pendingUpgradeVersion,+ readSnooze,+ readUpdateCache,+ snoozeHolds,+ writeSnooze,+ writeUpdateCache,+} from '../src/core/self-upgrade.ts';+import { STABLE_RECORD_URL, fetchStableRecord, parseStableRecord, requiredEvidenceKeys, sanitizeCause } from '../src/core/stable-channel.ts';+import { refreshUpdateCache } from '../src/commands/check-update.ts';+import { runSelfUpgrade } from '../src/commands/self-upgrade.ts';+import { CHANNEL_NOTICE_TEXT, maybeEmitChannelNotice } from '../src/core/release-channel-notice.ts';+import { checkSelfUpgradeHealth } from '../src/commands/doctor/checks/upgrade-health.ts';++const v = parseSemver(VERSION)!;+const AHEAD = `${v[0]}.${v[1]}.${v[2] + 5}.0`;+const AHEAD2 = `${v[0]}.${v[1]}.${v[2] + 9}.0`;+const BEHIND = `${v[0]}.${v[1]}.${Math.max(0, v[2] - 5)}.0`;+const SOAK = 'https://github.com/garrytan/gbrain/actions/runs/42';+const MATRIX = 'https://github.com/garrytan/gbrain/actions/runs/43';+const record = (version: string, over: Record<string, unknown> = {}) => JSON.stringify({ schema: 1, channel: 'stable', version, commit: 'a'.repeat(40), tree: 'b'.repeat(40), soak_run: SOAK, known_bad: [], ...over });++const realFetch = globalThis.fetch;+const realLog = console.log;+let home: string;+let saved: Record<string, string | undefined>;+let fetched: string[];++function serve(routes: { record?: string | null; recordStatus?: number; version?: string }): void {+ fetched = [];+ globalThis.fetch = (async (url: unknown) => {+ const u = String(url);+ fetched.push(u);+ if (u === STABLE_RECORD_URL) {+ if (routes.record === null) throw new Error('getaddrinfo ENOTFOUND raw.githubusercontent.com');+ return new Response(routes.record ?? 'Not Found', { status: routes.record === undefined ? 404 : routes.recordStatus ?? 200 });+ }+ if (u.endsWith('/latest-stable/VERSION')) return new Response(`${routes.version ?? AHEAD2}\n`);+ return new Response('', { status: 200 });+ }) as typeof fetch;+}++const dotG = () => join(home, '.gbrain');+function writeConfig(extra: Record<string, unknown> = {}, brain: 'repo-less' | 'repo' = 'repo-less'): void {+ mkdirSync(dotG(), { recursive: true });+ const base: Record<string, unknown> = { engine: 'pglite', database_path: join(home, 'brain.pglite') };+ if (brain === 'repo') {+ const repo = join(home, 'brain-repo');+ mkdirSync(repo, { recursive: true });+ spawnSync('git', ['init', '-q', repo]);+ base.sync = { repo_path: repo };+ }+ writeFileSync(join(dotG(), 'config.json'), JSON.stringify({ ...base, ...extra }));+}++beforeEach(() => {+ saved = { GBRAIN_HOME: process.env.GBRAIN_HOME, GBRAIN_RELEASE_CHANNEL: process.env.GBRAIN_RELEASE_CHANNEL, GBRAIN_SELF_UPGRADE_MODE: process.env.GBRAIN_SELF_UPGRADE_MODE };+ home = mkdtempSync(join(tmpdir(), 'gbrain-w1-'));+ process.env.GBRAIN_HOME = home;+ delete process.env.GBRAIN_RELEASE_CHANNEL;+ delete process.env.GBRAIN_SELF_UPGRADE_MODE;+});++afterEach(() => {+ globalThis.fetch = realFetch;+ console.log = realLog;+ for (const [k, val] of Object.entries(saved)) { if (val === undefined) delete process.env[k]; else process.env[k] = val; }+ rmSync(home, { recursive: true, force: true });+});++describe('evidence record generations', () => {+ test('generation 1 (soak only) is valid until the matrix cutover; from the cutover on matrix_run is required', () => {+ expect(STABLE_EVIDENCE_POLICY).toBe('stable-record-v1;matrix-from=none');+ expect(requiredEvidenceKeys('0.60.900.0')).toEqual(['soak_run']);+ expect(parseStableRecord(record('0.60.900.0'))).toMatchObject({ ok: true });+ const cut = '0.60.500.0';+ expect(requiredEvidenceKeys('0.60.499.0', cut)).toEqual(['soak_run']);+ expect(requiredEvidenceKeys('0.60.500.0', cut)).toEqual(['soak_run', 'matrix_run']);+ expect(parseStableRecord(record('0.60.499.0'), cut)).toMatchObject({ ok: true, record: { matrix_run: null } });+ expect(parseStableRecord(record('0.60.500.0'), cut)).toEqual({ ok: false, cause: 'the record for 0.60.500.0 lacks the evidence key matrix_run (a run of garrytan/gbrain)' });+ expect(parseStableRecord(record('0.60.501.0', { matrix_run: MATRIX }), cut)).toMatchObject({ ok: true, record: { matrix_run: MATRIX } });+ });++ test('a record is rejected for a missing or foreign soak run, bad commit or tree, bad known_bad, or listing itself as known_bad', () => {+ for (const over of [{ soak_run: undefined }, { soak_run: 'https://github.com/acme-example/gbrain/actions/runs/1' }, { commit: 'abc' }, { tree: undefined }, { known_bad: 'x' }, { known_bad: ['0.60.900.0'] }, { schema: 2 }]) {+ expect(parseStableRecord(record('0.60.900.0', over)).ok).toBe(false);+ }+ expect(parseStableRecord('not json')).toEqual({ ok: false, cause: 'the record is not JSON' });+ });++ test('fetch: 404 is stable_missing, other statuses and network failures stable_unreadable, a bad body stable_invalid; causes are sanitized', async () => {+ serve({});+ expect(await fetchStableRecord()).toMatchObject({ ok: false, code: 'stable_missing' });+ serve({ record: 'x', recordStatus: 500 });+ expect(await fetchStableRecord()).toMatchObject({ ok: false, code: 'stable_unreadable', cause: 'the stable record answered HTTP 500' });+ serve({ record: null });+ expect(await fetchStableRecord()).toMatchObject({ ok: false, code: 'stable_unreadable' });+ serve({ record: '{"schema":1}' });+ expect(await fetchStableRecord()).toMatchObject({ ok: false, code: 'stable_invalid' });+ expect(sanitizeCause('fetch https://user:[email protected]/x failed\n token ghp_ABCDEFGHIJKLMNOP')).toBe('fetch https://example.com/x failed token [redacted]');+ expect(sanitizeCause('x'.repeat(500))).toHaveLength(200);+ });+});++for (const brain of ['repo-less', 'repo'] as const) {+ describe(`background check and cache (${brain} brain)`, () => {+ test('the default is stable: the check reads only the evidence record and writes the stable partition', async () => {+ writeConfig({}, brain);+ serve({ record: record(AHEAD) });+ await refreshUpdateCache();+ expect(fetched).toEqual([STABLE_RECORD_URL]);+ expect(readUpdateCache('stable')).toMatchObject({ channel: 'stable', policy: STABLE_EVIDENCE_POLICY, latest: AHEAD, marker: { kind: 'upgrade_available', latest: AHEAD }, error: null });+ expect(readUpdateCache('alpha')).toBeNull();+ expect(pendingUpgradeVersion(VERSION)).toBe(AHEAD);+ });++ test('missing, invalid and unreadable stable are recorded and reported, never offered and never replaced by alpha', async () => {+ writeConfig({}, brain);+ serve({ record: record(AHEAD) });+ await refreshUpdateCache();+ serve({ record: null });+ await refreshUpdateCache();+ expect(readUpdateCache('stable')).toMatchObject({ error: { code: 'stable_unreadable' }, marker: { latest: AHEAD } });+ serve({});+ await refreshUpdateCache();+ expect(readUpdateCache('stable')).toMatchObject({ error: { code: 'stable_missing' }, marker: null, latest: null });+ expect(pendingUpgradeVersion(VERSION)).toBeNull();+ serve({ record: record(AHEAD, { soak_run: undefined }) });+ await refreshUpdateCache();+ expect(readUpdateCache('stable')).toMatchObject({ error: { code: 'stable_invalid', cause: expect.stringContaining('soak_run') } });+ expect(fetched.some(u => u.includes('latest-stable'))).toBe(false);+ expect(readUpdateCache('alpha')).toBeNull();+ });++ test('warm-cache default flip: a legacy unpartitioned cache from the old latest default is never read', async () => {+ writeConfig({}, brain);+ writeFileSync(join(dotG(), 'last-update-check'), `UPGRADE_AVAILABLE ${VERSION} ${AHEAD2}\n`);+ writeFileSync(join(dotG(), 'update-snoozed'), `${AHEAD2} 1 ${Date.now()}\n`);+ expect(readUpdateCache()).toBeNull();+ expect(pendingUpgradeVersion(VERSION)).toBeNull();+ serve({ record: record(AHEAD) });+ await refreshUpdateCache();+ expect(pendingUpgradeVersion(VERSION)).toBe(AHEAD);+ expect(existsSync(join(dotG(), 'last-update-check'))).toBe(false);+ });++ test('partitions: switching channel reads that channel\'s answer; another policy\'s entry is invalid; an older refresh never overwrites a newer one', async () => {+ writeConfig({}, brain);+ writeUpdateCache({ kind: 'upgrade_available', current: VERSION, latest: AHEAD }, { channel: 'stable', checkedAt: 2_000 });+ writeUpdateCache({ kind: 'upgrade_available', current: VERSION, latest: AHEAD2 }, { channel: 'alpha', checkedAt: 2_000 });+ expect(pendingUpgradeVersion(VERSION)).toBe(AHEAD);+ process.env.GBRAIN_RELEASE_CHANNEL = 'latest';+ expect(pendingUpgradeVersion(VERSION)).toBe(AHEAD2);+ delete process.env.GBRAIN_RELEASE_CHANNEL;+ writeConfig({ self_upgrade: { channel: 'alpha' } }, brain);+ expect(pendingUpgradeVersion(VERSION)).toBe(AHEAD2);+ writeUpdateCache({ kind: 'up_to_date', current: VERSION }, { channel: 'alpha', checkedAt: 1_000 });+ expect(readUpdateCache('alpha')?.latest).toBe(AHEAD2);+ const path = join(dotG(), 'update-check.stable.json');+ writeFileSync(path, readFileSync(path, 'utf8').replace(STABLE_EVIDENCE_POLICY, 'stable-record-v1;matrix-from=0.60.1.0'));+ expect(readUpdateCache('stable')).toBeNull();+ });++ test('an invalid configured channel checks and offers nothing', async () => {+ writeConfig({ self_upgrade: { channel: 'nightly' } }, brain);+ writeUpdateCache({ kind: 'upgrade_available', current: VERSION, latest: AHEAD }, { channel: 'stable' });+ serve({ record: record(AHEAD2) });+ await refreshUpdateCache();+ expect(fetched).toEqual([]);+ expect(pendingUpgradeVersion(VERSION)).toBeNull();+ });++ test('never downgrade: an install ahead of stable is offered nothing until stable passes it; a withdrawn install is offered stable', async () => {+ writeConfig({}, brain);+ expect(offeredVersion(VERSION, BEHIND, [])).toBeNull();+ expect(offeredVersion(VERSION, VERSION, [VERSION])).toBeNull();+ expect(offeredVersion(VERSION, BEHIND, [VERSION])).toBe(BEHIND);+ serve({ record: record(BEHIND) });+ await refreshUpdateCache();+ expect(pendingUpgradeVersion(VERSION)).toBeNull();+ serve({ record: record(BEHIND, { known_bad: [VERSION] }) });+ await refreshUpdateCache();+ expect(readUpdateCache('stable')).toMatchObject({ latest: BEHIND, knownBad: [VERSION], marker: { kind: 'upgrade_available', latest: BEHIND } });+ expect(pendingUpgradeVersion(VERSION)).toBe(BEHIND);+ });++ test('snooze holds its full window across any number of alpha releases; a stable rollback below the snoozed version clears it', () => {+ writeConfig({}, brain);+ const now = Date.now();+ writeSnooze(AHEAD, now, 'alpha');+ for (let i = 1; i <= 30; i++) expect(snoozeHolds(`${v[0]}.${v[1]}.${v[2] + 5 + i}.0`, now + i * 3_600_000 * 0.7, 'alpha')).toBe(true);+ expect(snoozeHolds(AHEAD2, now + 25 * 3_600_000, 'alpha')).toBe(false);+ writeSnooze(AHEAD2, now, 'stable');+ expect(snoozeHolds(AHEAD2, now + 1000, 'stable')).toBe(true);+ expect(snoozeHolds(AHEAD, now + 2000, 'stable')).toBe(false);+ expect(readSnooze('stable')).toBeNull();+ expect(readSnooze('alpha')).not.toBeNull();+ });++ test('the one-time notice prints once per GBRAIN_HOME on stderr, never as a marker, never under --json or MCP, and not when a channel was chosen', () => {+ writeConfig({}, brain);+ const lines: string[] = [];+ const write = (l: string) => { lines.push(l); };+ expect(maybeEmitChannelNotice({ command: 'search', args: ['search', 'x', '--json'], cfg: null, write })).toBe(false);+ expect(maybeEmitChannelNotice({ command: 'serve', args: ['serve'], cfg: null, write })).toBe(false);+ expect(maybeEmitChannelNotice({ command: 'mcp', args: ['mcp'], cfg: null, write })).toBe(false);+ expect(maybeEmitChannelNotice({ command: 'search', args: ['search'], cfg: { self_upgrade: { channel: 'stable' } }, write })).toBe(false);+ expect(maybeEmitChannelNotice({ command: 'search', args: ['search'], cfg: null, env: 'alpha', write })).toBe(false);+ expect(lines).toEqual([]);+ expect(maybeEmitChannelNotice({ command: 'search', args: ['search'], cfg: null, write })).toBe(true);+ expect(maybeEmitChannelNotice({ command: 'query', args: ['query'], cfg: null, write })).toBe(false);+ expect(lines).toEqual([`${CHANNEL_NOTICE_TEXT}\n`]);+ expect(lines[0]).toStartWith('[gbrain notice release_channel] ');+ expect(lines[0]).toContain('stable channel');+ expect(lines[0]).toContain('gbrain config set self_upgrade.channel alpha');+ expect(parseMarker(lines[0]!)).toBeNull();+ expect(lines[0]).not.toContain('UPGRADE_AVAILABLE');+ });++ test('self-upgrade --check-only --json names the channel, its source and the typed error; --snooze writes the channel snooze', async () => {+ writeConfig({}, brain);+ const out: string[] = [];+ console.log = (...a: unknown[]) => { out.push(a.join(' ')); };+ serve({});+ await runSelfUpgrade(['--check-only', '--json']);+ expect(JSON.parse(out.pop()!)).toMatchObject({ channel: 'stable', channel_source: 'default', update_available: false, error: { code: 'stable_missing', fix: expect.stringContaining('gbrain config set self_upgrade.channel alpha') } });+ serve({ record: record(BEHIND, { known_bad: [VERSION] }) });+ await runSelfUpgrade(['--check-only', '--json']);+ expect(JSON.parse(out.pop()!)).toMatchObject({ channel: 'stable', update_available: true, latest_version: BEHIND, withdrawn: true });+ serve({ record: record(AHEAD) });+ await runSelfUpgrade(['--check-only', '--json', '--channel', 'latest']);+ expect(JSON.parse(out.pop()!)).toMatchObject({ channel: 'alpha', channel_source: 'flag', latest_version: AHEAD2 });+ serve({ record: record(AHEAD) });+ await runSelfUpgrade(['--check-only', '--json']);+ await runSelfUpgrade(['--snooze', '--json']);+ expect(JSON.parse(out.pop()!)).toMatchObject({ snoozed: true, channel: 'stable', version: AHEAD, level: 1 });+ expect(readSnooze('stable')).toMatchObject({ version: AHEAD, level: 1 });+ });++ test('doctor names the effective channel and its source, and warns with the code when stable failed', async () => {+ writeConfig({}, brain);+ expect(checkSelfUpgradeHealth().message).toContain('channel=stable (default)');+ process.env.GBRAIN_RELEASE_CHANNEL = 'latest';+ expect(checkSelfUpgradeHealth().message).toContain('channel=alpha (env)');+ delete process.env.GBRAIN_RELEASE_CHANNEL;+ serve({});+ await refreshUpdateCache();+ const failing = checkSelfUpgradeHealth();+ expect(failing.status).toBe('warn');+ expect(failing.message).toContain('stable_missing');+ expect(failing.message).toContain('gbrain config set self_upgrade.channel alpha');+ writeConfig({ self_upgrade: { channel: 'nightly' } }, brain);+ expect(checkSelfUpgradeHealth()).toMatchObject({ status: 'warn', message: expect.stringContaining("self_upgrade.channel is 'nightly'") });+ });+ });+}diff --git a/test/scripts/promote-stable.test.ts b/test/scripts/promote-stable.test.tsindex 6d7f28cf84..b5623cc5ca 100644--- a/test/scripts/promote-stable.test.ts+++ b/test/scripts/promote-stable.test.ts@@ -19,9 +19,10 @@ import { tmpdir } from 'node:os';import { join } from 'node:path';import { load } from 'js-yaml';import {- checkOrder, checkSoakRun, compareVersions, normaliseWorkflowPath, parseRunUrl, processDeps, promote, Refusal, renderSummary, renderTagMessage,+ checkOrder, checkSoakRun, compareVersions, mergeKnownBad, normaliseWorkflowPath, parseRunUrl, processDeps, promote, Refusal, renderRecord, renderSummary, renderTagMessage,type GitResult, type PromoteDeps, type PromoteInputs, type SoakRun, type TagFields,} from '../../scripts/promote-stable.ts';+import { parseStableRecord } from '../../src/core/stable-channel.ts';const ROOT = join(import.meta.dir, '..', '..');const REPO = 'garrytan/gbrain';@@ -49,6 +50,10 @@ interface FakeRepo {/** What `git show v<version>:VERSION` prints; default: the tag's own version. */versionFile?: string;failPush?: boolean;+ /** Evidence record commits (stable-record branch history): commit → stable.json content. */+ records?: Record<string, string>;+ /** The remote stable-record branch head (fetched into refs/remotes/origin/stable-record); absent before the first promotion. */+ recordBranch?: string;}const ok = (stdout = ''): GitResult => ({ code: 0, stdout: `${stdout}\n`, stderr: '' });@@ -62,9 +67,19 @@ function fakeGit(repo: FakeRepo, calls: string[]) {if (tag) return { commit: tag.commit, object: tag.object ?? tag.commit };return repo.commits[spec] ? { commit: spec, object: spec } : null;};- return async (args: string[]): Promise<GitResult> => {+ const blobs: Record<string, string> = {};+ const trees: Record<string, string> = {};+ return async (args: string[], input?: string): Promise<GitResult> => {calls.push(args.join(' '));const [cmd, ...rest] = args;+ if (cmd === 'hash-object') { const id = `blob-${++objects}`; blobs[id] = input ?? ''; return ok(id); }+ if (cmd === 'mktree') { const id = `tree-${++objects}`; trees[id] = /blob (\S+) stable\.json/.exec(input ?? '')![1]!; return ok(id); }+ if (cmd === 'commit-tree') { const id = `rec-${++objects}`; (repo.records ??= {})[id] = blobs[trees[rest[0]!]!]!; return ok(id); }+ if (cmd === 'rev-parse' && rest.at(-1) === 'refs/remotes/origin/stable-record^{commit}') return repo.recordBranch ? ok(repo.recordBranch) : fail;+ if (cmd === 'show' && rest[0]!.endsWith(':stable.json')) {+ const body = repo.records?.[rest[0]!.replace(/:stable\.json$/, '')];+ return body === undefined ? fail : ok(body);+ }if (cmd === 'rev-parse') {const spec = rest.at(-1)!;const m = /^(.*?)(\^\{(commit|tree)\})?$/.exec(spec)!;@@ -84,12 +99,19 @@ function fakeGit(repo: FakeRepo, calls: string[]) {return ok();}if (cmd === 'push') {- const names = rest.filter(a => a.includes(':') && !a.startsWith('--')).map(r => r.split(':')[0]!.replace(/^refs\/tags\//, ''));- const lease = rest.find(a => a.startsWith('--force-with-lease='));+ const refspecs = rest.filter(a => a.includes(':') && !a.startsWith('--'));+ const lease = rest.find(a => a.startsWith('--force-with-lease=refs/tags/stable:'));+ const recordLease = rest.find(a => a.startsWith('--force-with-lease=refs/heads/stable-record:'));repo.remote ??= {};if (repo.failPush) return { code: 1, stdout: '', stderr: 'fatal: the remote end hung up unexpectedly' };if (lease && lease.split(':').at(-1) !== (repo.remote.stable ?? '')) return { code: 1, stdout: '', stderr: '! [rejected] stable -> stable (stale info)' };- for (const name of names) repo.remote[name] = repo.tags[name]!.object!;+ if (recordLease && recordLease.split(':').at(-1) !== (repo.recordBranch ?? '')) return { code: 1, stdout: '', stderr: '! [rejected] stable-record -> stable-record (stale info)' };+ for (const spec of refspecs) {+ const [src, dst] = spec.split(':') as [string, string];+ if (dst === 'refs/heads/stable-record') { repo.recordBranch = src; continue; }+ const name = src.replace(/^refs\/tags\//, '');+ repo.remote[name] = repo.tags[name]!.object!;+ }return ok();}if (cmd === 'show') {@@ -233,8 +255,8 @@ describe('tag message and summary', () => {});test('the step summary names version, commit, tree, soak run, scoreboard, previous and rollback', () => {- const md = renderSummary({ ...fields, rollback: true, reason: 'a | b', recordCreated: false });- for (const part of ['## Stable channel: v0.60.361.0', sha('b'), sha('2'), RUN_URL, 'https://example.com/scoreboard', 'v0.60.360.0', 'yes: a \\| b', 'already existed']) expect(md).toContain(part);+ const md = renderSummary({ ...fields, rollback: true, reason: 'a | b', recordCreated: false, knownBad: ['0.60.359.0'] });+ for (const part of ['## Stable channel: v0.60.361.0', sha('b'), sha('2'), RUN_URL, 'https://example.com/scoreboard', 'v0.60.360.0', 'yes: a \\| b', 'already existed', 'v0.60.359.0']) expect(md).toContain(part);});});@@ -246,8 +268,9 @@ describe('promote', () => {expect(h.api).toEqual([`repos/${REPO}/collaborators/alice-example/permission`, `repos/${REPO}/releases/tags/v0.60.361.0`, `repos/${REPO}/actions/runs/123456`]);const pushes = h.calls.filter(c => c.startsWith('push'));expect(pushes).toEqual([- 'push --atomic --force-with-lease=refs/tags/stable:tagobj-stable-old origin refs/tags/stable-v0.60.361.0:refs/tags/stable-v0.60.361.0 refs/tags/stable:refs/tags/stable',+ `push --atomic --force-with-lease=refs/tags/stable:tagobj-stable-old --force-with-lease=refs/heads/stable-record: origin refs/tags/stable-v0.60.361.0:refs/tags/stable-v0.60.361.0 refs/tags/stable:refs/tags/stable ${h.repo.recordBranch}:refs/heads/stable-record`,]);+ expect(JSON.parse(h.repo.records![h.repo.recordBranch!]!)).toEqual(JSON.parse(renderRecord(p, [])));expect(h.repo.tags['stable-v0.60.361.0']!.commit).toBe(sha('b'));expect(h.repo.tags.stable!.commit).toBe(sha('b'));expect(h.repo.tags.stable!.message).toBe(renderTagMessage(p));@@ -263,7 +286,7 @@ describe('promote', () => {expect(h.api[2]).toBe(`repos/${REPO}/actions/runs/123456/attempts/2`);expect(p.previous).toBeNull();expect(p.scoreboard).toBe('https://example.com/board');- expect(h.calls.at(-1)).toBe('push --atomic --force-with-lease=refs/tags/stable: origin refs/tags/stable-v0.60.361.0:refs/tags/stable-v0.60.361.0 refs/tags/stable:refs/tags/stable');+ expect(h.calls.at(-1)).toBe(`push --atomic --force-with-lease=refs/tags/stable: --force-with-lease=refs/heads/stable-record: origin refs/tags/stable-v0.60.361.0:refs/tags/stable-v0.60.361.0 refs/tags/stable:refs/tags/stable ${h.repo.recordBranch}:refs/heads/stable-record`);});test('admins pass; write, triage and read collaborators are refused before anything else is read', async () => {@@ -308,7 +331,7 @@ describe('promote', () => {const repo: FakeRepo = { commits: { [sha('b')]: sha('2') }, tags: { 'v0.60.361.0': { commit: sha('b') } } };const h = harness({ repo, run: { status: 'completed', conclusion: 'success', path: SOAK, head_sha: sha('d') } });const git = h.deps.git;- h.deps.git = async args => { if (args[0] === 'fetch') repo.commits[sha('d')] = sha('2'); return git(args); };+ h.deps.git = async (args, input) => { if (args[0] === 'fetch') repo.commits[sha('d')] = sha('2'); return git(args, input); };await promote(h.deps, inputs());expect(h.calls).toContain(`fetch --no-tags origin ${sha('d')}`);});@@ -325,7 +348,7 @@ describe('promote', () => {expect(p).toMatchObject({ previous: '0.60.361.0', rollback: true, recordCreated: false });expect(back.repo.tags.stable!.commit).toBe(sha('a'));expect(back.repo.tags.stable!.message).toContain('rollback: true\nreason: sync regression\n');- expect(back.calls.filter(c => c.startsWith('push'))).toEqual(['push --atomic --force-with-lease=refs/tags/stable:tagobj-stable-old origin refs/tags/stable:refs/tags/stable']);+ expect(back.calls.filter(c => c.startsWith('push'))).toEqual([`push --atomic --force-with-lease=refs/tags/stable:tagobj-stable-old --force-with-lease=refs/heads/stable-record: origin refs/tags/stable:refs/tags/stable ${back.repo.recordBranch}:refs/heads/stable-record`]);expect(back.repo.tags['stable-v0.60.360.0']!.object).toBe('tagobj-record-360');});@@ -361,6 +384,50 @@ describe('promote', () => {});});+describe('evidence record (GBRA-224 W1)', () => {+ test('the record a promotion writes is the generation-1 shape the client accepts (soak evidence, no matrix run)', async () => {+ const h = harness();+ const p = await promote(h.deps, inputs());+ const body = h.repo.records![h.repo.recordBranch!]!;+ expect(parseStableRecord(body)).toMatchObject({ ok: true, record: { schema: 1, version: '0.60.361.0', commit: sha('b'), tree: sha('2'), soak_run: RUN_URL, matrix_run: null, previous: '0.60.360.0', known_bad: [] } });+ expect(JSON.parse(body)).toMatchObject({ channel: 'stable', promoted_by: 'alice-example', promoted_at: p.promotedAt });+ expect(h.calls.some(c => c.startsWith('commit-tree ') && c.endsWith(' -m stable record: v0.60.361.0') && !c.includes(' -p '))).toBe(true);+ });++ test('known_bad carries forward from the previous record, gains this run\'s withdrawals and is parented on the previous record', async () => {+ const h = harness();+ h.repo.records = { 'rec-prior': JSON.stringify({ schema: 1, version: '0.60.360.0', known_bad: ['0.60.300.0'] }) };+ h.repo.recordBranch = 'rec-prior';+ const p = await promote(h.deps, inputs({ withdraw: ['0.60.355.0', '0.60.300.0'] }));+ expect(p.knownBad).toEqual(['0.60.300.0', '0.60.355.0']);+ expect(JSON.parse(h.repo.records![h.repo.recordBranch!]!).known_bad).toEqual(['0.60.300.0', '0.60.355.0']);+ expect(h.calls.some(c => c.startsWith('commit-tree') && c.includes('-p rec-prior'))).toBe(true);+ expect(h.calls.filter(c => c.startsWith('push'))[0]).toContain('--force-with-lease=refs/heads/stable-record:rec-prior');+ });++ test('refuses promoting a withdrawn version, a malformed withdrawal and an unreadable previous record, before anything moves', async () => {+ refused(() => mergeKnownBad(['0.60.361.0'], [], '0.60.361.0'), /known_bad list \(withdrawn\)/);+ refused(() => mergeKnownBad([], ['0.60.x'], '0.60.361.0'), /withdraw entry "0\.60\.x" is not a release version/);+ await refusedAsync(promote(harness().deps, inputs({ withdraw: ['0.60.361.0'] })), /known_bad list/);+ const corrupt = harness();+ corrupt.repo.records = { 'rec-prior': 'not json' };+ corrupt.repo.recordBranch = 'rec-prior';+ await refusedAsync(promote(corrupt.deps, inputs()), /previous stable record .* is not JSON/);+ expect(corrupt.calls.filter(c => c.startsWith('push'))).toEqual([]);+ });++ test('a record branch moved by someone else after it was read loses the lease and nothing changes', async () => {+ const h = harness();+ const git = h.deps.git;+ h.deps.git = async (args, input) => {+ if (args[0] === 'push') h.repo.recordBranch = 'rec-someone-else';+ return git(args, input);+ };+ await refusedAsync(promote(h.deps, inputs()), /Moving the stable tag failed.*re-run this workflow/);+ expect(h.repo.remote).toEqual({ stable: 'tagobj-stable-old', 'stable-v0.60.360.0': 'tagobj-record-360' });+ });+});+describe('promote against real git', () => {const git = (cwd: string, ...args: string[]) => {const r = spawnSync('git', args, { cwd, encoding: 'utf8', env: { ...process.env, GIT_CONFIG_NOSYSTEM: '1', GIT_TERMINAL_PROMPT: '0' } });@@ -409,10 +476,16 @@ describe('promote against real git', () => {expect(remote).toContain('refs/tags/stable-v1.0.0');expect(remote).toContain('refs/tags/stable-v1.0.1');+ const readRecord = () => parseStableRecord(git(dir, '--git-dir', origin, 'show', 'refs/heads/stable-record:stable.json'));+ expect(readRecord()).toMatchObject({ ok: true, record: { version: '1.0.1', commit: git(work, 'rev-parse', 'v1.0.1^{commit}'), tree: git(work, 'rev-parse', 'v1.0.1^{tree}'), soak_run: RUN_URL, previous: '1.0.0', known_bad: [] } });+const record = git(work, 'rev-parse', 'refs/tags/stable-v1.0.0');- await promote(deps('1.0.0'), inputs({ version: '1.0.0', rollback: true, reason: 'regression' }));+ await promote(deps('1.0.0'), inputs({ version: '1.0.0', rollback: true, reason: 'regression', withdraw: ['1.0.1'] }));expect(git(work, 'ls-remote', origin, 'refs/tags/stable^{}').split('\t')[0]).toBe(git(work, 'rev-parse', 'v1.0.0^{commit}'));expect(git(work, 'ls-remote', origin, 'refs/tags/stable-v1.0.0').split('\t')[0]).toBe(record);+ // The evidence record moved with the tag, in the same push, and carries the withdrawal; its history is the audit log.+ expect(readRecord()).toMatchObject({ ok: true, record: { version: '1.0.0', rollback: true, known_bad: ['1.0.1'] } });+ expect(git(dir, '--git-dir', origin, 'rev-list', '--count', 'refs/heads/stable-record')).toBe('3');} finally {rmSync(dir, { recursive: true, force: true });}@@ -431,7 +504,8 @@ describe('promote-stable.yml', () => {test('dispatch only, with the decided inputs, one serial group and scoped permissions', () => {expect(Object.keys(wf.on)).toEqual(['workflow_dispatch']);const i = wf.on.workflow_dispatch!.inputs;- expect(Object.keys(i)).toEqual(['version', 'soak_run_url', 'scoreboard_url', 'rollback', 'reason']);+ expect(Object.keys(i)).toEqual(['version', 'soak_run_url', 'scoreboard_url', 'rollback', 'reason', 'withdraw']);+ expect(i.withdraw).toMatchObject({ required: false, type: 'string', default: '' });expect([i.version!.required, i.soak_run_url!.required, i.scoreboard_url!.required]).toEqual([true, true, false]);expect(i.rollback).toMatchObject({ type: 'boolean', default: false });expect(wf.concurrency).toEqual({ group: 'promote-stable', 'cancel-in-progress': false });diff --git a/test/self-upgrade-checkonly.serial.test.ts b/test/self-upgrade-checkonly.serial.test.tsindex c6f49eb5ba..8f5d5fc9c9 100644--- a/test/self-upgrade-checkonly.serial.test.ts+++ b/test/self-upgrade-checkonly.serial.test.ts@@ -16,6 +16,7 @@ const realFetch = globalThis.fetch;const realLog = console.log;let home: string;let priorHome: string | undefined;+let priorChannel: string | undefined;let captured: string[];function minorBump(): string {@@ -42,6 +43,9 @@ function stub(tag: string | null, changelog: string): void {beforeEach(() => {priorHome = process.env.GBRAIN_HOME;+ priorChannel = process.env.GBRAIN_RELEASE_CHANNEL;+ // These cases cover the alpha channel (every release, VERSION at latest-stable); stable has its own suites.+ process.env.GBRAIN_RELEASE_CHANNEL = 'alpha';home = mkdtempSync(join(tmpdir(), 'gbrain-checkonly-'));process.env.GBRAIN_HOME = home;captured = [];@@ -51,6 +55,8 @@ beforeEach(() => {afterEach(() => {globalThis.fetch = realFetch;console.log = realLog;+ if (priorChannel === undefined) delete process.env.GBRAIN_RELEASE_CHANNEL;+ else process.env.GBRAIN_RELEASE_CHANNEL = priorChannel;if (priorHome === undefined) delete process.env.GBRAIN_HOME;else process.env.GBRAIN_HOME = priorHome;rmSync(home, { recursive: true, force: true });diff --git a/test/self-upgrade.test.ts b/test/self-upgrade.test.tsindex 848bd39e19..ede2298c19 100644--- a/test/self-upgrade.test.ts+++ b/test/self-upgrade.test.ts@@ -196,27 +196,30 @@ describe('snooze', () => {expect(snoozeDurationMs(3)).toBe(7 * 24 * 3600 * 1000);expect(snoozeDurationMs(99)).toBe(7 * 24 * 3600 * 1000);});- test('isSnoozeActive: only for matching version, within window', () => {+ test('isSnoozeActive: time-based, holds across newer releases, ends at its expiry or on a rollback below the snoozed version', () => {const now = 1_000_000_000_000;- const rec = { version: '0.43.0', level: 1, ts: now };+ const rec = { version: '0.43.0', level: 1, ts: now, until: now + 24 * 3600 * 1000 };expect(isSnoozeActive(rec, '0.43.0', now + 1000)).toBe(true);+ expect(isSnoozeActive(rec, '0.44.0', now + 1000)).toBe(true); // a newer release does not end it+ expect(isSnoozeActive(rec, '0.99.0', now + 23 * 3600 * 1000)).toBe(true);expect(isSnoozeActive(rec, '0.43.0', now + 25 * 3600 * 1000)).toBe(false); // expired- expect(isSnoozeActive(rec, '0.44.0', now + 1000)).toBe(false); // different version+ expect(isSnoozeActive(rec, '0.42.0', now + 1000)).toBe(false); // rolled back below the snoozed versionexpect(isSnoozeActive(null, '0.43.0', now)).toBe(false);});- test('writeSnooze escalates level for same version, resets for new version', async () => {+ test('writeSnooze escalates per channel whatever version is offered (24h, 48h, 7d), atomically; clearSnooze clears every channel', async () => {await withTmpHome(() => {const now = 1_700_000_000_000;- expect(writeSnooze('0.43.0', now)).toBe(1);- expect(writeSnooze('0.43.0', now)).toBe(2);- expect(writeSnooze('0.43.0', now)).toBe(3);- expect(writeSnooze('0.43.0', now)).toBe(3); // capped- expect(writeSnooze('0.44.0', now)).toBe(1); // new version resets- const rec = readSnooze();- expect(rec?.version).toBe('0.44.0');- expect(rec?.level).toBe(1);+ const h = 3600 * 1000;+ expect(writeSnooze('0.43.0', now, 'alpha')).toMatchObject({ level: 1, until: now + 24 * h });+ expect(writeSnooze('0.44.0', now, 'alpha')).toMatchObject({ level: 2, until: now + 48 * h });+ expect(writeSnooze('0.45.0', now, 'alpha')).toMatchObject({ level: 3, until: now + 7 * 24 * h });+ expect(writeSnooze('0.46.0', now, 'alpha').level).toBe(3); // capped+ expect(writeSnooze('0.43.0', now, 'stable').level).toBe(1); // channels are independent+ expect(readSnooze('alpha')).toMatchObject({ version: '0.46.0', level: 3 });+ expect(readSnooze('stable')).toMatchObject({ version: '0.43.0', level: 1 });clearSnooze();- expect(readSnooze()).toBeNull();+ expect(readSnooze('alpha')).toBeNull();+ expect(readSnooze('stable')).toBeNull();});});test('corrupt snooze file → null', async () => {@@ -226,6 +229,8 @@ describe('snooze', () => {mkdirSync(gbrainPath(), { recursive: true });writeFileSync(gbrainPath('update-snoozed'), 'garbage not three fields here');expect(readSnooze()).toBeNull();+ writeFileSync(gbrainPath('update-snoozed.stable.json'), '{"version":"0.43.0","level":"x"}');+ expect(readSnooze('stable')).toBeNull();});});});diff --git a/test/upgrade-bun-link-arc.serial.test.ts b/test/upgrade-bun-link-arc.serial.test.tsindex e3d0a5c49d..cddefa4aad 100644--- a/test/upgrade-bun-link-arc.serial.test.ts+++ b/test/upgrade-bun-link-arc.serial.test.ts@@ -244,6 +244,8 @@ async function spawnWithShims(PATH: `${fx.shimDir}:${process.env.PATH ?? ''}`,HOME: fx.home,GBRAIN_HOME: fx.home,+ // The install method's own path (alpha); the stable channel has its own suite (upgrade-stable-channel).+ GBRAIN_RELEASE_CHANNEL: 'alpha',GIT_CONFIG_NOSYSTEM: '1',GIT_TERMINAL_PROMPT: '0',NO_COLOR: '1',diff --git a/test/upgrade-exact-tag-pin.test.ts b/test/upgrade-exact-tag-pin.test.tsindex ce9d27197c..99a7552db4 100644--- a/test/upgrade-exact-tag-pin.test.ts+++ b/test/upgrade-exact-tag-pin.test.ts@@ -17,6 +17,7 @@ import { tmpdir } from 'os';import { bunGlobalExactTagPin, bunReinstallCommand } from '../src/commands/upgrade.ts';import { VERSION } from '../src/version.ts';import { upgradeErrorResolved } from '../src/commands/doctor.ts';+import { writeChannelCache } from './helpers/update-cache.ts';const REPO = resolve(import.meta.dir, '..');@@ -35,7 +36,7 @@ async function runBareUpgrade(spec: string, observedVersion: string, cache?: strchmodSync(join(bin, 'gbrain'), 0o755);if (cache) {mkdirSync(join(home, '.gbrain'), { recursive: true });- writeFileSync(join(home, '.gbrain', 'last-update-check'), `${cache}\n`);+ writeChannelCache(join(home, '.gbrain'), cache);}const globalRoot = join(home, '.bun', 'install', 'global');const pkgDir = join(globalRoot, 'node_modules', 'gbrain');@@ -44,7 +45,8 @@ async function runBareUpgrade(spec: string, observedVersion: string, cache?: strwriteFileSync(join(pkgDir, 'package.json'), JSON.stringify({ name: 'gbrain', repository: 'github:garrytan/gbrain' }));const driver = join(pkgDir, 'driver.ts');writeFileSync(driver, `import { runUpgrade } from '${REPO}/src/commands/upgrade.ts';\nawait runUpgrade(['--swap-only', '--no-bun-floor-check']);\n`);- const env: Record<string, string | undefined> = { ...process.env, HOME: home, GBRAIN_HOME: home, PATH: `${bin}:${process.env.PATH}` };+ // The bare-upgrade path under test is the install method's own (alpha); stable is covered in upgrade-stable-channel.+ const env: Record<string, string | undefined> = { ...process.env, HOME: home, GBRAIN_HOME: home, GBRAIN_RELEASE_CHANNEL: 'alpha', PATH: `${bin}:${process.env.PATH}` };delete env.BUN_INSTALL;const proc = Bun.spawn([process.execPath, 'run', driver], { cwd: REPO, env, stdout: 'pipe', stderr: 'pipe' });const [stdout, stderr] = await Promise.all([new Response(proc.stdout).text(), new Response(proc.stderr).text()]);diff --git a/test/upgrade-release-tag-hint.test.ts b/test/upgrade-release-tag-hint.test.tsindex aa03f3a6f2..2a42a066ef 100644--- a/test/upgrade-release-tag-hint.test.ts+++ b/test/upgrade-release-tag-hint.test.ts@@ -87,7 +87,8 @@ async function runPinnedUpgrade(gitShim: string, targetVersion: string): PromisewriteFileSync(join(pkgDir, 'package.json'), JSON.stringify({ name: 'gbrain', repository: 'github:garrytan/gbrain' }));const driver = join(pkgDir, 'driver.ts');writeFileSync(driver, `import { runUpgrade } from '${REPO}/src/commands/upgrade.ts';\nawait runUpgrade(['--swap-only', '--no-bun-floor-check'], { targetVersion: '${targetVersion}' });\n`);- const env: Record<string, string | undefined> = { ...process.env, HOME: home, GBRAIN_HOME: home, PATH: `${bin}:${process.env.PATH}` };+ // The alpha channel: a stable install resolves its target from the evidence record (test/upgrade-stable-channel.test.ts).+ const env: Record<string, string | undefined> = { ...process.env, HOME: home, GBRAIN_HOME: home, PATH: `${bin}:${process.env.PATH}`, GBRAIN_RELEASE_CHANNEL: 'alpha' };delete env.BUN_INSTALL;const proc = Bun.spawn([process.execPath, 'run', driver], { cwd: REPO, env, stdout: 'pipe', stderr: 'pipe' });const stderr = await new Response(proc.stderr).text();diff --git a/test/upgrade-restart.test.ts b/test/upgrade-restart.test.tsindex 8125714b63..e3f2c9ecd8 100644--- a/test/upgrade-restart.test.ts+++ b/test/upgrade-restart.test.ts@@ -6,6 +6,8 @@* heartbeat rows, the service managers and the socket.*/import { describe, expect, test } from 'bun:test';+import { readFileSync } from 'node:fs';+import { join } from 'node:path';import { EQUALS_READERS } from '../src/cli/flag-equals.ts';import { parseGlobalFlags } from '../src/core/cli-options.ts';import {@@ -401,8 +403,8 @@ describe('another install on the host (GBRA-175 production finding: serve ran fr});});-describe('--dry-run belongs to --restart-only (#2185)', () => {- test('a dry run without --restart-only is refused instead of ignored', async () => {+describe('--dry-run never installs (#2185)', () => {+ test('without --restart-only the restart handler leaves --dry-run to the channel preview, which installs nothing (GBRA-224; upgrade-stable-channel.test.ts runs it)', async () => {const opts = { stopMcp: false, json: false, rerunArgv: ['gbrain', 'upgrade'] };const writes: string[] = [];const write = process.stderr.write;@@ -410,15 +412,18 @@ describe('--dry-run belongs to --restart-only (#2185)', () => {const prevExit = process.exitCode;try {expect(await handleRestartOnly(['--channel', 'stable'], opts)).toBe(false);+ expect(await handleRestartOnly(['--dry-run'], opts)).toBe(false);expect(currentExitCode()).toBe(0);- expect(await handleRestartOnly(['--dry-run'], opts)).toBe(true);- expect(currentExitCode()).toBe(exitCodeForCode('invalid_params'));} finally {process.stderr.write = write;process.exitCode = prevExit ?? 0;_resetCliExitVerdictForTests();}- expect(writes.join('')).toContain('--dry-run previews only a restart');+ expect(writes.join('')).toBe('');+ const src = readFileSync(join(import.meta.dir, '..', 'src', 'commands', 'upgrade.ts'), 'utf8');+ const preview = src.indexOf("if (args.includes('--dry-run')) return runUpgradeDryRun(args, json);");+ expect(preview).toBeGreaterThan(src.indexOf('if (await handleRestartOnly(args, restartOpts)) return;'));+ expect(preview).toBeLessThan(src.indexOf('const stableTarget = await channelTarget('));});test('upgrade accepts --dry-run and post-upgrade, which shares its module, does not', () => {diff --git a/test/upgrade-stable-channel.test.ts b/test/upgrade-stable-channel.test.tsindex ca89c843d2..3836f558d8 100644--- a/test/upgrade-stable-channel.test.ts+++ b/test/upgrade-stable-channel.test.ts@@ -1,18 +1,19 @@/**- * GBRA-175: the stable release channel. `gbrain upgrade --channel stable` (or- * `self_upgrade.channel stable`) installs the release the `stable` tag names,- * pinned to its `v<version>` tag, never downgrades, and then restarts every- * process onto it through the new build's `gbrain upgrade --restart-only`.+ * GBRA-175 / GBRA-224 W1: the stable release channel, now the default. `gbrain upgrade` on stable installs the release+ * the evidence record names (checked against the `stable` and `v<version>` tags), pinned to its tag, never+ * downgrades except off a version the record withdrew, refuses with a typed code (stable_missing, stable_invalid,+ * stable_unreadable) when stable has no usable release, and then restarts every process onto it. Alpha (`latest` is its+ * alias) keeps the install method's own path.** Subprocess: detectInstallMethod keys on argv[1] living under node_modules,- * and git, bun and gbrain must hit PATH shims, which Bun snapshots at start.+ * and git, bun and gbrain must hit PATH shims, which Bun snapshots at start. The driver stubs fetch with the record.*/import { describe, expect, test } from 'bun:test';import { chmodSync, existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'fs';import { join, resolve } from 'path';import { tmpdir } from 'os';import { parseChannelArg, resolveStableRelease } from '../src/commands/upgrade.ts';-import { normalizeChannel, parseSelfUpgradeConfigValue, resolveReleaseChannel } from '../src/core/self-upgrade.ts';+import { channelSwitchCommand, normalizeChannel, parseSelfUpgradeConfigValue, resolveReleaseChannel } from '../src/core/self-upgrade.ts';import { parseSemver } from '../src/core/semver.ts';import { VERSION } from '../src/version.ts';@@ -21,56 +22,97 @@ const v = parseSemver(VERSION)!;const NEWER = `${v[0]}.${v[1]}.${v[2] + 5}.0`;const NEWEST = `${v[0]}.${v[1]}.${v[2] + 9}.0`;const OLDER = `${v[0]}.${v[1]}.${Math.max(0, v[2] - 5)}.0`;+const C_OLDER = '1'.repeat(40);+const C_NEWER = '2'.repeat(40);+const C_NEWEST = '3'.repeat(40);+const COMMIT_OF: Record<string, string> = { [OLDER]: C_OLDER, [NEWER]: C_NEWER, [NEWEST]: C_NEWEST };+const SOAK = 'https://github.com/garrytan/gbrain/actions/runs/123456';const tags = (stableCommit: string | null, annotated = true) => [- `1111\trefs/tags/v${OLDER}`, `2222\trefs/tags/v${NEWER}`, `3333\trefs/tags/v${NEWEST}`, '3333\trefs/tags/latest-stable',- ...(stableCommit ? (annotated ? ['9999\trefs/tags/stable', `${stableCommit}\trefs/tags/stable^{}`] : [`${stableCommit}\trefs/tags/stable`]) : []),+ `${C_OLDER}\trefs/tags/v${OLDER}`, `${C_NEWER}\trefs/tags/v${NEWER}`, `${C_NEWEST}\trefs/tags/v${NEWEST}`, `${C_NEWEST}\trefs/tags/latest-stable`,+ ...(stableCommit ? (annotated ? [`${'9'.repeat(40)}\trefs/tags/stable`, `${stableCommit}\trefs/tags/stable^{}`] : [`${stableCommit}\trefs/tags/stable`]) : []),].join('\n');+const record = (version: string, over: Record<string, unknown> = {}) => JSON.stringify({ schema: 1, channel: 'stable', version, commit: COMMIT_OF[version], tree: 'f'.repeat(40), soak_run: SOAK, known_bad: [], ...over });+const git = (out: string, status = 0) => () => ({ status, stdout: out });+const serve = (body: string | null, status = 200) => (async () => {+ if (body === null) throw new Error('getaddrinfo ENOTFOUND raw.githubusercontent.com');+ return new Response(body, { status });+}) as unknown as typeof fetch;-describe('resolveStableRelease', () => {- const git = (stdout: string, status = 0) => () => ({ status, stdout });- test('peels the annotated stable tag to the release commit and names its version', () => {- expect(resolveStableRelease(git(tags('2222')))).toEqual({ version: NEWER, commit: '2222' });- expect(resolveStableRelease(git(tags('2222', false)))).toEqual({ version: NEWER, commit: '2222' });+describe('resolveStableRelease (record + tags)', () => {+ test('the record names the release; the stable tag and v<version> must be its commit', async () => {+ expect(await resolveStableRelease({ git: git(tags(C_NEWER)), fetch: serve(record(NEWER)) })).toMatchObject({ ok: true, version: NEWER, commit: C_NEWER });+ expect(await resolveStableRelease({ git: git(tags(C_NEWER, false)), fetch: serve(record(NEWER)) })).toMatchObject({ ok: true, version: NEWER });});- test('the newest v tag wins when several share the stable commit', () => {- expect(resolveStableRelease(git(`${tags('2222')}\n2222\trefs/tags/v${NEWER.replace(/\.0$/, '.1')}`))).toEqual({ version: NEWER.replace(/\.0$/, '.1'), commit: '2222' });- });- test('no stable tag, a stable tag on no release, and an unreadable remote are distinct errors', () => {- expect(resolveStableRelease(git(tags(null)))).toEqual({ error: 'no_stable' });- expect(resolveStableRelease(git(tags('abcd')))).toEqual({ error: 'no_release_tag' });- expect(resolveStableRelease(git('', 128))).toEqual({ error: 'unreadable' });++ test('missing, invalid and unreadable are distinct typed codes', async () => {+ expect(await resolveStableRelease({ git: git(tags(null)), fetch: serve('Not Found', 404) })).toMatchObject({ ok: false, code: 'stable_missing' });+ expect(await resolveStableRelease({ git: git(tags(null)), fetch: serve(record(NEWER)) })).toMatchObject({ ok: false, code: 'stable_missing' });+ expect(await resolveStableRelease({ git: git(tags(C_NEWER)), fetch: serve('Not Found', 404) })).toMatchObject({ ok: false, code: 'stable_invalid', cause: expect.stringContaining('no published evidence record') });+ expect(await resolveStableRelease({ git: git(tags(C_NEWER)), fetch: serve('{"schema":1,"version":"x"}') })).toMatchObject({ ok: false, code: 'stable_invalid' });+ expect(await resolveStableRelease({ git: git(tags(C_NEWER)), fetch: serve(record(NEWER, { soak_run: undefined })) })).toMatchObject({ ok: false, code: 'stable_invalid', cause: expect.stringContaining('soak_run') });+ expect(await resolveStableRelease({ git: git(tags(C_NEWER)), fetch: serve(record(NEWER, { commit: C_OLDER })) })).toMatchObject({ ok: false, code: 'stable_unreadable', cause: expect.stringContaining('disagree') });+ expect(await resolveStableRelease({ git: git(tags(C_NEWEST)), fetch: serve(record(NEWER, { commit: C_NEWEST })) })).toMatchObject({ ok: false, code: 'stable_invalid', cause: expect.stringContaining(`v${NEWER} is not the stable commit`) });+ expect(await resolveStableRelease({ git: git('', 128), fetch: serve(record(NEWER)) })).toMatchObject({ ok: false, code: 'stable_unreadable' });+ expect(await resolveStableRelease({ git: git(tags(C_NEWER)), fetch: serve(null) })).toMatchObject({ ok: false, code: 'stable_unreadable', cause: expect.stringContaining('ENOTFOUND') });+ expect(await resolveStableRelease({ git: git(tags(C_NEWER)), fetch: serve('oops', 503) })).toMatchObject({ ok: false, code: 'stable_unreadable', cause: expect.stringContaining('HTTP 503') });});});describe('channel selection', () => {- test('--channel takes latest or stable, in either spelling', () => {+ test('--channel is read raw in either spelling; a bare flag is an empty value', () => {expect(parseChannelArg(['--channel', 'stable'])).toBe('stable');expect(parseChannelArg(['--channel=latest'])).toBe('latest');- expect(parseChannelArg(['--channel', 'beta'])).toBe('invalid');- expect(parseChannelArg(['--channel'])).toBe('invalid');- expect(parseChannelArg(['--swap-only'])).toBeNull();+ expect(parseChannelArg(['--channel', 'beta'])).toBe('beta');+ expect(parseChannelArg(['--channel'])).toBe('');+ expect(parseChannelArg(['--channel', '--json'])).toBe('');+ expect(parseChannelArg(['--json'])).toBeNull();+ });++ test('precedence: --channel, then GBRAIN_RELEASE_CHANNEL, then self_upgrade.channel, then stable', () => {+ const cfg = { self_upgrade: { channel: 'alpha' } };+ expect(resolveReleaseChannel(null, null, undefined)).toEqual({ ok: true, channel: 'stable', source: 'default' });+ expect(resolveReleaseChannel(cfg, null, undefined)).toEqual({ ok: true, channel: 'alpha', source: 'config' });+ expect(resolveReleaseChannel(cfg, null, 'stable')).toEqual({ ok: true, channel: 'stable', source: 'env' });+ expect(resolveReleaseChannel(cfg, 'stable', 'alpha')).toEqual({ ok: true, channel: 'stable', source: 'flag' });+ expect(resolveReleaseChannel(null, null, '')).toEqual({ ok: true, channel: 'stable', source: 'default' });});- test('self_upgrade.channel is validated and defaults to latest', () => {- expect(parseSelfUpgradeConfigValue('channel', 'stable')).toEqual({ ok: true, value: 'stable' });- expect(parseSelfUpgradeConfigValue('channel', 'nightly')).toMatchObject({ ok: false });- expect(resolveReleaseChannel({ self_upgrade: { channel: 'stable' } })).toBe('stable');- expect(resolveReleaseChannel({ self_upgrade: { channel: 'bogus' } })).toBe('latest');- expect(resolveReleaseChannel(null)).toBe('latest');- expect(normalizeChannel('latest')).toBe('latest');++ test('latest is an alias for alpha in the flag, the env and the config', () => {+ expect(normalizeChannel('latest')).toBe('alpha');+ expect(normalizeChannel(' Alpha ')).toBe('alpha');+ expect(resolveReleaseChannel(null, 'latest', undefined)).toMatchObject({ ok: true, channel: 'alpha', source: 'flag' });+ expect(resolveReleaseChannel(null, null, 'latest')).toMatchObject({ ok: true, channel: 'alpha', source: 'env' });+ expect(resolveReleaseChannel({ self_upgrade: { channel: 'latest' } }, null, undefined)).toMatchObject({ ok: true, channel: 'alpha', source: 'config' });+ expect(parseSelfUpgradeConfigValue('channel', 'latest')).toEqual({ ok: true, value: 'alpha' });+ });++ test('an invalid value is an error at the source that holds it, never a fallthrough, and names the valid values', () => {+ expect(resolveReleaseChannel({ self_upgrade: { channel: 'stable' } }, 'beta', undefined)).toEqual({ ok: false, source: 'flag', raw: 'beta' });+ expect(resolveReleaseChannel({ self_upgrade: { channel: 'stable' } }, null, 'nightly')).toEqual({ ok: false, source: 'env', raw: 'nightly' });+ expect(resolveReleaseChannel({ self_upgrade: { channel: 'bogus' } }, null, undefined)).toEqual({ ok: false, source: 'config', raw: 'bogus' });+ expect(parseSelfUpgradeConfigValue('channel', 'nightly')).toEqual({ ok: false, error: "must be stable or alpha (latest is an alias for alpha) (got 'nightly')" });+ });++ test('the switch command is rendered against what decided the channel', () => {+ expect(channelSwitchCommand('alpha', { ok: true, channel: 'stable', source: 'default' })).toBe('gbrain config set self_upgrade.channel alpha');+ expect(channelSwitchCommand('alpha', { ok: true, channel: 'stable', source: 'config' })).toBe('gbrain config set self_upgrade.channel alpha');+ expect(channelSwitchCommand('alpha', { ok: true, channel: 'stable', source: 'env' })).toStartWith('GBRAIN_RELEASE_CHANNEL=alpha');+ expect(channelSwitchCommand('alpha', { ok: true, channel: 'stable', source: 'flag' })).toBe('gbrain upgrade --channel alpha');});});interface Run { home: string; exitCode: number; stdout: string; stderr: string; bunCalls: string[]; gbrainCalls: string[] }+interface RunOpts { stableCommit?: string | null; record?: string | null; recordStatus?: number; config?: Record<string, unknown>; env?: Record<string, string>; failAdd?: string; spec?: string; noRepoConfig?: boolean }-async function runStableUpgrade(args: string[], opts: { stableCommit?: string | null; config?: Record<string, unknown>; failAdd?: string; spec?: string } = {}): Promise<Run> {+async function runStableUpgrade(args: string[], opts: RunOpts = {}): Promise<Run> {const home = mkdtempSync(join(tmpdir(), 'gbrain-stable-'));const bin = join(home, 'bin');mkdirSync(bin);const state = join(home, 'installed-version');writeFileSync(state, VERSION);writeFileSync(join(bin, 'git'), `#!/bin/sh\ncase "$1" in ls-remote) cat '${join(home, 'tags.txt')}'; exit 0;; esac\nexit 1\n`);- writeFileSync(join(home, 'tags.txt'), tags(opts.stableCommit === undefined ? '2222' : opts.stableCommit));+ writeFileSync(join(home, 'tags.txt'), tags(opts.stableCommit === undefined ? C_NEWER : opts.stableCommit));// `bun add -g github:garrytan/gbrain#v<x>` installs <x>; `gbrain --version` reports what is installed.writeFileSync(join(bin, 'bun'), `#!/bin/sh\necho "$*" >> '${join(home, 'bun-calls.log')}'\n${opts.failAdd ? `case "$*" in "add -g github:garrytan/gbrain#v${opts.failAdd}") exit 1;; esac\n` : ''}case "$*" in "add -g github:garrytan/gbrain#v"*) echo "$3" | sed 's/.*#v//' > '${state}';; esac\nexit 0\n`);writeFileSync(join(bin, 'gbrain'), `#!/bin/sh\nif [ "$1" = "--version" ]; then echo "gbrain $(cat '${state}')"; exit 0; fi\necho "$*" >> '${join(home, 'gbrain-calls.log')}'\nexit 0\n`);@@ -84,9 +126,22 @@ async function runStableUpgrade(args: string[], opts: { stableCommit?: string |mkdirSync(pkgDir, { recursive: true });writeFileSync(join(globalRoot, 'package.json'), JSON.stringify({ dependencies: { gbrain: opts.spec ?? 'github:garrytan/gbrain#latest-stable' } }));writeFileSync(join(pkgDir, 'package.json'), JSON.stringify({ name: 'gbrain', repository: 'github:garrytan/gbrain' }));+ const body = opts.record === undefined ? record(NEWER) : opts.record;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`);- const env: Record<string, string | undefined> = { ...process.env, HOME: home, GBRAIN_HOME: home, PATH: `${bin}:${process.env.PATH}` };+ writeFileSync(driver, [+ `const body = ${JSON.stringify(body)};`,+ `globalThis.fetch = (async (url: unknown) => {`,+ ` if (!String(url).endsWith('/stable-record/stable.json')) return new Response('', { status: 404 });`,+ ` if (body === null) throw new Error('network down');`,+ ` return new Response(body, { status: ${opts.recordStatus ?? 200} });`,+ `}) as typeof fetch;`,+ `const { runUpgrade } = await import('${REPO}/src/commands/upgrade.ts');`,+ `const { currentExitCode } = await import('${REPO}/src/core/cli-force-exit.ts');`,+ `await runUpgrade(${JSON.stringify(['--no-bun-floor-check', '--no-autopilot-install', ...args])});`,+ `process.exitCode = currentExitCode();`,+ ].join('\n'));+ const env: Record<string, string | undefined> = { ...process.env, HOME: home, GBRAIN_HOME: home, PATH: `${bin}:${process.env.PATH}`, ...opts.env };+ if (!opts.env?.GBRAIN_RELEASE_CHANNEL) delete env.GBRAIN_RELEASE_CHANNEL;delete env.BUN_INSTALL;delete env.DATABASE_URL;delete env.GBRAIN_DATABASE_URL;@@ -96,80 +151,130 @@ async function runStableUpgrade(args: string[], opts: { stableCommit?: string |return { home, exitCode: await proc.exited, stdout, stderr, bunCalls: lines('bun-calls.log'), gbrainCalls: lines('gbrain-calls.log') };}-describe('gbrain upgrade --channel stable', () => {- test('installs exactly the stable release pinned to its tag (remove, then add), not the newest release', async () => {- const r = await runStableUpgrade(['--channel', 'stable', '--swap-only']);- try {- expect(r.stdout).toContain(`Stable channel: installing gbrain ${NEWER}`);- expect(r.bunCalls).toEqual(['remove -g gbrain', `add -g github:garrytan/gbrain#v${NEWER}`]);- expect(r.stdout).toContain(`Now running: gbrain ${NEWER}`);- expect(r.exitCode).toBe(0);- } finally { rmSync(r.home, { recursive: true, force: true }); }- });+async function withRun(args: string[], opts: RunOpts, check: (r: Run) => void): Promise<void> {+ const r = await runStableUpgrade(args, opts);+ try { check(r); } finally { rmSync(r.home, { recursive: true, force: true }); }+}- test('then the new build restarts every process and the summary says so', async () => {- const r = await runStableUpgrade(['--channel', 'stable']);- try {- expect(r.gbrainCalls).toContain('upgrade --restart-only');- expect(r.stdout).toContain(`Restart: every gbrain process on this host runs ${NEWER}`);- expect(r.exitCode).toBe(0);- } finally { rmSync(r.home, { recursive: true, force: true }); }- });+describe('gbrain upgrade on the stable channel', () => {+ test('installs exactly the stable release pinned to its tag (remove, then add), not the newest release', () => withRun(['--channel', 'stable', '--swap-only'], {}, r => {+ expect(r.stdout).toContain(`Stable channel: installing gbrain ${NEWER}`);+ expect(r.bunCalls).toEqual(['remove -g gbrain', `add -g github:garrytan/gbrain#v${NEWER}`]);+ expect(r.stdout).toContain(`Now running: gbrain ${NEWER}`);+ expect(r.exitCode).toBe(0);+ }));- test('--no-restart installs without restarting and says what to run', async () => {- const r = await runStableUpgrade(['--channel', 'stable', '--no-restart']);- try {- expect(r.gbrainCalls.some(c => c.includes('--restart-only'))).toBe(false);- expect(r.stdout).toContain('Restart: skipped (--no-restart)');- } finally { rmSync(r.home, { recursive: true, force: true }); }+ test('then the new build restarts every process and the summary says so', () => withRun(['--channel', 'stable'], {}, r => {+ expect(r.gbrainCalls).toContain('upgrade --restart-only');+ expect(r.stdout).toContain(`Restart: every gbrain process on this host runs ${NEWER}`);+ expect(r.exitCode).toBe(0);+ }));++ test('--no-restart installs without restarting and says what to run', () => withRun(['--channel', 'stable', '--no-restart'], {}, r => {+ expect(r.gbrainCalls.some(c => c.includes('--restart-only'))).toBe(false);+ expect(r.stdout).toContain('Restart: skipped (--no-restart)');+ }));++ test('default flip: a home that never set a channel follows stable on a bare upgrade (repo-less config and no config at all)', async () => {+ await withRun(['--swap-only'], {}, r => expect(r.bunCalls).toEqual(['remove -g gbrain', `add -g github:garrytan/gbrain#v${NEWER}`]));+ await withRun(['--swap-only'], { config: { engine: 'pglite', database_path: '/tmp/gbrain-stable-example.pglite' } }, r => {+ expect(r.bunCalls).toEqual(['remove -g gbrain', `add -g github:garrytan/gbrain#v${NEWER}`]);+ });});- test('self_upgrade.channel stable makes a bare upgrade follow the stable channel', async () => {- const r = await runStableUpgrade(['--swap-only'], { config: { engine: 'pglite', database_path: '/tmp/gbrain-stable-example.pglite', self_upgrade: { channel: 'stable' } } });- try {+ test('self_upgrade.channel stable and GBRAIN_RELEASE_CHANNEL=stable both select stable over the other sources', async () => {+ await withRun(['--swap-only'], { config: { engine: 'pglite', database_path: '/tmp/gbrain-stable-example.pglite', self_upgrade: { channel: 'stable' } } }, r => {+ expect(r.bunCalls).toEqual(['remove -g gbrain', `add -g github:garrytan/gbrain#v${NEWER}`]);+ });+ await withRun(['--swap-only'], { config: { engine: 'pglite', database_path: '/tmp/gbrain-stable-example.pglite', self_upgrade: { channel: 'alpha' } }, env: { GBRAIN_RELEASE_CHANNEL: 'stable' } }, r => {expect(r.bunCalls).toEqual(['remove -g gbrain', `add -g github:garrytan/gbrain#v${NEWER}`]);- } finally { rmSync(r.home, { recursive: true, force: true }); }+ });});- test('a build at or above the stable release changes nothing (the stable channel never downgrades)', async () => {- const same = await runStableUpgrade(['--channel', 'stable'], { stableCommit: '1111' });- try {- expect(same.stdout).toContain(`is newer than the stable channel's release (${OLDER})`);- expect(same.bunCalls).toEqual([]);- expect(same.exitCode).toBe(0);- } finally { rmSync(same.home, { recursive: true, force: true }); }+ test('a build at or above the stable release changes nothing (the stable channel never downgrades)', () => withRun(['--channel', 'stable'], { stableCommit: C_OLDER, record: record(OLDER) }, r => {+ expect(r.stdout).toContain(`is newer than the stable channel's release (${OLDER})`);+ expect(r.bunCalls).toEqual([]);+ expect(r.exitCode).toBe(0);+ }));++ test('known_bad: a build the record withdrew is moved to the current stable, the one move below the running build', () => withRun(['--channel', 'stable', '--swap-only'], { stableCommit: C_OLDER, record: record(OLDER, { known_bad: [VERSION] }) }, r => {+ expect(r.stdout).toContain(`gbrain ${VERSION} was withdrawn from the stable channel`);+ expect(r.bunCalls).toEqual(['remove -g gbrain', `add -g github:garrytan/gbrain#v${OLDER}`]);+ expect(r.exitCode).toBe(0);+ }));++ test('a failed add restores the release that was installed and records the recovery step', () => withRun(['--channel', 'stable', '--swap-only'], { failAdd: NEWER }, r => {+ expect(r.bunCalls).toEqual(['remove -g gbrain', `add -g github:garrytan/gbrain#v${NEWER}`, `add -g github:garrytan/gbrain#v${VERSION}`]);+ expect(r.stderr).toContain(`Restored gbrain ${VERSION}.`);+ const rec = JSON.parse(readFileSync(join(r.home, '.gbrain', 'upgrade-errors.jsonl'), 'utf8').trim().split('\n').at(-1)!);+ expect(rec).toMatchObject({ phase: 'stable-reinstall', from_version: VERSION, to_version: NEWER });+ expect(rec.hint).toContain(`#v${NEWER}`);+ expect(r.exitCode).not.toBe(0);+ }));++ test('alpha (and its alias latest): a global install pinned to a commit is replaced with the newest release tag, not left on its pin', async () => {+ for (const channel of ['alpha', 'latest']) {+ await withRun(['--channel', channel, '--swap-only'], { spec: 'github:garrytan/gbrain#0123456789abcdef0123456789abcdef01234567' }, r => {+ 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);+ });+ }});- test('a failed add restores the release that was installed and records the recovery step', async () => {- const r = await runStableUpgrade(['--channel', 'stable', '--swap-only'], { failAdd: NEWER });- try {- expect(r.bunCalls).toEqual(['remove -g gbrain', `add -g github:garrytan/gbrain#v${NEWER}`, `add -g github:garrytan/gbrain#v${VERSION}`]);- expect(r.stderr).toContain(`Restored gbrain ${VERSION}.`);- const record = JSON.parse(readFileSync(join(r.home, '.gbrain', 'upgrade-errors.jsonl'), 'utf8').trim().split('\n').at(-1)!);- expect(record).toMatchObject({ phase: 'stable-reinstall', from_version: VERSION, to_version: NEWER });- expect(record.hint).toContain(`#v${NEWER}`);+ test('stable_missing: nothing promoted exits non-zero with the code and the config fix, and installs nothing', () => withRun(['--json'], { stableCommit: null, record: 'Not Found', recordStatus: 404 }, r => {+ const env = JSON.parse(r.stdout.slice(r.stdout.indexOf('{')));+ expect(env).toMatchObject({ code: 'stable_missing' });+ expect(JSON.stringify(env)).toContain('gbrain config set self_upgrade.channel alpha');+ expect(r.bunCalls).toEqual([]);+ expect(r.exitCode).not.toBe(0);+ }));++ test('stable_invalid: a record without its evidence exits non-zero; the fix names the override that chose stable', () => withRun([], { record: record(NEWER, { soak_run: 'https://example.com/x' }), env: { GBRAIN_RELEASE_CHANNEL: 'stable' } }, r => {+ expect(r.stderr).toContain('stable_invalid');+ expect(r.stderr).toContain('soak_run');+ expect(r.stderr).toContain('GBRAIN_RELEASE_CHANNEL=alpha');+ expect(r.bunCalls).toEqual([]);+ expect(r.exitCode).not.toBe(0);+ }));++ test('stable_unreadable: an unreachable record exits non-zero with a retry, never falls back to alpha', () => withRun([], { record: null }, r => {+ expect(r.stderr).toContain('stable_unreadable');+ expect(r.stderr).toContain('Fix: gbrain self-upgrade --check-only --json');+ expect(r.stderr).not.toContain('config set self_upgrade.channel alpha');+ expect(r.bunCalls).toEqual([]);+ expect(r.exitCode).not.toBe(0);+ }));++ test('an invalid channel is a usage error naming the valid values, from the flag or the env', async () => {+ await withRun(['--channel', 'beta'], {}, r => {+ expect(r.stderr).toContain('invalid_params');+ expect(r.stderr).toContain('stable or alpha (latest is an alias for alpha)');+ expect(r.bunCalls).toEqual([]);+ expect(r.exitCode).not.toBe(0);+ });+ await withRun([], { env: { GBRAIN_RELEASE_CHANNEL: 'nightly' } }, r => {+ expect(r.stderr).toContain("GBRAIN_RELEASE_CHANNEL is 'nightly'");expect(r.exitCode).not.toBe(0);- } 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}`);+ test('--dry-run prints the effective channel, its source and the target, and installs nothing', async () => {+ await withRun(['--dry-run'], {}, r => {+ expect(r.stdout).toContain('Channel: stable (from default)');+ expect(r.stdout).toContain(`Would install gbrain ${NEWER}`);+ expect(r.bunCalls).toEqual([]);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 {- expect(r.stderr).toContain('stable_channel_unresolved');- expect(r.stderr).toContain('No release has been promoted to the stable channel yet');+ });+ await withRun(['--dry-run', '--json'], { config: { engine: 'pglite', database_path: '/tmp/gbrain-stable-example.pglite', self_upgrade: { channel: 'latest' } } }, r => {+ expect(JSON.parse(r.stdout.slice(r.stdout.indexOf('{')))).toMatchObject({ dry_run: true, channel: 'alpha', channel_source: 'config', current_version: VERSION });expect(r.bunCalls).toEqual([]);+ });+ await withRun(['--dry-run'], { stableCommit: null, record: 'Not Found', recordStatus: 404 }, r => {+ expect(r.stderr).toContain('stable_missing');expect(r.exitCode).not.toBe(0);- } finally { rmSync(r.home, { recursive: true, force: true }); }+ });});});diff --git a/test/upgrade.serial.test.ts b/test/upgrade.serial.test.tsindex 4e91ca3331..872659df6d 100644--- a/test/upgrade.serial.test.ts+++ b/test/upgrade.serial.test.ts@@ -290,6 +290,8 @@ describe('runUpgrade target verification (#4366)', () => {...process.env,HOME: home,GBRAIN_HOME: home,+ // The install method's own path (alpha); the stable channel has its own suite (upgrade-stable-channel).+ GBRAIN_RELEASE_CHANNEL: 'alpha',PATH: `${bin}:${process.env.PATH}`,};delete env.TEST_TARGET_VERSION;