Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
GitHub's Latest release is now the stable release; batch releases publish as pre-releases (GST-2761) (#9408)
Garry Tan66d033aad087
diff --git a/.github/workflows/macos-validation.yml b/.github/workflows/macos-validation.ymlindex f9423f07bd..8365b9906e 100644--- a/.github/workflows/macos-validation.yml+++ b/.github/workflows/macos-validation.yml@@ -81,8 +81,9 @@ jobs:if-no-files-found: warn- name: "#5286 published signed release binary"run: |- tag="$(curl -fsSI https://github.com/garrytan/gbrain/releases/latest | awk 'tolower($1)=="location:" {print $2}' | tr -d '\r' | sed 's#.*/tag/##')"- echo "latest release: $tag"+ # The newest release is the one latest-stable names; GitHub's "Latest" is the stable release.+ tag="v$(curl -fsSL https://raw.githubusercontent.com/garrytan/gbrain/latest-stable/VERSION | head -n 1 | tr -d '[:space:]')"+ echo "newest release: $tag"curl -fsSL -o gbrain-darwin-arm64 "https://github.com/garrytan/gbrain/releases/download/$tag/gbrain-darwin-arm64"shasum -a 256 gbrain-darwin-arm64codesign --verify --strict --verbose=2 gbrain-darwin-arm64diff --git a/.github/workflows/release.yml b/.github/workflows/release.ymlindex 4ea58c5db8..2ac5d4bb21 100644--- a/.github/workflows/release.yml+++ b/.github/workflows/release.yml@@ -5,11 +5,14 @@ name: Release# compiled binaries attached (#3521), plus the skill resolver library bundle# for Node adapters (gbrain-skill-resolver.mjs, GBRA-377).#-# Why every bump: `gbrain check-update` resolves the latest version from the-# VERSION file on master, but binary self-update-# (src/core/binary-self-update.ts) downloads assets from `releases/latest`.-# If releases lag VERSION, binary installs are told an upgrade exists that-# self-update cannot apply. Keeping releases/latest == VERSION closes that gap.+# Every release is published as a pre-release that never becomes GitHub's+# "Latest": scripts/promote-stable.ts marks the stable release Latest, with+# notes rolled up since the previous stable, so the Releases page and its+# Latest badge show the release installs follow. The alpha channel follows+# the latest-stable tag this workflow moves last; binary self-update reads+# VERSION there and downloads that exact release (src/core/binary-self-update.ts),+# never releases/latest. Bring older releases in line, or take the rule out,+# with scripts/release-channel.ts (docs/RELEASING.md).## Idempotent: the `version` job skips build+release when a release for# v<VERSION> already exists WITH all expected assets. A half-published release@@ -250,6 +253,19 @@ jobs:if ! bash scripts/changelog-entry.sh "$v" > /tmp/release-notes.md || ! [ -s /tmp/release-notes.md ]; thenecho "See [CHANGELOG.md](https://github.com/${GITHUB_REPOSITORY}/blob/master/CHANGELOG.md) for v$v." > /tmp/release-notes.mdfi+ # A re-run that repairs a half-published release republishes it as a+ # pre-release. If that release is already the stable one, the re-run+ # would take away the stable flag and GitHub's Latest; refuse instead.+ - name: Refuse to republish the current stable release+ env:+ RELEASE_SHA: ${{ needs.ci-gate.outputs.sha }}+ RELEASE_VERSION: ${{ needs.version.outputs.version }}+ run: |+ stable="$(git ls-remote origin 'refs/tags/stable^{}' | cut -f1)"+ if [ -n "$stable" ] && [ "$stable" = "$RELEASE_SHA" ]; then+ echo "::error::v$RELEASE_VERSION is the current stable release; re-publishing it would mark it a pre-release. Upload the missing assets with gh release upload v$RELEASE_VERSION <files> instead (docs/RELEASING.md)."+ exit 1+ fi- name: Create releaseuses: softprops/action-gh-release@3bb12739c298aeb8a4eeaf626c5b8d85266b0e65 # v2with:@@ -257,6 +273,8 @@ jobs:name: v${{ needs.version.outputs.version }}target_commitish: ${{ needs.ci-gate.outputs.sha }}body_path: /tmp/release-notes.md+ prerelease: true+ make_latest: 'false'fail_on_unmatched_files: truefiles: |artifacts/gbrain-darwin-arm64/gbrain-darwin-arm64diff --git a/TODOS.md b/TODOS.mdindex 211aefd9a7..687d920fcc 100644--- a/TODOS.md+++ b/TODOS.md@@ -2343,7 +2343,7 @@ deferred M-effort issues above are NOT repeated here.## Security-sweep mitigation follow-ups (filed 2026-08-16)- [ ] **P1 — `gbrain upgrade` binary lane returns success exit status on failure (autopilot false-success).** **What:** `runUpgrade`'s `binary` case logs every failure reason (`smoke_failed`, `download_failed`, `integrity_failed`, `integrity_unavailable`, `version_mismatch`, `replace_failed`) but never sets a non-zero CLI exit verdict, so callers see exit 0. **Why:** autopilot (`src/commands/autopilot.ts`) can read a false success, record "applied," relaunch, and then mark a transiently-unavailable version permanently bad — an amplification loop, now more reachable because `integrity_unavailable` fires on ordinary GitHub API rate limits. **Context:** PRE-EXISTING for the whole binary lane (not introduced by the v0.46.12.3 integrity work); surfaced by that PR's adversarial review with 2-model consensus. Fix needs care: distinguish hard-fail (`integrity_failed`/`version_mismatch` → exit non-zero, autopilot should NOT mark-bad on a security rejection) from transient (`integrity_unavailable` → retry, not a version fault), with autopilot-loop tests — hence its own PR, not a rushed rider. **Start:** `src/commands/upgrade.ts` binary case + `setCliExitVerdict` + `src/commands/autopilot.ts` upgrade handling.-- [ ] **P3 — Self-update GitHub API rate-limit resilience.** **What:** each `gbrain upgrade` makes 2 unauthenticated `api.github.com` calls (releases/latest + attestations), 60/hr/IP; corporate NAT / CI fleets hit 403 → `integrity_unavailable` → fail-closed. **Why:** a hard availability regression for shared-egress fleets vs the pre-integrity path. **Options:** honor an ambient `GH_TOKEN`/`GITHUB_TOKEN` when present (weigh against widening what a leaked env token authorizes), or a small bounded retry with backoff, and align the attestation fetch timeout (10s) with the download budget so a slow-but-working link doesn't spuriously fail. **Start:** `defaultFetchRelease`/`defaultFetchAttestation` in `src/core/binary-self-update.ts`.+- [ ] **P3 — Self-update GitHub API rate-limit resilience.** **What:** each `gbrain upgrade` makes 2 unauthenticated `api.github.com` calls (the release by tag + attestations), 60/hr/IP; corporate NAT / CI fleets hit 403 → `integrity_unavailable` → fail-closed. **Why:** a hard availability regression for shared-egress fleets vs the pre-integrity path. **Options:** honor an ambient `GH_TOKEN`/`GITHUB_TOKEN` when present (weigh against widening what a leaked env token authorizes), or a small bounded retry with backoff, and align the attestation fetch timeout (10s) with the download budget so a slow-but-working link doesn't spuriously fail. **Start:** `defaultFetchRelease`/`defaultFetchAttestation` in `src/core/binary-self-update.ts`.- [ ] **P3 — Integrity for the from-source / `latest-stable` install paths.** **What:** thediff --git a/changelog.d/capy-release-channel-prerelease-latest-stable.md b/changelog.d/capy-release-channel-prerelease-latest-stable.mdnew file mode 100644index 0000000000..dce2a78592--- /dev/null+++ b/changelog.d/capy-release-channel-prerelease-latest-stable.md@@ -0,0 +1,13 @@+**GitHub's "Latest" release is now the stable release, with notes covering everything since the previous stable; every batch release is published as a pre-release.** Installs and `gbrain upgrade` already followed the stable tag, so nothing changes for anyone on the documented install. The Releases page and its Latest badge now show that same release, about once a day, instead of every batch release. Anyone who downloads from `releases/latest` by hand now gets the stable release. People watching the repository for releases are still notified of pre-releases, because GitHub has no setting to skip them.++### Changed+- `.github/workflows/release.yml` publishes each release with `prerelease: true` and `make_latest: false`.+- `scripts/promote-stable.ts` ends every promotion by marking the release Latest. A forward promotion also replaces its notes with every CHANGELOG entry since the previous stable; the oldest entries drop, with a link, past GitHub's size limit. Latest never moves back to an older release on a forward promotion, so until stable passes the newest batch release published before this change, Latest stays where it is.+- A hand re-run of the release workflow that would republish the current stable release as a pre-release refuses.+- Alpha binary self-update reads `VERSION` at the `latest-stable` tag and downloads that exact release instead of `releases/latest`.+- The upgrade matrix counts pre-releases as releases.+- The macOS 26 signature check takes its tag from `latest-stable`.++### Added+- `scripts/release-channel.ts` has three commands. `backfill` brings releases published before this change in line. `undo` takes the rule back out. `preview-promotion` shows what a promotion would write. `backfill` and `undo` only print their plan unless given `--apply`.+- Docs: docs/RELEASING.md, "Which release GitHub calls Latest".diff --git a/docs/RELEASING.md b/docs/RELEASING.mdindex 94858ca4bc..0b55ece698 100644--- a/docs/RELEASING.md+++ b/docs/RELEASING.md@@ -644,7 +644,9 @@ manual tag push is part of the ship flow — the workflow reads `VERSION` (thesingle source of truth), mints tag `v<VERSION>` at the pushed commit, titlesthe release the same, uses that version's `CHANGELOG.md` entry as the notes(`scripts/changelog-entry.sh`; falls back to a CHANGELOG link if the entry is-missing), and attaches the compiled binaries.+missing), and attaches the compiled binaries. Every one is published as a+pre-release; only the stable release is GitHub's "Latest" ([Which release GitHub+calls Latest](#which-release-github-calls-latest)).The executable build job pins Bun 1.4.4, the first release with the Brotli fixfor CVE-2026-111497 (#7373): a standalone binary embeds the Bun it was built@@ -707,6 +709,47 @@ release already exists with all assets):git push origin "+refs/tags/v<VERSION>^{commit}:refs/tags/latest-stable"```+### Which release GitHub calls Latest++release.yml publishes every batch release with `prerelease: true` and+`make_latest: false`, so the Releases page and its Latest badge point at the+release installs follow. Each promotion (`scripts/promote-stable.ts`, from the+promote dispatch or the daily check) ends by marking the promoted release+Latest and clearing its pre-release flag. A forward promotion also replaces its+notes with every CHANGELOG entry since the previous stable, newest first; the+oldest entries drop with a link to the full CHANGELOG once the notes would pass+GitHub's 125,000-character limit. A rollback keeps the notes.++A forward promotion never moves Latest to an older release than the one it+marks now, because binaries released before this rule download+`releases/latest` as their update. So during the changeover Latest stays on+the newest release published before the rule, until stable passes it; that+promotion sets Latest, and from then on Latest is stable. `backfill` should+not be needed. A hand re-run of release.yml that would republish the current+stable release as a pre-release refuses; upload missing assets with+`gh release upload` instead.++Nothing that installs or updates gbrain reads GitHub's Latest: `#stable` and+`gbrain upgrade` follow the `stable` tag and its record; the alpha channel+(binary self-update included) reads `VERSION` at `latest-stable` and fetches+that exact release; the upgrade matrix counts pre-releases as releases; the+macOS signature check resolves its tag from `latest-stable`. Anyone who+downloads from `releases/latest` by hand now gets the stable release, about a+day behind the newest. People who watch the repository for releases are still+notified of pre-releases: GitHub has no setting to skip them.++`scripts/release-channel.ts` handles GitHub release state outside a promotion;+each command prints its plan and writes nothing without `--apply`:++- `backfill`: every published release newer than the current stable becomes a+ pre-release and the stable release becomes Latest with rolled-up notes. It is+ also the repair when a promotion moved `stable` but could not mark it Latest+ (the refusal names it).+- `undo`: every pre-release goes back to a normal release and the newest release+ becomes Latest, as before this rule. Revert the workflow change with it.+- `preview-promotion [--version <v>]`: the release a promotion would make+ Latest and the notes it would write.+### Stable channel promotionThe stable channel, the clients' default since GBRA-224, is a slower ref than@@ -895,11 +938,10 @@ the template repository ONLY — no other repositories, no other permissions.Configure it as a repo secret; when absent, template publishing is disabledand the job skips cleanly.-Why every bump, not selective: `gbrain check-update` resolves the latest-version from `VERSION` on master, while binary self-update-(`src/core/binary-self-update.ts`) downloads assets from `releases/latest`.-Any release that lags `VERSION` tells binary installs an upgrade exists that-self-update cannot apply. `releases/latest` must track `VERSION`.+Why every bump, not selective: the alpha update check reads `VERSION` at+`latest-stable`, and binary self-update downloads that exact release+(`src/core/binary-self-update.ts`). Any version without a release tells binary+installs an upgrade exists that self-update cannot apply.Invariants:diff --git a/scripts/promote-stable.ts b/scripts/promote-stable.tsindex af63ccb364..b88c842df1 100644--- a/scripts/promote-stable.ts+++ b/scripts/promote-stable.ts@@ -35,6 +35,13 @@* 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.+ * 8. the release's GitHub release is marked "Latest" (pre-release cleared):+ * release.yml publishes every batch release as a pre-release, so the+ * stable channel is the one release GitHub calls Latest. A forward+ * promotion replaces its notes with every CHANGELOG entry since the+ * previous stable (rolledUpNotes()); a rollback keeps the notes. If this+ * last step fails, stable has already moved: the refusal names+ * `bun scripts/release-channel.ts backfill --apply`, which sets it.** Clients read the record at* https://raw.githubusercontent.com/garrytan/gbrain/stable-record/stable.json@@ -92,6 +99,8 @@ export interface PromoteDeps {scheduled?: boolean;soakWorkflow: string;ghApi(path: string): Promise<unknown>;+ /** A write to the GitHub API (only the release edit that marks stable Latest). */+ ghApiWrite(method: 'PATCH', path: string, body: Record<string, unknown>): Promise<unknown>;git(args: string[], input?: string): Promise<GitResult>;now(): Date;log(line: string): void;@@ -419,13 +428,15 @@ export async function promote(deps: PromoteDeps, inputs: PromoteInputs): Promiseif (deps.scheduled && !(await onReleaseBranch(deps, commit))) throw new Refusal(`v${version} (${commit}) is not on master; the scheduled check only promotes a release minted from master, so a maintainer decides on this one.`);const taggedVersion = (await deps.git(['show', `${releaseRef}:VERSION`])).stdout.trim();if (taggedVersion !== version) throw new Refusal(`v${version}'s VERSION file says "${taggedVersion || 'nothing'}"; promote a tag release.yml minted for its own VERSION.`);- let release: { draft?: boolean };+ let release: { draft?: boolean; id?: unknown };try {- release = await deps.ghApi(`repos/${deps.repo}/releases/tags/v${version}`) as { draft?: boolean };+ release = await deps.ghApi(`repos/${deps.repo}/releases/tags/v${version}`) as { draft?: boolean; id?: unknown };} catch (error) {throw new Refusal(`v${version} has no published GitHub release (${(error as Error).message.split('\n')[0]}); wait for release.yml to publish it, then promote.`);}if (release.draft) throw new Refusal(`The GitHub release for v${version} is still a draft; publish it (release.yml does), then promote.`);+ if (typeof release.id !== 'number') throw new Refusal(`The GitHub release for v${version} has no id, so it cannot be marked Latest; re-run this workflow.`);+ const releaseId = release.id;deps.log(`[promote-stable] v${version} is commit ${commit}, tree ${tree}, and its GitHub release is published.`);const { runId, attempt } = parseRunUrl(inputs.soakRunUrl, deps.repo);@@ -465,6 +476,8 @@ export async function promote(deps: PromoteDeps, inputs: PromoteInputs): Promiserollback, reason,};const message = renderTagMessage(fields);+ const changelog = rollback ? null : await deps.git(['show', `${releaseRef}:CHANGELOG.md`]);+ const notes = changelog === null ? null : rolledUpNotes(changelog.code === 0 ? changelog.stdout : '', fields.previous, version, deps.repo);// The evidence record: carried forward from the previous record commit (none before the first promotion).const prior = await readPriorRecord(deps);@@ -486,24 +499,100 @@ export async function promote(deps: PromoteDeps, inputs: PromoteInputs): Promise'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}).`);+ await markLatest(deps, releaseId, version, notes, rollback);const promotion: Promotion = { ...fields, recordCreated: !recordExists, knownBad };deps.summary(renderSummary(promotion, notPromotable));return promotion;}+/** GitHub's limit on a release body is 125,000 characters; stay under it with room for the trailer. */+export const RELEASE_NOTES_MAX = 120_000;++/**+ * The stable release's notes: every CHANGELOG.md section newer than `previous` up to and including `version`, newest+ * first, under one line naming the previous stable. Oldest sections drop first when the roll-up would pass+ * RELEASE_NOTES_MAX, and a link to the full CHANGELOG at the tag says so. With no previous stable it is the release's+ * own entry; with no matching section it is the same link stub release.yml writes.+ */+export function rolledUpNotes(changelog: string, previous: string | null, version: string, repo: string): string {+ const link = `https://github.com/${repo}/blob/v${version}/CHANGELOG.md`;+ const wanted = (v: string) => compareVersions(v, version) <= 0 && (previous === null ? compareVersions(v, version) === 0 : compareVersions(v, previous) > 0);+ const sections: string[][] = [];+ let current: string[] | null = null;+ for (const line of changelog.split('\n')) {+ if (line.startsWith('## [')) {+ const v = /^## \[(\d+(?:\.\d+){2,3})\]/.exec(line)?.[1];+ current = v && wanted(v) ? [line] : null;+ if (current) sections.push(current);+ continue;+ }+ current?.push(line);+ }+ if (sections.length === 0) return `See [CHANGELOG.md](${link}) for v${version}.\n`;+ const intro = previous === null ? `Stable release v${version}.\n` : `Stable release v${version}: every change since the previous stable release, v${previous}, newest first.\n`;+ const bodies = sections.map(s => `${s.join('\n').trimEnd()}\n`);+ const kept: string[] = [];+ let size = intro.length;+ for (const body of bodies) {+ if (kept.length > 0 && size + body.length + 200 > RELEASE_NOTES_MAX) break;+ kept.push(body);+ size += body.length + 1;+ }+ if (kept[0]!.length + intro.length + 200 > RELEASE_NOTES_MAX) return `${intro}\nThe notes are too long for this page; read them in [CHANGELOG.md](${link}).\n`;+ const dropped = bodies.length - kept.length;+ const tail = dropped ? `\n${dropped} older ${dropped === 1 ? 'entry is' : 'entries are'} in [CHANGELOG.md](${link}).\n` : '';+ return [intro, ...kept].join('\n') + tail;+}++/** The version of the release GitHub calls Latest now, or null when there is none or it cannot be read. */+export async function latestReleaseVersion(deps: Pick<PromoteDeps, 'repo' | 'ghApi'>): Promise<string | null> {+ try {+ const tag = ((await deps.ghApi(`repos/${deps.repo}/releases/latest`)) as { tag_name?: string }).tag_name ?? '';+ const v = tag.replace(/^v/, '');+ return VERSION_RE.test(v) ? v : null;+ } catch {+ return null;+ }+}++/**+ * Mark a release GitHub's "Latest": clear pre-release, set make_latest, and replace the notes when `notes` is given.+ * A forward promotion never moves Latest to an older release than the current one: binaries released before+ * pre-releases existed download `releases/latest` as their newest release, so moving it back would downgrade them. Latest+ * then stays put until stable passes it. A rollback moves it back on purpose.+ */+export async function markLatest(deps: PromoteDeps, releaseId: number, version: string, notes: string | null, rollback = false): Promise<void> {+ const latest = await latestReleaseVersion(deps);+ if (!rollback && latest && compareVersions(latest, version) > 0) {+ deps.log(`[promote-stable] GitHub's Latest stays v${latest}, which is newer than v${version}; it moves to the stable release once stable passes it.`);+ return;+ }+ try {+ await deps.ghApiWrite('PATCH', `repos/${deps.repo}/releases/${releaseId}`, { prerelease: false, make_latest: 'true', ...(notes === null ? {} : { body: notes }) });+ } catch (error) {+ throw new Refusal(`stable now points at v${version}, but marking its GitHub release Latest failed (${(error as Error).message.split('\n')[0]}); run \`bun scripts/release-channel.ts backfill --apply\` from a checkout to set it (${DOCS}).`);+ }+ deps.log(`[promote-stable] the GitHub release v${version} is now Latest${notes === null ? '' : ', with notes rolled up since the previous stable'}.`);+}+export function processDeps(env: NodeJS.ProcessEnv = process.env, cwd = process.cwd()): PromoteDeps {return {repo: env.GITHUB_REPOSITORY ?? '',actor: env.GITHUB_ACTOR ?? '',soakWorkflow: env.STABLE_SOAK_WORKFLOW ?? '',async ghApi(path) {- const r = spawnSync('gh', ['api', path], { cwd, env, encoding: 'utf8' });+ const r = spawnSync('gh', ['api', path], { cwd, env, encoding: 'utf8', maxBuffer: 64 * 1024 * 1024 });if (r.status !== 0) throw new Error(`gh api ${path} failed: ${(r.stderr || r.error?.message || '').trim()}`);return JSON.parse(r.stdout);},+ async ghApiWrite(method, path, body) {+ const r = spawnSync('gh', ['api', '--method', method, path, '--input', '-'], { cwd, env, encoding: 'utf8', input: JSON.stringify(body) });+ if (r.status !== 0) throw new Error(`gh api ${method} ${path} failed: ${(r.stderr || r.error?.message || '').trim()}`);+ return JSON.parse(r.stdout || '{}');+ },async git(args, input) {- const r = spawnSync('git', args, { cwd, env, encoding: 'utf8', ...(input !== undefined ? { input } : {}) });+ const r = spawnSync('git', args, { cwd, env, encoding: 'utf8', maxBuffer: 64 * 1024 * 1024, ...(input !== undefined ? { input } : {}) });return { code: r.status ?? 1, stdout: r.stdout ?? '', stderr: r.stderr ?? '' };},now: () => new Date(),diff --git a/scripts/release-channel.ts b/scripts/release-channel.tsnew file mode 100644index 0000000000..13f96131a9--- /dev/null+++ b/scripts/release-channel.ts@@ -0,0 +1,155 @@+#!/usr/bin/env bun+/**+ * GitHub release state for the stable channel (docs/RELEASING.md#which-release-github-calls-latest).+ *+ * bun scripts/release-channel.ts backfill [--apply]+ * bun scripts/release-channel.ts undo [--apply]+ * bun scripts/release-channel.ts preview-promotion [--version <v>]+ *+ * release.yml publishes every batch release as a pre-release and promote-stable.ts marks the stable release+ * "Latest". This script brings releases published before that rule in line, takes the rule back out, or shows what a+ * promotion would write, without promoting anything. backfill and undo only print their plan unless --apply is given.+ *+ * - backfill: every published release newer than the current stable becomes a pre-release, and the stable release+ * becomes Latest with notes rolled up since the previous stable (a rollback stable keeps its notes). Releases older+ * than stable are left alone. It is also the repair when a promotion moved stable but could not mark it Latest.+ * - undo: every pre-release with a v<VERSION> tag goes back to a normal release, then the newest release by version+ * becomes Latest, which is how releases looked before. Notes are left as they are. No tag or user data moves.+ * - preview-promotion: which release would become Latest (the newest published release unless --version names one)+ * and the notes promote-stable.ts would write for it against the current stable. Writes nothing.+ *+ * Runs from a checkout with gh signed in to an account that can edit releases (apply only) and git able to fetch tags.+ */+import { compareVersions, latestReleaseVersion, parseTagMessage, processDeps, Refusal, rolledUpNotes, type PromoteDeps } from './promote-stable.ts';++export type ReleaseDeps = Pick<PromoteDeps, 'repo' | 'ghApi' | 'ghApiWrite' | 'git' | 'log'>;+export interface ReleaseRow { id: number; tag_name: string; draft: boolean; prerelease: boolean }+export interface Target { id: number; version: string }++const RELEASE_TAG = /^v(\d+\.\d+\.\d+(?:\.\d+)?)$/;+const versionOf = (r: ReleaseRow) => RELEASE_TAG.exec(r.tag_name)?.[1] ?? null;+const published = (rows: readonly ReleaseRow[]) =>+ rows.filter(r => !r.draft && versionOf(r)).map(r => ({ ...r, version: versionOf(r)! })).sort((a, b) => compareVersions(b.version, a.version));++/** Releases newer than stable that are not pre-releases yet, and the stable release itself (null when it has no published release). */+export function planBackfill(rows: readonly ReleaseRow[], stable: string): { latest: Target | null; markPrerelease: Target[]; olderUntouched: number } {+ const all = published(rows);+ const hit = all.find(r => r.version === stable);+ return {+ latest: hit ? { id: hit.id, version: hit.version } : null,+ markPrerelease: all.filter(r => compareVersions(r.version, stable) > 0 && !r.prerelease).map(r => ({ id: r.id, version: r.version })),+ olderUntouched: all.filter(r => compareVersions(r.version, stable) < 0).length,+ };+}++/** Every v<VERSION> pre-release goes back to a normal release, and the newest release becomes Latest. */+export function planUndo(rows: readonly ReleaseRow[]): { latest: Target | null; clearPrerelease: Target[] } {+ const all = published(rows);+ return {+ latest: all[0] ? { id: all[0].id, version: all[0].version } : null,+ clearPrerelease: all.filter(r => r.prerelease).map(r => ({ id: r.id, version: r.version })),+ };+}++export async function listReleases(deps: ReleaseDeps): Promise<ReleaseRow[]> {+ const out: ReleaseRow[] = [];+ for (let page = 1; page <= 50; page++) {+ const rows = await deps.ghApi(`repos/${deps.repo}/releases?per_page=100&page=${page}`) as ReleaseRow[];+ out.push(...rows.map(r => ({ id: r.id, tag_name: r.tag_name, draft: r.draft, prerelease: r.prerelease })));+ if (rows.length < 100) break;+ }+ return out;+}++/** The current stable version, the stable before it and whether it was a rollback, from the `stable` tag's message. */+export async function readStable(deps: ReleaseDeps): Promise<{ version: string; previous: string | null; rollback: boolean }> {+ const ref = await deps.ghApi(`repos/${deps.repo}/git/ref/tags/stable`) as { object?: { sha?: string; type?: string } };+ if (ref.object?.type !== 'tag' || !ref.object.sha) throw new Refusal('refs/tags/stable is not an annotated tag, so the current stable cannot be read; repair it by hand (docs/RELEASING.md#stable-channel-promotion).');+ const tag = await deps.ghApi(`repos/${deps.repo}/git/tags/${ref.object.sha}`) as { message?: string };+ const fields = parseTagMessage(tag.message ?? '');+ if (!fields) throw new Refusal('The stable tag message is not a promotion record, so the current stable cannot be read; repair it by hand (docs/RELEASING.md#stable-channel-promotion).');+ return { version: fields.version, previous: fields.previous, rollback: fields.rollback };+}++async function changelogAt(deps: ReleaseDeps, version: string): Promise<string> {+ const fetched = await deps.git(['fetch', '--no-tags', 'origin', `refs/tags/v${version}`]);+ if (fetched.code !== 0) throw new Refusal(`Could not fetch the tag v${version} (${fetched.stderr.trim().split('\n').at(-1)}); check the remote, then re-run.`);+ const shown = await deps.git(['show', 'FETCH_HEAD:CHANGELOG.md']);+ if (shown.code !== 0) throw new Refusal(`Could not read CHANGELOG.md at v${version} (${shown.stderr.trim().split('\n').at(-1)}); re-run.`);+ return shown.stdout;+}++const list = (targets: readonly Target[]) => targets.length ? targets.map(t => `v${t.version}`).join(', ') : 'none';++export async function run(deps: ReleaseDeps, argv: string[]): Promise<void> {+ const [command, ...rest] = argv;+ const apply = rest.includes('--apply');+ const latestVersion = await latestReleaseVersion(deps);+ const latestNow = latestVersion ? `v${latestVersion}` : 'none';++ if (command === 'backfill') {+ const stable = await readStable(deps);+ const plan = planBackfill(await listReleases(deps), stable.version);+ if (!plan.latest) throw new Refusal(`The stable release v${stable.version} has no published GitHub release; publish it before backfilling.`);+ if (latestVersion && compareVersions(latestVersion, stable.version) > 0) {+ throw new Refusal(`GitHub's Latest is v${latestVersion}, newer than stable v${stable.version}. Backfilling now would move Latest back, and binaries released before this change install whatever Latest is, so they would downgrade; run backfill after stable passes v${latestVersion}. Would mark pre-release: ${plan.markPrerelease.length} (${list(plan.markPrerelease)}).`);+ }+ const notes = stable.rollback ? null : rolledUpNotes(await changelogAt(deps, stable.version), stable.previous, stable.version, deps.repo);+ deps.log(`release-channel backfill (${apply ? 'apply' : 'preview: nothing written; re-run with --apply to write'})`);+ deps.log(`current Latest: ${latestNow}`);+ deps.log(`stable: v${stable.version} (previous stable ${stable.previous ? `v${stable.previous}` : 'none'}${stable.rollback ? ', a rollback' : ''})`);+ deps.log(`mark Latest: v${plan.latest.version} (${notes === null ? 'notes kept' : `notes rolled up, ${notes.length} characters`})`);+ deps.log(`mark pre-release: ${plan.markPrerelease.length} (${list(plan.markPrerelease)})`);+ deps.log(`older releases left alone: ${plan.olderUntouched}`);+ if (!apply) return;+ if ((await readStable(deps)).version !== stable.version) throw new Refusal('stable moved while the plan was being built (a promotion ran); nothing was written, re-run backfill.');+ await deps.ghApiWrite('PATCH', `repos/${deps.repo}/releases/${plan.latest.id}`, { prerelease: false, make_latest: 'true', ...(notes === null ? {} : { body: notes }) });+ for (const t of plan.markPrerelease) await deps.ghApiWrite('PATCH', `repos/${deps.repo}/releases/${t.id}`, { prerelease: true, make_latest: 'false' });+ deps.log(`applied: v${plan.latest.version} is Latest; ${plan.markPrerelease.length} marked pre-release`);+ return;+ }++ if (command === 'undo') {+ const plan = planUndo(await listReleases(deps));+ if (!plan.latest) throw new Refusal('There are no published releases, so there is nothing to undo.');+ deps.log(`release-channel undo (${apply ? 'apply' : 'preview: nothing written; re-run with --apply to write'})`);+ deps.log(`current Latest: ${latestNow}`);+ deps.log(`clear pre-release: ${plan.clearPrerelease.length} (${list(plan.clearPrerelease)})`);+ deps.log(`mark Latest: v${plan.latest.version} (the newest release)`);+ if (!apply) return;+ for (const t of plan.clearPrerelease) await deps.ghApiWrite('PATCH', `repos/${deps.repo}/releases/${t.id}`, { prerelease: false, make_latest: 'false' });+ await deps.ghApiWrite('PATCH', `repos/${deps.repo}/releases/${plan.latest.id}`, { prerelease: false, make_latest: 'true' });+ deps.log(`applied: ${plan.clearPrerelease.length} pre-releases cleared; v${plan.latest.version} is Latest`);+ return;+ }++ if (command === 'preview-promotion') {+ const flag = rest.indexOf('--version');+ const stable = await readStable(deps);+ const all = published(await listReleases(deps));+ const version = flag >= 0 ? (rest[flag + 1] ?? '').replace(/^v/, '') : all[0]?.version;+ if (!version || !all.some(r => r.version === version)) throw new Refusal(`v${version ?? '?'} has no published GitHub release; name one with --version.`);+ if (compareVersions(version, stable.version) <= 0) throw new Refusal(`v${version} is not newer than the current stable v${stable.version}; a forward promotion needs a newer release.`);+ const notes = rolledUpNotes(await changelogAt(deps, version), stable.version, version, deps.repo);+ deps.log(`release-channel preview-promotion (nothing written)`);+ deps.log(`current Latest: ${latestNow}; current stable: v${stable.version}`);+ deps.log(`promoting v${version} would make it Latest with these notes (${notes.length} characters):`);+ deps.log('-----');+ deps.log(notes.trimEnd());+ deps.log('-----');+ return;+ }++ throw new Refusal('usage: bun scripts/release-channel.ts backfill [--apply] | undo [--apply] | preview-promotion [--version <v>]');+}++if (import.meta.main) {+ const deps = processDeps();+ if (!deps.repo) deps.repo = 'garrytan/gbrain';+ try {+ await run(deps, process.argv.slice(2));+ } catch (e) {+ console.error(`release-channel: ${e instanceof Error ? e.message : String(e)}`);+ process.exit(1);+ }+}diff --git a/scripts/structural-suites.tsv b/scripts/structural-suites.tsvindex 4c2e09991a..37fa18866f 100644--- a/scripts/structural-suites.tsv+++ b/scripts/structural-suites.tsv@@ -293,6 +293,7 @@ test/register-client-source-normalize.test.ts register-client route wiring (strutest/reindex-code-recovery.test.ts CLI help line (#3970 surface 1) 1 source-surface-helpertest/release-workflow.test.ts release.yml publish-template skip is visible (D-10) 1 readFileSynctest/release-workflow.test.ts release.yml ↔ binary-self-update asset contract 12 readFileSync+test/release-workflow.test.ts which release GitHub calls Latest 3 readFileSynctest/remediation-command-resolution.test.ts #3697 — remediation text resolves against the live CLI surface 3 readFileSynctest/reranker-default-seam.test.ts DEFAULT_RERANKER_MODEL seam (#3657, flipped v0.48.2) 3 readFileSynctest/resolver.test.ts RESOLVER.md trigger round-trip (D5/C) 2 readFileSyncdiff --git a/scripts/upgrade-matrix/versions.ts b/scripts/upgrade-matrix/versions.tsindex 89a925ba57..5827dfa668 100644--- a/scripts/upgrade-matrix/versions.ts+++ b/scripts/upgrade-matrix/versions.ts@@ -70,7 +70,7 @@ function token(): string | undefined {return process.env.GITHUB_TOKEN || process.env.GH_TOKEN || undefined;}-/** Published (non-draft, non-prerelease) release tags, newest first, reading pages until 'enough' holds. */+/** Published (non-draft) release tags, newest first, reading pages until 'enough' holds. Pre-releases count: every batch release is published as one, and only the stable release is not. */export async function fetchReleases(repo: string, enough: (releases: Release[]) => boolean, fetchImpl: typeof fetch = fetch): Promise<Release[]> {const out: Release[] = [];const auth = token();@@ -79,10 +79,10 @@ export async function fetchReleases(repo: string, enough: (releases: Release[])headers: { accept: 'application/vnd.github+json', 'user-agent': 'gbrain-upgrade-matrix', ...(auth ? { authorization: 'Bearer ' + auth } : {}) },});if (!res.ok) throw new Error('GET releases page ' + page + ' returned HTTP ' + res.status + (auth ? '' : ' (unauthenticated: set GITHUB_TOKEN)'));- const rows = await res.json() as Array<{ tag_name: string; published_at: string | null; draft: boolean; prerelease: boolean }>;+ const rows = await res.json() as Array<{ tag_name: string; published_at: string | null; draft: boolean }>;for (const r of rows) {const m = RELEASE_TAG.exec(r.tag_name);- if (m && !r.draft && !r.prerelease && r.published_at) out.push({ tag: r.tag_name, version: m[1]!, published_at: r.published_at });+ if (m && !r.draft && r.published_at) out.push({ tag: r.tag_name, version: m[1]!, published_at: r.published_at });}if (rows.length < 100 || enough(out)) break;}diff --git a/src/core/binary-self-update.ts b/src/core/binary-self-update.tsindex 6aa1e7a40c..d661095d6a 100644--- a/src/core/binary-self-update.ts+++ b/src/core/binary-self-update.ts@@ -156,7 +156,27 @@ export interface BinarySelfUpdateDeps {}async function defaultFetchRelease(): Promise<{ tag: string; assets: ReleaseAsset[] } | null> {- return fetchReleaseJson('https://api.github.com/repos/garrytan/gbrain/releases/latest');+ return fetchAlphaRelease();+}++/**+ * The alpha channel's release: the version in VERSION at the `latest-stable` tag (which release.yml moves on every+ * published release), then that exact release. Not `releases/latest`: GitHub's Latest is the stable release, and+ * every batch release is published as a pre-release, so reading it would quietly put alpha binaries on stable.+ */+export async function fetchAlphaRelease(fetchImpl: typeof fetch = fetch): Promise<{ tag: string; assets: ReleaseAsset[] } | null> {+ try {+ const res = await fetchImpl('https://raw.githubusercontent.com/garrytan/gbrain/latest-stable/VERSION', {+ headers: { 'User-Agent': 'gbrain-self-upgrade' },+ signal: AbortSignal.timeout(5_000),+ });+ if (!res.ok) return null;+ const version = /^v?(\d+\.\d+\.\d+(?:\.\d+)?)(?:[-+][0-9A-Za-z.-]+)?$/.exec(((await res.text()).slice(0, 256).trim().split('\n')[0] ?? '').trim())?.[1];+ if (!version) return null;+ return fetchReleaseJson(`https://api.github.com/repos/garrytan/gbrain/releases/tags/v${version}`, fetchImpl);+ } catch {+ return null;+ }}/** GBRA-175: one named release (the stable channel's), in the same shape as the latest release. */@@ -164,9 +184,9 @@ export function fetchReleaseByTag(tag: string): Promise<{ tag: string; assets: Rreturn fetchReleaseJson(`https://api.github.com/repos/garrytan/gbrain/releases/tags/${encodeURIComponent(tag)}`);}-async function fetchReleaseJson(url: string): Promise<{ tag: string; assets: ReleaseAsset[] } | null> {+async function fetchReleaseJson(url: string, fetchImpl: typeof fetch = fetch): Promise<{ tag: string; assets: ReleaseAsset[] } | null> {try {- const res = await fetch(url, {+ const res = await fetchImpl(url, {headers: { 'User-Agent': 'gbrain-self-upgrade' },signal: AbortSignal.timeout(5_000),});diff --git a/src/core/self-upgrade.ts b/src/core/self-upgrade.tsindex b0e96072c2..757456aaa3 100644--- a/src/core/self-upgrade.ts+++ b/src/core/self-upgrade.ts@@ -706,7 +706,7 @@ export type BreadcrumbTransition = 'applied' | 'failed' | null;* - No breadcrumb → nothing to do.* - currentVersion >= breadcrumb → the swap+relaunch worked. The swap* installs whatever is current at swap time (`git pull`, `bun update`,- * `releases/latest`), so a release published after the update check lands+ * the release `latest-stable` names), so a release published after the update check lands* a NEWER version than the breadcrumb names (#5813). Clear it, record* `last_applied_version`, and drop `failed_versions` entries at or below* the running version: `decideSelfUpgrade` only acts on a strictly newerdiff --git a/test/binary-self-update-alpha-release.test.ts b/test/binary-self-update-alpha-release.test.tsnew file mode 100644index 0000000000..237149f375--- /dev/null+++ b/test/binary-self-update-alpha-release.test.ts@@ -0,0 +1,51 @@+/**+ * Alpha binary self-update resolves its release from the latest-stable tag, not GitHub's "Latest".+ *+ * Protects: every batch release is published as a pre-release and only the stable release is GitHub's Latest, so an+ * alpha binary that read releases/latest would silently ride stable. The updater reads VERSION at latest-stable and+ * fetches that exact release by tag.+ */+import { describe, expect, test } from 'bun:test';+import { fetchAlphaRelease } from '../src/core/binary-self-update.ts';++function fakeFetch(answers: Record<string, { status: number; body: string }>) {+ const urls: string[] = [];+ const impl = (async (input: string | URL | Request) => {+ const url = String(input);+ urls.push(url);+ const a = answers[url] ?? { status: 404, body: '' };+ return new Response(a.body, { status: a.status });+ }) as unknown as typeof fetch;+ return { impl, urls };+}++const VERSION_URL = 'https://raw.githubusercontent.com/garrytan/gbrain/latest-stable/VERSION';+const TAG_URL = 'https://api.github.com/repos/garrytan/gbrain/releases/tags/v0.60.722.0';++describe('fetchAlphaRelease', () => {+ test('reads VERSION at latest-stable, then fetches that exact release, never releases/latest', async () => {+ const f = fakeFetch({+ [VERSION_URL]: { status: 200, body: '0.60.722.0\n' },+ [TAG_URL]: { status: 200, body: JSON.stringify({ tag_name: 'v0.60.722.0', assets: [{ name: 'gbrain-linux-x64', browser_download_url: 'https://example.com/gbrain-linux-x64' }] }) },+ });+ expect(await fetchAlphaRelease(f.impl)).toEqual({ tag: 'v0.60.722.0', assets: [{ name: 'gbrain-linux-x64', url: 'https://example.com/gbrain-linux-x64' }] });+ expect(f.urls).toEqual([VERSION_URL, TAG_URL]);+ expect(f.urls.some(u => u.includes('releases/latest'))).toBe(false);+ });++ test('a 3-part or suffixed VERSION resolves the same release the alpha update check offers', async () => {+ const f = fakeFetch({+ [VERSION_URL]: { status: 200, body: 'v0.60.722.0-fixwave\n' },+ [TAG_URL]: { status: 200, body: JSON.stringify({ tag_name: 'v0.60.722.0', assets: [] }) },+ });+ expect((await fetchAlphaRelease(f.impl))?.tag).toBe('v0.60.722.0');+ });++ test('an unreadable or malformed VERSION, or a missing release, gives null', async () => {+ expect(await fetchAlphaRelease(fakeFetch({ [VERSION_URL]: { status: 500, body: '' } }).impl)).toBeNull();+ expect(await fetchAlphaRelease(fakeFetch({ [VERSION_URL]: { status: 200, body: '<html>not a version</html>' } }).impl)).toBeNull();+ const noRelease = fakeFetch({ [VERSION_URL]: { status: 200, body: '0.60.722.0' } });+ expect(await fetchAlphaRelease(noRelease.impl)).toBeNull();+ expect(noRelease.urls).toEqual([VERSION_URL, TAG_URL]);+ });+});diff --git a/test/release-workflow.test.ts b/test/release-workflow.test.tsindex 0c168a7f11..4408678362 100644--- a/test/release-workflow.test.ts+++ b/test/release-workflow.test.ts@@ -2,14 +2,14 @@* Contract pin between .github/workflows/release.yml and* src/core/binary-self-update.ts (#3521).*- * Binary installs download upgrade assets from `releases/latest` by the exact+ * Binary installs download upgrade assets from the release `latest-stable` names, by the exact* names expectedAssetName() returns. If the workflow's build matrix or the* release `files:` list drifts from those names, self-update silently degrades* to notify-only (`no_asset`) for everyone — this test is the guard.*/import { describe, expect, test } from 'bun:test';import { execFileSync } from 'node:child_process';-import { mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';+import { mkdtempSync, readdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';import { tmpdir } from 'node:os';import { join } from 'node:path';import { EXPECTED_BUILDER_IDS, expectedAssetName } from '../src/core/binary-self-update.ts';@@ -217,3 +217,50 @@ describe('release.yml publish-template skip is visible (D-10)', () => {}});});++describe('which release GitHub calls Latest', () => {+ test('release.yml publishes every batch release as a pre-release that never becomes Latest', () => {+ const step = WORKFLOW.slice(WORKFLOW.indexOf('- name: Create release'), WORKFLOW.indexOf('- name: Advance latest-stable'));+ expect(step).toMatch(/^\s+prerelease: true$/m);+ expect(step).toMatch(/^\s+make_latest: 'false'$/m);+ });++ test('a hand re-run that repairs the current stable release refuses instead of turning it back into a pre-release', () => {+ const job = WORKFLOW.slice(WORKFLOW.indexOf('\n release:\n'));+ const start = job.indexOf('- name: Refuse to republish the current stable release');+ expect(start).toBeGreaterThan(-1);+ expect(start).toBeLessThan(job.indexOf('- name: Create release'));+ const step = job.slice(start, job.indexOf('- name: Create release'));+ expect(step).toContain('RELEASE_SHA: ${{ needs.ci-gate.outputs.sha }}');+ const script = step.slice(step.indexOf('run: |') + 'run: |'.length).split('\n').map(l => l.replace(/^ {10}/, '')).join('\n');+ const dir = mkdtempSync(join(tmpdir(), 'release-stable-guard-'));+ try {+ writeFileSync(join(dir, 'git'), '#!/bin/sh\n[ "$1 $2 $3" = "ls-remote origin refs/tags/stable^{}" ] || exit 9\nprintf "%s\\trefs/tags/stable^{}\\n" "$STABLE_SHA"\n', { mode: 0o755 });+ const runWith = (stable: string) => {+ try {+ return { code: 0, out: execFileSync('bash', ['-c', script], { env: { PATH: `${dir}:/usr/bin:/bin`, RELEASE_SHA: 'a'.repeat(40), RELEASE_VERSION: '0.60.722.0', STABLE_SHA: stable }, encoding: 'utf8', stdio: 'pipe' }) };+ } catch (e) {+ const err = e as { status: number; stdout: string; stderr: string };+ return { code: err.status, out: err.stdout + err.stderr };+ }+ };+ const stable = runWith('a'.repeat(40));+ expect(stable.code).toBe(1);+ expect(stable.out).toContain('v0.60.722.0 is the current stable release');+ expect(runWith('b'.repeat(40))).toEqual({ code: 0, out: '' });+ expect(runWith('')).toEqual({ code: 0, out: '' });+ } finally {+ rmSync(dir, { recursive: true, force: true });+ }+ });++ test('no workflow reads releases/latest, and the macOS signature check takes its tag from latest-stable', () => {+ const dir = join(ROOT, '.github/workflows');+ for (const file of readdirSync(dir)) {+ const body = readFileSync(join(dir, file), 'utf8').split('\n').filter(l => !l.trimStart().startsWith('#')).join('\n');+ expect({ file, reads: body.includes('releases/latest') }).toEqual({ file, reads: false });+ }+ const mac = readFileSync(join(dir, 'macos-validation.yml'), 'utf8');+ expect(mac).toContain('https://raw.githubusercontent.com/garrytan/gbrain/latest-stable/VERSION');+ });+});diff --git a/test/scripts/promote-stable.test.ts b/test/scripts/promote-stable.test.tsindex 543a14a258..ae64714ff7 100644--- a/test/scripts/promote-stable.test.ts+++ b/test/scripts/promote-stable.test.ts@@ -19,7 +19,7 @@ import { tmpdir } from 'node:os';import { join } from 'node:path';import { load } from 'js-yaml';import {- checkOrder, checkSoakRun, compareVersions, mergeKnownBad, mergeNotPromotable, normaliseWorkflowPath, parseRunUrl, parseTagMessage, processDeps, promote, Refusal, renderRecord, renderSummary, renderTagMessage, STABLE_RECORD_MAX_BYTES,+ checkOrder, checkSoakRun, compareVersions, RELEASE_NOTES_MAX, rolledUpNotes, mergeKnownBad, mergeNotPromotable, normaliseWorkflowPath, parseRunUrl, parseTagMessage, processDeps, promote, Refusal, renderRecord, renderSummary, renderTagMessage, STABLE_RECORD_MAX_BYTES,type GitResult, type PromoteDeps, type PromoteInputs, type SoakRun, type TagFields,} from '../../scripts/promote-stable.ts';import { offeredVersion } from '../../src/core/self-upgrade.ts';@@ -56,6 +56,8 @@ interface FakeRepo {records?: Record<string, string>;/** The remote stable-record branch head (fetched into refs/remotes/origin/stable-record); absent before the first promotion. */recordBranch?: string;+ /** What `git show v<version>:CHANGELOG.md` prints; absent: the tag has no CHANGELOG.md. */+ changelog?: string;}const ok = (stdout = ''): GitResult => ({ code: 0, stdout: `${stdout}\n`, stderr: '' });@@ -78,6 +80,7 @@ function fakeGit(repo: FakeRepo, calls: string[]) {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(':CHANGELOG.md')) return repo.changelog === undefined ? fail : ok(repo.changelog);if (cmd === 'show' && rest[0]!.endsWith(':stable.json')) {const body = repo.records?.[rest[0]!.replace(/:stable\.json$/, '')];return body === undefined ? fail : ok(body);@@ -133,7 +136,11 @@ interface Setup {role?: { permission: string; role_name?: string };run?: SoakRun;/** The GitHub release for the tag; null: there is none (404). */- release?: { draft: boolean } | null;+ release?: { draft: boolean; id?: number } | null;+ /** Make the release edit (marking it Latest) fail. */+ failWrite?: boolean;+ /** The tag GitHub calls Latest now; absent: none. */+ latest?: string;soakWorkflow?: string;repo?: FakeRepo;}@@ -143,6 +150,7 @@ function harness(setup: Setup = {}) {const api: string[] = [];const logs: string[] = [];const summaries: string[] = [];+ const writes: Array<{ method: string; path: string; body: Record<string, unknown> }> = [];const repo: FakeRepo = setup.repo ?? {commits: { [sha('a')]: sha('1'), [sha('b')]: sha('2'), [sha('c')]: sha('3') },tags: { 'v0.60.360.0': { commit: sha('a') }, 'v0.60.361.0': { commit: sha('b') }, stable: { commit: sha('a'), object: 'tagobj-stable-old' }, 'stable-v0.60.360.0': { commit: sha('a'), object: 'tagobj-record-360' } },@@ -156,18 +164,27 @@ function harness(setup: Setup = {}) {async ghApi(path) {api.push(path);if (path.endsWith('/permission')) return setup.role ?? { permission: 'write', role_name: 'maintain' };+ if (path.endsWith('/releases/latest')) {+ if (!setup.latest) throw new Error(`gh api ${path} failed: HTTP 404: Not Found`);+ return { tag_name: setup.latest };+ }if (path.includes('/releases/tags/')) {if (setup.release === null) throw new Error(`gh api ${path} failed: HTTP 404: Not Found`);- return setup.release ?? { draft: false };+ return setup.release ?? { draft: false, id: 42 };}return run;},+ async ghApiWrite(method, path, body) {+ if (setup.failWrite) throw new Error(`gh api ${method} ${path} failed: HTTP 502`);+ writes.push({ method, path, body });+ return {};+ },git: fakeGit(repo, calls),now: () => NOW,log: line => logs.push(line),summary: md => summaries.push(md),};- return { deps, calls, api, logs, summaries, repo };+ return { deps, calls, api, logs, summaries, repo, writes };}const bad = (version: string, fixed_in = '0.60.365.0') => ({ version, reason: 'preview exceeds its statement bound', fixed_in });@@ -272,7 +289,7 @@ describe('promote', () => {const h = harness();const p = await promote(h.deps, inputs());expect(p).toMatchObject({ version: '0.60.361.0', commit: sha('b'), tree: sha('2'), previous: '0.60.360.0', scoreboard: RUN_URL, recordCreated: true, promotedAt: '2026-10-21T17:00:00Z' });- expect(h.api).toEqual([`repos/${REPO}/collaborators/alice-example/permission`, `repos/${REPO}/releases/tags/v0.60.361.0`, `repos/${REPO}/actions/runs/123456`]);+ expect(h.api).toEqual([`repos/${REPO}/collaborators/alice-example/permission`, `repos/${REPO}/releases/tags/v0.60.361.0`, `repos/${REPO}/actions/runs/123456`, `repos/${REPO}/releases/latest`]);const pushes = h.calls.filter(c => c.startsWith('push'));expect(pushes).toEqual([`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`,@@ -532,8 +549,9 @@ describe('promote against real git', () => {const deps = (version: string): PromoteDeps => ({...processDeps(env, work), repo: REPO, actor: 'alice-example', soakWorkflow: 'soak.yml', now: () => NOW, log: () => {}, summary: () => {},ghApi: async path => (path.endsWith('/permission') ? { permission: 'admin', role_name: 'admin' }- : path.includes('/releases/tags/') ? { draft: false }+ : path.includes('/releases/tags/') ? { draft: false, id: 7 }: { ...run, head_sha: git(work, 'rev-parse', `v${version}^{commit}`) }),+ ghApiWrite: async () => ({}),});await promote(deps('1.0.0'), inputs({ version: '1.0.0' }));@@ -650,7 +668,7 @@ describe('stable.json bridge for a stable promoted before the evidence record (Gtest('the soak run is verified again: a failed run writes nothing', async () => {const h = preRecord();- h.deps.ghApi = async path => (path.endsWith('/permission') ? { permission: 'admin' } : path.includes('/releases/') ? { draft: false } : { status: 'completed', conclusion: 'failure', path: SOAK, head_sha: sha('b') });+ h.deps.ghApi = async path => (path.endsWith('/permission') ? { permission: 'admin' } : path.includes('/releases/') ? { draft: false, id: 42 } : { status: 'completed', conclusion: 'failure', path: SOAK, head_sha: sha('b') });await refusedAsync(promote(h.deps, inputs()), /concluded failure, not success/);expect(h.calls.filter(c => c.startsWith('push'))).toEqual([]);});@@ -689,7 +707,8 @@ describe('stable.json bridge for a stable promoted before the evidence record (Gconst env = { ...process.env, GIT_CONFIG_NOSYSTEM: '1', GIT_TERMINAL_PROMPT: '0' };const deps = (): PromoteDeps => ({...processDeps(env, work), repo: REPO, actor: 'alice-example', soakWorkflow: 'soak.yml', now: () => NOW, log: () => {}, summary: () => {},- ghApi: async path => (path.endsWith('/permission') ? { permission: 'admin', role_name: 'admin' } : path.includes('/releases/tags/') ? { draft: false } : { status: 'completed', conclusion: 'success', path: SOAK, head_sha: commit }),+ ghApi: async path => (path.endsWith('/permission') ? { permission: 'admin', role_name: 'admin' } : path.includes('/releases/tags/') ? { draft: false, id: 7 } : { status: 'completed', conclusion: 'success', path: SOAK, head_sha: commit }),+ ghApiWrite: async () => ({}),});await promote(deps(), inputs({ version: '1.0.0' }));@@ -753,3 +772,106 @@ describe('promote-stable.yml', () => {expect(workflowYml).not.toMatch(/bun install|ci-bun-install/);});});++describe('GitHub Latest release', () => {+ const CHANGELOG = [+ '# Changelog', '',+ '## [0.60.362.0] - 2026-10-22', '', 'Newer than the release.', '',+ '## [0.60.361.0] - 2026-10-21', '', 'Second change.', '',+ '## [0.60.360.5] - 2026-10-21', '', 'First change since stable.', '',+ '## [0.60.360.0] - 2026-10-20', '', 'The previous stable.', '',+ ].join('\n');++ test('rolledUpNotes takes every entry after the previous stable up to the release, newest first', () => {+ const notes = rolledUpNotes(CHANGELOG, '0.60.360.0', '0.60.361.0', REPO);+ expect(notes.split('\n')[0]).toBe('Stable release v0.60.361.0: every change since the previous stable release, v0.60.360.0, newest first.');+ expect(notes).toContain('## [0.60.361.0] - 2026-10-21\n\nSecond change.');+ expect(notes).toContain('## [0.60.360.5] - 2026-10-21\n\nFirst change since stable.');+ expect(notes.indexOf('0.60.361.0] -')).toBeLessThan(notes.indexOf('0.60.360.5] -'));+ expect(notes).not.toContain('Newer than the release.');+ expect(notes).not.toContain('The previous stable.');+ });++ test('rolledUpNotes with no previous stable is the release entry; with no entry it is the CHANGELOG link', () => {+ const first = rolledUpNotes(CHANGELOG, null, '0.60.361.0', REPO);+ expect(first).toContain('Second change.');+ expect(first).not.toContain('First change since stable.');+ expect(rolledUpNotes('', '0.60.360.0', '0.60.361.0', REPO)).toBe(`See [CHANGELOG.md](https://github.com/${REPO}/blob/v0.60.361.0/CHANGELOG.md) for v0.60.361.0.\n`);+ });++ test('rolledUpNotes drops the oldest entries past GitHub\'s size limit and links the rest', () => {+ const big = (v: string) => [`## [${v}] - 2026-10-21`, '', 'x'.repeat(50_000), ''].join('\n');+ const notes = rolledUpNotes(['0.60.363.0', '0.60.362.0', '0.60.361.0'].map(big).join('\n'), '0.60.360.0', '0.60.363.0', REPO);+ expect(notes.length).toBeLessThanOrEqual(RELEASE_NOTES_MAX);+ expect(notes).toContain('## [0.60.363.0]');+ expect(notes).not.toContain('## [0.60.361.0]');+ expect(notes).toContain(`1 older entry is in [CHANGELOG.md](https://github.com/${REPO}/blob/v0.60.363.0/CHANGELOG.md).`);+ });++ test('a forward promotion marks the release Latest, clears pre-release and writes the rolled-up notes, after the push', async () => {+ const h = harness();+ h.repo.changelog = CHANGELOG;+ await promote(h.deps, inputs());+ expect(h.writes).toHaveLength(1);+ expect(h.writes[0]).toMatchObject({ method: 'PATCH', path: `repos/${REPO}/releases/42`, body: { prerelease: false, make_latest: 'true' } });+ expect(h.writes[0]!.body.body).toBe(rolledUpNotes(CHANGELOG, '0.60.360.0', '0.60.361.0', REPO));+ expect(h.calls.findIndex(c => c.startsWith('push'))).toBeGreaterThanOrEqual(0);+ expect(h.logs.at(-1)).toContain('the GitHub release v0.60.361.0 is now Latest, with notes rolled up');+ });++ test('a rollback marks the older release Latest and keeps its notes', async () => {+ const h = harness({ run: { status: 'completed', conclusion: 'success', path: SOAK, head_sha: sha('c') } });+ h.repo.tags['v0.60.359.0'] = { commit: sha('c') };+ await promote(h.deps, inputs({ version: '0.60.359.0', rollback: true, reason: 'regression in 0.60.360.0' }));+ expect(h.writes).toHaveLength(1);+ expect(h.writes[0]!.body).toEqual({ prerelease: false, make_latest: 'true' });+ });++ test('a failed push marks nothing Latest; a failed release edit after the push says stable moved and names the repair', async () => {+ const pushFails = harness();+ pushFails.repo.failPush = true;+ await refusedAsync(promote(pushFails.deps, inputs()), /Moving the stable tag failed/);+ expect(pushFails.writes).toHaveLength(0);++ const editFails = harness({ failWrite: true });+ await refusedAsync(promote(editFails.deps, inputs()), /stable now points at v0\.60\.361\.0, but marking its GitHub release Latest failed \(gh api PATCH .* HTTP 502\); run `bun scripts\/release-channel\.ts backfill --apply`/);+ expect(editFails.repo.remote!.stable).not.toBe('tagobj-stable-old');+ });++ test('rolledUpNotes keeps an entry\'s own ## sub-headings, like its upgrade steps', () => {+ const changelog = ['## [0.60.361.0] - 2026-10-21', '', 'Lead.', '', '## To take advantage of v0.60.361.0', '', 'Run gbrain upgrade.', '', '### Itemized changes', '- one', '', '## [0.60.360.0] - 2026-10-20', 'old', ''].join('\n');+ const notes = rolledUpNotes(changelog, '0.60.360.0', '0.60.361.0', REPO);+ expect(notes).toContain('## To take advantage of v0.60.361.0\n\nRun gbrain upgrade.');+ expect(notes).toContain('### Itemized changes\n- one');+ expect(notes).not.toContain('old');+ });++ test('rolledUpNotes links the CHANGELOG instead of writing an entry too long for GitHub', () => {+ const notes = rolledUpNotes(['## [0.60.361.0] - 2026-10-21', '', 'x'.repeat(125_000), ''].join('\n'), '0.60.360.0', '0.60.361.0', REPO);+ expect(notes.length).toBeLessThan(1000);+ expect(notes).toContain(`read them in [CHANGELOG.md](https://github.com/${REPO}/blob/v0.60.361.0/CHANGELOG.md)`);+ });++ test('a forward promotion never moves Latest back to an older release; a rollback does', async () => {+ const forward = harness({ latest: 'v0.60.365.0' });+ forward.repo.changelog = CHANGELOG;+ await promote(forward.deps, inputs());+ expect(forward.writes).toEqual([]);+ expect(forward.logs.at(-1)).toContain("GitHub's Latest stays v0.60.365.0, which is newer than v0.60.361.0");++ const same = harness({ latest: 'v0.60.360.0' });+ await promote(same.deps, inputs());+ expect(same.writes).toHaveLength(1);++ const back = harness({ latest: 'v0.60.365.0', run: { status: 'completed', conclusion: 'success', path: SOAK, head_sha: sha('c') } });+ back.repo.tags['v0.60.359.0'] = { commit: sha('c') };+ await promote(back.deps, inputs({ version: '0.60.359.0', rollback: true, reason: 'regression in 0.60.360.0' }));+ expect(back.writes).toHaveLength(1);+ });++ test('a release with no id refuses before anything moves', async () => {+ const h = harness({ release: { draft: false } });+ await refusedAsync(promote(h.deps, inputs()), /has no id, so it cannot be marked Latest/);+ expect(h.calls.some(c => c.startsWith('push'))).toBe(false);+ });+});diff --git a/test/scripts/release-channel.test.ts b/test/scripts/release-channel.test.tsnew file mode 100644index 0000000000..579d48d412--- /dev/null+++ b/test/scripts/release-channel.test.ts@@ -0,0 +1,104 @@+/**+ * scripts/release-channel.ts: bring published releases in line with "stable is GitHub's Latest", or take it out.+ *+ * Protects: the backfill marks only releases newer than stable as pre-releases and makes stable Latest with rolled-up+ * notes; undo clears every pre-release and makes the newest release Latest; both write nothing without --apply; the+ * promotion preview writes nothing and shows the notes promote-stable.ts would write.+ */+import { describe, expect, test } from 'bun:test';+import { planBackfill, planUndo, run, type ReleaseDeps, type ReleaseRow } from '../../scripts/release-channel.ts';+import { renderTagMessage, rolledUpNotes } from '../../scripts/promote-stable.ts';++const REPO = 'garrytan/gbrain';+const row = (id: number, version: string, prerelease = false, draft = false): ReleaseRow => ({ id, tag_name: `v${version}`, draft, prerelease });+const RELEASES = [row(5, '1.0.5'), row(4, '1.0.4', true), row(3, '1.0.3'), row(2, '1.0.2'), row(1, '1.0.1'), row(9, '1.0.6', false, true), { id: 8, tag_name: 'nightly', draft: false, prerelease: false }];+const CHANGELOG = ['## [1.0.5] - d', 'five', '## [1.0.4] - d', 'four', '## [1.0.3] - d', 'three', '## [1.0.2] - d', 'two', '## [1.0.1] - d', 'one', ''].join('\n');++function fakeDeps(stable = '1.0.3', previous: string | null = '1.0.1', rollback = false, latest = `v${stable}`) {+ const logs: string[] = [];+ const writes: Array<{ path: string; body: Record<string, unknown> }> = [];+ let reads = 0;+ const messageFor = (v: string) => renderTagMessage({ version: v, commit: 'a'.repeat(40), tree: 'b'.repeat(40), soakRun: 'https://example.com/run', scoreboard: 'https://example.com/run', promotedBy: 'alice-example', promotedAt: '2026-11-14T00:00:00Z', previous, rollback, reason: rollback ? 'regression' : '' });+ const deps: ReleaseDeps = {+ repo: REPO,+ async ghApi(path) {+ if (path.endsWith('/git/ref/tags/stable')) return { object: { sha: 'c'.repeat(40), type: 'tag' } };+ if (path.includes('/git/tags/')) return { message: messageFor(reads++ === 0 ? stable : f.movedTo ?? stable) };+ if (path.endsWith('/releases/latest')) return { tag_name: latest };+ if (path.includes('/releases?')) return path.endsWith('page=1') ? RELEASES : [];+ throw new Error(`unexpected api ${path}`);+ },+ async ghApiWrite(_method, path, body) { writes.push({ path, body }); return {}; },+ async git(args) { return args[0] === 'show' ? { code: 0, stdout: CHANGELOG, stderr: '' } : { code: 0, stdout: '', stderr: '' }; },+ log: line => logs.push(line),+ };+ const f: { deps: ReleaseDeps; logs: string[]; writes: typeof writes; movedTo?: string } = { deps, logs, writes };+ return f;+}++describe('plans', () => {+ test('backfill marks only non-pre-release releases newer than stable, and makes stable Latest', () => {+ expect(planBackfill(RELEASES, '1.0.3')).toEqual({ latest: { id: 3, version: '1.0.3' }, markPrerelease: [{ id: 5, version: '1.0.5' }], olderUntouched: 2 });+ expect(planBackfill(RELEASES, '1.0.9').latest).toBeNull();+ });++ test('undo clears every pre-release and makes the newest published release Latest', () => {+ expect(planUndo(RELEASES)).toEqual({ latest: { id: 5, version: '1.0.5' }, clearPrerelease: [{ id: 4, version: '1.0.4' }] });+ });+});++describe('run', () => {+ test('backfill without --apply prints the plan and writes nothing', async () => {+ const f = fakeDeps();+ await run(f.deps, ['backfill']);+ expect(f.writes).toEqual([]);+ expect(f.logs).toContain('mark pre-release: 1 (v1.0.5)');+ expect(f.logs.some(l => l.startsWith('mark Latest: v1.0.3 (notes rolled up'))).toBe(true);+ });++ test('backfill --apply makes stable Latest with rolled-up notes first, then marks the newer releases pre-release', async () => {+ const f = fakeDeps();+ await run(f.deps, ['backfill', '--apply']);+ expect(f.writes).toEqual([+ { path: `repos/${REPO}/releases/3`, body: { prerelease: false, make_latest: 'true', body: rolledUpNotes(CHANGELOG, '1.0.1', '1.0.3', REPO) } },+ { path: `repos/${REPO}/releases/5`, body: { prerelease: true, make_latest: 'false' } },+ ]);+ });++ test('backfill refuses while GitHub\'s Latest is newer than stable, and writes nothing if stable moves mid-run', async () => {+ const ahead = fakeDeps('1.0.3', '1.0.1', false, 'v1.0.5');+ await expect(run(ahead.deps, ['backfill', '--apply'])).rejects.toThrow(/GitHub's Latest is v1\.0\.5, newer than stable v1\.0\.3\. Backfilling now would move Latest back.*Would mark pre-release: 1 \(v1\.0\.5\)/);+ expect(ahead.writes).toEqual([]);+ const moved = fakeDeps();+ moved.movedTo = '1.0.5';+ await expect(run(moved.deps, ['backfill', '--apply'])).rejects.toThrow(/stable moved while the plan was being built/);+ expect(moved.writes).toEqual([]);+ });++ test('backfill keeps a rollback stable\'s notes', async () => {+ const f = fakeDeps('1.0.3', '1.0.5', true);+ await run(f.deps, ['backfill', '--apply']);+ expect(f.writes[0]!.body).toEqual({ prerelease: false, make_latest: 'true' });+ });++ test('undo --apply clears pre-releases without making them Latest, then makes the newest Latest', async () => {+ const preview = fakeDeps();+ await run(preview.deps, ['undo']);+ expect(preview.writes).toEqual([]);+ const f = fakeDeps();+ await run(f.deps, ['undo', '--apply']);+ expect(f.writes).toEqual([+ { path: `repos/${REPO}/releases/4`, body: { prerelease: false, make_latest: 'false' } },+ { path: `repos/${REPO}/releases/5`, body: { prerelease: false, make_latest: 'true' } },+ ]);+ });++ test('preview-promotion shows the newest release\'s notes rolled up since stable and writes nothing', async () => {+ const f = fakeDeps();+ await run(f.deps, ['preview-promotion']);+ expect(f.writes).toEqual([]);+ expect(f.logs).toContain('promoting v1.0.5 would make it Latest with these notes (' + rolledUpNotes(CHANGELOG, '1.0.3', '1.0.5', REPO).length + ' characters):');+ expect(f.logs.join('\n')).toContain('Stable release v1.0.5: every change since the previous stable release, v1.0.3, newest first.');+ await expect(run(f.deps, ['preview-promotion', '--version', '1.0.2'])).rejects.toThrow(/not newer than the current stable v1\.0\.3/);+ });+});diff --git a/test/scripts/stable-daily.test.ts b/test/scripts/stable-daily.test.tsindex ee91e16511..decfa62295 100644--- a/test/scripts/stable-daily.test.ts+++ b/test/scripts/stable-daily.test.ts@@ -134,7 +134,7 @@ function world(w: World) {const run = runs.find(r => path.endsWith(`/${r.id}`))!;return { status: run.status, conclusion: run.conclusion, path: '.github/workflows/production-soak.yml', head_sha: run.head_sha };}- if (path.includes('/releases/tags/')) return { draft: false };+ if (path.includes('/releases/tags/')) return { draft: false, id: 42 };if (path.endsWith('/permission')) return { permission: 'none' };throw new Error(`unexpected api ${path}`);},@@ -143,6 +143,7 @@ function world(w: World) {log: line => logs.push(line),summary: () => {},async ghPost(path, body) { posts.push({ path, body }); },+ async ghApiWrite() { return {}; },async scoreboards(id) { return runs.find(r => r.id === id)?.boards ?? CLEAN; },};return { deps, posts, pushes, api, logs, tags, record: () => (record.head ? objects[record.head] : undefined) };diff --git a/test/scripts/upgrade-matrix-fetch-releases.test.ts b/test/scripts/upgrade-matrix-fetch-releases.test.tsnew file mode 100644index 0000000000..a7473bc453--- /dev/null+++ b/test/scripts/upgrade-matrix-fetch-releases.test.ts@@ -0,0 +1,24 @@+/**+ * The upgrade matrix's release list counts pre-releases.+ *+ * Protects: every batch release is published as a pre-release, so a list that skipped them would see only the+ * promoted stable releases, shift what N-1/N-10/N-50 mean and fail the 50-older-releases history check for months.+ * Drafts and unpublished rows still stay out.+ */+import { describe, expect, test } from 'bun:test';+import { fetchReleases } from '../../scripts/upgrade-matrix/versions.ts';++describe('fetchReleases', () => {+ test('keeps published pre-releases and normal releases, drops drafts, unpublished rows and other tags', async () => {+ const rows = [+ { tag_name: 'v0.60.722.0', published_at: '2026-11-14T20:00:00Z', draft: false, prerelease: true },+ { tag_name: 'v0.60.717.0', published_at: '2026-11-14T08:00:00Z', draft: false, prerelease: false },+ { tag_name: 'v0.60.716.0', published_at: '2026-11-14T07:00:00Z', draft: true, prerelease: true },+ { tag_name: 'v0.60.715.0', published_at: null, draft: false, prerelease: true },+ { tag_name: 'stable', published_at: '2026-11-14T08:00:00Z', draft: false, prerelease: false },+ ];+ const impl = (async () => new Response(JSON.stringify(rows), { status: 200 })) as unknown as typeof fetch;+ const out = await fetchReleases('garrytan/gbrain', () => true, impl);+ expect(out.map(r => r.version)).toEqual(['0.60.722.0', '0.60.717.0']);+ });+});diff --git a/test/self-upgrade.test.ts b/test/self-upgrade.test.tsindex fe65252633..3b8f2d6e65 100644--- a/test/self-upgrade.test.ts+++ b/test/self-upgrade.test.ts@@ -308,7 +308,7 @@ describe('reconcileBreadcrumb', () => {expect(r.state.failed_versions).toEqual(['0.43.0']);});// #5813: the swap installs whatever is current at swap time (git pull, bun- // update, releases/latest), so the relaunched binary can be NEWER than the+ // update, the release latest-stable names), so the relaunched binary can be NEWER than the// version the breadcrumb recorded from the update cache.const appliedCases: Array<{ name: string; su: SelfUpgradeState; running: string; failed: string[] | undefined }> = [{ name: 'running newer than attempted', su: { attempting_version: '0.60.22.0' }, running: '0.60.25.0', failed: undefined },