Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
stable-daily: twice-daily soak-gated stable promotion of important fixes with a weekly floor (R74)
garrytan4e7a36aef556
diff --git a/.github/workflows/stable-daily.yml b/.github/workflows/stable-daily.ymlnew file mode 100644index 0000000000..6a61798960--- /dev/null+++ b/.github/workflows/stable-daily.yml@@ -0,0 +1,64 @@+name: Stable daily++# The daily stable check (docs/RELEASING.md#daily-stable-check,+# scripts/stable-daily.ts). Twice a day it promotes the newest release whose+# exact tree passed the production soak with every integrity gate clean, but+# only when a reason exists: a merged PR labelled stable:important that is+# released but not yet in stable, or stable older than 7 days (the weekly+# floor). With nothing to promote yet it dispatches one soak on the newest+# release, and a later run promotes it. It never promotes without that soak,+# never moves stable backward, pauses while stable is a rollback, and does+# nothing while the STABLE_AUTO_PROMOTE repository variable is "off".+#+# A schedule event runs only this file as merged on the default branch, so a+# scheduled run promotes by rule without a maintainer+# (scripts/promote-stable.ts scheduleAuthorized). A dispatch defaults to a+# dry run; a dispatch with dry_run=false needs an admin or maintainer, exactly+# like promote-stable.yml. Rollback stays a maintainer dispatch of+# promote-stable.yml with rollback=true and a reason.+#+# Inputs reach the script through env only. No dependency install runs in+# this job, so the checkout credentials that push the tags are only ever used+# by git.++on:+ schedule:+ - cron: '17 5 * * *'+ - cron: '17 13 * * *'+ workflow_dispatch:+ inputs:+ dry_run:+ description: Report what the check would do and change nothing+ required: false+ type: boolean+ default: true++permissions:+ contents: write # push the stable-v<version> and stable tags+ actions: write # read soak runs and their scoreboards; dispatch a soak++concurrency:+ group: promote-stable+ cancel-in-progress: false++jobs:+ daily:+ runs-on: ubuntu-latest+ timeout-minutes: 20+ steps:+ - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4+ with:+ fetch-depth: 0+ - uses: oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6 # v2+ with:+ bun-version: 1.4.4+ - name: Daily stable check+ env:+ GH_TOKEN: ${{ github.token }}+ STABLE_SOAK_WORKFLOW: ${{ vars.STABLE_SOAK_WORKFLOW }}+ STABLE_AUTO_PROMOTE: ${{ vars.STABLE_AUTO_PROMOTE }}+ DAILY_DRY_RUN: ${{ github.event_name == 'workflow_dispatch' && inputs.dry_run }}+ run: |+ git config user.name "gbrain-release-bot"+ git config user.email "41898282+github-actions[bot]@users.noreply.github.com"+ bun run scripts/stable-daily.tsdiff --git a/CHANGELOG.md b/CHANGELOG.mdindex 8b7f30365a..ca8e2bcc54 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -10,6 +10,17 @@ credits are retained; no result has been reassigned to another provider. Originaidentifiers and attribution are available in the pre-removal Git revision`6040075c6cb95be5881cc2e1b76ef7d71f4e5d29` (retained on 2026-09-23).+## [Unreleased]++**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 --git a/docs/RELEASING.md b/docs/RELEASING.mdindex 22f8cd578a..93175cf0b5 100644--- a/docs/RELEASING.md+++ b/docs/RELEASING.md@@ -617,7 +617,7 @@ gh workflow run promote-stable.yml -f version=<VERSION> \`/attempts/<n>`), `scoreboard_url` (optional, defaults to the run URL),`rollback` (default false) and `reason` (required with rollback).- **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@@ -643,6 +643,45 @@ gh workflow run promote-stable.yml -f version=<VERSION> \time. The run's step summary lists the version, commit, tree, soak run,scoreboard, previous stable and rollback reason.+<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 --git a/scripts/stable-daily.ts b/scripts/stable-daily.tsnew file mode 100644index 0000000000..2e218c4e74--- /dev/null+++ b/scripts/stable-daily.ts@@ -0,0 +1,224 @@+#!/usr/bin/env bun+/**+ * The daily stable check (.github/workflows/stable-daily.yml, twice a day).+ *+ * bun run scripts/stable-daily.ts # from the workflow; DAILY_DRY_RUN=true reports and writes nothing+ *+ * Moves the stable channel forward by rule, never by guess:+ *+ * 1. Off when the STABLE_AUTO_PROMOTE repository variable is `off`, and paused+ * while the current stable record says `rollback: true` (a maintainer+ * promotes by hand to resume).+ * 2. A reason must exist: a merged PR labelled `stable:important` (security,+ * regression, data-loss or blocking fix, set by the merge lane) that is in a+ * published release but not in stable, or stable older than 7 days with a+ * newer release (the weekly floor). No reason: nothing happens.+ * 3. The candidate is the newest release newer than stable whose exact git tree+ * passed a successful run of the STABLE_SOAK_WORKFLOW soak with every+ * integrity gate (INTEGRITY_GATES) passing in every cell; on the+ * important-only path it must contain one of the important fixes. It is+ * promoted through scripts/promote-stable.ts promote(), so every promotion+ * check (published release, exact tree, never older) still applies.+ * 4. Nothing promotable yet: the newest release is soaked (one dispatch of the+ * soak on its tag) unless a soak is already running, or one already ran on+ * that tree; a failed soak is never retried by the schedule.+ *+ * Docs: docs/RELEASING.md#daily-stable-check+ */+import { spawnSync } from 'node:child_process';+import { appendFileSync, mkdtempSync, readdirSync, readFileSync, rmSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import {+ compareVersions, currentStable, processDeps, promote, Refusal, requireSoakWorkflow, scheduleAuthorized, STABLE_REF,+ type PromoteDeps, type Promotion,+} from './promote-stable.ts';++export const IMPORTANT_LABEL = 'stable:important';+export const WEEKLY_FLOOR_DAYS = 7;+/** The soak gates a scheduled promotion requires (pass === true in every cell); the latency gates stay record-only. */+export const INTEGRITY_GATES = ['privacy_leaks', 'read_errors', 'version_skew', 'residents_alive', 'session_refusals'] as const;+const DAY_MS = 86_400_000;+const VERSION_RE = /^\d+\.\d+\.\d+(\.\d+)?$/;++export interface SoakRunRow { id: number; status: string | null; conclusion: string | null; head_sha: string; html_url: string }+export interface Scoreboard { label?: string; gates?: Array<{ id: string; pass: boolean | null }> }++export interface DailyDeps extends PromoteDeps {+ ghPost(path: string, body: unknown): Promise<void>;+ scoreboards(runId: number): Promise<Scoreboard[]>;+ autoPromote: string;+ dryRun: boolean;+}++export type DailyResult =+ | { action: 'off' | 'paused' | 'none'; why: string }+ | { action: 'promoted'; why: string; promotion: Promotion }+ | { action: 'soak_dispatched' | 'waiting'; why: string; version: string }+ | { action: 'dry_run'; why: string; would: string };++export function parseRecord(message: string): Record<string, string> {+ const out: Record<string, string> = {};+ for (const line of message.split('\n')) {+ const m = /^([a-z_]+): (.*)$/.exec(line.trim());+ if (m) out[m[1]!] = m[2]!;+ }+ return out;+}++/** Integrity gate failures across a soak's cells; a missing cell set or a gate with no data fails closed. */+export function integrityFailures(boards: Scoreboard[]): string[] {+ if (boards.length === 0) return ['no scoreboard artifact'];+ const failures: string[] = [];+ for (const b of boards) {+ for (const id of INTEGRITY_GATES) {+ const gate = b.gates?.find(g => g.id === id);+ if (gate?.pass !== true) failures.push(`${b.label ?? 'cell'}: ${id} ${gate ? (gate.pass === null ? 'has no data' : 'failed') : 'missing'}`);+ }+ }+ return failures;+}++async function ok(deps: PromoteDeps, args: string[]): Promise<string> {+ const r = await deps.git(args);+ if (r.code !== 0) throw new Refusal(`git ${args.join(' ')} failed${r.stderr.trim() ? `: ${r.stderr.trim().split('\n').at(-1)}` : ''}; re-run the daily check.`);+ return r.stdout.trim();+}++const isAncestor = async (deps: PromoteDeps, a: string, b: string) => (await deps.git(['merge-base', '--is-ancestor', a, b])).code === 0;++async function treeOf(deps: PromoteDeps, commit: string): Promise<string | null> {+ let r = await deps.git(['rev-parse', `${commit}^{tree}`]);+ if (r.code !== 0) { await deps.git(['fetch', '--no-tags', 'origin', commit]); r = await deps.git(['rev-parse', `${commit}^{tree}`]); }+ return r.code === 0 ? r.stdout.trim() : null;+}++export async function daily(deps: DailyDeps): Promise<DailyResult> {+ if (deps.autoPromote.trim().toLowerCase() === 'off') return { action: 'off', why: 'STABLE_AUTO_PROMOTE is off; the daily check changes nothing.' };+ const soakPath = requireSoakWorkflow(deps.soakWorkflow);++ const current = await currentStable(deps);+ if (!current) throw new Refusal('There is no stable release yet; promote the first one by hand with promote-stable.yml.');+ const record = parseRecord(await ok(deps, ['for-each-ref', '--format=%(contents)', STABLE_REF]));+ if (record.rollback === 'true') {+ return { action: 'paused', why: `stable v${current.version} is a rollback (${record.reason ?? '-'}); the daily check stays paused until a maintainer promotes by hand.` };+ }+ const stableCommit = await ok(deps, ['rev-parse', `${STABLE_REF}^{commit}`]);+ const promotedAt = Date.parse(record.promoted_at ?? '');+ const ageDays = Number.isFinite(promotedAt) ? (deps.now().getTime() - promotedAt) / DAY_MS : Infinity;++ const releases: Array<{ version: string; commit: string }> = [];+ for (const tag of (await ok(deps, ['tag', '--list', 'v*'])).split('\n').map(t => t.trim())) {+ const version = tag.replace(/^v/, '');+ if (!VERSION_RE.test(version) || compareVersions(version, current.version) <= 0) continue;+ releases.push({ version, commit: await ok(deps, ['rev-parse', `refs/tags/${tag}^{commit}`]) });+ }+ releases.sort((a, b) => compareVersions(b.version, a.version));+ if (releases.length === 0) return { action: 'none', why: `no release is newer than stable v${current.version}.` };++ const since = new Date((Number.isFinite(promotedAt) ? promotedAt : deps.now().getTime()) - 14 * DAY_MS).toISOString().slice(0, 10);+ const q = `repo:${deps.repo} is:pr is:merged label:"${IMPORTANT_LABEL}" merged:>=${since}`;+ const found = await deps.ghApi(`search/issues?q=${encodeURIComponent(q)}&per_page=100`) as { items?: Array<{ number: number }> };+ const important: Array<{ pr: number; version: string }> = [];+ for (const { number } of found.items ?? []) {+ const pr = await deps.ghApi(`repos/${deps.repo}/pulls/${number}`) as { merge_commit_sha?: string | null };+ const sha = pr.merge_commit_sha;+ if (!sha || (await treeOf(deps, sha)) === null || await isAncestor(deps, sha, stableCommit)) continue;+ for (const r of [...releases].reverse()) {+ if (!(await isAncestor(deps, sha, r.commit))) continue;+ important.push({ pr: number, version: r.version });+ break;+ }+ }+ const weekly = ageDays > WEEKLY_FLOOR_DAYS;+ if (important.length === 0 && !weekly) {+ return { action: 'none', why: `no released ${IMPORTANT_LABEL} fix is missing from stable v${current.version}, and stable is ${ageDays.toFixed(1)} days old (floor ${WEEKLY_FLOOR_DAYS}).` };+ }+ const reason = [+ ...(important.length ? [`important: ${important.map(i => `#${i.pr} (v${i.version})`).join(', ')}`] : []),+ ...(weekly ? [`weekly floor: stable v${current.version} is ${ageDays.toFixed(1)} days old`] : []),+ ].join('; ');+ deps.log(`[stable-daily] reason: ${reason}.`);++ const runs = ((await deps.ghApi(`repos/${deps.repo}/actions/workflows/${soakPath.split('/').at(-1)}/runs?per_page=100`)) as { workflow_runs?: SoakRunRow[] }).workflow_runs ?? [];+ const runsByTree = new Map<string, SoakRunRow[]>();+ for (const run of runs) {+ const tree = await treeOf(deps, run.head_sha);+ if (tree) runsByTree.set(tree, [...(runsByTree.get(tree) ?? []), run]);+ }+ const oldestImportant = important.reduce<string | null>((v, i) => (!v || compareVersions(i.version, v) < 0 ? i.version : v), null);+ for (const rel of releases) {+ if (!weekly && oldestImportant && compareVersions(rel.version, oldestImportant) < 0) break;+ const tree = await treeOf(deps, rel.commit);+ const passed = (runsByTree.get(tree ?? '') ?? []).filter(r => r.status === 'completed' && r.conclusion === 'success');+ let chosen: SoakRunRow | null = null;+ for (const run of passed) {+ const failures = integrityFailures(await deps.scoreboards(run.id));+ if (failures.length === 0) { chosen = run; break; }+ deps.log(`[stable-daily] not promotable: v${rel.version} soak ${run.html_url}: ${failures.join(', ')}.`);+ }+ if (!chosen) continue;+ if (deps.dryRun) return { action: 'dry_run', why: reason, would: `promote v${rel.version} on soak ${chosen.html_url}` };+ const promotion = await promote(deps, { version: rel.version, soakRunUrl: chosen.html_url, scoreboardUrl: '', rollback: false, reason: `scheduled daily check; ${reason}` });+ return { action: 'promoted', why: reason, promotion };+ }++ const newest = releases[0]!;+ const newestTree = await treeOf(deps, newest.commit);+ const active = runs.find(r => r.status !== 'completed');+ if (active) return { action: 'waiting', why: `${reason}; soak ${active.html_url} is still running.`, version: newest.version };+ const ranOnNewest = runsByTree.get(newestTree ?? '') ?? [];+ if (ranOnNewest.length > 0) {+ return { action: 'waiting', why: `${reason}; v${newest.version} already had a soak (${ranOnNewest[0]!.html_url}, ${ranOnNewest[0]!.conclusion}) that did not qualify, so a maintainer decides.`, version: newest.version };+ }+ if (deps.dryRun) return { action: 'dry_run', why: reason, would: `dispatch the soak on v${newest.version}` };+ await deps.ghPost(`repos/${deps.repo}/actions/workflows/${soakPath.split('/').at(-1)}/dispatches`, { ref: `v${newest.version}` });+ return { action: 'soak_dispatched', why: reason, version: newest.version };+}++export function dailyDeps(env: NodeJS.ProcessEnv = process.env, cwd = process.cwd()): DailyDeps {+ const base = processDeps(env, cwd);+ return {+ ...base,+ scheduled: scheduleAuthorized(env, base.repo),+ autoPromote: env.STABLE_AUTO_PROMOTE ?? '',+ dryRun: env.DAILY_DRY_RUN === 'true',+ async ghPost(path, body) {+ const r = spawnSync('gh', ['api', '--method', 'POST', path, '--input', '-'], { cwd, env, encoding: 'utf8', input: JSON.stringify(body) });+ if (r.status !== 0) throw new Error(`gh api POST ${path} failed: ${(r.stderr || r.error?.message || '').trim()}`);+ },+ async scoreboards(runId) {+ const dir = mkdtempSync(join(tmpdir(), 'soak-'));+ try {+ const r = spawnSync('gh', ['run', 'download', String(runId), '-R', base.repo, '-p', 'production-soak-*', '-D', dir], { cwd, env, encoding: 'utf8' });+ if (r.status !== 0) return [];+ return readdirSync(dir).flatMap(cell => {+ try { return [JSON.parse(readFileSync(join(dir, cell, 'scoreboard.json'), 'utf8')) as Scoreboard]; } catch { return [{ label: cell, gates: [] }]; }+ });+ } finally {+ rmSync(dir, { recursive: true, force: true });+ }+ },+ };+}++export function renderDailySummary(r: DailyResult): string {+ const detail = r.action === 'promoted' ? `Promoted v${r.promotion.version} (previous v${r.promotion.previous ?? 'none'}).`+ : r.action === 'dry_run' ? `Dry run: would ${r.would}.`+ : 'version' in r ? `Release v${r.version}.` : '';+ return [`## Daily stable check: ${r.action}`, '', r.why, '', detail, ''].join('\n');+}++if (import.meta.main) {+ const deps = dailyDeps();+ try {+ if (!deps.repo) throw new Refusal('GITHUB_REPOSITORY is unset; run this from the Stable daily workflow.');+ const result = await daily(deps);+ console.log(`[stable-daily] ${result.action}: ${result.why}`);+ if (process.env.GITHUB_STEP_SUMMARY) appendFileSync(process.env.GITHUB_STEP_SUMMARY, renderDailySummary(result));+ } catch (e) {+ const why = e instanceof Refusal ? e.message : `the daily check stopped on an unexpected error (${e instanceof Error ? e.message : String(e)}).`;+ console.log(`::error::Daily stable check: ${why} Docs: docs/RELEASING.md#daily-stable-check`);+ process.exit(1);+ }+}diff --git a/test/scripts/stable-daily.test.ts b/test/scripts/stable-daily.test.tsnew file mode 100644index 0000000000..fdb113d40e--- /dev/null+++ b/test/scripts/stable-daily.test.ts@@ -0,0 +1,298 @@+/**+ * .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';++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> => {+ const [cmd, ...rest] = args;+ 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 === '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 };+}++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 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);+ });+});