Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
Merge capy/gbra346-stable-daily (R74: twice-daily soak-gated stable promotion)
garrytan2f76c4a16f88
diff --cc CHANGELOG.mdindex f905fe5b30,ca8e2bcc54..c325c7df80--- a/CHANGELOG.md+++ b/CHANGELOG.md@@@ -12,35 -12,15 +12,44 @@@ identifiers and attribution are availab## [Unreleased]+**Updates follow a stable channel by default; every release is one setting away on alpha.**++gbrain publishes a release for nearly every merged change, more than a hundred a week. Every install followed all of them, so an always-on brain upgraded several times a week onto releases no one had run on a production-shaped brain. Installs now follow the stable channel: weekly releases a maintainer promoted after the soak passed on that release's exact tree. The alpha channel (the old `latest`, which still works as an alias) keeps every release.++### What changed++| Situation | Before | Now |+|---|---|---|+| A new or existing install with no channel set | offered every published release | offered the newest stable release; one notice on stderr says so, once per brain home |+| Following every release | the default | `gbrain config set self_upgrade.channel alpha` (or `--channel alpha`, `GBRAIN_RELEASE_CHANNEL=alpha`) |+| Which stable release is offered | `VERSION` at the `stable` tag | the published evidence record (`stable.json` on `stable-record`): version, commit, tree, soak run, withdrawn versions; a record without the evidence is never trusted |+| Stable has no usable answer | `stable_channel_unresolved` on upgrade | `stable_missing`, `stable_invalid` or `stable_unreadable`; the background check only reports it, an explicit upgrade exits non-zero, neither falls back to alpha |+| An install ahead of stable (it ran alpha) | — | offered nothing until stable passes it; never downgraded unless its version was withdrawn |+| Update cache and snooze | one file for every channel; a snooze ended when a newer release shipped | one per channel, tagged with the evidence policy; a snooze holds its whole window (24 h, 48 h, 7 days); a stable rollback below it clears it |+| `gbrain upgrade --dry-run` | refused without `--restart-only` | reports channel, its source, current and target version and the action, installing nothing |+| doctor `self_upgrade_health` | — | names the channel and its source, warns on an invalid channel or a failed stable check |+| `Promote stable` workflow | moved the `stable` tag | also commits the evidence record in the same atomic push; new `withdraw` input adds versions to `known_bad`; 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.++**New installs now start on the stable channel: the soaked release, not every release.** The documented install (`bun install -g github:garrytan/gbrain#stable`) and the clone fallback (`git clone --branch stable`) follow the `stable` tag, which moves only to a published release whose exact tree passed the production soak, at least weekly. A fresh `gbrain init` (and so `gbrain setup claude-code` or `codex`) writes `self_upgrade.channel: stable`, so the update check and `gbrain upgrade` offer only stable releases. `#latest-stable` keeps working as the alpha line with every release. An existing brain is not changed: a re-init never sets or alters its channel.++### Itemized changes++- Install pins move from `#latest-stable` to `#stable` in README, AGENTS.md, INSTALL_FOR_AGENTS.md, BOOTSTRAP_FOR_AGENTS.md, docs/INSTALL.md, the MCP, headless, in-agent and tutorial guides, the setup skills, the Codex plugin manifests and launcher, doctor's npm-squat fix, the bootstrap hints and the agent-workspace template. The bootstrap runbook fetch and the in-agent setup helper read the `stable` ref, and the in-agent helper pins the commit `refs/tags/stable` peels to.+- `scripts/check-bootstrap-tag.sh` sanctions `stable` as the one distribution ref and now refuses `#latest-stable` in the entry docs.+- `src/commands/init.ts`: a fresh install (new content database, no prior config file) persists `self_upgrade.channel: stable` on PGLite and Postgres. A re-init keeps whatever the config says, including no channel. `test/init-stable-channel.test.ts` covers the fresh, re-init and explicit-channel cases.+- `docs/guides/upgrades-auto-update.md#stable-channel` describes stable as the default for new installs and `latest` as the alpha line.++ **Stable now moves forward by itself: a daily check promotes an important fix within a day and anything else within a week, and only after the soak passed on that exact release.** `.github/workflows/stable-daily.yml` runs at 05:17 and 13:17 UTC. It acts only when a merged PR labelled `stable:important` is released but not yet in stable, or stable is more than 7 days old. It promotes the newest release whose exact tree passed the production soak with every integrity gate clean, and otherwise dispatches one soak so a later run can promote. It never moves stable backward, pauses while stable is a rollback, and stops entirely with the repository variable `STABLE_AUTO_PROMOTE=off`.++ ### Itemized changes++ - New `scripts/stable-daily.ts` and `.github/workflows/stable-daily.yml`: the reason (a released `stable:important` fix stable lacks, or the 7-day weekly floor), the candidate (newest release newer than stable with a successful soak of its exact tree and `privacy_leaks`, `read_errors`, `version_skew`, `residents_alive` and `session_refusals` passing in every cell; on the important-only path it must contain the fix), one soak dispatch when nothing qualifies (never while a soak runs, never twice on one tree), the rollback pause and the kill switch. A manual dispatch defaults to a dry run.+ - `scripts/promote-stable.ts`: `scheduleAuthorized()` lets only a schedule event of `stable-daily.yml` on the default branch promote without the admin or maintain role; every other check is unchanged, and the record's `promoted_by` names the schedule. Manual dispatches keep the maintainer check.+ - `docs/RELEASING.md#daily-stable-check` documents the label, the schedule, the kill switch and the rollback.+ - `test/scripts/stable-daily.test.ts` covers the authorization, the integrity gates, each reason and no-op path, the soak dispatch rules, the dry run and the workflow shape.+## [0.60.593.0] - 2026-11-06**`gbrain repair failed-writes` now previews a brain with a large write journal in about a second instead of timing out.** On Postgres, the preview of refused writes read the request table once per refused write, and one of those reads walked the table from that write to its end. With hundreds of refused writes and a journal of over a million requests, the preview ran for minutes and the server's statement timeout ended it with a bare `internal_error`, so the operator had no way to see or recover the lost writes. The preview now classes refused writes together in set reads, each sized so it stays short even on a page with hundreds of refused writes and a long history. On a synthetic journal of 1.5 million requests with over 800 refused writes it took about a second (it took 265 seconds before), with the same classes and the same preview hash. When a preview read does still run past the timeout, it refuses `repair_preview_timeout` with a fix instead of `internal_error`, and nothing is saved.diff --cc docs/RELEASING.mdindex 2dced49191,93175cf0b5..4ed908bd32--- a/docs/RELEASING.md+++ b/docs/RELEASING.md@@@ -621,11 -615,9 +621,11 @@@ gh workflow run promote-stable.yml -f v- **Inputs.** `version` (an existing `v<VERSION>` release tag),`soak_run_url` (the soak's Actions run URL, optionally`/attempts/<n>`), `scoreboard_url` (optional, defaults to the run URL),- `rollback` (default false) and `reason` (required with rollback).+ `rollback` (default false), `reason` (required with rollback) and+ `withdraw` (versions added to the carried-forward `known_bad` list;+ clients on one are offered the current stable, even when older).- **Who.** Only an actor with the admin or maintain role; anyone else is- refused.+ refused. The one exception is the scheduled daily check below.- **Soak run.** The run must belong to this repository, be completed withconclusion `success`, and run the workflow file named by the`STABLE_SOAK_WORKFLOW` repository variable (Settings → Secrets and@@@ -653,29 -642,46 +653,68 @@@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.+ <a id="daily-stable-check"></a>+ ### Daily stable check++ `.github/workflows/stable-daily.yml` (`scripts/stable-daily.ts`) runs at 05:17 and 13:17 UTC+ and keeps stable between one day and one week behind what matters:++ - **Reason first.** It acts only when a merged PR labelled `stable:important` is in a+ published release but not in stable, or stable is more than 7 days old and+ a newer release exists (the weekly floor). Otherwise it does nothing. The+ merge lane sets the label at merge on a security, regression or data-loss+ fix, or a fix for something that blocks a crew or a user (on a train PR,+ the train carries it); a label added after the merge counts too.+ - **Soak first.** The candidate is the newest release newer than stable whose+ exact tree passed a successful `STABLE_SOAK_WORKFLOW` run with the integrity+ gates (`privacy_leaks`, `read_errors`, `version_skew`, `residents_alive`,+ `session_refusals`) passing in every cell; the latency gates stay+ record-only. On the important-only path the candidate must contain the fix.+ It is promoted through the same `promote()` as a manual promotion, so every+ check above still applies and the record's `promoted_by` is+ `schedule (.github/workflows/stable-daily.yml)` with the reason in `reason`.+ With no qualifying soak it dispatches one soak on the newest release's tag+ (never while another soak runs, and never again on a tree that already had+ one), and a later run promotes it.+ - **Who.** A schedule event runs only the workflow file as merged on the+ default branch, so a scheduled run promotes by rule without a maintainer. A+ manual dispatch defaults to `dry_run` (report only); `dry_run=false` needs an+ admin or maintainer. It shares the `promote-stable` concurrency group, so it+ never races a manual promotion.+ - **Stop it.** Set the repository variable `STABLE_AUTO_PROMOTE=off` (Settings →+ Secrets and variables → Actions → Variables). It also pauses by itself while+ the current stable record says `rollback: true`, until a maintainer promotes by+ hand.+ - **Roll back.** Dispatch `promote-stable.yml` as a maintainer with `version` set to the+ previous stable (`git tag --list 'stable-v*' --sort=-creatordate`, or the+ record's `previous` field: `git show stable --no-patch`), `soak_run_url` set to the+ soak run in that version's record tag, `rollback=true` and a `reason`. Clients on+ stable never downgrade on their own; the daily check stays paused until the+ next manual promotion.+### The `publish-template` jobAfter the release job, a `publish-template` job force-pushes the rendereddiff --cc scripts/promote-stable.tsindex ea8c3244a8,dd32b0495c..460f0d0a0a--- a/scripts/promote-stable.ts+++ b/scripts/promote-stable.ts@@@ -73,9 -61,11 +76,11 @@@ export interface GitResult { code: numbexport interface PromoteDeps {repo: string;actor: string;+ /** True only for the scheduled stable-daily.yml run (scheduleAuthorized); it replaces the role check. */+ scheduled?: boolean;soakWorkflow: string;ghApi(path: string): Promise<unknown>;- git(args: string[]): Promise<GitResult>;+ git(args: string[], input?: string): Promise<GitResult>;now(): Date;log(line: string): void;summary(markdown: string): void;@@@ -101,37 -91,19 +106,48 @@@ export interface TagFieldsreason: string;}-export interface Promotion extends TagFields { recordCreated: boolean }+export interface Promotion extends TagFields { recordCreated: boolean; knownBad: string[] }++/** The evidence record clients read (src/core/stable-channel.ts parseStableRecord); generation 1: soak evidence. */+export function renderRecord(f: TagFields, knownBad: readonly string[]): string {+ return JSON.stringify({+ schema: 1,+ channel: 'stable',+ version: f.version,+ commit: f.commit,+ tree: f.tree,+ soak_run: f.soakRun,+ scoreboard: f.scoreboard,+ promoted_by: f.promotedBy,+ promoted_at: f.promotedAt,+ previous: f.previous,+ rollback: f.rollback,+ reason: f.reason.trim().replace(/\s+/g, ' '),+ known_bad: [...knownBad],+ }, null, 2) + '\n';+}++/** The previous record's known_bad plus this run's withdrawals, deduplicated and sorted; refuses withdrawing the promoted version. */+export function mergeKnownBad(previous: readonly string[], withdraw: readonly string[], version: string): string[] {+ for (const v of withdraw) {+ if (!VERSION_RE.test(v)) throw new Refusal(`withdraw entry "${v}" is not a release version; pass versions like 0.60.361.0, comma-separated.`);+ }+ const all = [...new Set([...previous, ...withdraw])].sort(compareVersions);+ if (all.includes(version)) throw new Refusal(`v${version} is on the stable record's known_bad list (withdrawn); promote a different release.`);+ return all;+}+ export const DAILY_WORKFLOW = '.github/workflows/stable-daily.yml';++ /**+ * The scheduled daily check promotes without a maintainer: a schedule event only ever runs the workflow file as+ * merged on the default branch, so the rule it applies is reviewed code. Any other event (a dispatch of either+ * workflow) keeps the role check.+ */+ export function scheduleAuthorized(env: NodeJS.ProcessEnv, repo: string): boolean {+ return env.GITHUB_EVENT_NAME === 'schedule' && (env.GITHUB_WORKFLOW_REF ?? '').startsWith(`${repo}/${DAILY_WORKFLOW}@refs/heads/`);+ }+export function compareVersions(a: string, b: string): number {const pa = a.split('.').map(Number);const pb = b.split('.').map(Number);diff --cc test/scripts/stable-daily.test.tsindex 0000000000,fdb113d40e..cde41e2ec0mode 000000,100644..100644--- a/test/scripts/stable-daily.test.ts+++ b/test/scripts/stable-daily.test.ts@@@ -1,0 -1,298 +1,322 @@@+ /**+ * .github/workflows/stable-daily.yml + scripts/stable-daily.ts — the daily+ * stable check (R74), and the schedule-only authorization it adds to+ * scripts/promote-stable.ts.+ *+ * Protects: a scheduled run promotes only with a reason (a released+ * stable:important fix that stable lacks, or the 7-day weekly floor), only a+ * release newer than stable whose exact tree passed the soak with every+ * integrity gate clean, only a release that carries the fix on the+ * important-only path, and never while stable is a rollback or the kill switch+ * is off; with nothing promotable it dispatches at most one soak and never+ * retries a failed one; a dry run writes nothing; and only a schedule event of+ * stable-daily.yml skips the maintainer check.+ */+ import { describe, expect, test } from 'bun:test';+ import { readFileSync } from 'node:fs';+ import { join } from 'node:path';+ import { load } from 'js-yaml';+ import { promote, scheduleAuthorized, Refusal, type GitResult } from '../../scripts/promote-stable.ts';+ import { daily, integrityFailures, parseRecord, type DailyDeps, type Scoreboard, type SoakRunRow } from '../../scripts/stable-daily.ts';++import { parseStableRecord } from '../../src/core/stable-channel.ts';++ const ROOT = join(import.meta.dir, '..', '..');+ const REPO = 'garrytan/gbrain';+ const NOW = new Date('2026-11-10T13:17:00Z');+ const sha = (n: number) => String(n).padStart(40, 'c');+ const tree = (n: number) => String(n).padStart(40, 'e');+ const CLEAN: Scoreboard[] = ['rtt2', 'rtt65'].map(label => ({+ label,+ gates: ['privacy_leaks', 'read_errors', 'version_skew', 'residents_alive', 'session_refusals', 'freshness_p95'].map(id => ({ id, pass: id === 'freshness_p95' ? false : true })),+ }));+ const ok = (stdout = ''): GitResult => ({ code: 0, stdout: `${stdout}\n`, stderr: '' });+ const fail: GitResult = { code: 1, stdout: '', stderr: 'fatal: bad revision' };++ interface World {+ /** Linear history: commit n is an ancestor of every commit >= n. */+ head: number;+ releases: Record<string, number>;+ stable: { version: string; commit: number; message: string };+ importantPrs?: Array<{ number: number; merge: number }>;+ runs?: Array<SoakRunRow & { boards?: Scoreboard[] }>;+ autoPromote?: string;+ dryRun?: boolean;+ scheduled?: boolean;+ }++ const stableMessage = (version: string, promotedAt: string, rollback = false) =>+ `gbrain stable channel: v${version}\n\nversion: ${version}\npromoted_at: ${promotedAt}\nrollback: ${rollback}\nreason: ${rollback ? 'sync regression' : '-'}\n`;++ function world(w: World) {+ const posts: Array<{ path: string; body: unknown }> = [];+ const pushes: string[] = [];+ const api: string[] = [];+ const logs: string[] = [];+ const tags: Record<string, { commit: number; object: string; message?: string }> = {+ stable: { commit: w.stable.commit, object: 'tagobj-stable', message: w.stable.message },+ [`stable-v${w.stable.version}`]: { commit: w.stable.commit, object: 'tagobj-record' },+ };+ for (const [v, c] of Object.entries(w.releases)) tags[`v${v}`] = { commit: c, object: sha(c) };+ const commitOf = (spec: string): number | null => {+ const name = spec.replace(/^refs\/tags\//, '');+ if (tags[name]) return tags[name]!.commit;+ const n = Number.parseInt(spec.replace(/^c+/, ''), 10);+ return /^c*\d+$/.test(spec) && spec.length === 40 && n <= w.head ? n : null;+ };- const git = async (args: string[]): Promise<GitResult> => {++ /** The evidence record promote() commits (GBRA-224 W1): blob, tree and commit objects, and the pushed stable-record head. */++ const objects: Record<string, string> = {};++ const record: { head?: string } = {};++ const git = async (args: string[], input?: string): Promise<GitResult> => {+ const [cmd, ...rest] = args;++ if (cmd === 'hash-object') { const id = `blob-${Object.keys(objects).length}`; objects[id] = input ?? ''; return ok(id); }++ if (cmd === 'mktree') { const id = `tree-${Object.keys(objects).length}`; objects[id] = objects[/blob (\S+)\tstable\.json/.exec(input ?? '')![1]!]!; return ok(id); }++ if (cmd === 'commit-tree') { const id = `rec-${Object.keys(objects).length}`; objects[id] = objects[rest[0]!]!; return ok(id); }++ if (cmd === 'show' && rest[0]!.endsWith(':stable.json')) { const body = objects[rest[0]!.replace(/:stable\.json$/, '')]; return body === undefined ? fail : ok(body); }++ if (cmd === 'rev-parse' && rest.at(-1) === 'refs/remotes/origin/stable-record^{commit}') return record.head ? ok(record.head) : fail;+ if (cmd === 'rev-parse') {+ const spec = rest.at(-1)!;+ const m = /^(.*?)(\^\{(commit|tree)\})?$/.exec(spec)!;+ const c = commitOf(m[1]!);+ if (c === null) return fail;+ if (m[3] === 'tree') return ok(tree(c));+ if (m[3] === 'commit') return ok(sha(c));+ const name = m[1]!.replace(/^refs\/tags\//, '');+ return ok(tags[name]?.object ?? sha(c));+ }+ if (cmd === 'for-each-ref') return ok(tags.stable!.message ?? '');+ if (cmd === 'tag' && rest[0] === '--list') return ok(Object.keys(tags).filter(t => t.startsWith('v')).join('\n'));+ if (cmd === 'tag' && rest[0] === '--points-at') {+ const c = commitOf(rest[1]!);+ return ok(Object.entries(tags).filter(([n, t]) => n.startsWith('v') && t.commit === c).map(([n]) => n).join('\n'));+ }+ if (cmd === 'tag' && rest[0] === '-a') {+ const [name, commit] = rest.slice(-2) as [string, string];+ tags[name] = { commit: commitOf(commit)!, object: `tagobj-${name}-new`, message: rest[rest.indexOf('-m') + 1] };+ return ok();+ }+ if (cmd === 'show') return ok(rest[0]!.replace(/^refs\/tags\/v/, '').replace(/:VERSION$/, ''));+ if (cmd === 'merge-base') {+ const a = commitOf(rest[1]!); const b = commitOf(rest[2]!);+ return a !== null && b !== null && a <= b ? ok() : fail;+ }- if (cmd === 'push') { pushes.push(rest.join(' ')); return ok(); }++ if (cmd === 'push') {++ pushes.push(rest.join(' '));++ const head = rest.find(a => a.endsWith(':refs/heads/stable-record'));++ if (head) record.head = head.split(':')[0];++ return ok();++ }+ if (cmd === 'fetch') return ok();+ return fail;+ };+ const runs = w.runs ?? [];+ const deps: DailyDeps = {+ repo: REPO,+ actor: 'github-actions[bot]',+ scheduled: w.scheduled ?? true,+ soakWorkflow: 'production-soak.yml',+ autoPromote: w.autoPromote ?? '',+ dryRun: w.dryRun ?? false,+ async ghApi(path) {+ api.push(path);+ if (path.startsWith('search/issues')) return { items: (w.importantPrs ?? []).map(p => ({ number: p.number })) };+ const pull = /\/pulls\/(\d+)$/.exec(path);+ if (pull) return { merge_commit_sha: sha(w.importantPrs!.find(p => p.number === Number(pull[1]))!.merge) };+ if (path.includes('/actions/workflows/')) return { workflow_runs: runs };+ if (path.includes('/actions/runs/')) {+ 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.endsWith('/permission')) return { permission: 'none' };+ throw new Error(`unexpected api ${path}`);+ },+ git,+ now: () => NOW,+ log: line => logs.push(line),+ summary: () => {},+ async ghPost(path, body) { posts.push({ path, body }); },+ async scoreboards(id) { return runs.find(r => r.id === id)?.boards ?? CLEAN; },+ };- return { deps, posts, pushes, api, logs, tags };++ return { deps, posts, pushes, api, logs, tags, record: () => (record.head ? objects[record.head] : undefined) };+ }++ const soak = (id: number, commit: number, over: Partial<SoakRunRow> & { boards?: Scoreboard[] } = {}) =>+ ({ id, status: 'completed', conclusion: 'success', head_sha: sha(commit), html_url: `https://github.com/${REPO}/actions/runs/${id}`, ...over });++ const base = (over: Partial<World> = {}): World => ({+ head: 6,+ releases: { '1.0.1': 1, '1.0.2': 2, '1.0.3': 3, '1.0.4': 4 },+ stable: { version: '1.0.1', commit: 1, message: stableMessage('1.0.1', '2026-11-08T05:17:00Z') },+ ...over,+ });++ describe('scheduleAuthorized', () => {+ test('only a schedule event of stable-daily.yml on a branch of this repository', () => {+ const env = (event: string, ref: string) => ({ GITHUB_EVENT_NAME: event, GITHUB_WORKFLOW_REF: ref });+ expect(scheduleAuthorized(env('schedule', `${REPO}/.github/workflows/stable-daily.yml@refs/heads/master`), REPO)).toBe(true);+ expect(scheduleAuthorized(env('workflow_dispatch', `${REPO}/.github/workflows/stable-daily.yml@refs/heads/master`), REPO)).toBe(false);+ expect(scheduleAuthorized(env('schedule', `${REPO}/.github/workflows/promote-stable.yml@refs/heads/master`), REPO)).toBe(false);+ expect(scheduleAuthorized(env('schedule', `acme-example/gbrain/.github/workflows/stable-daily.yml@refs/heads/master`), REPO)).toBe(false);+ expect(scheduleAuthorized(env('schedule', `${REPO}/.github/workflows/stable-daily.yml@refs/tags/v1`), REPO)).toBe(false);+ expect(scheduleAuthorized({}, REPO)).toBe(false);+ });++ test('a scheduled promotion skips the role read and records the schedule as the promoter; a dispatch keeps the maintainer check', async () => {+ const w = world(base({ runs: [soak(9, 2)] }));+ const p = await promote(w.deps, { version: '1.0.2', soakRunUrl: `https://github.com/${REPO}/actions/runs/9`, scoreboardUrl: '', rollback: false, reason: '' });+ expect(w.api.some(a => a.endsWith('/permission'))).toBe(false);+ expect(p.promotedBy).toBe('schedule (.github/workflows/stable-daily.yml)');+ const d = world(base({ runs: [soak(9, 2)], scheduled: false }));+ const error = await promote(d.deps, { version: '1.0.2', soakRunUrl: `https://github.com/${REPO}/actions/runs/9`, scoreboardUrl: '', rollback: false, reason: '' }).then(() => null, e => e);+ expect(error).toBeInstanceOf(Refusal);+ expect((error as Error).message).toMatch(/has the none role/);+ });+ });++ describe('integrity gates', () => {+ test('every integrity gate must pass in every cell; latency gates stay record-only; no data or no cells fails closed', () => {+ expect(integrityFailures(CLEAN)).toEqual([]);+ expect(integrityFailures([])).toEqual(['no scoreboard artifact']);+ const leak = structuredClone(CLEAN);+ leak[1]!.gates!.find(g => g.id === 'privacy_leaks')!.pass = false;+ leak[0]!.gates!.find(g => g.id === 'read_errors')!.pass = null;+ expect(integrityFailures(leak)).toEqual(['rtt2: read_errors has no data', 'rtt65: privacy_leaks failed']);+ expect(integrityFailures([{ label: 'rtt2', gates: [] }])).toHaveLength(5);+ });++ test('parseRecord reads the key: value body of a stable tag', () => {+ expect(parseRecord(stableMessage('1.0.1', '2026-11-08T05:17:00Z', true))).toMatchObject({ version: '1.0.1', rollback: 'true', reason: 'sync regression' });+ });+ });++ describe('daily: when it does nothing', () => {+ test('the kill switch turns it off before anything is read', async () => {+ const w = world(base({ autoPromote: 'off' }));+ expect((await daily(w.deps)).action).toBe('off');+ expect(w.api).toEqual([]);+ });++ test('a rollback pauses it until a maintainer promotes by hand', async () => {+ const w = world(base({ stable: { version: '1.0.1', commit: 1, message: stableMessage('1.0.1', '2026-11-01T00:00:00Z', true) }, runs: [soak(9, 4)] }));+ const r = await daily(w.deps);+ expect(r.action).toBe('paused');+ expect(w.pushes).toEqual([]);+ expect(w.posts).toEqual([]);+ });++ test('no important fix and stable under 7 days old: nothing happens', async () => {+ const w = world(base({ runs: [soak(9, 4)] }));+ const r = await daily(w.deps);+ expect(r.action).toBe('none');+ expect(w.pushes).toEqual([]);+ expect(w.posts).toEqual([]);+ });++ test('an important fix already in stable, or not released yet, is no reason', async () => {+ const inStable = world(base({ importantPrs: [{ number: 11, merge: 1 }], runs: [soak(9, 4)] }));+ expect((await daily(inStable.deps)).action).toBe('none');+ const unreleased = world(base({ importantPrs: [{ number: 12, merge: 6 }], runs: [soak(9, 4)] }));+ expect((await daily(unreleased.deps)).action).toBe('none');+ });+ });++ describe('daily: important fixes', () => {+ test('promotes the newest soaked release that carries the fix', async () => {+ const w = world(base({ importantPrs: [{ number: 30, merge: 3 }], runs: [soak(8, 2), soak(9, 3)] }));+ const r = await daily(w.deps);+ expect(r.action).toBe('promoted');+ if (r.action !== 'promoted') return;+ expect(r.promotion.version).toBe('1.0.3');+ expect(r.promotion.soakRun).toBe(`https://github.com/${REPO}/actions/runs/9`);+ expect(r.promotion.reason).toContain('important: #30 (v1.0.3)');+ expect(w.pushes).toHaveLength(1);+ });+++ test('a scheduled promotion writes stable.json in the same atomic push as the tags, so stable clients read it', async () => {++ const w = world(base({ importantPrs: [{ number: 30, merge: 3 }], runs: [soak(9, 3)] }));++ const r = await daily(w.deps);++ expect(r.action).toBe('promoted');++ expect(w.pushes).toHaveLength(1);++ expect(w.pushes[0]).toMatch(/^--atomic .*--force-with-lease=refs\/heads\/stable-record: origin .*refs\/tags\/stable:refs\/tags\/stable rec-\d+:refs\/heads\/stable-record$/);++ expect(parseStableRecord(w.record()!)).toMatchObject({ ok: true, record: { version: '1.0.3', commit: sha(3), tree: tree(3), soak_run: `https://github.com/${REPO}/actions/runs/9`, previous: '1.0.1', rollback: false, known_bad: [] } });++ expect(JSON.parse(w.record()!)).toMatchObject({ promoted_by: 'schedule (.github/workflows/stable-daily.yml)' });++ });+++ test('a soaked release without the fix is not promoted on the important path; the newest release gets one soak instead', async () => {+ const w = world(base({ importantPrs: [{ number: 30, merge: 3 }], runs: [soak(8, 2)] }));+ const r = await daily(w.deps);+ expect(r).toMatchObject({ action: 'soak_dispatched', version: '1.0.4' });+ expect(w.posts).toEqual([{ path: `repos/${REPO}/actions/workflows/production-soak.yml/dispatches`, body: { ref: 'v1.0.4' } }]);+ expect(w.pushes).toEqual([]);+ });++ test('a soak whose integrity gates failed is skipped for an older clean one that still carries the fix', async () => {+ const leak = structuredClone(CLEAN);+ leak[0]!.gates!.find(g => g.id === 'privacy_leaks')!.pass = false;+ const w = world(base({ importantPrs: [{ number: 30, merge: 3 }], runs: [soak(9, 3), soak(10, 4, { boards: leak })] }));+ const r = await daily(w.deps);+ expect(r.action === 'promoted' && r.promotion.version).toBe('1.0.3');+ expect(w.logs.some(l => l.includes('rtt2: privacy_leaks failed'))).toBe(true);+ });++ test('a soak already running means wait; a finished soak on the newest release that did not qualify is never re-dispatched', async () => {+ const running = world(base({ importantPrs: [{ number: 40, merge: 4 }], runs: [soak(9, 4, { status: 'in_progress', conclusion: null })] }));+ expect((await daily(running.deps)).action).toBe('waiting');+ expect(running.posts).toEqual([]);+ const failed = world(base({ importantPrs: [{ number: 40, merge: 4 }], runs: [soak(9, 4, { conclusion: 'failure' })] }));+ const r = await daily(failed.deps);+ expect(r.action).toBe('waiting');+ expect(r.why).toContain('a maintainer decides');+ expect(failed.posts).toEqual([]);+ expect(failed.pushes).toEqual([]);+ });+ });++ describe('daily: weekly floor', () => {+ const old = { version: '1.0.1', commit: 1, message: stableMessage('1.0.1', '2026-11-02T05:17:00Z') };++ test('stable older than 7 days promotes the newest soaked release', async () => {+ const w = world(base({ stable: old, runs: [soak(8, 2), soak(9, 3)] }));+ const r = await daily(w.deps);+ expect(r.action === 'promoted' && r.promotion.version).toBe('1.0.3');+ expect(r.why).toContain('weekly floor');+ });++ test('a dry run reports and writes nothing', async () => {+ const w = world(base({ stable: old, runs: [soak(9, 3)], dryRun: true }));+ expect(await daily(w.deps)).toMatchObject({ action: 'dry_run', would: expect.stringContaining('promote v1.0.3') });+ const none = world(base({ stable: old, dryRun: true }));+ expect(await daily(none.deps)).toMatchObject({ action: 'dry_run', would: 'dispatch the soak on v1.0.4' });+ expect([...w.pushes, ...none.pushes]).toEqual([]);+ expect([...w.posts, ...none.posts]).toEqual([]);+ });++ test('never moves stable backward: only releases newer than stable are candidates', async () => {+ const w = world(base({ stable: { ...old, version: '1.0.4', commit: 4, message: stableMessage('1.0.4', '2026-11-02T05:17:00Z') }, runs: [soak(9, 3)] }));+ expect((await daily(w.deps)).action).toBe('none');+ });+ });++ describe('stable-daily.yml', () => {+ const wf = load(readFileSync(join(ROOT, '.github/workflows/stable-daily.yml'), 'utf8')) as {+ on: { schedule: Array<{ cron: string }>; workflow_dispatch: { inputs: Record<string, { default: unknown; type: string }> } };+ permissions: Record<string, string>;+ concurrency: { group: string; 'cancel-in-progress': boolean };+ jobs: { daily: { steps: Array<{ run?: string; env?: Record<string, string> }> } };+ };++ test('runs twice a day plus a dry-run-by-default dispatch, sharing the promote-stable concurrency group', () => {+ expect(Object.keys(wf.on).sort()).toEqual(['schedule', 'workflow_dispatch']);+ expect(wf.on.schedule.map(s => s.cron)).toEqual(['17 5 * * *', '17 13 * * *']);+ expect(wf.on.workflow_dispatch.inputs.dry_run).toMatchObject({ type: 'boolean', default: true });+ expect(wf.permissions).toEqual({ contents: 'write', actions: 'write' });+ expect(wf.concurrency).toEqual({ group: 'promote-stable', 'cancel-in-progress': false });+ });++ test('inputs reach the script through env only, and no dependency install runs', () => {+ const step = wf.jobs.daily.steps.find(s => s.run?.includes('scripts/stable-daily.ts'))!;+ expect(step.run).not.toContain('${{');+ expect(step.env).toMatchObject({ STABLE_AUTO_PROMOTE: '${{ vars.STABLE_AUTO_PROMOTE }}', STABLE_SOAK_WORKFLOW: '${{ vars.STABLE_SOAK_WORKFLOW }}' });+ expect(wf.jobs.daily.steps.some(s => /bun install|npm (ci|install)/.test(s.run ?? ''))).toBe(false);+ });+ });