Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
GBRA-346: stable.json bridge for stable releases promoted before the evidence record
garrytan8cc427564b72
diff --git a/.github/workflows/promote-stable.yml b/.github/workflows/promote-stable.ymlindex 7cc55093cd..d9c2728837 100644--- a/.github/workflows/promote-stable.yml+++ b/.github/workflows/promote-stable.yml@@ -15,7 +15,10 @@ name: Promote stable# 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).+# against refs/tags/stable^{} (src/core/stable-channel.ts). Dispatching the+# current stable version again moves no tag and writes the record from the+# stable tag's message when the published one does not name it (the one-time+# backfill for promotions made before the record existed, GBRA-346).## Inputs reach the script through env only, never interpolated into run:# (script injection). No dependency install runs in this job, so thediff --git a/CHANGELOG.md b/CHANGELOG.mdindex 2c10fce255..b87d4c7996 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -28,7 +28,7 @@ gbrain publishes a release for nearly every merged change, more than a hundred a| 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` |+| `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`; promoting the current stable again writes its record from the stable tag's message, moving no tag (the one-time backfill for releases promoted before the record existed) |Install commands now name `stable` (`bun install -g github:garrytan/gbrain#stable`), so a new install starts on the channel it follows. Every install surface goes through one constant (`src/core/install-ref.ts`), checked by `bun run check:install-ref`; `latest-stable` still installs the newest release for anyone who pins it.diff --git a/docs/RELEASING.md b/docs/RELEASING.mdindex faf303920f..2dced49191 100644--- a/docs/RELEASING.md+++ b/docs/RELEASING.md@@ -640,8 +640,10 @@ gh workflow run promote-stable.yml -f version=<VERSION> \run's head commit, even when the version string matches; soak the releaseitself, then promote that run.- **Ordering and rollback.** The version must be newer than the current- stable (numeric 3- or 4-part comparison); promoting the current stable is a- no-op refusal. `rollback=true` with a `reason` moves stable to an older+ stable (numeric 3- or 4-part comparison). Promoting the current stable+ again moves no tag: it writes `stable.json` when the published record does+ not already name that release (see the backfill below), and is a no-op+ refusal otherwise. `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, `stable` and the `stable-record`@@ -651,6 +653,28 @@ gh workflow run promote-stable.yml -f version=<VERSION> \clean 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,scoreboard, previous stable and rollback reason.+- **Record backfill (one time, GBRA-346).** Promotions made before this+ script wrote the evidence record moved `stable` with no `stable.json`,+ and a client that has the stable channel reads only the record, so it+ would report `stable_missing`. Before the first release with the channel+ client publishes, write the record for the current stable by promoting it+ again with the soak run its tag names:++ ```bash+ git fetch --tags --force origin+ git for-each-ref --format='%(contents)' refs/tags/stable # version: and soak_run: lines+ gh workflow run promote-stable.yml [--ref <branch with this script>] \+ -f version=<that version> -f soak_run_url=<that soak_run>+ ```++ The run re-checks the release and the soak run, requires the tag message to+ name the same release, tree and soak run, writes `stable.json` from it+ (`known_bad` carried forward, `withdraw` accepted) and pushes only the+ record branch, leasing `stable` unchanged. Running it from a branch before+ the client merges is safe: older clients never read the record. Repeat it+ after any promotion a pre-record copy of this script makes; a record that+ already names the current stable makes the run a no-op refusal. Every+ later promotion writes the record itself.### The `publish-template` jobdiff --git a/docs/architecture/key-files/ci-health-and-test-guards.md b/docs/architecture/key-files/ci-health-and-test-guards.mdindex 2f691b604d..ede851810d 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,7 @@ 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`, `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`.+- `.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 (no rollback) moves no tag: `recordCurrentStable()` writes `stable.json` from the stable tag's message (`parseTagMessage()`, which must name the same commit, tree and soak run) when the published record does not name that release, leasing `stable` unchanged and the record branch, and refuses as a no-op otherwise (GBRA-346 backfill for releases promoted before the record existed). 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).diff --git a/scripts/promote-stable.ts b/scripts/promote-stable.tsindex 6e2169725a..ea8c3244a8 100644--- a/scripts/promote-stable.ts+++ b/scripts/promote-stable.ts@@ -18,7 +18,9 @@* 4. the run's head commit has the release tree (the same bytes, not merely* the same version);* 5. the version is strictly newer than the current stable, unless this is a- * rollback with a reason; re-promoting the current stable is a no-op;+ * rollback with a reason; promoting the current stable again moves no+ * tag and only writes its evidence record when the published one does+ * not name it (recordCurrentStable, the GBRA-346 backfill), else no-ops;* 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();@@ -191,6 +193,31 @@ export function renderTagMessage(f: TagFields): string {].join('\n');}+/**+ * The fields a promotion wrote into the stable tag's message (renderTagMessage), or null when the message is not one.+ * GBRA-346: promotions made before the evidence record existed left only this message, so it is what stable.json is+ * backfilled from when the current stable is promoted again (recordCurrentStable).+ */+export function parseTagMessage(message: string): TagFields | null {+ if (!message.startsWith('gbrain stable channel: v')) return null;+ const kv = new Map<string, string>();+ for (const line of message.split('\n')) {+ const m = /^([a-z_]+): (.+)$/.exec(line);+ if (m && !kv.has(m[1]!)) kv.set(m[1]!, m[2]!);+ }+ const [version, commit, tree, soakRun, scoreboard, promotedBy, promotedAt, previous, rollback, reason] =+ ['version', 'commit', 'tree', 'soak_run', 'scoreboard', 'promoted_by', 'promoted_at', 'previous', 'rollback', 'reason'].map(k => kv.get(k));+ if (!version || !VERSION_RE.test(version) || !commit || !SHA_RE.test(commit) || !tree || !SHA_RE.test(tree)) return null;+ if (!soakRun || !scoreboard || !promotedBy || !promotedAt || !reason || (rollback !== 'true' && rollback !== 'false')) return null;+ if (!previous || (previous !== 'none' && !VERSION_RE.test(previous))) return null;+ return {+ version, commit, tree, soakRun, scoreboard, promotedBy, promotedAt,+ previous: previous === 'none' ? null : previous,+ rollback: rollback === 'true',+ reason: reason === '-' ? '' : reason,+ };+}+export function renderSummary(p: Promotion): string {const rows: Array<[string, string]> = [['Version', `v${p.version}`],@@ -229,6 +256,70 @@ export async function currentStable(deps: PromoteDeps): Promise<{ version: strinreturn { version: versions.sort(compareVersions).at(-1)!, tagObject };}+interface PriorRecord { commit: string; version: string | null; releaseCommit: string | null; knownBad: string[] }++/** The published evidence record (the remote stable-record head), or null before the first record. */+async function readPriorRecord(deps: PromoteDeps): Promise<PriorRecord | null> {+ await deps.git(['fetch', '--no-tags', 'origin', `+${RECORD_BRANCH_REF}:${RECORD_REMOTE_REF}`]);+ if (!(await refExists(deps, `${RECORD_REMOTE_REF}^{commit}`))) return null;+ const commit = await gitOut(deps, ['rev-parse', `${RECORD_REMOTE_REF}^{commit}`], `Could not resolve ${RECORD_REMOTE_REF}; re-run this workflow.`);+ const shown = await deps.git(['show', `${commit}:${RECORD_FILE}`]);+ let prior: { version?: unknown; commit?: unknown; known_bad?: unknown };+ try {+ prior = JSON.parse(shown.stdout);+ } catch {+ throw new Refusal(`The previous stable record (${commit}:${RECORD_FILE}) is not JSON, so its known_bad list cannot be carried forward; repair the stable-record branch by hand (${DOCS}).`);+ }+ return {+ commit,+ version: typeof prior.version === 'string' ? prior.version : null,+ releaseCommit: typeof prior.commit === 'string' ? prior.commit : null,+ knownBad: Array.isArray(prior.known_bad) ? prior.known_bad.filter((v): v is string => typeof v === 'string' && VERSION_RE.test(v)) : [],+ };+}++/** Commit stable.json for `fields` on top of the previous record commit (none before the first record). */+async function commitRecord(deps: PromoteDeps, fields: TagFields, knownBad: string[], parent: string | null): Promise<string> {+ 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, ...(parent ? ['-p', parent] : []), '-m', `stable record: v${fields.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'}).`);+ return recordCommit;+}++/**+ * GBRA-346 bridge: promoting the current stable again writes its stable.json and moves no tag. Promotions made before+ * the evidence record existed moved `stable` without one, so a client that reads only the record would see+ * `stable_missing`. The record is the stable tag's own message (the release, its tree and the soak run it was promoted+ * on), checked against the release just verified and the soak run passed in, with known_bad carried forward. The push+ * leases both `stable` (re-pushed unchanged) and the record branch, so a stable tag moved since it was read refuses.+ */+async function recordCurrentStable(deps: PromoteDeps, inputs: PromoteInputs, release: { version: string; commit: string; tree: string }, current: { tagObject: string }): Promise<Promotion> {+ const { version, commit, tree } = release;+ const already = `v${version} is already the stable release`;+ const tagged = parseTagMessage((await deps.git(['for-each-ref', '--format=%(contents)', STABLE_REF])).stdout);+ if (!tagged || tagged.version !== version) throw new Refusal(`${already}, but the stable tag carries no promotion message for it (the key: value body this script writes) to write stable.json from; write the record by hand (${DOCS}).`);+ if (tagged.commit !== commit) throw new Refusal(`${already}, but the stable tag's message names commit ${tagged.commit}, not v${version}'s commit ${commit}; investigate the stable tag before writing its record (${DOCS}).`);+ if (tagged.tree !== tree) throw new Refusal(`${already}, but the stable tag's message names tree ${tagged.tree}, not v${version}'s tree ${tree}; investigate the stable tag before writing its record (${DOCS}).`);+ if (tagged.soakRun !== inputs.soakRunUrl.trim()) throw new Refusal(`${already}, promoted on soak run ${tagged.soakRun}, not ${inputs.soakRunUrl.trim()}; pass the soak run the stable tag names to write its record.`);++ const prior = await readPriorRecord(deps);+ const knownBad = mergeKnownBad(prior?.knownBad ?? [], inputs.withdraw ?? [], version);+ if (prior && prior.version === version && prior.releaseCommit === commit && knownBad.length === new Set(prior.knownBad).size) {+ throw new Refusal(`${already}, and stable.json on stable-record records it, so there is nothing to promote.`);+ }+ deps.log(`[promote-stable] ${already}; writing its stable.json from the stable tag's message (${prior ? `the record named v${prior.version ?? 'nothing'}` : 'no record was published'}).`);+ const recordCommit = await commitRecord(deps, tagged, knownBad, prior?.commit ?? null);+ await gitOut(deps, ['push', '--atomic', `--force-with-lease=${STABLE_REF}:${current.tagObject}`, `--force-with-lease=${RECORD_BRANCH_REF}:${prior?.commit ?? ''}`, 'origin',+ `${STABLE_REF}:${STABLE_REF}`, `${recordCommit}:${RECORD_BRANCH_REF}`],+ 'Writing the stable record failed and nothing changed on the remote (stable or the record may have moved since this run read them); re-run this workflow, which re-reads both.');+ deps.log(`[promote-stable] stable.json now records v${version} (${commit}); no tag moved.`);+ const promotion: Promotion = { ...tagged, recordCreated: false, knownBad };+ deps.summary(renderSummary(promotion));+ return promotion;+}+export async function promote(deps: PromoteDeps, inputs: PromoteInputs): Promise<Promotion> {const { version, rollback, reason } = inputs;@@ -269,6 +360,7 @@ export async function promote(deps: PromoteDeps, inputs: PromoteInputs): Promisedeps.log(`[promote-stable] the soak ran the release's exact tree ${tree}.`);const current = await currentStable(deps);+ if (current && !rollback && compareVersions(version, current.version) === 0) return recordCurrentStable(deps, inputs, { version, commit, tree }, current);checkOrder(version, current?.version ?? null, rollback, reason);deps.log(`[promote-stable] current stable is ${current ? `v${current.version}` : 'none'}; ${rollback ? `rollback to v${version}: ${reason.trim()}` : `v${version} is newer`}.`);@@ -293,26 +385,10 @@ export async function promote(deps: PromoteDeps, inputs: PromoteInputs): Promiseconst 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'}).`);+ const prior = await readPriorRecord(deps);+ const priorRecordCommit = prior?.commit ?? null;+ const knownBad = mergeKnownBad(prior?.knownBad ?? [], inputs.withdraw ?? [], version);+ const recordCommit = await commitRecord(deps, fields, knownBad, priorRecordCommit);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.`);diff --git a/test/scripts/promote-stable.test.ts b/test/scripts/promote-stable.test.tsindex b5623cc5ca..13ca4d586c 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, normaliseWorkflowPath, parseRunUrl, processDeps, promote, Refusal, renderRecord, renderSummary, renderTagMessage,+ checkOrder, checkSoakRun, compareVersions, mergeKnownBad, normaliseWorkflowPath, parseRunUrl, parseTagMessage, 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';@@ -119,6 +119,10 @@ function fakeGit(repo: FakeRepo, calls: string[]) {return repo.tags[ref] ? ok(repo.versionFile ?? ref.replace(/^v/, '')) : fail;}if (cmd === 'fetch') return ok();+ if (cmd === 'for-each-ref' && rest[0] === '--format=%(contents)') {+ const tag = repo.tags[rest[1]!.replace(/^refs\/tags\//, '')];+ return tag ? ok(tag.message ?? '') : fail;+ }return fail;};}@@ -492,6 +496,141 @@ describe('promote against real git', () => {});});+describe('stable.json bridge for a stable promoted before the evidence record (GBRA-346)', () => {+ const prior: TagFields = {+ version: '0.60.361.0', commit: sha('b'), tree: sha('2'), soakRun: RUN_URL, scoreboard: RUN_URL,+ promotedBy: 'alice-example', promotedAt: '2026-10-20T09:00:00Z', previous: '0.60.360.0', rollback: false, reason: '',+ };+ /** Stable at 0.60.361.0, moved by a promotion that wrote no evidence record (no stable-record branch). */+ const preRecord = () => {+ const h = harness();+ h.repo.tags.stable = { commit: sha('b'), object: 'tagobj-stable-361', message: renderTagMessage(prior) };+ h.repo.tags['stable-v0.60.361.0'] = { commit: sha('b'), object: 'tagobj-record-361', message: renderTagMessage(prior) };+ h.repo.remote = { stable: 'tagobj-stable-361', 'stable-v0.60.361.0': 'tagobj-record-361' };+ return h;+ };++ test('the tag message parses back to the fields it was rendered from; anything else is null', () => {+ expect(parseTagMessage(renderTagMessage(prior))).toEqual(prior);+ expect(parseTagMessage(renderTagMessage({ ...prior, previous: null, rollback: true, reason: 'bad release' }))).toMatchObject({ previous: null, rollback: true, reason: 'bad release' });+ for (const junk of ['', 'hand-moved', renderTagMessage(prior).replace(/^commit: .*$/m, 'commit: nope'), renderTagMessage(prior).replace(/^soak_run: .*\n/m, '')]) {+ expect(parseTagMessage(junk)).toBeNull();+ }+ });++ test('re-promoting the current stable writes stable.json from its tag message and moves no tag', async () => {+ const h = preRecord();+ const p = await promote(h.deps, inputs());+ expect(p).toMatchObject({ version: '0.60.361.0', previous: '0.60.360.0', promotedAt: '2026-10-20T09:00:00Z', promotedBy: 'alice-example', recordCreated: false, knownBad: [] });+ expect(h.calls.filter(c => c.startsWith('tag -a'))).toEqual([]);+ expect(h.calls.filter(c => c.startsWith('push'))).toEqual([+ `push --atomic --force-with-lease=refs/tags/stable:tagobj-stable-361 --force-with-lease=refs/heads/stable-record: origin refs/tags/stable:refs/tags/stable ${h.repo.recordBranch}:refs/heads/stable-record`,+ ]);+ expect(h.repo.remote).toEqual({ stable: 'tagobj-stable-361', 'stable-v0.60.361.0': 'tagobj-record-361' });+ expect(parseStableRecord(h.repo.records![h.repo.recordBranch!]!)).toMatchObject({ ok: true, record: { version: '0.60.361.0', commit: sha('b'), tree: sha('2'), soak_run: RUN_URL, previous: '0.60.360.0', rollback: false, known_bad: [] } });+ expect(h.summaries).toHaveLength(1);+ });++ test('a published record that already matches is a no-op; a withdrawal still writes, carried forward', async () => {+ const h = preRecord();+ await promote(h.deps, inputs());+ await refusedAsync(promote(h.deps, inputs()), /already the stable release, and stable\.json on stable-record records it/);+ const first = h.repo.recordBranch!;+ const p = await promote(h.deps, inputs({ withdraw: ['0.60.355.0'] }));+ expect(p.knownBad).toEqual(['0.60.355.0']);+ expect(h.calls.some(c => c.startsWith('commit-tree') && c.includes(`-p ${first}`))).toBe(true);+ expect(JSON.parse(h.repo.records![h.repo.recordBranch!]!).known_bad).toEqual(['0.60.355.0']);+ });++ test('a record left behind by a later record-less promotion is brought up to the stable tag, keeping known_bad', async () => {+ const h = preRecord();+ h.repo.records = { 'rec-360': renderRecord({ ...prior, version: '0.60.360.0', commit: sha('a'), tree: sha('1'), previous: null }, ['0.60.300.0']) };+ h.repo.recordBranch = 'rec-360';+ await promote(h.deps, inputs());+ expect(JSON.parse(h.repo.records![h.repo.recordBranch!]!)).toMatchObject({ version: '0.60.361.0', commit: sha('b'), known_bad: ['0.60.300.0'] });+ expect(h.calls.filter(c => c.startsWith('push'))[0]).toContain('--force-with-lease=refs/heads/stable-record:rec-360');+ });++ test('refuses, writing nothing, when the tag message is missing, names another release or another soak run', async () => {+ const cases: Array<[string | undefined, Partial<PromoteInputs>, RegExp]> = [+ [undefined, {}, /stable tag carries no promotion message .* to write stable\.json from/],+ [renderTagMessage({ ...prior, commit: sha('c') }), {}, /stable tag's message names commit c+, not v0\.60\.361\.0's commit b+/],+ [renderTagMessage({ ...prior, tree: sha('3') }), {}, /names tree 3+, not v0\.60\.361\.0's tree 2+/],+ [renderTagMessage(prior), { soakRunUrl: `${RUN_URL}/attempts/2` }, /promoted on soak run .*runs\/123456, not .*attempts\/2; pass the soak run the stable tag names/],+ ];+ for (const [message, over, pattern] of cases) {+ const h = preRecord();+ h.repo.tags.stable!.message = message;+ await refusedAsync(promote(h.deps, inputs(over)), pattern);+ expect(h.calls.filter(c => c.startsWith('push') || c.startsWith('tag -a'))).toEqual([]);+ }+ });++ test('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') });+ await refusedAsync(promote(h.deps, inputs()), /concluded failure, not success/);+ expect(h.calls.filter(c => c.startsWith('push'))).toEqual([]);+ });++ test('a stable tag moved after it was read loses the lease and the record is not written', async () => {+ const h = preRecord();+ h.repo.remote!.stable = 'tagobj-someone-else';+ await refusedAsync(promote(h.deps, inputs()), /Writing the stable record failed and nothing changed on the remote/);+ expect(h.repo.recordBranch).toBeUndefined();+ });++ test('against real git: the backfill pushes only the record, and a moved stable tag refuses', async () => {+ 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' } });+ if (r.status !== 0) throw new Error(`git ${args.join(' ')}: ${r.stderr}`);+ return r.stdout.trim();+ };+ const dir = mkdtempSync(join(tmpdir(), 'promote-stable-bridge-'));+ try {+ const origin = join(dir, 'origin.git');+ const work = join(dir, 'work');+ git(dir, 'init', '-q', '--bare', origin);+ git(dir, 'init', '-q', work);+ for (const [k, v] of [['user.name', 'test-bot'], ['user.email', '[email protected]'], ['commit.gpgsign', 'false'], ['tag.gpgsign', 'false']]) git(work, 'config', k!, v!);+ git(work, 'remote', 'add', 'origin', origin);+ writeFileSync(join(work, 'VERSION'), '1.0.0\n');+ git(work, 'add', 'VERSION');+ git(work, 'commit', '-q', '-m', 'release 1.0.0');+ git(work, 'tag', 'v1.0.0');+ const commit = git(work, 'rev-parse', 'HEAD');+ const fields: TagFields = { ...prior, version: '1.0.0', commit, tree: git(work, 'rev-parse', 'HEAD^{tree}'), previous: null };+ // What a promotion without the evidence record left: the annotated tags, no stable-record branch.+ for (const tag of ['stable-v1.0.0', 'stable']) git(work, 'tag', '-a', '--cleanup=verbatim', '-m', renderTagMessage(fields), tag, commit);+ git(work, 'push', '-q', 'origin', 'HEAD:refs/heads/master', '--tags');+ const stableObject = git(work, 'rev-parse', 'refs/tags/stable');+ const 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 }),+ });++ await promote(deps(), inputs({ version: '1.0.0' }));+ expect(git(work, 'ls-remote', origin, 'refs/tags/stable').split('\t')[0]).toBe(stableObject);+ const record = parseStableRecord(git(dir, '--git-dir', origin, 'show', 'refs/heads/stable-record:stable.json'));+ expect(record).toMatchObject({ ok: true, record: { version: '1.0.0', commit, tree: fields.tree, soak_run: RUN_URL, promoted_at: '2026-10-20T09:00:00Z', previous: null } });+ await refusedAsync(promote(deps(), inputs({ version: '1.0.0' })), /records it, so there is nothing to promote/);++ // Someone moves stable on the remote after this checkout read it: the leased push refuses and the record stays.+ const other = join(dir, 'other');+ git(dir, 'clone', '-q', origin, other);+ for (const [k, v] of [['user.name', 'test-bot'], ['user.email', '[email protected]'], ['tag.gpgsign', 'false']]) git(other, 'config', k!, v!);+ git(other, 'tag', '-a', '-f', '-m', 'moved by hand', 'stable', commit);+ git(other, 'push', '-q', '-f', 'origin', 'refs/tags/stable:refs/tags/stable');+ const recordHead = git(dir, '--git-dir', origin, 'rev-parse', 'refs/heads/stable-record');+ await refusedAsync(promote(deps(), inputs({ version: '1.0.0', withdraw: ['0.9.0'] })), /Writing the stable record failed and nothing changed on the remote/);+ expect(git(dir, '--git-dir', origin, 'rev-parse', 'refs/heads/stable-record')).toBe(recordHead);+ } finally {+ rmSync(dir, { recursive: true, force: true });+ }+ });+});+describe('promote-stable.yml', () => {const workflowYml = readFileSync(join(ROOT, '.github/workflows/promote-stable.yml'), 'utf8');const wf = load(workflowYml) as {